blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
edbd8ded5808ea482e20ad4049efeb9c040258eb
0d0bb9bc41ab34f0c108bc2ac2ad33239613d9f3
/ThRend/settingsLoader.h
b7bac4852563ff9b657efd33ac4be3ad08b362a9
[]
no_license
jpaguerre/ThRend
bc000e3e00e7d72c294762a0ad3dd074fd48f390
eada2993bffa3ab9580f9dbcaed18db40630b72e
refs/heads/master
2023-07-08T09:54:55.122259
2023-07-04T20:12:59
2023-07-04T20:12:59
262,175,807
24
6
null
null
null
null
UTF-8
C++
false
false
3,091
h
#ifndef SETimporter #define SETimporter #include <string> #include <vector> #include <glm.hpp> #include <fstream> #include <sstream> #include <iostream> using namespace std; using namespace glm; typedef struct{ string sceneFile; string skyTempsFile; string colormapFile; vec3 cameraCenter; vec3 cameraDirection; vec3 cameraUp; float fovVertical; int imageWidth; int imageHeight; int aa; int MAX_BOUNCES; int reflSamples; float tmin; float tmax; float tmin_reflected; float tmax_reflected; } settings; settings loadSettings(std::string filename){ ifstream file(filename.c_str()); cout << "Loading file " << filename << " \n"; string line; settings s; while (getline(file, line)){ stringstream linestream(line); string id; linestream >> id; if (id.size() < 0 || (id.size() > 0 && id.at(0) == '#')){ } else if (id == "sceneFile"){ string x; linestream >> x; s.sceneFile = x; } else if (id == "skyTempsFile"){ string x; linestream >> x; s.skyTempsFile = x; } else if (id == "colormapFile"){ string x; linestream >> x; s.colormapFile = x; } else if (id == "cameraCenter"){ float x, y, z; linestream >> x >> y >> z; s.cameraCenter = vec3(x, y, z); } else if (id == "cameraDirection"){ float x, y, z; linestream >> x >> y >> z; s.cameraDirection = vec3(x, y, z); } else if (id == "cameraUp"){ float x, y, z; linestream >> x >> y >> z; s.cameraUp = vec3(x, y, z); } else if (id == "fovVertical"){ float x; linestream >> x ; s.fovVertical = x; } else if (id == "imageWidth"){ int x; linestream >> x; s.imageWidth = x; } else if (id == "imageHeight"){ int x; linestream >> x; s.imageHeight = x; } else if (id == "aa"){ int x; linestream >> x; s.aa = x; } else if (id == "MAX_BOUNCES"){ int x; linestream >> x; s.MAX_BOUNCES = x; if (s.MAX_BOUNCES < 1){ std::cout << "WARNING: MAX_BOUNCES set to 1, lower values are not allowed. \n"; s.MAX_BOUNCES = 1; } } else if (id == "reflSamples"){ int x; linestream >> x; s.reflSamples = x; } else if (id == "tmin"){ float x; linestream >> x; s.tmin = x; } else if (id == "tmax"){ float x; linestream >> x; s.tmax = x; } else if (id == "tmin_reflected"){ float x; linestream >> x; s.tmin_reflected = x; } else if (id == "tmax_reflected"){ float x; linestream >> x; s.tmax_reflected = x; } } cout << "View settings loaded succesfully \n"; return s; } void printSettings(settings s){ cout << "cameraCenter " << s.cameraCenter.x << " " << s.cameraCenter.y << " " << s.cameraCenter.z << "\n"; cout << "cameraDirection " << s.cameraDirection.x << " " << s.cameraDirection.y << " " << s.cameraDirection.z << "\n"; cout << "cameraUp " << s.cameraUp.x << " " << s.cameraUp.y << " " << s.cameraUp.z << "\n"; cout << "fovVertical " << s.fovVertical << "\n"; cout << "imageWidth " << s.imageWidth << "\n"; cout << "imageHeight " << s.imageHeight << "\n"; cout << "aa " << s.aa << "\n"; } #endif
[ "63473051+jpaguerre@users.noreply.github.com" ]
63473051+jpaguerre@users.noreply.github.com
e7eadfd6a29eff590a781ba977036bfa6d07e7c7
0cb85cd0c88a9b9f0cca4472742c2bf9febef2d8
/CommonFiles/Licensing2/include/utility/AutoPointer.h
ea22be12e29681a2f90dadaac76a638d28383cf9
[]
no_license
seth1002/antivirus-1
9dfbadc68e16e51f141ac8b3bb283c1d25792572
3752a3b20e1a8390f0889f6192ee6b851e99e8a4
refs/heads/master
2020-07-15T00:30:19.131934
2016-07-21T13:59:11
2016-07-21T13:59:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,764
h
/* Generated by Together */ #ifndef AUTOPOINTER_H #define AUTOPOINTER_H namespace KasperskyLicensing { namespace Implementation { void Deallocate(void*); } // http://www.josuttis.com/libbook/auto_ptr.html template <class T> class AutoPointer { template <class U> struct AutoPointerRef { AutoPointerRef(AutoPointer& rhs) : ref(rhs) {} AutoPointer<U>& ref; }; public: typedef T ElementType; explicit AutoPointer(T* p = 0) throw() : ptr(p) {} AutoPointer(AutoPointer& rhs) throw() : ptr(rhs.Release()) {} AutoPointer(AutoPointerRef<T> rhs) throw() : ptr(rhs.ref.Release()) {} template<class C> operator AutoPointer<C>() throw() { return (AutoPointer<C>(*this)); } template<class C> operator AutoPointerRef<C>() throw() { return (AutoPointerRef<C>(*this)); } template<class C> AutoPointer<T>& operator=(AutoPointer<C>& rhs) throw() { Reset(rhs.Release()); return (*this); } AutoPointer<T>& operator=(AutoPointer<T>& rhs) throw() { Reset(rhs.Release()); return (*this); } AutoPointer<T>& operator=(AutoPointerRef<T>& rhs) throw() { Reset(rhs.ref.Release()); return (*this); } ~AutoPointer() { if (ptr) Destroy(ptr); } T& operator*() const throw() { return (*ptr); } T* operator->() const throw() { return (&**this); } T* GetPointer() const throw() { return (ptr); } T* Release() throw() { T* tmp = ptr; ptr = 0; return (tmp); } void Reset(T* p = 0) { if (ptr && p != ptr) Destroy(ptr); ptr = p; } private: static void Destroy(T* p) { p->~T(); Implementation::Deallocate(p); } T* ptr; }; } // namespace KasperskyLicensing #endif // AUTOPOINTER_H
[ "idrez.mochamad@gmail.com" ]
idrez.mochamad@gmail.com
6f63e2a542a5607feb8fcf9046abf27cc9eab280
39a315a205bc2d818d2e3f289428c6b516351fdf
/RayCast/Runtime/Core/Core.h
394ebf68a1d578d97b15889059e142d5f38590b6
[]
no_license
ciccone1978/RayCast-Engine
540a47c236f160df1f314c7a0078be119722d665
588359c41a70d92c0bd364f3570930dce53369cb
refs/heads/master
2023-06-16T01:44:42.959256
2021-07-16T17:33:44
2021-07-16T17:33:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,211
h
#pragma once #include <iostream> #include <memory> #ifdef _WIN32 #define ENGINE_WINDOWS_PLATFORM #elif defined(__APPLE__) || defined(__MACH__) #error "Apple Macintosh is not supported!" #elif defined(__IOS__) #error "IOS simulation not supported" #elif defined(__ANDROID__) #define FATON_ANDROID_PLATFORM #error "Android is not currently supported" #elif defined(__linux__) #define FATON_LINUX_PLATFORM #error "Linux is not currently supported" #else #error "Unknow platform is not supported" #endif #ifdef _OPENGL #define ENGINE_OPENGL_API #elif defined(_VULKAN) #error "Vulkan API is not supported!" #elif defined(_DIRECTX) #error "Microsoft DirectX is not supported!" #endif #define ENGINE_ERROR_01 std::cout << "ERROR_01: None API, or Engine does not see his, or API is currently not ssupported!" << std::endl // Engine not use , or does not see API #define ENGINE_ERROR_02(filename) std::cout << "ERROR_02: Error load data from file " << filename << std::endl #define ENGINE_ERROR_03 std::cout << "RIGIDBODY ERROR: This rigid body is not a dynamic type.\n It is impossible to attach the value of mass\n" // error 1 for rigid body #define ENGINE_PRINT(text) std::cout << text << std::endl
[ "semyondyachenko@gmail.com" ]
semyondyachenko@gmail.com
a16e1920bb72b2826eb82bc8b27658113aee512e
a7f96d328f551a77ad9020b5f3b6eaa8f7af2f5c
/SCC_Snippet.cpp
e367a21c10c738b7a3b7fb324cbf95ca284289ba
[]
no_license
devarshi09/CP_Algorithms
74fdf29f07f9cbc27c0c88dbe0c7a00e43e6f162
91103d99b3577aec0acce419e7a2deb9c19b4a07
refs/heads/master
2021-08-07T18:00:19.038142
2020-05-18T11:45:11
2020-05-18T11:45:11
179,672,916
0
0
null
null
null
null
UTF-8
C++
false
false
1,367
cpp
#include<bits/stdc++.h> using namespace std; const int maxn = 1e5+1; vector< vector<int> > g(maxn),tg(maxn); vector<int> vis(maxn,false); stack<int> stk; vector<int> component_collection(maxn); int component = 0; void dfs(int cur){ vis[cur] = true; for(auto it:g[cur]){ if(vis[it]) continue; dfs(it); } stk.push(cur); } void tdfs(int cur){ vis[cur] = true; component_collection[cur] = component; for(auto it:tg[cur]){ if(vis[it]) continue; tdfs(it); } } int main(){ #ifndef ONLINE_JUDGE // for getting input from input.txt freopen("input.txt", "r", stdin); // for writing output to output.txt freopen("output.txt", "w", stdout); #endif int n,m; cin>>n>>m; int people[n+1]; for(int i=1;i<=n;i++) cin>>people[i]; vector<pair<int,int> > edges; while(m--){ int x,y; cin>>x>>y; edges.push_back(make_pair(x,y)); g[x].push_back(y); tg[y].push_back(x); } for(int i=1;i<=n;i++){ if(!vis[i]){ dfs(i); } } fill(vis.begin(),vis.end(),false); while(!stk.empty()){ int val = stk.top(); stk.pop(); if(vis[val]) continue; ++component; tdfs(val); } // Component of each node is stored in component_collection return 0; }
[ "noreply@github.com" ]
noreply@github.com
8e1efe64802c33301855323fca81eb8430ddde2a
c49cb882e12932bee40456a172bf4da6221b29f6
/codeforces/116a.cpp
60bcbaf7d8de2bbf27c7d6e688db1b05050c4e45
[]
no_license
alokkumar0723/codeforces
00ca794b22379ff69b1d4022a999bcada36fb060
582aa0eacb7a9b9d2f6e3cdda348f4d24582cf32
refs/heads/main
2023-06-20T10:24:40.303269
2021-07-20T11:16:15
2021-07-20T11:16:15
387,690,911
1
0
null
null
null
null
UTF-8
C++
false
false
226
cpp
#include<iostream> using namespace std; int main() { int i,n,a,b,p=0,max=0; cin>>n; for(i=0;i<n;i++) { cin>>a>>b; p=b-a+p; if(max<p) max=p; } cout<<max; return 0; }
[ "alokkumar0723@gmail.com" ]
alokkumar0723@gmail.com
4294150cea4ff15858aedfb0869e6b11bc8cb5f4
f706f775845b3c838a33b8277722c9a5a51543b4
/source/runtime/resource/Texture/TextureLoader.cpp
bebcbc9cb35701b7ccc0894b10dd4787a0cf9bdc
[]
no_license
RuggeroVisintin/spark-engine-desktop
87b218fa76323fffa875d62ff33830f2cc8f349d
4738f705f66c2ff7323cb628683e98f65e9ebd6f
refs/heads/master
2023-03-21T01:19:48.534866
2021-01-13T07:41:06
2021-01-13T07:41:06
315,026,669
0
0
null
null
null
null
UTF-8
C++
false
false
612
cpp
#include "TextureLoader.h" #include <FileSystem\File.h> #include <Parsers\bitmap\BmpParser.h> #include <PlatformUtils.h> namespace SE { namespace resource { //Texture TextureLoader::loadResource(SE::platform::backend::GLDevice* gfx, const std::string& filePath) { // SPARK_NOT_IMPLEMENTED() // //Texture result; // //SE::platform::filesystem::OsFile* textureFileHandle = mFileSystem->openFileRead(filePath); // //SE::core::parser::binary::bitmap::BmpParser bmpParser; // //SE::core::parser::binary::bitmap::BmpImage bmpImage; // //bmpParser.readBitmap(bmpImage, textureFileHandle); //} } }
[ "ruggerovisintin@gmail.com" ]
ruggerovisintin@gmail.com
4b1395fa6f69270ea3f326c2e18ec608c14c34ea
79a831fa2fae0c8ec1f856d8e861fcda9054c3e7
/Minimum number of edits-(DP).cpp
57a4100230df9acef78efb4f2606de25198aadd1
[]
no_license
warp-charge/Dynamic-Programming
e39f7d19379e47fc42bfdd5afd62380c2d9e2691
91e410970fab12a9c325ccfe6b285e9eb937a03f
refs/heads/master
2020-05-26T03:25:12.338555
2019-06-15T13:23:05
2019-06-15T13:23:05
188,090,986
0
0
null
null
null
null
UTF-8
C++
false
false
1,148
cpp
#include <bits/stdc++.h> using namespace std; #define ll long long int //given two strings s1,s2 and below operations that can be performed on //s1. Find minimum number of edits(operations) required to convert 's1' into 's2' //a>INSERT b>REMOVE c>REPLACE //DP Approach //Bottom up manner //Time Complexity: O(n1 x n2) //Auxiliary Space: O(n1 x n2) int editDist(string s1,string s2,int n1,int n2) { int dp[n1+1][n2+1],i,j; for(i=0;i<=n1;i++) { for(j=0;j<=n2;j++) { if(i==0) dp[i][j]=j; else if(j==0) dp[i][j]=i; else if(s1[i-1]==s2[j-1]) dp[i][j]=dp[i-1][j-1]; else dp[i][j]=1+min(dp[i][j-1], //Insert min(dp[i-1][j],//Remove dp[i-1][j-1]));//Replace } } return dp[n1][n2]; } int main() { string s1,s2; s1="sunday"; s2="saturday"; int n1,n2; n1=s1.length(); n2=s2.length(); cout<<"minimum no. of edits is "<<editDist(s1,s2,n1,n2); return 0; }
[ "noreply@github.com" ]
noreply@github.com
9225d7e71d8151fda4e5a435bf644c287ac1c258
2305cf66b77bf02b9dfdfa9a622622aecb4d226e
/findsetbits.cpp
0fbd2165c4d16844dbf8db1167a8e038f3aa64e1
[]
no_license
Sachin5411/Algo-Practice-C-
f59d8775e8b23f55dcec65b770576eec4fbfd0ed
7c20ef865d63d278477657ab476c578bf8db1156
refs/heads/master
2022-06-13T20:54:35.449427
2020-05-07T03:28:59
2020-05-07T03:28:59
254,549,246
1
0
null
null
null
null
UTF-8
C++
false
false
363
cpp
#include<iostream> using namespace std; int countbits(int n){ int counter=0; while(n>0){ int i=n&1; if(i==1){ counter++; } n=n>>1; } return counter; } //Second method int countbitsfast(int n){ int ans=0; while(n>0){ n=n&(n-1); ans++; } return ans; } int main(){ int n; cin>>n; cout<<countbits(n)<<endl; cout<<countbitsfast(n); return 0; }
[ "sharmasachin1309@gmail.com" ]
sharmasachin1309@gmail.com
925264b9fb3299450042705c38f8319c842f44c0
d47295e385e489bfaec356c625ef65827132a49a
/Client/src/Common/gui/NinjamTrackView.cpp
bfa0cf013479fdd6d1ff74735ed39de73f884d09
[]
no_license
gitter-badger/JamTaba
97e15e703d71c82db83acde99a5099f735997ce6
0456a9e00e5205deb67d8e92fd90a16beeeb2095
refs/heads/master
2020-12-07T06:26:18.861059
2015-12-29T02:40:46
2015-12-29T02:40:46
48,736,333
0
0
null
2015-12-29T08:12:19
2015-12-29T08:12:19
null
UTF-8
C++
false
false
6,440
cpp
#include "NinjamTrackView.h" #include "ui_TrackGroupView.h" #include "BaseTrackView.h" #include "ui_BaseTrackView.h" #include <QLineEdit> #include <QLabel> #include <QDebug> #include <QStyle> #include "MainController.h" #include "Utils.h" // +++++++++++++++++++++++++ NinjamTrackView::NinjamTrackView(Controller::MainController *mainController, long trackID) : BaseTrackView(mainController, trackID) { channelNameLabel = new MarqueeLabel(); channelNameLabel->setObjectName("channelName"); channelNameLabel->setText(""); ui->mainLayout->insertSpacing(0, 12); ui->mainLayout->insertWidget(1, channelNameLabel); chunksDisplay = new IntervalChunksDisplay(this); chunksDisplay->setObjectName("chunksDisplay"); ui->mainLayout->addSpacing(6); ui->mainLayout->addWidget(chunksDisplay); setUnlightStatus(true);/** disabled/grayed until receive the first bytes. When the first bytes // are downloaded the 'on_channelXmitChanged' slot is executed and this track is enabled.*/ } void NinjamTrackView::setInitialValues(Persistence::CacheEntry initialValues){ cacheEntry = initialValues; // remember last track values ui->levelSlider->setValue(initialValues.getGain() * 100); ui->panSlider->setValue(initialValues.getPan() * ui->panSlider->maximum()); if (initialValues.isMuted()) ui->muteButton->click(); if (initialValues.getBoost() < 1) { ui->buttonBoostMinus12->click(); } else { if (initialValues.getBoost() > 1) ui->buttonBoostPlus12->click(); else ui->buttonBoostZero->click(); } } // +++++++++++++++ void NinjamTrackView::updateGuiElements() { BaseTrackView::updateGuiElements(); channelNameLabel->updateMarquee(); } // +++++= interval chunks visual feedback ++++++= void NinjamTrackView::setUnlightStatus(bool status) { BaseTrackView::setUnlightStatus(status); chunksDisplay->setVisible(!status && chunksDisplay->isVisible()); } void NinjamTrackView::finishCurrentDownload() { if (chunksDisplay->isVisible()) chunksDisplay->startNewInterval(); } void NinjamTrackView::incrementDownloadedChunks() { chunksDisplay->incrementDownloadedChunks(); } void NinjamTrackView::setDownloadedChunksDisplayVisibility(bool visible) { if (chunksDisplay->isVisible() != visible) { chunksDisplay->reset(); chunksDisplay->setVisible(visible); } } // +++++++++++++++++++ void NinjamTrackView::setChannelName(QString name) { this->channelNameLabel->setText(name); int nameWidth = this->channelNameLabel->fontMetrics().width(name); if (nameWidth <= this->channelNameLabel->contentsRect().width()) this->channelNameLabel->setAlignment(Qt::AlignCenter); else this->channelNameLabel->setAlignment(Qt::AlignLeft); this->channelNameLabel->setToolTip(name); } // +++++++++++++++++++++ void NinjamTrackView::setPan(int value) { BaseTrackView::setPan(value); cacheEntry.setPan(mainController->getTrackNode(getTrackID())->getPan()); mainController->getUsersDataCache()->updateUserCacheEntry(cacheEntry); } void NinjamTrackView::setGain(int value) { BaseTrackView::setGain(value); cacheEntry.setGain(value/100.0); mainController->getUsersDataCache()->updateUserCacheEntry(cacheEntry); } void NinjamTrackView::toggleMuteStatus() { BaseTrackView::toggleMuteStatus(); cacheEntry.setMuted(mainController->getTrackNode(getTrackID())->isMuted()); mainController->getUsersDataCache()->updateUserCacheEntry(cacheEntry); } void NinjamTrackView::updateBoostValue() { BaseTrackView::updateBoostValue(); cacheEntry.setBoost(mainController->getTrackNode(getTrackID())->getBoost()); mainController->getUsersDataCache()->updateUserCacheEntry(cacheEntry); } // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void NinjamTrackGroupView::updateGeoLocation() { Geo::Location location = mainController->getGeoLocation(this->userIP); countryLabel->setText( "<img src=:/flags/flags/" + location.getCountryCode().toLower() +".png> <br>" + location.getCountryName()); } // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ NinjamTrackGroupView::NinjamTrackGroupView(QWidget *parent, Controller::MainController *mainController, long trackID, QString channelName, Persistence::CacheEntry initialValues) : TrackGroupView(parent), mainController(mainController), userIP(initialValues.getUserIP()) { setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred)); // change the top panel layout to vertical (original is horizontal) ui->topPanel->layout()->removeWidget(ui->groupNameField); delete ui->topPanel->layout(); ui->topPanel->setLayout(new QVBoxLayout()); ui->topPanel->layout()->setContentsMargins(3, 6, 3, 3); // replace the original QLineEdit with a MarqueeLabel groupNameLabel = new MarqueeLabel(); delete ui->groupNameField; groupNameLabel->setObjectName("groupNameField"); ui->topPanel->layout()->addWidget(groupNameLabel); setGroupName(initialValues.getUserName()); // country flag label countryLabel = new QLabel(); countryLabel->setObjectName("countryLabel"); countryLabel->setTextFormat(Qt::RichText); updateGeoLocation(); ui->topPanel->layout()->addWidget(countryLabel); // create the first subchannel by default NinjamTrackView* newTrackView = dynamic_cast<NinjamTrackView*>(addTrackView(trackID)); newTrackView->setChannelName(channelName); newTrackView->setInitialValues(initialValues); } BaseTrackView *NinjamTrackGroupView::createTrackView(long trackID) { return new NinjamTrackView(mainController, trackID); } void NinjamTrackGroupView::setGroupName(QString groupName) { groupNameLabel->setText(groupName); } void NinjamTrackGroupView::setNarrowStatus(bool narrow) { foreach (BaseTrackView *trackView, trackViews) { bool setToWide = !narrow && trackViews.size() <= 1; if (setToWide) trackView->setToWide(); else trackView->setToNarrow(); } } void NinjamTrackGroupView::updateGuiElements() { TrackGroupView::updateGuiElements(); groupNameLabel->updateMarquee(); } NinjamTrackGroupView::~NinjamTrackGroupView() { }
[ "elieserdejesus@gmail.com" ]
elieserdejesus@gmail.com
ca7250e0457b3232efe0d29e56e8dc786d69b217
fc5c129e41c34fd73a313d99dc10131a336d57a7
/Drawing/Queue.hh
fc7f8c419619de299c811df5665d807bc2f49bbd
[ "WTFPL" ]
permissive
Lilith2/HelvetaCS
2bdfe026b15b390b13494e892ffb0a9492c3fcb2
2c3627c3e179623f4678f166850cc20be8e8b335
refs/heads/main
2023-07-15T17:34:30.809458
2021-08-25T07:55:32
2021-08-25T07:55:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
449
hh
#pragma once #include "Geometry.hh" #include <vector> #include <memory> #include <functional> #include <shared_mutex> struct Queue_t { Queue_t() = default; Queue_t(std::shared_mutex *mutPtr); inline ~Queue_t(){}; void Push(std::shared_ptr<Base_t> &&pRenderable); virtual void Run(const std::function<void(Queue_t *)> &runFn); std::vector<std::shared_ptr<Base_t>> m_vecRenderables = {}; private: std::shared_mutex *m_mutPtr = nullptr; };
[ "cristei.g772@gmail.com" ]
cristei.g772@gmail.com
5fb0f5ecafaa9f62bb4fecb96affd10c341acc52
e108187f4a21009ad5c9749aa0100bb8daf1e817
/nn/Neuron.h
da9ddf05ed9990d8517827dd2a38391c415ab09b
[]
no_license
yzhang1991/coin-recognition
18bf81fc7277b05372dd6ff98b268f191ff7efa6
5791258c2ec164b843e2f670d474bd096849f2f4
refs/heads/master
2021-01-10T00:58:32.656340
2015-12-10T05:39:43
2015-12-10T05:39:43
47,646,950
1
2
null
null
null
null
UTF-8
C++
false
false
1,120
h
#ifndef __NEURON_H__ #define __NEURON_H__ #include <vector> #include <string> using namespace std; struct Neuron { int inputCount; std::vector<double> weights; std::vector<double> lastWeightUpdate; double activation; double error; std::vector<double> dw; double db; void initialize(int input_count) { this->inputCount = input_count + 1; this->weights.resize(this->inputCount); this->lastWeightUpdate.resize(this->inputCount); this->activation = 0.0; this->error = 0.0; this->dw.resize(input_count, 0.0); this->db = 0.0; } ~Neuron() { } }; struct NeuronLayer { int neuronCount; std::vector<Neuron> neurons; void initialize(int neuron_count, int input_count_per_neuron) { this->neuronCount = neuron_count; this->neurons.resize(neuron_count); for (int i = 0; i < neuron_count; i++) { this->neurons[i].initialize(input_count_per_neuron); } } ~NeuronLayer() { } }; struct NeuralParameter { int inputLayerCount; int outputLayerCount; int hiddenLayerCount; int neuCntPerHidLyr; int epochCount; }; #endif
[ "chenshen@chenshens-MacBook-Pro.local" ]
chenshen@chenshens-MacBook-Pro.local
a656e6012ab83a5463b1453caf2401c6883911e8
32a608f3dd766b2801a04af9468e0287eb53d31d
/draw2d_gdi/draw2d_gdi_brush.cpp
472c6f02073ea0d7ec94ecad6898f2485c85221b
[]
no_license
amanp7272/platform-windows
8bd1acfc101976bea408612caa00762708edd531
a13750577a987b3793f8fe958d15059c4c53e2b8
refs/heads/master
2023-01-08T06:49:48.385249
2020-11-01T15:07:20
2020-11-01T15:07:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,037
cpp
#include "framework.h" namespace draw2d_gdi { brush::brush(::layered * pobjectContext) : ::draw2d::brush(pobject) { m_bProcess = false; } brush::~brush() { } brush::operator HBRUSH() const { return (HBRUSH)(this == nullptr ? nullptr : get_os_data()); } bool brush::CreateSolid(COLORREF crColor) { return Attach(::CreateSolidBrush(argb_invert(crColor))); } bool brush::CreateHatchBrush(int nIndex, COLORREF crColor) { return Attach(::CreateHatchBrush(nIndex, argb_invert(crColor))); } bool brush::CreateBrushIndirect(const LOGBRUSH* lpLogBrush) { return Attach(::CreateBrushIndirect(lpLogBrush)); } bool brush::CreatePatternBrush(::draw2d::bitmap* pBitmap) { return Attach(::CreatePatternBrush((HBITMAP)pBitmap->get_os_data())); } bool brush::CreateDIBPatternBrush(const void * lpPackedDIB, UINT nUsage) { return Attach(::CreateDIBPatternBrushPt(lpPackedDIB, nUsage)); } bool brush::CreateSysColorBrush(int nIndex) { return Attach(::GetSysColorBrush(nIndex)); } int brush::GetLogBrush(LOGBRUSH* pLogBrush) { return get_object(sizeof(LOGBRUSH), pLogBrush); } void brush::construct(COLORREF crColor) { if (!Attach(::CreateSolidBrush(crColor))) throw resource_exception(); } void brush::construct(int nIndex, COLORREF crColor) { if (!Attach(::CreateHatchBrush(nIndex, crColor))) throw resource_exception(); } void brush::construct(::draw2d::bitmap* pBitmap) { // ASSERT_VALID(pBitmap); if (!Attach(::CreatePatternBrush((HBITMAP)pBitmap->get_os_data()))) throw resource_exception(); } bool brush::CreateDIBPatternBrush(HGLOBAL hPackedDIB, UINT nUsage) { ASSERT(hPackedDIB != nullptr); const void * lpPackedDIB = ::GlobalLock(hPackedDIB); ASSERT(lpPackedDIB != nullptr); bool bResult = Attach(::CreateDIBPatternBrushPt(lpPackedDIB, nUsage)); ::GlobalUnlock(hPackedDIB); return bResult; } void brush::dump(dump_context & dumpcontext) const { ::draw2d::object::dump(dumpcontext); if (get_os_data() == nullptr) return; /* if (!afxData.bWin95 && ::GetObjectType(get_os_data()) != OBJ_BRUSH) { // not a valid window dumpcontext << "has ILLEGAL HBRUSH!"; return; }*/ LOGBRUSH lb; VERIFY(get_object(sizeof(lb), &lb)); dumpcontext << "lb.lbStyle = " << lb.lbStyle; dumpcontext << "\nlb.lbHatch = " << (u32) lb.lbHatch; dumpcontext << "\nlb.lbColor = " << (void *)(DWORD_PTR)lb.lbColor; dumpcontext << "\n"; } bool brush::create() { ::draw2d_gdi::object::create(); if(m_bProcess) { CreateSolid(RGB(255, 255, 255)); } else if(m_etype == type_solid) { CreateSolid(m_color.get_rgb()); } return true; } } // namespace draw2d_gdi
[ "camilo@ca2.email" ]
camilo@ca2.email
8083a972f5407a498c82bc59603b6b9520cb3c7a
f0df97cb4b5c502f33f5c7cae910cb2065795ef0
/src/preferences/notifications/NotificationsView.cpp
bcde7ce4e48d1e68df1997dac8d9762a85a2d605
[]
no_license
mmadia/haiku-1
fc14dcfe6b3fb6440f0898a493962485f2417305
b02ef3fac8ed7a4f56749ae577c3ebe37684e8ca
refs/heads/master
2021-01-21T01:38:52.637798
2010-07-11T22:25:56
2010-07-13T20:37:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,878
cpp
/* * Copyright 2010, Haiku, Inc. All Rights Reserved. * Copyright 2009, Pier Luigi Fiorini. * Distributed under the terms of the MIT License. * * Authors: * Pier Luigi Fiorini, pierluigi.fiorini@gmail.com */ #include <Alert.h> #include <Directory.h> #include <FindDirectory.h> #include <GroupLayout.h> #include <GroupLayoutBuilder.h> #include <Window.h> #include <CheckBox.h> #include <TextControl.h> #include <Path.h> #include <Notification.h> #include <notification/Notifications.h> #include <notification/NotificationReceived.h> #include <ColumnListView.h> #include <ColumnTypes.h> #include "NotificationsView.h" #define _T(str) (str) const float kEdgePadding = 5.0; const float kCLVTitlePadding = 8.0; const int32 kApplicationSelected = '_ASL'; const int32 kNotificationSelected = '_NSL'; const int32 kCLVDeleteRow = 'av02'; // Applications column indexes const int32 kAppIndex = 0; const int32 kAppEnabledIndex = 1; // Notifications column indexes const int32 kTitleIndex = 0; const int32 kDateIndex = 1; const int32 kTypeIndex = 2; const int32 kAllowIndex = 3; const int32 kSettingChanged = '_STC'; NotificationsView::NotificationsView() : BView("apps", B_WILL_DRAW) { BRect rect(0, 0, 100, 100); // Search application field fSearch = new BTextControl(_T("Search:"), NULL, new BMessage(kSettingChanged)); // Applications list fApplications = new BColumnListView(rect, _T("Applications"), 0, B_WILL_DRAW, B_FANCY_BORDER, true); fApplications->SetSelectionMode(B_SINGLE_SELECTION_LIST); fAppCol = new BStringColumn(_T("Application"), 200, be_plain_font->StringWidth(_T("Application")) + (kCLVTitlePadding * 2), rect.Width(), B_TRUNCATE_END, B_ALIGN_LEFT); fApplications->AddColumn(fAppCol, kAppIndex); fAppEnabledCol = new BStringColumn(_T("Enabled"), 10, be_plain_font->StringWidth(_T("Enabled")) + (kCLVTitlePadding * 2), rect.Width(), B_TRUNCATE_END, B_ALIGN_LEFT); fApplications->AddColumn(fAppEnabledCol, kAppEnabledIndex); // Notifications list fNotifications = new BColumnListView(rect, _T("Notifications"), 0, B_WILL_DRAW, B_FANCY_BORDER, true); fNotifications->SetSelectionMode(B_SINGLE_SELECTION_LIST); fTitleCol = new BStringColumn(_T("Title"), 100, be_plain_font->StringWidth(_T("Title")) + (kCLVTitlePadding * 2), rect.Width(), B_TRUNCATE_END, B_ALIGN_LEFT); fNotifications->AddColumn(fTitleCol, kTitleIndex); fDateCol = new BDateColumn(_T("Last Received"), 100, be_plain_font->StringWidth(_T("Last Received")) + (kCLVTitlePadding * 2), rect.Width(), B_ALIGN_LEFT); fNotifications->AddColumn(fDateCol, kDateIndex); fTypeCol = new BStringColumn(_T("Type"), 100, be_plain_font->StringWidth(_T("Type")) + (kCLVTitlePadding * 2), rect.Width(), B_TRUNCATE_END, B_ALIGN_LEFT); fNotifications->AddColumn(fTypeCol, kTypeIndex); fAllowCol = new BStringColumn(_T("Allowed"), 100, be_plain_font->StringWidth(_T("Allowed")) + (kCLVTitlePadding * 2), rect.Width(), B_TRUNCATE_END, B_ALIGN_LEFT); fNotifications->AddColumn(fAllowCol, kAllowIndex); // Load the applications list _LoadAppUsage(); _PopulateApplications(); // Calculate inset float inset = ceilf(be_plain_font->Size() * 0.7f); // Set layout SetLayout(new BGroupLayout(B_VERTICAL)); // Add views AddChild(BGroupLayoutBuilder(B_VERTICAL, inset) .AddGroup(B_HORIZONTAL) .AddGlue() .Add(fSearch) .End() .Add(fApplications) .Add(fNotifications) ); } void NotificationsView::AttachedToWindow() { fApplications->SetTarget(this); fApplications->SetInvocationMessage(new BMessage(kApplicationSelected)); fNotifications->SetTarget(this); fNotifications->SetInvocationMessage(new BMessage(kNotificationSelected)); #if 0 fNotifications->AddFilter(new BMessageFilter(B_ANY_DELIVERY, B_ANY_SOURCE, B_KEY_DOWN, CatchDelete)); #endif } void NotificationsView::MessageReceived(BMessage* msg) { switch (msg->what) { case kApplicationSelected: { BRow *row = fApplications->CurrentSelection(); if (row == NULL) return; BStringField* appname = dynamic_cast<BStringField*>(row->GetField(kAppIndex)); appusage_t::iterator it = fAppFilters.find(appname->String()); if (it != fAppFilters.end()) _Populate(it->second); } break; case kNotificationSelected: break; default: BView::MessageReceived(msg); break; } } status_t NotificationsView::_LoadAppUsage() { BPath path; if (find_directory(B_USER_SETTINGS_DIRECTORY, &path) != B_OK) return B_ERROR; path.Append(kSettingsDirectory); if (create_directory(path.Path(), 0755) != B_OK) { BAlert* alert = new BAlert("", _T("There was a problem saving the preferences.\n" "It's possible you don't have write access to the " "settings directory."), "OK", NULL, NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT); (void)alert->Go(); return B_ERROR; } path.Append(kFiltersSettings); BFile file(path.Path(), B_READ_ONLY); BMessage settings; if (settings.Unflatten(&file) != B_OK) return B_ERROR; type_code type; int32 count = 0; if (settings.GetInfo("app_usage", &type, &count) != B_OK) return B_ERROR; // Clean filters appusage_t::iterator auIt; for (auIt = fAppFilters.begin(); auIt != fAppFilters.end(); auIt++) delete auIt->second; fAppFilters.clear(); // Add new filters for (int32 i = 0; i < count; i++) { AppUsage* app = new AppUsage(); settings.FindFlat("app_usage", i, app); fAppFilters[app->Name()] = app; } return B_OK; } void NotificationsView::_PopulateApplications() { appusage_t::iterator it; fApplications->Clear(); for (it = fAppFilters.begin(); it != fAppFilters.end(); ++it) { BRow* row = new BRow(); row->SetField(new BStringField(it->first.String()), kAppIndex); fApplications->AddRow(row); } } void NotificationsView::_Populate(AppUsage* usage) { // Sanity check if (!usage) return; int32 size = usage->Notifications(); if (usage->Allowed() == false) fBlockAll->SetValue(B_CONTROL_ON); fNotifications->Clear(); for (int32 i = 0; i < size; i++) { NotificationReceived* notification = usage->NotificationAt(i); time_t updated = notification->LastReceived(); const char* allow = notification->Allowed() ? _T("Yes") : _T("No"); const char* type = ""; switch (notification->Type()) { case B_INFORMATION_NOTIFICATION: type = _T("Information"); break; case B_IMPORTANT_NOTIFICATION: type = _T("Important"); break; case B_ERROR_NOTIFICATION: type = _T("Error"); break; case B_PROGRESS_NOTIFICATION: type = _T("Progress"); break; default: type = _T("Unknown"); } BRow* row = new BRow(); row->SetField(new BStringField(notification->Title()), kTitleIndex); row->SetField(new BDateField(&updated), kDateIndex); row->SetField(new BStringField(type), kTypeIndex); row->SetField(new BStringField(allow), kAllowIndex); fNotifications->AddRow(row); } }
[ "stippi@a95241bf-73f2-0310-859d-f6bbb57e9c96" ]
stippi@a95241bf-73f2-0310-859d-f6bbb57e9c96
d9aeb754f7eadfed95920e814fee722ed961c399
9d85c286a2fdadb082bd4284137e16442dd3ed8b
/project09/main-09.cpp
8ab6cc1bbb8196f82760bd945b15a32c45cf7fde
[]
no_license
wadegbow/CSE232-Project-Files
811cf551e4a59a428fd3a9fc652d5add9c65fa70
cfd2579062f2ff1b5682c105623f21429d8553ad
refs/heads/master
2020-04-10T19:07:03.174173
2016-09-12T15:39:06
2016-09-12T15:39:06
68,022,704
0
0
null
null
null
null
UTF-8
C++
false
false
430
cpp
#include<iostream> using std::cout; using std::endl; #include <initializer_list> using std::initializer_list; #include <stdexcept> using std::range_error; #include "class-09.h" int main (){ SparseVector vec(1000,1337,{ {873,3}, {999,-44385039845}, {2,9}, {333,50}, }); SparseVector temp(1); temp = vec * 2; SparseVector vec2(0,3); //for (int i = 0; i < temp.size(); i++) //cout << temp[i] << endl; }
[ "wadegbow@gmail.com" ]
wadegbow@gmail.com
7f8f04fc2a14e24fe10d8d28bf808c5953af8823
b5a9d42f7ea5e26cd82b3be2b26c324d5da79ba1
/tensorflow/core/kernels/softplus_op.cc
ba61835f2fd21ce09ddcac09fa9f7fa0ffa0fa72
[ "Apache-2.0" ]
permissive
uve/tensorflow
e48cb29f39ed24ee27e81afd1687960682e1fbef
e08079463bf43e5963acc41da1f57e95603f8080
refs/heads/master
2020-11-29T11:30:40.391232
2020-01-11T13:43:10
2020-01-11T13:43:10
230,088,347
0
0
Apache-2.0
2019-12-25T10:49:15
2019-12-25T10:49:14
null
UTF-8
C++
false
false
5,495
cc
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // See docs in ../ops/nn_ops.cc. #define EIGEN_USE_THREADS #include "tensorflow/core/kernels/softplus_op.h" #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/core/framework/numeric_op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/lib/core/errors.h" namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; typedef Eigen::GpuDevice GPUDevice; template <typename Device, typename T> class SoftplusOp : public UnaryElementWiseOp<T, SoftplusOp<Device, T>> { public: explicit SoftplusOp(OpKernelConstruction* context) : UnaryElementWiseOp<T, SoftplusOp<Device, T>>(context) {} void Operate(OpKernelContext* context, const Tensor& input, Tensor* output) { functor::Softplus<Device, T> functor; functor(context->eigen_device<Device>(), input.flat<T>(), output->flat<T>()); } }; template <typename Device, typename T> class SoftplusGradOp : public BinaryElementWiseOp<T, SoftplusGradOp<Device, T>> { public: explicit SoftplusGradOp(OpKernelConstruction* context) : BinaryElementWiseOp<T, SoftplusGradOp<Device, T>>(context) {} void OperateNoTemplate(OpKernelContext* context, const Tensor& g, const Tensor& a, Tensor* output); // INPUTS: // g (gradients): backpropagated gradients // a (inputs): inputs that were passed to SoftplusOp() // OUTPUT: // gradients to backprop template <int NDIMS> void Operate(OpKernelContext* context, const Tensor& g, const Tensor& a, Tensor* output) { OperateNoTemplate(context, g, a, output); } }; template <typename Device, typename T> void SoftplusGradOp<Device, T>::OperateNoTemplate(OpKernelContext* context, const Tensor& g, const Tensor& a, Tensor* output) { OP_REQUIRES(context, a.IsSameSize(g), errors::InvalidArgument("g and a must be the same size")); functor::SoftplusGrad<Device, T> functor; functor(context->eigen_device<Device>(), g.flat<T>(), a.flat<T>(), output->flat<T>()); } #define REGISTER_KERNELS(type) \ REGISTER_KERNEL_BUILDER( \ Name("Softplus").Device(DEVICE_CPU).TypeConstraint<type>("T"), \ SoftplusOp<CPUDevice, type>); \ REGISTER_KERNEL_BUILDER( \ Name("SoftplusGrad").Device(DEVICE_CPU).TypeConstraint<type>("T"), \ SoftplusGradOp<CPUDevice, type>); TF_CALL_FLOAT_TYPES(REGISTER_KERNELS); #undef REGISTER_KERNELS #if (defined(GOOGLE_CUDA) && GOOGLE_CUDA) || \ (defined(TENSORFLOW_USE_ROCM) && TENSORFLOW_USE_ROCM) // Forward declarations of the functor specializations for GPU. namespace functor { #define DECLARE_GPU_SPEC(T) \ template <> \ void Softplus<GPUDevice, T>::operator()( \ const GPUDevice& d, typename TTypes<T>::ConstTensor features, \ typename TTypes<T>::Tensor activations); \ extern template struct Softplus<GPUDevice, T>; \ \ template <> \ void SoftplusGrad<GPUDevice, T>::operator()( \ const GPUDevice& d, typename TTypes<T>::ConstTensor gradients, \ typename TTypes<T>::ConstTensor features, \ typename TTypes<T>::Tensor backprops); \ extern template struct SoftplusGrad<GPUDevice, T>; TF_CALL_GPU_NUMBER_TYPES(DECLARE_GPU_SPEC); } // namespace functor // Registration of the GPU implementations. #define REGISTER_GPU_KERNELS(type) \ REGISTER_KERNEL_BUILDER( \ Name("Softplus").Device(DEVICE_GPU).TypeConstraint<type>("T"), \ SoftplusOp<GPUDevice, type>); \ REGISTER_KERNEL_BUILDER( \ Name("SoftplusGrad").Device(DEVICE_GPU).TypeConstraint<type>("T"), \ SoftplusGradOp<GPUDevice, type>); TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU_KERNELS); #undef REGISTER_GPU_KERNELS #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM } // namespace tensorflow
[ "v-grniki@microsoft.com" ]
v-grniki@microsoft.com
4947d5963d9315ac1f227df0e6fa3e2fd609d181
6c9ddbf00c8e032747faf04ed31ea77049eaa5ce
/third_party/DuiLib/Core/UIBase.h
4bbb1b27726e27e5edd47dd5935ce488f65cb684
[]
no_license
pikazh/mc_launcher
cac9234566385f0fab0cbbe4292ffb5edfd6aa6d
6edca1a5e2e8f37e15601fbb9026e465fb203795
refs/heads/master
2020-04-21T06:16:28.269133
2019-02-06T05:58:44
2019-02-06T05:58:44
169,361,612
2
4
null
null
null
null
WINDOWS-1252
C++
false
false
3,355
h
#ifndef __UIBASE_H__ #define __UIBASE_H__ #pragma once namespace DuiLib { ///////////////////////////////////////////////////////////////////////////////////// // #define UI_WNDSTYLE_CONTAINER (0) #define UI_WNDSTYLE_FRAME (WS_VISIBLE | WS_OVERLAPPEDWINDOW) #define UI_WNDSTYLE_CHILD (WS_VISIBLE | WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN) #define UI_WNDSTYLE_DIALOG (WS_VISIBLE | WS_POPUPWINDOW | WS_CAPTION | WS_DLGFRAME | WS_CLIPSIBLINGS | WS_CLIPCHILDREN) #define UI_WNDSTYLE_EX_FRAME (WS_EX_WINDOWEDGE) #define UI_WNDSTYLE_EX_DIALOG (WS_EX_TOOLWINDOW | WS_EX_DLGMODALFRAME) #define UI_CLASSSTYLE_CONTAINER (0) #define UI_CLASSSTYLE_FRAME (CS_VREDRAW | CS_HREDRAW) #define UI_CLASSSTYLE_CHILD (CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS | CS_SAVEBITS) #define UI_CLASSSTYLE_DIALOG (CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS | CS_SAVEBITS) ///////////////////////////////////////////////////////////////////////////////////// // #ifndef ASSERT #define ASSERT(expr) _ASSERTE(expr) #endif #ifdef _DEBUG #ifndef DUITRACE #define DUITRACE DUI__Trace #endif #define DUITRACEMSG DUI__TraceMsg #else #ifndef DUITRACE #define DUITRACE #endif #define DUITRACEMSG _T("") #endif void DUILIB_API DUI__Trace(LPCTSTR pstrFormat, ...); LPCTSTR DUILIB_API DUI__TraceMsg(UINT uMsg); ///////////////////////////////////////////////////////////////////////////////////// // class DUILIB_API CNotifyPump { public: bool AddVirtualWnd(CDuiString strName,CNotifyPump* pObject); bool RemoveVirtualWnd(CDuiString strName); void NotifyPump(TNotifyUI& msg); bool LoopDispatch(TNotifyUI& msg); DUI_DECLARE_MESSAGE_MAP() private: CDuiStringPtrMap m_VirtualWndMap; }; class DUILIB_API CWindowWnd { public: CWindowWnd(); HWND GetHWND() const; operator HWND() const; bool RegisterWindowClass(); bool RegisterSuperclass(); HWND Create(HWND hwndParent, LPCTSTR pstrName, DWORD dwStyle, DWORD dwExStyle, const RECT rc, HMENU hMenu = NULL); HWND Create(HWND hwndParent, LPCTSTR pstrName, DWORD dwStyle, DWORD dwExStyle, int x = CW_USEDEFAULT, int y = CW_USEDEFAULT, int cx = CW_USEDEFAULT, int cy = CW_USEDEFAULT, HMENU hMenu = NULL); HWND CreateDuiWindow(HWND hwndParent, LPCTSTR pstrWindowName,DWORD dwStyle =0, DWORD dwExStyle =0); HWND Subclass(HWND hWnd); void Unsubclass(); void ShowWindow(bool bShow = true, bool bTakeFocus = true); UINT ShowModal(); void Close(UINT nRet = IDOK); void CenterWindow(); // ¾ÓÖУ¬Ö§³ÖÀ©Õ¹ÆÁÄ» void SetIcon(UINT nRes); bool IsWindow(); LRESULT SendMessage(UINT uMsg, WPARAM wParam = 0, LPARAM lParam = 0L); LRESULT PostMessage(UINT uMsg, WPARAM wParam = 0, LPARAM lParam = 0L); void ResizeClient(int cx = -1, int cy = -1); protected: virtual LPCTSTR GetWindowClassName() const = 0; virtual LPCTSTR GetSuperClassName() const; virtual UINT GetClassStyle() const; virtual LRESULT HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam); virtual void OnFinalMessage(HWND hWnd); static LRESULT CALLBACK __WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK __ControlProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); protected: HWND m_hWnd; WNDPROC m_OldWndProc; bool m_bSubclassed; }; } // namespace DuiLib #endif // __UIBASE_H__
[ "z_yixiang@foxmail.com" ]
z_yixiang@foxmail.com
f9a484082d98f24e37ee88d8dd38024a2ae7afd3
615b072bb289766ed4a91d113cfaed0d15689900
/UI.h
1465b770d7dc1bf2cf35b8737bec714d3861215d
[]
no_license
maciejkawka/Advanced-Programming-Coursework-2
36005838b4a213eed631769274d0d815cbb2dcc5
e598dd2e8b62f01047af332fcaf48e8c17f01eb5
refs/heads/master
2023-01-08T04:18:16.576982
2020-11-08T14:30:53
2020-11-08T14:30:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
344
h
#pragma once #include<iostream> #include"MazeGame.h" class UI { MazeGame* mainMaze; inline int InputInt(); public: UI(); ~UI(); void SetDimentions(); void SetExitsNumber(); void GenerateMaze(); void Reset(); void Load(); void Save(); void Welcome(); void Print(); void Analyse(); void NextRound(); void SeriesOfMazes(); };
[ "46383143+maciejkawka@users.noreply.github.com" ]
46383143+maciejkawka@users.noreply.github.com
bfdac1b581505a5129a8bb6c38af4604766b498a
641e1f44180bab7b74bb390d4adc0b4ab10dd145
/src/qt/walletmodeltransaction.h
6dec520caac190c5a80190b203396fd7b89841d2
[ "MIT" ]
permissive
mirzaei-ce/linux-ausbit
7ab641d607f15ed517318568ec1ba8a608e1adad
6d4f8ba69c46ce5c03c79fbaecaec69c6a54acd5
refs/heads/master
2021-08-19T08:48:34.207100
2017-11-25T15:47:45
2017-11-25T15:47:45
112,015,359
0
0
null
null
null
null
UTF-8
C++
false
false
1,223
h
// Copyright (c) 2011-2013 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef AUSBIT_QT_WALLETMODELTRANSACTION_H #define AUSBIT_QT_WALLETMODELTRANSACTION_H #include "walletmodel.h" #include <QObject> class SendCoinsRecipient; class CReserveKey; class CWallet; class CWalletTx; /** Data model for a walletmodel transaction. */ class WalletModelTransaction { public: explicit WalletModelTransaction(const QList<SendCoinsRecipient> &recipients); ~WalletModelTransaction(); QList<SendCoinsRecipient> getRecipients(); CWalletTx *getTransaction(); unsigned int getTransactionSize(); void setTransactionFee(const CAmount& newFee); CAmount getTransactionFee(); CAmount getTotalTransactionAmount(); void newPossibleKeyChange(CWallet *wallet); CReserveKey *getPossibleKeyChange(); void reassignAmounts(int nChangePosRet); // needed for the subtract-fee-from-amount feature private: QList<SendCoinsRecipient> recipients; CWalletTx *walletTransaction; CReserveKey *keyChange; CAmount fee; }; #endif // AUSBIT_QT_WALLETMODELTRANSACTION_H
[ "mirzaei@ce.sharif.edu" ]
mirzaei@ce.sharif.edu
93a88a2b2863738803557d30386b0b64ad80a0d6
1210a4094cc336a3c018696db34673fb5f72b0fe
/src/lib/operators/table_scan.cpp
bd59c40415e6f3cd8439a7ab4cfb7dfb8831ad6b
[ "MIT" ]
permissive
querenker/DYOD_WS1819
c4d30539359db95046f456e3e2c02eb7af307c87
d686103ded6d222fc48e1090392312adcb82b1b6
refs/heads/master
2020-04-02T09:57:32.357761
2018-11-27T21:16:24
2018-11-27T21:16:24
154,318,382
0
0
MIT
2018-11-27T21:16:25
2018-10-23T11:44:25
C++
UTF-8
C++
false
false
990
cpp
#include "table_scan.hpp" #include <memory> #include <string> #include "../resolve_type.hpp" #include "../storage/table.hpp" namespace opossum { TableScan::TableScan(const std::shared_ptr<const AbstractOperator> in, ColumnID column_id, const ScanType scan_type, const AllTypeVariant search_value) : AbstractOperator(in), _column_id{column_id}, _scan_type{scan_type}, _search_value{search_value} { const std::string& column_type = in->get_output()->column_type(column_id); _table_scan_impl = make_unique_by_data_type<TableScan::BaseTableScanImpl, TableScan::TableScanImpl>(column_type); } TableScan::~TableScan() = default; ColumnID TableScan::column_id() const { return _column_id; } ScanType TableScan::scan_type() const { return _scan_type; } const AllTypeVariant& TableScan::search_value() const { return _search_value; } std::shared_ptr<const Table> TableScan::_on_execute() { return _table_scan_impl->on_execute(*this); } } // namespace opossum
[ "noreply@github.com" ]
noreply@github.com
6b2e34dacf1cc4b74ea903fd7aa184ab22f501d0
85d483cc05b71314acf449a3004f44d84e0aadb2
/Source/Michelangelo/Unreal/Scene/URenderItem.h
9237f4ce21a2ceb513b79870f350cc0ac325e3d2
[]
no_license
JPMMaia/michelangelo-frontend
d5c3d4fd34f7c99887e40807bb8c622ba8409602
4141d249bc14acda4c5975582bd4078d7767586c
refs/heads/master
2021-01-20T11:09:33.857014
2017-07-18T16:32:18
2017-07-18T16:32:18
72,037,322
0
0
null
2017-04-21T17:15:46
2016-10-26T19:28:07
C++
UTF-8
C++
false
false
756
h
#pragma once #include <Object.h> #include "Unreal/Mesh/AMeshActor.h" #include "URenderItem.generated.h" namespace MichelangeloAPI { class SceneGeometry; } UCLASS() class MICHELANGELO_API URenderItem : public UObject { GENERATED_BODY() public: static URenderItem* Create(const MichelangeloAPI::SceneGeometry& sceneGeometry, const MichelangeloAPI::ObjectGeometry& objectGeometry); public: virtual void BeginDestroy() override; AMeshActor* GetMeshActor() const; UMaterialInterface* GetMaterial() const; const FString& GetMeshName() const; size_t GetMaterialIndex() const; private: UPROPERTY() AMeshActor* m_meshActor = nullptr; UPROPERTY() UMaterialInstanceDynamic* m_material = nullptr; FString m_meshName; size_t m_materialIndex; };
[ "jpmmaia@gmail.com" ]
jpmmaia@gmail.com
bda57cdd5a99321eb662384b433e2062ab5a872c
cc738f771e70e938e3f9d86396b36c59b9974ef0
/temperature.ino
6e521c896f4fb650d3ca70d0f2cffdbba27c93a7
[]
no_license
nzare/HealthMonitoringSuit
493ee7484d0d72df0b3d788308fa856ac0c2b4f1
663386ae4cf63da0121ea2d84cdacc3288a7fda8
refs/heads/master
2020-04-23T09:55:22.150998
2019-02-17T05:47:47
2019-02-17T05:47:47
171,086,279
0
0
null
null
null
null
UTF-8
C++
false
false
567
ino
/* This program Print temperature on terminal Hardware Connections (Breakoutboard to Arduino): Vin - 5V (3.3V is allowed) GND - GND SDA - A4 (or SDA) SCL - A5 (or SCL) */ #include <Wire.h> #include "Protocentral_MAX30205.h" MAX30205 tempSensor; void setup() { // put your setup code here, to run once: Wire.begin(); Serial.begin(9600); tempSensor.begin(); // set continuos mode, active mode } void loop() { float temp = tempSensor.getTemperature(); // read temperature for every 100ms Serial.print(temp ,2); Serial.println("'c" ); delay(100); }
[ "40881094+nzare@users.noreply.github.com" ]
40881094+nzare@users.noreply.github.com
bea0a5b84a1f7df4760be2507a964d229a8d3f8d
9d57c253f8a503170a0e9ac5d2a48b646048fb71
/A_Diverse_Strings.cpp
d94b302ea4918a3fcc4e46b32531b71c0fef2c5a
[]
no_license
tarundecipher/CompetitiveProgramming
4f2dfd3f77c2a1de0b56964650d5cad05e4258ab
466bdc6333ca2f14b3a8aef14063a1278523bb9c
refs/heads/master
2023-04-04T07:50:49.626690
2021-04-18T08:13:16
2021-04-18T08:13:16
359,052,986
0
0
null
null
null
null
UTF-8
C++
false
false
912
cpp
#include <bits/stdc++.h> #define ll long long int using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while (t--) { string s; cin >> s; sort(s.begin(), s.end()); int n = s.length(); bool cond = false; map<char, int> mp; for (int i = 0; i < n; i++) { mp[s[i]]++; } for (auto i : mp) { if (i.second > 1) { cond = true; break; } } for (int i = 0; i < n - 1; i++) { if (abs(s[i + 1] - s[i]) > 1) { cond = true; break; } } if (cond) { cout << "No" << endl; } else { cout << "Yes" << endl; } } }
[ "tarunyadav83333@gmail.com" ]
tarunyadav83333@gmail.com
6eb20390a9bf287aea59a859be37f46e7d58312a
9e889555277ac34cd20532b40c10369d132373f3
/Codechef/ZCO13001.cpp
abbe535134c3fe6e676424962b2b2aed8e6f82c4
[]
no_license
devanshu0987/Competitive-Programming
a756a093b9ec5fe684e7ceacaa37aba6ec32cd3b
000853cb4fd054c3d1328df11c6068d5e7d54aa9
refs/heads/master
2021-09-24T07:17:14.042005
2018-10-02T11:48:00
2018-10-02T12:54:40
60,449,318
0
5
null
2018-10-05T05:02:08
2016-06-05T07:55:41
C++
UTF-8
C++
false
false
564
cpp
#include<iostream> #include<algorithm> using namespace std; long long int absl(long long int x) { return (x>0)?x:(x*-1); } int cmp(int P,int Q) { return P>Q; } int main() { int N; cin>>N; int* A = new int[N]; int* SUM = new int[N]; for(int i=0;i<N;i++) cin>>A[i]; //sum if(N==2) { cout<<absl(A[1]-A[0])<<endl; return 0; } sort(A,A+N,cmp); SUM[N-1]=A[N-1]; for(int i=N-2;i>=0;i--) SUM[i]=A[i]+SUM[i+1]; long long int ans=0,temp=0; for(int i=1;i<N;i++) { temp= SUM[i] - (N-i)*A[i-1]; temp=absl(temp); ans+=temp; } cout<<ans<<endl; }
[ "devanshu0987@gmail.com" ]
devanshu0987@gmail.com
c36cf50472c74f09e8dcce45c8364f758357c21f
6c6470ec2f469db297d12752de5a2cb8b190b5e8
/include/pascal-s/lib/string.h
0d12834bcedf17e6052115f3afb27c3c7088f755
[]
no_license
Myriad-Dreamin/llvm-pascal-s
d505c73d3136ff4daf857c56445c08850850a7be
fcb25c0b4515220b811a8b261cae441039944917
refs/heads/master
2022-11-15T15:08:41.139358
2020-07-06T03:07:47
2020-07-06T03:07:47
277,430,857
1
0
null
null
null
null
UTF-8
C++
false
false
263
h
// // Created by kamiyoru on 2020/6/18. // #ifndef PASCAL_S_LIB_STRING_H #define PASCAL_S_LIB_STRING_H namespace pascal_s { char *copy_string(const char *content, int length); char *copy_string(const char *content); } #endif //PASCAL_S_LIB_STRING_H
[ "camiyoru@gmail.com" ]
camiyoru@gmail.com
c0bc675aa73e7d369520a90261a6d45d141aca56
15cdb7d5d791d60bff1238c38026e95d41a27eb6
/Pruebas/main.cpp
3dc5e61b0c14f60d8ebd051a8de77859cf1792fd
[]
no_license
Jodyannre/Laboratorio_EDD_201115018
3b973f2758015e399838bddc8a4f63737bbcc5e5
c45a0792e04395e8d6f20fdbe68ffd21135533f0
refs/heads/master
2022-12-13T11:31:59.037272
2020-09-04T01:27:47
2020-09-04T01:27:47
286,268,239
0
0
null
null
null
null
UTF-8
C++
false
false
658
cpp
#include "listaGenerica.h" #include "nodoGenerico.h" #include "nodoHijo.h" #include <iostream> using namespace std; int main(){ nodoHijo* n1 = new nodoHijo(1); nodoHijo* n2 = new nodoHijo(2); nodoHijo* n3 = new nodoHijo(3); nodoHijo* n4 = new nodoHijo(4); nodoHijo* n5 = new nodoHijo(5); listaGenerica<nodoGenerico>* lista = new listaGenerica<nodoGenerico>(); lista->add(n1); lista->add(n2); lista->add(n3); lista->add(n4); lista->add(n5); nodoGenerico* aux = lista->getPrimero(); for (int i;i<4;i++){ cout<<((nodoHijo*)aux)->getDato()<<endl; aux = aux->getSig(); } return 0; }
[ "Jers_033@hotmail.com" ]
Jers_033@hotmail.com
48358a1a8952c7f1f66c0781796b101a554104c1
4979915833a11a0306b66a25a91fadd009e7d863
/src/connectivity/wlan/testing/wlantap-driver/utils.cc
71433e67ae35eb88c946e8bb5e06d5da1248e68b
[ "BSD-2-Clause" ]
permissive
dreamboy9/fuchsia
1f39918fb8fe71d785b43b90e0b3128d440bd33f
4ec0c406a28f193fe6e7376ee7696cca0532d4ba
refs/heads/master
2023-05-08T02:11:06.045588
2021-06-03T01:59:17
2021-06-03T01:59:17
373,352,924
0
0
NOASSERTION
2021-06-03T01:59:18
2021-06-03T01:58:57
null
UTF-8
C++
false
false
7,332
cc
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "utils.h" #include <fuchsia/hardware/ethernet/c/banjo.h> #include <fuchsia/hardware/wlan/info/c/banjo.h> #include <fuchsia/hardware/wlan/mac/c/banjo.h> #include <fuchsia/hardware/wlanphyimpl/c/banjo.h> #include <fuchsia/wlan/device/cpp/fidl.h> #include <wlan/common/band.h> #include <wlan/common/channel.h> #include <wlan/common/element.h> #include <wlan/common/parse_element.h> namespace wlan { namespace wlan_common = ::fuchsia::wlan::common; namespace wlan_device = ::fuchsia::wlan::device; namespace wlan_tap = ::fuchsia::wlan::tap; uint16_t ConvertSupportedPhys(const ::std::vector<wlan_device::SupportedPhy>& phys) { uint16_t ret = 0; for (auto sp : phys) { switch (sp) { case wlan_device::SupportedPhy::DSSS: ret |= WLAN_INFO_PHY_TYPE_DSSS; break; case wlan_device::SupportedPhy::CCK: ret |= WLAN_INFO_PHY_TYPE_CCK; break; case wlan_device::SupportedPhy::OFDM: ret |= WLAN_INFO_PHY_TYPE_OFDM; break; case wlan_device::SupportedPhy::HT: ret |= WLAN_INFO_PHY_TYPE_HT; break; case wlan_device::SupportedPhy::VHT: ret |= WLAN_INFO_PHY_TYPE_VHT; break; } } return ret; } uint32_t ConvertDriverFeatures(const ::std::vector<wlan_common::DriverFeature>& dfs) { uint32_t ret = 0; for (auto df : dfs) { switch (df) { case wlan_common::DriverFeature::SCAN_OFFLOAD: ret |= WLAN_INFO_DRIVER_FEATURE_SCAN_OFFLOAD; break; case wlan_common::DriverFeature::RATE_SELECTION: ret |= WLAN_INFO_DRIVER_FEATURE_RATE_SELECTION; break; case wlan_common::DriverFeature::SYNTH: ret |= WLAN_INFO_DRIVER_FEATURE_SYNTH; break; case wlan_common::DriverFeature::TX_STATUS_REPORT: ret |= WLAN_INFO_DRIVER_FEATURE_TX_STATUS_REPORT; break; case wlan_common::DriverFeature::DFS: ret |= WLAN_INFO_DRIVER_FEATURE_DFS; break; case wlan_common::DriverFeature::PROBE_RESP_OFFLOAD: ret |= WLAN_INFO_DRIVER_FEATURE_PROBE_RESP_OFFLOAD; break; case wlan_common::DriverFeature::SAE_SME_AUTH: ret |= WLAN_INFO_DRIVER_FEATURE_SAE_SME_AUTH; break; case wlan_common::DriverFeature::SAE_DRIVER_AUTH: ret |= WLAN_INFO_DRIVER_FEATURE_SAE_DRIVER_AUTH; break; case wlan_common::DriverFeature::MFP: ret |= WLAN_INFO_DRIVER_FEATURE_MFP; break; // TODO(fxbug.dev/41640): Remove this flag once FullMAC drivers stop interacting with SME. case wlan_common::DriverFeature::TEMP_SOFTMAC: // Vendor driver has no control over this flag. break; } } return ret; } uint16_t ConvertMacRole(wlan_device::MacRole role) { switch (role) { case wlan_device::MacRole::AP: return WLAN_INFO_MAC_ROLE_AP; case wlan_device::MacRole::CLIENT: return WLAN_INFO_MAC_ROLE_CLIENT; case wlan_device::MacRole::MESH: return WLAN_INFO_MAC_ROLE_MESH; } } wlan_device::MacRole ConvertMacRole(uint16_t role) { switch (role) { case WLAN_INFO_MAC_ROLE_AP: return wlan_device::MacRole::AP; case WLAN_INFO_MAC_ROLE_CLIENT: return wlan_device::MacRole::CLIENT; case WLAN_INFO_MAC_ROLE_MESH: return wlan_device::MacRole::MESH; } ZX_ASSERT(0); } uint32_t ConvertCaps(const ::std::vector<wlan_device::Capability>& caps) { uint32_t ret = 0; for (auto cap : caps) { switch (cap) { case wlan_device::Capability::SHORT_PREAMBLE: ret |= WLAN_INFO_HARDWARE_CAPABILITY_SHORT_PREAMBLE; break; case wlan_device::Capability::SPECTRUM_MGMT: ret |= WLAN_INFO_HARDWARE_CAPABILITY_SPECTRUM_MGMT; break; case wlan_device::Capability::QOS: ret |= WLAN_INFO_HARDWARE_CAPABILITY_QOS; break; case wlan_device::Capability::SHORT_SLOT_TIME: ret |= WLAN_INFO_HARDWARE_CAPABILITY_SHORT_SLOT_TIME; break; case wlan_device::Capability::RADIO_MSMT: ret |= WLAN_INFO_HARDWARE_CAPABILITY_RADIO_MSMT; break; case wlan_device::Capability::SIMULTANEOUS_CLIENT_AP: ret |= WLAN_INFO_HARDWARE_CAPABILITY_SIMULTANEOUS_CLIENT_AP; break; } } return ret; } void ConvertBandInfo(const wlan_device::BandInfo& in, wlan_info_band_info_t* out) { memset(out, 0, sizeof(*out)); out->band = static_cast<uint8_t>(wlan::common::BandFromFidl(in.band_id)); if (in.ht_caps != nullptr) { out->ht_supported = true; out->ht_caps = ::wlan::common::ParseHtCapabilities(in.ht_caps->bytes)->ToDdk(); } else { out->ht_supported = false; } if (in.vht_caps != nullptr) { out->vht_supported = true; out->vht_caps = ::wlan::common::ParseVhtCapabilities(in.vht_caps->bytes)->ToDdk(); } else { out->vht_supported = false; } std::copy_n(in.rates.data(), std::min<size_t>(in.rates.size(), WLAN_INFO_BAND_INFO_MAX_RATES), out->rates); out->supported_channels.base_freq = in.supported_channels.base_freq; std::copy_n(in.supported_channels.channels.data(), std::min<size_t>(in.supported_channels.channels.size(), WLAN_INFO_CHANNEL_LIST_MAX_CHANNELS), out->supported_channels.channels); } zx_status_t ConvertTapPhyConfig(wlanmac_info_t * mac_info, const wlan_tap::WlantapPhyConfig& tap_phy_config) { std::memset(mac_info, 0, sizeof(*mac_info)); std::copy_n(tap_phy_config.iface_mac_addr.begin(), ETH_MAC_SIZE, mac_info->mac_addr); mac_info->supported_phys = ConvertSupportedPhys(tap_phy_config.supported_phys); mac_info->driver_features = ConvertDriverFeatures(tap_phy_config.driver_features); mac_info->mac_role = ConvertMacRole(tap_phy_config.mac_role); mac_info->caps = ConvertCaps(tap_phy_config.caps); mac_info->bands_count = std::min(tap_phy_config.bands.size(), static_cast<size_t>(WLAN_INFO_MAX_BANDS)); for (size_t i = 0; i < mac_info->bands_count; ++i) { ConvertBandInfo((tap_phy_config.bands)[i], &mac_info->bands[i]); } return ZX_OK; } zx_status_t ConvertTapPhyConfig(wlanphy_impl_info_t * phy_impl_info, const wlan_tap::WlantapPhyConfig& tap_phy_config) { std::memset(phy_impl_info, 0, sizeof(*phy_impl_info)); phy_impl_info->supported_mac_roles = ConvertMacRole(tap_phy_config.mac_role); return ZX_OK; } wlan_tx_status_t ConvertTxStatus(const wlan_tap::WlanTxStatus& in) { wlan_tx_status_t out; std::copy(in.peer_addr.cbegin(), in.peer_addr.cend(), out.peer_addr); for (size_t i = 0; i < in.tx_status_entries.size(); ++i) { out.tx_status_entry[i].tx_vector_idx = in.tx_status_entries[i].tx_vec_idx; out.tx_status_entry[i].attempts = in.tx_status_entries[i].attempts; } out.success = in.success; return out; } } // namespace wlan
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
66ef0e61fd96f3539a1e09307917507aab36c4ad
404b58190bc7d0264d598c5b7809db7dac70447a
/src/Collision.cpp
8a82ef09dbb2ae453cc24f4289390eb416a09ee2
[]
no_license
justlookingforcode/MeshSimilarityVisualizer
c914a240e9882bc0b93e5fe2538e7b18fa99cfd0
74f71377beecc7d7cf071a505426f49285a43835
refs/heads/master
2020-03-30T13:37:30.774472
2018-11-07T13:42:15
2018-11-07T13:42:15
151,280,522
0
0
null
null
null
null
UTF-8
C++
false
false
19,064
cpp
/* Start Header ------------------------------------------------------ Copyright (C) 2014 DigiPen Institute of Technology. Reproduction or disclosure of this file or its contents without the prior written consent of DigiPen Institute of Technology is prohibited. File Name: Collision.cpp Purpose: This is where the Collision and Collision Response function implementations are. Language: C++ Platform: Windows Visual Studio Author: Tan Wen De Kevin Creation Date: 19/Oct/2016 - End Header -------------------------------------------------------*/ #include "HierachicalAABB.h" #include "HierachicalBS.h" #include "BS.h" #include "AABB.h" #include "Collision.h" #include "math.hpp" #include <iostream> #include <stdio.h> #include <sstream> namespace Proto { const f32 OFFSET = 0.0002f; /************************************************************************** ********************//** * \fn bool IsCollided(BV & t_BV1, BV & t_BV2) * * \brief Checks for collision between any two bounding volumes. * * * \param [in,out] t_BV1 The 1st bounding volume object. * \param [in,out] t_BV2 The 2nd bounding volume object. * * \return true if collided, false if not. **************************************************************************************************/ bool IsCollided(BS & t_BV1, BS & t_BV2) { return SphereSphereCollision(t_BV1, t_BV2); } /**********************************************************************************************//** * \fn bool SphereSphereCollision(BS & t_BS1, BS & t_BS2) * * \brief Checks for sphere-sphere collision. * * * \param [in,out] t_BS1 The 1st bounding sphere object. * \param [in,out] t_BS2 The 2nd bounding sphere object. * * \return true if it succeeds, false if it fails. **************************************************************************************************/ bool SphereSphereCollision(BS & t_BS1, BS & t_BS2) { // Calculate squared distance between centers vec3 t_D = t_BS1.m_Center - t_BS2.m_Center; f32 t_Dist2 = Dot(t_D, t_D); // glm::dot(t_D, t_D); // Spheres interact if squared distance is leess than squared sum of radii f32 t_RadiusSum = t_BS1.GetRadius() + t_BS2.GetRadius(); return t_Dist2 <= t_RadiusSum * t_RadiusSum; } /**********************************************************************************************//** * \fn bool AABBAABBCollision(AABB & t_AABB1, AABB & t_AABB2) * * \brief Checks for AABB-AABB collision. * * * \param [in,out] t_AABB1 The 1st AABB object. * \param [in,out] t_AABB2 The 2nd AABB object. * * \return true if it succeeds, false if it fails. **************************************************************************************************/ bool AABBAABBCollision(const AABB & t_AABB1, const AABB & t_AABB2) { vec3 t_PosDiff = glm::abs(t_AABB1.m_Center - t_AABB2.m_Center); f32 t_PosDiffX = fabs(t_PosDiff.x); f32 t_PosDiffY = fabs(t_PosDiff.y); f32 t_PosDiffZ = fabs(t_PosDiff.z); vec3 t_TotalRadius = t_AABB1.GetRadius() + t_AABB2.GetRadius(); f32 t_TotalRadiusX = fabs(t_TotalRadius.x); f32 t_TotalRadiusY = fabs(t_TotalRadius.y); f32 t_TotalRadiusZ = fabs(t_TotalRadius.z); if ((t_PosDiffX > t_TotalRadiusX) || (t_PosDiffY > t_TotalRadiusY) || (t_PosDiffZ > t_TotalRadiusZ)) { return false; } //std::cout << "AABB-AABB Collision!\n"; return true; } /**********************************************************************************************//** * \fn f32 SqDistPointAABB(const vec3 & t_BSCenter, const AABB & t_AABB) * * \brief Sq distance point a bb. * * * \param t_Point The point. * \param t_AABB The AABB object. * * \return Square distance of float type **************************************************************************************************/ f32 SqDistPointAABB(const vec3 & t_BSCenter, const AABB & t_AABB) { f32 t_SqDist = 0.f; for (int i = 0; i < TOTAL_AXIS; ++i) { vec3 t_AABBMin = t_AABB.GetMinVertex(); vec3 t_AABBMax = t_AABB.GetMaxVertex(); // For each axis count any excess distance outside box extents f32 t_CurrPtVal = t_BSCenter[i]; if (t_CurrPtVal < t_AABB.GetMinVertex()[i]) { f32 t_Diff = t_AABBMin[i] - t_CurrPtVal; t_SqDist += (t_Diff * t_Diff); } if (t_CurrPtVal > t_AABB.GetMaxVertex()[i]) { f32 t_Diff = t_CurrPtVal - t_AABBMax[i]; t_SqDist += (t_Diff * t_Diff); } } return t_SqDist; } /**********************************************************************************************//** * \fn bool SphereAABBCollision(BS & t_BS, AABB & t_AABB) * * \brief Checks for BS-AABB collision. * * * \param [in,out] t_BS The bounding sphere object. * \param [in,out] t_AABB The AABB object. * * \return true if it succeeds, false if it fails. **************************************************************************************************/ bool SphereAABBCollision(const BS & t_BS, const AABB & t_AABB) { f32 t_SqDist = SqDistPointAABB(t_BS.m_Center, t_AABB); f32 t_BSRadius = t_BS.GetRadius(); f32 t_BSRadiusSq = t_BSRadius * t_BSRadius; // intersects if the dist. from center is > sphere radius return (t_SqDist <= t_BSRadiusSq + OFFSET); } /**********************************************************************************************//** * \fn vec3 Lerp(const vec3 & t_Start, const vec3 & t_End, const f32 & t_Percent) * * \brief Lerps. * * * \param t_Start The start. * \param t_End The end. * \param t_Percent The percent. * * \return . **************************************************************************************************/ vec3 Lerp(const vec3 & t_Start, const vec3 & t_End, const f32 & t_Percent) { return (t_Start + t_Percent * (t_End - t_Start)); } /**********************************************************************************************//** * \fn vec3 Slerp(const vec3 & t_Start, const vec3 & t_End, const f32 & t_Percent) * * \brief Slerps. * * * \param t_Start The start. * \param t_End The end. * \param t_Percent The percent. * * \return . **************************************************************************************************/ vec3 Slerp(const vec3 & t_Start, const vec3 & t_End, const f32 & t_Percent) { f32 t_DotProd = glm::dot(t_Start, t_End); glm::clamp(t_DotProd, -1.0f, 1.0f); f32 t_Theta = glm::acos((t_DotProd)*t_Percent); vec3 t_RelativeVec = t_End - t_Start * t_DotProd; Normalise(t_RelativeVec);//glm::normalize(t_RelativeVec); return ((t_Start * glm::cos(t_Theta)) + (t_RelativeVec * glm::sin(t_Theta))); } /**********************************************************************************************//** * \fn vec3 Nlerp(const vec3 & t_Start, const vec3 & t_End, const f32 & t_Percent) * * \brief Nlerps. * * * \param t_Start The start. * \param t_End The end. * \param t_Percent The percent. * * \return . **************************************************************************************************/ vec3 Nlerp(const vec3 & t_Start, const vec3 & t_End, const f32 & t_Percent) { return Normalise(Lerp(t_Start, t_End, t_Percent));//glm::normalize(Lerp(t_Start, t_End, t_Percent)); } /**********************************************************************************************//** * \fn bool SphereOBBCollision(BS & t_BS, OBB & t_OBB) * * \brief sphere obb collison * * * \param bounding sphere * \param aabb * * \return . **************************************************************************************************/ /*************************************************************************/ /*! \fn f32 ScalarCrossProduct2(vec3& v0, vec3& v1, vec3& v2) \brief This absoluted scalar cross product needd in dynamic OBB vs OBB test */ /*************************************************************************/ f32 ScalarCrossProduct2(vec3& v0, vec3& v1, vec3& v2) { vec3 cp(Cross(v1, v2)); return fabs(Dot(v0, cp)); } bool IntersectRaySphere(const vec3& origin, const vec3& ray, const BS& sphere, f32&t) { vec3 m = origin - sphere.m_Center; f32 b = Dot(m, ray); // detect if ray is pointing away from the sphere f32 c = Dot(m, m) - (sphere.m_Radius * sphere.m_Radius); //detect if object is in the sphere, negative is in sphere if (c > 0.f && b> 0.f) return false; f32 discr = b*b - c; if (discr < 0.f) return false; t = -b -sqrt(discr); t = (t < 0.f) ? 0.f : t; return true; } int CheckSign(const vec3& p0, const vec3& p1, const vec3& p2, const vec3& p3) { vec3 v10 = p1 - p0; vec3 v20 = p2 - p0; vec3 v30 = p3 - p0; float result = Dot(v10, Cross(v20,v30)); if (result > 0) { return 1; } else if (result <= 0.1f && result >= -0.1f) { return 0; } else return -1; } bool IntersectRayAABB(const vec3& origin, const vec3& ray, const AABB& aabb, f32& tMin, vec3& intersect) { tMin = 0; f32 tMax= FLT_MAX; // For all three slabs for (int i = 0; i < 3; i++) { f32 e= aabb.m_Radius[i]; f32 max = aabb.m_Center[i] + e; f32 min = aabb.m_Center[i] - e; if (fabs(ray[i]) < EPSILON) { // Ray is parallel to slab. No hit if origin not within slab if (origin[i] < min || origin[i] > max) return false; } else { // Compute intersection t value of ray with near and far plane of slab f32 ood = 1.0f / ray[i]; f32 t1 = (min - origin[i]) * ood; f32 t2 = (max - origin[i]) * ood; // Make t1 be intersection with near plane, t2 with far plane if (t1 > t2) std::swap(t1, t2); // Compute the intersection of slab intersection intervals if (t1 > tMin) tMin = t1; if (t2 > tMax) tMax = t2; // Exit with no collision as soon as slab intersection becomes empty if (tMin > tMax) return false; } } // Ray intersects all 3 slabs. Return point (q) and intersection t value (tmin) intersect = origin + ray * tMin; return true; } /*************************************************************************/ /*! \fn void getStaticExtremaProjection(std::vector<vec3>& t_Points, const vec3& axis, f32& min, f32& max) \brief project a static obb onto an axis */ /*************************************************************************/ void getStaticExtremaProjection(std::vector<vec3>& t_Points, const vec3& axis, f32& min, f32& max) { min = Dot(t_Points[0], axis); max = min; u32 total = t_Points.size(); for (u32 i = 1; i < total; ++i) { f32 p = Dot(t_Points[i], axis); max = (std::max)(p, max); min = (std::min)(p, min); } } /*************************************************************************/ /*! \fn void getDynamicExtremaProjection(std::vector<vec3>& t_Points, const vec3& vector, const vec3& axis, f32& min, f32& max) \brief project a dynamic obb onto an axis */ /*************************************************************************/ void getDynamicExtremaProjection(std::vector<vec3>& t_Points, const vec3& vector, const vec3& axis, f32& min, f32& max) { min = (std::numeric_limits<f32>::max)(); max = -(std::numeric_limits<f32>::max)(); u32 total = t_Points.size(); for (u32 i = 0; i < total; ++i) { f32 p = Dot(t_Points[i], axis); max = (std::max)(p, max); min = (std::min)(p, min); p = Dot(t_Points[i] + vector, axis); max = (std::max)(p, max); min = (std::min)(p, min); } } /*************************************************************************/ /*! \fn bool IsCollided(BS& t_BS1, BS& t_BS2, vec3& t_V1, vec3& t_V2, f32 t_DtTimeBound, f32& t_IntersectionTime) \brief dynamic Sphere vs Sphere collsion test */ /*************************************************************************/ bool IsCollided(BS& t_BS1, BS& t_BS2, vec3& t_V1, vec3& t_V2, f32 t_DtTimeBound, f32& t_IntersectionTime) { vec3 t_RelativeVelocity(t_V2 - t_V1); //<! treat BS 1 as a relative center, find vector between Sphere centres vec3 t_RelativePositionVector(t_BS1.m_Center - t_BS2.m_Center); BS t_RelativeSphere; t_RelativeSphere.m_Center = vec3(0, 0, 0); t_RelativeSphere.m_Radius = t_BS1.m_Radius + t_BS2.m_Radius; f32 t_direction = (Dot(-t_RelativePositionVector, t_RelativeVelocity)); vec3 t_x; f32 t_lineSegmentSquareLength(Dot(t_RelativePositionVector, t_RelativePositionVector)); if (t_direction <= 0) { t_IntersectionTime = 0.f; return true; } else if (t_direction >= t_lineSegmentSquareLength) { t_IntersectionTime = t_DtTimeBound; return true; } else { t_IntersectionTime = t_direction / t_lineSegmentSquareLength; return true; } return false; } /*************************************************************************/ /*! \fn bool IntersectSegmentPlane(const vec3& a, const vec3& ray, const Plane& p, float &t, vec3 &q) \brief line segment vs plane test */ /*************************************************************************/ bool IntersectSegmentPlane(const vec3& a, const vec3& ray, const Plane& p, float &t, vec3 &q) { // Compute the t value for the directed line ab intersecting the plane vec3 ab = ray; vec3 b = a + ray; f32 i_t; vec3 n(p.a, p.b, p.c); f32 d = Dot(n, ab); f32 num = p.d - Dot(n, a); i_t = (num) / d; // If t in [0..1] compute and return intersection point if (i_t == i_t && i_t >= 0.0f && i_t <= 1.0f) { t = i_t; q = a + t * ab; return true; } // Else no intersection return false; } bool IntersectSegmentPlane(const vec3& a, const vec3& ray, const vec3& d, const vec3& e, vec3& f, float &t, vec3 &q) { Plane p; vec3 v = Cross(e - d, f - d); p.a = v.x; p.b = v.y; p.c = v.z; p.d = Dot(d, v); return IntersectSegmentPlane(a, ray, p, t, q); } /*************************************************************************/ /*! \fn bool IntersectSegmentPlane(const vec3& a, const vec3& ray, const Plane& p, float &t, vec3 &q) \brief line vs plane test */ /*************************************************************************/ bool IntersectRayPlane(const vec3& a, const vec3& ray, const Plane& p, float &t, vec3 &q) { // Compute the t value for the directed line ab intersecting the plane vec3 b = a + ray; vec3 ab = ray; f32 i_t; vec3 n(p.a, p.b, p.c); f32 d = Dot(n, ray); // closest distance to triangle based on normal f32 num = p.d - Dot(n, a); // which side of the triangle is the origin of the ray #if 0 //<! return if ray is parallel to the plane, if a is within the plane return true, else return false if (d == 0.0f && num == 0.f){ t = 0; q = a; return true; } else if (d == 0.0f) return false; #endif i_t = (num) / d; // If t > 0 compute and return intersection point if (i_t == i_t && i_t >= 0.0f) { t = i_t; q = a + t * ray; return true; } // Else no intersection return false; } bool IntersectRayPlane(const vec3& a, const vec3& ray, const vec3& d, const vec3& e, const vec3& f, float &t, vec3 &q) { Plane p; vec3 v = Cross(e - d, f - d); p.a = v.x; p.b = v.y; p.c = v.z; p.d = Dot(v, d); return IntersectRayPlane(a, ray, p, t, q); } bool IsPointInRect(const vec2& t_point , const vec2& t_rectCenter , const vec2& t_rectSize) { //Check if point is inside rect if (t_point.x >= t_rectCenter.x - t_rectSize.x / 2.0f && t_point.x <= t_rectCenter.x + t_rectSize.x / 2.0f && t_point.y >= t_rectCenter.y - t_rectSize.y / 2.0f && t_point.y <= t_rectCenter.y + t_rectSize.y / 2.0f ) { //Return true if point is inside rect return true; } //else return false return false; } bool IntersectRayTriangle( const Vec3 &orig, const Vec3 &dir, const Vec3 &v0, const Vec3 &v1, const Vec3 &v2, f32 &t) { // compute plane's normal Vec3 v0v1 = v1 - v0; Vec3 v0v2 = v2 - v0; // no need to normalize Vec3 N = Cross(v0v1, v0v2); // N N = Normalise(N); // check if ray and plane are parallel ? float NdotRayDirection = Dot(N,dir); if (fabs(NdotRayDirection) < EPSILON) // almost 0 , ray is othogonal to the notmal vector return false; // they are parallel so they don't intersect ! // compute d parameter using equation 2 f32 d = -Dot(N,v0); // compute time to intersect infinite plane equatin t = -(Dot(N,orig) + d) / NdotRayDirection; // check if the triangle is in behind the ray if (t < 0) return false; // the triangle is behind // compute the intersection point using equation 1 Vec3 P = orig + t * dir; Vec3 R = P - v0; // edge 1 Vec3 Q1 = v1 - v0; // edge 2 Vec3 Q2 = v2 - v0; f32 d0 = Dot(R, Q1); f32 d1 = Dot(R, Q2); f32 q1q2 = Dot(Q1, Q2); f32 q1Sq = Dot(Q1, Q1); f32 q2Sq = Dot(Q2, Q2); glm::mat2 m; m[0][0] = q1Sq; m[0][1] = q1q2; m[1][0] = q1q2; m[1][1] = q2Sq; m = glm::inverse(m); vec2 v; v.x = d0; v.y = d1; v = m * v; if (v.x < 0 || v.y < 0 || v.x + v.y > 1.f) return false; return true; // this ray hits the triangle } void MarkAABBAsCollided(HierachicalAABB& t1, HierachicalAABB& t2, u32 i1, u32 i2) { if (i1 == -1 || i2 == -1) return; HierachicalAABBNode& n1(t1.nodes[i1]); HierachicalAABBNode& n2(t2.nodes[i2]); if (AABBAABBCollision(n1.m_AABB, n2.m_AABB)) { n1.collided = true; n2.collided = true; MarkAABBAsCollided(t1, t2, n1.m_LeftChild, n2.m_LeftChild); MarkAABBAsCollided(t1, t2, n1.m_LeftChild, n2.m_RightChild); MarkAABBAsCollided(t1, t2, n1.m_RightChild, n2.m_LeftChild); MarkAABBAsCollided(t1, t2, n1.m_RightChild, n2.m_RightChild); } } void hAABBhAABBCollision(HierachicalAABB& t1, HierachicalAABB& t2) { std::for_each(t1.nodes.begin(), t1.nodes.end(), [](HierachicalAABBNode& n){n.collided = false; }); std::for_each(t2.nodes.begin(), t2.nodes.end(), [](HierachicalAABBNode& n){n.collided = false; }); u32 total1(t1.nodes.size()), total2(t2.nodes.size()); u32 startIndex1(0); u32 startIndex2(0); MarkAABBAsCollided(t1, t2, startIndex1, startIndex2); } void MarkBSAsCollided(HierachicalBS& t1, HierachicalBS& t2, u32 i1, u32 i2) { if (i1 == -1 || i2 == -1) return; HierachicalBSNode& n1(t1.nodes[i1]); HierachicalBSNode& n2(t2.nodes[i2]); if (SphereSphereCollision(n1.m_BS, n2.m_BS)) { n1.collided = true; n2.collided = true; MarkBSAsCollided(t1, t2, n1.m_LeftChild, n2.m_LeftChild); MarkBSAsCollided(t1, t2, n1.m_LeftChild, n2.m_RightChild); MarkBSAsCollided(t1, t2, n1.m_RightChild, n2.m_LeftChild); MarkBSAsCollided(t1, t2, n1.m_RightChild, n2.m_RightChild); } } void hBShBSCollision(HierachicalBS& t1, HierachicalBS& t2) { std::for_each(t1.nodes.begin(), t1.nodes.end(), [](HierachicalBSNode& n){n.collided = false; }); std::for_each(t2.nodes.begin(), t2.nodes.end(), [](HierachicalBSNode& n){n.collided = false; }); u32 total1(t1.nodes.size()), total2(t2.nodes.size()); u32 startIndex1(0); u32 startIndex2(0); MarkBSAsCollided(t1, t2, startIndex1, startIndex2); } }
[ "muhammad.shahir.bin.mohamed.suhaimi@continental-corporation.com" ]
muhammad.shahir.bin.mohamed.suhaimi@continental-corporation.com
8d4659a7048908544fc4162ed83c381f65148f40
87c4fbb55e78981c19923753948303d08b6236ba
/WS02/at_home/src/Kingdom.cpp
fe5e011e1828ec64bff33e3de15f1982e38aa574
[]
no_license
jamesgiroux52/OOP244-Workshops
d8ffcfc82c355b004a9c3846387e286f943e18bd
dc9aff6625aca27528a1a9e607800293bcf13587
refs/heads/master
2022-12-09T10:51:43.646072
2019-08-02T19:27:05
2019-08-02T19:27:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,321
cpp
/* ============================================================================ Name : kingdom.cpp Author : James Giroux - jgiroux1@myseneca.ca Student # : 129198164 Section : SEE Date : May 19, 2019 ============================================================================ */ /* ============================================================================ Description : Kingdom module - source code ============================================================================ */ #include <iostream> #include "Kingdom.h" using namespace std; namespace sict { // display single kingdom void display(const Kingdom& kingdom){ cout << kingdom.m_name << ", population " << kingdom.m_population << endl; } // display array of kingdoms void display(const Kingdom* kingdom, int size){ int totalPopulation = 0; cout << "------------------------------" << endl; cout << "Kingdoms of SICT" << endl; cout << "------------------------------" << endl; for (int i = size - 1; i >= 0; --i){ cout << i + 1 << ". "; display(kingdom[i]); totalPopulation += kingdom[i].m_population; } cout << "------------------------------" << endl; cout << "Total population of SICT: " << totalPopulation << endl; cout << "------------------------------" << endl; } }
[ "jamesmac@192.168.2.11" ]
jamesmac@192.168.2.11
3ad2571fc56777291bfe3c1e78b423f7df5bd860
789f0be38ab96a1f1f6c2f88612f9d72e5bae41d
/src/libtriton/bindings/python/objects/pyMemoryAccess.cpp
5d028ae0bcca26a0fa1ce9dfbde805673d4e26f0
[ "BSD-2-Clause" ]
permissive
KnoooW/Triton
c08710ce4d29179fdf994964e80cec51b41db4c8
3f553314dc5280cef17f0c8bc863764046e8b363
refs/heads/master
2021-04-29T09:43:19.754825
2016-12-28T18:40:12
2016-12-28T18:40:12
77,657,963
1
0
null
2016-12-30T03:37:02
2016-12-30T03:37:01
null
UTF-8
C++
false
false
18,421
cpp
//! \file /* ** Copyright (C) - Triton ** ** This program is under the terms of the BSD License. */ #ifdef TRITON_PYTHON_BINDINGS #include <exceptions.hpp> #include <memoryAccess.hpp> #include <pythonObjects.hpp> #include <pythonUtils.hpp> #include <pythonXFunctions.hpp> /*! \page py_MemoryAccess_page MemoryAccess \brief [**python api**] All information about the memory access python object. \tableofcontents \section py_Memory_description Description <hr> This object is used to represent a memory access. \subsection py_MemoryAccess_example Example ~~~~~~~~~~~~~{.py} >>> processing(inst) >>> print inst 40000: mov ah, byte ptr [rdx + rcx*2 + 0x100] >>> op1 = inst.getOperands()[1] >>> print op1 [@0x6135a]:8 bv[7..0] >>> print op1.getBaseRegister() rdx:64 bv[63..0] >>> print op1.getIndexRegister() rcx:64 bv[63..0] >>> print op1.getScale() 0x2:8 bv[7..0] >>> print op1.getDisplacement() 0x100:8 bv[7..0] >>> print op1.getLeaAst() (bvadd (_ bv397882 64) (bvadd (bvmul (_ bv16 64) (_ bv2 64)) (_ bv256 64))) >>> print hex(op1.getLeaAst().evaluate()) 0x6135aL >>> print hex(op1.getAddress()) 0x6135aL >>> print op1.getSize() 1 ~~~~~~~~~~~~~ \subsection py_MemoryAccess_constructor Constructor ~~~~~~~~~~~~~{.py} >>> mem = MemoryAccess(0x400f4d3, 8, 0x6162636465666768) >>> print mem [@0x400f4d3]:64 bv[63..0] >>> hex(mem.getAddress()) '0x400f4d3' >>> mem.getSize() 8 >>> hex(mem.getConcreteValue()) '0x6162636465666768L' ~~~~~~~~~~~~~ \section MemoryAccess_py_api Python API - Methods of the MemoryAccess class <hr> - <b>integer getAddress(void)</b><br> Returns the target address of the memory access.<br> e.g: `0x7fffdd745ae0` - <b>\ref py_Register_page getBaseRegister(void)</b><br> Returns the base register (if exists) of the memory access<br> - <b>integer getBitSize(void)</b><br> Returns the size (in bits) of the memory access.<br> e.g: `64` - <b>\ref py_Bitvector_page getBitvector(void)</b><br> Returns the bitvector of the memory cells. - <b>integer getConcreteValue(void)</b><br> Returns the concrete value. It's basically the content which has been LOADED or STORED. Note that getting the concrete value does not relfect the real internal memory state. If you want to know the internal state of a memory cell, use the triton::API::getConcreteMemoryValue() function. - <b>\ref py_Immediate_page getDisplacement(void)</b><br> Returns the displacement (if exists) of the memory access. - <b>\ref py_Register_page getIndexRegister(void)</b><br> Returns the index register (if exists) of the memory access.<br> - <b>\ref py_AstNode_page getLeaAst(void)</b><br> Returns the AST of the memory access (LEA). - <b>\ref py_Immediate_page getScale(void)</b><br> Returns the scale (if exists) of the memory access. - <b>\ref py_Register_page getSegmentRegister(void)</b><br> Returns the segment register (if exists) of the memory access. Note that to be user-friendly, the segment register is used as base register and not as a selector into the GDT.<br> - <b>integer getSize(void)</b><br> Returns the size (in bytes) of the memory access.<br> e.g: `8` - <b>\ref py_OPERAND_page getType(void)</b><br> Returns type of the memory access. In this case this function returns `OPERAND.MEM`. - <b>void setBaseRegister(\ref py_Register_page reg)</b><br> Sets the base register of the memory access. - <b>void setConcreteValue(integer value)</b><br> Sets a concrete value to this memory access. Note that by setting the concrete value does not affect the internal memory value. If you want to define a concrete value at a specific memory cells, use the triton::API::setConcreteMemoryValue() function. - <b>void setDisplacement(\ref py_Immediate_page imm)</b><br> Sets the displacement of the memory access. - <b>void setIndexRegister(\ref py_Register_page reg)</b><br> Sets the index register of the memory' access. - <b>void setScale(\ref py_Immediate_page imm)</b><br> Sets the scale of the memory access. */ namespace triton { namespace bindings { namespace python { //! MemoryAccess destructor. void MemoryAccess_dealloc(PyObject* self) { std::cout << std::flush; delete PyMemoryAccess_AsMemoryAccess(self); Py_DECREF(self); } static PyObject* MemoryAccess_getAddress(PyObject* self, PyObject* noarg) { try { return PyLong_FromUint64(PyMemoryAccess_AsMemoryAccess(self)->getAddress()); } catch (const triton::exceptions::Exception& e) { return PyErr_Format(PyExc_TypeError, "%s", e.what()); } } static PyObject* MemoryAccess_getLeaAst(PyObject* self, PyObject* noarg) { try { if (PyMemoryAccess_AsMemoryAccess(self)->getLeaAst() == nullptr) { Py_INCREF(Py_None); return Py_None; } return PyAstNode(PyMemoryAccess_AsMemoryAccess(self)->getLeaAst()); } catch (const triton::exceptions::Exception& e) { return PyErr_Format(PyExc_TypeError, "%s", e.what()); } } static PyObject* MemoryAccess_getBaseRegister(PyObject* self, PyObject* noarg) { try { triton::arch::Register reg(PyMemoryAccess_AsMemoryAccess(self)->getBaseRegister()); return PyRegister(reg); } catch (const triton::exceptions::Exception& e) { return PyErr_Format(PyExc_TypeError, "%s", e.what()); } } static PyObject* MemoryAccess_getBitSize(PyObject* self, PyObject* noarg) { try { return PyLong_FromUint32(PyMemoryAccess_AsMemoryAccess(self)->getBitSize()); } catch (const triton::exceptions::Exception& e) { return PyErr_Format(PyExc_TypeError, "%s", e.what()); } } static PyObject* MemoryAccess_getBitvector(PyObject* self, PyObject* noarg) { try { return PyBitvector(*PyMemoryAccess_AsMemoryAccess(self)); } catch (const triton::exceptions::Exception& e) { return PyErr_Format(PyExc_TypeError, "%s", e.what()); } } static PyObject* MemoryAccess_getConcreteValue(PyObject* self, PyObject* noarg) { try { return PyLong_FromUint512(PyMemoryAccess_AsMemoryAccess(self)->getConcreteValue()); } catch (const triton::exceptions::Exception& e) { return PyErr_Format(PyExc_TypeError, "%s", e.what()); } } static PyObject* MemoryAccess_getDisplacement(PyObject* self, PyObject* noarg) { try { triton::arch::Immediate imm(PyMemoryAccess_AsMemoryAccess(self)->getDisplacement()); return PyImmediate(imm); } catch (const triton::exceptions::Exception& e) { return PyErr_Format(PyExc_TypeError, "%s", e.what()); } } static PyObject* MemoryAccess_getIndexRegister(PyObject* self, PyObject* noarg) { try { triton::arch::Register reg(PyMemoryAccess_AsMemoryAccess(self)->getIndexRegister()); return PyRegister(reg); } catch (const triton::exceptions::Exception& e) { return PyErr_Format(PyExc_TypeError, "%s", e.what()); } } static PyObject* MemoryAccess_getScale(PyObject* self, PyObject* noarg) { try { triton::arch::Immediate imm(PyMemoryAccess_AsMemoryAccess(self)->getScale()); return PyImmediate(imm); } catch (const triton::exceptions::Exception& e) { return PyErr_Format(PyExc_TypeError, "%s", e.what()); } } static PyObject* MemoryAccess_getSegmentRegister(PyObject* self, PyObject* noarg) { try { triton::arch::Register reg(PyMemoryAccess_AsMemoryAccess(self)->getSegmentRegister()); return PyRegister(reg); } catch (const triton::exceptions::Exception& e) { return PyErr_Format(PyExc_TypeError, "%s", e.what()); } } static PyObject* MemoryAccess_getSize(PyObject* self, PyObject* noarg) { try { return PyLong_FromUint32(PyMemoryAccess_AsMemoryAccess(self)->getSize()); } catch (const triton::exceptions::Exception& e) { return PyErr_Format(PyExc_TypeError, "%s", e.what()); } } static PyObject* MemoryAccess_getType(PyObject* self, PyObject* noarg) { try { return PyLong_FromUint32(PyMemoryAccess_AsMemoryAccess(self)->getType()); } catch (const triton::exceptions::Exception& e) { return PyErr_Format(PyExc_TypeError, "%s", e.what()); } } static PyObject* MemoryAccess_setBaseRegister(PyObject* self, PyObject* reg) { try { triton::arch::MemoryAccess* mem; if (!PyRegister_Check(reg)) return PyErr_Format(PyExc_TypeError, "MemoryAccess::setBaseRegister(): Expected a Register as argument."); mem = PyMemoryAccess_AsMemoryAccess(self); mem->setBaseRegister(*PyRegister_AsRegister(reg)); Py_INCREF(Py_None); return Py_None; } catch (const triton::exceptions::Exception& e) { return PyErr_Format(PyExc_TypeError, "%s", e.what()); } } static PyObject* MemoryAccess_setConcreteValue(PyObject* self, PyObject* value) { try { triton::arch::MemoryAccess* mem; if (!PyLong_Check(value) && !PyInt_Check(value)) return PyErr_Format(PyExc_TypeError, "MemoryAccess::setConcretevalue(): Expected an integer as argument."); mem = PyMemoryAccess_AsMemoryAccess(self); mem->setConcreteValue(PyLong_AsUint512(value)); Py_INCREF(Py_None); return Py_None; } catch (const triton::exceptions::Exception& e) { return PyErr_Format(PyExc_TypeError, "%s", e.what()); } } static PyObject* MemoryAccess_setDisplacement(PyObject* self, PyObject* imm) { try { triton::arch::MemoryAccess* mem; if (!PyImmediate_Check(imm)) return PyErr_Format(PyExc_TypeError, "MemoryAccess::setDisplacement(): Expected an Immediate as argument."); mem = PyMemoryAccess_AsMemoryAccess(self); mem->setDisplacement(*PyImmediate_AsImmediate(imm)); Py_INCREF(Py_None); return Py_None; } catch (const triton::exceptions::Exception& e) { return PyErr_Format(PyExc_TypeError, "%s", e.what()); } } static PyObject* MemoryAccess_setIndexRegister(PyObject* self, PyObject* reg) { try { triton::arch::MemoryAccess* mem; if (!PyRegister_Check(reg)) return PyErr_Format(PyExc_TypeError, "MemoryAccess::setIndexRegister(): Expected a Register as argument."); mem = PyMemoryAccess_AsMemoryAccess(self); mem->setIndexRegister(*PyRegister_AsRegister(reg)); Py_INCREF(Py_None); return Py_None; } catch (const triton::exceptions::Exception& e) { return PyErr_Format(PyExc_TypeError, "%s", e.what()); } } static PyObject* MemoryAccess_setScale(PyObject* self, PyObject* imm) { try { triton::arch::MemoryAccess* mem; if (!PyImmediate_Check(imm)) return PyErr_Format(PyExc_TypeError, "MemoryAccess::setScale(): Expected an Immediate as argument."); mem = PyMemoryAccess_AsMemoryAccess(self); mem->setScale(*PyImmediate_AsImmediate(imm)); Py_INCREF(Py_None); return Py_None; } catch (const triton::exceptions::Exception& e) { return PyErr_Format(PyExc_TypeError, "%s", e.what()); } } static PyObject* MemoryAccess_setSegmentRegister(PyObject* self, PyObject* reg) { try { triton::arch::MemoryAccess* mem; if (!PyRegister_Check(reg)) return PyErr_Format(PyExc_TypeError, "MemoryAccess::setSegmentRegister(): Expected a Register as argument."); mem = PyMemoryAccess_AsMemoryAccess(self); mem->setSegmentRegister(*PyRegister_AsRegister(reg)); Py_INCREF(Py_None); return Py_None; } catch (const triton::exceptions::Exception& e) { return PyErr_Format(PyExc_TypeError, "%s", e.what()); } } static int MemoryAccess_print(PyObject* self) { std::cout << PyMemoryAccess_AsMemoryAccess(self); return 0; } static PyObject* MemoryAccess_str(PyObject* self) { try { std::stringstream str; str << PyMemoryAccess_AsMemoryAccess(self); return PyString_FromFormat("%s", str.str().c_str()); } catch (const triton::exceptions::Exception& e) { return PyErr_Format(PyExc_TypeError, "%s", e.what()); } } //! MemoryAccess methods. PyMethodDef MemoryAccess_callbacks[] = { {"getAddress", MemoryAccess_getAddress, METH_NOARGS, ""}, {"getBaseRegister", MemoryAccess_getBaseRegister, METH_NOARGS, ""}, {"getBitSize", MemoryAccess_getBitSize, METH_NOARGS, ""}, {"getBitvector", MemoryAccess_getBitvector, METH_NOARGS, ""}, {"getConcreteValue", MemoryAccess_getConcreteValue, METH_NOARGS, ""}, {"getDisplacement", MemoryAccess_getDisplacement, METH_NOARGS, ""}, {"getIndexRegister", MemoryAccess_getIndexRegister, METH_NOARGS, ""}, {"getLeaAst", MemoryAccess_getLeaAst, METH_NOARGS, ""}, {"getScale", MemoryAccess_getScale, METH_NOARGS, ""}, {"getSegmentRegister", MemoryAccess_getSegmentRegister, METH_NOARGS, ""}, {"getSize", MemoryAccess_getSize, METH_NOARGS, ""}, {"getType", MemoryAccess_getType, METH_NOARGS, ""}, {"setBaseRegister", MemoryAccess_setBaseRegister, METH_O, ""}, {"setConcreteValue", MemoryAccess_setConcreteValue, METH_O, ""}, {"setDisplacement", MemoryAccess_setDisplacement, METH_O, ""}, {"setIndexRegister", MemoryAccess_setIndexRegister, METH_O, ""}, {"setScale", MemoryAccess_setScale, METH_O, ""}, {"setSegmentRegister", MemoryAccess_setSegmentRegister, METH_O, ""}, {nullptr, nullptr, 0, nullptr} }; PyTypeObject MemoryAccess_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, /* ob_size */ "MemoryAccess", /* tp_name */ sizeof(MemoryAccess_Object), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)MemoryAccess_dealloc, /* tp_dealloc */ (printfunc)MemoryAccess_print, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc)MemoryAccess_str, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "MemoryAccess objects", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ MemoryAccess_callbacks, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ 0, /* tp_del */ 0 /* tp_version_tag */ }; PyObject* PyMemoryAccess(const triton::arch::MemoryAccess& mem) { MemoryAccess_Object* object; PyType_Ready(&MemoryAccess_Type); object = PyObject_NEW(MemoryAccess_Object, &MemoryAccess_Type); if (object != NULL) object->mem = new triton::arch::MemoryAccess(mem); return (PyObject*)object; } }; /* python namespace */ }; /* bindings namespace */ }; /* triton namespace */ #endif /* TRITON_PYTHON_BINDINGS */
[ "jonathan.salwan@gmail.com" ]
jonathan.salwan@gmail.com
402850ecca7a34c7e1cd9b27250920a1c45c33a1
29b81bdc013d76b057a2ba12e912d6d4c5b033ef
/boost/include/boost/unordered/detail/extract_key.hpp
eebaa144b2e4b1bbf5bffeb06e27c59d2f65c5b5
[]
no_license
GSIL-Monitor/third_dependences
864d2ad73955ffe0ce4912966a4f0d1c60ebd960
888ebf538db072a92d444a9e5aaa5e18b0f11083
refs/heads/master
2020-04-17T07:32:49.546337
2019-01-18T08:47:28
2019-01-18T08:47:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
129
hpp
version https://git-lfs.github.com/spec/v1 oid sha256:4c082cc19fa048e9477be2ab68a984d15a3db9c74adf321423442ca7dac2738e size 6348
[ "you@example.com" ]
you@example.com
5c5fbe3316c0df3857cc324ccd8e6cd95bcc60ed
18fa1c3459c607891d7cdaaa413e20b5eca07638
/CppTest/TestString/main.cpp
ab4e009e740915a1e1dfad33b30c0e0c3f3e6b64
[]
no_license
lkllk/CPP
fb2974e832c1796ddf9340cef0148bdbe8bb217d
3c442ec7bf647d2bf6c67a6c1a0ce9893878b061
refs/heads/master
2022-01-23T05:28:20.491699
2018-05-17T05:36:09
2018-05-17T05:36:09
null
0
0
null
null
null
null
GB18030
C++
false
false
1,856
cpp
#include "string_utils.h" #include <string> using namespace std; int main(int agrc,char* argv[]) { string aaa = "abc"; string bbb = "1"; bool result = IsMatchPrefix(aaa,bbb); result = IsContainsSubStr(aaa,bbb); vector<string> aVec; StringSplit("123&","&",aVec,false); return 0; } /* class Person { public: Person(int age):_Age(age) { } Person(const Person& rhs) { this->_Age = rhs._Age; } Person& operator=(const Person& rhs) { this->_Age = rhs._Age; return *this; } public: int _Age; }; int main(int agrc,char* argv[]) { Person p1(8); // 直接调用构造方法 Person p2 = 8; // 直接调用构造方法,不需要临时对象,等价于Person p1(8) Person p3 = Person(8); // 直接调用构造方法,而且只调用一次,等价于Person p1(8) Person p4 = p1; // 调用copy构造 p4 = p1; // 调用copy赋值 p4 = Person(9); // 先调用构造方法,产生匿名对象,再调用copy赋值 p4 = 9; // 先调用构造方法,产生临时对象,再调用copy赋值 return 0; } */ /* int main(int argc, char* argv[]) { string aa = "abcd"; string bb = aa; printf("aa[%x:%s],bb[%x:%s]\n", &(aa[0]), aa.c_str(), &(bb[0]), bb.c_str()); char* pc= (char*)(&aa[1]); printf("pc[%x:%c]\n", pc, *pc); *pc = 'h'; printf("pc[%x:%c]\n", pc, *pc); printf("aa[%x:%s],bb[%x:%s]\n", &(aa[0]), aa.c_str(), &(bb[0]), bb.c_str()); return 0; } */ /* void setCharPointer(const char* pc) { string ss = "abcde"; pc = ss.c_str(); } */ /* int main(int argc, char* argv[]) { string ss; printf("[%s]",ss.c_str()); char* pc = NULL; setCharPointer(pc); printf("[%s]",pc); string s1 = "aa"; string s2 = "bb"; string s3 = s1+"_"+s2; char tmp[32] = "abcdef"; string s4 = tmp; s4[3] = 0; tmp[2] = '\0'; string s5 = tmp; return 0; } */
[ "nzbbody@163.com" ]
nzbbody@163.com
43c98f29013d86141c644d063916ab5666e8ca32
b27a3de8fa0372e6ed8a1c0e6e14fc3c58879a2f
/TopK/DataDefinition.h
757f6e2fbc08b78e86903d4f348cbfdb6928c359
[]
no_license
huangfeidian/TopK-orthogonal-range-search-
b14cd0e179125d4d2d56b33e447b0e1741c805f0
10d2f53e7a29a5a6ee805bc8d314d151693ccbc4
refs/heads/master
2021-01-23T20:13:20.696117
2015-09-13T08:19:44
2015-09-13T08:19:44
42,131,660
0
0
null
null
null
null
UTF-8
C++
false
false
1,660
h
#ifndef __H_DATADEFINITION_H__ #define __H_DATADEFINITION_H__ template <typename T1> class Position { public: T1 x; T1 y; Position(T1 in_x, T1 in_y) :x(in_x), y(in_y) { } bool operator==(const Position<T1>& a) { return x == a.x&&y == a.y; } Position() { } }; template <typename T> bool operator==(const Position<T>& a, const Position<T>& b) { return a.x == b.x&&a.y == b.y; } template <typename T> bool xpos_cmp(const Position<T>& a, const Position<T>& b) { return a.x < b.x; } template <typename T> bool ypos_cmp(const Position<T>& a, const Position<T>& b) { return a.y < b.y; } template <typename T1> class PackedPos { public: T1 x; T1 y; T1 neg_x; T1 neg_y; PackedPos(T1 in_x, T1 in_y) :x(in_x), y(in_y) { neg_x=-1*x; neg_y=-1*y; } PackedPos() { } }; template <typename T1, typename T2> class Node { public: Position<T1> pos; T2 priority; Node(T1 in_x, T1 in_y, T2 in_priority) :pos(in_x, in_y), priority(in_priority) { } Node() { } bool operator==(const Node<T1, T2>& a) { return priority == a.priority&&pos == a.pos; } }; template <typename T1, typename T2> bool operator==(const Node<T1, T2>& a, const Node<T1, T2>& b) { return a.pos == b.pos&&a.priority == b.priority; } template <typename T1, typename T2> class PriorityCmp { public: bool operator()(const Node<T1, T2>& a, const Node<T1, T2>& b) { return a.priority > b.priority; } }; template <typename T1,typename T2> bool xpos_cmp(const Node<T1,T2>& a, const Node<T1,T2>& b) { return a.pos.x < b.pos.x; } template <typename T1, typename T2> bool ypos_cmp(const Node<T1, T2>& a, const Node<T1,T2>& b) { return a.pos.y < b.pos.y; } #endif
[ "huanghuiliang@live.cn" ]
huanghuiliang@live.cn
8cd4cf60e2b9a7f011c675b97aac3439273a2c35
cb142e98b043e7088f0fe009f5159928877acf1b
/Tricycle/A9_Pid_2_ok/BBK5_Car_Run.ino
2355d128e79f9b03702bab1c461a9d6094287b43
[]
no_license
wetnt/Arduino_public
ef30502b4a30e099a09e2617fd58fd3a9801cf13
4cc331e2f43dda0df8f78d9cfe924da130ca5df3
refs/heads/master
2021-01-23T09:38:43.302783
2019-09-12T00:29:43
2019-09-12T00:29:43
33,909,041
2
2
null
null
null
null
UTF-8
C++
false
false
1,937
ino
//=================================================================== Wheel wr, wl; int wvr = 0, wvl = 0; int loopMS = 50;//50ms //=================================================================== void Car_Init() { //小车初始化 //--------------------------------------------------------- lg(F("Car_Init()...")); wr.init(2.5, 0, 20, 8, 9, 10); wl.init(2.5, 1, 20, 11, 12, 13); attachInterrupt(wr.I, interrupt_run_r, FALLING); attachInterrupt(wl.I, interrupt_run_l, FALLING); delay(500); lg(F("ok")); lg(); //--------------------------------------------------------- } void interrupt_run_r() { wr.intN++; wr.speedTimes(); }; void interrupt_run_l() { wl.intN++; wl.speedTimes(); }; void Car_Speed_Start() { //运行速度初始化 lg(F("Car_Speed_Start()...")); lg(); wl.sets(20, 20, "wl"); wr.sets(20, 20, "wr"); lg(F("Car_Speed_Start()...ok")); lg(); } void Car_SetVt(int r, int l) { wvr = r; wvl = l; } void Car_loop() { //--------------------------------------------------------- wr.runx(wvr); wl.runx(wvr); smartDelay(loopMS); //--------------------------------------------------------- //lg("CarCt = "); lg(r); lg(","); lg(l); lg(" "); //lg("Speed = "); lg(wr.sNow); lg(" "); lg(wr.sNow2); lg(" = "); lg(wl.sNow); lg(" "); lg(wl.sNow2); lg(" "); //lg(); //--------------------------------------------------------- } void Car_loopx(int r, int l, int delayMS) { //10ms运行一次 //--------------------------------------------------------- loopMS = delayMS; wr.runx(r); wl.runx(l); smartDelay(loopMS); //--------------------------------------------------------- //lg("CarCt = "); lg(r); lg(","); lg(l); lg(" "); //lg("Speed = "); lg(wr.sNow); lg(" "); lg(wr.sNow2); lg(" = "); lg(wl.sNow); lg(" "); lg(wl.sNow2); lg(" "); //lg(); //--------------------------------------------------------- } //===================================================================
[ "jinping.xu@woqu.com" ]
jinping.xu@woqu.com
3d6e90c4c7309d7d372b29b7470382639f6d8787
df90ed23a49dba79f61e5a28366424f0ecec60de
/src/configuration/csv/write.cpp
78ed5428772e950058bfb5f9fe204ac4c0a60c65
[ "BSD-2-Clause" ]
permissive
Damdoshi/LibLapin
306e8ae8be70be9e4de93db60913c4f092a714a7
41491d3d3926b8e42e3aec8d1621340501841aae
refs/heads/master
2023-09-03T10:11:06.743172
2023-08-25T08:03:33
2023-08-25T08:03:33
64,509,332
39
12
NOASSERTION
2021-02-03T17:18:22
2016-07-29T20:43:25
C++
UTF-8
C++
false
false
810
cpp
// Jason Brillante "Damdoshi" // Hanged Bunny Studio 2014-2018 // // Lapin library #include "lapin_private.h" char *_bunny_write_csv(const t_bunny_configuration *config) { std::stringstream ss; SmallConf &conf = *(SmallConf*)config; size_t i, j; char *ret; for (j = 0; j < conf.Size(); ++j) { for (i = 0; i < conf[j].Size(); ++i) { if (conf[j][i].have_value) writevalue(ss, conf[j][i]); if (i + 1 < conf[j].Size()) ss << ";"; } ss << std::endl; } if ((ret = (char*)bunny_malloc(sizeof(*ret) * (ss.str().size() + 1))) == NULL) scream_error_if (return (NULL), ENOMEM, "%p -> %p", "ressource,configuration", config, ret); strcpy(ret, ss.str().c_str()); scream_log_if("%p -> %p", "ressource,configuration", config, ret); return (ret); }
[ "jbrillante@anevia.com" ]
jbrillante@anevia.com
327783ae9a1586746170af6ff2f54eaa25edf075
c37fcc7c5314de1f497011e3f0c36f1bb31ad413
/graphchi/toolkits/collaborative_filtering/rating2.cpp
0320d5e284ff0ec890aee89659a03a33284a600b
[]
no_license
lewisren/Genie
99234fcb4d6c2b50ab31d7442b3aabc50f004d2c
f0ae52c8328a50c38b643b342a74aeadc53ef8df
refs/heads/master
2021-01-18T18:12:28.730960
2014-07-31T21:15:22
2014-07-31T21:15:22
10,602,502
0
1
null
null
null
null
UTF-8
C++
false
false
12,507
cpp
/** * @file * @author Danny Bickson, CMU * @version 1.0 * * @section LICENSE * * Copyright [2012] [Carnegie Mellon University] * * 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. * * @section DESCRIPTION * * This program computes top K recommendations based on the linear model computed * by one of: als,sparse_als,wals, sgd and nmf applications. * */ #include "common.hpp" #include "eigen_wrapper.hpp" #include "timer.hpp" int debug; int num_ratings; double knn_sample_percent = 1.0; const double epsilon = 1e-16; timer mytimer; int tokens_per_row = 3; int algo = 0; #define BIAS_POS -1 enum { SVDPP = 0, BIASSGD = 1 }; struct vertex_data { vec ratings; ivec ids; vec pvec; vec weight; double bias; vertex_data() { bias = 0; assert(num_ratings > 0); ratings = zeros(num_ratings); ids = ivec::Zero(num_ratings); assert(D > 0); pvec = zeros(D); weight = zeros(D); } void set_val(int index, float val){ if (index == BIAS_POS) bias = val; else if (index < D) pvec[index] = val; else weight[index-D] = val; } float get_val(int index){ if (index== BIAS_POS) return bias; else if (index < D) return pvec[index]; else return weight[index-D]; } }; struct edge_data { double weight; edge_data() { weight = 0; } edge_data(double weight) : weight(weight) { } }; struct edge_data4 { double weight; double time; edge_data4() { weight = time = 0; } edge_data4(double weight, double time) : weight(weight), time(time) { } }; /** * Type definitions. Remember to create suitable graph shards using the * Sharder-program. */ typedef vertex_data VertexDataType; typedef edge_data EdgeDataType; // Edges store the "rating" of user->movie pair graphchi_engine<VertexDataType, EdgeDataType> * pengine = NULL; std::vector<vertex_data> latent_factors_inmem; /** compute a missing value based on SVD++ algorithm */ float svdpp_predict(const vertex_data& user, const vertex_data& movie, const float rating, double & prediction, void * extra = NULL){ //\hat(r_ui) = \mu + prediction = globalMean; // + b_u + b_i + prediction += user.bias + movie.bias; // + q_i^T *(p_u +sqrt(|N(u)|)\sum y_j) //prediction += dot_prod(movie.pvec,(user.pvec+user.weight)); for (int j=0; j< D; j++) prediction += movie.pvec[j] * (user.pvec[j] + user.weight[j]); prediction = std::min((double)prediction, maxval); prediction = std::max((double)prediction, minval); float err = rating - prediction; if (std::isnan(err)) logstream(LOG_FATAL)<<"Got into numerical errors. Try to decrease step size using the command line: svdpp_user_bias_step, svdpp_item_bias_step, svdpp_user_factor2_step, svdpp_user_factor_step, svdpp_item_step" << std::endl; return err*err; } /** compute a missing value based on bias-SGD algorithm */ float biassgd_predict(const vertex_data& user, const vertex_data& movie, const float rating, double & prediction, void * extra = NULL){ prediction = globalMean + user.bias + movie.bias + dot_prod(user.pvec, movie.pvec); //truncate prediction to allowed values prediction = std::min((double)prediction, maxval); prediction = std::max((double)prediction, minval); //return the squared error float err = rating - prediction; if (std::isnan(err)) logstream(LOG_FATAL)<<"Got into numerical errors. Try to decrease step size using bias-SGD command line arugments)" << std::endl; return err*err; } void rating_stats(){ double min=1e100, max=0, avg=0; int cnt = 0; int startv = 0; int endv = M; for (int i=startv; i< endv; i++){ vertex_data& data = latent_factors_inmem[i]; if (data.ratings.size() > 0){ min = std::min(min, data.ratings[0]); max = std::max(max, data.ratings[0]); if (std::isnan(data.ratings[0])) printf("bug: nan on %d\n", i); else { avg += data.ratings[0]; cnt++; } } } printf("Distance statistics: min %g max %g avg %g\n", min, max, avg/cnt); } #include "io.hpp" void read_factors(std::string base_filename){ if (algo == SVDPP) load_matrix_market_matrix(training + "_U.mm", 0, 2*D); else if (algo == BIASSGD) load_matrix_market_matrix(training + "_U.mm", 0, D); else assert(false); load_matrix_market_matrix(training + "_V.mm", M, D); vec user_bias = load_matrix_market_vector(training +"_U_bias.mm", false, true); assert(user_bias.size() == M); vec item_bias = load_matrix_market_vector(training +"_V_bias.mm", false, true); assert(item_bias.size() == N); for (uint i=0; i<M+N; i++){ latent_factors_inmem[i].bias = ((i<M)?user_bias[i] : item_bias[i-M]); } vec gm = load_matrix_market_vector(training + "_global_mean.mm", false, true); globalMean = gm[0]; } template<typename VertexDataType, typename EdgeDataType> struct RatingVerticesInMemProgram : public GraphChiProgram<VertexDataType, EdgeDataType> { /** * Vertex update function - computes the least square step */ void update(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, graphchi_context &gcontext) { //compute only for user nodes if (vertex.id() >= M) return; vertex_data & vdata = latent_factors_inmem[vertex.id()]; int howmany = (int)(N*knn_sample_percent); assert(howmany > 0 ); vec distances = zeros(howmany); ivec indices = ivec::Zero(howmany); for (int i=0; i< howmany; i++){ indices[i]= -1; } std::vector<bool> curratings; curratings.resize(N); for(int e=0; e < vertex.num_edges(); e++) { //no need to calculate this rating since it is given in the training data reference assert(vertex.edge(e)->vertex_id() - M >= 0 && vertex.edge(e)->vertex_id() - M < N); curratings[vertex.edge(e)->vertex_id() - M] = true; } if (knn_sample_percent == 1.0){ for (uint i=M; i< M+N; i++){ if (curratings[i-M]) continue; vertex_data & other = latent_factors_inmem[i]; double dist; if (algo == SVDPP) svdpp_predict(vdata, other, 0, dist); else biassgd_predict(vdata, other, 0, dist); indices[i-M] = i-M; distances[i-M] = dist + 1e-10; } } else for (int i=0; i<howmany; i++){ int random_other = ::randi(M, M+N-1); vertex_data & other = latent_factors_inmem[random_other]; double dist; if (algo == SVDPP) svdpp_predict(vdata, other, 0, dist); else biassgd_predict(vdata, other, 0, dist); indices[i] = random_other-M; distances[i] = dist; } vec out_dist(num_ratings); ivec indices_sorted = reverse_sort_index2(distances, indices, out_dist, num_ratings); assert(indices_sorted.size() <= num_ratings); assert(out_dist.size() <= num_ratings); vdata.ids = indices_sorted; vdata.ratings = out_dist; if (debug) printf("Closest is: %d with distance %g\n", (int)vdata.ids[0], vdata.ratings[0]); if (vertex.id() % 1000 == 0) printf("Computing recommendations for user %d at time: %g\n", vertex.id()+1, mytimer.current_time()); } }; struct MMOutputter_ratings{ MMOutputter_ratings(std::string fname, uint start, uint end, std::string comment) { assert(start < end); MM_typecode matcode; set_matcode(matcode); FILE * outf = fopen(fname.c_str(), "w"); assert(outf != NULL); mm_write_banner(outf, matcode); if (comment != "") fprintf(outf, "%%%s\n", comment.c_str()); mm_write_mtx_array_size(outf, end-start, num_ratings+1); for (uint i=start; i < end; i++){ fprintf(outf, "%u ", i+1); for(int j=0; j < latent_factors_inmem[i].ratings.size(); j++) { fprintf(outf, "%1.12e ", latent_factors_inmem[i].ratings[j]); } fprintf(outf, "\n"); } fclose(outf); } }; struct MMOutputter_ids{ MMOutputter_ids(std::string fname, uint start, uint end, std::string comment) { assert(start < end); MM_typecode matcode; set_matcode(matcode); FILE * outf = fopen(fname.c_str(), "w"); assert(outf != NULL); mm_write_banner(outf, matcode); if (comment != "") fprintf(outf, "%%%s\n", comment.c_str()); mm_write_mtx_array_size(outf, end-start, num_ratings+1); for (uint i=start; i < end; i++){ fprintf(outf, "%u ", i+1); for(int j=0; j < latent_factors_inmem[i].ids.size(); j++) { fprintf(outf, "%u ", (int)latent_factors_inmem[i].ids[j]+1);//go back to item ids starting from 1,2,3, (and not from zero as in c) } fprintf(outf, "\n"); } fclose(outf); } }; void output_knn_result(std::string filename) { MMOutputter_ratings ratings(filename + ".ratings", 0, M,"This file contains user scalar ratings. In each row i, num_ratings top scalar ratings of different items for user i. (First column: user id, next columns, top K ratings)"); MMOutputter_ids mmoutput_ids(filename + ".ids", 0, M ,"This file contains item ids matching the ratings. In each row i, num_ratings top item ids for user i. (First column: user id, next columns, top K ratings). Note: 0 item id means there are no more items to recommend for this user."); std::cout << "Rating output files (in matrix market format): " << filename << ".ratings" << ", " << filename + ".ids " << std::endl; } int main(int argc, const char ** argv) { mytimer.start(); print_copyright(); /* GraphChi initialization will read the command line arguments and the configuration file. */ graphchi_init(argc, argv); /* Metrics object for keeping track of performance counters and other information. Currently required. */ metrics m("nmf-inmemory-factors"); knn_sample_percent = get_option_float("knn_sample_percent", 1.0); if (knn_sample_percent <= 0 || knn_sample_percent > 1) logstream(LOG_FATAL)<<"Sample percente should be in the range (0, 1] " << std::endl; num_ratings = get_option_int("num_ratings", 10); if (num_ratings <= 0) logstream(LOG_FATAL)<<"num_ratings, the number of recomended items for each user, should be >=1 " << std::endl; debug = get_option_int("debug", 0); tokens_per_row = get_option_int("tokens_per_row", tokens_per_row); std::string algorithm = get_option_string("algorithm"); if (algorithm == "svdpp" || algorithm == "svd++") algo = SVDPP; else if (algorithm == "biassgd") algo = BIASSGD; else logstream(LOG_FATAL)<<"--algorithm should be svd++ or biassgd"<<std::endl; parse_command_line_args(); /* Preprocess data if needed, or discover preprocess files */ int nshards = 0; if (tokens_per_row == 3) nshards = convert_matrixmarket<edge_data>(training, NULL, 0, 0, 3, TRAINING, false); else if (tokens_per_row == 4) nshards = convert_matrixmarket4<edge_data4>(training); else logstream(LOG_FATAL)<<"--tokens_per_row should be either 3 or 4" << std::endl; assert(M > 0 && N > 0); latent_factors_inmem.resize(M+N); // Initialize in-memory vertices. read_factors(training); if ((uint)num_ratings > N){ logstream(LOG_WARNING)<<"num_ratings is too big - setting it to: " << N << std::endl; num_ratings = N; } srand(time(NULL)); /* Run */ if (tokens_per_row == 3){ RatingVerticesInMemProgram<VertexDataType, EdgeDataType> program; graphchi_engine<VertexDataType, EdgeDataType> engine(training, nshards, false, m); set_engine_flags(engine); engine.run(program, 1); } else if (tokens_per_row == 4){ RatingVerticesInMemProgram<VertexDataType, edge_data4> program; graphchi_engine<VertexDataType, edge_data4> engine(training, nshards, false, m); set_engine_flags(engine); engine.run(program, 1); } /* Output latent factor matrices in matrix-market format */ output_knn_result(training); rating_stats(); /* Report execution metrics */ if (!quiet) metrics_report(m); return 0; }
[ "lewisren@gmail.com" ]
lewisren@gmail.com
ae5d74c1f8ff3788bee6ad829b65604ed063cf33
5cb1506f81324c8637aeb33ed731163b0de8b124
/Promocion/Promocion.cpp
6e97f2caffaf4c5d1007ecbe9607106471639ba0
[]
no_license
MauroCicerchia/Algoritmos
e4762bad12152347a0d62e13b5ca50bcb0121e8a
6dceac63ca3ccc5c4a59f55753a4e700f5916e01
refs/heads/master
2021-01-19T22:56:55.490887
2017-10-13T19:42:58
2017-10-13T19:42:58
88,897,936
0
0
null
null
null
null
UTF-8
C++
false
false
1,077
cpp
#include <iostream> #include <string.h> using namespace std; bool promociona(int [], string); int main() { int notas[4]; string nombre; cout << "Ingrese el nombre del alumno: "; getline(cin, nombre); cout << "Ingrese nota del primer parcial: "; cin >> notas[0]; cout << "Ingrese nota del primer recuperatorio del primer parcial (0 si no rindio): "; cin >> notas[1]; cout << "Ingrese nota del segundo parcial: "; cin >> notas[2]; cout << "Ingrese nota del primer recuperatorio del segundo parcial (0 si no rindio): "; cin >> notas[3]; if(promociona(notas, nombre)) cout << "El alumno " << nombre << " promociono la materia."; else cout << "El alumno " << nombre << " no promociono la materia."; } bool promociona(int notas[], string nombre) { if(notas[0] >= 8 && notas[2] >=8) { return true; } else { if(notas[0] >= 8) { if(notas[3] >= 8) return true; else return false; } else { if(notas[2] >= 8) { if(notas[1] >= 8) return true; else return false; } else { return false; } } } }
[ "maurocicerchia98@gmail.com" ]
maurocicerchia98@gmail.com
86faac6eff414ce6d7214aad829a2f2b1dcc1a76
f32426a2959435dcd834c46faf99983d47eb752a
/3.qmlDataModelView_sqlWithRefreshAndRoles/dbinterface.hpp
09654ffb729a62e784e537eeb65037d50406d8cb
[]
no_license
MohammadMazaheri/MySnipCodes
1879134a75eb4b1584306b18d7caeb83036e0386
b4f15d07d2e7cbc1f7feba8a286ea17a044d0aaa
refs/heads/main
2023-09-01T11:52:28.112423
2023-08-27T08:39:09
2023-08-27T08:39:09
326,453,951
0
0
null
null
null
null
UTF-8
C++
false
false
2,885
hpp
#ifndef DBINTERFACE_H #define DBINTERFACE_H #include <QQmlApplicationEngine> #include <QQmlContext> #include <QDebug> #include "dbconnection.hpp" class DbInterface: public QObject { Q_OBJECT Q_PROPERTY(SqlQueryModel* model READ model WRITE setModel NOTIFY modelChanged) public: explicit DbInterface(QString dbFullName, QQmlApplicationEngine* engine, QObject* parent = Q_NULLPTR): QObject(parent) ,m_engine(engine) { m_dbConnection = new DbConnection(dbFullName, parent); if (m_dbConnection->createDB()) qDebug()<<"DB is created"; else qDebug()<<"DB is existed"; m_model = new SqlQueryModel; } ~DbInterface() { delete m_model; delete m_dbConnection; } SqlQueryModel* model() const { return m_model; } void setModel(SqlQueryModel*& model) { m_model = model; emit modelChanged(); } private: DbConnection* m_dbConnection; SqlQueryModel* m_model; QString m_query; QQmlApplicationEngine* m_engine; const QString kTtableName = "tblTest"; Q_SIGNALS: void modelChanged(); //public Q_SLOTS: public slots: bool update(const int &id, const QString &name = "", const qreal &value = 0.0, const int &isDeleted = 0) { m_query = QString("UPDATE %1 SET name = '%2', value = '%3', isDeleted = '%4' WHERE id = %5") .arg(kTtableName).arg(name).arg(value).arg(isDeleted).arg(id); return m_dbConnection->execQuery(m_query); } bool append(const QString &name = "", const qreal &value = 0.0) { m_query = QString("SELECT * FROM %1 WHERE name = '%2'").arg(kTtableName).arg(name); m_dbConnection->execQueryModel(m_query, m_model); if(m_model->rowCount() > 0 && m_model->record(0).value("isDeleted").toInt() != 0) return update(m_model->record(0).value("id").toInt(), name, value, 0); else { m_query = QString("INSERT INTO %1 (name, value, isDeleted) VALUES('%2', '%3', 0)") .arg(kTtableName).arg(name).arg(value); return m_dbConnection->execQuery(m_query); } } bool remove(const int &id) { //m_query = QString("DELETE FROM %1 WHERE id = '%2'").arg(kTtableName).arg(id); m_query = QString("UPDATE %1 SET isDeleted = 1 WHERE id = %2").arg(kTtableName).arg(id); return m_dbConnection->execQuery(m_query); } QString getLastError() { return m_dbConnection->getLastError(); } void refresh(QString query) { m_dbConnection->execQueryModel(query, m_model); m_engine->rootContext()->setContextProperty("sqlModel", QVariant::fromValue(this->model())); } }; #endif // DBINTERFACE_H
[ "noreply@github.com" ]
noreply@github.com
12fa42308e3d1c5cff9ff0c399933eb52e736bae
914156e9ff65e2449ee75dd0216ef2e78c91e56c
/RAD COMs/CommonBaseClasses/BaseFacCfgWrap.cpp
934af01d3a603952d90fe87a6e9b625ff3b4c107
[ "BSD-2-Clause" ]
permissive
radtek/Radiation-Review
0db454921eab3b9c4132a4169c799d619f9c0919
37bca0eabe75429a794b0d81eba552afed68d2ff
refs/heads/master
2020-06-23T01:12:39.303595
2019-01-31T22:23:33
2019-01-31T22:23:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,553
cpp
/* This work was supported by the United States Member State Support Program to IAEA Safeguards; the U.S. Department of Energy, Office of Nonproliferation and National Security, International Safeguards Division; and the U.S. Department of Energy, Office of Safeguards and Security. LA-CC-14-040. This software was exported from the United States in accordance with the Export Administration Regulations. Diversion contrary to U.S. law prohibited. Copyright 2015, Los Alamos National Security, LLC. This software application and associated material ("The Software") was prepared by the Los Alamos National Security, LLC. (LANS), under Contract DE-AC52-06NA25396 with the U.S. Department of Energy (DOE). All rights in the software application and associated material are reserved by DOE on behalf of the Government and LANS pursuant to the contract. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the "Los Alamos National Security, LLC." 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 LOS ALAMOS NATIONAL SECURITY, LLC 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 LOS ALAMOS NATIONAL SECURITY, LLC 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 CONTRAT, 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. */ // BaseFacCfgWrap.cpp: implementation of the CBaseFacCfgWrap class. // ////////////////////////////////////////////////////////////////////// #include "BaseFacCfgWrap.h" #include "SafeArrayUtil.h" #include "ErrorProcessing.h" //for flag defines #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////// // PUT NO operator I/O in the functions in this file. // NDAR uses this file and must be assured that // no blocking operator I/O occurs from within the components // that use these functions. NDAR is unattended. // // If you must, figure out a way to get the system's // quiet mode setting and then be sure to bracket them with: // // if (!m_bQuietMode) // { // ...do the operator's message box, printing, etc.. // } // // pjm 11/27/2005 for B2R1 //////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CBaseFacCfgWrap::CBaseFacCfgWrap() { TRACE("CBaseFacCfgWrap::CTOR_1\n"); //Derived class needs to set the instrument name here. //Use this example: //m_csInstrumentName = CString("grand"); //m_bstrInstrumentName = m_csInstrumentName.AllocSysString(); HRESULT hr = m_pIFacCfgMgr.CreateInstance(CLSID_FacilityMgrData); SetFlags(VERBOSITY2_FATAL | QUIET_MODE | DISABLE_LOGGER); } CBaseFacCfgWrap::~CBaseFacCfgWrap() { TRACE("CBaseFacCfgWrap::DTOR\n"); if (m_bstrInstrumentName) ::SysFreeString(m_bstrInstrumentName); if (m_pIFacCfgMgr) m_pIFacCfgMgr = NULL; } void CBaseFacCfgWrap::SetFlags(long lFlags) { if (m_pIFacCfgMgr) m_pIFacCfgMgr->SetFacilityMgrErrorLoggingParameters(lFlags); } /* Virtual function GetStationRecord is not implemented in the base class. bool CBaseFacCfgWrap::GetStationRecord(short sFacID, long lSta, struct db_sta_rec *pdbSta) */ // 28-Sep-2005 SFK Added check on if m_pIFacCfgMgr is not NULL and // VariantInit of List (VERY IMPORTANT TO DO THIS!!!!!!) bool CBaseFacCfgWrap::GetStationIDs(short sFacID, short *psNum, long* pIDs) { bool bSuccess = false; VARIANT List; ::VariantInit(&List); try { if (m_pIFacCfgMgr != NULL) { m_pIFacCfgMgr->GetStationIDsWithInstrumentType(sFacID, m_bstrInstrumentName, true, &List); if(List.vt != VT_EMPTY) { long NumStations; SafeArrayGetUBound(List.parray, 1, &NumStations); if ((short)NumStations <= *psNum) { CString TempStr; long lTemp; int j=0; //for(long i = 0; i <= NumStations; i++) //STOMP for(long i = 0; i < NumStations; i++) { SA_GetElem(List.parray, i, 0, &lTemp); // station number id pIDs[j] = lTemp; j++; } bSuccess = true; *psNum = j; // return the number of GRAND stations at the facility } } } } catch(...) { bSuccess = false; } ::VariantClear(&List); return bSuccess; } int CBaseFacCfgWrap::GetNumStations(short sFacID) { int bNum = 0; if (m_pIFacCfgMgr) bNum = m_pIFacCfgMgr->GetNumberOfStationsForFacility(sFacID, VARIANT_TRUE); return(bNum); } CString CBaseFacCfgWrap::GetFacilityDirectory(short sFacID) { //USES_CONVERSION; CString strTemp("CBaseFacCfgWrap::GetFacilityDirectory() error"); if (m_pIFacCfgMgr) { BSTR bstr = m_pIFacCfgMgr->GetFacilityDirectory(sFacID); strTemp = bstr; ::SysFreeString(bstr); } //strTemp = W2T(m_pIFacCfgMgr->GetFacilityDirectory(sFacID)); return(strTemp); } CString CBaseFacCfgWrap::GetFacilityLongName(short sFacID) { //USES_CONVERSION; CString strTemp("CBaseFacCfgWrap::GetFacilityLongName() error"); if (m_pIFacCfgMgr) { BSTR bstr = m_pIFacCfgMgr->GetFacilityLongName(sFacID); CString cs(bstr); strTemp = cs; ::SysFreeString(bstr); } //if (m_pIFacCfgMgr) // strTemp = W2T(m_pIFacCfgMgr->GetFacilityLongName(sFacID)); return strTemp; } bool CBaseFacCfgWrap::FacilityExists(short sFacID) { VARIANT_BOOL vbExists = VARIANT_FALSE; if (m_pIFacCfgMgr) vbExists = m_pIFacCfgMgr->IsFacilityDefined(sFacID); return (vbExists != VARIANT_FALSE); }
[ "joseph.f.longo@gmail.com" ]
joseph.f.longo@gmail.com
036f35abcaacc776a8687231a1a989108f20436f
2a1863399058e5efb5c29385c23292403aa370d4
/code/main.cpp
0bf1d3014aae32360db180a2f8a8cb7d56cf54a8
[]
no_license
BryanGonz/ZombieGame
758166bc09626e89fe3e00c1653b0474434cd4e8
52cee9244d34fed405e9d8417db15ec050325b69
refs/heads/main
2023-06-27T03:02:29.299786
2021-08-04T23:46:57
2021-08-04T23:46:57
392,846,621
0
0
null
null
null
null
UTF-8
C++
false
false
179
cpp
#include "Game.h" int main() { // Create a game // Use this instead to create a mini-game: Game g(3, 4, 2); Game g(7, 8, 25); // Play the game g.play(); }
[ "bgon@ucla.edu" ]
bgon@ucla.edu
654581dae37410f89104bccadc38a6a57143e3d5
78435005fd4ddf72579eef4d253b66128120745c
/srs_env_model/src/but_context/but_context_server.cpp
3034a639375589967d7a5092beac720c4b64abfd
[]
no_license
Mazet/srs_public
57290f60dd9e3de2a11a6ef8774c3cf27dfbd342
4342d93ae44de2ef0dd9450679c667cad1701615
refs/heads/master
2021-01-17T22:25:07.604843
2012-07-19T08:50:36
2012-07-19T08:50:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,793
cpp
/****************************************************************************** * \file * * $Id: * * Copyright (C) Brno University of Technology * * This file is part of software developed by dcgm-robotics@FIT group. * * Author: Tomas Lokaj (xlokaj03@stud.fit.vutbr.cz) * Supervised by: Michal Spanel (spanel@fit.vutbr.cz) * Date: 16.4.2012 * * This file is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this file. If not, see <http://www.gnu.org/licenses/>. */ #include "but_context/but_context_server.h" /** * @brief Main function */ int main(int argc, char **argv) { // ROS initialization (the last argument is the name of the node) ros::init(argc, argv, "but_context_server"); // NodeHandle is the main access point to communications with the ROS system ros::NodeHandle n; but_context::contextServer = new but_context::ContextServer(); // Create and advertise this services over ROS ros::ServiceServer setContextService = n.advertiseService(BUT_SetContext_SRV, but_context::setContext); ros::ServiceServer getContextService = n.advertiseService(BUT_GetContext_SRV, but_context::getContext); ROS_INFO("BUT Context Server ready!"); // Enters a loop, calling message callbacks ros::spin(); return 0; }
[ "spanel@fit.vutbr.cz" ]
spanel@fit.vutbr.cz
f670b460e9c60c2138d13510ffb11b4ce3e14714
6b4e78812681004a321c3747de37cd903e9e7a4d
/Week1_Task1/ConsoleApplication1/ConsoleApplication1.cpp
da21c1c258060adc2e3d7e3c72f7c01836011d77
[]
no_license
Peritex/210CT
97864db2a34e2b9c038db55f5fd1f049bddcf1b4
50c6e1324b912f1dfd0d371df6c45040b94fe1f5
refs/heads/master
2020-06-14T21:08:23.278992
2016-12-02T19:23:54
2016-12-02T19:23:54
75,340,155
0
0
null
null
null
null
UTF-8
C++
false
false
934
cpp
// ConsoleApplication1.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <array> #include <stdlib.h> #include <time.h> void swap(int *a, int *b)//pointer swap function { int temp = *a; *a = *b; *b = temp; } void printarray (int arr[], int n) { for (int i = 0; i < 8; i++) std::cout << arr[i] << " "; std::cout << std::endl; } void shuffle(int arr[], int n) { srand(time(NULL)); //random num gen //shuffle over array for (int i = n - 1; i > 0; i--) { int j = rand() % (i + 1); swap(&arr[i], &arr[j]); } } void getinput(int arr[]) { std::cout << "Input Numbers" << std::endl; for (int i = 0; i < 8; i++) { std::cin >> arr[i]; } } int main() { int arr[8]; getinput(arr); int n = sizeof(arr) / sizeof(arr[0]); printarray(arr, n); shuffle(arr, n); printarray(arr, n); return 0; }
[ "noreply@github.com" ]
noreply@github.com
21a618ce547fee5e99ca57a9cf33f6b4f59de970
ab7ecfc8e6ec7793d61306f54a3b3f5670f77faa
/telemetria_v2/led.h
60a0be8992a7c5731189ad581b2c4091b30943b8
[]
no_license
RafaelMorandini/SE-GrupoJ
6cc7f7c7396ac01f2953cf9faf18a2bbd66075c6
2e2fa550f6c081cf87d4ca07688ad150a203a005
refs/heads/main
2023-06-25T08:29:45.925308
2021-07-22T09:03:57
2021-07-22T09:03:57
388,274,418
0
0
null
null
null
null
UTF-8
C++
false
false
264
h
#ifndef LED_H_INCLUDED #define LED_H_INCLUDED #include <Arduino.h> #include "definicoes_sistema.h" class LED { public: LED(int pin); int pino; void ligar(int controle); int ligado; int estaligado(); }; #endif // LED_H_INCLUDED
[ "noreply@github.com" ]
noreply@github.com
ac5aea78728f7cddf732b41060488bc8557593bb
1ae40287c5705f341886bbb5cc9e9e9cfba073f7
/Osmium/SDK/FN_GAB_TakerSoulSuck_parameters.hpp
a7aa37c6a93732964b27fd5f7c1f1da5a5e94e40
[]
no_license
NeoniteDev/Osmium
183094adee1e8fdb0d6cbf86be8f98c3e18ce7c0
aec854e60beca3c6804f18f21b6a0a0549e8fbf6
refs/heads/master
2023-07-05T16:40:30.662392
2023-06-28T23:17:42
2023-06-28T23:17:42
340,056,499
14
8
null
null
null
null
UTF-8
C++
false
false
12,768
hpp
#pragma once // Fortnite (4.5-CL-4159770) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.OnInterrupted_7817BC4E41E9CF270861B28630504E0D struct UGAB_TakerSoulSuck_C_OnInterrupted_7817BC4E41E9CF270861B28630504E0D_Params { }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.OnComplete_7817BC4E41E9CF270861B28630504E0D struct UGAB_TakerSoulSuck_C_OnComplete_7817BC4E41E9CF270861B28630504E0D_Params { }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.OnInterrupted_7817BC4E41E9CF270861B2865D46D1D6 struct UGAB_TakerSoulSuck_C_OnInterrupted_7817BC4E41E9CF270861B2865D46D1D6_Params { }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.OnComplete_7817BC4E41E9CF270861B2865D46D1D6 struct UGAB_TakerSoulSuck_C_OnComplete_7817BC4E41E9CF270861B2865D46D1D6_Params { }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.OnInterrupted_7817BC4E41E9CF270861B286146C2D8C struct UGAB_TakerSoulSuck_C_OnInterrupted_7817BC4E41E9CF270861B286146C2D8C_Params { }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.OnComplete_7817BC4E41E9CF270861B286146C2D8C struct UGAB_TakerSoulSuck_C_OnComplete_7817BC4E41E9CF270861B286146C2D8C_Params { }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.OnInterrupted_7817BC4E41E9CF270861B28685B20041 struct UGAB_TakerSoulSuck_C_OnInterrupted_7817BC4E41E9CF270861B28685B20041_Params { }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.OnComplete_7817BC4E41E9CF270861B28685B20041 struct UGAB_TakerSoulSuck_C_OnComplete_7817BC4E41E9CF270861B28685B20041_Params { }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.Completed_A9A1CE59416C7C1D5AF25DADAE0C61C2 struct UGAB_TakerSoulSuck_C_Completed_A9A1CE59416C7C1D5AF25DADAE0C61C2_Params { struct FGameplayAbilityTargetDataHandle TargetData; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm) struct FGameplayTag ApplicationTag; // (BlueprintVisible, BlueprintReadOnly, Parm) }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.Cancelled_A9A1CE59416C7C1D5AF25DADAE0C61C2 struct UGAB_TakerSoulSuck_C_Cancelled_A9A1CE59416C7C1D5AF25DADAE0C61C2_Params { struct FGameplayAbilityTargetDataHandle TargetData; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm) struct FGameplayTag ApplicationTag; // (BlueprintVisible, BlueprintReadOnly, Parm) }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.Triggered_A9A1CE59416C7C1D5AF25DADAE0C61C2 struct UGAB_TakerSoulSuck_C_Triggered_A9A1CE59416C7C1D5AF25DADAE0C61C2_Params { struct FGameplayAbilityTargetDataHandle TargetData; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm) struct FGameplayTag ApplicationTag; // (BlueprintVisible, BlueprintReadOnly, Parm) }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.OnInterrupted_7817BC4E41E9CF270861B28664B32580 struct UGAB_TakerSoulSuck_C_OnInterrupted_7817BC4E41E9CF270861B28664B32580_Params { }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.OnComplete_7817BC4E41E9CF270861B28664B32580 struct UGAB_TakerSoulSuck_C_OnComplete_7817BC4E41E9CF270861B28664B32580_Params { }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.Cancelled_4C2B63DE432CB715866443AE4D6362FD struct UGAB_TakerSoulSuck_C_Cancelled_4C2B63DE432CB715866443AE4D6362FD_Params { struct FGameplayAbilityTargetDataHandle TargetData; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm) struct FGameplayTag ApplicationTag; // (BlueprintVisible, BlueprintReadOnly, Parm) }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.Targeted_4C2B63DE432CB715866443AE4D6362FD struct UGAB_TakerSoulSuck_C_Targeted_4C2B63DE432CB715866443AE4D6362FD_Params { struct FGameplayAbilityTargetDataHandle TargetData; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm) struct FGameplayTag ApplicationTag; // (BlueprintVisible, BlueprintReadOnly, Parm) }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.K2_ActivateAbility struct UGAB_TakerSoulSuck_C_K2_ActivateAbility_Params { }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.Goal Pawn Died struct UGAB_TakerSoulSuck_C_Goal_Pawn_Died_Params { class AActor* DamagedActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) float Damage; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class AController* InstigatedBy; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class AActor* DamageCauser; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) struct FVector HitLocation; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData) class UPrimitiveComponent* FHitComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) struct FName BoneName; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) struct FVector Momentum; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData) }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.HitNothingTimeout struct UGAB_TakerSoulSuck_C_HitNothingTimeout_Params { }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.Taker Damaged struct UGAB_TakerSoulSuck_C_Taker_Damaged_Params { class AActor* DamagedActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) float Damage; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class AController* InstigatedBy; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class AActor* DamageCauser; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) struct FVector HitLocation; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData) class UPrimitiveComponent* FHitComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) struct FName BoneName; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) struct FVector Momentum; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData) }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.SoulSuck struct UGAB_TakerSoulSuck_C_SoulSuck_Params { }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.Taker Destroyed struct UGAB_TakerSoulSuck_C_Taker_Destroyed_Params { class AActor* DestroyedActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.Taker Died struct UGAB_TakerSoulSuck_C_Taker_Died_Params { class AActor* DamagedActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) float Damage; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class AController* InstigatedBy; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class AActor* DamageCauser; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) struct FVector HitLocation; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData) class UPrimitiveComponent* FHitComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) struct FName BoneName; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) struct FVector Momentum; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData) }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.UnbindAllEvents struct UGAB_TakerSoulSuck_C_UnbindAllEvents_Params { }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.K2_OnEndAbility struct UGAB_TakerSoulSuck_C_K2_OnEndAbility_Params { bool* bWasCancelled; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.Goal Pawn Damaged struct UGAB_TakerSoulSuck_C_Goal_Pawn_Damaged_Params { class AActor* DamagedActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) float Damage; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class AController* InstigatedBy; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class AActor* DamageCauser; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) struct FVector HitLocation; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData) class UPrimitiveComponent* FHitComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) struct FName BoneName; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) struct FVector Momentum; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData) }; // Function GAB_TakerSoulSuck.GAB_TakerSoulSuck_C.ExecuteUbergraph_GAB_TakerSoulSuck struct UGAB_TakerSoulSuck_C_ExecuteUbergraph_GAB_TakerSoulSuck_Params { int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "kareemolim@gmail.com" ]
kareemolim@gmail.com
839a19e258a16e18238c09dd8d035648a31eee5c
44d212e4b92b39a24b3fc9356c28bddd513f1f54
/UVa Online Judge/10013. Super Long Sums.cpp
ea8cb00520d64aec7e27e2fed9fc670d06e2a1fc
[ "MIT" ]
permissive
nicoelayda/competitive-programming
e946d4eeac5fadcae58d44dd3d9b6fb3d86983a4
5b5452d8d2865a1a5f1e3d2fece011749722e8c4
refs/heads/master
2020-04-23T09:42:46.697943
2019-02-18T16:29:27
2019-02-18T16:29:33
171,078,251
0
0
null
null
null
null
UTF-8
C++
false
false
921
cpp
#include <cstdio> #include <vector> using namespace std; int main() { int T; vector<int> sum(1000002, 0); scanf("%d", &T); while (T-- != 0) { int digits; int n1, n2; bool first_nonzero = false; scanf("%d", &digits); for (int i = 0; i < digits; i++) { scanf("%d %d", &n1, &n2); sum[i] = n1 + n2; } for (int i = digits - 1; i >= 0; i--) { if (sum[i] >= 10 && i != 0) { sum[i] %= 10; sum[i - 1] += 1; } } for (int i = 0; i < digits; i++) { if (first_nonzero || sum[i] != 0) { printf("%d", sum[i]); first_nonzero = true; } } printf("\n"); if (T != 0) printf("\n"); } return 0; }
[ "nico@elayda.com" ]
nico@elayda.com
edf109c69bdb7024132206300e9d4fbe0ddfe717
dcdb207fe61add28dc0589297853ef9e51367449
/mysql/.moc/moc_qsql_mysql_p.cpp
66045014a79335dda6247f75b1dbd0d3c26ec3c5
[]
no_license
fairytalefu/QMSYQL
d098f663b0c1994555b2bfcc0be4914ce6802b9f
4cc45f20c4d6eee7aca2063b023095c955f73c99
refs/heads/master
2021-05-13T16:13:27.707140
2018-01-09T12:33:35
2018-01-09T12:33:35
116,787,814
0
0
null
null
null
null
UTF-8
C++
false
false
2,651
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'qsql_mysql_p.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.3) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../qsql_mysql_p.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'qsql_mysql_p.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.9.3. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_QMYSQLDriver_t { QByteArrayData data[1]; char stringdata0[13]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_QMYSQLDriver_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_QMYSQLDriver_t qt_meta_stringdata_QMYSQLDriver = { { QT_MOC_LITERAL(0, 0, 12) // "QMYSQLDriver" }, "QMYSQLDriver" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_QMYSQLDriver[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; void QMYSQLDriver::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { Q_UNUSED(_o); Q_UNUSED(_id); Q_UNUSED(_c); Q_UNUSED(_a); } const QMetaObject QMYSQLDriver::staticMetaObject = { { &QSqlDriver::staticMetaObject, qt_meta_stringdata_QMYSQLDriver.data, qt_meta_data_QMYSQLDriver, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *QMYSQLDriver::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *QMYSQLDriver::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_QMYSQLDriver.stringdata0)) return static_cast<void*>(this); return QSqlDriver::qt_metacast(_clname); } int QMYSQLDriver::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QSqlDriver::qt_metacall(_c, _id, _a); return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
[ "fairytalefu@gmail.com" ]
fairytalefu@gmail.com
d8f01691c52c67a156f8b3fe668b5bbaa848d5aa
ad572d5ce0be185edc0e4066f55eac78c8970d2c
/src/client/particles/CountdownParticle.hpp
06b40ed1e310f4b7be9d3acbcea46906b07d6444
[ "MIT" ]
permissive
AzariasB/MultiPlayerPong
086f4b1292d482b851c31457a42ff189c1af9326
4b9af38198945b31b05ca83acadccef333e32284
refs/heads/master
2021-06-23T13:41:55.204845
2019-05-09T04:35:55
2019-05-09T04:35:55
108,720,391
0
0
null
null
null
null
UTF-8
C++
false
false
2,642
hpp
/* * The MIT License * * Copyright 2017 azarias. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* * File: CoundtownParticle.hpp * Author: azarias * * Created on 2/5/2018 */ #pragma once #include <SFML/Config.hpp> #include <SFML/Graphics/Text.hpp> #include "Particle.hpp" #include "src/lib/twin.hpp" namespace mp { /** * @brief The CoundtownParticle class * particle used when doing the countdown * before a game, in order to have * a stylized countdown */ class CountdownParticle : public Particle { public: /** * @brief CountdownParticle constructor */ CountdownParticle(); /** * @brief update inherited function * @param elapsed */ void update(const sf::Time &elapsed) override; /** * @brief render inherited function * @param renderer */ void render(Renderer &renderer) const override; /** * @brief isFinished when the text is finally rendered * @return */ bool isFinished() const override; /** * @brief init initializes the partile * @param text * @param position * @param lifetime */ void init(const std::string &text, const sf::Vector2f &position, const sf::Time &lifetime); private: /** * @brief m_textScale scale of the text */ twin::Twin<float> m_textScale; /** * @brief m_textAlpha tweening for the text alpha */ twin::Twin<sf::Uint8> m_textAlpha; /** * @brief m_text text to draw */ sf::Text m_text; /** * @brief m_textColor color of the text */ sf::Color m_textColor; }; }
[ "azarias.boutin@gmail.com" ]
azarias.boutin@gmail.com
336a776d4d73daf062ef08825ef919ae65a03d9a
ff3cd2a23b8d582f8ce3eca4a16bcf7a248e3f7c
/Soil_Moisture.ino
ff0f0d604e84dc33fd719e9377884289192dd49e
[]
no_license
kitter007/IoT-SmartFarm
c70ce76aa0764b64d723839ac9e6091f2561f501
3780c176621f442d18879575560cf23188889768
refs/heads/master
2020-07-15T07:11:51.419594
2019-11-02T04:02:55
2019-11-02T04:02:55
205,509,752
0
0
null
null
null
null
UTF-8
C++
false
false
177
ino
#include <ESP8266WiFi.h> int moisture; void setup(){ Serial.begin(9600); } void loop(){ moisture = analogRead(A0); Serial.println(moisture); delay(500); }
[ "noreply@github.com" ]
noreply@github.com
36cdfcf752fa3744bc7352db1c4febe5671ab0fc
2c0b4335fec9aa36ac63b178a5e64b587b1f668e
/jetson/i2c.cpp
110f6d7b5e14ad1a2648562d8d5588fd7363583f
[]
no_license
stephenwang5/ideasclinic-i2c
eb4aa331117d96bcd1634663f7068e07bf932da8
960616c9f190b02eae4970b2a5ba769ec3e61f9b
refs/heads/master
2022-12-18T07:01:06.109369
2020-08-18T19:20:27
2020-08-18T19:20:27
266,660,556
0
0
null
null
null
null
UTF-8
C++
false
false
1,384
cpp
#include "i2c.hpp" Instruction::Instruction() : x(0), y(0), width(0), height(0), gripper_angle(0) {} Instruction::Instruction(float x, float y, float w, float h, float ga) : x(x), y(y), width(w), height(h), gripper_angle(ga) {} I2C_Bus::I2C_Bus(const char* bus, unsigned char unshifted_address) : bus(bus), slave_address(unshifted_address) {} // Helper for turning a float into 4 bytes void I2C_Bus::disassemble_float(float target, unsigned char* destination, int start) { Converter temp; temp.argument = target; for (int i = 0; i < 4; i++) destination[start+i] = temp.bytes[i]; } bool I2C_Bus::send(Instruction arg) { int file = open(bus, O_RDWR); if (file < 0) { std::cerr << "Failed to open bus char device\n"; return false; } if (ioctl(file, I2C_SLAVE, slave_address) < 0) { std::cerr << "Failed to acquire bus access\n"; close(file); return false; } // Change this buffer size to the number of arguments x 4 (for float) unsigned char buffer[20]; disassemble_float(arg.x, buffer, 0); disassemble_float(arg.y, buffer, 4); disassemble_float(arg.width, buffer, 8); disassemble_float(arg.height, buffer, 12); disassemble_float(arg.gripper_angle, buffer, 16); // Remember to match the size of buffer if (write(file, buffer, 20) != 20) { std::cerr << "Failed to write to slave\n"; close(file); return false; } close(file); return true; }
[ "ste53539@gmail.com" ]
ste53539@gmail.com
202ecc4d798ba3593aa8413e12359cd434d4c628
1c862e7030af7114c04d9dcecb8de6a5a7a60a0b
/typy.cpp
4f3677a76b0e0c3d68915323388e0ce07f0ad2f9
[]
no_license
mateuszSmi/CG
8a86f744d66d52eb60d1efc8748731a85d9a8edd
dae99b0f0f9a493d99c880e627822a332d7c3315
refs/heads/main
2023-04-26T12:19:46.406299
2021-05-18T13:59:00
2021-05-18T13:59:00
368,545,627
0
0
null
null
null
null
UTF-8
C++
false
false
1,138
cpp
#include <iostream> #include <fstream> using namespace std; //difinicja NAZWA wartość- pewna stała ma stałą wartość #define ROZMIAR 20 //enum zwraca enum REZULTAT { ISTNIEJE = 1, NIEISTNIEJE = -1 }; //const-słuzy określeniu, że zmeinna za modyfikatorem nie może zostać zmieniona //const - zasbezpiecza zmienna przed modyfikacja REZULTAT czyjest(const char * npliku) { ifstream f(npliku); if (f.good()) { f.close(); return ISTNIEJE; } else { f.close(); return NIEISTNIEJE; } } void typwylicz() { //użycie typu stałej ROZMIAR i typu wylicznieowego char plik[ROZMIAR]; cout<<plik<<endl; cout<< "Podaj nazwe pliku: "; cin.getline(plik, ROZMIAR); cout<< "Nazwa: "<<plik<<endl; REZULTAT jestplik; jestplik = czyjest(plik); if (jestplik == ISTNIEJE) cout<<"Jest plik!"; else cout<<"Nie ma pliku!"; } void nowytyp() { // // uużwycie typedef str jako alias typedef string str; str x; cout<< "Podaj tekst: "; cin>> ws >> x; cout<<x<<endl; } int main(int argc, char **argv) { //nowytyp(); typwylicz(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
04e47f95d7873dcf740ffd48606dddf498568471
834558e34d3f868289f573338eefd458a14b1253
/tests/test.cpp
d48d1cbf3fbf6ad8457c7b5fe8d69915c99cff15
[]
no_license
gleyba/yazik
5ebba4092f86335158f33c271545427fd837a912
a6b481a1b49962b3f641704cf2876297182b0825
refs/heads/master
2021-09-08T01:37:47.302756
2018-02-28T07:38:24
2018-02-28T07:38:24
113,197,483
0
0
null
null
null
null
UTF-8
C++
false
false
1,446
cpp
#include <iostream> #include <array> #include <yazik/o2tree/o2tree.hpp> // #include <boost/context/all.hpp> // #include <yazik/intrusive_ptr.hpp> #include <future> #define __l_move(x) x = std::move(x) // namespace yazik { // // namespace executor { // // class t { // // }; // // } //end of yazik::executor namespace // // namespace loop { // // class t { // // }; // // } //end of yazik::loop namespace // // namespace async { // // // // } //end of yazik::async // // namespace coro { // // namespace ctx = boost::context; // // class t { // // ctx::continuation source_; // // // }; // // } //end of yazik::coro namespace // // } //end of yazik namespace int main() { // namespace ctx = boost::context; // ctx::continuation source=ctx::callcc // ( // [](ctx::continuation && sink) // { // int a=0; // int b=1; // for(;;) // { // sink=sink.resume(); // auto next=a+b; // a=b; // b=next; // } // return std::move(sink); // } // ); // // std::async( // std::launch::async, // [__l_move(source)] () mutable { // for (int j=0;j<10;++j) { // if (source) { // source=source.resume(); // std::cout << source << std::endl; // } // } // } // ).get(); return 0; }
[ "gleyba.k@gmail.com" ]
gleyba.k@gmail.com
afe1941afdfbb3dda83a217859eb2c1dc4ac6c0e
96148bf17555c028f5650d51f496f349c89e8c79
/devel/include/cob_object_detection_msgs/DetectObjects.h
2aa70e1812ee5d904f5c5ddb6f8372b7aff95589
[]
no_license
kerekare/ros_hydra_libphidgetsupdated
239daed94a95f60743c5659f1102183641761240
e05e58417fb03a14d627bc80d09af3b2a0fcceab
refs/heads/master
2016-09-05T23:35:43.792883
2014-03-25T16:32:01
2014-03-25T16:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,977
h
/* Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Auto-generated by gensrv_cpp from file /home/kerekare/workspace/care-o-bot/src/cob_perception_common/cob_object_detection_msgs/srv/DetectObjects.srv * */ #ifndef COB_OBJECT_DETECTION_MSGS_MESSAGE_DETECTOBJECTS_H #define COB_OBJECT_DETECTION_MSGS_MESSAGE_DETECTOBJECTS_H #include <ros/service_traits.h> #include <cob_object_detection_msgs/DetectObjectsRequest.h> #include <cob_object_detection_msgs/DetectObjectsResponse.h> namespace cob_object_detection_msgs { struct DetectObjects { typedef DetectObjectsRequest Request; typedef DetectObjectsResponse Response; Request request; Response response; typedef Request RequestType; typedef Response ResponseType; }; // struct DetectObjects } // namespace cob_object_detection_msgs namespace ros { namespace service_traits { template<> struct MD5Sum< ::cob_object_detection_msgs::DetectObjects > { static const char* value() { return "3e7b1c8cc85eedd71f86f7179c8873b6"; } static const char* value(const ::cob_object_detection_msgs::DetectObjects&) { return value(); } }; template<> struct DataType< ::cob_object_detection_msgs::DetectObjects > { static const char* value() { return "cob_object_detection_msgs/DetectObjects"; } static const char* value(const ::cob_object_detection_msgs::DetectObjects&) { return value(); } }; // service_traits::MD5Sum< ::cob_object_detection_msgs::DetectObjectsRequest> should match // service_traits::MD5Sum< ::cob_object_detection_msgs::DetectObjects > template<> struct MD5Sum< ::cob_object_detection_msgs::DetectObjectsRequest> { static const char* value() { return MD5Sum< ::cob_object_detection_msgs::DetectObjects >::value(); } static const char* value(const ::cob_object_detection_msgs::DetectObjectsRequest&) { return value(); } }; // service_traits::DataType< ::cob_object_detection_msgs::DetectObjectsRequest> should match // service_traits::DataType< ::cob_object_detection_msgs::DetectObjects > template<> struct DataType< ::cob_object_detection_msgs::DetectObjectsRequest> { static const char* value() { return DataType< ::cob_object_detection_msgs::DetectObjects >::value(); } static const char* value(const ::cob_object_detection_msgs::DetectObjectsRequest&) { return value(); } }; // service_traits::MD5Sum< ::cob_object_detection_msgs::DetectObjectsResponse> should match // service_traits::MD5Sum< ::cob_object_detection_msgs::DetectObjects > template<> struct MD5Sum< ::cob_object_detection_msgs::DetectObjectsResponse> { static const char* value() { return MD5Sum< ::cob_object_detection_msgs::DetectObjects >::value(); } static const char* value(const ::cob_object_detection_msgs::DetectObjectsResponse&) { return value(); } }; // service_traits::DataType< ::cob_object_detection_msgs::DetectObjectsResponse> should match // service_traits::DataType< ::cob_object_detection_msgs::DetectObjects > template<> struct DataType< ::cob_object_detection_msgs::DetectObjectsResponse> { static const char* value() { return DataType< ::cob_object_detection_msgs::DetectObjects >::value(); } static const char* value(const ::cob_object_detection_msgs::DetectObjectsResponse&) { return value(); } }; } // namespace service_traits } // namespace ros #endif // COB_OBJECT_DETECTION_MSGS_MESSAGE_DETECTOBJECTS_H
[ "kerekare@i60sr2.(none)" ]
kerekare@i60sr2.(none)
3944344330857f1e91649b2ef8f6dcb2293fb5ed
aa1351e056e3b87ccf18a36ebe24a9f928ba81ca
/cpp_course(apna_college)/l_008.5.2_array_challenges._subarray_with_given_sum.cpp
225ae92355bdb06162d563c488cff476d18e4dfd
[]
no_license
wisdom-weaver/c_cpp_mini
d13dc9fd4d83228b3c589c419545d44e6640f28b
c9f38ee6a2172f1a035deb60fb727016fff09e1a
refs/heads/main
2023-08-18T20:04:53.371934
2021-09-23T11:52:52
2021-09-23T11:52:52
378,346,514
1
0
null
null
null
null
UTF-8
C++
false
false
1,036
cpp
#include <cmath> #include <iostream> using namespace std; int main() { int ar[] = {1, 1, 1, 3, 4, 3, 5, 6}; int n = sizeof(ar) / sizeof(ar[0]); int req_sum = 6; // M-1: Brute Force - by subarrays sum method // int sum, s = -1, e = -1; // for (int i = 0; i < n; i++) { // int j = i; // sum = 0; // while (j--) { // sum += ar[j]; // if (sum == req_sum) { // s = j; // e = i; // goto got; // } else if (sum > req_sum) { // break; // } // } // } // M-2: Efficient int curr_sum = ar[0], s = 0, e = 0; for (int i = 1; i < n; i++) { // remove elems from start if current sum excedes while (curr_sum > req_sum && s < i - 1) curr_sum -= ar[s++]; if (curr_sum == req_sum) { // terminate if you find the e = i - 1; goto got; } else // add elems to the end curr_sum += ar[i]; } got: cout << s << " : " << e << endl; for (int i = s; i <= e; i++) cout << ar[i] << " "; cout << endl; }
[ "danish.ansari.nox@gmail.com" ]
danish.ansari.nox@gmail.com
1e4e5f1dc80e890045e70b4cc3ff12baeab7d956
29a7891c9de974400bdc802ae7bd6d0ab6683d3a
/client3.cpp
926f877fb0b99720c8797a1182f67cb3f906378e
[]
no_license
joseph101039/socketProgramming
a7a5ce20ed1f326e084160dbdcc9c892a4542855
5c7dc1872c033bf014d0f34815638792bbda9231
refs/heads/master
2021-01-13T13:05:30.741163
2017-01-11T16:05:02
2017-01-11T16:05:02
78,655,024
0
0
null
null
null
null
UTF-8
C++
false
false
3,274
cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #include<unistd.h> #include <sys/socket.h> #include <arpa/inet.h> #include <sys/types.h> #include <netdb.h> //for gethostbyname #include <errno.h> //for strerror() #define DEFAULT_PORT 5900 /*設定port 為 5900*/ #define BUFSIZE 4096 int main(int argc, char *argv[]) { struct sockaddr_in server; /* 伺服器位址*/ unsigned long dst_ip; /* 目標位址 */ int port; /* 埠口碼 */ int s; /* 套接口描述子 */ int n; /* 輸入端byte數 */ int len; /* 應用軟體資料長度 */ char send_buf[BUFSIZE]; /*發送緩衝區 */ printf("Please input IP address\n"); char ip_address[16]; scanf("%s", ip_address); printf("Please input port number\n"); char port_num[6]; scanf("%s", port_num); /* 檢索伺服器IP位址 ,指定給dst_ip*/ if ((dst_ip = inet_addr(ip_address)) == INADDR_NONE) { //如果伺服端IP為255.255.255.255 ? struct hostent *he; /* 主機訊息(IP) */ if ((he = gethostbyname(ip_address)) == NULL) { //檢索後為錯誤值終止 fprintf(stderr, "gethostbyname error\n"); exit(EXIT_FAILURE); } memcpy((char *) &dst_ip, (char *) he->h_addr, he->h_length); //複製伺服端IP位置到dst_ip } /* 如果有輸入埠口碼, 指定給port*/ if ((port = atoi(port_num)) == 0) { struct servent *se; /*服務訊息(port) */ if ((se = getservbyname(port_num, "tcp")) != NULL) port = (int) ntohs((u_int16_t) se->s_port); //(將主機big / little endian 調整成 network byte) else { fprintf(stderr, "getservbyname error\n"); exit(EXIT_FAILURE); } } else port = DEFAULT_PORT; /* 使用TCP協定開啟套接口 */ if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) { //如果沒有成功 Allocate a socket perror("socket"); //print error message exit(EXIT_FAILURE); } /* 設定伺服器位址確定連結 */ memset(&server, 0, sizeof server); //clean up server.sin_family = AF_INET; //address family: Internet server.sin_addr.s_addr = dst_ip; server.sin_port = htons(port); if (connect(s, (struct sockaddr *) &server, sizeof server) < 0) { //如果連接伺服器不成功 perror("connect"); exit(EXIT_FAILURE); } printf("connected to '%s'\n", inet_ntoa(server.sin_addr)); /*prepare to send message*/ char send_msg[BUFSIZE] ; char recv_msg[BUFSIZE]; memset(send_msg, 0, BUFSIZE); memset(recv_msg, 0, BUFSIZE); char guess[4]; while(1){ memset(guess, 0, BUFSIZE); input: printf("Please guess a 4-digital number: "); scanf("%s", guess); if(strlen(guess) != 4) goto input; if(send(s, guess, strlen(guess), 0) <= 0){ perror("send"); } for(int i = 0; i < 4; i++) recv(s, &recv_msg[i], 1, 0); printf("result is : %s\n", recv_msg); if(strcmp(recv_msg, "4A0B") == 0){ printf("Your get the correct answer!\n"); break; } } close(s); return 0; }
[ "noreply@github.com" ]
noreply@github.com
e9e46809c798990887f32f4dc4d4a6567de561b8
c77a8579ab98ba0c6eaaf36ac1382cb2b1a4046c
/519D - A and B and Interesting Substrings.cpp
3cba03ae9d85d1c5a1225307d7652378194d5b1f
[]
no_license
arjunbhatt670/CodeForces
2dadb9f53bcd6cfa1b1146524624320434991995
b358049e3da7d9c3bbc8f03986e364be1925688b
refs/heads/master
2022-04-07T19:02:42.320001
2020-03-21T06:44:02
2020-03-21T06:44:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
902
cpp
/* * User: Isanchez_Aguilar * Problem: CodeForces 519D - A and B and Interesting Substrings */ #include <iostream> #include <algorithm> #include <vector> #include <cstring> #include <map> using namespace std; using Long = long long; int main(void) { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); Long vals[26]; for (int i = 0; i < 26; ++i) cin >> vals[i]; string s; cin >> s; Long ans = 0; if (s.length() > 1) { vector< map<Long, Long> > prevData(26); Long currSum = vals[s[0] - 'a'] + vals[s[1] - 'a']; ++prevData[s[0] - 'a'][vals[s[0] - 'a']]; ++prevData[s[1] - 'a'][currSum]; if (s[0] == s[1]) ++ans; for (int i = 2; i < s.length(); ++i) { short idChar = s[i] - 'a'; const Long prefixSum = currSum; currSum += vals[idChar]; ans += prevData[idChar][prefixSum]; ++prevData[idChar][currSum]; } } cout << ans << "\n"; return 0; }
[ "noreply@github.com" ]
noreply@github.com
b83ed30b11e7c6d0edf626a3671b621ad6cc40c1
26fb901ef4e90e15a097fd0da94807750f93b897
/MC34933.h
a0ff5e5e0df17278cdf3dd1235179106c030d7ee
[ "MIT" ]
permissive
willumpie82/MC34933
f68f5e79711acae77a8251951a19fdb14054742f
f3481ea0a93070cd2d06ad1ec72a218f467ef74e
refs/heads/master
2022-12-16T08:33:15.488118
2020-09-13T14:43:34
2020-09-13T14:43:34
295,167,696
0
0
null
null
null
null
UTF-8
C++
false
false
1,401
h
/* MC34933.h - Library for the Toshiba MC34933 motor driver. Created by TheDIYGuy999 June - November 2016 Released into the public domain. This is Version 1.2 Change history: V1.1: The pin configuration was moved to the separate begin() function. Change your existing programs in accordance with the provided example V1.2: minPWM input variable added to the drive() function. Allows to eliminate the backlash in self balancing applications */ #ifndef MC34933H #define MC34933H #include "Arduino.h" // Class definition (header) ======================================================================== class MC34933 { public: MC34933(); void begin(int pin1, int pin2, int pwmPin, int minInput, int maxInput, int neutralWidth, boolean invert); boolean drive(int controlValue, int minPWM, int maxPWM, int rampTime, boolean neutralBrake); boolean brakeActive(); private: int _pin1; int _pin2; int _pwmPin; int _minInput; int _maxInput; int _minNeutral; int _maxNeutral; int _controlValue; int _controlValueRamp; int _minPWM; int _maxPWM; int _rampTime; boolean _neutralBrake; boolean _invert; unsigned long _previousMillis = 0; unsigned long _previousMillisBrake = 0; byte _state = 0; byte _forward; byte _reverse; byte _upwards; byte _downwards; }; #endif //MC34933H
[ "willemoldemans@willems-MacBook-Pro.local" ]
willemoldemans@willems-MacBook-Pro.local
5de37c8c9008dcea14c306b7bb86f1d6559864e4
8b545e38af1cce05b047dc79a19a0d047026e2d0
/Cpp-Primer-Plus/7/exercises/7.cpp
046ead58bc3f462de82d945710c50135daed2e34
[]
no_license
LyingHid/Learning-C-and-Cpp
b182c5399a1834b94c59036420a6a64fa8d7fe78
008ebdce3b079bee8864f4eca97f954a3cc20cb0
refs/heads/master
2021-08-31T12:31:30.977588
2017-12-21T09:11:22
2017-12-21T09:11:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,456
cpp
#include <iostream> const int Max = 5; double *fill_array(double *begin, double *end); void show_array(const double *begin, const double *end); void revalue(double r, double *begin, double *end); int main() { using namespace std; double properties[Max]; double *end = fill_array(properties, properties + Max - 1); show_array(properties, end); cout << "Enter revaluation factor: "; double factor; cin >> factor; revalue(factor, properties, end); show_array(properties, end); cout << "Done.\n"; return 0; } double *fill_array(double *begin, double *end) { using namespace std; double temp; int i; for(double *l = begin; l <= end; l++) { cout << "Enter value #" << (l - begin + 1) << ": "; cin >> temp; if (!cin) { cin.clear(); while (cin.get() != '\n') continue; cout << "Bad input: input process terminated.\n"; return l - 1; } else if (temp < 0) return l - 1; *l = temp; } return end; } void show_array(const double *begin, const double *end) { using namespace std; for (const double *l = begin; l <= end; l++) { cout << "Property #" << (l - begin + 1) << ": $"; cout << *l << endl; } } void revalue(double r, double *begin, double *end) { for (double *l = begin; l <= end; l++) { *l *= r; } }
[ "GloveInTheHouse@gmail.com" ]
GloveInTheHouse@gmail.com
1afa581beb9c659523042f84802f564bab23a2eb
ecac474a3f5095c61cfccd0e69cab0d4ca050ebd
/atcoder/AtCoder Regular Contest 081/D-Coloring Dominoes-dp.cpp
b16de053f2ff6e1656ba4827f5081cd5f7874b45
[ "Apache-2.0" ]
permissive
xehoth/OnlineJudgeCodes
478e678b35ba1b7e168b8230da594f03532aa74c
013d31cccaaa1d2b6d652c2f5d5d6cb2e39884a7
refs/heads/master
2021-01-20T05:37:25.194545
2019-08-17T16:07:02
2019-08-17T16:07:02
101,457,867
7
3
null
null
null
null
UTF-8
C++
false
false
1,032
cpp
/** * Copyright (c) 2017, xehoth * All rights reserved. * 「ARC 081D」Coloring Dominoes 21-08-2017 * dp * @author xehoth */ #include <bits/stdc++.h> namespace Task { const int MAXN = 52; const int MOD = 1e9 + 7; char s[2][MAXN]; inline void solve() { std::ios::sync_with_stdio(false), std::cin.tie(NULL), std::cout.tie(NULL); register int n; std::cin >> n >> s[0] >> s[1]; register int ans, tot = 0; if (s[0][0] == s[1][0]) ans = 3, tot = 1; else if (s[0][0] == s[0][1]) ans = 6, tot = 2; for (; tot < n;) { if (s[0][tot] == s[1][tot]) { if (s[0][tot - 1] == s[1][tot - 1]) ans = ans * 2ll % MOD; tot++; } else if (s[0][tot] == s[0][tot + 1]) { if (s[0][tot - 1] == s[1][tot - 1]) ans = ans * 2ll % MOD; else if (s[0][tot - 1] == s[0][tot - 2]) ans = ans * 3ll % MOD; tot += 2; } } std::cout << ans; } } int main() { Task::solve(); return 0; }
[ "824547322@qq.com" ]
824547322@qq.com
ed402c84e33a2f6c8043c43b3ece858da40f7047
dbb2ccb685c71435a8d2debef81a4441011ca2f3
/goaler/main.cpp
7c29fc5fcb271a21c5cd3f3ac43dcf48afc53891
[]
no_license
atomy/qt
dbf8c77d3adfa6cf4af61881987f5018e6e37ed8
efd4dbb3774360a904085577aeaf31a388c736f1
refs/heads/master
2020-05-18T12:56:16.112771
2013-04-08T21:19:46
2013-04-08T21:19:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
250
cpp
#include <QApplication> #include "GoalApp.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); GoalApp goalApp; #if defined(Q_OS_SYMBIAN) goalApp.showMaximized(); #else goalApp.show(); #endif return app.exec(); }
[ "atomy@jackinpoint.net" ]
atomy@jackinpoint.net
270feec26830c9e93e0f8ddd0340b35c2f8f441e
5ab7032615235c10c68d738fa57aabd5bc46ea59
/monk_and_cursed_tree.cpp
eafe70071cf7b8c712826492926c4212a812d0d5
[]
no_license
g-akash/spoj_codes
12866cd8da795febb672b74a565e41932abf6871
a2bf08ecd8a20f896537b6fbf96a2542b8ecf5c0
refs/heads/master
2021-09-07T21:07:17.267517
2018-03-01T05:41:12
2018-03-01T05:41:12
66,132,917
2
0
null
null
null
null
UTF-8
C++
false
false
1,721
cpp
#include <iostream> #include <vector> #include <unordered_map> #include <string> #include <math.h> #include <map> #include <queue> #include <stack> #include <algorithm> #include <list> using namespace std; #define ll long long int #define ull unsigned ll #define umm(x,y) unordered_map<x,y > #define mm(x,y) map<x,y > #define pb push_back #define foi(n) for(int i=0;i<n;i++) #define foj(n) for(int j=0;j<n;j++) #define foi1(n) for(int i=1;i<=n;i++) #define foj1(n) for(int j=1;j<=n;j++) #define vi vector<int> #define vb vector<bool> #define vvi vector<vi > #define vvb vector<vb > #define vll vector<ll> #define vvll vector<vll > #define si size() class node { public: int data; node *left, *right; }; node* insert(node *n, int data) { if(n==NULL) { node *nn = new node(); nn->data = data; return nn; } if(n->data==data)return n; if(n->data>data) { n->left = insert(n->left,data); return n; } else n->right = insert(n->right,data); return n; } vi get_path(node *n, int val) { vi ans; node *tmp=n; ans.pb(tmp->data); while(tmp->data!=val) { if(tmp->data<val) { tmp=tmp->right; } else tmp=tmp->left; ans.pb(tmp->data); } //foi(ans.size())cout<<ans[i]<<" "; return ans; } int main() { int n,data; node *root; cin>>n; foi(n) { cin>>data; root = insert(root,data); } int a,b,pos; cin>>a>>b; vi p1=get_path(root,a),p2=get_path(root,b); foi(p1.size()) { if(p1[i]==p2[i]) { pos=i; } else break; if(i==p2.size()-1)break; } vi tot_path; for(int i=pos;i<p1.size();i++) { tot_path.pb(p1[i]); } for(int i=pos;i<p2.size();i++) { tot_path.pb(p2[i]); } sort(tot_path.begin(),tot_path.end()); cout<<tot_path[tot_path.size()-1]<<endl; }
[ "akash.garg2007@gmail.com" ]
akash.garg2007@gmail.com
1cac089593d07553866818615823502bcc32cf62
b86f9b27178268065fc56e75af47356bb3c73bea
/Implementering/SW CSS Hovedenhed/PC RS232IF Test program/PC RS232IF Test program/RS232IF.h
8dcc5418495bca5768d08d927167e28d175c67a5
[]
no_license
mickkn/E2PRJ2
5b585957333aa6577785557455164fe94863f4e5
3d81a7ce6ee45d73293da281fdad8fef132a4b6e
refs/heads/master
2021-01-13T02:16:27.548333
2014-05-27T15:38:50
2014-05-27T15:38:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,371
h
/* * Klasse RS232IF * * Styrer kommunikation mellem PC og CSS hovedenhed over RS232 protokollen * * Af Bjørn Sørensen * */ #pragma once #define F_CPU 3686400 #include <avr/io.h> #include <string.h> #include <stdlib.h> #include <util/delay.h> #include "UART.h" class RS232IF { public: RS232IF( ); // Indsæt som første parameter: UC1Login * UC1Ptr, UC2Aktiver * UC2Ptr, UC3Deaktiver * UC3Ptr, ~RS232IF(); unsigned char getUC(char *); // Henter fuld kommando, unwrapper og dekoder protokollen, returnerer nummer på næste UC kald: // // 1: UC1 Login // // 2: UC2 Aktiver // // 3: UC3 Deaktiver void getAdresse(char *kommando, char *adresse); // Hent adresse ud af kommando void loginStatus( bool status ); // Afsend login status void adviser( ); // Alarmer PC om babyalarm private: // Referencer /*UC1Login * UC1Ptr_; UC2Aktiver * UC2Ptr_; UC3Deaktiver * UC3Ptr_;*/ // Kommandowrapper (STX og ETX) void wrapper(const char *kommando, char *wrapped); void unwrapper(const char *wrapped, char *kommando); unsigned char protokolUnwrap(char *kommando); // Afsend wrapped kommando void sendKommando(char * wrapped); void loginTrue( ); // Afsend login verificeret void loginFalse( ); // Afsend login ikke verificeret };
[ "karnich99@gmail.com" ]
karnich99@gmail.com
1898791d2741d10468a19c035fe0438073f4c5ba
6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849
/sstd_boost/sstd/libs/ratio/test/ratio_extensions/mpl_rational_constant_pass.cpp
369fb1f2b34aeffbb97b9b3b9c179d34261bbd90
[ "NCSA", "MIT", "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
KqSMea8/sstd_library
9e4e622e1b01bed5de7322c2682539400d13dd58
0fcb815f50d538517e70a788914da7fbbe786ce1
refs/heads/master
2020-05-03T21:07:01.650034
2019-04-01T00:10:47
2019-04-01T00:10:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
335
cpp
//===----------------------------------------------------------------------===// // Copyright 2011 Vicente J. Botet Escriba // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt #define BOOST_RATIO_EXTENSIONS #include <sstd/boost/ratio/mpl/comparison.hpp> void test() { }
[ "zhaixueqiang@hotmail.com" ]
zhaixueqiang@hotmail.com
50a7ff50b811e84e3be98afb1fc40a6a686ed39a
2d6319e30ca60a5fe535f6c437d0c27bade939d7
/luciolinae_ctl/src/NearestPointOnLineToPoint.cpp
0130186073951b5cae2a0ffbb9ed4816564ac765
[]
no_license
simonec77/damian_public_of_apps
fa8bf8e177d39bb83db8fd5d2d3872a40dd5a8ca
ebedbf3db44df413175f6c51b7c9cb0c56378238
refs/heads/master
2021-01-23T22:05:32.302618
2010-08-15T09:50:21
2010-08-15T09:50:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,247
cpp
/* * NearestPointOnLineToPoint.cpp * luciolinae_ctl * * Created by damian on 18/05/10. * Copyright 2010 frey damian@frey.co.nz. All rights reserved. * */ #include "NearestPointOnLineToPoint.h" // stolen from // http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/ // Calculate the nearest point on the given line segment to the given point. // Return the intersection point on the line. If linePosition is non-NULL, // return the normalised line position (0=LineStart, 1=LineEnd, <0=before // LineStart, >1=after LineEnd). ofxVec3f NearestPointOnLineToPoint::calculateNearestPoint( const ofxVec3f &LineStart, const ofxVec3f &LineEnd, const ofxVec3f &Point, float* linePosition ) { float LineMagSq; float U; LineMagSq = (LineEnd-LineStart).lengthSquared(); if ( LineMagSq > (0.000001f*0.000001f) ) { U = ( ( ( Point.x - LineStart.x ) * ( LineEnd.x - LineStart.x ) ) + ( ( Point.y - LineStart.y ) * ( LineEnd.y - LineStart.y ) ) + ( ( Point.z - LineStart.z ) * ( LineEnd.z - LineStart.z ) ) ) / LineMagSq; } else U = 1.0f; ofxVec3f intersection = LineStart + U*(LineEnd-LineStart); // save linePosition if ( linePosition != NULL ) *linePosition = U; return intersection; }
[ "damian@frey.NOSPAMco.nz" ]
damian@frey.NOSPAMco.nz
bcb6da67ac8dfdaf90973b1a92170d0ac7998fbb
4a5f51c19965e5347dc0d11f1677994f289688a5
/src/semantics/include/sema/types.h
da729e2abb3ae334bdf2f9170b50454a2ed7eea3
[]
no_license
MacDue/Mank
7e7ed4886c3c8736a31bb234f1ca1802554cacc4
1f4dde18c5fe1b550e47805c69e79990cc72e75f
refs/heads/master
2023-05-22T06:38:57.714008
2021-06-13T14:10:37
2021-06-13T14:10:37
299,920,292
3
0
null
null
null
null
UTF-8
C++
false
false
2,381
h
#pragma once #include <utility> #include <optional> #include <type_traits> #include <mpark/patterns.hpp> #include "ast/types.h" #include "ast/ast_builder.h" #include "sema/type_infer.h" #include "errors/compiler_errors.h" // The resolved type + a the type's identifier in the source (for error messages) using TypeResolution = std::pair<Type_Ptr, std::optional<Ast_Identifier>>; using MakeConstraint = std::optional<Infer::MakeConstraint>; bool match_types(Type_Ptr a, Type_Ptr b, MakeConstraint const & make_constraint = std::nullopt, bool ignore_refs = true); inline bool is_tvar(Type_Ptr type) { if (!type) return false; // Should ref TVar = TVar???? return std::holds_alternative<TypeVar>(remove_reference(type)->v); } template <typename T> T min_type(T a, T b) { using namespace mpark::patterns; // Reutrn the opposite as there's a chance it's non-null & a tvar. if (!a) return b; if (!b) return a; return match(a->v, b->v)( pattern(as<TypeVar>(_), _) = [&]{ return a; }, pattern(_, as<TypeVar>(_)) = [&]{ return b; }, pattern(_, _) = [&]{ return a; } ); } // Used to resolve type aliases (that could be infinte types) using TypeStarts = std::optional<std::set<Ast_Identifier>>; TypeResolution resolve_type(Scope& scope, Type_Ptr type, TypeStarts starting_points = std::nullopt); Type_Ptr get_field_type(Ast_Field_Access& access); Type_Ptr get_field_type(TypeFieldConstraint& field_constraint); Type_Ptr get_field_type( Ast_Pod_Bind& pod_bind, Expr_Ptr init, Type_Ptr init_type); Type_Ptr get_element_type(Type_Ptr type, Ast_Index_Access& access); bool validate_type_cast(Type_Ptr type, Ast_As_Cast& as_cast); bool is_switchable_type(Type_Ptr type); void assert_has_switchable_type(Expr_Ptr expr); template<typename T> void resolve_type_or_fail( Scope& scope, Type_Ptr& to_resolve, T error_format, TypeStarts starting_points = std::nullopt ) { auto [ resolved_type, type_slot ] = resolve_type(scope, to_resolve, starting_points); if (resolved_type) { to_resolve = resolved_type; } else if (type_slot) { throw_error_at(*type_slot, error_format); } else { IMPOSSIBLE(); } } template<typename T1> T1* get_if_dereferenced_type(Type_Ptr& type) { return std::get_if<T1>(&remove_reference(type)->v); } void static_check_array_bounds(Ast_Index_Access& index_access, bool allow_missing_types = false);
[ "macdue@dueutil.tech" ]
macdue@dueutil.tech
2c3d3df318c4e963922c030218318fe79dc0bb09
a7fcba705ef0e1969d8fd1a450b25e682c0f37d4
/server/sqldaoimp.h
7c5983e2e6d0d886ae2487227bfcb549ff45efc7
[]
no_license
1375917982/Online-Video-Streaming-Platform
5d1ecd19652415777e3c0773bf151e1858376d9f
ec73124c4cee91147220e6440bd9e1ca18905c93
refs/heads/master
2022-06-13T01:17:41.682712
2020-04-30T21:19:31
2020-04-30T21:19:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
439
h
#ifndef SQLDAOIMP_H #define SQLDAOIMP_H #include "sqldao.h" class SqlDaoImp : public SqlDao { public: SqlDaoImp(); virtual void insertUser(const User& user); virtual void deleteUser(const User& user); virtual void updateUser(const User& user); virtual User* selectUser(const User& user); virtual QVector<User> getAllUser(); virtual void exec(const QString& sql); }; #endif // SQLDAOIMP_H
[ "noreply@github.com" ]
noreply@github.com
2996f1e94323a7911868ab47213032588ce59aa8
bd1fea86d862456a2ec9f56d57f8948456d55ee6
/000/074/233/CWE124_Buffer_Underwrite__CWE839_rand_74b.cpp
25320078974e46b3e01baa110f5baeb12f7ad862
[]
no_license
CU-0xff/juliet-cpp
d62b8485104d8a9160f29213368324c946f38274
d8586a217bc94cbcfeeec5d39b12d02e9c6045a2
refs/heads/master
2021-03-07T15:44:19.446957
2020-03-10T12:45:40
2020-03-10T12:45:40
246,275,244
0
1
null
null
null
null
UTF-8
C++
false
false
2,704
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE124_Buffer_Underwrite__CWE839_rand_74b.cpp Label Definition File: CWE124_Buffer_Underwrite__CWE839.label.xml Template File: sources-sinks-74b.tmpl.cpp */ /* * @description * CWE: 124 Buffer Underwrite * BadSource: rand Set data to result of rand(), which may be zero * GoodSource: Non-negative but less than 10 * Sinks: * GoodSink: Ensure the array index is valid * BadSink : Improperly check the array index by not checking the lower bound * Flow Variant: 74 Data flow: data passed in a map from one function to another in different source files * * */ #include "std_testcase.h" #include <map> using namespace std; namespace CWE124_Buffer_Underwrite__CWE839_rand_74 { #ifndef OMITBAD void badSink(map<int, int> dataMap) { /* copy data out of dataMap */ int data = dataMap[2]; { int i; int buffer[10] = { 0 }; /* POTENTIAL FLAW: Attempt to access a negative index of the array * This code does not check to see if the array index is negative */ if (data < 10) { buffer[data] = 1; /* Print the array values */ for(i = 0; i < 10; i++) { printIntLine(buffer[i]); } } else { printLine("ERROR: Array index is negative."); } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(map<int, int> dataMap) { int data = dataMap[2]; { int i; int buffer[10] = { 0 }; /* POTENTIAL FLAW: Attempt to access a negative index of the array * This code does not check to see if the array index is negative */ if (data < 10) { buffer[data] = 1; /* Print the array values */ for(i = 0; i < 10; i++) { printIntLine(buffer[i]); } } else { printLine("ERROR: Array index is negative."); } } } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSink(map<int, int> dataMap) { int data = dataMap[2]; { int i; int buffer[10] = { 0 }; /* FIX: Properly validate the array index and prevent a buffer underwrite */ if (data >= 0 && data < (10)) { buffer[data] = 1; /* Print the array values */ for(i = 0; i < 10; i++) { printIntLine(buffer[i]); } } else { printLine("ERROR: Array index is out-of-bounds"); } } } #endif /* OMITGOOD */ } /* close namespace */
[ "frank@fischer.com.mt" ]
frank@fischer.com.mt
73c4d334cc214ea6a2cae62d3af0b83940dfde05
363751d054420a77bd6e04c6057e852b9cf75990
/examples/src/applications/datums/ResourceOwners.cpp
45217b3b88beef298c67f8862423a3bbe727116c
[ "Unlicense", "MIT", "FSFAP" ]
permissive
kspine/zapata
53450b0a1960aad07525724f4de125ed832a51e3
514aa5fe6e8b3c0a5a3c9ea6a4df842c1f55e2a4
refs/heads/master
2020-04-08T01:48:46.627797
2018-11-02T16:42:49
2018-11-02T16:42:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,701
cpp
#include <zapata/applications/datums/ResourceOwners.h> auto zpt::apps::datums::ResourceOwners::get(std::string _topic, zpt::ev::emitter _emitter, zpt::json _identity, zpt::json _envelope) -> zpt::json { zpt::json _r_data; zpt::connector _c = _emitter->connector("dbms.redis.zpt.apps"); _r_data = _c->get("ResourceOwners", _topic, {"href", _topic}); return _r_data; } auto zpt::apps::datums::ResourceOwners::query(std::string _topic, zpt::json _filter, zpt::ev::emitter _emitter, zpt::json _identity, zpt::json _envelope) -> zpt::json { zpt::json _r_data; zpt::connector _c = _emitter->connector("dbms.mongodb.zpt.apps"); _r_data = _c->query("ResourceOwners", _filter, _filter + zpt::json({"href", _topic})); return _r_data; } auto zpt::apps::datums::ResourceOwners::insert(std::string _topic, zpt::json _document, zpt::ev::emitter _emitter, zpt::json _identity, zpt::json _envelope) -> zpt::json { zpt::json _r_data; bool _r_extends = false; zpt::connector _c = _emitter->connector("dbms.pgsql.zpt.apps"); _document << "created" << zpt::json::date() << "updated" << zpt::json::date(); _r_data = {"href", (_topic + std::string("/") + _c->insert("ResourceOwners", _topic, _document, {"href", _topic}))}; if (!_r_extends) _emitter->mutations()->route(zpt::mutation::Insert, _topic, {"performative", "insert", "href", _document["href"], "new", _document}); return _r_data; } auto zpt::apps::datums::ResourceOwners::save(std::string _topic, zpt::json _document, zpt::ev::emitter _emitter, zpt::json _identity, zpt::json _envelope) -> zpt::json { zpt::json _r_data; bool _r_extends = false; zpt::connector _c = _emitter->connector("dbms.pgsql.zpt.apps"); _document << "updated" << zpt::json::date(); _r_data = {"href", _topic, "n_updated", _c->save("ResourceOwners", _topic, _document, {"href", _topic})}; if (!_r_extends) _emitter->mutations()->route( zpt::mutation::Replace, _topic, {"performative", "save", "href", _topic, "new", _document}); return _r_data; } auto zpt::apps::datums::ResourceOwners::set(std::string _topic, zpt::json _document, zpt::ev::emitter _emitter, zpt::json _identity, zpt::json _envelope) -> zpt::json { zpt::json _r_data; bool _r_extends = false; zpt::connector _c = _emitter->connector("dbms.pgsql.zpt.apps"); _document << "updated" << zpt::json::date(); _r_data = {"href", _topic, "n_updated", _c->set("ResourceOwners", _topic, _document, {"href", _topic})}; if (!_r_extends) _emitter->mutations()->route( zpt::mutation::Update, _topic, {"performative", "set", "href", _topic, "changes", _document}); return _r_data; } auto zpt::apps::datums::ResourceOwners::set(std::string _topic, zpt::json _document, zpt::json _filter, zpt::ev::emitter _emitter, zpt::json _identity, zpt::json _envelope) -> zpt::json { zpt::json _r_data; bool _r_extends = false; zpt::connector _c = _emitter->connector("dbms.pgsql.zpt.apps"); _document << "updated" << zpt::json::date(); _r_data = {"href", _topic, "n_updated", _c->set("ResourceOwners", _filter, _document, {"href", _topic})}; if (!_r_extends) _emitter->mutations()->route( zpt::mutation::Update, _topic, {"performative", "set", "href", _topic, "changes", _document, "filter", _filter}); return _r_data; } auto zpt::apps::datums::ResourceOwners::remove(std::string _topic, zpt::ev::emitter _emitter, zpt::json _identity, zpt::json _envelope) -> zpt::json { zpt::json _r_data; bool _r_extends = false; zpt::connector _c = _emitter->connector("dbms.pgsql.zpt.apps"); _r_data = {"href", _topic, "n_deleted", _c->remove("ResourceOwners", _topic, {"href", _topic})}; if (!_r_extends) _emitter->mutations()->route(zpt::mutation::Remove, _topic, {"performative", "remove", "href", _topic}); return _r_data; } auto zpt::apps::datums::ResourceOwners::remove(std::string _topic, zpt::json _filter, zpt::ev::emitter _emitter, zpt::json _identity, zpt::json _envelope) -> zpt::json { zpt::json _r_data; bool _r_extends = false; zpt::connector _c = _emitter->connector("dbms.pgsql.zpt.apps"); _r_data = { "href", _topic, "n_deleted", _c->remove("ResourceOwners", _filter, _filter + zpt::json({"href", _topic}))}; if (!_r_extends) _emitter->mutations()->route( zpt::mutation::Remove, _topic, {"performative", "remove", "href", _topic, "filter", _filter}); return _r_data; }
[ "pedro.figueiredo@gmail.com" ]
pedro.figueiredo@gmail.com
bb375ce43768871a76cc25f150f6fa60188c42c8
7af400b31210a6c0f7d4b5e93783e919d94a3266
/sampleCode/maximumSizeSquareSubMatrixWithAllSameValue.cpp
a0be7891dbaffbc0b8ebb52f3783909f79e30991
[]
no_license
abhishek-nvcc/sampleCode
078df9237880d906303f378124b5fc9550e20abd
089676018d6fc767191ac38e1f60c64f7bdeb709
refs/heads/master
2021-04-03T01:58:30.668640
2018-07-24T06:23:29
2018-07-24T06:23:29
124,633,062
0
0
null
null
null
null
UTF-8
C++
false
false
5,505
cpp
#include <stdio.h> #include <iostream> #include <string> #include <vector> #include <assert.h> using namespace std; typedef std::vector<int> listOfInt; typedef std::vector<listOfInt> arrayOfInt; bool hasDataCorrectValues(const arrayOfInt& originalData) { bool bRetVal = true; for (const listOfInt rowVec : originalData) { for (const int dataValue : rowVec) { if(0 != dataValue && 1 != dataValue) { bRetVal = false; break; } } if(false == bRetVal) { break; } } return bRetVal; } bool isDataSquare(const arrayOfInt& originalData) { bool bRetVal = true; size_t numOfRows = originalData.size(); for (const listOfInt rowVec : originalData) { if(numOfRows != rowVec.size()) { bRetVal = false; break; } } return bRetVal; } bool checkSquare(const arrayOfInt& originalData, const int testVal, const int rowNum, const int colNum, const int intermediateSizeOfSquare) { bool bRetVal = true; size_t sizeOfSquare = originalData.size(); for(int rowCount = 0; rowCount < intermediateSizeOfSquare; ++rowCount) { if(sizeOfSquare > (rowNum + rowCount)) { listOfInt list = originalData[rowNum + rowCount]; for(int colCount = 0; colCount < intermediateSizeOfSquare; ++colCount) { if(sizeOfSquare > (colNum + colCount)) { int testData = list[colNum + colCount]; if(testVal != testData) { bRetVal = false; break; } } } if(false == bRetVal) { break; } } } return bRetVal; } void checkBiggestSquare(const arrayOfInt& originalData, const int testVal, int& biggestSquareStartingRowNum, int& biggestSquareStartingColNum, int& biggestSquareSize) { if(false == isDataSquare(originalData) || false == hasDataCorrectValues(originalData)) return; biggestSquareSize = 0; size_t sizeOfSquare = originalData.size(); for (int rowNum = 0; rowNum < sizeOfSquare; ++rowNum) { if(sizeOfSquare > rowNum) { listOfInt list = originalData[rowNum]; for (int colNum = 0; colNum < sizeOfSquare; ++colNum) { if(biggestSquareSize < (sizeOfSquare - rowNum) && biggestSquareSize < (sizeOfSquare - colNum) && sizeOfSquare > colNum) { if(testVal != list[colNum]) { continue; } int intermediateSizeOfSquare = 2; bool bFoundValue = false; while((true == checkSquare(originalData, testVal, rowNum, colNum, intermediateSizeOfSquare)) && (sizeOfSquare >= (colNum + intermediateSizeOfSquare)) && (sizeOfSquare >= (rowNum + intermediateSizeOfSquare))) { bFoundValue = true; ++intermediateSizeOfSquare; } if(true == bFoundValue) { --intermediateSizeOfSquare; if(intermediateSizeOfSquare > biggestSquareSize) { biggestSquareStartingRowNum = rowNum; biggestSquareStartingColNum = colNum; biggestSquareSize = intermediateSizeOfSquare; } } } } } } } void findAndDumpOutput(const arrayOfInt& matrix, const int testVal) { int biggestSquareStartingRowNum = 0, biggestSquareStartingColNum = 0, biggestSquareSize = 0; checkBiggestSquare(matrix, testVal, biggestSquareStartingRowNum, biggestSquareStartingColNum, biggestSquareSize); std::cout << "biggestSquareStartingRowNum: " << biggestSquareStartingRowNum << std::endl; std::cout << "biggestSquareStartingColNum: " << biggestSquareStartingColNum << std::endl; std::cout << "biggestSquareSize: " << biggestSquareSize << std::endl; } void testCase1() { std::cout << "**********************TEST CASE 1**********************" << std::endl; listOfInt row1 = {0,1,0,1,1,1,0,0,0,1}; listOfInt row2 = {1,1,0,0,0,0,0,0,0,1}; listOfInt row3 = {0,1,0,1,1,1,0,0,1,1}; listOfInt row4 = {0,1,1,1,0,1,1,1,0,1}; listOfInt row5 = {1,1,1,1,1,1,0,0,0,1}; listOfInt row6 = {1,1,0,1,1,1,0,1,0,1}; listOfInt row7 = {0,1,0,1,1,1,1,1,1,1}; listOfInt row8 = {1,1,1,1,1,1,1,1,0,1}; listOfInt row9 = {0,1,0,1,1,1,1,1,1,1}; listOfInt row10 = {1,1,1,1,1,1,1,1,1,1}; arrayOfInt matrix = {row1, row2, row3, row4, row5, row6, row7, row8, row9, row10}; int testVal = 1; findAndDumpOutput(matrix, testVal); } void testCase2() { std::cout << "**********************TEST CASE 2**********************" << std::endl; listOfInt row1 = {0,1,0,1,1}; listOfInt row2 = {1,1,1,1,1}; listOfInt row3 = {1,1,0,1,1}; listOfInt row4 = {0,1,1,1,1}; listOfInt row5 = {0,0,1,0,0}; arrayOfInt matrix = {row1, row2, row3, row4, row5}; int testVal = 1; findAndDumpOutput(matrix, testVal); } int main() { testCase1(); testCase2(); return 1; }
[ "abhishek.nvcc@gmail.com" ]
abhishek.nvcc@gmail.com
0aa9452aa3b0ee37f81ff1490b85a175f60295bf
1722686f8139aca7d6927ec7a6dfed13a5d319fb
/pc-common/AudioVideoSDKs/wangyi_163/Processing_C_Channel.h
97636ebc7997877e692e5dee63463ae83789dc9f
[]
no_license
oamates/clientmy
610ca1c825e503e0b477a9a579248d608435a5d0
b3618b2225da198f338a3f2981c841dde010cd8d
refs/heads/main
2022-12-30T14:53:43.037242
2020-10-21T01:01:12
2020-10-21T01:01:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,704
h
#ifndef PROCESSING_C_CHANNEL_H #define PROCESSING_C_CHANNEL_H #include "../AudioVideoBase.h" #include "channel_wangyi.h" #include <QMap> #include <QStringList> #include <QCryptographicHash> #include <QIODevice> class Processing_C_Channel : public AudioVideoBase { Q_OBJECT private: explicit Processing_C_Channel(); static Processing_C_Channel *m_processing_C_Channel; public: virtual ~Processing_C_Channel(); static Processing_C_Channel *getInstance(); virtual bool initChannel(COURSE_TYPE courseType, ROLE_TYPE role, QString userId, QString lessonId, QString camera, QString microphone, QString strSpeaker, QString strMicPhone, QString strCamera, QString apiVersion, QString appVersion, QString token, QString strDllFile, QString strAppName, QString &logFilePath);// 初始化频道 virtual bool enterChannel(const char *channelKey,const char *channelName, const char *info, unsigned int uid, QMap<QString, QPair<QString, QString>>& cameraPhone,int videoSpan = 0);// 进入频道 virtual bool leaveChannel()override;// 离开频道 virtual bool openLocalVideo()override;// 打开本地视频 virtual bool closeLocalVideo()override;// 关闭本地视频 virtual bool openLocalAudio()override;// 打开本地音频 virtual bool closeLocalAudio()override;// 关闭本地音频 public: bool doGet_User_Name_pwd(); // 得到网易C通道的用户名, 密码 bool doGet_Push_Url(); // 得到网易C通道的录播推流地址 signals: void sigChangeChannel(QJsonObject changeChannelObj); private: chanel_wangyi m_objChanelWangyi; YMHttpClientUtils *m_httpClient; QString m_httpUrl; }; #endif
[ "shaohua.zhang@yimifudao.com" ]
shaohua.zhang@yimifudao.com
6ab743b33d8da3a3a39235a1cbf5b4c1763f95cf
8f29bbdbc1b29365eca840b72d61f63abe8f829f
/Semester2/3001/AI midterm/SDLGameEngine/Shoot.h
309fb5c273df8a808fbc8fdd2209883c826a8711
[]
no_license
CccrizzZ/GBC01
d294f01aab97de37f2b70bcf325ae713e4eed740
c44130872f609e5778992d8a6dad09caed29ff71
refs/heads/master
2022-02-22T11:32:54.720661
2019-10-14T00:07:50
2019-10-14T00:07:50
158,318,882
0
0
null
null
null
null
UTF-8
C++
false
false
120
h
#pragma once #include "Behaviour.h" class Shoot : public Behaviour { public: Shoot(); ~Shoot(); void Update(); };
[ "ccccrizzzz@gmail.com" ]
ccccrizzzz@gmail.com
118b29826102a30bfffaf03c5979d635bce99733
26df6604faf41197c9ced34c3df13839be6e74d4
/src/org/apache/poi/ss/formula/functions/NumericFunction_18.hpp
7e7e54f664a9f5671a4437243030a4f1b9c45588
[ "Apache-2.0" ]
permissive
pebble2015/cpoi
58b4b1e38a7769b13ccfb2973270d15d490de07f
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
refs/heads/master
2021-07-09T09:02:41.986901
2017-10-08T12:12:56
2017-10-08T12:12:56
105,988,119
0
0
null
null
null
null
UTF-8
C++
false
false
2,806
hpp
// Generated from /POI/java/org/apache/poi/ss/formula/functions/NumericFunction.java #pragma once #include <fwd-POI.hpp> #include <java/lang/fwd-POI.hpp> #include <org/apache/poi/ss/formula/eval/fwd-POI.hpp> #include <org/apache/poi/ss/formula/functions/fwd-POI.hpp> #include <org/apache/poi/ss/formula/functions/NumericFunction_OneArg.hpp> template<typename ComponentType, typename... Bases> struct SubArray; namespace poi { namespace ss { namespace formula { namespace eval { typedef ::SubArray< ::poi::ss::formula::eval::ValueEval, ::java::lang::ObjectArray > ValueEvalArray; } // eval } // formula } // ss } // poi struct default_init_tag; class poi::ss::formula::functions::NumericFunction_18 : public NumericFunction_OneArg { public: typedef NumericFunction_OneArg super; public: /* protected */ double evaluate(double d) override; // Generated NumericFunction_18(); public: static ::java::lang::Class *class_(); ::poi::ss::formula::eval::ValueEval* evaluate(int32_t srcRowIndex, int32_t srcColumnIndex, ::poi::ss::formula::eval::ValueEval* arg0); ::poi::ss::formula::eval::ValueEval* evaluate(::poi::ss::formula::eval::ValueEvalArray* args, int32_t srcRowIndex, int32_t srcColumnIndex); private: virtual ::java::lang::Class* getClass0(); friend class NumericFunction; friend class NumericFunction_OneArg; friend class NumericFunction_TwoArg; friend class NumericFunction_1; friend class NumericFunction_2; friend class NumericFunction_3; friend class NumericFunction_4; friend class NumericFunction_5; friend class NumericFunction_6; friend class NumericFunction_7; friend class NumericFunction_8; friend class NumericFunction_9; friend class NumericFunction_10; friend class NumericFunction_11; friend class NumericFunction_12; friend class NumericFunction_13; friend class NumericFunction_14; friend class NumericFunction_15; friend class NumericFunction_16; friend class NumericFunction_17; friend class NumericFunction_19; friend class NumericFunction_20; friend class NumericFunction_21; friend class NumericFunction_22; friend class NumericFunction_23; friend class NumericFunction_24; friend class NumericFunction_25; friend class NumericFunction_26; friend class NumericFunction_27; friend class NumericFunction_28; friend class NumericFunction_29; friend class NumericFunction_30; friend class NumericFunction_31; friend class NumericFunction_32; friend class NumericFunction_33; friend class NumericFunction_Log; friend class NumericFunction_34; friend class NumericFunction_35; friend class NumericFunction_36; };
[ "zhang.chen.yu@outlook.com" ]
zhang.chen.yu@outlook.com
4c051ce31ced7cf102edb4e4de64155051c6f2cd
22f8ce70cc780eda7cb11f93803058831f43c7c5
/Plugins/BlueprintTool/Source/BlueprintToolRuntime/Public/BlueprintToolRuntime.h
fe5517bb86bcc5b56418702310f0a818f008b432
[]
no_license
VegetableWithChicken/SomeTest
4d26ebc44fbf8a387bec2ec9677d51485c7c9668
8659f9b99ec05f3e235ec9d7839671751c85cbf8
refs/heads/dev
2023-03-16T05:40:16.603350
2020-11-02T07:04:52
2020-11-02T07:04:52
508,117,547
1
0
null
2022-06-28T01:42:35
2022-06-28T01:42:34
null
UTF-8
C++
false
false
332
h
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "Modules/ModuleManager.h" class FBlueprintToolRuntimeModule : public IModuleInterface { public: /** IModuleInterface implementation */ virtual void StartupModule() override; virtual void ShutdownModule() override; };
[ "563412673@qq.com" ]
563412673@qq.com
62e69b3f5e843fcf3e2fcbb862ffa00976bfa591
fb888e19c1d595701fe806b5e3ddd85388de0f45
/src/utils/logger.h
e5aa2393da65fe05b28385ae43a68de56d3f5a90
[ "Apache-2.0" ]
permissive
yt-zgl/bubichain
f3514c6974b92f3575a19d9ac6a97fae50460788
a47ef90b10e50d80a52e5d374672152d6a2a3ba0
refs/heads/master
2020-03-12T19:37:37.498814
2017-08-28T05:38:25
2017-08-28T05:38:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,616
h
/* Copyright © Bubi Technologies Co., Ltd. 2017 All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef UTILS_LOGGER_H_ #define UTILS_LOGGER_H_ #include "common.h" #include "singleton.h" #include "thread.h" #define LOG_TRACE(fmt, ...) utils::Logger::Instance().LogStubVm(utils::LOG_LEVEL_TRACE,__FILE__,__func__, __LINE__ , fmt , ## __VA_ARGS__) #define LOG_DEBUG(fmt, ...) utils::Logger::Instance().LogStubVm(utils::LOG_LEVEL_DEBUG,__FILE__,__func__, __LINE__ , fmt , ## __VA_ARGS__) #define LOG_INFO(fmt, ...) utils::Logger::Instance().LogStubVm(utils::LOG_LEVEL_INFO,__FILE__,__func__, __LINE__ , fmt , ## __VA_ARGS__) #define LOG_WARN(fmt, ...) utils::Logger::Instance().LogStubVm(utils::LOG_LEVEL_WARN,__FILE__,__func__, __LINE__ , fmt , ## __VA_ARGS__) #define LOG_ERROR(fmt, ...) utils::Logger::Instance().LogStubVm(utils::LOG_LEVEL_ERROR,__FILE__,__func__, __LINE__ , fmt , ## __VA_ARGS__) #define LOG_FATAL(fmt, ...) utils::Logger::Instance().LogStubVm(utils::LOG_LEVEL_FATAL,__FILE__,__func__, __LINE__ , fmt , ## __VA_ARGS__) #define LOG_TRACE_ERRNO(fmt, ...) utils::Logger::Instance().LogStubVm(utils::LOG_LEVEL_TRACE,__FILE__,__func__, __LINE__ , fmt" (%u:%s)" , ## __VA_ARGS__) #define LOG_DEBUG_ERRNO(fmt, ...) utils::Logger::Instance().LogStubVm(utils::LOG_LEVEL_DEBUG,__FILE__,__func__, __LINE__ , fmt" (%u:%s)" , ## __VA_ARGS__) #define LOG_INFO_ERRNO(fmt, ...) utils::Logger::Instance().LogStubVm(utils::LOG_LEVEL_INFO,__FILE__,__func__, __LINE__ , fmt" (%u:%s)" , ## __VA_ARGS__) #define LOG_WARN_ERRNO(fmt, ...) utils::Logger::Instance().LogStubVm(utils::LOG_LEVEL_WARN,__FILE__,__func__, __LINE__ , fmt" (%u:%s)" , ## __VA_ARGS__) #define LOG_ERROR_ERRNO(fmt, ...) utils::Logger::Instance().LogStubVm(utils::LOG_LEVEL_ERROR,__FILE__,__func__, __LINE__ , fmt" (%u:%s)" , ## __VA_ARGS__) #define LOG_FATAL_ERRNO(fmt, ...) utils::Logger::Instance().LogStubVm(utils::LOG_LEVEL_FATAL,__FILE__,__func__, __LINE__ , fmt" (%u:%s)" , ## __VA_ARGS__) #define LOG_STD_ERR(fmt, ...) utils::Logger::Instance().LogStubVmError(__FILE__,__func__, __LINE__ , fmt , ## __VA_ARGS__) #define LOG_STD_ERRNO(fmt, ...) utils::Logger::Instance().LogStubVmError(__FILE__,__func__, __LINE__ , fmt" (%u:%s)" , ## __VA_ARGS__) #define STD_ERR_CODE utils::error_code() #define STD_ERR_DESC utils::error_desc().c_str() #define BUBI_EXIT(fmt, ...) { utils::Logger::Instance().LogStubVm(utils::LOG_LEVEL_ERROR,__FILE__,__func__, __LINE__ , fmt , ## __VA_ARGS__); exit(-1); } #define BUBI_EXIT_ERRNO(fmt, ...) { utils::Logger::Instance().LogStubVm(utils::LOG_LEVEL_ERROR,__FILE__,__func__, __LINE__ , fmt" (%u:%s)" , ## __VA_ARGS__); exit(-1); } namespace utils { typedef enum tagLogDest { /** Indicates that logging should be done to file. */ LOG_DEST_NONE = 0x00, LOG_DEST_FILE = 0x01, /** Log to Console. (stdout) */ LOG_DEST_OUT = 0x02, LOG_DEST_ERR = 0x04, LOG_DEST_ALL = 0xFF, LOG_DEST_FILE_OUT_ID = 0, LOG_DEST_FILE_ERR_ID = 1, LOG_DEST_OUT_ID = 2, LOG_DEST_ERR_ID = 3, LOG_DEST_COUNT = 4, }LogDest; typedef enum tagLogLevel { LOG_LEVEL_NONE = 0x00, LOG_LEVEL_TRACE = 0x01, LOG_LEVEL_DEBUG = 0x02, LOG_LEVEL_INFO = 0x04, LOG_LEVEL_WARN = 0x08, LOG_LEVEL_ERROR = 0x10, LOG_LEVEL_FATAL = 0x20, LOG_LEVEL_ALL = 0xFF }LogLevel; class Logger; class LogWriter { public: LogWriter(); ~LogWriter(); bool Init(LogDest dest, const std::string &file_name, bool open_mode); bool Write(Logger *logger, const LogLevel logLevel, const char *current_time, const char* file, const char* funcName, const int lineNum, const char* fmt, va_list ap); bool Close(); LogDest log_dest(); static std::string GetLogPrefix(const LogLevel logLevel); private: LogDest dest_; FILE *file_ptr_; uint64_t size_; time_t begin_time_; std::string file_name_; }; class Logger : public Singleton<Logger> { friend class Singleton<Logger>; friend class LogWriter; private: Logger(); ~Logger(); public: bool Initialize(utils::LogDest log_dest, utils::LogLevel log_level, const std::string &file_name, bool open_mode); bool Exit(); int LogStubVm(LogLevel logLevel, const char* file, const char* funcName, const int lineNum, const char* fmt, ...); int LogStubVmError( const char* file, const char* funcName, const int lineNum, const char* fmt, ...); int LogStub(utils::LogLevel log_Level, const char* file, const char* funcName, const int lineNum, const char* fmt, va_list ap); void SetCapacity(uint32_t time_cap, uint64_t size_cap); void SetExpireDays(uint32_t expire_days); void SetLogLevel(LogLevel log_level); void CheckExpiredLog(); bool GetBackupNameTime(const std::string &strBackupName, time_t &nTimeFrom, time_t &nTimeTo); private: LogWriter log_writers_[LOG_DEST_COUNT]; LogLevel log_level_; LogDest log_dest_; utils::Mutex mutex_; time_t time_capacity_; uint64_t size_capacity_; uint32_t expire_days_; std::string log_path_; int64_t m_nCheckRunLogTime_; }; } #endif
[ "liuchunwei@bubi.cn" ]
liuchunwei@bubi.cn
4c72a7c9e108be9c91f13552141b8dacf2d54e50
f921d605ad9fbc65fb360ef00dd137e77e94b787
/Codeking_2021/harvard.cpp
933a83d85fad94bf7fedff973416ef4b8e2f5d5c
[]
no_license
maybehieu/C_Training
79702e096bd706ec06fc7965b7b63249d140c41b
e1fa87e0bc0a6569ab7ebc847ffbf4324f2fe922
refs/heads/master
2023-07-22T20:06:36.552137
2021-09-04T15:29:17
2021-09-04T15:29:17
403,091,644
0
0
null
null
null
null
UTF-8
C++
false
false
751
cpp
#include <bits/stdc++.h> using namespace std; int main() { int test; cin >> test; while (test--) { int n, arr[1005] = {}, du1 = 0, du2 = 0, dem = 0; cin >> n; for (int i = 0; i < n; i++) { cin >> arr[i]; if (arr[i] % 3 == 0 && arr[i] != 0) { dem++; } else if (arr[i] % 3 == 1) { du1++; } else if (arr[i] % 3 == 2) { du2++; } } while (du1 > 0 && du2 > 0) { dem++; du1--, du2--; } dem += du1 / 3; dem += du2 / 3; cout << dem << endl; } return 0; }
[ "71547583+maybehieu@users.noreply.github.com" ]
71547583+maybehieu@users.noreply.github.com
2bd30990020cfe5394ca1e5c0a6761aafd743c50
2f98c60a171b8f6df0f411255589ee6f26737cfb
/multimedia/Animation/WindowsAnimationManagerWithTimer/WindowsAnimationManagerWithTimer/MainWindow.cpp
6a57da95db307b96c9bdeb9fc40c5eb339a51573
[]
no_license
bbesbes/WindowsSDK7-Samples
4df1d7f2c6fae7bd84411b4c13751a4085144af9
14e1c3daff5927791c9e17083ea455ba3de84444
refs/heads/master
2021-09-23T10:05:42.764049
2021-09-16T19:45:25
2021-09-16T19:45:25
118,103,268
0
0
null
2018-01-19T09:12:39
2018-01-19T09:12:39
null
UTF-8
C++
false
false
9,386
cpp
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved #include "MainWindow.h" #include "SimpleTimerEventHandler.h" /****************************************************************** * * * CMainWindow::Initialize * * * * Initialize Animation * * * ******************************************************************/ HRESULT CMainWindow::Initialize() { HRESULT hr = S_OK; // Create the Animation Manager, Transition Library, and Animation Timer IFR( m_spManager.CoCreateInstance( __uuidof(UIAnimationManager), NULL, CLSCTX_INPROC_SERVER ) ); IFR( m_spTransitionLibrary.CoCreateInstance( __uuidof(UIAnimationTransitionLibrary), NULL, CLSCTX_INPROC_SERVER ) ); IFR( m_spTimer.CoCreateInstance( __uuidof(UIAnimationTimer), NULL, CLSCTX_INPROC_SERVER ) ); // Connect the animation manager to the timer // UI_ANIMATION_IDLE_BEHAVIOR_DISABLE tells the timer to shut itself off wh,en there is nothing to animate CComQIPtr<IUIAnimationTimerUpdateHandler> spTimerUpdateHandler(m_spManager); _ASSERT(spTimerUpdateHandler != NULL); IFR( m_spTimer->SetTimerUpdateHandler( spTimerUpdateHandler, UI_ANIMATION_IDLE_BEHAVIOR_DISABLE ) ); // Create a timer event handler CComObject<CSimpleTimerEventHandler> *pSimpleTimerEventHandler; IFR( CComObject<CSimpleTimerEventHandler>::CreateInstance( &pSimpleTimerEventHandler ) ); pSimpleTimerEventHandler->Initialize( this ); CComQIPtr<IUIAnimationTimerEventHandler> spTimerEventHandler(pSimpleTimerEventHandler); _ASSERT(spTimerEventHandler); // Set the timer event handler IFR( m_spTimer->SetTimerEventHandler( spTimerEventHandler ) ); // Create animation RGB variables IFR( m_spManager->CreateAnimationVariable( 255, &m_spVariableRed ) ); IFR( m_spManager->CreateAnimationVariable( 255, &m_spVariableGreen ) ); IFR( m_spManager->CreateAnimationVariable( 255, &m_spVariableBlue ) ); // Initial background color change IFR( ChangeColor( RandomFromRange(0, 255), RandomFromRange(0, 255), RandomFromRange(0, 255) ) ); return hr; } /****************************************************************** * * * CMainWindow::OnEraseBkgnd * * * * Clears the background of the application window. * * * ******************************************************************/ LRESULT CMainWindow::OnEraseBkgnd( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL &fHandled ) { fHandled = TRUE; return TRUE; } /****************************************************************** * * * CMainWindow::OnPaint * * * * Handles incoming WM_PAINT and WM_DISPLAYCHANGE messages * * * ******************************************************************/ LRESULT CMainWindow::OnPaint( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL &fHandled ) { PAINTSTRUCT ps; BeginPaint( &ps ); // Get the animation variable values INT32 red; m_spVariableRed->GetIntegerValue( &red ); INT32 green; m_spVariableGreen->GetIntegerValue( &green ); INT32 blue; m_spVariableBlue->GetIntegerValue( &blue ); // Create brush to paint the background color HBRUSH hBrush = CreateSolidBrush( RGB( red, green, blue) ); HDC hDC = GetDC(); RECT rect; GetClientRect( &rect ); FillRect( hDC, &rect, hBrush ); DeleteObject( hBrush ); ReleaseDC(hDC); EndPaint( &ps ); return FALSE; } /****************************************************************** * * * CMainWindow::OnLButtonDown * * * * Handles incoming WM_LBUTTONDOWN messages and changes the * * background color of the window to a random color * * * ******************************************************************/ LRESULT CMainWindow::OnLButtonDown( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL &fHandled ) { HRESULT hr = S_OK; IFR( ChangeColor( RandomFromRange(0, 255), RandomFromRange(0, 255), RandomFromRange(0, 255) ) ); Invalidate( FALSE ); return FALSE; } /****************************************************************** * * * CMainWindow::OnDestroy * * * * Handles incoming WM_DESTORY messages and destroys the window * * * ******************************************************************/ LRESULT CMainWindow::OnDestroy( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL &fHandled ) { PostQuitMessage( FALSE ); return FALSE; } /****************************************************************** * * * CMainWindow::ChangeColor * * * * Randomly animates an RGB value of the window background * * * ******************************************************************/ HRESULT CMainWindow::ChangeColor( DOUBLE red, DOUBLE green, DOUBLE blue ) { HRESULT hr = S_OK; const DOUBLE DURATION = 2.0; const DOUBLE ACCELERATION_RATIO = 0.2; const DOUBLE DECELERATION_RATIO = 0.8; // Create a new storyboard CComPtr<IUIAnimationStoryboard> spStoryboard; IFR( m_spManager->CreateStoryboard(&spStoryboard) ); // Create an accelerate/decelerate transition over the red CComPtr<IUIAnimationTransition> spTransitionRed; IFR( m_spTransitionLibrary->CreateAccelerateDecelerateTransition( DURATION, red, ACCELERATION_RATIO, DECELERATION_RATIO, &spTransitionRed ) ); // Create an accelerate/decelerate transition over the green CComPtr<IUIAnimationTransition> spTransitionGreen; IFR( m_spTransitionLibrary->CreateAccelerateDecelerateTransition( DURATION, green, ACCELERATION_RATIO, DECELERATION_RATIO, &spTransitionGreen ) ); // Create an accelerate/decelerate transition over the blue CComPtr<IUIAnimationTransition> spTransitionBlue; IFR( m_spTransitionLibrary->CreateAccelerateDecelerateTransition( DURATION, blue, ACCELERATION_RATIO, DECELERATION_RATIO, &spTransitionBlue ) ); // Add RGB transitions IFR( spStoryboard->AddTransition( m_spVariableRed, spTransitionRed ) ); IFR( spStoryboard->AddTransition( m_spVariableGreen, spTransitionGreen ) ); IFR( spStoryboard->AddTransition( m_spVariableBlue, spTransitionBlue ) ); // Schedule the storyboard to animate UI_ANIMATION_SECONDS timeNow; IFR( m_spTimer->GetTime( &timeNow ) ); IFR( spStoryboard->Schedule( timeNow ) ); return hr; } /****************************************************************** * * * CMainWindow::RandomFromRange * * * * Generates a random number between minimum and maximum value * * * ******************************************************************/ DOUBLE CMainWindow::RandomFromRange( INT32 minimum, INT32 maximum ) { return minimum + (maximum - minimum) * (DOUBLE)rand() / RAND_MAX; }
[ "theonlylawislove@gmail.com" ]
theonlylawislove@gmail.com
7512ce0d77de1fe885dbe39ff3f31a5296c74601
5479a6ed839b5d08536301a828761bcf0ab1ffc7
/include/chef_base/chef_filepath_op.hpp
b6949c5d84978ab456f12c8ddc37bfafeddd2906
[ "MIT" ]
permissive
dede8385/starry-night
f8b219b7e21120c3fd9b7154ffdf32f8e28e8ed8
2324cb7228e9b05658b2c02cd1b5337418ccf00b
refs/heads/master
2020-04-12T16:29:48.337447
2018-12-19T09:09:06
2018-12-19T09:09:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,352
hpp
/** * @tag v1.7.16 * @file chef_filepath_op.hpp * @deps nope * @platform linux | macos | xxx * * @author * chef <191201771@qq.com> * - initial release xxxx-xx-xx * * @brief 文件、文件夹常用操作帮助函数集合 * */ #ifndef _CHEF_BASE_FILEPATH_OP_HPP_ #define _CHEF_BASE_FILEPATH_OP_HPP_ #pragma once #include <string> #include <vector> #include <stdint.h> namespace chef { class filepath_op { public: /** * @return * 0 存在,文件或文件夹都可 * -1 不存在 * */ static int exist(const std::string &name); /** * @return * 0 存在,且为文件夹 * -1 不存在,或不是文件夹 * */ static int is_dir(const std::string &pathname); /** * @param pathname 需要查询的文件夹 * @param child_dirs 传出参数,文件夹下的文件夹 * @param child_files 传出参数,文件夹下的文件 * @param with_pathname_prefix 传出的文件、文件夹前是否加上`pathname`前缀 * * @return 0 成功 -1 失败 `pathname`不可遍历 * * @NOTICE 只访问第一层目录,不会递归访问子目录下的内容 * */ static int walk_dir(const std::string &pathname, std::vector<std::string> &child_dirs /*out*/, std::vector<std::string> &child_files /*out*/, bool with_pathname_prefix=true); /** * @return * 0 创建成功,或创建前已经存在 * -1 失败 * */ static int mkdir_recursive(const std::string &pathname); /** * @param name 文件名 * * @return * 0 删除成功,或删除前就不存在 * -1 删除失败,或`name`是文件夹 * */ static int rm_file(const std::string &name); /** * @param pathname 文件夹名 * * @return * 0 删除成功,或删除前就不存在 * -1 删除失败,或`pathname`不是文件夹 * */ static int rmdir_recursive(const std::string &pathname); /** * @param src 源文件 * @param dst 目标文件 * * @return 0 成功 -1 失败 * */ static int rename(const std::string &src, const std::string &dst); /** * 写文件 * * @param append 当文件已经存在时,true则追加至末尾,false则覆盖原文件内容 * @return 0 成功 -1 失败 * */ static int write_file(const std::string &filename, const std::string &content, bool append=false); /** * 写文件 * * @param append 当文件已经存在时,true则追加至末尾,false则覆盖原文件内容 * @return 0 成功 -1 失败 * */ static int write_file(const std::string &filename, const char *content, size_t content_size, bool append=false); /** * @NOTICE * For most files under the /proc directory, stat() does not return the file * size in the st_size field; instead the field is returned with the value 0. * * @return 文件大小,失败则返回-1 * */ static int64_t get_file_size(const std::string &filename); /** * 读文件,对get_file_size()+read_file()的封装,更易于使用 * * @return 成功返回文件内容,失败返回std::string() * */ static std::string read_file(const std::string &filename); /** * 由于/proc下面的文件无法通过::stat()获取文件长度,所以提供参数让调用者填入一个fixed长度 * */ static std::string read_file(const std::string &filename, size_t content_size); /** * @param filename 文件名 * @param content 传出参数,读取到的文件内容,内存由外部申请 * @param content_size 最大读入大小 * * @return 成功返回实际读入大小,失败返回-1 * */ static int64_t read_file(const std::string &filename, char *content /*out*/, size_t content_size); /// @TODO 能否统一成一个接口,内部判断是否是否为link static std::string read_link(const std::string &filename, size_t content_size); /** * @param path 目录 * @param filename 文件名 * * 连接目录和文件名,解决`path`后面'/'和`filename`前面'/'是否存在,重复的问题 * */ static std::string join(const std::string &path, const std::string &filename); private: filepath_op(); filepath_op(const filepath_op &); filepath_op &operator=(const filepath_op &); }; // class filepath_op } // namespace chef /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // @NOTICE 该分隔线以上部分为该模块的接口,分割线以下部分为对应的实现 #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <errno.h> namespace chef { #define IF_ZERO_RETURN_NAGETIVE_ONE(x) do { if ((x) == 0) return -1; } while(0); #define IF_NULL_RETURN_NAGETIVE_ONE(x) do { if ((x) == NULL) return -1; } while(0); #define IF_STRING_EMPTY_RETURN_NAGETIVE_ONE(x) do { if (x.empty()) return -1; } while(0); inline int filepath_op::exist(const std::string &name) { IF_STRING_EMPTY_RETURN_NAGETIVE_ONE(name); struct stat st; return stat(name.c_str(), &st); } inline int filepath_op::is_dir(const std::string &pathname) { IF_STRING_EMPTY_RETURN_NAGETIVE_ONE(pathname); struct stat st; if (stat(pathname.c_str(), &st) == -1) { return -1; } return S_ISDIR(st.st_mode) ? 0 : -1; } inline int filepath_op::walk_dir(const std::string &pathname, std::vector<std::string> &child_dirs, std::vector<std::string> &child_files, bool with_pathname_prefix) { if (is_dir(pathname) == -1) { return -1; } child_dirs.clear(); child_files.clear(); DIR *open_ret = ::opendir(pathname.c_str()); IF_NULL_RETURN_NAGETIVE_ONE(open_ret); struct dirent entry; struct dirent *result = NULL; for (;;) { if (::readdir_r(open_ret, &entry, &result) != 0) { break; } if (result == NULL) { break; } char *name = result->d_name; if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0 ) { continue; } std::string file_with_path = filepath_op::join(pathname, name); if (filepath_op::exist(file_with_path.c_str()) != 0) { fprintf(stderr, "%s:%d %s\n", __FUNCTION__, __LINE__, file_with_path.c_str()); continue; } if (filepath_op::is_dir(file_with_path.c_str()) == 0) { child_dirs.push_back(with_pathname_prefix ? file_with_path : name); } else { child_files.push_back(with_pathname_prefix ? file_with_path : name); } } if (open_ret) { ::closedir(open_ret); } return 0; } inline int filepath_op::mkdir_recursive(const std::string &pathname) { IF_STRING_EMPTY_RETURN_NAGETIVE_ONE(pathname); char *path_dup = strdup(pathname.c_str()); size_t len = strlen(path_dup); if (len == 0) { return -1; } size_t i = path_dup[0] == '/' ? 1 : 0; for (; i <= len; ++i) { if (path_dup[i] == '/' || path_dup[i] == '\0') { char ch = path_dup[i]; path_dup[i] = '\0'; if (::mkdir(path_dup, 0755) == -1 && errno != EEXIST) { free(path_dup); return -1; } path_dup[i] = ch; } } free(path_dup); return 0; } inline int filepath_op::rm_file(const std::string &name) { IF_STRING_EMPTY_RETURN_NAGETIVE_ONE(name); if (exist(name) == -1) { return 0; } if (is_dir(name) == 0) { return -1; } if (::unlink(name.c_str()) == -1) { return -1; } return 0; } inline int filepath_op::rmdir_recursive(const std::string &pathname) { IF_STRING_EMPTY_RETURN_NAGETIVE_ONE(pathname); if (exist(pathname) == -1) { return 0; } if (is_dir(pathname) == -1) { return -1; } DIR *open_ret = ::opendir(pathname.c_str()); IF_NULL_RETURN_NAGETIVE_ONE(open_ret); struct dirent entry; struct dirent *result = NULL; int ret = 0; for (;;) { if (::readdir_r(open_ret, &entry, &result) != 0) { break; } if (result == NULL) { break; } char *name = result->d_name; if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0 ) { continue; } std::string file_with_path = filepath_op::join(pathname, name); if (filepath_op::exist(file_with_path.c_str()) != 0) { fprintf(stderr, "%s:%d %s\n", __FUNCTION__, __LINE__, file_with_path.c_str()); continue; } if (filepath_op::is_dir(file_with_path.c_str()) == 0) { if (filepath_op::rmdir_recursive(file_with_path.c_str()) != 0) { ret = -1; } } else { if (filepath_op::rm_file(file_with_path.c_str()) != 0) { ret = -1; } } } if (open_ret) { ::closedir(open_ret); } return (::rmdir(pathname.c_str()) == 0 && ret == 0) ? 0 : -1; } inline int filepath_op::rename(const std::string &src, const std::string &dst) { IF_STRING_EMPTY_RETURN_NAGETIVE_ONE(src); IF_STRING_EMPTY_RETURN_NAGETIVE_ONE(dst); return ::rename(src.c_str(), dst.c_str()); } inline int filepath_op::write_file(const std::string &filename, const char *content, size_t content_size, bool append) { IF_STRING_EMPTY_RETURN_NAGETIVE_ONE(filename); IF_NULL_RETURN_NAGETIVE_ONE(content); IF_ZERO_RETURN_NAGETIVE_ONE(content_size); FILE *fp = fopen(filename.c_str(), append ? "ab" : "wb"); IF_NULL_RETURN_NAGETIVE_ONE(fp); size_t written = fwrite(reinterpret_cast<const void *>(content), 1, content_size, fp); fclose(fp); return (written == content_size) ? 0 : -1; } inline int filepath_op::write_file(const std::string &filename, const std::string &content, bool append) { return filepath_op::write_file(filename, content.c_str(), content.length(), append); } inline int64_t filepath_op::get_file_size(const std::string &filename) { IF_STRING_EMPTY_RETURN_NAGETIVE_ONE(filename); if (exist(filename) == -1 || is_dir(filename) == 0) { return -1; } struct stat st; if (::stat(filename.c_str(), &st) == -1) { return -1; } return st.st_size; } inline int64_t filepath_op::read_file(const std::string &filename, char *content, size_t content_size) { IF_STRING_EMPTY_RETURN_NAGETIVE_ONE(filename); IF_NULL_RETURN_NAGETIVE_ONE(content); IF_ZERO_RETURN_NAGETIVE_ONE(content_size); FILE *fp = fopen(filename.c_str(), "rb"); IF_NULL_RETURN_NAGETIVE_ONE(fp); size_t read_size = fread(reinterpret_cast<void *>(content), 1, content_size, fp); fclose(fp); return read_size; } inline std::string filepath_op::read_file(const std::string &filename) { int64_t size = get_file_size(filename); if (size <= 0) { return std::string(); } return read_file(filename, size); } inline std::string filepath_op::read_file(const std::string &filename, size_t content_size) { if (content_size == 0) { return std::string(); } char *content = new char[content_size]; int64_t read_size = read_file(filename.c_str(), content, content_size); if (read_size == -1) { delete []content; return std::string(); } std::string content_string(content, read_size); delete []content; return content_string; } inline std::string filepath_op::read_link(const std::string &filename, size_t content_size) { if (filename.empty() || content_size == 0) { return std::string(); } char *content = new char[content_size]; ssize_t length = ::readlink(filename.c_str(), content, content_size); if (length == -1) { delete []content; return std::string(); } std::string ret(content, length); delete []content; return ret; } inline std::string filepath_op::join(const std::string &path, const std::string &filename) { std::string ret; size_t path_length = path.length(); size_t filename_length = filename.length(); if (path_length == 0) { return filename; } if (filename_length == 0) { return path; } if (path[path_length - 1] == '/') { ret = path.substr(0, path_length - 1); } else { ret = path; } ret += "/"; if (filename[0] == '/') { ret += filename.substr(1, filename_length - 1); } else { ret += filename; } return ret; } #undef IF_ZERO_RETURN_NAGETIVE_ONE #undef IF_NULL_RETURN_NAGETIVE_ONE #undef IF_STRING_EMPTY_RETURN_NAGETIVE_ONE } // namespace chef #endif // _CHEF_BASE_FILEPATH_OP_HPP_
[ "191201771@qq.com" ]
191201771@qq.com
7c1609e8edb4f54db643fc3204cafa64a9b1a896
edc5c44ab9249bc9c518c9875bdd1b39e52c0118
/4/2.cc
72a5a60124fa85321e65c597e67c74596ff33195
[]
no_license
AlbandeCrevoisier/CtCI
cff4091e5d094cf02ee2f923ead30b1796ab0c25
946e14def6e3ee702094b380a48134ef62689b0c
refs/heads/master
2020-03-23T18:17:03.284301
2018-12-04T15:44:44
2018-12-04T15:44:44
141,899,053
0
0
null
null
null
null
UTF-8
C++
false
false
939
cc
/* Minimal Tree Given a sorted array with unique integers elements, write an algorithm to create a binary search tree with minimal height. */ #include <iostream> #include <vector> namespace { struct Node { int val; Node *left; Node *right; }; int MinimalTree(std::vector<Node> &nodes, int start, int end) { if (start == end) { return start; } else if (end - start == 1) { nodes[end].left = &nodes[start]; return end; } int mid = start + ((end-start+1) % 2 == 0) ? (end-start+1)/2 : (end-start)/2; int left = MinimalTree(nodes, start, mid-1); int right = MinimalTree(nodes, mid+1, end); nodes[mid].left = &nodes[left]; nodes[mid].right = &nodes[right]; return mid; } } // namespace int main(void) { std::vector<int> numbers = {1, 2, 3, 5, 7, 9}; std::vector<Node> nodes; for (auto i : numbers) nodes.push_back({i, nullptr, nullptr}); int root = MinimalTree(nodes, 0, 5); return 0; }
[ "albandecrevoisier@gmail.com" ]
albandecrevoisier@gmail.com
4769634acfed98a860a6a87215843de2ca6546da
8a9649e72f2a9b2b5e54643614189cd5401da2e1
/src/plugins/yanlr/yanlr.cpp
0d1afba591b7906e8ceb0c1e1124476efb36938f
[ "BSD-3-Clause" ]
permissive
rkamisetti792/libelektra
720adc1f267e0738b16b12c716d98d4d51f46810
9228d8f5af8dd878a63053213b1466fb9551f694
refs/heads/master
2023-07-19T20:27:06.184265
2019-02-08T09:18:15
2019-02-08T09:18:15
169,867,354
0
0
BSD-3-Clause
2023-09-01T23:38:34
2019-02-09T13:00:23
C
UTF-8
C++
false
false
3,924
cpp
/** * @file * * @brief Source for yanlr plugin * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) * */ // -- Imports ------------------------------------------------------------------------------------------------------------------------------ #include <iostream> #include <kdb.hpp> #include <kdberrors.h> #include <antlr4-runtime.h> #include "YAML.h" #include "error_listener.hpp" #include "listener.hpp" #include "yaml_lexer.hpp" #include "yanlr.hpp" using CppKey = kdb::Key; using CppKeySet = kdb::KeySet; using antlr::YAML; using antlr4::ANTLRInputStream; using antlr4::CommonTokenStream; using ParseTree = antlr4::tree::ParseTree; using ParseTreeWalker = antlr4::tree::ParseTreeWalker; using std::ifstream; // -- Functions ---------------------------------------------------------------------------------------------------------------------------- namespace { /** * @brief This function returns a key set containing the contract of this plugin. * * @return A contract describing the functionality of this plugin. */ CppKeySet getContract () { return CppKeySet{ 30, keyNew ("system/elektra/modules/yanlr", KEY_VALUE, "yanlr plugin waits for your orders", KEY_END), keyNew ("system/elektra/modules/yanlr/exports", KEY_END), keyNew ("system/elektra/modules/yanlr/exports/get", KEY_FUNC, elektraYanlrGet, KEY_END), #include ELEKTRA_README (yanlr) keyNew ("system/elektra/modules/yanlr/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END }; } /** * @brief This function parses the content of a YAML file and saves the result in the given key set. * * @param file This file contains the YAML content this function should parse. * @param keys The function adds the key set representing `file` in this key set, if the parsing process finished successfully. * @param parent The function uses this parameter to emit error information. * * @retval ELEKTRA_PLUGIN_STATUS_NO_UPDATE If parsing was successful and `keys` was not updated * @retval ELEKTRA_PLUGIN_STATUS_SUCCESS If parsing was successful and `keys` was updated * @retval ELEKTRA_PLUGIN_STATUS_ERROR If there was an error parsing `file` */ int parseYAML (ifstream & file, CppKeySet & keys, CppKey & parent) { ANTLRInputStream input{ file }; YAMLLexer lexer{ &input }; CommonTokenStream tokens{ &lexer }; YAML parser{ &tokens }; ParseTreeWalker walker{}; KeyListener listener{ parent }; ErrorListener errorListener{}; parser.removeErrorListeners (); parser.addErrorListener (&errorListener); ParseTree * tree = parser.yaml (); if (parser.getNumberOfSyntaxErrors () > 0) { ELEKTRA_SET_ERROR (ELEKTRA_ERROR_PARSE, parent.getKey (), errorListener.message ()); return ELEKTRA_PLUGIN_STATUS_ERROR; } walker.walk (&listener, tree); auto readKeys = listener.keySet (); keys.append (readKeys); return readKeys.size () <= 0 ? ELEKTRA_PLUGIN_STATUS_NO_UPDATE : ELEKTRA_PLUGIN_STATUS_SUCCESS; } } // end namespace extern "C" { // ==================== // = Plugin Interface = // ==================== /** @see elektraDocGet */ int elektraYanlrGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey) { CppKey parent{ parentKey }; CppKeySet keys{ returned }; if (parent.getName () == "system/elektra/modules/yanlr") { keys.append (getContract ()); keys.release (); parent.release (); return ELEKTRA_PLUGIN_STATUS_SUCCESS; } ifstream file (parent.getString ()); if (!file.is_open ()) { ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_COULD_NOT_OPEN, parent.getKey (), "Unable to open file “%s”", parent.getString ().c_str ()); return ELEKTRA_PLUGIN_STATUS_ERROR; } int status = parseYAML (file, keys, parent); keys.release (); parent.release (); return status; } Plugin * ELEKTRA_PLUGIN_EXPORT (yanlr) { return elektraPluginExport ("yanlr", ELEKTRA_PLUGIN_GET, &elektraYanlrGet, ELEKTRA_PLUGIN_END); } } // end extern "C"
[ "sanssecours@me.com" ]
sanssecours@me.com
cb684e5d7ff67ff95e1abaa449f82fad40c21b35
1aa9a9498148edefc0a41ea67f9e913d2bf35ee0
/code/baxter_code_old/devel/include/baxter_core_msgs/ListCamerasResponse.h
6df0d5caedd5fef70d336b6a67c539cd92d80fda
[]
no_license
hril230/theoryofintentions
affeee9fce88474dacc928679307f0349edd8ee5
ab2315522141fe069fefeda00aa6424a0e7ecaf1
refs/heads/master
2021-06-22T05:34:16.899960
2019-07-01T11:15:12
2019-07-01T11:15:12
109,830,791
0
2
null
null
null
null
UTF-8
C++
false
false
5,972
h
// Generated by gencpp from file baxter_core_msgs/ListCamerasResponse.msg // DO NOT EDIT! #ifndef BAXTER_CORE_MSGS_MESSAGE_LISTCAMERASRESPONSE_H #define BAXTER_CORE_MSGS_MESSAGE_LISTCAMERASRESPONSE_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace baxter_core_msgs { template <class ContainerAllocator> struct ListCamerasResponse_ { typedef ListCamerasResponse_<ContainerAllocator> Type; ListCamerasResponse_() : cameras() { } ListCamerasResponse_(const ContainerAllocator& _alloc) : cameras(_alloc) { (void)_alloc; } typedef std::vector<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > , typename ContainerAllocator::template rebind<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::other > _cameras_type; _cameras_type cameras; typedef boost::shared_ptr< ::baxter_core_msgs::ListCamerasResponse_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::baxter_core_msgs::ListCamerasResponse_<ContainerAllocator> const> ConstPtr; }; // struct ListCamerasResponse_ typedef ::baxter_core_msgs::ListCamerasResponse_<std::allocator<void> > ListCamerasResponse; typedef boost::shared_ptr< ::baxter_core_msgs::ListCamerasResponse > ListCamerasResponsePtr; typedef boost::shared_ptr< ::baxter_core_msgs::ListCamerasResponse const> ListCamerasResponseConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::baxter_core_msgs::ListCamerasResponse_<ContainerAllocator> & v) { ros::message_operations::Printer< ::baxter_core_msgs::ListCamerasResponse_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace baxter_core_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False} // {'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg'], 'sensor_msgs': ['/opt/ros/indigo/share/sensor_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/indigo/share/geometry_msgs/cmake/../msg'], 'baxter_core_msgs': ['/home/heather/ros_ws/src/baxter_common/baxter_core_msgs/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::baxter_core_msgs::ListCamerasResponse_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::baxter_core_msgs::ListCamerasResponse_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::baxter_core_msgs::ListCamerasResponse_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::baxter_core_msgs::ListCamerasResponse_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::baxter_core_msgs::ListCamerasResponse_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::baxter_core_msgs::ListCamerasResponse_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::baxter_core_msgs::ListCamerasResponse_<ContainerAllocator> > { static const char* value() { return "855b31192ab61744e7deb992d94db7ff"; } static const char* value(const ::baxter_core_msgs::ListCamerasResponse_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x855b31192ab61744ULL; static const uint64_t static_value2 = 0xe7deb992d94db7ffULL; }; template<class ContainerAllocator> struct DataType< ::baxter_core_msgs::ListCamerasResponse_<ContainerAllocator> > { static const char* value() { return "baxter_core_msgs/ListCamerasResponse"; } static const char* value(const ::baxter_core_msgs::ListCamerasResponse_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::baxter_core_msgs::ListCamerasResponse_<ContainerAllocator> > { static const char* value() { return "string[] cameras\n\ \n\ "; } static const char* value(const ::baxter_core_msgs::ListCamerasResponse_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::baxter_core_msgs::ListCamerasResponse_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.cameras); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct ListCamerasResponse_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::baxter_core_msgs::ListCamerasResponse_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::baxter_core_msgs::ListCamerasResponse_<ContainerAllocator>& v) { s << indent << "cameras[]" << std::endl; for (size_t i = 0; i < v.cameras.size(); ++i) { s << indent << " cameras[" << i << "]: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.cameras[i]); } } }; } // namespace message_operations } // namespace ros #endif // BAXTER_CORE_MSGS_MESSAGE_LISTCAMERASRESPONSE_H
[ "hril230@aucklanduni.ac.nz" ]
hril230@aucklanduni.ac.nz
8e843927d3953e32e84ffd04da58a8804a68a7a4
75a5bf2dd70dd59fc6e03d14663de7d7bc4da3d8
/include/cli/StateManager.h
36cf7d97ec0c246aae773abd642df99b76f51d0f
[]
no_license
EgorKekor/SAMOSBOR_2
a7f4f17ebe26b91a35f3e3e8bd77265b5ad6d9fa
4696351008e493a524516b7310c89d2133c22312
refs/heads/master
2020-04-27T13:38:07.300313
2019-05-20T17:54:03
2019-05-20T17:54:03
174,376,892
0
1
null
2019-05-20T16:11:24
2019-03-07T16:02:18
C++
UTF-8
C++
false
false
645
h
#ifndef SERVER_STATEMANAGER_H #define SERVER_STATEMANAGER_H #include <iostream> #include <vector> #include <memory> #include "State.h" #include "GameContext.h" class StateManager { using STATE_PTR = std::unique_ptr<State>; public: explicit StateManager(GameContext &context); void process_events(const sf::Event &event); void update(sf::Time deltaTime); void draw(); STATE_PTR &get_state(); void push_state(STATE_PTR &&new_state); void pop_state(); size_t get_states_size(); private: std::vector<STATE_PTR> StatesStack; std::vector<STATE_PTR> StatesBuf; GameContext &Context; }; #endif //SERVER_STATEMANAGER_H
[ "smirnovasiberia@gmail.com" ]
smirnovasiberia@gmail.com
da691d0fe59feeeab182054d2b4963d7f4b7969b
f6326925918e8a426abac4a05a848b60013e873b
/libsensors/TaosProximity.cpp
6b834a6e83349bce8ef535369e0a037af407a3d7
[ "Apache-2.0" ]
permissive
D3abL3/android_device_zte_skate
5b8fade6a2383fff5864bf1618fb26ec8c55dbc1
4adc2ca45532d2c5cb181a8fddc236725594c0c2
HEAD
2016-09-01T21:16:19.093273
2012-01-09T18:45:36
2012-01-09T18:45:36
3,181,471
1
1
null
null
null
null
UTF-8
C++
false
false
5,185
cpp
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <fcntl.h> #include <errno.h> #include <math.h> #include <poll.h> #include <unistd.h> #include <dirent.h> #include <sys/select.h> #include <stdio.h> #include <stdlib.h> #include "taos_common.h" #include <cutils/log.h> #include "TaosProximity.h" /*****************************************************************************/ TaosProximity::TaosProximity() : SensorBase(TAOS_DEVICE_NAME, "proximity"), mEnabled(0), mInputReader(4), mPendingMask(0), mInitialised(0) { mPendingEvents.version = sizeof(sensors_event_t); mPendingEvents.sensor = ID_P; mPendingEvents.type = SENSOR_TYPE_PROXIMITY; open_device(); if(!mInitialised) mInitialised = initialise(); if ((!ioctl(dev_fd, TAOS_IOCTL_PROX_ON))) { mEnabled = ioctl(dev_fd, TAOS_IOCTL_PROX_GET_ENABLED); setInitialState(); } if (!mEnabled) { close_device(); } } TaosProximity::~TaosProximity() { if (mEnabled) { enable(ID_P,0); } } int TaosProximity::initialise() { struct taos_cfg cfg; FILE * cFile; int array[20]; int i=0; int rv; char cNum[10] ; char cfg_data[100]; rv = ioctl(dev_fd, TAOS_IOCTL_CONFIG_GET, &cfg); if(rv) LOGE("Failed to read Taos defaults from kernel!!!"); cFile = fopen(PROX_FILE,"r"); if (cFile != NULL){ fgets(cfg_data, 100, cFile); fclose(cFile); if(sscanf(cfg_data,"%hu,%hu,%hhu,%hhu,%hhu,%hhu,%hhu,%hhu,%hhu\n", &cfg.prox_threshold_hi, &cfg.prox_threshold_lo, &cfg.prox_int_time, &cfg.prox_adc_time, &cfg.prox_wait_time, &cfg.prox_intr_filter, &cfg.prox_config, &cfg.prox_pulse_cnt, &cfg.prox_gain ) == 9){ rv = ioctl(dev_fd, TAOS_IOCTL_CONFIG_SET, &cfg); if(rv) LOGE("Set proximity data failed!!!"); else LOGD("Proximity calibration data successfully loaded from %s",PROX_FILE); } else { LOGD("Prximity calibration data is not valid. Using defaults."); } } else { LOGD("No proximity calibration data found. Using defaults."); } return 1; } int TaosProximity::setInitialState() { struct input_absinfo absinfo; if (!ioctl(data_fd, EVIOCGABS(EVENT_TYPE_PROXIMITY), &absinfo)) { mPendingEvents.distance = indexToValue(absinfo.value); } return 0; } int TaosProximity::enable(int32_t handle, int en) { if (handle != ID_P) return -EINVAL; int newState = en ? 1 : 0; int err = 0; if (uint32_t(newState) != mEnabled) { if (!mEnabled) { open_device(); } int cmd; if (newState) { cmd = TAOS_IOCTL_PROX_ON; LOGD_IF(DEBUG,"PROX ON"); } else { cmd = TAOS_IOCTL_PROX_OFF; LOGD_IF(DEBUG,"PROX OFF"); } err = ioctl(dev_fd, cmd); err = err<0 ? -errno : 0; LOGE_IF(err, "TAOS_IOCTL_XXX failed (%s)", strerror(-err)); if (!err) { if (en) { setInitialState(); mEnabled = 1; } else mEnabled = 0; } if (!mEnabled) { LOGD_IF(DEBUG,"closing device"); close_device(); } } return err; } bool TaosProximity::hasPendingEvents() const { return mPendingMask; } int TaosProximity::readEvents(sensors_event_t* data, int count) { if (count < 1) return -EINVAL; ssize_t n = mInputReader.fill(data_fd); if (n < 0) return n; int numEventReceived = 0; input_event const* event; while (count && mInputReader.readEvent(&event)) { int type = event->type; if (type == EV_ABS) { if (event->code == EVENT_TYPE_PROXIMITY) { LOGD_IF(DEBUG,"Prox value=%i",event->value); mPendingEvents.distance = indexToValue(event->value); } } else if (type == EV_SYN) { int64_t time = timevalToNano(event->time); if (mEnabled){ *data++ = mPendingEvents; mPendingEvents.timestamp=time; count--; numEventReceived++; } } else { LOGE("TaosSensor: unknown event (type=%d, code=%d)",type, event->code); } mInputReader.next(); } return numEventReceived; } float TaosProximity::indexToValue(size_t index) const { return index; }
[ "tilal6991@gmail.com" ]
tilal6991@gmail.com
73421acfe5d7098d6e3eb7a19dee82c7983d41d5
7bac60813fef44fbb60a196909540c07c90fc63d
/Arduino/Dice/Dice/Dice.ino
af8729c2c422dd938800dee9b282e289aae0f67b
[]
no_license
TomCarton/embedded
9bd83e1e9e5df3033d0a5827eb94d654d496b62c
84d82e9a72b3a4e8c2e6499c59dbd9e2b3784f33
refs/heads/master
2023-08-14T04:17:52.794084
2021-10-06T15:01:54
2021-10-06T15:01:54
412,399,084
0
0
null
2021-10-10T10:15:16
2021-10-01T09:06:20
C++
UTF-8
C++
false
false
1,985
ino
// Dice // int Led1 = 2; int Led2 = 3; int Led3 = 4; int Led4 = 5; int Led5 = 6; int Led6 = 7; int Led7 = 8; int ButtonPin = 9; int blinkingTime = 300; void setup() { pinMode(Led1, OUTPUT); pinMode(Led2, OUTPUT); pinMode(Led3, OUTPUT); pinMode(Led4, OUTPUT); pinMode(Led5, OUTPUT); pinMode(Led6, OUTPUT); pinMode(Led7, OUTPUT); pinMode(ButtonPin, INPUT); randomSeed(analogRead(0)); } // at the moment: (7 wires) // 4 6 - 1, 7 4, 1+2+4+6 // 3 7 5 - 2, 2+6 5, 1+2+4+6+7 // 2 1 - 3, 2+6+7 6, 1+2+3+4+5+6 // but could be: (4 wires) // 4 2 - 1, 1 4, 2+4 // 3 1 3 - 2, 2 5, 1+2+4 // 2 4 - 3, 1+2 6, 2+3+4 void displayNumber(int number) { digitalWrite(Led1, LOW); digitalWrite(Led2, LOW); digitalWrite(Led3, LOW); digitalWrite(Led4, LOW); digitalWrite(Led5, LOW); digitalWrite(Led6, LOW); digitalWrite(Led7, LOW); switch (number) { case 1: digitalWrite(Led7, HIGH); break; case 2: digitalWrite(Led2, HIGH); digitalWrite(Led6, HIGH); break; case 3: digitalWrite(Led2, HIGH); digitalWrite(Led6, HIGH); digitalWrite(Led7, HIGH); break; case 4: digitalWrite(Led1, HIGH); digitalWrite(Led2, HIGH); digitalWrite(Led4, HIGH); digitalWrite(Led6, HIGH); break; case 5: digitalWrite(Led1, HIGH); digitalWrite(Led2, HIGH); digitalWrite(Led4, HIGH); digitalWrite(Led6, HIGH); digitalWrite(Led7, HIGH); break; case 6: digitalWrite(Led1, HIGH); digitalWrite(Led2, HIGH); digitalWrite(Led3, HIGH); digitalWrite(Led4, HIGH); digitalWrite(Led5, HIGH); digitalWrite(Led6, HIGH); break; } } void loop() { if (digitalRead(ButtonPin) == HIGH) { int value; for (int i = 0; i < 10; ++i) { value = random(0, 6) + 1; displayNumber(value); delay(blinkingTime); } delay(5000); displayNumber(0); } }
[ "tom.carton@gmail.com" ]
tom.carton@gmail.com
ed5171a1fd1e5634c26eb1b01c9f50ce68aea8e0
6b64b310d8385961095c19bfe1b2a15e82700d19
/CvUnit.cpp
d17289f79e51ae882b6e2c564abe6d19fdb02065
[]
no_license
Vincentz1911/CvGameCoreDLL-2010
b539184b35571f1923a1e80b78da9b77cc7937e2
ff6f76fb7880da9d58c43d8e906af3f62633c5a8
refs/heads/master
2020-04-21T22:44:01.709081
2019-02-10T17:20:11
2019-02-10T17:20:11
169,922,700
0
0
null
null
null
null
UTF-8
C++
false
false
338,780
cpp
// unit.cpp #include "CvGameCoreDLL.h" #include "CvUnit.h" #include "CvArea.h" #include "CvPlot.h" #include "CvCity.h" #include "CvGlobals.h" #include "CvGameCoreUtils.h" #include "CvGameAI.h" #include "CvMap.h" #include "CvPlayerAI.h" #include "CvRandom.h" #include "CvTeamAI.h" #include "CvGameCoreUtils.h" #include "CyUnit.h" #include "CyArgsList.h" #include "CyPlot.h" #include "CvDLLEntityIFaceBase.h" #include "CvDLLInterfaceIFaceBase.h" #include "CvDLLEngineIFaceBase.h" #include "CvEventReporter.h" #include "CvDLLPythonIFaceBase.h" #include "CvDLLFAStarIFaceBase.h" #include "CvInfos.h" #include "FProfiler.h" #include "CvPopupInfo.h" #include "CvArtFileMgr.h" // Public Functions... CvUnit::CvUnit() { /**************************************** * Archid Mod: 10 Oct 2012 * Functionality: SeeInvisiblePromotion - Archid * * Source: * Archid * ****************************************/ m_paiSeeInvisible = NULL; /** ** End: SeeInvisiblePromotion **/ //Vincentz m_paiUnitClassCount = NULL; //Vincentz m_aiExtraDomainModifier = new int[NUM_DOMAIN_TYPES]; m_pabHasPromotion = NULL; m_paiTerrainDoubleMoveCount = NULL; m_paiFeatureDoubleMoveCount = NULL; m_paiExtraTerrainAttackPercent = NULL; m_paiExtraTerrainDefensePercent = NULL; m_paiExtraFeatureAttackPercent = NULL; m_paiExtraFeatureDefensePercent = NULL; m_paiExtraUnitCombatModifier = NULL; CvDLLEntity::createUnitEntity(this); // create and attach entity to unit reset(0, NO_UNIT, NO_PLAYER, true); } CvUnit::~CvUnit() { if (!gDLL->GetDone() && GC.IsGraphicsInitialized()) // don't need to remove entity when the app is shutting down, or crash can occur { gDLL->getEntityIFace()->RemoveUnitFromBattle(this); CvDLLEntity::removeEntity(); // remove entity from engine } CvDLLEntity::destroyEntity(); // delete CvUnitEntity and detach from us uninit(); SAFE_DELETE_ARRAY(m_aiExtraDomainModifier); } void CvUnit::reloadEntity() { //destroy old entity if (!gDLL->GetDone() && GC.IsGraphicsInitialized()) // don't need to remove entity when the app is shutting down, or crash can occur { gDLL->getEntityIFace()->RemoveUnitFromBattle(this); CvDLLEntity::removeEntity(); // remove entity from engine } CvDLLEntity::destroyEntity(); // delete CvUnitEntity and detach from us //creat new one CvDLLEntity::createUnitEntity(this); // create and attach entity to unit setupGraphical(); } void CvUnit::init(int iID, UnitTypes eUnit, UnitAITypes eUnitAI, PlayerTypes eOwner, int iX, int iY, DirectionTypes eFacingDirection) { CvWString szBuffer; int iUnitName; int iI, iJ; FAssert(NO_UNIT != eUnit); //-------------------------------- // Init saved data reset(iID, eUnit, eOwner); if(eFacingDirection == NO_DIRECTION) m_eFacingDirection = DIRECTION_SOUTH; else m_eFacingDirection = eFacingDirection; //-------------------------------- // Init containers //-------------------------------- // Init pre-setup() data /**************************************** * Archid Mod: 10 Oct 2012 * Functionality: SeeInvisiblePromotion - Archid * * Source: * Archid * ****************************************/ // This needs to be before the setXY call as that is the one that sets the units visibility // so we need to have configured the invisibles that it can see beforehand for (int i = 0; i < m_pUnitInfo->getNumSeeInvisibleTypes(); i++) { changeSeeInvisibleCount((InvisibleTypes)m_pUnitInfo->getSeeInvisibleType(i), 1); } /** ** End: SeeInvisiblePromotion **/ setXY(iX, iY, false, false); //-------------------------------- // Init non-saved data setupGraphical(); //-------------------------------- // Init other game data plot()->updateCenterUnit(); plot()->setFlagDirty(true); iUnitName = GC.getGameINLINE().getUnitCreatedCount(getUnitType()); int iNumNames = m_pUnitInfo->getNumUnitNames(); if (iUnitName < iNumNames) { int iOffset = GC.getGameINLINE().getSorenRandNum(iNumNames, "Unit name selection"); for (iI = 0; iI < iNumNames; iI++) { int iIndex = (iI + iOffset) % iNumNames; CvWString szName = gDLL->getText(m_pUnitInfo->getUnitNames(iIndex)); if (!GC.getGameINLINE().isGreatPersonBorn(szName)) { setName(szName); GC.getGameINLINE().addGreatPersonBornName(szName); break; } } } setGameTurnCreated(GC.getGameINLINE().getGameTurn()); GC.getGameINLINE().incrementUnitCreatedCount(getUnitType()); GC.getGameINLINE().incrementUnitClassCreatedCount((UnitClassTypes)(m_pUnitInfo->getUnitClassType())); GET_TEAM(getTeam()).changeUnitClassCount(((UnitClassTypes)(m_pUnitInfo->getUnitClassType())), 1); GET_PLAYER(getOwnerINLINE()).changeUnitClassCount(((UnitClassTypes)(m_pUnitInfo->getUnitClassType())), 1); GET_PLAYER(getOwnerINLINE()).changeExtraUnitCost(m_pUnitInfo->getExtraCost()); if (m_pUnitInfo->getNukeRange() != -1) { GET_PLAYER(getOwnerINLINE()).changeNumNukeUnits(1); } if (m_pUnitInfo->isMilitarySupport()) { GET_PLAYER(getOwnerINLINE()).changeNumMilitaryUnits(1); } GET_PLAYER(getOwnerINLINE()).changeAssets(m_pUnitInfo->getAssetValue()); GET_PLAYER(getOwnerINLINE()).changePower(m_pUnitInfo->getPowerValue()); for (iI = 0; iI < GC.getNumPromotionInfos(); iI++) { if (m_pUnitInfo->getFreePromotions(iI)) { setHasPromotion(((PromotionTypes)iI), true); } } FAssertMsg((GC.getNumTraitInfos() > 0), "GC.getNumTraitInfos() is less than or equal to zero but is expected to be larger than zero in CvUnit::init"); for (iI = 0; iI < GC.getNumTraitInfos(); iI++) { if (GET_PLAYER(getOwnerINLINE()).hasTrait((TraitTypes)iI)) { for (iJ = 0; iJ < GC.getNumPromotionInfos(); iJ++) { if (GC.getTraitInfo((TraitTypes) iI).isFreePromotion(iJ)) { if ((getUnitCombatType() != NO_UNITCOMBAT) && GC.getTraitInfo((TraitTypes) iI).isFreePromotionUnitCombat(getUnitCombatType())) { setHasPromotion(((PromotionTypes)iJ), true); } } } } } if (NO_UNITCOMBAT != getUnitCombatType()) { for (iJ = 0; iJ < GC.getNumPromotionInfos(); iJ++) { if (GET_PLAYER(getOwnerINLINE()).isFreePromotion(getUnitCombatType(), (PromotionTypes)iJ)) { setHasPromotion(((PromotionTypes)iJ), true); } } } if (NO_UNITCLASS != getUnitClassType()) { for (iJ = 0; iJ < GC.getNumPromotionInfos(); iJ++) { if (GET_PLAYER(getOwnerINLINE()).isFreePromotion(getUnitClassType(), (PromotionTypes)iJ)) { setHasPromotion(((PromotionTypes)iJ), true); } } } if (getDomainType() == DOMAIN_LAND) { if (baseCombatStr() > 0) { if ((GC.getGameINLINE().getBestLandUnit() == NO_UNIT) || (baseCombatStr() > GC.getGameINLINE().getBestLandUnitCombat())) { GC.getGameINLINE().setBestLandUnit(getUnitType()); } } } if (getOwnerINLINE() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); } if (isWorldUnitClass((UnitClassTypes)(m_pUnitInfo->getUnitClassType()))) { for (iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { if (GET_TEAM(getTeam()).isHasMet(GET_PLAYER((PlayerTypes)iI).getTeam())) { szBuffer = gDLL->getText("TXT_KEY_MISC_SOMEONE_CREATED_UNIT", GET_PLAYER(getOwnerINLINE()).getNameKey(), getNameKey()); gDLL->getInterfaceIFace()->addMessage(((PlayerTypes)iI), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_WONDER_UNIT_BUILD", MESSAGE_TYPE_MAJOR_EVENT, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_UNIT_TEXT"), getX_INLINE(), getY_INLINE(), true, true); } else { szBuffer = gDLL->getText("TXT_KEY_MISC_UNKNOWN_CREATED_UNIT", getNameKey()); gDLL->getInterfaceIFace()->addMessage(((PlayerTypes)iI), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_WONDER_UNIT_BUILD", MESSAGE_TYPE_MAJOR_EVENT, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_UNIT_TEXT")); } } } szBuffer = gDLL->getText("TXT_KEY_MISC_SOMEONE_CREATED_UNIT", GET_PLAYER(getOwnerINLINE()).getNameKey(), getNameKey()); GC.getGameINLINE().addReplayMessage(REPLAY_MESSAGE_MAJOR_EVENT, getOwnerINLINE(), szBuffer, getX_INLINE(), getY_INLINE(), (ColorTypes)GC.getInfoTypeForString("COLOR_UNIT_TEXT")); } AI_init(eUnitAI); CvEventReporter::getInstance().unitCreated(this); } void CvUnit::uninit() { /**************************************** * Archid Mod: 10 Oct 2012 * Functionality: SeeInvisiblePromotion - Archid * * Source: * Archid * ****************************************/ SAFE_DELETE_ARRAY(m_paiSeeInvisible); /** ** End: SeeInvisiblePromotion **/ SAFE_DELETE_ARRAY(m_pabHasPromotion); SAFE_DELETE_ARRAY(m_paiTerrainDoubleMoveCount); SAFE_DELETE_ARRAY(m_paiFeatureDoubleMoveCount); SAFE_DELETE_ARRAY(m_paiExtraTerrainAttackPercent); SAFE_DELETE_ARRAY(m_paiExtraTerrainDefensePercent); SAFE_DELETE_ARRAY(m_paiExtraFeatureAttackPercent); SAFE_DELETE_ARRAY(m_paiExtraFeatureDefensePercent); SAFE_DELETE_ARRAY(m_paiExtraUnitCombatModifier); } // FUNCTION: reset() // Initializes data members that are serialized. void CvUnit::reset(int iID, UnitTypes eUnit, PlayerTypes eOwner, bool bConstructorCall) { int iI; //-------------------------------- // Uninit class uninit(); /**************************************** * Archid Mod: 10 Oct 2012 * Functionality: SeeInvisiblePromotion - Archid * * Source: * Archid * ****************************************/ m_paiSeeInvisible = new int[GC.getNumInvisibleInfos()]; for (iI = 0; iI < GC.getNumInvisibleInfos(); iI++) { m_paiSeeInvisible[iI] = 0; } /** ** End: SeeInvisiblePromotion **/ m_iID = iID; m_iGroupID = FFreeList::INVALID_INDEX; m_iHotKeyNumber = -1; m_iX = INVALID_PLOT_COORD; m_iY = INVALID_PLOT_COORD; m_iLastMoveTurn = 0; m_iReconX = INVALID_PLOT_COORD; m_iReconY = INVALID_PLOT_COORD; m_iGameTurnCreated = 0; m_iDamage = 0; m_iMoves = 0; m_iExperience = 0; m_iLevel = 1; m_iCargo = 0; m_iAttackPlotX = INVALID_PLOT_COORD; m_iAttackPlotY = INVALID_PLOT_COORD; m_iCombatTimer = 0; m_iCombatFirstStrikes = 0; m_iFortifyTurns = 0; m_iBlitzCount = 0; m_iAmphibCount = 0; m_iRiverCount = 0; m_iEnemyRouteCount = 0; m_iAlwaysHealCount = 0; m_iHillsDoubleMoveCount = 0; m_iImmuneToFirstStrikesCount = 0; m_iExtraVisibilityRange = 0; m_iExtraMoves = 0; m_iExtraMoveDiscount = 0; m_iExtraAirRange = 0; m_iExtraIntercept = 0; m_iExtraEvasion = 0; m_iExtraFirstStrikes = 0; m_iExtraChanceFirstStrikes = 0; m_iExtraWithdrawal = 0; m_iExtraCollateralDamage = 0; m_iExtraBombardRate = 0; m_iExtraEnemyHeal = 0; m_iExtraNeutralHeal = 0; m_iExtraFriendlyHeal = 0; m_iSameTileHeal = 0; m_iAdjacentTileHeal = 0; m_iExtraCombatPercent = 0; m_iExtraCityAttackPercent = 0; m_iExtraCityDefensePercent = 0; m_iExtraHillsAttackPercent = 0; m_iExtraHillsDefensePercent = 0; m_iRevoltProtection = 0; m_iCollateralDamageProtection = 0; m_iPillageChange = 0; m_iUpgradeDiscount = 0; m_iExperiencePercent = 0; m_iKamikazePercent = 0; m_eFacingDirection = DIRECTION_SOUTH; m_iImmobileTimer = 0; m_bMadeAttack = false; m_bMadeInterception = false; m_bPromotionReady = false; m_bDeathDelay = false; m_bCombatFocus = false; m_bInfoBarDirty = false; m_bBlockading = false; m_bAirCombat = false; m_eOwner = eOwner; m_eCapturingPlayer = NO_PLAYER; m_eUnitType = eUnit; m_pUnitInfo = (NO_UNIT != m_eUnitType) ? &GC.getUnitInfo(m_eUnitType) : NULL; m_iBaseCombat = (NO_UNIT != m_eUnitType) ? m_pUnitInfo->getCombat() : 0; m_eLeaderUnitType = NO_UNIT; m_iCargoCapacity = (NO_UNIT != m_eUnitType) ? m_pUnitInfo->getCargoSpace() : 0; m_combatUnit.reset(); m_transportUnit.reset(); for (iI = 0; iI < NUM_DOMAIN_TYPES; iI++) { m_aiExtraDomainModifier[iI] = 0; } m_szName.clear(); m_szScriptData =""; if (!bConstructorCall) { FAssertMsg((0 < GC.getNumPromotionInfos()), "GC.getNumPromotionInfos() is not greater than zero but an array is being allocated in CvUnit::reset"); m_pabHasPromotion = new bool[GC.getNumPromotionInfos()]; for (iI = 0; iI < GC.getNumPromotionInfos(); iI++) { m_pabHasPromotion[iI] = false; } FAssertMsg((0 < GC.getNumTerrainInfos()), "GC.getNumTerrainInfos() is not greater than zero but a float array is being allocated in CvUnit::reset"); m_paiTerrainDoubleMoveCount = new int[GC.getNumTerrainInfos()]; m_paiExtraTerrainAttackPercent = new int[GC.getNumTerrainInfos()]; m_paiExtraTerrainDefensePercent = new int[GC.getNumTerrainInfos()]; for (iI = 0; iI < GC.getNumTerrainInfos(); iI++) { m_paiTerrainDoubleMoveCount[iI] = 0; m_paiExtraTerrainAttackPercent[iI] = 0; m_paiExtraTerrainDefensePercent[iI] = 0; } FAssertMsg((0 < GC.getNumFeatureInfos()), "GC.getNumFeatureInfos() is not greater than zero but a float array is being allocated in CvUnit::reset"); m_paiFeatureDoubleMoveCount = new int[GC.getNumFeatureInfos()]; m_paiExtraFeatureDefensePercent = new int[GC.getNumFeatureInfos()]; m_paiExtraFeatureAttackPercent = new int[GC.getNumFeatureInfos()]; for (iI = 0; iI < GC.getNumFeatureInfos(); iI++) { m_paiFeatureDoubleMoveCount[iI] = 0; m_paiExtraFeatureAttackPercent[iI] = 0; m_paiExtraFeatureDefensePercent[iI] = 0; } FAssertMsg((0 < GC.getNumUnitCombatInfos()), "GC.getNumUnitCombatInfos() is not greater than zero but an array is being allocated in CvUnit::reset"); m_paiExtraUnitCombatModifier = new int[GC.getNumUnitCombatInfos()]; for (iI = 0; iI < GC.getNumUnitCombatInfos(); iI++) { m_paiExtraUnitCombatModifier[iI] = 0; } AI_reset(); } } ////////////////////////////////////// // graphical only setup ////////////////////////////////////// void CvUnit::setupGraphical() { if (!GC.IsGraphicsInitialized()) { return; } CvDLLEntity::setup(); if (getGroup()->getActivityType() == ACTIVITY_INTERCEPT) { airCircle(true); } } void CvUnit::convert(CvUnit* pUnit) { CvPlot* pPlot = plot(); for (int iI = 0; iI < GC.getNumPromotionInfos(); iI++) { setHasPromotion(((PromotionTypes)iI), (pUnit->isHasPromotion((PromotionTypes)iI) || m_pUnitInfo->getFreePromotions(iI))); } setGameTurnCreated(pUnit->getGameTurnCreated()); setDamage(pUnit->getDamage()); setMoves(pUnit->getMoves()); setLevel(pUnit->getLevel()); int iOldModifier = std::max(1, 100 + GET_PLAYER(pUnit->getOwnerINLINE()).getLevelExperienceModifier()); int iOurModifier = std::max(1, 100 + GET_PLAYER(getOwnerINLINE()).getLevelExperienceModifier()); setExperience(std::max(0, (pUnit->getExperience() * iOurModifier) / iOldModifier)); setName(pUnit->getNameNoDesc()); setLeaderUnitType(pUnit->getLeaderUnitType()); CvUnit* pTransportUnit = pUnit->getTransportUnit(); if (pTransportUnit != NULL) { pUnit->setTransportUnit(NULL); setTransportUnit(pTransportUnit); } std::vector<CvUnit*> aCargoUnits; pUnit->getCargoUnits(aCargoUnits); for (uint i = 0; i < aCargoUnits.size(); ++i) { aCargoUnits[i]->setTransportUnit(this); } pUnit->kill(true); } void CvUnit::kill(bool bDelay, PlayerTypes ePlayer) { PROFILE_FUNC(); CLLNode<IDInfo>* pUnitNode; CvUnit* pTransportUnit; CvUnit* pLoopUnit; CvPlot* pPlot; CvWString szBuffer; PlayerTypes eOwner; PlayerTypes eCapturingPlayer; UnitTypes eCaptureUnitType; pPlot = plot(); FAssertMsg(pPlot != NULL, "Plot is not assigned a valid value"); static std::vector<IDInfo> oldUnits; oldUnits.clear(); pUnitNode = pPlot->headUnitNode(); while (pUnitNode != NULL) { oldUnits.push_back(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); } for (uint i = 0; i < oldUnits.size(); i++) { pLoopUnit = ::getUnit(oldUnits[i]); if (pLoopUnit != NULL) { if (pLoopUnit->getTransportUnit() == this) { //save old units because kill will clear the static list std::vector<IDInfo> tempUnits = oldUnits; if (pPlot->isValidDomainForLocation(*pLoopUnit)) { pLoopUnit->setCapturingPlayer(NO_PLAYER); } pLoopUnit->kill(false, ePlayer); oldUnits = tempUnits; } } } if (ePlayer != NO_PLAYER) { CvEventReporter::getInstance().unitKilled(this, ePlayer); if (NO_UNIT != getLeaderUnitType()) { for (int iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { szBuffer = gDLL->getText("TXT_KEY_MISC_GENERAL_KILLED", getNameKey()); gDLL->getInterfaceIFace()->addMessage(((PlayerTypes)iI), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, GC.getEraInfo(GC.getGameINLINE().getCurrentEra()).getAudioUnitDefeatScript(), MESSAGE_TYPE_MAJOR_EVENT); } } } } if (bDelay) { startDelayedDeath(); return; } if (isMadeAttack() && nukeRange() != -1) { CvPlot* pTarget = getAttackPlot(); if (pTarget) { pTarget->nukeExplosion(nukeRange(), this); setAttackPlot(NULL, false); } } finishMoves(); if (IsSelected()) { if (gDLL->getInterfaceIFace()->getLengthSelectionList() == 1) { if (!(gDLL->getInterfaceIFace()->isFocused()) && !(gDLL->getInterfaceIFace()->isCitySelection()) && !(gDLL->getInterfaceIFace()->isDiploOrPopupWaiting())) { GC.getGameINLINE().updateSelectionList(); } if (IsSelected()) { gDLL->getInterfaceIFace()->setCycleSelectionCounter(1); } else { gDLL->getInterfaceIFace()->setDirty(SelectionCamera_DIRTY_BIT, true); } } } gDLL->getInterfaceIFace()->removeFromSelectionList(this); // XXX this is NOT a hack, without it, the game crashes. gDLL->getEntityIFace()->RemoveUnitFromBattle(this); FAssertMsg(!isCombat(), "isCombat did not return false as expected"); pTransportUnit = getTransportUnit(); if (pTransportUnit != NULL) { setTransportUnit(NULL); } setReconPlot(NULL); setBlockading(false); FAssertMsg(getAttackPlot() == NULL, "The current unit instance's attack plot is expected to be NULL"); FAssertMsg(getCombatUnit() == NULL, "The current unit instance's combat unit is expected to be NULL"); GET_TEAM(getTeam()).changeUnitClassCount((UnitClassTypes)m_pUnitInfo->getUnitClassType(), -1); GET_PLAYER(getOwnerINLINE()).changeUnitClassCount((UnitClassTypes)m_pUnitInfo->getUnitClassType(), -1); GET_PLAYER(getOwnerINLINE()).changeExtraUnitCost(-(m_pUnitInfo->getExtraCost())); if (m_pUnitInfo->getNukeRange() != -1) { GET_PLAYER(getOwnerINLINE()).changeNumNukeUnits(-1); } if (m_pUnitInfo->isMilitarySupport()) { GET_PLAYER(getOwnerINLINE()).changeNumMilitaryUnits(-1); } GET_PLAYER(getOwnerINLINE()).changeAssets(-(m_pUnitInfo->getAssetValue())); GET_PLAYER(getOwnerINLINE()).changePower(-(m_pUnitInfo->getPowerValue())); GET_PLAYER(getOwnerINLINE()).AI_changeNumAIUnits(AI_getUnitAIType(), -1); eOwner = getOwnerINLINE(); eCapturingPlayer = getCapturingPlayer(); eCaptureUnitType = ((eCapturingPlayer != NO_PLAYER) ? getCaptureUnitType(GET_PLAYER(eCapturingPlayer).getCivilizationType()) : NO_UNIT); setXY(INVALID_PLOT_COORD, INVALID_PLOT_COORD, true); joinGroup(NULL, false, false); CvEventReporter::getInstance().unitLost(this); GET_PLAYER(getOwnerINLINE()).deleteUnit(getID()); if ((eCapturingPlayer != NO_PLAYER) && (eCaptureUnitType != NO_UNIT) && !(GET_PLAYER(eCapturingPlayer).isBarbarian())) { if (GET_PLAYER(eCapturingPlayer).isHuman() || GET_PLAYER(eCapturingPlayer).AI_captureUnit(eCaptureUnitType, pPlot) || 0 == GC.getDefineINT("AI_CAN_DISBAND_UNITS")) { CvUnit* pkCapturedUnit = GET_PLAYER(eCapturingPlayer).initUnit(eCaptureUnitType, pPlot->getX_INLINE(), pPlot->getY_INLINE()); if (pkCapturedUnit != NULL) { szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_CAPTURED_UNIT", GC.getUnitInfo(eCaptureUnitType).getTextKeyWide()); gDLL->getInterfaceIFace()->addMessage(eCapturingPlayer, true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_UNITCAPTURE", MESSAGE_TYPE_INFO, pkCapturedUnit->getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); // Add a captured mission CvMissionDefinition kMission; kMission.setMissionTime(GC.getMissionInfo(MISSION_CAPTURED).getTime() * gDLL->getSecsPerTurn()); kMission.setUnit(BATTLE_UNIT_ATTACKER, pkCapturedUnit); kMission.setUnit(BATTLE_UNIT_DEFENDER, NULL); kMission.setPlot(pPlot); kMission.setMissionType(MISSION_CAPTURED); gDLL->getEntityIFace()->AddMission(&kMission); pkCapturedUnit->finishMoves(); if (!GET_PLAYER(eCapturingPlayer).isHuman()) { CvPlot* pPlot = pkCapturedUnit->plot(); if (pPlot && !pPlot->isCity(false)) { if (GET_PLAYER(eCapturingPlayer).AI_getPlotDanger(pPlot) && GC.getDefineINT("AI_CAN_DISBAND_UNITS")) { pkCapturedUnit->kill(false); } } } } } } } void CvUnit::NotifyEntity(MissionTypes eMission) { gDLL->getEntityIFace()->NotifyEntity(getUnitEntity(), eMission); } void CvUnit::doTurn() { PROFILE("CvUnit::doTurn()") FAssertMsg(!isDead(), "isDead did not return false as expected"); FAssertMsg(getGroup() != NULL, "getGroup() is not expected to be equal with NULL"); testPromotionReady(); if (isBlockading()) { collectBlockadeGold(); } if (isSpy() && isIntruding() && !isCargo()) { TeamTypes eTeam = plot()->getTeam(); if (NO_TEAM != eTeam) { if (GET_TEAM(getTeam()).isOpenBorders(eTeam)) { //Vincentz Spy testSpyIntercepted(plot()->getOwnerINLINE(), (GC.getDefineINT("ESPIONAGE_SPY_NO_INTRUDE_INTERCEPT_MOD") - evasionProbability())); } else { testSpyIntercepted(plot()->getOwnerINLINE(), (GC.getDefineINT("ESPIONAGE_SPY_INTERCEPT_MOD") - evasionProbability())); //Vincentz Spy end } } } if (baseCombatStr() > 0) { FeatureTypes eFeature = plot()->getFeatureType(); if (NO_FEATURE != eFeature) { if (0 != GC.getFeatureInfo(eFeature).getTurnDamage()) { changeDamage(GC.getFeatureInfo(eFeature).getTurnDamage(), NO_PLAYER); } } } if (hasMoved()) { //Vincentz Heal if (isAlwaysHeal() && isHurt()) { doHeal(); } } else { if (isHurt()) { doHeal(); } if (!isCargo()) { changeFortifyTurns(1); } } //Vincentz UPT verifyStackValid(); changeImmobileTimer(-1); setMadeAttack(false); setMadeInterception(false); setReconPlot(NULL); //Vincentz VMoves int newMoves = getMoves() - maxMoves(); if (newMoves < 0) { newMoves = 0; } setMoves(newMoves); // setMoves(0); } void CvUnit::updateAirStrike(CvPlot* pPlot, bool bQuick, bool bFinish) { bool bVisible = false; if (!bFinish) { if (isFighting()) { return; } if (!bQuick) { bVisible = isCombatVisible(NULL); } if (!airStrike(pPlot)) { return; } if (bVisible) { CvAirMissionDefinition kAirMission; kAirMission.setMissionType(MISSION_AIRSTRIKE); kAirMission.setUnit(BATTLE_UNIT_ATTACKER, this); kAirMission.setUnit(BATTLE_UNIT_DEFENDER, NULL); kAirMission.setDamage(BATTLE_UNIT_DEFENDER, 0); kAirMission.setDamage(BATTLE_UNIT_ATTACKER, 0); kAirMission.setPlot(pPlot); setCombatTimer(GC.getMissionInfo(MISSION_AIRSTRIKE).getTime()); GC.getGameINLINE().incrementTurnTimer(getCombatTimer()); kAirMission.setMissionTime(getCombatTimer() * gDLL->getSecsPerTurn()); if (pPlot->isActiveVisible(false)) { gDLL->getEntityIFace()->AddMission(&kAirMission); } return; } } CvUnit *pDefender = getCombatUnit(); if (pDefender != NULL) { pDefender->setCombatUnit(NULL); } setCombatUnit(NULL); setAttackPlot(NULL, false); getGroup()->clearMissionQueue(); if (isSuicide() && !isDead()) { kill(true); } } void CvUnit::resolveAirCombat(CvUnit* pInterceptor, CvPlot* pPlot, CvAirMissionDefinition& kBattle) { CvWString szBuffer; int iTheirStrength = (DOMAIN_AIR == pInterceptor->getDomainType() ? pInterceptor->airCurrCombatStr(this) : pInterceptor->currCombatStr(NULL, NULL)); int iOurStrength = (DOMAIN_AIR == getDomainType() ? airCurrCombatStr(pInterceptor) : currCombatStr(NULL, NULL)); int iTotalStrength = iOurStrength + iTheirStrength; if (0 == iTotalStrength) { FAssert(false); return; } int iOurOdds = (100 * iOurStrength) / std::max(1, iTotalStrength); int iOurRoundDamage = (pInterceptor->currInterceptionProbability() * GC.getDefineINT("MAX_INTERCEPTION_DAMAGE")) / 100; int iTheirRoundDamage = (currInterceptionProbability() * GC.getDefineINT("MAX_INTERCEPTION_DAMAGE")) / 100; if (getDomainType() == DOMAIN_AIR) { iTheirRoundDamage = std::max(GC.getDefineINT("MIN_INTERCEPTION_DAMAGE"), iTheirRoundDamage); } int iTheirDamage = 0; int iOurDamage = 0; for (int iRound = 0; iRound < GC.getDefineINT("INTERCEPTION_MAX_ROUNDS"); ++iRound) { if (GC.getGameINLINE().getSorenRandNum(100, "Air combat") < iOurOdds) { if (DOMAIN_AIR == pInterceptor->getDomainType()) { iTheirDamage += iTheirRoundDamage; pInterceptor->changeDamage(iTheirRoundDamage, getOwnerINLINE()); if (pInterceptor->isDead()) { break; } } } else { iOurDamage += iOurRoundDamage; changeDamage(iOurRoundDamage, pInterceptor->getOwnerINLINE()); if (isDead()) { break; } } } if (isDead()) { if (iTheirRoundDamage > 0) { int iExperience = attackXPValue(); iExperience = (iExperience * iOurStrength) / std::max(1, iTheirStrength); iExperience = range(iExperience, GC.getDefineINT("MIN_EXPERIENCE_PER_COMBAT"), GC.getDefineINT("MAX_EXPERIENCE_PER_COMBAT")); pInterceptor->changeExperience(iExperience, maxXPValue(), true, pPlot->getOwnerINLINE() == pInterceptor->getOwnerINLINE(), !isBarbarian()); } } else if (pInterceptor->isDead()) { int iExperience = pInterceptor->defenseXPValue(); iExperience = (iExperience * iTheirStrength) / std::max(1, iOurStrength); iExperience = range(iExperience, GC.getDefineINT("MIN_EXPERIENCE_PER_COMBAT"), GC.getDefineINT("MAX_EXPERIENCE_PER_COMBAT")); changeExperience(iExperience, pInterceptor->maxXPValue(), true, pPlot->getOwnerINLINE() == getOwnerINLINE(), !pInterceptor->isBarbarian()); } else if (iOurDamage > 0) { if (iTheirRoundDamage > 0) { pInterceptor->changeExperience(GC.getDefineINT("EXPERIENCE_FROM_WITHDRAWL"), maxXPValue(), true, pPlot->getOwnerINLINE() == pInterceptor->getOwnerINLINE(), !isBarbarian()); } } else if (iTheirDamage > 0) { changeExperience(GC.getDefineINT("EXPERIENCE_FROM_WITHDRAWL"), pInterceptor->maxXPValue(), true, pPlot->getOwnerINLINE() == getOwnerINLINE(), !pInterceptor->isBarbarian()); } kBattle.setDamage(BATTLE_UNIT_ATTACKER, iOurDamage); kBattle.setDamage(BATTLE_UNIT_DEFENDER, iTheirDamage); } void CvUnit::updateAirCombat(bool bQuick) { CvUnit* pInterceptor = NULL; bool bFinish = false; FAssert(getDomainType() == DOMAIN_AIR || getDropRange() > 0); if (getCombatTimer() > 0) { changeCombatTimer(-1); if (getCombatTimer() > 0) { return; } else { bFinish = true; } } CvPlot* pPlot = getAttackPlot(); if (pPlot == NULL) { return; } if (bFinish) { pInterceptor = getCombatUnit(); } else { pInterceptor = bestInterceptor(pPlot); } if (pInterceptor == NULL) { setAttackPlot(NULL, false); setCombatUnit(NULL); getGroup()->clearMissionQueue(); return; } //check if quick combat bool bVisible = false; if (!bQuick) { bVisible = isCombatVisible(pInterceptor); } //if not finished and not fighting yet, set up combat damage and mission if (!bFinish) { if (!isFighting()) { if (plot()->isFighting() || pPlot->isFighting()) { return; } setMadeAttack(true); setCombatUnit(pInterceptor, true); pInterceptor->setCombatUnit(this, false); } FAssertMsg(pInterceptor != NULL, "Defender is not assigned a valid value"); FAssertMsg(plot()->isFighting(), "Current unit instance plot is not fighting as expected"); FAssertMsg(pInterceptor->plot()->isFighting(), "pPlot is not fighting as expected"); CvAirMissionDefinition kAirMission; if (DOMAIN_AIR != getDomainType()) { kAirMission.setMissionType(MISSION_PARADROP); } else { kAirMission.setMissionType(MISSION_AIRSTRIKE); } kAirMission.setUnit(BATTLE_UNIT_ATTACKER, this); kAirMission.setUnit(BATTLE_UNIT_DEFENDER, pInterceptor); resolveAirCombat(pInterceptor, pPlot, kAirMission); if (!bVisible) { bFinish = true; } else { kAirMission.setPlot(pPlot); kAirMission.setMissionTime(GC.getMissionInfo(MISSION_AIRSTRIKE).getTime() * gDLL->getSecsPerTurn()); setCombatTimer(GC.getMissionInfo(MISSION_AIRSTRIKE).getTime()); GC.getGameINLINE().incrementTurnTimer(getCombatTimer()); if (pPlot->isActiveVisible(false)) { gDLL->getEntityIFace()->AddMission(&kAirMission); } } //Vincentz Move changeMoves(GC.getMOVE_DENOMINATOR() * 2); if (DOMAIN_AIR != pInterceptor->getDomainType()) { pInterceptor->setMadeInterception(true); } if (isDead()) { CvWString szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_SHOT_DOWN_ENEMY", pInterceptor->getNameKey(), getNameKey(), getVisualCivAdjective(pInterceptor->getTeam())); gDLL->getInterfaceIFace()->addMessage(pInterceptor->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_INTERCEPT", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pPlot->getX_INLINE(), pPlot->getY_INLINE(), true, true); szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_UNIT_SHOT_DOWN", getNameKey(), pInterceptor->getNameKey()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_INTERCEPTED", MESSAGE_TYPE_INFO, pInterceptor->getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); } else if (kAirMission.getDamage(BATTLE_UNIT_ATTACKER) > 0) { CvWString szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_HURT_ENEMY_AIR", pInterceptor->getNameKey(), getNameKey(), -(kAirMission.getDamage(BATTLE_UNIT_ATTACKER)), getVisualCivAdjective(pInterceptor->getTeam())); gDLL->getInterfaceIFace()->addMessage(pInterceptor->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_INTERCEPT", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pPlot->getX_INLINE(), pPlot->getY_INLINE(), true, true); szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_AIR_UNIT_HURT", getNameKey(), pInterceptor->getNameKey(), -(kAirMission.getDamage(BATTLE_UNIT_ATTACKER))); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_INTERCEPTED", MESSAGE_TYPE_INFO, pInterceptor->getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); } if (pInterceptor->isDead()) { CvWString szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_SHOT_DOWN_ENEMY", getNameKey(), pInterceptor->getNameKey(), pInterceptor->getVisualCivAdjective(getTeam())); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_INTERCEPT", MESSAGE_TYPE_INFO, pInterceptor->getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pPlot->getX_INLINE(), pPlot->getY_INLINE(), true, true); szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_UNIT_SHOT_DOWN", pInterceptor->getNameKey(), getNameKey()); gDLL->getInterfaceIFace()->addMessage(pInterceptor->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_INTERCEPTED", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); } else if (kAirMission.getDamage(BATTLE_UNIT_DEFENDER) > 0) { CvWString szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_DAMAGED_ENEMY_AIR", getNameKey(), pInterceptor->getNameKey(), -(kAirMission.getDamage(BATTLE_UNIT_DEFENDER)), pInterceptor->getVisualCivAdjective(getTeam())); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_INTERCEPT", MESSAGE_TYPE_INFO, pInterceptor->getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pPlot->getX_INLINE(), pPlot->getY_INLINE(), true, true); szBuffer = gDLL->getText("TXT_KEY_MISC_YOUR_AIR_UNIT_DAMAGED", pInterceptor->getNameKey(), getNameKey(), -(kAirMission.getDamage(BATTLE_UNIT_DEFENDER))); gDLL->getInterfaceIFace()->addMessage(pInterceptor->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_INTERCEPTED", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); } if (0 == kAirMission.getDamage(BATTLE_UNIT_ATTACKER) + kAirMission.getDamage(BATTLE_UNIT_DEFENDER)) { CvWString szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_ABORTED_ENEMY_AIR", pInterceptor->getNameKey(), getNameKey(), getVisualCivAdjective(getTeam())); gDLL->getInterfaceIFace()->addMessage(pInterceptor->getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_INTERCEPT", MESSAGE_TYPE_INFO, pInterceptor->getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pPlot->getX_INLINE(), pPlot->getY_INLINE(), true, true); szBuffer = gDLL->getText("TXT_KEY_MISC_YOUR_AIR_UNIT_ABORTED", getNameKey(), pInterceptor->getNameKey()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_INTERCEPTED", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); } } if (bFinish) { setAttackPlot(NULL, false); setCombatUnit(NULL); pInterceptor->setCombatUnit(NULL); if (!isDead() && isSuicide()) { kill(true); } } } void CvUnit::resolveCombat(CvUnit* pDefender, CvPlot* pPlot, CvBattleDefinition& kBattle) { CombatDetails cdAttackerDetails; CombatDetails cdDefenderDetails; int iAttackerStrength = currCombatStr(NULL, NULL, &cdAttackerDetails); int iAttackerFirepower = currFirepower(NULL, NULL); int iDefenderStrength; int iAttackerDamage; int iDefenderDamage; int iDefenderOdds; getDefenderCombatValues(*pDefender, pPlot, iAttackerStrength, iAttackerFirepower, iDefenderOdds, iDefenderStrength, iAttackerDamage, iDefenderDamage, &cdDefenderDetails); int iAttackerKillOdds = iDefenderOdds * (100 - withdrawalProbability()) / 100; if (isHuman() || pDefender->isHuman()) { //Added ST CyArgsList pyArgsCD; pyArgsCD.add(gDLL->getPythonIFace()->makePythonObject(&cdAttackerDetails)); pyArgsCD.add(gDLL->getPythonIFace()->makePythonObject(&cdDefenderDetails)); pyArgsCD.add(getCombatOdds(this, pDefender)); CvEventReporter::getInstance().genericEvent("combatLogCalc", pyArgsCD.makeFunctionArgs()); } collateralCombat(pPlot, pDefender); //@MOD DWM: [ int iCloseCombatRoundNum = -1; bool bTryMobileWithdraw = false; //if unit will be trying to withdraw from a plot it occupies if (pPlot->getNumDefenders(pDefender->getOwner()) == 1 && pDefender->baseMoves() + 2 > baseMoves()) //must be faster than attacker { bTryMobileWithdraw = true; } int iWinningOdds = getCombatOdds(this, pDefender); bool bDefenderSkirmish = false; //iWinningOdds > 60; m_combatResult.bDefenderWithdrawn = false; m_combatResult.pPlot = NULL; m_combatResult.iAttacksCount++; //(new variable declaration) ] int WDModifier; int WDWWModifier; if (GET_PLAYER(this->getOwnerINLINE()).isNoNonStateReligionSpread()) { WDModifier = 2; } else { WDModifier = 1; } if (GET_PLAYER(this->getOwnerINLINE()).getWarWearinessModifier() > 50) { WDWWModifier = 5; } else { WDWWModifier = 1; } int iMaxCombatRounds = 0; //Vincentz MaxCombatRounds while (true) { //Vincentz MaxCombatRounds iMaxCombatRounds++; if (iMaxCombatRounds > GC.getDefineINT("MAX_COMBATROUNDS") + movesLeft()/GC.getDefineINT("MOVE_DENOMINATOR")) { if (GC.getGameINLINE().getSorenRandNum(100, "Withdrawal") < withdrawalProbability() / WDModifier) { changeExperience(GC.getDefineINT("EXPERIENCE_FROM_WITHDRAWL"), pDefender->maxXPValue(), true, pPlot->getOwnerINLINE() == getOwnerINLINE(), !pDefender->isBarbarian()); break; } else { changeDamage(iAttackerDamage, pDefender->getOwnerINLINE()); pDefender->changeExperience(GC.getDefineINT("EXPERIENCE_FROM_WITHDRAWL"), maxXPValue(), true, pPlot->getOwnerINLINE() == pDefender->getOwnerINLINE(), !isBarbarian()); if (isHuman() || pDefender->isHuman()) { CyArgsList pyArgs; pyArgs.add(gDLL->getPythonIFace()->makePythonObject(&cdAttackerDetails)); pyArgs.add(gDLL->getPythonIFace()->makePythonObject(&cdDefenderDetails)); pyArgs.add(0); pyArgs.add(iDefenderDamage); CvEventReporter::getInstance().genericEvent("combatLogHit", pyArgs.makeFunctionArgs()); } break; } } if (GC.getGameINLINE().getSorenRandNum(GC.getDefineINT("COMBAT_DIE_SIDES"), "Combat") < iDefenderOdds) //if (GC.getGameINLINE().getSorenRandNum(GC.getDefineINT("COMBAT_DIE_SIDES"), "Combat") < 400 + iDefenderOdds / 5) // Vincentz New Combat { if (getCombatFirstStrikes() == 0) { if (getDamage() + iAttackerDamage * WDWWModifier >= maxHitPoints() && GC.getGameINLINE().getSorenRandNum(100, "Withdrawal") < withdrawalProbability() / WDModifier) { flankingStrikeCombat(pPlot, iAttackerStrength, iAttackerFirepower, iAttackerKillOdds, iDefenderDamage, pDefender); changeExperience(GC.getDefineINT("EXPERIENCE_FROM_WITHDRAWL"), pDefender->maxXPValue(), true, pPlot->getOwnerINLINE() == getOwnerINLINE(), !pDefender->isBarbarian()); break; } changeDamage(iAttackerDamage, pDefender->getOwnerINLINE()); if (pDefender->getCombatFirstStrikes() > 0 && pDefender->isRanged()) { kBattle.addFirstStrikes(BATTLE_UNIT_DEFENDER, 1); kBattle.addDamage(BATTLE_UNIT_ATTACKER, BATTLE_TIME_RANGED, iAttackerDamage); } cdAttackerDetails.iCurrHitPoints = currHitPoints(); if (isHuman() || pDefender->isHuman()) { CyArgsList pyArgs; pyArgs.add(gDLL->getPythonIFace()->makePythonObject(&cdAttackerDetails)); pyArgs.add(gDLL->getPythonIFace()->makePythonObject(&cdDefenderDetails)); pyArgs.add(1); pyArgs.add(iAttackerDamage); CvEventReporter::getInstance().genericEvent("combatLogHit", pyArgs.makeFunctionArgs()); } } } else { if (pDefender->getCombatFirstStrikes() == 0) { //@MOD DWM: [ iCloseCombatRoundNum++; //(code added) ] //combat limit: if (std::min(GC.getMAX_HIT_POINTS(), pDefender->getDamage() + iDefenderDamage) > combatLimit()) { changeExperience(GC.getDefineINT("EXPERIENCE_FROM_WITHDRAWL"), pDefender->maxXPValue(), true, pPlot->getOwnerINLINE() == getOwnerINLINE(), !pDefender->isBarbarian()); pDefender->setDamage(combatLimit(), getOwnerINLINE()); break; } //@MOD DWM: [ //defender trying to withdraw: else if ( (pDefender->getDamage() + iDefenderDamage >= maxHitPoints() || bDefenderSkirmish) && GC.getGameINLINE().getSorenRandNum(100, "Withdrawal") < pDefender->withdrawalProbability() && !isSuicide() && iCloseCombatRoundNum > 3) //can not to escape at close combat round 1 { //attacker got experience int iExperience = pDefender->attackXPValue(); iExperience = ((iExperience * iDefenderStrength) / iAttackerStrength); iExperience = range(iExperience, GC.getDefineINT("MIN_EXPERIENCE_PER_COMBAT"), GC.getDefineINT("MAX_EXPERIENCE_PER_COMBAT")); changeExperience(iExperience, pDefender->maxXPValue(), true, pPlot->getOwnerINLINE() == getOwnerINLINE(), !pDefender->isBarbarian()); if (pPlot->getNumDefenders(pDefender->getOwner()) == 1 && pDefender->baseMoves() > baseMoves()) //must be faster to flee a battle { //try to leave a plot: use back 3 plots int iDeltaX = pPlot->getX() - plot()->getX(); int iDeltaY = pPlot->getY() - plot()->getY(); m_combatResult.pPlot = GC.getMapINLINE().plotINLINE(pPlot->getX() + iDeltaX, pPlot->getY() + iDeltaY); //plot opposed to attacker if (pDefender->canMoveInto(m_combatResult.pPlot)) { m_combatResult.bDefenderWithdrawn = true; } else if (iDeltaX == 0) { m_combatResult.pPlot = GC.getMapINLINE().plotINLINE(pPlot->getX() - 1, pPlot->getY() + iDeltaY); //to the west if (pDefender->canMoveInto(m_combatResult.pPlot)) { m_combatResult.bDefenderWithdrawn = true; } else { m_combatResult.pPlot = GC.getMapINLINE().plotINLINE(pPlot->getX() + 1, pPlot->getY() + iDeltaY); //to the east if (pDefender->canMoveInto(m_combatResult.pPlot)) { //defender got experience: pDefender->changeExperience(GC.getDefineINT("EXPERIENCE_FROM_WITHDRAWL"), maxXPValue(), true, pPlot->getOwnerINLINE() == pDefender->getOwnerINLINE(), !isBarbarian()); return; } } } else if (iDeltaY == 0) { m_combatResult.pPlot = GC.getMapINLINE().plotINLINE(pPlot->getX() + iDeltaX, pPlot->getY() - 1); //to the north if (pDefender->canMoveInto(m_combatResult.pPlot)) { m_combatResult.bDefenderWithdrawn = true; } else { m_combatResult.pPlot = GC.getMapINLINE().plotINLINE(pPlot->getX() + iDeltaX, pPlot->getY() + 1); //to the south if (pDefender->canMoveInto(m_combatResult.pPlot)) { m_combatResult.bDefenderWithdrawn = true; } } } else { m_combatResult.pPlot = GC.getMapINLINE().plotINLINE(pPlot->getX() + iDeltaX, pPlot->getY()); //along w-e if (pDefender->canMoveInto(m_combatResult.pPlot)) { m_combatResult.bDefenderWithdrawn = true; } else { m_combatResult.pPlot = GC.getMapINLINE().plotINLINE(pPlot->getX(), pPlot->getY() + iDeltaY); //along n-s if (pDefender->canMoveInto(m_combatResult.pPlot)) { m_combatResult.bDefenderWithdrawn = true; } } } if (m_combatResult.bDefenderWithdrawn) { //defender got experience: pDefender->changeExperience(GC.getDefineINT("EXPERIENCE_FROM_WITHDRAWL"), maxXPValue(), true, pPlot->getOwnerINLINE() == pDefender->getOwnerINLINE(), !isBarbarian()); return; } else { //withdrawal failed m_combatResult.pPlot = NULL; } } else { //defender got experience: pDefender->changeExperience(GC.getDefineINT("EXPERIENCE_FROM_WITHDRAWL"), maxXPValue(), true, pPlot->getOwnerINLINE() == pDefender->getOwnerINLINE(), !isBarbarian()); m_combatResult.bDefenderWithdrawn = true; return; } } //end mod DWM (new code added) ] pDefender->changeDamage(iDefenderDamage, getOwnerINLINE()); if (getCombatFirstStrikes() > 0 && isRanged()) { kBattle.addFirstStrikes(BATTLE_UNIT_ATTACKER, 1); kBattle.addDamage(BATTLE_UNIT_DEFENDER, BATTLE_TIME_RANGED, iDefenderDamage); } cdDefenderDetails.iCurrHitPoints=pDefender->currHitPoints(); if (isHuman() || pDefender->isHuman()) { CyArgsList pyArgs; pyArgs.add(gDLL->getPythonIFace()->makePythonObject(&cdAttackerDetails)); pyArgs.add(gDLL->getPythonIFace()->makePythonObject(&cdDefenderDetails)); pyArgs.add(0); pyArgs.add(iDefenderDamage); CvEventReporter::getInstance().genericEvent("combatLogHit", pyArgs.makeFunctionArgs()); } } } if (getCombatFirstStrikes() > 0) { changeCombatFirstStrikes(-1); } if (pDefender->getCombatFirstStrikes() > 0) { pDefender->changeCombatFirstStrikes(-1); } if (isDead() || pDefender->isDead()) { if (isDead()) { int iExperience = defenseXPValue(); iExperience = ((iExperience * iAttackerStrength) / iDefenderStrength); iExperience = range(iExperience, GC.getDefineINT("MIN_EXPERIENCE_PER_COMBAT"), GC.getDefineINT("MAX_EXPERIENCE_PER_COMBAT")); pDefender->changeExperience(iExperience, maxXPValue(), true, pPlot->getOwnerINLINE() == pDefender->getOwnerINLINE(), !isBarbarian()); } else { flankingStrikeCombat(pPlot, iAttackerStrength, iAttackerFirepower, iAttackerKillOdds, iDefenderDamage, pDefender); int iExperience = pDefender->attackXPValue(); iExperience = ((iExperience * iDefenderStrength) / iAttackerStrength); iExperience = range(iExperience, GC.getDefineINT("MIN_EXPERIENCE_PER_COMBAT"), GC.getDefineINT("MAX_EXPERIENCE_PER_COMBAT")); changeExperience(iExperience, pDefender->maxXPValue(), true, pPlot->getOwnerINLINE() == getOwnerINLINE(), !pDefender->isBarbarian()); } break; } } } void CvUnit::updateCombat(bool bQuick) { CvWString szBuffer; bool bFinish = false; bool bVisible = false; if (getCombatTimer() > 0) { changeCombatTimer(-1); if (getCombatTimer() > 0) { return; } else { bFinish = true; } } CvPlot* pPlot = getAttackPlot(); if (pPlot == NULL) { return; } if (getDomainType() == DOMAIN_AIR) { updateAirStrike(pPlot, bQuick, bFinish); return; } CvUnit* pDefender = NULL; if (bFinish) { pDefender = getCombatUnit(); } else { pDefender = pPlot->getBestDefender(NO_PLAYER, getOwnerINLINE(), this, true); } if (pDefender == NULL) { setAttackPlot(NULL, false); setCombatUnit(NULL); getGroup()->groupMove(pPlot, true, ((canAdvance(pPlot, 0)) ? this : NULL)); getGroup()->clearMissionQueue(); return; } //check if quick combat if (!bQuick) { bVisible = isCombatVisible(pDefender); } //FAssertMsg((pPlot == pDefender->plot()), "There is not expected to be a defender or the defender's plot is expected to be pPlot (the attack plot)"); //if not finished and not fighting yet, set up combat damage and mission if (!bFinish) { if (!isFighting()) { if (plot()->isFighting() || pPlot->isFighting()) { return; } setMadeAttack(true); //rotate to face plot DirectionTypes newDirection = estimateDirection(this->plot(), pDefender->plot()); if (newDirection != NO_DIRECTION) { setFacingDirection(newDirection); } //rotate enemy to face us newDirection = estimateDirection(pDefender->plot(), this->plot()); if (newDirection != NO_DIRECTION) { pDefender->setFacingDirection(newDirection); } setCombatUnit(pDefender, true); pDefender->setCombatUnit(this, false); pDefender->getGroup()->clearMissionQueue(); bool bFocused = (bVisible && isCombatFocus() && gDLL->getInterfaceIFace()->isCombatFocus()); if (bFocused) { DirectionTypes directionType = directionXY(plot(), pPlot); // N NE E SE S SW W NW NiPoint2 directions[8] = {NiPoint2(0, 1), NiPoint2(1, 1), NiPoint2(1, 0), NiPoint2(1, -1), NiPoint2(0, -1), NiPoint2(-1, -1), NiPoint2(-1, 0), NiPoint2(-1, 1)}; NiPoint3 attackDirection = NiPoint3(directions[directionType].x, directions[directionType].y, 0); float plotSize = GC.getPLOT_SIZE(); NiPoint3 lookAtPoint(plot()->getPoint().x + plotSize / 2 * attackDirection.x, plot()->getPoint().y + plotSize / 2 * attackDirection.y, (plot()->getPoint().z + pPlot->getPoint().z) / 2); attackDirection.Unitize(); gDLL->getInterfaceIFace()->lookAt(lookAtPoint, (((getOwnerINLINE() != GC.getGameINLINE().getActivePlayer()) || gDLL->getGraphicOption(GRAPHICOPTION_NO_COMBAT_ZOOM)) ? CAMERALOOKAT_BATTLE : CAMERALOOKAT_BATTLE_ZOOM_IN), attackDirection); } else { PlayerTypes eAttacker = getVisualOwner(pDefender->getTeam()); CvWString szMessage; if (BARBARIAN_PLAYER != eAttacker) { szMessage = gDLL->getText("TXT_KEY_MISC_YOU_UNITS_UNDER_ATTACK", GET_PLAYER(getOwnerINLINE()).getNameKey()); } else { szMessage = gDLL->getText("TXT_KEY_MISC_YOU_UNITS_UNDER_ATTACK_UNKNOWN"); } gDLL->getInterfaceIFace()->addMessage(pDefender->getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szMessage, "AS2D_COMBAT", MESSAGE_TYPE_DISPLAY_ONLY, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE(), true); } } FAssertMsg(pDefender != NULL, "Defender is not assigned a valid value"); FAssertMsg(plot()->isFighting(), "Current unit instance plot is not fighting as expected"); FAssertMsg(pPlot->isFighting(), "pPlot is not fighting as expected"); if (!pDefender->canDefend()) { if (!bVisible) { bFinish = true; } else { CvMissionDefinition kMission; kMission.setMissionTime(getCombatTimer() * gDLL->getSecsPerTurn()); kMission.setMissionType(MISSION_SURRENDER); kMission.setUnit(BATTLE_UNIT_ATTACKER, this); kMission.setUnit(BATTLE_UNIT_DEFENDER, pDefender); kMission.setPlot(pPlot); gDLL->getEntityIFace()->AddMission(&kMission); // Surrender mission setCombatTimer(GC.getMissionInfo(MISSION_SURRENDER).getTime()); GC.getGameINLINE().incrementTurnTimer(getCombatTimer()); } // Kill them! pDefender->setDamage(GC.getMAX_HIT_POINTS()); } else { CvBattleDefinition kBattle; kBattle.setUnit(BATTLE_UNIT_ATTACKER, this); kBattle.setUnit(BATTLE_UNIT_DEFENDER, pDefender); kBattle.setDamage(BATTLE_UNIT_ATTACKER, BATTLE_TIME_BEGIN, getDamage()); kBattle.setDamage(BATTLE_UNIT_DEFENDER, BATTLE_TIME_BEGIN, pDefender->getDamage()); resolveCombat(pDefender, pPlot, kBattle); if (!bVisible) { bFinish = true; } else { kBattle.setDamage(BATTLE_UNIT_ATTACKER, BATTLE_TIME_END, getDamage()); kBattle.setDamage(BATTLE_UNIT_DEFENDER, BATTLE_TIME_END, pDefender->getDamage()); kBattle.setAdvanceSquare(canAdvance(pPlot, 1)); if (isRanged() && pDefender->isRanged()) { kBattle.setDamage(BATTLE_UNIT_ATTACKER, BATTLE_TIME_RANGED, kBattle.getDamage(BATTLE_UNIT_ATTACKER, BATTLE_TIME_END)); kBattle.setDamage(BATTLE_UNIT_DEFENDER, BATTLE_TIME_RANGED, kBattle.getDamage(BATTLE_UNIT_DEFENDER, BATTLE_TIME_END)); } else { kBattle.addDamage(BATTLE_UNIT_ATTACKER, BATTLE_TIME_RANGED, kBattle.getDamage(BATTLE_UNIT_ATTACKER, BATTLE_TIME_BEGIN)); kBattle.addDamage(BATTLE_UNIT_DEFENDER, BATTLE_TIME_RANGED, kBattle.getDamage(BATTLE_UNIT_DEFENDER, BATTLE_TIME_BEGIN)); } int iTurns = planBattle( kBattle); kBattle.setMissionTime(iTurns * gDLL->getSecsPerTurn()); setCombatTimer(iTurns); GC.getGameINLINE().incrementTurnTimer(getCombatTimer()); if (pPlot->isActiveVisible(false)) { ExecuteMove(0.5f, true); gDLL->getEntityIFace()->AddMission(&kBattle); } } } } if (bFinish) { if (bVisible) { if (isCombatFocus() && gDLL->getInterfaceIFace()->isCombatFocus()) { if (getOwnerINLINE() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->releaseLockedCamera(); } } } //end the combat mission if this code executes first gDLL->getEntityIFace()->RemoveUnitFromBattle(this); gDLL->getEntityIFace()->RemoveUnitFromBattle(pDefender); //@MOD DWM: [ if (!m_combatResult.bDefenderWithdrawn || m_combatResult.iAttacksCount > 2) { setAttackPlot(NULL, false); } //(changed) //was: //setAttackPlot(NULL, false); ] setCombatUnit(NULL); pDefender->setCombatUnit(NULL); NotifyEntity(MISSION_DAMAGE); pDefender->NotifyEntity(MISSION_DAMAGE); if (isDead()) { if (isBarbarian()) { GET_PLAYER(pDefender->getOwnerINLINE()).changeWinsVsBarbs(1); } if (!m_pUnitInfo->isHiddenNationality() && !pDefender->getUnitInfo().isHiddenNationality()) { GET_TEAM(getTeam()).changeWarWeariness(pDefender->getTeam(), *pPlot, GC.getDefineINT("WW_UNIT_KILLED_ATTACKING")); GET_TEAM(pDefender->getTeam()).changeWarWeariness(getTeam(), *pPlot, GC.getDefineINT("WW_KILLED_UNIT_DEFENDING")); GET_TEAM(pDefender->getTeam()).AI_changeWarSuccess(getTeam(), GC.getDefineINT("WAR_SUCCESS_DEFENDING")); } szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_UNIT_DIED_ATTACKING", getNameKey(), pDefender->getNameKey()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, GC.getEraInfo(GC.getGameINLINE().getCurrentEra()).getAudioUnitDefeatScript(), MESSAGE_TYPE_INFO, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_KILLED_ENEMY_UNIT", pDefender->getNameKey(), getNameKey(), getVisualCivAdjective(pDefender->getTeam())); gDLL->getInterfaceIFace()->addMessage(pDefender->getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, GC.getEraInfo(GC.getGameINLINE().getCurrentEra()).getAudioUnitVictoryScript(), MESSAGE_TYPE_INFO, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); // report event to Python, along with some other key state CvEventReporter::getInstance().combatResult(pDefender, this); } else if (pDefender->isDead()) { if (pDefender->isBarbarian()) { GET_PLAYER(getOwnerINLINE()).changeWinsVsBarbs(1); } if (!m_pUnitInfo->isHiddenNationality() && !pDefender->getUnitInfo().isHiddenNationality()) { GET_TEAM(pDefender->getTeam()).changeWarWeariness(getTeam(), *pPlot, GC.getDefineINT("WW_UNIT_KILLED_DEFENDING")); GET_TEAM(getTeam()).changeWarWeariness(pDefender->getTeam(), *pPlot, GC.getDefineINT("WW_KILLED_UNIT_ATTACKING")); GET_TEAM(getTeam()).AI_changeWarSuccess(pDefender->getTeam(), GC.getDefineINT("WAR_SUCCESS_ATTACKING")); } szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_UNIT_DESTROYED_ENEMY", getNameKey(), pDefender->getNameKey()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, GC.getEraInfo(GC.getGameINLINE().getCurrentEra()).getAudioUnitVictoryScript(), MESSAGE_TYPE_INFO, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); if (getVisualOwner(pDefender->getTeam()) != getOwnerINLINE()) { szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_UNIT_WAS_DESTROYED_UNKNOWN", pDefender->getNameKey(), getNameKey()); } else { szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_UNIT_WAS_DESTROYED", pDefender->getNameKey(), getNameKey(), getVisualCivAdjective(pDefender->getTeam())); } gDLL->getInterfaceIFace()->addMessage(pDefender->getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer,GC.getEraInfo(GC.getGameINLINE().getCurrentEra()).getAudioUnitDefeatScript(), MESSAGE_TYPE_INFO, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); // report event to Python, along with some other key state CvEventReporter::getInstance().combatResult(this, pDefender); bool bAdvance = false; if (isSuicide()) { kill(true); pDefender->kill(false); pDefender = NULL; } else { bAdvance = canAdvance(pPlot, ((pDefender->canDefend()) ? 1 : 0)); if (bAdvance) { if (!isNoCapture()) { pDefender->setCapturingPlayer(getOwnerINLINE()); } } pDefender->kill(false); pDefender = NULL; if (!bAdvance) { changeMoves(std::max(GC.getMOVE_DENOMINATOR(), pPlot->movementCost(this, plot()))); checkRemoveSelectionAfterAttack(); } } if (pPlot->getNumVisibleEnemyDefenders(this) == 0) { getGroup()->groupMove(pPlot, true, ((bAdvance) ? this : NULL)); } // This is is put before the plot advancement, the unit will always try to walk back // to the square that they came from, before advancing. getGroup()->clearMissionQueue(); } //@MOD DWM: defender withdrawn [ else if (m_combatResult.bDefenderWithdrawn) { szBuffer = gDLL->getText("TXT_KEY_MISC_ENEMY_UNIT_WITHDRAW", pDefender->getNameKey(), getNameKey()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_OUR_WITHDRAWL", MESSAGE_TYPE_INFO, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_UNIT_WITHDRAW", pDefender->getNameKey(), getNameKey()); gDLL->getInterfaceIFace()->addMessage(pDefender->getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_THEIR_WITHDRAWL", MESSAGE_TYPE_INFO, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); if (m_combatResult.pPlot != NULL) { //defender escapes to a safe plot pDefender->move(m_combatResult.pPlot, true); } if (m_combatResult.iAttacksCount > 2) { changeMoves(std::max(GC.getMOVE_DENOMINATOR(), pPlot->movementCost(this, plot()))); checkRemoveSelectionAfterAttack(); getGroup()->clearMissionQueue(); } else { updateCombat(bQuick); } } //end mod DWM (new code added) ] else //attacker withdrawn { szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_UNIT_WITHDRAW", getNameKey(), pDefender->getNameKey()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_OUR_WITHDRAWL", MESSAGE_TYPE_INFO, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); szBuffer = gDLL->getText("TXT_KEY_MISC_ENEMY_UNIT_WITHDRAW", getNameKey(), pDefender->getNameKey()); gDLL->getInterfaceIFace()->addMessage(pDefender->getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_THEIR_WITHDRAWL", MESSAGE_TYPE_INFO, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); changeMoves(std::max(GC.getMOVE_DENOMINATOR(), pPlot->movementCost(this, plot()))); checkRemoveSelectionAfterAttack(); getGroup()->clearMissionQueue(); } } } void CvUnit::checkRemoveSelectionAfterAttack() { if (!canMove() || !isBlitz()) { if (IsSelected()) { if (gDLL->getInterfaceIFace()->getLengthSelectionList() > 1) { gDLL->getInterfaceIFace()->removeFromSelectionList(this); } } } } bool CvUnit::isActionRecommended(int iAction) { CvCity* pWorkingCity; CvPlot* pPlot; ImprovementTypes eImprovement; ImprovementTypes eFinalImprovement; BuildTypes eBuild; RouteTypes eRoute; BonusTypes eBonus; int iIndex; if (getOwnerINLINE() != GC.getGameINLINE().getActivePlayer()) { return false; } if (GET_PLAYER(getOwnerINLINE()).isOption(PLAYEROPTION_NO_UNIT_RECOMMENDATIONS)) { return false; } CyUnit* pyUnit = new CyUnit(this); CyArgsList argsList; argsList.add(gDLL->getPythonIFace()->makePythonObject(pyUnit)); // pass in unit class argsList.add(iAction); long lResult=0; gDLL->getPythonIFace()->callFunction(PYGameModule, "isActionRecommended", argsList.makeFunctionArgs(), &lResult); delete pyUnit; // python fxn must not hold on to this pointer if (lResult == 1) { return true; } pPlot = gDLL->getInterfaceIFace()->getGotoPlot(); if (pPlot == NULL) { if (gDLL->shiftKey()) { pPlot = getGroup()->lastMissionPlot(); } } if (pPlot == NULL) { pPlot = plot(); } if (GC.getActionInfo(iAction).getMissionType() == MISSION_FORTIFY) { if (pPlot->isCity(true, getTeam())) { if (canDefend(pPlot)) { if (pPlot->getNumDefenders(getOwnerINLINE()) < ((atPlot(pPlot)) ? 2 : 1)) { return true; } } } } if (GC.getActionInfo(iAction).getMissionType() == MISSION_HEAL) { if (isHurt()) { if (!hasMoved()) { if ((pPlot->getTeam() == getTeam()) || (healTurns(pPlot) < 4)) { return true; } } } } if (GC.getActionInfo(iAction).getMissionType() == MISSION_FOUND) { if (canFound(pPlot)) { if (pPlot->isBestAdjacentFound(getOwnerINLINE())) { return true; } } } if (GC.getActionInfo(iAction).getMissionType() == MISSION_BUILD) { if (pPlot->getOwnerINLINE() == getOwnerINLINE()) { eBuild = ((BuildTypes)(GC.getActionInfo(iAction).getMissionData())); FAssert(eBuild != NO_BUILD); FAssertMsg(eBuild < GC.getNumBuildInfos(), "Invalid Build"); if (canBuild(pPlot, eBuild)) { eImprovement = ((ImprovementTypes)(GC.getBuildInfo(eBuild).getImprovement())); eRoute = ((RouteTypes)(GC.getBuildInfo(eBuild).getRoute())); eBonus = pPlot->getBonusType(getTeam()); pWorkingCity = pPlot->getWorkingCity(); if (pPlot->getImprovementType() == NO_IMPROVEMENT) { if (pWorkingCity != NULL) { iIndex = pWorkingCity->getCityPlotIndex(pPlot); if (iIndex != -1) { if (pWorkingCity->AI_getBestBuild(iIndex) == eBuild) { return true; } } } if (eImprovement != NO_IMPROVEMENT) { if (eBonus != NO_BONUS) { if (GC.getImprovementInfo(eImprovement).isImprovementBonusTrade(eBonus)) { return true; } } if (pPlot->getImprovementType() == NO_IMPROVEMENT) { if (!(pPlot->isIrrigated()) && pPlot->isIrrigationAvailable(true)) { if (GC.getImprovementInfo(eImprovement).isCarriesIrrigation()) { return true; } } if (pWorkingCity != NULL) { if (GC.getImprovementInfo(eImprovement).getYieldChange(YIELD_FOOD) > 0) { return true; } if (pPlot->isHills()) { if (GC.getImprovementInfo(eImprovement).getYieldChange(YIELD_PRODUCTION) > 0) { return true; } } else { if (GC.getImprovementInfo(eImprovement).getYieldChange(YIELD_COMMERCE) > 0) { return true; } } } } } } if (eRoute != NO_ROUTE) { if (!(pPlot->isRoute())) { if (eBonus != NO_BONUS) { return true; } if (pWorkingCity != NULL) { if (pPlot->isRiver()) { return true; } } } eFinalImprovement = eImprovement; if (eFinalImprovement == NO_IMPROVEMENT) { eFinalImprovement = pPlot->getImprovementType(); } if (eFinalImprovement != NO_IMPROVEMENT) { if ((GC.getImprovementInfo(eFinalImprovement).getRouteYieldChanges(eRoute, YIELD_FOOD) > 0) || (GC.getImprovementInfo(eFinalImprovement).getRouteYieldChanges(eRoute, YIELD_PRODUCTION) > 0) || (GC.getImprovementInfo(eFinalImprovement).getRouteYieldChanges(eRoute, YIELD_COMMERCE) > 0)) { return true; } } } } } } if (GC.getActionInfo(iAction).getCommandType() == COMMAND_PROMOTION) { return true; } return false; } bool CvUnit::isBetterDefenderThan(const CvUnit* pDefender, const CvUnit* pAttacker) const { int iOurDefense; int iTheirDefense; if (pDefender == NULL) { return true; } TeamTypes eAttackerTeam = NO_TEAM; if (NULL != pAttacker) { eAttackerTeam = pAttacker->getTeam(); } if (canCoexistWithEnemyUnit(eAttackerTeam)) { return false; } if (!canDefend()) { return false; } if (canDefend() && !(pDefender->canDefend())) { return true; } if (pAttacker) { if (isTargetOf(*pAttacker) && !pDefender->isTargetOf(*pAttacker)) { return true; } if (!isTargetOf(*pAttacker) && pDefender->isTargetOf(*pAttacker)) { return false; } if (pAttacker->canAttack(*pDefender) && !pAttacker->canAttack(*this)) { return false; } if (pAttacker->canAttack(*this) && !pAttacker->canAttack(*pDefender)) { return true; } } iOurDefense = currCombatStr(plot(), pAttacker); if (::isWorldUnitClass(getUnitClassType())) { iOurDefense /= 2; } if (NULL == pAttacker) { if (pDefender->collateralDamage() > 0) { iOurDefense *= (100 + pDefender->collateralDamage()); iOurDefense /= 100; } if (pDefender->currInterceptionProbability() > 0) { iOurDefense *= (100 + pDefender->currInterceptionProbability()); iOurDefense /= 100; } } else { if (!(pAttacker->immuneToFirstStrikes())) { iOurDefense *= ((((firstStrikes() * 2) + chanceFirstStrikes()) * ((GC.getDefineINT("COMBAT_DAMAGE") * 2) / 5)) + 100); iOurDefense /= 100; } if (immuneToFirstStrikes()) { iOurDefense *= ((((pAttacker->firstStrikes() * 2) + pAttacker->chanceFirstStrikes()) * ((GC.getDefineINT("COMBAT_DAMAGE") * 2) / 5)) + 100); iOurDefense /= 100; } } int iAssetValue = std::max(1, getUnitInfo().getAssetValue()); int iCargoAssetValue = 0; std::vector<CvUnit*> aCargoUnits; getCargoUnits(aCargoUnits); for (uint i = 0; i < aCargoUnits.size(); ++i) { iCargoAssetValue += aCargoUnits[i]->getUnitInfo().getAssetValue(); } iOurDefense = iOurDefense * iAssetValue / std::max(1, iAssetValue + iCargoAssetValue); iTheirDefense = pDefender->currCombatStr(plot(), pAttacker); if (::isWorldUnitClass(pDefender->getUnitClassType())) { iTheirDefense /= 2; } if (NULL == pAttacker) { if (collateralDamage() > 0) { iTheirDefense *= (100 + collateralDamage()); iTheirDefense /= 100; } if (currInterceptionProbability() > 0) { iTheirDefense *= (100 + currInterceptionProbability()); iTheirDefense /= 100; } } else { if (!(pAttacker->immuneToFirstStrikes())) { iTheirDefense *= ((((pDefender->firstStrikes() * 2) + pDefender->chanceFirstStrikes()) * ((GC.getDefineINT("COMBAT_DAMAGE") * 2) / 5)) + 100); iTheirDefense /= 100; } if (pDefender->immuneToFirstStrikes()) { iTheirDefense *= ((((pAttacker->firstStrikes() * 2) + pAttacker->chanceFirstStrikes()) * ((GC.getDefineINT("COMBAT_DAMAGE") * 2) / 5)) + 100); iTheirDefense /= 100; } } iAssetValue = std::max(1, pDefender->getUnitInfo().getAssetValue()); iCargoAssetValue = 0; pDefender->getCargoUnits(aCargoUnits); for (uint i = 0; i < aCargoUnits.size(); ++i) { iCargoAssetValue += aCargoUnits[i]->getUnitInfo().getAssetValue(); } iTheirDefense = iTheirDefense * iAssetValue / std::max(1, iAssetValue + iCargoAssetValue); if (iOurDefense == iTheirDefense) { if (NO_UNIT == getLeaderUnitType() && NO_UNIT != pDefender->getLeaderUnitType()) { ++iOurDefense; } else if (NO_UNIT != getLeaderUnitType() && NO_UNIT == pDefender->getLeaderUnitType()) { ++iTheirDefense; } else if (isBeforeUnitCycle(this, pDefender)) { ++iOurDefense; } } return (iOurDefense > iTheirDefense); } bool CvUnit::canDoCommand(CommandTypes eCommand, int iData1, int iData2, bool bTestVisible, bool bTestBusy) { CvUnit* pUnit; if (bTestBusy && getGroup()->isBusy()) { return false; } switch (eCommand) { case COMMAND_PROMOTION: if (canPromote((PromotionTypes)iData1, iData2)) { return true; } break; case COMMAND_UPGRADE: if (canUpgrade(((UnitTypes)iData1), bTestVisible)) { return true; } break; case COMMAND_AUTOMATE: if (canAutomate((AutomateTypes)iData1)) { return true; } break; case COMMAND_WAKE: if (!isAutomated() && isWaiting()) { return true; } break; case COMMAND_CANCEL: case COMMAND_CANCEL_ALL: if (!isAutomated() && (getGroup()->getLengthMissionQueue() > 0)) { return true; } break; case COMMAND_STOP_AUTOMATION: if (isAutomated()) { return true; } break; case COMMAND_DELETE: if (canScrap()) { return true; } break; case COMMAND_GIFT: if (canGift(bTestVisible)) { return true; } break; case COMMAND_LOAD: if (canLoad(plot())) { return true; } break; case COMMAND_LOAD_UNIT: pUnit = ::getUnit(IDInfo(((PlayerTypes)iData1), iData2)); if (pUnit != NULL) { if (canLoadUnit(pUnit, plot())) { return true; } } break; case COMMAND_UNLOAD: if (canUnload()) { return true; } break; case COMMAND_UNLOAD_ALL: if (canUnloadAll()) { return true; } break; case COMMAND_HOTKEY: if (isGroupHead()) { return true; } break; default: FAssert(false); break; } return false; } void CvUnit::doCommand(CommandTypes eCommand, int iData1, int iData2) { CvUnit* pUnit; bool bCycle; bCycle = false; FAssert(getOwnerINLINE() != NO_PLAYER); if (canDoCommand(eCommand, iData1, iData2)) { switch (eCommand) { case COMMAND_PROMOTION: promote((PromotionTypes)iData1, iData2); break; case COMMAND_UPGRADE: upgrade((UnitTypes)iData1); bCycle = true; break; case COMMAND_AUTOMATE: automate((AutomateTypes)iData1); bCycle = true; break; case COMMAND_WAKE: getGroup()->setActivityType(ACTIVITY_AWAKE); break; case COMMAND_CANCEL: getGroup()->popMission(); break; case COMMAND_CANCEL_ALL: getGroup()->clearMissionQueue(); break; case COMMAND_STOP_AUTOMATION: getGroup()->setAutomateType(NO_AUTOMATE); break; case COMMAND_DELETE: scrap(); bCycle = true; break; case COMMAND_GIFT: gift(); bCycle = true; break; case COMMAND_LOAD: load(); bCycle = true; break; case COMMAND_LOAD_UNIT: pUnit = ::getUnit(IDInfo(((PlayerTypes)iData1), iData2)); if (pUnit != NULL) { loadUnit(pUnit); bCycle = true; } break; case COMMAND_UNLOAD: unload(); bCycle = true; break; case COMMAND_UNLOAD_ALL: unloadAll(); bCycle = true; break; case COMMAND_HOTKEY: setHotKeyNumber(iData1); break; default: FAssert(false); break; } } if (bCycle) { if (IsSelected()) { gDLL->getInterfaceIFace()->setCycleSelectionCounter(1); } } getGroup()->doDelayedDeath(); } FAStarNode* CvUnit::getPathLastNode() const { return getGroup()->getPathLastNode(); } CvPlot* CvUnit::getPathEndTurnPlot() const { return getGroup()->getPathEndTurnPlot(); } bool CvUnit::generatePath(const CvPlot* pToPlot, int iFlags, bool bReuse, int* piPathTurns) const { return getGroup()->generatePath(plot(), pToPlot, iFlags, bReuse, piPathTurns); } bool CvUnit::canEnterTerritory(TeamTypes eTeam, bool bIgnoreRightOfPassage) const { if (GET_TEAM(getTeam()).isFriendlyTerritory(eTeam)) { return true; } if (eTeam == NO_TEAM) { return true; } if (isEnemy(eTeam)) { return true; } if (isRivalTerritory()) { return true; } if (alwaysInvisible()) { return true; } if (m_pUnitInfo->isHiddenNationality()) { return true; } if (!bIgnoreRightOfPassage) { if (GET_TEAM(getTeam()).isOpenBorders(eTeam)) { return true; } } return false; } bool CvUnit::canEnterArea(TeamTypes eTeam, const CvArea* pArea, bool bIgnoreRightOfPassage) const { if (!canEnterTerritory(eTeam, bIgnoreRightOfPassage)) { return false; } if (isBarbarian() && DOMAIN_LAND == getDomainType()) { if (eTeam != NO_TEAM && eTeam != getTeam()) { if (pArea && pArea->isBorderObstacle(eTeam)) { return false; } } } return true; } // Returns the ID of the team to declare war against TeamTypes CvUnit::getDeclareWarMove(const CvPlot* pPlot) const { CvUnit* pUnit; TeamTypes eRevealedTeam; FAssert(isHuman()); if (getDomainType() != DOMAIN_AIR) { eRevealedTeam = pPlot->getRevealedTeam(getTeam(), false); if (eRevealedTeam != NO_TEAM) { if (!canEnterArea(eRevealedTeam, pPlot->area()) || (getDomainType() == DOMAIN_SEA && !canCargoEnterArea(eRevealedTeam, pPlot->area(), false) && getGroup()->isAmphibPlot(pPlot))) { if (GET_TEAM(getTeam()).canDeclareWar(pPlot->getTeam())) { return eRevealedTeam; } } } else { if (pPlot->isActiveVisible(false)) { if (canMoveInto(pPlot, true, true, true)) { pUnit = pPlot->plotCheck(PUF_canDeclareWar, getOwnerINLINE(), isAlwaysHostile(pPlot), NO_PLAYER, NO_TEAM, PUF_isVisible, getOwnerINLINE()); if (pUnit != NULL) { return pUnit->getTeam(); } } } } } return NO_TEAM; } bool CvUnit::willRevealByMove(const CvPlot* pPlot) const { int iRange = visibilityRange() + 1; for (int i = -iRange; i <= iRange; ++i) { for (int j = -iRange; j <= iRange; ++j) { CvPlot* pLoopPlot = ::plotXY(pPlot->getX_INLINE(), pPlot->getY_INLINE(), i, j); if (NULL != pLoopPlot) { if (!pLoopPlot->isRevealed(getTeam(), false) && pPlot->canSeePlot(pLoopPlot, getTeam(), visibilityRange(), NO_DIRECTION)) { return true; } } } } return false; } bool CvUnit::canMoveInto(const CvPlot* pPlot, bool bAttack, bool bDeclareWar, bool bIgnoreLoad) const { FAssertMsg(pPlot != NULL, "Plot is not assigned a valid value"); if (atPlot(pPlot)) { return false; } if (pPlot->isImpassable()) { if (!canMoveImpassable()) { return false; } } // Cannot move around in unrevealed land freely if (m_pUnitInfo->isNoRevealMap() && willRevealByMove(pPlot)) { return false; } if (GC.getUSE_SPIES_NO_ENTER_BORDERS()) { if (isSpy() && NO_PLAYER != pPlot->getOwnerINLINE()) { if (!GET_PLAYER(getOwnerINLINE()).canSpiesEnterBorders(pPlot->getOwnerINLINE())) { return false; } } } CvArea *pPlotArea = pPlot->area(); TeamTypes ePlotTeam = pPlot->getTeam(); bool bCanEnterArea = canEnterArea(ePlotTeam, pPlotArea); if (bCanEnterArea) { if (pPlot->getFeatureType() != NO_FEATURE) { if (m_pUnitInfo->getFeatureImpassable(pPlot->getFeatureType())) { TechTypes eTech = (TechTypes)m_pUnitInfo->getFeaturePassableTech(pPlot->getFeatureType()); if (NO_TECH == eTech || !GET_TEAM(getTeam()).isHasTech(eTech)) { if (DOMAIN_SEA != getDomainType() || pPlot->getTeam() != getTeam()) // sea units can enter impassable in own cultural borders { return false; } } } } else { if (m_pUnitInfo->getTerrainImpassable(pPlot->getTerrainType())) { TechTypes eTech = (TechTypes)m_pUnitInfo->getTerrainPassableTech(pPlot->getTerrainType()); if (NO_TECH == eTech || !GET_TEAM(getTeam()).isHasTech(eTech)) { if (DOMAIN_SEA != getDomainType() || pPlot->getTeam() != getTeam()) // sea units can enter impassable in own cultural borders { if (bIgnoreLoad || !canLoad(pPlot)) { return false; } } } } } } switch (getDomainType()) { case DOMAIN_SEA: if (!pPlot->isWater() && !canMoveAllTerrain()) { if (!pPlot->isFriendlyCity(*this, true) || !pPlot->isCoastalLand()) { return false; } } break; case DOMAIN_AIR: if (!bAttack) { bool bValid = false; if (pPlot->isFriendlyCity(*this, true)) { bValid = true; if (m_pUnitInfo->getAirUnitCap() > 0) { if (pPlot->airUnitSpaceAvailable(getTeam()) <= 0) { bValid = false; } } } if (!bValid) { if (bIgnoreLoad || !canLoad(pPlot)) { return false; } } } break; case DOMAIN_LAND: if (pPlot->isWater() && !canMoveAllTerrain()) { if (!pPlot->isCity() || 0 == GC.getDefineINT("LAND_UNITS_CAN_ATTACK_WATER_CITIES")) { if (bIgnoreLoad || !isHuman() || plot()->isWater() || !canLoad(pPlot)) { return false; } } } break; case DOMAIN_IMMOBILE: return false; break; case DOMAIN_SPACE: return true; break; default: FAssert(false); break; } //Vincentz UPT int iNumVisibleUnits = 0; if (pPlot->isVisible(GC.getGameINLINE().getActiveTeam(), false)) { CLLNode<IDInfo>* pUnitNode5 = pPlot->headUnitNode(); while (pUnitNode5 != NULL) { CvUnit* pUnit = ::getUnit(pUnitNode5->m_data); pUnitNode5 = pPlot->nextUnitNode(pUnitNode5); if (pUnit && !pUnit->isInvisible(GC.getGameINLINE().getActiveTeam(), false)) { ++iNumVisibleUnits; } } } if (!pPlot->isVisibleEnemyUnit(this)) { if (iNumVisibleUnits >= GC.getDefineINT("MAXUPT") * GET_PLAYER(getOwnerINLINE()).getCurrentEra() + GC.getDefineINT("STARTUPT")) { return false; } } //Vincentz #UPT if (isAnimal()) { if (pPlot->isOwned()) { return false; } if (!bAttack) { if (pPlot->getBonusType() != NO_BONUS) { return false; } if (pPlot->getImprovementType() != NO_IMPROVEMENT) { return false; } if (pPlot->getNumUnits() > 0) { return false; } } } if (isNoCapture()) { if (!bAttack) { if (pPlot->isEnemyCity(*this)) { return false; } } } if (bAttack) { if (isMadeAttack() && !isBlitz()) { return false; } } // Vincentz Rangestrike cannot move if (bAttack) { if (getDomainType() == DOMAIN_LAND && canRangeStrike() && baseCombatStr() <= airBaseCombatStr()) { return false; } } if (getDomainType() == DOMAIN_AIR) { if (bAttack) { if (!canAirStrike(pPlot)) { return false; } } } else { if (canAttack()) { if (bAttack || !canCoexistWithEnemyUnit(NO_TEAM)) { if (!isHuman() || (pPlot->isVisible(getTeam(), false))) { if (pPlot->isVisibleEnemyUnit(this) != bAttack) { //FAssertMsg(isHuman() || (!bDeclareWar || (pPlot->isVisibleOtherUnit(getOwnerINLINE()) != bAttack)), "hopefully not an issue, but tracking how often this is the case when we dont want to really declare war"); if (!bDeclareWar || (pPlot->isVisibleOtherUnit(getOwnerINLINE()) != bAttack && !(bAttack && pPlot->getPlotCity() && !isNoCapture()))) { return false; } } } } if (bAttack) { CvUnit* pDefender = pPlot->getBestDefender(NO_PLAYER, getOwnerINLINE(), this, true); if (NULL != pDefender) { if (!canAttack(*pDefender)) { return false; } } } } else { if (bAttack) { return false; } if (!canCoexistWithEnemyUnit(NO_TEAM)) { if (!isHuman() || pPlot->isVisible(getTeam(), false)) { if (pPlot->isEnemyCity(*this)) { return false; } if (pPlot->isVisibleEnemyUnit(this)) { return false; } } } } if (isHuman()) { ePlotTeam = pPlot->getRevealedTeam(getTeam(), false); bCanEnterArea = canEnterArea(ePlotTeam, pPlotArea); } if (!bCanEnterArea) { FAssert(ePlotTeam != NO_TEAM); if (!(GET_TEAM(getTeam()).canDeclareWar(ePlotTeam))) { return false; } if (isHuman()) { if (!bDeclareWar) { return false; } } else { if (GET_TEAM(getTeam()).AI_isSneakAttackReady(ePlotTeam)) { if (!(getGroup()->AI_isDeclareWar(pPlot))) { return false; } } else { return false; } } } } if (GC.getUSE_UNIT_CANNOT_MOVE_INTO_CALLBACK()) { // Python Override CyArgsList argsList; argsList.add(getOwnerINLINE()); // Player ID argsList.add(getID()); // Unit ID argsList.add(pPlot->getX()); // Plot X argsList.add(pPlot->getY()); // Plot Y long lResult=0; gDLL->getPythonIFace()->callFunction(PYGameModule, "unitCannotMoveInto", argsList.makeFunctionArgs(), &lResult); if (lResult != 0) { return false; } } return true; } bool CvUnit::canMoveOrAttackInto(const CvPlot* pPlot, bool bDeclareWar) const { return (canMoveInto(pPlot, false, bDeclareWar) || canMoveInto(pPlot, true, bDeclareWar)); } bool CvUnit::canMoveThrough(const CvPlot* pPlot) const { return canMoveInto(pPlot, false, false, true); } void CvUnit::attack(CvPlot* pPlot, bool bQuick) { FAssert(canMoveInto(pPlot, true)); FAssert(getCombatTimer() == 0); //@MOD DWM: m_combatResult.iAttacksCount = 0; //end mod setAttackPlot(pPlot, false); updateCombat(bQuick); } void CvUnit::fightInterceptor(const CvPlot* pPlot, bool bQuick) { FAssert(getCombatTimer() == 0); setAttackPlot(pPlot, true); updateAirCombat(bQuick); } void CvUnit::attackForDamage(CvUnit *pDefender, int attackerDamageChange, int defenderDamageChange) { FAssert(getCombatTimer() == 0); FAssert(pDefender != NULL); FAssert(!isFighting()); if(pDefender == NULL) { return; } setAttackPlot(pDefender->plot(), false); CvPlot* pPlot = getAttackPlot(); if (pPlot == NULL) { return; } //rotate to face plot DirectionTypes newDirection = estimateDirection(this->plot(), pDefender->plot()); if(newDirection != NO_DIRECTION) { setFacingDirection(newDirection); } //rotate enemy to face us newDirection = estimateDirection(pDefender->plot(), this->plot()); if(newDirection != NO_DIRECTION) { pDefender->setFacingDirection(newDirection); } //check if quick combat bool bVisible = isCombatVisible(pDefender); //if not finished and not fighting yet, set up combat damage and mission if (!isFighting()) { if (plot()->isFighting() || pPlot->isFighting()) { return; } setCombatUnit(pDefender, true); pDefender->setCombatUnit(this, false); pDefender->getGroup()->clearMissionQueue(); bool bFocused = (bVisible && isCombatFocus() && gDLL->getInterfaceIFace()->isCombatFocus()); if (bFocused) { DirectionTypes directionType = directionXY(plot(), pPlot); // N NE E SE S SW W NW NiPoint2 directions[8] = {NiPoint2(0, 1), NiPoint2(1, 1), NiPoint2(1, 0), NiPoint2(1, -1), NiPoint2(0, -1), NiPoint2(-1, -1), NiPoint2(-1, 0), NiPoint2(-1, 1)}; NiPoint3 attackDirection = NiPoint3(directions[directionType].x, directions[directionType].y, 0); float plotSize = GC.getPLOT_SIZE(); NiPoint3 lookAtPoint(plot()->getPoint().x + plotSize / 2 * attackDirection.x, plot()->getPoint().y + plotSize / 2 * attackDirection.y, (plot()->getPoint().z + pPlot->getPoint().z) / 2); attackDirection.Unitize(); gDLL->getInterfaceIFace()->lookAt(lookAtPoint, (((getOwnerINLINE() != GC.getGameINLINE().getActivePlayer()) || gDLL->getGraphicOption(GRAPHICOPTION_NO_COMBAT_ZOOM)) ? CAMERALOOKAT_BATTLE : CAMERALOOKAT_BATTLE_ZOOM_IN), attackDirection); } else { PlayerTypes eAttacker = getVisualOwner(pDefender->getTeam()); CvWString szMessage; if (BARBARIAN_PLAYER != eAttacker) { szMessage = gDLL->getText("TXT_KEY_MISC_YOU_UNITS_UNDER_ATTACK", GET_PLAYER(getOwnerINLINE()).getNameKey()); } else { szMessage = gDLL->getText("TXT_KEY_MISC_YOU_UNITS_UNDER_ATTACK_UNKNOWN"); } gDLL->getInterfaceIFace()->addMessage(pDefender->getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szMessage, "AS2D_COMBAT", MESSAGE_TYPE_DISPLAY_ONLY, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE(), true); } } FAssertMsg(plot()->isFighting(), "Current unit instance plot is not fighting as expected"); FAssertMsg(pPlot->isFighting(), "pPlot is not fighting as expected"); //setup battle object CvBattleDefinition kBattle; kBattle.setUnit(BATTLE_UNIT_ATTACKER, this); kBattle.setUnit(BATTLE_UNIT_DEFENDER, pDefender); kBattle.setDamage(BATTLE_UNIT_ATTACKER, BATTLE_TIME_BEGIN, getDamage()); kBattle.setDamage(BATTLE_UNIT_DEFENDER, BATTLE_TIME_BEGIN, pDefender->getDamage()); changeDamage(attackerDamageChange, pDefender->getOwnerINLINE()); pDefender->changeDamage(defenderDamageChange, getOwnerINLINE()); if (bVisible) { kBattle.setDamage(BATTLE_UNIT_ATTACKER, BATTLE_TIME_END, getDamage()); kBattle.setDamage(BATTLE_UNIT_DEFENDER, BATTLE_TIME_END, pDefender->getDamage()); kBattle.setAdvanceSquare(canAdvance(pPlot, 1)); kBattle.addDamage(BATTLE_UNIT_ATTACKER, BATTLE_TIME_RANGED, kBattle.getDamage(BATTLE_UNIT_ATTACKER, BATTLE_TIME_BEGIN)); kBattle.addDamage(BATTLE_UNIT_DEFENDER, BATTLE_TIME_RANGED, kBattle.getDamage(BATTLE_UNIT_DEFENDER, BATTLE_TIME_BEGIN)); int iTurns = planBattle( kBattle); kBattle.setMissionTime(iTurns * gDLL->getSecsPerTurn()); setCombatTimer(iTurns); GC.getGameINLINE().incrementTurnTimer(getCombatTimer()); if (pPlot->isActiveVisible(false)) { ExecuteMove(0.5f, true); gDLL->getEntityIFace()->AddMission(&kBattle); } } else { setCombatTimer(1); } } void CvUnit::move(CvPlot* pPlot, bool bShow) { FAssert(canMoveOrAttackInto(pPlot) || isMadeAttack()); CvPlot* pOldPlot = plot(); changeMoves(pPlot->movementCost(this, plot())); setXY(pPlot->getX_INLINE(), pPlot->getY_INLINE(), true, true, bShow && pPlot->isVisibleToWatchingHuman(), bShow); //change feature FeatureTypes featureType = pPlot->getFeatureType(); if(featureType != NO_FEATURE) { CvString featureString(GC.getFeatureInfo(featureType).getOnUnitChangeTo()); if(!featureString.IsEmpty()) { FeatureTypes newFeatureType = (FeatureTypes) GC.getInfoTypeForString(featureString); pPlot->setFeatureType(newFeatureType); } } if (getOwnerINLINE() == GC.getGameINLINE().getActivePlayer()) { if (!(pPlot->isOwned())) { //spawn birds if trees present - JW if (featureType != NO_FEATURE) { if (GC.getASyncRand().get(100) < GC.getFeatureInfo(featureType).getEffectProbability()) { EffectTypes eEffect = (EffectTypes)GC.getInfoTypeForString(GC.getFeatureInfo(featureType).getEffectType()); gDLL->getEngineIFace()->TriggerEffect(eEffect, pPlot->getPoint(), (float)(GC.getASyncRand().get(360))); gDLL->getInterfaceIFace()->playGeneralSound("AS3D_UN_BIRDS_SCATTER", pPlot->getPoint()); } } } } CvEventReporter::getInstance().unitMove(pPlot, this, pOldPlot); } // false if unit is killed bool CvUnit::jumpToNearestValidPlot() { CvCity* pNearestCity; CvPlot* pLoopPlot; CvPlot* pBestPlot; int iValue; int iBestValue; int iI; FAssertMsg(!isAttacking(), "isAttacking did not return false as expected"); FAssertMsg(!isFighting(), "isFighting did not return false as expected"); pNearestCity = GC.getMapINLINE().findCity(getX_INLINE(), getY_INLINE(), getOwnerINLINE()); iBestValue = MAX_INT; pBestPlot = NULL; for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++) { pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI); if (pLoopPlot->isValidDomainForLocation(*this)) { if (canMoveInto(pLoopPlot)) { if (canEnterArea(pLoopPlot->getTeam(), pLoopPlot->area()) && !isEnemy(pLoopPlot->getTeam(), pLoopPlot)) { FAssertMsg(!atPlot(pLoopPlot), "atPlot(pLoopPlot) did not return false as expected"); if ((getDomainType() != DOMAIN_AIR) || pLoopPlot->isFriendlyCity(*this, true)) { if (pLoopPlot->isRevealed(getTeam(), false)) { iValue = (plotDistance(getX_INLINE(), getY_INLINE(), pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE()) * 2); if (pNearestCity != NULL) { iValue += plotDistance(pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE(), pNearestCity->getX_INLINE(), pNearestCity->getY_INLINE()); } if (getDomainType() == DOMAIN_SEA && !plot()->isWater()) { if (!pLoopPlot->isWater() || !pLoopPlot->isAdjacentToArea(area())) { iValue *= 3; } } else { if (pLoopPlot->area() != area()) { iValue *= 3; } } if (iValue < iBestValue) { iBestValue = iValue; pBestPlot = pLoopPlot; } } } } } } } bool bValid = true; if (pBestPlot != NULL) { setXY(pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE()); } else { kill(false); bValid = false; } return bValid; } bool CvUnit::canAutomate(AutomateTypes eAutomate) const { if (eAutomate == NO_AUTOMATE) { return false; } if (!isGroupHead()) { return false; } switch (eAutomate) { case AUTOMATE_BUILD: if ((AI_getUnitAIType() != UNITAI_WORKER) && (AI_getUnitAIType() != UNITAI_WORKER_SEA)) { return false; } break; case AUTOMATE_NETWORK: if ((AI_getUnitAIType() != UNITAI_WORKER) || !canBuildRoute()) { return false; } break; case AUTOMATE_CITY: if (AI_getUnitAIType() != UNITAI_WORKER) { return false; } break; case AUTOMATE_EXPLORE: if ((!canFight() && (getDomainType() != DOMAIN_SEA)) || (getDomainType() == DOMAIN_AIR) || (getDomainType() == DOMAIN_IMMOBILE)) { return false; } break; case AUTOMATE_RELIGION: if (AI_getUnitAIType() != UNITAI_MISSIONARY) { return false; } break; default: FAssert(false); break; } return true; } void CvUnit::automate(AutomateTypes eAutomate) { if (!canAutomate(eAutomate)) { return; } getGroup()->setAutomateType(eAutomate); } bool CvUnit::canScrap() const { if (plot()->isFighting()) { return false; } return true; } void CvUnit::scrap() { if (!canScrap()) { return; } //@MOD GFD: get gold when unit is killed by no_player inside its borders int iCost = (getUnitInfo().getProductionCost() * GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getTrainPercent()) / 100; GET_PLAYER(getOwnerINLINE()).changeGold(iCost / 4); //end mod kill(true); } bool CvUnit::canGift(bool bTestVisible, bool bTestTransport) { CvPlot* pPlot = plot(); CvUnit* pTransport = getTransportUnit(); if (!(pPlot->isOwned())) { return false; } if (pPlot->getOwnerINLINE() == getOwnerINLINE()) { return false; } if (pPlot->isVisibleEnemyUnit(this)) { return false; } if (pPlot->isVisibleEnemyUnit(pPlot->getOwnerINLINE())) { return false; } if (!pPlot->isValidDomainForLocation(*this) && NULL == pTransport) { return false; } for (int iCorp = 0; iCorp < GC.getNumCorporationInfos(); ++iCorp) { if (m_pUnitInfo->getCorporationSpreads(iCorp) > 0) { return false; } } if (bTestTransport) { if (pTransport && pTransport->getTeam() != pPlot->getTeam()) { return false; } } if (!bTestVisible) { if (GET_TEAM(pPlot->getTeam()).isUnitClassMaxedOut(getUnitClassType(), GET_TEAM(pPlot->getTeam()).getUnitClassMaking(getUnitClassType()))) { return false; } if (GET_PLAYER(pPlot->getOwnerINLINE()).isUnitClassMaxedOut(getUnitClassType(), GET_PLAYER(pPlot->getOwnerINLINE()).getUnitClassMaking(getUnitClassType()))) { return false; } if (!(GET_PLAYER(pPlot->getOwnerINLINE()).AI_acceptUnit(this))) { return false; } } return !atWar(pPlot->getTeam(), getTeam()); } void CvUnit::gift(bool bTestTransport) { CvUnit* pGiftUnit; CvWString szBuffer; PlayerTypes eOwner; if (!canGift(false, bTestTransport)) { return; } std::vector<CvUnit*> aCargoUnits; getCargoUnits(aCargoUnits); for (uint i = 0; i < aCargoUnits.size(); ++i) { aCargoUnits[i]->gift(false); } FAssertMsg(plot()->getOwnerINLINE() != NO_PLAYER, "plot()->getOwnerINLINE() is not expected to be equal with NO_PLAYER"); pGiftUnit = GET_PLAYER(plot()->getOwnerINLINE()).initUnit(getUnitType(), getX_INLINE(), getY_INLINE(), AI_getUnitAIType()); FAssertMsg(pGiftUnit != NULL, "GiftUnit is not assigned a valid value"); eOwner = getOwnerINLINE(); pGiftUnit->convert(this); GET_PLAYER(pGiftUnit->getOwnerINLINE()).AI_changePeacetimeGrantValue(eOwner, (pGiftUnit->getUnitInfo().getProductionCost() / 5)); szBuffer = gDLL->getText("TXT_KEY_MISC_GIFTED_UNIT_TO_YOU", GET_PLAYER(eOwner).getNameKey(), pGiftUnit->getNameKey()); gDLL->getInterfaceIFace()->addMessage(pGiftUnit->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_UNITGIFTED", MESSAGE_TYPE_INFO, pGiftUnit->getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_WHITE"), pGiftUnit->getX_INLINE(), pGiftUnit->getY_INLINE(), true, true); // Python Event CvEventReporter::getInstance().unitGifted(pGiftUnit, getOwnerINLINE(), plot()); } bool CvUnit::canLoadUnit(const CvUnit* pUnit, const CvPlot* pPlot) const { FAssert(pUnit != NULL); FAssert(pPlot != NULL); if (pUnit == this) { return false; } if (pUnit->getTeam() != getTeam()) { return false; } if (getCargo() > 0) { return false; } if (pUnit->isCargo()) { return false; } if (!(pUnit->cargoSpaceAvailable(getSpecialUnitType(), getDomainType()))) { return false; } if (!(pUnit->atPlot(pPlot))) { return false; } if (!m_pUnitInfo->isHiddenNationality() && pUnit->getUnitInfo().isHiddenNationality()) { return false; } if (NO_SPECIALUNIT != getSpecialUnitType()) { if (GC.getSpecialUnitInfo(getSpecialUnitType()).isCityLoad()) { if (!pPlot->isCity(true, getTeam())) { return false; } } } //Vincentz Load Unit if have moves if (!(canMove()) && !(pPlot->isWater())) { return false; } //Vincentz Load Unit if have moves end return true; } void CvUnit::loadUnit(CvUnit* pUnit) { if (!canLoadUnit(pUnit, plot())) { return; } setTransportUnit(pUnit); } bool CvUnit::shouldLoadOnMove(const CvPlot* pPlot) const { if (isCargo()) { return false; } switch (getDomainType()) { case DOMAIN_LAND: if (pPlot->isWater()) { return true; } break; case DOMAIN_AIR: if (!pPlot->isFriendlyCity(*this, true)) { return true; } if (m_pUnitInfo->getAirUnitCap() > 0) { if (pPlot->airUnitSpaceAvailable(getTeam()) <= 0) { return true; } } break; default: break; } if (m_pUnitInfo->getTerrainImpassable(pPlot->getTerrainType())) { TechTypes eTech = (TechTypes)m_pUnitInfo->getTerrainPassableTech(pPlot->getTerrainType()); if (NO_TECH == eTech || !GET_TEAM(getTeam()).isHasTech(eTech)) { return true; } } return false; } bool CvUnit::canLoad(const CvPlot* pPlot) const { PROFILE_FUNC(); FAssert(pPlot != NULL); CLLNode<IDInfo>* pUnitNode = pPlot->headUnitNode(); while (pUnitNode != NULL) { CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); if (canLoadUnit(pLoopUnit, pPlot)) { return true; } } return false; } void CvUnit::load() { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; CvPlot* pPlot; int iPass; if (!canLoad(plot())) { return; } pPlot = plot(); for (iPass = 0; iPass < 2; iPass++) { pUnitNode = pPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); if (canLoadUnit(pLoopUnit, pPlot)) { if ((iPass == 0) ? (pLoopUnit->getOwnerINLINE() == getOwnerINLINE()) : (pLoopUnit->getTeam() == getTeam())) { setTransportUnit(pLoopUnit); break; } } } if (isCargo()) { break; } } } bool CvUnit::canUnload() const { CvPlot& kPlot = *(plot()); if (getTransportUnit() == NULL) { return false; } if (!kPlot.isValidDomainForLocation(*this)) { return false; } if (getDomainType() == DOMAIN_AIR) { if (kPlot.isFriendlyCity(*this, true)) { int iNumAirUnits = kPlot.countNumAirUnits(getTeam()); CvCity* pCity = kPlot.getPlotCity(); if (NULL != pCity) { if (iNumAirUnits >= pCity->getAirUnitCapacity(getTeam())) { return false; } } else { if (iNumAirUnits >= GC.getDefineINT("CITY_AIR_UNIT_CAPACITY")) { return false; } } } } return true; } void CvUnit::unload() { if (!canUnload()) { return; } setTransportUnit(NULL); } bool CvUnit::canUnloadAll() const { if (getCargo() == 0) { return false; } return true; } void CvUnit::unloadAll() { if (!canUnloadAll()) { return; } std::vector<CvUnit*> aCargoUnits; getCargoUnits(aCargoUnits); for (uint i = 0; i < aCargoUnits.size(); ++i) { CvUnit* pCargo = aCargoUnits[i]; if (pCargo->canUnload()) { pCargo->setTransportUnit(NULL); } else { FAssert(isHuman() || pCargo->getDomainType() == DOMAIN_AIR); pCargo->getGroup()->setActivityType(ACTIVITY_AWAKE); } } } bool CvUnit::canHold(const CvPlot* pPlot) const { return true; } bool CvUnit::canSleep(const CvPlot* pPlot) const { if (isFortifyable()) { return false; } if (isWaiting()) { return false; } return true; } bool CvUnit::canFortify(const CvPlot* pPlot) const { if (!isFortifyable()) { return false; } if (isWaiting()) { return false; } return true; } bool CvUnit::canAirPatrol(const CvPlot* pPlot) const { if (getDomainType() != DOMAIN_AIR) { return false; } if (!canAirDefend(pPlot)) { return false; } if (isWaiting()) { return false; } return true; } bool CvUnit::canSeaPatrol(const CvPlot* pPlot) const { if (!pPlot->isWater()) { return false; } if (getDomainType() != DOMAIN_SEA) { return false; } if (!canFight() || isOnlyDefensive()) { return false; } if (isWaiting()) { return false; } return true; } void CvUnit::airCircle(bool bStart) { if (!GC.IsGraphicsInitialized()) { return; } if ((getDomainType() != DOMAIN_AIR) || (maxInterceptionProbability() == 0)) { return; } //cancel previos missions gDLL->getEntityIFace()->RemoveUnitFromBattle( this ); if (bStart) { CvAirMissionDefinition kDefinition; kDefinition.setPlot(plot()); kDefinition.setUnit(BATTLE_UNIT_ATTACKER, this); kDefinition.setUnit(BATTLE_UNIT_DEFENDER, NULL); kDefinition.setMissionType(MISSION_AIRPATROL); kDefinition.setMissionTime(1.0f); // patrol is indefinite - time is ignored gDLL->getEntityIFace()->AddMission( &kDefinition ); } } bool CvUnit::canHeal(const CvPlot* pPlot) const { if (!isHurt()) { return false; } //Vincentz Healing if (getGroup()->getActivityType() != ACTIVITY_HEAL && isWaiting()) // if (isWaiting()) { return false; } if (healRate(pPlot) <= 0) { return false; } //Vincentz Healing if (((currHitPoints() * 100) / maxHitPoints()) >= (healRate(pPlot) * 5)) { return false; } //Vincentz Healing end return true; } bool CvUnit::canSentry(const CvPlot* pPlot) const { if (!canDefend(pPlot)) { return false; } if (isWaiting()) { return false; } return true; } int CvUnit::healRate(const CvPlot* pPlot) const { PROFILE_FUNC(); CLLNode<IDInfo>* pUnitNode; CvCity* pCity; CvUnit* pLoopUnit; CvPlot* pLoopPlot; int iTotalHeal; int iHeal; int iBestHeal; int iI; pCity = pPlot->getPlotCity(); iTotalHeal = 0; if (pPlot->isCity(true, getTeam())) { //Vincentz Healing if (pCity && pCity->isOccupation()) { iTotalHeal += (GC.getDefineINT("ENEMY_HEAL_RATE") + getExtraEnemyHeal()); } else { iTotalHeal += GC.getDefineINT("CITY_HEAL_RATE") + (GET_TEAM(getTeam()).isFriendlyTerritory(pPlot->getTeam()) ? getExtraFriendlyHeal() : getExtraNeutralHeal()); if (pCity && !pCity->isOccupation()) { iTotalHeal += pCity->getHealRate(); } //Vincentz Healing } } else { if (!GET_TEAM(getTeam()).isFriendlyTerritory(pPlot->getTeam())) { if (isEnemy(pPlot->getTeam(), pPlot)) { iTotalHeal += (GC.getDefineINT("ENEMY_HEAL_RATE") + getExtraEnemyHeal()); } else { iTotalHeal += (GC.getDefineINT("NEUTRAL_HEAL_RATE") + getExtraNeutralHeal()); } } else { iTotalHeal += (GC.getDefineINT("FRIENDLY_HEAL_RATE") + getExtraFriendlyHeal()); } } // XXX optimize this (save it?) iBestHeal = 0; pUnitNode = pPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); if (pLoopUnit->getTeam() == getTeam()) // XXX what about alliances? { iHeal = pLoopUnit->getSameTileHeal(); if (iHeal > iBestHeal) { iBestHeal = iHeal; } } } for (iI = 0; iI < NUM_DIRECTION_TYPES; iI++) { pLoopPlot = plotDirection(pPlot->getX_INLINE(), pPlot->getY_INLINE(), ((DirectionTypes)iI)); if (pLoopPlot != NULL) { if (pLoopPlot->area() == pPlot->area()) { pUnitNode = pLoopPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pLoopPlot->nextUnitNode(pUnitNode); if (pLoopUnit->getTeam() == getTeam()) // XXX what about alliances? { iHeal = pLoopUnit->getAdjacentTileHeal(); if (iHeal > iBestHeal) { iBestHeal = iHeal; } } } } } } iTotalHeal += iBestHeal; // XXX return iTotalHeal; } int CvUnit::healTurns(const CvPlot* pPlot) const { int iHeal; int iTurns; if (!isHurt()) { return 0; } iHeal = healRate(pPlot); if (iHeal > 0) { iTurns = (getDamage() / iHeal); if ((getDamage() % iHeal) != 0) { iTurns++; } return iTurns; } else { return MAX_INT; } } void CvUnit::doHeal() // Vincentz Healing Cost { if (((currHitPoints() * 100) / maxHitPoints()) < (healRate(plot())) * 5) { if (GC.getGameINLINE().isOption(GAMEOPTION_HEALING_COST_GOLD)) { int unitHealCost = (GC.getDefineINT("UNITHEAL_COSTMODIFIER") * healRate(plot()) * getUnitInfo().getProductionCost() * GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getTrainPercent()); if (isHuman()) { unitHealCost *= (GC.getHandicapInfo(getHandicapType()).getUnitCostPercent()); unitHealCost /= 50; } if (getDamage() - healRate(plot()) < 0) { unitHealCost *= getDamage(); unitHealCost /= healRate(plot()); } unitHealCost /= 100 * 100 * 100; if (GET_PLAYER(getOwnerINLINE()).getGold() > unitHealCost) { // CvWString szBuffer = gDLL->getText("TXT_KEY_HEALING_COST", healRate(plot()), getUnitInfo().getProductionCost(), getDamage(), GC.getDefineINT("UNITHEAL_COSTMODIFIER"), unitHealCost, unitHealCost+1); // gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_WONDER_UNIT_BUILD", MESSAGE_TYPE_MAJOR_EVENT, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_UNIT_TEXT"), getX_INLINE(), getY_INLINE(), true, true); changeDamage(-(healRate(plot()))); GET_PLAYER(getOwnerINLINE()).changeGold(-(unitHealCost + 1)); } } else { changeDamage(-(healRate(plot()))); } } } // Vincentz Healing end bool CvUnit::canAirlift(const CvPlot* pPlot) const { CvCity* pCity; if (getDomainType() != DOMAIN_LAND) { return false; } if (hasMoved()) { return false; } pCity = pPlot->getPlotCity(); if (pCity == NULL) { return false; } if (pCity->getCurrAirlift() >= pCity->getMaxAirlift()) { return false; } if (pCity->getTeam() != getTeam()) { return false; } return true; } bool CvUnit::canAirliftAt(const CvPlot* pPlot, int iX, int iY) const { CvPlot* pTargetPlot; CvCity* pTargetCity; if (!canAirlift(pPlot)) { return false; } pTargetPlot = GC.getMapINLINE().plotINLINE(iX, iY); if (!canMoveInto(pTargetPlot)) { return false; } pTargetCity = pTargetPlot->getPlotCity(); if (pTargetCity == NULL) { return false; } if (pTargetCity->isAirliftTargeted()) { return false; } if (pTargetCity->getTeam() != getTeam() && !GET_TEAM(pTargetCity->getTeam()).isVassal(getTeam())) { return false; } return true; } bool CvUnit::airlift(int iX, int iY) { CvCity* pCity; CvCity* pTargetCity; CvPlot* pTargetPlot; if (!canAirliftAt(plot(), iX, iY)) { return false; } pCity = plot()->getPlotCity(); FAssert(pCity != NULL); pTargetPlot = GC.getMapINLINE().plotINLINE(iX, iY); FAssert(pTargetPlot != NULL); pTargetCity = pTargetPlot->getPlotCity(); FAssert(pTargetCity != NULL); FAssert(pCity != pTargetCity); pCity->changeCurrAirlift(1); if (pTargetCity->getMaxAirlift() == 0) { pTargetCity->setAirliftTargeted(true); } finishMoves(); setXY(pTargetPlot->getX_INLINE(), pTargetPlot->getY_INLINE()); return true; } bool CvUnit::isNukeVictim(const CvPlot* pPlot, TeamTypes eTeam) const { CvPlot* pLoopPlot; int iDX, iDY; if (!(GET_TEAM(eTeam).isAlive())) { return false; } if (eTeam == getTeam()) { return false; } for (iDX = -(nukeRange()); iDX <= nukeRange(); iDX++) { for (iDY = -(nukeRange()); iDY <= nukeRange(); iDY++) { pLoopPlot = plotXY(pPlot->getX_INLINE(), pPlot->getY_INLINE(), iDX, iDY); if (pLoopPlot != NULL) { if (pLoopPlot->getTeam() == eTeam) { return true; } if (pLoopPlot->plotCheck(PUF_isCombatTeam, eTeam, getTeam()) != NULL) { return true; } } } } return false; } bool CvUnit::canNuke(const CvPlot* pPlot) const { if (nukeRange() == -1) { return false; } return true; } bool CvUnit::canNukeAt(const CvPlot* pPlot, int iX, int iY) const { CvPlot* pTargetPlot; int iI; if (!canNuke(pPlot)) { return false; } int iDistance = plotDistance(pPlot->getX_INLINE(), pPlot->getY_INLINE(), iX, iY); if (iDistance <= nukeRange()) { return false; } if (airRange() > 0 && iDistance > airRange()) { return false; } pTargetPlot = GC.getMapINLINE().plotINLINE(iX, iY); for (iI = 0; iI < MAX_TEAMS; iI++) { if (isNukeVictim(pTargetPlot, ((TeamTypes)iI))) { if (!isEnemy((TeamTypes)iI, pPlot)) { return false; } } } return true; } bool CvUnit::nuke(int iX, int iY) { CvPlot* pPlot; CvWString szBuffer; bool abTeamsAffected[MAX_TEAMS]; TeamTypes eBestTeam; int iBestInterception; int iI, iJ, iK; if (!canNukeAt(plot(), iX, iY)) { return false; } pPlot = GC.getMapINLINE().plotINLINE(iX, iY); for (iI = 0; iI < MAX_TEAMS; iI++) { abTeamsAffected[iI] = isNukeVictim(pPlot, ((TeamTypes)iI)); } for (iI = 0; iI < MAX_TEAMS; iI++) { if (abTeamsAffected[iI]) { if (!isEnemy((TeamTypes)iI)) { GET_TEAM(getTeam()).declareWar(((TeamTypes)iI), false, WARPLAN_LIMITED); } } } iBestInterception = 0; eBestTeam = NO_TEAM; for (iI = 0; iI < MAX_TEAMS; iI++) { if (abTeamsAffected[iI]) { if (GET_TEAM((TeamTypes)iI).getNukeInterception() > iBestInterception) { iBestInterception = GET_TEAM((TeamTypes)iI).getNukeInterception(); eBestTeam = ((TeamTypes)iI); } } } iBestInterception *= (100 - m_pUnitInfo->getEvasionProbability()); iBestInterception /= 100; setReconPlot(pPlot); if (GC.getGameINLINE().getSorenRandNum(100, "Nuke") < iBestInterception) { for (iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { szBuffer = gDLL->getText("TXT_KEY_MISC_NUKE_INTERCEPTED", GET_PLAYER(getOwnerINLINE()).getNameKey(), getNameKey(), GET_TEAM(eBestTeam).getName().GetCString()); gDLL->getInterfaceIFace()->addMessage(((PlayerTypes)iI), (((PlayerTypes)iI) == getOwnerINLINE()), GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_NUKE_INTERCEPTED", MESSAGE_TYPE_MAJOR_EVENT, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE(), true, true); } } if (pPlot->isActiveVisible(false)) { // Nuke entity mission CvMissionDefinition kDefiniton; kDefiniton.setMissionTime(GC.getMissionInfo(MISSION_NUKE).getTime() * gDLL->getSecsPerTurn()); kDefiniton.setMissionType(MISSION_NUKE); kDefiniton.setPlot(pPlot); kDefiniton.setUnit(BATTLE_UNIT_ATTACKER, this); kDefiniton.setUnit(BATTLE_UNIT_DEFENDER, this); // Add the intercepted mission (defender is not NULL) gDLL->getEntityIFace()->AddMission(&kDefiniton); } kill(true); return true; // Intercepted!!! (XXX need special event for this...) } if (pPlot->isActiveVisible(false)) { // Nuke entity mission CvMissionDefinition kDefiniton; kDefiniton.setMissionTime(GC.getMissionInfo(MISSION_NUKE).getTime() * gDLL->getSecsPerTurn()); kDefiniton.setMissionType(MISSION_NUKE); kDefiniton.setPlot(pPlot); kDefiniton.setUnit(BATTLE_UNIT_ATTACKER, this); kDefiniton.setUnit(BATTLE_UNIT_DEFENDER, NULL); // Add the non-intercepted mission (defender is NULL) gDLL->getEntityIFace()->AddMission(&kDefiniton); } setMadeAttack(true); setAttackPlot(pPlot, false); for (iI = 0; iI < MAX_TEAMS; iI++) { if (abTeamsAffected[iI]) { GET_TEAM((TeamTypes)iI).changeWarWeariness(getTeam(), 100 * GC.getDefineINT("WW_HIT_BY_NUKE")); GET_TEAM(getTeam()).changeWarWeariness(((TeamTypes)iI), 100 * GC.getDefineINT("WW_ATTACKED_WITH_NUKE")); GET_TEAM(getTeam()).AI_changeWarSuccess(((TeamTypes)iI), GC.getDefineINT("WAR_SUCCESS_NUKE")); } } for (iI = 0; iI < MAX_TEAMS; iI++) { if (GET_TEAM((TeamTypes)iI).isAlive()) { if (iI != getTeam()) { if (abTeamsAffected[iI]) { for (iJ = 0; iJ < MAX_PLAYERS; iJ++) { if (GET_PLAYER((PlayerTypes)iJ).isAlive()) { if (GET_PLAYER((PlayerTypes)iJ).getTeam() == ((TeamTypes)iI)) { GET_PLAYER((PlayerTypes)iJ).AI_changeMemoryCount(getOwnerINLINE(), MEMORY_NUKED_US, 1); } } } } else { for (iJ = 0; iJ < MAX_TEAMS; iJ++) { if (GET_TEAM((TeamTypes)iJ).isAlive()) { if (abTeamsAffected[iJ]) { if (GET_TEAM((TeamTypes)iI).isHasMet((TeamTypes)iJ)) { if (GET_TEAM((TeamTypes)iI).AI_getAttitude((TeamTypes)iJ) >= ATTITUDE_CAUTIOUS) { for (iK = 0; iK < MAX_PLAYERS; iK++) { if (GET_PLAYER((PlayerTypes)iK).isAlive()) { if (GET_PLAYER((PlayerTypes)iK).getTeam() == ((TeamTypes)iI)) { GET_PLAYER((PlayerTypes)iK).AI_changeMemoryCount(getOwnerINLINE(), MEMORY_NUKED_FRIEND, 1); } } } break; } } } } } } } } } // XXX some AI should declare war here... for (iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { szBuffer = gDLL->getText("TXT_KEY_MISC_NUKE_LAUNCHED", GET_PLAYER(getOwnerINLINE()).getNameKey(), getNameKey()); gDLL->getInterfaceIFace()->addMessage(((PlayerTypes)iI), (((PlayerTypes)iI) == getOwnerINLINE()), GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_NUKE_EXPLODES", MESSAGE_TYPE_MAJOR_EVENT, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE(), true, true); } } if (isSuicide()) { kill(true); } return true; } bool CvUnit::canRecon(const CvPlot* pPlot) const { if (getDomainType() != DOMAIN_AIR) { return false; } if (airRange() == 0) { return false; } if (m_pUnitInfo->isSuicide()) { return false; } return true; } bool CvUnit::canReconAt(const CvPlot* pPlot, int iX, int iY) const { if (!canRecon(pPlot)) { return false; } int iDistance = plotDistance(pPlot->getX_INLINE(), pPlot->getY_INLINE(), iX, iY); if (iDistance > airRange() || 0 == iDistance) { return false; } return true; } bool CvUnit::recon(int iX, int iY) { CvPlot* pPlot; if (!canReconAt(plot(), iX, iY)) { return false; } pPlot = GC.getMapINLINE().plotINLINE(iX, iY); setReconPlot(pPlot); //Vincentz Moves changeMoves(GC.getMOVE_DENOMINATOR()); // finishMoves(); if (pPlot->isActiveVisible(false)) { CvAirMissionDefinition kAirMission; kAirMission.setMissionType(MISSION_RECON); kAirMission.setUnit(BATTLE_UNIT_ATTACKER, this); kAirMission.setUnit(BATTLE_UNIT_DEFENDER, NULL); kAirMission.setDamage(BATTLE_UNIT_DEFENDER, 0); kAirMission.setDamage(BATTLE_UNIT_ATTACKER, 0); kAirMission.setPlot(pPlot); kAirMission.setMissionTime(GC.getMissionInfo((MissionTypes)MISSION_RECON).getTime() * gDLL->getSecsPerTurn()); gDLL->getEntityIFace()->AddMission(&kAirMission); } return true; } bool CvUnit::canParadrop(const CvPlot* pPlot) const { if (getDropRange() <= 0) { return false; } if (hasMoved()) { return false; } if (!pPlot->isFriendlyCity(*this, true)) { return false; } return true; } bool CvUnit::canParadropAt(const CvPlot* pPlot, int iX, int iY) const { if (!canParadrop(pPlot)) { return false; } CvPlot* pTargetPlot = GC.getMapINLINE().plotINLINE(iX, iY); if (NULL == pTargetPlot || pTargetPlot == pPlot) { return false; } if (!pTargetPlot->isVisible(getTeam(), false)) { return false; } if (!canMoveInto(pTargetPlot, false, false, true)) { return false; } if (plotDistance(pPlot->getX_INLINE(), pPlot->getY_INLINE(), iX, iY) > getDropRange()) { return false; } if (!canCoexistWithEnemyUnit(NO_TEAM)) { if (pTargetPlot->isEnemyCity(*this)) { return false; } if (pTargetPlot->isVisibleEnemyUnit(this)) { return false; } } return true; } bool CvUnit::paradrop(int iX, int iY) { if (!canParadropAt(plot(), iX, iY)) { return false; } CvPlot* pPlot = GC.getMapINLINE().plotINLINE(iX, iY); changeMoves(GC.getMOVE_DENOMINATOR() * GC.getDefineINT("MOVE_MULTIPLIER") * 2); // setMadeAttack(true); Vincentz Paratrooper setXY(pPlot->getX_INLINE(), pPlot->getY_INLINE()); //check if intercepted if(interceptTest(pPlot)) { return true; } //play paradrop animation by itself if (pPlot->isActiveVisible(false)) { CvAirMissionDefinition kAirMission; kAirMission.setMissionType(MISSION_PARADROP); kAirMission.setUnit(BATTLE_UNIT_ATTACKER, this); kAirMission.setUnit(BATTLE_UNIT_DEFENDER, NULL); kAirMission.setDamage(BATTLE_UNIT_DEFENDER, 0); kAirMission.setDamage(BATTLE_UNIT_ATTACKER, 0); kAirMission.setPlot(pPlot); kAirMission.setMissionTime(GC.getMissionInfo((MissionTypes)MISSION_PARADROP).getTime() * gDLL->getSecsPerTurn()); gDLL->getEntityIFace()->AddMission(&kAirMission); } return true; } bool CvUnit::canAirBomb(const CvPlot* pPlot) const { if (getDomainType() != DOMAIN_AIR) { return false; } if (airBombBaseRate() == 0) { return false; } if (isMadeAttack()) { return false; } return true; } bool CvUnit::canAirBombAt(const CvPlot* pPlot, int iX, int iY) const { CvCity* pCity; CvPlot* pTargetPlot; if (!canAirBomb(pPlot)) { return false; } pTargetPlot = GC.getMapINLINE().plotINLINE(iX, iY); if (plotDistance(pPlot->getX_INLINE(), pPlot->getY_INLINE(), pTargetPlot->getX_INLINE(), pTargetPlot->getY_INLINE()) > airRange()) { return false; } if (pTargetPlot->isOwned()) { if (!potentialWarAction(pTargetPlot)) { return false; } } pCity = pTargetPlot->getPlotCity(); if (pCity != NULL) { if (!(pCity->isBombardable(this))) { return false; } } else { //Vincentz Cannot bombard negative improvement costs if (pTargetPlot->getImprovementType() == NO_IMPROVEMENT && pTargetPlot->getRouteType() == NO_ROUTE) { return false; } // < Air Combat Experience Start > if (pTargetPlot->getImprovementType() != NO_IMPROVEMENT) { if (GC.getImprovementInfo(pTargetPlot->getImprovementType()).isPermanent()) { return false; } if (GC.getImprovementInfo(pTargetPlot->getImprovementType()).getAirBombDefense() == -1) { return false; } } if (GC.getGameINLINE().isRouteDestructionThroughAirBombs()) { if (pTargetPlot->getRouteType() != NO_ROUTE && GC.getRouteInfo(pTargetPlot->getRouteType()).getAirBombDefense() == -1) { return false; } } // < Air Combat Experience End > } return true; } bool CvUnit::airBomb(int iX, int iY) { CvCity* pCity; CvPlot* pPlot; CvWString szBuffer; if (!canAirBombAt(plot(), iX, iY)) { return false; } pPlot = GC.getMapINLINE().plotINLINE(iX, iY); if (!isEnemy(pPlot->getTeam())) { getGroup()->groupDeclareWar(pPlot, true); } // < Air Combat Experience Start > if (!isEnemy(pPlot->getTeam()) && !GC.getGameINLINE().isBombNoMansLand()) { return false; } // < Air Combat Experience End > if (interceptTest(pPlot)) { return true; } pCity = pPlot->getPlotCity(); if (pCity != NULL) { //Vincentz Randomized Airbomb pCity->changeDefenseModifier((-airBombCurrRate() * 50 + GC.getGameINLINE().getSorenRandNum(100, "Air Bomb - Random")) / 100); szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_DEFENSES_REDUCED_TO", pCity->getNameKey(), pCity->getDefenseModifier(false), getNameKey()); gDLL->getInterfaceIFace()->addMessage(pCity->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_BOMBARDED", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pCity->getX_INLINE(), pCity->getY_INLINE(), true, true); szBuffer = gDLL->getText("TXT_KEY_MISC_ENEMY_DEFENSES_REDUCED_TO", getNameKey(), pCity->getNameKey(), pCity->getDefenseModifier(false)); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_BOMBARD", MESSAGE_TYPE_INFO, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pCity->getX_INLINE(), pCity->getY_INLINE()); // < Air Combat Experience Start > if (GC.getGameINLINE().isExperienceGainByAttackingCities()) { int iExperience = (int)((attackXPValue()*((float)pCity->getDefenseModifier(false) / 100)) / 1.25); iExperience = range(iExperience, GC.getDefineINT("MIN_EXPERIENCE_PER_COMBAT"), GC.getDefineINT("MAX_EXPERIENCE_PER_COMBAT")); changeExperience(iExperience, maxXPValue(), false, pPlot->getOwnerINLINE() == getOwnerINLINE(), !isBarbarian()); } // < Air Combat Experience End > } else { if (pPlot->getImprovementType() != NO_IMPROVEMENT) { if (GC.getGameINLINE().getSorenRandNum(airBombCurrRate(), "Air Bomb - Offense") >= GC.getGameINLINE().getSorenRandNum(GC.getImprovementInfo(pPlot->getImprovementType()).getAirBombDefense(), "Air Bomb - Defense")) { szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_UNIT_DESTROYED_IMP", getNameKey(), GC.getImprovementInfo(pPlot->getImprovementType()).getTextKeyWide()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_PILLAGE", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); if (pPlot->isOwned()) { szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_IMP_WAS_DESTROYED", GC.getImprovementInfo(pPlot->getImprovementType()).getTextKeyWide(), getNameKey(), getVisualCivAdjective(pPlot->getTeam())); gDLL->getInterfaceIFace()->addMessage(pPlot->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_PILLAGED", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE(), true, true); } // < Air Combat Experience Start > if (GC.getGameINLINE().isExperienceGainByDestroyingImprovements()) { int iExperience = 0; iExperience = (GC.getImprovementInfo(pPlot->getImprovementType()).getAirBombDefense() / 10); iExperience = range(iExperience, GC.getDefineINT("MIN_EXPERIENCE_PER_COMBAT"), GC.getDefineINT("MAX_EXPERIENCE_PER_COMBAT")); changeExperience(iExperience, maxXPValue(), false, pPlot->getOwnerINLINE() == getOwnerINLINE(), !isBarbarian()); } // < Air Combat Experience End > pPlot->setImprovementType((ImprovementTypes)(GC.getImprovementInfo(pPlot->getImprovementType()).getImprovementPillage())); } else { szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_UNIT_FAIL_DESTROY_IMP", getNameKey(), GC.getImprovementInfo(pPlot->getImprovementType()).getTextKeyWide()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_BOMB_FAILS", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); } } // < Air Combat Experience Start > else if (pPlot->getRouteType() != NO_ROUTE) { if (GC.getGameINLINE().isRouteDestructionThroughAirBombs()) { if (GC.getGameINLINE().getSorenRandNum(airBombCurrRate(), "Air Bomb - Offense") >= GC.getGameINLINE().getSorenRandNum(GC.getRouteInfo(pPlot->getRouteType()).getAirBombDefense(), "Air Bomb - Defense")) { szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_UNIT_DESTROYED_ROUTE", getNameKey(), GC.getRouteInfo(pPlot->getRouteType()).getTextKeyWide()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_PILLAGE", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); if (pPlot->isOwned()) { szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_ROUTE_WAS_DESTROYED", GC.getRouteInfo(pPlot->getRouteType()).getTextKeyWide(), getNameKey(), getVisualCivAdjective(pPlot->getTeam())); gDLL->getInterfaceIFace()->addMessage(pPlot->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_PILLAGED", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE(), true, true); } if (GC.getGameINLINE().isExperienceGainByDestroyingRoutes()) { int iExperience = 0; iExperience = (GC.getRouteInfo(pPlot->getRouteType()).getAirBombDefense() / 10); iExperience = range(iExperience, GC.getDefineINT("MIN_EXPERIENCE_PER_COMBAT"), GC.getDefineINT("MAX_EXPERIENCE_PER_COMBAT")); changeExperience(iExperience, maxXPValue(), false, pPlot->getOwnerINLINE() == getOwnerINLINE(), !isBarbarian()); } pPlot->setRouteType(NO_ROUTE, true); } else { szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_UNIT_FAIL_DESTROY_ROUTE", getNameKey(), GC.getRouteInfo(pPlot->getRouteType()).getTextKeyWide()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_BOMB_FAILS", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); } } } // < Air Combat Experience End > } setReconPlot(pPlot); setMadeAttack(true); //Vincentz Moves extra move for airbomb changeMoves(GC.getMOVE_DENOMINATOR() * 2); if (pPlot->isActiveVisible(false)) { CvAirMissionDefinition kAirMission; kAirMission.setMissionType(MISSION_AIRBOMB); kAirMission.setUnit(BATTLE_UNIT_ATTACKER, this); kAirMission.setUnit(BATTLE_UNIT_DEFENDER, NULL); kAirMission.setDamage(BATTLE_UNIT_DEFENDER, 0); kAirMission.setDamage(BATTLE_UNIT_ATTACKER, 0); kAirMission.setPlot(pPlot); kAirMission.setMissionTime(GC.getMissionInfo((MissionTypes)MISSION_AIRBOMB).getTime() * gDLL->getSecsPerTurn()); gDLL->getEntityIFace()->AddMission(&kAirMission); } if (isSuicide()) { kill(true); } return true; } CvCity* CvUnit::bombardTarget(const CvPlot* pPlot) const { int iBestValue = MAX_INT; CvCity* pBestCity = NULL; for (int iI = 0; iI < NUM_DIRECTION_TYPES; iI++) { CvPlot* pLoopPlot = plotDirection(pPlot->getX_INLINE(), pPlot->getY_INLINE(), ((DirectionTypes)iI)); if (pLoopPlot != NULL) { CvCity* pLoopCity = pLoopPlot->getPlotCity(); if (pLoopCity != NULL) { if (pLoopCity->isBombardable(this)) { int iValue = pLoopCity->getDefenseDamage(); // always prefer cities we are at war with if (isEnemy(pLoopCity->getTeam(), pPlot)) { iValue *= 128; } if (iValue < iBestValue) { iBestValue = iValue; pBestCity = pLoopCity; } } } } } return pBestCity; } bool CvUnit::canBombard(const CvPlot* pPlot) const { if (bombardRate() <= 0) { return false; } if (isMadeAttack()) { return false; } if (isCargo()) { return false; } if (bombardTarget(pPlot) == NULL) { return false; } return true; } bool CvUnit::bombard() { CvPlot* pPlot = plot(); if (!canBombard(pPlot)) { return false; } CvCity* pBombardCity = bombardTarget(pPlot); FAssertMsg(pBombardCity != NULL, "BombardCity is not assigned a valid value"); CvPlot* pTargetPlot = pBombardCity->plot(); if (!isEnemy(pTargetPlot->getTeam())) { getGroup()->groupDeclareWar(pTargetPlot, true); } if (!isEnemy(pTargetPlot->getTeam())) { return false; } int iBombardModifier = 0; if (!ignoreBuildingDefense()) { iBombardModifier -= pBombardCity->getBuildingBombardDefense(); } //Vincentz Bombard random int RandomBombardChance = GC.getGameINLINE().getSorenRandNum(100, "RandomHit"); int RandomBombardDamage = 50 + GC.getGameINLINE().getSorenRandNum(100, "RandomDamage"); if (RandomBombardChance > (bombardRate() + GC.getDefineINT("BOMBARD_HIT_CHANCE"))) { CvWString szBuffer = gDLL->getText("TXT_KEY_MISC_DEFENSES_IN_CITY_MISSED", pBombardCity->getNameKey(), pBombardCity->getDefenseModifier(false), GET_PLAYER(getOwnerINLINE()).getNameKey()); gDLL->getInterfaceIFace()->addMessage(pBombardCity->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_BOMBARDED", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pBombardCity->getX_INLINE(), pBombardCity->getY_INLINE(), true, true); szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_MISSED_CITY_DEFENSES", getNameKey(), pBombardCity->getNameKey(), pBombardCity->getDefenseModifier(false)); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_BOMBARD", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pBombardCity->getX_INLINE(), pBombardCity->getY_INLINE()); } else { pBombardCity->changeDefenseModifier(-(bombardRate() * currHitPoints() / maxHitPoints() * RandomBombardDamage * std::max(0, 100 + iBombardModifier)) / (100 * 100)); CvWString szBuffer = gDLL->getText("TXT_KEY_MISC_DEFENSES_IN_CITY_REDUCED_TO", pBombardCity->getNameKey(), pBombardCity->getDefenseModifier(false), GET_PLAYER(getOwnerINLINE()).getNameKey()); gDLL->getInterfaceIFace()->addMessage(pBombardCity->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_BOMBARDED", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pBombardCity->getX_INLINE(), pBombardCity->getY_INLINE(), true, true); szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_REDUCE_CITY_DEFENSES", getNameKey(), pBombardCity->getNameKey(), pBombardCity->getDefenseModifier(false)); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_BOMBARD", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pBombardCity->getX_INLINE(), pBombardCity->getY_INLINE()); if (RandomBombardDamage > 75) { changeExperience(1); } } setMadeAttack(true); // changeMoves(GC.getMOVE_DENOMINATOR()); Vincentz Bombard extracost if (getDomainType() == DOMAIN_LAND) { finishMoves(); } else { changeMoves(GC.getMOVE_DENOMINATOR() * GC.getDefineINT("MOVE_MULTIPLIER")); } /* // < Bombard Experience Start > int iExperience = (int)((attackXPValue()*((float)pBombardCity->getDefenseModifier(false)/100))/1.25); iExperience = range(iExperience, GC.getDefineINT("MIN_EXPERIENCE_PER_COMBAT"), GC.getDefineINT("MAX_EXPERIENCE_PER_COMBAT")); changeExperience(iExperience, maxXPValue(), false, pPlot->getOwnerINLINE() == getOwnerINLINE(), !isBarbarian()); // <Bombard Experience End > */ if (pPlot->isActiveVisible(false)) { CvUnit *pDefender = pBombardCity->plot()->getBestDefender(NO_PLAYER, getOwnerINLINE(), this, true); // Bombard entity mission CvMissionDefinition kDefiniton; kDefiniton.setMissionTime(GC.getMissionInfo(MISSION_BOMBARD).getTime() * gDLL->getSecsPerTurn()); kDefiniton.setMissionType(MISSION_BOMBARD); kDefiniton.setPlot(pBombardCity->plot()); kDefiniton.setUnit(BATTLE_UNIT_ATTACKER, this); kDefiniton.setUnit(BATTLE_UNIT_DEFENDER, pDefender); gDLL->getEntityIFace()->AddMission(&kDefiniton); } return true; } bool CvUnit::canPillage(const CvPlot* pPlot) const { if (!(m_pUnitInfo->isPillage())) { return false; } if (pPlot->isCity()) { return false; } //Vincentz Cannot pillage negative improvement cost if ((pPlot->getImprovementType() == NO_IMPROVEMENT) || (GC.getImprovementInfo(pPlot->getImprovementType()).getPillageGold() < 0)) { if (!(pPlot->isRoute())) { return false; } } else { if (GC.getImprovementInfo(pPlot->getImprovementType()).isPermanent()) { return false; } } if (pPlot->isOwned()) { if (!potentialWarAction(pPlot)) { if ((pPlot->getImprovementType() == NO_IMPROVEMENT) || (pPlot->getOwnerINLINE() != getOwnerINLINE())) { return false; } } } if (!(pPlot->isValidDomainForAction(*this))) { return false; } return true; } bool CvUnit::pillage() { CvWString szBuffer; int iPillageGold; long lPillageGold; ImprovementTypes eTempImprovement = NO_IMPROVEMENT; RouteTypes eTempRoute = NO_ROUTE; CvPlot* pPlot = plot(); if (!canPillage(pPlot)) { return false; } if (pPlot->isOwned()) { // we should not be calling this without declaring war first, so do not declare war here if (!isEnemy(pPlot->getTeam(), pPlot)) { if ((pPlot->getImprovementType() == NO_IMPROVEMENT) || (pPlot->getOwnerINLINE() != getOwnerINLINE())) { return false; } } } if (pPlot->isWater()) { CvUnit* pInterceptor = bestSeaPillageInterceptor(this, GC.getDefineINT("COMBAT_DIE_SIDES") / 2); if (NULL != pInterceptor) { setMadeAttack(false); int iWithdrawal = withdrawalProbability(); changeExtraWithdrawal(-iWithdrawal); // no withdrawal since we are really the defender attack(pInterceptor->plot(), false); changeExtraWithdrawal(iWithdrawal); return false; } } //Vincentz Cannot pillage negative improvement costs if ((pPlot->getImprovementType() != NO_IMPROVEMENT) && !(GC.getImprovementInfo(pPlot->getImprovementType()).getPillageGold() < 0)) { eTempImprovement = pPlot->getImprovementType(); if (pPlot->getTeam() != getTeam()) { // Use python to determine pillage amounts... lPillageGold = 0; CyPlot* pyPlot = new CyPlot(pPlot); CyUnit* pyUnit = new CyUnit(this); CyArgsList argsList; argsList.add(gDLL->getPythonIFace()->makePythonObject(pyPlot)); // pass in plot class argsList.add(gDLL->getPythonIFace()->makePythonObject(pyUnit)); // pass in unit class gDLL->getPythonIFace()->callFunction(PYGameModule, "doPillageGold", argsList.makeFunctionArgs(),&lPillageGold); delete pyPlot; // python fxn must not hold on to this pointer delete pyUnit; // python fxn must not hold on to this pointer iPillageGold = (int)lPillageGold; if (iPillageGold > 0) { GET_PLAYER(getOwnerINLINE()).changeGold(iPillageGold); szBuffer = gDLL->getText("TXT_KEY_MISC_PLUNDERED_GOLD_FROM_IMP", iPillageGold, GC.getImprovementInfo(pPlot->getImprovementType()).getTextKeyWide()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_PILLAGE", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); if (pPlot->isOwned()) { szBuffer = gDLL->getText("TXT_KEY_MISC_IMP_DESTROYED", GC.getImprovementInfo(pPlot->getImprovementType()).getTextKeyWide(), getNameKey(), getVisualCivAdjective(pPlot->getTeam())); gDLL->getInterfaceIFace()->addMessage(pPlot->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_PILLAGED", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE(), true, true); } } } pPlot->setImprovementType((ImprovementTypes)(GC.getImprovementInfo(pPlot->getImprovementType()).getImprovementPillage())); } else if (pPlot->isRoute()) { eTempRoute = pPlot->getRouteType(); pPlot->setRouteType(NO_ROUTE, true); // XXX downgrade rail??? } //Vincentz Move changeMoves(GC.getMOVE_DENOMINATOR() * GC.getDefineINT("MOVE_MULTIPLIER")); if (pPlot->isActiveVisible(false)) { // Pillage entity mission CvMissionDefinition kDefiniton; kDefiniton.setMissionTime(GC.getMissionInfo(MISSION_PILLAGE).getTime() * gDLL->getSecsPerTurn()); kDefiniton.setMissionType(MISSION_PILLAGE); kDefiniton.setPlot(pPlot); kDefiniton.setUnit(BATTLE_UNIT_ATTACKER, this); kDefiniton.setUnit(BATTLE_UNIT_DEFENDER, NULL); gDLL->getEntityIFace()->AddMission(&kDefiniton); } if (eTempImprovement != NO_IMPROVEMENT || eTempRoute != NO_ROUTE) { CvEventReporter::getInstance().unitPillage(this, eTempImprovement, eTempRoute, getOwnerINLINE()); } return true; } bool CvUnit::canPlunder(const CvPlot* pPlot, bool bTestVisible) const { /* Vincentz Plunder if (getDomainType() != DOMAIN_SEA) { return false; } */ if (!(m_pUnitInfo->isPillage())) { return false; } /* if (!pPlot->isWater()) { return false; } if (pPlot->isFreshWater()) { return false; } */ if (!pPlot->isValidDomainForAction(*this)) { return false; } if (!bTestVisible) { if (pPlot->getTeam() == getTeam()) { return false; } } return true; } bool CvUnit::plunder() { CvPlot* pPlot = plot(); if (!canPlunder(pPlot)) { return false; } setBlockading(true); finishMoves(); return true; } void CvUnit::updatePlunder(int iChange, bool bUpdatePlotGroups) { int iBlockadeRange = GC.getDefineINT("SHIP_BLOCKADE_RANGE"); bool bOldTradeNet; bool bChanged = false; for (int iTeam = 0; iTeam < MAX_TEAMS; ++iTeam) { if (isEnemy((TeamTypes)iTeam)) { for (int i = -iBlockadeRange; i <= iBlockadeRange; ++i) { for (int j = -iBlockadeRange; j <= iBlockadeRange; ++j) { CvPlot* pLoopPlot = ::plotXY(getX_INLINE(), getY_INLINE(), i, j); // if (NULL != pLoopPlot && pLoopPlot->isWater() && pLoopPlot->area() == area()) Vincentz if (NULL != pLoopPlot && pLoopPlot->area() == area()) { if (!bChanged) { bOldTradeNet = pLoopPlot->isTradeNetwork((TeamTypes)iTeam); } pLoopPlot->changeBlockadedCount((TeamTypes)iTeam, iChange); if (!bChanged) { bChanged = (bOldTradeNet != pLoopPlot->isTradeNetwork((TeamTypes)iTeam)); } } } } } } if (bChanged) { gDLL->getInterfaceIFace()->setDirty(BlockadedPlots_DIRTY_BIT, true); if (bUpdatePlotGroups) { GC.getGameINLINE().updatePlotGroups(); } } } int CvUnit::sabotageCost(const CvPlot* pPlot) const { return GC.getDefineINT("BASE_SPY_SABOTAGE_COST"); } // XXX compare with destroy prob... int CvUnit::sabotageProb(const CvPlot* pPlot, ProbabilityTypes eProbStyle) const { CvPlot* pLoopPlot; int iDefenseCount; int iCounterSpyCount; int iProb; int iI; iProb = 0; // XXX if (pPlot->isOwned()) { iDefenseCount = pPlot->plotCount(PUF_canDefend, -1, -1, NO_PLAYER, pPlot->getTeam()); iCounterSpyCount = pPlot->plotCount(PUF_isCounterSpy, -1, -1, NO_PLAYER, pPlot->getTeam()); for (iI = 0; iI < NUM_DIRECTION_TYPES; iI++) { pLoopPlot = plotDirection(pPlot->getX_INLINE(), pPlot->getY_INLINE(), ((DirectionTypes)iI)); if (pLoopPlot != NULL) { iCounterSpyCount += pLoopPlot->plotCount(PUF_isCounterSpy, -1, -1, NO_PLAYER, pPlot->getTeam()); } } } else { iDefenseCount = 0; iCounterSpyCount = 0; } if (eProbStyle == PROBABILITY_HIGH) { iCounterSpyCount = 0; } iProb += (40 / (iDefenseCount + 1)); // XXX if (eProbStyle != PROBABILITY_LOW) { iProb += (50 / (iCounterSpyCount + 1)); // XXX } return iProb; } bool CvUnit::canSabotage(const CvPlot* pPlot, bool bTestVisible) const { if (!(m_pUnitInfo->isSabotage())) { return false; } if (pPlot->getTeam() == getTeam()) { return false; } if (pPlot->isCity()) { return false; } if (pPlot->getImprovementType() == NO_IMPROVEMENT) { return false; } if (!bTestVisible) { if (GET_PLAYER(getOwnerINLINE()).getGold() < sabotageCost(pPlot)) { return false; } } return true; } bool CvUnit::sabotage() { CvCity* pNearestCity; CvPlot* pPlot; CvWString szBuffer; bool bCaught; if (!canSabotage(plot())) { return false; } pPlot = plot(); bCaught = (GC.getGameINLINE().getSorenRandNum(100, "Spy: Sabotage") > sabotageProb(pPlot)); GET_PLAYER(getOwnerINLINE()).changeGold(-(sabotageCost(pPlot))); if (!bCaught) { pPlot->setImprovementType((ImprovementTypes)(GC.getImprovementInfo(pPlot->getImprovementType()).getImprovementPillage())); finishMoves(); pNearestCity = GC.getMapINLINE().findCity(pPlot->getX_INLINE(), pPlot->getY_INLINE(), pPlot->getOwnerINLINE(), NO_TEAM, false); if (pNearestCity != NULL) { szBuffer = gDLL->getText("TXT_KEY_MISC_SPY_SABOTAGED", getNameKey(), pNearestCity->getNameKey()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_SABOTAGE", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); if (pPlot->isOwned()) { szBuffer = gDLL->getText("TXT_KEY_MISC_SABOTAGE_NEAR", pNearestCity->getNameKey()); gDLL->getInterfaceIFace()->addMessage(pPlot->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_SABOTAGE", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE(), true, true); } } if (pPlot->isActiveVisible(false)) { NotifyEntity(MISSION_SABOTAGE); } } else { if (pPlot->isOwned()) { szBuffer = gDLL->getText("TXT_KEY_MISC_SPY_CAUGHT_AND_KILLED", GET_PLAYER(getOwnerINLINE()).getCivilizationAdjective(), getNameKey()); gDLL->getInterfaceIFace()->addMessage(pPlot->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_EXPOSE", MESSAGE_TYPE_INFO); } szBuffer = gDLL->getText("TXT_KEY_MISC_YOUR_SPY_CAUGHT", getNameKey()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_EXPOSED", MESSAGE_TYPE_INFO); if (plot()->isActiveVisible(false)) { NotifyEntity(MISSION_SURRENDER); } if (pPlot->isOwned()) { if (!isEnemy(pPlot->getTeam(), pPlot)) { GET_PLAYER(pPlot->getOwnerINLINE()).AI_changeMemoryCount(getOwnerINLINE(), MEMORY_SPY_CAUGHT, 1); } } kill(true, pPlot->getOwnerINLINE()); } return true; } int CvUnit::destroyCost(const CvPlot* pPlot) const { CvCity* pCity; bool bLimited; pCity = pPlot->getPlotCity(); if (pCity == NULL) { return 0; } bLimited = false; if (pCity->isProductionUnit()) { bLimited = isLimitedUnitClass((UnitClassTypes)(GC.getUnitInfo(pCity->getProductionUnit()).getUnitClassType())); } else if (pCity->isProductionBuilding()) { bLimited = isLimitedWonderClass((BuildingClassTypes)(GC.getBuildingInfo(pCity->getProductionBuilding()).getBuildingClassType())); } else if (pCity->isProductionProject()) { bLimited = isLimitedProject(pCity->getProductionProject()); } return (GC.getDefineINT("BASE_SPY_DESTROY_COST") + (pCity->getProduction() * ((bLimited) ? GC.getDefineINT("SPY_DESTROY_COST_MULTIPLIER_LIMITED") : GC.getDefineINT("SPY_DESTROY_COST_MULTIPLIER")))); } int CvUnit::destroyProb(const CvPlot* pPlot, ProbabilityTypes eProbStyle) const { CvCity* pCity; CvPlot* pLoopPlot; int iDefenseCount; int iCounterSpyCount; int iProb; int iI; pCity = pPlot->getPlotCity(); if (pCity == NULL) { return 0; } iProb = 0; // XXX iDefenseCount = pPlot->plotCount(PUF_canDefend, -1, -1, NO_PLAYER, pPlot->getTeam()); iCounterSpyCount = pPlot->plotCount(PUF_isCounterSpy, -1, -1, NO_PLAYER, pPlot->getTeam()); for (iI = 0; iI < NUM_DIRECTION_TYPES; iI++) { pLoopPlot = plotDirection(pPlot->getX_INLINE(), pPlot->getY_INLINE(), ((DirectionTypes)iI)); if (pLoopPlot != NULL) { iCounterSpyCount += pLoopPlot->plotCount(PUF_isCounterSpy, -1, -1, NO_PLAYER, pPlot->getTeam()); } } if (eProbStyle == PROBABILITY_HIGH) { iCounterSpyCount = 0; } iProb += (25 / (iDefenseCount + 1)); // XXX if (eProbStyle != PROBABILITY_LOW) { iProb += (50 / (iCounterSpyCount + 1)); // XXX } iProb += std::min(25, pCity->getProductionTurnsLeft()); // XXX return iProb; } bool CvUnit::canDestroy(const CvPlot* pPlot, bool bTestVisible) const { CvCity* pCity; if (!(m_pUnitInfo->isDestroy())) { return false; } if (pPlot->getTeam() == getTeam()) { return false; } pCity = pPlot->getPlotCity(); if (pCity == NULL) { return false; } if (pCity->getProduction() == 0) { return false; } if (!bTestVisible) { if (GET_PLAYER(getOwnerINLINE()).getGold() < destroyCost(pPlot)) { return false; } } return true; } bool CvUnit::destroy() { CvCity* pCity; CvWString szBuffer; bool bCaught; if (!canDestroy(plot())) { return false; } bCaught = (GC.getGameINLINE().getSorenRandNum(100, "Spy: Destroy") > destroyProb(plot())); pCity = plot()->getPlotCity(); FAssertMsg(pCity != NULL, "City is not assigned a valid value"); GET_PLAYER(getOwnerINLINE()).changeGold(-(destroyCost(plot()))); if (!bCaught) { pCity->setProduction(pCity->getProduction() / 2); finishMoves(); szBuffer = gDLL->getText("TXT_KEY_MISC_SPY_DESTROYED_PRODUCTION", getNameKey(), pCity->getProductionNameKey(), pCity->getNameKey()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_DESTROY", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pCity->getX_INLINE(), pCity->getY_INLINE()); szBuffer = gDLL->getText("TXT_KEY_MISC_CITY_PRODUCTION_DESTROYED", pCity->getProductionNameKey(), pCity->getNameKey()); gDLL->getInterfaceIFace()->addMessage(pCity->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_DESTROY", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pCity->getX_INLINE(), pCity->getY_INLINE(), true, true); if (plot()->isActiveVisible(false)) { NotifyEntity(MISSION_DESTROY); } } else { szBuffer = gDLL->getText("TXT_KEY_MISC_SPY_CAUGHT_AND_KILLED", GET_PLAYER(getOwnerINLINE()).getCivilizationAdjective(), getNameKey()); gDLL->getInterfaceIFace()->addMessage(pCity->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_EXPOSE", MESSAGE_TYPE_INFO); szBuffer = gDLL->getText("TXT_KEY_MISC_YOUR_SPY_CAUGHT", getNameKey()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_EXPOSED", MESSAGE_TYPE_INFO); if (plot()->isActiveVisible(false)) { NotifyEntity(MISSION_SURRENDER); } if (!isEnemy(pCity->getTeam())) { GET_PLAYER(pCity->getOwnerINLINE()).AI_changeMemoryCount(getOwnerINLINE(), MEMORY_SPY_CAUGHT, 1); } kill(true, pCity->getOwnerINLINE()); } return true; } int CvUnit::stealPlansCost(const CvPlot* pPlot) const { CvCity* pCity; pCity = pPlot->getPlotCity(); if (pCity == NULL) { return 0; } return (GC.getDefineINT("BASE_SPY_STEAL_PLANS_COST") + ((GET_TEAM(pCity->getTeam()).getTotalLand() + GET_TEAM(pCity->getTeam()).getTotalPopulation()) * GC.getDefineINT("SPY_STEAL_PLANS_COST_MULTIPLIER"))); } // XXX compare with destroy prob... int CvUnit::stealPlansProb(const CvPlot* pPlot, ProbabilityTypes eProbStyle) const { CvCity* pCity; CvPlot* pLoopPlot; int iDefenseCount; int iCounterSpyCount; int iProb; int iI; pCity = pPlot->getPlotCity(); if (pCity == NULL) { return 0; } iProb = ((pCity->isGovernmentCenter()) ? 20 : 0); // XXX iDefenseCount = pPlot->plotCount(PUF_canDefend, -1, -1, NO_PLAYER, pPlot->getTeam()); iCounterSpyCount = pPlot->plotCount(PUF_isCounterSpy, -1, -1, NO_PLAYER, pPlot->getTeam()); for (iI = 0; iI < NUM_DIRECTION_TYPES; iI++) { pLoopPlot = plotDirection(pPlot->getX_INLINE(), pPlot->getY_INLINE(), ((DirectionTypes)iI)); if (pLoopPlot != NULL) { iCounterSpyCount += pLoopPlot->plotCount(PUF_isCounterSpy, -1, -1, NO_PLAYER, pPlot->getTeam()); } } if (eProbStyle == PROBABILITY_HIGH) { iCounterSpyCount = 0; } iProb += (20 / (iDefenseCount + 1)); // XXX if (eProbStyle != PROBABILITY_LOW) { iProb += (50 / (iCounterSpyCount + 1)); // XXX } return iProb; } bool CvUnit::canStealPlans(const CvPlot* pPlot, bool bTestVisible) const { CvCity* pCity; if (!(m_pUnitInfo->isStealPlans())) { return false; } if (pPlot->getTeam() == getTeam()) { return false; } pCity = pPlot->getPlotCity(); if (pCity == NULL) { return false; } if (!bTestVisible) { if (GET_PLAYER(getOwnerINLINE()).getGold() < stealPlansCost(pPlot)) { return false; } } return true; } bool CvUnit::stealPlans() { CvCity* pCity; CvWString szBuffer; bool bCaught; if (!canStealPlans(plot())) { return false; } bCaught = (GC.getGameINLINE().getSorenRandNum(100, "Spy: Steal Plans") > stealPlansProb(plot())); pCity = plot()->getPlotCity(); FAssertMsg(pCity != NULL, "City is not assigned a valid value"); GET_PLAYER(getOwnerINLINE()).changeGold(-(stealPlansCost(plot()))); if (!bCaught) { GET_TEAM(getTeam()).changeStolenVisibilityTimer(pCity->getTeam(), 2); finishMoves(); szBuffer = gDLL->getText("TXT_KEY_MISC_SPY_STOLE_PLANS", getNameKey(), pCity->getNameKey()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_STEALPLANS", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pCity->getX_INLINE(), pCity->getY_INLINE()); szBuffer = gDLL->getText("TXT_KEY_MISC_PLANS_STOLEN", pCity->getNameKey()); gDLL->getInterfaceIFace()->addMessage(pCity->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_STEALPLANS", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pCity->getX_INLINE(), pCity->getY_INLINE(), true, true); if (plot()->isActiveVisible(false)) { NotifyEntity(MISSION_STEAL_PLANS); } } else { szBuffer = gDLL->getText("TXT_KEY_MISC_SPY_CAUGHT_AND_KILLED", GET_PLAYER(getOwnerINLINE()).getCivilizationAdjective(), getNameKey()); gDLL->getInterfaceIFace()->addMessage(pCity->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_EXPOSE", MESSAGE_TYPE_INFO); szBuffer = gDLL->getText("TXT_KEY_MISC_YOUR_SPY_CAUGHT", getNameKey()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_EXPOSED", MESSAGE_TYPE_INFO); if (plot()->isActiveVisible(false)) { NotifyEntity(MISSION_SURRENDER); } if (!isEnemy(pCity->getTeam())) { GET_PLAYER(pCity->getOwnerINLINE()).AI_changeMemoryCount(getOwnerINLINE(), MEMORY_SPY_CAUGHT, 1); } kill(true, pCity->getOwnerINLINE()); } return true; } bool CvUnit::canFound(const CvPlot* pPlot, bool bTestVisible) const { if (!isFound()) { return false; } if (!(GET_PLAYER(getOwnerINLINE()).canFound(pPlot->getX_INLINE(), pPlot->getY_INLINE(), bTestVisible))) { return false; } return true; } bool CvUnit::found() { if (!canFound(plot())) { return false; } if (GC.getGameINLINE().getActivePlayer() == getOwnerINLINE()) { gDLL->getInterfaceIFace()->lookAt(plot()->getPoint(), CAMERALOOKAT_NORMAL); } GET_PLAYER(getOwnerINLINE()).found(getX_INLINE(), getY_INLINE()); if (plot()->isActiveVisible(false)) { NotifyEntity(MISSION_FOUND); } kill(true); return true; } bool CvUnit::canSpread(const CvPlot* pPlot, ReligionTypes eReligion, bool bTestVisible) const { CvCity* pCity; if (GC.getUSE_USE_CANNOT_SPREAD_RELIGION_CALLBACK()) { CyArgsList argsList; argsList.add(getOwnerINLINE()); argsList.add(getID()); argsList.add((int) eReligion); argsList.add(pPlot->getX()); argsList.add(pPlot->getY()); long lResult=0; gDLL->getPythonIFace()->callFunction(PYGameModule, "cannotSpreadReligion", argsList.makeFunctionArgs(), &lResult); if (lResult > 0) { return false; } } if (eReligion == NO_RELIGION) { return false; } if (m_pUnitInfo->getReligionSpreads(eReligion) <= 0) { return false; } pCity = pPlot->getPlotCity(); if (pCity == NULL) { return false; } if (pCity->isHasReligion(eReligion)) { return false; } if (!canEnterArea(pPlot->getTeam(), pPlot->area())) { return false; } if (!bTestVisible) { if (pCity->getTeam() != getTeam()) { if (GET_PLAYER(pCity->getOwnerINLINE()).isNoNonStateReligionSpread()) { if (eReligion != GET_PLAYER(pCity->getOwnerINLINE()).getStateReligion()) { return false; } } } } return true; } bool CvUnit::spread(ReligionTypes eReligion) { CvCity* pCity; CvWString szBuffer; int iSpreadProb; if (!canSpread(plot(), eReligion)) { return false; } pCity = plot()->getPlotCity(); if (pCity != NULL) { iSpreadProb = m_pUnitInfo->getReligionSpreads(eReligion); if (pCity->getTeam() != getTeam()) { iSpreadProb /= 2; } bool bSuccess; iSpreadProb += (((GC.getNumReligionInfos() - pCity->getReligionCount()) * (100 - iSpreadProb)) / GC.getNumReligionInfos()); if (GC.getGameINLINE().getSorenRandNum(100, "Unit Spread Religion") < iSpreadProb) { pCity->setHasReligion(eReligion, true, true, false); bSuccess = true; } else { szBuffer = gDLL->getText("TXT_KEY_MISC_RELIGION_FAILED_TO_SPREAD", getNameKey(), GC.getReligionInfo(eReligion).getChar(), pCity->getNameKey()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_NOSPREAD", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pCity->getX_INLINE(), pCity->getY_INLINE()); bSuccess = false; } // Python Event CvEventReporter::getInstance().unitSpreadReligionAttempt(this, eReligion, bSuccess); } if (plot()->isActiveVisible(false)) { NotifyEntity(MISSION_SPREAD); } kill(true); return true; } bool CvUnit::canSpreadCorporation(const CvPlot* pPlot, CorporationTypes eCorporation, bool bTestVisible) const { if (NO_CORPORATION == eCorporation) { return false; } if (!GET_PLAYER(getOwnerINLINE()).isActiveCorporation(eCorporation)) { return false; } if (m_pUnitInfo->getCorporationSpreads(eCorporation) <= 0) { return false; } CvCity* pCity = pPlot->getPlotCity(); if (NULL == pCity) { return false; } if (pCity->isHasCorporation(eCorporation)) { return false; } if (!canEnterArea(pPlot->getTeam(), pPlot->area())) { return false; } if (!bTestVisible) { if (!GET_PLAYER(pCity->getOwnerINLINE()).isActiveCorporation(eCorporation)) { return false; } for (int iCorporation = 0; iCorporation < GC.getNumCorporationInfos(); ++iCorporation) { if (pCity->isHeadquarters((CorporationTypes)iCorporation)) { if (GC.getGameINLINE().isCompetingCorporation((CorporationTypes)iCorporation, eCorporation)) { return false; } } } bool bValid = false; for (int i = 0; i < GC.getNUM_CORPORATION_PREREQ_BONUSES(); ++i) { BonusTypes eBonus = (BonusTypes)GC.getCorporationInfo(eCorporation).getPrereqBonus(i); if (NO_BONUS != eBonus) { if (pCity->hasBonus(eBonus)) { bValid = true; break; } } } if (!bValid) { return false; } if (GET_PLAYER(getOwnerINLINE()).getGold() < spreadCorporationCost(eCorporation, pCity)) { return false; } } return true; } int CvUnit::spreadCorporationCost(CorporationTypes eCorporation, CvCity* pCity) const { int iCost = std::max(0, GC.getCorporationInfo(eCorporation).getSpreadCost() * (100 + GET_PLAYER(getOwnerINLINE()).calculateInflationRate())); iCost /= 100; if (NULL != pCity) { if (getTeam() != pCity->getTeam() && !GET_TEAM(pCity->getTeam()).isVassal(getTeam())) { iCost *= GC.getDefineINT("CORPORATION_FOREIGN_SPREAD_COST_PERCENT"); iCost /= 100; } for (int iCorp = 0; iCorp < GC.getNumCorporationInfos(); ++iCorp) { if (iCorp != eCorporation) { if (pCity->isActiveCorporation((CorporationTypes)iCorp)) { if (GC.getGameINLINE().isCompetingCorporation(eCorporation, (CorporationTypes)iCorp)) { iCost *= 100 + GC.getCorporationInfo((CorporationTypes)iCorp).getSpreadFactor(); iCost /= 100; } } } } } return iCost; } bool CvUnit::spreadCorporation(CorporationTypes eCorporation) { int iSpreadProb; if (!canSpreadCorporation(plot(), eCorporation)) { return false; } CvCity* pCity = plot()->getPlotCity(); if (NULL != pCity) { GET_PLAYER(getOwnerINLINE()).changeGold(-spreadCorporationCost(eCorporation, pCity)); iSpreadProb = m_pUnitInfo->getCorporationSpreads(eCorporation); if (pCity->getTeam() != getTeam()) { iSpreadProb /= 2; } iSpreadProb += (((GC.getNumCorporationInfos() - pCity->getCorporationCount()) * (100 - iSpreadProb)) / GC.getNumCorporationInfos()); if (GC.getGameINLINE().getSorenRandNum(100, "Unit Spread Corporation") < iSpreadProb) { pCity->setHasCorporation(eCorporation, true, true, false); } else { CvWString szBuffer = gDLL->getText("TXT_KEY_MISC_CORPORATION_FAILED_TO_SPREAD", getNameKey(), GC.getCorporationInfo(eCorporation).getChar(), pCity->getNameKey()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_NOSPREAD", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pCity->getX_INLINE(), pCity->getY_INLINE()); } } if (plot()->isActiveVisible(false)) { NotifyEntity(MISSION_SPREAD_CORPORATION); } kill(true); return true; } bool CvUnit::canJoin(const CvPlot* pPlot, SpecialistTypes eSpecialist) const { CvCity* pCity; if (eSpecialist == NO_SPECIALIST) { return false; } if (!(m_pUnitInfo->getGreatPeoples(eSpecialist))) { return false; } pCity = pPlot->getPlotCity(); if (pCity == NULL) { return false; } if (!(pCity->canJoin())) { return false; } if (pCity->getTeam() != getTeam()) { return false; } if (isDelayedDeath()) { return false; } return true; } bool CvUnit::join(SpecialistTypes eSpecialist) { CvCity* pCity; if (!canJoin(plot(), eSpecialist)) { return false; } pCity = plot()->getPlotCity(); if (pCity != NULL) { pCity->changeFreeSpecialistCount(eSpecialist, 1); } if (plot()->isActiveVisible(false)) { NotifyEntity(MISSION_JOIN); } kill(true); return true; } bool CvUnit::canConstruct(const CvPlot* pPlot, BuildingTypes eBuilding, bool bTestVisible) const { CvCity* pCity; if (eBuilding == NO_BUILDING) { return false; } pCity = pPlot->getPlotCity(); if (pCity == NULL) { return false; } if (getTeam() != pCity->getTeam()) { return false; } if (pCity->getNumRealBuilding(eBuilding) > 0) { return false; } if (!(m_pUnitInfo->getForceBuildings(eBuilding))) { if (!(m_pUnitInfo->getBuildings(eBuilding))) { return false; } if (!(pCity->canConstruct(eBuilding, false, bTestVisible, true))) { return false; } } if (isDelayedDeath()) { return false; } return true; } bool CvUnit::construct(BuildingTypes eBuilding) { CvCity* pCity; if (!canConstruct(plot(), eBuilding)) { return false; } pCity = plot()->getPlotCity(); if (pCity != NULL) { pCity->setNumRealBuilding(eBuilding, pCity->getNumRealBuilding(eBuilding) + 1); CvEventReporter::getInstance().buildingBuilt(pCity, eBuilding); } if (plot()->isActiveVisible(false)) { NotifyEntity(MISSION_CONSTRUCT); } kill(true); return true; } TechTypes CvUnit::getDiscoveryTech() const { return ::getDiscoveryTech(getUnitType(), getOwnerINLINE()); } int CvUnit::getDiscoverResearch(TechTypes eTech) const { int iResearch; iResearch = (m_pUnitInfo->getBaseDiscover() + (m_pUnitInfo->getDiscoverMultiplier() * GET_TEAM(getTeam()).getTotalPopulation())); iResearch *= GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getUnitDiscoverPercent(); iResearch /= 100; if (eTech != NO_TECH) { iResearch = std::min(GET_TEAM(getTeam()).getResearchLeft(eTech), iResearch); } return std::max(0, iResearch); } bool CvUnit::canDiscover(const CvPlot* pPlot) const { TechTypes eTech; eTech = getDiscoveryTech(); if (eTech == NO_TECH) { return false; } if (getDiscoverResearch(eTech) == 0) { return false; } if (isDelayedDeath()) { return false; } return true; } bool CvUnit::discover() { TechTypes eDiscoveryTech; if (!canDiscover(plot())) { return false; } eDiscoveryTech = getDiscoveryTech(); FAssertMsg(eDiscoveryTech != NO_TECH, "DiscoveryTech is not assigned a valid value"); GET_TEAM(getTeam()).changeResearchProgress(eDiscoveryTech, getDiscoverResearch(eDiscoveryTech), getOwnerINLINE()); if (plot()->isActiveVisible(false)) { NotifyEntity(MISSION_DISCOVER); } kill(true); return true; } int CvUnit::getMaxHurryProduction(CvCity* pCity) const { int iProduction; iProduction = (m_pUnitInfo->getBaseHurry() + (m_pUnitInfo->getHurryMultiplier() * pCity->getPopulation())); iProduction *= GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getUnitHurryPercent(); iProduction /= 100; return std::max(0, iProduction); } int CvUnit::getHurryProduction(const CvPlot* pPlot) const { CvCity* pCity; int iProduction; pCity = pPlot->getPlotCity(); if (pCity == NULL) { return 0; } iProduction = getMaxHurryProduction(pCity); iProduction = std::min(pCity->productionLeft(), iProduction); return std::max(0, iProduction); } bool CvUnit::canHurry(const CvPlot* pPlot, bool bTestVisible) const { if (isDelayedDeath()) { return false; } CvCity* pCity; if (getHurryProduction(pPlot) == 0) { return false; } pCity = pPlot->getPlotCity(); if (pCity == NULL) { return false; } if (pCity->getProductionTurnsLeft() == 1) { return false; } if (!bTestVisible) { if (!(pCity->isProductionBuilding())) { return false; } } return true; } bool CvUnit::hurry() { CvCity* pCity; if (!canHurry(plot())) { return false; } pCity = plot()->getPlotCity(); if (pCity != NULL) { pCity->changeProduction(getHurryProduction(plot())); } if (plot()->isActiveVisible(false)) { NotifyEntity(MISSION_HURRY); } kill(true); return true; } int CvUnit::getTradeGold(const CvPlot* pPlot) const { CvCity* pCapitalCity; CvCity* pCity; int iGold; pCity = pPlot->getPlotCity(); pCapitalCity = GET_PLAYER(getOwnerINLINE()).getCapitalCity(); if (pCity == NULL) { return 0; } iGold = (m_pUnitInfo->getBaseTrade() + (m_pUnitInfo->getTradeMultiplier() * ((pCapitalCity != NULL) ? pCity->calculateTradeProfit(pCapitalCity) : 0))); iGold *= GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getUnitTradePercent(); iGold /= 100; return std::max(0, iGold); } bool CvUnit::canTrade(const CvPlot* pPlot, bool bTestVisible) const { if (isDelayedDeath()) { return false; } CvCity* pCity = pPlot->getPlotCity(); if (pCity == NULL) { return false; } if (getTradeGold(pPlot) == 0) { return false; } if (!canEnterArea(pPlot->getTeam(), pPlot->area())) { return false; } if (!bTestVisible) { if (pCity->getTeam() == getTeam()) { return false; } } return true; } bool CvUnit::trade() { if (!canTrade(plot())) { return false; } GET_PLAYER(getOwnerINLINE()).changeGold(getTradeGold(plot())); if (plot()->isActiveVisible(false)) { NotifyEntity(MISSION_TRADE); } kill(true); return true; } int CvUnit::getGreatWorkCulture(const CvPlot* pPlot) const { int iCulture; iCulture = m_pUnitInfo->getGreatWorkCulture(); iCulture *= GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getUnitGreatWorkPercent(); iCulture /= 100; return std::max(0, iCulture); } bool CvUnit::canGreatWork(const CvPlot* pPlot) const { if (isDelayedDeath()) { return false; } CvCity* pCity = pPlot->getPlotCity(); if (pCity == NULL) { return false; } if (pCity->getOwnerINLINE() != getOwnerINLINE()) { return false; } if (getGreatWorkCulture(pPlot) == 0) { return false; } return true; } bool CvUnit::greatWork() { if (!canGreatWork(plot())) { return false; } CvCity* pCity = plot()->getPlotCity(); if (pCity != NULL) { pCity->setCultureUpdateTimer(0); pCity->setOccupationTimer(0); int iCultureToAdd = 100 * getGreatWorkCulture(plot()); int iNumTurnsApplied = (GC.getDefineINT("GREAT_WORKS_CULTURE_TURNS") * GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getUnitGreatWorkPercent()) / 100; for (int i = 0; i < iNumTurnsApplied; ++i) { pCity->changeCultureTimes100(getOwnerINLINE(), iCultureToAdd / iNumTurnsApplied, true, true); } if (iNumTurnsApplied > 0) { pCity->changeCultureTimes100(getOwnerINLINE(), iCultureToAdd % iNumTurnsApplied, false, true); } } if (plot()->isActiveVisible(false)) { NotifyEntity(MISSION_GREAT_WORK); } kill(true); return true; } int CvUnit::getEspionagePoints(const CvPlot* pPlot) const { int iEspionagePoints; iEspionagePoints = m_pUnitInfo->getEspionagePoints(); iEspionagePoints *= GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getUnitGreatWorkPercent(); iEspionagePoints /= 100; return std::max(0, iEspionagePoints); } bool CvUnit::canInfiltrate(const CvPlot* pPlot, bool bTestVisible) const { if (isDelayedDeath()) { return false; } if (GC.getGameINLINE().isOption(GAMEOPTION_NO_ESPIONAGE)) { return false; } if (getEspionagePoints(NULL) == 0) { return false; } CvCity* pCity = pPlot->getPlotCity(); if (pCity == NULL || pCity->isBarbarian()) { return false; } if (!bTestVisible) { if (NULL != pCity && pCity->getTeam() == getTeam()) { return false; } } return true; } bool CvUnit::infiltrate() { if (!canInfiltrate(plot())) { return false; } int iPoints = getEspionagePoints(NULL); GET_TEAM(getTeam()).changeEspionagePointsAgainstTeam(GET_PLAYER(plot()->getOwnerINLINE()).getTeam(), iPoints); GET_TEAM(getTeam()).changeEspionagePointsEver(iPoints); if (plot()->isActiveVisible(false)) { NotifyEntity(MISSION_INFILTRATE); } kill(true); return true; } bool CvUnit::canEspionage(const CvPlot* pPlot, bool bTestVisible) const { if (isDelayedDeath()) { return false; } if (!isSpy()) { return false; } if (GC.getGameINLINE().isOption(GAMEOPTION_NO_ESPIONAGE)) { return false; } PlayerTypes ePlotOwner = pPlot->getOwnerINLINE(); if (NO_PLAYER == ePlotOwner) { return false; } CvPlayer& kTarget = GET_PLAYER(ePlotOwner); if (kTarget.isBarbarian()) { return false; } if (kTarget.getTeam() == getTeam()) { return false; } if (GET_TEAM(getTeam()).isVassal(kTarget.getTeam())) { return false; } if (!bTestVisible) { if (isMadeAttack()) { return false; } if (hasMoved()) { return false; } if (kTarget.getTeam() != getTeam() && !isInvisible(kTarget.getTeam(), false)) { return false; } } return true; } //TSHEEP start SuperSpy Vincentz bool CvUnit::awardSpyExperience(TeamTypes eTargetTeam, int iModifier) { int iDifficulty = (getSpyInterceptPercent(eTargetTeam) * (100 + iModifier)) / 100; if (iDifficulty < 1) changeExperience(1); else if (iDifficulty < 10) changeExperience(2); else if (iDifficulty < 25) changeExperience(3); else if (iDifficulty < 50) changeExperience(4); else if (iDifficulty < 75) changeExperience(5); else if (iDifficulty >= 75) changeExperience(6); testPromotionReady(); return true; } //TSHEEP End bool CvUnit::espionage(EspionageMissionTypes eMission, int iData) { if (!canEspionage(plot())) { return false; } PlayerTypes eTargetPlayer = plot()->getOwnerINLINE(); if (NO_ESPIONAGEMISSION == eMission) { FAssert(GET_PLAYER(getOwnerINLINE()).isHuman()); CvPopupInfo* pInfo = new CvPopupInfo(BUTTONPOPUP_DOESPIONAGE); if (NULL != pInfo) { gDLL->getInterfaceIFace()->addPopup(pInfo, getOwnerINLINE(), true); } } else if (GC.getEspionageMissionInfo(eMission).isTwoPhases() && -1 == iData) { FAssert(GET_PLAYER(getOwnerINLINE()).isHuman()); CvPopupInfo* pInfo = new CvPopupInfo(BUTTONPOPUP_DOESPIONAGE_TARGET); if (NULL != pInfo) { pInfo->setData1(eMission); gDLL->getInterfaceIFace()->addPopup(pInfo, getOwnerINLINE(), true); } } else { //Vincentz Spy if (testSpyIntercepted(eTargetPlayer, (GC.getEspionageMissionInfo(eMission).getDifficultyMod() - evasionProbability()))) //Vincentz Spy { return false; } if (GET_PLAYER(getOwnerINLINE()).doEspionageMission(eMission, eTargetPlayer, plot(), iData, this)) { if (plot()->isActiveVisible(false)) { NotifyEntity(MISSION_ESPIONAGE); } //Vincentz Spy if (!testSpyIntercepted(eTargetPlayer, (GC.getDefineINT("ESPIONAGE_SPY_MISSION_ESCAPE_MOD") - evasionProbability()))) { setFortifyTurns(0); setMadeAttack(true); // finishMoves(); changeMoves(GC.getMOVE_DENOMINATOR() * ((200 + GC.getEspionageMissionInfo(eMission).getDifficultyMod()) / 5)); //TSHEEP Give spies xp for successful missions SuperSpy Vincentz awardSpyExperience(GET_PLAYER(eTargetPlayer).getTeam(), GC.getEspionageMissionInfo(eMission).getDifficultyMod()); //TSHEEP end //Vincentz Spy /* CvCity* pCapital = GET_PLAYER(getOwnerINLINE()).getCapitalCity(); if (NULL != pCapital) { setXY(pCapital->getX_INLINE(), pCapital->getY_INLINE(), false, false, false); CvWString szBuffer = gDLL->getText("TXT_KEY_ESPIONAGE_SPY_SUCCESS", getNameKey(), pCapital->getNameKey()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_POSITIVE_DINK", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_WHITE"), pCapital->getX_INLINE(), pCapital->getY_INLINE(), true, true); } */ } //Vincentz Spy End return true; } } return false; } bool CvUnit::testSpyIntercepted(PlayerTypes eTargetPlayer, int iModifier) { CvPlayer& kTargetPlayer = GET_PLAYER(eTargetPlayer); if (kTargetPlayer.isBarbarian()) { return false; } if (GC.getGameINLINE().getSorenRandNum(10000, "Spy Interception") >= getSpyInterceptPercent(kTargetPlayer.getTeam()) * (100 + iModifier)) { return false; } CvString szFormatNoReveal; CvString szFormatReveal; if (GET_TEAM(kTargetPlayer.getTeam()).getCounterespionageModAgainstTeam(getTeam()) > 0) { szFormatNoReveal = "TXT_KEY_SPY_INTERCEPTED_MISSION"; szFormatReveal = "TXT_KEY_SPY_INTERCEPTED_MISSION_REVEAL"; } else if (plot()->isEspionageCounterSpy(kTargetPlayer.getTeam())) { szFormatNoReveal = "TXT_KEY_SPY_INTERCEPTED_SPY"; szFormatReveal = "TXT_KEY_SPY_INTERCEPTED_SPY_REVEAL"; } else { szFormatNoReveal = "TXT_KEY_SPY_INTERCEPTED"; szFormatReveal = "TXT_KEY_SPY_INTERCEPTED_REVEAL"; } CvWString szCityName = kTargetPlayer.getCivilizationShortDescription(); CvCity* pClosestCity = GC.getMapINLINE().findCity(getX_INLINE(), getY_INLINE(), eTargetPlayer, kTargetPlayer.getTeam(), true, false); if (pClosestCity != NULL) { szCityName = pClosestCity->getName(); } CvWString szBuffer = gDLL->getText(szFormatReveal.GetCString(), GET_PLAYER(getOwnerINLINE()).getCivilizationAdjectiveKey(), getNameKey(), kTargetPlayer.getCivilizationAdjectiveKey(), szCityName.GetCString()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_EXPOSED", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), getX_INLINE(), getY_INLINE(), true, true); if (GC.getGameINLINE().getSorenRandNum(100, "Spy Reveal identity") < GC.getDefineINT("ESPIONAGE_SPY_REVEAL_IDENTITY_PERCENT")) { if (!isEnemy(kTargetPlayer.getTeam())) { GET_PLAYER(eTargetPlayer).AI_changeMemoryCount(getOwnerINLINE(), MEMORY_SPY_CAUGHT, 1); } gDLL->getInterfaceIFace()->addMessage(eTargetPlayer, true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_EXPOSE", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), getX_INLINE(), getY_INLINE(), true, true); } else { szBuffer = gDLL->getText(szFormatNoReveal.GetCString(), getNameKey(), kTargetPlayer.getCivilizationAdjectiveKey(), szCityName.GetCString()); gDLL->getInterfaceIFace()->addMessage(eTargetPlayer, true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_EXPOSE", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), getX_INLINE(), getY_INLINE(), true, true); } if (plot()->isActiveVisible(false)) { NotifyEntity(MISSION_SURRENDER); } kill(true); return true; } int CvUnit::getSpyInterceptPercent(TeamTypes eTargetTeam) const { FAssert(isSpy()); FAssert(getTeam() != eTargetTeam); int iSuccess = 0; int iTargetPoints = GET_TEAM(eTargetTeam).getEspionagePointsEver(); int iOurPoints = GET_TEAM(getTeam()).getEspionagePointsEver(); iSuccess += (GC.getDefineINT("ESPIONAGE_INTERCEPT_SPENDING_MAX") * iTargetPoints) / std::max(1, iTargetPoints + iOurPoints); if (plot()->isEspionageCounterSpy(eTargetTeam)) { iSuccess += GC.getDefineINT("ESPIONAGE_INTERCEPT_COUNTERSPY"); } if (GET_TEAM(eTargetTeam).getCounterespionageModAgainstTeam(getTeam()) > 0) { iSuccess += GC.getDefineINT("ESPIONAGE_INTERCEPT_COUNTERESPIONAGE_MISSION"); } if (0 == getFortifyTurns() || plot()->plotCount(PUF_isSpy, -1, -1, NO_PLAYER, getTeam()) > 1) { iSuccess += GC.getDefineINT("ESPIONAGE_INTERCEPT_RECENT_MISSION"); } return std::min(100, std::max(0, iSuccess)); } bool CvUnit::isIntruding() const { TeamTypes eLocalTeam = plot()->getTeam(); if (NO_TEAM == eLocalTeam || eLocalTeam == getTeam()) { return false; } if (GET_TEAM(eLocalTeam).isVassal(getTeam())) { return false; } return true; } bool CvUnit::canGoldenAge(const CvPlot* pPlot, bool bTestVisible) const { if (!isGoldenAge()) { return false; } if (!bTestVisible) { if (GET_PLAYER(getOwnerINLINE()).unitsRequiredForGoldenAge() > GET_PLAYER(getOwnerINLINE()).unitsGoldenAgeReady()) { return false; } } return true; } bool CvUnit::goldenAge() { if (!canGoldenAge(plot())) { return false; } GET_PLAYER(getOwnerINLINE()).killGoldenAgeUnits(this); GET_PLAYER(getOwnerINLINE()).changeGoldenAgeTurns(GET_PLAYER(getOwnerINLINE()).getGoldenAgeLength()); GET_PLAYER(getOwnerINLINE()).changeNumUnitGoldenAges(1); if (plot()->isActiveVisible(false)) { NotifyEntity(MISSION_GOLDEN_AGE); } kill(true); return true; } bool CvUnit::canBuild(const CvPlot* pPlot, BuildTypes eBuild, bool bTestVisible) const { FAssertMsg(eBuild < GC.getNumBuildInfos(), "Index out of bounds"); if (!(m_pUnitInfo->getBuilds(eBuild))) { return false; } if (!(GET_PLAYER(getOwnerINLINE()).canBuild(pPlot, eBuild, false, bTestVisible))) { return false; } if (!pPlot->isValidDomainForAction(*this)) { return false; } return true; } // Returns true if build finished... bool CvUnit::build(BuildTypes eBuild) { bool bFinished; FAssertMsg(eBuild < GC.getNumBuildInfos(), "Invalid Build"); if (!canBuild(plot(), eBuild)) { return false; } // Note: notify entity must come before changeBuildProgress - because once the unit is done building, // that function will notify the entity to stop building. NotifyEntity((MissionTypes)GC.getBuildInfo(eBuild).getMissionType()); GET_PLAYER(getOwnerINLINE()).changeGold(-(GET_PLAYER(getOwnerINLINE()).getBuildCost(plot(), eBuild))); bFinished = plot()->changeBuildProgress(eBuild, workRate(false), getTeam()); finishMoves(); // needs to be at bottom because movesLeft() can affect workRate()... if (bFinished) { if (GC.getBuildInfo(eBuild).isKill()) { kill(true); } } // Python Event CvEventReporter::getInstance().unitBuildImprovement(this, eBuild, bFinished); return bFinished; } bool CvUnit::canPromote(PromotionTypes ePromotion, int iLeaderUnitId) const { if (iLeaderUnitId >= 0) { if (iLeaderUnitId == getID()) { return false; } // The command is always possible if it's coming from a Warlord unit that gives just experience points CvUnit* pWarlord = GET_PLAYER(getOwnerINLINE()).getUnit(iLeaderUnitId); if (pWarlord && NO_UNIT != pWarlord->getUnitType() && pWarlord->getUnitInfo().getLeaderExperience() > 0 && NO_PROMOTION == pWarlord->getUnitInfo().getLeaderPromotion() && canAcquirePromotionAny()) { return true; } } if (ePromotion == NO_PROMOTION) { return false; } if (!canAcquirePromotion(ePromotion)) { return false; } if (GC.getPromotionInfo(ePromotion).isLeader()) { if (iLeaderUnitId >= 0) { CvUnit* pWarlord = GET_PLAYER(getOwnerINLINE()).getUnit(iLeaderUnitId); if (pWarlord && NO_UNIT != pWarlord->getUnitType()) { return (pWarlord->getUnitInfo().getLeaderPromotion() == ePromotion); } } return false; } else { if (!isPromotionReady()) { return false; } } return true; } void CvUnit::promote(PromotionTypes ePromotion, int iLeaderUnitId) { if (!canPromote(ePromotion, iLeaderUnitId)) { return; } if (iLeaderUnitId >= 0) { CvUnit* pWarlord = GET_PLAYER(getOwnerINLINE()).getUnit(iLeaderUnitId); if (pWarlord) { pWarlord->giveExperience(); if (!pWarlord->getNameNoDesc().empty()) { setName(pWarlord->getNameKey()); } //update graphics models m_eLeaderUnitType = pWarlord->getUnitType(); reloadEntity(); } } if (!GC.getPromotionInfo(ePromotion).isLeader()) { changeLevel(1); changeDamage(-(getDamage() / 2)); } setHasPromotion(ePromotion, true); testPromotionReady(); if (IsSelected()) { gDLL->getInterfaceIFace()->playGeneralSound(GC.getPromotionInfo(ePromotion).getSound()); gDLL->getInterfaceIFace()->setDirty(UnitInfo_DIRTY_BIT, true); } else { setInfoBarDirty(true); } CvEventReporter::getInstance().unitPromoted(this, ePromotion); } bool CvUnit::lead(int iUnitId) { if (!canLead(plot(), iUnitId)) { return false; } PromotionTypes eLeaderPromotion = (PromotionTypes)m_pUnitInfo->getLeaderPromotion(); if (-1 == iUnitId) { CvPopupInfo* pInfo = new CvPopupInfo(BUTTONPOPUP_LEADUNIT, eLeaderPromotion, getID()); if (pInfo) { gDLL->getInterfaceIFace()->addPopup(pInfo, getOwnerINLINE(), true); } return false; } else { CvUnit* pUnit = GET_PLAYER(getOwnerINLINE()).getUnit(iUnitId); if (!pUnit || !pUnit->canPromote(eLeaderPromotion, getID())) { return false; } pUnit->joinGroup(NULL, true, true); pUnit->promote(eLeaderPromotion, getID()); if (plot()->isActiveVisible(false)) { NotifyEntity(MISSION_LEAD); } kill(true); return true; } } int CvUnit::canLead(const CvPlot* pPlot, int iUnitId) const { PROFILE_FUNC(); if (isDelayedDeath()) { return 0; } if (NO_UNIT == getUnitType()) { return 0; } int iNumUnits = 0; CvUnitInfo& kUnitInfo = getUnitInfo(); if (-1 == iUnitId) { CLLNode<IDInfo>* pUnitNode = pPlot->headUnitNode(); while(pUnitNode != NULL) { CvUnit* pUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); if (pUnit && pUnit != this && pUnit->getOwnerINLINE() == getOwnerINLINE() && pUnit->canPromote((PromotionTypes)kUnitInfo.getLeaderPromotion(), getID())) { ++iNumUnits; } } } else { CvUnit* pUnit = GET_PLAYER(getOwnerINLINE()).getUnit(iUnitId); if (pUnit && pUnit != this && pUnit->canPromote((PromotionTypes)kUnitInfo.getLeaderPromotion(), getID())) { iNumUnits = 1; } } return iNumUnits; } int CvUnit::canGiveExperience(const CvPlot* pPlot) const { int iNumUnits = 0; if (NO_UNIT != getUnitType() && m_pUnitInfo->getLeaderExperience() > 0) { CLLNode<IDInfo>* pUnitNode = pPlot->headUnitNode(); while(pUnitNode != NULL) { CvUnit* pUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); if (pUnit && pUnit != this && pUnit->getOwnerINLINE() == getOwnerINLINE() && pUnit->canAcquirePromotionAny()) { ++iNumUnits; } } } return iNumUnits; } bool CvUnit::giveExperience() { CvPlot* pPlot = plot(); if (pPlot) { int iNumUnits = canGiveExperience(pPlot); if (iNumUnits > 0) { int iTotalExperience = getStackExperienceToGive(iNumUnits); int iMinExperiencePerUnit = iTotalExperience / iNumUnits; int iRemainder = iTotalExperience % iNumUnits; CLLNode<IDInfo>* pUnitNode = pPlot->headUnitNode(); int i = 0; while(pUnitNode != NULL) { CvUnit* pUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); if (pUnit && pUnit != this && pUnit->getOwnerINLINE() == getOwnerINLINE() && pUnit->canAcquirePromotionAny()) { pUnit->changeExperience(i < iRemainder ? iMinExperiencePerUnit+1 : iMinExperiencePerUnit); pUnit->testPromotionReady(); } i++; } return true; } } return false; } int CvUnit::getStackExperienceToGive(int iNumUnits) const { return (m_pUnitInfo->getLeaderExperience() * (100 + std::min(50, (iNumUnits - 1) * GC.getDefineINT("WARLORD_EXTRA_EXPERIENCE_PER_UNIT_PERCENT")))) / 100; } //Vincentz int CvUnit::getUnitClassCount(UnitClassTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumUnitClassInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiUnitClassCount[eIndex]; } //Vincentz end int CvUnit::upgradePrice(UnitTypes eUnit) const { int iPrice; CyArgsList argsList; argsList.add(getOwnerINLINE()); argsList.add(getID()); argsList.add((int) eUnit); long lResult=0; gDLL->getPythonIFace()->callFunction(PYGameModule, "getUpgradePriceOverride", argsList.makeFunctionArgs(), &lResult); if (lResult >= 0) { return lResult; } if (isBarbarian()) { return 0; } iPrice = GC.getDefineINT("BASE_UNIT_UPGRADE_COST"); //Vincentz Upgrade cost per unit amount fixed iPrice += (std::max(0, (GET_PLAYER(getOwnerINLINE()).getProductionNeeded(eUnit) - GC.getUnitInfo(getUnitType()).getProductionCost())) * GC.getDefineINT("UNIT_UPGRADE_COST_PER_PRODUCTION")); // iPrice += (std::max(0, (GET_PLAYER(getOwnerINLINE()).getProductionNeeded(eUnit) - GET_PLAYER(getOwnerINLINE()).getProductionNeeded(getUnitType()))) * GC.getDefineINT("UNIT_UPGRADE_COST_PER_PRODUCTION")); //Vincentz end UnitClassTypes eUnitClass = (UnitClassTypes)GC.getUnitInfo(eUnit).getUnitClassType(); if (!isHuman() && !isBarbarian()) { iPrice *= GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIUnitUpgradePercent(); iPrice /= 100; iPrice *= std::max(0, ((GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIPerEraModifier() * GET_PLAYER(getOwnerINLINE()).getCurrentEra()) + 100)); iPrice /= 100; } iPrice -= (iPrice * getUpgradeDiscount()) / 100; return iPrice; } bool CvUnit::upgradeAvailable(UnitTypes eFromUnit, UnitClassTypes eToUnitClass, int iCount) const { UnitTypes eLoopUnit; int iI; int numUnitClassInfos = GC.getNumUnitClassInfos(); if (iCount > numUnitClassInfos) { return false; } CvUnitInfo &fromUnitInfo = GC.getUnitInfo(eFromUnit); if (fromUnitInfo.getUpgradeUnitClass(eToUnitClass)) { return true; } for (iI = 0; iI < numUnitClassInfos; iI++) { if (fromUnitInfo.getUpgradeUnitClass(iI)) { eLoopUnit = ((UnitTypes)(GC.getCivilizationInfo(getCivilizationType()).getCivilizationUnits(iI))); if (eLoopUnit != NO_UNIT) { if (upgradeAvailable(eLoopUnit, eToUnitClass, (iCount + 1))) { return true; } } } } return false; } bool CvUnit::canUpgrade(UnitTypes eUnit, bool bTestVisible) const { if (eUnit == NO_UNIT) { return false; } if(!isReadyForUpgrade()) { return false; } if (!bTestVisible) { if (GET_PLAYER(getOwnerINLINE()).getGold() < upgradePrice(eUnit)) { return false; } } if (hasUpgrade(eUnit)) { return true; } return false; } bool CvUnit::isReadyForUpgrade() const { if (!canMove()) { return false; } if (plot()->getTeam() != getTeam()) { return false; } return true; } // has upgrade is used to determine if an upgrade is possible, // it specifically does not check whether the unit can move, whether the current plot is owned, enough gold // those are checked in canUpgrade() // does not search all cities, only checks the closest one bool CvUnit::hasUpgrade(bool bSearch) const { return (getUpgradeCity(bSearch) != NULL); } // has upgrade is used to determine if an upgrade is possible, // it specifically does not check whether the unit can move, whether the current plot is owned, enough gold // those are checked in canUpgrade() // does not search all cities, only checks the closest one bool CvUnit::hasUpgrade(UnitTypes eUnit, bool bSearch) const { return (getUpgradeCity(eUnit, bSearch) != NULL); } // finds the 'best' city which has a valid upgrade for the unit, // it specifically does not check whether the unit can move, or if the player has enough gold to upgrade // those are checked in canUpgrade() // if bSearch is true, it will check every city, if not, it will only check the closest valid city // NULL result means the upgrade is not possible CvCity* CvUnit::getUpgradeCity(bool bSearch) const { CvPlayerAI& kPlayer = GET_PLAYER(getOwnerINLINE()); UnitAITypes eUnitAI = AI_getUnitAIType(); CvArea* pArea = area(); int iCurrentValue = kPlayer.AI_unitValue(getUnitType(), eUnitAI, pArea); int iBestSearchValue = MAX_INT; CvCity* pBestUpgradeCity = NULL; for (int iI = 0; iI < GC.getNumUnitInfos(); iI++) { int iNewValue = kPlayer.AI_unitValue(((UnitTypes)iI), eUnitAI, pArea); if (iNewValue > iCurrentValue) { int iSearchValue; CvCity* pUpgradeCity = getUpgradeCity((UnitTypes)iI, bSearch, &iSearchValue); if (pUpgradeCity != NULL) { // if not searching or close enough, then this match will do if (!bSearch || iSearchValue < 16) { return pUpgradeCity; } if (iSearchValue < iBestSearchValue) { iBestSearchValue = iSearchValue; pBestUpgradeCity = pUpgradeCity; } } } } return pBestUpgradeCity; } // finds the 'best' city which has a valid upgrade for the unit, to eUnit type // it specifically does not check whether the unit can move, or if the player has enough gold to upgrade // those are checked in canUpgrade() // if bSearch is true, it will check every city, if not, it will only check the closest valid city // if iSearchValue non NULL, then on return it will be the city's proximity value, lower is better // NULL result means the upgrade is not possible CvCity* CvUnit::getUpgradeCity(UnitTypes eUnit, bool bSearch, int* iSearchValue) const { if (eUnit == NO_UNIT) { return false; } CvPlayerAI& kPlayer = GET_PLAYER(getOwnerINLINE()); CvUnitInfo& kUnitInfo = GC.getUnitInfo(eUnit); if (GC.getCivilizationInfo(kPlayer.getCivilizationType()).getCivilizationUnits(kUnitInfo.getUnitClassType()) != eUnit) { return false; } if (!upgradeAvailable(getUnitType(), ((UnitClassTypes)(kUnitInfo.getUnitClassType())))) { return false; } if (kUnitInfo.getCargoSpace() < getCargo()) { return false; } CLLNode<IDInfo>* pUnitNode = plot()->headUnitNode(); while (pUnitNode != NULL) { CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = plot()->nextUnitNode(pUnitNode); if (pLoopUnit->getTransportUnit() == this) { if (kUnitInfo.getSpecialCargo() != NO_SPECIALUNIT) { if (kUnitInfo.getSpecialCargo() != pLoopUnit->getSpecialUnitType()) { return false; } } if (kUnitInfo.getDomainCargo() != NO_DOMAIN) { if (kUnitInfo.getDomainCargo() != pLoopUnit->getDomainType()) { return false; } } } } // sea units must be built on the coast bool bCoastalOnly = (getDomainType() == DOMAIN_SEA); // results int iBestValue = MAX_INT; CvCity* pBestCity = NULL; // if search is true, check every city for our team if (bSearch) { // air units can travel any distance bool bIgnoreDistance = (getDomainType() == DOMAIN_AIR); TeamTypes eTeam = getTeam(); int iArea = getArea(); int iX = getX_INLINE(), iY = getY_INLINE(); // check every player on our team's cities for (int iI = 0; iI < MAX_PLAYERS; iI++) { // is this player on our team? CvPlayerAI& kLoopPlayer = GET_PLAYER((PlayerTypes)iI); if (kLoopPlayer.isAlive() && kLoopPlayer.getTeam() == eTeam) { int iLoop; for (CvCity* pLoopCity = kLoopPlayer.firstCity(&iLoop); pLoopCity != NULL; pLoopCity = kLoopPlayer.nextCity(&iLoop)) { // if coastal only, then make sure we are coast CvArea* pWaterArea = NULL; if (!bCoastalOnly || ((pWaterArea = pLoopCity->waterArea()) != NULL && !pWaterArea->isLake())) { // can this city tran this unit? if (pLoopCity->canTrain(eUnit, false, false, true)) { // if we do not care about distance, then the first match will do if (bIgnoreDistance) { // if we do not care about distance, then return 1 for value if (iSearchValue != NULL) { *iSearchValue = 1; } return pLoopCity; } int iValue = plotDistance(iX, iY, pLoopCity->getX_INLINE(), pLoopCity->getY_INLINE()); // if not same area, not as good (lower numbers are better) if (iArea != pLoopCity->getArea() && (!bCoastalOnly || iArea != pWaterArea->getID())) { iValue *= 16; } // if we cannot path there, not as good (lower numbers are better) if (!generatePath(pLoopCity->plot(), 0, true)) { iValue *= 16; } if (iValue < iBestValue) { iBestValue = iValue; pBestCity = pLoopCity; } } } } } } } else { // find the closest city CvCity* pClosestCity = GC.getMapINLINE().findCity(getX_INLINE(), getY_INLINE(), NO_PLAYER, getTeam(), true, bCoastalOnly); if (pClosestCity != NULL) { // if we can train, then return this city (otherwise it will return NULL) if (pClosestCity->canTrain(eUnit, false, false, true)) { // did not search, always return 1 for search value iBestValue = 1; pBestCity = pClosestCity; } } } // return the best value, if non-NULL if (iSearchValue != NULL) { *iSearchValue = iBestValue; } return pBestCity; } void CvUnit::upgrade(UnitTypes eUnit) { CvUnit* pUpgradeUnit; if (!canUpgrade(eUnit)) { return; } GET_PLAYER(getOwnerINLINE()).changeGold(-(upgradePrice(eUnit))); pUpgradeUnit = GET_PLAYER(getOwnerINLINE()).initUnit(eUnit, getX_INLINE(), getY_INLINE(), AI_getUnitAIType()); FAssertMsg(pUpgradeUnit != NULL, "UpgradeUnit is not assigned a valid value"); pUpgradeUnit->joinGroup(getGroup()); pUpgradeUnit->convert(this); //TODO Vincentz upgrade takes 3 turns pUpgradeUnit->changeMoves(maxMoves() * 3); //pUpgradeUnit->finishMoves(); //Vincentz Upgrade end if (pUpgradeUnit->getLeaderUnitType() == NO_UNIT) { int MaxXPEra = GC.getDefineINT("MAX_EXPERIENCE_AFTER_UPGRADE") * GET_PLAYER(getOwnerINLINE()).getCurrentEra(); if (pUpgradeUnit->getExperience() > MaxXPEra) { //Vincentz Upgrade softcap // pUpgradeUnit->setExperience(((pUpgradeUnit->getExperience() - GC.getDefineINT("MAX_EXPERIENCE_AFTER_UPGRADE")) / 2) + GC.getDefineINT("MAX_EXPERIENCE_AFTER_UPGRADE")); pUpgradeUnit->setExperience((pUpgradeUnit->getExperience() - MaxXPEra / 2) + MaxXPEra); //pUpgradeUnit->setExperience(GC.getDefineINT("MAX_EXPERIENCE_AFTER_UPGRADE")); //getCurrentEra() } } } HandicapTypes CvUnit::getHandicapType() const { return GET_PLAYER(getOwnerINLINE()).getHandicapType(); } CivilizationTypes CvUnit::getCivilizationType() const { return GET_PLAYER(getOwnerINLINE()).getCivilizationType(); } const wchar* CvUnit::getVisualCivAdjective(TeamTypes eForTeam) const { if (getVisualOwner(eForTeam) == getOwnerINLINE()) { return GC.getCivilizationInfo(getCivilizationType()).getAdjectiveKey(); } return L""; } SpecialUnitTypes CvUnit::getSpecialUnitType() const { return ((SpecialUnitTypes)(m_pUnitInfo->getSpecialUnitType())); } UnitTypes CvUnit::getCaptureUnitType(CivilizationTypes eCivilization) const { FAssert(eCivilization != NO_CIVILIZATION); return ((m_pUnitInfo->getUnitCaptureClassType() == NO_UNITCLASS) ? NO_UNIT : (UnitTypes)GC.getCivilizationInfo(eCivilization).getCivilizationUnits(m_pUnitInfo->getUnitCaptureClassType())); } UnitCombatTypes CvUnit::getUnitCombatType() const { return ((UnitCombatTypes)(m_pUnitInfo->getUnitCombatType())); } DomainTypes CvUnit::getDomainType() const { return ((DomainTypes)(m_pUnitInfo->getDomainType())); } InvisibleTypes CvUnit::getInvisibleType() const { return ((InvisibleTypes)(m_pUnitInfo->getInvisibleType())); } int CvUnit::getNumSeeInvisibleTypes() const { /**************************************** * Archid Mod: 10 Oct 2012 * Functionality: SeeInvisiblePromotion - Archid * * Source: * Archid * **************************************** return m_pUnitInfo->getNumSeeInvisibleTypes(); ** ---- End Original Code ---- **/ int numSeeInvisibles = 0; for (int i = 0; i < GC.getNumInvisibleInfos(); i++) { if (getSeeInvisibleCount((InvisibleTypes)i) > 0) { numSeeInvisibles++; } } return numSeeInvisibles; /** ** End: SeeInvisiblePromotion **/ } InvisibleTypes CvUnit::getSeeInvisibleType(int i) const { /**************************************** * Archid Mod: 10 Oct 2012 * Functionality: SeeInvisiblePromotion - Archid * * Source: * Archid * **************************************** return (InvisibleTypes)(m_pUnitInfo->getSeeInvisibleType(i)); ** ---- End Original Code ---- **/ InvisibleTypes eInvisibleType = NO_INVISIBLE; int currSeeVisibleIndex = 0; for (int j = 0; j < GC.getNumInvisibleInfos(); j++) { if (getSeeInvisibleCount((InvisibleTypes)j) > 0 && currSeeVisibleIndex++ == i) { return (InvisibleTypes)j; } } return eInvisibleType; /** ** End: SeeInvisiblePromotion **/ } int CvUnit::flavorValue(FlavorTypes eFlavor) const { return m_pUnitInfo->getFlavorValue(eFlavor); } bool CvUnit::isBarbarian() const { return GET_PLAYER(getOwnerINLINE()).isBarbarian(); } bool CvUnit::isHuman() const { return GET_PLAYER(getOwnerINLINE()).isHuman(); } int CvUnit::visibilityRange() const { return (GC.getDefineINT("UNIT_VISIBILITY_RANGE") + getExtraVisibilityRange()); } int CvUnit::baseMoves() const { return (m_pUnitInfo->getMoves() + getExtraMoves() + GET_TEAM(getTeam()).getExtraMoves(getDomainType())); } int CvUnit::maxMoves() const { return (baseMoves() * GC.getMOVE_DENOMINATOR()); } int CvUnit::movesLeft() const { //Vincentz Moves // return std::max(0, (maxMoves() - getMoves())); return maxMoves() - getMoves(); } bool CvUnit::canMove() const { if (isDead()) { return false; } if (getMoves() >= maxMoves()) { return false; } if (getImmobileTimer() > 0) { return false; } return true; } bool CvUnit::hasMoved() const { return (getMoves() > 0); } int CvUnit::airRange() const { return (m_pUnitInfo->getAirRange() + getExtraAirRange()); } int CvUnit::nukeRange() const { return m_pUnitInfo->getNukeRange(); } // XXX should this test for coal? bool CvUnit::canBuildRoute() const { int iI; for (iI = 0; iI < GC.getNumBuildInfos(); iI++) { if (GC.getBuildInfo((BuildTypes)iI).getRoute() != NO_ROUTE) { if (m_pUnitInfo->getBuilds(iI)) { if (GET_TEAM(getTeam()).isHasTech((TechTypes)(GC.getBuildInfo((BuildTypes)iI).getTechPrereq()))) { return true; } } } } return false; } BuildTypes CvUnit::getBuildType() const { BuildTypes eBuild; if (getGroup()->headMissionQueueNode() != NULL) { switch (getGroup()->headMissionQueueNode()->m_data.eMissionType) { case MISSION_MOVE_TO: break; case MISSION_ROUTE_TO: if (getGroup()->getBestBuildRoute(plot(), &eBuild) != NO_ROUTE) { return eBuild; } break; case MISSION_MOVE_TO_UNIT: case MISSION_SKIP: case MISSION_SLEEP: case MISSION_FORTIFY: case MISSION_PLUNDER: case MISSION_AIRPATROL: case MISSION_SEAPATROL: case MISSION_HEAL: case MISSION_SENTRY: case MISSION_AIRLIFT: case MISSION_NUKE: case MISSION_RECON: case MISSION_PARADROP: case MISSION_AIRBOMB: case MISSION_BOMBARD: case MISSION_RANGE_ATTACK: case MISSION_PILLAGE: case MISSION_SABOTAGE: case MISSION_DESTROY: case MISSION_STEAL_PLANS: case MISSION_FOUND: case MISSION_SPREAD: case MISSION_SPREAD_CORPORATION: case MISSION_JOIN: case MISSION_CONSTRUCT: case MISSION_DISCOVER: case MISSION_HURRY: case MISSION_TRADE: case MISSION_GREAT_WORK: case MISSION_INFILTRATE: case MISSION_GOLDEN_AGE: case MISSION_LEAD: case MISSION_ESPIONAGE: case MISSION_DIE_ANIMATION: break; case MISSION_BUILD: return (BuildTypes)getGroup()->headMissionQueueNode()->m_data.iData1; break; default: FAssert(false); break; } } return NO_BUILD; } int CvUnit::workRate(bool bMax) const { int iRate; if (!bMax) { if (!canMove()) { return 0; } } iRate = m_pUnitInfo->getWorkRate(); iRate *= std::max(0, (GET_PLAYER(getOwnerINLINE()).getWorkerSpeedModifier() + 100)); iRate /= 100; if (!isHuman() && !isBarbarian()) { iRate *= std::max(0, (GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIWorkRateModifier() + 100)); iRate /= 100; } return iRate; } bool CvUnit::isAnimal() const { return m_pUnitInfo->isAnimal(); } bool CvUnit::isNoBadGoodies() const { return m_pUnitInfo->isNoBadGoodies(); } bool CvUnit::isOnlyDefensive() const { return m_pUnitInfo->isOnlyDefensive(); } bool CvUnit::isNoCapture() const { return m_pUnitInfo->isNoCapture(); } bool CvUnit::isRivalTerritory() const { return m_pUnitInfo->isRivalTerritory(); } bool CvUnit::isMilitaryHappiness() const { return m_pUnitInfo->isMilitaryHappiness(); } bool CvUnit::isInvestigate() const { return m_pUnitInfo->isInvestigate(); } bool CvUnit::isCounterSpy() const { return m_pUnitInfo->isCounterSpy(); } bool CvUnit::isSpy() const { return m_pUnitInfo->isSpy(); } bool CvUnit::isFound() const { return m_pUnitInfo->isFound(); } bool CvUnit::isGoldenAge() const { if (isDelayedDeath()) { return false; } return m_pUnitInfo->isGoldenAge(); } bool CvUnit::canCoexistWithEnemyUnit(TeamTypes eTeam) const { if (NO_TEAM == eTeam) { if(alwaysInvisible()) { return true; } return false; } if(isInvisible(eTeam, false)) { return true; } return false; } bool CvUnit::isFighting() const { return (getCombatUnit() != NULL); } bool CvUnit::isAttacking() const { return (getAttackPlot() != NULL && !isDelayedDeath()); } bool CvUnit::isDefending() const { return (isFighting() && !isAttacking()); } bool CvUnit::isCombat() const { return (isFighting() || isAttacking()); } int CvUnit::maxHitPoints() const { return GC.getMAX_HIT_POINTS(); } int CvUnit::currHitPoints() const { return (maxHitPoints() - getDamage()); } bool CvUnit::isHurt() const { return (getDamage() > 0); } bool CvUnit::isDead() const { return (getDamage() >= maxHitPoints()); } void CvUnit::setBaseCombatStr(int iCombat) { m_iBaseCombat = iCombat; } int CvUnit::baseCombatStr() const { return m_iBaseCombat; } // maxCombatStr can be called in four different configurations // pPlot == NULL, pAttacker == NULL for combat when this is the attacker // pPlot valid, pAttacker valid for combat when this is the defender // pPlot valid, pAttacker == NULL (new case), when this is the defender, attacker unknown // pPlot valid, pAttacker == this (new case), when the defender is unknown, but we want to calc approx str // note, in this last case, it is expected pCombatDetails == NULL, it does not have to be, but some // values may be unexpectedly reversed in this case (iModifierTotal will be the negative sum) int CvUnit::maxCombatStr(const CvPlot* pPlot, const CvUnit* pAttacker, CombatDetails* pCombatDetails) const { int iCombat; FAssertMsg((pPlot == NULL) || (pPlot->getTerrainType() != NO_TERRAIN), "(pPlot == NULL) || (pPlot->getTerrainType() is not expected to be equal with NO_TERRAIN)"); // handle our new special case const CvPlot* pAttackedPlot = NULL; bool bAttackingUnknownDefender = false; if (pAttacker == this) { bAttackingUnknownDefender = true; pAttackedPlot = pPlot; // reset these values, we will fiddle with them below pPlot = NULL; pAttacker = NULL; } // otherwise, attack plot is the plot of us (the defender) else if (pAttacker != NULL) { pAttackedPlot = plot(); } if (pCombatDetails != NULL) { pCombatDetails->iExtraCombatPercent = 0; pCombatDetails->iAnimalCombatModifierTA = 0; pCombatDetails->iAIAnimalCombatModifierTA = 0; pCombatDetails->iAnimalCombatModifierAA = 0; pCombatDetails->iAIAnimalCombatModifierAA = 0; pCombatDetails->iBarbarianCombatModifierTB = 0; pCombatDetails->iAIBarbarianCombatModifierTB = 0; pCombatDetails->iBarbarianCombatModifierAB = 0; pCombatDetails->iAIBarbarianCombatModifierAB = 0; pCombatDetails->iPlotDefenseModifier = 0; pCombatDetails->iFortifyModifier = 0; pCombatDetails->iCityDefenseModifier = 0; pCombatDetails->iHillsAttackModifier = 0; pCombatDetails->iHillsDefenseModifier = 0; pCombatDetails->iFeatureAttackModifier = 0; pCombatDetails->iFeatureDefenseModifier = 0; pCombatDetails->iTerrainAttackModifier = 0; pCombatDetails->iTerrainDefenseModifier = 0; pCombatDetails->iCityAttackModifier = 0; pCombatDetails->iDomainDefenseModifier = 0; pCombatDetails->iCityBarbarianDefenseModifier = 0; pCombatDetails->iClassDefenseModifier = 0; pCombatDetails->iClassAttackModifier = 0; pCombatDetails->iCombatModifierA = 0; pCombatDetails->iCombatModifierT = 0; pCombatDetails->iDomainModifierA = 0; pCombatDetails->iDomainModifierT = 0; pCombatDetails->iAnimalCombatModifierA = 0; pCombatDetails->iAnimalCombatModifierT = 0; pCombatDetails->iRiverAttackModifier = 0; pCombatDetails->iAmphibAttackModifier = 0; pCombatDetails->iKamikazeModifier = 0; pCombatDetails->iModifierTotal = 0; pCombatDetails->iBaseCombatStr = 0; pCombatDetails->iCombat = 0; pCombatDetails->iMaxCombatStr = 0; pCombatDetails->iCurrHitPoints = 0; pCombatDetails->iMaxHitPoints = 0; pCombatDetails->iCurrCombatStr = 0; pCombatDetails->eOwner = getOwnerINLINE(); pCombatDetails->eVisualOwner = getVisualOwner(); pCombatDetails->sUnitName = getName().GetCString(); } if (baseCombatStr() == 0) { return 0; } int iModifier = 0; int iExtraModifier; iExtraModifier = getExtraCombatPercent(); iModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iExtraCombatPercent = iExtraModifier; } // do modifiers for animals and barbarians (leaving these out for bAttackingUnknownDefender case) if (pAttacker != NULL) { if (isAnimal()) { if (pAttacker->isHuman()) { iExtraModifier = GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAnimalCombatModifier(); iModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iAnimalCombatModifierTA = iExtraModifier; } } else { iExtraModifier = GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIAnimalCombatModifier(); iModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iAIAnimalCombatModifierTA = iExtraModifier; } } } if (pAttacker->isAnimal()) { if (isHuman()) { iExtraModifier = -GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAnimalCombatModifier(); iModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iAnimalCombatModifierAA = iExtraModifier; } } else { iExtraModifier = -GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIAnimalCombatModifier(); iModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iAIAnimalCombatModifierAA = iExtraModifier; } } } if (isBarbarian()) { if (pAttacker->isHuman()) { iExtraModifier = GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getBarbarianCombatModifier(); iModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iBarbarianCombatModifierTB = iExtraModifier; } } else { iExtraModifier = GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIBarbarianCombatModifier(); iModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iAIBarbarianCombatModifierTB = iExtraModifier; } } } if (pAttacker->isBarbarian()) { if (isHuman()) { iExtraModifier = -GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getBarbarianCombatModifier(); iModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iBarbarianCombatModifierAB = iExtraModifier; } } else { iExtraModifier = -GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIBarbarianCombatModifier(); iModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iAIBarbarianCombatModifierTB = iExtraModifier; } } } } // add defensive bonuses (leaving these out for bAttackingUnknownDefender case) if (pPlot != NULL) { if (!noDefensiveBonus()) { iExtraModifier = pPlot->defenseModifier(getTeam(), (pAttacker != NULL) ? pAttacker->ignoreBuildingDefense() : true); iModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iPlotDefenseModifier = iExtraModifier; } } iExtraModifier = fortifyModifier(); iModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iFortifyModifier = iExtraModifier; } if (pPlot->isCity(true, getTeam())) { iExtraModifier = cityDefenseModifier(); iModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iCityDefenseModifier = iExtraModifier; } } if (pPlot->isHills()) { iExtraModifier = hillsDefenseModifier(); iModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iHillsDefenseModifier = iExtraModifier; } } if (pPlot->getFeatureType() != NO_FEATURE) { iExtraModifier = featureDefenseModifier(pPlot->getFeatureType()); iModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iFeatureDefenseModifier = iExtraModifier; } } else { iExtraModifier = terrainDefenseModifier(pPlot->getTerrainType()); iModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iTerrainDefenseModifier = iExtraModifier; } } } // if we are attacking to an plot with an unknown defender, the calc the modifier in reverse if (bAttackingUnknownDefender) { pAttacker = this; } // calc attacker bonueses if (pAttacker != NULL) { int iTempModifier = 0; if (pAttackedPlot->isCity(true, getTeam())) { iExtraModifier = -pAttacker->cityAttackModifier(); iTempModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iCityAttackModifier = iExtraModifier; } if (pAttacker->isBarbarian()) { iExtraModifier = GC.getDefineINT("CITY_BARBARIAN_DEFENSE_MODIFIER"); iTempModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iCityBarbarianDefenseModifier = iExtraModifier; } } } if (pAttackedPlot->isHills()) { iExtraModifier = -pAttacker->hillsAttackModifier(); iTempModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iHillsAttackModifier = iExtraModifier; } } if (pAttackedPlot->getFeatureType() != NO_FEATURE) { iExtraModifier = -pAttacker->featureAttackModifier(pAttackedPlot->getFeatureType()); iTempModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iFeatureAttackModifier = iExtraModifier; } } else { iExtraModifier = -pAttacker->terrainAttackModifier(pAttackedPlot->getTerrainType()); iModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iTerrainAttackModifier = iExtraModifier; } } // only compute comparisions if we are the defender with a known attacker if (!bAttackingUnknownDefender) { FAssertMsg(pAttacker != this, "pAttacker is not expected to be equal with this"); iExtraModifier = unitClassDefenseModifier(pAttacker->getUnitClassType()); iTempModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iClassDefenseModifier = iExtraModifier; } iExtraModifier = -pAttacker->unitClassAttackModifier(getUnitClassType()); iTempModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iClassAttackModifier = iExtraModifier; } if (pAttacker->getUnitCombatType() != NO_UNITCOMBAT) { iExtraModifier = unitCombatModifier(pAttacker->getUnitCombatType()); iTempModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iCombatModifierA = iExtraModifier; } } if (getUnitCombatType() != NO_UNITCOMBAT) { iExtraModifier = -pAttacker->unitCombatModifier(getUnitCombatType()); iTempModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iCombatModifierT = iExtraModifier; } } iExtraModifier = domainModifier(pAttacker->getDomainType()); iTempModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iDomainModifierA = iExtraModifier; } iExtraModifier = -pAttacker->domainModifier(getDomainType()); iTempModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iDomainModifierT = iExtraModifier; } if (pAttacker->isAnimal()) { iExtraModifier = animalCombatModifier(); iTempModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iAnimalCombatModifierA = iExtraModifier; } } if (isAnimal()) { iExtraModifier = -pAttacker->animalCombatModifier(); iTempModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iAnimalCombatModifierT = iExtraModifier; } } } if (!(pAttacker->isRiver())) { if (pAttacker->plot()->isRiverCrossing(directionXY(pAttacker->plot(), pAttackedPlot))) { iExtraModifier = -GC.getRIVER_ATTACK_MODIFIER(); iTempModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iRiverAttackModifier = iExtraModifier; } } } if (!(pAttacker->isAmphib())) { if (!(pAttackedPlot->isWater()) && pAttacker->plot()->isWater()) { iExtraModifier = -GC.getAMPHIB_ATTACK_MODIFIER(); iTempModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iAmphibAttackModifier = iExtraModifier; } } } if (pAttacker->getKamikazePercent() != 0) { iExtraModifier = pAttacker->getKamikazePercent(); iTempModifier += iExtraModifier; if (pCombatDetails != NULL) { pCombatDetails->iKamikazeModifier = iExtraModifier; } } // if we are attacking an unknown defender, then use the reverse of the modifier if (bAttackingUnknownDefender) { iModifier -= iTempModifier; } else { iModifier += iTempModifier; } } if (pCombatDetails != NULL) { pCombatDetails->iModifierTotal = iModifier; pCombatDetails->iBaseCombatStr = baseCombatStr(); } if (iModifier > 0) { iCombat = (baseCombatStr() * (iModifier + 100)); } else { iCombat = ((baseCombatStr() * 10000) / (100 - iModifier)); } if (pCombatDetails != NULL) { pCombatDetails->iCombat = iCombat; pCombatDetails->iMaxCombatStr = std::max(1, iCombat); pCombatDetails->iCurrHitPoints = currHitPoints(); pCombatDetails->iMaxHitPoints = maxHitPoints(); pCombatDetails->iCurrCombatStr = ((pCombatDetails->iMaxCombatStr * pCombatDetails->iCurrHitPoints) / pCombatDetails->iMaxHitPoints); } return std::max(1, iCombat); } int CvUnit::currCombatStr(const CvPlot* pPlot, const CvUnit* pAttacker, CombatDetails* pCombatDetails) const { return ((maxCombatStr(pPlot, pAttacker, pCombatDetails) * currHitPoints()) / maxHitPoints()); } int CvUnit::currFirepower(const CvPlot* pPlot, const CvUnit* pAttacker) const { return ((maxCombatStr(pPlot, pAttacker) + currCombatStr(pPlot, pAttacker) + 1) / 2); } // this nomalizes str by firepower, useful for quick odds calcs // the effect is that a damaged unit will have an effective str lowered by firepower/maxFirepower // doing the algebra, this means we mulitply by 1/2(1 + currHP)/maxHP = (maxHP + currHP) / (2 * maxHP) int CvUnit::currEffectiveStr(const CvPlot* pPlot, const CvUnit* pAttacker, CombatDetails* pCombatDetails) const { int currStr = currCombatStr(pPlot, pAttacker, pCombatDetails); currStr *= (maxHitPoints() + currHitPoints()); currStr /= (2 * maxHitPoints()); return currStr; } float CvUnit::maxCombatStrFloat(const CvPlot* pPlot, const CvUnit* pAttacker) const { return (((float)(maxCombatStr(pPlot, pAttacker))) / 100.0f); } float CvUnit::currCombatStrFloat(const CvPlot* pPlot, const CvUnit* pAttacker) const { return (((float)(currCombatStr(pPlot, pAttacker))) / 100.0f); } bool CvUnit::canFight() const { return (baseCombatStr() > 0); } bool CvUnit::canAttack() const { if (!canFight()) { return false; } if (isOnlyDefensive()) { return false; } return true; } bool CvUnit::canAttack(const CvUnit& defender) const { if (!canAttack()) { return false; } if (defender.getDamage() >= combatLimit()) { return false; } // Artillery can't amphibious attack if (plot()->isWater() && !defender.plot()->isWater()) { if (combatLimit() < 100) { return false; } } return true; } bool CvUnit::canDefend(const CvPlot* pPlot) const { if (pPlot == NULL) { pPlot = plot(); } if (!canFight()) { return false; } if (!pPlot->isValidDomainForAction(*this)) { if (GC.getDefineINT("LAND_UNITS_CAN_ATTACK_WATER_CITIES") == 0) { return false; } } return true; } bool CvUnit::canSiege(TeamTypes eTeam) const { if (!canDefend()) { return false; } if (!isEnemy(eTeam)) { return false; } if (!isNeverInvisible()) { return false; } return true; } int CvUnit::airBaseCombatStr() const { return m_pUnitInfo->getAirCombat(); } int CvUnit::airMaxCombatStr(const CvUnit* pOther) const { int iModifier; int iCombat; if (airBaseCombatStr() == 0) { return 0; } iModifier = getExtraCombatPercent(); if (getKamikazePercent() != 0) { iModifier += getKamikazePercent(); } if (getExtraCombatPercent() != 0) { iModifier += getExtraCombatPercent(); } if (NULL != pOther) { if (pOther->getUnitCombatType() != NO_UNITCOMBAT) { iModifier += unitCombatModifier(pOther->getUnitCombatType()); } iModifier += domainModifier(pOther->getDomainType()); if (pOther->isAnimal()) { iModifier += animalCombatModifier(); } } if (iModifier > 0) { iCombat = (airBaseCombatStr() * (iModifier + 100)); } else { iCombat = ((airBaseCombatStr() * 10000) / (100 - iModifier)); } return std::max(1, iCombat); } int CvUnit::airCurrCombatStr(const CvUnit* pOther) const { return ((airMaxCombatStr(pOther) * currHitPoints()) / maxHitPoints()); } float CvUnit::airMaxCombatStrFloat(const CvUnit* pOther) const { return (((float)(airMaxCombatStr(pOther))) / 100.0f); } float CvUnit::airCurrCombatStrFloat(const CvUnit* pOther) const { return (((float)(airCurrCombatStr(pOther))) / 100.0f); } int CvUnit::combatLimit() const { return m_pUnitInfo->getCombatLimit(); } int CvUnit::airCombatLimit() const { return m_pUnitInfo->getAirCombatLimit(); } bool CvUnit::canAirAttack() const { return (airBaseCombatStr() > 0); } bool CvUnit::canAirDefend(const CvPlot* pPlot) const { if (pPlot == NULL) { pPlot = plot(); } if (maxInterceptionProbability() == 0) { return false; } if (getDomainType() != DOMAIN_AIR) { if (!pPlot->isValidDomainForLocation(*this)) { return false; } } return true; } int CvUnit::airCombatDamage(const CvUnit* pDefender) const { CvCity* pCity; CvPlot* pPlot; int iOurStrength; int iTheirStrength; int iStrengthFactor; int iDamage; pPlot = pDefender->plot(); iOurStrength = airCurrCombatStr(pDefender); FAssertMsg(iOurStrength > 0, "Air combat strength is expected to be greater than zero"); iTheirStrength = pDefender->maxCombatStr(pPlot, this); iStrengthFactor = ((iOurStrength + iTheirStrength + 1) / 2); iDamage = std::max(1, ((GC.getDefineINT("AIR_COMBAT_DAMAGE") * (iOurStrength + iStrengthFactor)) / (iTheirStrength + iStrengthFactor))); pCity = pPlot->getPlotCity(); if (pCity != NULL) { iDamage *= std::max(0, (pCity->getAirModifier() + 100)); iDamage /= 100; } //Vincentz Random Damage Start iDamage *= (50 + GC.getGameINLINE().getSorenRandNum(100, "RandomHit")); iDamage /= 100; //Vincentz Random Damage End return iDamage; } int CvUnit::rangeCombatDamage(const CvUnit* pDefender) const { CvPlot* pPlot; int iOurStrength; int iTheirStrength; int iStrengthFactor; int iDamage; pPlot = pDefender->plot(); iOurStrength = airCurrCombatStr(pDefender); FAssertMsg(iOurStrength > 0, "Combat strength is expected to be greater than zero"); iTheirStrength = pDefender->maxCombatStr(pPlot, this); iStrengthFactor = ((iOurStrength + iTheirStrength + 1) / 2); iDamage = std::max(1, ((GC.getDefineINT("RANGE_COMBAT_DAMAGE") * (iOurStrength + iStrengthFactor)) / (iTheirStrength + iStrengthFactor))); //Vincentz Random Damage Start if (pPlot->getPlotCity() != NULL) { iDamage *= 100; iDamage /= std::max(0, (pPlot->getPlotCity()->getBuildingDefense() + 100)); } iDamage *= (50 + GC.getGameINLINE().getSorenRandNum(100, "RandomHit")); iDamage /= 100; //Vincentz Random Damage End return iDamage; } CvUnit* CvUnit::bestInterceptor(const CvPlot* pPlot) const { CvUnit* pLoopUnit; CvUnit* pBestUnit; int iValue; int iBestValue; int iLoop; int iI; iBestValue = 0; pBestUnit = NULL; for (iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { if (isEnemy(GET_PLAYER((PlayerTypes)iI).getTeam()) && !isInvisible(GET_PLAYER((PlayerTypes)iI).getTeam(), false, false)) { for(pLoopUnit = GET_PLAYER((PlayerTypes)iI).firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = GET_PLAYER((PlayerTypes)iI).nextUnit(&iLoop)) { if (pLoopUnit->canAirDefend()) { if (!pLoopUnit->isMadeInterception()) { if ((pLoopUnit->getDomainType() != DOMAIN_AIR) || !(pLoopUnit->hasMoved())) { if ((pLoopUnit->getDomainType() != DOMAIN_AIR) || (pLoopUnit->getGroup()->getActivityType() == ACTIVITY_INTERCEPT)) { if (plotDistance(pLoopUnit->getX_INLINE(), pLoopUnit->getY_INLINE(), pPlot->getX_INLINE(), pPlot->getY_INLINE()) <= pLoopUnit->airRange()) { iValue = pLoopUnit->currInterceptionProbability(); if (iValue > iBestValue) { iBestValue = iValue; pBestUnit = pLoopUnit; } } } } } } } } } } return pBestUnit; } CvUnit* CvUnit::bestSeaPillageInterceptor(CvUnit* pPillager, int iMinOdds) const { CvUnit* pBestUnit = NULL; for (int iDX = -1; iDX <= 1; ++iDX) { for (int iDY = -1; iDY <= 1; ++iDY) { CvPlot* pLoopPlot = plotXY(pPillager->getX_INLINE(), pPillager->getY_INLINE(), iDX, iDY); if (NULL != pLoopPlot) { CLLNode<IDInfo>* pUnitNode = pLoopPlot->headUnitNode(); while (NULL != pUnitNode) { CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pLoopPlot->nextUnitNode(pUnitNode); if (NULL != pLoopUnit) { if (pLoopUnit->area() == pPillager->plot()->area()) { if (!pLoopUnit->isInvisible(getTeam(), false)) { if (isEnemy(pLoopUnit->getTeam())) { if (DOMAIN_SEA == pLoopUnit->getDomainType()) { if (ACTIVITY_PATROL == pLoopUnit->getGroup()->getActivityType()) { if (NULL == pBestUnit || pLoopUnit->isBetterDefenderThan(pBestUnit, this)) { if (getCombatOdds(pPillager, pLoopUnit) < iMinOdds) { pBestUnit = pLoopUnit; } } } } } } } } } } } } return pBestUnit; } bool CvUnit::isAutomated() const { return getGroup()->isAutomated(); } bool CvUnit::isWaiting() const { return getGroup()->isWaiting(); } bool CvUnit::isFortifyable() const { if (!canFight() || noDefensiveBonus() || ((getDomainType() != DOMAIN_LAND) && (getDomainType() != DOMAIN_IMMOBILE))) { return false; } return true; } int CvUnit::fortifyModifier() const { if (!isFortifyable()) { return 0; } return (getFortifyTurns() * GC.getFORTIFY_MODIFIER_PER_TURN()); } int CvUnit::experienceNeeded() const { // Use python to determine pillage amounts... int iExperienceNeeded; long lExperienceNeeded; lExperienceNeeded = 0; iExperienceNeeded = 0; CyArgsList argsList; argsList.add(getLevel()); // pass in the units level argsList.add(getOwnerINLINE()); // pass in the units gDLL->getPythonIFace()->callFunction(PYGameModule, "getExperienceNeeded", argsList.makeFunctionArgs(),&lExperienceNeeded); iExperienceNeeded = (int)lExperienceNeeded; return iExperienceNeeded; } int CvUnit::attackXPValue() const { return m_pUnitInfo->getXPValueAttack(); } int CvUnit::defenseXPValue() const { return m_pUnitInfo->getXPValueDefense(); } int CvUnit::maxXPValue() const { int iMaxValue; iMaxValue = MAX_INT; if (isAnimal()) { iMaxValue = std::min(iMaxValue, GC.getDefineINT("ANIMAL_MAX_XP_VALUE")); } if (isBarbarian()) { iMaxValue = std::min(iMaxValue, GC.getDefineINT("BARBARIAN_MAX_XP_VALUE")); } return iMaxValue; } int CvUnit::firstStrikes() const { return std::max(0, (m_pUnitInfo->getFirstStrikes() + getExtraFirstStrikes())); } int CvUnit::chanceFirstStrikes() const { return std::max(0, (m_pUnitInfo->getChanceFirstStrikes() + getExtraChanceFirstStrikes())); } int CvUnit::maxFirstStrikes() const { return (firstStrikes() + chanceFirstStrikes()); } bool CvUnit::isRanged() const { int i; CvUnitInfo * pkUnitInfo = &getUnitInfo(); for ( i = 0; i < pkUnitInfo->getGroupDefinitions(); i++ ) { if ( !getArtInfo(i, GET_PLAYER(getOwnerINLINE()).getCurrentEra())->getActAsRanged() ) { return false; } } return true; } bool CvUnit::alwaysInvisible() const { return m_pUnitInfo->isInvisible(); } bool CvUnit::immuneToFirstStrikes() const { return (m_pUnitInfo->isFirstStrikeImmune() || (getImmuneToFirstStrikesCount() > 0)); } bool CvUnit::noDefensiveBonus() const { return m_pUnitInfo->isNoDefensiveBonus(); } bool CvUnit::ignoreBuildingDefense() const { return m_pUnitInfo->isIgnoreBuildingDefense(); } bool CvUnit::canMoveImpassable() const { return m_pUnitInfo->isCanMoveImpassable(); } bool CvUnit::canMoveAllTerrain() const { return m_pUnitInfo->isCanMoveAllTerrain(); } bool CvUnit::flatMovementCost() const { return m_pUnitInfo->isFlatMovementCost(); } bool CvUnit::ignoreTerrainCost() const { return m_pUnitInfo->isIgnoreTerrainCost(); } bool CvUnit::isNeverInvisible() const { return (!alwaysInvisible() && (getInvisibleType() == NO_INVISIBLE)); } bool CvUnit::isInvisible(TeamTypes eTeam, bool bDebug, bool bCheckCargo) const { if (bDebug && GC.getGameINLINE().isDebugMode()) { return false; } if (getTeam() == eTeam) { return false; } if (alwaysInvisible()) { return true; } if (bCheckCargo && isCargo()) { return true; } if (getInvisibleType() == NO_INVISIBLE) { return false; } return !(plot()->isInvisibleVisible(eTeam, getInvisibleType())); } bool CvUnit::isNukeImmune() const { return m_pUnitInfo->isNukeImmune(); } int CvUnit::maxInterceptionProbability() const { return std::max(0, m_pUnitInfo->getInterceptionProbability() + getExtraIntercept()); } int CvUnit::currInterceptionProbability() const { if (getDomainType() != DOMAIN_AIR) { return maxInterceptionProbability(); } else { return ((maxInterceptionProbability() * currHitPoints()) / maxHitPoints()); } } int CvUnit::evasionProbability() const { return std::max(0, m_pUnitInfo->getEvasionProbability() + getExtraEvasion()); } int CvUnit::withdrawalProbability() const { if (getDomainType() == DOMAIN_LAND && plot()->isWater()) { return 0; } return std::max(0, (m_pUnitInfo->getWithdrawalProbability() + getExtraWithdrawal())); } int CvUnit::collateralDamage() const { return std::max(0, (m_pUnitInfo->getCollateralDamage())); } int CvUnit::collateralDamageLimit() const { return std::max(0, m_pUnitInfo->getCollateralDamageLimit() * GC.getMAX_HIT_POINTS() / 100); } int CvUnit::collateralDamageMaxUnits() const { return std::max(0, m_pUnitInfo->getCollateralDamageMaxUnits()); } int CvUnit::cityAttackModifier() const { return (m_pUnitInfo->getCityAttackModifier() + getExtraCityAttackPercent()); } int CvUnit::cityDefenseModifier() const { return (m_pUnitInfo->getCityDefenseModifier() + getExtraCityDefensePercent()); } int CvUnit::animalCombatModifier() const { return m_pUnitInfo->getAnimalCombatModifier(); } int CvUnit::hillsAttackModifier() const { return (m_pUnitInfo->getHillsAttackModifier() + getExtraHillsAttackPercent()); } int CvUnit::hillsDefenseModifier() const { return (m_pUnitInfo->getHillsDefenseModifier() + getExtraHillsDefensePercent()); } int CvUnit::terrainAttackModifier(TerrainTypes eTerrain) const { FAssertMsg(eTerrain >= 0, "eTerrain is expected to be non-negative (invalid Index)"); FAssertMsg(eTerrain < GC.getNumTerrainInfos(), "eTerrain is expected to be within maximum bounds (invalid Index)"); return (m_pUnitInfo->getTerrainAttackModifier(eTerrain) + getExtraTerrainAttackPercent(eTerrain)); } int CvUnit::terrainDefenseModifier(TerrainTypes eTerrain) const { FAssertMsg(eTerrain >= 0, "eTerrain is expected to be non-negative (invalid Index)"); FAssertMsg(eTerrain < GC.getNumTerrainInfos(), "eTerrain is expected to be within maximum bounds (invalid Index)"); return (m_pUnitInfo->getTerrainDefenseModifier(eTerrain) + getExtraTerrainDefensePercent(eTerrain)); } int CvUnit::featureAttackModifier(FeatureTypes eFeature) const { FAssertMsg(eFeature >= 0, "eFeature is expected to be non-negative (invalid Index)"); FAssertMsg(eFeature < GC.getNumFeatureInfos(), "eFeature is expected to be within maximum bounds (invalid Index)"); return (m_pUnitInfo->getFeatureAttackModifier(eFeature) + getExtraFeatureAttackPercent(eFeature)); } int CvUnit::featureDefenseModifier(FeatureTypes eFeature) const { FAssertMsg(eFeature >= 0, "eFeature is expected to be non-negative (invalid Index)"); FAssertMsg(eFeature < GC.getNumFeatureInfos(), "eFeature is expected to be within maximum bounds (invalid Index)"); return (m_pUnitInfo->getFeatureDefenseModifier(eFeature) + getExtraFeatureDefensePercent(eFeature)); } int CvUnit::unitClassAttackModifier(UnitClassTypes eUnitClass) const { FAssertMsg(eUnitClass >= 0, "eUnitClass is expected to be non-negative (invalid Index)"); FAssertMsg(eUnitClass < GC.getNumUnitClassInfos(), "eUnitClass is expected to be within maximum bounds (invalid Index)"); return m_pUnitInfo->getUnitClassAttackModifier(eUnitClass); } int CvUnit::unitClassDefenseModifier(UnitClassTypes eUnitClass) const { FAssertMsg(eUnitClass >= 0, "eUnitClass is expected to be non-negative (invalid Index)"); FAssertMsg(eUnitClass < GC.getNumUnitClassInfos(), "eUnitClass is expected to be within maximum bounds (invalid Index)"); return m_pUnitInfo->getUnitClassDefenseModifier(eUnitClass); } int CvUnit::unitCombatModifier(UnitCombatTypes eUnitCombat) const { FAssertMsg(eUnitCombat >= 0, "eUnitCombat is expected to be non-negative (invalid Index)"); FAssertMsg(eUnitCombat < GC.getNumUnitCombatInfos(), "eUnitCombat is expected to be within maximum bounds (invalid Index)"); return (m_pUnitInfo->getUnitCombatModifier(eUnitCombat) + getExtraUnitCombatModifier(eUnitCombat)); } int CvUnit::domainModifier(DomainTypes eDomain) const { FAssertMsg(eDomain >= 0, "eDomain is expected to be non-negative (invalid Index)"); FAssertMsg(eDomain < NUM_DOMAIN_TYPES, "eDomain is expected to be within maximum bounds (invalid Index)"); return (m_pUnitInfo->getDomainModifier(eDomain) + getExtraDomainModifier(eDomain)); } int CvUnit::bombardRate() const { return (m_pUnitInfo->getBombardRate() + getExtraBombardRate()); } int CvUnit::airBombBaseRate() const { return m_pUnitInfo->getBombRate(); } int CvUnit::airBombCurrRate() const { return ((airBombBaseRate() * currHitPoints()) / maxHitPoints()); } SpecialUnitTypes CvUnit::specialCargo() const { return ((SpecialUnitTypes)(m_pUnitInfo->getSpecialCargo())); } DomainTypes CvUnit::domainCargo() const { return ((DomainTypes)(m_pUnitInfo->getDomainCargo())); } int CvUnit::cargoSpace() const { return m_iCargoCapacity; } void CvUnit::changeCargoSpace(int iChange) { if (iChange != 0) { m_iCargoCapacity += iChange; FAssert(m_iCargoCapacity >= 0); setInfoBarDirty(true); } } bool CvUnit::isFull() const { return (getCargo() >= cargoSpace()); } int CvUnit::cargoSpaceAvailable(SpecialUnitTypes eSpecialCargo, DomainTypes eDomainCargo) const { if (specialCargo() != NO_SPECIALUNIT) { if (specialCargo() != eSpecialCargo) { return 0; } } if (domainCargo() != NO_DOMAIN) { if (domainCargo() != eDomainCargo) { return 0; } } return std::max(0, (cargoSpace() - getCargo())); } bool CvUnit::hasCargo() const { return (getCargo() > 0); } bool CvUnit::canCargoAllMove() const { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; CvPlot* pPlot; pPlot = plot(); pUnitNode = pPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); if (pLoopUnit->getTransportUnit() == this) { if (pLoopUnit->getDomainType() == DOMAIN_LAND) { if (!(pLoopUnit->canMove())) { return false; } } } } return true; } bool CvUnit::canCargoEnterArea(TeamTypes eTeam, const CvArea* pArea, bool bIgnoreRightOfPassage) const { CvPlot* pPlot = plot(); CLLNode<IDInfo>* pUnitNode = pPlot->headUnitNode(); while (pUnitNode != NULL) { CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); if (pLoopUnit->getTransportUnit() == this) { if (!pLoopUnit->canEnterArea(eTeam, pArea, bIgnoreRightOfPassage)) { return false; } } } return true; } int CvUnit::getUnitAICargo(UnitAITypes eUnitAI) const { int iCount = 0; std::vector<CvUnit*> aCargoUnits; getCargoUnits(aCargoUnits); for (uint i = 0; i < aCargoUnits.size(); ++i) { if (aCargoUnits[i]->AI_getUnitAIType() == eUnitAI) { ++iCount; } } return iCount; } int CvUnit::getID() const { return m_iID; } int CvUnit::getIndex() const { return (getID() & FLTA_INDEX_MASK); } IDInfo CvUnit::getIDInfo() const { IDInfo unit(getOwnerINLINE(), getID()); return unit; } void CvUnit::setID(int iID) { m_iID = iID; } int CvUnit::getGroupID() const { return m_iGroupID; } bool CvUnit::isInGroup() const { return(getGroupID() != FFreeList::INVALID_INDEX); } bool CvUnit::isGroupHead() const // XXX is this used??? { return (getGroup()->getHeadUnit() == this); } CvSelectionGroup* CvUnit::getGroup() const { return GET_PLAYER(getOwnerINLINE()).getSelectionGroup(getGroupID()); } bool CvUnit::canJoinGroup(const CvPlot* pPlot, CvSelectionGroup* pSelectionGroup) const { CvUnit* pHeadUnit; // do not allow someone to join a group that is about to be split apart // this prevents a case of a never-ending turn if (pSelectionGroup->AI_isForceSeparate()) { return false; } if (pSelectionGroup->getOwnerINLINE() == NO_PLAYER) { pHeadUnit = pSelectionGroup->getHeadUnit(); if (pHeadUnit != NULL) { if (pHeadUnit->getOwnerINLINE() != getOwnerINLINE()) { return false; } } } else { if (pSelectionGroup->getOwnerINLINE() != getOwnerINLINE()) { return false; } } if (pSelectionGroup->getNumUnits() > 0) { if (!(pSelectionGroup->atPlot(pPlot))) { return false; } if (pSelectionGroup->getDomainType() != getDomainType()) { return false; } } return true; } void CvUnit::joinGroup(CvSelectionGroup* pSelectionGroup, bool bRemoveSelected, bool bRejoin) { CvSelectionGroup* pOldSelectionGroup; CvSelectionGroup* pNewSelectionGroup; CvPlot* pPlot; pOldSelectionGroup = GET_PLAYER(getOwnerINLINE()).getSelectionGroup(getGroupID()); if ((pSelectionGroup != pOldSelectionGroup) || (pOldSelectionGroup == NULL)) { pPlot = plot(); if (pSelectionGroup != NULL) { pNewSelectionGroup = pSelectionGroup; } else { if (bRejoin) { pNewSelectionGroup = GET_PLAYER(getOwnerINLINE()).addSelectionGroup(); pNewSelectionGroup->init(pNewSelectionGroup->getID(), getOwnerINLINE()); } else { pNewSelectionGroup = NULL; } } if ((pNewSelectionGroup == NULL) || canJoinGroup(pPlot, pNewSelectionGroup)) { if (pOldSelectionGroup != NULL) { bool bWasHead = false; if (!isHuman()) { if (pOldSelectionGroup->getNumUnits() > 1) { if (pOldSelectionGroup->getHeadUnit() == this) { bWasHead = true; } } } pOldSelectionGroup->removeUnit(this); // if we were the head, if the head unitAI changed, then force the group to separate (non-humans) if (bWasHead) { FAssert(pOldSelectionGroup->getHeadUnit() != NULL); if (pOldSelectionGroup->getHeadUnit()->AI_getUnitAIType() != AI_getUnitAIType()) { pOldSelectionGroup->AI_makeForceSeparate(); } } } if ((pNewSelectionGroup != NULL) && pNewSelectionGroup->addUnit(this, false)) { m_iGroupID = pNewSelectionGroup->getID(); } else { m_iGroupID = FFreeList::INVALID_INDEX; } if (getGroup() != NULL) { if (getGroup()->getNumUnits() > 1) { getGroup()->setActivityType(ACTIVITY_AWAKE); } else { GET_PLAYER(getOwnerINLINE()).updateGroupCycle(this); } } if (getTeam() == GC.getGameINLINE().getActiveTeam()) { if (pPlot != NULL) { pPlot->setFlagDirty(true); } } if (pPlot == gDLL->getInterfaceIFace()->getSelectionPlot()) { gDLL->getInterfaceIFace()->setDirty(PlotListButtons_DIRTY_BIT, true); } } if (bRemoveSelected) { if (IsSelected()) { gDLL->getInterfaceIFace()->removeFromSelectionList(this); } } } } int CvUnit::getHotKeyNumber() { return m_iHotKeyNumber; } void CvUnit::setHotKeyNumber(int iNewValue) { CvUnit* pLoopUnit; int iLoop; FAssert(getOwnerINLINE() != NO_PLAYER); if (getHotKeyNumber() != iNewValue) { if (iNewValue != -1) { for(pLoopUnit = GET_PLAYER(getOwnerINLINE()).firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = GET_PLAYER(getOwnerINLINE()).nextUnit(&iLoop)) { if (pLoopUnit->getHotKeyNumber() == iNewValue) { pLoopUnit->setHotKeyNumber(-1); } } } m_iHotKeyNumber = iNewValue; if (IsSelected()) { gDLL->getInterfaceIFace()->setDirty(InfoPane_DIRTY_BIT, true); } } } int CvUnit::getX() const { return m_iX; } int CvUnit::getY() const { return m_iY; } void CvUnit::setXY(int iX, int iY, bool bGroup, bool bUpdate, bool bShow, bool bCheckPlotVisible) { CLLNode<IDInfo>* pUnitNode; CvCity* pOldCity; CvCity* pNewCity; CvCity* pWorkingCity; CvUnit* pTransportUnit; CvUnit* pLoopUnit; CvPlot* pOldPlot; CvPlot* pNewPlot; CvPlot* pLoopPlot; CLinkList<IDInfo> oldUnits; ActivityTypes eOldActivityType; int iI; // OOS!! Temporary for Out-of-Sync madness debugging... if (GC.getLogging()) { if (gDLL->getChtLvl() > 0) { char szOut[1024]; sprintf(szOut, "Player %d Unit %d (%S's %S) moving from %d:%d to %d:%d\n", getOwnerINLINE(), getID(), GET_PLAYER(getOwnerINLINE()).getNameKey(), getName().GetCString(), getX_INLINE(), getY_INLINE(), iX, iY); gDLL->messageControlLog(szOut); } } FAssert(!at(iX, iY)); FAssert(!isFighting()); FAssert((iX == INVALID_PLOT_COORD) || (GC.getMapINLINE().plotINLINE(iX, iY)->getX_INLINE() == iX)); FAssert((iY == INVALID_PLOT_COORD) || (GC.getMapINLINE().plotINLINE(iX, iY)->getY_INLINE() == iY)); if (getGroup() != NULL) { eOldActivityType = getGroup()->getActivityType(); } else { eOldActivityType = NO_ACTIVITY; } setBlockading(false); if (!bGroup || isCargo()) { joinGroup(NULL, true); bShow = false; } pNewPlot = GC.getMapINLINE().plotINLINE(iX, iY); if (pNewPlot != NULL) { pTransportUnit = getTransportUnit(); if (pTransportUnit != NULL) { if (!(pTransportUnit->atPlot(pNewPlot))) { setTransportUnit(NULL); } } if (canFight()) { oldUnits.clear(); pUnitNode = pNewPlot->headUnitNode(); while (pUnitNode != NULL) { oldUnits.insertAtEnd(pUnitNode->m_data); pUnitNode = pNewPlot->nextUnitNode(pUnitNode); } pUnitNode = oldUnits.head(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = oldUnits.next(pUnitNode); if (pLoopUnit != NULL) { if (isEnemy(pLoopUnit->getTeam(), pNewPlot) || pLoopUnit->isEnemy(getTeam())) { if (!pLoopUnit->canCoexistWithEnemyUnit(getTeam())) { if (NO_UNITCLASS == pLoopUnit->getUnitInfo().getUnitCaptureClassType() && pLoopUnit->canDefend(pNewPlot)) { pLoopUnit->jumpToNearestValidPlot(); // can kill unit } else { if (!m_pUnitInfo->isHiddenNationality() && !pLoopUnit->getUnitInfo().isHiddenNationality()) { GET_TEAM(pLoopUnit->getTeam()).changeWarWeariness(getTeam(), *pNewPlot, GC.getDefineINT("WW_UNIT_CAPTURED")); GET_TEAM(getTeam()).changeWarWeariness(pLoopUnit->getTeam(), *pNewPlot, GC.getDefineINT("WW_CAPTURED_UNIT")); GET_TEAM(getTeam()).AI_changeWarSuccess(pLoopUnit->getTeam(), GC.getDefineINT("WAR_SUCCESS_UNIT_CAPTURING")); } if (!isNoCapture()) { pLoopUnit->setCapturingPlayer(getOwnerINLINE()); } pLoopUnit->kill(false, getOwnerINLINE()); } } } } } } if (pNewPlot->isGoody(getTeam())) { GET_PLAYER(getOwnerINLINE()).doGoody(pNewPlot, this); } } pOldPlot = plot(); if (pOldPlot != NULL) { pOldPlot->removeUnit(this, bUpdate && !hasCargo()); pOldPlot->changeAdjacentSight(getTeam(), visibilityRange(), false, this, true); pOldPlot->area()->changeUnitsPerPlayer(getOwnerINLINE(), -1); pOldPlot->area()->changePower(getOwnerINLINE(), -(m_pUnitInfo->getPowerValue())); if (AI_getUnitAIType() != NO_UNITAI) { pOldPlot->area()->changeNumAIUnits(getOwnerINLINE(), AI_getUnitAIType(), -1); } if (isAnimal()) { pOldPlot->area()->changeAnimalsPerPlayer(getOwnerINLINE(), -1); } if (pOldPlot->getTeam() != getTeam() && (pOldPlot->getTeam() == NO_TEAM || !GET_TEAM(pOldPlot->getTeam()).isVassal(getTeam()))) { GET_PLAYER(getOwnerINLINE()).changeNumOutsideUnits(-1); } setLastMoveTurn(GC.getGameINLINE().getTurnSlice()); pOldCity = pOldPlot->getPlotCity(); if (pOldCity != NULL) { if (isMilitaryHappiness()) { pOldCity->changeMilitaryHappinessUnits(-1); } } pWorkingCity = pOldPlot->getWorkingCity(); if (pWorkingCity != NULL) { if (canSiege(pWorkingCity->getTeam())) { pWorkingCity->AI_setAssignWorkDirty(true); } } if (pOldPlot->isWater()) { for (iI = 0; iI < NUM_DIRECTION_TYPES; iI++) { pLoopPlot = plotDirection(pOldPlot->getX_INLINE(), pOldPlot->getY_INLINE(), ((DirectionTypes)iI)); if (pLoopPlot != NULL) { if (pLoopPlot->isWater()) { pWorkingCity = pLoopPlot->getWorkingCity(); if (pWorkingCity != NULL) { if (canSiege(pWorkingCity->getTeam())) { pWorkingCity->AI_setAssignWorkDirty(true); } } } } } } if (pOldPlot->isActiveVisible(true)) { pOldPlot->updateMinimapColor(); } if (pOldPlot == gDLL->getInterfaceIFace()->getSelectionPlot()) { gDLL->getInterfaceIFace()->verifyPlotListColumn(); gDLL->getInterfaceIFace()->setDirty(PlotListButtons_DIRTY_BIT, true); } } if (pNewPlot != NULL) { m_iX = pNewPlot->getX_INLINE(); m_iY = pNewPlot->getY_INLINE(); } else { m_iX = INVALID_PLOT_COORD; m_iY = INVALID_PLOT_COORD; } FAssertMsg(plot() == pNewPlot, "plot is expected to equal pNewPlot"); if (pNewPlot != NULL) { pNewCity = pNewPlot->getPlotCity(); if (pNewCity != NULL) { if (isEnemy(pNewCity->getTeam()) && !canCoexistWithEnemyUnit(pNewCity->getTeam()) && canFight()) { GET_TEAM(getTeam()).changeWarWeariness(pNewCity->getTeam(), *pNewPlot, GC.getDefineINT("WW_CAPTURED_CITY")); GET_TEAM(getTeam()).AI_changeWarSuccess(pNewCity->getTeam(), GC.getDefineINT("WAR_SUCCESS_CITY_CAPTURING")); PlayerTypes eNewOwner = GET_PLAYER(getOwnerINLINE()).pickConqueredCityOwner(*pNewCity); if (NO_PLAYER != eNewOwner) { GET_PLAYER(eNewOwner).acquireCity(pNewCity, true, false, true); // will delete the pointer pNewCity = NULL; } } } //update facing direction if(pOldPlot != NULL) { DirectionTypes newDirection = estimateDirection(pOldPlot, pNewPlot); if(newDirection != NO_DIRECTION) m_eFacingDirection = newDirection; } //update cargo mission animations if (isCargo()) { if (eOldActivityType != ACTIVITY_MISSION) { getGroup()->setActivityType(eOldActivityType); } } setFortifyTurns(0); pNewPlot->changeAdjacentSight(getTeam(), visibilityRange(), true, this, true); // needs to be here so that the square is considered visible when we move into it... pNewPlot->addUnit(this, bUpdate && !hasCargo()); pNewPlot->area()->changeUnitsPerPlayer(getOwnerINLINE(), 1); pNewPlot->area()->changePower(getOwnerINLINE(), m_pUnitInfo->getPowerValue()); if (AI_getUnitAIType() != NO_UNITAI) { pNewPlot->area()->changeNumAIUnits(getOwnerINLINE(), AI_getUnitAIType(), 1); } if (isAnimal()) { pNewPlot->area()->changeAnimalsPerPlayer(getOwnerINLINE(), 1); } if (pNewPlot->getTeam() != getTeam() && (pNewPlot->getTeam() == NO_TEAM || !GET_TEAM(pNewPlot->getTeam()).isVassal(getTeam()))) { GET_PLAYER(getOwnerINLINE()).changeNumOutsideUnits(1); } if (shouldLoadOnMove(pNewPlot)) { load(); } for (iI = 0; iI < MAX_CIV_TEAMS; iI++) { if (GET_TEAM((TeamTypes)iI).isAlive()) { if (!isInvisible(((TeamTypes)iI), false)) { if (pNewPlot->isVisible((TeamTypes)iI, false)) { GET_TEAM((TeamTypes)iI).meet(getTeam(), true); } } } } pNewCity = pNewPlot->getPlotCity(); if (pNewCity != NULL) { if (isMilitaryHappiness()) { pNewCity->changeMilitaryHappinessUnits(1); } } pWorkingCity = pNewPlot->getWorkingCity(); if (pWorkingCity != NULL) { if (canSiege(pWorkingCity->getTeam())) { pWorkingCity->verifyWorkingPlot(pWorkingCity->getCityPlotIndex(pNewPlot)); } } if (pNewPlot->isWater()) { for (iI = 0; iI < NUM_DIRECTION_TYPES; iI++) { pLoopPlot = plotDirection(pNewPlot->getX_INLINE(), pNewPlot->getY_INLINE(), ((DirectionTypes)iI)); if (pLoopPlot != NULL) { if (pLoopPlot->isWater()) { pWorkingCity = pLoopPlot->getWorkingCity(); if (pWorkingCity != NULL) { if (canSiege(pWorkingCity->getTeam())) { pWorkingCity->verifyWorkingPlot(pWorkingCity->getCityPlotIndex(pLoopPlot)); } } } } } } if (pNewPlot->isActiveVisible(true)) { pNewPlot->updateMinimapColor(); } if (GC.IsGraphicsInitialized()) { //override bShow if check plot visible if(bCheckPlotVisible && pNewPlot->isVisibleToWatchingHuman()) bShow = true; if (bShow) { QueueMove(pNewPlot); } else { SetPosition(pNewPlot); } } if (pNewPlot == gDLL->getInterfaceIFace()->getSelectionPlot()) { gDLL->getInterfaceIFace()->verifyPlotListColumn(); gDLL->getInterfaceIFace()->setDirty(PlotListButtons_DIRTY_BIT, true); } } if (pOldPlot != NULL) { if (hasCargo()) { pUnitNode = pOldPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pOldPlot->nextUnitNode(pUnitNode); if (pLoopUnit->getTransportUnit() == this) { pLoopUnit->setXY(iX, iY, bGroup, false); } } } } if (bUpdate && hasCargo()) { if (pOldPlot != NULL) { pOldPlot->updateCenterUnit(); pOldPlot->setFlagDirty(true); } if (pNewPlot != NULL) { pNewPlot->updateCenterUnit(); pNewPlot->setFlagDirty(true); } } FAssert(pOldPlot != pNewPlot); GET_PLAYER(getOwnerINLINE()).updateGroupCycle(this); setInfoBarDirty(true); if (IsSelected()) { if (isFound()) { gDLL->getInterfaceIFace()->setDirty(GlobeLayer_DIRTY_BIT, true); gDLL->getEngineIFace()->updateFoundingBorder(); } gDLL->getInterfaceIFace()->setDirty(ColoredPlots_DIRTY_BIT, true); } //update glow if (pNewPlot != NULL) { gDLL->getEntityIFace()->updateEnemyGlow(getUnitEntity()); } // report event to Python, along with some other key state CvEventReporter::getInstance().unitSetXY(pNewPlot, this); } bool CvUnit::at(int iX, int iY) const { return((getX_INLINE() == iX) && (getY_INLINE() == iY)); } bool CvUnit::atPlot(const CvPlot* pPlot) const { return (plot() == pPlot); } CvPlot* CvUnit::plot() const { return GC.getMapINLINE().plotSorenINLINE(getX_INLINE(), getY_INLINE()); } int CvUnit::getArea() const { return plot()->getArea(); } CvArea* CvUnit::area() const { return plot()->area(); } bool CvUnit::onMap() const { return (plot() != NULL); } int CvUnit::getLastMoveTurn() const { return m_iLastMoveTurn; } void CvUnit::setLastMoveTurn(int iNewValue) { m_iLastMoveTurn = iNewValue; FAssert(getLastMoveTurn() >= 0); } CvPlot* CvUnit::getReconPlot() const { return GC.getMapINLINE().plotSorenINLINE(m_iReconX, m_iReconY); } void CvUnit::setReconPlot(CvPlot* pNewValue) { CvPlot* pOldPlot; pOldPlot = getReconPlot(); if (pOldPlot != pNewValue) { if (pOldPlot != NULL) { pOldPlot->changeAdjacentSight(getTeam(), GC.getDefineINT("RECON_VISIBILITY_RANGE"), false, this, true); pOldPlot->changeReconCount(-1); // changeAdjacentSight() tests for getReconCount() } if (pNewValue == NULL) { m_iReconX = INVALID_PLOT_COORD; m_iReconY = INVALID_PLOT_COORD; } else { m_iReconX = pNewValue->getX_INLINE(); m_iReconY = pNewValue->getY_INLINE(); pNewValue->changeReconCount(1); // changeAdjacentSight() tests for getReconCount() pNewValue->changeAdjacentSight(getTeam(), GC.getDefineINT("RECON_VISIBILITY_RANGE"), true, this, true); } } } int CvUnit::getGameTurnCreated() const { return m_iGameTurnCreated; } void CvUnit::setGameTurnCreated(int iNewValue) { m_iGameTurnCreated = iNewValue; FAssert(getGameTurnCreated() >= 0); } int CvUnit::getDamage() const { return m_iDamage; } void CvUnit::setDamage(int iNewValue, PlayerTypes ePlayer, bool bNotifyEntity) { int iOldValue; iOldValue = getDamage(); m_iDamage = range(iNewValue, 0, maxHitPoints()); FAssertMsg(currHitPoints() >= 0, "currHitPoints() is expected to be non-negative (invalid Index)"); if (iOldValue != getDamage()) { if (GC.getGameINLINE().isFinalInitialized() && bNotifyEntity) { NotifyEntity(MISSION_DAMAGE); } setInfoBarDirty(true); if (IsSelected()) { gDLL->getInterfaceIFace()->setDirty(InfoPane_DIRTY_BIT, true); } if (plot() == gDLL->getInterfaceIFace()->getSelectionPlot()) { gDLL->getInterfaceIFace()->setDirty(PlotListButtons_DIRTY_BIT, true); } } if (isDead()) { kill(true, ePlayer); } } void CvUnit::changeDamage(int iChange, PlayerTypes ePlayer) { setDamage((getDamage() + iChange), ePlayer); } int CvUnit::getMoves() const { return m_iMoves; } void CvUnit::setMoves(int iNewValue) { CvPlot* pPlot; if (getMoves() != iNewValue) { pPlot = plot(); m_iMoves = iNewValue; //Vincentz Move // FAssert(getMoves() >= 0); if (getTeam() == GC.getGameINLINE().getActiveTeam()) { if (pPlot != NULL) { pPlot->setFlagDirty(true); } } if (IsSelected()) { gDLL->getFAStarIFace()->ForceReset(&GC.getInterfacePathFinder()); gDLL->getInterfaceIFace()->setDirty(InfoPane_DIRTY_BIT, true); } if (pPlot == gDLL->getInterfaceIFace()->getSelectionPlot()) { gDLL->getInterfaceIFace()->setDirty(PlotListButtons_DIRTY_BIT, true); } } } void CvUnit::changeMoves(int iChange) { setMoves(getMoves() + iChange); } void CvUnit::finishMoves() { //Vincentz vmoves setMoves(getMoves() + maxMoves()); } int CvUnit::getExperience() const { return m_iExperience; } void CvUnit::setExperience(int iNewValue, int iMax) { if ((getExperience() != iNewValue) && (getExperience() < ((iMax == -1) ? MAX_INT : iMax))) { m_iExperience = std::min(((iMax == -1) ? MAX_INT : iMax), iNewValue); FAssert(getExperience() >= 0); if (IsSelected()) { gDLL->getInterfaceIFace()->setDirty(InfoPane_DIRTY_BIT, true); } } } void CvUnit::changeExperience(int iChange, int iMax, bool bFromCombat, bool bInBorders, bool bUpdateGlobal) { int iUnitExperience = iChange; if (bFromCombat) { CvPlayer& kPlayer = GET_PLAYER(getOwnerINLINE()); int iCombatExperienceMod = 100 + kPlayer.getGreatGeneralRateModifier(); if (bInBorders) { iCombatExperienceMod += kPlayer.getDomesticGreatGeneralRateModifier() + kPlayer.getExpInBorderModifier(); iUnitExperience += (iChange * kPlayer.getExpInBorderModifier()) / 100; } if (bUpdateGlobal) { kPlayer.changeCombatExperience((iChange * iCombatExperienceMod) / 100); } if (getExperiencePercent() != 0) { iUnitExperience *= std::max(0, 100 + getExperiencePercent()); iUnitExperience /= 100; } } setExperience((getExperience() + iUnitExperience), iMax); } int CvUnit::getLevel() const { return m_iLevel; } void CvUnit::setLevel(int iNewValue) { if (getLevel() != iNewValue) { m_iLevel = iNewValue; FAssert(getLevel() >= 0); if (getLevel() > GET_PLAYER(getOwnerINLINE()).getHighestUnitLevel()) { GET_PLAYER(getOwnerINLINE()).setHighestUnitLevel(getLevel()); } if (IsSelected()) { gDLL->getInterfaceIFace()->setDirty(InfoPane_DIRTY_BIT, true); } } } void CvUnit::changeLevel(int iChange) { setLevel(getLevel() + iChange); } int CvUnit::getCargo() const { return m_iCargo; } void CvUnit::changeCargo(int iChange) { m_iCargo += iChange; FAssert(getCargo() >= 0); } void CvUnit::getCargoUnits(std::vector<CvUnit*>& aUnits) const { aUnits.clear(); if (hasCargo()) { CvPlot* pPlot = plot(); CLLNode<IDInfo>* pUnitNode = pPlot->headUnitNode(); while (pUnitNode != NULL) { CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); if (pLoopUnit->getTransportUnit() == this) { aUnits.push_back(pLoopUnit); } } } FAssert(getCargo() == aUnits.size()); } CvPlot* CvUnit::getAttackPlot() const { return GC.getMapINLINE().plotSorenINLINE(m_iAttackPlotX, m_iAttackPlotY); } void CvUnit::setAttackPlot(const CvPlot* pNewValue, bool bAirCombat) { if (getAttackPlot() != pNewValue) { if (pNewValue != NULL) { m_iAttackPlotX = pNewValue->getX_INLINE(); m_iAttackPlotY = pNewValue->getY_INLINE(); } else { m_iAttackPlotX = INVALID_PLOT_COORD; m_iAttackPlotY = INVALID_PLOT_COORD; } } m_bAirCombat = bAirCombat; } bool CvUnit::isAirCombat() const { return m_bAirCombat; } int CvUnit::getCombatTimer() const { return m_iCombatTimer; } void CvUnit::setCombatTimer(int iNewValue) { m_iCombatTimer = iNewValue; FAssert(getCombatTimer() >= 0); } void CvUnit::changeCombatTimer(int iChange) { setCombatTimer(getCombatTimer() + iChange); } int CvUnit::getCombatFirstStrikes() const { return m_iCombatFirstStrikes; } void CvUnit::setCombatFirstStrikes(int iNewValue) { m_iCombatFirstStrikes = iNewValue; FAssert(getCombatFirstStrikes() >= 0); } void CvUnit::changeCombatFirstStrikes(int iChange) { setCombatFirstStrikes(getCombatFirstStrikes() + iChange); } int CvUnit::getFortifyTurns() const { return m_iFortifyTurns; } void CvUnit::setFortifyTurns(int iNewValue) { iNewValue = range(iNewValue, 0, GC.getDefineINT("MAX_FORTIFY_TURNS")); if (iNewValue != getFortifyTurns()) { m_iFortifyTurns = iNewValue; setInfoBarDirty(true); } } void CvUnit::changeFortifyTurns(int iChange) { setFortifyTurns(getFortifyTurns() + iChange); } int CvUnit::getBlitzCount() const { return m_iBlitzCount; } bool CvUnit::isBlitz() const { return (getBlitzCount() > 0); } void CvUnit::changeBlitzCount(int iChange) { m_iBlitzCount += iChange; FAssert(getBlitzCount() >= 0); } int CvUnit::getAmphibCount() const { return m_iAmphibCount; } bool CvUnit::isAmphib() const { return (getAmphibCount() > 0); } void CvUnit::changeAmphibCount(int iChange) { m_iAmphibCount += iChange; FAssert(getAmphibCount() >= 0); } int CvUnit::getRiverCount() const { return m_iRiverCount; } bool CvUnit::isRiver() const { return (getRiverCount() > 0); } void CvUnit::changeRiverCount(int iChange) { m_iRiverCount += iChange; FAssert(getRiverCount() >= 0); } int CvUnit::getEnemyRouteCount() const { return m_iEnemyRouteCount; } bool CvUnit::isEnemyRoute() const { return (getEnemyRouteCount() > 0); } void CvUnit::changeEnemyRouteCount(int iChange) { m_iEnemyRouteCount += iChange; FAssert(getEnemyRouteCount() >= 0); } int CvUnit::getAlwaysHealCount() const { return m_iAlwaysHealCount; } bool CvUnit::isAlwaysHeal() const { return (getAlwaysHealCount() > 0); } void CvUnit::changeAlwaysHealCount(int iChange) { m_iAlwaysHealCount += iChange; FAssert(getAlwaysHealCount() >= 0); } int CvUnit::getHillsDoubleMoveCount() const { return m_iHillsDoubleMoveCount; } bool CvUnit::isHillsDoubleMove() const { return (getHillsDoubleMoveCount() > 0); } void CvUnit::changeHillsDoubleMoveCount(int iChange) { m_iHillsDoubleMoveCount += iChange; FAssert(getHillsDoubleMoveCount() >= 0); } int CvUnit::getImmuneToFirstStrikesCount() const { return m_iImmuneToFirstStrikesCount; } void CvUnit::changeImmuneToFirstStrikesCount(int iChange) { m_iImmuneToFirstStrikesCount += iChange; FAssert(getImmuneToFirstStrikesCount() >= 0); } int CvUnit::getExtraVisibilityRange() const { return m_iExtraVisibilityRange; } void CvUnit::changeExtraVisibilityRange(int iChange) { if (iChange != 0) { plot()->changeAdjacentSight(getTeam(), visibilityRange(), false, this, true); m_iExtraVisibilityRange += iChange; FAssert(getExtraVisibilityRange() >= 0); plot()->changeAdjacentSight(getTeam(), visibilityRange(), true, this, true); } } int CvUnit::getExtraMoves() const { return m_iExtraMoves; } void CvUnit::changeExtraMoves(int iChange) { m_iExtraMoves += iChange; //Vincentz Move // FAssert(getExtraMoves() >= 0); } int CvUnit::getExtraMoveDiscount() const { return m_iExtraMoveDiscount; } void CvUnit::changeExtraMoveDiscount(int iChange) { m_iExtraMoveDiscount += iChange; FAssert(getExtraMoveDiscount() >= 0); } int CvUnit::getExtraAirRange() const { return m_iExtraAirRange; } void CvUnit::changeExtraAirRange(int iChange) { m_iExtraAirRange += iChange; } int CvUnit::getExtraIntercept() const { return m_iExtraIntercept; } void CvUnit::changeExtraIntercept(int iChange) { m_iExtraIntercept += iChange; } int CvUnit::getExtraEvasion() const { return m_iExtraEvasion; } void CvUnit::changeExtraEvasion(int iChange) { m_iExtraEvasion += iChange; } int CvUnit::getExtraFirstStrikes() const { return m_iExtraFirstStrikes; } void CvUnit::changeExtraFirstStrikes(int iChange) { m_iExtraFirstStrikes += iChange; FAssert(getExtraFirstStrikes() >= 0); } int CvUnit::getExtraChanceFirstStrikes() const { return m_iExtraChanceFirstStrikes; } void CvUnit::changeExtraChanceFirstStrikes(int iChange) { m_iExtraChanceFirstStrikes += iChange; FAssert(getExtraChanceFirstStrikes() >= 0); } int CvUnit::getExtraWithdrawal() const { return m_iExtraWithdrawal; } void CvUnit::changeExtraWithdrawal(int iChange) { m_iExtraWithdrawal += iChange; FAssert(getExtraWithdrawal() >= 0); } int CvUnit::getExtraCollateralDamage() const { return m_iExtraCollateralDamage; } void CvUnit::changeExtraCollateralDamage(int iChange) { m_iExtraCollateralDamage += iChange; FAssert(getExtraCollateralDamage() >= 0); } int CvUnit::getExtraBombardRate() const { return m_iExtraBombardRate; } void CvUnit::changeExtraBombardRate(int iChange) { m_iExtraBombardRate += iChange; FAssert(getExtraBombardRate() >= 0); } int CvUnit::getExtraEnemyHeal() const { return m_iExtraEnemyHeal; } void CvUnit::changeExtraEnemyHeal(int iChange) { m_iExtraEnemyHeal += iChange; FAssert(getExtraEnemyHeal() >= 0); } int CvUnit::getExtraNeutralHeal() const { return m_iExtraNeutralHeal; } void CvUnit::changeExtraNeutralHeal(int iChange) { m_iExtraNeutralHeal += iChange; FAssert(getExtraNeutralHeal() >= 0); } int CvUnit::getExtraFriendlyHeal() const { return m_iExtraFriendlyHeal; } void CvUnit::changeExtraFriendlyHeal(int iChange) { m_iExtraFriendlyHeal += iChange; FAssert(getExtraFriendlyHeal() >= 0); } int CvUnit::getSameTileHeal() const { return m_iSameTileHeal; } void CvUnit::changeSameTileHeal(int iChange) { m_iSameTileHeal += iChange; FAssert(getSameTileHeal() >= 0); } int CvUnit::getAdjacentTileHeal() const { return m_iAdjacentTileHeal; } void CvUnit::changeAdjacentTileHeal(int iChange) { m_iAdjacentTileHeal += iChange; FAssert(getAdjacentTileHeal() >= 0); } int CvUnit::getExtraCombatPercent() const { return m_iExtraCombatPercent; } void CvUnit::changeExtraCombatPercent(int iChange) { if (iChange != 0) { m_iExtraCombatPercent += iChange; setInfoBarDirty(true); } } int CvUnit::getExtraCityAttackPercent() const { return m_iExtraCityAttackPercent; } void CvUnit::changeExtraCityAttackPercent(int iChange) { if (iChange != 0) { m_iExtraCityAttackPercent += iChange; setInfoBarDirty(true); } } int CvUnit::getExtraCityDefensePercent() const { return m_iExtraCityDefensePercent; } void CvUnit::changeExtraCityDefensePercent(int iChange) { if (iChange != 0) { m_iExtraCityDefensePercent += iChange; setInfoBarDirty(true); } } int CvUnit::getExtraHillsAttackPercent() const { return m_iExtraHillsAttackPercent; } void CvUnit::changeExtraHillsAttackPercent(int iChange) { if (iChange != 0) { m_iExtraHillsAttackPercent += iChange; setInfoBarDirty(true); } } int CvUnit::getExtraHillsDefensePercent() const { return m_iExtraHillsDefensePercent; } void CvUnit::changeExtraHillsDefensePercent(int iChange) { if (iChange != 0) { m_iExtraHillsDefensePercent += iChange; setInfoBarDirty(true); } } int CvUnit::getRevoltProtection() const { return m_iRevoltProtection; } void CvUnit::changeRevoltProtection(int iChange) { if (iChange != 0) { m_iRevoltProtection += iChange; setInfoBarDirty(true); } } int CvUnit::getCollateralDamageProtection() const { return m_iCollateralDamageProtection; } void CvUnit::changeCollateralDamageProtection(int iChange) { if (iChange != 0) { m_iCollateralDamageProtection += iChange; setInfoBarDirty(true); } } int CvUnit::getPillageChange() const { return m_iPillageChange; } void CvUnit::changePillageChange(int iChange) { if (iChange != 0) { m_iPillageChange += iChange; setInfoBarDirty(true); } } int CvUnit::getUpgradeDiscount() const { return m_iUpgradeDiscount; } void CvUnit::changeUpgradeDiscount(int iChange) { if (iChange != 0) { m_iUpgradeDiscount += iChange; setInfoBarDirty(true); } } int CvUnit::getExperiencePercent() const { return m_iExperiencePercent; } void CvUnit::changeExperiencePercent(int iChange) { if (iChange != 0) { m_iExperiencePercent += iChange; setInfoBarDirty(true); } } int CvUnit::getKamikazePercent() const { return m_iKamikazePercent; } void CvUnit::changeKamikazePercent(int iChange) { if (iChange != 0) { m_iKamikazePercent += iChange; setInfoBarDirty(true); } } DirectionTypes CvUnit::getFacingDirection(bool checkLineOfSightProperty) const { if (checkLineOfSightProperty) { if (m_pUnitInfo->isLineOfSight()) { return m_eFacingDirection; //only look in facing direction } else { return NO_DIRECTION; //look in all directions } } else { return m_eFacingDirection; } } void CvUnit::setFacingDirection(DirectionTypes eFacingDirection) { if (eFacingDirection != m_eFacingDirection) { if (m_pUnitInfo->isLineOfSight()) { //remove old fog plot()->changeAdjacentSight(getTeam(), visibilityRange(), false, this, true); //change direction m_eFacingDirection = eFacingDirection; //clear new fog plot()->changeAdjacentSight(getTeam(), visibilityRange(), true, this, true); gDLL->getInterfaceIFace()->setDirty(ColoredPlots_DIRTY_BIT, true); } else { m_eFacingDirection = eFacingDirection; } //update formation NotifyEntity(NO_MISSION); } } void CvUnit::rotateFacingDirectionClockwise() { //change direction DirectionTypes eNewDirection = (DirectionTypes) ((m_eFacingDirection + 1) % NUM_DIRECTION_TYPES); setFacingDirection(eNewDirection); } void CvUnit::rotateFacingDirectionCounterClockwise() { //change direction DirectionTypes eNewDirection = (DirectionTypes) ((m_eFacingDirection + NUM_DIRECTION_TYPES - 1) % NUM_DIRECTION_TYPES); setFacingDirection(eNewDirection); } int CvUnit::getImmobileTimer() const { return m_iImmobileTimer; } void CvUnit::setImmobileTimer(int iNewValue) { if (iNewValue != getImmobileTimer()) { m_iImmobileTimer = iNewValue; setInfoBarDirty(true); } } void CvUnit::changeImmobileTimer(int iChange) { if (iChange != 0) { setImmobileTimer(std::max(0, getImmobileTimer() + iChange)); } } bool CvUnit::isMadeAttack() const { return m_bMadeAttack; } void CvUnit::setMadeAttack(bool bNewValue) { m_bMadeAttack = bNewValue; } bool CvUnit::isMadeInterception() const { return m_bMadeInterception; } void CvUnit::setMadeInterception(bool bNewValue) { m_bMadeInterception = bNewValue; } bool CvUnit::isPromotionReady() const { return m_bPromotionReady; } void CvUnit::setPromotionReady(bool bNewValue) { if (isPromotionReady() != bNewValue) { m_bPromotionReady = bNewValue; if (m_bPromotionReady) { getGroup()->setAutomateType(NO_AUTOMATE); getGroup()->clearMissionQueue(); getGroup()->setActivityType(ACTIVITY_AWAKE); } gDLL->getEntityIFace()->showPromotionGlow(getUnitEntity(), bNewValue); if (IsSelected()) { gDLL->getInterfaceIFace()->setDirty(SelectionButtons_DIRTY_BIT, true); } } } void CvUnit::testPromotionReady() { setPromotionReady((getExperience() >= experienceNeeded()) && canAcquirePromotionAny()); } bool CvUnit::isDelayedDeath() const { return m_bDeathDelay; } void CvUnit::startDelayedDeath() { m_bDeathDelay = true; } // Returns true if killed... bool CvUnit::doDelayedDeath() { if (m_bDeathDelay && !isFighting()) { kill(false); return true; } return false; } bool CvUnit::isCombatFocus() const { return m_bCombatFocus; } bool CvUnit::isInfoBarDirty() const { return m_bInfoBarDirty; } void CvUnit::setInfoBarDirty(bool bNewValue) { m_bInfoBarDirty = bNewValue; } bool CvUnit::isBlockading() const { return m_bBlockading; } void CvUnit::setBlockading(bool bNewValue) { if (bNewValue != isBlockading()) { m_bBlockading = bNewValue; updatePlunder(isBlockading() ? 1 : -1, true); } } void CvUnit::collectBlockadeGold() { if (plot()->getTeam() == getTeam()) { return; } int iBlockadeRange = GC.getDefineINT("SHIP_BLOCKADE_RANGE"); for (int i = -iBlockadeRange; i <= iBlockadeRange; ++i) { for (int j = -iBlockadeRange; j <= iBlockadeRange; ++j) { CvPlot* pLoopPlot = ::plotXY(getX_INLINE(), getY_INLINE(), i, j); if (NULL != pLoopPlot && pLoopPlot->isRevealed(getTeam(), false)) { CvCity* pCity = pLoopPlot->getPlotCity(); if (NULL != pCity && !pCity->isPlundered() && isEnemy(pCity->getTeam()) && !atWar(pCity->getTeam(), getTeam())) { if (pCity->area() == area() || pCity->plot()->isAdjacentToArea(area())) { int iGold = pCity->calculateTradeProfit(pCity) * pCity->getTradeRoutes(); if (iGold > 0) { pCity->setPlundered(true); GET_PLAYER(getOwnerINLINE()).changeGold(iGold); GET_PLAYER(pCity->getOwnerINLINE()).changeGold(-iGold); CvWString szBuffer = gDLL->getText("TXT_KEY_MISC_TRADE_ROUTE_PLUNDERED", getNameKey(), pCity->getNameKey(), iGold); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_BUILD_BANK", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), getX_INLINE(), getY_INLINE()); szBuffer = gDLL->getText("TXT_KEY_MISC_TRADE_ROUTE_PLUNDER", getNameKey(), pCity->getNameKey(), iGold); gDLL->getInterfaceIFace()->addMessage(pCity->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_BUILD_BANK", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pCity->getX_INLINE(), pCity->getY_INLINE()); } } } } } } } PlayerTypes CvUnit::getOwner() const { return getOwnerINLINE(); } PlayerTypes CvUnit::getVisualOwner(TeamTypes eForTeam) const { if (NO_TEAM == eForTeam) { eForTeam = GC.getGameINLINE().getActiveTeam(); } if (getTeam() != eForTeam && eForTeam != BARBARIAN_TEAM) { if (m_pUnitInfo->isHiddenNationality()) { if (!plot()->isCity(true, getTeam())) { return BARBARIAN_PLAYER; } } } return getOwnerINLINE(); } PlayerTypes CvUnit::getCombatOwner(TeamTypes eForTeam, const CvPlot* pPlot) const { if (eForTeam != NO_TEAM && getTeam() != eForTeam && eForTeam != BARBARIAN_TEAM) { if (isAlwaysHostile(pPlot)) { return BARBARIAN_PLAYER; } } return getOwnerINLINE(); } TeamTypes CvUnit::getTeam() const { return GET_PLAYER(getOwnerINLINE()).getTeam(); } PlayerTypes CvUnit::getCapturingPlayer() const { return m_eCapturingPlayer; } void CvUnit::setCapturingPlayer(PlayerTypes eNewValue) { m_eCapturingPlayer = eNewValue; } const UnitTypes CvUnit::getUnitType() const { return m_eUnitType; } CvUnitInfo &CvUnit::getUnitInfo() const { return *m_pUnitInfo; } UnitClassTypes CvUnit::getUnitClassType() const { return (UnitClassTypes)m_pUnitInfo->getUnitClassType(); } const UnitTypes CvUnit::getLeaderUnitType() const { return m_eLeaderUnitType; } void CvUnit::setLeaderUnitType(UnitTypes leaderUnitType) { if(m_eLeaderUnitType != leaderUnitType) { m_eLeaderUnitType = leaderUnitType; reloadEntity(); } } CvUnit* CvUnit::getCombatUnit() const { return getUnit(m_combatUnit); } void CvUnit::setCombatUnit(CvUnit* pCombatUnit, bool bAttacking) { if (isCombatFocus()) { gDLL->getInterfaceIFace()->setCombatFocus(false); } if (pCombatUnit != NULL) { if (bAttacking) { if (GC.getLogging()) { if (gDLL->getChtLvl() > 0) { // Log info about this combat... char szOut[1024]; sprintf( szOut, "*** KOMBAT!\n ATTACKER: Player %d Unit %d (%S's %S), CombatStrength=%d\n DEFENDER: Player %d Unit %d (%S's %S), CombatStrength=%d\n", getOwnerINLINE(), getID(), GET_PLAYER(getOwnerINLINE()).getName(), getName().GetCString(), currCombatStr(NULL, NULL), pCombatUnit->getOwnerINLINE(), pCombatUnit->getID(), GET_PLAYER(pCombatUnit->getOwnerINLINE()).getName(), pCombatUnit->getName().GetCString(), pCombatUnit->currCombatStr(pCombatUnit->plot(), this)); gDLL->messageControlLog(szOut); } } if (getDomainType() == DOMAIN_LAND && !m_pUnitInfo->isIgnoreBuildingDefense() && pCombatUnit->plot()->getPlotCity() && pCombatUnit->plot()->getPlotCity()->getBuildingDefense() > 0 && cityAttackModifier() >= GC.getDefineINT("MIN_CITY_ATTACK_MODIFIER_FOR_SIEGE_TOWER")) { CvDLLEntity::SetSiegeTower(true); } } FAssertMsg(getCombatUnit() == NULL, "Combat Unit is not expected to be assigned"); FAssertMsg(!(plot()->isFighting()), "(plot()->isFighting()) did not return false as expected"); m_bCombatFocus = (bAttacking && !(gDLL->getInterfaceIFace()->isFocusedWidget()) && ((getOwnerINLINE() == GC.getGameINLINE().getActivePlayer()) || ((pCombatUnit->getOwnerINLINE() == GC.getGameINLINE().getActivePlayer()) && !(GC.getGameINLINE().isMPOption(MPOPTION_SIMULTANEOUS_TURNS))))); m_combatUnit = pCombatUnit->getIDInfo(); setCombatFirstStrikes((pCombatUnit->immuneToFirstStrikes()) ? 0 : (firstStrikes() + GC.getGameINLINE().getSorenRandNum(chanceFirstStrikes() + 1, "First Strike"))); } else { if(getCombatUnit() != NULL) { FAssertMsg(getCombatUnit() != NULL, "getCombatUnit() is not expected to be equal with NULL"); FAssertMsg(plot()->isFighting(), "plot()->isFighting is expected to be true"); m_bCombatFocus = false; m_combatUnit.reset(); setCombatFirstStrikes(0); if (IsSelected()) { gDLL->getInterfaceIFace()->setDirty(InfoPane_DIRTY_BIT, true); } if (plot() == gDLL->getInterfaceIFace()->getSelectionPlot()) { gDLL->getInterfaceIFace()->setDirty(PlotListButtons_DIRTY_BIT, true); } CvDLLEntity::SetSiegeTower(false); } } setCombatTimer(0); setInfoBarDirty(true); if (isCombatFocus()) { gDLL->getInterfaceIFace()->setCombatFocus(true); } } CvUnit* CvUnit::getTransportUnit() const { return getUnit(m_transportUnit); } bool CvUnit::isCargo() const { return (getTransportUnit() != NULL); } void CvUnit::setTransportUnit(CvUnit* pTransportUnit) { CvUnit* pOldTransportUnit; pOldTransportUnit = getTransportUnit(); if (pOldTransportUnit != pTransportUnit) { if (pOldTransportUnit != NULL) { pOldTransportUnit->changeCargo(-1); } if (pTransportUnit != NULL) { FAssertMsg(pTransportUnit->cargoSpaceAvailable(getSpecialUnitType(), getDomainType()) > 0, "Cargo space is expected to be available"); joinGroup(NULL, true); // Because what if a group of 3 tries to get in a transport which can hold 2... m_transportUnit = pTransportUnit->getIDInfo(); if (getDomainType() != DOMAIN_AIR) { getGroup()->setActivityType(ACTIVITY_SLEEP); } if (GC.getGameINLINE().isFinalInitialized()) { finishMoves(); } pTransportUnit->changeCargo(1); pTransportUnit->getGroup()->setActivityType(ACTIVITY_AWAKE); } else { m_transportUnit.reset(); getGroup()->setActivityType(ACTIVITY_AWAKE); } #ifdef _DEBUG std::vector<CvUnit*> aCargoUnits; if (pOldTransportUnit != NULL) { pOldTransportUnit->getCargoUnits(aCargoUnits); } if (pTransportUnit != NULL) { pTransportUnit->getCargoUnits(aCargoUnits); } #endif } } int CvUnit::getExtraDomainModifier(DomainTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_DOMAIN_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); return m_aiExtraDomainModifier[eIndex]; } void CvUnit::changeExtraDomainModifier(DomainTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_DOMAIN_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); m_aiExtraDomainModifier[eIndex] = (m_aiExtraDomainModifier[eIndex] + iChange); } const CvWString CvUnit::getName(uint uiForm) const { CvWString szBuffer; if (m_szName.empty()) { return m_pUnitInfo->getDescription(uiForm); } szBuffer.Format(L"%s (%s)", m_szName.GetCString(), m_pUnitInfo->getDescription(uiForm)); return szBuffer; } const wchar* CvUnit::getNameKey() const { if (m_szName.empty()) { return m_pUnitInfo->getTextKeyWide(); } else { return m_szName.GetCString(); } } const CvWString& CvUnit::getNameNoDesc() const { return m_szName; } void CvUnit::setName(CvWString szNewValue) { gDLL->stripSpecialCharacters(szNewValue); m_szName = szNewValue; if (IsSelected()) { gDLL->getInterfaceIFace()->setDirty(InfoPane_DIRTY_BIT, true); } } std::string CvUnit::getScriptData() const { return m_szScriptData; } void CvUnit::setScriptData(std::string szNewValue) { m_szScriptData = szNewValue; } int CvUnit::getTerrainDoubleMoveCount(TerrainTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumTerrainInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiTerrainDoubleMoveCount[eIndex]; } bool CvUnit::isTerrainDoubleMove(TerrainTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumTerrainInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return (getTerrainDoubleMoveCount(eIndex) > 0); } void CvUnit::changeTerrainDoubleMoveCount(TerrainTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumTerrainInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); m_paiTerrainDoubleMoveCount[eIndex] = (m_paiTerrainDoubleMoveCount[eIndex] + iChange); FAssert(getTerrainDoubleMoveCount(eIndex) >= 0); } int CvUnit::getFeatureDoubleMoveCount(FeatureTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumFeatureInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiFeatureDoubleMoveCount[eIndex]; } bool CvUnit::isFeatureDoubleMove(FeatureTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumFeatureInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return (getFeatureDoubleMoveCount(eIndex) > 0); } void CvUnit::changeFeatureDoubleMoveCount(FeatureTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumFeatureInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); m_paiFeatureDoubleMoveCount[eIndex] = (m_paiFeatureDoubleMoveCount[eIndex] + iChange); FAssert(getFeatureDoubleMoveCount(eIndex) >= 0); } int CvUnit::getExtraTerrainAttackPercent(TerrainTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumTerrainInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiExtraTerrainAttackPercent[eIndex]; } void CvUnit::changeExtraTerrainAttackPercent(TerrainTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumTerrainInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_paiExtraTerrainAttackPercent[eIndex] += iChange; setInfoBarDirty(true); } } int CvUnit::getExtraTerrainDefensePercent(TerrainTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumTerrainInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiExtraTerrainDefensePercent[eIndex]; } void CvUnit::changeExtraTerrainDefensePercent(TerrainTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumTerrainInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_paiExtraTerrainDefensePercent[eIndex] += iChange; setInfoBarDirty(true); } } int CvUnit::getExtraFeatureAttackPercent(FeatureTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumFeatureInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiExtraFeatureAttackPercent[eIndex]; } void CvUnit::changeExtraFeatureAttackPercent(FeatureTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumFeatureInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_paiExtraFeatureAttackPercent[eIndex] += iChange; setInfoBarDirty(true); } } int CvUnit::getExtraFeatureDefensePercent(FeatureTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumFeatureInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiExtraFeatureDefensePercent[eIndex]; } void CvUnit::changeExtraFeatureDefensePercent(FeatureTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumFeatureInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_paiExtraFeatureDefensePercent[eIndex] += iChange; setInfoBarDirty(true); } } int CvUnit::getExtraUnitCombatModifier(UnitCombatTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumUnitCombatInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiExtraUnitCombatModifier[eIndex]; } void CvUnit::changeExtraUnitCombatModifier(UnitCombatTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumUnitCombatInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); m_paiExtraUnitCombatModifier[eIndex] = (m_paiExtraUnitCombatModifier[eIndex] + iChange); } bool CvUnit::canAcquirePromotion(PromotionTypes ePromotion) const { FAssertMsg(ePromotion >= 0, "ePromotion is expected to be non-negative (invalid Index)"); FAssertMsg(ePromotion < GC.getNumPromotionInfos(), "ePromotion is expected to be within maximum bounds (invalid Index)"); if (isHasPromotion(ePromotion)) { return false; } if (GC.getPromotionInfo(ePromotion).getPrereqPromotion() != NO_PROMOTION) { if (!isHasPromotion((PromotionTypes)(GC.getPromotionInfo(ePromotion).getPrereqPromotion()))) { return false; } } if (GC.getPromotionInfo(ePromotion).getPrereqOrPromotion1() != NO_PROMOTION) { if (!isHasPromotion((PromotionTypes)(GC.getPromotionInfo(ePromotion).getPrereqOrPromotion1()))) { if ((GC.getPromotionInfo(ePromotion).getPrereqOrPromotion2() == NO_PROMOTION) || !isHasPromotion((PromotionTypes)(GC.getPromotionInfo(ePromotion).getPrereqOrPromotion2()))) { return false; } } } if (GC.getPromotionInfo(ePromotion).getTechPrereq() != NO_TECH) { if (!(GET_TEAM(getTeam()).isHasTech((TechTypes)(GC.getPromotionInfo(ePromotion).getTechPrereq())))) { return false; } } if (GC.getPromotionInfo(ePromotion).getStateReligionPrereq() != NO_RELIGION) { if (GET_PLAYER(getOwnerINLINE()).getStateReligion() != GC.getPromotionInfo(ePromotion).getStateReligionPrereq()) { return false; } } if (!isPromotionValid(ePromotion)) { return false; } return true; } bool CvUnit::isPromotionValid(PromotionTypes ePromotion) const { if (!::isPromotionValid(ePromotion, getUnitType(), true)) { return false; } CvPromotionInfo& promotionInfo = GC.getPromotionInfo(ePromotion); if (promotionInfo.getWithdrawalChange() + m_pUnitInfo->getWithdrawalProbability() + getExtraWithdrawal() > GC.getDefineINT("MAX_WITHDRAWAL_PROBABILITY")) { return false; } if (promotionInfo.getInterceptChange() + maxInterceptionProbability() > GC.getDefineINT("MAX_INTERCEPTION_PROBABILITY")) { return false; } if (promotionInfo.getEvasionChange() + evasionProbability() > GC.getDefineINT("MAX_EVASION_PROBABILITY")) { return false; } return true; } bool CvUnit::canAcquirePromotionAny() const { int iI; for (iI = 0; iI < GC.getNumPromotionInfos(); iI++) { if (canAcquirePromotion((PromotionTypes)iI)) { return true; } } return false; } bool CvUnit::isHasPromotion(PromotionTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumPromotionInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_pabHasPromotion[eIndex]; } void CvUnit::setHasPromotion(PromotionTypes eIndex, bool bNewValue) { int iChange; int iI; if (isHasPromotion(eIndex) != bNewValue) { m_pabHasPromotion[eIndex] = bNewValue; iChange = ((isHasPromotion(eIndex)) ? 1 : -1); /**************************************** * Archid Mod: 10 Oct 2012 * Functionality: SeeInvisiblePromotion - Archid * * Source: * Archid * ****************************************/ bool bAdd = iChange == 1 ? true : false; std::vector<InvisibleTypes> vInvisibilityTypes; for (int i = 0; i < GC.getPromotionInfo(eIndex).getNumSeeInvisibleTypes(); i++) { changeSeeInvisibleCount((InvisibleTypes)GC.getPromotionInfo(eIndex).getSeeInvisibleType(i), iChange); vInvisibilityTypes.push_back((InvisibleTypes)GC.getPromotionInfo(eIndex).getSeeInvisibleType(i)); } if (vInvisibilityTypes.size() > 0) { plot()->changeAdjacentSight(getTeam(), visibilityRange(), bAdd, this, true, vInvisibilityTypes); } vInvisibilityTypes.clear(); /** ** End: SeeInvisiblePromotion **/ changeBlitzCount((GC.getPromotionInfo(eIndex).isBlitz()) ? iChange : 0); changeAmphibCount((GC.getPromotionInfo(eIndex).isAmphib()) ? iChange : 0); changeRiverCount((GC.getPromotionInfo(eIndex).isRiver()) ? iChange : 0); changeEnemyRouteCount((GC.getPromotionInfo(eIndex).isEnemyRoute()) ? iChange : 0); changeAlwaysHealCount((GC.getPromotionInfo(eIndex).isAlwaysHeal()) ? iChange : 0); changeHillsDoubleMoveCount((GC.getPromotionInfo(eIndex).isHillsDoubleMove()) ? iChange : 0); changeImmuneToFirstStrikesCount((GC.getPromotionInfo(eIndex).isImmuneToFirstStrikes()) ? iChange : 0); changeExtraVisibilityRange(GC.getPromotionInfo(eIndex).getVisibilityChange() * iChange); changeExtraMoves(GC.getPromotionInfo(eIndex).getMovesChange() * iChange); changeExtraMoveDiscount(GC.getPromotionInfo(eIndex).getMoveDiscountChange() * iChange); changeExtraAirRange(GC.getPromotionInfo(eIndex).getAirRangeChange() * iChange); changeExtraIntercept(GC.getPromotionInfo(eIndex).getInterceptChange() * iChange); changeExtraEvasion(GC.getPromotionInfo(eIndex).getEvasionChange() * iChange); changeExtraFirstStrikes(GC.getPromotionInfo(eIndex).getFirstStrikesChange() * iChange); changeExtraChanceFirstStrikes(GC.getPromotionInfo(eIndex).getChanceFirstStrikesChange() * iChange); changeExtraWithdrawal(GC.getPromotionInfo(eIndex).getWithdrawalChange() * iChange); changeExtraCollateralDamage(GC.getPromotionInfo(eIndex).getCollateralDamageChange() * iChange); changeExtraBombardRate(GC.getPromotionInfo(eIndex).getBombardRateChange() * iChange); changeExtraEnemyHeal(GC.getPromotionInfo(eIndex).getEnemyHealChange() * iChange); changeExtraNeutralHeal(GC.getPromotionInfo(eIndex).getNeutralHealChange() * iChange); changeExtraFriendlyHeal(GC.getPromotionInfo(eIndex).getFriendlyHealChange() * iChange); changeSameTileHeal(GC.getPromotionInfo(eIndex).getSameTileHealChange() * iChange); changeAdjacentTileHeal(GC.getPromotionInfo(eIndex).getAdjacentTileHealChange() * iChange); changeExtraCombatPercent(GC.getPromotionInfo(eIndex).getCombatPercent() * iChange); changeExtraCityAttackPercent(GC.getPromotionInfo(eIndex).getCityAttackPercent() * iChange); changeExtraCityDefensePercent(GC.getPromotionInfo(eIndex).getCityDefensePercent() * iChange); changeExtraHillsAttackPercent(GC.getPromotionInfo(eIndex).getHillsAttackPercent() * iChange); changeExtraHillsDefensePercent(GC.getPromotionInfo(eIndex).getHillsDefensePercent() * iChange); changeRevoltProtection(GC.getPromotionInfo(eIndex).getRevoltProtection() * iChange); changeCollateralDamageProtection(GC.getPromotionInfo(eIndex).getCollateralDamageProtection() * iChange); changePillageChange(GC.getPromotionInfo(eIndex).getPillageChange() * iChange); changeUpgradeDiscount(GC.getPromotionInfo(eIndex).getUpgradeDiscount() * iChange); changeExperiencePercent(GC.getPromotionInfo(eIndex).getExperiencePercent() * iChange); changeKamikazePercent((GC.getPromotionInfo(eIndex).getKamikazePercent()) * iChange); changeCargoSpace(GC.getPromotionInfo(eIndex).getCargoChange() * iChange); for (iI = 0; iI < GC.getNumTerrainInfos(); iI++) { changeExtraTerrainAttackPercent(((TerrainTypes)iI), (GC.getPromotionInfo(eIndex).getTerrainAttackPercent(iI) * iChange)); changeExtraTerrainDefensePercent(((TerrainTypes)iI), (GC.getPromotionInfo(eIndex).getTerrainDefensePercent(iI) * iChange)); changeTerrainDoubleMoveCount(((TerrainTypes)iI), ((GC.getPromotionInfo(eIndex).getTerrainDoubleMove(iI)) ? iChange : 0)); } for (iI = 0; iI < GC.getNumFeatureInfos(); iI++) { changeExtraFeatureAttackPercent(((FeatureTypes)iI), (GC.getPromotionInfo(eIndex).getFeatureAttackPercent(iI) * iChange)); changeExtraFeatureDefensePercent(((FeatureTypes)iI), (GC.getPromotionInfo(eIndex).getFeatureDefensePercent(iI) * iChange)); changeFeatureDoubleMoveCount(((FeatureTypes)iI), ((GC.getPromotionInfo(eIndex).getFeatureDoubleMove(iI)) ? iChange : 0)); } for (iI = 0; iI < GC.getNumUnitCombatInfos(); iI++) { changeExtraUnitCombatModifier(((UnitCombatTypes)iI), (GC.getPromotionInfo(eIndex).getUnitCombatModifierPercent(iI) * iChange)); } for (iI = 0; iI < NUM_DOMAIN_TYPES; iI++) { changeExtraDomainModifier(((DomainTypes)iI), (GC.getPromotionInfo(eIndex).getDomainModifierPercent(iI) * iChange)); } if (IsSelected()) { gDLL->getInterfaceIFace()->setDirty(SelectionButtons_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(InfoPane_DIRTY_BIT, true); } //update graphics gDLL->getEntityIFace()->updatePromotionLayers(getUnitEntity()); } } int CvUnit::getSubUnitCount() const { return m_pUnitInfo->getGroupSize(); } int CvUnit::getSubUnitsAlive() const { return getSubUnitsAlive( getDamage()); } int CvUnit::getSubUnitsAlive(int iDamage) const { if (iDamage >= maxHitPoints()) { return 0; } else { return std::max(1, (((m_pUnitInfo->getGroupSize() * (maxHitPoints() - iDamage)) + (maxHitPoints() / ((m_pUnitInfo->getGroupSize() * 2) + 1))) / maxHitPoints())); } } // returns true if unit can initiate a war action with plot (possibly by declaring war) bool CvUnit::potentialWarAction(const CvPlot* pPlot) const { TeamTypes ePlotTeam = pPlot->getTeam(); TeamTypes eUnitTeam = getTeam(); if (ePlotTeam == NO_TEAM) { return false; } if (isEnemy(ePlotTeam, pPlot)) { return true; } if (getGroup()->AI_isDeclareWar(pPlot) && GET_TEAM(eUnitTeam).AI_getWarPlan(ePlotTeam) != NO_WARPLAN) { return true; } return false; } void CvUnit::read(FDataStreamBase* pStream) { // Init data before load reset(); uint uiFlag=0; pStream->Read(&uiFlag); // flags for expansion /**************************************** * Archid Mod: 10 Oct 2012 * Functionality: SeeInvisiblePromotion - Archid * * Source: * Archid * ****************************************/ pStream->Read(GC.getNumInvisibleInfos(), m_paiSeeInvisible); /** ** End: SeeInvisiblePromotion **/ pStream->Read(&m_iID); pStream->Read(&m_iGroupID); pStream->Read(&m_iHotKeyNumber); pStream->Read(&m_iX); pStream->Read(&m_iY); pStream->Read(&m_iLastMoveTurn); pStream->Read(&m_iReconX); pStream->Read(&m_iReconY); pStream->Read(&m_iGameTurnCreated); pStream->Read(&m_iDamage); pStream->Read(&m_iMoves); pStream->Read(&m_iExperience); pStream->Read(&m_iLevel); pStream->Read(&m_iCargo); pStream->Read(&m_iCargoCapacity); pStream->Read(&m_iAttackPlotX); pStream->Read(&m_iAttackPlotY); pStream->Read(&m_iCombatTimer); pStream->Read(&m_iCombatFirstStrikes); if (uiFlag < 2) { int iCombatDamage; pStream->Read(&iCombatDamage); } pStream->Read(&m_iFortifyTurns); pStream->Read(&m_iBlitzCount); pStream->Read(&m_iAmphibCount); pStream->Read(&m_iRiverCount); pStream->Read(&m_iEnemyRouteCount); pStream->Read(&m_iAlwaysHealCount); pStream->Read(&m_iHillsDoubleMoveCount); pStream->Read(&m_iImmuneToFirstStrikesCount); pStream->Read(&m_iExtraVisibilityRange); pStream->Read(&m_iExtraMoves); pStream->Read(&m_iExtraMoveDiscount); pStream->Read(&m_iExtraAirRange); pStream->Read(&m_iExtraIntercept); pStream->Read(&m_iExtraEvasion); pStream->Read(&m_iExtraFirstStrikes); pStream->Read(&m_iExtraChanceFirstStrikes); pStream->Read(&m_iExtraWithdrawal); pStream->Read(&m_iExtraCollateralDamage); pStream->Read(&m_iExtraBombardRate); pStream->Read(&m_iExtraEnemyHeal); pStream->Read(&m_iExtraNeutralHeal); pStream->Read(&m_iExtraFriendlyHeal); pStream->Read(&m_iSameTileHeal); pStream->Read(&m_iAdjacentTileHeal); pStream->Read(&m_iExtraCombatPercent); pStream->Read(&m_iExtraCityAttackPercent); pStream->Read(&m_iExtraCityDefensePercent); pStream->Read(&m_iExtraHillsAttackPercent); pStream->Read(&m_iExtraHillsDefensePercent); pStream->Read(&m_iRevoltProtection); pStream->Read(&m_iCollateralDamageProtection); pStream->Read(&m_iPillageChange); pStream->Read(&m_iUpgradeDiscount); pStream->Read(&m_iExperiencePercent); pStream->Read(&m_iKamikazePercent); pStream->Read(&m_iBaseCombat); pStream->Read((int*)&m_eFacingDirection); pStream->Read(&m_iImmobileTimer); pStream->Read(&m_bMadeAttack); pStream->Read(&m_bMadeInterception); pStream->Read(&m_bPromotionReady); pStream->Read(&m_bDeathDelay); pStream->Read(&m_bCombatFocus); // m_bInfoBarDirty not saved... pStream->Read(&m_bBlockading); if (uiFlag > 0) { pStream->Read(&m_bAirCombat); } pStream->Read((int*)&m_eOwner); pStream->Read((int*)&m_eCapturingPlayer); pStream->Read((int*)&m_eUnitType); FAssert(NO_UNIT != m_eUnitType); m_pUnitInfo = (NO_UNIT != m_eUnitType) ? &GC.getUnitInfo(m_eUnitType) : NULL; pStream->Read((int*)&m_eLeaderUnitType); pStream->Read((int*)&m_combatUnit.eOwner); pStream->Read(&m_combatUnit.iID); pStream->Read((int*)&m_transportUnit.eOwner); pStream->Read(&m_transportUnit.iID); pStream->Read(NUM_DOMAIN_TYPES, m_aiExtraDomainModifier); pStream->ReadString(m_szName); pStream->ReadString(m_szScriptData); pStream->Read(GC.getNumPromotionInfos(), m_pabHasPromotion); pStream->Read(GC.getNumTerrainInfos(), m_paiTerrainDoubleMoveCount); pStream->Read(GC.getNumFeatureInfos(), m_paiFeatureDoubleMoveCount); pStream->Read(GC.getNumTerrainInfos(), m_paiExtraTerrainAttackPercent); pStream->Read(GC.getNumTerrainInfos(), m_paiExtraTerrainDefensePercent); pStream->Read(GC.getNumFeatureInfos(), m_paiExtraFeatureAttackPercent); pStream->Read(GC.getNumFeatureInfos(), m_paiExtraFeatureDefensePercent); pStream->Read(GC.getNumUnitCombatInfos(), m_paiExtraUnitCombatModifier); } void CvUnit::write(FDataStreamBase* pStream) { uint uiFlag=2; pStream->Write(uiFlag); // flag for expansion /**************************************** * Archid Mod: 10 Oct 2012 * Functionality: SeeInvisiblePromotion - Archid * * Source: * Archid * ****************************************/ pStream->Write(GC.getNumInvisibleInfos(), m_paiSeeInvisible); /** ** End: SeeInvisiblePromotion **/ pStream->Write(m_iID); pStream->Write(m_iGroupID); pStream->Write(m_iHotKeyNumber); pStream->Write(m_iX); pStream->Write(m_iY); pStream->Write(m_iLastMoveTurn); pStream->Write(m_iReconX); pStream->Write(m_iReconY); pStream->Write(m_iGameTurnCreated); pStream->Write(m_iDamage); pStream->Write(m_iMoves); pStream->Write(m_iExperience); pStream->Write(m_iLevel); pStream->Write(m_iCargo); pStream->Write(m_iCargoCapacity); pStream->Write(m_iAttackPlotX); pStream->Write(m_iAttackPlotY); pStream->Write(m_iCombatTimer); pStream->Write(m_iCombatFirstStrikes); pStream->Write(m_iFortifyTurns); pStream->Write(m_iBlitzCount); pStream->Write(m_iAmphibCount); pStream->Write(m_iRiverCount); pStream->Write(m_iEnemyRouteCount); pStream->Write(m_iAlwaysHealCount); pStream->Write(m_iHillsDoubleMoveCount); pStream->Write(m_iImmuneToFirstStrikesCount); pStream->Write(m_iExtraVisibilityRange); pStream->Write(m_iExtraMoves); pStream->Write(m_iExtraMoveDiscount); pStream->Write(m_iExtraAirRange); pStream->Write(m_iExtraIntercept); pStream->Write(m_iExtraEvasion); pStream->Write(m_iExtraFirstStrikes); pStream->Write(m_iExtraChanceFirstStrikes); pStream->Write(m_iExtraWithdrawal); pStream->Write(m_iExtraCollateralDamage); pStream->Write(m_iExtraBombardRate); pStream->Write(m_iExtraEnemyHeal); pStream->Write(m_iExtraNeutralHeal); pStream->Write(m_iExtraFriendlyHeal); pStream->Write(m_iSameTileHeal); pStream->Write(m_iAdjacentTileHeal); pStream->Write(m_iExtraCombatPercent); pStream->Write(m_iExtraCityAttackPercent); pStream->Write(m_iExtraCityDefensePercent); pStream->Write(m_iExtraHillsAttackPercent); pStream->Write(m_iExtraHillsDefensePercent); pStream->Write(m_iRevoltProtection); pStream->Write(m_iCollateralDamageProtection); pStream->Write(m_iPillageChange); pStream->Write(m_iUpgradeDiscount); pStream->Write(m_iExperiencePercent); pStream->Write(m_iKamikazePercent); pStream->Write(m_iBaseCombat); pStream->Write(m_eFacingDirection); pStream->Write(m_iImmobileTimer); pStream->Write(m_bMadeAttack); pStream->Write(m_bMadeInterception); pStream->Write(m_bPromotionReady); pStream->Write(m_bDeathDelay); pStream->Write(m_bCombatFocus); // m_bInfoBarDirty not saved... pStream->Write(m_bBlockading); pStream->Write(m_bAirCombat); pStream->Write(m_eOwner); pStream->Write(m_eCapturingPlayer); pStream->Write(m_eUnitType); pStream->Write(m_eLeaderUnitType); pStream->Write(m_combatUnit.eOwner); pStream->Write(m_combatUnit.iID); pStream->Write(m_transportUnit.eOwner); pStream->Write(m_transportUnit.iID); pStream->Write(NUM_DOMAIN_TYPES, m_aiExtraDomainModifier); pStream->WriteString(m_szName); pStream->WriteString(m_szScriptData); pStream->Write(GC.getNumPromotionInfos(), m_pabHasPromotion); pStream->Write(GC.getNumTerrainInfos(), m_paiTerrainDoubleMoveCount); pStream->Write(GC.getNumFeatureInfos(), m_paiFeatureDoubleMoveCount); pStream->Write(GC.getNumTerrainInfos(), m_paiExtraTerrainAttackPercent); pStream->Write(GC.getNumTerrainInfos(), m_paiExtraTerrainDefensePercent); pStream->Write(GC.getNumFeatureInfos(), m_paiExtraFeatureAttackPercent); pStream->Write(GC.getNumFeatureInfos(), m_paiExtraFeatureDefensePercent); pStream->Write(GC.getNumUnitCombatInfos(), m_paiExtraUnitCombatModifier); } // Protected Functions... bool CvUnit::canAdvance(const CvPlot* pPlot, int iThreshold) const { FAssert(canFight()); FAssert(!(isAnimal() && pPlot->isCity())); FAssert(getDomainType() != DOMAIN_AIR); FAssert(getDomainType() != DOMAIN_IMMOBILE); if (pPlot->getNumVisibleEnemyDefenders(this) > iThreshold) { return false; } if (isNoCapture()) { if (pPlot->isEnemyCity(*this)) { return false; } } return true; } void CvUnit::collateralCombat(const CvPlot* pPlot, CvUnit* pSkipUnit) { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; CvUnit* pBestUnit; CvWString szBuffer; int iTheirStrength; int iStrengthFactor; int iCollateralDamage; int iUnitDamage; int iDamageCount; int iPossibleTargets; int iCount; int iValue; int iBestValue; std::map<CvUnit*, int> mapUnitDamage; std::map<CvUnit*, int>::iterator it; int iCollateralStrength = (getDomainType() == DOMAIN_AIR ? airBaseCombatStr() : baseCombatStr()) * collateralDamage() / 100; if (iCollateralStrength == 0) { return; } iPossibleTargets = std::min((pPlot->getNumVisibleEnemyDefenders(this) - 1), collateralDamageMaxUnits()); pUnitNode = pPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); if (pLoopUnit != pSkipUnit) { if (isEnemy(pLoopUnit->getTeam(), pPlot)) { if (!(pLoopUnit->isInvisible(getTeam(), false))) { if (pLoopUnit->canDefend()) { iValue = (1 + GC.getGameINLINE().getSorenRandNum(10000, "Collateral Damage")); iValue *= pLoopUnit->currHitPoints(); mapUnitDamage[pLoopUnit] = iValue; } } } } } CvCity* pCity = NULL; if (getDomainType() == DOMAIN_AIR) { pCity = pPlot->getPlotCity(); } iDamageCount = 0; iCount = 0; while (iCount < iPossibleTargets) { iBestValue = 0; pBestUnit = NULL; for (it = mapUnitDamage.begin(); it != mapUnitDamage.end(); it++) { if (it->second > iBestValue) { iBestValue = it->second; pBestUnit = it->first; } } if (pBestUnit != NULL) { mapUnitDamage.erase(pBestUnit); if (NO_UNITCOMBAT == getUnitCombatType() || !pBestUnit->getUnitInfo().getUnitCombatCollateralImmune(getUnitCombatType())) { iTheirStrength = pBestUnit->baseCombatStr(); iStrengthFactor = ((iCollateralStrength + iTheirStrength + 1) / 2); iCollateralDamage = (GC.getDefineINT("COLLATERAL_COMBAT_DAMAGE") * (iCollateralStrength + iStrengthFactor)) / (iTheirStrength + iStrengthFactor); iCollateralDamage *= 100 + getExtraCollateralDamage(); iCollateralDamage *= std::max(0, 100 - pBestUnit->getCollateralDamageProtection()); iCollateralDamage /= 100; if (pCity != NULL) { iCollateralDamage *= 100 + pCity->getAirModifier(); iCollateralDamage /= 100; } iCollateralDamage /= 100; iCollateralDamage = std::max(0, iCollateralDamage); int iMaxDamage = std::min(collateralDamageLimit(), (collateralDamageLimit() * (iCollateralStrength + iStrengthFactor)) / (iTheirStrength + iStrengthFactor)); iUnitDamage = std::max(pBestUnit->getDamage(), std::min(pBestUnit->getDamage() + iCollateralDamage, iMaxDamage)); if (pBestUnit->getDamage() != iUnitDamage) { pBestUnit->setDamage(iUnitDamage, getOwnerINLINE()); iDamageCount++; } } iCount++; } else { break; } } if (iDamageCount > 0) { szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_SUFFER_COL_DMG", iDamageCount); gDLL->getInterfaceIFace()->addMessage(pSkipUnit->getOwnerINLINE(), (pSkipUnit->getDomainType() != DOMAIN_AIR), GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_COLLATERAL", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pSkipUnit->getX_INLINE(), pSkipUnit->getY_INLINE(), true, true); szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_INFLICT_COL_DMG", getNameKey(), iDamageCount); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_COLLATERAL", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pSkipUnit->getX_INLINE(), pSkipUnit->getY_INLINE()); } } void CvUnit::flankingStrikeCombat(const CvPlot* pPlot, int iAttackerStrength, int iAttackerFirepower, int iDefenderOdds, int iDefenderDamage, CvUnit* pSkipUnit) { if (pPlot->isCity(true, pSkipUnit->getTeam())) { return; } CLLNode<IDInfo>* pUnitNode = pPlot->headUnitNode(); std::vector< std::pair<CvUnit*, int> > listFlankedUnits; while (NULL != pUnitNode) { CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); if (pLoopUnit != pSkipUnit) { if (!pLoopUnit->isDead() && isEnemy(pLoopUnit->getTeam(), pPlot)) { if (!(pLoopUnit->isInvisible(getTeam(), false))) { if (pLoopUnit->canDefend()) { int iFlankingStrength = m_pUnitInfo->getFlankingStrikeUnitClass(pLoopUnit->getUnitClassType()); if (iFlankingStrength > 0) { int iFlankedDefenderStrength; int iFlankedDefenderOdds; int iAttackerDamage; int iFlankedDefenderDamage; getDefenderCombatValues(*pLoopUnit, pPlot, iAttackerStrength, iAttackerFirepower, iFlankedDefenderOdds, iFlankedDefenderStrength, iAttackerDamage, iFlankedDefenderDamage); if (GC.getGameINLINE().getSorenRandNum(GC.getDefineINT("COMBAT_DIE_SIDES"), "Flanking Combat") >= iDefenderOdds) { int iCollateralDamage = (iFlankingStrength * iDefenderDamage) / 100; int iUnitDamage = std::max(pLoopUnit->getDamage(), std::min(pLoopUnit->getDamage() + iCollateralDamage, collateralDamageLimit())); if (pLoopUnit->getDamage() != iUnitDamage) { listFlankedUnits.push_back(std::make_pair(pLoopUnit, iUnitDamage)); } } } } } } } } int iNumUnitsHit = std::min((int)listFlankedUnits.size(), collateralDamageMaxUnits()); for (int i = 0; i < iNumUnitsHit; ++i) { int iIndexHit = GC.getGameINLINE().getSorenRandNum(listFlankedUnits.size(), "Pick Flanked Unit"); CvUnit* pUnit = listFlankedUnits[iIndexHit].first; int iDamage = listFlankedUnits[iIndexHit].second; pUnit->setDamage(iDamage, getOwnerINLINE()); if (pUnit->isDead()) { CvWString szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_KILLED_UNIT_BY_FLANKING", getNameKey(), pUnit->getNameKey(), pUnit->getVisualCivAdjective(getTeam())); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, GC.getEraInfo(GC.getGameINLINE().getCurrentEra()).getAudioUnitVictoryScript(), MESSAGE_TYPE_INFO, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); szBuffer = gDLL->getText("TXT_KEY_MISC_YOUR_UNIT_DIED_BY_FLANKING", pUnit->getNameKey(), getNameKey(), getVisualCivAdjective(pUnit->getTeam())); gDLL->getInterfaceIFace()->addMessage(pUnit->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, GC.getEraInfo(GC.getGameINLINE().getCurrentEra()).getAudioUnitDefeatScript(), MESSAGE_TYPE_INFO, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); pUnit->kill(false); } listFlankedUnits.erase(std::remove(listFlankedUnits.begin(), listFlankedUnits.end(), listFlankedUnits[iIndexHit])); } if (iNumUnitsHit > 0) { CvWString szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_DAMAGED_UNITS_BY_FLANKING", getNameKey(), iNumUnitsHit); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, GC.getEraInfo(GC.getGameINLINE().getCurrentEra()).getAudioUnitVictoryScript(), MESSAGE_TYPE_INFO, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); if (NULL != pSkipUnit) { szBuffer = gDLL->getText("TXT_KEY_MISC_YOUR_UNITS_DAMAGED_BY_FLANKING", getNameKey(), iNumUnitsHit); gDLL->getInterfaceIFace()->addMessage(pSkipUnit->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, GC.getEraInfo(GC.getGameINLINE().getCurrentEra()).getAudioUnitDefeatScript(), MESSAGE_TYPE_INFO, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); } } } // Returns true if we were intercepted... bool CvUnit::interceptTest(const CvPlot* pPlot) { if (GC.getGameINLINE().getSorenRandNum(100, "Evasion Rand") >= evasionProbability()) { CvUnit* pInterceptor = bestInterceptor(pPlot); if (pInterceptor != NULL) { /************************************************************************************************/ /* Afforess Start 03/6/10 */ /* */ /* Better Air Interception */ /************************************************************************************************/ int iInterceptionOdds = pInterceptor->currInterceptionProbability(); //if (GC.getDefineINT("BETTER_AIR_INTERCEPTION")) if (GC.getGameINLINE().isOption(GAMEOPTION_BETTER_AIR_INTERCEPTION)) iInterceptionOdds = interceptionChance(pPlot); /************************************************************************************************/ /* Afforess END */ /************************************************************************************************/ if (GC.getGameINLINE().getSorenRandNum(100, "Intercept Rand (Air)") < pInterceptor->currInterceptionProbability()) { fightInterceptor(pPlot, false); return true; } } } return false; } CvUnit* CvUnit::airStrikeTarget(const CvPlot* pPlot) const { CvUnit* pDefender; pDefender = pPlot->getBestDefender(NO_PLAYER, getOwnerINLINE(), this, true); if (pDefender != NULL) { if (!pDefender->isDead()) { if (pDefender->canDefend()) { return pDefender; } } } return NULL; } bool CvUnit::canAirStrike(const CvPlot* pPlot) const { if (getDomainType() != DOMAIN_AIR) { return false; } if (!canAirAttack()) { return false; } if (pPlot == plot()) { return false; } if (!pPlot->isVisible(getTeam(), false)) { return false; } if (plotDistance(getX_INLINE(), getY_INLINE(), pPlot->getX_INLINE(), pPlot->getY_INLINE()) > airRange()) { return false; } if (airStrikeTarget(pPlot) == NULL) { return false; } return true; } bool CvUnit::airStrike(CvPlot* pPlot) { if (!canAirStrike(pPlot)) { return false; } if (interceptTest(pPlot)) { return false; } CvUnit* pDefender = airStrikeTarget(pPlot); FAssert(pDefender != NULL); FAssert(pDefender->canDefend()); setReconPlot(pPlot); setMadeAttack(true); //Vincentz Moves extra move for Airstrike changeMoves(GC.getMOVE_DENOMINATOR() * 2); int iDamage = airCombatDamage(pDefender); // < Air Combat Experience Start > int iUnitDamage = pDefender->getDamage() + iDamage; //std::max(pDefender->getDamage(), std::min((pDefender->getDamage() + iDamage), airCombatLimit())); // < Air Combat Experience End > CvWString szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_ARE_ATTACKED_BY_AIR", pDefender->getNameKey(), getNameKey(), -(((iUnitDamage - pDefender->getDamage()) * 100) / pDefender->maxHitPoints())); gDLL->getInterfaceIFace()->addMessage(pDefender->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_AIR_ATTACK", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE(), true, true); szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_ATTACK_BY_AIR", getNameKey(), pDefender->getNameKey(), -(((iUnitDamage - pDefender->getDamage()) * 100) / pDefender->maxHitPoints())); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_AIR_ATTACKED", MESSAGE_TYPE_INFO, pDefender->getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); collateralCombat(pPlot, pDefender); pDefender->setDamage(iUnitDamage, getOwnerINLINE()); // < Air Combat Experience Start > if (GC.getGameINLINE().isExperienceGainByAttackingUnits()) { int iExperience = 0; int iTheirStrength = (DOMAIN_AIR == pDefender->getDomainType() ? pDefender->airCurrCombatStr(this) : pDefender->currCombatStr(NULL, NULL)); int iOurStrength = (DOMAIN_AIR == getDomainType() ? airCurrCombatStr(pDefender) : currCombatStr(NULL, NULL)); iExperience = pDefender->defenseXPValue(); iExperience = (iExperience * iTheirStrength) / std::max(1, iOurStrength); iExperience = range(iExperience, GC.getDefineINT("MIN_EXPERIENCE_PER_COMBAT"), GC.getDefineINT("MAX_EXPERIENCE_PER_COMBAT")); if (!pDefender->isDead()) { iExperience = iExperience / 2; } changeExperience(iExperience, pDefender->maxXPValue(), true, pPlot->getOwnerINLINE() == getOwnerINLINE(), !pDefender->isBarbarian()); } // < Air Combat Experience End > return true; } bool CvUnit::canRangeStrike() const { if (getDomainType() == DOMAIN_AIR) { return false; } //Vincentz Rangestrike //if (airRange() <= 0) //{ // return false; //} if (airBaseCombatStr() <= 0) { return false; } if (!canFight()) { return false; } //Vincentz Rangestrike start if (isMadeAttack() && !isBlitz() && (getTeam() == GC.getGameINLINE().getActiveTeam())) { return false; } if ((!canMove() && getMoves() > 0) && (getTeam() == GC.getGameINLINE().getActiveTeam())) { return false; } if (isCargo()) { return false; } // Vincentz Rangestrike end return true; } bool CvUnit::canRangeStrikeAt(const CvPlot* pPlot, int iX, int iY) const { if (!canRangeStrike()) { return false; } CvPlot* pTargetPlot = GC.getMapINLINE().plotINLINE(iX, iY); if (NULL == pTargetPlot) { return false; } if (!pPlot->isVisible(getTeam(), false)) { return false; } //Vincentz Rangestrike extra range from city /* if (plotDistance(pPlot->getX_INLINE(), pPlot->getY_INLINE(), pTargetPlot->getX_INLINE(), pTargetPlot->getY_INLINE()) > airRange()) { return false; } */ int rangestrikeRangechange = 0; if (((plot()->isCity(true, getTeam())) || (pPlot->isHills())) && (getDomainType() == DOMAIN_LAND)) { rangestrikeRangechange += 1; // changeExtraAirRange(1); } if (plotDistance(pPlot->getX_INLINE(), pPlot->getY_INLINE(), pTargetPlot->getX_INLINE(), pTargetPlot->getY_INLINE()) > airRange() + rangestrikeRangechange) { return false; } //Vincentz End CvUnit* pDefender = airStrikeTarget(pTargetPlot); if (NULL == pDefender) { return false; } /* Vincentz Rangestrike off if (!pPlot->canSeePlot(pTargetPlot, getTeam(), airRange(), getFacingDirection(true))) { return false; } */ return true; } bool CvUnit::rangeStrike(int iX, int iY) { CvUnit* pDefender; CvWString szBuffer; CvCity* pCity; CvPlot* pTargetPlot; int iUnitDamage; int iDamage; pTargetPlot = GC.getMapINLINE().plotINLINE(iX, iY); CvPlot* pPlot = GC.getMapINLINE().plot(iX, iY); if (NULL == pPlot) { return false; } if (!canRangeStrikeAt(pPlot, iX, iY)) { return false; } pDefender = airStrikeTarget(pPlot); FAssert(pDefender != NULL); FAssert(pDefender->canDefend()); if (GC.getDefineINT("RANGED_ATTACKS_USE_MOVES") == 0) { setMadeAttack(true); } if (getDomainType() == DOMAIN_LAND) { finishMoves(); } else { changeMoves(GC.getMOVE_DENOMINATOR() * GC.getDefineINT("MOVE_MULTIPLIER")); } pCity = pTargetPlot->getPlotCity(); if (pCity != NULL && (pCity->isBombardable(this))) { pCity->changeDefenseModifier((-bombardRate() * currHitPoints() / maxHitPoints() * 50 + GC.getGameINLINE().getSorenRandNum(100, "Bombard - Random")) / 100); szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_DEFENSES_REDUCED_TO", pCity->getNameKey(), pCity->getDefenseModifier(false), getNameKey()); gDLL->getInterfaceIFace()->addMessage(pCity->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_BOMBARDED", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pCity->getX_INLINE(), pCity->getY_INLINE(), true, true); szBuffer = gDLL->getText("TXT_KEY_MISC_ENEMY_DEFENSES_REDUCED_TO", getNameKey(), pCity->getNameKey(), pCity->getDefenseModifier(false)); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_BOMBARD", MESSAGE_TYPE_INFO, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pCity->getX_INLINE(), pCity->getY_INLINE()); } else { iDamage = rangeCombatDamage(pDefender) * currHitPoints() / maxHitPoints(); iUnitDamage = std::max(pDefender->getDamage(), std::min((pDefender->getDamage() + iDamage), airCombatLimit())); //Vincentz Rangestrike check airCurrCombatStr if (((GC.getGameINLINE().getSorenRandNum(GC.getDefineINT("RANGESTRIKE_DICE"), "Random")) + airBaseCombatStr() * GC.getDefineINT("RANGESTRIKE_HIT_MODIFIER") * currHitPoints() / maxHitPoints()) < ((GC.getGameINLINE().getSorenRandNum(GC.getDefineINT("RANGESTRIKE_DICE"), "Random")) + pDefender->baseCombatStr() * pDefender->currHitPoints() / pDefender->maxHitPoints())) { szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_ARE_ATTACKED_BY_AIR_MISS", pDefender->getNameKey(), getNameKey()); //red icon over attacking unit gDLL->getInterfaceIFace()->addMessage(pDefender->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_COMBAT", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), this->getX_INLINE(), this->getY_INLINE(), true, true); //white icon over defending unit gDLL->getInterfaceIFace()->addMessage(pDefender->getOwnerINLINE(), false, 0, L"", "AS2D_COMBAT", MESSAGE_TYPE_DISPLAY_ONLY, pDefender->getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_WHITE"), pDefender->getX_INLINE(), pDefender->getY_INLINE(), true, true); szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_ATTACK_BY_AIR_MISS", getNameKey(), pDefender->getNameKey()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_COMBAT", MESSAGE_TYPE_INFO, pDefender->getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); } else { szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_ARE_ATTACKED_BY_AIR", pDefender->getNameKey(), getNameKey(), (((iUnitDamage - pDefender->getDamage()) * 100) / pDefender->maxHitPoints())); //red icon over attacking unit gDLL->getInterfaceIFace()->addMessage(pDefender->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_COMBAT", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), this->getX_INLINE(), this->getY_INLINE(), true, true); //white icon over defending unit gDLL->getInterfaceIFace()->addMessage(pDefender->getOwnerINLINE(), false, 0, L"", "AS2D_COMBAT", MESSAGE_TYPE_DISPLAY_ONLY, pDefender->getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_WHITE"), pDefender->getX_INLINE(), pDefender->getY_INLINE(), true, true); szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_ATTACK_BY_AIR", getNameKey(), pDefender->getNameKey(), (((iUnitDamage - pDefender->getDamage()) * 100) / pDefender->maxHitPoints())); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_COMBAT", MESSAGE_TYPE_INFO, pDefender->getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); collateralCombat(pPlot, pDefender); //set damage but don't update entity damage visibility pDefender->setDamage(iUnitDamage, getOwnerINLINE(), false); } } if (pPlot->isActiveVisible(false)) { // Range strike entity mission CvMissionDefinition kDefiniton; kDefiniton.setMissionTime(GC.getMissionInfo(MISSION_RANGE_ATTACK).getTime() * gDLL->getSecsPerTurn() + 2); kDefiniton.setMissionType(MISSION_RANGE_ATTACK); kDefiniton.setPlot(pDefender->plot()); kDefiniton.setUnit(BATTLE_UNIT_ATTACKER, this); kDefiniton.setUnit(BATTLE_UNIT_DEFENDER, pDefender); gDLL->getEntityIFace()->AddMission(&kDefiniton); //delay death pDefender->getGroup()->setMissionTimer(GC.getMissionInfo(MISSION_RANGE_ATTACK).getTime() + 4); } if (pDefender->isDead()) { szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_UNIT_DESTROYED_ENEMY", getNameKey(), pDefender->getNameKey()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, GC.getEraInfo(GC.getGameINLINE().getCurrentEra()).getAudioUnitVictoryScript(), MESSAGE_TYPE_INFO, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); changeExperience(GC.getDefineINT("MIN_EXPERIENCE_PER_COMBAT")); } //Vincentz Rangestrike Strikeback // if (pDefender->plotDistance(pPlot->getX_INLINE(), pPlot->getY_INLINE(), pTargetPlot->getX_INLINE(), pTargetPlot->getY_INLINE()) > airRange()) // if (GC.getDefineINT("RANGESTRIKE_RETURN_FIRE") == 1 && (pDefender->canRangeStrikeAt(pDefender->plot(), this->plot()->getX_INLINE(), this->plot()->getY_INLINE()))) if (GC.getDefineINT("RANGESTRIKE_RETURN_FIRE") == 1) { if (!pDefender->canRangeStrikeAt(pDefender->plot(), this->plot()->getX_INLINE(), this->plot()->getY_INLINE())) { pDefender = NULL; CLLNode<IDInfo>* pUnitNode = pTargetPlot->headUnitNode(); while (NULL != pUnitNode) { CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pTargetPlot->nextUnitNode(pUnitNode); if (pLoopUnit->canRangeStrikeAt(pLoopUnit->plot(), this->plot()->getX_INLINE(), this->plot()->getY_INLINE())) { pDefender = pLoopUnit; } } } if (pDefender != NULL) { iDamage = rangeCombatDamage(this) * pDefender->currHitPoints() / pDefender->maxHitPoints(); iUnitDamage = std::max(this->getDamage(), std::min((this->getDamage() + iDamage), pDefender->airCombatLimit())); if (((GC.getGameINLINE().getSorenRandNum(GC.getDefineINT("RANGESTRIKE_DICE"), "Random")) + pDefender->airBaseCombatStr()) * GC.getDefineINT("RANGESTRIKE_HIT_MODIFIER") > ((GC.getGameINLINE().getSorenRandNum(GC.getDefineINT("RANGESTRIKE_DICE"), "Random")) + this->baseCombatStr())) { szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_RETURN_ATTACK_BY_AIR", pDefender->getNameKey(), getNameKey(), (((iUnitDamage - this->getDamage()) * 100) / this->maxHitPoints())); gDLL->getInterfaceIFace()->addMessage(pDefender->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_COMBAT", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), this->getX_INLINE(), this->getY_INLINE(), true, true); szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_ARE_RETURN_ATTACKED_BY_AIR", getNameKey(), pDefender->getNameKey(), (((iUnitDamage - this->getDamage()) * 100) / this->maxHitPoints())); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_COMBAT", MESSAGE_TYPE_INFO, this->getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); this->setDamage(iUnitDamage, this->getOwnerINLINE(), false); // collateralCombat(plot(), this); } else { szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_RETURN_ATTACK_BY_AIR_MISS", pDefender->getNameKey(), getNameKey()); gDLL->getInterfaceIFace()->addMessage(pDefender->getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_COMBAT", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), this->getX_INLINE(), this->getY_INLINE(), true, true); szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_ARE_RETURN_ATTACKED_BY_AIR_MISS", getNameKey(), pDefender->getNameKey()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_COMBAT", MESSAGE_TYPE_INFO, pDefender->getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); } if (pTargetPlot->isActiveVisible(false)) { // Range strike entity mission CvMissionDefinition kDefiniton2; kDefiniton2.setMissionTime(GC.getMissionInfo(MISSION_RANGE_ATTACK).getTime() * gDLL->getSecsPerTurn() + 4); kDefiniton2.setMissionType(MISSION_RANGE_ATTACK); kDefiniton2.setPlot(this->plot()); kDefiniton2.setUnit(BATTLE_UNIT_ATTACKER, pDefender); kDefiniton2.setUnit(BATTLE_UNIT_DEFENDER, this); gDLL->getEntityIFace()->AddMission(&kDefiniton2); //delay death this->getGroup()->setMissionTimer(GC.getMissionInfo(MISSION_RANGE_ATTACK).getTime() + 2); } } } return true; } //------------------------------------------------------------------------------------------------ // FUNCTION: CvUnit::planBattle //! \brief Determines in general how a battle will progress. //! //! Note that the outcome of the battle is not determined here. This function plans //! how many sub-units die and in which 'rounds' of battle. //! \param kBattleDefinition The battle definition, which receives the battle plan. //! \retval The number of game turns that the battle should be given. //------------------------------------------------------------------------------------------------ int CvUnit::planBattle( CvBattleDefinition & kBattleDefinition ) const { #define BATTLE_TURNS_SETUP 4 #define BATTLE_TURNS_ENDING 4 #define BATTLE_TURNS_MELEE 6 #define BATTLE_TURNS_RANGED 6 #define BATTLE_TURN_RECHECK 4 int aiUnitsBegin[BATTLE_UNIT_COUNT]; int aiUnitsEnd[BATTLE_UNIT_COUNT]; int aiToKillMelee[BATTLE_UNIT_COUNT]; int aiToKillRanged[BATTLE_UNIT_COUNT]; CvBattleRoundVector::iterator iIterator; int i, j; bool bIsLoser; int iRoundIndex; int iTotalRounds = 0; int iRoundCheck = BATTLE_TURN_RECHECK; // Initial conditions kBattleDefinition.setNumRangedRounds(0); kBattleDefinition.setNumMeleeRounds(0); int iFirstStrikesDelta = kBattleDefinition.getFirstStrikes(BATTLE_UNIT_ATTACKER) - kBattleDefinition.getFirstStrikes(BATTLE_UNIT_DEFENDER); if (iFirstStrikesDelta > 0) // Attacker first strikes { int iKills = computeUnitsToDie( kBattleDefinition, true, BATTLE_UNIT_DEFENDER ); kBattleDefinition.setNumRangedRounds(std::max(iFirstStrikesDelta, iKills / iFirstStrikesDelta)); } else if (iFirstStrikesDelta < 0) // Defender first strikes { int iKills = computeUnitsToDie( kBattleDefinition, true, BATTLE_UNIT_ATTACKER ); iFirstStrikesDelta = -iFirstStrikesDelta; kBattleDefinition.setNumRangedRounds(std::max(iFirstStrikesDelta, iKills / iFirstStrikesDelta)); } increaseBattleRounds( kBattleDefinition); // Keep randomizing until we get something valid do { iRoundCheck++; if ( iRoundCheck >= BATTLE_TURN_RECHECK ) { increaseBattleRounds( kBattleDefinition); iTotalRounds = kBattleDefinition.getNumRangedRounds() + kBattleDefinition.getNumMeleeRounds(); iRoundCheck = 0; } // Make sure to clear the battle plan, we may have to do this again if we can't find a plan that works. kBattleDefinition.clearBattleRounds(); // Create the round list CvBattleRound kRound; kBattleDefinition.setBattleRound(iTotalRounds, kRound); // For the attacker and defender for ( i = 0; i < BATTLE_UNIT_COUNT; i++ ) { // Gather some initial information BattleUnitTypes unitType = (BattleUnitTypes) i; aiUnitsBegin[unitType] = kBattleDefinition.getUnit(unitType)->getSubUnitsAlive(kBattleDefinition.getDamage(unitType, BATTLE_TIME_BEGIN)); aiToKillRanged[unitType] = computeUnitsToDie( kBattleDefinition, true, unitType); aiToKillMelee[unitType] = computeUnitsToDie( kBattleDefinition, false, unitType); aiUnitsEnd[unitType] = aiUnitsBegin[unitType] - aiToKillMelee[unitType] - aiToKillRanged[unitType]; // Make sure that if they aren't dead at the end, they have at least one unit left if ( aiUnitsEnd[unitType] == 0 && !kBattleDefinition.getUnit(unitType)->isDead() ) { aiUnitsEnd[unitType]++; if ( aiToKillMelee[unitType] > 0 ) { aiToKillMelee[unitType]--; } else { aiToKillRanged[unitType]--; } } // If one unit is the loser, make sure that at least one of their units dies in the last round if ( aiUnitsEnd[unitType] == 0 ) { kBattleDefinition.getBattleRound(iTotalRounds - 1).addNumKilled(unitType, 1); if ( aiToKillMelee[unitType] > 0) { aiToKillMelee[unitType]--; } else { aiToKillRanged[unitType]--; } } // Randomize in which round each death occurs bIsLoser = aiUnitsEnd[unitType] == 0; // Randomize the ranged deaths for ( j = 0; j < aiToKillRanged[unitType]; j++ ) { iRoundIndex = GC.getGameINLINE().getSorenRandNum( range( kBattleDefinition.getNumRangedRounds(), 0, kBattleDefinition.getNumRangedRounds()), "Ranged combat death"); kBattleDefinition.getBattleRound(iRoundIndex).addNumKilled(unitType, 1); } // Randomize the melee deaths for ( j = 0; j < aiToKillMelee[unitType]; j++ ) { iRoundIndex = GC.getGameINLINE().getSorenRandNum( range( kBattleDefinition.getNumMeleeRounds() - (bIsLoser ? 1 : 2 ), 0, kBattleDefinition.getNumMeleeRounds()), "Melee combat death"); kBattleDefinition.getBattleRound(kBattleDefinition.getNumRangedRounds() + iRoundIndex).addNumKilled(unitType, 1); } // Compute alive sums int iNumberKilled = 0; for(int j=0;j<kBattleDefinition.getNumBattleRounds();j++) { CvBattleRound &round = kBattleDefinition.getBattleRound(j); round.setRangedRound(j < kBattleDefinition.getNumRangedRounds()); iNumberKilled += round.getNumKilled(unitType); round.setNumAlive(unitType, aiUnitsBegin[unitType] - iNumberKilled); } } // Now compute wave sizes for(int i=0;i<kBattleDefinition.getNumBattleRounds();i++) { CvBattleRound &round = kBattleDefinition.getBattleRound(i); round.setWaveSize(computeWaveSize(round.isRangedRound(), round.getNumAlive(BATTLE_UNIT_ATTACKER) + round.getNumKilled(BATTLE_UNIT_ATTACKER), round.getNumAlive(BATTLE_UNIT_DEFENDER) + round.getNumKilled(BATTLE_UNIT_DEFENDER))); } if ( iTotalRounds > 400 ) { kBattleDefinition.setNumMeleeRounds(1); kBattleDefinition.setNumRangedRounds(0); break; } } while ( !verifyRoundsValid( kBattleDefinition )); //add a little extra time for leader to surrender bool attackerLeader = false; bool defenderLeader = false; bool attackerDie = false; bool defenderDie = false; int lastRound = kBattleDefinition.getNumBattleRounds() - 1; if(kBattleDefinition.getUnit(BATTLE_UNIT_ATTACKER)->getLeaderUnitType() != NO_UNIT) attackerLeader = true; if(kBattleDefinition.getUnit(BATTLE_UNIT_DEFENDER)->getLeaderUnitType() != NO_UNIT) defenderLeader = true; if(kBattleDefinition.getBattleRound(lastRound).getNumAlive(BATTLE_UNIT_ATTACKER) == 0) attackerDie = true; if(kBattleDefinition.getBattleRound(lastRound).getNumAlive(BATTLE_UNIT_DEFENDER) == 0) defenderDie = true; int extraTime = 0; if((attackerLeader && attackerDie) || (defenderLeader && defenderDie)) extraTime = BATTLE_TURNS_MELEE; if(gDLL->getEntityIFace()->GetSiegeTower(kBattleDefinition.getUnit(BATTLE_UNIT_ATTACKER)->getUnitEntity()) || gDLL->getEntityIFace()->GetSiegeTower(kBattleDefinition.getUnit(BATTLE_UNIT_DEFENDER)->getUnitEntity())) extraTime = BATTLE_TURNS_MELEE; return BATTLE_TURNS_SETUP + BATTLE_TURNS_ENDING + kBattleDefinition.getNumMeleeRounds() * BATTLE_TURNS_MELEE + kBattleDefinition.getNumRangedRounds() * BATTLE_TURNS_MELEE + extraTime; } //------------------------------------------------------------------------------------------------ // FUNCTION: CvBattleManager::computeDeadUnits //! \brief Computes the number of units dead, for either the ranged or melee portion of combat. //! \param kDefinition The battle definition. //! \param bRanged true if computing the number of units that die during the ranged portion of combat, //! false if computing the number of units that die during the melee portion of combat. //! \param iUnit The index of the unit to compute (BATTLE_UNIT_ATTACKER or BATTLE_UNIT_DEFENDER). //! \retval The number of units that should die for the given unit in the given portion of combat //------------------------------------------------------------------------------------------------ int CvUnit::computeUnitsToDie( const CvBattleDefinition & kDefinition, bool bRanged, BattleUnitTypes iUnit ) const { FAssertMsg( iUnit == BATTLE_UNIT_ATTACKER || iUnit == BATTLE_UNIT_DEFENDER, "Invalid unit index"); BattleTimeTypes iBeginIndex = bRanged ? BATTLE_TIME_BEGIN : BATTLE_TIME_RANGED; BattleTimeTypes iEndIndex = bRanged ? BATTLE_TIME_RANGED : BATTLE_TIME_END; return kDefinition.getUnit(iUnit)->getSubUnitsAlive(kDefinition.getDamage(iUnit, iBeginIndex)) - kDefinition.getUnit(iUnit)->getSubUnitsAlive( kDefinition.getDamage(iUnit, iEndIndex)); } //------------------------------------------------------------------------------------------------ // FUNCTION: CvUnit::verifyRoundsValid //! \brief Verifies that all rounds in the battle plan are valid //! \param vctBattlePlan The battle plan //! \retval true if the battle plan (seems) valid, false otherwise //------------------------------------------------------------------------------------------------ bool CvUnit::verifyRoundsValid( const CvBattleDefinition & battleDefinition ) const { for(int i=0;i<battleDefinition.getNumBattleRounds();i++) { if(!battleDefinition.getBattleRound(i).isValid()) return false; } return true; } //------------------------------------------------------------------------------------------------ // FUNCTION: CvUnit::increaseBattleRounds //! \brief Increases the number of rounds in the battle. //! \param kBattleDefinition The definition of the battle //------------------------------------------------------------------------------------------------ void CvUnit::increaseBattleRounds( CvBattleDefinition & kBattleDefinition ) const { if ( kBattleDefinition.getUnit(BATTLE_UNIT_ATTACKER)->isRanged() && kBattleDefinition.getUnit(BATTLE_UNIT_DEFENDER)->isRanged()) { kBattleDefinition.addNumRangedRounds(1); } else { kBattleDefinition.addNumMeleeRounds(1); } } //------------------------------------------------------------------------------------------------ // FUNCTION: CvUnit::computeWaveSize //! \brief Computes the wave size for the round. //! \param bRangedRound true if the round is a ranged round //! \param iAttackerMax The maximum number of attackers that can participate in a wave (alive) //! \param iDefenderMax The maximum number of Defenders that can participate in a wave (alive) //! \retval The desired wave size for the given parameters //------------------------------------------------------------------------------------------------ int CvUnit::computeWaveSize( bool bRangedRound, int iAttackerMax, int iDefenderMax ) const { FAssertMsg( getCombatUnit() != NULL, "You must be fighting somebody!" ); int aiDesiredSize[BATTLE_UNIT_COUNT]; if ( bRangedRound ) { aiDesiredSize[BATTLE_UNIT_ATTACKER] = getUnitInfo().getRangedWaveSize(); aiDesiredSize[BATTLE_UNIT_DEFENDER] = getCombatUnit()->getUnitInfo().getRangedWaveSize(); } else { aiDesiredSize[BATTLE_UNIT_ATTACKER] = getUnitInfo().getMeleeWaveSize(); aiDesiredSize[BATTLE_UNIT_DEFENDER] = getCombatUnit()->getUnitInfo().getMeleeWaveSize(); } aiDesiredSize[BATTLE_UNIT_DEFENDER] = aiDesiredSize[BATTLE_UNIT_DEFENDER] <= 0 ? iDefenderMax : aiDesiredSize[BATTLE_UNIT_DEFENDER]; aiDesiredSize[BATTLE_UNIT_ATTACKER] = aiDesiredSize[BATTLE_UNIT_ATTACKER] <= 0 ? iDefenderMax : aiDesiredSize[BATTLE_UNIT_ATTACKER]; return std::min( std::min( aiDesiredSize[BATTLE_UNIT_ATTACKER], iAttackerMax ), std::min( aiDesiredSize[BATTLE_UNIT_DEFENDER], iDefenderMax) ); } bool CvUnit::isTargetOf(const CvUnit& attacker) const { CvUnitInfo& attackerInfo = attacker.getUnitInfo(); CvUnitInfo& ourInfo = getUnitInfo(); if (!plot()->isCity(true, getTeam())) { if (NO_UNITCLASS != getUnitClassType() && attackerInfo.getTargetUnitClass(getUnitClassType())) { return true; } if (NO_UNITCOMBAT != getUnitCombatType() && attackerInfo.getTargetUnitCombat(getUnitCombatType())) { return true; } } if (NO_UNITCLASS != attackerInfo.getUnitClassType() && ourInfo.getDefenderUnitClass(attackerInfo.getUnitClassType())) { return true; } if (NO_UNITCOMBAT != attackerInfo.getUnitCombatType() && ourInfo.getDefenderUnitCombat(attackerInfo.getUnitCombatType())) { return true; } return false; } bool CvUnit::isEnemy(TeamTypes eTeam, const CvPlot* pPlot) const { if (NULL == pPlot) { pPlot = plot(); } return (atWar(GET_PLAYER(getCombatOwner(eTeam, pPlot)).getTeam(), eTeam)); } bool CvUnit::isPotentialEnemy(TeamTypes eTeam, const CvPlot* pPlot) const { if (NULL == pPlot) { pPlot = plot(); } return (::isPotentialEnemy(GET_PLAYER(getCombatOwner(eTeam, pPlot)).getTeam(), eTeam)); } bool CvUnit::isSuicide() const { return (m_pUnitInfo->isSuicide() || getKamikazePercent() != 0); } int CvUnit::getDropRange() const { return (m_pUnitInfo->getDropRange()); } void CvUnit::getDefenderCombatValues(CvUnit& kDefender, const CvPlot* pPlot, int iOurStrength, int iOurFirepower, int& iTheirOdds, int& iTheirStrength, int& iOurDamage, int& iTheirDamage, CombatDetails* pTheirDetails) const { iTheirStrength = kDefender.currCombatStr(pPlot, this, pTheirDetails); int iTheirFirepower = kDefender.currFirepower(pPlot, this); FAssert((iOurStrength + iTheirStrength) > 0); FAssert((iOurFirepower + iTheirFirepower) > 0); iTheirOdds = ((GC.getDefineINT("COMBAT_DIE_SIDES") * iTheirStrength) / (iOurStrength + iTheirStrength)); if (kDefender.isBarbarian()) { if (GET_PLAYER(getOwnerINLINE()).getWinsVsBarbs() < GC.getHandicapInfo(GET_PLAYER(getOwnerINLINE()).getHandicapType()).getFreeWinsVsBarbs()) { iTheirOdds = std::min((10 * GC.getDefineINT("COMBAT_DIE_SIDES")) / 100, iTheirOdds); } } if (isBarbarian()) { if (GET_PLAYER(kDefender.getOwnerINLINE()).getWinsVsBarbs() < GC.getHandicapInfo(GET_PLAYER(kDefender.getOwnerINLINE()).getHandicapType()).getFreeWinsVsBarbs()) { iTheirOdds = std::max((90 * GC.getDefineINT("COMBAT_DIE_SIDES")) / 100, iTheirOdds); } } int iStrengthFactor = ((iOurFirepower + iTheirFirepower + 1) / 2); // Vincentz Damage iOurDamage = std::max(1, ((GC.getDefineINT("COMBAT_DAMAGE") * (iTheirFirepower + iStrengthFactor)) / (iOurFirepower + iStrengthFactor)) / 2); iTheirDamage = std::max(1, ((GC.getDefineINT("COMBAT_DAMAGE") * (iOurFirepower + iStrengthFactor)) / (iTheirFirepower + iStrengthFactor)) / 2); } int CvUnit::getTriggerValue(EventTriggerTypes eTrigger, const CvPlot* pPlot, bool bCheckPlot) const { CvEventTriggerInfo& kTrigger = GC.getEventTriggerInfo(eTrigger); if (kTrigger.getNumUnits() <= 0) { return MIN_INT; } if (isDead()) { return MIN_INT; } if (!CvString(kTrigger.getPythonCanDoUnit()).empty()) { long lResult; CyArgsList argsList; argsList.add(eTrigger); argsList.add(getOwnerINLINE()); argsList.add(getID()); gDLL->getPythonIFace()->callFunction(PYRandomEventModule, kTrigger.getPythonCanDoUnit(), argsList.makeFunctionArgs(), &lResult); if (0 == lResult) { return MIN_INT; } } if (kTrigger.getNumUnitsRequired() > 0) { bool bFoundValid = false; for (int i = 0; i < kTrigger.getNumUnitsRequired(); ++i) { if (getUnitClassType() == kTrigger.getUnitRequired(i)) { bFoundValid = true; break; } } if (!bFoundValid) { return MIN_INT; } } if (bCheckPlot) { if (kTrigger.isUnitsOnPlot()) { if (!plot()->canTrigger(eTrigger, getOwnerINLINE())) { return MIN_INT; } } } int iValue = 0; if (0 == getDamage() && kTrigger.getUnitDamagedWeight() > 0) { return MIN_INT; } iValue += getDamage() * kTrigger.getUnitDamagedWeight(); iValue += getExperience() * kTrigger.getUnitExperienceWeight(); if (NULL != pPlot) { iValue += plotDistance(getX_INLINE(), getY_INLINE(), pPlot->getX_INLINE(), pPlot->getY_INLINE()) * kTrigger.getUnitDistanceWeight(); } return iValue; } bool CvUnit::canApplyEvent(EventTypes eEvent) const { CvEventInfo& kEvent = GC.getEventInfo(eEvent); if (0 != kEvent.getUnitExperience()) { if (!canAcquirePromotionAny()) { return false; } } if (NO_PROMOTION != kEvent.getUnitPromotion()) { if (!canAcquirePromotion((PromotionTypes)kEvent.getUnitPromotion())) { return false; } } if (kEvent.getUnitImmobileTurns() > 0) { if (!canAttack()) { return false; } } return true; } void CvUnit::applyEvent(EventTypes eEvent) { if (!canApplyEvent(eEvent)) { return; } CvEventInfo& kEvent = GC.getEventInfo(eEvent); if (0 != kEvent.getUnitExperience()) { setDamage(0); changeExperience(kEvent.getUnitExperience()); } if (NO_PROMOTION != kEvent.getUnitPromotion()) { setHasPromotion((PromotionTypes)kEvent.getUnitPromotion(), true); } if (kEvent.getUnitImmobileTurns() > 0) { changeImmobileTimer(kEvent.getUnitImmobileTurns()); CvWString szText = gDLL->getText("TXT_KEY_EVENT_UNIT_IMMOBILE", getNameKey(), kEvent.getUnitImmobileTurns()); gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), false, GC.getEVENT_MESSAGE_TIME(), szText, "AS2D_UNITGIFTED", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_UNIT_TEXT"), getX_INLINE(), getY_INLINE(), true, true); } CvWString szNameKey(kEvent.getUnitNameKey()); if (!szNameKey.empty()) { setName(gDLL->getText(kEvent.getUnitNameKey())); } if (kEvent.isDisbandUnit()) { kill(false); } } const CvArtInfoUnit* CvUnit::getArtInfo(int i, EraTypes eEra) const { return m_pUnitInfo->getArtInfo(i, eEra, (UnitArtStyleTypes) GC.getCivilizationInfo(getCivilizationType()).getUnitArtStyleType()); } const TCHAR* CvUnit::getButton() const { const CvArtInfoUnit* pArtInfo = getArtInfo(0, GET_PLAYER(getOwnerINLINE()).getCurrentEra()); if (NULL != pArtInfo) { return pArtInfo->getButton(); } return m_pUnitInfo->getButton(); } int CvUnit::getGroupSize() const { return m_pUnitInfo->getGroupSize(); } int CvUnit::getGroupDefinitions() const { return m_pUnitInfo->getGroupDefinitions(); } int CvUnit::getUnitGroupRequired(int i) const { return m_pUnitInfo->getUnitGroupRequired(i); } bool CvUnit::isRenderAlways() const { return m_pUnitInfo->isRenderAlways(); } float CvUnit::getAnimationMaxSpeed() const { return m_pUnitInfo->getUnitMaxSpeed(); } float CvUnit::getAnimationPadTime() const { return m_pUnitInfo->getUnitPadTime(); } const char* CvUnit::getFormationType() const { return m_pUnitInfo->getFormationType(); } bool CvUnit::isMechUnit() const { return m_pUnitInfo->isMechUnit(); } bool CvUnit::isRenderBelowWater() const { return m_pUnitInfo->isRenderBelowWater(); } int CvUnit::getRenderPriority(UnitSubEntityTypes eUnitSubEntity, int iMeshGroupType, int UNIT_MAX_SUB_TYPES) const { if (eUnitSubEntity == UNIT_SUB_ENTITY_SIEGE_TOWER) { return (getOwner() * (GC.getNumUnitInfos() + 2) * UNIT_MAX_SUB_TYPES) + iMeshGroupType; } else { return (getOwner() * (GC.getNumUnitInfos() + 2) * UNIT_MAX_SUB_TYPES) + m_eUnitType * UNIT_MAX_SUB_TYPES + iMeshGroupType; } } bool CvUnit::isAlwaysHostile(const CvPlot* pPlot) const { if (!m_pUnitInfo->isAlwaysHostile()) { return false; } if (NULL != pPlot && pPlot->isCity(true, getTeam())) { return false; } return true; //Vincentz Hostile before open borders OFF for now /* if ((!m_pUnitInfo->isAlwaysHostile()) && (GET_TEAM(GC.getGameINLINE().getActiveTeam()).isOpenBordersTrading())) //Vincentz Always war without openborders enabled { return false; } if (NULL != pPlot && pPlot->isCity(true, getTeam())) //&& (GET_TEAM(GC.getGameINLINE().getActiveTeam()).isOpenBordersTrading())) { return false; } //Vincentz Always War start TeamTypes eTeam = plot()->getTeam(); if ((GET_TEAM(getTeam()).isFriendlyTerritory(eTeam)) && !(GET_TEAM(GC.getGameINLINE().getActiveTeam()).isOpenBordersTrading())) { return false; } //Vincentz Always War end return true; */ } bool CvUnit::verifyStackValid() { if (!alwaysInvisible()) { if (plot()->isVisibleEnemyUnit(this)) { return jumpToNearestValidPlot(); } } //Vincentz #UPT int iNumVisibleUnits = 0; if (plot()->isVisible(GC.getGameINLINE().getActiveTeam(), !GC.getGameINLINE().isDebugMode())) { CLLNode<IDInfo>* pUnitNode5 = plot()->headUnitNode(); while (pUnitNode5 != NULL) { CvUnit* pUnit = ::getUnit(pUnitNode5->m_data); pUnitNode5 = plot()->nextUnitNode(pUnitNode5); if (pUnit && !pUnit->isInvisible(GC.getGameINLINE().getActiveTeam(), false)) { ++iNumVisibleUnits; } } } // if ((plot()->getNumUnits() > GC.getDefineINT("MAXUPT")) && (getDomainType() != DOMAIN_AIR)) if ((iNumVisibleUnits > GC.getDefineINT("MAXUPT") * GET_PLAYER(getOwnerINLINE()).getCurrentEra() + GC.getDefineINT("STARTUPT")) && (getDomainType() != DOMAIN_AIR)) { return jumpToNearestValidPlot(); } //Vincentz #UPT return true; } // Private Functions... //check if quick combat bool CvUnit::isCombatVisible(const CvUnit* pDefender) const { bool bVisible = false; if (!m_pUnitInfo->isQuickCombat()) { if (NULL == pDefender || !pDefender->getUnitInfo().isQuickCombat()) { if (isHuman()) { if (!GET_PLAYER(getOwnerINLINE()).isOption(PLAYEROPTION_QUICK_ATTACK)) { bVisible = true; } } else if (NULL != pDefender && pDefender->isHuman()) { if (!GET_PLAYER(pDefender->getOwnerINLINE()).isOption(PLAYEROPTION_QUICK_DEFENSE)) { bVisible = true; } } } } return bVisible; } // used by the executable for the red glow and plot indicators bool CvUnit::shouldShowEnemyGlow(TeamTypes eForTeam) const { if (isDelayedDeath()) { return false; } if (getDomainType() == DOMAIN_AIR) { return false; } if (!canFight()) { return false; } CvPlot* pPlot = plot(); if (pPlot == NULL) { return false; } TeamTypes ePlotTeam = pPlot->getTeam(); if (ePlotTeam != eForTeam) { return false; } if (!isEnemy(ePlotTeam)) { return false; } return true; } bool CvUnit::shouldShowFoundBorders() const { return isFound(); } void CvUnit::cheat(bool bCtrl, bool bAlt, bool bShift) { if (gDLL->getChtLvl() > 0) { if (bCtrl) { setPromotionReady(true); } } } float CvUnit::getHealthBarModifier() const { return (GC.getDefineFLOAT("HEALTH_BAR_WIDTH") / (GC.getGameINLINE().getBestLandUnitCombat() * 2)); } void CvUnit::getLayerAnimationPaths(std::vector<AnimationPathTypes>& aAnimationPaths) const { for (int i=0; i < GC.getNumPromotionInfos(); ++i) { PromotionTypes ePromotion = (PromotionTypes) i; if (isHasPromotion(ePromotion)) { AnimationPathTypes eAnimationPath = (AnimationPathTypes) GC.getPromotionInfo(ePromotion).getLayerAnimationPath(); if(eAnimationPath != ANIMATIONPATH_NONE) { aAnimationPaths.push_back(eAnimationPath); } } } } int CvUnit::getSelectionSoundScript() const { int iScriptId = getArtInfo(0, GET_PLAYER(getOwnerINLINE()).getCurrentEra())->getSelectionSoundScriptId(); if (iScriptId == -1) { iScriptId = GC.getCivilizationInfo(getCivilizationType()).getSelectionSoundScriptId(); } return iScriptId; } /**************************************** * Archid Mod: 10 Oct 2012 * Functionality: SeeInvisiblePromotion - Archid * * Source: * Archid * ****************************************/ void CvUnit::changeSeeInvisibleCount(InvisibleTypes eInvisibleType, int iChange) { FAssertMsg(eInvisibleType >= 0, "eInvisibleType expected to be >= 0"); FAssertMsg(eInvisibleType < GC.getNumInvisibleInfos(), "eInvisibleType expected to be < GC.getNumInvisibleInfos()"); // Now do the extra slave processing int iNewValue = getSeeInvisibleCount(eInvisibleType) + iChange; m_paiSeeInvisible[eInvisibleType] = iNewValue; FAssert(getSeeInvisibleCount(eInvisibleType) >= 0); } int CvUnit::getSeeInvisibleCount(InvisibleTypes eInvisibleType) const { return m_paiSeeInvisible[eInvisibleType]; } /** ** End: SeeInvisiblePromotion **/ /************************************************************************************************/ /* Afforess Start 03/6/10 */ /* */ /* Better Air Interception */ /************************************************************************************************/ int CvUnit::interceptionChance(const CvPlot* pPlot) const { int iValue; int iLoop; int iI; int iNoInterceptionChanceTimes100 = 10000; CvUnit* pLoopUnit; for (iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { if (isEnemy(GET_PLAYER((PlayerTypes)iI).getTeam()) && !isInvisible(GET_PLAYER((PlayerTypes)iI).getTeam(), false, false)) { for (pLoopUnit = GET_PLAYER((PlayerTypes)iI).firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = GET_PLAYER((PlayerTypes)iI).nextUnit(&iLoop)) { if (pLoopUnit->canAirDefend()) { if (!pLoopUnit->isMadeInterception()) { if ((pLoopUnit->getDomainType() != DOMAIN_AIR) || !(pLoopUnit->hasMoved())) { if ((pLoopUnit->getDomainType() != DOMAIN_AIR) || (pLoopUnit->getGroup()->getActivityType() == ACTIVITY_INTERCEPT)) { if (plotDistance(pLoopUnit->getX_INLINE(), pLoopUnit->getY_INLINE(), pPlot->getX_INLINE(), pPlot->getY_INLINE()) <= pLoopUnit->airRange()) { iValue = pLoopUnit->currInterceptionProbability(); if (iValue > 0 && iValue < 100) { iNoInterceptionChanceTimes100 *= (100 - iValue); iNoInterceptionChanceTimes100 /= 100; } else if (iValue >= 100) return 100; } } } } } } } } } return 100 - (iNoInterceptionChanceTimes100 / 100); } /************************************************************************************************/ /* Afforess END */ /************************************************************************************************/
[ "henrik_v_poulsen@hotmail.com" ]
henrik_v_poulsen@hotmail.com
6a93fc5052e788f0971c86160cb918649d673f34
9d364070c646239b2efad7abbab58f4ad602ef7b
/platform/external/chromium_org/chrome/browser/chromeos/policy/user_policy_token_loader.h
c4100cf2bc0a7bf09b4a6008f71b39c78731661a
[ "BSD-3-Clause" ]
permissive
denix123/a32_ul
4ffe304b13c1266b6c7409d790979eb8e3b0379c
b2fd25640704f37d5248da9cc147ed267d4771c2
refs/heads/master
2021-01-17T20:21:17.196296
2016-08-16T04:30:53
2016-08-16T04:30:53
65,786,970
0
2
null
2020-03-06T22:00:52
2016-08-16T04:15:54
null
UTF-8
C++
false
false
1,551
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_CHROMEOS_POLICY_USER_POLICY_TOKEN_LOADER_H_ #define CHROME_BROWSER_CHROMEOS_POLICY_USER_POLICY_TOKEN_LOADER_H_ #include <string> #include "base/basictypes.h" #include "base/files/file_path.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" namespace base { class SequencedTaskRunner; } namespace policy { class UserPolicyTokenLoader : public base::RefCountedThreadSafe<UserPolicyTokenLoader> { public: class Delegate { public: virtual ~Delegate(); virtual void OnTokenLoaded(const std::string& token, const std::string& device_id) = 0; }; UserPolicyTokenLoader( const base::WeakPtr<Delegate>& delegate, const base::FilePath& cache_file, scoped_refptr<base::SequencedTaskRunner> background_task_runner); void Load(); private: friend class base::RefCountedThreadSafe<UserPolicyTokenLoader>; ~UserPolicyTokenLoader(); void LoadOnBackgroundThread(); void NotifyOnOriginThread(const std::string& token, const std::string& device_id); const base::WeakPtr<Delegate> delegate_; const base::FilePath cache_file_; scoped_refptr<base::SequencedTaskRunner> origin_task_runner_; scoped_refptr<base::SequencedTaskRunner> background_task_runner_; DISALLOW_COPY_AND_ASSIGN(UserPolicyTokenLoader); }; } #endif
[ "allegrant@mail.ru" ]
allegrant@mail.ru
620af87aa7833870de938d99f5d85e9608e35683
e049ee8d57363548f91b30b6148f0db03123190b
/functions.hpp
6236923a674ab539ed0631b23c89390d9e09958c
[]
no_license
embedded-systems-programming-aa-2021-22/assignment-01-alberto-trabacchin-unipd
4b13bb674b489259c236fc735e27dc62da180002
82f2ce2ac955ab7a36476f4d6372100b57c58a54
refs/heads/master
2023-08-24T21:09:24.900248
2021-10-29T08:08:51
2021-10-29T08:08:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
523
hpp
#ifndef FUNCTIONS_H #define FUNCTIONS_H #include <iostream> #include <vector> #include <string> namespace pse { void print(std::vector<std::string> v); void print(std::vector<int> v); std::vector<int> string_lengths(std::vector<std::string> v); std::string longest_string(std::vector<std::string> v); std::string shortest_string(std::vector<std::string> v); std::string alpha_first_string(std::vector<std::string> v); std::string alpha_last_string(std::vector<std::string> v); } #endif
[ "alberto.trabacchin@studenti.unipd.it" ]
alberto.trabacchin@studenti.unipd.it
60cb569987a63216d7e8ef84be44f0e37a0d1b7b
58da52e029ab1e9ee91ee290aab97185a57b77d3
/include/AcEsentLibrary.h
9d620db5e15f19b42f872533c72aa487ca4daac8
[]
no_license
vladp72/ac
9998f3fcbdc6bd1108fe73bfcd87b5353e8a6683
5c0bda70dc6f9eddb80230edfc33300eb02ac4cd
refs/heads/master
2020-03-27T08:21:22.998284
2018-09-17T00:01:43
2018-09-17T00:01:43
146,247,066
0
0
null
null
null
null
UTF-8
C++
false
false
18,843
h
#pragma once namespace ac { enum class esent_set_mode : int { default, must_succeed, // Setting this parameter must succeed (including not have been previously set) failure_ok_if_equal, // Setting this parameter must succeed (doesn't matter if previously set to same value, only allowed for numeric values, not strings) failure_ok_if_equal_or_greater, // Setting this parameter must succeed (doesn't matter if previously set to same or larger value, only allowed for numeric values, not strings) ignore_failure, // Don't care if setting this parameter succeeds }; struct esent_parameter : JET_SETSYSPARAM { esent_parameter() = default; esent_parameter(esent_parameter const &) = default; esent_parameter(esent_parameter &&) = default; esent_parameter &operator= (esent_parameter const &) = default; esent_parameter &operator= (esent_parameter &&) = default; static unsigned long const max_sessions{ 32 }; static unsigned long const max_cursors{ 40 }; // Only allow nesting of 40 transaction layers static unsigned long const database_page_size{ 8 * 1024 }; // 8k page size static unsigned long const log_file_size_in_kb{ 512 }; // 512k log files static unsigned long const cache_size{ 512 }; // 512k cache size (in db pages) static unsigned long const max_jet_sessions = 30000; static unsigned long const max_jet_open_tables = (max_jet_sessions * 10); esent_parameter(unsigned long parameter_id, JET_API_PTR number_value, TCHAR const *string_value) : JET_SETSYSPARAM{ parameter_id, number_value, string_value, JET_errSuccess} { } esent_parameter(unsigned long parameter_id, JET_API_PTR number_value) : JET_SETSYSPARAM{ parameter_id, number_value, nullptr, JET_errSuccess} { } esent_parameter(unsigned long parameter_id, TCHAR const *string_value) : JET_SETSYSPARAM{ parameter_id, 0, string_value, JET_errSuccess} { } }; //using esent_system_parameter_value = std::variant<unsigned long, tstring>; // // By default Esent is in single instance mode. // always call this function to enable multiinstance // optionally set ste-sys-param if you want to set some // parameters that should apply to all instances. // Only sys-params from first caller are stored. // class esent_library { public: esent_library() = delete; ~esent_library() = delete; static std::error_code try_init(); static void init(); static std::error_code try_enable_multiple_instances(JET_SETSYSPARAM* psetsysparam = nullptr, unsigned long csetsysparam = 0, unsigned long* pcsetsucceed = nullptr) noexcept { std::error_code err = make_esent_error_code( JetEnableMultiInstance(psetsysparam, csetsysparam, pcsetsucceed )); return err; } static bool enable_multiple_instances(JET_SETSYSPARAM* psetsysparam = nullptr, unsigned long csetsysparam = 0, unsigned long* pcsetsucceed = nullptr) { std::error_code err = make_esent_error_code( JetEnableMultiInstance(psetsysparam, csetsysparam, pcsetsucceed )); if (esent_err::errSystemParamsAlreadySet == err) { return false; } ESENT_THROW_ON_ERROR_FMT(err, "JetEnableMultiInstance(%u) failed", csetsysparam); return true; } static std::error_code try_get_instances_info(ecent_instances_info &info) noexcept { unsigned long count{ 0 }; JET_INSTANCE_INFO *ptr{ nullptr }; std::error_code err = make_esent_error_code(JetGetInstanceInfo(&count, &ptr)); if (esent_err::errSuccess == err) { info.count = count; info.info.reset(ptr); } return err; } static ecent_instances_info get_instances_info() { ecent_instances_info info; std::error_code err = try_get_instances_info(info); ESENT_THROW_ON_ERROR(err, "JetGetInstanceInfo failed"); return info; } static std::error_code try_set_system_parameter(JET_INSTANCE instance_id, JET_SESID session_id, ULONG const parameter_id, JET_API_PTR number_value, TCHAR const *string_value, esent_set_mode set_mode = esent_set_mode::default); static void set_system_parameter(JET_INSTANCE instance_id, JET_SESID session_id, ULONG parameter_id, JET_API_PTR number_value, TCHAR const *string_value, esent_set_mode set_mode = esent_set_mode::default) { std::error_code err = try_set_system_parameter(instance_id, session_id, parameter_id, number_value, string_value, set_mode); ESENT_THROW_ON_ERROR_FMT(err, "JetSetSystemParameter(0x%p, 0x%p, %u, %Iu, %s) set mode %u, failed", instance_id, session_id, parameter_id, number_value, t_to_a(SANITIZE_CSTR_FOR_PRINTF(string_value)).c_str(), set_mode); } static std::error_code try_set_system_parameter(unsigned long parameter_id, JET_API_PTR number_value = 0, esent_set_mode set_mode = esent_set_mode::default) noexcept { return try_set_system_parameter(JET_instanceNil, JET_sesidNil, parameter_id, number_value, nullptr, set_mode); } static std::error_code try_set_system_parameter(unsigned long parameter_id, TCHAR const *string_value, esent_set_mode set_mode = esent_set_mode::default) noexcept { return try_set_system_parameter(JET_instanceNil, JET_sesidNil, parameter_id, 0, string_value, set_mode); } static void set_system_parameter(unsigned long parameter_id, JET_API_PTR number_value = 0, esent_set_mode set_mode = esent_set_mode::default) { set_system_parameter(JET_instanceNil, JET_sesidNil, parameter_id, number_value, nullptr, set_mode); } static void set_system_parameter(unsigned long parameter_id, TCHAR const *string_value, esent_set_mode set_mode = esent_set_mode::default) { set_system_parameter(JET_instanceNil, JET_sesidNil, parameter_id, 0, string_value, set_mode); } static std::error_code try_get_system_parameter(unsigned long parameter_id, JET_API_PTR *param) noexcept { std::error_code err = make_esent_error_code( JetGetSystemParameter(JET_instanceNil, JET_sesidNil, parameter_id, param, nullptr, sizeof(JET_API_PTR))); JET_CODDING_ERROR_IF(esent_err::errAlreadyInitialized == err || esent_err::errInvalidInstance == err || esent_err::errInvalidSesid == err); return err; } static std::error_code try_get_system_parameter(unsigned long parameter_id, TCHAR *param, unsigned long buffer_size = 0) noexcept { std::error_code err = make_esent_error_code( JetGetSystemParameter(JET_instanceNil, JET_sesidNil, parameter_id, nullptr, param, buffer_size)); JET_CODDING_ERROR_IF(esent_err::errAlreadyInitialized == err || esent_err::errInvalidInstance == err || esent_err::errInvalidSesid == err); return err; } static JET_API_PTR get_system_parameter_as_long(unsigned long parameter_id) { JET_API_PTR param{ 0 }; std::error_code err = try_get_system_parameter(parameter_id, &param); ESENT_THROW_ON_ERROR_FMT(err, "JetGetSystemParameter(%u) failed", parameter_id); return param; } static tstring get_system_parameter_as_string(unsigned long parameter_id) { tbuffer buffer{ 1024+8, _T('\0') }; std::error_code err = try_get_system_parameter(parameter_id, &buffer[0], static_cast<unsigned long>(buffer.size() - sizeof(TCHAR))); tstring value{ &buffer[0] }; ESENT_THROW_ON_ERROR_FMT(err, "JetGetSystemParameter(%u, %s) failed", parameter_id, value.c_str()); return value; } static std::error_code try_get_thread_stats(JET_THREADSTATS &thread_stats) noexcept { std::error_code err = make_esent_error_code( JetGetThreadStats(&thread_stats, sizeof(thread_stats))); return err; } static JET_THREADSTATS get_thread_stats() { JET_THREADSTATS thread_stats{}; std::error_code err = try_get_thread_stats(thread_stats); ESENT_THROW_ON_ERROR_FMT(err, "JetGetThreadStats(%u) failed", sizeof(thread_stats)); } private : }; struct esent_thread_stats { public: esent_thread_stats() noexcept { std::error_code err = try_reset(); } esent_thread_stats(esent_thread_stats const &other) noexcept : error_(other.error_) , stats_(other.stats_) { } esent_thread_stats operator= (esent_thread_stats const &other) noexcept { error_ = other.error_; stats_ = other.stats_; return *this; } std::error_code const &try_reset() noexcept { error_ = esent_library::try_get_thread_stats(stats_); return error_; } void reset() noexcept { std::error_code error = try_reset(); } std::error_code get_reset_error() const noexcept { return error_; } bool is_valid() const { return (error_ == esent_err::errSuccess); } explicit operator bool() const noexcept { return is_valid(); } std::error_code try_now(JET_THREADSTATS &diff) const noexcept { std::error_code error = esent_err::errSuccess; if (error_ == esent_err::errSuccess) { error = esent_library::try_get_thread_stats(diff); if (error == esent_err::errSuccess) { if (diff.cPageReferenced >= stats_.cPageReferenced) { diff.cPageReferenced -= stats_.cPageReferenced; } else { diff.cPageReferenced = 0; } if (diff.cPageRead >= stats_.cPageRead) { diff.cPageRead -= stats_.cPageRead; } else { diff.cPageRead = 0; } if (diff.cPagePreread >= stats_.cPagePreread) { diff.cPagePreread -= stats_.cPagePreread; } else { diff.cPagePreread = 0; } if (diff.cPageDirtied >= stats_.cPageDirtied) { diff.cPageDirtied -= stats_.cPageDirtied; } else { diff.cPageDirtied = 0; } if (diff.cPageRedirtied >= stats_.cPageRedirtied) { diff.cPageRedirtied -= stats_.cPageRedirtied; } else { diff.cPageRedirtied = 0; } if (diff.cLogRecord >= stats_.cLogRecord) { diff.cLogRecord -= stats_.cLogRecord; } else { diff.cLogRecord = 0; } if (diff.cbLogRecord >= stats_.cbLogRecord) { diff.cbLogRecord -= stats_.cbLogRecord; } else { diff.cbLogRecord = 0; } } } else { error = error_; } return error; } void now(JET_THREADSTATS &diff) const noexcept { std::error_code err = try_now(diff); if (err != esent_err::errSuccess) { memset(&diff, 0, sizeof(diff)); diff.cbStruct = sizeof(diff); } } JET_THREADSTATS now() const noexcept { JET_THREADSTATS diff; now(diff); return diff; } tstring now_as_tstring() const { tstring str; JET_THREADSTATS diff; std::error_code err = try_now(diff); if (err == esent_err::errSuccess) { str = make_tstring(_T("thread_stats={page_referenced=%u, page_read=%u, page_preread=%u, page_dirtied=%u, page_redirtied=%u, log_records=%u, log_records_size=%u}"), diff.cPageReferenced, diff.cPageRead, diff.cPagePreread, diff.cPageDirtied, diff.cPageRedirtied, diff.cLogRecord, diff.cbLogRecord); } return str; } std::string now_as_string() const { std::string str; JET_THREADSTATS diff; std::error_code err = try_now(diff); if (err == esent_err::errSuccess) { str = make_string("thread_stats={page_referenced=%u, page_read=%u, page_preread=%u, page_dirtied=%u, page_redirtied=%u, log_records=%u, log_records_size=%u}", diff.cPageReferenced, diff.cPageRead, diff.cPagePreread, diff.cPageDirtied, diff.cPageRedirtied, diff.cLogRecord, diff.cbLogRecord); } return str; } std::wstring now_as_wstring() const { std::wstring str; JET_THREADSTATS diff; std::error_code err = try_now(diff); if (err == esent_err::errSuccess) { str = make_wstring(L"thread_stats={page_referenced=%u, page_read=%u, page_preread=%u, page_dirtied=%u, page_redirtied=%u, log_records=%u, log_records_size=%u}", diff.cPageReferenced, diff.cPageRead, diff.cPagePreread, diff.cPageDirtied, diff.cPageRedirtied, diff.cLogRecord, diff.cbLogRecord); } return str; } private: std::error_code error_{ esent_err::errNotInitialized }; JET_THREADSTATS stats_{}; }; }
[ "vladp72@hotmail.com" ]
vladp72@hotmail.com
302b4d974ce765d18d2555680991c72f0acf79a3
49f88ff91aa582e1a9d5ae5a7014f5c07eab7503
/gen/third_party/blink/renderer/core/css/properties/longhands/flex_grow.h
9d89bcaea12fa089da3d434d461c55232da7c61f
[]
no_license
AoEiuV020/kiwibrowser-arm64
b6c719b5f35d65906ae08503ec32f6775c9bb048
ae7383776e0978b945e85e54242b4e3f7b930284
refs/heads/main
2023-06-01T21:09:33.928929
2021-06-22T15:56:53
2021-06-22T15:56:53
379,186,747
0
1
null
null
null
null
UTF-8
C++
false
false
2,732
h
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Generated from template: // core/css/properties/templates/css_property_subclass.h.tmpl // and input files: // ../../third_party/blink/renderer/core/css/ComputedStyleFieldAliases.json5 // ../../third_party/blink/renderer/core/css/CSSProperties.json5 // ../../third_party/blink/renderer/core/css/properties/CSSPropertyMethods.json5 #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_LONGHAND_FLEX_GROW_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_LONGHAND_FLEX_GROW_H_ #include "third_party/blink/renderer/core/css/css_primitive_value.h" #include "third_party/blink/renderer/core/css/css_primitive_value_mappings.h" #include "third_party/blink/renderer/core/css/css_primitive_value_mappings.h" #include "third_party/blink/renderer/core/css/properties/longhand.h" #include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h" #include "third_party/blink/renderer/core/style/computed_style.h" namespace blink { namespace CSSLonghand { // Implements the 'flex-grow' CSS property // See src/third_party/WebKit/Source/core/css/properties/README.md class FlexGrow final : public Longhand { public: constexpr FlexGrow() : Longhand() {} const char* GetPropertyName() const override { return "flex-grow\0"; } const WTF::AtomicString& GetPropertyNameAtomicString() const override { static const WTF::AtomicString& name = WTF::AtomicString("flex-grow\0"); return name; } const WTF::String GetJSPropertyName() const override { return WTF::String("flexGrow\0"); } CSSPropertyID PropertyID() const override { return CSSPropertyFlexGrow; } const CSSValue* ParseSingleValue(CSSParserTokenRange&, const CSSParserContext&, const CSSParserLocalContext&) const override; const CSSValue* CSSValueFromComputedStyleInternal(const ComputedStyle&, const SVGComputedStyle&, const LayoutObject*, Node*, bool allow_visited_style) const override; bool IsInterpolable() const override { return true; } // Style builder functions void ApplyInitial(StyleResolverState& state) const override { state.Style()->SetFlexGrow(ComputedStyleInitialValues::InitialFlexGrow()); } void ApplyInherit(StyleResolverState& state) const override { state.Style()->SetFlexGrow(state.ParentStyle()->FlexGrow()); } void ApplyValue(StyleResolverState& state, const CSSValue& value) const override { state.Style()->SetFlexGrow(ToCSSPrimitiveValue(value).ConvertTo<float>()); } }; } // namespace CSSLonghand } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_LONGHAND_FLEX_GROW_H_
[ "aoeiuv020@gmail.com" ]
aoeiuv020@gmail.com
6914e26bc202a421781ded15a07d4929e885400b
b8b69b9721088fc60a523ada7650c7fb8864ff2a
/src/Graphics/Vulkan/AssetViews/ImageAsset.hpp
8215657d9e13c9c6d36baa3a38c55eed69bff7fa
[]
no_license
jvidziunas/Eldritch2
7a99ab852c93768b4caf1cefe7ba415b71987281
3491f2f380f5ae4dd155594b94fea28f791f3069
refs/heads/master
2021-01-10T09:37:08.120746
2018-04-11T00:22:20
2018-04-11T00:22:20
43,710,529
2
1
null
null
null
null
WINDOWS-1252
C++
false
false
1,617
hpp
/*==================================================================*\ ImageAsset.hpp ------------------------------------------------------------------ Purpose: ------------------------------------------------------------------ ©2010-2016 Eldritch Entertainment, LLC. \*==================================================================*/ #pragma once //==================================================================// // INCLUDES //==================================================================// #include <Graphics/CrunchImageSource.hpp> #include <Assets/Asset.hpp> //------------------------------------------------------------------// namespace Eldritch2 { namespace Graphics { namespace Vulkan { namespace AssetViews { class ImageAsset : public Assets::Asset, public CrunchImageSource { // - CONSTRUCTOR/DESTRUCTOR -------------------------- public: //! Constructs this @ref ImageAsset instance. /*! @param[in] path Null-terminated, UTF-8-encoded file system path to the asset this @ref ImageAsset describes. */ ImageAsset( const Utf8Char* const path ); //! Disable copy construction. ImageAsset( const ImageAsset& ) = delete; ~ImageAsset() override = default; // --------------------------------------------------- public: ErrorCode BindResources( const Builder& builder ) override; void FreeResources() override; // --------------------------------------------------- //! Disable copy assignment. ImageAsset& operator=( const ImageAsset& ) = delete; }; } // namespace AssetViews } // namespace Vulkan } // namespace Graphics } // namespace Eldritch2
[ "jvidziunas@sbcglobal.net" ]
jvidziunas@sbcglobal.net
cba316735700f3ca0378361b442e1a2388ac380f
3dae85df94e05bb1f3527bca0d7ad413352e49d0
/ml/nn/runtime/test/generated/models/pad_v2_1_float_relaxed.model.cpp
dad329b83b38cd8e98c266139c390b4ddfda3374
[ "Apache-2.0" ]
permissive
Wenzhao-Xiang/webml-wasm
e48f4cde4cb986eaf389edabe78aa32c2e267cb9
0019b062bce220096c248b1fced09b90129b19f9
refs/heads/master
2020-04-08T11:57:07.170110
2018-11-29T07:21:37
2018-11-29T07:21:37
159,327,152
0
0
null
null
null
null
UTF-8
C++
false
false
1,213
cpp
// clang-format off // Generated file (from: pad_v2_1_float_relaxed.mod.py). Do not edit void CreateModel(Model *model) { OperandType type0(Type::TENSOR_FLOAT32, {1, 2, 3, 1}); OperandType type1(Type::TENSOR_INT32, {4, 2}); OperandType type2(Type::FLOAT32, {}); OperandType type3(Type::TENSOR_FLOAT32, {1, 4, 7, 1}); // Phase 1, operands auto input0 = model->addOperand(&type0); auto paddings = model->addOperand(&type1); auto pad_value = model->addOperand(&type2); auto output0 = model->addOperand(&type3); // Phase 2, operations static int32_t paddings_init[] = {0, 0, 0, 2, 1, 3, 0, 0}; model->setOperandValue(paddings, paddings_init, sizeof(int32_t) * 8); static float pad_value_init[] = {9.3f}; model->setOperandValue(pad_value, pad_value_init, sizeof(float) * 1); model->addOperation(ANEURALNETWORKS_PAD_V2, {input0, paddings, pad_value}, {output0}); // Phase 3, inputs and outputs model->identifyInputsAndOutputs( {input0}, {output0}); // Phase 4: set relaxed execution model->relaxComputationFloat32toFloat16(true); assert(model->isValid()); } inline bool is_ignored(int i) { static std::set<int> ignore = {}; return ignore.find(i) != ignore.end(); }
[ "wenzhao.xiang@intel.com" ]
wenzhao.xiang@intel.com
be26662e2b2e7f433379657cc4e2b6af1922ebee
2859a7c8fb2a22471e22d1bbfd9ad34101c9593a
/project/src/CollisionEnvironment.cpp
56eb081863bacdb06b08ec209c6ebb52b7a40aef
[]
no_license
kobutri/cgintro_animation_project
bf06f095ad6a953e94b3fbe0fa6e7d56bd37f77d
f21e268ec96be856a337a9a76e87146c460746d2
refs/heads/master
2022-11-20T16:17:10.538864
2020-07-17T13:56:01
2020-07-17T13:56:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
619
cpp
#include "CollisionEnvironment.h" #include "Shader.h" CollisionEnvironmentObjectsBuffer::CollisionEnvironmentObjectsBuffer(CollisionEnvironmentObjects objects) : Buffer( objects.collisionObjects.data(), sizeof(CollisionObject) * objects.collisionObjects.size(), GL_STATIC_DRAW) {} void CollisionEnvironmentObjectsBuffer::bind(ComputeShader shader, GLuint position) { shader.use(); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, position, buffer); } void CollisionEnvironmentObjects::updateUniforms(ComputeShader shader) { shader.use(); shader.setUint("model_count", collisionObjects.size()); }
[ "ymi.yugy@gmx.de" ]
ymi.yugy@gmx.de
ec72a3ec68e426b3cc44eb9a01477cfddeac53bd
aa9887968b39c45f0cda27cf22152fc5e5b7d46d
/src/vendor/cget/cget/pkg/pqrs-org__cpp-osx-input_source_selector/install/include/pqrs/osx/input_source_selector/specifier.hpp
195fee9a7d47cfa03370e44eb7c4728761a1397a
[ "Unlicense" ]
permissive
paganholiday/key-remap
9edef7910dc8a791090d559997d42e94fca8b904
a9154a6b073a3396631f43ed11f6dc603c28ea7b
refs/heads/master
2021-07-06T05:11:50.653378
2020-01-11T14:21:58
2020-01-11T14:21:58
233,709,937
0
1
Unlicense
2021-04-13T18:21:39
2020-01-13T22:50:13
C++
UTF-8
C++
false
false
3,821
hpp
#pragma once // (C) Copyright Takayama Fumihiko 2019. // Distributed under the Boost Software License, Version 1.0. // (See http://www.boost.org/LICENSE_1_0.txt) #include <optional> #include <pqrs/hash.hpp> #include <pqrs/osx/input_source.hpp> #include <regex> #include <string> namespace pqrs { namespace osx { namespace input_source_selector { class specifier { public: const std::optional<std::string>& get_language_string(void) const { return language_string_; } specifier& set_language(const std::optional<std::string>& value) { language_string_ = value; if (language_string_) { language_regex_ = std::regex(*language_string_); } else { language_regex_ = std::nullopt; } return *this; } const std::optional<std::string>& get_input_source_id_string(void) const { return input_source_id_string_; } specifier& set_input_source_id(const std::optional<std::string>& value) { input_source_id_string_ = value; if (input_source_id_string_) { input_source_id_regex_ = std::regex(*input_source_id_string_); } else { input_source_id_regex_ = std::nullopt; } return *this; } const std::optional<std::string>& get_input_mode_id_string(void) const { return input_mode_id_string_; } specifier& set_input_mode_id(const std::optional<std::string>& value) { input_mode_id_string_ = value; if (input_mode_id_string_) { input_mode_id_regex_ = std::regex(*input_mode_id_string_); } else { input_mode_id_regex_ = std::nullopt; } return *this; } bool test(const input_source::properties& properties) const { if (language_regex_) { if (auto& v = properties.get_first_language()) { if (!regex_search(std::begin(*v), std::end(*v), *language_regex_)) { return false; } } else { return false; } } if (input_source_id_regex_) { if (auto& v = properties.get_input_source_id()) { if (!regex_search(std::begin(*v), std::end(*v), *input_source_id_regex_)) { return false; } } else { return false; } } if (input_mode_id_regex_) { if (auto& v = properties.get_input_mode_id()) { if (!regex_search(std::begin(*v), std::end(*v), *input_mode_id_regex_)) { return false; } } else { return false; } } return true; } bool operator==(const specifier& other) const { return language_string_ == other.language_string_ && input_source_id_string_ == other.input_source_id_string_ && input_mode_id_string_ == other.input_mode_id_string_; } bool operator!=(const specifier& other) const { return !(*this == other); } private: std::optional<std::string> language_string_; std::optional<std::string> input_source_id_string_; std::optional<std::string> input_mode_id_string_; std::optional<std::regex> language_regex_; std::optional<std::regex> input_source_id_regex_; std::optional<std::regex> input_mode_id_regex_; }; } // namespace input_source_selector } // namespace osx } // namespace pqrs namespace std { template <> struct hash<pqrs::osx::input_source_selector::specifier> final { std::size_t operator()(const pqrs::osx::input_source_selector::specifier& value) const { size_t h = 0; if (auto& s = value.get_language_string()) { pqrs::hash_combine(h, *s); } if (auto& s = value.get_input_source_id_string()) { pqrs::hash_combine(h, *s); } if (auto& s = value.get_input_mode_id_string()) { pqrs::hash_combine(h, *s); } return h; } }; } // namespace std
[ "tekezo@pqrs.org" ]
tekezo@pqrs.org
a1c61ec3091ae6747f4022bbf48368b244449a53
78dc9f82fc24a614b2ccdcfc9789f7d04454f05e
/android/hardware/aw/atw/atw1.0/client/PortalClientLocal.h
5481547a8fea5dc0e98da7acb4e74897d208b945
[]
no_license
dcboy/BPI-A83T-Android7
8af2a4e4f6856260f3c47417e03ba61fa2d7a4a0
518ce59fcab35adce0a2183ef5fca017d2c448d5
refs/heads/master
2023-06-27T21:45:44.939149
2019-05-23T03:48:14
2019-05-23T03:48:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,659
h
#pragma once #include "PortalClient.h" #include "IAtwService.h" #include "IAtwClient.h" #include "HeadTrackerThread.h" #include "HeadTracker.h" #include "AtwRenderFpsObserver.h" using namespace android; namespace allwinner { class PortalClientLocal : public PortalClient { public: PortalClientLocal(); virtual ~PortalClientLocal(); virtual int init(ANativeWindow** nativeSur); virtual int prepareFrame(uint64_t frameNumber, eye_t eye); virtual int swapToScreen(uint64_t frameNumber, const avrQuatf &orientation, uint64_t expectedDisplayTimeInNano = 0); virtual int doReprojection(int mode); virtual int setTracker(PTRFUN_HeadTracker cb, int run); protected: virtual int createAtwSurface(ANativeWindow** nativeSur, uint32_t width, uint32_t height, int format, int flags); status_t openService(); status_t enableReprojection(bool enable); private: sp<IAtwService> mService = 0; sp<IAtwClient> mClient = 0; ANativeWindow *mNativeWindow = NULL; int mViewportWidth = -1; int mViewportHeight = -1; int mDisplayWidth = -1; int mDisplayHeight = -1; sp<HeadTrackerThread> mHeadTrackerThread = 0; uint64_t mFrameNumber = 1; #if 0 EGLDisplay mDisplay = EGL_NO_DISPLAY; EGLSurface mSurface = EGL_NO_SURFACE; #endif AtwRenderFpsObserver mFpsObserver; bool mReprojectionEnabled = false; int32_t mDefaultRefreshRate = 60; const char* mDefaultRenderFps = "60"; const char* mReprojectionRenderFps = "30"; int mClientID; private: friend class PortalFactory; }; }; // namespace allwinner
[ "Justin" ]
Justin
6deca7eb7ac0f40b63def905b964add87fb8024d
7a7db30f6e59fb019289f3d2630b5997751c5f22
/testMM_threads.cpp
f3a85b07c02e71d4d3c69a62a9cab6358f5109a2
[]
no_license
darkac/CacheFrame_Simple
b231d6e53a40ab1c2841bd6c952332a73c19586a
5d791f7d51a7134815f49ffe38d61d126bb36d72
refs/heads/master
2021-01-23T14:57:47.914763
2013-04-24T13:01:25
2013-04-24T13:01:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,095
cpp
// Last modified: 2012-11-21 03:15:55 /** * @file: testMM.cpp * @author: tongjiancong(lingfenghx@gmail.com) * @date: 2012-08-28 18:23:34 * @brief: **/ /* Talk is cheap, show me the code. */ /* Good luck and have fun. */ #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <cassert> #include <sys/time.h> #include "hash.h" #include "function.h" #include "ListHandler.h" #include "MemoryDict.h" //#include "MemoryManager.h" //#include "CacheFrame.h" #include "lru.h" #include "qtca.h" #include "lfu.h" using namespace std; #define THREAD_NUM 1000 #define TERM_NUM 5000000 FILE *pIndex; MemoryDict dict; hashnode_t *hashTable[MAX_HASH]; CCacheFrame *CF; pthread_mutex_t ot_mutex = PTHREAD_MUTEX_INITIALIZER; void LoadDict() { string strDictDir = "/home/fan/Index/ori/"; string strDictName = "GOV2.Rand"; bool bRet = dict.Load(strDictDir, strDictName); if(!bRet) { cout << "Error in reading the dict" << endl; return ; } string file =strDictDir + "/" + strDictName + ".index"; pIndex = fopen(file.c_str(), "rb"); assert(pIndex != NULL); } void *run(void *arg) { unsigned int range = 1024; int tno = *(int *)arg; for (int i = 0; i < TERM_NUM / THREAD_NUM; ++i) { int termid = TERM_NUM / THREAD_NUM * tno + i; int docid = 1023; ListHandler *LH = new ListHandler(termid, dict.m_vecDict[termid]); if (LH->GetLength() >= range) { pthread_mutex_lock(&ot_mutex); cout << termid << "\t" << docid << "\t-\t" << LH->GetItem(docid) << "\t" << LH->GetLength() << endl; pthread_mutex_unlock(&ot_mutex); } delete LH; } for (int i = 0; i < TERM_NUM / THREAD_NUM; ++i) { int termid = TERM_NUM / THREAD_NUM * tno + i; ListHandler *LH = new ListHandler(termid, dict.m_vecDict[termid]); delete LH; } return (void *)0; } int main(int argc, char **argv) { init_hash(); LoadDict(); int sup = 100, wnd = 10; double conf = 0.3; if (argc == 4) { sup = atoi(argv[1]); wnd = atoi(argv[3]); conf = atof(argv[2]); } //CCacheFrame_QTCA *CF_QTCA = new CCacheFrame_QTCA(MEMORYSIZE, 8, sup, wnd, conf, &dict); //CF = CF_QTCA; //CCacheFrame_LFU *CF_LFU = new CCacheFrame_LFU(MEMORYSIZE); //CF = CF_LFU; CCacheFrame_LRU *CF_LRU = new CCacheFrame_LRU(MEMORYSIZE); CF = CF_LRU; pthread_t tid[THREAD_NUM]; int arg[THREAD_NUM]; for (int i = 0; i < THREAD_NUM; ++i) { arg[i] = i; pthread_create(&tid[i], NULL, run, &arg[i]); } for (int i = 0; i < THREAD_NUM; ++i) { pthread_join(tid[i], NULL); } int range = 1024; int docid = 1023; int listLength, offset; int *space = (int *)malloc(1024); for (int termid = 0; termid < TERM_NUM; ++termid) { listLength = dict.m_vecDict[termid].m_nFreq; offset = dict.m_vecDict[termid].m_nOffset; space = (int *)realloc(space, listLength * sizeof(int)); fseek(pIndex, offset, SEEK_SET); fread(space, sizeof(int), listLength, pIndex); if (listLength >= range) { cerr << termid << "\t" << docid << "\t-\t" << space[docid] << "\t" << listLength << endl; } } freeResource(space); delete CF; free_hash(); return 0; }
[ "lingfenghx@gmail.com" ]
lingfenghx@gmail.com
949046123bb92b7c7e89d0b2cb1a9842847988c6
e2c2d90fb9ea7a912497d23e95b8fcfc5184283f
/src/Parser.cxx
1ec73fc44f88deacb57baaf17eb5eda4912bf960
[]
no_license
Maciej-Poleski/kompilator
404f0dff13aa81c0918d5f11205eb6c5308e02ad
073aad48510e3a9fc641d940906e1a7f0875fe7f
refs/heads/master
2021-09-14T10:49:06.954127
2021-08-15T16:30:23
2021-08-15T16:30:23
96,228,470
0
0
null
null
null
null
UTF-8
C++
false
false
293
cxx
#include "Parser.hxx" #include "lexer.hxx" int Parser::parse(const std::string &f) { yyin = fopen(f.c_str(), "r"); yy::parser parser(*this); int res = parser.parse(); return res; } void yy::parser::error(const std::string &msg) { std::cerr << "ERROR: " << msg << '\n'; }
[ "d82ks8djf82msd83hf8sc02lqb5gh5@gmail.com" ]
d82ks8djf82msd83hf8sc02lqb5gh5@gmail.com
7175beb48ab58a6c63c00c8bfc15d2c117b868ae
b0c66358ae5c0386db5887e2609929e753c38d18
/arch/rychlostne/2019-rychlostne-vs-vyberko/onoriver.cpp
9843c5b8516426a2c030b1a43d2434eb1a46ee79
[]
no_license
michalsvagerka/competitive
e7683133ee5f108429135a3a19b3bbaa6732ea9f
07f084dff6c1ba6f151c93bf78405574456100e4
refs/heads/master
2021-06-07T14:54:35.516490
2020-07-07T08:17:56
2020-07-07T08:19:09
113,440,107
4
0
null
null
null
null
UTF-8
C++
false
false
1,427
cpp
#include "../l/lib.h" #include "../l/segtree.h" class onoriver { public: void solve(istream& cin, ostream& cout) { int N; cin >> N; ll D, W; cin >> W >> D; vector<ll> S(N), E(N), M(N); for (int i = 0; i < N; ++i) { cin >> M[i] >> S[i] >> E[i]; } vector<pair<ll, pii>> Ev; for (int i = 0; i < N; ++i) { Ev.push_back({S[i], {1, i}}); Ev.push_back({E[i], {-1, i}}); } sort(Ev.begin(),Ev.end()); vector<pair<ll,int>> ByM; for (int i = 0; i < N; ++i) ByM.emplace_back(M[i], i); ByM.emplace_back(W, N); sort(ByM.begin(),ByM.end()); vector<int> I(N); for (int i = 0; i < N; ++i) I[ByM[i].y] = i; AddMinTree<int> T; T.setup(N+1, 0); for (int i = 0; i < N; ++i) { if (ByM[i].x <= D) { T.put(i, 1); } } ll ans = 0, lastT = 0, lo = -1; for (auto &ev: Ev) { if (lastT != ev.x && T.get(0, N) > 0) { if (lo == -1) lo = lastT; ans += ev.x - lastT; } lastT = ev.x; int j = ev.y.y; int h = bsh(I[j], N, [&](int x) { return ByM[x].x <= M[j] + D; }); if (h != I[j]) { T.put(I[j]+1, h, ev.y.x); } } cout << lo << ' ' << ans << endl; } };
[ "michal.svagerka@dswiss.com" ]
michal.svagerka@dswiss.com
1540f2e517ad205064b11f9944354134ee7b561a
36f8c734bce7c42861b771e73a56fa2fc8f9996c
/include/hfsm2/detail/structure/root.inl
f9452d7122bf9e31c855f1044fc47331ef6ae4df
[ "MIT" ]
permissive
carlchan0514/HFSM2
412e2d7d65e899794b38cb03fe90c74468a9086f
f30ac971b7a6d36cc60c2b49f837df392d9f04ad
refs/heads/master
2020-08-01T04:51:22.736388
2019-08-16T20:58:20
2019-08-16T20:58:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,500
inl
namespace hfsm2 { namespace detail { //////////////////////////////////////////////////////////////////////////////// template <typename TG, typename TA> R_<TG, TA>::R_(Context& context, Random_& random HFSM_IF_LOGGER(, Logger* const logger)) : _context{context} , _random{random} HFSM_IF_LOGGER(, _logger{logger}) { _apex.deepRegister(_stateRegistry, Parent{}); HFSM_IF_STRUCTURE(getStateNames()); initialEnter(); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TG, typename TA> R_<TG, TA>::~R_() { PlanControl control{_context, _random, _stateRegistry, _planData, HFSM_LOGGER_OR(_logger, nullptr)}; _apex.deepExit(control); HFSM_IF_ASSERT(_planData.verifyPlans()); } //------------------------------------------------------------------------------ template <typename TG, typename TA> void R_<TG, TA>::update() { FullControl control(_context, _random, _stateRegistry, _planData, _requests, HFSM_LOGGER_OR(_logger, nullptr)); _apex.deepUpdate(control); HFSM_IF_ASSERT(_planData.verifyPlans()); if (_requests.count()) processTransitions(); _requests.clear(); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TG, typename TA> template <typename TEvent> void R_<TG, TA>::react(const TEvent& event) { FullControl control{_context, _random, _stateRegistry, _planData, _requests, HFSM_LOGGER_OR(_logger, nullptr)}; _apex.deepReact(control, event); HFSM_IF_ASSERT(_planData.verifyPlans()); if (_requests.count()) processTransitions(); _requests.clear(); } //------------------------------------------------------------------------------ template <typename TG, typename TA> void R_<TG, TA>::changeTo(const StateID stateId) { const Request request{Request::Type::CHANGE, stateId}; _requests << request; HFSM_LOG_TRANSITION(_context, INVALID_STATE_ID, Transition::CHANGE, stateId); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TG, typename TA> void R_<TG, TA>::changeTo(const StateID stateId, const Payload& payload) { const Request request{Request::Type::CHANGE, stateId, payload}; _requests << request; HFSM_LOG_TRANSITION(_context, INVALID_STATE_ID, Transition::CHANGE, stateId); } //------------------------------------------------------------------------------ template <typename TG, typename TA> void R_<TG, TA>::restart(const StateID stateId) { const Request request{Request::Type::RESTART, stateId}; _requests << request; HFSM_LOG_TRANSITION(_context, INVALID_STATE_ID, Transition::RESTART, stateId); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TG, typename TA> void R_<TG, TA>::restart(const StateID stateId, const Payload& payload) { const Request request{Request::Type::RESTART, stateId, payload}; _requests << request; HFSM_LOG_TRANSITION(_context, INVALID_STATE_ID, Transition::RESTART, stateId); } //------------------------------------------------------------------------------ template <typename TG, typename TA> void R_<TG, TA>::resume(const StateID stateId) { const Request request{Request::Type::RESUME, stateId}; _requests << request; HFSM_LOG_TRANSITION(_context, INVALID_STATE_ID, Transition::RESUME, stateId); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TG, typename TA> void R_<TG, TA>::resume(const StateID stateId, const Payload& payload) { const Request request{Request::Type::RESUME, stateId, payload}; _requests << request; HFSM_LOG_TRANSITION(_context, INVALID_STATE_ID, Transition::RESUME, stateId); } //------------------------------------------------------------------------------ template <typename TG, typename TA> void R_<TG, TA>::utilize(const StateID stateId) { const Request request{Request::Type::UTILIZE, stateId}; _requests << request; HFSM_LOG_TRANSITION(_context, INVALID_STATE_ID, Transition::UTILIZE, stateId); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TG, typename TA> void R_<TG, TA>::utilize(const StateID stateId, const Payload& payload) { const Request request{Request::Type::UTILIZE, stateId, payload}; _requests << request; HFSM_LOG_TRANSITION(_context, INVALID_STATE_ID, Transition::UTILIZE, stateId); } //------------------------------------------------------------------------------ template <typename TG, typename TA> void R_<TG, TA>::randomize(const StateID stateId) { const Request request{Request::Type::RANDOMIZE, stateId}; _requests << request; HFSM_LOG_TRANSITION(_context, INVALID_STATE_ID, Transition::RANDOMIZE, stateId); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TG, typename TA> void R_<TG, TA>::randomize(const StateID stateId, const Payload& payload) { const Request request{Request::Type::RANDOMIZE, stateId, payload}; _requests << request; HFSM_LOG_TRANSITION(_context, INVALID_STATE_ID, Transition::RANDOMIZE, stateId); } //------------------------------------------------------------------------------ template <typename TG, typename TA> void R_<TG, TA>::schedule(const StateID stateId) { const Request request{Request::Type::SCHEDULE, stateId}; _requests << request; HFSM_LOG_TRANSITION(_context, INVALID_STATE_ID, Transition::SCHEDULE, stateId); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TG, typename TA> void R_<TG, TA>::schedule(const StateID stateId, const Payload& payload) { const Request request{Request::Type::SCHEDULE, stateId, payload}; _requests << request; HFSM_LOG_TRANSITION(_context, INVALID_STATE_ID, Transition::SCHEDULE, stateId); } //------------------------------------------------------------------------------ template <typename TG, typename TA> void R_<TG, TA>::resetStateData(const StateID stateId) { HFSM_ASSERT(stateId < Payloads::CAPACITY); if (stateId < Payloads::CAPACITY) _payloadsSet.reset(stateId); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TG, typename TA> void R_<TG, TA>::setStateData(const StateID stateId, const Payload& payload) { HFSM_ASSERT(stateId < Payloads::CAPACITY); if (stateId < Payloads::CAPACITY) { _payloads[stateId] = payload; _payloadsSet.set(stateId); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TG, typename TA> bool R_<TG, TA>::isStateDataSet(const StateID stateId) const { HFSM_ASSERT(stateId < Payloads::CAPACITY); return stateId < Payloads::CAPACITY ? _payloadsSet.get(stateId) : false; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TG, typename TA> const typename R_<TG, TA>::Payload* R_<TG, TA>::getStateData(const StateID stateId) const { HFSM_ASSERT(stateId < Payloads::CAPACITY); return stateId < Payloads::CAPACITY && _payloadsSet.get(stateId) ? &_payloads[stateId] : nullptr; } //------------------------------------------------------------------------------ template <typename TG, typename TA> void R_<TG, TA>::initialEnter() { Control control{_context, _random, _stateRegistry, _planData, HFSM_LOGGER_OR(_logger, nullptr)}; AllForks undoRequested = _stateRegistry.requested; _apex.deepRequestChange(control); Requests lastRequests = _requests; _requests.clear(); if (cancelledByEntryGuards(lastRequests)) _stateRegistry.requested = undoRequested; for (LongIndex i = 0; i < SUBSTITUTION_LIMIT && _requests.count(); ++i) { undoRequested = _stateRegistry.requested; if (applyRequests(control)) { lastRequests = _requests; _requests.clear(); if (cancelledByEntryGuards(lastRequests)) _stateRegistry.requested = undoRequested; } _requests.clear(); } HFSM_ASSERT(_requests.count() == 0); { PlanControl planControl{_context, _random, _stateRegistry, _planData, HFSM_LOGGER_OR(_logger, nullptr)}; _apex.deepEnterRequested(planControl); _stateRegistry.clearRequests(); HFSM_IF_ASSERT(_planData.verifyPlans()); } HFSM_IF_STRUCTURE(udpateActivity()); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TG, typename TA> void R_<TG, TA>::processTransitions() { HFSM_ASSERT(_requests.count()); HFSM_IF_STRUCTURE(_lastTransitions.clear()); AllForks undoRequested; Requests lastRequests; Control control(_context, _random, _stateRegistry, _planData, HFSM_LOGGER_OR(_logger, nullptr)); for (LongIndex i = 0; i < SUBSTITUTION_LIMIT && _requests.count(); ++i) { undoRequested = _stateRegistry.requested; if (applyRequests(control)) { lastRequests = _requests; _requests.clear(); if (cancelledByGuards(lastRequests)) _stateRegistry.requested = undoRequested; } else _requests.clear(); } { PlanControl planControl{_context, _random, _stateRegistry, _planData, HFSM_LOGGER_OR(_logger, nullptr)}; _apex.deepChangeToRequested(planControl); _stateRegistry.clearRequests(); HFSM_IF_ASSERT(_planData.verifyPlans()); } HFSM_IF_STRUCTURE(udpateActivity()); } //------------------------------------------------------------------------------ template <typename TG, typename TA> bool R_<TG, TA>::applyRequests(Control& control) { bool changesMade = false; for (const Request& request : _requests) { HFSM_IF_STRUCTURE(_lastTransitions << TransitionInfo(request, Method::UPDATE)); switch (request.type) { case Request::CHANGE: case Request::RESTART: case Request::RESUME: case Request::UTILIZE: case Request::RANDOMIZE: if (_stateRegistry.requestImmediate(request)) _apex.deepForwardActive(control, request.type); else _apex.deepRequest (control, request.type); changesMade = true; break; case Request::SCHEDULE: _stateRegistry.requestScheduled(request.stateId); break; default: HFSM_BREAK(); } } return changesMade; } //------------------------------------------------------------------------------ template <typename TG, typename TA> bool R_<TG, TA>::cancelledByEntryGuards(const Requests& pendingRequests) { GuardControl guardControl{_context, _random, _stateRegistry, _planData, _requests, pendingRequests, HFSM_LOGGER_OR(_logger, nullptr)}; if (_apex.deepEntryGuard(guardControl)) { HFSM_IF_STRUCTURE(recordRequestsAs(Method::ENTRY_GUARD)); return true; } else return false; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TG, typename TA> bool R_<TG, TA>::cancelledByGuards(const Requests& pendingRequests) { GuardControl guardControl{_context, _random, _stateRegistry, _planData, _requests, pendingRequests, HFSM_LOGGER_OR(_logger, nullptr)}; if (_apex.deepForwardExitGuard(guardControl)) { HFSM_IF_STRUCTURE(recordRequestsAs(Method::EXIT_GUARD)); return true; } else if (_apex.deepForwardEntryGuard(guardControl)) { HFSM_IF_STRUCTURE(recordRequestsAs(Method::ENTRY_GUARD)); return true; } else return false; } //------------------------------------------------------------------------------ #ifdef HFSM_ENABLE_STRUCTURE_REPORT template <typename TG, typename TA> void R_<TG, TA>::getStateNames() { _stateInfos.clear(); _apex.deepGetNames((LongIndex) -1, StructureStateInfo::COMPOSITE, 0, _stateInfos); LongIndex margin = (LongIndex) -1; for (LongIndex s = 0; s < _stateInfos.count(); ++s) { const auto& state = _stateInfos[s]; auto& prefix = _prefixes[s]; if (margin > state.depth && state.name[0] != '\0') margin = state.depth; if (state.depth == 0) prefix[0] = L'\0'; else { const LongIndex mark = state.depth * 2 - 1; prefix[mark + 0] = state.region == StructureStateInfo::COMPOSITE ? L'└' : L'╙'; prefix[mark + 1] = L' '; prefix[mark + 2] = L'\0'; for (auto d = mark; d > 0; --d) prefix[d - 1] = L' '; for (auto r = s; r > state.parent; --r) { auto& prefixAbove = _prefixes[r - 1]; switch (prefixAbove[mark]) { case L' ': prefixAbove[mark] = state.region == StructureStateInfo::COMPOSITE ? L'│' : L'║'; break; case L'└': prefixAbove[mark] = L'├'; break; case L'╙': prefixAbove[mark] = L'╟'; break; } } } } if (margin > 0) margin -= 1; _structure.clear(); for (LongIndex s = 0; s < _stateInfos.count(); ++s) { const auto& state = _stateInfos[s]; auto& prefix = _prefixes[s]; const LongIndex space = state.depth * 2; if (state.name[0] != L'\0') { _structure << StructureEntry { false, &prefix[margin * 2], state.name }; _activityHistory << (char) 0; } else if (s + 1 < _stateInfos.count()) { auto& nextPrefix = _prefixes[s + 1]; if (s > 0) for (LongIndex c = 0; c <= space; ++c) nextPrefix[c] = prefix[c]; const LongIndex mark = space + 1; switch (nextPrefix[mark]) { case L'├': nextPrefix[mark] = state.depth == margin ? L'┌' : L'┬'; break; case L'╟': nextPrefix[mark] = state.depth == margin ? L'╓' : L'╥'; break; } } } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TG, typename TA> void R_<TG, TA>::udpateActivity() { for (LongIndex s = 0, i = 0; s < _stateInfos.count(); ++s) if (_stateInfos[s].name[0] != L'\0') { _structure[i].isActive = isActive(s); auto& activity = _activityHistory[i]; if (_structure[i].isActive) { if (activity < 0) activity = +1; else activity = activity < INT8_MAX ? activity + 1 : activity; } else { if (activity > 0) activity = -1; else activity = activity > INT8_MIN ? activity - 1 : activity; } ++i; } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TG, typename TA> void R_<TG, TA>::recordRequestsAs(const Method method) { for (const auto& request : _requests) _lastTransitions << TransitionInfo(request, method); } #endif //////////////////////////////////////////////////////////////////////////////// } }
[ "andrew-gresyk@users.noreply.github.com" ]
andrew-gresyk@users.noreply.github.com
9c62060506d273dfaa011c4c341e4fb87b99b608
2a7b6bcc05a71a65caf48aa05de5d590811d4c81
/src/dex/hashlib/algorithms/algorithm.CRC-16_BUYPASS.c.inl
61a5f8d61ea838360f5b8d264370f276cdaa08ff
[ "Zlib" ]
permissive
GrieferAtWork/deemon
339281627990604fd0acfc534b8fb7751d84894e
3f9cd7ae815b8b42bd931d9d3ef6adf5656ca074
refs/heads/master
2023-08-31T09:33:57.382088
2023-08-19T15:14:13
2023-08-19T15:14:13
143,714,050
10
2
null
null
null
null
UTF-8
C++
false
false
4,644
inl
{ UINT16_C(0x0000), UINT16_C(0x8005), UINT16_C(0x800f), UINT16_C(0x000a), UINT16_C(0x801b), UINT16_C(0x001e), UINT16_C(0x0014), UINT16_C(0x8011), UINT16_C(0x8033), UINT16_C(0x0036), UINT16_C(0x003c), UINT16_C(0x8039), UINT16_C(0x0028), UINT16_C(0x802d), UINT16_C(0x8027), UINT16_C(0x0022), UINT16_C(0x8063), UINT16_C(0x0066), UINT16_C(0x006c), UINT16_C(0x8069), UINT16_C(0x0078), UINT16_C(0x807d), UINT16_C(0x8077), UINT16_C(0x0072), UINT16_C(0x0050), UINT16_C(0x8055), UINT16_C(0x805f), UINT16_C(0x005a), UINT16_C(0x804b), UINT16_C(0x004e), UINT16_C(0x0044), UINT16_C(0x8041), UINT16_C(0x80c3), UINT16_C(0x00c6), UINT16_C(0x00cc), UINT16_C(0x80c9), UINT16_C(0x00d8), UINT16_C(0x80dd), UINT16_C(0x80d7), UINT16_C(0x00d2), UINT16_C(0x00f0), UINT16_C(0x80f5), UINT16_C(0x80ff), UINT16_C(0x00fa), UINT16_C(0x80eb), UINT16_C(0x00ee), UINT16_C(0x00e4), UINT16_C(0x80e1), UINT16_C(0x00a0), UINT16_C(0x80a5), UINT16_C(0x80af), UINT16_C(0x00aa), UINT16_C(0x80bb), UINT16_C(0x00be), UINT16_C(0x00b4), UINT16_C(0x80b1), UINT16_C(0x8093), UINT16_C(0x0096), UINT16_C(0x009c), UINT16_C(0x8099), UINT16_C(0x0088), UINT16_C(0x808d), UINT16_C(0x8087), UINT16_C(0x0082), UINT16_C(0x8183), UINT16_C(0x0186), UINT16_C(0x018c), UINT16_C(0x8189), UINT16_C(0x0198), UINT16_C(0x819d), UINT16_C(0x8197), UINT16_C(0x0192), UINT16_C(0x01b0), UINT16_C(0x81b5), UINT16_C(0x81bf), UINT16_C(0x01ba), UINT16_C(0x81ab), UINT16_C(0x01ae), UINT16_C(0x01a4), UINT16_C(0x81a1), UINT16_C(0x01e0), UINT16_C(0x81e5), UINT16_C(0x81ef), UINT16_C(0x01ea), UINT16_C(0x81fb), UINT16_C(0x01fe), UINT16_C(0x01f4), UINT16_C(0x81f1), UINT16_C(0x81d3), UINT16_C(0x01d6), UINT16_C(0x01dc), UINT16_C(0x81d9), UINT16_C(0x01c8), UINT16_C(0x81cd), UINT16_C(0x81c7), UINT16_C(0x01c2), UINT16_C(0x0140), UINT16_C(0x8145), UINT16_C(0x814f), UINT16_C(0x014a), UINT16_C(0x815b), UINT16_C(0x015e), UINT16_C(0x0154), UINT16_C(0x8151), UINT16_C(0x8173), UINT16_C(0x0176), UINT16_C(0x017c), UINT16_C(0x8179), UINT16_C(0x0168), UINT16_C(0x816d), UINT16_C(0x8167), UINT16_C(0x0162), UINT16_C(0x8123), UINT16_C(0x0126), UINT16_C(0x012c), UINT16_C(0x8129), UINT16_C(0x0138), UINT16_C(0x813d), UINT16_C(0x8137), UINT16_C(0x0132), UINT16_C(0x0110), UINT16_C(0x8115), UINT16_C(0x811f), UINT16_C(0x011a), UINT16_C(0x810b), UINT16_C(0x010e), UINT16_C(0x0104), UINT16_C(0x8101), UINT16_C(0x8303), UINT16_C(0x0306), UINT16_C(0x030c), UINT16_C(0x8309), UINT16_C(0x0318), UINT16_C(0x831d), UINT16_C(0x8317), UINT16_C(0x0312), UINT16_C(0x0330), UINT16_C(0x8335), UINT16_C(0x833f), UINT16_C(0x033a), UINT16_C(0x832b), UINT16_C(0x032e), UINT16_C(0x0324), UINT16_C(0x8321), UINT16_C(0x0360), UINT16_C(0x8365), UINT16_C(0x836f), UINT16_C(0x036a), UINT16_C(0x837b), UINT16_C(0x037e), UINT16_C(0x0374), UINT16_C(0x8371), UINT16_C(0x8353), UINT16_C(0x0356), UINT16_C(0x035c), UINT16_C(0x8359), UINT16_C(0x0348), UINT16_C(0x834d), UINT16_C(0x8347), UINT16_C(0x0342), UINT16_C(0x03c0), UINT16_C(0x83c5), UINT16_C(0x83cf), UINT16_C(0x03ca), UINT16_C(0x83db), UINT16_C(0x03de), UINT16_C(0x03d4), UINT16_C(0x83d1), UINT16_C(0x83f3), UINT16_C(0x03f6), UINT16_C(0x03fc), UINT16_C(0x83f9), UINT16_C(0x03e8), UINT16_C(0x83ed), UINT16_C(0x83e7), UINT16_C(0x03e2), UINT16_C(0x83a3), UINT16_C(0x03a6), UINT16_C(0x03ac), UINT16_C(0x83a9), UINT16_C(0x03b8), UINT16_C(0x83bd), UINT16_C(0x83b7), UINT16_C(0x03b2), UINT16_C(0x0390), UINT16_C(0x8395), UINT16_C(0x839f), UINT16_C(0x039a), UINT16_C(0x838b), UINT16_C(0x038e), UINT16_C(0x0384), UINT16_C(0x8381), UINT16_C(0x0280), UINT16_C(0x8285), UINT16_C(0x828f), UINT16_C(0x028a), UINT16_C(0x829b), UINT16_C(0x029e), UINT16_C(0x0294), UINT16_C(0x8291), UINT16_C(0x82b3), UINT16_C(0x02b6), UINT16_C(0x02bc), UINT16_C(0x82b9), UINT16_C(0x02a8), UINT16_C(0x82ad), UINT16_C(0x82a7), UINT16_C(0x02a2), UINT16_C(0x82e3), UINT16_C(0x02e6), UINT16_C(0x02ec), UINT16_C(0x82e9), UINT16_C(0x02f8), UINT16_C(0x82fd), UINT16_C(0x82f7), UINT16_C(0x02f2), UINT16_C(0x02d0), UINT16_C(0x82d5), UINT16_C(0x82df), UINT16_C(0x02da), UINT16_C(0x82cb), UINT16_C(0x02ce), UINT16_C(0x02c4), UINT16_C(0x82c1), UINT16_C(0x8243), UINT16_C(0x0246), UINT16_C(0x024c), UINT16_C(0x8249), UINT16_C(0x0258), UINT16_C(0x825d), UINT16_C(0x8257), UINT16_C(0x0252), UINT16_C(0x0270), UINT16_C(0x8275), UINT16_C(0x827f), UINT16_C(0x027a), UINT16_C(0x826b), UINT16_C(0x026e), UINT16_C(0x0264), UINT16_C(0x8261), UINT16_C(0x0220), UINT16_C(0x8225), UINT16_C(0x822f), UINT16_C(0x022a), UINT16_C(0x823b), UINT16_C(0x023e), UINT16_C(0x0234), UINT16_C(0x8231), UINT16_C(0x8213), UINT16_C(0x0216), UINT16_C(0x021c), UINT16_C(0x8219), UINT16_C(0x0208), UINT16_C(0x820d), UINT16_C(0x8207), UINT16_C(0x0202), }
[ "GrieferAtWork@users.noreply.github.com" ]
GrieferAtWork@users.noreply.github.com
bf06fb2fe5b300f0aceafbd5bb53f85847c94d16
4fab2ca0f9c32c394dc0c3dcd3a4e72884c83310
/src/leveldb/doc/bench/db_bench_tree_db.cc
dea40117537d04ff92761eb539a44912dbd8be2e
[ "MIT" ]
permissive
WiseCoinDev1/pro
169ae72fda68b219f86d8c0f0c8043f7def0f208
9f5d268c32124051baf811d05d5837e7eed04d9e
refs/heads/master
2020-03-07T08:30:57.491696
2018-03-30T08:30:54
2018-03-30T08:30:54
127,380,515
0
0
null
null
null
null
UTF-8
C++
false
false
15,946
cc
// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LILMENSE file. See the AUTHORS file for names of contributors. #include <stdio.h> #include <stdlib.h> #include <kcpolydb.h> #include "util/histogram.h" #include "util/random.h" #include "util/testutil.h" // Comma-separated list of operations to run in the specified order // Actual benchmarks: // // fillseq -- write N values in sequential key order in async mode // fillrandom -- write N values in random key order in async mode // overwrite -- overwrite N values in random key order in async mode // fillseqsync -- write N/100 values in sequential key order in sync mode // fillrandsync -- write N/100 values in random key order in sync mode // fillrand100K -- write N/1000 100K values in random order in async mode // fillseq100K -- write N/1000 100K values in seq order in async mode // readseq -- read N times sequentially // readseq100K -- read N/1000 100K values in sequential order in async mode // readrand100K -- read N/1000 100K values in sequential order in async mode // readrandom -- read N times in random order static const char* FLAGS_benchmarks = "fillseq," "fillseqsync," "fillrandsync," "fillrandom," "overwrite," "readrandom," "readseq," "fillrand100K," "fillseq100K," "readseq100K," "readrand100K," ; // Number of key/values to place in database static int FLAGS_num = 1000000; // Number of read operations to do. If negative, do FLAGS_num reads. static int FLAGS_reads = -1; // Size of each value static int FLAGS_value_size = 100; // Arrange to generate values that shrink to this fraction of // their original size after compression static double FLAGS_compression_ratio = 0.5; // Print histogram of operation timings static bool FLAGS_histogram = false; // Cache size. Default 4 MB static int FLAGS_cache_size = 4194304; // Page size. Default 1 KB static int FLAGS_page_size = 1024; // If true, do not destroy the existing database. If you set this // flag and also specify a benchmark that wants a fresh database, that // benchmark will fail. static bool FLAGS_use_existing_db = false; // Compression flag. If true, compression is on. If false, compression // is off. static bool FLAGS_compression = true; // Use the db with the following name. static const char* FLAGS_db = NULL; inline static void DBSynchronize(kyotocabinet::TreeDB* db_) { // Synchronize will flush writes to disk if (!db_->synchronize()) { fprintf(stderr, "synchronize error: %s\n", db_->error().name()); } } namespace leveldb { // Helper for quickly generating random data. namespace { class RandomGenerator { private: std::string data_; int pos_; public: RandomGenerator() { // We use a limited amount of data over and over again and ensure // that it is larger than the compression window (32KB), and also // large enough to serve all typical value sizes we want to write. Random rnd(301); std::string piece; while (data_.size() < 1048576) { // Add a short fragment that is as compressible as specified // by FLAGS_compression_ratio. test::CompressibleString(&rnd, FLAGS_compression_ratio, 100, &piece); data_.append(piece); } pos_ = 0; } Slice Generate(int len) { if (pos_ + len > data_.size()) { pos_ = 0; assert(len < data_.size()); } pos_ += len; return Slice(data_.data() + pos_ - len, len); } }; static Slice TrimSpace(Slice s) { int start = 0; while (start < s.size() && isspace(s[start])) { start++; } int limit = s.size(); while (limit > start && isspace(s[limit-1])) { limit--; } return Slice(s.data() + start, limit - start); } } // namespace class Benchmark { private: kyotocabinet::TreeDB* db_; int db_num_; int num_; int reads_; double start_; double last_op_finish_; int64_t bytes_; std::string message_; Histogram hist_; RandomGenerator gen_; Random rand_; kyotocabinet::LZOCompressor<kyotocabinet::LZO::RAW> comp_; // State kept for progress messages int done_; int next_report_; // When to report next void PrintHeader() { const int kKeySize = 16; PrintEnvironment(); fprintf(stdout, "Keys: %d bytes each\n", kKeySize); fprintf(stdout, "Values: %d bytes each (%d bytes after compression)\n", FLAGS_value_size, static_cast<int>(FLAGS_value_size * FLAGS_compression_ratio + 0.5)); fprintf(stdout, "Entries: %d\n", num_); fprintf(stdout, "RawSize: %.1f MB (estimated)\n", ((static_cast<int64_t>(kKeySize + FLAGS_value_size) * num_) / 1048576.0)); fprintf(stdout, "FileSize: %.1f MB (estimated)\n", (((kKeySize + FLAGS_value_size * FLAGS_compression_ratio) * num_) / 1048576.0)); PrintWarnings(); fprintf(stdout, "------------------------------------------------\n"); } void PrintWarnings() { #if defined(__GNUC__) && !defined(__OPTIMIZE__) fprintf(stdout, "WARNING: Optimization is disabled: benchmarks unnecessarily slow\n" ); #endif #ifndef NDEBUG fprintf(stdout, "WARNING: Assertions are enabled; benchmarks unnecessarily slow\n"); #endif } void PrintEnvironment() { fprintf(stderr, "Kyoto Cabinet: version %s, lib ver %d, lib rev %d\n", kyotocabinet::VERSION, kyotocabinet::LIBVER, kyotocabinet::LIBREV); #if defined(__linux) time_t now = time(NULL); fprintf(stderr, "Date: %s", ctime(&now)); // ctime() adds newline FILE* cpuinfo = fopen("/proc/cpuinfo", "r"); if (cpuinfo != NULL) { char line[1000]; int num_cpus = 0; std::string cpu_type; std::string cache_size; while (fgets(line, sizeof(line), cpuinfo) != NULL) { const char* sep = strchr(line, ':'); if (sep == NULL) { continue; } Slice key = TrimSpace(Slice(line, sep - 1 - line)); Slice val = TrimSpace(Slice(sep + 1)); if (key == "model name") { ++num_cpus; cpu_type = val.ToString(); } else if (key == "cache size") { cache_size = val.ToString(); } } fclose(cpuinfo); fprintf(stderr, "CPU: %d * %s\n", num_cpus, cpu_type.c_str()); fprintf(stderr, "CPUCache: %s\n", cache_size.c_str()); } #endif } void Start() { start_ = Env::Default()->NowMicros() * 1e-6; bytes_ = 0; message_.clear(); last_op_finish_ = start_; hist_.Clear(); done_ = 0; next_report_ = 100; } void FinishedSingleOp() { if (FLAGS_histogram) { double now = Env::Default()->NowMicros() * 1e-6; double micros = (now - last_op_finish_) * 1e6; hist_.Add(micros); if (micros > 20000) { fprintf(stderr, "long op: %.1f micros%30s\r", micros, ""); fflush(stderr); } last_op_finish_ = now; } done_++; if (done_ >= next_report_) { if (next_report_ < 1000) next_report_ += 100; else if (next_report_ < 5000) next_report_ += 500; else if (next_report_ < 10000) next_report_ += 1000; else if (next_report_ < 50000) next_report_ += 5000; else if (next_report_ < 100000) next_report_ += 10000; else if (next_report_ < 500000) next_report_ += 50000; else next_report_ += 100000; fprintf(stderr, "... finished %d ops%30s\r", done_, ""); fflush(stderr); } } void Stop(const Slice& name) { double finish = Env::Default()->NowMicros() * 1e-6; // Pretend at least one op was done in case we are running a benchmark // that does not call FinishedSingleOp(). if (done_ < 1) done_ = 1; if (bytes_ > 0) { char rate[100]; snprintf(rate, sizeof(rate), "%6.1f MB/s", (bytes_ / 1048576.0) / (finish - start_)); if (!message_.empty()) { message_ = std::string(rate) + " " + message_; } else { message_ = rate; } } fprintf(stdout, "%-12s : %11.3f micros/op;%s%s\n", name.ToString().c_str(), (finish - start_) * 1e6 / done_, (message_.empty() ? "" : " "), message_.c_str()); if (FLAGS_histogram) { fprintf(stdout, "Microseconds per op:\n%s\n", hist_.ToString().c_str()); } fflush(stdout); } public: enum Order { SEQUENTIAL, RANDOM }; enum DBState { FRESH, EXISTING }; Benchmark() : db_(NULL), num_(FLAGS_num), reads_(FLAGS_reads < 0 ? FLAGS_num : FLAGS_reads), bytes_(0), rand_(301) { std::vector<std::string> files; std::string test_dir; Env::Default()->GetTestDirectory(&test_dir); Env::Default()->GetChildren(test_dir.c_str(), &files); if (!FLAGS_use_existing_db) { for (int i = 0; i < files.size(); i++) { if (Slice(files[i]).starts_with("dbbench_polyDB")) { std::string file_name(test_dir); file_name += "/"; file_name += files[i]; Env::Default()->DeleteFile(file_name.c_str()); } } } } ~Benchmark() { if (!db_->close()) { fprintf(stderr, "close error: %s\n", db_->error().name()); } } void Run() { PrintHeader(); Open(false); const char* benchmarks = FLAGS_benchmarks; while (benchmarks != NULL) { const char* sep = strchr(benchmarks, ','); Slice name; if (sep == NULL) { name = benchmarks; benchmarks = NULL; } else { name = Slice(benchmarks, sep - benchmarks); benchmarks = sep + 1; } Start(); bool known = true; bool write_sync = false; if (name == Slice("fillseq")) { Write(write_sync, SEQUENTIAL, FRESH, num_, FLAGS_value_size, 1); } else if (name == Slice("fillrandom")) { Write(write_sync, RANDOM, FRESH, num_, FLAGS_value_size, 1); DBSynchronize(db_); } else if (name == Slice("overwrite")) { Write(write_sync, RANDOM, EXISTING, num_, FLAGS_value_size, 1); DBSynchronize(db_); } else if (name == Slice("fillrandsync")) { write_sync = true; Write(write_sync, RANDOM, FRESH, num_ / 100, FLAGS_value_size, 1); DBSynchronize(db_); } else if (name == Slice("fillseqsync")) { write_sync = true; Write(write_sync, SEQUENTIAL, FRESH, num_ / 100, FLAGS_value_size, 1); DBSynchronize(db_); } else if (name == Slice("fillrand100K")) { Write(write_sync, RANDOM, FRESH, num_ / 1000, 100 * 1000, 1); DBSynchronize(db_); } else if (name == Slice("fillseq100K")) { Write(write_sync, SEQUENTIAL, FRESH, num_ / 1000, 100 * 1000, 1); DBSynchronize(db_); } else if (name == Slice("readseq")) { ReadSequential(); } else if (name == Slice("readrandom")) { ReadRandom(); } else if (name == Slice("readrand100K")) { int n = reads_; reads_ /= 1000; ReadRandom(); reads_ = n; } else if (name == Slice("readseq100K")) { int n = reads_; reads_ /= 1000; ReadSequential(); reads_ = n; } else { known = false; if (name != Slice()) { // No error message for empty name fprintf(stderr, "unknown benchmark '%s'\n", name.ToString().c_str()); } } if (known) { Stop(name); } } } private: void Open(bool sync) { assert(db_ == NULL); // Initialize db_ db_ = new kyotocabinet::TreeDB(); char file_name[100]; db_num_++; std::string test_dir; Env::Default()->GetTestDirectory(&test_dir); snprintf(file_name, sizeof(file_name), "%s/dbbench_polyDB-%d.kct", test_dir.c_str(), db_num_); // Create tuning options and open the database int open_options = kyotocabinet::PolyDB::OWRITER | kyotocabinet::PolyDB::OCREATE; int tune_options = kyotocabinet::TreeDB::TSMALL | kyotocabinet::TreeDB::TLINEAR; if (FLAGS_compression) { tune_options |= kyotocabinet::TreeDB::TCOMPRESS; db_->tune_compressor(&comp_); } db_->tune_options(tune_options); db_->tune_page_cache(FLAGS_cache_size); db_->tune_page(FLAGS_page_size); db_->tune_map(256LL<<20); if (sync) { open_options |= kyotocabinet::PolyDB::OAUTOSYNC; } if (!db_->open(file_name, open_options)) { fprintf(stderr, "open error: %s\n", db_->error().name()); } } void Write(bool sync, Order order, DBState state, int num_entries, int value_size, int entries_per_batch) { // Create new database if state == FRESH if (state == FRESH) { if (FLAGS_use_existing_db) { message_ = "skipping (--use_existing_db is true)"; return; } delete db_; db_ = NULL; Open(sync); Start(); // Do not count time taken to destroy/open } if (num_entries != num_) { char msg[100]; snprintf(msg, sizeof(msg), "(%d ops)", num_entries); message_ = msg; } // Write to database for (int i = 0; i < num_entries; i++) { const int k = (order == SEQUENTIAL) ? i : (rand_.Next() % num_entries); char key[100]; snprintf(key, sizeof(key), "%016d", k); bytes_ += value_size + strlen(key); std::string cpp_key = key; if (!db_->set(cpp_key, gen_.Generate(value_size).ToString())) { fprintf(stderr, "set error: %s\n", db_->error().name()); } FinishedSingleOp(); } } void ReadSequential() { kyotocabinet::DB::Cursor* cur = db_->cursor(); cur->jump(); std::string ckey, cvalue; while (cur->get(&ckey, &cvalue, true)) { bytes_ += ckey.size() + cvalue.size(); FinishedSingleOp(); } delete cur; } void ReadRandom() { std::string value; for (int i = 0; i < reads_; i++) { char key[100]; const int k = rand_.Next() % reads_; snprintf(key, sizeof(key), "%016d", k); db_->get(key, &value); FinishedSingleOp(); } } }; } // namespace leveldb int main(int argc, char** argv) { std::string default_db_path; for (int i = 1; i < argc; i++) { double d; int n; char junk; if (leveldb::Slice(argv[i]).starts_with("--benchmarks=")) { FLAGS_benchmarks = argv[i] + strlen("--benchmarks="); } else if (sscanf(argv[i], "--compression_ratio=%lf%c", &d, &junk) == 1) { FLAGS_compression_ratio = d; } else if (sscanf(argv[i], "--histogram=%d%c", &n, &junk) == 1 && (n == 0 || n == 1)) { FLAGS_histogram = n; } else if (sscanf(argv[i], "--num=%d%c", &n, &junk) == 1) { FLAGS_num = n; } else if (sscanf(argv[i], "--reads=%d%c", &n, &junk) == 1) { FLAGS_reads = n; } else if (sscanf(argv[i], "--value_size=%d%c", &n, &junk) == 1) { FLAGS_value_size = n; } else if (sscanf(argv[i], "--cache_size=%d%c", &n, &junk) == 1) { FLAGS_cache_size = n; } else if (sscanf(argv[i], "--page_size=%d%c", &n, &junk) == 1) { FLAGS_page_size = n; } else if (sscanf(argv[i], "--compression=%d%c", &n, &junk) == 1 && (n == 0 || n == 1)) { FLAGS_compression = (n == 1) ? true : false; } else if (strncmp(argv[i], "--db=", 5) == 0) { FLAGS_db = argv[i] + 5; } else { fprintf(stderr, "Invalid flag '%s'\n", argv[i]); exit(1); } } // Choose a location for the test database if none given with --db=<path> if (FLAGS_db == NULL) { leveldb::Env::Default()->GetTestDirectory(&default_db_path); default_db_path += "/dbbench"; FLAGS_db = default_db_path.c_str(); } leveldb::Benchmark benchmark; benchmark.Run(); return 0; }
[ "4mindsmine@gmail.com" ]
4mindsmine@gmail.com
3534711a9d8766256253da20d83fd986e2bfe218
b1ec5452ac46b20b0adc1117ebafae7ee7dc9782
/work/cpp/RandomPaint/ParametricCurve.cpp
4344b23dbe28fc50bf173d2ea5b73b302a1e0309
[]
no_license
MishaLivshitz/experis
bce65d9d7a457fc48492105d51f4a9e51ef3ae88
038fe5e5a318ed11c595bce6654ff11ac7fbb355
refs/heads/master
2020-07-31T13:33:47.318537
2019-09-24T14:13:52
2019-09-24T14:13:52
210,619,343
0
0
null
null
null
null
UTF-8
C++
false
false
363
cpp
#include "ParametricCurve.h" ParametricCurve::ParametricCurve(Color const& _c, Point const& _begin, Point const& _end ,Point const& _control) : Line(_c,_begin,_end) ,m_controlP(_control) { } void ParametricCurve::Move(Point const& _diraction) { Line::Move(_diraction); m_controlP += _diraction; } double const ParametricCurve::m_advancement = 0.001;
[ "michaellivshitz91@gmail.com" ]
michaellivshitz91@gmail.com
7dd2eb8d6ed11f2450f91bb79b9d17e6ef034847
bc29e081d40bd65f60af7bd6c89a02fdb500db45
/drivers/STM32_DFU/tools/DfuSe v3.0.5/Sources/STDFUPRT/DetachThread.CPP
b83e7ea2cf627f7208099cbe1a307b9d93337fee
[ "CC-BY-3.0", "Apache-2.0" ]
permissive
myriadrf/LMS8001-Companion
3907770a5aeb51b0c473bb1266e5d3a8050c73e9
4238ff999e62607d27aee17d513e53dc4e3a1a40
refs/heads/master
2021-05-15T13:56:47.820118
2019-09-10T07:56:46
2019-09-10T07:56:46
107,255,219
24
20
null
null
null
null
UTF-8
C++
false
false
11,992
cpp
/******************** (C) COPYRIGHT 2015 STMicroelectronics ******************** * Company : STMicroelectronics * Author : MCD Application Team * Description : STMicroelectronics Device Firmware Upgrade Extension Demo * Version : V3.0.5 * Date : 01-September-2015 ******************************************************************************** * THE PRESENT SOFTWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH SOFTWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. ******************************************************************************** * FOR MORE INFORMATION PLEASE CAREFULLY READ THE LICENSE AGREEMENT FILE * "MCD-ST Liberty SW License Agreement V2.pdf" *******************************************************************************/ #include "stdafx.h" #include "STThread.h" #include "../STDFU/STDFU.h" #include "STDFUPRTINC.h" #include "DFUThread.h" #include "DetachThread.h" typedef DWORD (__stdcall *pCMP_WaitNoPendingInstallEvents)(DWORD); pCMP_WaitNoPendingInstallEvents CMP_WaitNoPendingInstallEvents; LRESULT CALLBACK WndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { static CDetachThread *pThread; if (Msg==WM_CREATE) { LPCREATESTRUCT cs=(LPCREATESTRUCT)lParam; pThread=(CDetachThread *)cs->lpCreateParams; return DefWindowProc(hWnd, Msg, wParam, lParam); } else if (Msg==WM_DEVICECHANGE) { if (wParam==DBT_DEVICEARRIVAL) { _DEV_BROADCAST_HEADER *pHeader=(_DEV_BROADCAST_HEADER *)lParam; if (pHeader->dbcd_devicetype==DBT_DEVTYP_DEVICEINTERFACE) { PDEV_BROADCAST_DEVICEINTERFACE pData=(PDEV_BROADCAST_DEVICEINTERFACE)pHeader; DFUThreadContext Context; pThread->GetCurrentContext(&Context); if (Context.CurrentRequest==STDFU_RQ_AWAITINGPNPPLUGEVENT) { Context.CurrentRequest=STDFU_RQ_IDENTIFYINGDEVICE; lstrcpy(Context.szDevLink, pData->dbcc_name); pThread->SetCurrentContext(&Context); } } } else if (wParam==DBT_DEVICEREMOVECOMPLETE) { _DEV_BROADCAST_HEADER *pHeader=(_DEV_BROADCAST_HEADER *)lParam; if (pHeader->dbcd_devicetype==DBT_DEVTYP_DEVICEINTERFACE) { PDEV_BROADCAST_DEVICEINTERFACE pData=(PDEV_BROADCAST_DEVICEINTERFACE)pHeader; DFUThreadContext Context; pThread->GetCurrentContext(&Context); if ( (strcmpi(Context.szDevLink, pData->dbcc_name)==0) && (Context.CurrentRequest==STDFU_RQ_AWAITINGPNPUNPLUGEVENT) ) { if (Context.Operation==OPERATION_RETURN) { Context.CurrentRequest=STDFU_RQ_IDENTIFYINGDEVICE; lstrcpy(Context.szDevLink, "Tolerant"); pThread->SetCurrentContext(&Context); } else { Context.CurrentRequest=STDFU_RQ_AWAITINGPNPPLUGEVENT; pThread->m_TimesToWait=0; lstrcpy(Context.szDevLink, "Resetting"); pThread->SetCurrentContext(&Context); } } } } return 0L; } return DefWindowProc(hWnd, Msg, wParam, lParam); } CDetachThread::CDetachThread(PDFUThreadContext pContext) : CDFUThread(pContext) { WNDCLASSEX Class = {0}; char ClassName[]="DETACHWIND"; DEV_BROADCAST_DEVICEINTERFACE dbi={0}; m_TimesToWait=0; m_hMod=LoadLibrary("setupapi.dll"); CMP_WaitNoPendingInstallEvents=(pCMP_WaitNoPendingInstallEvents)GetProcAddress(m_hMod, "CMP_WaitNoPendingInstallEvents"); Class.cbSize=sizeof(WNDCLASSEX); Class.style=0; Class.lpfnWndProc=WndProc; Class.cbClsExtra=0; Class.cbWndExtra=0; Class.hInstance=GetModuleHandle(NULL); Class.hIcon=NULL; Class.hIconSm=NULL; Class.hCursor=NULL; Class.hbrBackground=NULL; Class.lpszMenuName=NULL; Class.lpszClassName=ClassName; RegisterClassEx(&Class); m_hWnd=CreateWindowEx(WS_EX_TOOLWINDOW, Class.lpszClassName, NULL, WS_POPUP, 0, 0, 0, 0, 0, 0, Class.hInstance, this); dbi.dbcc_size=sizeof(dbi); dbi.dbcc_devicetype=DBT_DEVTYP_DEVICEINTERFACE; dbi.dbcc_classguid=pContext->DfuGUID; /*m_Notif=(DWORD)RegisterDeviceNotification(m_hWnd, &dbi, DEVICE_NOTIFY_WINDOW_HANDLE); dbi.dbcc_classguid=pContext->AppGUID; m_Notif=(DWORD)RegisterDeviceNotification(m_hWnd, &dbi, DEVICE_NOTIFY_WINDOW_HANDLE);*/ // V3.0.4 m_Notif[0]=RegisterDeviceNotification(m_hWnd, &dbi, DEVICE_NOTIFY_WINDOW_HANDLE); dbi.dbcc_classguid=pContext->AppGUID; m_Notif[1]=RegisterDeviceNotification(m_hWnd, &dbi, DEVICE_NOTIFY_WINDOW_HANDLE); } CDetachThread::~CDetachThread() { /*UnregisterDeviceNotification((void*)m_Notif);*/ // V3.0.4 UnregisterDeviceNotification(m_Notif[1]); UnregisterDeviceNotification(m_Notif[0]); DestroyWindow(m_hWnd); UnregisterClass("DETACHWIND", GetModuleHandle(NULL)); FreeLibrary(m_hMod); } BOOL CDetachThread::RunThread() { DFUThreadContext Context; BOOL bRet=TRUE; int i; m_PollTime=0; // Detach State Machine. GetCurrentContext(&Context); if (Context.LastDFUStatus.bState==0xFF) { Context.LastDFUStatus.bState=0xFE; Context.CurrentRequest=STDFU_RQ_OPEN; SetCurrentContext(&Context); // We start our state machine. Let's open the handle if (STDFU_Open(Context.szDevLink, &Context.hDevice)!=STDFU_NOERROR) { Context.ErrorCode=STDFU_OPENDRIVERERROR; bRet=FALSE; // Stops here SetCurrentContext(&Context); } else { // Check if device supports this command if (!(m_DfuDesc.bmAttributes & ATTR_WILL_DETACH)) { Context.ErrorCode=STDFUPRT_UNSUPPORTEDFEATURE; SetCurrentContext(&Context); bRet=FALSE; // Stops here } else { if (Context.Operation==OPERATION_DETACH) { // We are ready to issue our detach command. . Context.Percent=10; Context.CurrentRequest=STDFU_RQ_DETACH; SetCurrentContext(&Context); if (STDFU_Detach(&Context.hDevice, m_DfuInterfaceIdx)!=STDFU_NOERROR) { Context.ErrorCode=STDFUPRT_UNEXPECTEDERROR; SetCurrentContext(&Context); bRet=FALSE; // Stops here } else { // At this stage, the handle is closed and we need to wait for the device removal Context.CurrentRequest=STDFU_RQ_AWAITINGPNPUNPLUGEVENT; SetCurrentContext(&Context); } if (bRet) { for (i=0;i<30;i++) { GetCurrentContext(&Context); Context.Percent=10+i/2; SetCurrentContext(&Context); CMP_WaitNoPendingInstallEvents(INFINITE); Sleep(100); } } } else { if (m_DfuDesc.bmAttributes & ATTR_MANIFESTATION_TOLERANT) { Context.ErrorCode=STDFUPRT_UNSUPPORTEDFEATURE; SetCurrentContext(&Context); bRet=FALSE; // Stops here } else { bRet=EnsureIdleMode(&Context); if (bRet) { // Return to application Operation // We are ready to issue the zero length DnLoad Command Context.Percent=15; Context.CurrentRequest=STDFU_RQ_DOWNLOAD; Context.CurrentNBlock=0; Context.CurrentLength=0; Context.CurrentImageElement=0; bRet=DownloadAndGetStatus(&Context); bRet=TRUE; Context.ErrorCode=STDFUPRT_NOERROR; STDFU_Close(&Context.hDevice); Context.hDevice=0; if (!bRet) { // Not supported. // Let's try by going to DnLoad state machine Context.ErrorCode=STDFUPRT_NOERROR; Context.Percent=16; bRet=SetAddressAndGetStatus(&Context); if (!bRet) { Context.ErrorCode=STDFUPRT_UNEXPECTEDERROR; SetCurrentContext(&Context); bRet=FALSE; // Stops here } } else { // Accepted by the device ! Let's check the handle was closed (entered in Manifest) if (Context.hDevice!=0) { Context.ErrorCode=STDFUPRT_UNEXPECTEDERROR; SetCurrentContext(&Context); bRet=FALSE; // Stops here if (Context.hDevice!=0) STDFU_Abort(&Context.hDevice); // Reset State machine } else { // At this stage, the handle is closed and we need to wait for the device removal Context.CurrentRequest=STDFU_RQ_AWAITINGPNPUNPLUGEVENT; m_PollTime=50; m_TimesToWait=0; SetCurrentContext(&Context); } } } } } } } } else if (Context.LastDFUStatus.bState==STATE_DFU_DOWNLOAD_BUSY) { // End of PollTimeOut Context.Percent=16; Context.CurrentRequest=STDFU_RQ_GET_STATUS; SetCurrentContext(&Context); // We finished to wait. Let's get the status if (STDFU_Getstatus(&Context.hDevice, &Context.LastDFUStatus)!=STDFU_NOERROR) { Context.ErrorCode=STDFUPRT_UNEXPECTEDERROR; SetCurrentContext(&Context); bRet=FALSE; // Stops here STDFU_Abort(&Context.hDevice); // Reset State machine } else { Context.Percent=17; Context.CurrentRequest=STDFU_RQ_DOWNLOAD; Context.CurrentNBlock=0; Context.CurrentLength=0; bRet=DownloadAndGetStatus(&Context); if ( (!bRet) || (Context.hDevice!=0) ) { Context.ErrorCode=STDFUPRT_UNEXPECTEDERROR; SetCurrentContext(&Context); bRet=FALSE; // Stops here if (Context.hDevice!=0) STDFU_Abort(&Context.hDevice); // Reset State machine } else { // At this stage, the handle is closed and we need to wait for the device removal Context.CurrentRequest=STDFU_RQ_AWAITINGPNPUNPLUGEVENT; m_PollTime=50; m_TimesToWait=0; SetCurrentContext(&Context); } } } else if ( (Context.CurrentRequest==STDFU_RQ_AWAITINGPNPUNPLUGEVENT) || (Context.CurrentRequest==STDFU_RQ_AWAITINGPNPPLUGEVENT) ) { CMP_WaitNoPendingInstallEvents(INFINITE); m_TimesToWait++; if (Context.CurrentRequest==STDFU_RQ_AWAITINGPNPUNPLUGEVENT) m_Context.Percent=25+m_TimesToWait/8; else m_Context.Percent=50+m_TimesToWait/8; //SetCurrentContext(&Context); if (m_TimesToWait>=200) { // Time Out... Context.ErrorCode=STDFUPRT_UNEXPECTEDERROR; SetCurrentContext(&Context); bRet=FALSE; // Stops here } else m_PollTime=50; } else if (Context.CurrentRequest!=STDFU_RQ_IDENTIFYINGDEVICE) { // Time Out... Context.ErrorCode=STDFUPRT_UNEXPECTEDERROR; SetCurrentContext(&Context); bRet=FALSE; // Stops here } else { // Succeeded ! if (Context.Operation==OPERATION_DETACH) { // Let's reopen the device, in order to put it in IDLE mode Context.Percent=75; Context.CurrentRequest=STDFU_RQ_OPEN; SetCurrentContext(&Context); if (STDFU_Open(Context.szDevLink, &Context.hDevice)!=STDFU_NOERROR) { Context.ErrorCode=STDFU_OPENDRIVERERROR; bRet=FALSE; // Stops here SetCurrentContext(&Context); } else { Context.Percent=85; bRet=EnsureIdleMode(&Context); if (bRet) { Context.Percent=100; SetCurrentContext(&Context); bRet=FALSE; } else { Context.ErrorCode=STDFUPRT_UNEXPECTEDERROR; SetCurrentContext(&Context); bRet=FALSE; // Stops here } } } else { // Return to application Operation // Success ! Context.Percent=100; SetCurrentContext(&Context); bRet=FALSE; } } return bRet; } BOOL CDetachThread::StopThread(PDWORD ExitCode) { DFUThreadContext Context; DWORD ExCode; BOOL Ret=CSTThread::StopThread(&ExCode); if (ExitCode) *ExitCode=ExCode; GetCurrentContext(&Context); if (Context.hDevice!=0) { STDFU_Close(&Context.hDevice); SetCurrentContext(&Context); } return Ret; }
[ "arback@computer.org" ]
arback@computer.org
33744b1bd728e35c43eec7f5b9b15eea636e195d
62d33fa0eca8c0145611cd0efe6e9c4d8bb8b378
/Zerojudge/b211.cpp
e3d08d459d04d69e204cb6085c0c00d702497cdb
[ "MIT" ]
permissive
yousefalaa2021/OJ
da085e3eba1c80b7998c471bd3aed71d774985f2
67d1d32770376865eba8a9dd1767e97dae68989a
refs/heads/master
2023-03-15T20:16:56.439701
2019-05-01T11:29:10
2019-05-01T11:29:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
604
cpp
#include <cstdlib> #include <iostream> using namespace std; int GCD(int m, int n) { int k; while (n!=0) { k=m%n; m=n; n=k; } return m; } int Pow(int a, int n, int p) { int i, t; for (i=0, t=1; i<n; i++) t=(t*a)%p; return t; } main() { int a, b, m, n, p, g, t; while (1) { cin >> a >> b >> m >> n >> p; if (cin.fail()) break; if (a<b) { t=a; a=b; b=t; } g=GCD(m, n); a=Pow(a, g, p); b=Pow(b, g, p); cout << (p+a-b)%p << endl; } }
[ "w181496@gmail.com" ]
w181496@gmail.com