blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
f96c0f6593904d7109149f72b555c8d508a237b8
0b3a6cd668ba97425dbf5bd217b6d29e156a8c73
/app/widgets/missionrejectedwidget.cpp
746d123012b4e938b57ea68f8a7050474f7a0d26
[]
no_license
VasylA/quest
e676e161d2c2be4ce33dad10e3cbb8247b7f76c6
aaf8121d01e5239c92510cdcb266b9fcdcf9dd86
refs/heads/master
2020-04-07T14:32:49.805193
2018-11-25T17:31:46
2018-11-25T17:31:46
158,451,602
0
0
null
null
null
null
UTF-8
C++
false
false
1,092
cpp
#include "missionrejectedwidget.h" #include <QLabel> #include <QMovie> #include <QHBoxLayout> MissionRejectedWidget::MissionRejectedWidget(QWidget *parent) : QWidget(parent) , _animationLabel(new QLabel) { setupUi(); setupTimer(); } void MissionRejectedWidget::launch(int millisecondsToShutdown) { _countdown.start(millisecondsToShutdown); } void MissionRejectedWidget::setupUi() { setupAnimationLabel(); QLayout *centralLayout = new QHBoxLayout; centralLayout->addWidget(_animationLabel); setLayout(centralLayout); } void MissionRejectedWidget::setupAnimationLabel() { _animationLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); _animationLabel->setAlignment(Qt::AlignHCenter); QMovie *movie = new QMovie("://animations/mouse.gif"); movie->setScaledSize(QSize(width(), 2 * width() / 3)); _animationLabel->setMovie(movie); movie->start(); } void MissionRejectedWidget::setupTimer() { _countdown.setSingleShot(true); connect(&_countdown, SIGNAL(timeout()), this, SIGNAL(countdownFinished())); }
[ "vasyl18@ukr.net" ]
vasyl18@ukr.net
2764beb1a2def2cc11ac84dbd43ce198ce89e700
9c677a1775705f7c8f683d1f89d47e9ed15a32ee
/ACM/luogu/1072.cpp
7fca5a302f2989f5a674b7c49dde8cdb410f3529
[]
no_license
nc-77/algorithms
16e00a0f8ce60f9b998b9ee4ccc69bcfdb5aa832
ced943900a2756a76b2c197002010dc9e08b79c4
refs/heads/main
2023-05-26T20:11:25.762015
2021-06-08T07:16:30
2021-06-08T07:16:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,432
cpp
#include<bits/stdc++.h> #define ll long long #define debug(x) cout<<#x<<'='<<x<<endl #define set0(x) memset(x,0,sizeof(x)) using namespace std; //#define int long long const int inf=0x3f3f3f3f; const int maxn=2e6+10; map<ll,ll>prime[4]; void fac(ll n,map<ll,ll>&prime) { prime.clear(); for(int i=2;i<=n/i;i++) { while(n%i==0) { prime[i]++; n=n/i; } } if(n>1) prime[n]++; } map<ll,ll>xx; map<ll,ll>cnt; int main() { ios::sync_with_stdio(false); int t; cin>>t; while(t--) { xx.clear(); cnt.clear(); int a0,a1,b0,b1,flag=1; cin>>a0>>a1>>b0>>b1; fac(b0,prime[2]); fac(b1,prime[3]); for(auto x:prime[3]){ int id=x.first; int num=x.second; if(num<prime[2][id]){ flag=0; break; } else if(num>prime[2][id]){ xx[id]=num; cnt[id]=1; } else { cnt[id]=num+1; } } fac(a0,prime[0]); fac(a1,prime[1]); for(auto x:prime[0]){ int id=x.first; int num=x.second; if(num<prime[1][id]) { flag=0; break; } else if(num>prime[1][id]){ if(!cnt[id]) { xx[id]=prime[1][id]; cnt[id]=1; } else { if(cnt[id]==1&&xx[id]!=prime[1][id]) {flag=0;break;} else if(cnt[id]>1) { if(cnt[id]>=prime[1][id]){ cnt[id]=1; xx[id]=prime[1][id]; } else {flag=0;break;} } } } else { if(!cnt[id]) {flag=0;break;} else if(cnt[id]==1&&xx[id]<num) {flag=0;break;} else if(cnt[id]>1){ if(cnt[id]<num) {flag=0;break;} else { cnt[id]=cnt[id]-num; } } } } ll ans=1; for(auto x:cnt){ int num=x.second; //debug(x.first),debug(x.second); if(num!=0) ans=ans*num; } if(!flag) cout<<0<<endl; else cout<<ans<<endl; } //system("pause"); return 0; }
[ "291993554@qq.com" ]
291993554@qq.com
9ac4398b4fe525e81f03f199533a90913a2ab51b
831b714d97e68e34f18ada861b7c9b19902fdaae
/libsource/include/motors.h
7b53f98aa992e12732141142f9456d27dedf7bfa
[]
no_license
anosnowhong/phantom
05f9bb292f65ad7501fe855d3efa94e61395f8a0
7d20ce9672e1d9f37ca5b656c56eb81751da7304
refs/heads/master
2021-01-10T13:52:28.920575
2016-09-16T23:41:00
2016-09-16T23:41:00
52,229,681
1
0
null
null
null
null
UTF-8
C++
false
false
1,020
h
/******************************************************************************/ class MOTOR { private: int Type; #define MOTOR_TYPE_MAXON_RE35 0 #define MOTOR_TYPE_MAXON_RE25 1 CONTROLLER *Controller; int Channel; double UnitsPerNm; STRING ObjectName; public: MOTOR( int type, CONTROLLER *controller, int channel, char *name ); MOTOR( int type, CONTROLLER *controller, int channel ); ~MOTOR( void ); void Init( int type, CONTROLLER *controller, int channel, char *name ); char *TypeText( void ); long CurrentUnits; BOOL Open( void ); void Close( void ); BOOL Start( void ); void Stop( void ); void Reset( void ); void Torque( double Nm ); void Units( long units ); }; /******************************************************************************/ extern struct STR_TextItem MOTOR_TypeText[]; /******************************************************************************/
[ "hong@Snows-MacBook-Pro.local" ]
hong@Snows-MacBook-Pro.local
d426c1342c7df6231859f84d809b73849272609f
ea33b4b176770d7bab5508489da61313ad66c54e
/My Addons/ofxFlash/iosExample/src/testApp.h
6413ea9df393420bdb9ec0b08267cc88a36679ed
[]
no_license
roikr/openFrameworks007
e14576fa329070b3eb603004904d76515350991a
7ee9268ea64b71bfa8aba43d4aee10c690f35da8
refs/heads/master
2021-01-20T11:31:37.809556
2014-08-14T09:43:39
2014-08-14T09:43:39
22,948,501
3
0
null
null
null
null
UTF-8
C++
false
false
610
h
#pragma once #include "ofMain.h" #include "ofxiPhone.h" #include "ofxiPhoneExtras.h" #include "ofxFlash.h" class testApp : public ofxiPhoneApp { public: void setup(); void update(); void draw(); void exit(); void touchDown(ofTouchEventArgs &touch); void touchMoved(ofTouchEventArgs &touch); void touchUp(ofTouchEventArgs &touch); void touchDoubleTap(ofTouchEventArgs &touch); void touchCancelled(ofTouchEventArgs &touch); void lostFocus(); void gotFocus(); void gotMemoryWarning(); void deviceOrientationChanged(int newOrientation); ofxDocument doc; ofxSymbolInstance layout; };
[ "roikr75@gmail.com" ]
roikr75@gmail.com
6b252118f239414cd9958838eac3da78d7707273
dfd48108f1a289d935d531cadfe50a37570c277f
/assignments/assignment_1/src/heartRates/GetTargetHeartRateLower.cpp
466472c33b9573b3df5742be1252a9c24d4875cf
[]
no_license
reilly-q/com326
5f7aeba5b3d7bc2b1d406923b9dad684bffb982d
18e712ec53ab6f8b18009f9351f7c2291f285da9
refs/heads/master
2023-01-28T06:55:38.693391
2020-12-08T13:18:25
2020-12-08T13:18:25
298,539,587
0
0
null
null
null
null
UTF-8
C++
false
false
274
cpp
/* * GetTargetHeartRateLower.cpp * * Version Information v1.0 * Author: Quinn Reilly * Date: 08 oct 2020 * * Copyright notice */ // Include classes and headers #include "HeartRates.h" int HeartRates::GetTargetHeartRateLower() { return targetHeartRateLower_; }
[ "reilly-q@ulster.ac.uk" ]
reilly-q@ulster.ac.uk
c66dc8b4393b90a924810926f313b50c884aac9d
8481b904e1ed3b25f5daa982a3d0cafff5a8d201
/C++/POJ/POJ 2954.cpp
350cf32a2ef04b618e50433e8470a15b8a059de0
[]
no_license
lwher/Algorithm-exercise
e4ac914b90b6e4098ab5236cc936a58f437c2e06
2d545af90f7051bf20db0a7a51b8cd0588902bfa
refs/heads/master
2021-01-17T17:39:33.019131
2017-09-12T09:58:54
2017-09-12T09:58:54
70,559,619
1
2
null
null
null
null
UTF-8
C++
false
false
1,055
cpp
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> using namespace std; int t,n; int x1,x2,x3,y1,y2,y3; int ans,on; int gcd(int a,int b) { if(b==0) return a; return gcd(b,a%b); } int main() { int i,j; while(scanf("%d%d%d%d%d%d",&x1,&y1,&x2,&y2,&x3,&y3)) { if(x1==0&&y1==0&&x2==0&&y2==0&&x3==0&&y3==0) break; on=0;ans=0; if(abs(x1-x2)!=0 && abs(y1-y2)!=0) on+=gcd(abs(x1-x2),abs(y1-y2))-1; else if(abs(x1-x2)==0) on+=abs(y1-y2)-1; else on+=abs(x1-x2)-1; ans+=x1*y2-x2*y1; if(abs(x3-x2)!=0 && abs(y3-y2)!=0) on+=gcd(abs(x3-x2),abs(y3-y2))-1; else if(abs(x3-x2)==0) on+=abs(y3-y2)-1; else on+=abs(x3-x2)-1; ans+=x2*y3-x3*y2; if(abs(x1-x3)!=0 && abs(y1-y3)!=0) on+=gcd(abs(x1-x3),abs(y1-y3))-1; else if(abs(x1-x3)==0) on+=abs(y1-y3)-1; else on+=abs(x1-x3)-1; ans+=x3*y1-x1*y3; ans=abs(ans); on+=3; printf("%d\n",(ans-on)/2+1); } system("pause"); return 0; }
[ "751276936@qq.com" ]
751276936@qq.com
a3baea67ec101f35724cd55d31d651446307598f
c18e3cba4f445613b2ed7503061cdfe088d46da5
/docs/atl/codesnippet/CPP/modifying-the-atl-dhtml-control_3.cpp
a7f42c8b59eafe3c7a8e9da761fbed7d6f115e8b
[ "CC-BY-4.0", "MIT" ]
permissive
MicrosoftDocs/cpp-docs
dad03e548e13ca6a6e978df3ba84c4858c77d4bd
87bacc85d5a1e9118a69122d84c43d70f6893f72
refs/heads/main
2023-09-01T00:19:22.423787
2023-08-28T17:27:40
2023-08-28T17:27:40
73,740,405
1,354
1,213
CC-BY-4.0
2023-09-08T21:27:46
2016-11-14T19:38:32
PowerShell
UTF-8
C++
false
false
81
cpp
m_spBrowser->Navigate(CComBSTR(L"www.microsoft.com"), NULL, NULL, NULL, NULL);
[ "v-zhecai@microsoft.com" ]
v-zhecai@microsoft.com
4a4a976aff2cac632d1623a96e473480f993230d
b27291aa51411e0cdc1b0a49e85a4af7b1894eff
/Date/Date.h
db063d0b63a92436ccb30b8630826f887d4b45be
[]
no_license
Ilya837/Date
19f54a02961a5ded47bb026bb16d6cd74cba4f83
c0506ce6d550818a2d353dcaa040444c04cdc63c
refs/heads/master
2023-03-25T04:01:38.631119
2021-03-21T08:02:34
2021-03-21T08:02:34
347,344,421
0
0
null
null
null
null
UTF-8
C++
false
false
756
h
#pragma once #include <iostream> #include <assert.h> #include <string> #include <iomanip> #include <limits> using namespace std; class Date { private: int Day, Month, Year; public: Date(); Date(const Date& date); Date(const int day, const int mouth, const int year); Date(string date); ~Date(); Date operator = (const Date& date); Date operator - (const long double& days) const; Date operator + (const long double& days) const; bool operator < (const Date& date); bool operator > (const Date& date); bool operator <= (const Date& date); bool operator >= (const Date& date); bool operator == (const Date& date); friend ostream& operator << (ostream& out, const Date& date); friend istream& operator >> (istream& in, Date& date); };
[ "mikerin-2002@mail.ru" ]
mikerin-2002@mail.ru
cbd0e8fd0c88b04673775e03eb5a88a13587454f
2ffc0539201e0c1feae3f98efa8c54f28a99a5ac
/src/qt/bitcoingui.cpp
f9e6c2d02a6f7f1ccdb63c55f1a41ebffb535630
[ "MIT" ]
permissive
BovineOverlord/DorfcoinSourceCode
a0a48094690139c23f3eabd9a8509d713ec37c61
2d380cea86837e9b15923e8bd9b2e9b5cacac967
refs/heads/master
2021-01-15T17:16:05.534569
2017-08-09T00:03:03
2017-08-09T00:03:03
99,747,030
0
0
null
null
null
null
UTF-8
C++
false
false
30,158
cpp
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <QApplication> #include "bitcoingui.h" #include "transactiontablemodel.h" #include "optionsdialog.h" #include "aboutdialog.h" #include "clientmodel.h" #include "walletmodel.h" #include "walletframe.h" #include "optionsmodel.h" #include "transactiondescdialog.h" #include "bitcoinunits.h" #include "guiconstants.h" #include "notificator.h" #include "guiutil.h" #include "rpcconsole.h" #include "ui_interface.h" #include "wallet.h" #include "init.h" #ifdef Q_OS_MAC #include "macdockiconhandler.h" #endif #include <QMenuBar> #include <QMenu> #include <QIcon> #include <QVBoxLayout> #include <QToolBar> #include <QStatusBar> #include <QLabel> #include <QMessageBox> #include <QProgressBar> #include <QStackedWidget> #include <QDateTime> #include <QMovie> #include <QTimer> #include <QDragEnterEvent> #if QT_VERSION < 0x050000 #include <QUrl> #endif #include <QMimeData> #include <QStyle> #include <QSettings> #include <QDesktopWidget> #include <QListWidget> #include <iostream> const QString BitcoinGUI::DEFAULT_WALLET = "~Default"; BitcoinGUI::BitcoinGUI(QWidget *parent) : QMainWindow(parent), clientModel(0), encryptWalletAction(0), changePassphraseAction(0), aboutQtAction(0), trayIcon(0), notificator(0), rpcConsole(0), prevBlocks(0) { restoreWindowGeometry(); setWindowTitle(tr("Dorfcoin") + " - " + tr("Wallet")); #ifndef Q_OS_MAC QApplication::setWindowIcon(QIcon(":icons/bitcoin")); setWindowIcon(QIcon(":icons/bitcoin")); #else setUnifiedTitleAndToolBarOnMac(true); QApplication::setAttribute(Qt::AA_DontShowIconsInMenus); #endif // Create wallet frame and make it the central widget walletFrame = new WalletFrame(this); setCentralWidget(walletFrame); // Accept D&D of URIs setAcceptDrops(true); // Create actions for the toolbar, menu bar and tray/dock icon // Needs walletFrame to be initialized createActions(); // Create application menu bar createMenuBar(); // Create the toolbars createToolBars(); // Create system tray icon and notification createTrayIcon(); // Create status bar statusBar(); // Status bar notification icons QFrame *frameBlocks = new QFrame(); frameBlocks->setContentsMargins(0,0,0,0); frameBlocks->setMinimumWidth(56); frameBlocks->setMaximumWidth(56); QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks); frameBlocksLayout->setContentsMargins(3,0,3,0); frameBlocksLayout->setSpacing(3); labelEncryptionIcon = new QLabel(); labelConnectionsIcon = new QLabel(); labelBlocksIcon = new QLabel(); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelEncryptionIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelConnectionsIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelBlocksIcon); frameBlocksLayout->addStretch(); // Progress bar and label for blocks download progressBarLabel = new QLabel(); progressBarLabel->setVisible(false); progressBar = new QProgressBar(); progressBar->setAlignment(Qt::AlignCenter); progressBar->setVisible(false); // Override style sheet for progress bar for styles that have a segmented progress bar, // as they make the text unreadable (workaround for issue #1071) // See https://qt-project.org/doc/qt-4.8/gallery.html QString curStyle = QApplication::style()->metaObject()->className(); if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle") { progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }"); } statusBar()->addWidget(progressBarLabel); statusBar()->addWidget(progressBar); statusBar()->addPermanentWidget(frameBlocks); syncIconMovie = new QMovie(":/movies/update_spinner", "mng", this); rpcConsole = new RPCConsole(this); connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show())); // prevents an oben debug window from becoming stuck/unusable on client shutdown connect(quitAction, SIGNAL(triggered()), rpcConsole, SLOT(hide())); // Install event filter to be able to catch status tip events (QEvent::StatusTip) this->installEventFilter(this); // Initially wallet actions should be disabled setWalletActionsEnabled(false); } BitcoinGUI::~BitcoinGUI() { saveWindowGeometry(); if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu) trayIcon->hide(); #ifdef Q_OS_MAC delete appMenuBar; MacDockIconHandler::instance()->setMainWindow(NULL); #endif } void BitcoinGUI::createActions() { QActionGroup *tabGroup = new QActionGroup(this); overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this); overviewAction->setStatusTip(tr("Show general overview of wallet")); overviewAction->setToolTip(overviewAction->statusTip()); overviewAction->setCheckable(true); overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1)); tabGroup->addAction(overviewAction); sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send"), this); sendCoinsAction->setStatusTip(tr("Send coins to a Dorfcoin address")); sendCoinsAction->setToolTip(sendCoinsAction->statusTip()); sendCoinsAction->setCheckable(true); sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2)); tabGroup->addAction(sendCoinsAction); receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive"), this); receiveCoinsAction->setStatusTip(tr("Show the list of addresses for receiving payments")); receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip()); receiveCoinsAction->setCheckable(true); receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3)); tabGroup->addAction(receiveCoinsAction); historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this); historyAction->setStatusTip(tr("Browse transaction history")); historyAction->setToolTip(historyAction->statusTip()); historyAction->setCheckable(true); historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4)); tabGroup->addAction(historyAction); addressBookAction = new QAction(QIcon(":/icons/address-book"), tr("&Addresses"), this); addressBookAction->setStatusTip(tr("Edit the list of stored addresses and labels")); addressBookAction->setToolTip(addressBookAction->statusTip()); addressBookAction->setCheckable(true); addressBookAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5)); tabGroup->addAction(addressBookAction); connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage())); connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage())); connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage())); connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage())); connect(addressBookAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(addressBookAction, SIGNAL(triggered()), this, SLOT(gotoAddressBookPage())); quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this); quitAction->setStatusTip(tr("Quit application")); quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q)); quitAction->setMenuRole(QAction::QuitRole); aboutAction = new QAction(QIcon(":/icons/bitcoin"), tr("&About Dorfcoin"), this); aboutAction->setStatusTip(tr("Show information about Dorfcoin")); aboutAction->setMenuRole(QAction::AboutRole); aboutQtAction = new QAction(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this); aboutQtAction->setStatusTip(tr("Show information about Qt")); aboutQtAction->setMenuRole(QAction::AboutQtRole); optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this); optionsAction->setStatusTip(tr("Modify configuration options for Dorfcoin")); optionsAction->setMenuRole(QAction::PreferencesRole); toggleHideAction = new QAction(QIcon(":/icons/bitcoin"), tr("&Show / Hide"), this); toggleHideAction->setStatusTip(tr("Show or hide the main Window")); encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this); encryptWalletAction->setStatusTip(tr("Encrypt the private keys that belong to your wallet")); encryptWalletAction->setCheckable(true); backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this); backupWalletAction->setStatusTip(tr("Backup wallet to another location")); changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this); changePassphraseAction->setStatusTip(tr("Change the passphrase used for wallet encryption")); signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this); signMessageAction->setStatusTip(tr("Sign messages with your Dorfcoin addresses to prove you own them")); verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this); verifyMessageAction->setStatusTip(tr("Verify messages to ensure they were signed with specified Dorfcoin addresses")); openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug window"), this); openRPCConsoleAction->setStatusTip(tr("Open debugging and diagnostic console")); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked())); connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt())); connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked())); connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden())); connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool))); connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet())); connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase())); connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab())); connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab())); } void BitcoinGUI::createMenuBar() { #ifdef Q_OS_MAC // Create a decoupled menu bar on Mac which stays even if the window is closed appMenuBar = new QMenuBar(); #else // Get the main window's menu bar on other platforms appMenuBar = menuBar(); #endif // Configure the menus QMenu *file = appMenuBar->addMenu(tr("&File")); file->addAction(backupWalletAction); file->addAction(signMessageAction); file->addAction(verifyMessageAction); file->addSeparator(); file->addAction(quitAction); QMenu *settings = appMenuBar->addMenu(tr("&Settings")); settings->addAction(encryptWalletAction); settings->addAction(changePassphraseAction); settings->addSeparator(); settings->addAction(optionsAction); QMenu *help = appMenuBar->addMenu(tr("&Help")); help->addAction(openRPCConsoleAction); help->addSeparator(); help->addAction(aboutAction); help->addAction(aboutQtAction); } void BitcoinGUI::createToolBars() { QToolBar *toolbar = addToolBar(tr("Tabs toolbar")); toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); toolbar->addAction(overviewAction); toolbar->addAction(sendCoinsAction); toolbar->addAction(receiveCoinsAction); toolbar->addAction(historyAction); toolbar->addAction(addressBookAction); } void BitcoinGUI::setClientModel(ClientModel *clientModel) { this->clientModel = clientModel; if(clientModel) { // Replace some strings and icons, when using the testnet if(clientModel->isTestNet()) { setWindowTitle(windowTitle() + QString(" ") + tr("[testnet]")); #ifndef Q_OS_MAC QApplication::setWindowIcon(QIcon(":icons/bitcoin_testnet")); setWindowIcon(QIcon(":icons/bitcoin_testnet")); #else MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet")); #endif if(trayIcon) { // Just attach " [testnet]" to the existing tooltip trayIcon->setToolTip(trayIcon->toolTip() + QString(" ") + tr("[testnet]")); trayIcon->setIcon(QIcon(":/icons/toolbar_testnet")); } toggleHideAction->setIcon(QIcon(":/icons/toolbar_testnet")); aboutAction->setIcon(QIcon(":/icons/toolbar_testnet")); } // Create system tray menu (or setup the dock menu) that late to prevent users from calling actions, // while the client has not yet fully loaded createTrayIconMenu(); // Keep up to date with client setNumConnections(clientModel->getNumConnections()); connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); setNumBlocks(clientModel->getNumBlocks(), clientModel->getNumBlocksOfPeers()); connect(clientModel, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int))); // Receive and report messages from network/worker thread connect(clientModel, SIGNAL(message(QString,QString,unsigned int)), this, SLOT(message(QString,QString,unsigned int))); rpcConsole->setClientModel(clientModel); walletFrame->setClientModel(clientModel); } } bool BitcoinGUI::addWallet(const QString& name, WalletModel *walletModel) { setWalletActionsEnabled(true); return walletFrame->addWallet(name, walletModel); } bool BitcoinGUI::setCurrentWallet(const QString& name) { return walletFrame->setCurrentWallet(name); } void BitcoinGUI::removeAllWallets() { setWalletActionsEnabled(false); walletFrame->removeAllWallets(); } void BitcoinGUI::setWalletActionsEnabled(bool enabled) { overviewAction->setEnabled(enabled); sendCoinsAction->setEnabled(enabled); receiveCoinsAction->setEnabled(enabled); historyAction->setEnabled(enabled); encryptWalletAction->setEnabled(enabled); backupWalletAction->setEnabled(enabled); changePassphraseAction->setEnabled(enabled); signMessageAction->setEnabled(enabled); verifyMessageAction->setEnabled(enabled); addressBookAction->setEnabled(enabled); } void BitcoinGUI::createTrayIcon() { #ifndef Q_OS_MAC trayIcon = new QSystemTrayIcon(this); trayIcon->setToolTip(tr("Dorfcoin client")); trayIcon->setIcon(QIcon(":/icons/toolbar")); trayIcon->show(); #endif notificator = new Notificator(QApplication::applicationName(), trayIcon); } void BitcoinGUI::createTrayIconMenu() { QMenu *trayIconMenu; #ifndef Q_OS_MAC // return if trayIcon is unset (only on non-Mac OSes) if (!trayIcon) return; trayIconMenu = new QMenu(this); trayIcon->setContextMenu(trayIconMenu); connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason))); #else // Note: On Mac, the dock icon is used to provide the tray's functionality. MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance(); dockIconHandler->setMainWindow((QMainWindow *)this); trayIconMenu = dockIconHandler->dockMenu(); #endif // Configuration of the tray icon (or dock icon) icon menu trayIconMenu->addAction(toggleHideAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(sendCoinsAction); trayIconMenu->addAction(receiveCoinsAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(signMessageAction); trayIconMenu->addAction(verifyMessageAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(optionsAction); trayIconMenu->addAction(openRPCConsoleAction); #ifndef Q_OS_MAC // This is built-in on Mac trayIconMenu->addSeparator(); trayIconMenu->addAction(quitAction); #endif } #ifndef Q_OS_MAC void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason) { if(reason == QSystemTrayIcon::Trigger) { // Click on system tray icon triggers show/hide of the main window toggleHideAction->trigger(); } } #endif void BitcoinGUI::saveWindowGeometry() { QSettings settings; settings.setValue("nWindowPos", pos()); settings.setValue("nWindowSize", size()); } void BitcoinGUI::restoreWindowGeometry() { QSettings settings; QPoint pos = settings.value("nWindowPos").toPoint(); QSize size = settings.value("nWindowSize", QSize(850, 550)).toSize(); if (!pos.x() && !pos.y()) { QRect screen = QApplication::desktop()->screenGeometry(); pos.setX((screen.width()-size.width())/2); pos.setY((screen.height()-size.height())/2); } resize(size); move(pos); } void BitcoinGUI::optionsClicked() { if(!clientModel || !clientModel->getOptionsModel()) return; OptionsDialog dlg; dlg.setModel(clientModel->getOptionsModel()); dlg.exec(); } void BitcoinGUI::aboutClicked() { AboutDialog dlg; dlg.setModel(clientModel); dlg.exec(); } void BitcoinGUI::gotoOverviewPage() { if (walletFrame) walletFrame->gotoOverviewPage(); } void BitcoinGUI::gotoHistoryPage() { if (walletFrame) walletFrame->gotoHistoryPage(); } void BitcoinGUI::gotoAddressBookPage() { if (walletFrame) walletFrame->gotoAddressBookPage(); } void BitcoinGUI::gotoReceiveCoinsPage() { if (walletFrame) walletFrame->gotoReceiveCoinsPage(); } void BitcoinGUI::gotoSendCoinsPage(QString addr) { if (walletFrame) walletFrame->gotoSendCoinsPage(addr); } void BitcoinGUI::gotoSignMessageTab(QString addr) { if (walletFrame) walletFrame->gotoSignMessageTab(addr); } void BitcoinGUI::gotoVerifyMessageTab(QString addr) { if (walletFrame) walletFrame->gotoVerifyMessageTab(addr); } void BitcoinGUI::setNumConnections(int count) { QString icon; switch(count) { case 0: icon = ":/icons/connect_0"; break; case 1: case 2: case 3: icon = ":/icons/connect_1"; break; case 4: case 5: case 6: icon = ":/icons/connect_2"; break; case 7: case 8: case 9: icon = ":/icons/connect_3"; break; default: icon = ":/icons/connect_4"; break; } labelConnectionsIcon->setPixmap(QIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelConnectionsIcon->setToolTip(tr("%n active connection(s) to Dorfcoin network", "", count)); } void BitcoinGUI::setNumBlocks(int count, int nTotalBlocks) { // Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text) statusBar()->clearMessage(); // Acquire current block source enum BlockSource blockSource = clientModel->getBlockSource(); switch (blockSource) { case BLOCK_SOURCE_NETWORK: progressBarLabel->setText(tr("Synchronizing with network...")); break; case BLOCK_SOURCE_DISK: progressBarLabel->setText(tr("Importing blocks from disk...")); break; case BLOCK_SOURCE_REINDEX: progressBarLabel->setText(tr("Reindexing blocks on disk...")); break; case BLOCK_SOURCE_NONE: // Case: not Importing, not Reindexing and no network connection progressBarLabel->setText(tr("No block source available...")); break; } QString tooltip; QDateTime lastBlockDate = clientModel->getLastBlockDate(); QDateTime currentDate = QDateTime::currentDateTime(); int secs = lastBlockDate.secsTo(currentDate); if(count < nTotalBlocks) { tooltip = tr("Processed %1 of %2 (estimated) blocks of transaction history.").arg(count).arg(nTotalBlocks); } else { tooltip = tr("Processed %1 blocks of transaction history.").arg(count); } // Set icon state: spinning if catching up, tick otherwise if(secs < 90*60 && count >= nTotalBlocks) { tooltip = tr("Up to date") + QString(".<br>") + tooltip; labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); walletFrame->showOutOfSyncWarning(false); progressBarLabel->setVisible(false); progressBar->setVisible(false); } else { // Represent time from last generated block in human readable text QString timeBehindText; if(secs < 48*60*60) { timeBehindText = tr("%n hour(s)","",secs/(60*60)); } else if(secs < 14*24*60*60) { timeBehindText = tr("%n day(s)","",secs/(24*60*60)); } else { timeBehindText = tr("%n week(s)","",secs/(7*24*60*60)); } progressBarLabel->setVisible(true); progressBar->setFormat(tr("%1 behind").arg(timeBehindText)); progressBar->setMaximum(1000000000); progressBar->setValue(clientModel->getVerificationProgress() * 1000000000.0 + 0.5); progressBar->setVisible(true); tooltip = tr("Catching up...") + QString("<br>") + tooltip; labelBlocksIcon->setMovie(syncIconMovie); if(count != prevBlocks) syncIconMovie->jumpToNextFrame(); prevBlocks = count; walletFrame->showOutOfSyncWarning(true); tooltip += QString("<br>"); tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText); tooltip += QString("<br>"); tooltip += tr("Transactions after this will not yet be visible."); } // Don't word-wrap this (fixed-width) tooltip tooltip = QString("<nobr>") + tooltip + QString("</nobr>"); labelBlocksIcon->setToolTip(tooltip); progressBarLabel->setToolTip(tooltip); progressBar->setToolTip(tooltip); } void BitcoinGUI::message(const QString &title, const QString &message, unsigned int style, bool *ret) { QString strTitle = tr("Dorfcoin"); // default title // Default to information icon int nMBoxIcon = QMessageBox::Information; int nNotifyIcon = Notificator::Information; QString msgType; // Prefer supplied title over style based title if (!title.isEmpty()) { msgType = title; } else { switch (style) { case CClientUIInterface::MSG_ERROR: msgType = tr("Error"); break; case CClientUIInterface::MSG_WARNING: msgType = tr("Warning"); break; case CClientUIInterface::MSG_INFORMATION: msgType = tr("Information"); break; default: break; } } // Append title to "Bitcoin - " if (!msgType.isEmpty()) strTitle += " - " + msgType; // Check for error/warning icon if (style & CClientUIInterface::ICON_ERROR) { nMBoxIcon = QMessageBox::Critical; nNotifyIcon = Notificator::Critical; } else if (style & CClientUIInterface::ICON_WARNING) { nMBoxIcon = QMessageBox::Warning; nNotifyIcon = Notificator::Warning; } // Display message if (style & CClientUIInterface::MODAL) { // Check for buttons, use OK as default, if none was supplied QMessageBox::StandardButton buttons; if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK))) buttons = QMessageBox::Ok; // Ensure we get users attention showNormalIfMinimized(); QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons, this); int r = mBox.exec(); if (ret != NULL) *ret = r == QMessageBox::Ok; } else notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message); } void BitcoinGUI::changeEvent(QEvent *e) { QMainWindow::changeEvent(e); #ifndef Q_OS_MAC // Ignored on Mac if(e->type() == QEvent::WindowStateChange) { if(clientModel && clientModel->getOptionsModel()->getMinimizeToTray()) { QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e); if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized()) { QTimer::singleShot(0, this, SLOT(hide())); e->ignore(); } } } #endif } void BitcoinGUI::closeEvent(QCloseEvent *event) { if(clientModel) { #ifndef Q_OS_MAC // Ignored on Mac if(!clientModel->getOptionsModel()->getMinimizeToTray() && !clientModel->getOptionsModel()->getMinimizeOnClose()) { QApplication::quit(); } #endif } QMainWindow::closeEvent(event); } void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee) { QString strMessage = tr("This transaction is over the size limit. You can still send it for a fee of %1, " "which goes to the nodes that process your transaction and helps to support the network. " "Do you want to pay the fee?").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nFeeRequired)); QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm transaction fee"), strMessage, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Yes); *payFee = (retval == QMessageBox::Yes); } void BitcoinGUI::incomingTransaction(const QString& date, int unit, qint64 amount, const QString& type, const QString& address) { // On new transaction, make an info balloon message((amount)<0 ? tr("Sent transaction") : tr("Incoming transaction"), tr("Date: %1\n" "Amount: %2\n" "Type: %3\n" "Address: %4\n") .arg(date) .arg(BitcoinUnits::formatWithUnit(unit, amount, true)) .arg(type) .arg(address), CClientUIInterface::MSG_INFORMATION); } void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event) { // Accept only URIs if(event->mimeData()->hasUrls()) event->acceptProposedAction(); } void BitcoinGUI::dropEvent(QDropEvent *event) { if(event->mimeData()->hasUrls()) { int nValidUrisFound = 0; QList<QUrl> uris = event->mimeData()->urls(); foreach(const QUrl &uri, uris) { if (walletFrame->handleURI(uri.toString())) nValidUrisFound++; } // if valid URIs were found if (nValidUrisFound) walletFrame->gotoSendCoinsPage(); else message(tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid Dorfcoin address or malformed URI parameters."), CClientUIInterface::ICON_WARNING); } event->acceptProposedAction(); } bool BitcoinGUI::eventFilter(QObject *object, QEvent *event) { // Catch status tip events if (event->type() == QEvent::StatusTip) { // Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff if (progressBarLabel->isVisible() || progressBar->isVisible()) return true; } return QMainWindow::eventFilter(object, event); } void BitcoinGUI::handleURI(QString strURI) { // URI has to be valid if (!walletFrame->handleURI(strURI)) message(tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid Dorfcoin address or malformed URI parameters."), CClientUIInterface::ICON_WARNING); } void BitcoinGUI::setEncryptionStatus(int status) { switch(status) { case WalletModel::Unencrypted: labelEncryptionIcon->hide(); encryptWalletAction->setChecked(false); changePassphraseAction->setEnabled(false); encryptWalletAction->setEnabled(true); break; case WalletModel::Unlocked: labelEncryptionIcon->show(); labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>")); encryptWalletAction->setChecked(true); changePassphraseAction->setEnabled(true); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported break; case WalletModel::Locked: labelEncryptionIcon->show(); labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>")); encryptWalletAction->setChecked(true); changePassphraseAction->setEnabled(true); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported break; } } void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden) { // activateWindow() (sometimes) helps with keyboard focus on Windows if (isHidden()) { show(); activateWindow(); } else if (isMinimized()) { showNormal(); activateWindow(); } else if (GUIUtil::isObscured(this)) { raise(); activateWindow(); } else if(fToggleHidden) hide(); } void BitcoinGUI::toggleHidden() { showNormalIfMinimized(true); } void BitcoinGUI::detectShutdown() { if (ShutdownRequested()) QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection); }
[ "andrew_sainz@live.com" ]
andrew_sainz@live.com
c052a69c15f1a948cc954838d8ea310583df991a
70cdf389c2bc8f0b34e8f6d461b3dae7c52af549
/tests/test_operator_run.cpp
938bcda1f0d6ca1e9dc3920137eb2e97148da19a
[]
no_license
LIZECHUAN/openlf
526839545414c59d9584f78c11aa282ab5c34869
fe907092f23f9457e151f36e2faa6ea41e4cef43
refs/heads/master
2020-05-31T07:27:43.838912
2015-09-23T14:44:15
2015-09-23T14:44:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,111
cpp
/* * File: test_operator_run.cpp * Author: swanner * * Created on Mar 25, 2014, 11:06:07 AM */ #include <cppunit/BriefTestProgressListener.h> #include <cppunit/CompilerOutputter.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/TestResult.h> #include <cppunit/TestResultCollector.h> #include <cppunit/TestRunner.h> int main() { // Create the event manager and test controller CPPUNIT_NS::TestResult controller; // Add a listener that colllects test result CPPUNIT_NS::TestResultCollector result; controller.addListener(&result); // Add a listener that print dots as test run. CPPUNIT_NS::BriefTestProgressListener progress; controller.addListener(&progress); // Add the top suite to the test runner CPPUNIT_NS::TestRunner runner; runner.addTest(CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest()); runner.run(controller); // Print test in a compiler compatible format. CPPUNIT_NS::CompilerOutputter outputter(&result, CPPUNIT_NS::stdCOut()); outputter.write(); return result.wasSuccessful() ? 0 : 1; }
[ "kiryl2009@hotmail.com" ]
kiryl2009@hotmail.com
7ff54ba55ff9573c74a21e208b9e14dddac2b907
b2d5e4c4bac4e040d83ce87cc1baa1c1bd330287
/CodeChef/NAME1.cpp
f007850fe725c420649df355d171ce4b0a31f509
[ "MIT" ]
permissive
stalin18/C-and-CPlusPlus-Programs
7b4894f66a767f093f8649c6db983b6f9a2bb53a
b2a303fe6b16e42c3b6d1a4167e6b884142d1928
refs/heads/master
2016-08-04T15:03:09.200457
2014-02-13T02:23:58
2014-02-13T02:23:58
11,862,479
0
1
null
null
null
null
UTF-8
C++
false
false
913
cpp
#include<iostream> #include<string> using namespace std; int main(){ int t, n; string a, b, child_concat; cin>>t; while(t--){ int parent[26]={0}; int children_[26]={0}; int i=0; child_concat=""; cin>>a>>b; a+=b; cin>>n; string children[n]; for(i=0;i<n;i++){ cin>>children[i]; child_concat+=children[i]; } for(i=0;i<child_concat.size();i++){ children_[child_concat[i]-'a']++; } for(i=0;i<a.size();i++){ parent[a[i]-'a']++; } for(i=0;i<26;i++){ if(children_[i]!=0&&(children_[i]>parent[i])){ break; } } if(i!=26){ cout<<"NO\n"; } else{ cout<<"YES\n"; } } return 0; }
[ "kunalswami@live.in" ]
kunalswami@live.in
ad59df8e6e287f3a545080db1f80c0db5ecbdcaf
3352a1db84dd6a6164b2d0832f1cb57e94f2e1e3
/FFH2 BA Mod/Assets/src/CvGameCoreDLL.041o/CvUnit.cpp
4fa583a7de844fcde0da3f14d3058f11d4e565b3
[]
no_license
AdrianGin/pic-source
bef9fe0d52e356b7e8579e2a82e9271f4a877bcb
54f321d0a5ad3530a1c46d53ca24cee62f20aa4a
refs/heads/master
2023-09-02T22:57:08.380760
2021-11-20T10:19:11
2021-11-20T10:19:11
273,621,080
0
0
null
null
null
null
UTF-8
C++
false
false
516,277
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() { m_aiExtraDomainModifier = new int[NUM_DOMAIN_TYPES]; //FfH Damage Types: Added by Kael 08/23/2007 m_paiBonusAffinity = NULL; m_paiBonusAffinityAmount = NULL; m_paiDamageTypeCombat = NULL; m_paiDamageTypeResist = NULL; //FfH: End Add 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() { //FfH: Added by Kael 07/05/2009 (fixes a crash when promotions are applid before the game is loaded) bool bSelected = IsSelected(); //FfH: End Add //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(); //FfH: Added by Kael 07/05/2009 (fixes a crash when promotions are applid before the game is loaded) if (bSelected) { gDLL->getInterfaceIFace()->selectUnit(this, false, false, false); } //FfH: End Add } 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 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())) //FfH: Added by Kael 11/05/2007 && GC.getGameINLINE().getUnitClassCreatedCount((UnitClassTypes)(m_pUnitInfo->getUnitClassType())) == 1 //FfH: End Add ) { 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); //FfH Units: Added by Kael 04/18/2008 if (m_pUnitInfo->getFreePromotionPick() > 0) { changeFreePromotionPick(m_pUnitInfo->getFreePromotionPick()); setPromotionReady(true); } GC.getGameINLINE().changeGlobalCounter(m_pUnitInfo->getModifyGlobalCounter()); m_iReligion = m_pUnitInfo->getReligionType(); for (iI = 0; iI < GC.getNumBonusInfos(); iI++) { changeBonusAffinity((BonusTypes)iI, m_pUnitInfo->getBonusAffinity((BonusTypes)iI)); } if (m_pUnitInfo->isMechUnit()) { changeAlive(1); } if (GC.getCivilizationInfo(getCivilizationType()).getDefaultRace() != NO_PROMOTION) { if (getRace() == NO_PROMOTION) { if (!::isWorldUnitClass(getUnitClassType()) && !isAnimal() && isAlive() && getDomainType() == DOMAIN_LAND) { setHasPromotion((PromotionTypes)GC.getCivilizationInfo(getCivilizationType()).getDefaultRace(), true); } } } //FfH: End Add CvEventReporter::getInstance().unitCreated(this); } void CvUnit::uninit() { //FfH Damage Types: Added by Kael 08/23/2007 SAFE_DELETE_ARRAY(m_paiBonusAffinity); SAFE_DELETE_ARRAY(m_paiBonusAffinityAmount); SAFE_DELETE_ARRAY(m_paiDamageTypeCombat); SAFE_DELETE_ARRAY(m_paiDamageTypeResist); //FfH: End Add 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(); 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; //Unit Per Tile -- START m_iUnitPlotCost = 0; //Unit Per Tile -- END 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; //FfH Spell System: Added by Kael 07/23/2007 m_bFleeWithdrawl = false; m_bHasCasted = false; m_bIgnoreHide = false; m_bTerraformer = false; m_iAlive = 0; m_iAIControl = 0; m_iBoarding = 0; m_iDefensiveStrikeChance = (NO_UNIT != m_eUnitType) ? m_pUnitInfo->getDefensiveStrikeChance() : 0; m_iDefensiveStrikeDamage = (NO_UNIT != m_eUnitType) ? m_pUnitInfo->getDefensiveStrikeDamage() : 0; m_iDoubleFortifyBonus = 0; m_iFear = 0; m_iFlying = 0; m_iHeld = 0; m_iHiddenNationality = (NO_UNIT != m_eUnitType) ? m_pUnitInfo->isHiddenNationality() : 0; m_iIgnoreBuildingDefense = (NO_UNIT != m_eUnitType) ? m_pUnitInfo->isIgnoreBuildingDefense() : 0; m_iImmortal = (NO_UNIT != m_eUnitType) ? m_pUnitInfo->isImmortal() : 0; m_iImmuneToCapture = 0; m_iImmuneToDefensiveStrike = (NO_UNIT != m_eUnitType) ? m_pUnitInfo->isImmuneToDefensiveStrike() : 0; m_iImmuneToFear = 0; m_iImmuneToMagic = 0; m_iInvisible = 0; m_iOnlyDefensive = 0; m_iSeeInvisible = 0; m_iTargetWeakestUnit = 0; m_iTargetWeakestUnitCounter = 0; m_iTwincast = 0; m_iWaterWalking = 0; m_iBaseCombatDefense = (NO_UNIT != m_eUnitType) ? m_pUnitInfo->getCombatDefense() : 0; m_iBetterDefenderThanPercent = 100; m_iCombatHealPercent = 0; m_iCombatLimit = (NO_UNIT != m_eUnitType) ? m_pUnitInfo->getCombatLimit() : 0; m_iCombatPercentInBorders = 0; m_iCombatPercentGlobalCounter = 0; m_iDelayedSpell = NO_SPELL; m_iDuration = 0; m_iFreePromotionPick = 0; m_iGoldFromCombat = (NO_UNIT != m_eUnitType) ? m_pUnitInfo->getGoldFromCombat() : 0; m_iGroupSize = (NO_UNIT != m_eUnitType) ? m_pUnitInfo->getGroupSize() : 0; m_iInvisibleType = (NO_UNIT != m_eUnitType) ? m_pUnitInfo->getInvisibleType() : 0; m_iRace = NO_PROMOTION; m_iReligion = NO_RELIGION; m_iResist = 0; m_iResistModify = 0; m_iScenarioCounter = -1; m_iSpellCasterXP = 0; m_iSpellDamageModify = 0; m_iSummoner = -1; m_iTotalDamageTypeCombat = 0; m_iUnitArtStyleType = NO_UNIT_ARTSTYLE; m_iWorkRateModify = 0; if (!bConstructorCall) { m_paiDamageTypeCombat = new int[GC.getNumDamageTypeInfos()]; m_paiDamageTypeResist = new int[GC.getNumDamageTypeInfos()]; for (iI = 0; iI < GC.getNumDamageTypeInfos(); iI++) { int iChange = (NO_UNIT != m_eUnitType) ? m_pUnitInfo->getDamageTypeCombat(iI) : 0; m_paiDamageTypeCombat[iI] = iChange; m_paiDamageTypeResist[iI] = 0; m_iTotalDamageTypeCombat += iChange; } m_paiBonusAffinity = new int[GC.getNumBonusInfos()]; m_paiBonusAffinityAmount = new int[GC.getNumBonusInfos()]; for (iI = 0; iI < GC.getNumBonusInfos(); iI++) { m_paiBonusAffinity[iI] = 0; m_paiBonusAffinityAmount[iI] = 0; } } //FfH: End Add /*************************************************************************************************/ /** ADDON (New Functions Definition) Sephi **/ /** **/ /** **/ /*************************************************************************************************/ m_iAutoSpellCast = NO_SPELL; /*************************************************************************************************/ /** END **/ /*************************************************************************************************/ 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(); //FfH: Modified by Kael 08/21/2008 // for (int iI = 0; iI < GC.getNumPromotionInfos(); iI++) // { // setHasPromotion(((PromotionTypes)iI), (pUnit->isHasPromotion((PromotionTypes)iI) || m_pUnitInfo->getFreePromotions(iI))); // } if (getRace() != NO_PROMOTION) { if (!m_pUnitInfo->getFreePromotions(getRace())) { setHasPromotion(((PromotionTypes)getRace()), false); } else { pUnit->setHasPromotion(((PromotionTypes)getRace()), true); } } if (pUnit->isHasPromotion((PromotionTypes)GC.getDefineINT("HIDDEN_NATIONALITY_PROMOTION"))) { CvUnit* pLoopUnit; CLLNode<IDInfo>* pUnitNode; pUnitNode = pPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); if (pLoopUnit->getTeam() != getTeam()) { pUnit->setHasPromotion((PromotionTypes)GC.getDefineINT("HIDDEN_NATIONALITY_PROMOTION"), false); } } } for (int iI = 0; iI < GC.getNumPromotionInfos(); iI++) { if (pUnit->isHasPromotion((PromotionTypes)iI)) { if (iI == GC.getDefineINT("MUTATED_PROMOTION")) { m_pabHasPromotion[iI] = pUnit->isHasPromotion((PromotionTypes)iI); } else { setHasPromotion(((PromotionTypes)iI), true); if (GC.getPromotionInfo((PromotionTypes)iI).isEquipment()) { pUnit->setHasPromotion((PromotionTypes)iI, false); } } if (GC.getPromotionInfo((PromotionTypes)iI).isValidate()) { if (!GC.getPromotionInfo((PromotionTypes)iI).getUnitCombat(getUnitCombatType())) { setHasPromotion(((PromotionTypes)iI), false); } } } } if (GC.getDefineINT("WEAPON_PROMOTION_TIER1") != -1 && isHasPromotion((PromotionTypes)GC.getDefineINT("WEAPON_PROMOTION_TIER1"))) { if (m_pUnitInfo->getWeaponTier() < 1 || isHasPromotion((PromotionTypes)GC.getDefineINT("WEAPON_PROMOTION_TIER2")) || isHasPromotion((PromotionTypes)GC.getDefineINT("WEAPON_PROMOTION_TIER3"))) { setHasPromotion((PromotionTypes)GC.getDefineINT("WEAPON_PROMOTION_TIER1"), false); } } if (GC.getDefineINT("WEAPON_PROMOTION_TIER2") != -1 && isHasPromotion((PromotionTypes)GC.getDefineINT("WEAPON_PROMOTION_TIER2"))) { if (m_pUnitInfo->getWeaponTier() < 2 || isHasPromotion((PromotionTypes)GC.getDefineINT("WEAPON_PROMOTION_TIER3"))) { setHasPromotion((PromotionTypes)GC.getDefineINT("WEAPON_PROMOTION_TIER2"), false); } } if (GC.getDefineINT("WEAPON_PROMOTION_TIER3") != -1 && isHasPromotion((PromotionTypes)GC.getDefineINT("WEAPON_PROMOTION_TIER3"))) { if (m_pUnitInfo->getWeaponTier() < 3) { setHasPromotion((PromotionTypes)GC.getDefineINT("WEAPON_PROMOTION_TIER3"), false); } } if (m_pUnitInfo->getFreePromotionPick() > 0 && getGameTurnCreated() == GC.getGameINLINE().getGameTurn()) { setPromotionReady(true); } setDuration(pUnit->getDuration()); if (pUnit->getReligion() != NO_RELIGION && getReligion() == NO_RELIGION) { setReligion(pUnit->getReligion()); } if (pUnit->isImmortal()) { pUnit->changeImmortal(-1); } if (pUnit->isHasCasted()) { setHasCasted(true); } if (pUnit->getScenarioCounter() != -1) { setScenarioCounter(pUnit->getScenarioCounter()); } //FfH: End Modify setGameTurnCreated(pUnit->getGameTurnCreated()); setDamage(pUnit->getDamage()); setMoves(pUnit->getMoves()); //Unit Per Tile -- START setUnitPlotCost(pUnit->UnitPlotCost()); //Unit Per Tile -- END 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()); /*************************************************************************************************/ /** BETTER AI (New UNITAI) Sephi **/ /** **/ /** **/ /*************************************************************************************************/ AI_setGroupflag(pUnit->AI_getGroupflag()); AI_setUnitAIType(pUnit->AI_getUnitAIType()); /*************************************************************************************************/ /** END **/ /*************************************************************************************************/ //FfH: Added by Kael 10/03/2008 if (!isWorldUnitClass((UnitClassTypes)(m_pUnitInfo->getUnitClassType())) && isWorldUnitClass((UnitClassTypes)(pUnit->getUnitClassType()))) { setName(pUnit->getName()); } //FfH: End Add 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) { //FfH: Modified by Kael 02/05/2009 // CvEventReporter::getInstance().unitKilled(this, ePlayer); if (!isImmortal()) { CvEventReporter::getInstance().unitKilled(this, ePlayer); } //FfH: End Modify 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; } //FfH: Added by Kael 07/23/2008 if (isImmortal()) { if (GET_PLAYER(getOwnerINLINE()).getCapitalCity() != NULL) { m_bDeathDelay = false; doImmortalRebirth(); return; } } GC.getGameINLINE().changeGlobalCounter(-1 * m_pUnitInfo->getModifyGlobalCounter()); for (int iI = 0; iI < GC.getNumPromotionInfos(); iI++) { if (isHasPromotion((PromotionTypes)iI)) { GC.getGameINLINE().changeGlobalCounter(-1 * GC.getPromotionInfo((PromotionTypes)iI).getModifyGlobalCounter()); if (GC.getPromotionInfo((PromotionTypes)iI).isEquipment()) { for (int iJ = 0; iJ < GC.getNumUnitInfos(); iJ++) { if (GC.getUnitInfo((UnitTypes)iJ).getEquipmentPromotion() == iI) { GET_PLAYER(getOwnerINLINE()).initUnit((UnitTypes)iJ, getX_INLINE(), getY_INLINE(), AI_getUnitAIType()); setHasPromotion((PromotionTypes)iI, false); } } } } } if (isWorldUnitClass((UnitClassTypes)(m_pUnitInfo->getUnitClassType())) && GC.getGameINLINE().getUnitClassCreatedCount((UnitClassTypes)(m_pUnitInfo->getUnitClassType())) == 1) { for (int iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive() && GET_PLAYER((PlayerTypes)iI).isHuman() && getOwner() != iI) { szBuffer = gDLL->getText("TXT_KEY_MISC_SOMEONE_KILLED_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"), getX_INLINE(), getY_INLINE(), true, true); } } } int iLoop; for (pLoopUnit = GET_PLAYER(getOwnerINLINE()).firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = GET_PLAYER(getOwnerINLINE()).nextUnit(&iLoop)) { if (pLoopUnit->getSummoner() == getID()) { pLoopUnit->setSummoner(-1); } } //FfH: End Add 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(); //FfH: Modified by Kael 09/01/2007 // eCaptureUnitType = ((eCapturingPlayer != NO_PLAYER) ? getCaptureUnitType(GET_PLAYER(eCapturingPlayer).getCivilizationType()) : NO_UNIT); eCaptureUnitType = ((eCapturingPlayer != NO_PLAYER) ? getCaptureUnitType(GET_PLAYER(getOwnerINLINE()).getCivilizationType()) : NO_UNIT); if (m_pUnitInfo->getUnitCaptureClassType() == getUnitClassType()) { eCaptureUnitType = (UnitTypes)getUnitType(); } int iRace = getRace(); //FfH: End Modify setXY(INVALID_PLOT_COORD, INVALID_PLOT_COORD, true); joinGroup(NULL, false, false); CvEventReporter::getInstance().unitLost(this); GET_PLAYER(getOwnerINLINE()).deleteUnit(getID()); //FfH: Modified by Kael 01/19/2008 // if ((eCapturingPlayer != NO_PLAYER) && (eCaptureUnitType != NO_UNIT) && !(GET_PLAYER(eCapturingPlayer).isBarbarian())) if ((eCapturingPlayer != NO_PLAYER) && (eCaptureUnitType != NO_UNIT)) //FfH: End Modify { 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()); //FfH: Added by Kael 08/18/2008 if (pkCapturedUnit->getRace() != NO_PROMOTION) { pkCapturedUnit->setHasPromotion((PromotionTypes)pkCapturedUnit->getRace(), false); } if (iRace != NO_PROMOTION) { pkCapturedUnit->setHasPromotion((PromotionTypes)iRace, true); } //FfH: End Add 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") //FfH: Added by Kael 12/02/2007 && pkCapturedUnit->canScrap() //FfH: End Add ) { 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"); //FfH Spell System: Added by Kael 07/23/2007 int iI; CvPlot* pPlot = plot(); if (hasMoved()) { if (isAlwaysHeal() || isBarbarian()) { doHeal(); } } else { if (isHurt()) { doHeal(); } if (!isCargo()) { changeFortifyTurns(1); } } if (m_pUnitInfo->isAbandon()) { if (!isBarbarian()) { bool bValid = true; if (m_pUnitInfo->getPrereqCivic() != NO_CIVIC) { bValid = false; for (int iI = 0; iI < GC.getDefineINT("MAX_CIVIC_OPTIONS"); iI++) { if (GET_PLAYER(getOwnerINLINE()).getCivics((CivicOptionTypes)iI) == m_pUnitInfo->getPrereqCivic()) { bValid = true; } } if (GET_PLAYER(getOwnerINLINE()).isAnarchy()) { bValid = true; } } if (bValid == true) { if (m_pUnitInfo->getStateReligion() != NO_RELIGION) { bValid = false; if (GET_PLAYER(getOwnerINLINE()).getStateReligion() == m_pUnitInfo->getStateReligion()) { bValid = true; } } } if (bValid == false) { gDLL->getInterfaceIFace()->addMessage((PlayerTypes)getOwnerINLINE(), true, GC.getDefineINT("EVENT_MESSAGE_TIME"), gDLL->getText("TXT_KEY_MESSAGE_UNIT_ABANDON", getNameKey()), GC.getEraInfo(GC.getGameINLINE().getCurrentEra()).getAudioUnitDefeatScript(), MESSAGE_TYPE_INFO, m_pUnitInfo->getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), plot()->getX_INLINE(), plot()->getY_INLINE()); kill(true); GC.getGameINLINE().decrementUnitCreatedCount(getUnitType()); GC.getGameINLINE().decrementUnitClassCreatedCount((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() * -1); } } } for (iI = 0; iI < GC.getNumPromotionInfos(); iI++) { if (isHasPromotion((PromotionTypes)iI)) { if (GC.getPromotionInfo((PromotionTypes)iI).getFreeXPPerTurn() != 0) { if (getExperience() < GC.getDefineINT("FREE_XP_MAX")) { changeExperience(GC.getPromotionInfo((PromotionTypes)iI).getFreeXPPerTurn(), -1, false, false, false); } } if (GC.getPromotionInfo((PromotionTypes)iI).getPromotionRandomApply() != NO_PROMOTION) { if (!isHasPromotion((PromotionTypes)GC.getPromotionInfo((PromotionTypes)iI).getPromotionRandomApply())) { if (GC.getGameINLINE().getSorenRandNum(100, "Promotion Random Apply") <= 3) { setHasPromotion(((PromotionTypes)GC.getPromotionInfo((PromotionTypes)iI).getPromotionRandomApply()), true); } } } if (GC.getPromotionInfo((PromotionTypes)iI).getBetrayalChance() != 0) { if (!isImmuneToCapture() && !isBarbarian() && !GC.getGameINLINE().isOption(GAMEOPTION_NO_BARBARIANS)) { if (GC.getGameINLINE().getSorenRandNum(100, "Betrayal Chance") <= GC.getPromotionInfo((PromotionTypes)iI).getBetrayalChance()) { betray(BARBARIAN_PLAYER); } } } if (!CvString(GC.getPromotionInfo((PromotionTypes)iI).getPyPerTurn()).empty()) { CyUnit* pyUnit = new CyUnit(this); CyArgsList argsList; argsList.add(gDLL->getPythonIFace()->makePythonObject(pyUnit)); // pass in unit class argsList.add(iI);//the promotion # gDLL->getPythonIFace()->callFunction(PYSpellModule, "effect", argsList.makeFunctionArgs()); //, &lResult delete pyUnit; // python fxn must not hold on to this pointer } if (GC.getPromotionInfo((PromotionTypes)iI).getExpireChance() != 0) { if (GC.getGameINLINE().getSorenRandNum(100, "Promotion Expire") <= GC.getPromotionInfo((PromotionTypes)iI).getExpireChance()) { setHasPromotion(((PromotionTypes)iI), false); } } if (!isHurt()) { if (GC.getPromotionInfo((PromotionTypes)iI).isRemovedWhenHealed()) { setHasPromotion(((PromotionTypes)iI), false); } } } } setHasCasted(false); if (getSpellCasterXP() > 0) { if (GC.getGameINLINE().getSorenRandNum(100, "SpellCasterXP") < getSpellCasterXP() - getExperience()) { changeExperience(1, -1, false, false, false); } } if (getDuration() > 0) { changeDuration(-1); if (getDuration() == 0) { if (isImmortal()) { changeImmortal(-1); } kill(true); } } if (pPlot->isCity()) { if (m_pUnitInfo->getWeaponTier() > 0) { setWeapons(); } if (isBarbarian()) { if (m_pUnitInfo->isAutoRaze()) { if (pPlot->getOwner() == getOwnerINLINE()) { pPlot->getPlotCity()->kill(true); } } } } if (m_pUnitInfo->isImmortal()) { if (!isImmortal()) { changeImmortal(1); } } //FfH: End Add testPromotionReady(); if (isBlockading()) { collectBlockadeGold(); } //FfH: Modified by Kael 02/03/2009 (spy intercept and feature damage commented out for performance, healing moved to earlier in the function) // if (isSpy() && isIntruding() && !isCargo()) // { // TeamTypes eTeam = plot()->getTeam(); // if (NO_TEAM != eTeam) // { // if (GET_TEAM(getTeam()).isOpenBorders(eTeam)) // { // testSpyIntercepted(plot()->getOwnerINLINE(), GC.getDefineINT("ESPIONAGE_SPY_NO_INTRUDE_INTERCEPT_MOD")); // } // else // { // testSpyIntercepted(plot()->getOwnerINLINE(), GC.getDefineINT("ESPIONAGE_SPY_INTERCEPT_MOD")); // } // } // } // 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()) // { // if (isAlwaysHeal()) // { // doHeal(); // } // } // else // { // if (isHurt()) // { // doHeal(); // } // if (!isCargo()) // { // changeFortifyTurns(1); // } // } //FfH:End Modify changeImmobileTimer(-1); setMadeAttack(false); setMadeInterception(false); setReconPlot(NULL); setMoves(0); /*************************************************************************************************/ /** BETTER AI (Choose Groupflag) Sephi **/ /** **/ /** **/ /*************************************************************************************************/ if (!GET_PLAYER(getOwnerINLINE()).isHuman()) { if (!isBarbarian()) { if (AI_getGroupflag()==GROUPFLAG_NONE) { AI_chooseGroupflag(); } } } /*************************************************************************************************/ /** END **/ /*************************************************************************************************/ } 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); } } changeMoves(GC.getMOVE_DENOMINATOR()); 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; //FfH: Modified by Kael 01/14/2009 // int iAttackerStrength = currCombatStr(NULL, NULL, &cdAttackerDetails); // int iAttackerFirepower = currFirepower(NULL, NULL); int iAttackerStrength = currCombatStr(NULL, pDefender, &cdAttackerDetails); int iAttackerFirepower = currFirepower(NULL, pDefender); //FfH: End Modify int iDefenderStrength; int iAttackerDamage; int iDefenderDamage; int iDefenderOdds; getDefenderCombatValues(*pDefender, pPlot, iAttackerStrength, iAttackerFirepower, iDefenderOdds, iDefenderStrength, iAttackerDamage, iDefenderDamage, &cdDefenderDetails); int iAttackerKillOdds = iDefenderOdds * (100 - withdrawalProbability()) / 100; //FfH: Modified by Kael 08/02/2008 // 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)); // gDLL->getEventReporterIFace()->genericEvent("combatLogCalc", pyArgsCD.makeFunctionArgs()); // } if(GC.getUSE_COMBAT_RESULT_CALLBACK()) { if (isHuman() || pDefender->isHuman()) { 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()); } } //FfH: End Modify collateralCombat(pPlot, pDefender); while (true) { if (GC.getGameINLINE().getSorenRandNum(GC.getDefineINT("COMBAT_DIE_SIDES"), "Combat") < iDefenderOdds) { if (getCombatFirstStrikes() == 0) { if (getDamage() + iAttackerDamage >= maxHitPoints() && GC.getGameINLINE().getSorenRandNum(100, "Withdrawal") < withdrawalProbability()) { flankingStrikeCombat(pPlot, iAttackerStrength, iAttackerFirepower, iAttackerKillOdds, iDefenderDamage, pDefender); changeExperience(GC.getDefineINT("EXPERIENCE_FROM_WITHDRAWL"), pDefender->maxXPValue(), true, pPlot->getOwnerINLINE() == getOwnerINLINE(), !pDefender->isBarbarian()); //FfH Promotions: Added by Kael 08/12/2007 setFleeWithdrawl(true); //FfH: End Add 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(); //FfH: Modified by Kael 08/02/2008 // if (isHuman() || pDefender->isHuman()) // { // CyArgsList pyArgs; // pyArgs.add(gDLL->getPythonIFace()->makePythonObject(&cdAttackerDetails)); // pyArgs.add(gDLL->getPythonIFace()->makePythonObject(&cdDefenderDetails)); // pyArgs.add(1); // pyArgs.add(iAttackerDamage); // gDLL->getEventReporterIFace()->genericEvent("combatLogHit", pyArgs.makeFunctionArgs()); // } if(GC.getUSE_COMBAT_RESULT_CALLBACK()) { 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()); } } //FfH: End Modify } } else { if (pDefender->getCombatFirstStrikes() == 0) { if (pDefender->getDamage() + iDefenderDamage >= pDefender->maxHitPoints()) { if (!pPlot->isCity()) { if (GC.getGameINLINE().getSorenRandNum(100, "Withdrawal") < pDefender->getWithdrawlProbDefensive()) { pDefender->setFleeWithdrawl(true); break; } } } //FfH: End Add 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()); //FfH: Added by Kael 05/27/2008 setMadeAttack(true); changeMoves(std::max(GC.getMOVE_DENOMINATOR(), pPlot->movementCost(this, plot()))); //FfH: End Add break; } 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(); //FfH: Modified by Kael 08/02/2008 // 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(GC.getUSE_COMBAT_RESULT_CALLBACK()) { 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()); } } //FfH: End Modify } } 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)"); //FfH: Added by Kael 07/30/2007 if (!isImmuneToDefensiveStrike()) { pDefender->doDefensiveStrike(this); } if (pDefender->isFear()) { if (!isImmuneToFear()) { int iChance = baseCombatStr() + 20 + getLevel() - pDefender->baseCombatStr() - pDefender->getLevel(); if (iChance < 4) { iChance = 4; } if (GC.getGameINLINE().getSorenRandNum(40, "Im afeared!") > iChance) { setMadeAttack(true); changeMoves(std::max(GC.getMOVE_DENOMINATOR(), pPlot->movementCost(this, plot()))); szBuffer = gDLL->getText("TXT_KEY_MESSAGE_IM_AFEARED", getNameKey()); gDLL->getInterfaceIFace()->addMessage(((PlayerTypes)getOwner()), false, GC.getDefineINT("EVENT_MESSAGE_TIME"), szBuffer, "AS2D_DISCOVERBONUS", MESSAGE_TYPE_MAJOR_EVENT, "Art/Interface/Buttons/Promotions/Fear.dds", (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), getX_INLINE(), getY_INLINE(), true, true); bFinish = true; } } } //FfH: End Add //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); 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); } //FfH Hidden Nationality: Modified by Kael 08/27/2007 // if (!m_pUnitInfo->isHiddenNationality() && !pDefender->getUnitInfo().isHiddenNationality()) if (!isHiddenNationality() && !pDefender->isHiddenNationality() && getDuration() == 0 && !m_pUnitInfo->isNoWarWeariness()) //FfH: End Modify { 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()); //FfH: Added by Kael 07/30/2007 pDefender->combatWon(this, false); //FfH: End Add // report event to Python, along with some other key state //FfH: Modified by Kael 08/02/2008 // CvEventReporter::getInstance().combatResult(pDefender, this); if(GC.getUSE_COMBAT_RESULT_CALLBACK()) { CvEventReporter::getInstance().combatResult(pDefender, this); } //FfH: End Modify } else if (pDefender->isDead()) { if (pDefender->isBarbarian()) { GET_PLAYER(getOwnerINLINE()).changeWinsVsBarbs(1); } //FfH Hidden Nationality: Modified by Kael 08/27/2007 // if (!m_pUnitInfo->isHiddenNationality() && !pDefender->getUnitInfo().isHiddenNationality()) if (!isHiddenNationality() && !pDefender->isHiddenNationality() && pDefender->getDuration() == 0 && !pDefender->getUnitInfo().isNoWarWeariness()) //FfH: End Modify { 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()); //FfH: Added by Kael 05/15/2007 combatWon(pDefender, true); //FfH: End Add // report event to Python, along with some other key state //FfH: Modified by Kael 08/02/2008 // CvEventReporter::getInstance().combatResult(this, pDefender); if(GC.getUSE_COMBAT_RESULT_CALLBACK()) { CvEventReporter::getInstance().combatResult(this, pDefender); } //FfH: End Modify bool bAdvance = false; if (isSuicide()) { kill(true); pDefender->kill(false); pDefender = NULL; } else { bAdvance = canAdvance(pPlot, ((pDefender->canDefend()) ? 1 : 0)); if (bAdvance) { if (!isNoCapture() //FfH: Added by Kael 11/14/2007 || GC.getUnitInfo((UnitTypes)pDefender->getUnitType()).getEquipmentPromotion() != NO_PROMOTION //FfH: End Add ) { pDefender->setCapturingPlayer(getOwnerINLINE()); } } pDefender->kill(false); pDefender = NULL; //FfH Fear: Added by Kael 07/30/2007 if (isFear() && pPlot->isCity() == false) { CvUnit* pLoopUnit; CLLNode<IDInfo>* pUnitNode; pUnitNode = pPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); if (pLoopUnit->isEnemy(getTeam())) { if (!pLoopUnit->isImmuneToFear()) { if (GC.getGameINLINE().getSorenRandNum(20, "Im afeared!") <= (baseCombatStr() + 10 - pLoopUnit->baseCombatStr())) { pLoopUnit->joinGroup(NULL); pLoopUnit->withdrawlToNearestValidPlot(false); } } } } } bAdvance = canAdvance(pPlot, 0); //FfH: End Add 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(); } else { //FfH Promotions: Modified by Kael 08/12/2007 // 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(); if (pDefender->isFleeWithdrawl()) { pDefender->joinGroup(NULL); pDefender->setFleeWithdrawl(false); pDefender->withdrawlToNearestValidPlot(true); //>>>>BUGFfH: Modified by Denev 10/14/2009 (0.41k) /* When defender fleed, attacker loses movement point as same as wining */ /* checkRemoveSelectionAfterAttack(); if (pPlot->getNumVisibleEnemyDefenders(this) == 0) { getGroup()->groupMove(pPlot, true, ((canAdvance(pPlot, 0)) ? this : NULL)); } */ if (canAdvance(pPlot, 0)) { getGroup()->groupMove(pPlot, true, this); } else { changeMoves(std::max(GC.getMOVE_DENOMINATOR(), pPlot->movementCost(this, plot()))); checkRemoveSelectionAfterAttack(); } //<<<<BUGFfH: End Modify getGroup()->clearMissionQueue(); szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_UNIT_FLED", pDefender->getNameKey(), getNameKey()); gDLL->getInterfaceIFace()->addMessage(pDefender->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_FLED", pDefender->getNameKey(), getNameKey()); gDLL->getInterfaceIFace()->addMessage(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()); } if (isFleeWithdrawl()) { joinGroup(NULL); setFleeWithdrawl(false); 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(); } //FfH: End Modify } } } 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); //FfH Promotions: Added by Kael 07/30/2007 iOurDefense *= getBetterDefenderThanPercent(); iOurDefense /= 100; iTheirDefense *= pDefender->getBetterDefenderThanPercent(); iTheirDefense /= 100; //FfH Promotions: End Add 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; /*************************************************************************************************/ /** ADDON (automatic Spellcasting) Sephi **/ /** **/ /** **/ /*************************************************************************************************/ case COMMAND_AUTOMATE_SPELL: if (canSpellAutomate(iData1)) { return true; } break; /*************************************************************************************************/ /** END **/ /*************************************************************************************************/ 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; //FfH Spell System: Added by Kael 07/23/2007 case COMMAND_CAST:{ if(canCast(iData1, bTestVisible)) { return true; } break; } //FfH: End Add 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; /*************************************************************************************************/ /** ADDON (automatic spellcasting) Sephi **/ /** **/ /** **/ /*************************************************************************************************/ case COMMAND_AUTOMATE_SPELL: if (getAutoSpellCast()==iData1) setAutoSpellCast(NO_SPELL); else setAutoSpellCast(iData1); break; /*************************************************************************************************/ /** END **/ /*************************************************************************************************/ 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; //FfH Spell System: Added by Kael 07/23/2007 case COMMAND_CAST:{ cast(iData1); break; } //FfH: End Add 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 (!bIgnoreRightOfPassage) { if (GET_TEAM(getTeam()).isOpenBorders(eTeam)) { return true; } } //FfH: Added by Kael 09/02/2007 (so hidden nationality units can enter all territories) if (isHiddenNationality()) { return true; } if (GET_TEAM(eTeam).isBarbarian()) // (so barbarians can enter player areas they are at peace with an vice versa) { return true; } if (GET_TEAM(getTeam()).isBarbarian()) { return true; } if (GET_PLAYER(getOwnerINLINE()).isDeclaringWar()) { if (GET_PLAYER(getOwnerINLINE()).getStateReligion() != NO_RELIGION) { if (GC.getReligionInfo(GET_PLAYER(getOwnerINLINE()).getStateReligion()).isSneakAttack()) { return true; } } } //FfH: End Add 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))) { //FfH: Modified by Kael 03/29/2009 // if (GET_TEAM(getTeam()).canDeclareWar(pPlot->getTeam())) if (isAlwaysHostile(pPlot) || GET_TEAM(getTeam()).canDeclareWar(pPlot->getTeam())) //FfH: End Modify { 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; } // Unit Capacity START bool CvUnit::validUnitForCost(const CvPlot* pPlot) const { if( isCargo() || !canDefend(pPlot) ) { return false; } return true; } bool CvUnit::hasMaxUnitPerTile(const CvPlot* pPlot) const { int iMaxUnit = pPlot->getUnitPlotCapacity(); int iFlyingMaxUnit = GC.getDefineINT("AIR_SPACE_CAPACITY"); int iFlyingUnitCost = 0; if( pPlot->isCity(true) ) { CvCity* pCity = pPlot->getPlotCity(); iFlyingMaxUnit = GC.getDefineINT("City_Unit_Capacity"); iFlyingMaxUnit += (GC.getDefineINT("CITY_POPULATION_CAPACITY_FACTOR") * ( pCity->getPopulation() / GC.getDefineINT("CITY_POPULATION_CAPACITY_DIVISOR") )); } int iLandUnitCost = 0; int iActualUnitWithCargo = UnitPlotCost(); //FFH Only START //Flying units are unaffacted by hills/features and improvements. iFlyingMaxUnit -= iMaxUnit; if( iFlyingMaxUnit < 0 ) { iFlyingMaxUnit = 0; } if( isFlying() ) { iFlyingUnitCost = UnitPlotCost(); } else { iLandUnitCost = UnitPlotCost(); } //FFH ONLY END //count up all the cost of a transport and its cargo. if( hasCargo() ) { std::vector<CvUnit*> aCargoUnits; getCargoUnits(aCargoUnits); for( uint i = 0; i < aCargoUnits.size(); i++ ) { if( aCargoUnits[i]->canDefend(pPlot) ) { iActualUnitWithCargo += GC.getUnitInfo(aCargoUnits[i]->getUnitType()).getUnitPlotCost(); } } } //Zero cost units can always move if( (iLandUnitCost == 0) && (iFlyingUnitCost == 0) ) { return false; } //Units which cant defend can have unlimited of if( !canDefend(pPlot) ) { return false; } //Units going into a transport can always do so long as there is space. //Also make sure it's not flying. if( (getDomainType() == DOMAIN_LAND) && (pPlot->isWater()) && !isFlying() ) { return false; } for ( int iNumberOfUnit = 0 ; iNumberOfUnit < pPlot->getNumUnits(); iNumberOfUnit++ ) { //Got through all units on plot and add the UnitPlotCost CvUnit* unitOnPlot = pPlot->getUnitByIndex(iNumberOfUnit); if( unitOnPlot->validUnitForCost(pPlot) ) { if( unitOnPlot->isFlying()) { iFlyingUnitCost += GC.getUnitInfo(unitOnPlot->getUnitType()).getUnitPlotCost(); // Get the UnitPlotcost from the Unit the pointer shows } else { iLandUnitCost += GC.getUnitInfo(unitOnPlot->getUnitType()).getUnitPlotCost(); // Get the UnitPlotcost from the Unit the pointer shows } } } //if(!pPlot->isCity(true)) { //Is Plot not a city if( isFlying() ) { iFlyingMaxUnit -= iFlyingUnitCost; if( iFlyingMaxUnit < 0 ) { iMaxUnit += iFlyingMaxUnit; } iMaxUnit -= iLandUnitCost; int result = iMaxUnit; if( result < 0 ) { return true; } return false; } else { iFlyingMaxUnit -= iFlyingUnitCost; if( iFlyingMaxUnit < 0 ) { iMaxUnit += iFlyingMaxUnit; } if( (iLandUnitCost) > (iMaxUnit) ){ return true; } return false; } } return false; } // Unit Capacity END 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; } } /* ########################################################### # VKs Plot Capacity - Start ########################################################### */ if ( (pPlot->getNumUnits() > 0) ) //only go through when there is a Unit on the Plot, and it's not attackable. //Plot have to be Land, because of Transporters. { if( !bAttack ) { if( hasMaxUnitPerTile(pPlot) == true ) { return false; } } else { if( pPlot->isFriendlyCity(*this, true) ) { if( hasMaxUnitPerTile(pPlot) == true ) { return false; } } } } /* ########################################################### # VKs Plot Capacity - End ########################################################### */ // 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; } } } } /************************************************************************************************/ /* UNOFFICIAL_PATCH 09/17/09 TC01 & jdog5000 */ /* */ /* Bugfix */ /************************************************************************************************/ /* original bts code else */ // always check terrain also /************************************************************************************************/ /* UNOFFICIAL_PATCH END */ /************************************************************************************************/ { 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() //FfH: Added by Kael 08/27/2007 (for boarding) && !(bAttack && isBoarding()) //FfH: End Add ) { 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; default: FAssert(false); break; } //FfH: Modified by Kael 08/04/2007 (So owned animals dont have limited movement) // if (isAnimal()) if (isAnimal() && isBarbarian()) //FfH: End Add { 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; } } 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; } } } } //FfH: Added by Kael 09/02/2007 if (pPlot->getFeatureType() != NO_FEATURE) { if (GC.getFeatureInfo((FeatureTypes)pPlot->getFeatureType()).getRequireResist() != NO_DAMAGE) { if (getDamageTypeResist((DamageTypes)GC.getFeatureInfo((FeatureTypes)pPlot->getFeatureType()).getRequireResist()) < GC.getDefineINT("FEATURE_REQUIRE_RESIST_AMOUNT")) { return false; } } } if (pPlot->isOwned()) { if (pPlot->getTeam() != getTeam()) { if (GET_PLAYER(pPlot->getOwnerINLINE()).getSanctuaryTimer() != 0) { return false; } } } if (getLevel() < pPlot->getMinLevel()) { return false; } if (pPlot->isMoveDisabledHuman()) { if (isHuman()) { return false; } } if (pPlot->isMoveDisabledAI()) { if (!isHuman()) { return false; } } //FfH: End Add 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); 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()); } } } } //FfH: Modified by Kael 08/02/2008 // CvEventReporter::getInstance().unitMove(pPlot, this, pOldPlot); if(GC.getUSE_ON_UNIT_MOVE_CALLBACK()) { CvEventReporter::getInstance().unitMove(pPlot, this, pOldPlot); } //FfH: End Modify } // 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: /************************************************************************************************/ /* BETTER_BTS_AI_MOD 06/02/09 jdog5000 */ /* */ /* Player Interface */ /************************************************************************************************/ /** BTS orig if ((!canFight() && (getDomainType() != DOMAIN_SEA)) || (getDomainType() == DOMAIN_AIR) || (getDomainType() == DOMAIN_IMMOBILE)) { return false; } **/ // Enable exploration for air units if ((!canFight() && (getDomainType() != DOMAIN_SEA) && (getDomainType() != DOMAIN_AIR)) || (getDomainType() == DOMAIN_IMMOBILE)) { return false; } if( getDomainType() == DOMAIN_AIR && !canRecon(NULL) ) { return false; } /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ break; case AUTOMATE_RELIGION: if (AI_getUnitAIType() != UNITAI_MISSIONARY) { return false; } break; /*************************************************************************************************/ /** ADDON (automatic terraforming) Sephi **/ /** Rewritten by Kael 09/19/2009 **/ /** **/ /*************************************************************************************************/ case AUTOMATE_TERRAFORMING: if (!isTerraformer()) { return false; } break; /*************************************************************************************************/ /** END **/ /*************************************************************************************************/ default: FAssert(false); break; } return true; } /*************************************************************************************************/ /** ADDON (New Functions) Sephi **/ /** **/ /** **/ /*************************************************************************************************/ bool CvUnit::canSpellAutomate(int spell) { if (!GET_PLAYER(this->getOwnerINLINE()).isHuman()) { return false; } if (!GC.getSpellInfo((SpellTypes)spell).isAllowAuto()) { return false; } if (GET_PLAYER(getOwnerINLINE()).getDisableSpellcasting() > 0) { return false; } int currentspell=getAutoSpellCast(); if (currentspell!=NO_SPELL) { if (spell!=currentspell) { return false; } else { return true; } } bool bvalid=true; if (!isHasPromotion((PromotionTypes)GC.getSpellInfo((SpellTypes)spell).getPromotionPrereq1())) { bvalid=false; } if (!isHasPromotion((PromotionTypes)GC.getSpellInfo((SpellTypes)spell).getPromotionPrereq2())) { bvalid=false; } if ((UnitTypes)GC.getSpellInfo((SpellTypes)spell).getUnitPrereq()!=NO_UNIT) { if (getUnitType()!=(UnitTypes)GC.getSpellInfo((SpellTypes)spell).getUnitPrereq()) { bvalid=false; } } if ((UnitClassTypes)GC.getSpellInfo((SpellTypes)spell).getUnitClassPrereq()!=NO_UNITCLASS) { if (getUnitClassType()!=(UnitClassTypes)GC.getSpellInfo((SpellTypes)spell).getUnitClassPrereq()) { bvalid=false; } } if ((CivilizationTypes)GC.getSpellInfo((SpellTypes)spell).getCivilizationPrereq()!=NO_CIVILIZATION) { if (getCivilizationType()!=(CivilizationTypes)GC.getSpellInfo((SpellTypes)spell).getCivilizationPrereq()) { bvalid=false; } } if (GC.getSpellInfo((SpellTypes)spell).getBuildingClassOwnedPrereq()!=NO_BUILDINGCLASS) { if (GET_PLAYER(getOwnerINLINE()).getBuildingClassCount((BuildingClassTypes)GC.getSpellInfo((SpellTypes)spell).getBuildingClassOwnedPrereq())==0) { bvalid=false; } } if ((ReligionTypes)GC.getSpellInfo((SpellTypes)spell).getReligionPrereq()!=NO_RELIGION) { if (getReligion()!=(ReligionTypes)GC.getSpellInfo((SpellTypes)spell).getReligionPrereq()) { bvalid=false; } } if ((ReligionTypes)GC.getSpellInfo((SpellTypes)spell).getStateReligionPrereq()!=NO_RELIGION) { if (getReligion()!=(ReligionTypes)GC.getSpellInfo((SpellTypes)spell).getStateReligionPrereq()) { bvalid=false; } } return bvalid; } /*************************************************************************************************/ /** END **/ /*************************************************************************************************/ void CvUnit::automate(AutomateTypes eAutomate) { if (!canAutomate(eAutomate)) { return; } getGroup()->setAutomateType(eAutomate); } bool CvUnit::canScrap() const { if (plot()->isFighting()) { return false; } //FfH: Added by Kael 11/06/2007 if (GET_PLAYER(getOwnerINLINE()).getTempPlayerTimer() > 0) { return false; } if (m_pUnitInfo->getEquipmentPromotion() != NO_PROMOTION) { return false; } //FfH: End Add return true; } void CvUnit::scrap() { if (!canScrap()) { return; } //FfH: Added by Kael 11/04/2007 for (int iI = 0; iI < GC.getNumPromotionInfos(); iI++) { if (isHasPromotion((PromotionTypes)iI)) { if (GC.getPromotionInfo((PromotionTypes)iI).getBetrayalChance() != 0) { betray(BARBARIAN_PLAYER); } } } //FfH: End Add kill(true); } bool CvUnit::canGift(bool bTestVisible, bool bTestTransport) { //FfH: Added by Kael 04/22/2008 (to disable gifting) return false; //FfH: End Add 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; } } //FfH: Added by Kael 11/06/2007 if (GET_PLAYER(getOwnerINLINE()).getTempPlayerTimer() > 0) { return false; } //FfH: End Add 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; } /************************************************************************************************/ /* UNOFFICIAL_PATCH 10/30/09 Mongoose & jdog5000 */ /* */ /* Bugfix */ /************************************************************************************************/ // From Mongoose SDK if (isCargo()) { return false; } /************************************************************************************************/ /* UNOFFICIAL_PATCH END */ /************************************************************************************************/ if (getCargo() > 0) { return false; } if (pUnit->isCargo()) { return false; } if (!(pUnit->cargoSpaceAvailable(getSpecialUnitType(), getDomainType()))) { return false; } if (!(pUnit->atPlot(pPlot))) { return false; } //FfH Hidden Nationality: Modified by Kael 08/27/2007 // if (!m_pUnitInfo->isHiddenNationality() && pUnit->getUnitInfo().isHiddenNationality()) if (isHiddenNationality() != pUnit->isHiddenNationality()) //FfH: End Modify { return false; } if (NO_SPECIALUNIT != getSpecialUnitType()) { if (GC.getSpecialUnitInfo(getSpecialUnitType()).isCityLoad()) { if (!pPlot->isCity(true, getTeam())) { return false; } } } 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: /************************************************************************************************/ /* UNOFFICIAL_PATCH 10/30/09 Mongoose & jdog5000 */ /* */ /* Bugfix */ /************************************************************************************************/ /* original bts code if (pPlot->isWater()) */ // From Mongoose SDK if (pPlot->isWater() && !canMoveAllTerrain()) { return true; } /************************************************************************************************/ /* UNOFFICIAL_PATCH END */ /************************************************************************************************/ 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; } } } } if( hasMaxUnitPerTile(&kPlot) ) { 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; } if (isWaiting()) { return false; } if (healRate(pPlot) <= 0) { return false; } 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; //FfH: Added by Kael 11/05/2008 if (GC.getGameINLINE().isOption(GAMEOPTION_NO_HEALING_FOR_HUMANS)) { if (isHuman()) { if (isAlive()) { return 0; } } } //FfH: End Add pCity = pPlot->getPlotCity(); iTotalHeal = 0; if (pPlot->isCity(true, getTeam())) { iTotalHeal += GC.getDefineINT("CITY_HEAL_RATE") + (GET_TEAM(getTeam()).isFriendlyTerritory(pPlot->getTeam()) ? getExtraFriendlyHeal() : getExtraNeutralHeal()); if (pCity && !pCity->isOccupation()) { iTotalHeal += pCity->getHealRate(); } } else { if (!GET_TEAM(getTeam()).isFriendlyTerritory(pPlot->getTeam())) { if (isEnemy(pPlot->getTeam(), pPlot)) { iTotalHeal += (GC.getDefineINT("ENEMY_HEAL_RATE") + getExtraEnemyHeal()); //FfH Mana Effects: Added by Kael 08/21/2007 if (pPlot->getOwnerINLINE() != NO_PLAYER) { iTotalHeal += GET_PLAYER(pPlot->getOwnerINLINE()).getHealChangeEnemy(); } //FfH: End Add } else { iTotalHeal += (GC.getDefineINT("NEUTRAL_HEAL_RATE") + getExtraNeutralHeal()); } } else { iTotalHeal += (GC.getDefineINT("FRIENDLY_HEAL_RATE") + getExtraFriendlyHeal()); //FfH Mana Effects: Added by Kael 08/21/2007 iTotalHeal += GET_PLAYER(getOwnerINLINE()).getHealChange(); //FfH: End Add } } // 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 //FfH: Added by Kael 10/29/2007 if (pPlot->getImprovementType() != NO_IMPROVEMENT) { iTotalHeal += GC.getImprovementInfo((ImprovementTypes)pPlot->getImprovementType()).getHealRateChange(); } if (iTotalHeal < 0) { iTotalHeal = 0; } //FfH: End Add 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() { changeDamage(-(healRate(plot()))); } 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); 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() / 2); setMadeAttack(true); 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 { if (pTargetPlot->getImprovementType() == NO_IMPROVEMENT) { return false; } if (GC.getImprovementInfo(pTargetPlot->getImprovementType()).isPermanent()) { return false; } if (GC.getImprovementInfo(pTargetPlot->getImprovementType()).getAirBombDefense() == -1) { return false; } } 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); } if (!isEnemy(pPlot->getTeam())) { return false; } if (interceptTest(pPlot)) { return true; } pCity = pPlot->getPlotCity(); if (pCity != NULL) { pCity->changeDefenseModifier(-airBombCurrRate()); 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 { 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); } 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()); } } } setReconPlot(pPlot); setMadeAttack(true); changeMoves(GC.getMOVE_DENOMINATOR()); 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(); } pBombardCity->changeDefenseModifier(-(bombardRate() * std::max(0, 100 + iBombardModifier)) / 100); setMadeAttack(true); changeMoves(GC.getMOVE_DENOMINATOR()); 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 (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); } //FfH: Added by Kael 08/30/2007 if (isSuicide()) { kill(true); } //FfH: End Add return true; } bool CvUnit::canPillage(const CvPlot* pPlot) const { if (!(m_pUnitInfo->isPillage())) { return false; } if (pPlot->isCity()) { return false; } if (pPlot->getImprovementType() == NO_IMPROVEMENT) { 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; } //FfH: Added by Kael 03/24/2009 if (isBarbarian()) { if (pPlot->getImprovementType() != NO_IMPROVEMENT) { if (GC.getImprovementInfo(pPlot->getImprovementType()).getSpawnUnitType() != NO_UNIT) { return false; } } } //FfH: End Add 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; } } if (pPlot->getImprovementType() != NO_IMPROVEMENT) { 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) { //FfH Traits: Added by Kale 08/02/2007 iPillageGold += (iPillageGold * GET_PLAYER(getOwnerINLINE()).getPillagingGold()) / 100; //FfH: End Add 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??? } changeMoves(GC.getMOVE_DENOMINATOR()); 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()); } //FfH: Added by Kael 03/02/2009 for (int iI = 0; iI < GC.getNumPromotionInfos(); iI++) { if (isHasPromotion((PromotionTypes)iI)) { if (GC.getPromotionInfo((PromotionTypes)iI).isRemovedByCombat()) { setHasPromotion(((PromotionTypes)iI), false); } } } //FfH: End Add return true; } bool CvUnit::canPlunder(const CvPlot* pPlot, bool bTestVisible) const { 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()) { 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; } //FfH: Added by Kael 05/06/2010 if (pPlot->isFoundDisabled()) { return false; } if (isHasCasted()) { return false; } //FfH: End Add return true; } bool CvUnit::found() { if (!canFound(plot())) { return false; } if (GC.getGameINLINE().getActivePlayer() == getOwnerINLINE()) { gDLL->getInterfaceIFace()->lookAt(plot()->getPoint(), CAMERALOOKAT_NORMAL); } /*************************************************************************************************/ /** BETTER AI (Use Patrol for CityDefense) Sephi **/ /** **/ /** **/ /*************************************************************************************************/ if (!isHuman()) { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; pUnitNode = getGroup()->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = plot()->nextUnitNode(pUnitNode); if (pLoopUnit!=NULL) { if(pLoopUnit!=this && pLoopUnit->AI_getUnitAIType()==UNITAI_COUNTER) { if(pLoopUnit->isUnitAllowedPermDefense()) { pLoopUnit->joinGroup(NULL); pLoopUnit->AI_setGroupflag(GROUPFLAG_PERMDEFENSE_NEW); pLoopUnit->setOriginPlot(NULL); pLoopUnit->AI_setUnitAIType(UNITAI_CITY_DEFENSE); } else { pLoopUnit->joinGroup(NULL); pLoopUnit->setOriginPlot(NULL); } } } } } /*************************************************************************************************/ /** END **/ /*************************************************************************************************/ 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; /************************************************************************************************/ /* UNOFFICIAL_PATCH 08/19/09 jdog5000 */ /* */ /* Efficiency */ /************************************************************************************************/ /* orginal bts code 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; } } */ // UP efficiency: Moved below faster calls /************************************************************************************************/ /* UNOFFICIAL_PATCH END */ /************************************************************************************************/ 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; } } } } /************************************************************************************************/ /* UNOFFICIAL_PATCH 08/19/09 jdog5000 */ /* */ /* Efficiency */ /************************************************************************************************/ 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; } } /************************************************************************************************/ /* UNOFFICIAL_PATCH END */ /************************************************************************************************/ 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) { //FfH: Modified by Kael 10/04/2008 // pCity->setHasReligion(eReligion, true, true, false); if (GC.getGameINLINE().isReligionFounded(eReligion)) { pCity->setHasReligion(eReligion, true, true, false); } else { pCity->setHasReligion(eReligion, true, true, false); GC.getGameINLINE().setHolyCity(eReligion, pCity, true); GC.getGameINLINE().setReligionSlotTaken(eReligion, true); } //FfH: End Modify 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; //FfH: Added by Kael 10/21/2007 (So that corporations can be made to not require bonuses) if (GC.getCorporationInfo(eCorporation).getPrereqBonus(0) == NO_BONUS) { bValid = true; } //FfH: End Add 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; } //FfH: Added by Kael 08/18/2008 if (isHasCasted()) { return false; } //FfH: End Add 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; } //FfH: Added by Kael 08/18/2008 if (isHasCasted()) { return false; } //FfH: End Add 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); } //FfH: Added by Kael 08/18/2008 if (isHasCasted()) { return 0; } //FfH: End Add 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; //FfH: Added by Kael 08/18/2008 if (isHasCasted()) { return 0; } //FfH: End Add 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; //FfH: Added by Kael 08/18/2008 if (isHasCasted()) { return 0; } //FfH: End Add 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; //FfH: Added by Kael 08/18/2008 if (isHasCasted()) { return 0; } //FfH: End Add 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; } 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 { if (testSpyIntercepted(eTargetPlayer, GC.getEspionageMissionInfo(eMission).getDifficultyMod())) { return false; } if (GET_PLAYER(getOwnerINLINE()).doEspionageMission(eMission, eTargetPlayer, plot(), iData, this)) { if (plot()->isActiveVisible(false)) { NotifyEntity(MISSION_ESPIONAGE); } if (!testSpyIntercepted(eTargetPlayer, GC.getDefineINT("ESPIONAGE_SPY_MISSION_ESCAPE_MOD"))) { setFortifyTurns(0); setMadeAttack(true); finishMoves(); 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); } } 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; } /*************************************************************************************************/ /** ADDON (stop automated workers from building forts) Sephi **/ /** **/ /** **/ /*************************************************************************************************/ if (isAutomated()) { if (eBuild == GC.getDefineINT("BUILD_FORT")) { return false; } } /*************************************************************************************************/ /** END **/ /*************************************************************************************************/ 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; } //FfH Units: Added by Kael 08/04/2007 if (getFreePromotionPick() > 0) { return true; } //FfH: End Add 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(); } } //FfH Units: Modified by Kael 08/04/2007 // if (!GC.getPromotionInfo(ePromotion).isLeader()) if ((!GC.getPromotionInfo(ePromotion).isLeader()) && getFreePromotionPick() == 0) //FfH: End Modify { changeLevel(1); //changeDamage(-(getDamage() / 2)); int iHealDamage = 0; iHealDamage = (getDamage() * GC.getDefineINT("PROMOTIONS_HEAL_PERCENTAGE_DAMAGE")) / 100; changeDamage(-iHealDamage); //PROMOTIONS_HEAL_PERCENTAGE } //FfH: Added by Kael 01/09/2008 if (getFreePromotionPick() > 0) { changeFreePromotionPick(-1); } //FfH: End Add 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; } 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"); iPrice += (std::max(0, (GET_PLAYER(getOwnerINLINE()).getProductionNeeded(eUnit) - GET_PLAYER(getOwnerINLINE()).getProductionNeeded(getUnitType()))) * GC.getDefineINT("UNIT_UPGRADE_COST_PER_PRODUCTION")); 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; //FfH Traits: Added by Kael 08/02/2007 iPrice += (iPrice * GET_PLAYER(getOwnerINLINE()).getUpgradeCostModifier()) / 100; //FfH: End Add 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; } } //FfH Units: Added by Kael 05/24/2008 if (getLevel() < GC.getUnitInfo(eUnit).getMinLevel()) { if (isHuman() || !GC.getGameINLINE().isOption(GAMEOPTION_AI_NO_MINIMUM_LEVEL)) { return false; } } if (GC.getUnitInfo(eUnit).isDisableUpgradeTo()) { return false; } if (GET_PLAYER(getOwnerINLINE()).isUnitClassMaxedOut((UnitClassTypes)(GC.getUnitInfo(eUnit).getUnitClassType()))) { return false; } if (!isHuman()) //added so the AI wont spam UNTIAI_MISSIONARY priests by upgradign disciples { if (AI_getUnitAIType() == UNITAI_MISSIONARY && getLevel() < 2) { return false; } } //FfH: End Add /*************************************************************************************************/ /** BETTER AI (Smarter Upgrading) Sephi 0.41k **/ /** **/ /** **/ /*************************************************************************************************/ if (!isHuman()) { if((AI_getGroupflag()==GROUPFLAG_PERMDEFENSE) || (AI_getGroupflag()==GROUPFLAG_PERMDEFENSE_NEW)) { if(GC.getUnitInfo(eUnit).isNoDefensiveBonus()) { return false; } } } /*************************************************************************************************/ /** END **/ /*************************************************************************************************/ 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); //FfH: Modified by Kael 05/09/2008 // if (GC.getCivilizationInfo(kPlayer.getCivilizationType()).getCivilizationUnits(kUnitInfo.getUnitClassType()) != eUnit) // { // return false; // } if (m_pUnitInfo->getUpgradeCiv() == NO_CIVILIZATION) { if (!kPlayer.isAssimilation()) { if (GC.getCivilizationInfo(kPlayer.getCivilizationType()).getCivilizationUnits(kUnitInfo.getUnitClassType()) != eUnit) { return false; } } } else { if (GC.getCivilizationInfo((CivilizationTypes)m_pUnitInfo->getUpgradeCiv()).getCivilizationUnits(kUnitInfo.getUnitClassType()) != eUnit) { return false; } } //FfH: End Modify 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? //FfH Units: Modified by Kael 05/24/2008 // if (pLoopCity->canTrain(eUnit, false, false, true)) if (pLoopCity->canUpgrade(eUnit, false, false, true)) //FfH: End Modify { // 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) /*************************************************************************************************/ /** SPEED TWEAK Sephi **/ /** We only check for cities not that far away **/ /** **/ /*************************************************************************************************/ /** Start Orig Code if (!generatePath(pLoopCity->plot(), 0, true)) { iValue *= 16; } /** End Orig Code **/ int XDist=pLoopCity->plot()->getX_INLINE() - plot()->getX_INLINE(); int YDist=pLoopCity->plot()->getY_INLINE() - plot()->getY_INLINE(); if (((XDist*XDist)+(YDist*YDist))<10) { if (!generatePath(pLoopCity->plot(), 0, true)) { iValue *= 16; } } else { iValue *= 16; } /*************************************************************************************************/ /** END **/ /*************************************************************************************************/ 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) //FfH Units: Modified by Kael 08/07/2007 // if (pClosestCity->canTrain(eUnit, false, false, true)) if (kPlayer.isAssimilation() && (m_pUnitInfo->getUpgradeCiv() == NO_CIVILIZATION)) { if (GC.getCivilizationInfo(pClosestCity->getCivilizationType()).getCivilizationUnits(kUnitInfo.getUnitClassType()) != eUnit && GC.getCivilizationInfo(kPlayer.getCivilizationType()).getCivilizationUnits(kUnitInfo.getUnitClassType()) != eUnit) { return false; } } if (pClosestCity->canUpgrade(eUnit, false, false, true)) //FfH: End Add { // 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))); //FfH: Modified by Kael 04/18/2009 // pUpgradeUnit = GET_PLAYER(getOwnerINLINE()).initUnit(eUnit, getX_INLINE(), getY_INLINE(), AI_getUnitAIType()); UnitAITypes eUnitAI = AI_getUnitAIType(); if (eUnitAI == UNITAI_MISSIONARY) { ReligionTypes eReligion = GET_PLAYER(getOwnerINLINE()).getStateReligion(); if (eReligion == NO_RELIGION || GC.getUnitInfo(eUnit).getReligionSpreads(eReligion) == 0) { eUnitAI = UNITAI_RESERVE; } } pUpgradeUnit = GET_PLAYER(getOwnerINLINE()).initUnit(eUnit, getX_INLINE(), getY_INLINE(), eUnitAI); //FfH: End Modify FAssertMsg(pUpgradeUnit != NULL, "UpgradeUnit is not assigned a valid value"); pUpgradeUnit->joinGroup(getGroup()); pUpgradeUnit->convert(this); pUpgradeUnit->finishMoves(); if (pUpgradeUnit->getLeaderUnitType() == NO_UNIT) { if (pUpgradeUnit->getExperience() > GC.getDefineINT("MAX_EXPERIENCE_AFTER_UPGRADE")) { pUpgradeUnit->setExperience(GC.getDefineINT("MAX_EXPERIENCE_AFTER_UPGRADE")); } } } 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 { //FfH: Modified by Kael 06/20/2010 // return ((InvisibleTypes)(m_pUnitInfo->getInvisibleType())); if (m_iInvisibleType == NO_INVISIBLE) { if (plot() != NULL) { if (plot()->isOwned()) { if (GET_PLAYER(plot()->getOwnerINLINE()).isHideUnits() && !isIgnoreHide()) { if (plot()->getTeam() == getTeam()) { if (!plot()->isCity()) { return ((InvisibleTypes)GC.getDefineINT("INVISIBLE_TYPE")); } } } } } } if (isInvisibleFromPromotion()) { if (m_pUnitInfo->getEquipmentPromotion() != NO_PROMOTION) { return ((InvisibleTypes)2); } else { return ((InvisibleTypes)GC.getDefineINT("INVISIBLE_TYPE")); } } return ((InvisibleTypes)m_iInvisibleType); //FfH: End Modify } int CvUnit::getNumSeeInvisibleTypes() const { //FfH: Added by Kael 12/07/2008 if (isSeeInvisible()) { return 1; } //FfH: End Add return m_pUnitInfo->getNumSeeInvisibleTypes(); } InvisibleTypes CvUnit::getSeeInvisibleType(int i) const { //FfH: Added by Kael 12/07/2008 if (isSeeInvisible()) { return ((InvisibleTypes)GC.getDefineINT("INVISIBLE_TYPE")); } //FfH: End Add return (InvisibleTypes)(m_pUnitInfo->getSeeInvisibleType(i)); } 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 { //FfH: Modified by Kael 08/10/2007 // return (GC.getDefineINT("UNIT_VISIBILITY_RANGE") + getExtraVisibilityRange()); int iRange = GC.getDefineINT("UNIT_VISIBILITY_RANGE"); iRange += getExtraVisibilityRange(); if (plot()->getImprovementType() != NO_IMPROVEMENT) { iRange += GC.getImprovementInfo((ImprovementTypes)plot()->getImprovementType()).getVisibilityChange(); } return iRange; //FfH: End Modify } 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 { return std::max(0, (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(); //FfH: Added by Kael 08/13/2008 iRate += getWorkRateModify(); //FfH: End Add 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 { //FfH Promotions: Added by Kael 08/14/2007 if (m_iOnlyDefensive > 0) { return true; } //FfH: End Add return m_pUnitInfo->isOnlyDefensive(); } bool CvUnit::isNoCapture() const { //FfH: Added by Kael 10/25/2007 if (isHiddenNationality()) { return true; } //FfH: End Add 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 { //FfH Damage Types: Modified by Kael 10/26/2007 // return m_iBaseCombat; int iStr = m_iBaseCombat + m_iTotalDamageTypeCombat; if (iStr < 0) { iStr = 0; } return iStr; //FfH: End Add } //FfH Defense Str: Added by Kael 10/26/2007 void CvUnit::setBaseCombatStrDefense(int iCombat) { m_iBaseCombatDefense = iCombat; } int CvUnit::baseCombatStrDefense() const { int iStr = m_iBaseCombatDefense + m_iTotalDamageTypeCombat; if (iStr < 0) { iStr = 0; } return iStr; } //FfH: End Add // 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 /**** Dexy - Surround and Destroy START ****/ // pPlot == NULL, pAttacker valid for combat when this is the defender, attacker is just surrounding us (then defender gets no plot defensive bonuses) /**** Dexy - Surround and Destroy END ****/ // 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) /**** Dexy - Surround and Destroy START ****/ int CvUnit::maxCombatStr(const CvPlot* pPlot, const CvUnit* pAttacker, CombatDetails* pCombatDetails, bool bSurroundedModifier) const // OLD CODE // int CvUnit::maxCombatStr(const CvPlot* pPlot, const CvUnit* pAttacker, CombatDetails* pCombatDetails) const /**** Dexy - Surround and Destroy END ****/ { int iCombat; //FfH Damage Types: Added by Kael 09/02/2007 const CvUnit* pDefender = NULL; if (pPlot == NULL) { if (pAttacker != NULL) { pDefender = pAttacker; pAttacker = NULL; } } //FfH: End Add 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(); } //FfH Defense Str: Modified by Kael 08/18/2007 // if (baseCombatStr() == 0) // { // return 0; // } int iStr; if ((pAttacker == NULL && pPlot == NULL) || pAttacker == this) { iStr = baseCombatStr(); } else { iStr = baseCombatStrDefense(); } if (iStr == 0) { return 0; } //FfH: End Modify 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) { //FfH: Modified by Kael 07/31/2008 // pCombatDetails->iAIBarbarianCombatModifierTB = iExtraModifier; pCombatDetails->iAIBarbarianCombatModifierAB = iExtraModifier; //FfH: End Modify } } } } // 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 /************************************************************************************************/ /* UNOFFICIAL_PATCH 09/20/09 jdog5000 */ /* */ /* Bugfix */ /************************************************************************************************/ /* original code if (pAttacker != NULL) */ if (pAttacker != NULL && pAttackedPlot != NULL) /************************************************************************************************/ /* UNOFFICIAL_PATCH END */ /************************************************************************************************/ { 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"); //FfH Promotions: Added by Kael 08/13/2007 for (int iJ=0;iJ<GC.getNumPromotionInfos();iJ++) { if ((isHasPromotion((PromotionTypes)iJ)) && (GC.getPromotionInfo((PromotionTypes)iJ).getPromotionCombatMod()>0)) { if (pAttacker->isHasPromotion((PromotionTypes)GC.getPromotionInfo((PromotionTypes)iJ).getPromotionCombatType())) { iModifier += GC.getPromotionInfo((PromotionTypes)iJ).getPromotionCombatMod(); } } if ((pAttacker->isHasPromotion((PromotionTypes)iJ)) && (GC.getPromotionInfo((PromotionTypes)iJ).getPromotionCombatMod() > 0)) { if (isHasPromotion((PromotionTypes)GC.getPromotionInfo((PromotionTypes)iJ).getPromotionCombatType())) { iModifier -= GC.getPromotionInfo((PromotionTypes)iJ).getPromotionCombatMod(); } } } if (GC.getGameINLINE().getGlobalCounter() * getCombatPercentGlobalCounter() / 100 != 0) { iModifier += GC.getGameINLINE().getGlobalCounter() * getCombatPercentGlobalCounter() / 100; } if (GC.getGameINLINE().getGlobalCounter() * pAttacker->getCombatPercentGlobalCounter() / 100 != 0) { iModifier -= GC.getGameINLINE().getGlobalCounter() * pAttacker->getCombatPercentGlobalCounter() / 100; } //FfH: End Add 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; } } /**** Dexy - Surround and Destroy START ****/ if (bSurroundedModifier) { // the stronger the surroundings -> decrease the iModifier more iExtraModifier = -pAttacker->surroundedDefenseModifier(pAttackedPlot, bAttackingUnknownDefender ? NULL : this); iTempModifier += iExtraModifier; } /**** Dexy - Surround and Destroy END ****/ // if we are attacking an unknown defender, then use the reverse of the modifier if (bAttackingUnknownDefender) { iModifier -= iTempModifier; } else { iModifier += iTempModifier; } } //FfH Defense Str: Modified by Kael 08/18/2007 // 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->iModifierTotal = iModifier; pCombatDetails->iBaseCombatStr = iStr; } iStr *= 100; if (pAttacker != NULL) { for (int iI = 0; iI < GC.getNumDamageTypeInfos(); iI++) { if (getDamageTypeCombat((DamageTypes) iI) != 0) { if (pAttacker->getDamageTypeResist((DamageTypes) iI) != 0) { iStr -= getDamageTypeCombat((DamageTypes) iI) * 100; iStr += getDamageTypeCombat((DamageTypes) iI) * (100 - pAttacker->getDamageTypeResist((DamageTypes) iI)); } } } } if (pDefender != NULL) { for (int iI = 0; iI < GC.getNumDamageTypeInfos(); iI++) { if (getDamageTypeCombat((DamageTypes) iI) != 0) { if (pDefender->getDamageTypeResist((DamageTypes) iI) != 0) { iStr -= getDamageTypeCombat((DamageTypes) iI) * 100; iStr += getDamageTypeCombat((DamageTypes) iI) * (100 - pDefender->getDamageTypeResist((DamageTypes) iI)); } } } } if (iModifier > 0) { iCombat = (iStr * (iModifier + 100)) / 100; } else { iCombat = ((iStr * 100) / (100 - iModifier)); } //FfH: End Modify 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); } /**** Dexy - Surround and Destroy START ****/ int CvUnit::currCombatStr(const CvPlot* pPlot, const CvUnit* pAttacker, CombatDetails* pCombatDetails, bool bSurroundedModifier) const { return ((maxCombatStr(pPlot, pAttacker, pCombatDetails, bSurroundedModifier) * currHitPoints()) / maxHitPoints()); } // OLD CODE // int CvUnit::currCombatStr(const CvPlot* pPlot, const CvUnit* pAttacker, CombatDetails* pCombatDetails) const // { // return ((maxCombatStr(pPlot, pAttacker, pCombatDetails) * currHitPoints()) / maxHitPoints()); // } /**** Dexy - Surround and Destroy END ****/ 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 { //FfH: Modified by Kael 10/31/2007 // return (baseCombatStr() > 0); if (baseCombatStr() == 0 && baseCombatStrDefense() == 0) { return false; } return true; //FfH: End Modify } bool CvUnit::canAttack() const { if (!canFight()) { return false; } if (isOnlyDefensive()) { return false; } //FfH: Added by Kael 04/25/2010 if (baseCombatStr() == 0) { return false; } if (getImmobileTimer() != 0) { return false; } //FfH: End Add 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; } } //FfH: Added by Kael 10/31/2007 if (baseCombatStrDefense() == 0) { return false; } //FfH: End Add 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 { //FfH: Modified by Kael 04/26/2008 // return m_pUnitInfo->getCombatLimit(); return m_iCombatLimit; //FfH: End Modify } 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) { /************************************************************************************************/ /* UNOFFICIAL_PATCH 10/30/09 Mongoose & jdog5000 */ /* */ /* Bugfix */ /************************************************************************************************/ /* original bts code if (!pPlot->isValidDomainForLocation(*this)) */ // From Mongoose SDK // Land units which are cargo cannot intercept if (!pPlot->isValidDomainForLocation(*this) || isCargo()) /************************************************************************************************/ /* UNOFFICIAL_PATCH END */ /************************************************************************************************/ { 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; } 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))); 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; } //FfH: Modified by Kael 10/26/2007 // return (getFortifyTurns() * GC.getFORTIFY_MODIFIER_PER_TURN()); int i = getFortifyTurns() * GC.getFORTIFY_MODIFIER_PER_TURN(); if (isDoubleFortifyBonus()) { i *= 2; } return i; //FfH: End Modify } 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 { //FfH: Modified by Kael 02/12/2009 // return m_pUnitInfo->getXPValueAttack(); int iXP = m_pUnitInfo->getXPValueAttack(); if (isAnimal() || isBarbarian()) { iXP = iXP * GC.getDefineINT("BARBARIAN_EXPERIENCE_MODIFIER") / 100; } return iXP; //FfH: End Modify } int CvUnit::defenseXPValue() const { //FfH: Modified by Kael 02/12/2009 // return m_pUnitInfo->getXPValueDefense(); int iXP = m_pUnitInfo->getXPValueDefense(); if (isAnimal() || isBarbarian()) { iXP = iXP * GC.getDefineINT("BARBARIAN_EXPERIENCE_MODIFIER") / 100; } return iXP; //FfH: End Modify } int CvUnit::maxXPValue() const { int iMaxValue; iMaxValue = MAX_INT; //FfH: Modified by Kael 02/12/2009 // if (isAnimal()) // { // iMaxValue = std::min(iMaxValue, GC.getDefineINT("ANIMAL_MAX_XP_VALUE")); // } // if (isBarbarian()) // { // iMaxValue = std::min(iMaxValue, GC.getDefineINT("BARBARIAN_MAX_XP_VALUE")); // } if (!::isWorldUnitClass(getUnitClassType())) { if (isAnimal()) { iMaxValue = std::min(iMaxValue, GC.getDefineINT("ANIMAL_MAX_XP_VALUE")); } if (isBarbarian()) { iMaxValue = std::min(iMaxValue, GC.getDefineINT("BARBARIAN_MAX_XP_VALUE")); } } //FfH: End Modify 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 { //FfH: Modifed by Kael 11/17/2007 // return m_pUnitInfo->isIgnoreBuildingDefense(); if (m_pUnitInfo->isIgnoreBuildingDefense()) { return true; } return m_iIgnoreBuildingDefense == 0 ? false : true; //FfH: End Modify } bool CvUnit::canMoveImpassable() const { //FfH Flying: Added by Kael 07/30/2007 if (isFlying()) { return true; } //FfH: End Add return m_pUnitInfo->isCanMoveImpassable(); } bool CvUnit::canMoveAllTerrain() const { //FfH Flying: Added by Kael 07/30/2007 if (isFlying() || isWaterWalking()) { return true; } //FfH: End Add return m_pUnitInfo->isCanMoveAllTerrain(); } bool CvUnit::flatMovementCost() const { //FfH Flying: Added by Kael 07/30/2007 if (isFlying()) { return true; } //FfH: End Add return m_pUnitInfo->isFlatMovementCost(); } bool CvUnit::ignoreTerrainCost() const { //FfH Flying: Added by Kael 07/30/2007 if (isFlying()) { return true; } //FfH: End Add 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; } //FfH: Added by Kael 04/11/2008 if (plot() != NULL) { if (plot()->isCity()) { if (getTeam() == plot()->getTeam()) { return false; } } if (plot()->isOwned()) { if (plot()->getTeam() != getTeam()) { if (GET_PLAYER(plot()->getOwnerINLINE()).isSeeInvisible()) { return false; } } if (plot()->getTeam() == getTeam()) { if (GET_PLAYER(plot()->getOwnerINLINE()).isHideUnits() && !isIgnoreHide()) { return true; } } } } //FfH: End Add if (alwaysInvisible()) { return true; } if (bCheckCargo && isCargo()) { return true; } if (getInvisibleType() == NO_INVISIBLE) { return false; } //FfH: Added by Kael 01/16/2009 if (plot() == NULL) { return false; } //FfH: End Add return !(plot()->isInvisibleVisible(eTeam, getInvisibleType())); } //FfH: Added by Kael 06/22/2010 bool CvUnit::isInvisibleInPlot(TeamTypes eTeam, const CvPlot* pPlot, bool bDebug, bool bCheckCargo) const { if (bDebug && GC.getGameINLINE().isDebugMode()) { return false; } if (getTeam() == eTeam) { return false; } if (pPlot != NULL) { if (pPlot->isCity()) { if (getTeam() == pPlot->getTeam()) { return false; } } if (pPlot->isOwned()) { if (pPlot->getTeam() != getTeam()) { if (GET_PLAYER(pPlot->getOwnerINLINE()).isSeeInvisible()) { return false; } } if (pPlot->getTeam() == getTeam()) { if (GET_PLAYER(pPlot->getOwnerINLINE()).isHideUnits() && !isIgnoreHide()) { return true; } } } } if (alwaysInvisible()) { return true; } if (bCheckCargo && isCargo()) { return true; } if (getInvisibleType() == NO_INVISIBLE) { return false; } if (pPlot == NULL) { return false; } return !(pPlot->isInvisibleVisible(eTeam, getInvisibleType())); } //FfH: End Add 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; } //FfH: Added by Kael 04/06/2009 if (getImmobileTimer() > 0) { return 0; } //FfH: End Add 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)); } /**** Dexy - Surround and Destroy START ****/ int CvUnit::surroundedDefenseModifier(const CvPlot *pPlot, const CvUnit *pDefender) const { CvPlot *pLoopPlot; DirectionTypes dtDirectionAttacker = directionXY(pPlot, plot()); int iExtraModifier = 0, iI; if( dtDirectionAttacker == NO_DIRECTION ) { return 0; } for (iI = 0; iI < NUM_DIRECTION_TYPES; iI++) { pLoopPlot = plotDirection(pPlot->getX_INLINE(), pPlot->getY_INLINE(), ((DirectionTypes)iI)); if ((pLoopPlot != NULL) && (pLoopPlot->isWater() == pPlot->isWater()) && (iI != dtDirectionAttacker)) { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; CvUnit* pBestUnit; int iBestCurrCombatStr, iLowestCurrCombatStr; pBestUnit = NULL; iBestCurrCombatStr = 0; iLowestCurrCombatStr = INT_MAX; pUnitNode = pLoopPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pLoopPlot->nextUnitNode(pUnitNode); if (pLoopUnit->getTeam() == getTeam()) { // if pDefender == null - use the last config of maxCombatStr() where pAttacker == this, else - use the pDefender to find the best attacker if (pDefender != NULL) { // pPlot == NULL -> defender gets no plot defense bonuses (hills, forest, fortify, etc.) against surrounding units (will have them for the attacker) int iTmpCurrCombatStr = pDefender->currCombatStr(NULL, pLoopUnit, NULL, false); if (iTmpCurrCombatStr < iLowestCurrCombatStr) { iLowestCurrCombatStr = iTmpCurrCombatStr; pBestUnit = pLoopUnit; } } else { int iTmpCurrCombatStr = pLoopUnit->currCombatStr(pPlot, pLoopUnit, NULL, false); if (iTmpCurrCombatStr > iBestCurrCombatStr) { iBestCurrCombatStr = iTmpCurrCombatStr; pBestUnit = pLoopUnit; } } } } double fAttDeffFactor = 0.0; if (pDefender != NULL) { if (pBestUnit != NULL) { fAttDeffFactor = ((double) pBestUnit->currCombatStr(pPlot, pBestUnit, NULL, false)) / iLowestCurrCombatStr; } } else { fAttDeffFactor = (double) iBestCurrCombatStr; } /* surrounding distance = 1, 2, 3 or 4; the bigger the better */ int iSurroundingDistance = abs(std::min(abs(iI - dtDirectionAttacker), abs(abs(iI - dtDirectionAttacker) - 8))); double fSurroundingDistanceFactor; switch (iSurroundingDistance) { case 1: fSurroundingDistanceFactor = GC.getDefineFLOAT("SAD_FACTOR_1"); break; case 2: fSurroundingDistanceFactor = GC.getDefineFLOAT("SAD_FACTOR_2"); break; case 3: fSurroundingDistanceFactor = GC.getDefineFLOAT("SAD_FACTOR_3"); break; case 4: fSurroundingDistanceFactor = GC.getDefineFLOAT("SAD_FACTOR_4"); break; } if (fAttDeffFactor == 1) { iExtraModifier += int(fSurroundingDistanceFactor); } else if (fAttDeffFactor != 0) { iExtraModifier += int(fSurroundingDistanceFactor * ((fAttDeffFactor - 1) * pow(abs(fAttDeffFactor - 1), -0.75) + 1)); } } } return std::min(GC.getDefineINT("SAD_MAX_MODIFIER"), iExtraModifier); } /**** Dexy - Surround and Destroy END ****/ 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; } //FfH: Added by Kael 06/20/2010 if (isAIControl()) { return false; } if (isHiddenNationality()) { return false; } pHeadUnit = pSelectionGroup->getHeadUnit(); if (pHeadUnit != NULL) { if (pHeadUnit->isHiddenNationality()) { return false; } if (pHeadUnit->isAIControl()) { return false; } } //FfH: End Add } 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) /*************************************************************************************************/ /** BETTER AI (Stop some groups from forceseperating) Sephi **/ /** **/ /** **/ /*************************************************************************************************/ // if (bWasHead) // { bool bValid = true; if (pSelectionGroup != NULL && pSelectionGroup->getHeadUnit()) { if (AI_getGroupflag() == GROUPFLAG_CONQUEST && pSelectionGroup->getHeadUnit()->AI_getGroupflag() == GROUPFLAG_CONQUEST) { bValid = false; } } if (pSelectionGroup!=NULL && pSelectionGroup->getHeadUnit()) { if (AI_getGroupflag()==GROUPFLAG_DEFENSE_NEW && pSelectionGroup->getHeadUnit()->AI_getGroupflag()==GROUPFLAG_DEFENSE_NEW) { bValid=false; } } if (bWasHead && bValid) { /*************************************************************************************************/ /** END **/ /*************************************************************************************************/ 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)) { //FfH: Modified by Kael 04/25/2010 // pLoopUnit->jumpToNearestValidPlot(); // can kill unit if (pLoopUnit->plot() != NULL) { if (!isInvisibleInPlot(pLoopUnit->getTeam(), pNewPlot, false)) { pLoopUnit->withdrawlToNearestValidPlot(true); // can kill unit } } //FfH: End Modify } else { //FfH Hidden Nationality: Modified by Kael 08/27/2007 // if (!m_pUnitInfo->isHiddenNationality() && !pLoopUnit->getUnitInfo().isHiddenNationality()) if (!isHiddenNationality() && !pLoopUnit->isHiddenNationality()) //FfH: End Modify { 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")); } //FfH: Modified by Kael 12/30/2207 // if (!isNoCapture()) // { // pLoopUnit->setCapturingPlayer(getOwnerINLINE()); // } if (!isNoCapture() || GC.getUnitInfo((UnitTypes)pLoopUnit->getUnitType()).getEquipmentPromotion() != NO_PROMOTION) { if (!pLoopUnit->isHiddenNationality()) { pLoopUnit->setCapturingPlayer(getOwnerINLINE()); } } //FfH: End Modify 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()))) { //FfH: Modified by Kael 04/19/2009 // GET_PLAYER(getOwnerINLINE()).changeNumOutsideUnits(-1); if (getDuration() == 0) { GET_PLAYER(getOwnerINLINE()).changeNumOutsideUnits(-1); } //FfH: End Modify } 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()))) { //FfH: Modified by Kael 04/19/2009 // GET_PLAYER(getOwnerINLINE()).changeNumOutsideUnits(1); if (getDuration() == 0) { GET_PLAYER(getOwnerINLINE()).changeNumOutsideUnits(1); } //FfH: End Modify } 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); } } //FfH Units: Added by Kael 11/10/2008 if (pNewPlot != NULL) { int iImprovement = pNewPlot->getImprovementType(); if (iImprovement != NO_IMPROVEMENT) { if (GC.getImprovementInfo((ImprovementTypes)iImprovement).getSpawnUnitType() != NO_UNIT) { if (!isHuman() || GC.getImprovementInfo((ImprovementTypes)iImprovement).isPermanent() == false) { if (atWar(getTeam(), GET_PLAYER(BARBARIAN_PLAYER).getTeam())) { if (isHuman()) { gDLL->getInterfaceIFace()->addMessage(getOwner(), false, GC.getDefineINT("EVENT_MESSAGE_TIME"), gDLL->getText("TXT_KEY_MESSAGE_LAIR_DESTROYED"), "AS2D_CITYRAZE", MESSAGE_TYPE_MAJOR_EVENT, GC.getImprovementInfo((ImprovementTypes)iImprovement).getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pNewPlot->getX(), pNewPlot->getY(), true, true); } pNewPlot->setImprovementType(NO_IMPROVEMENT); } } } } iImprovement = pNewPlot->getImprovementType(); // rechecking because the previous function may have deleted the improvement if (iImprovement != NO_IMPROVEMENT) { if (!CvString(GC.getImprovementInfo((ImprovementTypes)iImprovement).getPythonOnMove()).empty()) { if (pNewPlot->isPythonActive()) { CyUnit* pyUnit = new CyUnit(this); CyPlot* pyPlot = new CyPlot(pNewPlot); CyArgsList argsList; argsList.add(gDLL->getPythonIFace()->makePythonObject(pyUnit)); // pass in unit class argsList.add(gDLL->getPythonIFace()->makePythonObject(pyPlot)); // pass in plot class argsList.add(iImprovement);//the promotion # gDLL->getPythonIFace()->callFunction(PYSpellModule, "onMove", argsList.makeFunctionArgs()); //, &lResult delete pyUnit; // python fxn must not hold on to this pointer delete pyPlot; // python fxn must not hold on to this pointer } } } for (int iI = 0; iI < NUM_DIRECTION_TYPES; iI++) { pLoopPlot = plotDirection(pNewPlot->getX_INLINE(), pNewPlot->getY_INLINE(), ((DirectionTypes)iI)); if (pLoopPlot != NULL) { if (pLoopPlot->getImprovementType() != NO_IMPROVEMENT) { if (!CvString(GC.getImprovementInfo((ImprovementTypes)pLoopPlot->getImprovementType()).getPythonAtRange()).empty()) { if (pLoopPlot->isPythonActive()) { CyUnit* pyUnit = new CyUnit(this); CyPlot* pyPlot = new CyPlot(pLoopPlot); CyArgsList argsList; argsList.add(gDLL->getPythonIFace()->makePythonObject(pyUnit)); // pass in unit class argsList.add(gDLL->getPythonIFace()->makePythonObject(pyPlot)); // pass in plot class argsList.add(pLoopPlot->getImprovementType()); gDLL->getPythonIFace()->callFunction(PYSpellModule, "atRange", argsList.makeFunctionArgs()); //, &lResult delete pyUnit; // python fxn must not hold on to this pointer delete pyPlot; // python fxn must not hold on to this pointer } } } } } if (pNewPlot->getFeatureType() != NO_FEATURE) { if (!CvString(GC.getFeatureInfo((FeatureTypes)pNewPlot->getFeatureType()).getPythonOnMove()).empty()) { CyUnit* pyUnit = new CyUnit(this); CyPlot* pyPlot = new CyPlot(pNewPlot); CyArgsList argsList; argsList.add(gDLL->getPythonIFace()->makePythonObject(pyUnit)); // pass in unit class argsList.add(gDLL->getPythonIFace()->makePythonObject(pyPlot)); // pass in plot class argsList.add(pNewPlot->getFeatureType()); gDLL->getPythonIFace()->callFunction(PYSpellModule, "onMoveFeature", argsList.makeFunctionArgs()); //, &lResult delete pyUnit; // python fxn must not hold on to this pointer delete pyPlot; // python fxn must not hold on to this pointer } } if (pNewPlot->isCity() && m_pUnitInfo->getWeaponTier() > 0) { if (getOwner() == pNewPlot->getOwner()) { setWeapons(); } } if (m_pUnitInfo->isAutoRaze()) { if (pNewPlot->isOwned()) { if (pNewPlot->getImprovementType() != NO_IMPROVEMENT) { if (!GC.getImprovementInfo((ImprovementTypes)pNewPlot->getImprovementType()).isPermanent()) { if (atWar(getTeam(), GET_PLAYER(pNewPlot->getOwner()).getTeam())) { pNewPlot->setImprovementType(NO_IMPROVEMENT); } } } } pNewPlot->setFeatureType(NO_FEATURE, -1); } } //FfH: End Add 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 //FfH: Modified by Kael 10/15/2008 // CvEventReporter::getInstance().unitSetXY(pNewPlot, this); if(GC.getUSE_ON_UNIT_MOVE_CALLBACK()) { CvEventReporter::getInstance().unitSetXY(pNewPlot, this); } //FfH: End Modify } 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; 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); } } } /* ########################################################### # VKs Plot Capacity - Start ########################################################### */ void CvUnit::setUnitPlotCost(int i) { m_iUnitPlotCost = i; } int CvUnit::UnitPlotCost() const { return GC.getUnitInfo(getUnitType()).getUnitPlotCost(); } /* ########################################################### # VKs Plot Capacity - End ########################################################### */ void CvUnit::changeMoves(int iChange) { setMoves(getMoves() + iChange); } void CvUnit::finishMoves() { setMoves(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; } //FfH: Added by Kael 05/17/2008 if (GC.getGameINLINE().isOption(GAMEOPTION_SLOWER_XP)) { iUnitExperience += 1; iUnitExperience /= 2; } //FfH: End Add } 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); some promotions can reduce visibility modified Sephi 0.41k plot()->changeAdjacentSight(getTeam(), visibilityRange(), true, this, true); } } int CvUnit::getExtraMoves() const { return m_iExtraMoves; } void CvUnit::changeExtraMoves(int iChange) { m_iExtraMoves += iChange; // FAssert(getExtraMoves() >= 0); mutations can make this negative modified Sephi 0.41k } int CvUnit::getExtraMoveDiscount() const { return m_iExtraMoveDiscount; } void CvUnit::changeExtraMoveDiscount(int iChange) { m_iExtraMoveDiscount += iChange; // FAssert(getExtraMoveDiscount() >= 0); //mutate can give negative value Sephi 0.41k } 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); Modified by Kael 11/13/2009 0.41k } int CvUnit::getExtraNeutralHeal() const { return m_iExtraNeutralHeal; } void CvUnit::changeExtraNeutralHeal(int iChange) { m_iExtraNeutralHeal += iChange; // FAssert(getExtraNeutralHeal() >= 0); Modified by Kael 11/13/2009 0.41k } int CvUnit::getExtraFriendlyHeal() const { return m_iExtraFriendlyHeal; } void CvUnit::changeExtraFriendlyHeal(int iChange) { m_iExtraFriendlyHeal += iChange; // FAssert(getExtraFriendlyHeal() >= 0); Modified by Kael 0.41k } 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 { //FfH: Modified by Kael 10/26/2007 // return m_iExtraCombatPercent; int i = m_iExtraCombatPercent; if (plot()->getOwnerINLINE() == getOwnerINLINE()) { i += getCombatPercentInBorders(); } return i; //FfH: End Modify } 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 { //FfH: Added by Kael 09/15/2008 if (isHeld()) { return 999; } //FfH: End Add return m_iImmobileTimer; } void CvUnit::setImmobileTimer(int iNewValue) { //FfH: Modified by Kael 09/15/2008 // if (iNewValue != getImmobileTimer()) // { // m_iImmobileTimer = iNewValue; // setInfoBarDirty(true); if (iNewValue != getImmobileTimer() && !isHeld()) { m_iImmobileTimer = iNewValue; setInfoBarDirty(true); if (getImmobileTimer() == 0) { if (getDelayedSpell() != NO_SPELL) { cast(getDelayedSpell()); } } //FfH: End Modify } } 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; /*************************************************************************************************/ /** ADDON (automatic terraforming) Sephi **/ /** **/ /** **/ /*************************************************************************************************/ // if (m_bPromotionReady) if ((m_bPromotionReady && AI_getUnitAIType() != UNITAI_TERRAFORMER)) /*************************************************************************************************/ /** END **/ /*************************************************************************************************/ { 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) { //FfH Hidden Nationality: Modified by Kael 08/27/2007 // if (m_pUnitInfo->isHiddenNationality()) if (isHiddenNationality()) //FfH: End Modify { 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) { //FfH: Modified by Kael 08/12/2007 // m_eCapturingPlayer = eNewValue; if (!isImmuneToCapture()) { m_eCapturingPlayer = eNewValue; } //FfH: End Add } 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; } } //FfH: Modified by Kael 07/30/2007 // 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).getMinLevel() == -1) { return false; } if (GC.getPromotionInfo(ePromotion).isRace()) { return false; } if (GC.getPromotionInfo(ePromotion).isEquipment()) { return false; } if (GC.getPromotionInfo(ePromotion).getMinLevel() > getLevel()) { return false; } if (GC.getPromotionInfo(ePromotion).getPromotionPrereqAnd() != NO_PROMOTION) { if (!isHasPromotion((PromotionTypes)(GC.getPromotionInfo(ePromotion).getPromotionPrereqAnd()))) { return false; } } if (GC.getPromotionInfo(ePromotion).getPrereqOrPromotion1() != NO_PROMOTION) { bool bValid = false; if (isHasPromotion((PromotionTypes)(GC.getPromotionInfo(ePromotion).getPrereqOrPromotion1()))) { bValid = true; } if (GC.getPromotionInfo(ePromotion).getPrereqOrPromotion2() != NO_PROMOTION) { if (isHasPromotion((PromotionTypes)(GC.getPromotionInfo(ePromotion).getPrereqOrPromotion2()))) { bValid = true; } } if (GC.getPromotionInfo(ePromotion).getPromotionPrereqOr3() != NO_PROMOTION) { if (isHasPromotion((PromotionTypes)(GC.getPromotionInfo(ePromotion).getPromotionPrereqOr3()))) { bValid = true; } } if (GC.getPromotionInfo(ePromotion).getPromotionPrereqOr4() != NO_PROMOTION) { if (isHasPromotion((PromotionTypes)(GC.getPromotionInfo(ePromotion).getPromotionPrereqOr4()))) { bValid = true; } } if (!bValid) { return false; } } if (GC.getPromotionInfo(ePromotion).getBonusPrereq() != NO_BONUS) { if (!GET_PLAYER(getOwnerINLINE()).hasBonus((BonusTypes)GC.getPromotionInfo(ePromotion).getBonusPrereq())) { return false; } } for (int iI = 0; iI < GC.getNumPromotionInfos(); iI++) { if (isHasPromotion((PromotionTypes)iI)) { if (GC.getPromotionInfo((PromotionTypes)iI).getPromotionImmune1() == ePromotion) { return false; } if (GC.getPromotionInfo((PromotionTypes)iI).getPromotionImmune2() == ePromotion) { return false; } if (GC.getPromotionInfo((PromotionTypes)iI).getPromotionImmune3() == ePromotion) { return false; } } } if (GC.getPromotionInfo(ePromotion).isPrereqAlive()) { if (!isAlive()) { return false; } } //FfH: End Add 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); //FfH: Modified by Kael 10/28/2008 // if (promotionInfo.getWithdrawalChange() + m_pUnitInfo->getWithdrawalProbability() + getExtraWithdrawal() > GC.getDefineINT("MAX_WITHDRAWAL_PROBABILITY")) // { // return false; // } if (promotionInfo.getWithdrawalChange() > 0) { if (promotionInfo.getWithdrawalChange() + m_pUnitInfo->getWithdrawalProbability() + getExtraWithdrawal() > GC.getDefineINT("MAX_WITHDRAWAL_PROBABILITY")) { return false; } } //FfH: End Modify 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; //FfH: Added by Kael 07/28/2008 if (bNewValue) { for (int iI = 0; iI < GC.getNumPromotionInfos(); iI++) { if (isHasPromotion((PromotionTypes)iI)) { if (GC.getPromotionInfo((PromotionTypes)iI).getPromotionImmune1() == eIndex) { return; } if (GC.getPromotionInfo((PromotionTypes)iI).getPromotionImmune2() == eIndex) { return; } if (GC.getPromotionInfo((PromotionTypes)iI).getPromotionImmune3() == eIndex) { return; } } } } //FfH: End Add if (isHasPromotion(eIndex) != bNewValue) { m_pabHasPromotion[eIndex] = bNewValue; iChange = ((isHasPromotion(eIndex)) ? 1 : -1); 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); //FfH: Added by Kael 07/30/2007 if (GC.getPromotionInfo(eIndex).isAIControl() && bNewValue) { joinGroup(NULL); } changeAIControl((GC.getPromotionInfo(eIndex).isAIControl()) ? iChange : 0); changeAlive((GC.getPromotionInfo(eIndex).isNotAlive()) ? iChange : 0); changeBaseCombatStr(GC.getPromotionInfo(eIndex).getExtraCombatStr() * iChange); changeBaseCombatStrDefense(GC.getPromotionInfo(eIndex).getExtraCombatDefense() * iChange); changeBetterDefenderThanPercent(GC.getPromotionInfo(eIndex).getBetterDefenderThanPercent() * iChange); changeBoarding((GC.getPromotionInfo(eIndex).isBoarding()) ? iChange : 0); changeCombatHealPercent(GC.getPromotionInfo(eIndex).getCombatHealPercent() * iChange); changeCombatPercentInBorders(GC.getPromotionInfo(eIndex).getCombatPercentInBorders() * iChange); changeCombatPercentGlobalCounter(GC.getPromotionInfo(eIndex).getCombatPercentGlobalCounter() * iChange); changeDefensiveStrikeChance(GC.getPromotionInfo(eIndex).getDefensiveStrikeChance() * iChange); changeDefensiveStrikeDamage(GC.getPromotionInfo(eIndex).getDefensiveStrikeDamage() * iChange); changeDoubleFortifyBonus((GC.getPromotionInfo(eIndex).isDoubleFortifyBonus()) ? iChange : 0); changeFear((GC.getPromotionInfo(eIndex).isFear()) ? iChange : 0); changeFlying((GC.getPromotionInfo(eIndex).isFlying()) ? iChange : 0); changeGoldFromCombat(GC.getPromotionInfo(eIndex).getGoldFromCombat() * iChange); changeHeld((GC.getPromotionInfo(eIndex).isHeld()) ? iChange : 0); changeHiddenNationality((GC.getPromotionInfo(eIndex).isHiddenNationality()) ? iChange : 0); changeIgnoreBuildingDefense((GC.getPromotionInfo(eIndex).isIgnoreBuildingDefense()) ? iChange : 0); changeImmortal((GC.getPromotionInfo(eIndex).isImmortal()) ? iChange : 0); changeImmuneToCapture((GC.getPromotionInfo(eIndex).isImmuneToCapture()) ? iChange : 0); changeImmuneToDefensiveStrike((GC.getPromotionInfo(eIndex).isImmuneToDefensiveStrike()) ? iChange : 0); changeImmuneToFear((GC.getPromotionInfo(eIndex).isImmuneToFear()) ? iChange : 0); changeImmuneToMagic((GC.getPromotionInfo(eIndex).isImmuneToMagic()) ? iChange : 0); changeInvisibleFromPromotion((GC.getPromotionInfo(eIndex).isInvisible()) ? iChange : 0); changeOnlyDefensive((GC.getPromotionInfo(eIndex).isOnlyDefensive()) ? iChange : 0); changeResist(GC.getPromotionInfo(eIndex).getResistMagic() * iChange); changeResistModify(GC.getPromotionInfo(eIndex).getCasterResistModify() * iChange); changeSeeInvisible((GC.getPromotionInfo(eIndex).isSeeInvisible()) ? iChange : 0); changeSpellCasterXP(GC.getPromotionInfo(eIndex).getSpellCasterXP() * iChange); changeSpellDamageModify(GC.getPromotionInfo(eIndex).getSpellDamageModify() * iChange); changeTargetWeakestUnit((GC.getPromotionInfo(eIndex).isTargetWeakestUnit()) ? iChange : 0); changeTargetWeakestUnitCounter((GC.getPromotionInfo(eIndex).isTargetWeakestUnitCounter()) ? iChange : 0); changeTwincast((GC.getPromotionInfo(eIndex).isTwincast()) ? iChange : 0); changeWaterWalking((GC.getPromotionInfo(eIndex).isWaterWalking()) ? iChange : 0); changeWorkRateModify(GC.getPromotionInfo(eIndex).getWorkRateModify() * iChange); GC.getGameINLINE().changeGlobalCounter(GC.getPromotionInfo(eIndex).getModifyGlobalCounter() * iChange); if (GC.getPromotionInfo(eIndex).getCombatLimit() != 0) { calcCombatLimit(); } if (eIndex == GC.getDefineINT("MUTATED_PROMOTION") && bNewValue) { mutate(); } if (GC.getPromotionInfo(eIndex).isRace()) { if (bNewValue) { setRace(eIndex); } else { setRace(NO_PROMOTION); } } for (iI = 0; iI < GC.getNumDamageTypeInfos(); iI++) { changeDamageTypeCombat(((DamageTypes)iI), (GC.getPromotionInfo(eIndex).getDamageTypeCombat(iI) * iChange)); } for (iI = 0; iI < GC.getNumBonusInfos(); iI++) { changeBonusAffinity(((BonusTypes)iI), (GC.getPromotionInfo(eIndex).getBonusAffinity(iI) * iChange)); } for (iI = 0; iI < GC.getNumDamageTypeInfos(); iI++) { changeDamageTypeResist(((DamageTypes)iI), (GC.getPromotionInfo(eIndex).getDamageTypeResist(iI) * iChange)); } //FfH: End Add 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()); //FfH: Added by Kael 07/04/2009 if (GC.getPromotionInfo(eIndex).getUnitArtStyleType() != NO_UNIT_ARTSTYLE) { if (iChange > 0) { setUnitArtStyleType(GC.getPromotionInfo(eIndex).getUnitArtStyleType()); } else { if (GC.getPromotionInfo(eIndex).getUnitArtStyleType() == getUnitArtStyleType()) { setUnitArtStyleType(NO_UNIT_ARTSTYLE); } } reloadEntity(); } if (GC.getPromotionInfo(eIndex).getGroupSize() != 0) { if (bNewValue) { setGroupSize(GC.getPromotionInfo(eIndex).getGroupSize()); } else { setGroupSize(0); } reloadEntity(); } updateTerraformer(); //FfH: End Add } } 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 { //FfH: Modified by Kael 10/26/2007 // return std::max(1, (((m_pUnitInfo->getGroupSize() * (maxHitPoints() - iDamage)) + (maxHitPoints() / ((m_pUnitInfo->getGroupSize() * 2) + 1))) / maxHitPoints())); return std::max(1, (((getGroupSize() * (maxHitPoints() - iDamage)) + (maxHitPoints() / ((getGroupSize() * 2) + 1))) / maxHitPoints())); //FfH: End Modify } } // 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; } //FfH Spell System: Added by Kael 07/23/2007 bool CvUnit::canCast(int spell, bool bTestVisible) { SpellTypes eSpell = (SpellTypes)spell; CvPlot* pPlot = plot(); CvUnit* pLoopUnit; CLLNode<IDInfo>* pUnitNode; bool bValid = false; if (getImmobileTimer() > 0) { return false; } if (!isHuman()) { if (!GC.getSpellInfo(eSpell).isAllowAI()) { return false; } } if (GC.getSpellInfo(eSpell).getPromotionPrereq1() != NO_PROMOTION) { if (!isHasPromotion((PromotionTypes)GC.getSpellInfo(eSpell).getPromotionPrereq1())) { return false; } } if (GC.getSpellInfo(eSpell).getPromotionPrereq2() != NO_PROMOTION) { if (!isHasPromotion((PromotionTypes)GC.getSpellInfo(eSpell).getPromotionPrereq2())) { return false; } } if (GC.getSpellInfo(eSpell).getUnitClassPrereq() != NO_UNITCLASS) { if (getUnitClassType() != (UnitClassTypes)GC.getSpellInfo(eSpell).getUnitClassPrereq()) { return false; } } if (GC.getSpellInfo(eSpell).getUnitPrereq() != NO_UNIT) { if (getUnitType() != (UnitTypes)GC.getSpellInfo(eSpell).getUnitPrereq()) { return false; } } if (GC.getSpellInfo(eSpell).getUnitCombatPrereq() != NO_UNITCOMBAT) { if (getUnitCombatType() != (UnitCombatTypes)GC.getSpellInfo(eSpell).getUnitCombatPrereq()) { return false; } } if (GC.getSpellInfo(eSpell).getBuildingPrereq() != NO_BUILDING) { if (!pPlot->isCity()) { return false; } if (pPlot->getPlotCity()->getNumBuilding((BuildingTypes)GC.getSpellInfo(eSpell).getBuildingPrereq()) == 0) { return false; } } if (GC.getSpellInfo(eSpell).getBuildingClassOwnedPrereq() != NO_BUILDINGCLASS) { if (GET_PLAYER(getOwnerINLINE()).getBuildingClassCount((BuildingClassTypes)GC.getSpellInfo(eSpell).getBuildingClassOwnedPrereq()) == 0) { return false; } } if (GC.getSpellInfo(eSpell).getCivilizationPrereq() != NO_CIVILIZATION) { if (getCivilizationType() != (CivilizationTypes)GC.getSpellInfo(eSpell).getCivilizationPrereq()) { return false; } } if (GC.getSpellInfo(eSpell).getCorporationPrereq() != NO_CORPORATION) { if (!pPlot->isCity()) { return false; } if (!pPlot->getPlotCity()->isHasCorporation((CorporationTypes)GC.getSpellInfo(eSpell).getCorporationPrereq())) { return false; } } if (GC.getSpellInfo(eSpell).getImprovementPrereq() != NO_IMPROVEMENT) { if (pPlot->getImprovementType() != GC.getSpellInfo(eSpell).getImprovementPrereq()) { return false; } } if (GC.getSpellInfo(eSpell).getReligionPrereq() != NO_RELIGION) { if (getReligion() != (ReligionTypes)GC.getSpellInfo(eSpell).getReligionPrereq()) { return false; } } if (GC.getSpellInfo(eSpell).getStateReligionPrereq() != NO_RELIGION) { if (GET_PLAYER(getOwnerINLINE()).getStateReligion() != (ReligionTypes)GC.getSpellInfo(eSpell).getStateReligionPrereq()) { return false; } } if (GC.getSpellInfo(eSpell).getTechPrereq() != NO_TECH) { if (!GET_TEAM(getTeam()).isHasTech((TechTypes)GC.getSpellInfo(eSpell).getTechPrereq())) { return false; } } if (GC.getSpellInfo(eSpell).getConvertUnitType() != NO_UNIT) { if (getUnitType() == (UnitTypes)GC.getSpellInfo(eSpell).getConvertUnitType()) { return false; } } if (GC.getSpellInfo(eSpell).isGlobal()) { if (GC.getGameINLINE().isOption(GAMEOPTION_NO_WORLD_SPELLS)) { return false; } if (GET_PLAYER(getOwnerINLINE()).isFeatAccomplished(FEAT_GLOBAL_SPELL)) { return false; } } if (GC.getSpellInfo(eSpell).isPrereqSlaveTrade()) { if (!GET_PLAYER(getOwnerINLINE()).isSlaveTrade()) { return false; } } if (GC.getUnitInfo((UnitTypes)getUnitType()).getEquipmentPromotion() != NO_PROMOTION) { if (GC.getSpellInfo(eSpell).getUnitClassPrereq() != getUnitClassType()) { return false; } } if (GC.getSpellInfo(eSpell).getCasterMinLevel() != 0) { if (getLevel() < GC.getSpellInfo(eSpell).getCasterMinLevel()) { return false; } } if (GC.getSpellInfo(eSpell).isCasterMustBeAlive()) { if (!isAlive()) { return false; } } if (GC.getSpellInfo(eSpell).isCasterNoDuration()) { if (getDuration() != 0) { return false; } } if (GET_PLAYER(getOwnerINLINE()).getDisableSpellcasting() > 0) { if (!GC.getSpellInfo(eSpell).isAbility()) { return false; } } if (GC.getSpellInfo(eSpell).getPromotionInStackPrereq() != NO_PROMOTION) { if (isHasPromotion((PromotionTypes)GC.getSpellInfo(eSpell).getPromotionInStackPrereq())) { return false; } bValid = false; pUnitNode = pPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); if (pLoopUnit->isHasPromotion((PromotionTypes)GC.getSpellInfo(eSpell).getPromotionInStackPrereq())) { if (getOwner() == pLoopUnit->getOwner()) { bValid = true; } } } if (bValid == false) { return false; } } if (GC.getSpellInfo(eSpell).getUnitInStackPrereq() != NO_UNIT) { if (getUnitType() == GC.getSpellInfo(eSpell).getUnitInStackPrereq()) { return false; } bValid = false; pUnitNode = pPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); if (pLoopUnit->getUnitType() == (UnitTypes)GC.getSpellInfo(eSpell).getUnitInStackPrereq()) { if (getOwner() == pLoopUnit->getOwner()) { if (!pLoopUnit->isDelayedDeath()) { bValid = true; } } } } if (bValid == false) { return false; } } if (bTestVisible) { if (GC.getSpellInfo(eSpell).isDisplayWhenDisabled()) { return true; } } if (GC.getSpellInfo(eSpell).getFeatureOrPrereq1() != NO_FEATURE) { if (pPlot->getFeatureType() != GC.getSpellInfo(eSpell).getFeatureOrPrereq1()) { if (GC.getSpellInfo(eSpell).getFeatureOrPrereq2() == NO_FEATURE || pPlot->getFeatureType() != GC.getSpellInfo(eSpell).getFeatureOrPrereq2()) { return false; } } } if (!GC.getSpellInfo(eSpell).isIgnoreHasCasted()) { if (isHasCasted()) { return false; } } if (GC.getSpellInfo(eSpell).isAdjacentToWaterOnly()) { if (!pPlot->isAdjacentToWater()) { return false; } } if (GC.getSpellInfo(eSpell).isInBordersOnly()) { if (pPlot->getOwner() != getOwner()) { return false; } } if (GC.getSpellInfo(eSpell).isInCityOnly()) { if (!pPlot->isCity()) { return false; } } if (GC.getSpellInfo(eSpell).getChangePopulation() != 0) { if (!pPlot->isCity()) { return false; } if (pPlot->getPlotCity()->getPopulation() <= (-1 * GC.getSpellInfo(eSpell).getChangePopulation())) { return false; } } int iCost = GC.getSpellInfo(eSpell).getCost(); if (iCost != 0) { if (GC.getSpellInfo(eSpell).getConvertUnitType() != NO_UNIT) { iCost += (iCost * GET_PLAYER(getOwnerINLINE()).getUpgradeCostModifier()) / 100; } if (GET_PLAYER(getOwnerINLINE()).getGold() < iCost) { return false; } } if (GC.getSpellInfo(eSpell).isRemoveHasCasted()) { if (!isHasCasted()) { return false; } if (getDuration() > 0) { return false; } } if (GC.getSpellInfo(eSpell).getCreateUnitType() != NO_UNIT) { if (!canCreateUnit(spell)) { return false; } } if (GC.getSpellInfo(eSpell).getCreateBuildingType() != NO_BUILDING) { if (!canCreateBuilding(spell)) { return false; } } if (!CvString(GC.getSpellInfo(eSpell).getPyRequirement()).empty()) { CyUnit* pyUnit = new CyUnit(this); CyArgsList argsList; argsList.add(gDLL->getPythonIFace()->makePythonObject(pyUnit)); // pass in unit class argsList.add(spell);//the spell # long lResult=0; gDLL->getPythonIFace()->callFunction(PYSpellModule, "canCast", argsList.makeFunctionArgs(), &lResult); delete pyUnit; // python fxn must not hold on to this pointer if (lResult == 0) { return false; } return true; } if (GC.getSpellInfo(eSpell).isRemoveHasCasted()) { if (isHasCasted()) { return true; } } if (GC.getSpellInfo(eSpell).getAddPromotionType1() != NO_PROMOTION) { if (canAddPromotion(spell)) { return true; } } if (GC.getSpellInfo(eSpell).getRemovePromotionType1() != NO_PROMOTION) { if (canRemovePromotion(spell)) { return true; } } if (GC.getSpellInfo(eSpell).getConvertUnitType() != NO_UNIT) { return true; } if (GC.getSpellInfo(eSpell).getCreateFeatureType() != NO_FEATURE) { if (canCreateFeature(spell)) { return true; } } if (GC.getSpellInfo(eSpell).getCreateImprovementType() != NO_IMPROVEMENT) { if (canCreateImprovement(spell)) { return true; } } if (GC.getSpellInfo(eSpell).getSpreadReligion() != NO_RELIGION) { if (canSpreadReligion(spell)) { return true; } } if (GC.getSpellInfo(eSpell).getCreateBuildingType() != NO_BUILDING) { return true; } if (GC.getSpellInfo(eSpell).getCreateUnitType() != NO_UNIT) { return true; } if (GC.getSpellInfo(eSpell).getDamage() != 0) { return true; } if (GC.getSpellInfo(eSpell).isDispel()) { if (canDispel(spell)) { return true; } } if (GC.getSpellInfo(eSpell).getImmobileTurns() > 0) { if (canImmobile(spell)) { return true; } } if (GC.getSpellInfo(eSpell).isPush()) { if (canPush(spell)) { return true; } } if (GC.getSpellInfo(eSpell).getChangePopulation() > 0) { return true; } if (!CvString(GC.getSpellInfo(eSpell).getPyResult()).empty()) { return true; } return false; } bool CvUnit::canCreateUnit(int spell) const { if (getDuration() > 0) // to prevent summons summoning spinlocks { if (GC.getSpellInfo((SpellTypes)spell).getCreateUnitType() == getUnitType()) { return false; } } if (plot()->isVisibleEnemyUnit(getOwnerINLINE())) // keeps invisible units from CtDing summoning on top of enemies { return false; } if (GC.getSpellInfo((SpellTypes)spell).isPermanentUnitCreate()) { int iCount = 0; int iLoop = 0; CvUnit* pLoopUnit; CvPlayer& kPlayer = GET_PLAYER(getOwnerINLINE()); for (pLoopUnit = kPlayer.firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = kPlayer.nextUnit(&iLoop)) { if ((GC.getSpellInfo((SpellTypes)spell).getPromotionPrereq1() == NO_PROMOTION || pLoopUnit->isHasPromotion((PromotionTypes)GC.getSpellInfo((SpellTypes)spell).getPromotionPrereq1())) && (GC.getSpellInfo((SpellTypes)spell).getPromotionPrereq2() == NO_PROMOTION || pLoopUnit->isHasPromotion((PromotionTypes)GC.getSpellInfo((SpellTypes)spell).getPromotionPrereq2())) && (GC.getSpellInfo((SpellTypes)spell).getReligionPrereq() == NO_RELIGION || pLoopUnit->getReligion() == GC.getSpellInfo((SpellTypes)spell).getReligionPrereq())) { iCount += 1; } } if (iCount <= kPlayer.getUnitClassCount((UnitClassTypes)GC.getUnitInfo((UnitTypes)GC.getSpellInfo((SpellTypes)spell).getCreateUnitType()).getUnitClassType())) { return false; } } return true; } bool CvUnit::canAddPromotion(int spell) { PromotionTypes ePromotion1 = (PromotionTypes)GC.getSpellInfo((SpellTypes)spell).getAddPromotionType1(); PromotionTypes ePromotion2 = (PromotionTypes)GC.getSpellInfo((SpellTypes)spell).getAddPromotionType2(); PromotionTypes ePromotion3 = (PromotionTypes)GC.getSpellInfo((SpellTypes)spell).getAddPromotionType3(); if (GC.getSpellInfo((SpellTypes)spell).isBuffCasterOnly()) { if (ePromotion1 != NO_PROMOTION) { if (!isHasPromotion(ePromotion1)) { return true; } } if (ePromotion2 != NO_PROMOTION) { if (!isHasPromotion(ePromotion2)) { return true; } } if (ePromotion3 != NO_PROMOTION) { if (!isHasPromotion(ePromotion3)) { return true; } } return false; } CvUnit* pLoopUnit; CvPlot* pLoopPlot; int iRange = GC.getSpellInfo((SpellTypes)spell).getRange(); for (int i = -iRange; i <= iRange; ++i) { for (int j = -iRange; j <= iRange; ++j) { pLoopPlot = ::plotXY(plot()->getX_INLINE(), plot()->getY_INLINE(), i, j); if (NULL != pLoopPlot) { CLLNode<IDInfo>* pUnitNode = pLoopPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pLoopPlot->nextUnitNode(pUnitNode); if (!pLoopUnit->isImmuneToSpell(this, spell)) { if (ePromotion1 != NO_PROMOTION) { if (pLoopUnit->getUnitCombatType() != NO_UNITCOMBAT) { if (GC.getPromotionInfo(ePromotion1).getUnitCombat(pLoopUnit->getUnitCombatType())) { if (!pLoopUnit->isHasPromotion(ePromotion1)) { return true; } } } } if (ePromotion2 != NO_PROMOTION) { if (pLoopUnit->getUnitCombatType() != NO_UNITCOMBAT) { if (GC.getPromotionInfo(ePromotion2).getUnitCombat(pLoopUnit->getUnitCombatType())) { if (!pLoopUnit->isHasPromotion(ePromotion2)) { return true; } } } } if (ePromotion3 != NO_PROMOTION) { if (pLoopUnit->getUnitCombatType() != NO_UNITCOMBAT) { if (GC.getPromotionInfo(ePromotion3).getUnitCombat(pLoopUnit->getUnitCombatType())) { if (!pLoopUnit->isHasPromotion(ePromotion3)) { return true; } } } } } } } } } return false; } bool CvUnit::canCreateBuilding(int spell) const { if (!plot()->isCity()) { return false; } if (plot()->getPlotCity()->getNumBuilding((BuildingTypes)GC.getSpellInfo((SpellTypes)spell).getCreateBuildingType()) > 0) { return false; } return true; } bool CvUnit::canCreateFeature(int spell) const { if (plot()->isCity()) { return false; } if (!plot()->canHaveFeature((FeatureTypes)GC.getSpellInfo((SpellTypes)spell).getCreateFeatureType())) { return false; } if (plot()->getFeatureType() != NO_FEATURE) { return false; } if (plot()->getImprovementType() != NO_IMPROVEMENT) { if (!GC.getCivilizationInfo(getCivilizationType()).isMaintainFeatures(GC.getSpellInfo((SpellTypes)spell).getCreateFeatureType())) { return false; } } return true; } bool CvUnit::canCreateImprovement(int spell) const { if (plot()->isCity()) { return false; } if (!plot()->canHaveImprovement((ImprovementTypes)GC.getSpellInfo((SpellTypes)spell).getCreateImprovementType())) { return false; } if (plot()->getImprovementType() != NO_IMPROVEMENT) { return false; } return true; } bool CvUnit::canDispel(int spell) { int iRange = GC.getSpellInfo((SpellTypes)spell).getRange(); CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; CvPlot* pLoopPlot; for (int i = -iRange; i <= iRange; ++i) { for (int j = -iRange; j <= iRange; ++j) { pLoopPlot = ::plotXY(plot()->getX_INLINE(), plot()->getY_INLINE(), i, j); if (NULL != pLoopPlot) { pUnitNode = pLoopPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pLoopPlot->nextUnitNode(pUnitNode); if (!pLoopUnit->isImmuneToSpell(this, spell)) { for (int iI = 0; iI < GC.getNumPromotionInfos(); iI++) { if (pLoopUnit->isHasPromotion((PromotionTypes)iI)) { if (GC.getPromotionInfo((PromotionTypes)iI).isDispellable()) { if ((GC.getPromotionInfo((PromotionTypes)iI).getAIWeight() < 0 && pLoopUnit->getTeam() == getTeam()) || (GC.getPromotionInfo((PromotionTypes)iI).getAIWeight() > 0 && pLoopUnit->isEnemy(getTeam()))) { return true; } } } } } } } } } return false; } bool CvUnit::canImmobile(int spell) { int iRange = GC.getSpellInfo((SpellTypes)spell).getRange(); CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; CvPlot* pLoopPlot; for (int i = -iRange; i <= iRange; ++i) { for (int j = -iRange; j <= iRange; ++j) { pLoopPlot = ::plotXY(plot()->getX_INLINE(), plot()->getY_INLINE(), i, j); if (NULL != pLoopPlot) { pUnitNode = pLoopPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pLoopPlot->nextUnitNode(pUnitNode); if (!pLoopUnit->isImmuneToSpell(this, spell)) { return true; } } } } } return false; } bool CvUnit::canPush(int spell) { int iRange = GC.getSpellInfo((SpellTypes)spell).getRange(); CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; CvPlot* pLoopPlot; for (int i = -iRange; i <= iRange; ++i) { for (int j = -iRange; j <= iRange; ++j) { pLoopPlot = ::plotXY(plot()->getX_INLINE(), plot()->getY_INLINE(), i, j); if (NULL != pLoopPlot) { if (!pLoopPlot->isCity()) { pUnitNode = pLoopPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pLoopPlot->nextUnitNode(pUnitNode); if (!pLoopUnit->isImmuneToSpell(this, spell)) { return true; } } } } } } return false; } bool CvUnit::canRemovePromotion(int spell) { PromotionTypes ePromotion1 = (PromotionTypes)GC.getSpellInfo((SpellTypes)spell).getRemovePromotionType1(); PromotionTypes ePromotion2 = (PromotionTypes)GC.getSpellInfo((SpellTypes)spell).getRemovePromotionType2(); PromotionTypes ePromotion3 = (PromotionTypes)GC.getSpellInfo((SpellTypes)spell).getRemovePromotionType3(); if (plot()->isVisibleEnemyUnit(getOwnerINLINE())) { if (ePromotion1 == (PromotionTypes)GC.getDefineINT("HIDDEN_NATIONALITY_PROMOTION")) { return false; } if (ePromotion2 == (PromotionTypes)GC.getDefineINT("HIDDEN_NATIONALITY_PROMOTION")) { return false; } if (ePromotion3 == (PromotionTypes)GC.getDefineINT("HIDDEN_NATIONALITY_PROMOTION")) { return false; } } if (GC.getSpellInfo((SpellTypes)spell).isBuffCasterOnly()) { if (ePromotion1 != NO_PROMOTION) { if (isHasPromotion(ePromotion1)) { return true; } } if (ePromotion2 != NO_PROMOTION) { if (isHasPromotion(ePromotion2)) { return true; } } if (ePromotion3 != NO_PROMOTION) { if (isHasPromotion(ePromotion3)) { return true; } } return false; } CvUnit* pLoopUnit; CvPlot* pLoopPlot; int iRange = GC.getSpellInfo((SpellTypes)spell).getRange(); for (int i = -iRange; i <= iRange; ++i) { for (int j = -iRange; j <= iRange; ++j) { pLoopPlot = ::plotXY(plot()->getX_INLINE(), plot()->getY_INLINE(), i, j); if (NULL != pLoopPlot) { CLLNode<IDInfo>* pUnitNode = pLoopPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pLoopPlot->nextUnitNode(pUnitNode); if (!pLoopUnit->isImmuneToSpell(this, spell)) { if (ePromotion1 != NO_PROMOTION) { if (pLoopUnit->isHasPromotion(ePromotion1)) { return true; } } if (ePromotion2 != NO_PROMOTION) { if (pLoopUnit->isHasPromotion(ePromotion2)) { return true; } } if (ePromotion3 != NO_PROMOTION) { if (pLoopUnit->isHasPromotion(ePromotion3)) { return true; } } } } } } } return false; } bool CvUnit::canSpreadReligion(int spell) const { ReligionTypes eReligion = (ReligionTypes)GC.getSpellInfo((SpellTypes)spell).getSpreadReligion(); if (eReligion == NO_RELIGION) { return false; } CvCity* pCity = plot()->getPlotCity(); if (pCity == NULL) { return false; } if (pCity->isHasReligion(eReligion)) { return false; } return true; } void CvUnit::cast(int spell) { if (GC.getSpellInfo((SpellTypes)spell).isHasCasted()) { setHasCasted(true); } for (int iI = 0; iI < GC.getNumPromotionInfos(); iI++) { if (isHasPromotion((PromotionTypes)iI)) { if (GC.getPromotionInfo((PromotionTypes)iI).isRemovedByCasting()) { setHasPromotion((PromotionTypes)iI, false); } } } if (GC.getSpellInfo((SpellTypes)spell).isGlobal()) { GET_PLAYER(getOwnerINLINE()).setFeatAccomplished(FEAT_GLOBAL_SPELL, true); for (int iPlayer = 0; iPlayer < MAX_CIV_PLAYERS; ++iPlayer) { if (GET_PLAYER((PlayerTypes)iPlayer).isAlive()) { gDLL->getInterfaceIFace()->addMessage((PlayerTypes)iPlayer, false, GC.getEVENT_MESSAGE_TIME(), gDLL->getText("TXT_KEY_MESSAGE_GLOBAL_SPELL", GC.getSpellInfo((SpellTypes)spell).getDescription()), "AS2D_CIVIC_ADOPT", MESSAGE_TYPE_MINOR_EVENT); } } } int iMiscastChance = GC.getSpellInfo((SpellTypes)spell).getMiscastChance() + m_pUnitInfo->getMiscastChance(); if (iMiscastChance > 0) { if (GC.getGameINLINE().getSorenRandNum(100, "Miscast") < iMiscastChance) { if (!CvString(GC.getSpellInfo((SpellTypes)spell).getPyMiscast()).empty()) { CyUnit* pyUnit = new CyUnit(this); CyArgsList argsList; argsList.add(gDLL->getPythonIFace()->makePythonObject(pyUnit)); // pass in unit class argsList.add(spell);//the spell # gDLL->getPythonIFace()->callFunction(PYSpellModule, "miscast", argsList.makeFunctionArgs()); //, &lResult delete pyUnit; // python fxn must not hold on to this pointer } gDLL->getInterfaceIFace()->addMessage((PlayerTypes)getOwner(), true, GC.getEVENT_MESSAGE_TIME(), gDLL->getText("TXT_KEY_MESSAGE_SPELL_MISCAST"), "AS2D_WONDER_UNIT_BUILD", MESSAGE_TYPE_MAJOR_EVENT, "art/interface/buttons/spells/miscast.dds", (ColorTypes)GC.getInfoTypeForString("COLOR_UNIT_TEXT"), getX_INLINE(), getY_INLINE(), true, true); gDLL->getInterfaceIFace()->setDirty(SelectionButtons_DIRTY_BIT, true); return; } } if (GC.getSpellInfo((SpellTypes)spell).getDelay() > 0) { if (getDelayedSpell() == NO_SPELL) { changeImmobileTimer(GC.getSpellInfo((SpellTypes)spell).getDelay()); setDelayedSpell(spell); gDLL->getInterfaceIFace()->setDirty(SelectionButtons_DIRTY_BIT, true); gDLL->getInterfaceIFace()->changeCycleSelectionCounter((GET_PLAYER(getOwnerINLINE()).isOption(PLAYEROPTION_QUICK_MOVES)) ? 1 : 2); return; } setDelayedSpell(NO_SPELL); } if (GC.getSpellInfo((SpellTypes)spell).getCreateUnitType() != -1) { int iUnitNum = GC.getSpellInfo((SpellTypes)spell).getCreateUnitNum(); if (isTwincast()) { iUnitNum *= 2; } for (int i=0; i < iUnitNum; ++i) { castCreateUnit(spell); } } if (GC.getSpellInfo((SpellTypes)spell).getAddPromotionType1() != -1) { castAddPromotion(spell); } if (GC.getSpellInfo((SpellTypes)spell).getRemovePromotionType1() != -1) { castRemovePromotion(spell); } if (GC.getSpellInfo((SpellTypes)spell).getConvertUnitType() != NO_UNIT) { castConvertUnit(spell); } if (GC.getSpellInfo((SpellTypes)spell).getCreateBuildingType() != NO_BUILDING) { if (canCreateBuilding(spell)) { plot()->getPlotCity()->setNumRealBuilding((BuildingTypes)GC.getSpellInfo((SpellTypes)spell).getCreateBuildingType(), true); } } if (GC.getSpellInfo((SpellTypes)spell).getCreateFeatureType() != NO_FEATURE) { if (canCreateFeature(spell)) { plot()->setFeatureType((FeatureTypes)GC.getSpellInfo((SpellTypes)spell).getCreateFeatureType(), -1); } } if (GC.getSpellInfo((SpellTypes)spell).getCreateImprovementType() != NO_IMPROVEMENT) { if (canCreateImprovement(spell)) { plot()->setImprovementType((ImprovementTypes)GC.getSpellInfo((SpellTypes)spell).getCreateImprovementType()); } } if (GC.getSpellInfo((SpellTypes)spell).getSpreadReligion() != NO_RELIGION) { if (canSpreadReligion(spell)) { plot()->getPlotCity()->setHasReligion((ReligionTypes)GC.getSpellInfo((SpellTypes)spell).getSpreadReligion(), true, true, true); } } if (GC.getSpellInfo((SpellTypes)spell).getDamage() != 0) { castDamage(spell); } if (GC.getSpellInfo((SpellTypes)spell).getImmobileTurns() != 0) { castImmobile(spell); } if (GC.getSpellInfo((SpellTypes)spell).isPush()) { castPush(spell); } if (GC.getSpellInfo((SpellTypes)spell).isRemoveHasCasted()) { if (getDuration() == 0) { setHasCasted(false); } } int iCost = GC.getSpellInfo((SpellTypes)spell).getCost(); if (iCost != 0) { if (GC.getSpellInfo((SpellTypes)spell).getConvertUnitType() != NO_UNIT) { iCost += (iCost * GET_PLAYER(getOwnerINLINE()).getUpgradeCostModifier()) / 100; } GET_PLAYER(getOwnerINLINE()).changeGold(-1 * iCost); } if (GC.getSpellInfo((SpellTypes)spell).getChangePopulation() != 0) { plot()->getPlotCity()->changePopulation(GC.getSpellInfo((SpellTypes)spell).getChangePopulation()); } if (GC.getSpellInfo((SpellTypes)spell).isDispel()) { castDispel(spell); } if (plot()->isVisibleToWatchingHuman()) { if (GC.getSpellInfo((SpellTypes)spell).getEffect() != -1) { gDLL->getEngineIFace()->TriggerEffect(GC.getSpellInfo((SpellTypes)spell).getEffect(), plot()->getPoint(), (float)(GC.getASyncRand().get(360))); } if (GC.getSpellInfo((SpellTypes)spell).getSound() != NULL) { gDLL->getInterfaceIFace()->playGeneralSound(GC.getSpellInfo((SpellTypes)spell).getSound(), plot()->getPoint()); } gDLL->getInterfaceIFace()->addMessage((PlayerTypes)getOwner(), true, GC.getEVENT_MESSAGE_TIME(), GC.getSpellInfo((SpellTypes)spell).getDescription(), "AS2D_WONDER_UNIT_BUILD", MESSAGE_TYPE_MAJOR_EVENT, GC.getSpellInfo((SpellTypes)spell).getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_UNIT_TEXT"), getX_INLINE(), getY_INLINE(), true, true); } if (!CvString(GC.getSpellInfo((SpellTypes)spell).getPyResult()).empty()) { CyUnit* pyUnit = new CyUnit(this); CyArgsList argsList; argsList.add(gDLL->getPythonIFace()->makePythonObject(pyUnit)); // pass in unit class argsList.add(spell);//the spell # gDLL->getPythonIFace()->callFunction(PYSpellModule, "cast", argsList.makeFunctionArgs()); //, &lResult delete pyUnit; // python fxn must not hold on to this pointer } gDLL->getInterfaceIFace()->setDirty(SelectionButtons_DIRTY_BIT, true); if (GC.getSpellInfo((SpellTypes)spell).isSacrificeCaster()) { kill(true); } } void CvUnit::castAddPromotion(int spell) { PromotionTypes ePromotion1 = (PromotionTypes)GC.getSpellInfo((SpellTypes)spell).getAddPromotionType1(); PromotionTypes ePromotion2 = (PromotionTypes)GC.getSpellInfo((SpellTypes)spell).getAddPromotionType2(); PromotionTypes ePromotion3 = (PromotionTypes)GC.getSpellInfo((SpellTypes)spell).getAddPromotionType3(); if (GC.getSpellInfo((SpellTypes)spell).isBuffCasterOnly()) { if (ePromotion1 != NO_PROMOTION) { setHasPromotion(ePromotion1, true); } if (ePromotion2 != NO_PROMOTION) { setHasPromotion(ePromotion2, true); } if (ePromotion3 != NO_PROMOTION) { setHasPromotion(ePromotion3, true); } } else { int iRange = GC.getSpellInfo((SpellTypes)spell).getRange(); bool bResistable = GC.getSpellInfo((SpellTypes)spell).isResistable(); CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; CvPlot* pLoopPlot; for (int i = -iRange; i <= iRange; ++i) { for (int j = -iRange; j <= iRange; ++j) { pLoopPlot = ::plotXY(plot()->getX_INLINE(), plot()->getY_INLINE(), i, j); if (NULL != pLoopPlot) { pUnitNode = pLoopPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pLoopPlot->nextUnitNode(pUnitNode); if (!pLoopUnit->isImmuneToSpell(this, spell)) { if (bResistable) { if (!pLoopUnit->isResisted(this, spell)) { if (ePromotion1 != NO_PROMOTION) { if (pLoopUnit->getUnitCombatType() != NO_UNITCOMBAT) { if (GC.getPromotionInfo(ePromotion1).getUnitCombat(pLoopUnit->getUnitCombatType())) { pLoopUnit->setHasPromotion(ePromotion1, true); } } } if (ePromotion2 != NO_PROMOTION) { if (pLoopUnit->getUnitCombatType() != NO_UNITCOMBAT) { if (GC.getPromotionInfo(ePromotion2).getUnitCombat(pLoopUnit->getUnitCombatType())) { pLoopUnit->setHasPromotion(ePromotion2, true); } } } if (ePromotion3 != NO_PROMOTION) { if (pLoopUnit->getUnitCombatType() != NO_UNITCOMBAT) { if (GC.getPromotionInfo(ePromotion3).getUnitCombat(pLoopUnit->getUnitCombatType())) { pLoopUnit->setHasPromotion(ePromotion3, true); } } } } } else { if (ePromotion1 != NO_PROMOTION) { if (pLoopUnit->getUnitCombatType() != NO_UNITCOMBAT) { if (GC.getPromotionInfo(ePromotion1).getUnitCombat(pLoopUnit->getUnitCombatType())) { pLoopUnit->setHasPromotion(ePromotion1, true); } } } if (ePromotion2 != NO_PROMOTION) { if (pLoopUnit->getUnitCombatType() != NO_UNITCOMBAT) { if (GC.getPromotionInfo(ePromotion2).getUnitCombat(pLoopUnit->getUnitCombatType())) { pLoopUnit->setHasPromotion(ePromotion2, true); } } } if (ePromotion3 != NO_PROMOTION) { if (pLoopUnit->getUnitCombatType() != NO_UNITCOMBAT) { if (GC.getPromotionInfo(ePromotion3).getUnitCombat(pLoopUnit->getUnitCombatType())) { pLoopUnit->setHasPromotion(ePromotion3, true); } } } } } } } } } } } void CvUnit::castDamage(int spell) { bool bResistable = GC.getSpellInfo((SpellTypes)spell).isResistable(); int iDmg = GC.getSpellInfo((SpellTypes)spell).getDamage(); int iDmgLimit = GC.getSpellInfo((SpellTypes)spell).getDamageLimit(); int iDmgType = GC.getSpellInfo((SpellTypes)spell).getDamageType(); int iRange = GC.getSpellInfo((SpellTypes)spell).getRange(); CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; CvPlot* pLoopPlot; for (int i = -iRange; i <= iRange; ++i) { for (int j = -iRange; j <= iRange; ++j) { pLoopPlot = ::plotXY(plot()->getX_INLINE(), plot()->getY_INLINE(), i, j); if (NULL != pLoopPlot) { if (pLoopPlot->getX() != plot()->getX() || pLoopPlot->getY() != plot()->getY()) { pUnitNode = pLoopPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pLoopPlot->nextUnitNode(pUnitNode); if (!pLoopUnit->isImmuneToSpell(this, spell)) { if (bResistable) { if (!pLoopUnit->isResisted(this, spell)) { pLoopUnit->doDamage((iDmg / 2) + GC.getGameINLINE().getSorenRandNum(iDmg, "doDamage"), iDmgLimit, this, iDmgType, true); } } else { pLoopUnit->doDamage((iDmg / 2) + GC.getGameINLINE().getSorenRandNum(iDmg, "doDamage"), iDmgLimit, this, iDmgType, true); } } } } } } } } void CvUnit::castDispel(int spell) { bool bResistable = GC.getSpellInfo((SpellTypes)spell).isResistable(); int iRange = GC.getSpellInfo((SpellTypes)spell).getRange(); CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; CvPlot* pLoopPlot; for (int i = -iRange; i <= iRange; ++i) { for (int j = -iRange; j <= iRange; ++j) { pLoopPlot = ::plotXY(plot()->getX_INLINE(), plot()->getY_INLINE(), i, j); if (NULL != pLoopPlot) { pUnitNode = pLoopPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pLoopPlot->nextUnitNode(pUnitNode); if (!pLoopUnit->isImmuneToSpell(this, spell)) { if (pLoopUnit->isEnemy(getTeam())) { if (bResistable) { if (pLoopUnit->isResisted(this, spell)) { continue; } } for (int iI = 0; iI < GC.getNumPromotionInfos(); iI++) { if (GC.getPromotionInfo((PromotionTypes)iI).isDispellable() && GC.getPromotionInfo((PromotionTypes)iI).getAIWeight() > 0) { pLoopUnit->setHasPromotion((PromotionTypes)iI, false); } } } else { for (int iI = 0; iI < GC.getNumPromotionInfos(); iI++) { if (GC.getPromotionInfo((PromotionTypes)iI).isDispellable() && GC.getPromotionInfo((PromotionTypes)iI).getAIWeight() < 0) { pLoopUnit->setHasPromotion((PromotionTypes)iI, false); } } } } } } } } } void CvUnit::castImmobile(int spell) { bool bResistable = GC.getSpellInfo((SpellTypes)spell).isResistable(); int iImmobileTurns = GC.getSpellInfo((SpellTypes)spell).getImmobileTurns(); int iRange = GC.getSpellInfo((SpellTypes)spell).getRange(); CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; CvPlot* pLoopPlot; for (int i = -iRange; i <= iRange; ++i) { for (int j = -iRange; j <= iRange; ++j) { pLoopPlot = ::plotXY(plot()->getX_INLINE(), plot()->getY_INLINE(), i, j); if (NULL != pLoopPlot) { if (pLoopPlot->getX() != plot()->getX() || pLoopPlot->getY() != plot()->getY()) { pUnitNode = pLoopPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pLoopPlot->nextUnitNode(pUnitNode); if (!pLoopUnit->isImmuneToSpell(this, spell) && pLoopUnit->getImmobileTimer() == 0) { if (bResistable) { if (!pLoopUnit->isResisted(this, spell)) { pLoopUnit->changeImmobileTimer(iImmobileTurns); gDLL->getInterfaceIFace()->addMessage((PlayerTypes)pLoopUnit->getOwner(), true, GC.getEVENT_MESSAGE_TIME(), gDLL->getText("TXT_KEY_MESSAGE_SPELL_IMMOBILE"), "AS2D_DISCOVERBONUS", MESSAGE_TYPE_MAJOR_EVENT, GC.getSpellInfo((SpellTypes)spell).getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), getX_INLINE(), getY_INLINE(), true, true); gDLL->getInterfaceIFace()->addMessage((PlayerTypes)getOwner(), true, GC.getEVENT_MESSAGE_TIME(), gDLL->getText("TXT_KEY_MESSAGE_SPELL_IMMOBILE"), "AS2D_DISCOVERBONUS", MESSAGE_TYPE_MAJOR_EVENT, GC.getSpellInfo((SpellTypes)spell).getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), getX_INLINE(), getY_INLINE(), true, true); } } else { pLoopUnit->changeImmobileTimer(iImmobileTurns); gDLL->getInterfaceIFace()->addMessage((PlayerTypes)pLoopUnit->getOwner(), true, GC.getEVENT_MESSAGE_TIME(), gDLL->getText("TXT_KEY_MESSAGE_SPELL_IMMOBILE"), "AS2D_DISCOVERBONUS", MESSAGE_TYPE_MAJOR_EVENT, GC.getSpellInfo((SpellTypes)spell).getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), getX_INLINE(), getY_INLINE(), true, true); gDLL->getInterfaceIFace()->addMessage((PlayerTypes)getOwner(), true, GC.getEVENT_MESSAGE_TIME(), gDLL->getText("TXT_KEY_MESSAGE_SPELL_IMMOBILE"), "AS2D_DISCOVERBONUS", MESSAGE_TYPE_MAJOR_EVENT, GC.getSpellInfo((SpellTypes)spell).getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), getX_INLINE(), getY_INLINE(), true, true); } } } } } } } } void CvUnit::castPush(int spell) { bool bResistable = GC.getSpellInfo((SpellTypes)spell).isResistable(); int iRange = GC.getSpellInfo((SpellTypes)spell).getRange(); CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; CvPlot* pLoopPlot; CvPlot* pPushPlot; for (int i = -iRange; i <= iRange; ++i) { for (int j = -iRange; j <= iRange; ++j) { int iPushY = plot()->getY_INLINE() + (i*2); pLoopPlot = ::plotXY(plot()->getX_INLINE(), plot()->getY_INLINE(), i, j); pPushPlot = ::plotXY(plot()->getX_INLINE(), plot()->getY_INLINE(), i*2, j*2); if (!pLoopPlot->isCity()) { if (NULL != pLoopPlot) { if (NULL != pPushPlot) { if (pLoopPlot->getX() != plot()->getX() || pLoopPlot->getY() != plot()->getY()) { pUnitNode = pLoopPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pLoopPlot->nextUnitNode(pUnitNode); if (pLoopUnit->canMoveInto(pPushPlot, false, false, false)) { if (!pLoopUnit->isImmuneToSpell(this, spell)) { if (bResistable) { if (!pLoopUnit->isResisted(this, spell)) { pLoopUnit->setXY(pPushPlot->getX(),pPushPlot->getY(),false,true,true); gDLL->getInterfaceIFace()->addMessage((PlayerTypes)pLoopUnit->getOwner(), false, GC.getEVENT_MESSAGE_TIME(), gDLL->getText("TXT_KEY_MESSAGE_SPELL_PUSH"), "AS2D_DISCOVERBONUS", MESSAGE_TYPE_MAJOR_EVENT, GC.getSpellInfo((SpellTypes)spell).getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), getX_INLINE(), getY_INLINE(), true, true); gDLL->getInterfaceIFace()->addMessage((PlayerTypes)getOwner(), false, GC.getEVENT_MESSAGE_TIME(), gDLL->getText("TXT_KEY_MESSAGE_SPELL_PUSH"), "AS2D_DISCOVERBONUS", MESSAGE_TYPE_MAJOR_EVENT, GC.getSpellInfo((SpellTypes)spell).getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), getX_INLINE(), getY_INLINE(), true, true); } } else { pLoopUnit->setXY(pPushPlot->getX(),pPushPlot->getY(),false,true,true); gDLL->getInterfaceIFace()->addMessage((PlayerTypes)pLoopUnit->getOwner(), false, GC.getEVENT_MESSAGE_TIME(), gDLL->getText("TXT_KEY_MESSAGE_SPELL_PUSH"), "AS2D_DISCOVERBONUS", MESSAGE_TYPE_MAJOR_EVENT, GC.getSpellInfo((SpellTypes)spell).getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), getX_INLINE(), getY_INLINE(), true, true); gDLL->getInterfaceIFace()->addMessage((PlayerTypes)getOwner(), false, GC.getEVENT_MESSAGE_TIME(), gDLL->getText("TXT_KEY_MESSAGE_SPELL_PUSH"), "AS2D_DISCOVERBONUS", MESSAGE_TYPE_MAJOR_EVENT, GC.getSpellInfo((SpellTypes)spell).getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), getX_INLINE(), getY_INLINE(), true, true); } } } } } } } } } } } void CvUnit::castRemovePromotion(int spell) { PromotionTypes ePromotion1 = (PromotionTypes)GC.getSpellInfo((SpellTypes)spell).getRemovePromotionType1(); PromotionTypes ePromotion2 = (PromotionTypes)GC.getSpellInfo((SpellTypes)spell).getRemovePromotionType2(); PromotionTypes ePromotion3 = (PromotionTypes)GC.getSpellInfo((SpellTypes)spell).getRemovePromotionType3(); if (GC.getSpellInfo((SpellTypes)spell).isBuffCasterOnly()) { if (ePromotion1 != NO_PROMOTION) { setHasPromotion(ePromotion1, false); } if (ePromotion2 != NO_PROMOTION) { setHasPromotion(ePromotion2, false); } if (ePromotion3 != NO_PROMOTION) { setHasPromotion(ePromotion3, false); } } else { int iRange = GC.getSpellInfo((SpellTypes)spell).getRange(); bool bResistable = GC.getSpellInfo((SpellTypes)spell).isResistable(); CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; CvPlot* pLoopPlot; for (int i = -iRange; i <= iRange; ++i) { for (int j = -iRange; j <= iRange; ++j) { pLoopPlot = ::plotXY(plot()->getX_INLINE(), plot()->getY_INLINE(), i, j); if (NULL != pLoopPlot) { pUnitNode = pLoopPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pLoopPlot->nextUnitNode(pUnitNode); if (!pLoopUnit->isImmuneToSpell(this, spell)) { if (bResistable) { if (!pLoopUnit->isResisted(this, spell)) { if (ePromotion1 != NO_PROMOTION) { pLoopUnit->setHasPromotion(ePromotion1, false); } if (ePromotion2 != NO_PROMOTION) { pLoopUnit->setHasPromotion(ePromotion2, false); } if (ePromotion3 != NO_PROMOTION) { pLoopUnit->setHasPromotion(ePromotion3, false); } } } else { if (ePromotion1 != NO_PROMOTION) { pLoopUnit->setHasPromotion(ePromotion1, false); } if (ePromotion2 != NO_PROMOTION) { pLoopUnit->setHasPromotion(ePromotion2, false); } if (ePromotion3 != NO_PROMOTION) { pLoopUnit->setHasPromotion(ePromotion3, false); } } } } } } } } } void CvUnit::castConvertUnit(int spell) { CvUnit* pUnit; pUnit = GET_PLAYER(getOwnerINLINE()).initUnit((UnitTypes)GC.getSpellInfo((SpellTypes)spell).getConvertUnitType(), getX_INLINE(), getY_INLINE(), AI_getUnitAIType()); pUnit->convert(this); pUnit->changeImmobileTimer(1); } void CvUnit::castCreateUnit(int spell) { int iI; CvUnit* pUnit; pUnit = GET_PLAYER(getOwnerINLINE()).initUnit((UnitTypes)GC.getSpellInfo((SpellTypes)spell).getCreateUnitType(), getX_INLINE(), getY_INLINE(), UNITAI_ATTACK); pUnit->setSummoner(getID()); if (GC.getSpellInfo((SpellTypes)spell).isPermanentUnitCreate()) { pUnit->changeImmobileTimer(2); } else { pUnit->changeDuration(2); if (pUnit->getSpecialUnitType() != GC.getDefineINT("SPECIALUNIT_SPELL")) { pUnit->changeDuration(GET_PLAYER(getOwnerINLINE()).getSummonDuration()); } if (plot()->getTeam() != getTeam()) { GET_PLAYER(getOwnerINLINE()).changeNumOutsideUnits(-1); } } for (iI = 0; iI < GC.getNumPromotionInfos(); iI++) { if (isHasPromotion((PromotionTypes)iI)) { if (GC.getSpellInfo((SpellTypes)spell).isCopyCastersPromotions()) { if (!GC.getPromotionInfo((PromotionTypes)iI).isEquipment() && !GC.getPromotionInfo((PromotionTypes)iI).isRace() && iI != GC.getDefineINT("GREAT_COMMANDER_PROMOTION")) { pUnit->setHasPromotion((PromotionTypes)iI, true); } } //>>>>BUGFfH: Modified by Denev 2009/10/08 /* if summoning action is not a spell (e.g. Hire Goblin), summoner's promotion doesn't affect to summoned creature. */ // else else if (!GC.getSpellInfo((SpellTypes)spell).isAbility()) //<<<<BUGFfH: End Modify { if (GC.getPromotionInfo((PromotionTypes)iI).getPromotionSummonPerk() != NO_PROMOTION) { pUnit->setHasPromotion((PromotionTypes)GC.getPromotionInfo((PromotionTypes)iI).getPromotionSummonPerk(), true); } } } } if (GC.getSpellInfo((SpellTypes)spell).getCreateUnitPromotion() != NO_PROMOTION) { pUnit->setHasPromotion((PromotionTypes)GC.getSpellInfo((SpellTypes)spell).getCreateUnitPromotion(), true); } pUnit->doTurn(); if (!isHuman()) { /*************************************************************************************************/ /** BETTER AI (Better use of Summons) Sephi **/ /** **/ /** **/ /*************************************************************************************************/ if (GET_PLAYER(getOwnerINLINE()).AI_isSummonSuicideMode()) { if (pUnit->canMove()) { pUnit->AI_setGroupflag(GROUPFLAG_NONE); pUnit->setSuicideSummon(true); pUnit->AI_update(); } } else if (pUnit->getUnitType()==GC.getDefineINT("UNIT_FIREBALL")) { if (pUnit->bombard()) { return; } } if (pUnit->getDuration()>0) { if (pUnit->getMoves()>0) { pUnit->joinGroup(getGroup(),false,true); } } /*************************************************************************************************/ /** END **/ /*************************************************************************************************/ } } bool CvUnit::isHasCasted() const { return m_bHasCasted; } void CvUnit::setHasCasted(bool bNewValue) { m_bHasCasted = bNewValue; } bool CvUnit::isIgnoreHide() const { return m_bIgnoreHide; } void CvUnit::setIgnoreHide(bool bNewValue) { m_bIgnoreHide = bNewValue; } bool CvUnit::isImmuneToSpell(CvUnit* pCaster, int spell) const { if (isImmuneToMagic()) { if (!GC.getSpellInfo((SpellTypes)spell).isAbility()) { return true; } } if (GC.getSpellInfo((SpellTypes)spell).isImmuneTeam()) { if (getTeam() == pCaster->getTeam()) { return true; } } if (GC.getSpellInfo((SpellTypes)spell).isImmuneNeutral()) { if (getTeam() != pCaster->getTeam()) { if (!isEnemy(pCaster->getTeam())) { return true; } } } if (GC.getSpellInfo((SpellTypes)spell).isImmuneEnemy()) { if (isEnemy(pCaster->getTeam())) { return true; } } if (GC.getSpellInfo((SpellTypes)spell).isImmuneFlying()) { if (isFlying()) { return true; } } if (GC.getSpellInfo((SpellTypes)spell).isImmuneNotAlive()) { if (!isAlive()) { return true; } } return false; } int CvUnit::getDelayedSpell() const { return m_iDelayedSpell; } void CvUnit::setDelayedSpell(int iNewValue) { m_iDelayedSpell = iNewValue; } int CvUnit::getDuration() const { return m_iDuration; } void CvUnit::setDuration(int iNewValue) { m_iDuration = iNewValue; } void CvUnit::changeDuration(int iChange) { setDuration(getDuration() + iChange); } bool CvUnit::isFleeWithdrawl() const { return m_bFleeWithdrawl; } void CvUnit::setFleeWithdrawl(bool bNewValue) { m_bFleeWithdrawl = bNewValue; } bool CvUnit::isAlive() const { return m_iAlive == 0 ? true : false; } void CvUnit::changeAlive(int iNewValue) { if (iNewValue != 0) { m_iAlive += iNewValue; } } bool CvUnit::isAIControl() const { return m_iAIControl == 0 ? false : true; } void CvUnit::changeAIControl(int iNewValue) { if (iNewValue != 0) { m_iAIControl += iNewValue; } } bool CvUnit::isBoarding() const { return m_iBoarding == 0 ? false : true; } void CvUnit::changeBoarding(int iNewValue) { if (iNewValue != 0) { m_iBoarding += iNewValue; } } int CvUnit::getDefensiveStrikeChance() const { return m_iDefensiveStrikeChance; } void CvUnit::changeDefensiveStrikeChance(int iChange) { if (iChange != 0) { m_iDefensiveStrikeChance += iChange; } } int CvUnit::getDefensiveStrikeDamage() const { return m_iDefensiveStrikeDamage; } void CvUnit::changeDefensiveStrikeDamage(int iChange) { if (iChange != 0) { m_iDefensiveStrikeDamage += iChange; } } bool CvUnit::isDoubleFortifyBonus() const { return m_iDoubleFortifyBonus == 0 ? false : true; } void CvUnit::changeDoubleFortifyBonus(int iNewValue) { if (iNewValue != 0) { m_iDoubleFortifyBonus += iNewValue; } } bool CvUnit::isFear() const { return m_iFear == 0 ? false : true; } void CvUnit::changeFear(int iNewValue) { if (iNewValue != 0) { m_iFear += iNewValue; } } bool CvUnit::isFlying() const { return m_iFlying == 0 ? false : true; } void CvUnit::changeFlying(int iNewValue) { if (iNewValue != 0) { m_iFlying += iNewValue; } } bool CvUnit::isHeld() const { return m_iHeld == 0 ? false : true; } void CvUnit::changeHeld(int iNewValue) { if (iNewValue != 0) { m_iHeld += iNewValue; } } bool CvUnit::isHiddenNationality() const { if (isCargo()) { if (!getTransportUnit()->isHiddenNationality()) { return false; } } return m_iHiddenNationality == 0 ? false : true; } void CvUnit::changeHiddenNationality(int iNewValue) { if (iNewValue != 0) { if (m_iHiddenNationality + iNewValue == 0) { updatePlunder(-1, false); m_iHiddenNationality += iNewValue; joinGroup(NULL, true); updatePlunder(1, false); } else { m_iHiddenNationality += iNewValue; } } } void CvUnit::changeIgnoreBuildingDefense(int iNewValue) { if (iNewValue != 0) { m_iIgnoreBuildingDefense += iNewValue; } } bool CvUnit::isImmortal() const { return m_iImmortal == 0 ? false : true; } void CvUnit::changeImmortal(int iNewValue) { if (iNewValue != 0) { m_iImmortal += iNewValue; if (m_iImmortal < 0) { m_iImmortal = 0; } } } bool CvUnit::isImmuneToCapture() const { return m_iImmuneToCapture == 0 ? false : true; } void CvUnit::changeImmuneToCapture(int iNewValue) { if (iNewValue != 0) { m_iImmuneToCapture += iNewValue; } } bool CvUnit::isImmuneToDefensiveStrike() const { return m_iImmuneToDefensiveStrike == 0 ? false : true; } void CvUnit::changeImmuneToDefensiveStrike(int iChange) { if (iChange != 0) { m_iImmuneToDefensiveStrike += iChange; } } bool CvUnit::isImmuneToFear() const { if(!isAlive()) { return true; } return m_iImmuneToFear == 0 ? false : true; } void CvUnit::changeImmuneToFear(int iNewValue) { if (iNewValue != 0) { m_iImmuneToFear += iNewValue; } } bool CvUnit::isImmuneToMagic() const { return m_iImmuneToMagic == 0 ? false : true; } void CvUnit::changeImmuneToMagic(int iNewValue) { if (iNewValue != 0) { m_iImmuneToMagic += iNewValue; } } bool CvUnit::isInvisibleFromPromotion() const { return m_iInvisible == 0 ? false : true; } void CvUnit::changeInvisibleFromPromotion(int iNewValue) { if (iNewValue != 0) { m_iInvisible += iNewValue; if (!isInvisibleFromPromotion() && plot()->isVisibleEnemyUnit(this)) { if (getDomainType() != DOMAIN_IMMOBILE) { withdrawlToNearestValidPlot(true); } } } } bool CvUnit::isSeeInvisible() const { return m_iSeeInvisible == 0 ? false : true; } void CvUnit::changeSeeInvisible(int iNewValue) { if (iNewValue != 0) { m_iSeeInvisible += iNewValue; } } void CvUnit::changeOnlyDefensive(int iNewValue) { if (iNewValue != 0) { m_iOnlyDefensive += iNewValue; } } bool CvUnit::isTargetWeakestUnit() const { return m_iTargetWeakestUnit == 0 ? false : true; } void CvUnit::changeTargetWeakestUnit(int iNewValue) { if (iNewValue != 0) { m_iTargetWeakestUnit += iNewValue; } } bool CvUnit::isTargetWeakestUnitCounter() const { return m_iTargetWeakestUnitCounter == 0 ? false : true; } void CvUnit::changeTargetWeakestUnitCounter(int iNewValue) { if (iNewValue != 0) { m_iTargetWeakestUnitCounter += iNewValue; } } bool CvUnit::isTwincast() const { return m_iTwincast == 0 ? false : true; } void CvUnit::changeTwincast(int iNewValue) { if (iNewValue != 0) { m_iTwincast += iNewValue; } } bool CvUnit::isWaterWalking() const { return m_iWaterWalking == 0 ? false : true; } void CvUnit::changeWaterWalking(int iNewValue) { if (iNewValue != 0) { m_iWaterWalking += iNewValue; } } int CvUnit::getBetterDefenderThanPercent() const { return m_iBetterDefenderThanPercent; } void CvUnit::changeBetterDefenderThanPercent(int iChange) { if (iChange != 0) { m_iBetterDefenderThanPercent = (m_iBetterDefenderThanPercent + iChange); } } int CvUnit::getCombatHealPercent() const { return m_iCombatHealPercent; } void CvUnit::changeCombatHealPercent(int iChange) { if (iChange != 0) { m_iCombatHealPercent = (m_iCombatHealPercent + iChange); } } void CvUnit::calcCombatLimit() { int iBestValue = m_pUnitInfo->getCombatLimit(); int iValue = 0; for (int iI = 0; iI < GC.getNumPromotionInfos(); iI++) { if (isHasPromotion((PromotionTypes)iI)) { iValue = GC.getPromotionInfo((PromotionTypes)iI).getCombatLimit(); if (iValue != 0) { if (iValue < iBestValue) { iBestValue = iValue; } } } } m_iCombatLimit = iBestValue; } int CvUnit::getCombatPercentInBorders() const { return m_iCombatPercentInBorders; } void CvUnit::changeCombatPercentInBorders(int iChange) { if (iChange != 0) { m_iCombatPercentInBorders = (m_iCombatPercentInBorders + iChange); setInfoBarDirty(true); } } int CvUnit::getCombatPercentGlobalCounter() const { return m_iCombatPercentGlobalCounter; } void CvUnit::changeCombatPercentGlobalCounter(int iChange) { if (iChange != 0) { m_iCombatPercentGlobalCounter = (m_iCombatPercentGlobalCounter + iChange); setInfoBarDirty(true); } } int CvUnit::getFreePromotionPick() const { return m_iFreePromotionPick; } void CvUnit::changeFreePromotionPick(int iChange) { if (iChange != 0) { m_iFreePromotionPick = getFreePromotionPick() + iChange; } } int CvUnit::getGoldFromCombat() const { return m_iGoldFromCombat; } void CvUnit::changeGoldFromCombat(int iChange) { if (iChange != 0) { m_iGoldFromCombat = getGoldFromCombat() + iChange; } } void CvUnit::setGroupSize(int iNewValue) { m_iGroupSize = iNewValue; } void CvUnit::mutate() { int iMutationChance = GC.getDefineINT("MUTATION_CHANCE"); for (int iI = 0; iI < GC.getNumPromotionInfos(); iI++) { if (GC.getPromotionInfo((PromotionTypes)iI).isMutation()) { if (GC.getGameINLINE().getSorenRandNum(100, "Mutation") <= iMutationChance) { setHasPromotion(((PromotionTypes)iI), true); } } } } int CvUnit::getWithdrawlProbDefensive() const { if (getImmobileTimer() > 0) { return 0; } return std::max(0, (m_pUnitInfo->getWithdrawlProbDefensive() + getExtraWithdrawal())); } void CvUnit::setInvisibleType(int iNewValue) { m_iInvisibleType = iNewValue; } int CvUnit::getRace() const { return m_iRace; } void CvUnit::setRace(int iNewValue) { if (m_iRace != NO_PROMOTION) { setHasPromotion((PromotionTypes)m_iRace, false); } m_iRace = iNewValue; } int CvUnit::getReligion() const { return m_iReligion; } void CvUnit::setReligion(int iReligion) { m_iReligion = iReligion; } int CvUnit::getResist() const { return m_iResist; } void CvUnit::setResist(int iNewValue) { m_iResist = iNewValue; } void CvUnit::changeResist(int iChange) { setResist(getResist() + iChange); } int CvUnit::getResistModify() const { return m_iResistModify; } void CvUnit::setResistModify(int iNewValue) { m_iResistModify = iNewValue; } void CvUnit::changeResistModify(int iChange) { setResistModify(getResistModify() + iChange); } int CvUnit::getScenarioCounter() const { return m_iScenarioCounter; } void CvUnit::setScenarioCounter(int iNewValue) { m_iScenarioCounter = iNewValue; } int CvUnit::getSpellCasterXP() const { if (!m_pUnitInfo->isFreeXP()) { return 0; } return m_iSpellCasterXP; } void CvUnit::changeSpellCasterXP(int iChange) { if (iChange != 0) { m_iSpellCasterXP += iChange; } } int CvUnit::getSpellDamageModify() const { return m_iSpellDamageModify; } void CvUnit::changeSpellDamageModify(int iChange) { if (iChange != 0) { m_iSpellDamageModify += iChange; } } int CvUnit::getSummoner() const { return m_iSummoner; } void CvUnit::setSummoner(int iNewValue) { m_iSummoner = iNewValue; } int CvUnit::getWorkRateModify() const { return m_iWorkRateModify; } void CvUnit::changeWorkRateModify(int iChange) { if (iChange != 0) { m_iWorkRateModify += iChange; } } bool CvUnit::isResisted(CvUnit* pCaster, int iSpell) const { if (GC.getGameINLINE().getSorenRandNum(100, "is Resisted") <= getResistChance(pCaster, iSpell)) { gDLL->getInterfaceIFace()->addMessage(getOwner(), true, GC.getEVENT_MESSAGE_TIME(), gDLL->getText("TXT_KEY_MESSAGE_SPELL_RESISTED"), "", MESSAGE_TYPE_MAJOR_EVENT, "art/interface/buttons/promotions/magicresistance.dds", (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), getX_INLINE(), getY_INLINE(), true, true); gDLL->getInterfaceIFace()->addMessage(pCaster->getOwner(), true, GC.getEVENT_MESSAGE_TIME(), gDLL->getText("TXT_KEY_MESSAGE_SPELL_RESISTED"), "", MESSAGE_TYPE_MAJOR_EVENT, "art/interface/buttons/promotions/magicresistance.dds", (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), getX_INLINE(), getY_INLINE(), true, true); gDLL->getInterfaceIFace()->playGeneralSound("AS3D_RESIST", plot()->getPoint()); return true; } return false; } int CvUnit::getResistChance(CvUnit* pCaster, int iSpell) const { if (isImmuneToSpell(pCaster, iSpell)) { return 100; } int iResist = GC.getDefineINT("SPELL_RESIST_CHANCE_BASE"); iResist += getLevel() * 5; iResist += getResist(); iResist += pCaster->getResistModify(); iResist += GC.getSpellInfo((SpellTypes)iSpell).getResistModify(); iResist += GET_PLAYER(getOwnerINLINE()).getResistModify(); iResist += GET_PLAYER(pCaster->getOwnerINLINE()).getResistEnemyModify(); if (plot()->isCity()) { iResist += 10; iResist += plot()->getPlotCity()->getResistMagic(); } if (iResist >= GC.getDefineINT("SPELL_RESIST_CHANCE_MAX")) { iResist = GC.getDefineINT("SPELL_RESIST_CHANCE_MAX"); } if (iResist <= GC.getDefineINT("SPELL_RESIST_CHANCE_MIN")) { iResist = GC.getDefineINT("SPELL_RESIST_CHANCE_MIN"); } return iResist; } void CvUnit::changeBaseCombatStr(int iChange) { setBaseCombatStr(m_iBaseCombat + iChange); } void CvUnit::changeBaseCombatStrDefense(int iChange) { setBaseCombatStrDefense(m_iBaseCombatDefense + iChange); } int CvUnit::getUnitArtStyleType() const { return m_iUnitArtStyleType; } void CvUnit::setUnitArtStyleType(int iNewValue) { m_iUnitArtStyleType = iNewValue; } int CvUnit::chooseSpell() { int iBestSpell = -1; int iRange; int iTempValue; int iValue; int iBestSpellValue = 0; CvPlot* pLoopPlot; CvUnit* pLoopUnit; CLLNode<IDInfo>* pUnitNode; for (int iSpell = 0; iSpell < GC.getNumSpellInfos(); iSpell++) { iValue = 0; if (canCast(iSpell, false)) { iRange = GC.getSpellInfo((SpellTypes)iSpell).getRange(); if (GC.getSpellInfo((SpellTypes)iSpell).getCreateUnitType() != NO_UNIT) { int iMoveRange = GC.getUnitInfo((UnitTypes)GC.getSpellInfo((SpellTypes)iSpell).getCreateUnitType()).getMoves() + getExtraSpellMove(); bool bEnemy = false; for (int i = -iMoveRange; i <= iMoveRange; ++i) { for (int j = -iMoveRange; j <= iMoveRange; ++j) { pLoopPlot = ::plotXY(plot()->getX_INLINE(), plot()->getY_INLINE(), i, j); if (NULL != pLoopPlot) { if (pLoopPlot->isVisibleEnemyUnit(this)) { bEnemy = true; } } } } if (bEnemy) { iTempValue = GC.getUnitInfo((UnitTypes)GC.getSpellInfo((SpellTypes)iSpell).getCreateUnitType()).getCombat(); for (int iI = 0; iI < GC.getNumDamageTypeInfos(); iI++) { iTempValue += GC.getUnitInfo((UnitTypes)GC.getSpellInfo((SpellTypes)iSpell).getCreateUnitType()).getDamageTypeCombat(iI); } iTempValue *= 100; iTempValue *= GC.getSpellInfo((SpellTypes)iSpell).getCreateUnitNum(); iValue += iTempValue; } } if (GC.getSpellInfo((SpellTypes)iSpell).getDamage() != 0) { int iDmg = GC.getSpellInfo((SpellTypes)iSpell).getDamage(); int iDmgLimit = GC.getSpellInfo((SpellTypes)iSpell).getDamageLimit(); for (int i = -iRange; i <= iRange; ++i) { for (int j = -iRange; j <= iRange; ++j) { pLoopPlot = ::plotXY(plot()->getX_INLINE(), plot()->getY_INLINE(), i, j); if (NULL != pLoopPlot) { if (pLoopPlot->getX() != plot()->getX() || pLoopPlot->getY() != plot()->getY()) { pUnitNode = pLoopPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pLoopPlot->nextUnitNode(pUnitNode); if (!pLoopUnit->isImmuneToSpell(this, iSpell)) { if (pLoopUnit->isEnemy(getTeam())) { if (pLoopUnit->getDamage() < iDmgLimit) { iValue += iDmg * 10; } } if (pLoopUnit->getTeam() == getTeam()) { iValue -= iDmg * 20; } if (pLoopUnit->getTeam() != getTeam() && pLoopUnit->isEnemy(getTeam()) == false) { iValue -= 1000; } } } } } } } } if (GC.getSpellInfo((SpellTypes)iSpell).getAddPromotionType1() != NO_PROMOTION) { iValue += AI_promotionValue((PromotionTypes)GC.getSpellInfo((SpellTypes)iSpell).getAddPromotionType1()); } if (GC.getSpellInfo((SpellTypes)iSpell).getAddPromotionType2() != NO_PROMOTION) { iValue += AI_promotionValue((PromotionTypes)GC.getSpellInfo((SpellTypes)iSpell).getAddPromotionType2()); } if (GC.getSpellInfo((SpellTypes)iSpell).getAddPromotionType3() != NO_PROMOTION) { iValue += AI_promotionValue((PromotionTypes)GC.getSpellInfo((SpellTypes)iSpell).getAddPromotionType3()); } if (GC.getSpellInfo((SpellTypes)iSpell).getRemovePromotionType1() != NO_PROMOTION) { iValue -= AI_promotionValue((PromotionTypes)GC.getSpellInfo((SpellTypes)iSpell).getRemovePromotionType1()); } if (GC.getSpellInfo((SpellTypes)iSpell).getRemovePromotionType2() != NO_PROMOTION) { iValue -= AI_promotionValue((PromotionTypes)GC.getSpellInfo((SpellTypes)iSpell).getRemovePromotionType2()); } if (GC.getSpellInfo((SpellTypes)iSpell).getRemovePromotionType3() != NO_PROMOTION) { iValue -= AI_promotionValue((PromotionTypes)GC.getSpellInfo((SpellTypes)iSpell).getRemovePromotionType3()); } if (GC.getSpellInfo((SpellTypes)iSpell).getConvertUnitType() != NO_UNIT) { iValue += GET_PLAYER(getOwnerINLINE()).AI_unitValue((UnitTypes)GC.getSpellInfo((SpellTypes)iSpell).getConvertUnitType(), UNITAI_ATTACK, area()); iValue -= GET_PLAYER(getOwnerINLINE()).AI_unitValue((UnitTypes)getUnitType(), UNITAI_ATTACK, area()); } if (GC.getSpellInfo((SpellTypes)iSpell).getCreateBuildingType() != NO_BUILDING) { iValue += plot()->getPlotCity()->AI_buildingValue((BuildingTypes)GC.getSpellInfo((SpellTypes)iSpell).getCreateBuildingType()); } if (GC.getSpellInfo((SpellTypes)iSpell).getCreateFeatureType() != NO_FEATURE) { iValue += 10; } if (GC.getSpellInfo((SpellTypes)iSpell).getCreateImprovementType() != NO_IMPROVEMENT) { iValue += 10; } if (GC.getSpellInfo((SpellTypes)iSpell).isDispel()) { iValue += 25 * (iRange + 1) * (iRange + 1); } if (GC.getSpellInfo((SpellTypes)iSpell).isPush()) { iValue += 20 * (iRange + 1) * (iRange + 1); if (plot()->isCity()) { iValue *= 3; } } if (GC.getSpellInfo((SpellTypes)iSpell).getChangePopulation() != 0) { iValue += 50 * GC.getSpellInfo((SpellTypes)iSpell).getChangePopulation(); } if (GC.getSpellInfo((SpellTypes)iSpell).getCost() != 0) { iValue -= 4 * GC.getSpellInfo((SpellTypes)iSpell).getCost(); } if (GC.getSpellInfo((SpellTypes)iSpell).getImmobileTurns() != 0) { iValue += 20 * GC.getSpellInfo((SpellTypes)iSpell).getImmobileTurns() * (iRange + 1) * (iRange + 1); } if (GC.getSpellInfo((SpellTypes)iSpell).isSacrificeCaster()) { iValue -= getLevel() * GET_PLAYER(getOwnerINLINE()).AI_unitValue((UnitTypes)getUnitType(), UNITAI_ATTACK, area()); } if (GC.getSpellInfo((SpellTypes)iSpell).isResistable()) { iValue /= 2; } iValue += GC.getSpellInfo((SpellTypes)iSpell).getAIWeight(); if (iValue > iBestSpellValue) { iBestSpellValue = iValue; iBestSpell = iSpell; } } } return iBestSpell; } int CvUnit::getExtraSpellMove() const { int iCount = 0; for (int iI = 0; iI < GC.getNumPromotionInfos(); iI++) { if (isHasPromotion((PromotionTypes)iI)) { if (GC.getPromotionInfo((PromotionTypes)iI).getPromotionSummonPerk() != NO_PROMOTION) { iCount += GC.getPromotionInfo((PromotionTypes)GC.getPromotionInfo((PromotionTypes)iI).getPromotionSummonPerk()).getMovesChange(); } } } return iCount; } void CvUnit::doDamage(int iDmg, int iDmgLimit, CvUnit* pAttacker, int iDmgType, bool bStartWar) { if (isDelayedDeath()) //prevents some pyre zombie caused CtD's 05/23/2010 { return; } CvWString szMessage; int iResist; iResist = baseCombatStrDefense() *2; iResist += getLevel() * 2; if (plot()->getPlotCity() != NULL) { iResist += (plot()->getPlotCity()->getDefenseModifier(false) / 4); } if (iDmgType != -1) { iResist += getDamageTypeResist((DamageTypes)iDmgType); } if (pAttacker != NULL && iDmgType != DAMAGE_PHYSICAL) { iDmg += pAttacker->getSpellDamageModify(); } if (iResist < 100) { iDmg = GC.getGameINLINE().getSorenRandNum(iDmg, "Damage") + GC.getGameINLINE().getSorenRandNum(iDmg, "Damage"); iDmg = iDmg * (100 - iResist) / 100; if (iDmg + getDamage() > iDmgLimit) { iDmg = iDmgLimit - getDamage(); } if (iDmg > 0) { if (iDmg + getDamage() >= GC.getMAX_HIT_POINTS()) { szMessage = gDLL->getText("TXT_KEY_MESSAGE_KILLED_BY", m_pUnitInfo->getDescription(), GC.getDamageTypeInfo((DamageTypes)iDmgType).getDescription()); } else { szMessage = gDLL->getText("TXT_KEY_MESSAGE_DAMAGED_BY", m_pUnitInfo->getDescription(), iDmg, GC.getDamageTypeInfo((DamageTypes)iDmgType).getDescription()); } gDLL->getInterfaceIFace()->addMessage(((PlayerTypes)getOwner()), true, GC.getDefineINT("EVENT_MESSAGE_TIME"), szMessage, "", MESSAGE_TYPE_MAJOR_EVENT, GC.getDamageTypeInfo((DamageTypes)iDmgType).getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), getX_INLINE(), getY_INLINE(), true, true); if (pAttacker != NULL) { gDLL->getInterfaceIFace()->addMessage(((PlayerTypes)pAttacker->getOwner()), true, GC.getDefineINT("EVENT_MESSAGE_TIME"), szMessage, "", MESSAGE_TYPE_MAJOR_EVENT, GC.getDamageTypeInfo((DamageTypes)iDmgType).getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), getX_INLINE(), getY_INLINE(), true, true); changeDamage(iDmg, pAttacker->getOwner()); if (getDamage() >= GC.getMAX_HIT_POINTS()) { kill(true,pAttacker->getOwner()); } if (bStartWar) { if (!(pAttacker->isHiddenNationality()) && !(isHiddenNationality())) { /*************************************************************************************************/ /** GAMECHANGE (Different condition for Areaspells to trigger war) Sephi **/ /** **/ /** **/ /*************************************************************************************************/ /** orig if (getTeam() != pAttacker->getTeam()) { if (!GET_TEAM(pAttacker->getTeam()).isPermanentWarPeace(getTeam())) { GET_TEAM(pAttacker->getTeam()).declareWar(getTeam(), false, WARPLAN_TOTAL); } } **/ if (getTeam()==plot()->getTeam()) { if (!GET_TEAM(getTeam()).isVassal(pAttacker->getTeam()) && !GET_TEAM(pAttacker->getTeam()).isVassal(getTeam())) { if (getTeam() != pAttacker->getTeam()) { if (!GET_TEAM(pAttacker->getTeam()).isPermanentWarPeace(getTeam())) { GET_TEAM(pAttacker->getTeam()).declareWar(getTeam(), false, WARPLAN_TOTAL); } } } } /*************************************************************************************************/ /** END **/ /*************************************************************************************************/ } } } else { changeDamage(iDmg, NO_PLAYER); if (getDamage() >= GC.getMAX_HIT_POINTS()) { kill(true,NO_PLAYER); } } } } } void CvUnit::doDefensiveStrike(CvUnit* pAttacker) { CvUnit* pBestUnit; int iBestDamage = 0; CvPlot* pPlot = plot(); CLLNode<IDInfo>* pUnitNode = pPlot->headUnitNode(); while (pUnitNode != NULL) { CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); if (pLoopUnit->getDefensiveStrikeChance() > 0) { if (atWar(pLoopUnit->getTeam(), pAttacker->getTeam())) { if (pLoopUnit->isBlitz() || !pLoopUnit->isMadeAttack()) { if (GC.getGameINLINE().getSorenRandNum(100, "Defensive Strike") < pLoopUnit->getDefensiveStrikeChance()) { if (pLoopUnit->getDefensiveStrikeDamage() > iBestDamage) { iBestDamage = pLoopUnit->getDefensiveStrikeDamage(); pBestUnit = pLoopUnit; } } } } } } if (iBestDamage > 0) { if (!pBestUnit->isBlitz()) { pBestUnit->setMadeAttack(true); } int iDmg = 0; iDmg += GC.getGameINLINE().getSorenRandNum(pBestUnit->getDefensiveStrikeDamage(), "Defensive Strike 1"); iDmg += GC.getGameINLINE().getSorenRandNum(pBestUnit->getDefensiveStrikeDamage(), "Defensive Strike 2"); iDmg -= pAttacker->baseCombatStrDefense() * 2; iDmg -= pAttacker->getLevel(); if (iDmg + pAttacker->getDamage() > 95) { iDmg = 95 - pAttacker->getDamage(); } if (iDmg > 0) { pAttacker->changeDamage(iDmg, pBestUnit->getOwner()); CvWString szMessage = gDLL->getText("TXT_KEY_MESSAGE_DEFENSIVE_STRIKE_BY", GC.getUnitInfo((UnitTypes)pAttacker->getUnitType()).getDescription(), iDmg, GC.getUnitInfo((UnitTypes)pBestUnit->getUnitType()).getDescription()); gDLL->getInterfaceIFace()->addMessage(((PlayerTypes)pAttacker->getOwner()), true, GC.getDefineINT("EVENT_MESSAGE_TIME"), szMessage, "", MESSAGE_TYPE_MAJOR_EVENT, GC.getUnitInfo((UnitTypes)pBestUnit->getUnitType()).getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pAttacker->getX(), pAttacker->getY(), true, true); szMessage = gDLL->getText("TXT_KEY_MESSAGE_DEFENSIVE_STRIKE", GC.getUnitInfo((UnitTypes)pBestUnit->getUnitType()).getDescription(), GC.getUnitInfo((UnitTypes)pAttacker->getUnitType()).getDescription(), iDmg); gDLL->getInterfaceIFace()->addMessage(((PlayerTypes)pBestUnit->getOwner()), true, GC.getDefineINT("EVENT_MESSAGE_TIME"), szMessage, "", MESSAGE_TYPE_MAJOR_EVENT, GC.getUnitInfo((UnitTypes)pBestUnit->getUnitType()).getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pAttacker->getX(), pAttacker->getY(), true, true); pBestUnit->changeExperience(1, 100, true, false, false); } } } void CvUnit::doEscape() { if (GET_PLAYER(getOwnerINLINE()).getCapitalCity() != NULL) { setXY(GET_PLAYER(getOwnerINLINE()).getCapitalCity()->getX(), GET_PLAYER(getOwnerINLINE()).getCapitalCity()->getY(), false, true, true); } } void CvUnit::doImmortalRebirth() { joinGroup(NULL); setDamage(75, NO_PLAYER); bool bFromProm = false; for (int iI = 0; iI < GC.getNumPromotionInfos(); iI++) { if (isHasPromotion((PromotionTypes)iI)) { if (GC.getPromotionInfo((PromotionTypes)iI).isImmortal()) { setHasPromotion(((PromotionTypes)iI), false); bFromProm = true; break; } } } if (!bFromProm) { changeImmortal(-1); } doEscape(); /*************************************************************************************************/ /** BETTER AI (Immortal Units heal) Sephi **/ /** **/ /** **/ /*************************************************************************************************/ if (!isHuman()) { getGroup()->pushMission(MISSION_HEAL); } /*************************************************************************************************/ /** END **/ /*************************************************************************************************/ } void CvUnit::combatWon(CvUnit* pLoser, bool bAttacking) { PromotionTypes ePromotion; bool bConvert = false; int iUnit = NO_UNIT; CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; CvPlot* pPlot; CvUnit* pUnit; for (int iI = 0; iI < GC.getNumPromotionInfos(); iI++) { if (isHasPromotion((PromotionTypes)iI)) { if (GC.getPromotionInfo((PromotionTypes)iI).getFreeXPFromCombat() != 0) { changeExperience(GC.getPromotionInfo((PromotionTypes)iI).getFreeXPFromCombat(), -1, false, false, false); } if (GC.getPromotionInfo((PromotionTypes)iI).getModifyGlobalCounterOnCombat() != 0) { if (pLoser->isAlive()) { GC.getGameINLINE().changeGlobalCounter(GC.getPromotionInfo((PromotionTypes)iI).getModifyGlobalCounterOnCombat()); } } if (GC.getPromotionInfo((PromotionTypes)iI).isRemovedByCombat()) { setHasPromotion(((PromotionTypes)iI), false); } if (GC.getPromotionInfo((PromotionTypes)iI).getPromotionCombatApply() != NO_PROMOTION) { ePromotion = (PromotionTypes)GC.getPromotionInfo((PromotionTypes)iI).getPromotionCombatApply(); pPlot = pLoser->plot(); pUnitNode = pPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); if (pLoopUnit->isHasPromotion(ePromotion) == false) { if (pLoopUnit->isAlive() || !GC.getPromotionInfo(ePromotion).isPrereqAlive()) { if (isEnemy(pLoopUnit->getTeam())) { if (pLoopUnit->canAcquirePromotion(ePromotion)) { if (GC.getGameINLINE().getSorenRandNum(100, "Combat Apply") <= GC.getDefineINT("COMBAT_APPLY_CHANCE")) { pLoopUnit->setHasPromotion(ePromotion, true); gDLL->getInterfaceIFace()->addMessage((PlayerTypes)pLoopUnit->getOwner(), true, GC.getEVENT_MESSAGE_TIME(), GC.getPromotionInfo(ePromotion).getDescription(), "", MESSAGE_TYPE_INFO, GC.getPromotionInfo(ePromotion).getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), getX_INLINE(), getY_INLINE(), true, true); gDLL->getInterfaceIFace()->addMessage((PlayerTypes)getOwner(), true, GC.getEVENT_MESSAGE_TIME(), GC.getPromotionInfo(ePromotion).getDescription(), "", MESSAGE_TYPE_INFO, GC.getPromotionInfo(ePromotion).getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), getX_INLINE(), getY_INLINE(), true, true); } } } } } } } if (GC.getPromotionInfo((PromotionTypes)iI).getCombatCapturePercent() != 0) { if (iUnit == NO_UNIT && pLoser->isAlive()) { if (GC.getGameINLINE().getSorenRandNum(100, "Combat Capture") <= GC.getPromotionInfo((PromotionTypes)iI).getCombatCapturePercent()) { iUnit = pLoser->getUnitType(); bConvert = true; } } } if (GC.getPromotionInfo((PromotionTypes)iI).getCaptureUnitCombat() != NO_UNITCOMBAT) { if (iUnit == NO_UNIT && pLoser->getUnitCombatType() == GC.getPromotionInfo((PromotionTypes)iI).getCaptureUnitCombat()) { iUnit = pLoser->getUnitType(); bConvert = true; } } } if (pLoser->isHasPromotion((PromotionTypes)iI)) { if (GC.getPromotionInfo((PromotionTypes)iI).getPromotionCombatApply() != NO_PROMOTION) { ePromotion = (PromotionTypes)GC.getPromotionInfo((PromotionTypes)iI).getPromotionCombatApply(); if (isHasPromotion(ePromotion) == false) { if (isAlive() || !GC.getPromotionInfo(ePromotion).isPrereqAlive()) { if (pLoser->isEnemy(getTeam())) { if (GC.getGameINLINE().getSorenRandNum(100, "Combat Apply") <= GC.getDefineINT("COMBAT_APPLY_CHANCE")) { setHasPromotion(ePromotion, true); gDLL->getInterfaceIFace()->addMessage((PlayerTypes)getOwner(), true, GC.getEVENT_MESSAGE_TIME(), GC.getPromotionInfo(ePromotion).getDescription(), "", MESSAGE_TYPE_INFO, GC.getPromotionInfo(ePromotion).getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), getX_INLINE(), getY_INLINE(), true, true); gDLL->getInterfaceIFace()->addMessage((PlayerTypes)pLoser->getOwner(), true, GC.getEVENT_MESSAGE_TIME(), GC.getPromotionInfo(ePromotion).getDescription(), "", MESSAGE_TYPE_INFO, GC.getPromotionInfo(ePromotion).getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), getX_INLINE(), getY_INLINE(), true, true); } } } } } } } if (GET_PLAYER(getOwnerINLINE()).getFreeXPFromCombat() != 0) { changeExperience(GET_PLAYER(getOwnerINLINE()).getFreeXPFromCombat(), -1, false, false, false); } if (getCombatHealPercent() != 0) { if (pLoser->isAlive()) { int i = getCombatHealPercent(); if (i > getDamage()) { i = getDamage(); } if (i != 0) { changeDamage(-1 * i, NO_PLAYER); } } } if (m_pUnitInfo->isExplodeInCombat() && m_pUnitInfo->isSuicide()) { if (bAttacking) { pPlot = pLoser->plot(); } else { pPlot = plot(); } if (plot()->isVisibleToWatchingHuman()) { gDLL->getEngineIFace()->TriggerEffect((EffectTypes)GC.getInfoTypeForString("EFFECT_ARTILLERY_SHELL_EXPLODE"), pPlot->getPoint(), (float)(GC.getASyncRand().get(360))); gDLL->getInterfaceIFace()->playGeneralSound("AS3D_UN_GRENADE_EXPLODE", pPlot->getPoint()); } } if (GC.getUnitInfo(pLoser->getUnitType()).isExplodeInCombat()) { if (plot()->isVisibleToWatchingHuman()) { gDLL->getEngineIFace()->TriggerEffect((EffectTypes)GC.getInfoTypeForString("EFFECT_ARTILLERY_SHELL_EXPLODE"), plot()->getPoint(), (float)(GC.getASyncRand().get(360))); gDLL->getInterfaceIFace()->playGeneralSound("AS3D_UN_GRENADE_EXPLODE", plot()->getPoint()); } } if ((m_pUnitInfo->getEnslavementChance() + GET_PLAYER(getOwnerINLINE()).getEnslavementChance()) > 0) { if (getDuration() == 0 && pLoser->isAlive() && !pLoser->isAnimal() && iUnit == NO_UNIT) { if (GC.getGameINLINE().getSorenRandNum(100, "Enslavement") <= (m_pUnitInfo->getEnslavementChance() + GET_PLAYER(getOwnerINLINE()).getEnslavementChance())) { iUnit = GC.getDefineINT("SLAVE_UNIT"); } } } if (m_pUnitInfo->getPromotionFromCombat() != NO_PROMOTION) { if (pLoser->isAlive()) { setHasPromotion((PromotionTypes)m_pUnitInfo->getPromotionFromCombat(), true); } } if (getGoldFromCombat() != 0) { if (!pLoser->isAnimal()) { GET_PLAYER(getOwnerINLINE()).changeGold(getGoldFromCombat()); CvWString szBuffer = gDLL->getText("TXT_KEY_MESSAGE_GOLD_FROM_COMBAT", getGoldFromCombat()).GetCString(); gDLL->getInterfaceIFace()->addMessage((PlayerTypes)getOwner(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_GOODY_GOLD", MESSAGE_TYPE_INFO, getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_WHITE"), getX_INLINE(), getY_INLINE(), true, true); } } if (getDuration() > 0) { changeDuration(m_pUnitInfo->getDurationFromCombat()); } if (pLoser->getDamageTypeCombat(DAMAGE_POISON) > 0 && GC.getDefineINT("POISONED_PROMOTION") != -1) { if (isAlive() && getDamage() > 0) { if (GC.getGameINLINE().getSorenRandNum(100, "Poisoned") >= getDamageTypeResist(DAMAGE_POISON)) { setHasPromotion((PromotionTypes)GC.getDefineINT("POISONED_PROMOTION"), true); } } } if (m_pUnitInfo->getUnitCreateFromCombat() != NO_UNIT) { if (!pLoser->isImmuneToCapture() && pLoser->isAlive() && GC.getUnitInfo((UnitTypes)pLoser->getUnitType()).getEquipmentPromotion() == NO_PROMOTION) { if (GC.getGameINLINE().getSorenRandNum(100, "Create Unit from Combat") <= m_pUnitInfo->getUnitCreateFromCombatChance()) { pUnit = GET_PLAYER(getOwnerINLINE()).initUnit((UnitTypes)m_pUnitInfo->getUnitCreateFromCombat(), plot()->getX_INLINE(), plot()->getY_INLINE()); pUnit->setDuration(getDuration()); if (isHiddenNationality()) { pUnit->setHasPromotion((PromotionTypes)GC.getDefineINT("HIDDEN_NATIONALITY_PROMOTION"), true); } iUnit = NO_UNIT; } } } if (iUnit != NO_UNIT) { if ((!pLoser->isImmuneToCapture() && !isNoCapture() && !pLoser->isImmortal()) || GC.getUnitInfo((UnitTypes)pLoser->getUnitType()).getEquipmentPromotion() != NO_PROMOTION) { pUnit = GET_PLAYER(getOwnerINLINE()).initUnit((UnitTypes)iUnit, plot()->getX_INLINE(), plot()->getY_INLINE()); if (getDuration() != 0) { pUnit->setDuration(getDuration()); } if (iUnit == GC.getDefineINT("SLAVE_UNIT")) { if (pLoser->getRace() != NO_PROMOTION) { pUnit->setHasPromotion((PromotionTypes)pLoser->getRace(), true); } } if (bConvert) { pLoser->setDamage(75, NO_PLAYER, false); pUnit->convert(pLoser); } } } if (!CvString(GC.getUnitInfo(getUnitType()).getPyPostCombatWon()).empty()) { CyUnit* pyCaster = new CyUnit(this); CyUnit* pyOpponent = new CyUnit(pLoser); CyArgsList argsList; argsList.add(gDLL->getPythonIFace()->makePythonObject(pyCaster)); // pass in unit class argsList.add(gDLL->getPythonIFace()->makePythonObject(pyOpponent)); // pass in unit class gDLL->getPythonIFace()->callFunction(PYSpellModule, "postCombatWon", argsList.makeFunctionArgs()); //, &lResult delete pyCaster; // python fxn must not hold on to this pointer delete pyOpponent; // python fxn must not hold on to this pointer } if (!CvString(GC.getUnitInfo(pLoser->getUnitType()).getPyPostCombatLost()).empty()) { CyUnit* pyCaster = new CyUnit(pLoser); CyUnit* pyOpponent = new CyUnit(this); CyArgsList argsList; argsList.add(gDLL->getPythonIFace()->makePythonObject(pyCaster)); // pass in unit class argsList.add(gDLL->getPythonIFace()->makePythonObject(pyOpponent)); // pass in unit class gDLL->getPythonIFace()->callFunction(PYSpellModule, "postCombatLost", argsList.makeFunctionArgs()); //, &lResult delete pyCaster; // python fxn must not hold on to this pointer delete pyOpponent; // python fxn must not hold on to this pointer } if (m_pUnitInfo->getUnitConvertFromCombat() != NO_UNIT) { if (GC.getGameINLINE().getSorenRandNum(100, "Convert Unit from Combat") <= m_pUnitInfo->getUnitConvertFromCombatChance()) { pUnit = GET_PLAYER(getOwnerINLINE()).initUnit((UnitTypes)m_pUnitInfo->getUnitConvertFromCombat(), getX_INLINE(), getY_INLINE(), AI_getUnitAIType()); pUnit->convert(this); } } } void CvUnit::setWeapons() { CvPlot* pPlot; CvCity* pCity; if (GC.getDefineINT("WEAPON_PROMOTION_TIER1") == -1) { return; } pPlot = plot(); if (pPlot->isCity()) { pCity = pPlot->getPlotCity(); if (pCity->getOwner() == getOwner()) { PromotionTypes ePromT1 = (PromotionTypes)GC.getDefineINT("WEAPON_PROMOTION_TIER1"); PromotionTypes ePromT2 = (PromotionTypes)GC.getDefineINT("WEAPON_PROMOTION_TIER2"); PromotionTypes ePromT3 = (PromotionTypes)GC.getDefineINT("WEAPON_PROMOTION_TIER3"); if (isHasPromotion(ePromT3) == false) { if (pCity->hasBonus((BonusTypes)GC.getDefineINT("WEAPON_REQ_BONUS_TIER3")) && m_pUnitInfo->getWeaponTier() >= 3) { setHasPromotion(ePromT3, true); gDLL->getInterfaceIFace()->addMessage(getOwner(), true, GC.getDefineINT("EVENT_MESSAGE_TIME"), gDLL->getText("TXT_KEY_MESSAGE_WEAPONS_MITHRIL"), "AS2D_REPAIR", MESSAGE_TYPE_MAJOR_EVENT, GC.getPromotionInfo(ePromT3).getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), getX(), getY(), true, true); setHasPromotion(ePromT2, false); setHasPromotion(ePromT1, false); } else { if (isHasPromotion(ePromT2) == false) { if (pCity->hasBonus((BonusTypes)GC.getDefineINT("WEAPON_REQ_BONUS_TIER2")) && m_pUnitInfo->getWeaponTier() >= 2) { setHasPromotion(ePromT2, true); gDLL->getInterfaceIFace()->addMessage(getOwner(), true, GC.getDefineINT("EVENT_MESSAGE_TIME"), gDLL->getText("TXT_KEY_MESSAGE_WEAPONS_IRON"), "AS2D_REPAIR", MESSAGE_TYPE_MAJOR_EVENT, GC.getPromotionInfo(ePromT2).getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), getX(), getY(), true, true); setHasPromotion(ePromT1, false); } else { if (isHasPromotion(ePromT1) == false) { if (pCity->hasBonus((BonusTypes)GC.getDefineINT("WEAPON_REQ_BONUS_TIER1")) && m_pUnitInfo->getWeaponTier() >= 1) { gDLL->getInterfaceIFace()->addMessage(getOwner(), true, GC.getDefineINT("EVENT_MESSAGE_TIME"), gDLL->getText("TXT_KEY_MESSAGE_WEAPONS_BRONZE"), "AS2D_REPAIR", MESSAGE_TYPE_MAJOR_EVENT, GC.getPromotionInfo(ePromT1).getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), getX(), getY(), true, true); setHasPromotion(ePromT1, true); } } } } } } } } } void CvUnit::changeBonusAffinity(BonusTypes eIndex, int iChange) { if (iChange != 0) { m_paiBonusAffinity[eIndex] += iChange; } updateBonusAffinity(eIndex); } int CvUnit::getBonusAffinity(BonusTypes eIndex) const { return m_paiBonusAffinity[eIndex]; } void CvUnit::updateBonusAffinity(BonusTypes eIndex) { int iNew = GET_PLAYER(getOwnerINLINE()).getNumAvailableBonuses(eIndex) * getBonusAffinity(eIndex); int iOld = m_paiBonusAffinityAmount[eIndex]; if (GC.getBonusInfo(eIndex).getDamageType() == NO_DAMAGE) { m_iBaseCombat += iNew - iOld; m_iBaseCombatDefense += iNew - iOld; } else { m_paiDamageTypeCombat[GC.getBonusInfo(eIndex).getDamageType()] += iNew - iOld; m_iTotalDamageTypeCombat += iNew - iOld; } m_paiBonusAffinityAmount[eIndex] = iNew; } void CvUnit::changeDamageTypeCombat(DamageTypes eIndex, int iChange) { if (iChange != 0) { m_paiDamageTypeCombat[eIndex] = (m_paiDamageTypeCombat[eIndex] + iChange); m_iTotalDamageTypeCombat = (m_iTotalDamageTypeCombat + iChange); } } int CvUnit::getDamageTypeCombat(DamageTypes eIndex) const { return m_paiDamageTypeCombat[eIndex]; } int CvUnit::getTotalDamageTypeCombat() const { return m_iTotalDamageTypeCombat; } int CvUnit::getDamageTypeResist(DamageTypes eIndex) const { int i = m_paiDamageTypeResist[eIndex]; if (i <= -100) { return -100; } if (i >= 100) { return 100; } return i; } void CvUnit::changeDamageTypeResist(DamageTypes eIndex, int iChange) { if (iChange != 0) { m_paiDamageTypeResist[eIndex] = (m_paiDamageTypeResist[eIndex] + iChange); } } int CvUnit::countUnitsWithinRange(int iRange, bool bEnemy, bool bNeutral, bool bTeam) { CLLNode<IDInfo>* pUnitNode; CvUnit* pLoopUnit; CvPlot* pLoopPlot; int iCount = 0; for (int i = -iRange; i <= iRange; ++i) { for (int j = -iRange; j <= iRange; ++j) { pLoopPlot = ::plotXY(plot()->getX_INLINE(), plot()->getY_INLINE(), i, j); if (NULL != pLoopPlot) { pUnitNode = pLoopPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pLoopPlot->nextUnitNode(pUnitNode); if (bTeam && pLoopUnit->getTeam() == getTeam()) { iCount += 1; } if (bEnemy && atWar(pLoopUnit->getTeam(), getTeam())) { iCount += 1; } if (bNeutral && pLoopUnit->getTeam() != getTeam() && !atWar(pLoopUnit->getTeam(), getTeam())) { iCount += 1; } } } } } return iCount; } CvPlot* CvUnit::getOpenPlot() const { CvPlot* pLoopPlot; CvPlot* pBestPlot = NULL; int iValue; int iBestValue = MAX_INT; bool bEquipment = false; if (m_pUnitInfo->getEquipmentPromotion() != NO_PROMOTION) { bEquipment = true; } for (int iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++) { pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI); if (pLoopPlot->isValidDomainForLocation(*this)) { if (canMoveInto(pLoopPlot) || bEquipment) { if (pLoopPlot->getNumUnits() == 0) { iValue = plotDistance(getX_INLINE(), getY_INLINE(), pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE()) * 2; if (pLoopPlot->area() != area()) { iValue *= 3; } if (iValue < iBestValue) { iBestValue = iValue; pBestPlot = pLoopPlot; } } } } } return pBestPlot; } void CvUnit::betray(PlayerTypes ePlayer) { if (getOwnerINLINE() == ePlayer) { return; } CvPlot* pNewPlot = getOpenPlot(); if (pNewPlot != NULL) { CvUnit* pUnit = GET_PLAYER(ePlayer).initUnit((UnitTypes)getUnitType(), pNewPlot->getX(), pNewPlot->getY(), AI_getUnitAIType()); pUnit->convert(this); if (pUnit->getDuration() > 0) { pUnit->setDuration(0); } } } void CvUnit::updateTerraformer() { m_bTerraformer = false; for (int iSpell = 0; iSpell < GC.getNumSpellInfos(); iSpell++) { if (GC.getSpellInfo((SpellTypes)iSpell).isAllowAutomateTerrain()) { if (canCast(iSpell, false)) { m_bTerraformer = true; return; } } } return; } bool CvUnit::isTerraformer() const { return m_bTerraformer; } bool CvUnit::withdrawlToNearestValidPlot(bool bKill) { CvPlot* pLoopPlot; CvPlot* pBestPlot = NULL; int iValue; int iBestValue = MAX_INT; for (int iI = -1; iI <= 1; ++iI) { for (int iJ = -1; iJ <= 1; ++iJ) { pLoopPlot = ::plotXY(getX_INLINE(), getY_INLINE(), iI, iJ); if (NULL != pLoopPlot) { if (pLoopPlot->isValidDomainForLocation(*this)) { if (canMoveInto(pLoopPlot)) { iValue = (plotDistance(getX_INLINE(), getY_INLINE(), pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE()) * 2); 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) { bValid = false; } if (bValid) { setXY(pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE()); } else { if (bKill) { kill(false); } } return bValid; } //FfH: End Add /*************************************************************************************************/ /** ADDON (New Functions) Sephi **/ /** Rewritten by Kael 09/19/2009 **/ /** **/ /*************************************************************************************************/ int CvUnit::getAutoSpellCast() const { return m_iAutoSpellCast; } void CvUnit::setAutoSpellCast(int newvalue) { m_iAutoSpellCast = newvalue; } /*************************************************************************************************/ /** END **/ /*************************************************************************************************/ void CvUnit::read(FDataStreamBase* pStream) { // Init data before load reset(); uint uiFlag=0; pStream->Read(&uiFlag); // flags for expansion 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); // VKs Plot Capacity - Start pStream->Read(&m_iUnitPlotCost); // VKs Plot Capacity - End 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); } //FfH Spell System: Added by Kael 07/23/2007 pStream->Read(&m_bFleeWithdrawl); pStream->Read(&m_bHasCasted); pStream->Read(&m_bIgnoreHide); pStream->Read(&m_bTerraformer); pStream->Read(&m_iAlive); pStream->Read(&m_iAIControl); pStream->Read(&m_iBoarding); pStream->Read(&m_iDefensiveStrikeChance); pStream->Read(&m_iDefensiveStrikeDamage); pStream->Read(&m_iDoubleFortifyBonus); pStream->Read(&m_iFear); pStream->Read(&m_iFlying); pStream->Read(&m_iHeld); pStream->Read(&m_iHiddenNationality); pStream->Read(&m_iIgnoreBuildingDefense); pStream->Read(&m_iImmortal); pStream->Read(&m_iImmuneToCapture); pStream->Read(&m_iImmuneToDefensiveStrike); pStream->Read(&m_iImmuneToFear); pStream->Read(&m_iImmuneToMagic); pStream->Read(&m_iInvisible); pStream->Read(&m_iSeeInvisible); pStream->Read(&m_iOnlyDefensive); pStream->Read(&m_iTargetWeakestUnit); pStream->Read(&m_iTargetWeakestUnitCounter); pStream->Read(&m_iTwincast); pStream->Read(&m_iWaterWalking); pStream->Read(&m_iBaseCombatDefense); pStream->Read(&m_iBetterDefenderThanPercent); pStream->Read(&m_iCombatHealPercent); pStream->Read(&m_iCombatLimit); pStream->Read(&m_iCombatPercentInBorders); pStream->Read(&m_iCombatPercentGlobalCounter); pStream->Read(&m_iDelayedSpell); pStream->Read(&m_iDuration); pStream->Read(&m_iFreePromotionPick); pStream->Read(&m_iGoldFromCombat); pStream->Read(&m_iGroupSize); pStream->Read(&m_iInvisibleType); pStream->Read(&m_iRace); pStream->Read(&m_iReligion); pStream->Read(&m_iResist); pStream->Read(&m_iResistModify); pStream->Read(&m_iScenarioCounter); pStream->Read(&m_iSpellCasterXP); pStream->Read(&m_iSpellDamageModify); pStream->Read(&m_iSummoner); pStream->Read(&m_iTotalDamageTypeCombat); pStream->Read(&m_iUnitArtStyleType); pStream->Read(&m_iWorkRateModify); pStream->Read(GC.getNumBonusInfos(), m_paiBonusAffinity); pStream->Read(GC.getNumBonusInfos(), m_paiBonusAffinityAmount); pStream->Read(GC.getNumDamageTypeInfos(), m_paiDamageTypeCombat); pStream->Read(GC.getNumDamageTypeInfos(), m_paiDamageTypeResist); //FfH: End Add /*************************************************************************************************/ /** ADDON (New Functions Definition) Sephi **/ /** **/ /** **/ /*************************************************************************************************/ pStream->Read(&m_iAutoSpellCast); /*************************************************************************************************/ /** END **/ /*************************************************************************************************/ 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 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); // VKs Plot Capacity - Start pStream->Write(m_iUnitPlotCost); // VKs Plot Capacity - End 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); //FfH Spell System: Added by Kael 07/23/2007 pStream->Write(m_bFleeWithdrawl); pStream->Write(m_bHasCasted); pStream->Write(m_bIgnoreHide); pStream->Write(m_bTerraformer); pStream->Write(m_iAlive); pStream->Write(m_iAIControl); pStream->Write(m_iBoarding); pStream->Write(m_iDefensiveStrikeChance); pStream->Write(m_iDefensiveStrikeDamage); pStream->Write(m_iDoubleFortifyBonus); pStream->Write(m_iFear); pStream->Write(m_iFlying); pStream->Write(m_iHeld); pStream->Write(m_iHiddenNationality); pStream->Write(m_iIgnoreBuildingDefense); pStream->Write(m_iImmortal); pStream->Write(m_iImmuneToCapture); pStream->Write(m_iImmuneToDefensiveStrike); pStream->Write(m_iImmuneToFear); pStream->Write(m_iImmuneToMagic); pStream->Write(m_iInvisible); pStream->Write(m_iSeeInvisible); pStream->Write(m_iOnlyDefensive); pStream->Write(m_iTargetWeakestUnit); pStream->Write(m_iTargetWeakestUnitCounter); pStream->Write(m_iTwincast); pStream->Write(m_iWaterWalking); pStream->Write(m_iBaseCombatDefense); pStream->Write(m_iBetterDefenderThanPercent); pStream->Write(m_iCombatHealPercent); pStream->Write(m_iCombatLimit); pStream->Write(m_iCombatPercentInBorders); pStream->Write(m_iCombatPercentGlobalCounter); pStream->Write(m_iDelayedSpell); pStream->Write(m_iDuration); pStream->Write(m_iFreePromotionPick); pStream->Write(m_iGoldFromCombat); pStream->Write(m_iGroupSize); pStream->Write(m_iInvisibleType); pStream->Write(m_iRace); pStream->Write(m_iReligion); pStream->Write(m_iResist); pStream->Write(m_iResistModify); pStream->Write(m_iScenarioCounter); pStream->Write(m_iSpellCasterXP); pStream->Write(m_iSpellDamageModify); pStream->Write(m_iSummoner); pStream->Write(m_iTotalDamageTypeCombat); pStream->Write(m_iUnitArtStyleType); pStream->Write(m_iWorkRateModify); pStream->Write(GC.getNumBonusInfos(), m_paiBonusAffinity); pStream->Write(GC.getNumBonusInfos(), m_paiBonusAffinityAmount); pStream->Write(GC.getNumDamageTypeInfos(), m_paiDamageTypeCombat); pStream->Write(GC.getNumDamageTypeInfos(), m_paiDamageTypeResist); //FfH: End Add /*************************************************************************************************/ /** ADDON (New Functions Definition) Sephi **/ /** **/ /** **/ /*************************************************************************************************/ pStream->Write(m_iAutoSpellCast); /*************************************************************************************************/ /** END **/ /*************************************************************************************************/ 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())); //modified animals Sephi 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) { 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); changeMoves(GC.getMOVE_DENOMINATOR()); int iDamage = airCombatDamage(pDefender); int iUnitDamage = std::max(pDefender->getDamage(), std::min((pDefender->getDamage() + iDamage), airCombatLimit())); 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()); return true; } bool CvUnit::canRangeStrike() const { if (getDomainType() == DOMAIN_AIR) { return false; } if (airRange() <= 0) { return false; } if (airBaseCombatStr() <= 0) { return false; } if (!canFight()) { return false; } if (isMadeAttack() && !isBlitz()) { return false; } if (!canMove() && getMoves() > 0) { return false; } 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; } if (plotDistance(pPlot->getX_INLINE(), pPlot->getY_INLINE(), pTargetPlot->getX_INLINE(), pTargetPlot->getY_INLINE()) > airRange()) { return false; } CvUnit* pDefender = airStrikeTarget(pTargetPlot); if (NULL == pDefender) { return false; } if (!pPlot->canSeePlot(pTargetPlot, getTeam(), airRange(), getFacingDirection(true))) { return false; } return true; } bool CvUnit::rangeStrike(int iX, int iY) { CvUnit* pDefender; CvWString szBuffer; int iUnitDamage; int iDamage; 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); } changeMoves(GC.getMOVE_DENOMINATOR()); iDamage = rangeCombatDamage(pDefender); iUnitDamage = std::max(pDefender->getDamage(), std::min((pDefender->getDamage() + iDamage), airCombatLimit())); 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()); 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()); } 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(); } //FfH: Added by Kael 10/26/2007 (to prevent spinlocks when always hostile units attack barbarian allied teams) if (isAlwaysHostile(pPlot)) { if (getTeam() != eTeam) { return true; } } //FfH: End Add 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); iOurDamage = std::max(1, ((GC.getDefineINT("COMBAT_DAMAGE") * (iTheirFirepower + iStrengthFactor)) / (iOurFirepower + iStrengthFactor))); iTheirDamage = std::max(1, ((GC.getDefineINT("COMBAT_DAMAGE") * (iOurFirepower + iStrengthFactor)) / (iTheirFirepower + iStrengthFactor))); } 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()) { //FfH: Modified by Kael 10/29/2007 // if (!canAcquirePromotion((PromotionTypes)kEvent.getUnitPromotion())) // { // return false; // } if (isHasPromotion((PromotionTypes)kEvent.getUnitPromotion())) { return false; } //FfH: End Modify } 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()) { //FfH: Modified by Kael 02/02/2009 (if we spawn a new unit the promotion goes to the spawned unit, not to the eventtrigger target) // setHasPromotion((PromotionTypes)kEvent.getUnitPromotion(), true); if (kEvent.getUnitClass() == NO_UNITCLASS || kEvent.getNumUnits() == 0) { setHasPromotion((PromotionTypes)kEvent.getUnitPromotion(), true); } //FfH: End Modify } 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 { //FfH: Added by Kael 10/26/2007 if (getUnitArtStyleType() != NO_UNIT_ARTSTYLE) { return m_pUnitInfo->getArtInfo(i, eEra, (UnitArtStyleTypes) getUnitArtStyleType()); } //FfH: End Add 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(); } //FfH: Modified by Kael 06/17/2009 //int CvUnit::getGroupSize() const //{ // return m_pUnitInfo->getGroupSize(); //} int CvUnit::getGroupSize() const { if (GC.getGameINLINE().isOption(GAMEOPTION_ADVENTURE_MODE)) { return 1; } return m_iGroupSize; } //FfH: End Modify 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 { //FfH: Added by Kael 09/15/2007 if (isHiddenNationality()) { return true; } //FfH: End Add if (!m_pUnitInfo->isAlwaysHostile()) { return false; } if (NULL != pPlot && pPlot->isCity(true, getTeam())) { return false; } return true; } bool CvUnit::verifyStackValid() { if (!alwaysInvisible()) { if (plot()->isVisibleEnemyUnit(this)) { return jumpToNearestValidPlot(); } } 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; } /*************************************************************************************************/ /** ADDON (New Functions Definition) Sephi **/ /** **/ /** **/ /*************************************************************************************************/ //Unlike CvUnit::canJoinGroup this Function doesn't check for atPlot(), so we can use it to plan AI moves ahead of time bool CvUnit::AI_canJoinGroup(CvSelectionGroup* pSelectionGroup) const { CvUnit* pHeadUnit; 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->getDomainType() != getDomainType()) { return false; } pHeadUnit = pSelectionGroup->getHeadUnit(); if (pHeadUnit != NULL) { if (pHeadUnit->isHiddenNationality() != isHiddenNationality()) { return false; } if (pHeadUnit->isAIControl() != isAIControl()) { return false; } } } return true; }
[ "adrian.gin@gmail.com" ]
adrian.gin@gmail.com
18dabc5192383046b1e82224ca0d094d23a2dbde
867820e33acc08a858007da901c48b12f9a4b424
/src/QAPSolGenerator.cpp
c9b0eb093d99b6022ba7fba1f98f9221b8a1f615
[]
no_license
gemari7/P5
ab212e00c497a8576bd6f0a0172f94b473625bd9
f15922e6c21d881dca6042ab051b0509003c62f6
refs/heads/master
2020-03-15T20:21:04.164487
2018-05-13T20:55:21
2018-05-13T20:55:21
132,330,629
0
0
null
null
null
null
UTF-8
C++
false
false
527
cpp
#include "QAPSolGenerator.h" #include "QAPInstance.h" #include "QAPSolution.h" #include <stdlib.h> void QAPSolGenerator::genRandomSol(QAPInstance &instance, QAPSolution &solution){ int numBuildings=instance.getNumBuildings(); int numLocations=numBuildings; int randomLocation; for (int i = 0; i < numBuildings; i++){ do{ randomLocation=rand()%numLocations; if(!solution.hasBuilding(randomLocation)){ solution.putBuildingIn(i,randomLocation); } }while(solution.whereIsBuilding(i)!=randomLocation); } }
[ "gemari777@gmail.com" ]
gemari777@gmail.com
8a750e92c04f27c925b99c8eaacb9e73689dd912
cb2c81f37cc3b4d660a66db69c1ac35027c4fe9d
/example/separate/03.cpp
ac17ce50ac916ed49a04b5ef7326a750921eb97d
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
lcaminiti/lcxx
f15ecb57bfbf8356d9607aa05e9abed554cc4a97
c492f3d724209cfcb0cf22599e60c468fa0ab546
refs/heads/master
2021-05-01T15:03:53.531280
2018-02-24T17:00:39
2018-02-24T17:00:39
121,028,771
1
0
null
null
null
null
UTF-8
C++
false
false
1,862
cpp
#include <queue> #include <future> #include <condition_variable> #include <mutex> #include <thread> #include <utility> #include <iostream> template<typename T> class threadsafe_queue { public: void push(T&& value) { std::lock_guard<std::mutex> l(mut_); data_.push(std::move(value)); cond_.notify_one(); } void wait_for_pop(T& value) { std::unique_lock<std::mutex> l(mut_); cond_.wait(l, [this] { return !data_.empty(); }); value = std::move(data_.front()); data_.pop(); } private: mutable std::mutex mut_; std::queue<T> data_; std::condition_variable cond_; }; std::atomic_bool done; std::mutex m; threadsafe_queue<std::packaged_task<void ()> > tasks; void work() { while(!done) { std::packaged_task<void ()> task; //{ // std::lock_guard<std::mutex> l(m); // if(tasks.empty()) continue; // task = std::move(tasks.front()); // tasks.pop_front(); //} std::cout << "work waiting..." << std::endl; tasks.wait_for_pop(task); std::cout << "work start" << std::endl; task(); std::cout << "work end" << std::endl; } } template<typename F> std::future<void> push(F f) { std::packaged_task<void ()> task(f); std::future<void> r = task.get_future(); //std::lock_guard<std::mutex> l(m); //tasks.push_back(std::move(task)); tasks.push(std::move(task)); return r; } int main() { done = false; std::thread th(work); push([] { std::cout << 1 << std::endl; }); push([] { std::cout << 2 << std::endl; }); auto x = push([] { std::cout << 3 << std::endl; }); x.get(); std::cout << "passed future get" << std::endl; done = true; push([] {}); // Last task, force out of wait_for_pop. th.join(); return 0; }
[ "lorcaminiti@gmail.com" ]
lorcaminiti@gmail.com
91c4c468ffa30b80c896b6f778804743140219e9
55d7754ace69c50ec9ea74d68b5f3ca2ad554113
/src/common/CmdLine/include/Support/CmdLine.h
70c8fb998bf49ccff288f49d428eaba7475bcb16
[ "MIT", "NCSA" ]
permissive
ukoeln-vis/sgrvr
ad6f7531a054c306683199fc4720d2cfecef961e
e4a3f98fdede7af2f62adea49900788a16c6680c
refs/heads/master
2016-09-05T17:32:54.583647
2015-11-24T13:43:41
2015-11-24T13:43:41
40,511,153
1
1
null
null
null
null
UTF-8
C++
false
false
17,434
h
// This file is distributed under the MIT license. // See the LICENSE file for details. #pragma once #include "Support/StringRef.h" #include "Support/StringRefStream.h" #include <algorithm> #include <memory> #include <stdexcept> #include <vector> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4512) // assignment operator could not be generated #endif namespace support { namespace cl { //-------------------------------------------------------------------------------------------------- // Option flags // // Flags for the number of occurrences allowed enum NumOccurrences : unsigned char { Optional, // Zero or one occurrence allowed ZeroOrMore, // Zero or more occurrences allowed Required, // Exactly one occurrence required OneOrMore, // One or more occurrences required }; // Is a value required for the option? enum NumArgs : unsigned char { ArgOptional, // A value can appear... or not ArgRequired, // A value is required to appear! ArgDisallowed, // A value may not be specified (for flags) }; // This controls special features that the option might have that cause it to be // parsed differently... enum Formatting : unsigned char { DefaultFormatting, // Nothing special Prefix, // Must this option directly prefix its value? MayPrefix, // Can this option directly prefix its value? Grouping, // Can this option group with other options? Positional, // Is a positional argument, no '-' required }; enum MiscFlags : unsigned char { None = 0, CommaSeparated = 0x01, // Should this list split between commas? ConsumeAfter = 0x02, // Handle all following arguments as positional arguments Hidden = 0x04, // Do not show this option in the help message }; //-------------------------------------------------------------------------------------------------- // CmdLine // class OptionBase; class CmdLine { public: using OptionMap = std::vector<std::pair<StringRef, OptionBase*>>; using OptionVector = std::vector<OptionBase*>; using ConstOptionVector = std::vector<OptionBase const*>; using StringVector = std::vector<std::string>; private: // The current argument StringVector::const_iterator argCurr_; // End of command line arguments StringVector::const_iterator argLast_; // Index of the currently processed argument size_t index_; // List of options OptionMap options_; // List of positional options OptionVector positionals_; // The length of the longest prefix option size_t maxPrefixLength_; public: CmdLine(); ~CmdLine(); // Adds the given option to the command line void add(OptionBase& opt); // Parse the given command line arguments void parse(StringVector const& argv, bool checkRequired = true); // Returns whether all command line arguments have been processed bool empty() const; // Returns the index of the currently processed argument size_t index() const; // Returns the current command line argument StringRef curr() const; // Returns the next argument and increments the index StringRef bump(); // Returns a short usage description std::string usage() const; // Returns the help message std::string help(StringRef programName, StringRef overview = "") const; private: void parse(bool checkRequired); OptionBase* findOption(StringRef name) const; ConstOptionVector getUniqueOptions() const; void handleArg(bool& dashdash, OptionVector::iterator& pos); void handlePositional(StringRef curr, OptionVector::iterator& pos); bool handleOption(StringRef curr); bool handlePrefix(StringRef curr); bool handleGroup(StringRef curr); void addOccurrence(OptionBase* opt, StringRef name); void addOccurrence(OptionBase* opt, StringRef name, StringRef arg); void parse(OptionBase* opt, StringRef name, StringRef arg); void check(OptionBase const* opt); void check(); }; //-------------------------------------------------------------------------------------------------- // ArgName // struct ArgName { std::string value; explicit ArgName(std::string value) : value(std::move(value)) {} }; //-------------------------------------------------------------------------------------------------- // Desc // struct Desc { std::string value; explicit Desc(std::string value) : value(std::move(value)) {} }; //-------------------------------------------------------------------------------------------------- // Initializer // namespace details { template <class T> struct Initializer { T value; explicit Initializer(T x) : value(std::forward<T>(x)) {} // extract operator T() { return std::forward<T>(value); } }; } template <class T> inline auto init(T&& value) -> details::Initializer<T&&> { return details::Initializer<T&&>(std::forward<T>(value)); } //-------------------------------------------------------------------------------------------------- // Parser // template <class T = void> struct Parser { void operator()(StringRef name, StringRef arg, T& value) const { StringRefStream stream(arg); stream.setf(std::ios_base::fmtflags(0), std::ios::basefield); if (!(stream >> value) || !stream.eof()) throw std::runtime_error("invalid argument '" + arg + "' for option '" + name + "'"); } }; template <> struct Parser<bool> { void operator()(StringRef name, StringRef arg, bool& value) const { if (arg.empty() || arg == "1" || arg == "true" || arg == "on") value = true; else if (arg == "0" || arg == "false" || arg == "off") value = false; else throw std::runtime_error("invalid argument '" + arg + "' for option '" + name + "'"); } }; template <> struct Parser<std::string> { void operator()(StringRef /*name*/, StringRef arg, std::string& value) const { value.assign(arg.data(), arg.size()); } }; template <> struct Parser<void> // default parser { template <class T> void operator()(StringRef name, StringRef arg, T& value) const { Parser<T>()(name, arg, value); } }; //-------------------------------------------------------------------------------------------------- // MapParser // template <class T> struct MapParser { using ValueType = typename std::remove_reference<T>::type; struct MapValueType { // Key std::string key; // Value ValueType value; // An optional description of the value std::string desc; MapValueType(std::string key, ValueType value, std::string desc = "(description missing)") : key(std::move(key)) , value(std::move(value)) , desc(std::move(desc)) { } }; using MapType = std::vector<MapValueType>; MapType map; explicit MapParser(std::initializer_list<MapValueType> ilist) : map(ilist) { } void operator()(StringRef name, StringRef arg, ValueType& value) const { // If the arg is empty, the option is specified by name auto key = arg.empty() ? name : arg; auto I = std::find_if(map.begin(), map.end(), [&](MapValueType const& s) { return s.key == key; }); if (I == map.end()) throw std::runtime_error("invalid argument '" + arg + "' for option '" + name + "'"); value = I->value; } std::vector<StringRef> getAllowedValues() const { std::vector<StringRef> vec; for (auto&& I : map) vec.emplace_back(I.key); return vec; } std::vector<StringRef> getDescriptions() const { std::vector<StringRef> vec; for (auto&& I : map) vec.emplace_back(I.desc); return vec; } }; //-------------------------------------------------------------------------------------------------- // Traits // template <class ElementT, class InserterT = void> struct BasicTraits { using ElementType = ElementT; using InserterType = InserterT; }; template <class T> using ScalarType = BasicTraits<T>; namespace details { struct R2 {}; struct R1 : R2 {}; template <class T> struct RecRemoveCV { using type = typename std::remove_cv<T>::type; }; template <template <class...> class T, class... A> struct RecRemoveCV<T<A...>> { using type = T<typename RecRemoveCV<A>::type...>; }; template <class T> struct UnwrapReferenceWrapper { using type = T; }; template <class T> struct UnwrapReferenceWrapper<std::reference_wrapper<T>> { using type = T; }; struct Inserter { template <class C, class V> void operator()(C& c, V&& v) const { c.insert(c.end(), std::forward<V>(v)); } }; struct No {}; template <class T> auto TestValueType(R1, T const&) -> typename T::value_type; template <class T> auto TestValueType(R2, T const&) -> No; template <class T> struct MissingValueType : std::is_same<No, decltype( TestValueType(std::declval<R1>(), std::declval<T const&>()) )> { }; template <class T, bool = MissingValueType<T>::value> struct TestInsert { using type = BasicTraits<typename RecRemoveCV<typename T::value_type>::type, Inserter>; }; template <class T> struct TestInsert<T, true> { using type = BasicTraits<T>; }; template <class T> using TestInsertType = typename TestInsert<T>::type; } template <class T> struct Traits : details::TestInsertType<T> { }; template <class T> struct Traits<T&> : Traits<T> {}; template <class T> struct Traits<std::reference_wrapper<T>> : Traits<T> {}; template <> struct Traits<std::string> : BasicTraits<std::string> { }; //-------------------------------------------------------------------------------------------------- // OptionBase // class OptionBase { friend class CmdLine; // The name of this option std::string name_; // The name of the value of this option std::string argName_; // Option description std::string desc_; // Controls how often the option must/may be specified on the command line NumOccurrences numOccurrences_; // Controls whether the option expects a value NumArgs numArgs_; // Controls how the option might be specified Formatting formatting_; // Other flags MiscFlags miscFlags_; // The number of times this option was specified on the command line unsigned count_; protected: OptionBase(); public: virtual ~OptionBase(); // Returns the name of this option std::string const& name() const { return name_; } // Return name of the value std::string const& argName() const { return argName_; } // Returns the option description std::string const& desc() const { return desc_; } // Returns the number of times this option has been specified on the command line unsigned count() const { return count_; } // Returns a short usage description std::string usage() const; // Returns the help message std::string help() const; protected: void apply(std::string x) { name_ = std::move(x); } void apply(ArgName x) { argName_ = std::move(x.value); } void apply(Desc x) { desc_ = std::move(x.value); } void apply(NumOccurrences x) { numOccurrences_ = x; } void apply(NumArgs x) { numArgs_ = x; } void apply(Formatting x) { formatting_ = x; } void apply(MiscFlags x) { miscFlags_ = static_cast<MiscFlags>(miscFlags_ | x); } template <class U> void apply(details::Initializer<U>) {} void applyAll() {} template <class A, class... Args> void applyAll(A&& a, Args&&... args) { apply(std::forward<A>(a)); applyAll(std::forward<Args>(args)...); } template <class... Args> void applyAll(CmdLine& cmd, Args&&... args) { applyAll(std::forward<Args>(args)...); cmd.add(*this); } private: StringRef displayName() const; bool isOccurrenceAllowed() const; bool isOccurrenceRequired() const; bool isUnbounded() const; bool isRequired() const; bool isPrefix() const; // Parses the given value and stores the result. virtual void parse(StringRef name, StringRef arg) = 0; // Returns a list of allowed values for this option virtual std::vector<StringRef> getAllowedValues() const = 0; // Returns a list of descriptions for the values this option accepts virtual std::vector<StringRef> getDescriptions() const = 0; }; //-------------------------------------------------------------------------------------------------- // BasicOption<T> // template <class T> class BasicOption : public OptionBase { T value_; protected: BasicOption(std::piecewise_construct_t) : value_() {} template <class U, class... Args> BasicOption(std::piecewise_construct_t, details::Initializer<U> x, Args&&...) : OptionBase() , value_(x) { } template <class A, class... Args> BasicOption(std::piecewise_construct_t, A&&, Args&&... args) : BasicOption(std::piecewise_construct, std::forward<Args>(args)...) { } public: using ValueType = typename std::remove_reference<T>::type; // Returns the option value ValueType& value() { return value_; } // Returns the option value ValueType const& value() const { return value_; } }; //-------------------------------------------------------------------------------------------------- // Option // template <class T, template <class> class TraitsT = Traits, class ParserT = Parser<typename TraitsT<T>::ElementType>> class Option : public BasicOption<T> { public: using BaseType = BasicOption<T>; using ElementType = typename TraitsT<T>::ElementType; using InserterType = typename TraitsT<T>::InserterType; using IsScalar = typename std::is_void<InserterType>::type; private: static_assert(IsScalar::value || std::is_default_constructible<ElementType>::value, "elements of containers must be default constructible"); ParserT parser_; public: using ParserType = typename details::UnwrapReferenceWrapper<ParserT>::type; template <class P, class... Args> explicit Option(std::piecewise_construct_t, P&& p, Args&&... args) : BaseType(std::piecewise_construct, std::forward<Args>(args)...) , parser_(std::forward<P>(p)) { this->applyAll(IsScalar::value ? Optional : ZeroOrMore, std::forward<Args>(args)...); } // Returns the parser ParserType& parser() { return parser_; } // Returns the parser ParserType const& parser() const { return parser_; } private: void parse(StringRef name, StringRef arg, std::false_type) { ElementType t; parser()(name, arg, t); InserterType()(this->value(), std::move(t)); } void parse(StringRef name, StringRef arg, std::true_type) { parser()(name, arg, this->value()); } virtual void parse(StringRef name, StringRef arg) override final { this->parse(name, arg, IsScalar()); } template <class X = ParserType> auto getAllowedValues(details::R1) const -> decltype(std::declval<X const&>().getAllowedValues()) { return parser().getAllowedValues(); } auto getAllowedValues(details::R2) const -> std::vector<StringRef> { return {}; } virtual std::vector<StringRef> getAllowedValues() const override final { return this->getAllowedValues(details::R1()); } template <class X = ParserType> auto getDescriptions(details::R1) const -> decltype(std::declval<X const&>().getDescriptions()) { return parser().getDescriptions(); } auto getDescriptions(details::R2) const -> std::vector<StringRef> { return {}; } virtual std::vector<StringRef> getDescriptions() const override final { return this->getDescriptions(details::R1()); } }; //-------------------------------------------------------------------------------------------------- // makeOption // // Constructs a new Option with a custom parser template <class T, template <class> class TraitsT = Traits, class P, class... Args> auto makeOption(P&& p, Args&&... args) -> std::unique_ptr<Option<T, TraitsT, typename std::decay<P>::type>> { using U = Option<T, TraitsT, typename std::decay<P>::type>; return std::unique_ptr<U>( new U(std::piecewise_construct, std::forward<P>(p), std::forward<Args>(args)...)); } // Constructs a new Option with a MapParser template <class T, template <class> class TraitsT = Traits, class... Args> auto makeOption(std::initializer_list<typename MapParser<T>::MapValueType> ilist, Args&&... args) -> std::unique_ptr<Option<T, TraitsT, MapParser<T>>> { using U = Option<T, TraitsT, MapParser<T>>; return std::unique_ptr<U>( new U(std::piecewise_construct, ilist, std::forward<Args>(args)...)); } } // namespace cl } // namespace support #ifdef _MSC_VER #pragma warning(pop) #endif
[ "info@szellmann.de" ]
info@szellmann.de
cd139ebf197d408f35cf79b0496d8f09a9bd5436
18b6aef6ebe67c63a4943e3c5beabd1db440017d
/EnduringLife_Client/Object.h
cbce069554c6e469fcff3f89181a80c5f63c2b48
[]
no_license
HoinJang/EnduringLife
317d08fa3ba0f1d85128e4703afda03e4b8996cd
f2819c865b2fc093fa54c4f4e7879cce15ffab7e
refs/heads/master
2021-06-28T18:48:28.225393
2019-02-18T06:53:41
2019-02-18T06:53:41
132,803,888
0
0
null
null
null
null
UHC
C++
false
false
14,445
h
//------------------------------------------------------- ---------------------- // File: Object.h //----------------------------------------------------------------------------- #pragma once #include "Mesh.h" #include "Camera.h" #include "Mydefine.h" #define DIR_FORWARD 0x01 #define DIR_BACKWARD 0x02 #define DIR_LEFT 0x04 #define DIR_RIGHT 0x08 #define DIR_UP 0x10 #define DIR_DOWN 0x20 #define RESOURCE_TEXTURE2D 0x01 #define RESOURCE_TEXTURE2D_ARRAY 0x02 //[] #define RESOURCE_TEXTURE2DARRAY 0x03 #define RESOURCE_TEXTURE_CUBE 0x04 #define RESOURCE_BUFFER 0x05 class CShader; struct CB_GAMEOBJECT_INFO { XMFLOAT4X4 m_xmf4x4World; UINT m_nMaterial; }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // struct SRVROOTARGUMENTINFO { UINT m_nRootParameterIndex = 0; D3D12_GPU_DESCRIPTOR_HANDLE m_d3dSrvGpuDescriptorHandle; }; class CTexture { public: CTexture(int nTextureResources = 1, UINT nResourceType = RESOURCE_TEXTURE2D, int nSamplers = 0); virtual ~CTexture(); private: int m_nReferences = 0; UINT m_nTextureType = RESOURCE_TEXTURE2D; int m_nTextures = 0; ID3D12Resource **m_ppd3dTextures = NULL; ID3D12Resource **m_ppd3dTextureUploadBuffers; SRVROOTARGUMENTINFO *m_pRootArgumentInfos = NULL; int m_nSamplers = 0; D3D12_GPU_DESCRIPTOR_HANDLE *m_pd3dSamplerGpuDescriptorHandles = NULL; public: void AddRef() { m_nReferences++; } void Release() { if (--m_nReferences <= 0) delete this; } void SetRootArgument(int nIndex, UINT nRootParameterIndex, D3D12_GPU_DESCRIPTOR_HANDLE d3dsrvGpuDescriptorHandle); void SetSampler(int nIndex, D3D12_GPU_DESCRIPTOR_HANDLE d3dSamplerGpuDescriptorHandle); void UpdateShaderVariables(ID3D12GraphicsCommandList *pd3dCommandList); void UpdateShaderVariable(ID3D12GraphicsCommandList *pd3dCommandList, int nIndex); void ReleaseShaderVariables(); void LoadTextureFromFile(ID3D12Device *pd3dDevice, ID3D12GraphicsCommandList *pd3dCommandList, wchar_t *pszFileName, UINT nIndex); int GetTextureCount() { return(m_nTextures); } ID3D12Resource *GetTexture(int nIndex) { return(m_ppd3dTextures[nIndex]); } UINT GetTextureType() { return(m_nTextureType); } void ReleaseUploadBuffers(); }; class CMaterial { public: CMaterial(); virtual ~CMaterial(); private: int m_nReferences = 0; public: void AddRef() { m_nReferences++; } void Release() { if (--m_nReferences <= 0) delete this; } XMFLOAT4 m_xmf4Albedo = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); UINT m_nReflection = 0; CTexture *m_pTexture = NULL; CShader *m_pShader = NULL; void SetAlbedo(XMFLOAT4 xmf4Albedo) { m_xmf4Albedo = xmf4Albedo; } void SetReflection(UINT nReflection) { m_nReflection = nReflection; } void SetTexture(CTexture *pTexture); void SetShader(CShader *pShader); void UpdateShaderVariables(ID3D12GraphicsCommandList *pd3dCommandList); void ReleaseShaderVariables(); void ReleaseUploadBuffers(); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // class CGameObject { public: CGameObject(int nMeshes = 1); virtual ~CGameObject(); private: int m_nReferences = 0; private: bool m_bVisible = false; SCENE scene; float m_hp; float m_mp; float m_MaxHP; public: SCENE GetScene() { return scene; } void SetScene(SCENE s) { scene = s; } void SetHp(float hp) { m_hp = hp; } void SetMp(float mp) { m_mp = mp; } void SetMaxHP(float maxhp) {m_MaxHP = maxhp ;} float GetHP() { return m_hp; } float GetMP() { return m_mp; } float GetMaxMP() { return m_MaxHP; } void SetVisible(bool b) { m_bVisible = b; } bool GetVisible() { return m_bVisible; } public: void AddRef() { m_nReferences++; } void Release() { if (--m_nReferences <= 0) delete this; } public: TCHAR m_pstrFrameName[256]; bool m_bActive = true; XMFLOAT4X4 m_xmf4x4ToParentTransform; XMFLOAT4X4 m_xmf4x4ToRootTransform; XMFLOAT4X4 m_xmf4x4World; CMesh **m_ppMeshes; int m_nMeshes; BoundingOrientedBox m_xmOOBB; CMaterial *m_pMaterial = NULL; D3D12_GPU_DESCRIPTOR_HANDLE m_d3dCbvGPUDescriptorHandle; protected: ID3D12Resource *m_pd3dcbGameObject = NULL; CB_GAMEOBJECT_INFO *m_pcbMappedGameObject = NULL; public: void SetMesh(int nIndex, CMesh *pMesh); void SetShader(CShader *pShader); void SetMaterial(CMaterial *pMaterial); void ResizeMeshes(int nMeshes); void SetCbvGPUDescriptorHandle(D3D12_GPU_DESCRIPTOR_HANDLE d3dCbvGPUDescriptorHandle) { m_d3dCbvGPUDescriptorHandle = d3dCbvGPUDescriptorHandle; } void SetCbvGPUDescriptorHandlePtr(UINT64 nCbvGPUDescriptorHandlePtr) { m_d3dCbvGPUDescriptorHandle.ptr = nCbvGPUDescriptorHandlePtr; } D3D12_GPU_DESCRIPTOR_HANDLE GetCbvGPUDescriptorHandle() { return(m_d3dCbvGPUDescriptorHandle); } virtual ID3D12Resource *CreateShaderVariables(ID3D12Device *pd3dDevice, ID3D12GraphicsCommandList *pd3dCommandList); virtual void ReleaseShaderVariables(); virtual void UpdateShaderVariables(ID3D12GraphicsCommandList *pd3dCommandList); virtual void OnPrepareRender(); virtual void SetRootParameter(ID3D12GraphicsCommandList *pd3dCommandList); virtual void Animate(float fTimeElapsed); virtual void Render(ID3D12GraphicsCommandList *pd3dCommandList, CCamera *pCamera=NULL); virtual void BuildMaterials(ID3D12Device *pd3dDevice, ID3D12GraphicsCommandList *pd3dCommandList) { } virtual void ReleaseUploadBuffers(); XMFLOAT3 GetPosition(); XMFLOAT3 GetLook(); XMFLOAT3 GetUp(); XMFLOAT3 GetRight(); void SetPosition(float x, float y, float z); void SetPosition(XMFLOAT3 xmf3Position); void SetXPosition(float x); void SetYPosition(float y); void SetZPosition(float z); void SetLocalPosition(XMFLOAT3 xmf3Position); void SetWorldPosition(float x, float y, float z); void SetScale(float x, float y, float z); void SetLocalScale(float x, float y, float z); void MoveStrafe(float fDistance = 1.0f); void MoveUp(float fDistance = 1.0f); void MoveForward(float fDistance = 1.0f); void Rotate(float fPitch = 10.0f, float fYaw = 10.0f, float fRoll = 10.0f); void Rotate(XMFLOAT3 *pxmf3Axis, float fAngle); void Rotate(XMFLOAT4 *pxmf4Quaternion); void UpdateTransform(XMFLOAT4X4 *pxmf4x4Parent=NULL); virtual void UpdateBuffer(ID3D12GraphicsCommandList *pd3dCommandList) {} virtual bool FrameAdvance(float fTimeElapsed) { return false; } virtual void UpdateBoneTransform(ID3D12Device *pd3dDevice) {} virtual void UpdatePosition(float fTimeElapsed) {} virtual void SetAnimation(int nFBXAnimation) {}; public: CGameObject *m_pParent = NULL; CGameObject *m_pChild = NULL; CGameObject *m_pSibling = NULL; int Timer = 0; bool moveFlag = false; void SetChild(CGameObject *pChild); CGameObject *GetParent() { return(m_pParent); } //-----0305 추가한 코드----- void LoadGeometryFromFBX(ID3D12Device *pd3dDevice, ID3D12GraphicsCommandList *pd3dCommandList, ID3D12RootSignature *pd3dGraphicsRootSignature, char * pszFileName, wchar_t* pszDDSFileName); //-----0420 추가한 코드----- void LoadNormalMappedGeometryFromFBX(ID3D12Device * pd3dDevice, ID3D12GraphicsCommandList * pd3dCommandList, ID3D12RootSignature * pd3dGraphicsRootSignature, char * pszFileName, wchar_t* pszTextureFileName, wchar_t* pszNormalmapFileName); //-----0511 추가한 코드------ void LoadGeometryFromSpiderFBX(ID3D12Device *pd3dDevice, ID3D12GraphicsCommandList *pd3dCommandList, ID3D12RootSignature *pd3dGraphicsRootSignature, char * pszFileName, wchar_t* pszDDSFileName); //----shader에서 읽는 용도. 메쉬만 불러오는 거---- void LoadMeshFromFBX(ID3D12Device *pd3dDevice, ID3D12GraphicsCommandList *pd3dCommandList, char * pszFileName ); }; //========================================================================================================================================================================== // 상수 버퍼를 위한 구조체 struct CB_SKINNED_INFO { XMMATRIX m_xmtxBone[64]; }; struct BoneAnimationData { int m_nFrameCount; float *m_pfAniTime; XMFLOAT3 *m_pd3dxvScale; XMFLOAT3 *m_pd3dxvTranslate; XMFLOAT4 *m_pd3dxvQuaternion; }; class CAnimatedModelObject : public CGameObject { public: CAnimatedModelObject(int nMeshes = 1); CAnimatedModelObject(PLAYERTYPE type, ID3D12Device *pd3dDevice, ID3D12GraphicsCommandList *pd3dCommandList, ID3D12RootSignature *pd3dGraphicsRootSignature, char * pszFileName, wchar_t* pszDDSFileName, float scale); //-----0520 수정한 코드----- void LoadGeometryFromAnimatedFBX(PLAYERTYPE type, ID3D12Device *pd3dDevice, ID3D12GraphicsCommandList *pd3dCommandList, ID3D12RootSignature *pd3dGraphicsRootSignature, char * pszFileName, wchar_t* pszDDSFileName, float scale); float m_fFBXModelScale = 1.f; // 모델의 사이즈 (보통 Animate에서 조절해주기 위함) XMFLOAT3 m_xmf3FBXModelRotate; //모델의 회전 정보 float m_fFBXAnimationTime = 0.0f; int m_nFBXAnimationNum = 0; int m_nFBXMaxFrameNum = 0; // 모델이 실행할 애니메이션의 최대 프레임 수. int m_nFBXNowFrameNum = 0; // 모델이 진행중인 애니메이션의 현재 프레임 값. BoneAnimationData **m_ppBoneAnimationData; XMFLOAT3 *pxmf3Positions = NULL, *pxmf3Normals = NULL; XMFLOAT2 *pxmf3TextureCoords0 = NULL; XMFLOAT4 *pxmf4BoneIndices = NULL, *pxmf4BoneWeights = NULL; UINT *m_pBoneHierarchy; XMFLOAT4X4 *m_pxm4x4BoneOffsets; XMMATRIX *m_pxm4x4SQTTransform; XMFLOAT4X4 *m_pxm4x4FinalBone; XMFLOAT4X4 m_xmf4x4Frame[128]; PLAYERTYPE m_fbxType; protected: // 뼈대 상수버퍼 ID3D12Resource * m_pd3dcbBones = NULL; CB_SKINNED_INFO *m_pcbMappedBoneInfo = NULL; public: // 뼈대 상수버퍼 전달 부분!+_+ void CreateBuffer(ID3D12Device *pd3dDevice, ID3D12GraphicsCommandList *pd3dCommandList); void ReleaseBuffer(); virtual void UpdateBuffer(ID3D12GraphicsCommandList *pd3dCommandList); float GetFBXAnimationTime() { return m_fFBXAnimationTime; } int GetFBXAnimationNum() { return m_nFBXAnimationNum; } int GetFBXNowFrameNum() { return m_nFBXNowFrameNum; } int GetFBXMaxFrameNum() { return m_nFBXMaxFrameNum; } int m_nBoneCount; int m_nAnimationClip; virtual void UpdateBoneTransform(ID3D12Device *pd3dDevice); void MakeBoneMatrix(int nNowframe, int nAnimationNum, int nBoneNum, XMMATRIX& BoneMatrix); virtual bool FrameAdvance(float fTimeElapsed); virtual void SetAnimation(int nFBXAnimation); float m_fRotationTime = 0.f; float m_fTheta = 0.f; void UpdatePosition(float fTimeElapsed); bool IsAnimationFinish(); }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // class CPlaneObject : public CGameObject { public: CPlaneObject(int nMeshes=1); virtual ~CPlaneObject(); public: virtual void Animate(float fTimeElapsed); //virtual void Render(ID3D12GraphicsCommandList *pd3dCommandList, CCamera *pCamera = NULL); }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // class CFBXModel : public CGameObject { public: CFBXModel( ID3D12Device *pd3dDevice, ID3D12GraphicsCommandList *pd3dCommandList, ID3D12RootSignature *pd3dGraphicsRootSignature, char * pszFileNam, wchar_t* pszDDSFileNamee); virtual ~CFBXModel(); }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // class CFBXBumpedModel : public CGameObject { public: CFBXBumpedModel(ID3D12Device *pd3dDevice, ID3D12GraphicsCommandList *pd3dCommandList, ID3D12RootSignature *pd3dGraphicsRootSignature, char * pszFileName, wchar_t* pszTextureFileName, wchar_t* pszNormalmapFileName); virtual ~CFBXBumpedModel(); }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // class CHeightMapTerrain : public CGameObject { public: CHeightMapTerrain(ID3D12Device *pd3dDevice, ID3D12GraphicsCommandList *pd3dCommandList, ID3D12RootSignature *pd3dGraphicsRootSignature,char type, LPCTSTR pFileName, int nWidth, int nLength, int nBlockWidth, int nBlockLength, XMFLOAT3 xmf3Scale, XMFLOAT4 xmf4Color); virtual ~CHeightMapTerrain(); private: CHeightMapImage * m_pHeightMapImage; int m_nWidth; int m_nLength; XMFLOAT3 m_xmf3Scale; public: float GetHeight(float x, float z, bool bReverseQuad = false) { return(m_pHeightMapImage->GetHeight(x, z, bReverseQuad) * m_xmf3Scale.y); } //World XMFLOAT3 GetNormal(float x, float z) { return(m_pHeightMapImage->GetHeightMapNormal(int(x / m_xmf3Scale.x), int(z / m_xmf3Scale.z))); } int GetHeightMapWidth() { return(m_pHeightMapImage->GetHeightMapWidth()); } int GetHeightMapLength() { return(m_pHeightMapImage->GetHeightMapLength()); } XMFLOAT3 GetScale() { return(m_xmf3Scale); } float GetWidth() { return(m_nWidth * m_xmf3Scale.x); } float GetLength() { return(m_nLength * m_xmf3Scale.z); } }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // class CSkyBox : public CGameObject { public: CSkyBox(ID3D12Device *pd3dDevice, ID3D12GraphicsCommandList *pd3dCommandList, ID3D12RootSignature *pd3dGraphicsRootSignature); virtual ~CSkyBox(); virtual void Render(ID3D12GraphicsCommandList *pd3dCommandList, CCamera *pCamera = NULL); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class CBillboardObject :public CGameObject { public: CBillboardObject(int nMeshes = 1); virtual ~CBillboardObject(); virtual void Animate(float fTimeElapsed, CCamera * pCamera); void SetLookAt(XMFLOAT3& xmf3Target); }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // class CTreeModel : public CGameObject { public: CTreeModel(ID3D12Device *pd3dDevice, ID3D12GraphicsCommandList *pd3dCommandList, char * pszFileNam ); virtual ~CTreeModel(); };
[ "ghdlsfl@naver.com" ]
ghdlsfl@naver.com
cb295e6821a2ccfcc1b385a31402f86a3bc243b8
89c7bead0bfb7b3b4d3d53450cc69bc4db47b7c2
/Engine/Code/Engine/Core/General/Tags.cpp
09afe218679078681ccbd16e7b19f87a6f98eb3b
[]
no_license
itsdrell/SoftwareDevelopment
73fb218ae002a4dc3cd9bbed8f50ccc1a2d8a2f4
546b0d59e21f25a9b951ca0adc38783c1305f7ab
refs/heads/master
2020-03-19T00:43:23.348211
2019-05-08T17:21:37
2019-05-08T17:21:37
135,498,540
0
0
null
null
null
null
UTF-8
C++
false
false
1,088
cpp
#include "Tags.hpp" bool DoTagsShareATag(Tags & a, Tags & b) { for(uint i = 0; i < a.GetSize(); i++) { std::string aCurrent = a.GetTagAtIndex(i); for(uint j = 0; j < b.GetSize(); j++) { std::string bCurrent = b.GetTagAtIndex(j); if(aCurrent == bCurrent) return true; } } return false; } bool Tags::operator==(const Tags& toCompare) const { if(m_tags.size() != toCompare.GetSize()) return false; bool found; for(uint i = 0; i < m_tags.size(); i++) { found = false; std::string aCurrent = m_tags.at(i); for(uint j = 0; j < m_tags.size(); j++) { std::string bCurrent = toCompare.GetTagAtIndex(j); if(bCurrent == aCurrent) found = true; } // If we didn't find a match looping through then they don't match if(found == false) return false; } return true; } //----------------------------------------------------------------------------------------------- bool Tags::Contains(const std::string& tagToCheck) { for(uint i = 0; i < m_tags.size(); i++) { if(m_tags.at(i) == tagToCheck) return true; } return false; }
[ "ztbracken@gmail.com" ]
ztbracken@gmail.com
d89906ced9f86135a55a72d112e55d4aa4afbdce
f6f2c2b157cf1e9b10ca33acb41b13c795e55191
/test/test_pid.cpp
8ea20258094490b59e3279d793eaf7e64dbcaa2c
[]
no_license
ashwinvk94/ackermann_pid
fc515612b639c5604952e03b37b6c9333a402d2e
87a3262fc2c8e11da7d6cbd43dde8b83570b7a4d
refs/heads/master
2020-08-09T05:28:59.452064
2019-10-11T22:28:35
2019-10-11T22:28:35
214,008,498
0
0
null
null
null
null
UTF-8
C++
false
false
1,451
cpp
/** * @file test_ackerman_controller.cpp * @author Ashwin Varghese Kurutukullam * @author Charan Karthikeyan * @brief Testing cases for ackerman_controller * * @Copyright "Copyright 2019 <Charan Karthikeyan> * @Copyright "Copyright 2019 <Ashwin Varghese Kurutukullam> */ #include <gtest/gtest.h> #include "pid.hpp" /** * @brief Runs and tests the constructor for the PID class for certain inputs */ TEST(ValidatePIDClass,TestpidConstructor){ pid mypid(1,0,0,false); mypid.setdt(0.5); EXPECT_EQ(mypid.getdt(),0.5); EXPECT_EQ(mypid.getkp(),1); EXPECT_EQ(mypid.getki(),0); EXPECT_EQ(mypid.getkd(),0); EXPECT_EQ(mypid.getdtMode(),false); } /** *@brief Runs and test the second constructor for the PID class for certain inputs. */ TEST(ValidatePIDClass,TestpidConstructor2){ pid mypid(1,10,2000); EXPECT_EQ(mypid.getkp(),1); EXPECT_EQ(mypid.getki(),10); EXPECT_EQ(mypid.getkd(),2000); } /** * @brief Runs and tests he compute function for the PID class for certain values. */ TEST(ValidatePIDClass,Testcompute){ pid mypid(1,0,0); double temp = mypid.setSp(12); EXPECT_EQ(mypid.compute(10),-2); } /** * @brief Runs and test the reset function of the PID class */ TEST(ValidatePIDClass,Testreset){ pid mypid(1,0,0); double temp = mypid.compute(10); EXPECT_NE(temp, 0); mypid.reset(); double temp1 = mypid.compute(10); EXPECT_EQ(mypid.getPrevError(),0); EXPECT_EQ(mypid.getErrorSum(),0); }
[ "pvcharankarthikeyan@gmail.com" ]
pvcharankarthikeyan@gmail.com
bee7cac5be0d708dcc4044ecc41430ea96ba1d59
3e000de4c63cadc352cec1224c275275085ebf87
/src/reverselock.h
aefcf766ede9f4eee8a4ae0ee0a88e67f26cd870
[ "MIT" ]
permissive
mo-bay/oasis
0c02ad688aeb3ccdcc7dc8d8e11c5a2701a6903f
0d9469399907f69e4ac9c51fd4791e84d2926363
refs/heads/main
2023-04-17T18:54:08.094658
2021-05-06T15:16:31
2021-05-06T15:16:31
363,743,117
0
0
MIT
2021-05-02T20:25:25
2021-05-02T20:25:24
null
UTF-8
C++
false
false
807
h
// Copyright (c) 2015 The Bitcoin Core developers // Copyright (c) 2017-2019 The oasis developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_REVERSELOCK_H #define BITCOIN_REVERSELOCK_H /** * An RAII-style reverse lock. Unlocks on construction and locks on destruction. */ template<typename Lock> class reverse_lock { public: explicit reverse_lock(Lock& lock) : lock(lock) { lock.unlock(); lock.swap(templock); } ~reverse_lock() { templock.lock(); templock.swap(lock); } private: reverse_lock(reverse_lock const&); reverse_lock& operator=(reverse_lock const&); Lock& lock; Lock templock; }; #endif // BITCOIN_REVERSELOCK_H
[ "derek@Dereks-iMac.local" ]
derek@Dereks-iMac.local
e7cc390f8f49809e9e64d2cd1faa871c744c98ac
9bdb9ca05409a125a000636d6da6df5316959329
/libfranka/src/network.h
8236a7f4ce68ef7a3792063fe05bd9584dfb8311
[ "Apache-2.0" ]
permissive
IntelligentSun/franka
612ccdfc5042e98c9abb876df3f31193e6c7a179
a28b3015c5810da3fe0a60ae14041300e187165b
refs/heads/master
2020-05-03T12:34:11.931502
2019-03-31T01:40:35
2019-03-31T01:40:35
178,627,207
0
0
null
null
null
null
UTF-8
C++
false
false
9,362
h
// Copyright (c) 2017 Franka Emika GmbH // Use of this source code is governed by the Apache-2.0 license, see LICENSE #pragma once #include <chrono> #include <cmath> #include <cstdint> #include <cstring> #include <functional> #include <mutex> #include <unordered_map> #include <vector> #include <Poco/Net/DatagramSocket.h> #include <Poco/Net/NetException.h> #include <Poco/Net/StreamSocket.h> #include <franka/exception.h> namespace franka { class Network { public: Network(const std::string& franka_address, uint16_t franka_port, std::chrono::milliseconds tcp_timeout = std::chrono::seconds(60), std::chrono::milliseconds udp_timeout = std::chrono::seconds(1), std::tuple<bool, int, int, int> tcp_keepalive = std::make_tuple(true, 1, 3, 1)); ~Network(); uint16_t udpPort() const noexcept; template <typename T> T udpBlockingReceive(); template <typename T> bool udpReceive(T* data); template <typename T> void udpSend(const T& data); void tcpThrowIfConnectionClosed(); /** * Blocks until a T::Response message with the given command ID has been received. * * Additional variable-length data for the expected response (if any) is written into the given * vl_buffer. If vl_buffer is not given, this data is discarded. * * @param[in] command_id Expected command ID of the T::Response. * @param[out] vl_buffer If given, variable-length data for the expected T::Response message (if * any has been received) is copied into it. * * @return Received T::Response instance. */ template <typename T> typename T::Response tcpBlockingReceiveResponse(uint32_t command_id, std::vector<uint8_t>* vl_buffer = nullptr); /** * Tries to receive a T::Response message with the given command ID (non-blocking). * * Additional variable-length data for the expected response (if any) is discarded. * * @param[in] command_id Expected command ID of the T::Response. * @param[in] handler Callback to be invoked if the expected response has been received. * * @return True if a T::Response message with the given command_id has been received, false * otherwise. */ template <typename T> bool tcpReceiveResponse(uint32_t command_id, std::function<void(const typename T::Response&)> handler); template <typename T, typename... TArgs> uint32_t tcpSendRequest(TArgs&&... args); private: template <typename T> T udpBlockingReceiveUnsafe(); template <typename T> void tcpReadFromBuffer(std::chrono::microseconds timeout); Poco::Net::StreamSocket tcp_socket_; Poco::Net::DatagramSocket udp_socket_; Poco::Net::SocketAddress udp_server_address_; uint16_t udp_port_; std::mutex tcp_mutex_; std::mutex udp_mutex_; uint32_t command_id_{0}; std::vector<uint8_t> pending_response_{}; size_t pending_response_offset_ = 0; uint32_t pending_command_id_ = 0; std::unordered_map<uint32_t, std::vector<uint8_t>> received_responses_{}; }; template <typename T> bool Network::udpReceive(T* data) { std::lock_guard<std::mutex> _(udp_mutex_); if (udp_socket_.available() >= static_cast<int>(sizeof(T))) { *data = udpBlockingReceiveUnsafe<T>(); return true; } return false; } template <typename T> T Network::udpBlockingReceive() { std::lock_guard<std::mutex> _(udp_mutex_); return udpBlockingReceiveUnsafe<T>(); } template <typename T> T Network::udpBlockingReceiveUnsafe() try { std::array<uint8_t, sizeof(T)> buffer; int bytes_received = udp_socket_.receiveFrom(buffer.data(), static_cast<int>(buffer.size()), udp_server_address_); if (bytes_received != buffer.size()) { throw ProtocolException("libfranka: incorrect object size"); } return *reinterpret_cast<T*>(buffer.data()); } catch (const Poco::Exception& e) { using namespace std::string_literals; // NOLINT(google-build-using-namespace) throw NetworkException("libfranka: UDP receive: "s + e.what()); } template <typename T> void Network::udpSend(const T& data) try { std::lock_guard<std::mutex> _(udp_mutex_); int bytes_sent = udp_socket_.sendTo(&data, sizeof(data), udp_server_address_); if (bytes_sent != sizeof(data)) { throw NetworkException("libfranka: could not send UDP data"); } } catch (const Poco::Exception& e) { using namespace std::string_literals; // NOLINT(google-build-using-namespace) throw NetworkException("libfranka: UDP send: "s + e.what()); } template <typename T> void Network::tcpReadFromBuffer(std::chrono::microseconds timeout) try { if (!tcp_socket_.poll(timeout.count(), Poco::Net::Socket::SELECT_READ)) { return; } int available_bytes = tcp_socket_.available(); if (pending_response_.empty() && available_bytes >= static_cast<int>(sizeof(typename T::Header))) { typename T::Header header; tcp_socket_.receiveBytes(&header, sizeof(header)); if (header.size < sizeof(header)) { throw ProtocolException("libfranka: Incorrect TCP message size."); } pending_response_.resize(header.size); std::memcpy(pending_response_.data(), &header, sizeof(header)); pending_response_offset_ = sizeof(header); pending_command_id_ = header.command_id; } if (!pending_response_.empty() && available_bytes > 0) { pending_response_offset_ += tcp_socket_.receiveBytes( &pending_response_[pending_response_offset_], std::min(tcp_socket_.available(), static_cast<int>(pending_response_.size() - pending_response_offset_))); if (pending_response_offset_ == pending_response_.size()) { received_responses_.emplace(pending_command_id_, pending_response_); pending_response_.clear(); pending_response_offset_ = 0; pending_command_id_ = 0; } } } catch (const Poco::Exception& e) { using namespace std::string_literals; // NOLINT(google-build-using-namespace) throw NetworkException("libfranka: TCP receive: "s + e.what()); } template <typename T, typename... TArgs> uint32_t Network::tcpSendRequest(TArgs&&... args) try { std::lock_guard<std::mutex> _(tcp_mutex_); typename T::template Message<typename T::Request> message( typename T::Header(T::kCommand, command_id_++, sizeof(message)), typename T::Request(std::forward<TArgs>(args)...)); tcp_socket_.sendBytes(&message, sizeof(message)); return message.header.command_id; } catch (const Poco::Exception& e) { using namespace std::string_literals; // NOLINT(google-build-using-namespace) throw NetworkException("libfranka: TCP send bytes: "s + e.what()); } template <typename T> bool Network::tcpReceiveResponse(uint32_t command_id, std::function<void(const typename T::Response&)> handler) { using namespace std::literals::chrono_literals; // NOLINT(google-build-using-namespace) std::unique_lock<std::mutex> lock(tcp_mutex_, std::try_to_lock); if (!lock.owns_lock()) { return false; } tcpReadFromBuffer<T>(0us); decltype(received_responses_)::const_iterator it = received_responses_.find(command_id); if (it != received_responses_.end()) { auto message = reinterpret_cast<const typename T::template Message<typename T::Response>*>( it->second.data()); if (message->header.size < sizeof(message)) { throw ProtocolException("libfranka: Incorrect TCP message size."); } handler(message->getInstance()); received_responses_.erase(it); return true; } return false; } template <typename T> typename T::Response Network::tcpBlockingReceiveResponse(uint32_t command_id, std::vector<uint8_t>* vl_buffer) { using namespace std::literals::chrono_literals; // NOLINT(google-build-using-namespace) std::unique_lock<std::mutex> lock(tcp_mutex_, std::defer_lock); decltype(received_responses_)::const_iterator it; do { lock.lock(); tcpReadFromBuffer<T>(10ms); it = received_responses_.find(command_id); lock.unlock(); } while (it == received_responses_.end()); auto message = *reinterpret_cast<const typename T::template Message<typename T::Response>*>( it->second.data()); if (message.header.size < sizeof(message)) { throw ProtocolException("libfranka: Incorrect TCP message size."); } if (vl_buffer != nullptr && message.header.size != sizeof(message)) { size_t data_size = message.header.size - sizeof(message); std::vector<uint8_t> data_buffer(data_size); std::memcpy(data_buffer.data(), &it->second[sizeof(message)], data_size); *vl_buffer = data_buffer; } received_responses_.erase(it); return message.getInstance(); } template <typename T, uint16_t kLibraryVersion> void connect(Network& network, uint16_t* ri_version) { uint32_t command_id = network.tcpSendRequest<T>(network.udpPort()); typename T::Response connect_response = network.tcpBlockingReceiveResponse<T>(command_id); switch (connect_response.status) { case (T::Status::kIncompatibleLibraryVersion): throw IncompatibleVersionException(connect_response.version, kLibraryVersion); case (T::Status::kSuccess): *ri_version = connect_response.version; break; default: throw ProtocolException("libfranka: Protocol error during connection attempt"); } } } // namespace franka
[ "17321255121@163.com" ]
17321255121@163.com
48e88f8f9cd667b8a74b54b071f9b37d7bc145c6
ac8013f41c0c8e48394b63f78f49c6d57b365b76
/GNN-Computing/include/aggregator.h
1b746c9801bdfc710997f2e1be28ff5166695113
[]
no_license
lichong0309/lcsrc
7eefac366220fa6c03de137b5bd9f67821011ef2
673b72e6fbb1a4e4173d93dff1de5792c266fea9
refs/heads/main
2023-08-07T17:42:11.840314
2021-09-30T07:27:26
2021-09-30T07:27:26
403,853,738
1
0
null
null
null
null
UTF-8
C++
false
false
4,743
h
#ifndef AGGREGATOR_H #define AGGREGATOR_H #define __shfl(a, b, c) __shfl_sync(0xffffffff, a, b, c) #define __shfl_down(a, b) __shfl_down_sync(0xffffffff, a, b) #include "util.h" #include "data.h" #include "graph_schedule.h" __global__ void convertCSRToEdgelist(int *ptr, int *idx, int *edgelist, int num_v) { int lane = threadIdx.x & 31; int row = (blockIdx.x * (blockDim.x >> 5)) + (threadIdx.x >> 5); if (row >= num_v) return; int begin = ptr[row], end = ptr[row + 1]; for (int i = begin + lane; i < end; i += 32) { edgelist[i * 2] = idx[i]; edgelist[i * 2 + 1] = row; } } class Aggregator { public: Aggregator(int *host_out_ptr, int *host_out_idx, int *dev_out_ptr, int *dev_out_idx, int out_num_v, int out_num_e, int out_feat_in, int out_feat_out) : h_ptr(host_out_ptr), h_idx(host_out_idx), d_ptr(dev_out_ptr), d_idx(dev_out_idx), num_v(out_num_v), num_e(out_num_e), feat_in(out_feat_in), feat_out(out_feat_out) { if (h_ptr == NULL) { h_ptr = new int[num_v + 1]; checkCudaErrors(cudaMemcpy(h_ptr, d_ptr, (num_v + 1) * sizeof(int), cudaMemcpyDeviceToHost)); } if (h_idx == NULL) { h_idx = new int[num_e]; checkCudaErrors(cudaMemcpy(h_idx, d_idx, (num_e) * sizeof(int), cudaMemcpyDeviceToHost)); } return; } Aggregator(CSRSubGraph g, int out_feat_in, int out_feat_out) : feat_in(out_feat_in), feat_out(out_feat_out) { d_ptr = g.ptr; d_idx = g.idx; num_v = g.num_v; num_e = g.num_e; h_ptr = new int[num_v + 1]; h_idx = new int[num_e]; checkCudaErrors(cudaMemcpy(h_ptr, d_ptr, (num_v + 1) * sizeof(int), cudaMemcpyDeviceToHost)); checkCudaErrors(cudaMemcpy(h_idx, d_idx, (num_e) * sizeof(int), cudaMemcpyDeviceToHost)); d_vset = g.vertexset; // dbg(h_ptr[num_v]); // dbg(h_idx[num_e - 1]); // dbg(num_v); // dbg(num_e); } ~Aggregator() { safeFree(d_ptr); safeFree(d_idx); safeFree(d_ptr_scheduled); safeFree(d_idx_scheduled); safeFree(d_target_scheduled); safeFree(d_vset); } virtual void schedule(Schedule s, int *param) { std::vector<int> ptr_vec; std::vector<int> idx_vec; std::vector<int> target_vec; sche = s; safeFree(d_ptr_scheduled); safeFree(d_idx_scheduled); safeFree(d_target_scheduled); switch (s) { case locality: locality_schedule(h_ptr, h_idx, param[0], num_v, &ptr_vec, &idx_vec, &target_vec, n); locality_partition_num = param[0]; break; case neighbor_grouping: neighbor_grouping_schedule(h_ptr, h_idx, param[0], num_v, num_e, &ptr_vec, &idx_vec, &target_vec); neighbor_group_size = param[0]; break; case locality_neighbor_grouping: localityNeighborGrouping(h_ptr, h_idx, param[0], param[1], num_v, &ptr_vec, &idx_vec, &target_vec, n); locality_partition_num = param[0]; neighbor_group_size = param[1]; break; default: break; } num_target = target_vec.size(); dbg(num_target); copyVec2Dev(&ptr_vec, d_ptr_scheduled); copyVec2Dev(&idx_vec, d_idx_scheduled); copyVec2Dev(&target_vec, d_target_scheduled); } virtual double run(float *vin, float *vout, int BLOCK_SIZE, bool scheduled) { assert(false); return -1; } virtual double run(float *v1, float *v2, float *outval, int BLOCK_SIZE, bool scheduled) { assert(false); return -1; } virtual double runEdgeWise(float *vin, float *vout, int BLOCK_SIZE, bool scheduled) { assert(false); return -1; } void csr2edgelist() { safeFree(d_edgelist); checkCudaErrors(cudaMalloc2((void **)&d_edgelist, 2 * num_e * sizeof(int))); int BLOCK_SIZE = 64; int target_in_block = BLOCK_SIZE / 32; convertCSRToEdgelist<<<(num_v + target_in_block - 1) / target_in_block, BLOCK_SIZE>>>(d_ptr, d_idx, d_edgelist, num_v); } int feat_in = 0; int feat_out = 0; int num_target = 0; protected: int *d_ptr = NULL; int *d_idx = NULL; int *d_ptr_scheduled = NULL; int *d_idx_scheduled = NULL; int *d_target_scheduled = NULL; int *h_ptr = NULL; int *h_idx = NULL; int *d_vset = NULL; int *h_vset = NULL; int *d_edgelist = NULL; int num_v = 0; int num_e = 0; int neighbor_group_size = 0; int locality_partition_num = 0; Schedule sche = nop; }; #endif
[ "chongli0309@gmail.com" ]
chongli0309@gmail.com
93b17db39b7d02dacdc1badaf96b47fd8bc84333
17dbbbdc6bd3fe56a466d97f674b735720da60a5
/services/tracing/public/cpp/perfetto/producer_client.h
30b9019b8ac4f0458dc192a02d238018f245209b
[ "BSD-3-Clause" ]
permissive
aileolin1981/chromium
3df50a9833967cf68e9809017deb9f0c79722687
876a076ba4c2fac9d01814e21e6b5bcb7ec78ad3
refs/heads/master
2022-12-21T09:32:02.120314
2019-03-21T02:41:19
2019-03-21T02:41:19
173,888,576
0
1
null
2019-03-05T06:31:00
2019-03-05T06:31:00
null
UTF-8
C++
false
false
7,122
h
// Copyright 2018 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 SERVICES_TRACING_PUBLIC_CPP_PERFETTO_PRODUCER_CLIENT_H_ #define SERVICES_TRACING_PUBLIC_CPP_PERFETTO_PRODUCER_CLIENT_H_ #include <memory> #include <set> #include <string> #include <utility> #include <vector> #include "base/atomicops.h" #include "base/component_export.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/sequence_checker.h" #include "mojo/public/cpp/bindings/binding.h" #include "services/tracing/public/cpp/perfetto/task_runner.h" #include "services/tracing/public/mojom/perfetto_service.mojom.h" #include "third_party/perfetto/include/perfetto/tracing/core/tracing_service.h" namespace perfetto { class SharedMemoryArbiter; class StartupTraceWriterRegistry; } // namespace perfetto namespace tracing { class MojoSharedMemory; // This class is the per-process client side of the Perfetto // producer, and is responsible for creating specific kinds // of DataSources (like ChromeTracing) on demand, and provide // them with TraceWriters and a configuration to start logging. // Implementations of new DataSources should: // * Implement ProducerClient::DataSourceBase. // * Add a new data source name in perfetto_service.mojom. // * Register the data source with Perfetto in ProducerHost::OnConnect. // * Construct the new implementation when requested to // in ProducerClient::StartDataSource. class COMPONENT_EXPORT(TRACING_CPP) ProducerClient : public mojom::ProducerClient, public perfetto::TracingService::ProducerEndpoint { public: class DataSourceBase { public: explicit DataSourceBase(const std::string& name); virtual ~DataSourceBase(); void StartTracingWithID( uint64_t data_source_id, ProducerClient* producer_client, const perfetto::DataSourceConfig& data_source_config); virtual void StartTracing( ProducerClient* producer_client, const perfetto::DataSourceConfig& data_source_config) = 0; virtual void StopTracing( base::OnceClosure stop_complete_callback = base::OnceClosure()) = 0; // Flush the data source. virtual void Flush(base::RepeatingClosure flush_complete_callback) = 0; const std::string& name() const { return name_; } uint64_t data_source_id() const { return data_source_id_; } private: uint64_t data_source_id_ = 0; std::string name_; }; // Returns the process-wide instance of the ProducerClient. static ProducerClient* Get(); ~ProducerClient() override; static void DeleteSoonForTesting(std::unique_ptr<ProducerClient>); // Returns the taskrunner used by Perfetto. static base::SequencedTaskRunner* GetTaskRunner(); void Connect(mojom::PerfettoServicePtr perfetto_service); // Create the messagepipes that'll be used to connect // to the service-side ProducerHost, on the correct // sequence. The callback will be called on same sequence // as CreateMojoMessagepipes() got called on. using MessagepipesReadyCallback = base::OnceCallback<void(mojom::ProducerClientPtr, mojom::ProducerHostRequest)>; void CreateMojoMessagepipes(MessagepipesReadyCallback); // Binds the registry and its trace writers to the ProducerClient's SMB, to // write into the given target buffer. The ownership of |registry| is // transferred to ProducerClient (and its SharedMemoryArbiter). void BindStartupTraceWriterRegistry( std::unique_ptr<perfetto::StartupTraceWriterRegistry> registry, perfetto::BufferID target_buffer); // Add a new data source to the ProducerClient; the caller // retains ownership and is responsible for making sure // the data source outlives the ProducerClient. void AddDataSource(DataSourceBase*); // mojom::ProducerClient implementation. // Called through Mojo by the ProducerHost on the service-side to control // tracing and toggle specific DataSources. void OnTracingStart(mojo::ScopedSharedBufferHandle shared_memory) override; void StartDataSource( uint64_t id, const perfetto::DataSourceConfig& data_source_config) override; void StopDataSource(uint64_t id, StopDataSourceCallback callback) override; void Flush(uint64_t flush_request_id, const std::vector<uint64_t>& data_source_ids) override; // perfetto::TracingService::ProducerEndpoint implementation. // Used by the TraceWriters // to signal Perfetto that shared memory chunks are ready // for consumption. void CommitData(const perfetto::CommitDataRequest& commit, CommitDataCallback callback) override; // Used by the DataSource implementations to create TraceWriters // for writing their protobufs, and respond to flushes. std::unique_ptr<perfetto::TraceWriter> CreateTraceWriter( perfetto::BufferID target_buffer) override; void NotifyFlushComplete(perfetto::FlushRequestID) override; perfetto::SharedMemory* shared_memory() const override; void RegisterTraceWriter(uint32_t writer_id, uint32_t target_buffer) override; void UnregisterTraceWriter(uint32_t writer_id) override; // These ProducerEndpoint functions are only used on the service // side and should not be called on the clients. void RegisterDataSource(const perfetto::DataSourceDescriptor&) override; void UnregisterDataSource(const std::string& name) override; void NotifyDataSourceStopped(perfetto::DataSourceInstanceID) override; void NotifyDataSourceStarted(perfetto::DataSourceInstanceID) override; size_t shared_buffer_page_size_kb() const override; static void ResetTaskRunnerForTesting(); protected: // protected for testing. ProducerClient(); private: friend class base::NoDestructor<ProducerClient>; void CommitDataOnSequence(const perfetto::CommitDataRequest& request); void AddDataSourceOnSequence(DataSourceBase*); void RegisterDataSourceWithHost(DataSourceBase* data_source); // The callback will be run on the |origin_task_runner|, meaning // the same sequence as CreateMojoMessagePipes() got called on. void CreateMojoMessagepipesOnSequence( scoped_refptr<base::SequencedTaskRunner> origin_task_runner, MessagepipesReadyCallback, mojom::ProducerClientRequest, mojom::ProducerClientPtr); std::unique_ptr<mojo::Binding<mojom::ProducerClient>> binding_; std::unique_ptr<perfetto::SharedMemoryArbiter> shared_memory_arbiter_; mojom::ProducerHostPtr producer_host_; std::unique_ptr<MojoSharedMemory> shared_memory_; std::set<DataSourceBase*> data_sources_; // First value is the flush ID, the second is the number of // replies we're still waiting for. std::pair<uint64_t, size_t> pending_replies_for_latest_flush_; SEQUENCE_CHECKER(sequence_checker_); // NOTE: Weak pointers must be invalidated before all other member variables. base::WeakPtrFactory<ProducerClient> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(ProducerClient); }; } // namespace tracing #endif // SERVICES_TRACING_PUBLIC_CPP_PERFETTO_PRODUCER_CLIENT_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
1cdc81dbd1870bbb0ef9f78dada279204e780132
5aa916bf1650c7c28818cf569cf717b3db32ead6
/TornadoEngine/Source/Developer/ShareDev/Scene/Common/GameObject.cpp
ade3872ef33f4b7dc337fa2d4dc22c8315e624a1
[]
no_license
lxq2537664558/MMO-Framework
125c21d2cec6e29ec42bb72f05691ddaef9de448
b0bac7e040ec632543d3d3d4ee23be1bf6224dd9
refs/heads/master
2021-08-19T04:22:28.528036
2017-11-24T18:48:46
2017-11-24T18:48:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,011
cpp
/* Author: Gudakov Ramil Sergeevich a.k.a. Gauss Гудаков Рамиль Сергеевич Contacts: [ramil2085@mail.ru, ramil2085@gmail.com] See for more information License.h. */ #include "GameObject.h" #include "BehaviourPattern.h" TGameObject::TGameObject() { mPtrPattern = NULL; mID = 0; } //---------------------------------------------------------------- TGameObject::~TGameObject() { delete mPtrPattern; } //---------------------------------------------------------------- int TGameObject::GetID() const { return mID; } //---------------------------------------------------------------- void TGameObject::SetID( int id ) { mID = id; } //---------------------------------------------------------------- void TGameObject::SetPattern(TBehaviourPattern* p) { mPtrPattern = p; } //---------------------------------------------------------------- TBehaviourPattern* TGameObject::GetPattern() { return mPtrPattern; } //----------------------------------------------------------------
[ "ramil2085@mail.ru" ]
ramil2085@mail.ru
8b662ff536f8597f2ed35c1e82b94193c6dc6f3f
85c5b0ad7cd689ef9f6865af7c7b1829fc513aae
/containers/OptionContainer.hpp
1c03018e2e4a85c65353019877bfa94d85563751
[]
no_license
Busiu/Games
025433ca3f547c816ae68e8eb0d47caf8813a710
b56d01ffe1a1467e81cf6f21ce7692fdd61a4746
refs/heads/master
2020-03-28T11:35:52.989971
2019-03-06T02:27:46
2019-03-06T02:27:46
148,229,682
0
0
null
null
null
null
UTF-8
C++
false
false
645
hpp
// // Created by Busiu on 12.09.2018. // #ifndef GAMES_OPTIONCONTAINER_HPP #define GAMES_OPTIONCONTAINER_HPP #include "../Libraries.hpp" #include "../util/Types.hpp" class OptionContainer { private: int currentResolution = 1; const static int noResolutions = 5; std::array<Resolution, noResolutions> resolutions; int fpsCap = 60; public: OptionContainer(); Resolution getCertainResolution(int index); int getCurrentResolution(); int getNoResolutions(); Resolution getWindowResolution(); int getFpsCap(); void setCurrentResolution(int currentResolution); }; #endif //GAMES_OPTIONCONTAINER_HPP
[ "busiu69@gmail.com" ]
busiu69@gmail.com
7a801e819f48871c55bcdc8b30d122a32db824ee
c71d9862169295dd650390ca44f2ebeb2e6740af
/src/gui/accessible/qaccessiblebridge.h
b21fced6293f14e623bc7fc9cfd97e3845de5c56
[]
no_license
maoxingda/qt-src
d23c8d0469f234f89fdcbdbe6f3d50fa16e7a0e3
e01aee06520bf526975b0bedafe78eb003b5ead6
refs/heads/master
2020-04-14T00:05:16.292626
2019-01-05T05:49:42
2019-01-05T05:49:42
163,524,224
1
0
null
null
null
null
UTF-8
C++
false
false
3,061
h
/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QACCESSIBLEBRIDGE_H #define QACCESSIBLEBRIDGE_H #include <QtCore/qplugin.h> #include <QtCore/qfactoryinterface.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) #ifndef QT_NO_ACCESSIBILITY class QAccessibleInterface; class QAccessibleBridge { public: virtual ~QAccessibleBridge() {} virtual void setRootObject(QAccessibleInterface *) = 0; virtual void notifyAccessibilityUpdate(int, QAccessibleInterface*, int) = 0; }; struct Q_GUI_EXPORT QAccessibleBridgeFactoryInterface : public QFactoryInterface { virtual QAccessibleBridge *create(const QString& name) = 0; }; #define QAccessibleBridgeFactoryInterface_iid "com.trolltech.Qt.QAccessibleBridgeFactoryInterface" Q_DECLARE_INTERFACE(QAccessibleBridgeFactoryInterface, QAccessibleBridgeFactoryInterface_iid) class Q_GUI_EXPORT QAccessibleBridgePlugin : public QObject, public QAccessibleBridgeFactoryInterface { Q_OBJECT Q_INTERFACES(QAccessibleBridgeFactoryInterface:QFactoryInterface) public: explicit QAccessibleBridgePlugin(QObject *parent = 0); ~QAccessibleBridgePlugin(); virtual QStringList keys() const = 0; virtual QAccessibleBridge *create(const QString &key) = 0; }; #endif // QT_NO_ACCESSIBILITY QT_END_NAMESPACE QT_END_HEADER #endif // QACCESSIBLEBRIDGE_H
[ "39357378+maoxingda@users.noreply.github.com" ]
39357378+maoxingda@users.noreply.github.com
fab7eddd1f85df94a4486dc735b0b284a3ca9033
531eed13a18d37f3b098fff0a2e9a4c82d01be66
/termproject/fold_block.cpp
f0935abc067d06a04c8e821b1e80a1bc938ab501
[]
no_license
metrosxxmin/OOP_201502090
fa44d9b08c72603f3358794a9922c0e57a2c3e1c
f90fe64d4d3009bc2f6fec245dabad96fb37c39f
refs/heads/master
2020-07-24T01:58:52.409679
2019-12-18T14:17:57
2019-12-18T14:17:57
207,767,588
0
0
null
null
null
null
UTF-8
C++
false
false
4,101
cpp
// // Created by Soomin on 2019-11-27. // #include "fold_block.h" #include "block.h" #include "array_2d.h" fold_block::fold_block(int c1, int c2, int c3) { block * _part1 = new block(c1); _part1->set_location(2, 1); block * _part2 = new block(c2); _part2->set_location(2, 0); block * _part3 = new block(c3); _part3->set_location(1, 0); big_block::v.push_back(_part1); big_block::v.push_back(_part2); big_block::v.push_back(_part3); array_2d::insert(big_block::v); } void fold_block::rotate() { big_block::flag++; block * _part1 = big_block::v.at(0); block * _part2 = big_block::v.at(1); block * _part3 = big_block::v.at(2); block * _part4; block * _part5; if (array_2d::visit_check(_part2->get_x() - 1, _part2->get_y())) return; if (array_2d::visit_check(_part2->get_x() + 1, _part2->get_y())) return; if (array_2d::visit_check(_part2->get_x(), _part2->get_y() - 1)) return; if (array_2d::visit_check(_part2->get_x(), _part2->get_y() + 1)) return; if (big_block::flag % 4 == 1) { _part4 = new block(_part1->get_color()); _part5 = new block(_part3->get_color()); _part4->set_location(_part2->get_x() - 1, _part2->get_y()); _part5->set_location(_part2->get_x(), _part2->get_y() - 1); if (!array_2d::can_move(_part4->get_x(), _part4->get_y()) || !array_2d::can_move(_part5->get_x(), _part5->get_y())) { big_block::flag--; return; } array_2d::delete_block(_part1->get_x(), _part1->get_y()); array_2d::delete_block(_part3->get_x(), _part3->get_y()); big_block::v.clear(); big_block::v.push_back(_part4); big_block::v.push_back(_part2); big_block::v.push_back(_part5); } else if (big_block::flag % 4 == 2) { _part4 = new block(_part1->get_color()); _part5 = new block(_part3->get_color()); _part4->set_location(_part2->get_x(), _part2->get_y() - 1); _part5->set_location(_part2->get_x() + 1, _part2->get_y()); if (!array_2d::can_move(_part4->get_x(), _part4->get_y()) || !array_2d::can_move(_part5->get_x(), _part5->get_y())) { big_block::flag--; return; } array_2d::delete_block(_part1->get_x(), _part1->get_y()); array_2d::delete_block(_part3->get_x(), _part3->get_y()); big_block::v.clear(); big_block::v.push_back(_part5); big_block::v.push_back(_part2); big_block::v.push_back(_part4); } else if (big_block::flag % 4 == 3) { _part4 = new block(_part3->get_color()); _part5 = new block(_part1->get_color()); _part4->set_location(_part2->get_x() + 1, _part2->get_y()); _part5->set_location(_part2->get_x(), _part2->get_y() + 1); if (!array_2d::can_move(_part4->get_x(), _part4->get_y()) || !array_2d::can_move(_part5->get_x(), _part5->get_y())) { big_block::flag--; return; } array_2d::delete_block(_part1->get_x(), _part1->get_y()); array_2d::delete_block(_part3->get_x(), _part3->get_y()); big_block::v.clear(); big_block::v.push_back(_part5); big_block::v.push_back(_part2); big_block::v.push_back(_part4); } else { _part4 = new block(_part3->get_color()); _part5 = new block(_part1->get_color()); _part4->set_location(_part2->get_x(), _part2->get_y() + 1); _part5->set_location(_part2->get_x() - 1, _part2->get_y()); if (!array_2d::can_move(_part4->get_x(), _part4->get_y()) || !array_2d::can_move(_part5->get_x(), _part5->get_y())) { big_block::flag--; return; } array_2d::delete_block(_part1->get_x(), _part1->get_y()); array_2d::delete_block(_part3->get_x(), _part3->get_y()); big_block::v.clear(); big_block::v.push_back(_part4); big_block::v.push_back(_part2); big_block::v.push_back(_part5); } array_2d::insert(big_block::v); }
[ "sxxmin.lee@gmail.com" ]
sxxmin.lee@gmail.com
2fe4e1fb3869d6b21c875cf09671307a63925c75
ef4d8a0d5aa7cfa3e9d16c358a7c2c41424a1b07
/src/chainparams.h
2fc8041ebdc5e7971da15381df190c21b0a52428
[ "MIT" ]
permissive
dutcoin/dutcoin
c9810befeb7cd8cbde9a6013f589cd845b7314fb
7c68a7e7561ca1185603be614aeefc2a96d5d3c1
refs/heads/main
2023-03-19T22:59:41.281470
2021-03-21T00:51:01
2021-03-21T00:51:01
348,498,448
1
0
null
null
null
null
UTF-8
C++
false
false
10,459
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2018 The PIVX developers // Copyright (c) 2018 The dutcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CHAINPARAMS_H #define BITCOIN_CHAINPARAMS_H #include "chainparamsbase.h" #include "checkpoints.h" #include "primitives/block.h" #include "protocol.h" #include "uint256.h" #include "libzerocoin/Params.h" #include <vector> typedef unsigned char MessageStartChars[MESSAGE_START_SIZE]; struct CDNSSeedData { std::string name, host; CDNSSeedData(const std::string& strName, const std::string& strHost) : name(strName), host(strHost) {} }; /** * CChainParams defines various tweakable parameters of a given instance of the * dutcoin system. There are three: the main network on which people trade goods * and services, the public test network which gets reset from time to time and * a regression test mode which is intended for private networks only. It has * minimal difficulty to ensure that blocks can be found instantly. */ class CChainParams { public: enum Base58Type { PUBKEY_ADDRESS, SCRIPT_ADDRESS, SECRET_KEY, // BIP16 EXT_PUBLIC_KEY, // BIP32 EXT_SECRET_KEY, // BIP32 EXT_COIN_TYPE, // BIP44 MAX_BASE58_TYPES }; const uint256& HashGenesisBlock() const { return hashGenesisBlock; } const MessageStartChars& MessageStart() const { return pchMessageStart; } const std::vector<unsigned char>& AlertKey() const { return vAlertPubKey; } int GetDefaultPort() const { return nDefaultPort; } const uint256& ProofOfWorkLimit() const { return bnProofOfWorkLimit; } /** Used to check majorities for block version upgrade */ int EnforceBlockUpgradeMajority() const { return nEnforceBlockUpgradeMajority; } int RejectBlockOutdatedMajority() const { return nRejectBlockOutdatedMajority; } int ToCheckBlockUpgradeMajority() const { return nToCheckBlockUpgradeMajority; } int MaxReorganizationDepth() const { return nMaxReorganizationDepth; } /** Used if GenerateBitcoins is called with a negative number of threads */ int DefaultMinerThreads() const { return nMinerThreads; } const CBlock& GenesisBlock() const { return genesis; } /** Make miner wait to have peers to avoid wasting work */ bool MiningRequiresPeers() const { return fMiningRequiresPeers; } /** Default value for -checkmempool and -checkblockindex argument */ bool DefaultConsistencyChecks() const { return fDefaultConsistencyChecks; } /** Allow mining of a min-difficulty block */ bool AllowMinDifficultyBlocks() const { return fAllowMinDifficultyBlocks; } /** Skip proof-of-work check: allow mining of any difficulty block */ bool SkipProofOfWorkCheck() const { return fSkipProofOfWorkCheck; } /** Make standard checks */ bool RequireStandard() const { return fRequireStandard; } int64_t TargetTimespan() const { return nTargetTimespan; } int64_t TargetSpacing() const { return nTargetSpacing; } int64_t Interval() const { return nTargetTimespan / nTargetSpacing; } int COINBASE_MATURITY() const { return nMaturity; } CAmount MaxMoneyOut() const { return nMaxMoneyOut; } /** The masternode count that we will allow the see-saw reward payments to be off by */ int MasternodeCountDrift() const { return nMasternodeCountDrift; } /** Make miner stop after a block is found. In RPC, don't return until nGenProcLimit blocks are generated */ bool MineBlocksOnDemand() const { return fMineBlocksOnDemand; } /** In the future use NetworkIDString() for RPC fields */ bool TestnetToBeDeprecatedFieldRPC() const { return fTestnetToBeDeprecatedFieldRPC; } /** Return the BIP70 network string (main, test or regtest) */ std::string NetworkIDString() const { return strNetworkID; } const std::vector<CDNSSeedData>& DNSSeeds() const { return vSeeds; } const std::vector<unsigned char>& Base58Prefix(Base58Type type) const { return base58Prefixes[type]; } const std::vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } virtual const Checkpoints::CCheckpointData& Checkpoints() const = 0; int PoolMaxTransactions() const { return nPoolMaxTransactions; } /** Spork key and Masternode Handling **/ std::string SporkKey() const { return strSporkKey; } std::string SporkKeyOld() const { return strSporkKeyOld; } int64_t NewSporkStart() const { return nEnforceNewSporkKey; } int64_t RejectOldSporkKey() const { return nRejectOldSporkKey; } std::string ObfuscationPoolDummyAddress() const { return strObfuscationPoolDummyAddress; } int64_t StartMasternodePayments() const { return nStartMasternodePayments; } int64_t Budget_Fee_Confirmations() const { return nBudget_Fee_Confirmations; } CBaseChainParams::Network NetworkID() const { return networkID; } /** Zerocoin **/ std::string Zerocoin_Modulus() const { return zerocoinModulus; } libzerocoin::ZerocoinParams* Zerocoin_Params(bool useModulusV1) const; int Zerocoin_MaxSpendsPerTransaction() const { return nMaxZerocoinSpendsPerTransaction; } CAmount Zerocoin_MintFee() const { return nMinZerocoinMintFee; } int Zerocoin_MintRequiredConfirmations() const { return nMintRequiredConfirmations; } int Zerocoin_RequiredAccumulation() const { return nRequiredAccumulation; } int Zerocoin_DefaultSpendSecurity() const { return nDefaultSecurityLevel; } int Zerocoin_HeaderVersion() const { return nZerocoinHeaderVersion; } int Zerocoin_RequiredStakeDepth() const { return nZerocoinRequiredStakeDepth; } /** Height or Time Based Activations **/ int ModifierUpgradeBlock() const { return nModifierUpdateBlock; } int WALLET_UPGRADE_BLOCK() const { return nMandatoryUpgradeBlock; } int WALLET_UPGRADE_VERSION() const { return nUpgradeBlockVersion; } int LAST_POW_BLOCK() const { return nLastPOWBlock; } int POS_START_BLOCK() const { return nPOSStartBlock; } int Zerocoin_StartHeight() const { return nZerocoinStartHeight; } int Zerocoin_Block_EnforceSerialRange() const { return nBlockEnforceSerialRange; } int Zerocoin_Block_RecalculateAccumulators() const { return nBlockRecalculateAccumulators; } int Zerocoin_Block_FirstFraudulent() const { return nBlockFirstFraudulent; } int Zerocoin_Block_LastGoodCheckpoint() const { return nBlockLastGoodCheckpoint; } //int64_t Zerocoin_StartTime() const { return nZerocoinStartTime; } int Block_Enforce_Invalid() const { return nBlockEnforceInvalidUTXO; } int Zerocoin_Block_V2_Start() const { return nBlockZerocoinV2; } CAmount InvalidAmountFiltered() const { return nInvalidAmountFiltered; }; protected: CChainParams() {} uint256 hashGenesisBlock; MessageStartChars pchMessageStart; //! Raw pub key bytes for the broadcast alert signing key. std::vector<unsigned char> vAlertPubKey; int nDefaultPort; uint256 bnProofOfWorkLimit; int nMaxReorganizationDepth; int nEnforceBlockUpgradeMajority; int nRejectBlockOutdatedMajority; int nToCheckBlockUpgradeMajority; int64_t nTargetTimespan; int64_t nTargetSpacing; int nMandatoryUpgradeBlock; int nUpgradeBlockVersion; int nLastPOWBlock; int nPOSStartBlock; int nMasternodeCountDrift; int nMaturity; int nModifierUpdateBlock; CAmount nMaxMoneyOut; int nMinerThreads; std::vector<CDNSSeedData> vSeeds; std::vector<unsigned char> base58Prefixes[MAX_BASE58_TYPES]; CBaseChainParams::Network networkID; std::string strNetworkID; CBlock genesis; std::vector<CAddress> vFixedSeeds; bool fMiningRequiresPeers; bool fAllowMinDifficultyBlocks; bool fDefaultConsistencyChecks; bool fRequireStandard; bool fMineBlocksOnDemand; bool fSkipProofOfWorkCheck; bool fTestnetToBeDeprecatedFieldRPC; int nPoolMaxTransactions; std::string strSporkKey; std::string strSporkKeyOld; int64_t nEnforceNewSporkKey; int64_t nRejectOldSporkKey; std::string strObfuscationPoolDummyAddress; int64_t nStartMasternodePayments; std::string zerocoinModulus; int nMaxZerocoinSpendsPerTransaction; CAmount nMinZerocoinMintFee; CAmount nInvalidAmountFiltered; int nMintRequiredConfirmations; int nRequiredAccumulation; int nDefaultSecurityLevel; int nZerocoinHeaderVersion; int64_t nBudget_Fee_Confirmations; int nZerocoinStartHeight; //int64_t nZerocoinStartTime; int nZerocoinRequiredStakeDepth; int nBlockEnforceSerialRange; int nBlockRecalculateAccumulators; int nBlockFirstFraudulent; int nBlockLastGoodCheckpoint; int nBlockEnforceInvalidUTXO; int nBlockZerocoinV2; }; /** * Modifiable parameters interface is used by test cases to adapt the parameters in order * to test specific features more easily. Test cases should always restore the previous * values after finalization. */ class CModifiableParams { public: //! Published setters to allow changing values in unit test cases virtual void setEnforceBlockUpgradeMajority(int anEnforceBlockUpgradeMajority) = 0; virtual void setRejectBlockOutdatedMajority(int anRejectBlockOutdatedMajority) = 0; virtual void setToCheckBlockUpgradeMajority(int anToCheckBlockUpgradeMajority) = 0; virtual void setDefaultConsistencyChecks(bool aDefaultConsistencyChecks) = 0; virtual void setAllowMinDifficultyBlocks(bool aAllowMinDifficultyBlocks) = 0; virtual void setSkipProofOfWorkCheck(bool aSkipProofOfWorkCheck) = 0; }; /** * Return the currently selected parameters. This won't change after app startup * outside of the unit tests. */ const CChainParams& Params(); /** Return parameters for the given network. */ CChainParams& Params(CBaseChainParams::Network network); /** Get modifiable network parameters (UNITTEST only) */ CModifiableParams* ModifiableParams(); /** Sets the params returned by Params() to those for the given network. */ void SelectParams(CBaseChainParams::Network network); /** * Looks for -regtest or -testnet and then calls SelectParams as appropriate. * Returns false if an invalid combination is given. */ bool SelectParamsFromCommandLine(); #endif // BITCOIN_CHAINPARAMS_H
[ "dutcoin@hotmail.com" ]
dutcoin@hotmail.com
5460a42b3a2316f6dac2b214ec5a96bf2cc9a326
bf1d7de7f83d4e2b085acb10ada52f3d19128111
/les13Mesh/src/ofApp.cpp
f51207e5adf4d41ebf98045e1c5d9478b22fba25
[]
no_license
julianbeek/openFrameworksHKU
fd7d29ac2df1dc67dfd2c5fb99de828b9341767d
e53b23464a2d2c11c00e6c63acca61c48c8e0fc4
refs/heads/master
2021-01-10T09:31:53.014852
2015-12-08T00:17:35
2015-12-08T00:17:35
43,745,658
0
0
null
null
null
null
UTF-8
C++
false
false
1,842
cpp
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ image.load("image.jpg"); for (int y=0; y<MESH_HEIGHT; y++){ for (int x=0; x<MESH_WIDTH; x++) { ofPoint vertex = ofPoint((x - MESH_WIDTH/2)*MESH_SIZE, (y - MESH_HEIGHT/2)*MESH_SIZE, 0); mesh.addVertex(vertex); mesh.addTexCoord(ofPoint(x * (IMAGE_WIDTH/IMAGE_HEIGHT), y * (IMAGE_HEIGHT/IMAGE_WIDTH))); ofColor color = ofColor(255,255,255); mesh.addColor(color); } } for (int y=0; y<MESH_HEIGHT-1; y++){ for (int x=0; x<MESH_WIDTH; x++){ int vertex1 = x + MESH_WIDTH * y; int vertex2 = x + 1 + MESH_WIDTH * y; int vertex3 = x + MESH_WIDTH * (y+1); int vertex4 = x + 1 + MESH_WIDTH * (y+1); mesh.addTriangle(vertex1, vertex2, vertex3); mesh.addTriangle(vertex2, vertex4, vertex3); } } } //-------------------------------------------------------------- void ofApp::update(){ for (int y=0; y<MESH_WIDTH; y++){ for (int x=0; x<MESH_HEIGHT; x++) { int index = x+ MESH_WIDTH*y; ofPoint vertex = mesh.getVertex(index); vertex.z = ofNoise(x * 0.05, y * 0.05, ofGetElapsedTimef() * 0.5)* 100; mesh.setVertex(index, vertex); } } } //-------------------------------------------------------------- void ofApp::draw(){ ofBackground(0); cam.setVFlip(true); cam.begin(); image.bind(); mesh.drawWireframe(); image.unbind(); cam.end(); }
[ "julian.vandebeek@student.hku.nl" ]
julian.vandebeek@student.hku.nl
01f0fc95c4be9d4867965e1bbcce5a982fefb329
a75bfdb61d2bfa20f71d2a1548188db18a8e5e6d
/Codeforces/377/d.cpp
2218ea2cf754f4bd338b4cd62d6585bd09bca2e8
[]
no_license
Ra1nWarden/Online-Judges
79bbe269fd35bfb1b4a5b3ea68b806fb39b49e15
6d8516bb1560f3620bdc2fc429863a1551d60e6a
refs/heads/master
2022-05-01T17:50:00.253901
2022-04-18T06:55:25
2022-04-18T06:55:25
18,355,773
0
0
null
null
null
null
UTF-8
C++
false
false
898
cpp
#include <cstdio> #include <cstring> using namespace std; const int maxn = 100000; int t[maxn+5]; int v[maxn+5]; int o[maxn+5]; int d[maxn+5]; int n, m; bool test(int x) { memset(d, -1, sizeof d); int idx = m; for(int i = x; i >= 1; i--) { if(t[i] == 0 || d[t[i]] != -1) { continue; } o[idx--] = t[i]; d[t[i]] = i; } if(idx != 0) return false; int total = 0; for(int i = 1; i <= m; i++) { total += v[o[i]]; if(total + i > d[o[i]]) return false; } return true; } int main() { scanf("%d%d", &n, &m); for(int i = 1; i <= n; i++) scanf("%d", &t[i]); for(int i = 1; i <= m; i++) scanf("%d", &v[i]); int l = 1, r = n + 1; while(l != r) { int mid = (l + r) >> 1; if(test(mid)) { r = mid; } else { l = mid + 1; } } if(l == n + 1) printf("-1\n"); else printf("%d\n", l); return 0; }
[ "wzh19921016@gmail.com" ]
wzh19921016@gmail.com
18f0297657ef8be3ef6d4112d9ea5a142fc54564
7b266ba5ba9a4aef70306222e3d75c13c90cc907
/pyschedcl/passes/feature_pass/thrud/include/thrud/DivergenceAnalysis.h
34d2ae7ce25935543b03d9d7c6846365dda52331
[ "NCSA", "MIT" ]
permissive
anighose25/pyschedcl-concurrent
7d5ef37c6787e31515bfa02517a9f58c8b4d6512
b50db92f090c2299b4cb080d40cd8d9a269b7bf7
refs/heads/master
2023-02-02T09:02:51.768124
2020-10-08T07:42:13
2020-10-08T07:42:13
287,000,379
0
1
MIT
2020-12-10T18:06:48
2020-08-12T11:50:04
C
UTF-8
C++
false
false
1,722
h
#ifndef DIVERGENCE_ANALYSIS_H #define DIVERGENCE_ANALYSIS_H #include "thrud/DataTypes.h" #include "thrud/DivergentRegion.h" #include "thrud/NDRange.h" #include "thrud/ControlDependenceAnalysis.h" #include "llvm/Pass.h" #include "llvm/Analysis/PostDominators.h" using namespace llvm; class DivergenceAnalysis { public: InstVector &getDivInsts(); InstVector &getOutermostDivInsts(); InstVector getDivInsts(DivergentRegion *region); bool isDivergent(Instruction *inst); RegionVector &getDivRegions(); RegionVector &getOutermostDivRegions(); RegionVector getDivRegions(DivergentRegion *region); protected: virtual InstVector getTids(); void performAnalysis(); void init(); void findBranches(); void findRegions(); void findOutermostInsts(InstVector &insts, RegionVector &regions, InstVector &result); void findOutermostRegions(); protected: InstVector divInsts; InstVector outermostDivInsts; InstVector divBranches; RegionVector regions; RegionVector outermostRegions; NDRange *ndr; PostDominatorTree *pdt; DominatorTree *dt; LoopInfo *loopInfo; ControlDependenceAnalysis *cda; }; class SingleDimDivAnalysis : public FunctionPass, public DivergenceAnalysis { public: static char ID; SingleDimDivAnalysis(); virtual bool runOnFunction(Function &F); virtual void getAnalysisUsage(AnalysisUsage &AU) const; public: virtual InstVector getTids(); }; class MultiDimDivAnalysis : public FunctionPass, public DivergenceAnalysis { public: static char ID; MultiDimDivAnalysis(); virtual bool runOnFunction(Function &F); virtual void getAnalysisUsage(AnalysisUsage &AU) const; public: virtual InstVector getTids(); }; #endif
[ "anighose25@gmail.com" ]
anighose25@gmail.com
6f2cd47ac889b08c5b52c87526093aab98e0bcb0
190c5e13c9710e77d84fe70e33988332834188bc
/gml/source/vector3.cpp
2c282a28980bc1261cdf25ea55d2460858f068c2
[]
no_license
YgritteSnow/gml
de2810da885be8cf9f3b651a09b334b89b2c0f16
97255cf5e91f319cdc13485f77b56582468bc5b8
refs/heads/master
2021-01-11T08:25:59.430879
2016-10-28T15:39:49
2016-10-28T15:39:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,138
cpp
#include "../include/gmlvector.h" #include "../include/gmlutility.h" #include <cmath> #include <cassert> #include "inner_util.h" namespace gml { const vec3& vec3::zero() { static vec3 v(0.0f, 0.0f, 0.0f); return v; } const vec3& vec3::one() { static vec3 v(1.0f, 1.0f, 1.0f); return v; } const vec3& vec3::left() { static vec3 v(-1.0f, 0.0f, 0.0f); return v; } const vec3& vec3::right() { static vec3 v(1.0f, 0.0f, 0.0f); return v; } const vec3& vec3::up() { static vec3 v(0.0f, 1.0f, 0.0f); return v; } const vec3& vec3::down() { static vec3 v(0.0f, -1.0f, 0.0f); return v; } const vec3& vec3::forward() { static vec3 v(0.0f, 0.0f, 1.0f); return v; } const vec3& vec3::backward() { static vec3 v(0.0f, 0.0f, -1.0f); return v; } vec3::vec3() { } vec3::vec3(float x, float y, float z) { set(x, y, z); } vec3::vec3(const vec2& v2, float z) { set(v2, z); } vec3::vec3(const vec4& v4) { set(v4.x, v4.y, v4.z); } vec3 vec3::operator-() const { return vec3(-x, -y, -z); } bool vec3::operator==(const vec3& rhs) const { if (&rhs == this) return true; return fequal(x, rhs.x) && fequal(y, rhs.y) && fequal(z, rhs.z); } bool vec3::operator!=(const vec3& rhs) const { return !(*this == rhs); } vec3 vec3::operator+(float value) const { vec3 copy(*this); copy += value; return copy; } vec3 vec3::operator-(float value) const { vec3 copy(*this); copy -= value; return copy; } vec3 vec3::operator*(float value) const { vec3 copy(*this); copy *= value; return copy; } vec3 vec3::operator+(const vec3& rhs) const { return vec3(x + rhs.x, y + rhs.y, z + rhs.z); } vec3 vec3::operator-(const vec3& rhs) const { return vec3(x - rhs.x, y - rhs.y, z - rhs.z); } vec3 vec3::operator*(const vec3& rhs) const { return vec3(x * rhs.x, y * rhs.y, z * rhs.z); } vec3& vec3::operator+=(float value) { x += value; y += value; z += value; return *this; } vec3& vec3::operator-=(float value) { x -= value; y -= value; z -= value; return *this; } vec3& vec3::operator*=(float value) { x *= value; y *= value; z *= value; return *this; } vec3& vec3::operator+=(const vec3& rhs) { x += rhs.x; y += rhs.y; z += rhs.z; return *this; } vec3& vec3::operator-=(const vec3& rhs) { x -= rhs.x; y -= rhs.y; z -= rhs.z; return *this; } vec3& vec3::operator*=(const vec3& rhs) { x *= rhs.x; y *= rhs.y; z *= rhs.z; return *this; } float& vec3::operator[](int index) { return const_cast<float&>(const_cast<const vec3*>(this)->operator[](index)); } const float& vec3::operator[](int index) const { assert(index >= 0 && index < 3); return *(&x + index); } vec3::operator float*() { return &(this->x); } vec3& vec3::set(const vec2& v2, float z) { this->x = v2.x; this->y = v2.y; this->z = z; return *this; } vec3& vec3::set(float x, float y, float z) { this->x = x; this->y = y; this->z = z; return *this; } vec3& vec3::set(const vec4& v4) { set(v4.x, v4.y, v4.z); return *this; } vec3& vec3::replace(const vec2& v2) { x = v2.x; y = v2.y; return *this; } vec3 vec3::normalized() const { vec3 copy(*this); return copy.normalize(); } vec3& vec3::normalize() { float length2 = length_sqr(); if (!fequal(length2, 0.0f) && !fequal(1.0f, length2)) { float invLength = 1.0f / sqrtf(length2); this->x *= invLength; this->y *= invLength; this->z *= invLength; } else { *this = zero(); } return *this; } vec3& vec3::inverse() { x = 1.0f / x; y = 1.0f / y; z = 1.0f / z; return *this; } vec3 vec3::inversed() const { vec3 copy(*this); return copy.inverse(); } float vec3::length() const { return sqrtf(x*x + y*y + z*z); } float vec3::length_sqr() const { return x*x + y*y + z*z; } vec3 operator+(float value, const vec3& rhs) { return rhs + value; } vec3 operator-(float value, const vec3& rhs) { return rhs - value; } vec3 operator*(float value, const vec3& rhs) { return rhs * value; } float dot(const vec3& lhs, const vec3& rhs) { return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z; } vec3 cross(const vec3& lhs, const vec3& rhs) { return vec3( lhs.y * rhs.z - lhs.z * rhs.y, lhs.z * rhs.x - lhs.x * rhs.z, lhs.x * rhs.y - lhs.y * rhs.x ); } vec3 min_combine(const vec3& lhs, const vec3& rhs) { return vec3( lhs.x < rhs.x ? lhs.x : rhs.x, lhs.y < rhs.y ? lhs.y : rhs.y, lhs.z < rhs.z ? lhs.z : rhs.z ); } vec3 max_combine(const vec3& lhs, const vec3& rhs) { return vec3( lhs.x > rhs.x ? lhs.x : rhs.x, lhs.y > rhs.y ? lhs.y : rhs.y, lhs.z > rhs.z ? lhs.z : rhs.z ); } float det33(const gml::vec3& row1, const gml::vec3& row2, const gml::vec3& row3) { return determinant_impl(row1.x, row1.y, row1.z, row2.x, row2.y, row2.z, row3.x, row3.y, row3.z); } float det33_t(const gml::vec3& row1, const gml::vec3& row2, const gml::vec3& row3) { return determinant_impl(row1.x, row2.x, row3.x, row1.y, row2.y, row3.y, row1.z, row2.z, row3.z); } }
[ "goteet@126.com" ]
goteet@126.com
2b248958a2fab3d4b8f1afa9e1da4947b9c290b3
27b06e601577ea8ed643d83c878608f47b6cd929
/multiphaseInterFoam/waveSlopeOil/system/decomposeParDict
6a431055e6fa796f55d02275b4463624c4e2dd7f
[]
no_license
SMUZYG/olaFlow_supplementary
891e7f377562d72bb18fc88947c77d62a790fb80
f87d4fe3274f4174453c15f65b5e02524732c776
refs/heads/master
2023-07-27T02:48:42.961568
2021-09-08T14:52:01
2021-09-08T14:53:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,183
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.1.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "system"; object decomposeParDict; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // numberOfSubdomains 2; method scotch; simpleCoeffs { n ( 2 2 1 ); delta 0.001; } hierarchicalCoeffs { n ( 1 1 1 ); delta 0.001; order xyz; } manualCoeffs { dataFile ""; } distributed no; roots ( ); // ************************************************************************* //
[ "phicau@gmail.com" ]
phicau@gmail.com
1c868561c5f0ea07c9d4d9ee447666242b10518c
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/git/gumtree/git_new_hunk_2016.cpp
829ae1c3ba69b4323b013c8e7858f6d320f0f8db
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
400
cpp
die("More than one commit to dig from %s and %s?", revs->pending.objects[i].name, final_commit_name); sb->final = (struct commit *) obj; final_commit_name = revs->pending.objects[i].name; } return xstrdup_or_null(final_commit_name); } static char *prepare_initial(struct scoreboard *sb) { int i; const char *final_commit_name = NULL; struct rev_info *revs = sb->revs; /*
[ "993273596@qq.com" ]
993273596@qq.com
18df51c42bb368e7e9c40617a8d09fda4f9ed54a
8566324b0a42dd56ef204ee1a02b8d701346793a
/deps/quic/quic_session_test.cc
e50985adbad2c15312559293d52d54f028912155
[]
no_license
kppamy/Orca
b81c54c930722f664363c53f36a85e71704af80a
416226cf9ca6a57c933ef8379bbf0e3ad405dd40
refs/heads/master
2021-05-29T04:15:00.438930
2015-07-16T04:56:45
2015-07-16T04:56:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,825
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/quic/quic_session.h" #include <set> #include <vector> #include "base/basictypes.h" #include "base/containers/hash_tables.h" #include "net/quic/crypto/crypto_protocol.h" #include "net/quic/quic_crypto_stream.h" #include "net/quic/quic_flags.h" #include "net/quic/quic_protocol.h" #include "net/quic/quic_utils.h" #include "net/quic/reliable_quic_stream.h" #include "net/quic/test_tools/quic_connection_peer.h" #include "net/quic/test_tools/quic_data_stream_peer.h" #include "net/quic/test_tools/quic_session_peer.h" #include "net/quic/test_tools/quic_test_utils.h" #include "net/quic/test_tools/reliable_quic_stream_peer.h" #include "net/spdy/spdy_framer.h" #include "net/test/gtest_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using base::hash_map; using std::set; using std::vector; using testing::_; using testing::InSequence; using testing::InvokeWithoutArgs; using testing::Return; using testing::StrictMock; namespace net { namespace test { namespace { const QuicPriority kHighestPriority = 0; const QuicPriority kSomeMiddlePriority = 3; class TestCryptoStream : public QuicCryptoStream { public: explicit TestCryptoStream(QuicSession* session) : QuicCryptoStream(session) { } virtual void OnHandshakeMessage( const CryptoHandshakeMessage& message) OVERRIDE { encryption_established_ = true; handshake_confirmed_ = true; CryptoHandshakeMessage msg; string error_details; session()->config()->SetInitialFlowControlWindowToSend( kInitialFlowControlWindowForTest); session()->config()->ToHandshakeMessage(&msg); const QuicErrorCode error = session()->config()->ProcessPeerHello( msg, CLIENT, &error_details); EXPECT_EQ(QUIC_NO_ERROR, error); session()->OnConfigNegotiated(); session()->OnCryptoHandshakeEvent(QuicSession::HANDSHAKE_CONFIRMED); } MOCK_METHOD0(OnCanWrite, void()); }; class TestStream : public QuicDataStream { public: TestStream(QuicStreamId id, QuicSession* session) : QuicDataStream(id, session) { } using ReliableQuicStream::CloseWriteSide; virtual uint32 ProcessData(const char* data, uint32 data_len) { return data_len; } void SendBody(const string& data, bool fin) { WriteOrBufferData(data, fin, NULL); } MOCK_METHOD0(OnCanWrite, void()); }; // Poor man's functor for use as callback in a mock. class StreamBlocker { public: StreamBlocker(QuicSession* session, QuicStreamId stream_id) : session_(session), stream_id_(stream_id) { } void MarkWriteBlocked() { session_->MarkWriteBlocked(stream_id_, kSomeMiddlePriority); } private: QuicSession* const session_; const QuicStreamId stream_id_; }; class TestSession : public QuicSession { public: explicit TestSession(QuicConnection* connection) : QuicSession(connection, DefaultQuicConfig()), crypto_stream_(this), writev_consumes_all_data_(false) { } virtual TestCryptoStream* GetCryptoStream() OVERRIDE { return &crypto_stream_; } virtual TestStream* CreateOutgoingDataStream() OVERRIDE { TestStream* stream = new TestStream(GetNextStreamId(), this); ActivateStream(stream); return stream; } virtual TestStream* CreateIncomingDataStream(QuicStreamId id) OVERRIDE { return new TestStream(id, this); } bool IsClosedStream(QuicStreamId id) { return QuicSession::IsClosedStream(id); } QuicDataStream* GetIncomingDataStream(QuicStreamId stream_id) { return QuicSession::GetIncomingDataStream(stream_id); } virtual QuicConsumedData WritevData( QuicStreamId id, const IOVector& data, QuicStreamOffset offset, bool fin, QuicAckNotifier::DelegateInterface* ack_notifier_delegate) OVERRIDE { // Always consumes everything. if (writev_consumes_all_data_) { return QuicConsumedData(data.TotalBufferSize(), fin); } else { return QuicSession::WritevData(id, data, offset, fin, ack_notifier_delegate); } } void set_writev_consumes_all_data(bool val) { writev_consumes_all_data_ = val; } QuicConsumedData SendStreamData() { return WritevData(5, IOVector(), 0, true, NULL); } private: TestCryptoStream crypto_stream_; bool writev_consumes_all_data_; }; class QuicSessionTest : public ::testing::TestWithParam<QuicVersion> { protected: QuicSessionTest() : connection_(new MockConnection(true, SupportedVersions(GetParam()))), session_(connection_) { headers_[":host"] = "www.google.com"; headers_[":path"] = "/index.hml"; headers_[":scheme"] = "http"; headers_["cookie"] = "__utma=208381060.1228362404.1372200928.1372200928.1372200928.1; " "__utmc=160408618; " "GX=DQAAAOEAAACWJYdewdE9rIrW6qw3PtVi2-d729qaa-74KqOsM1NVQblK4VhX" "hoALMsy6HOdDad2Sz0flUByv7etmo3mLMidGrBoljqO9hSVA40SLqpG_iuKKSHX" "RW3Np4bq0F0SDGDNsW0DSmTS9ufMRrlpARJDS7qAI6M3bghqJp4eABKZiRqebHT" "pMU-RXvTI5D5oCF1vYxYofH_l1Kviuiy3oQ1kS1enqWgbhJ2t61_SNdv-1XJIS0" "O3YeHLmVCs62O6zp89QwakfAWK9d3IDQvVSJzCQsvxvNIvaZFa567MawWlXg0Rh" "1zFMi5vzcns38-8_Sns; " "GA=v*2%2Fmem*57968640*47239936%2Fmem*57968640*47114716%2Fno-nm-" "yj*15%2Fno-cc-yj*5%2Fpc-ch*133685%2Fpc-s-cr*133947%2Fpc-s-t*1339" "47%2Fno-nm-yj*4%2Fno-cc-yj*1%2Fceft-as*1%2Fceft-nqas*0%2Fad-ra-c" "v_p%2Fad-nr-cv_p-f*1%2Fad-v-cv_p*859%2Fad-ns-cv_p-f*1%2Ffn-v-ad%" "2Fpc-t*250%2Fpc-cm*461%2Fpc-s-cr*722%2Fpc-s-t*722%2Fau_p*4" "SICAID=AJKiYcHdKgxum7KMXG0ei2t1-W4OD1uW-ecNsCqC0wDuAXiDGIcT_HA2o1" "3Rs1UKCuBAF9g8rWNOFbxt8PSNSHFuIhOo2t6bJAVpCsMU5Laa6lewuTMYI8MzdQP" "ARHKyW-koxuhMZHUnGBJAM1gJODe0cATO_KGoX4pbbFxxJ5IicRxOrWK_5rU3cdy6" "edlR9FsEdH6iujMcHkbE5l18ehJDwTWmBKBzVD87naobhMMrF6VvnDGxQVGp9Ir_b" "Rgj3RWUoPumQVCxtSOBdX0GlJOEcDTNCzQIm9BSfetog_eP_TfYubKudt5eMsXmN6" "QnyXHeGeK2UINUzJ-D30AFcpqYgH9_1BvYSpi7fc7_ydBU8TaD8ZRxvtnzXqj0RfG" "tuHghmv3aD-uzSYJ75XDdzKdizZ86IG6Fbn1XFhYZM-fbHhm3mVEXnyRW4ZuNOLFk" "Fas6LMcVC6Q8QLlHYbXBpdNFuGbuZGUnav5C-2I_-46lL0NGg3GewxGKGHvHEfoyn" "EFFlEYHsBQ98rXImL8ySDycdLEFvBPdtctPmWCfTxwmoSMLHU2SCVDhbqMWU5b0yr" "JBCScs_ejbKaqBDoB7ZGxTvqlrB__2ZmnHHjCr8RgMRtKNtIeuZAo "; } void CheckClosedStreams() { for (int i = kCryptoStreamId; i < 100; i++) { if (closed_streams_.count(i) == 0) { EXPECT_FALSE(session_.IsClosedStream(i)) << " stream id: " << i; } else { EXPECT_TRUE(session_.IsClosedStream(i)) << " stream id: " << i; } } } void CloseStream(QuicStreamId id) { session_.CloseStream(id); closed_streams_.insert(id); } QuicVersion version() const { return connection_->version(); } MockConnection* connection_; TestSession session_; set<QuicStreamId> closed_streams_; SpdyHeaderBlock headers_; }; INSTANTIATE_TEST_CASE_P(Tests, QuicSessionTest, ::testing::ValuesIn(QuicSupportedVersions())); TEST_P(QuicSessionTest, PeerAddress) { EXPECT_EQ(IPEndPoint(Loopback4(), kTestPort), session_.peer_address()); } TEST_P(QuicSessionTest, IsCryptoHandshakeConfirmed) { EXPECT_FALSE(session_.IsCryptoHandshakeConfirmed()); CryptoHandshakeMessage message; session_.GetCryptoStream()->OnHandshakeMessage(message); EXPECT_TRUE(session_.IsCryptoHandshakeConfirmed()); } TEST_P(QuicSessionTest, IsClosedStreamDefault) { // Ensure that no streams are initially closed. for (int i = kCryptoStreamId; i < 100; i++) { EXPECT_FALSE(session_.IsClosedStream(i)) << "stream id: " << i; } } TEST_P(QuicSessionTest, ImplicitlyCreatedStreams) { ASSERT_TRUE(session_.GetIncomingDataStream(7) != NULL); // Both 3 and 5 should be implicitly created. EXPECT_FALSE(session_.IsClosedStream(3)); EXPECT_FALSE(session_.IsClosedStream(5)); ASSERT_TRUE(session_.GetIncomingDataStream(5) != NULL); ASSERT_TRUE(session_.GetIncomingDataStream(3) != NULL); } TEST_P(QuicSessionTest, IsClosedStreamLocallyCreated) { TestStream* stream2 = session_.CreateOutgoingDataStream(); EXPECT_EQ(2u, stream2->id()); TestStream* stream4 = session_.CreateOutgoingDataStream(); EXPECT_EQ(4u, stream4->id()); CheckClosedStreams(); CloseStream(4); CheckClosedStreams(); CloseStream(2); CheckClosedStreams(); } TEST_P(QuicSessionTest, IsClosedStreamPeerCreated) { QuicStreamId stream_id1 = 5; QuicStreamId stream_id2 = stream_id1 + 2; QuicDataStream* stream1 = session_.GetIncomingDataStream(stream_id1); QuicDataStreamPeer::SetHeadersDecompressed(stream1, true); QuicDataStream* stream2 = session_.GetIncomingDataStream(stream_id2); QuicDataStreamPeer::SetHeadersDecompressed(stream2, true); CheckClosedStreams(); CloseStream(stream_id1); CheckClosedStreams(); CloseStream(stream_id2); // Create a stream explicitly, and another implicitly. QuicDataStream* stream3 = session_.GetIncomingDataStream(stream_id2 + 4); QuicDataStreamPeer::SetHeadersDecompressed(stream3, true); CheckClosedStreams(); // Close one, but make sure the other is still not closed CloseStream(stream3->id()); CheckClosedStreams(); } TEST_P(QuicSessionTest, StreamIdTooLarge) { QuicStreamId stream_id = 5; session_.GetIncomingDataStream(stream_id); EXPECT_CALL(*connection_, SendConnectionClose(QUIC_INVALID_STREAM_ID)); session_.GetIncomingDataStream(stream_id + kMaxStreamIdDelta + 2); } TEST_P(QuicSessionTest, DecompressionError) { QuicHeadersStream* stream = QuicSessionPeer::GetHeadersStream(&session_); const unsigned char data[] = { 0x80, 0x03, 0x00, 0x01, // SPDY/3 SYN_STREAM frame 0x00, 0x00, 0x00, 0x25, // flags/length 0x00, 0x00, 0x00, 0x05, // stream id 0x00, 0x00, 0x00, 0x00, // associated stream id 0x00, 0x00, 'a', 'b', 'c', 'd' // invalid compressed data }; EXPECT_CALL(*connection_, SendConnectionCloseWithDetails(QUIC_INVALID_HEADERS_STREAM_DATA, "SPDY framing error.")); stream->ProcessRawData(reinterpret_cast<const char*>(data), arraysize(data)); } TEST_P(QuicSessionTest, DebugDFatalIfMarkingClosedStreamWriteBlocked) { TestStream* stream2 = session_.CreateOutgoingDataStream(); // Close the stream. stream2->Reset(QUIC_BAD_APPLICATION_PAYLOAD); // TODO(rtenneti): enable when chromium supports EXPECT_DEBUG_DFATAL. /* QuicStreamId kClosedStreamId = stream2->id(); EXPECT_DEBUG_DFATAL( session_.MarkWriteBlocked(kClosedStreamId, kSomeMiddlePriority), "Marking unknown stream 2 blocked."); */ } TEST_P(QuicSessionTest, DebugDFatalIfMarkWriteBlockedCalledWithWrongPriority) { const QuicPriority kDifferentPriority = 0; TestStream* stream2 = session_.CreateOutgoingDataStream(); EXPECT_NE(kDifferentPriority, stream2->EffectivePriority()); // TODO(rtenneti): enable when chromium supports EXPECT_DEBUG_DFATAL. /* EXPECT_DEBUG_DFATAL( session_.MarkWriteBlocked(stream2->id(), kDifferentPriority), "Priorities do not match. Got: 0 Expected: 3"); */ } TEST_P(QuicSessionTest, OnCanWrite) { TestStream* stream2 = session_.CreateOutgoingDataStream(); TestStream* stream4 = session_.CreateOutgoingDataStream(); TestStream* stream6 = session_.CreateOutgoingDataStream(); session_.MarkWriteBlocked(stream2->id(), kSomeMiddlePriority); session_.MarkWriteBlocked(stream6->id(), kSomeMiddlePriority); session_.MarkWriteBlocked(stream4->id(), kSomeMiddlePriority); InSequence s; StreamBlocker stream2_blocker(&session_, stream2->id()); EXPECT_CALL(*stream2, OnCanWrite()).WillOnce( // Reregister, to test the loop limit. InvokeWithoutArgs(&stream2_blocker, &StreamBlocker::MarkWriteBlocked)); EXPECT_CALL(*stream6, OnCanWrite()); EXPECT_CALL(*stream4, OnCanWrite()); session_.OnCanWrite(); EXPECT_TRUE(session_.HasPendingWrites()); } TEST_P(QuicSessionTest, OnCanWriteBundlesStreams) { // Drive congestion control manually. MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>; QuicConnectionPeer::SetSendAlgorithm(session_.connection(), send_algorithm); TestStream* stream2 = session_.CreateOutgoingDataStream(); TestStream* stream4 = session_.CreateOutgoingDataStream(); TestStream* stream6 = session_.CreateOutgoingDataStream(); session_.MarkWriteBlocked(stream2->id(), kSomeMiddlePriority); session_.MarkWriteBlocked(stream6->id(), kSomeMiddlePriority); session_.MarkWriteBlocked(stream4->id(), kSomeMiddlePriority); EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _)).WillRepeatedly( Return(QuicTime::Delta::Zero())); EXPECT_CALL(*send_algorithm, GetCongestionWindow()).WillOnce( Return(kMaxPacketSize * 10)); EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(IgnoreResult( InvokeWithoutArgs(&session_, &TestSession::SendStreamData))); EXPECT_CALL(*stream6, OnCanWrite()).WillOnce(IgnoreResult( InvokeWithoutArgs(&session_, &TestSession::SendStreamData))); EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(IgnoreResult( InvokeWithoutArgs(&session_, &TestSession::SendStreamData))); MockPacketWriter* writer = static_cast<MockPacketWriter*>( QuicConnectionPeer::GetWriter(session_.connection())); EXPECT_CALL(*writer, WritePacket(_, _, _, _)).WillOnce( Return(WriteResult(WRITE_STATUS_OK, 0))); EXPECT_CALL(*send_algorithm, OnPacketSent(_, _, _, _)); session_.OnCanWrite(); EXPECT_FALSE(session_.HasPendingWrites()); } TEST_P(QuicSessionTest, OnCanWriteCongestionControlBlocks) { InSequence s; // Drive congestion control manually. MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>; QuicConnectionPeer::SetSendAlgorithm(session_.connection(), send_algorithm); TestStream* stream2 = session_.CreateOutgoingDataStream(); TestStream* stream4 = session_.CreateOutgoingDataStream(); TestStream* stream6 = session_.CreateOutgoingDataStream(); session_.MarkWriteBlocked(stream2->id(), kSomeMiddlePriority); session_.MarkWriteBlocked(stream6->id(), kSomeMiddlePriority); session_.MarkWriteBlocked(stream4->id(), kSomeMiddlePriority); StreamBlocker stream2_blocker(&session_, stream2->id()); EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _)).WillOnce(Return( QuicTime::Delta::Zero())); EXPECT_CALL(*stream2, OnCanWrite()); EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _)).WillOnce(Return( QuicTime::Delta::Zero())); EXPECT_CALL(*stream6, OnCanWrite()); EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _)).WillOnce(Return( QuicTime::Delta::Infinite())); // stream4->OnCanWrite is not called. session_.OnCanWrite(); EXPECT_TRUE(session_.HasPendingWrites()); // Still congestion-control blocked. EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _)).WillOnce(Return( QuicTime::Delta::Infinite())); session_.OnCanWrite(); EXPECT_TRUE(session_.HasPendingWrites()); // stream4->OnCanWrite is called once the connection stops being // congestion-control blocked. EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _)).WillOnce(Return( QuicTime::Delta::Zero())); EXPECT_CALL(*stream4, OnCanWrite()); session_.OnCanWrite(); EXPECT_FALSE(session_.HasPendingWrites()); } TEST_P(QuicSessionTest, BufferedHandshake) { EXPECT_FALSE(session_.HasPendingHandshake()); // Default value. // Test that blocking other streams does not change our status. TestStream* stream2 = session_.CreateOutgoingDataStream(); StreamBlocker stream2_blocker(&session_, stream2->id()); stream2_blocker.MarkWriteBlocked(); EXPECT_FALSE(session_.HasPendingHandshake()); TestStream* stream3 = session_.CreateOutgoingDataStream(); StreamBlocker stream3_blocker(&session_, stream3->id()); stream3_blocker.MarkWriteBlocked(); EXPECT_FALSE(session_.HasPendingHandshake()); // Blocking (due to buffering of) the Crypto stream is detected. session_.MarkWriteBlocked(kCryptoStreamId, kHighestPriority); EXPECT_TRUE(session_.HasPendingHandshake()); TestStream* stream4 = session_.CreateOutgoingDataStream(); StreamBlocker stream4_blocker(&session_, stream4->id()); stream4_blocker.MarkWriteBlocked(); EXPECT_TRUE(session_.HasPendingHandshake()); InSequence s; // Force most streams to re-register, which is common scenario when we block // the Crypto stream, and only the crypto stream can "really" write. // Due to prioritization, we *should* be asked to write the crypto stream // first. // Don't re-register the crypto stream (which signals complete writing). TestCryptoStream* crypto_stream = session_.GetCryptoStream(); EXPECT_CALL(*crypto_stream, OnCanWrite()); // Re-register all other streams, to show they weren't able to proceed. EXPECT_CALL(*stream2, OnCanWrite()).WillOnce( InvokeWithoutArgs(&stream2_blocker, &StreamBlocker::MarkWriteBlocked)); EXPECT_CALL(*stream3, OnCanWrite()).WillOnce( InvokeWithoutArgs(&stream3_blocker, &StreamBlocker::MarkWriteBlocked)); EXPECT_CALL(*stream4, OnCanWrite()).WillOnce( InvokeWithoutArgs(&stream4_blocker, &StreamBlocker::MarkWriteBlocked)); session_.OnCanWrite(); EXPECT_TRUE(session_.HasPendingWrites()); EXPECT_FALSE(session_.HasPendingHandshake()); // Crypto stream wrote. } TEST_P(QuicSessionTest, OnCanWriteWithClosedStream) { TestStream* stream2 = session_.CreateOutgoingDataStream(); TestStream* stream4 = session_.CreateOutgoingDataStream(); TestStream* stream6 = session_.CreateOutgoingDataStream(); session_.MarkWriteBlocked(stream2->id(), kSomeMiddlePriority); session_.MarkWriteBlocked(stream6->id(), kSomeMiddlePriority); session_.MarkWriteBlocked(stream4->id(), kSomeMiddlePriority); CloseStream(stream6->id()); InSequence s; EXPECT_CALL(*stream2, OnCanWrite()); EXPECT_CALL(*stream4, OnCanWrite()); session_.OnCanWrite(); EXPECT_FALSE(session_.HasPendingWrites()); } TEST_P(QuicSessionTest, SendGoAway) { EXPECT_CALL(*connection_, SendGoAway(QUIC_PEER_GOING_AWAY, 0u, "Going Away.")); session_.SendGoAway(QUIC_PEER_GOING_AWAY, "Going Away."); EXPECT_TRUE(session_.goaway_sent()); EXPECT_CALL(*connection_, SendRstStream(3u, QUIC_STREAM_PEER_GOING_AWAY, 0)).Times(0); EXPECT_TRUE(session_.GetIncomingDataStream(3u)); } TEST_P(QuicSessionTest, DoNotSendGoAwayTwice) { EXPECT_CALL(*connection_, SendGoAway(QUIC_PEER_GOING_AWAY, 0u, "Going Away.")).Times(1); session_.SendGoAway(QUIC_PEER_GOING_AWAY, "Going Away."); EXPECT_TRUE(session_.goaway_sent()); session_.SendGoAway(QUIC_PEER_GOING_AWAY, "Going Away."); } TEST_P(QuicSessionTest, IncreasedTimeoutAfterCryptoHandshake) { EXPECT_EQ(kDefaultInitialTimeoutSecs, QuicConnectionPeer::GetNetworkTimeout(connection_).ToSeconds()); CryptoHandshakeMessage msg; session_.GetCryptoStream()->OnHandshakeMessage(msg); EXPECT_EQ(kDefaultTimeoutSecs, QuicConnectionPeer::GetNetworkTimeout(connection_).ToSeconds()); } TEST_P(QuicSessionTest, RstStreamBeforeHeadersDecompressed) { QuicStreamId stream_id1 = 5; // Send two bytes of payload. QuicStreamFrame data1(stream_id1, false, 0, MakeIOVector("HT")); vector<QuicStreamFrame> frames; frames.push_back(data1); EXPECT_TRUE(session_.WillAcceptStreamFrames(frames)); EXPECT_EQ(1u, session_.GetNumOpenStreams()); QuicRstStreamFrame rst1(stream_id1, QUIC_STREAM_NO_ERROR, 0); session_.OnRstStream(rst1); EXPECT_EQ(0u, session_.GetNumOpenStreams()); } TEST_P(QuicSessionTest, MultipleRstStreamsCauseSingleConnectionClose) { // If multiple invalid reset stream frames arrive in a single packet, this // should trigger a connection close. However there is no need to send // multiple connection close frames. // Create valid stream. const QuicStreamId kStreamId = 5; QuicStreamFrame data1(kStreamId, false, 0, MakeIOVector("HT")); vector<QuicStreamFrame> frames; frames.push_back(data1); EXPECT_TRUE(session_.WillAcceptStreamFrames(frames)); EXPECT_EQ(1u, session_.GetNumOpenStreams()); // Process first invalid stream reset, resulting in the connection being // closed. EXPECT_CALL(*connection_, SendConnectionClose(QUIC_INVALID_STREAM_ID)) .Times(1); QuicStreamId kLargeInvalidStreamId = 99999999; QuicRstStreamFrame rst1(kLargeInvalidStreamId, QUIC_STREAM_NO_ERROR, 0); session_.OnRstStream(rst1); QuicConnectionPeer::CloseConnection(connection_); // Processing of second invalid stream reset should not result in the // connection being closed for a second time. QuicRstStreamFrame rst2(kLargeInvalidStreamId, QUIC_STREAM_NO_ERROR, 0); session_.OnRstStream(rst2); } TEST_P(QuicSessionTest, HandshakeUnblocksFlowControlBlockedStream) { // Test that if a stream is flow control blocked, then on receipt of the SHLO // containing a suitable send window offset, the stream becomes unblocked. if (version() < QUIC_VERSION_17) { return; } ValueRestore<bool> old_flag(&FLAGS_enable_quic_stream_flow_control_2, true); // Ensure that Writev consumes all the data it is given (simulate no socket // blocking). session_.set_writev_consumes_all_data(true); // Create a stream, and send enough data to make it flow control blocked. TestStream* stream2 = session_.CreateOutgoingDataStream(); string body(kDefaultFlowControlSendWindow, '.'); EXPECT_FALSE(stream2->flow_controller()->IsBlocked()); stream2->SendBody(body, false); EXPECT_TRUE(stream2->flow_controller()->IsBlocked()); // Now complete the crypto handshake, resulting in an increased flow control // send window. CryptoHandshakeMessage msg; session_.GetCryptoStream()->OnHandshakeMessage(msg); // Stream is now unblocked. EXPECT_FALSE(stream2->flow_controller()->IsBlocked()); } TEST_P(QuicSessionTest, InvalidFlowControlWindowInHandshake) { // Test that receipt of an invalid (< default) flow control window from peer // results in the connection being torn down. if (version() < QUIC_VERSION_17) { return; } ValueRestore<bool> old_flag(&FLAGS_enable_quic_stream_flow_control_2, true); uint32 kInvalidWindow = kDefaultFlowControlSendWindow - 1; CryptoHandshakeMessage msg; string error_details; session_.config()->SetInitialFlowControlWindowToSend(kInvalidWindow); session_.config()->ToHandshakeMessage(&msg); const QuicErrorCode error = session_.config()->ProcessPeerHello(msg, CLIENT, &error_details); EXPECT_EQ(QUIC_NO_ERROR, error); EXPECT_CALL(*connection_, SendConnectionClose(QUIC_FLOW_CONTROL_ERROR)); session_.OnConfigNegotiated(); } } // namespace } // namespace test } // namespace net
[ "kohachiro@qq.com" ]
kohachiro@qq.com
c2383c1815872955ffa6739350b177c84e8d6804
bc33c7c9f47857290e82a40a4867ade56484ff3f
/main.cpp
eea8eb73d27d342b9bb8845b278f91114b368b05
[]
no_license
philip-h/cgol
c78fd697f7ca5bfd964d913f297bcef1d359053c
65b0cd84c2400c356179e9cf86ccefc062563c20
refs/heads/master
2022-11-21T08:13:03.865413
2020-06-25T02:54:36
2020-06-25T02:54:36
274,806,489
0
0
null
null
null
null
UTF-8
C++
false
false
520
cpp
#include "Game.h" Game *game = nullptr; int main( void ) { const int FPS = 15; const int frameDelay = 1000 / FPS; Uint32 frameStart; int frameTime; game = new Game(); game->init("Game", 800, 800, false); while (game->isGameRunning()) { frameStart = SDL_GetTicks(); game->handleEvents(); game->update(); game->render(); frameTime = SDL_GetTicks() - frameStart; if (frameDelay > frameTime) { SDL_Delay(frameDelay - frameTime); } } game->clean(); return 0; }
[ "philip.habib6347@gmail.com" ]
philip.habib6347@gmail.com
cb6b3a8cfce792fe0ff38a2ae92d46f339ad431a
fdebed37cdfcf61f2e38f92abd59608d9a65271c
/src/world_generation/MountainModule.cpp
05775febdca6c92e2cd875b6c43c23071ee84929
[ "Apache-2.0" ]
permissive
guymor4/EagleBird
71022d143bee308cdf77bc5648688b55036c21fa
6b21819345c2a5d983a9d7fac2a12d85e3bbe9c2
refs/heads/master
2022-03-02T09:17:41.534035
2019-10-17T20:09:15
2019-10-17T20:09:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,364
cpp
// MountainModule.cpp // // Copyright (C) 2003, 2004 Jason Bevins // // This library 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 2.1 of the License, or (at // your option) any later version. // // This library 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 (COPYING.txt) for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // The developer's email is jlbezigvins@gmzigail.com (for great email, take // off every 'zig'.) // #include "MountainModule.h" using namespace noise::module; MountainModule::MountainModule() : Module(GetSourceModuleCount()), m_frequency(DEFAULT_RIDGED_FREQUENCY), m_lacunarity(DEFAULT_RIDGED_LACUNARITY), m_noiseQuality(DEFAULT_RIDGED_QUALITY), m_octaveCount(DEFAULT_RIDGED_OCTAVE_COUNT), m_seed(DEFAULT_RIDGED_SEED) { CalcSpectralWeights(); } // Calculates the spectral weights for each octave. void MountainModule::CalcSpectralWeights() { // This exponent parameter should be user-defined; it may be exposed in a // future version of libnoise. double h = 1.0; double frequency = 1.0; for (int i = 0; i < RIDGED_MAX_OCTAVE; i++) { // Compute weight for each frequency. m_pSpectralWeights[i] = pow(frequency, -h); frequency *= m_lacunarity; } } // Multifractal code originally written by F. Kenton "Doc Mojo" Musgrave, // 1998. Modified by jas for use with libnoise. double MountainModule::GetValue(double x, double y, double z) const { x *= m_frequency; y *= m_frequency; z *= m_frequency; double signal = 0.0; double value = 0.0; double weight = 1.0; // These parameters should be user-defined; they may be exposed in a // future version of libnoise. double offset = 1.0; double gain = 2.0; for (int curOctave = 0; curOctave < m_octaveCount; curOctave++) { // Make sure that these floating-point values have the same range as a 32- // bit integer so that we can pass them to the coherent-noise functions. double nx, ny, nz; nx = MakeInt32Range(x); ny = MakeInt32Range(y); nz = MakeInt32Range(z); // Get the coherent-noise value. int seed = (m_seed + curOctave) & 0x7fffffff; signal = GradientCoherentNoise3D(nx, ny, nz, seed, m_noiseQuality); // Make the ridges. signal = fabs(signal); signal = offset - signal; // Square the signal to increase the sharpness of the ridges. //signal *= signal; // The weighting from the previous octave is applied to the signal. // Larger values have higher weights, producing sharp points along the // ridges. signal *= weight; // Weight successive contributions by the previous signal. weight = signal * gain; if (weight > 1.0) { weight = 1.0; } if (weight < 0.0) { weight = 0.0; } // Add the signal to the output value. value += (signal * m_pSpectralWeights[curOctave]); // Go to the next octave. x *= m_lacunarity; y *= m_lacunarity; z *= m_lacunarity; } return (value * 1.25) - 1.0; }
[ "guymor4@gmail.com" ]
guymor4@gmail.com
296f575b55c19d470a6b98759f11115ec059f380
0f8c689169c39d435b8559b7c1bd5fb80cceb8fc
/include/Paper.h
392b5401b86bb92970313adfb2aa3ec8e6be6475
[]
no_license
hervasManuel/paperMarker
981ea198e4f10ea269947c0b8be95517d088996c
476b0e3f3462a9d54991e88f1db8c5b02c195461
refs/heads/master
2016-09-10T11:41:45.105448
2015-03-14T08:56:20
2015-03-14T08:56:20
32,203,403
1
0
null
null
null
null
UTF-8
C++
false
false
3,562
h
#ifndef _ARGOS_PAPER_H #define _ARGOS_PAPER_H #include "CameraModel.h" #include <vector> #include <iostream> #include <opencv2/opencv.hpp> using namespace std; using namespace cv; /** *\brief This class represents a sheet of paper. It is a vector of the fours corners of the paper * */ class Paper: public vector<cv::Point2f> { public: /** * Default Constructor */ Paper(); /** * */ Paper(cv::Size size); /** * */ Paper(const Paper &P); /** * */ Paper(const vector<cv::Point2f> &corners); /** * Default Destructor */ ~Paper() {} cv::Size getPaperSize() const{ return paperSize; } cv::Mat getRotVec() const{ return rotVec; } cv::Mat getTransVec() const{ return transVec; } void setRotVec(cv::Mat &rot) const{ rot.copyTo(rotVec); } void setTransVec(cv::Mat &trans) const{ trans.copyTo(transVec); } void setPaperSize(cv::Size size){ paperSize = size; } int getId() const{ return id; } void setId(int number){ id = number; } cv::Point2f& getFingerPoint(){ return fingerPoint; } void setFingerPoint(cv::Point2f pt){ fingerPoint = pt; } /** * Indicates if this object is valid */ bool isValid() const{ return size() == 4;} /** *Draws this paper in the input image */ void draw(cv::Mat &in, cv::Scalar color, int lineWidth=1, bool writeId=true)const; /** * Returns the centroid of the paper */ cv::Point2f getCenter()const; /** * Returns the perimeter of the paper */ float getPerimeter()const; /** * Returns the area */ float getArea()const; /** */ //friend bool operator<(const Paper &M1, const Paper &M2){ // return M1.id < M2.id; //} void glGetModelViewMatrix(float modelview_matrix[16]) throw(cv::Exception); void OgreGetPoseParameters(float position[3], float orientation[4]) throw(cv::Exception); //void calculateExtrinsics(cv::Size paperSizeMeters, CameraModel& camera, bool setYPerperdicular, bool screenExtrinsics) throw(cv::Exception); void calculateScreenExtrinsics(cv::Size paperSizeMeters, CameraModel& camera, bool setYPerperdicular) throw(cv::Exception); //void calculateProjectorExtrinsics(cv::Size paperSizeMeters, CameraProjectorSystem& cameraProjector, bool setYPerperdicular) throw(cv::Exception); void rotateXAxis(Mat &rotation); void rotateYAxis(Mat &rotation); void rotateYAxis2(Mat &rotation); void rotateZAxis(Mat &rotation); //void calculateExtrinsics(cv::Size paperSizeMeters, cv::Mat camMatrix, cv::Mat distCoeff, bool setYPerperdicular) throw(cv::Exception); /** */ friend ostream& operator<<(ostream &str, const Paper &P){ for (int i=0; i<4; i++) str<<"("<<P[i].x<< ","<<P[i].y<<") "; str<<"Rxyz="; for (int i=0; i<3; i++) str<<P.getRotVec().ptr<float>(0)[i]<<" "; str<<"Txyz="; for (int i=0;i<3;i++) str<<P.getTransVec().ptr<float>(0)[i]<<" "; return str; } protected: int id; // id of document detected cv::Size paperSize; // size of the paper sides in meters cv::Mat rotVec; // rotation matrix (Object->Projector) cv::Mat transVec; // translation matrix (Object->Projector) cv::Point2f fingerPoint; }; #endif
[ "hervas.manuel@gmail.com" ]
hervas.manuel@gmail.com
d7b57ab4fab2cd7cc19ce41822c0c7364f987688
33d6f34adda0007c7e1c7a9e1c1226879ebd8eff
/level0/CacheSet.cc
d6bd3cb1ef11431e4a0daf5b82989194c21638d6
[]
no_license
mdacrim97/cache-memory-simulations
8b2a7e74439cf73934cafe35b99a5db833f4617f
2621470ffc15f67fdf05df9a674b9f4478d8c53c
refs/heads/master
2022-06-20T21:13:04.642832
2020-05-13T16:32:32
2020-05-13T16:32:32
263,681,571
0
0
null
null
null
null
UTF-8
C++
false
false
1,450
cc
#include "CacheSet.h" using namespace std; //Mario Alex Crim /************************************************************************************ The CacheSet class is meant to simulate one set of CacheSet entries (in an N-way CacheSet) *************************************************************************************/ // constructor CacheSet::CacheSet(int lineSize, int Nway) { line_size = lineSize; associativity_factor = Nway; // create a line for each entry in the set for (int i=0; i < Nway; i++) cacheLine.push_back(CacheEntry(line_size)); hitCount = 0; missCount = 0; memoryReadCount = 0; } bool CacheSet::hit(int tag){ bool haveHit = false; for (int lineNumber=0; lineNumber < associativity_factor; lineNumber ++) if (cacheLine[lineNumber].hit(tag)) return true; return false; } bool CacheSet::readByte(int tag, int offset){ if(hit(tag)) return true; else if(cacheLine[0].readByte(offset)) loadLine(tag); return false; } void CacheSet::loadLine(int inputTag){ cacheLine[0].loadLine(inputTag); } int CacheSet::getHitCount(){ return hitCount; } int CacheSet::getMissCount(){ return missCount; } int CacheSet::getMemoryReadCount(){ return memoryReadCount; } void CacheSet::incrementHit(){ hitCount++; } void CacheSet::incrementMiss(){ missCount++; } void CacheSet::incrementRead(){ memoryReadCount++; }
[ "mdacrim97@gmail.com" ]
mdacrim97@gmail.com
c33be47164cdb75e107da20eaaa33b04cff52bd6
1fd1f1be6794b9bc9234e8af9cec5519c7cf1b58
/cs225/graph.cpp
5716da4d6bdd90fe4eb142b5101d6cc0d74ba665
[]
no_license
ylim31/graph-algorithm
657c8db3e3a66459613dc5fcbb59364a404554ff
099a0749065e1e592716b8b4f87de8991aaba3f7
refs/heads/master
2023-03-06T04:27:33.739667
2020-12-12T01:31:10
2020-12-12T01:31:10
339,611,073
0
0
null
null
null
null
UTF-8
C++
false
false
12,224
cpp
#include "graph.h" const Vertex Graph::InvalidVertex = "_CS225INVALIDVERTEX"; const int Graph::InvalidWeight = INT_MIN; const string Graph:: InvalidLabel = "_CS225INVALIDLABEL"; const Edge Graph::InvalidEdge = Edge(Graph::InvalidVertex, Graph::InvalidVertex, Graph::InvalidWeight, Graph::InvalidLabel); Graph::Graph(bool weighted) : weighted(weighted),directed(false),random(Random(0)) { number_of_nodes = 0; } Graph::Graph(bool weighted, bool directed) : weighted(weighted),directed(directed),random(Random(0)) { number_of_nodes = 0; } vector<Vertex> Graph::getAdjacent(Vertex source) const { auto lookup = adjacency_list.find(source); if(lookup == adjacency_list.end()) return vector<Vertex>(); else { vector<Vertex> vertex_list; unordered_map <Vertex, Edge> & map = adjacency_list[source]; for (auto it = map.begin(); it != map.end(); it++) { vertex_list.push_back(it->first); } return vertex_list; } } Vertex Graph::getStartingVertex() const { return adjacency_list.begin()->first; } vector<Vertex> Graph::getVertices() const { vector<Vertex> ret; for(auto it = adjacency_list.begin(); it != adjacency_list.end(); it++) { ret.push_back(it->first); } return ret; } Edge Graph::getEdge(Vertex source , Vertex destination) const { if(assertEdgeExists(source, destination, __func__) == false) return Edge(); Edge ret = adjacency_list[source][destination]; return ret; } vector<Edge> Graph::getEdges() const { if (adjacency_list.empty()) return vector<Edge>(); vector<Edge> ret; set<pair<Vertex, Vertex>> seen; for (auto it = adjacency_list.begin(); it != adjacency_list.end(); it++) { Vertex source = it->first; for (auto its = adjacency_list[source].begin(); its != adjacency_list[source].end(); its++) { Vertex destination = its->first; if(seen.find(make_pair(source, destination)) == seen.end()) { //this pair is never added to seen ret.push_back(its->second); seen.insert(make_pair(source,destination)); if(!directed) { seen.insert(make_pair(destination, source)); } } } } return ret; } bool Graph::vertexExists(Vertex v) const { return assertVertexExists(v, ""); } bool Graph::edgeExists(Vertex source, Vertex destination) const { return assertEdgeExists(source, destination, ""); } Edge Graph::setEdgeLabel(Vertex source, Vertex destination, string label) { if (assertEdgeExists(source, destination, __func__) == false) return InvalidEdge; Edge e = adjacency_list[source][destination]; Edge new_edge(source, destination, e.getWeight(), label); adjacency_list[source][destination] = new_edge; if(!directed) { Edge new_edge_reverse(destination,source, e.getWeight(), label); adjacency_list[destination][source] = new_edge_reverse; } return new_edge; } string Graph::getEdgeLabel(Vertex source, Vertex destination) const { if(assertEdgeExists(source, destination, __func__) == false) return InvalidLabel; return adjacency_list[source][destination].getLabel(); } int Graph::getEdgeWeight(Vertex source, Vertex destination) const { if (!weighted) error("can't get edge weights on non-weighted graphs!"); if(assertEdgeExists(source, destination, __func__) == false) return InvalidWeight; return adjacency_list[source][destination].getWeight(); } void Graph::insertVertex(Vertex v) { // will overwrite if old stuff was there removeVertex(v); // make it empty again adjacency_list[v] = unordered_map<Vertex, Edge>(); number_of_nodes++; } int Graph::getSize() { return number_of_nodes; } Vertex Graph::removeVertex(Vertex v) { if (adjacency_list.find(v) != adjacency_list.end()) { number_of_nodes--; if(!directed){ for (auto it = adjacency_list[v].begin(); it != adjacency_list[v].end(); it++) { Vertex u = it->first; adjacency_list[u].erase(v); } adjacency_list.erase(v); return v; } adjacency_list.erase(v); for(auto it2 = adjacency_list.begin(); it2 != adjacency_list.end(); it2++) { Vertex u = it2->first; if (it2->second.find(v)!=it2->second.end()) { it2->second.erase(v); } } return v; } return InvalidVertex; } bool Graph::insertEdge(Vertex source, Vertex destination) { if(adjacency_list.find(source)!= adjacency_list.end() && adjacency_list[source].find(destination)!= adjacency_list[source].end()) { //edge already exit return false; } if(adjacency_list.find(source)==adjacency_list.end()) { adjacency_list[source] = unordered_map<Vertex, Edge>(); } //source vertex exists adjacency_list[source][destination] = Edge(source, destination); if(!directed) { if(adjacency_list.find(destination)== adjacency_list.end()) { adjacency_list[destination] = unordered_map<Vertex, Edge>(); } adjacency_list[destination][source] = Edge(source, destination); } return true; } Edge Graph::removeEdge(Vertex source, Vertex destination) { if(assertEdgeExists(source, destination, __func__) == false) return InvalidEdge; Edge e = adjacency_list[source][destination]; adjacency_list[source].erase(destination); // if undirected, remove the corresponding edge if(!directed) { adjacency_list[destination].erase(source); } return e; } Edge Graph::setEdgeWeight(Vertex source, Vertex destination, int weight) { if (assertEdgeExists(source, destination, __func__) == false) return InvalidEdge; Edge e = adjacency_list[source][destination]; //std::cout << "setting weight: " << weight << std::endl; Edge new_edge(source, destination, weight, e.getLabel()); adjacency_list[source][destination] = new_edge; if(!directed) { Edge new_edge_reverse(destination,source, weight, e.getLabel()); adjacency_list[destination][source] = new_edge_reverse; } return new_edge; } bool Graph::assertVertexExists(Vertex v, string functionName) const { if (adjacency_list.find(v) == adjacency_list.end()) { if (functionName != "") error(functionName + " called on nonexistent vertices"); return false; } return true; } bool Graph::assertEdgeExists(Vertex source, Vertex destination, string functionName) const { if(assertVertexExists(source,functionName) == false) return false; if(adjacency_list[source].find(destination)== adjacency_list[source].end()) { if (functionName != "") error(functionName + " called on nonexistent edge " + source + " -> " + destination); return false; } if(!directed) { if (assertVertexExists(destination,functionName) == false) return false; if(adjacency_list[destination].find(source)== adjacency_list[destination].end()) { if (functionName != "") error(functionName + " called on nonexistent edge " + destination + " -> " + source); return false; } } return true; } bool Graph::isDirected() const { return directed; } void Graph::clear() { adjacency_list.clear(); } /** * Prints a graph error and quits the program. * The program is exited with a segfault to provide a stack trace. * @param message - the error message that is printed */ void Graph::error(string message) const { cerr << "\033[1;31m[Graph Error]\033[0m " + message << endl; } /** * Creates a name for snapshots of the graph. * @param title - the name to save the snapshots as */ void Graph::initSnapshot(string title) { picNum = 0; picName = title; } /** * Saves a snapshot of the graph to file. * initSnapshot() must be run first. */ void Graph::snapshot() { std::stringstream ss; ss << picNum; string newName = picName + ss.str(); savePNG(newName); ++picNum; } /** * Prints the graph to stdout. */ void Graph::print() const { for (auto it = adjacency_list.begin(); it != adjacency_list.end(); ++it) { cout << it->first << endl; for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) { std::stringstream ss; ss << it2->first; string vertexColumn = " => " + ss.str(); vertexColumn += " " ; cout << std::left << std::setw(26) << vertexColumn; string edgeColumn = "edge label = \"" + it2->second.getLabel()+ "\""; cout << std::left << std::setw(26) << edgeColumn; if (weighted) cout << "weight = " << it2->second.getWeight(); cout << endl; } cout << endl; } } /** * Saves the graph as a PNG image. * @param title - the filename of the PNG image */ void Graph::savePNG(string title) const { std::ofstream neatoFile; string filename = "images/" + title + ".dot"; neatoFile.open(filename.c_str()); if (!neatoFile.good()) error("couldn't create " + filename + ".dot"); neatoFile << "strict graph G {\n" << "\toverlap=\"false\";\n" << "\tdpi=\"1300\";\n" << "\tsep=\"1.5\";\n" << "\tnode [fixedsize=\"true\", shape=\"circle\", fontsize=\"7.0\"];\n" << "\tedge [penwidth=\"1.5\", fontsize=\"7.0\"];\n"; vector<Vertex> allv = getVertices(); //lambda expression sort(allv.begin(), allv.end(), [](const Vertex& lhs, const Vertex& rhs) { return stoi(lhs.substr(3)) > stoi(rhs.substr(3)); }); int xpos1 = 100; int xpos2 = 100; int xpos, ypos; for (auto it : allv) { string current = it; neatoFile << "\t\"" << current << "\""; if (current[1] == '1') { ypos = 100; xpos = xpos1; xpos1 += 100; } else { ypos = 200; xpos = xpos2; xpos2 += 100; } neatoFile << "[pos=\""<< xpos << "," << ypos <<"\"]"; neatoFile << ";\n"; } neatoFile << "\tedge [penwidth=\"1.5\", fontsize=\"7.0\"];\n"; for (auto it = adjacency_list.begin(); it != adjacency_list.end(); ++it) { for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) { string vertex1Text = it->first; string vertex2Text = it2->first; neatoFile << "\t\"" ; neatoFile << vertex1Text; neatoFile << "\" -- \"" ; neatoFile << vertex2Text; neatoFile << "\""; string edgeLabel = it2->second.getLabel(); if (edgeLabel == "WIN") { neatoFile << "[color=\"blue\"]"; } else if (edgeLabel == "LOSE") { neatoFile << "[color=\"red\"]"; } else { neatoFile << "[color=\"grey\"]"; } if (weighted && it2->second.getWeight() != -1) neatoFile << "[label=\"" << it2->second.getWeight() << "\"]"; neatoFile<< "[constraint = \"false\"]" << ";\n"; } } neatoFile << "}"; neatoFile.close(); string command = "neato -n -Tpng " + filename + " -o " + "images/" + title + ".png 2> /dev/null"; int result = system(command.c_str()); if (result == 0) { cout << "Output graph saved as images/" << title << ".png" << endl; } else { cout << "Failed to generate visual output graph using `neato`. Install `graphviz` or `neato` to generate a visual graph." << endl; } string rmCommand = "rm -f " + filename + " 2> /dev/null"; system(rmCommand.c_str()); }
[ "ylim31@illinois.edu" ]
ylim31@illinois.edu
c9a40c5d31920d5bebd15fad1eba4b1110686b5a
82ed416edcfdef66cb457415f11b5d399e07ac33
/basicWindow/basicWindow.cpp
89c31bfb4f85a697760dda0db1c865eb0025f78b
[]
no_license
tirodkar-raj/glGA
279acd914fc27074a995e161f9af0f533913f85f
999c9f384937a684c6579a3e6c751dc84123dfb6
refs/heads/master
2016-09-10T01:39:35.150625
2014-02-24T19:03:49
2014-02-24T19:03:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,445
cpp
// // main.cpp // basicWindow // // Created by George Papagiannakis on 23/10/12. // Copyright (c) 2012 University Of Crete & FORTH. All rights reserved. // // basic STL streams #include <iostream> #include "PlatformWrapper.h" // GLM lib // http://glm.g-truc.net/api/modules.html #define GLM_SWIZZLE #define GLM_FORCE_INLINE #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/quaternion.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/random.hpp> // global variables int windowWidth=1024, windowHeight=768; int main (int argc, const char * argv[]) { // test a simple GLM vector glm::vec4 origin(0.0f, 0.0f,0.0f,1.0f); // test a simple GLM matrix glm::mat4 matrix( 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); // initialise GLFW int running = GL_TRUE; if (!glfwInit()) { exit(EXIT_FAILURE); } //only for OpenGL 2.1 #ifdef USE_OPENGL21 glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 2); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 1); #endif //Only for OpenGL 3.2 #ifdef USE_OPENGL32 glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2); glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwOpenWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, 1); #endif GLFWvidmode mode; glfwGetDesktopMode(&mode); if( !glfwOpenWindow(windowWidth, windowHeight, mode.RedBits, mode.GreenBits, mode.BlueBits, 0, 32, 0, GLFW_WINDOW /* or GLFW_FULLSCREEN */) ) { glfwTerminate(); exit(EXIT_FAILURE); } glfwEnable(GLFW_MOUSE_CURSOR); glfwEnable(GLFW_KEY_REPEAT); // Ensure we can capture the escape key being pressed below glfwEnable( GLFW_STICKY_KEYS ); glfwSetMousePos(windowWidth/2, windowHeight/2); glfwSetWindowTitle("basic window for shader-based OpenGL"); //init GLEW and basic OpenGL information // VERY IMPORTANT OTHERWISE GLEW CANNOT HANDLE GL3 #ifdef USE_OPENGL32 glewExperimental = true; #endif glewInit(); std::cout<<"\nUsing GLEW "<<glewGetString(GLEW_VERSION)<<std::endl; if (GLEW_VERSION_2_1) { std::cout<<"\nYay! OpenGL 2.1 is supported and GLSL 1.2!\n"<<std::endl; } if (GLEW_VERSION_3_2) { std::cout<<"Yay! OpenGL 3.2 is supported and GLSL 1.5!\n"<<std::endl; } /* This extension defines an interface that allows various types of data (especially vertex array data) to be cached in high-performance graphics memory on the server, thereby increasing the rate of data transfers. Chunks of data are encapsulated within "buffer objects", which conceptually are nothing more than arrays of bytes, just like any chunk of memory. An API is provided whereby applications can read from or write to buffers, either via the GL itself (glBufferData, glBufferSubData, glGetBufferSubData) or via a pointer to the memory. */ if (glewIsSupported("GL_ARB_vertex_buffer_object")) std::cout<<"ARB VBO's are supported"<<std::endl; else if (glewIsSupported("GL_APPLE_vertex_buffer_object")) std::cout<<"APPLE VBO's are supported"<<std::endl; else std::cout<<"VBO's are not supported,program will not run!!!"<<std::endl; /* This extension introduces named vertex array objects which encapsulate vertex array state on the client side. The main purpose of these objects is to keep pointers to static vertex data and provide a name for different sets of static vertex data. By extending vertex array range functionality this extension allows multiple vertex array ranges to exist at one time, including their complete sets of state, in manner analogous to texture objects. GenVertexArraysAPPLE creates a list of n number of vertex array object names. After creating a name, BindVertexArrayAPPLE associates the name with a vertex array object and selects this vertex array and its associated state as current. To get back to the default vertex array and its associated state the client should bind to vertex array named 0. */ if (glewIsSupported("GL_ARB_vertex_array_object")) std::cout<<"ARB VAO's are supported\n"<<std::endl; else if (glewIsSupported("GL_APPLE_vertex_array_object"))//this is the name of the extension for GL2.1 in MacOSX std::cout<<"APPLE VAO's are supported\n"<<std::endl; else std::cout<<"VAO's are not supported, program will not run!!!\n"<<std::endl; std::cout<<"Vendor: "<<glGetString (GL_VENDOR)<<std::endl; std::cout<<"Renderer: "<<glGetString (GL_RENDERER)<<std::endl; std::cout<<"Version: "<<glGetString (GL_VERSION)<<std::endl; //GLFW main loop while (running) { glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT ); glClearColor( 0.0, 0.0, 1.0, 1.0); glfwSwapBuffers(); //check if ESC was pressed running=!glfwGetKey(GLFW_KEY_ESC) && glfwGetWindowParam(GLFW_OPENED); } //close OpenGL window and terminate GLFW glfwTerminate(); std::cout << "Hello, GLFW, GLEW, GLM World!\n"; exit(EXIT_SUCCESS); }
[ "papagian@ics.forth.gr" ]
papagian@ics.forth.gr
f2f269d6253887450617b67b30aaad80998465e0
fe5a8141eb208eb5b667c9698863235210452b47
/src/s2/s2furthest_edge_query.h
30615b5d6915064c9d1a7aaefad32b8317a501c1
[ "Apache-2.0" ]
permissive
TheMBTH/s2geometry
ae1abb681321dabdf74d08730451b630caf4c188
efb4eb8d0cbe8ddcf68a8600ab217129a2d94283
refs/heads/master
2023-03-09T16:02:34.307849
2023-01-12T05:48:11
2023-01-12T05:48:11
182,154,924
0
0
null
2019-04-18T20:43:55
2019-04-18T20:43:55
null
UTF-8
C++
false
false
18,573
h
// Copyright Google Inc. 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 S2_S2FURTHEST_EDGE_QUERY_H_ #define S2_S2FURTHEST_EDGE_QUERY_H_ #include <memory> #include <queue> #include <type_traits> #include <vector> #include "s2/base/integral_types.h" #include "s2/base/logging.h" #include "absl/base/macros.h" #include "absl/container/inlined_vector.h" #include "s2/_fp_contract_off.h" #include "s2/s1angle.h" #include "s2/s1chord_angle.h" #include "s2/s2cell.h" #include "s2/s2cell_id.h" #include "s2/s2closest_edge_query_base.h" #include "s2/s2distance_target.h" #include "s2/s2edge_distances.h" #include "s2/s2max_distance_targets.h" #include "s2/s2point.h" #include "s2/s2shape.h" #include "s2/s2shape_index.h" // S2FurthestEdgeQuery is a helper class for searching within an S2ShapeIndex // for the furthest edge(s) to a given query point, edge, S2Cell, or geometry // collection. The furthest edge is defined as the one which maximizes the // distance from any point on that edge to any point on the target geometry. // As an example, given a set of polylines, the following code efficiently // finds the furthest 5 edges to a query point: // // void Test(const vector<S2Polyline*>& polylines, const S2Point& point) { // MutableS2ShapeIndex index; // for (S2Polyline* polyline : polylines) { // index.Add(new S2Polyline::Shape(polyline)); // } // S2FurthestEdgeQuery query(&index); // query.mutable_options()->set_max_results(5); // S2FurthestEdgeQuery::PointTarget target(point); // for (const auto& result : query.FindFurthestEdges(&target)) { // // The Result object contains the following accessors: // // distance() is the distance to the edge. // // shape_id() identifies the S2Shape containing the edge. // // edge_id() identifies the edge with the given shape. // // is_interior() indicates that the result is an interior point. // // // // The following convenience method may also be useful: // // query.GetEdge(result) returns the endpoints of the edge. // int polyline_index = result.shape_id(); // int edge_index = result.edge_id(); // S1ChordAngle distance = result.distance(); // Can convert to S1Angle. // S2Shape::Edge edge = query.GetEdge(result); // } // } // // You can find either the k furthest edges, or all edges no closer than a // given radius, or both (i.e., the k furthest edges no closer than a given // minimum radius). // E.g. to find all the edges further than 5 kilometers, call // // query.mutable_options()->set_min_distance( // S2Earth::ToAngle(util::units::Kilometers(5))); // // By default *all* edges are returned, so you should always specify either // max_results() or min_distance() or both. Setting min distance may not be // very restrictive, so strongly consider using max_results(). There is also a // FindFurthestEdge() convenience method that returns only the single furthest // edge. // // Note that by default, distances are measured to the boundary and interior // of polygons. To change this behavior, call set_include_interiors(false). // // If you only need to test whether the distance is above or below a given // threshold (e.g., 10 km), you can use the IsDistanceGreater() method. This // is much faster than actually calculating the distance with // FindFurthestEdge(), since the implementation can stop as soon as it can // prove that the maximum distance is either above or below the threshold. // // To find the furthest edges to a query edge rather than a point, use: // // S2FurthestEdgeQuery::EdgeTarget target(v0, v1); // query.FindFurthestEdges(&target); // // Similarly you can find the furthest edges to an S2Cell by using an // S2FurthestEdgeQuery::CellTarget, and you can find the furthest edges to an // arbitrary collection of points, polylines, and polygons by using an // S2FurthestEdgeQuery::ShapeIndexTarget. // // The implementation is designed to be fast for both simple and complex // geometric objects. class S2FurthestEdgeQuery { public: // See S2FurthestEdgeQueryBase for full documentation. // S2MaxDistance is a thin wrapper around S1ChordAngle that implements the // Distance concept required by S2ClosestEdgeQueryBase. It inverts the sense // of some methods to enable the closest edge query to return furthest // edges. // // Distance and Base are made private to prevent leakage outside of this // class. The private and public sections are interleaved since the public // options class needs the private Base class. private: using Distance = S2MaxDistance; using Base = S2ClosestEdgeQueryBase<Distance>; public: // Options that control the set of edges returned. Note that by default // *all* edges are returned, so you will always want to set either the // max_results() option or the min_distance() option (or both). class Options : public Base::Options { public: // See S2ClosestEdgeQueryBase::Options for the full set of options. Options(); // The following methods are like the corresponding max_distance() methods // in S2ClosestEdgeQuery, except that they specify the minimum distance to // the target. S1ChordAngle min_distance() const; void set_min_distance(S1ChordAngle min_distance); void set_inclusive_min_distance(S1ChordAngle min_distance); void set_conservative_min_distance(S1ChordAngle min_distance); void set_min_distance(S1Angle min_distance); void set_inclusive_min_distance(S1Angle min_distance); void set_conservative_min_distance(S1Angle min_distance); // Versions of set_max_error() that accept S1ChordAngle / S1Angle. // (See S2ClosestEdgeQueryBaseOptions for details.) S1ChordAngle max_error() const; void set_max_error(S1ChordAngle max_error); void set_max_error(S1Angle max_error); // Inherited options (see s2closestedgequerybase.h for details): using Base::Options::set_max_results; using Base::Options::set_include_interiors; using Base::Options::set_use_brute_force; private: // The S2MaxDistance versions of these methods are not intended for // public use. using Base::Options::set_max_distance; using Base::Options::set_max_error; using Base::Options::max_distance; using Base::Options::max_error; }; // "Target" represents the geometry to which the distance is measured. // There are subtypes for measuring the distance to a point, an edge, an // S2Cell, or an S2ShapeIndex (an arbitrary collection of geometry). Note // that S2DistanceTarget<Distance> is equivalent to S2MaxDistanceTarget in // s2max_distance_targets, which the following subtypes // (e.g. S2MaxDistancePointTarget) extend. using Target = S2DistanceTarget<Distance>; // Target subtype that computes the furthest distance to a point. class PointTarget final : public S2MaxDistancePointTarget { public: explicit PointTarget(const S2Point& point); int max_brute_force_index_size() const override; }; // Target subtype that computes the furthest distance to an edge. class EdgeTarget final : public S2MaxDistanceEdgeTarget { public: explicit EdgeTarget(const S2Point& a, const S2Point& b); int max_brute_force_index_size() const override; }; // Target subtype that computes the furthest distance to an S2Cell // (including the interior of the cell). class CellTarget final : public S2MaxDistanceCellTarget { public: explicit CellTarget(const S2Cell& cell); int max_brute_force_index_size() const override; }; // Target subtype that computes the furthest distance to an S2ShapeIndex // (an arbitrary collection of points, polylines, and/or polygons). // // By default, distances are measured to the boundary and interior of // polygons in the S2ShapeIndex rather than to polygon boundaries only. // If you wish to change this behavior, you may call // // target.set_include_interiors(false); // // (see S2MaxDistanceShapeIndexTarget for details). class ShapeIndexTarget final : public S2MaxDistanceShapeIndexTarget { public: explicit ShapeIndexTarget(const S2ShapeIndex* index); int max_brute_force_index_size() const override; }; // Each "Result" object represents a furthest edge. We choose to pass back // this result type, which has an S1ChordAngle as its distance, rather than // the Base::Result returned from the query which uses S2MaxDistance. Note // the following special cases: // // - (shape_id() >= 0) && (edge_id() < 0) represents the interior of a shape. // Such results may be returned when options.include_interiors() is true. // Such results can be identified using the is_interior() method. // // - (shape_id() < 0) && (edge_id() < 0) is returned by FindFurthestEdge() // to indicate that no edge satisfies the given query options. Such // results can be identified using is_empty() method. class Result { public: // The default constructor, which yields an invalid result. Result() : Result(S1ChordAngle::Negative(), -1, -1) {} // Construct a Result from a Base::Result. explicit Result(const Base::Result& base) : Result(S1ChordAngle(base.distance()), base.shape_id(), base.edge_id()) {} // Constructs a Result object for the given edge with the given distance. Result(S1ChordAngle distance, int32 _shape_id, int32 _edge_id) : distance_(distance), shape_id_(_shape_id), edge_id_(_edge_id) {} // The distance from the target to this point. S1ChordAngle distance() const { return distance_; } // The edge identifiers. int32 shape_id() const { return shape_id_; } int32 edge_id() const { return edge_id_; } // Returns true if this Result object represents the interior of a shape. // (Such results may be returned when options.include_interiors() is true.) bool is_interior() const { return shape_id_ >= 0 && edge_id_ < 0; } // Returns true if this Result object indicates that no edge satisfies the // given query options. (This result is only returned in one special // case, namely when FindFurthestEdge() does not find any suitable edges. // It is never returned by methods that return a vector of results.) bool is_empty() const { return shape_id_ < 0; } // Returns true if two Result objects are identical. friend bool operator==(const Result& x, const Result& y) { return (x.distance_ == y.distance_ && x.shape_id_ == y.shape_id_ && x.edge_id_ == y.edge_id_); } // Compares edges first by distance, then by (shape_id, edge_id). friend bool operator<(const Result& x, const Result& y) { if (x.distance_ < y.distance_) return true; if (y.distance_ < x.distance_) return false; if (x.shape_id_ < y.shape_id_) return true; if (y.shape_id_ < x.shape_id_) return false; return x.edge_id_ < y.edge_id_; } private: S1ChordAngle distance_; int32 shape_id_; // Identifies an indexed shape. int32 edge_id_; // Identifies an edge within the shape. }; // Convenience constructor that calls Init(). Options may be specified here // or changed at any time using the mutable_options() accessor method. explicit S2FurthestEdgeQuery(const S2ShapeIndex* index, const Options& options = Options()); // Default constructor; requires Init() to be called. S2FurthestEdgeQuery(); ~S2FurthestEdgeQuery(); S2FurthestEdgeQuery(const S2FurthestEdgeQuery&) = delete; void operator=(const S2FurthestEdgeQuery&) = delete; // Initializes the query. Options may be specified here or changed at any // time using the mutable_options() accessor method. // // REQUIRES: "index" must persist for the lifetime of this object. // REQUIRES: ReInit() must be called if "index" is modified. void Init(const S2ShapeIndex* index, const Options& options = Options()); // Reinitializes the query. This method must be called whenever the // underlying S2ShapeIndex is modified. void ReInit(); // Returns a reference to the underlying S2ShapeIndex. const S2ShapeIndex& index() const; // Returns the query options. Options can be modified between queries. const Options& options() const; Options* mutable_options(); // Returns the furthest edges to the given target that satisfy the given // options. This method may be called multiple times. // // Note that if options().include_interiors() is true, the result vector may // include some entries with edge_id == -1. This indicates that the // furthest distance is attained at a point in the interior of the indexed // polygon with the given shape_id. Such results may be identifed by // calling Result::is_interior(). std::vector<Result> FindFurthestEdges(Target* target); // This version can be more efficient when this method is called many times, // since it does not require allocating a new vector on each call. void FindFurthestEdges(Target* target, std::vector<Result>* results); //////////////////////// Convenience Methods //////////////////////// // Returns the furthest edge to the target. If no edge satisfies the search // criteria, then the result object's is_empty() method will be true. // // Note that if options.include_interiors() is true, Result::is_interior() // should be called to check whether the result represents an interior point // (in which case edge_id() == -1). Result FindFurthestEdge(Target* target); // Returns the maximum distance to the target. If the index or target is // empty, returns S1ChordAngle::Negative(). // // Use IsDistanceGreater() if you only want to compare the distance against a // threshold value, since it is often much faster. S1ChordAngle GetDistance(Target* target); // Returns true if the distance to "target" is greater than "limit". // // This method is usually much faster than GetDistance(), since it is much // less work to determine whether the maximum distance is above or below a // threshold than it is to calculate the actual maximum distance. bool IsDistanceGreater(Target* target, S1ChordAngle limit); // Like IsDistanceGreater(), but also returns true if the distance to // "target" is exactly equal to "limit". bool IsDistanceGreaterOrEqual(Target* target, S1ChordAngle limit); // Like IsDistanceGreaterOrEqual(), except that "limit" is decreased by the // maximum error in the distance calculation. This ensures that this // function returns true whenever the true, exact distance is greater than // or equal to "limit". bool IsConservativeDistanceGreaterOrEqual(Target* target, S1ChordAngle limit); // Returns the endpoints of the given result edge. // REQUIRES: !result.is_interior() S2Shape::Edge GetEdge(const Result& result) const; private: Options options_; Base base_; }; ////////////////// Implementation details follow //////////////////// inline S2FurthestEdgeQuery::Options::Options() = default; inline S1ChordAngle S2FurthestEdgeQuery::Options::min_distance() const { return S1ChordAngle(max_distance()); } inline void S2FurthestEdgeQuery::Options::set_min_distance( S1ChordAngle min_distance) { Base::Options::set_max_distance(Distance(min_distance)); } inline void S2FurthestEdgeQuery::Options::set_min_distance( S1Angle min_distance) { Base::Options::set_max_distance(Distance(S1ChordAngle(min_distance))); } inline void S2FurthestEdgeQuery::Options::set_inclusive_min_distance( S1ChordAngle min_distance) { set_min_distance(min_distance.Predecessor()); } inline void S2FurthestEdgeQuery::Options::set_inclusive_min_distance( S1Angle min_distance) { set_inclusive_min_distance(S1ChordAngle(min_distance)); } inline S1ChordAngle S2FurthestEdgeQuery::Options::max_error() const { return S1ChordAngle(Base::Options::max_error()); } inline void S2FurthestEdgeQuery::Options::set_max_error( S1ChordAngle max_error) { Base::Options::set_max_error(max_error); } inline void S2FurthestEdgeQuery::Options::set_max_error(S1Angle max_error) { Base::Options::set_max_error(S1ChordAngle(max_error)); } inline S2FurthestEdgeQuery::PointTarget::PointTarget(const S2Point& point) : S2MaxDistancePointTarget(point) { } inline S2FurthestEdgeQuery::EdgeTarget::EdgeTarget(const S2Point& a, const S2Point& b) : S2MaxDistanceEdgeTarget(a, b) { } inline S2FurthestEdgeQuery::CellTarget::CellTarget(const S2Cell& cell) : S2MaxDistanceCellTarget(cell) { } inline S2FurthestEdgeQuery::ShapeIndexTarget::ShapeIndexTarget( const S2ShapeIndex* index) : S2MaxDistanceShapeIndexTarget(index) { } inline S2FurthestEdgeQuery::S2FurthestEdgeQuery(const S2ShapeIndex* index, const Options& options) { Init(index, options); } inline void S2FurthestEdgeQuery::Init(const S2ShapeIndex* index, const Options& options) { options_ = options; base_.Init(index); } inline void S2FurthestEdgeQuery::ReInit() { base_.ReInit(); } inline const S2ShapeIndex& S2FurthestEdgeQuery::index() const { return base_.index(); } inline const S2FurthestEdgeQuery::Options& S2FurthestEdgeQuery::options() const { return options_; } inline S2FurthestEdgeQuery::Options* S2FurthestEdgeQuery::mutable_options() { return &options_; } inline std::vector<S2FurthestEdgeQuery::Result> S2FurthestEdgeQuery::FindFurthestEdges(Target* target) { std::vector<S2FurthestEdgeQuery::Result> results; FindFurthestEdges(target, &results); return results; } inline S1ChordAngle S2FurthestEdgeQuery::GetDistance(Target* target) { return FindFurthestEdge(target).distance(); } inline S2Shape::Edge S2FurthestEdgeQuery::GetEdge(const Result& result) const { return index().shape(result.shape_id())->edge(result.edge_id()); } #endif // S2_S2FURTHEST_EDGE_QUERY_H_
[ "jmr@google.com" ]
jmr@google.com
5b8c686306c34db61be1007b5159b7340904aa68
63cc8d2f24108115622939ba206703d12cfb9a97
/WinAPI-슈팅 게임/Bullet.cpp
337427472e3e72933cc9da6bed126a8e754bd245
[]
no_license
kthss01/SGA_Programming_Homework
936bc34bd181b88348c697a817f91260480af5bf
a86b43791e7eb96638f36a984eb493a914240fa5
refs/heads/master
2018-08-25T06:37:38.186468
2018-06-03T05:00:38
2018-06-03T05:00:38
118,196,014
3
8
null
null
null
null
UTF-8
C++
false
false
4,027
cpp
#include "stdafx.h" #include "Bullet.h" Bullet::Bullet() { } Bullet::~Bullet() { } HRESULT Bullet::Init(int bulletMax) { bulletImage = new Image; bulletImage ->Init("images/bullet_blue_10x1.bmp", 25 * 10, 25, 10, 1, true, RGB(255, 0, 255)); for (int i = 0; i < bulletMax; i++) { tagBullet bullet; ZeroMemory(&bullet, sizeof(tagBullet)); //bullet.bulletImage = new Image; //bullet.bulletImage // ->Init("images/bullet_blue_10x1.bmp", 25 * 10, // 25, 10, 1, true, RGB(255, 0, 255)); bullet.speed = 2.5f; bullet.fire = false; _vBullet.push_back(bullet); } return S_OK; } void Bullet::Release() { //for (_viBullet = _vBullet.begin(); // _viBullet != _vBullet.end(); ++_viBullet) { // SAFE_DELETE(_viBullet->bulletImage); //} SAFE_DELETE(bulletImage); } void Bullet::Update() { Move(); for (_viBullet = _vBullet.begin(); _viBullet != _vBullet.end(); ++_viBullet) { if (!_viBullet->fire) continue; if(_viBullet->moveFrame < 10) _viBullet->moveFrame += 0.1f; } } void Bullet::Render() { for (tagBullet iter : _vBullet) { if (!iter.fire) continue; bulletImage->FrameRender(GetMemDC(), iter.rc.left, iter.rc.top, (int)iter.moveFrame, 0); } } void Bullet::Fire(float x, float y, float destX, float destY) { _viBullet = _vBullet.begin(); for (; _viBullet != _vBullet.end(); ++_viBullet) { if (_viBullet->fire) continue; _viBullet->fire = true; _viBullet->moveFrame = 0; _viBullet->x = x; _viBullet->y = y; _viBullet->angle = GetAngle(x, y, destX, destY); _viBullet->rc = RectMakeCenter( _viBullet->x, _viBullet->y, bulletImage->GetFrameWidth(), bulletImage->GetFrameHeight()); break; } } void Bullet::Move() { _viBullet = _vBullet.begin(); for (; _viBullet != _vBullet.end(); ++_viBullet) { if (!_viBullet->fire) continue; _viBullet->x += cosf(_viBullet->angle) * _viBullet->speed; _viBullet->y -= sinf(_viBullet->angle) * _viBullet->speed; _viBullet->rc = RectMakeCenter( _viBullet->x, _viBullet->y, bulletImage->GetFrameWidth(), bulletImage->GetFrameHeight()); if (_viBullet->rc.top >= WINSIZEY) _viBullet->fire = false; } } /******************************************************/ HRESULT Missile::Init(int bulletMax, float range) { _range = range; _bulletImage = new Image; _bulletImage ->Init("images/missile.bmp", 26, 124, true, RGB(255, 0, 255)); for (int i = 0; i < bulletMax; i++) { tagBullet bullet; ZeroMemory(&bullet, sizeof(tagBullet)); bullet.speed = 2.5f; bullet.fire = false; bullet.moveFrame = 0; _vBullet.push_back(bullet); } return S_OK; } void Missile::Release() { //for (_viBullet = _vBullet.begin(); // _viBullet != _vBullet.end(); ++_viBullet) { // SAFE_DELETE(_viBullet->bulletImage); //} SAFE_DELETE(_bulletImage); } void Missile::Update() { Move(); } void Missile::Render() { for (tagBullet iter : _vBullet) { if (!iter.fire) continue; _bulletImage->Render(GetMemDC(), iter.rc.left, iter.rc.top); } } void Missile::Fire(float x, float y) { _viBullet = _vBullet.begin(); for (; _viBullet != _vBullet.end(); ++_viBullet) { if (_viBullet->fire) continue; _viBullet->fire = true; _viBullet->x = _viBullet->fireX = x; _viBullet->y = _viBullet->fireY = y; _viBullet->rc = RectMakeCenter( _viBullet->x, _viBullet->y, _bulletImage->GetWidth(), _bulletImage->GetHeight()); break; } } void Missile::Move() { _viBullet = _vBullet.begin(); for (; _viBullet != _vBullet.end(); ++_viBullet) { if (!_viBullet->fire) continue; _viBullet->y -= _viBullet->speed; _viBullet->rc = RectMakeCenter( _viBullet->x, _viBullet->y, _bulletImage->GetWidth(), _bulletImage->GetHeight()); if (_range < GetDistance( _viBullet->fireX, _viBullet->fireY, _viBullet->x, _viBullet->y)) { _viBullet->fire = false; } } } void Missile::Bomb() { _viBullet = _vBullet.begin(); for (; _viBullet != _vBullet.end(); ++_viBullet) { if (!_viBullet->fire) continue; _viBullet->fire = false; } }
[ "kthss01@naver.com" ]
kthss01@naver.com
490429b5c9c9ae764cc8e739148833220ed0f3b7
1ae40287c5705f341886bbb5cc9e9e9cfba073f7
/Osmium/SDK/FN_HeroSquadBonusesDetailWidget_classes.hpp
8a26cd72791cb7de37dd58d2d60e9ac7dd253db7
[]
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
2,313
hpp
#pragma once // Fortnite (4.5-CL-4159770) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // WidgetBlueprintGeneratedClass HeroSquadBonusesDetailWidget.HeroSquadBonusesDetailWidget_C // 0x0018 (0x0270 - 0x0258) class UHeroSquadBonusesDetailWidget_C : public UFortItemDetailElementWidget { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x0258(0x0008) (Transient, DuplicateTransient) class UFortHeroSupportPerkWidget_C* SupportPerkWidget; // 0x0260(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UFortHeroSupportPerkWidget_C* TacticalPerkWidget; // 0x0268(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) static UClass* StaticClass() { static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass HeroSquadBonusesDetailWidget.HeroSquadBonusesDetailWidget_C"); return ptr; } void UpdatePerkWidgets(); void HandlePostDifferentItemToDetailSet(); void ExecuteUbergraph_HeroSquadBonusesDetailWidget(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "kareemolim@gmail.com" ]
kareemolim@gmail.com
246f46bd7b61f8b7234956793632a1ca15d03f35
9ae5edf1371569f182ba3dd87bd2414ec98f523c
/cracking_coding_interview/balanced_tree.cpp
adbc58b0316ffa6e80edfa90c4cd9c62b08dc219
[]
no_license
Manan007224/street-coding
19000ed422563ca776053ec33adcd4e0b2734a8d
d3337805e0406684bcb3392898df163d315db624
refs/heads/master
2020-03-08T02:01:33.063948
2019-09-16T04:33:22
2019-09-16T04:33:22
127,847,522
1
0
null
2019-07-06T13:06:05
2018-04-03T03:47:59
C++
UTF-8
C++
false
false
114
cpp
#include <iostream> using namespace std; struct Node{ int val; Node* l; Node* r; } int main(){ return 0; }
[ "maniyarmanan1996@gmail.com" ]
maniyarmanan1996@gmail.com
ce7ef32c791c2dbab4ed91db9cb41c663d5cf53c
d2249116413e870d8bf6cd133ae135bc52021208
/MFC CodeGuru/misc/writeavi/WRITEAVI.CPP
aea2d87d7185838b29c71c914c017ca60071abfb
[]
no_license
Unknow-man/mfc-4
ecbdd79cc1836767ab4b4ca72734bc4fe9f5a0b5
b58abf9eb4c6d90ef01b9f1203b174471293dfba
refs/heads/master
2023-02-17T18:22:09.276673
2021-01-20T07:46:14
2021-01-20T07:46:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,526
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) 1992 - 1996 Microsoft Corporation. All Rights Reserved. * **************************************************************************/ /**************************************************************************** * * WRITEAVI.C * * Creates the file OUTPUT.AVI, an AVI file consisting of a rotating clock * face. This program demonstrates using the functions in AVIFILE.DLL * to make writing AVI files simple. * * This is a stripped-down example; a real application would have a user * interface and check for errors. * ***************************************************************************/ #include "stdafx.h" #include <windowsx.h> #include <memory.h> #include <mmsystem.h> #include <vfw.h> #include "writeavi.h" static HANDLE MakeDib( HBITMAP hbitmap, UINT bits ) { HANDLE hdib ; HDC hdc ; BITMAP bitmap ; UINT wLineLen ; DWORD dwSize ; DWORD wColSize ; LPBITMAPINFOHEADER lpbi ; LPBYTE lpBits ; GetObject(hbitmap,sizeof(BITMAP),&bitmap) ; // // DWORD align the width of the DIB // Figure out the size of the colour table // Calculate the size of the DIB // wLineLen = (bitmap.bmWidth*bits+31)/32 * 4; wColSize = sizeof(RGBQUAD)*((bits <= 8) ? 1<<bits : 0); dwSize = sizeof(BITMAPINFOHEADER) + wColSize + (DWORD)(UINT)wLineLen*(DWORD)(UINT)bitmap.bmHeight; // // Allocate room for a DIB and set the LPBI fields // hdib = GlobalAlloc(GHND,dwSize); if (!hdib) return hdib ; lpbi = (LPBITMAPINFOHEADER)GlobalLock(hdib) ; lpbi->biSize = sizeof(BITMAPINFOHEADER) ; lpbi->biWidth = bitmap.bmWidth ; lpbi->biHeight = bitmap.bmHeight ; lpbi->biPlanes = 1 ; lpbi->biBitCount = (WORD) bits ; lpbi->biCompression = BI_RGB ; lpbi->biSizeImage = dwSize - sizeof(BITMAPINFOHEADER) - wColSize ; lpbi->biXPelsPerMeter = 0 ; lpbi->biYPelsPerMeter = 0 ; lpbi->biClrUsed = (bits <= 8) ? 1<<bits : 0; lpbi->biClrImportant = 0 ; // // Get the bits from the bitmap and stuff them after the LPBI // lpBits = (LPBYTE)(lpbi+1)+wColSize ; hdc = CreateCompatibleDC(NULL) ; GetDIBits(hdc,hbitmap,0,bitmap.bmHeight,lpBits,(LPBITMAPINFO)lpbi, DIB_RGB_COLORS); // Fix this if GetDIBits messed it up.... lpbi->biClrUsed = (bits <= 8) ? 1<<bits : 0; DeleteDC(hdc) ; GlobalUnlock(hdib); return hdib ; } CAVIFile::CAVIFile(LPCTSTR lpszFileName, int xdim, int ydim) : FName(lpszFileName), xDim(xdim), yDim(ydim), bOK(true), nFrames(0) { pfile = NULL; ps = NULL; psCompressed = NULL; psText = NULL; aopts[0] = &opts; WORD wVer = HIWORD(VideoForWindowsVersion()); if (wVer < 0x010A) { // oops, we are too old, blow out of here bOK = false; } else { AVIFileInit(); } } CAVIFile::~CAVIFile() { if (ps) AVIStreamClose(ps); if (psCompressed) AVIStreamClose(psCompressed); if (psText) AVIStreamClose(psText); if (pfile) AVIFileClose(pfile); WORD wVer = HIWORD(VideoForWindowsVersion()); if (wVer >= 0x010A) { AVIFileExit(); } } bool CAVIFile::AddFrame(CBitmap& bmp) { HRESULT hr; char szMessage[BUFSIZE]; if (!bOK) return false; LPBITMAPINFOHEADER alpbi = (LPBITMAPINFOHEADER)GlobalLock(MakeDib(bmp, 8)); if (alpbi == NULL) return false; if (xDim>=0 && xDim != alpbi->biWidth) { GlobalFreePtr(alpbi); return false; } if (yDim>=0 && yDim != alpbi->biHeight) { GlobalFreePtr(alpbi); return false; } xDim = alpbi->biWidth; yDim = alpbi->biHeight; if (nFrames == 0) { hr = AVIFileOpen(&pfile, // returned file pointer FName, // file name OF_WRITE | OF_CREATE, // mode to open file with NULL); // use handler determined // from file extension.... if (hr != AVIERR_OK) { GlobalFreePtr(alpbi); bOK = false; return false; } _fmemset(&strhdr, 0, sizeof(strhdr)); strhdr.fccType = streamtypeVIDEO;// stream type strhdr.fccHandler = 0; strhdr.dwScale = 1; strhdr.dwRate = 15; // 15 fps strhdr.dwSuggestedBufferSize = alpbi->biSizeImage; SetRect(&strhdr.rcFrame, 0, 0, // rectangle for stream (int) alpbi->biWidth, (int) alpbi->biHeight); // And create the stream; hr = AVIFileCreateStream(pfile, // file pointer &ps, // returned stream pointer &strhdr); // stream header if (hr != AVIERR_OK) { GlobalFreePtr(alpbi); bOK = false; return false; } _fmemset(&opts, 0, sizeof(opts)); if (!AVISaveOptions(NULL, 0, 1, &ps, (LPAVICOMPRESSOPTIONS FAR *) &aopts)) { GlobalFreePtr(alpbi); bOK = false; return false; } hr = AVIMakeCompressedStream(&psCompressed, ps, &opts, NULL); if (hr != AVIERR_OK) { GlobalFreePtr(alpbi); bOK = false; return false; } hr = AVIStreamSetFormat(psCompressed, 0, alpbi, // stream format alpbi->biSize + // format size alpbi->biClrUsed * sizeof(RGBQUAD)); if (hr != AVIERR_OK) { GlobalFreePtr(alpbi); bOK = false; return false; } // Fill in the stream header for the text stream.... // The text stream is in 60ths of a second.... /* _fmemset(&strhdr, 0, sizeof(strhdr)); strhdr.fccType = streamtypeTEXT; strhdr.fccHandler = mmioFOURCC('D', 'R', 'A', 'W'); strhdr.dwScale = 1; strhdr.dwRate = 60; strhdr.dwSuggestedBufferSize = sizeof(szText); SetRect(&strhdr.rcFrame, 0, (int) alpbi->biHeight, (int) alpbi->biWidth, (int) alpbi->biHeight + TEXT_HEIGHT); // ....and create the stream. hr = AVIFileCreateStream(pfile, &psText, &strhdr); if (hr != AVIERR_OK) { GlobalFreePtr(alpbi); bOK = false; return false; } dwTextFormat = sizeof(dwTextFormat); hr = AVIStreamSetFormat(psText, 0, &dwTextFormat, sizeof(dwTextFormat)); if (hr != AVIERR_OK) { GlobalFreePtr(alpbi); bOK = false; return false; } */ } // Jetzt eigentliches Schreiben hr = AVIStreamWrite(psCompressed, // stream pointer nFrames * 10, // time of this frame 1, // number to write (LPBYTE) alpbi + // pointer to data alpbi->biSize + alpbi->biClrUsed * sizeof(RGBQUAD), alpbi->biSizeImage, // size of this frame AVIIF_KEYFRAME, // flags.... NULL, NULL); if (hr != AVIERR_OK) { GlobalFreePtr(alpbi); bOK = false; return false; } // Make some text to put in the file ... //LoadString(hInstance, IDS_TEXTFORMAT, szMessage, BUFSIZE ); /* strcpy(szMessage, "This is frame #%d"); int iLen = wsprintf(szText, szMessage, (int)(nFrames + 1)); // ... and write it as well. hr = AVIStreamWrite(psText, nFrames * 40, 1, szText, iLen + 1, AVIIF_KEYFRAME, NULL, NULL); if (hr != AVIERR_OK) { GlobalFreePtr(alpbi); bOK = false; return false; } */ GlobalFreePtr(alpbi); nFrames++; return true; }
[ "chenchao0632@163.com" ]
chenchao0632@163.com
c6b4838da83e89e6884debeca374a70d36bf1ea8
10ee2f7993bee6bc055b4fb88975997fa4ae9266
/iPics.h
0e96532016b086ccdb9b151662ec9d02dac26b5b
[]
no_license
sbrotee63/The-Lone-Ranger-Lab-Project
bcf19461953100027883133d1e387c6c3d4738c9
f54d89f63def81ba52bf2fce76558b8b8c8e4f22
refs/heads/master
2020-04-06T10:46:25.898006
2018-11-13T14:41:31
2018-11-13T14:41:31
157,391,273
0
1
null
null
null
null
UTF-8
C++
false
false
575
h
#include "stdio.h" using namespace std; #define endl "\n" struct pic { int x,y; int pxl[800][500]; }; struct ENEMY { struct pic die, arrowLoad, arrowUnload, knife, stand; int life, arrow; double x, y; }; struct BOSS { struct pic bossArrowLoad, bossArrowUnload, bossKnife, bossShield, bossStand; int life, arrow; double x, y; }; struct HERO { struct pic stand, move[4], crouch, arrowLoad, arrowUnload, die; int life, arrow; double x, y; }; struct ARROW { struct pic img; double x, y; }; struct SHIELD { struct pic heroShield, enemyShield; double x, y; };
[ "44999838+sbrotee63@users.noreply.github.com" ]
44999838+sbrotee63@users.noreply.github.com
8cca07674ad20cd0f0b57b58309ef31e34faba2c
ae04470c3c266513002c2c5c9ac9b034614930cb
/27XX/zoj.2748.src.1.cpp
430c25e89b8d90bbd619d991344a2471c01389c0
[]
no_license
fish-ball/acm.zju.edu.cn
281315b9aab0517801ca780972a327642867eb7d
984d48539607ed082749204a81d4aecac5bdac53
refs/heads/master
2021-03-12T19:15:13.640962
2018-11-16T10:34:34
2018-11-16T10:34:34
14,883,882
1
1
null
null
null
null
GB18030
C++
false
false
758
cpp
// 2016200 2009-10-17 11:37:51 Accepted 2748 C++ 0 184 呆滞的慢板 // 足球人墙,很无聊的几何题,注意墙一定是直线,不能是弧线就是了。 #include <iostream> #include <cmath> using namespace std; int main() { double a, W, x, y, D, A; const double PI = acos(-1.0); while(cin >> a >> W >> x >> y >> D >> A) { double sa = a + a; double sb = sqrt((x-a)*(x-a) + y*y); double sc = sqrt((x+a)*(x+a) + y*y); double agl = acos(-(sa*sa - sc*sc - sb*sb) / 2.0 / sb / sc); agl -= A * PI / 180; double ans = tan(agl / 2) * D * 2 / W; if(ans <= 0) puts("0"); else if(ans - int(ans) == 0) cout << ans << endl; else cout << int(ans) + 1 << endl; } }
[ "alfred.h@163.com" ]
alfred.h@163.com
03a582b4d90b4d47b60ed776b79dfb0dc18b6ed6
2a68bf731b4a7771bc0be45a5ba667be259662c6
/LinkListImpl/LinkListImpl/main.cpp
91294e554149acc989f1b9d8b9cb8e9be0099a60
[]
no_license
loypt/Data-Structure-wtu
0e6ee509d1cbd958db41af99beb5e72c020d4985
29585183cfcca2faaa4a68642dc8dbe22dde650e
refs/heads/main
2023-06-01T22:03:24.519554
2021-06-18T12:39:11
2021-06-18T12:39:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,311
cpp
// // main.cpp // LinkListImpl // // Created by Loyio Hex on 3/26/21. // #include <stdio.h> #include <stdlib.h> #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 typedef int Status; typedef int LElemType_L; typedef struct LNode { LElemType_L data; struct LNode* next; }LNode; void PrintElem(LElemType_L e) { printf("%d ", e); } Status CmpGreater(LElemType_L data, LElemType_L e) { return data > e ? TRUE : FALSE; } typedef LNode* LinkList; Status InitList_L(LinkList *L); Status ClearList_L(LinkList L); void DestroyList_L(LinkList *L); Status ListEmpty_L(LinkList L); int ListLength_L(LinkList L); Status GetElem_L(LinkList L, int i, LElemType_L *e); int LocateElem_L(LinkList L, LElemType_L e, Status(Compare)(LElemType_L, LElemType_L)); Status PriorElem_L(LinkList L, LElemType_L cur_e, LElemType_L *pre_e); Status NextElem_L(LinkList L, LElemType_L cur_e, LElemType_L *next_e); Status ListInsert_L(LinkList L, int i, LElemType_L e); Status ListDelete_L(LinkList L, int i, LElemType_L *e); Status ListTraverse_L(LinkList L, void(Visit)(LElemType_L)); Status CreateList_HL(FILE *fp, LinkList *L, int n); Status CreateList_TL(FILE *fp, LinkList *L, int n); // Question 5 void MergeList_L(LinkList La, LinkList *Lb, LinkList *Lc); // Question 8 void ReverseList_L(LinkList L); // Question 14 bool SortList_L(LinkList L); LinkList DisCreat_1(LinkList &A); int main(int argc, const char * argv[]) { LinkList L1; int i; LElemType_L e; // Question 1 InitList_L(&L1); int a[] = {3, 5, 6, 8, 11, 15, 23, 16}; for(i=0; i<8; i++){ printf("在 L1 第 %d 个位置插入 \"%d\" \n", i+1, a[i]); ListInsert_L(L1, i+1, a[i]); } printf("\n\n"); // new test LNode *B = DisCreat_1(L1); printf("A: "); ListTraverse_L(L1, PrintElem); printf("\n\n"); printf("B: "); ListTraverse_L(B, PrintElem); printf("\n\n"); //Question 2 ListTraverse_L(L1, PrintElem); printf("\n\n"); // Question 3 LinkList L2; InitList_L(&L2); int b[] = {2, 6, 8, 9, 11, 15, 20}; for(i=0; i<7; i++){ printf("在 L2 第 %d 个位置插入 \"%d\" \n", i+1, b[i]); ListInsert_L(L2, i+1, b[i]); } printf("\n\n"); // Question 4 ListTraverse_L(L2, PrintElem); printf("\n\n"); // Question 6 LinkList L3; InitList_L(&L3); MergeList_L(L1, &L2, &L3); printf("合并La和Lb为Lc = "); // Question 7 ListTraverse_L(L3, PrintElem); printf("\n\n"); // Question 9 ReverseList_L(L3); printf("反转链表L3\n"); // Questoin 10 ListTraverse_L(L3, PrintElem); printf("\n\n"); // Question 11 DestroyList_L(&L3); printf("销毁 L3 后:"); L3 ? printf(" L3 存在!\n") : printf(" L3 不存在!!\n"); printf("\n\n"); // Question 12 LinkList L4; InitList_L(&L4); int c[] = {8, 6, 15, 9, 20, 15, 11}; for(i=0; i<7; i++){ printf("在 L4 第 %d 个位置插入 \"%d\" \n", i+1, c[i]); ListInsert_L(L4, i+1, c[i]); } printf("\n\n"); // Question 13 ListTraverse_L(L4, PrintElem); printf("\n\n"); // Question 15 printf("L4进行排序\n"); SortList_L(L4); printf("\n\n"); // Question 16 printf("遍历L4\n"); ListTraverse_L(L4, PrintElem); printf("\n\n"); // Question 17 DestroyList_L(&L4); printf("销毁 L4 后:"); L4 ? printf(" L4 存在!\n") : printf(" L4 不存在!!\n"); printf("\n\n"); return 0; } Status InitList_L(LinkList *L) { (*L) = (LinkList)malloc(sizeof(LNode)); if(!(*L)) exit(OVERFLOW); (*L)->next = NULL; return OK; } Status ClearList_L(LinkList L) { LinkList pre, p; if(!L) return ERROR; pre = L->next; while(pre) { p = pre->next; free(pre); pre = p; } L->next = NULL; return OK; } void DestroyList_L(LinkList *L) { LinkList p = *L; while(p) { p = (*L)->next; free(*L); (*L) = p; } } Status ListEmpty_L(LinkList L) { if(L!=NULL && L->next==NULL) //链表存在且只有头结点 return TRUE; else return FALSE; } int ListLength_L(LinkList L) { LinkList p; int i; if(L) { i = 0; p = L->next; while(p) { i++; p = p->next; } } return i; } Status GetElem_L(LinkList L, int i, LElemType_L *e) { int j; LinkList p = L->next; j = 1; p = L->next; while(p && j<i) { j++; p = p->next; } if(!p || j>i) return ERROR; *e = p->data; return OK; } int LocateElem_L(LinkList L, LElemType_L e, Status(Compare)(LElemType_L, LElemType_L)) { int i; LinkList p; i = -1; if(L) { i = 0; p = L->next; while(p) { i++; if(!Compare(e, p->data)) { p = p->next; if(p==NULL) i++; } else break; } } return i; } Status PriorElem_L(LinkList L, LElemType_L cur_e, LElemType_L *pre_e) { LinkList p, suc; if(L) { p = L->next; if(p->data!=cur_e) { while(p->next) { suc = p->next; if(suc->data==cur_e) { *pre_e = p->data; return OK; } p = suc; } } } return ERROR; } Status NextElem_L(LinkList L, LElemType_L cur_e, LElemType_L *next_e) { LinkList p, suc; if(L) { p = L->next; while(p && p->next) { suc = p->next; if(suc && p->data==cur_e) { *next_e = suc->data; return OK; } if(suc) p = suc; else break; } } return ERROR; } Status ListInsert_L(LinkList L, int i, LElemType_L e) { LinkList p, s; int j; p = L; j = 0; while(p && j<i-1) { p = p->next; ++j; } if(!p || j>i-1) return ERROR; s = (LinkList)malloc(sizeof(LNode)); if(!s) exit(OVERFLOW); s->data = e; s->next = p->next; p->next = s; return OK; } Status ListDelete_L(LinkList L, int i, LElemType_L *e) { LinkList pre, p; int j; pre = L; j = 1; while(pre->next && j<i) { pre = pre->next; ++j; } if(!pre->next || j>i) return ERROR; p = pre->next; pre->next = p->next; *e = p->data; free(p); return OK; } Status ListTraverse_L(LinkList L, void(Visit)(LElemType_L)) { LinkList p; if(!L) return ERROR; else p = L->next; while(p) { Visit(p->data); p = p->next; } return OK; } Status CreateList_HL(FILE *fp, LinkList *L, int n) { int i; LinkList p; LElemType_L tmp; *L = (LinkList)malloc(sizeof(LNode)); if(!(*L)) exit(OVERFLOW); (*L)->next = NULL; //建立头结点 for(i=1; i<=n; ++i) { if(fscanf(fp, "%d", &tmp)==1) { p = (LinkList)malloc(sizeof(LNode)); if(!p) exit(OVERFLOW); p->data = tmp; //录入数据 p->next = (*L)->next; (*L)->next = p; } else return ERROR; } return OK; } Status CreateList_TL(FILE *fp, LinkList *L, int n) { int i; LinkList p, q; LElemType_L tmp; *L = (LinkList)malloc(sizeof(LNode)); if(!(*L)) exit(OVERFLOW); (*L)->next = NULL; for(i=1,q=*L; i<=n; ++i) { if(fscanf(fp, "%d", &tmp)==1) { p = (LinkList)malloc(sizeof(LNode)); if(!p) exit(OVERFLOW); p->data = tmp; q->next = p; q = q->next; } else return ERROR; } q->next = NULL; return OK; } void MergeList_L(LinkList La, LinkList *Lb, LinkList *Lc){ LinkList pa, pb, pc; pa = La->next; pb = (*Lb)->next; pc = *Lc = La; while(pa && pb) { if(pa->data <= pb->data) { pc->next = pa; pc = pa; pa = pa->next; } else { pc->next = pb; pc = pb; pb = pb->next; } } pc->next = pa ? pa : pb; free(*Lb); *Lb = NULL; } void ReverseList_L(LinkList L){ LNode* p = L->next; LNode* q; L->next = NULL; while (p) { q = p->next; p->next = L->next; L->next = p; p = q; } } bool SortList_L(LinkList L){ if (L == NULL || L->next == NULL) { return false; } LinkList flagNode = NULL; bool isChange = true; while (flagNode != L->next || isChange) { LinkList curNode = L; isChange = false; while (curNode->next && curNode->next != flagNode) { if(curNode->data > curNode->next->data){ LElemType_L temp = curNode->data; curNode->data = curNode->next->data; curNode->next->data = temp; } curNode = curNode->next; } flagNode = curNode; } return true; } // 将表A中结点按序号的奇偶性分解到表A或表B中 LinkList DisCreat_1(LinkList &A){ int i = 0; LinkList B = (LinkList)malloc(sizeof(LNode)); B->next = NULL; LNode *ra = A, *rb = B; LNode *p = A->next; A->next = NULL; while (p!=NULL) { i++; if(i % 2 == 0){ rb->next = p; rb = p; }else{ ra->next = p; ra = p; } p = p->next; } ra->next = NULL; rb->next = NULL; return B; }
[ "i@loyio.me" ]
i@loyio.me
9487a6fdf0d0b412e4a0dcb8bc5d42fe2c6ce27d
d5d6047d86e39a99cd09a5bbb2ad0820f5f2d39f
/glm/glm.hpp
f357abfeaa08e30ef99940d4759ee2cd138164bf
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
gchunev/Dice4D
5bb184c3767294bb1e80111651d6601fab076335
f96db406204fdca0155d26db856b66a2afd4e664
refs/heads/master
2020-05-23T22:33:42.752018
2019-05-24T14:50:28
2019-05-24T14:50:28
186,976,624
1
0
null
null
null
null
UTF-8
C++
false
false
4,541
hpp
/// @ref core /// @file glm/glm.hpp /// /// @defgroup core Core features /// /// @brief Features that implement in C++ the GLSL specification as closely as possible. /// /// The GLM core consists of C++ types that mirror GLSL types and /// C++ functions that mirror the GLSL functions. /// /// The best documentation for GLM Core is the current GLSL specification, /// <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.clean.pdf">version 4.2 /// (pdf file)</a>. /// /// GLM core functionalities require <glm/glm.hpp> to be included to be used. /// /// /// @defgroup core_vector Vector types /// /// Vector types of two to four components with an exhaustive set of operators. /// /// @ingroup core /// /// /// @defgroup core_vector_precision Vector types with precision qualifiers /// /// @brief Vector types with precision qualifiers which may result in various precision in term of ULPs /// /// GLSL allows defining qualifiers for particular variables. /// With OpenGL's GLSL, these qualifiers have no effect; they are there for compatibility, /// with OpenGL ES's GLSL, these qualifiers do have an effect. /// /// C++ has no language equivalent to qualifier qualifiers. So GLM provides the next-best thing: /// a number of typedefs that use a particular qualifier. /// /// None of these types make any guarantees about the actual qualifier used. /// /// @ingroup core /// /// /// @defgroup core_matrix Matrix types /// /// Matrix types of with C columns and R rows where C and R are values between 2 to 4 included. /// These types have exhaustive sets of operators. /// /// @ingroup core /// /// /// @defgroup core_matrix_precision Matrix types with precision qualifiers /// /// @brief Matrix types with precision qualifiers which may result in various precision in term of ULPs /// /// GLSL allows defining qualifiers for particular variables. /// With OpenGL's GLSL, these qualifiers have no effect; they are there for compatibility, /// with OpenGL ES's GLSL, these qualifiers do have an effect. /// /// C++ has no language equivalent to qualifier qualifiers. So GLM provides the next-best thing: /// a number of typedefs that use a particular qualifier. /// /// None of these types make any guarantees about the actual qualifier used. /// /// @ingroup core /// /// /// @defgroup ext Stable extensions /// /// @brief Additional features not specified by GLSL specification. /// /// EXT extensions are fully tested and documented. /// /// Even if it's highly unrecommended, it's possible to include all the extensions at once by /// including <glm/ext.hpp>. Otherwise, each extension needs to be included a specific file. /// /// /// @defgroup gtc Recommended extensions /// /// @brief Additional features not specified by GLSL specification. /// /// GTC extensions aim to be stable with tests and documentation. /// /// Even if it's highly unrecommended, it's possible to include all the extensions at once by /// including <glm/ext.hpp>. Otherwise, each extension needs to be included a specific file. /// /// /// @defgroup gtx Experimental extensions /// /// @brief Experimental features not specified by GLSL specification. /// /// Experimental extensions are useful functions and types, but the development of /// their API and functionality is not necessarily stable. They can change /// substantially between versions. Backwards compatibility is not much of an issue /// for them. /// /// Even if it's highly unrecommended, it's possible to include all the extensions /// at once by including <glm/ext.hpp>. Otherwise, each extension needs to be /// included a specific file. /// /// @mainpage OpenGL Mathematics (GLM) /// - Website: <a href="https://glm.g-truc.net">glm.g-truc.net</a> /// - <a href="modules.html">GLM API documentation</a> /// - <a href="https://github.com/g-truc/glm/blob/master/manual.md">GLM Manual</a> #include "detail/_fixes.hpp" #include "detail/setup.hpp" #pragma once #include <cmath> #include <climits> #include <cfloat> #include <limits> #include <cassert> #include "fwd.hpp" #include "vec2.hpp" #include "vec3.hpp" #include "vec4.hpp" #include "vec5.hpp" #include "mat2x2.hpp" #include "mat2x3.hpp" #include "mat2x4.hpp" #include "mat3x2.hpp" #include "mat3x3.hpp" #include "mat3x4.hpp" #include "mat4x2.hpp" #include "mat4x3.hpp" #include "mat4x4.hpp" #include "mat5x5.hpp" #include "trigonometric.hpp" #include "exponential.hpp" #include "common.hpp" #include "packing.hpp" #include "geometric.hpp" #include "matrix.hpp" #include "vector_relational.hpp" #include "integer.hpp"
[ "georgi.chunev@gameloft.com" ]
georgi.chunev@gameloft.com
c3ccb8c993cb79e42cbdd3c524f8ce6663d55b40
8a55bdec478d2fb48508deac13ca3aeeda46fa06
/src/wallet/walletdb.h
8adf153fb637dc8e98499d0cd5176cfb04768d03
[ "MIT" ]
permissive
hideoussquid/aureus-core-gui
83b0525e1afa349e0834e1a3baed5534043cd689
ce075f2f0f9c99a344a1b0629cfd891526daac7b
refs/heads/master
2021-01-19T00:04:39.888184
2017-04-04T08:15:18
2017-04-04T08:15:18
87,142,504
0
0
null
null
null
null
UTF-8
C++
false
false
7,214
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 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 AUREUS_WALLET_WALLETDB_H #define AUREUS_WALLET_WALLETDB_H #include "amount.h" #include "primitives/transaction.h" #include "wallet/db.h" #include "key.h" #include <list> #include <stdint.h> #include <string> #include <utility> #include <vector> static const bool DEFAULT_FLUSHWALLET = true; class CAccount; class CAccountingEntry; struct CBlockLocator; class CKeyPool; class CMasterKey; class CScript; class CWallet; class CWalletTx; class uint160; class uint256; /** Error statuses for the wallet database */ enum DBErrors { DB_LOAD_OK, DB_CORRUPT, DB_NONCRITICAL_ERROR, DB_TOO_NEW, DB_LOAD_FAIL, DB_NEED_REWRITE }; /* simple HD chain data model */ class CHDChain { public: uint32_t nExternalChainCounter; uint32_t nInternalChainCounter; CKeyID masterKeyID; //!< master key hash160 static const int VERSION_HD_BASE = 1; static const int VERSION_HD_CHAIN_SPLIT = 2; static const int CURRENT_VERSION = VERSION_HD_CHAIN_SPLIT; int nVersion; CHDChain() { SetNull(); } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(this->nVersion); READWRITE(nExternalChainCounter); READWRITE(masterKeyID); if (this->nVersion >= VERSION_HD_CHAIN_SPLIT) READWRITE(nInternalChainCounter); } void SetNull() { nVersion = CHDChain::CURRENT_VERSION; nExternalChainCounter = 0; nInternalChainCounter = 0; masterKeyID.SetNull(); } }; class CKeyMetadata { public: static const int VERSION_BASIC=1; static const int VERSION_WITH_HDDATA=10; static const int CURRENT_VERSION=VERSION_WITH_HDDATA; int nVersion; int64_t nCreateTime; // 0 means unknown std::string hdKeypath; //optional HD/bip32 keypath CKeyID hdMasterKeyID; //id of the HD masterkey used to derive this key CKeyMetadata() { SetNull(); } CKeyMetadata(int64_t nCreateTime_) { SetNull(); nCreateTime = nCreateTime_; } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(this->nVersion); READWRITE(nCreateTime); if (this->nVersion >= VERSION_WITH_HDDATA) { READWRITE(hdKeypath); READWRITE(hdMasterKeyID); } } void SetNull() { nVersion = CKeyMetadata::CURRENT_VERSION; nCreateTime = 0; hdKeypath.clear(); hdMasterKeyID.SetNull(); } }; /** Access to the wallet database */ class CWalletDB : public CDB { public: CWalletDB(const std::string& strFilename, const char* pszMode = "r+", bool _fFlushOnClose = true) : CDB(strFilename, pszMode, _fFlushOnClose) { } bool WriteName(const std::string& strAddress, const std::string& strName); bool EraseName(const std::string& strAddress); bool WritePurpose(const std::string& strAddress, const std::string& purpose); bool ErasePurpose(const std::string& strAddress); bool WriteTx(const CWalletTx& wtx); bool EraseTx(uint256 hash); bool WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata &keyMeta); bool WriteCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret, const CKeyMetadata &keyMeta); bool WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey); bool WriteCScript(const uint160& hash, const CScript& redeemScript); bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta); bool EraseWatchOnly(const CScript &script); bool WriteBestBlock(const CBlockLocator& locator); bool ReadBestBlock(CBlockLocator& locator); bool WriteOrderPosNext(int64_t nOrderPosNext); bool WriteDefaultKey(const CPubKey& vchPubKey); bool ReadPool(int64_t nPool, CKeyPool& keypool); bool WritePool(int64_t nPool, const CKeyPool& keypool); bool ErasePool(int64_t nPool); bool WriteMinVersion(int nVersion); /// This writes directly to the database, and will not update the CWallet's cached accounting entries! /// Use wallet.AddAccountingEntry instead, to write *and* update its caches. bool WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry); bool WriteAccountingEntry_Backend(const CAccountingEntry& acentry); bool ReadAccount(const std::string& strAccount, CAccount& account); bool WriteAccount(const std::string& strAccount, const CAccount& account); /// Write destination data key,value tuple to database bool WriteDestData(const std::string &address, const std::string &key, const std::string &value); /// Erase destination data tuple from wallet database bool EraseDestData(const std::string &address, const std::string &key); CAmount GetAccountCreditDebit(const std::string& strAccount); void ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& acentries); DBErrors LoadWallet(CWallet* pwallet); DBErrors FindWalletTx(std::vector<uint256>& vTxHash, std::vector<CWalletTx>& vWtx); DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx); DBErrors ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut); /* Try to (very carefully!) recover wallet database (with a possible key type filter) */ static bool Recover(const std::string& filename, void *callbackDataIn, bool (*recoverKVcallback)(void* callbackData, CDataStream ssKey, CDataStream ssValue)); /* Recover convenience-function to bypass the key filter callback, called when verify fails, recovers everything */ static bool Recover(const std::string& filename); /* Recover filter (used as callback), will only let keys (cryptographical keys) as KV/key-type pass through */ static bool RecoverKeysOnlyFilter(void *callbackData, CDataStream ssKey, CDataStream ssValue); /* Function to determine if a certain KV/key-type is a key (cryptographical key) type */ static bool IsKeyType(const std::string& strType); /* verifies the database environment */ static bool VerifyEnvironment(const std::string& walletFile, const boost::filesystem::path& dataDir, std::string& errorStr); /* verifies the database file */ static bool VerifyDatabaseFile(const std::string& walletFile, const boost::filesystem::path& dataDir, std::string& warningStr, std::string& errorStr); //! write the hdchain model (external chain child index counter) bool WriteHDChain(const CHDChain& chain); static void IncrementUpdateCounter(); static unsigned int GetUpdateCounter(); private: CWalletDB(const CWalletDB&); void operator=(const CWalletDB&); }; //! Compacts BDB state so that wallet.dat is self-contained (if there are changes) void MaybeCompactWalletDB(); #endif // AUREUS_WALLET_WALLETDB_H
[ "thesquid@mac.com" ]
thesquid@mac.com
2a84f946f30fbcaa3858fd87596da0e938e53d5a
f66d08afc3a54a78f6fdb7c494bc2624d70c5d25
/Code/CLN/src/real/format-output/cl_fmt_paddedstring.cc
127d23a0e2ba5dea2c70ec6d5e61dbb85f09b334
[]
no_license
NBAlexis/GiNaCToolsVC
46310ae48cff80b104cc4231de0ed509116193d9
62a25e0b201436316ddd3d853c8c5e738d66f436
refs/heads/master
2021-04-26T23:56:43.627861
2018-03-09T19:15:53
2018-03-09T19:15:53
123,883,542
1
0
null
null
null
null
UTF-8
C++
false
false
694
cc
// format_padded_string(). // General includes. #include "cln_private.h" // Specification. #include "real/format-output/cl_format.h" // Implementation. #include <cstring> namespace cln { void format_padded_string (std::ostream& stream, sintL mincol, sintL colinc, sintL minpad, char padchar, bool padleftflag, const char * str) { var sintL need = static_cast<sintL>(::strlen(str) + minpad); // so viele Zeichen mindestens var uintL auxpad = (need < mincol ? ceiling((uintL)(mincol - need), colinc) * colinc : 0 ); if (!padleftflag) fprint(stream,str); format_padding(stream,minpad+auxpad,padchar); if (padleftflag) fprint(stream,str); } } // namespace cln
[ "nbalexis@gmail.com" ]
nbalexis@gmail.com
639acd30d9579904a5b0e3b43a1f321d7d3e3192
38f574a4c10f8f7e2ec775e7a3db7c7003d36540
/deps/include/objscip/objprobdata.h
cb78ba1968cd611bf772682b31afe2000fea9c78
[ "MIT", "Apache-2.0" ]
permissive
kjartanm/sudoku-solver
a601c20122ffbdc95fc33a09d579f287575e3b7b
a376e33bafd91f0e33b0cade5be90c4f48ed73af
refs/heads/master
2022-12-08T00:50:14.609241
2020-08-31T06:36:26
2020-08-31T06:36:26
288,816,033
2
1
null
null
null
null
UTF-8
C++
false
false
10,415
h
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* SCIP --- Solving Constraint Integer Programs */ /* */ /* Copyright (C) 2002-2020 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* SCIP is distributed under the terms of the ZIB Academic License. */ /* */ /* You should have received a copy of the ZIB Academic License. */ /* along with SCIP; see the file COPYING. If not visit scipopt.org. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /**@file objprobdata.h * @brief C++ wrapper for user problem data * @author Tobias Achterberg */ /*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/ #ifndef __SCIP_OBJPROBDATA_H__ #define __SCIP_OBJPROBDATA_H__ #include <cassert> #include "scip/scip.h" #include "objscip/objcloneable.h" namespace scip { /** @brief C++ wrapper for user problem data * * This class defines the interface for user problem data implemented in C++. This class can be accessed at any time * using the methods SCIPgetObjProbData(). Therefore, it can be used to store data which has to be accessible within * several plugins. * * - \ref type_prob.h "Corresponding C interface" */ class ObjProbData { public: /** default constructor */ ObjProbData() { } /** destructor */ virtual ~ObjProbData() { } /** destructor of user problem data to free original user data (called when original problem is freed) * * If the "deleteobject" flag in the SCIPcreateObjProb() method was set to TRUE, this method is not needed, * because all the work to delete the user problem data can be done in the destructor of the user problem * data object. If the "deleteobject" flag was set to FALSE, and the user problem data object stays alive * after the SCIP problem is freed, this method should delete all the problem specific data that is no * longer needed. */ /*lint -e715*/ virtual SCIP_RETCODE scip_delorig( SCIP* scip /**< SCIP data structure */ ) { /*lint --e{715}*/ return SCIP_OKAY; } /** creates user data of transformed problem by transforming the original user problem data * (called after problem was transformed) * * The user has two possibilities to implement this method: * 1. Return the pointer to the original problem data object (this) as pointer to the transformed problem data * object. The user may modify some internal attributes, but he has to make sure, that these modifications are * reversed in the scip_deltrans() method, such that the original problem data is restored. In this case, * he should set *deleteobject to FALSE, because the problem data must not be destructed by SCIP after the * solving process is terminated. * 2. Call the copy constructor of the problem data object and return the created copy as transformed problem * data object. In this case, he probably wants to set *deleteobject to TRUE, thus letting SCIP call the * destructor of the object if the transformed problem data is no longer needed. */ /*lint -e715*/ virtual SCIP_RETCODE scip_trans( SCIP* scip, /**< SCIP data structure */ ObjProbData** objprobdata, /**< pointer to store the transformed problem data object */ SCIP_Bool* deleteobject /**< pointer to store whether SCIP should delete the object after solving */ ) { /*lint --e{715}*/ assert(objprobdata != NULL); assert(deleteobject != NULL); /* the default implementation just copies the pointer to the problem data object; * SCIP must not destruct the transformed problem data object, because the original problem data must stay alive */ *objprobdata = this; *deleteobject = FALSE; return SCIP_OKAY; } /** destructor of user problem data to free transformed user data (called when transformed problem is freed) * * If the "*deleteobject" flag in the scip_trans() method was set to TRUE, this method is not needed, * because all the work to delete the user problem data can be done in the destructor of the user problem * data object. If the "*deleteobject" flag was set to FALSE, and the user problem data object stays alive * after the SCIP problem is freed, this method should delete all the problem specific data that is no * longer needed. */ /*lint -e715*/ virtual SCIP_RETCODE scip_deltrans( SCIP* scip /**< SCIP data structure */ ) { /*lint --e{715}*/ return SCIP_OKAY; } /** solving process initialization method of transformed data (called before the branch and bound process begins) * * This method is called before the branch and bound process begins and can be used to initialize user problem * data that depends for example on the number of active problem variables, because these are now fixed. */ /*lint -e715*/ virtual SCIP_RETCODE scip_initsol( SCIP* scip /**< SCIP data structure */ ) { /*lint --e{715}*/ return SCIP_OKAY; } /** solving process deinitialization method of transformed data (called before the branch and bound data is freed) * * This method is called before the branch and bound data is freed and should be used to free all data that * was allocated in the solving process initialization method. The user has to make sure, that all LP rows associated * to the transformed user problem data are released. */ /*lint -e715*/ virtual SCIP_RETCODE scip_exitsol( SCIP* scip, /**< SCIP data structure */ SCIP_Bool restart /**< was this exit solve call triggered by a restart? */ ) { /*lint --e{715}*/ return SCIP_OKAY; } /** copies user data of source SCIP for the target SCIP * * This method should copy the problem data of the source SCIP and create a target problem data for (target) * SCIP. Implementing this callback is optional. If the copying process was successful the target SCIP gets this * problem data assigned. In case the result pointer is set to SCIP_DIDNOTRUN the target SCIP will have no problem data * at all. * * The variable map and the constraint map can be used via the function SCIPgetVarCopy() and SCIPgetConsCopy(), * respectively, to get for certain variables and constraints of the source SCIP the counter parts in the target * SCIP. You should be very carefully in using these two methods since they could lead to an infinite loop due to * recursion. * * possible return values for *result: * - SCIP_DIDNOTRUN : the copying process was not performed * - SCIP_SUCCESS : the copying process was successfully performed */ /*lint -e715*/ virtual SCIP_RETCODE scip_copy( SCIP* scip, /**< SCIP data structure */ SCIP* sourcescip, /**< source SCIP main data structure */ SCIP_HASHMAP* varmap, /**< a hashmap which stores the mapping of source variables to corresponding * target variables */ SCIP_HASHMAP* consmap, /**< a hashmap which stores the mapping of source contraints to corresponding * target constraints */ ObjProbData** objprobdata, /**< pointer to store the copied problem data object */ SCIP_Bool global, /**< create a global or a local copy? */ SCIP_RESULT* result /**< pointer to store the result of the call */ ) { /*lint --e{715}*/ (*objprobdata) = 0; (*result) = SCIP_DIDNOTRUN; return SCIP_OKAY; } }; } /* namespace scip */ /** creates empty problem, initializes all solving data structures, and sets the user problem data to point to the * given user data object * * The method should be called in one of the following ways: * * 1. The user is resposible of deleting the object: * SCIP_CALL( SCIPcreate(&scip) ); * ... * MyProbData* myprobdata = new MyProbData(...); * SCIP_CALL( SCIPcreateObjProb(scip, "probname", &myprobdata, FALSE) ); * ... // solve the problem * SCIP_CALL( SCIPfreeProb(scip) ); * delete myprobdata; // delete probdata AFTER SCIPfreeProb() ! * ... * SCIP_CALL( SCIPfree(&scip) ); * * 2. The object pointer is passed to SCIP and deleted by SCIP in the SCIPfreeProb() call: * SCIP_CALL( SCIPcreate(&scip) ); * ... * SCIP_CALL( SCIPcreateObjProb(scip, "probname", new MyProbData(...), TRUE) ); * ... * SCIP_CALL( SCIPfree(&scip) ); // problem is freed and destructor of MyProbData is called here */ SCIP_EXPORT SCIP_RETCODE SCIPcreateObjProb( SCIP* scip, /**< SCIP data structure */ const char* name, /**< problem name */ scip::ObjProbData* objprobdata, /**< user problem data object */ SCIP_Bool deleteobject /**< should the user problem data object be deleted when problem is freed? */ ); /** gets user problem data object * Warning! This method should only be called after a problem was created with SCIPcreateObjProb(). * Otherwise, a segmentation fault may arise, or an undefined pointer is returned. */ SCIP_EXPORT scip::ObjProbData* SCIPgetObjProbData( SCIP* scip /**< SCIP data structure */ ); #endif
[ "kjartan@muller.no" ]
kjartan@muller.no
4b776d18038896f0d09e4fa93f7e960cb47538d3
e9321204dfca38eaf12eca38f83476879c170441
/PDA/VTK-6.3.0/Utilities/KWSys/vtksys/SystemTools.cxx
6c4a7a67586fe1f6e6d655e08eedd555811b2e50
[ "BSD-3-Clause" ]
permissive
jumperbeng/backup
1d96d471e4aa1adc1179fa78db02b08ff944f7ab
64e36db87446ddae132524e19fef45f2b1b01242
refs/heads/master
2021-07-14T08:27:34.831316
2017-10-17T04:09:31
2017-10-17T04:09:31
107,211,167
1
0
null
null
null
null
UTF-8
C++
false
false
136,756
cxx
/*============================================================================ KWSys - Kitware System Library Copyright 2000-2009 Kitware, Inc., Insight Software Consortium Distributed under the OSI-approved BSD License (the "License"); see accompanying file Copyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more information. ============================================================================*/ #ifdef __osf__ # define _OSF_SOURCE # define _POSIX_C_SOURCE 199506L # define _XOPEN_SOURCE_EXTENDED #endif #if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__) || defined(__MINGW32__)) # define KWSYS_WINDOWS_DIRS #else # if defined(__SUNPRO_CC) # include <fcntl.h> # endif #endif #include "kwsysPrivate.h" #include KWSYS_HEADER(RegularExpression.hxx) #include KWSYS_HEADER(SystemTools.hxx) #include KWSYS_HEADER(Directory.hxx) #include KWSYS_HEADER(FStream.hxx) #include KWSYS_HEADER(Encoding.hxx) #include KWSYS_HEADER(ios/iostream) #include KWSYS_HEADER(ios/fstream) #include KWSYS_HEADER(ios/sstream) #include KWSYS_HEADER(stl/set) // Work-around CMake dependency scanning limitation. This must // duplicate the above list of headers. #if 0 # include "SystemTools.hxx.in" # include "Directory.hxx.in" # include "FStream.hxx.in" # include "Encoding.hxx.in" # include "kwsys_ios_iostream.h.in" # include "kwsys_ios_fstream.h.in" # include "kwsys_ios_sstream.h.in" #endif #ifdef _MSC_VER # pragma warning (disable: 4786) #endif #if defined(__sgi) && !defined(__GNUC__) # pragma set woff 1375 /* base class destructor not virtual */ #endif #include <ctype.h> #include <errno.h> #ifdef __QNX__ # include <malloc.h> /* for malloc/free on QNX */ #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <time.h> // support for realpath call #ifndef _WIN32 #include <sys/time.h> #include <utime.h> #include <limits.h> #include <sys/wait.h> #include <sys/ioctl.h> #include <unistd.h> #include <pwd.h> #ifndef __VMS #include <sys/param.h> #include <termios.h> #endif #include <signal.h> /* sigprocmask */ #endif // Windows API. #if defined(_WIN32) # include <windows.h> # ifndef INVALID_FILE_ATTRIBUTES # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) # endif # if defined(_MSC_VER) && _MSC_VER >= 1800 # define KWSYS_WINDOWS_DEPRECATED_GetVersionEx # endif #elif defined (__CYGWIN__) # include <windows.h> # undef _WIN32 #endif #if !KWSYS_CXX_HAS_ENVIRON_IN_STDLIB_H extern char **environ; #endif #ifdef __CYGWIN__ # include <sys/cygwin.h> #endif // getpwnam doesn't exist on Windows and Cray Xt3/Catamount // same for TIOCGWINSZ #if defined(_WIN32) || defined (__LIBCATAMOUNT__) # undef HAVE_GETPWNAM # undef HAVE_TTY_INFO #else # define HAVE_GETPWNAM 1 # define HAVE_TTY_INFO 1 #endif #define VTK_URL_PROTOCOL_REGEX "([a-zA-Z0-9]*)://(.*)" #define VTK_URL_REGEX "([a-zA-Z0-9]*)://(([A-Za-z0-9]+)(:([^:@]+))?@)?([^:@/]+)(:([0-9]+))?/(.+)?" #ifdef _MSC_VER #include <sys/utime.h> #else #include <utime.h> #endif // This is a hack to prevent warnings about these functions being // declared but not referenced. #if defined(__sgi) && !defined(__GNUC__) # include <sys/termios.h> namespace KWSYS_NAMESPACE { class SystemToolsHack { public: enum { Ref1 = sizeof(cfgetospeed(0)), Ref2 = sizeof(cfgetispeed(0)), Ref3 = sizeof(tcgetattr(0, 0)), Ref4 = sizeof(tcsetattr(0, 0, 0)), Ref5 = sizeof(cfsetospeed(0,0)), Ref6 = sizeof(cfsetispeed(0,0)) }; }; } #endif #if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) ||defined(__BORLANDC__) || defined(__MINGW32__)) #include <io.h> #include <direct.h> #define _unlink unlink #endif /* The maximum length of a file name. */ #if defined(PATH_MAX) # define KWSYS_SYSTEMTOOLS_MAXPATH PATH_MAX #elif defined(MAXPATHLEN) # define KWSYS_SYSTEMTOOLS_MAXPATH MAXPATHLEN #else # define KWSYS_SYSTEMTOOLS_MAXPATH 16384 #endif #if defined(__WATCOMC__) #include <direct.h> #define _mkdir mkdir #define _rmdir rmdir #define _getcwd getcwd #define _chdir chdir #endif #if defined(__BEOS__) && !defined(__ZETA__) #include <be/kernel/OS.h> #include <be/storage/Path.h> // BeOS 5 doesn't have usleep(), but it has snooze(), which is identical. static inline void usleep(unsigned int msec) { ::snooze(msec); } // BeOS 5 also doesn't have realpath(), but its C++ API offers something close. static inline char *realpath(const char *path, char *resolved_path) { const size_t maxlen = KWSYS_SYSTEMTOOLS_MAXPATH; snprintf(resolved_path, maxlen, "%s", path); BPath normalized(resolved_path, NULL, true); const char *resolved = normalized.Path(); if (resolved != NULL) // NULL == No such file. { if (snprintf(resolved_path, maxlen, "%s", resolved) < maxlen) { return resolved_path; } } return NULL; // something went wrong. } #endif #ifdef _WIN32 static time_t windows_filetime_to_posix_time(const FILETIME& ft) { LARGE_INTEGER date; date.HighPart = ft.dwHighDateTime; date.LowPart = ft.dwLowDateTime; // removes the diff between 1970 and 1601 date.QuadPart -= ((LONGLONG)(369 * 365 + 89) * 24 * 3600 * 10000000); // converts back from 100-nanoseconds to seconds return date.QuadPart / 10000000; } #endif #ifdef KWSYS_WINDOWS_DIRS #include <wctype.h> inline int Mkdir(const kwsys_stl::string& dir) { return _wmkdir( KWSYS_NAMESPACE::SystemTools::ConvertToWindowsExtendedPath(dir).c_str()); } inline int Rmdir(const kwsys_stl::string& dir) { return _wrmdir( KWSYS_NAMESPACE::SystemTools::ConvertToWindowsExtendedPath(dir).c_str()); } inline const char* Getcwd(char* buf, unsigned int len) { std::vector<wchar_t> w_buf(len); if(_wgetcwd(&w_buf[0], len)) { // make sure the drive letter is capital if(wcslen(&w_buf[0]) > 1 && w_buf[1] == L':') { w_buf[0] = towupper(w_buf[0]); } std::string tmp = KWSYS_NAMESPACE::Encoding::ToNarrow(&w_buf[0]); strcpy(buf, tmp.c_str()); return buf; } return 0; } inline int Chdir(const kwsys_stl::string& dir) { #if defined(__BORLANDC__) return chdir(dir.c_str()); #else return _wchdir(KWSYS_NAMESPACE::Encoding::ToWide(dir).c_str()); #endif } inline void Realpath(const kwsys_stl::string& path, kwsys_stl::string& resolved_path, kwsys_stl::string* errorMessage = 0) { kwsys_stl::wstring tmp = KWSYS_NAMESPACE::Encoding::ToWide(path); wchar_t *ptemp; wchar_t fullpath[MAX_PATH]; DWORD bufferLen = GetFullPathNameW(tmp.c_str(), sizeof(fullpath) / sizeof(fullpath[0]), fullpath, &ptemp); if( bufferLen < sizeof(fullpath)/sizeof(fullpath[0]) ) { resolved_path = KWSYS_NAMESPACE::Encoding::ToNarrow(fullpath); KWSYS_NAMESPACE::SystemTools::ConvertToUnixSlashes(resolved_path); } else if(errorMessage) { if(bufferLen) { *errorMessage = "Destination path buffer size too small."; } else if(unsigned int errorId = GetLastError()) { LPSTR message = NULL; DWORD size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorId, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&message, 0, NULL); *errorMessage = std::string(message, size); LocalFree(message); } else { *errorMessage = "Unknown error."; } resolved_path = ""; } else { resolved_path = path; } } #else #include <sys/types.h> #include <fcntl.h> #include <unistd.h> inline int Mkdir(const kwsys_stl::string& dir) { return mkdir(dir.c_str(), 00777); } inline int Rmdir(const kwsys_stl::string& dir) { return rmdir(dir.c_str()); } inline const char* Getcwd(char* buf, unsigned int len) { return getcwd(buf, len); } inline int Chdir(const kwsys_stl::string& dir) { return chdir(dir.c_str()); } inline void Realpath(const kwsys_stl::string& path, kwsys_stl::string& resolved_path, kwsys_stl::string* errorMessage = 0) { char resolved_name[KWSYS_SYSTEMTOOLS_MAXPATH]; errno = 0; char *ret = realpath(path.c_str(), resolved_name); if(ret) { resolved_path = ret; } else if(errorMessage) { if(errno) { *errorMessage = strerror(errno); } else { *errorMessage = "Unknown error."; } resolved_path = ""; } else { // if path resolution fails, return what was passed in resolved_path = path; } } #endif #if !defined(_WIN32) && defined(__COMO__) // Hack for como strict mode to avoid defining _SVID_SOURCE or _BSD_SOURCE. extern "C" { extern FILE *popen (__const char *__command, __const char *__modes) __THROW; extern int pclose (FILE *__stream) __THROW; extern char *realpath (__const char *__restrict __name, char *__restrict __resolved) __THROW; extern char *strdup (__const char *__s) __THROW; extern int putenv (char *__string) __THROW; } #endif namespace KWSYS_NAMESPACE { double SystemTools::GetTime(void) { #if defined(_WIN32) && !defined(__CYGWIN__) FILETIME ft; GetSystemTimeAsFileTime(&ft); return (429.4967296*ft.dwHighDateTime + 0.0000001*ft.dwLowDateTime - 11644473600.0); #else struct timeval t; gettimeofday(&t, 0); return 1.0*double(t.tv_sec) + 0.000001*double(t.tv_usec); #endif } class SystemToolsTranslationMap : public kwsys_stl::map<kwsys_stl::string,kwsys_stl::string> { }; // adds the elements of the env variable path to the arg passed in void SystemTools::GetPath(kwsys_stl::vector<kwsys_stl::string>& path, const char* env) { #if defined(_WIN32) && !defined(__CYGWIN__) const char pathSep = ';'; #else const char pathSep = ':'; #endif if(!env) { env = "PATH"; } const char* cpathEnv = SystemTools::GetEnv(env); if ( !cpathEnv ) { return; } kwsys_stl::string pathEnv = cpathEnv; // A hack to make the below algorithm work. if(!pathEnv.empty() && *pathEnv.rbegin() != pathSep) { pathEnv += pathSep; } kwsys_stl::string::size_type start =0; bool done = false; while(!done) { kwsys_stl::string::size_type endpos = pathEnv.find(pathSep, start); if(endpos != kwsys_stl::string::npos) { path.push_back(pathEnv.substr(start, endpos-start)); start = endpos+1; } else { done = true; } } for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin(); i != path.end(); ++i) { SystemTools::ConvertToUnixSlashes(*i); } } const char* SystemTools::GetEnv(const char* key) { return getenv(key); } const char* SystemTools::GetEnv(const kwsys_stl::string& key) { return SystemTools::GetEnv(key.c_str()); } bool SystemTools::GetEnv(const char* key, kwsys_stl::string& result) { const char* v = getenv(key); if(v) { result = v; return true; } else { return false; } } bool SystemTools::GetEnv(const kwsys_stl::string& key, kwsys_stl::string& result) { return SystemTools::GetEnv(key.c_str(), result); } //---------------------------------------------------------------------------- #if defined(__CYGWIN__) || defined(__GLIBC__) # define KWSYS_PUTENV_NAME /* putenv("A") removes A. */ #elif defined(_WIN32) # define KWSYS_PUTENV_EMPTY /* putenv("A=") removes A. */ #endif #if KWSYS_CXX_HAS_UNSETENV /* unsetenv("A") removes A from the environment. On older platforms it returns void instead of int. */ static int kwsysUnPutEnv(const kwsys_stl::string& env) { size_t pos = env.find('='); if(pos != env.npos) { std::string name = env.substr(0, pos); unsetenv(name.c_str()); } else { unsetenv(env.c_str()); } return 0; } #elif defined(KWSYS_PUTENV_EMPTY) || defined(KWSYS_PUTENV_NAME) /* putenv("A=") or putenv("A") removes A from the environment. */ static int kwsysUnPutEnv(const kwsys_stl::string& env) { int err = 0; size_t pos = env.find('='); size_t const len = pos == env.npos ? env.size() : pos; # ifdef KWSYS_PUTENV_EMPTY size_t const sz = len + 2; # else size_t const sz = len + 1; # endif char local_buf[256]; char* buf = sz > sizeof(local_buf) ? (char*)malloc(sz) : local_buf; if(!buf) { return -1; } strncpy(buf, env.c_str(), len); # ifdef KWSYS_PUTENV_EMPTY buf[len] = '='; buf[len+1] = 0; if(putenv(buf) < 0) { err = errno; } # else buf[len] = 0; if(putenv(buf) < 0 && errno != EINVAL) { err = errno; } # endif if(buf != local_buf) { free(buf); } if(err) { errno = err; return -1; } return 0; } #else /* Manipulate the "environ" global directly. */ static int kwsysUnPutEnv(const kwsys_stl::string& env) { size_t pos = env.find('='); size_t const len = pos == env.npos ? env.size() : pos; int in = 0; int out = 0; while(environ[in]) { if(strlen(environ[in]) > len && environ[in][len] == '=' && strncmp(env.c_str(), environ[in], len) == 0) { ++in; } else { environ[out++] = environ[in++]; } } while(out < in) { environ[out++] = 0; } return 0; } #endif //---------------------------------------------------------------------------- #if KWSYS_CXX_HAS_SETENV /* setenv("A", "B", 1) will set A=B in the environment and makes its own copies of the strings. */ bool SystemTools::PutEnv(const kwsys_stl::string& env) { size_t pos = env.find('='); if(pos != env.npos) { std::string name = env.substr(0, pos); return setenv(name.c_str(), env.c_str() + pos + 1, 1) == 0; } else { return kwsysUnPutEnv(env) == 0; } } bool SystemTools::UnPutEnv(const kwsys_stl::string& env) { return kwsysUnPutEnv(env) == 0; } #else /* putenv("A=B") will set A=B in the environment. Most putenv implementations put their argument directly in the environment. They never free the memory on program exit. Keep an active set of pointers to memory we allocate and pass to putenv, one per environment key. At program exit remove any environment values that may still reference memory we allocated. Then free the memory. This will not affect any environment values we never set. */ # ifdef __INTEL_COMPILER # pragma warning disable 444 /* base has non-virtual destructor */ # endif /* Order by environment key only (VAR from VAR=VALUE). */ struct kwsysEnvCompare { bool operator() (const char* l, const char* r) const { const char* leq = strchr(l, '='); const char* req = strchr(r, '='); size_t llen = leq? (leq-l) : strlen(l); size_t rlen = req? (req-r) : strlen(r); if(llen == rlen) { return strncmp(l,r,llen) < 0; } else { return strcmp(l,r) < 0; } } }; class kwsysEnv: public kwsys_stl::set<const char*, kwsysEnvCompare> { class Free { const char* Env; public: Free(const char* env): Env(env) {} ~Free() { free(const_cast<char*>(this->Env)); } }; public: typedef kwsys_stl::set<const char*, kwsysEnvCompare> derived; ~kwsysEnv() { for(derived::iterator i = this->begin(); i != this->end(); ++i) { kwsysUnPutEnv(*i); free(const_cast<char*>(*i)); } } const char* Release(const char* env) { const char* old = 0; derived::iterator i = this->find(env); if(i != this->end()) { old = *i; this->erase(i); } return old; } bool Put(const char* env) { Free oldEnv(this->Release(env)); static_cast<void>(oldEnv); char* newEnv = strdup(env); this->insert(newEnv); return putenv(newEnv) == 0; } bool UnPut(const char* env) { Free oldEnv(this->Release(env)); static_cast<void>(oldEnv); return kwsysUnPutEnv(env) == 0; } }; static kwsysEnv kwsysEnvInstance; bool SystemTools::PutEnv(const kwsys_stl::string& env) { return kwsysEnvInstance.Put(env.c_str()); } bool SystemTools::UnPutEnv(const kwsys_stl::string& env) { return kwsysEnvInstance.UnPut(env.c_str()); } #endif //---------------------------------------------------------------------------- const char* SystemTools::GetExecutableExtension() { #if defined(_WIN32) || defined(__CYGWIN__) || defined(__VMS) return ".exe"; #else return ""; #endif } FILE* SystemTools::Fopen(const kwsys_stl::string& file, const char* mode) { #ifdef _WIN32 return _wfopen(SystemTools::ConvertToWindowsExtendedPath(file).c_str(), Encoding::ToWide(mode).c_str()); #else return fopen(file.c_str(), mode); #endif } bool SystemTools::MakeDirectory(const char* path) { if(!path) { return false; } return SystemTools::MakeDirectory(kwsys_stl::string(path)); } bool SystemTools::MakeDirectory(const kwsys_stl::string& path) { if(SystemTools::FileExists(path)) { return SystemTools::FileIsDirectory(path); } if(path.empty()) { return false; } kwsys_stl::string dir = path; SystemTools::ConvertToUnixSlashes(dir); kwsys_stl::string::size_type pos = 0; kwsys_stl::string topdir; while((pos = dir.find('/', pos)) != kwsys_stl::string::npos) { topdir = dir.substr(0, pos); Mkdir(topdir); pos++; } topdir = dir; if(Mkdir(topdir) != 0) { // There is a bug in the Borland Run time library which makes MKDIR // return EACCES when it should return EEXISTS // if it is some other error besides directory exists // then return false if( (errno != EEXIST) #ifdef __BORLANDC__ && (errno != EACCES) #endif ) { return false; } } return true; } // replace replace with with as many times as it shows up in source. // write the result into source. void SystemTools::ReplaceString(kwsys_stl::string& source, const kwsys_stl::string& replace, const kwsys_stl::string& with) { // do while hangs if replaceSize is 0 if (replace.empty()) { return; } SystemTools::ReplaceString(source, replace.c_str(), replace.size(), with); } void SystemTools::ReplaceString(kwsys_stl::string& source, const char* replace, const char* with) { // do while hangs if replaceSize is 0 if (!*replace) { return; } SystemTools::ReplaceString(source, replace, strlen(replace), with ? with : ""); } void SystemTools::ReplaceString(kwsys_stl::string& source, const char* replace, size_t replaceSize, const kwsys_stl::string& with) { const char *src = source.c_str(); char *searchPos = const_cast<char *>(strstr(src,replace)); // get out quick if string is not found if (!searchPos) { return; } // perform replacements until done char *orig = strdup(src); char *currentPos = orig; searchPos = searchPos - src + orig; // initialize the result source.erase(source.begin(),source.end()); do { *searchPos = '\0'; source += currentPos; currentPos = searchPos + replaceSize; // replace source += with; searchPos = strstr(currentPos,replace); } while (searchPos); // copy any trailing text source += currentPos; free(orig); } #if defined(KEY_WOW64_32KEY) && defined(KEY_WOW64_64KEY) # define KWSYS_ST_KEY_WOW64_32KEY KEY_WOW64_32KEY # define KWSYS_ST_KEY_WOW64_64KEY KEY_WOW64_64KEY #else # define KWSYS_ST_KEY_WOW64_32KEY 0x0200 # define KWSYS_ST_KEY_WOW64_64KEY 0x0100 #endif #if defined(_WIN32) && !defined(__CYGWIN__) static bool SystemToolsParseRegistryKey(const kwsys_stl::string& key, HKEY& primaryKey, kwsys_stl::string& second, kwsys_stl::string& valuename) { kwsys_stl::string primary = key; size_t start = primary.find('\\'); if (start == kwsys_stl::string::npos) { return false; } size_t valuenamepos = primary.find(';'); if (valuenamepos != kwsys_stl::string::npos) { valuename = primary.substr(valuenamepos+1); } second = primary.substr(start+1, valuenamepos-start-1); primary = primary.substr(0, start); if (primary == "HKEY_CURRENT_USER") { primaryKey = HKEY_CURRENT_USER; } if (primary == "HKEY_CURRENT_CONFIG") { primaryKey = HKEY_CURRENT_CONFIG; } if (primary == "HKEY_CLASSES_ROOT") { primaryKey = HKEY_CLASSES_ROOT; } if (primary == "HKEY_LOCAL_MACHINE") { primaryKey = HKEY_LOCAL_MACHINE; } if (primary == "HKEY_USERS") { primaryKey = HKEY_USERS; } return true; } static DWORD SystemToolsMakeRegistryMode(DWORD mode, SystemTools::KeyWOW64 view) { // only add the modes when on a system that supports Wow64. static FARPROC wow64p = GetProcAddress(GetModuleHandleW(L"kernel32"), "IsWow64Process"); if(wow64p == NULL) { return mode; } if(view == SystemTools::KeyWOW64_32) { return mode | KWSYS_ST_KEY_WOW64_32KEY; } else if(view == SystemTools::KeyWOW64_64) { return mode | KWSYS_ST_KEY_WOW64_64KEY; } return mode; } #endif #if defined(_WIN32) && !defined(__CYGWIN__) bool SystemTools::GetRegistrySubKeys(const kwsys_stl::string& key, kwsys_stl::vector<kwsys_stl::string>& subkeys, KeyWOW64 view) { HKEY primaryKey = HKEY_CURRENT_USER; kwsys_stl::string second; kwsys_stl::string valuename; if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename)) { return false; } HKEY hKey; if(RegOpenKeyExW(primaryKey, Encoding::ToWide(second).c_str(), 0, SystemToolsMakeRegistryMode(KEY_READ, view), &hKey) != ERROR_SUCCESS) { return false; } else { wchar_t name[1024]; DWORD dwNameSize = sizeof(name)/sizeof(name[0]); DWORD i = 0; while (RegEnumKeyW(hKey, i, name, dwNameSize) == ERROR_SUCCESS) { subkeys.push_back(Encoding::ToNarrow(name)); ++i; } RegCloseKey(hKey); } return true; } #else bool SystemTools::GetRegistrySubKeys(const kwsys_stl::string&, kwsys_stl::vector<kwsys_stl::string>&, KeyWOW64) { return false; } #endif // Read a registry value. // Example : // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath // => will return the data of the "default" value of the key // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root // => will return the data of the "Root" value of the key #if defined(_WIN32) && !defined(__CYGWIN__) bool SystemTools::ReadRegistryValue(const kwsys_stl::string& key, kwsys_stl::string &value, KeyWOW64 view) { bool valueset = false; HKEY primaryKey = HKEY_CURRENT_USER; kwsys_stl::string second; kwsys_stl::string valuename; if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename)) { return false; } HKEY hKey; if(RegOpenKeyExW(primaryKey, Encoding::ToWide(second).c_str(), 0, SystemToolsMakeRegistryMode(KEY_READ, view), &hKey) != ERROR_SUCCESS) { return false; } else { DWORD dwType, dwSize; dwSize = 1023; wchar_t data[1024]; if(RegQueryValueExW(hKey, Encoding::ToWide(valuename).c_str(), NULL, &dwType, (BYTE *)data, &dwSize) == ERROR_SUCCESS) { if (dwType == REG_SZ) { value = Encoding::ToNarrow(data); valueset = true; } else if (dwType == REG_EXPAND_SZ) { wchar_t expanded[1024]; DWORD dwExpandedSize = sizeof(expanded)/sizeof(expanded[0]); if(ExpandEnvironmentStringsW(data, expanded, dwExpandedSize)) { value = Encoding::ToNarrow(expanded); valueset = true; } } } RegCloseKey(hKey); } return valueset; } #else bool SystemTools::ReadRegistryValue(const kwsys_stl::string&, kwsys_stl::string &, KeyWOW64) { return false; } #endif // Write a registry value. // Example : // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath // => will set the data of the "default" value of the key // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root // => will set the data of the "Root" value of the key #if defined(_WIN32) && !defined(__CYGWIN__) bool SystemTools::WriteRegistryValue(const kwsys_stl::string& key, const kwsys_stl::string& value, KeyWOW64 view) { HKEY primaryKey = HKEY_CURRENT_USER; kwsys_stl::string second; kwsys_stl::string valuename; if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename)) { return false; } HKEY hKey; DWORD dwDummy; wchar_t lpClass[] = L""; if(RegCreateKeyExW(primaryKey, Encoding::ToWide(second).c_str(), 0, lpClass, REG_OPTION_NON_VOLATILE, SystemToolsMakeRegistryMode(KEY_WRITE, view), NULL, &hKey, &dwDummy) != ERROR_SUCCESS) { return false; } std::wstring wvalue = Encoding::ToWide(value); if(RegSetValueExW(hKey, Encoding::ToWide(valuename).c_str(), 0, REG_SZ, (CONST BYTE *)wvalue.c_str(), (DWORD)(sizeof(wchar_t) * (wvalue.size() + 1))) == ERROR_SUCCESS) { return true; } return false; } #else bool SystemTools::WriteRegistryValue(const kwsys_stl::string&, const kwsys_stl::string&, KeyWOW64) { return false; } #endif // Delete a registry value. // Example : // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath // => will delete the data of the "default" value of the key // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root // => will delete the data of the "Root" value of the key #if defined(_WIN32) && !defined(__CYGWIN__) bool SystemTools::DeleteRegistryValue(const kwsys_stl::string& key, KeyWOW64 view) { HKEY primaryKey = HKEY_CURRENT_USER; kwsys_stl::string second; kwsys_stl::string valuename; if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename)) { return false; } HKEY hKey; if(RegOpenKeyExW(primaryKey, Encoding::ToWide(second).c_str(), 0, SystemToolsMakeRegistryMode(KEY_WRITE, view), &hKey) != ERROR_SUCCESS) { return false; } else { if(RegDeleteValue(hKey, (LPTSTR)valuename.c_str()) == ERROR_SUCCESS) { RegCloseKey(hKey); return true; } } return false; } #else bool SystemTools::DeleteRegistryValue(const kwsys_stl::string&, KeyWOW64) { return false; } #endif bool SystemTools::SameFile(const kwsys_stl::string& file1, const kwsys_stl::string& file2) { #ifdef _WIN32 HANDLE hFile1, hFile2; hFile1 = CreateFileW( Encoding::ToWide(file1).c_str(), GENERIC_READ, FILE_SHARE_READ , NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL ); hFile2 = CreateFileW( Encoding::ToWide(file2).c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL ); if( hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE) { if(hFile1 != INVALID_HANDLE_VALUE) { CloseHandle(hFile1); } if(hFile2 != INVALID_HANDLE_VALUE) { CloseHandle(hFile2); } return false; } BY_HANDLE_FILE_INFORMATION fiBuf1; BY_HANDLE_FILE_INFORMATION fiBuf2; GetFileInformationByHandle( hFile1, &fiBuf1 ); GetFileInformationByHandle( hFile2, &fiBuf2 ); CloseHandle(hFile1); CloseHandle(hFile2); return (fiBuf1.dwVolumeSerialNumber == fiBuf2.dwVolumeSerialNumber && fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh && fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow); #else struct stat fileStat1, fileStat2; if (stat(file1.c_str(), &fileStat1) == 0 && stat(file2.c_str(), &fileStat2) == 0) { // see if the files are the same file // check the device inode and size if(memcmp(&fileStat2.st_dev, &fileStat1.st_dev, sizeof(fileStat1.st_dev)) == 0 && memcmp(&fileStat2.st_ino, &fileStat1.st_ino, sizeof(fileStat1.st_ino)) == 0 && fileStat2.st_size == fileStat1.st_size ) { return true; } } return false; #endif } //---------------------------------------------------------------------------- bool SystemTools::FileExists(const char* filename) { if(!filename) { return false; } return SystemTools::FileExists(kwsys_stl::string(filename)); } //---------------------------------------------------------------------------- bool SystemTools::FileExists(const kwsys_stl::string& filename) { if(filename.empty()) { return false; } #if defined(__CYGWIN__) // Convert filename to native windows path if possible. char winpath[MAX_PATH]; if(SystemTools::PathCygwinToWin32(filename.c_str(), winpath)) { return (GetFileAttributesA(winpath) != INVALID_FILE_ATTRIBUTES); } return access(filename.c_str(), R_OK) == 0; #elif defined(_WIN32) return (GetFileAttributesW( SystemTools::ConvertToWindowsExtendedPath(filename).c_str()) != INVALID_FILE_ATTRIBUTES); #else return access(filename.c_str(), R_OK) == 0; #endif } //---------------------------------------------------------------------------- bool SystemTools::FileExists(const char* filename, bool isFile) { if(SystemTools::FileExists(filename)) { // If isFile is set return not FileIsDirectory, // so this will only be true if it is a file return !isFile || !SystemTools::FileIsDirectory(filename); } return false; } //---------------------------------------------------------------------------- bool SystemTools::FileExists(const kwsys_stl::string& filename, bool isFile) { if(SystemTools::FileExists(filename)) { // If isFile is set return not FileIsDirectory, // so this will only be true if it is a file return !isFile || !SystemTools::FileIsDirectory(filename); } return false; } //---------------------------------------------------------------------------- #ifdef __CYGWIN__ bool SystemTools::PathCygwinToWin32(const char *path, char *win32_path) { SystemToolsTranslationMap::iterator i = SystemTools::Cyg2Win32Map->find(path); if (i != SystemTools::Cyg2Win32Map->end()) { strncpy(win32_path, i->second.c_str(), MAX_PATH); } else { if(cygwin_conv_path(CCP_POSIX_TO_WIN_A, path, win32_path, MAX_PATH) != 0) { win32_path[0] = 0; } SystemToolsTranslationMap::value_type entry(path, win32_path); SystemTools::Cyg2Win32Map->insert(entry); } return win32_path[0] != 0; } #endif bool SystemTools::Touch(const kwsys_stl::string& filename, bool create) { if (!SystemTools::FileExists(filename)) { if(create) { FILE* file = Fopen(filename, "a+b"); if(file) { fclose(file); return true; } return false; } else { return true; } } #if defined(_WIN32) && !defined(__CYGWIN__) HANDLE h = CreateFileW( SystemTools::ConvertToWindowsExtendedPath(filename).c_str(), FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0); if(!h) { return false; } FILETIME mtime; GetSystemTimeAsFileTime(&mtime); if(!SetFileTime(h, 0, 0, &mtime)) { CloseHandle(h); return false; } CloseHandle(h); #elif KWSYS_CXX_HAS_UTIMENSAT struct timespec times[2] = {{0,UTIME_OMIT},{0,UTIME_NOW}}; if(utimensat(AT_FDCWD, filename.c_str(), times, 0) < 0) { return false; } #else struct stat st; if(stat(filename.c_str(), &st) < 0) { return false; } struct timeval mtime; gettimeofday(&mtime, 0); # if KWSYS_CXX_HAS_UTIMES struct timeval times[2] = { # if KWSYS_STAT_HAS_ST_MTIM {st.st_atim.tv_sec, st.st_atim.tv_nsec/1000}, /* tv_sec, tv_usec */ # else {st.st_atime, 0}, # endif mtime }; if(utimes(filename.c_str(), times) < 0) { return false; } # else struct utimbuf times = {st.st_atime, mtime.tv_sec}; if(utime(filename.c_str(), &times) < 0) { return false; } # endif #endif return true; } bool SystemTools::FileTimeCompare(const kwsys_stl::string& f1, const kwsys_stl::string& f2, int* result) { // Default to same time. *result = 0; #if !defined(_WIN32) || defined(__CYGWIN__) // POSIX version. Use stat function to get file modification time. struct stat s1; if(stat(f1.c_str(), &s1) != 0) { return false; } struct stat s2; if(stat(f2.c_str(), &s2) != 0) { return false; } # if KWSYS_STAT_HAS_ST_MTIM // Compare using nanosecond resolution. if(s1.st_mtim.tv_sec < s2.st_mtim.tv_sec) { *result = -1; } else if(s1.st_mtim.tv_sec > s2.st_mtim.tv_sec) { *result = 1; } else if(s1.st_mtim.tv_nsec < s2.st_mtim.tv_nsec) { *result = -1; } else if(s1.st_mtim.tv_nsec > s2.st_mtim.tv_nsec) { *result = 1; } # else // Compare using 1 second resolution. if(s1.st_mtime < s2.st_mtime) { *result = -1; } else if(s1.st_mtime > s2.st_mtime) { *result = 1; } # endif #else // Windows version. Get the modification time from extended file attributes. WIN32_FILE_ATTRIBUTE_DATA f1d; WIN32_FILE_ATTRIBUTE_DATA f2d; if(!GetFileAttributesExW( SystemTools::ConvertToWindowsExtendedPath(f1).c_str(), GetFileExInfoStandard, &f1d)) { return false; } if(!GetFileAttributesExW( SystemTools::ConvertToWindowsExtendedPath(f2).c_str(), GetFileExInfoStandard, &f2d)) { return false; } // Compare the file times using resolution provided by system call. *result = (int)CompareFileTime(&f1d.ftLastWriteTime, &f2d.ftLastWriteTime); #endif return true; } // Return a capitalized string (i.e the first letter is uppercased, all other // are lowercased) kwsys_stl::string SystemTools::Capitalized(const kwsys_stl::string& s) { kwsys_stl::string n; if(s.empty()) { return n; } n.resize(s.size()); n[0] = static_cast<kwsys_stl::string::value_type>(toupper(s[0])); for (size_t i = 1; i < s.size(); i++) { n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i])); } return n; } // Return capitalized words kwsys_stl::string SystemTools::CapitalizedWords(const kwsys_stl::string& s) { kwsys_stl::string n(s); for (size_t i = 0; i < s.size(); i++) { #if defined(_MSC_VER) && defined (_MT) && defined (_DEBUG) // MS has an assert that will fail if s[i] < 0; setting // LC_CTYPE using setlocale() does *not* help. Painful. if ((int)s[i] >= 0 && isalpha(s[i]) && (i == 0 || ((int)s[i - 1] >= 0 && isspace(s[i - 1])))) #else if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1]))) #endif { n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i])); } } return n; } // Return uncapitalized words kwsys_stl::string SystemTools::UnCapitalizedWords(const kwsys_stl::string& s) { kwsys_stl::string n(s); for (size_t i = 0; i < s.size(); i++) { #if defined(_MSC_VER) && defined (_MT) && defined (_DEBUG) // MS has an assert that will fail if s[i] < 0; setting // LC_CTYPE using setlocale() does *not* help. Painful. if ((int)s[i] >= 0 && isalpha(s[i]) && (i == 0 || ((int)s[i - 1] >= 0 && isspace(s[i - 1])))) #else if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1]))) #endif { n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i])); } } return n; } // only works for words with at least two letters kwsys_stl::string SystemTools::AddSpaceBetweenCapitalizedWords( const kwsys_stl::string& s) { kwsys_stl::string n; if (!s.empty()) { n.reserve(s.size()); n += s[0]; for (size_t i = 1; i < s.size(); i++) { if (isupper(s[i]) && !isspace(s[i - 1]) && !isupper(s[i - 1])) { n += ' '; } n += s[i]; } } return n; } char* SystemTools::AppendStrings(const char* str1, const char* str2) { if (!str1) { return SystemTools::DuplicateString(str2); } if (!str2) { return SystemTools::DuplicateString(str1); } size_t len1 = strlen(str1); char *newstr = new char[len1 + strlen(str2) + 1]; if (!newstr) { return 0; } strcpy(newstr, str1); strcat(newstr + len1, str2); return newstr; } char* SystemTools::AppendStrings( const char* str1, const char* str2, const char* str3) { if (!str1) { return SystemTools::AppendStrings(str2, str3); } if (!str2) { return SystemTools::AppendStrings(str1, str3); } if (!str3) { return SystemTools::AppendStrings(str1, str2); } size_t len1 = strlen(str1), len2 = strlen(str2); char *newstr = new char[len1 + len2 + strlen(str3) + 1]; if (!newstr) { return 0; } strcpy(newstr, str1); strcat(newstr + len1, str2); strcat(newstr + len1 + len2, str3); return newstr; } // Return a lower case string kwsys_stl::string SystemTools::LowerCase(const kwsys_stl::string& s) { kwsys_stl::string n; n.resize(s.size()); for (size_t i = 0; i < s.size(); i++) { n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i])); } return n; } // Return a lower case string kwsys_stl::string SystemTools::UpperCase(const kwsys_stl::string& s) { kwsys_stl::string n; n.resize(s.size()); for (size_t i = 0; i < s.size(); i++) { n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i])); } return n; } // Count char in string size_t SystemTools::CountChar(const char* str, char c) { size_t count = 0; if (str) { while (*str) { if (*str == c) { ++count; } ++str; } } return count; } // Remove chars in string char* SystemTools::RemoveChars(const char* str, const char *toremove) { if (!str) { return NULL; } char *clean_str = new char [strlen(str) + 1]; char *ptr = clean_str; while (*str) { const char *str2 = toremove; while (*str2 && *str != *str2) { ++str2; } if (!*str2) { *ptr++ = *str; } ++str; } *ptr = '\0'; return clean_str; } // Remove chars in string char* SystemTools::RemoveCharsButUpperHex(const char* str) { if (!str) { return 0; } char *clean_str = new char [strlen(str) + 1]; char *ptr = clean_str; while (*str) { if ((*str >= '0' && *str <= '9') || (*str >= 'A' && *str <= 'F')) { *ptr++ = *str; } ++str; } *ptr = '\0'; return clean_str; } // Replace chars in string char* SystemTools::ReplaceChars(char* str, const char *toreplace, char replacement) { if (str) { char *ptr = str; while (*ptr) { const char *ptr2 = toreplace; while (*ptr2) { if (*ptr == *ptr2) { *ptr = replacement; } ++ptr2; } ++ptr; } } return str; } // Returns if string starts with another string bool SystemTools::StringStartsWith(const char* str1, const char* str2) { if (!str1 || !str2) { return false; } size_t len1 = strlen(str1), len2 = strlen(str2); return len1 >= len2 && !strncmp(str1, str2, len2) ? true : false; } // Returns if string starts with another string bool SystemTools::StringStartsWith(const kwsys_stl::string& str1, const char* str2) { if (!str2) { return false; } size_t len1 = str1.size(), len2 = strlen(str2); return len1 >= len2 && !strncmp(str1.c_str(), str2, len2) ? true : false; } // Returns if string ends with another string bool SystemTools::StringEndsWith(const char* str1, const char* str2) { if (!str1 || !str2) { return false; } size_t len1 = strlen(str1), len2 = strlen(str2); return len1 >= len2 && !strncmp(str1 + (len1 - len2), str2, len2) ? true : false; } // Returns if string ends with another string bool SystemTools::StringEndsWith(const kwsys_stl::string& str1, const char* str2) { if (!str2) { return false; } size_t len1 = str1.size(), len2 = strlen(str2); return len1 >= len2 && !strncmp(str1.c_str() + (len1 - len2), str2, len2) ? true : false; } // Returns a pointer to the last occurence of str2 in str1 const char* SystemTools::FindLastString(const char* str1, const char* str2) { if (!str1 || !str2) { return NULL; } size_t len1 = strlen(str1), len2 = strlen(str2); if (len1 >= len2) { const char *ptr = str1 + len1 - len2; do { if (!strncmp(ptr, str2, len2)) { return ptr; } } while (ptr-- != str1); } return NULL; } // Duplicate string char* SystemTools::DuplicateString(const char* str) { if (str) { char *newstr = new char [strlen(str) + 1]; return strcpy(newstr, str); } return NULL; } // Return a cropped string kwsys_stl::string SystemTools::CropString(const kwsys_stl::string& s, size_t max_len) { if (!s.size() || max_len == 0 || max_len >= s.size()) { return s; } kwsys_stl::string n; n.reserve(max_len); size_t middle = max_len / 2; n += s.substr(0, middle); n += s.substr(s.size() - (max_len - middle), kwsys_stl::string::npos); if (max_len > 2) { n[middle] = '.'; if (max_len > 3) { n[middle - 1] = '.'; if (max_len > 4) { n[middle + 1] = '.'; } } } return n; } //---------------------------------------------------------------------------- kwsys_stl::vector<kwsys::String> SystemTools::SplitString(const kwsys_stl::string& p, char sep, bool isPath) { kwsys_stl::string path = p; kwsys_stl::vector<kwsys::String> paths; if(path.empty()) { return paths; } if(isPath && path[0] == '/') { path.erase(path.begin()); paths.push_back("/"); } kwsys_stl::string::size_type pos1 = 0; kwsys_stl::string::size_type pos2 = path.find(sep, pos1+1); while(pos2 != kwsys_stl::string::npos) { paths.push_back(path.substr(pos1, pos2-pos1)); pos1 = pos2+1; pos2 = path.find(sep, pos1+1); } paths.push_back(path.substr(pos1, pos2-pos1)); return paths; } //---------------------------------------------------------------------------- int SystemTools::EstimateFormatLength(const char *format, va_list ap) { if (!format) { return 0; } // Quick-hack attempt at estimating the length of the string. // Should never under-estimate. // Start with the length of the format string itself. size_t length = strlen(format); // Increase the length for every argument in the format. const char* cur = format; while(*cur) { if(*cur++ == '%') { // Skip "%%" since it doesn't correspond to a va_arg. if(*cur != '%') { while(!int(isalpha(*cur))) { ++cur; } switch (*cur) { case 's': { // Check the length of the string. char* s = va_arg(ap, char*); if(s) { length += strlen(s); } } break; case 'e': case 'f': case 'g': { // Assume the argument contributes no more than 64 characters. length += 64; // Eat the argument. static_cast<void>(va_arg(ap, double)); } break; default: { // Assume the argument contributes no more than 64 characters. length += 64; // Eat the argument. static_cast<void>(va_arg(ap, int)); } break; } } // Move past the characters just tested. ++cur; } } return static_cast<int>(length); } kwsys_stl::string SystemTools::EscapeChars( const char *str, const char *chars_to_escape, char escape_char) { kwsys_stl::string n; if (str) { if (!chars_to_escape || !*chars_to_escape) { n.append(str); } else { n.reserve(strlen(str)); while (*str) { const char *ptr = chars_to_escape; while (*ptr) { if (*str == *ptr) { n += escape_char; break; } ++ptr; } n += *str; ++str; } } } return n; } #ifdef __VMS static void ConvertVMSToUnix(kwsys_stl::string& path) { kwsys_stl::string::size_type rootEnd = path.find(":["); kwsys_stl::string::size_type pathEnd = path.find("]"); if(rootEnd != path.npos) { kwsys_stl::string root = path.substr(0, rootEnd); kwsys_stl::string pathPart = path.substr(rootEnd+2, pathEnd - rootEnd-2); const char* pathCString = pathPart.c_str(); const char* pos0 = pathCString; for (kwsys_stl::string::size_type pos = 0; *pos0; ++ pos ) { if ( *pos0 == '.' ) { pathPart[pos] = '/'; } pos0 ++; } path = "/"+ root + "/" + pathPart; } } #endif // convert windows slashes to unix slashes void SystemTools::ConvertToUnixSlashes(kwsys_stl::string& path) { const char* pathCString = path.c_str(); bool hasDoubleSlash = false; #ifdef __VMS ConvertVMSToUnix(path); #else const char* pos0 = pathCString; const char* pos1 = pathCString+1; for (kwsys_stl::string::size_type pos = 0; *pos0; ++ pos ) { // make sure we don't convert an escaped space to a unix slash if ( *pos0 == '\\' && *pos1 != ' ' ) { path[pos] = '/'; } // Also, reuse the loop to check for slash followed by another slash if (*pos1 == '/' && *(pos1+1) == '/' && !hasDoubleSlash) { #ifdef _WIN32 // However, on windows if the first characters are both slashes, // then keep them that way, so that network paths can be handled. if ( pos > 0) { hasDoubleSlash = true; } #else hasDoubleSlash = true; #endif } pos0 ++; pos1 ++; } if ( hasDoubleSlash ) { SystemTools::ReplaceString(path, "//", "/"); } #endif // remove any trailing slash if(!path.empty()) { // if there is a tilda ~ then replace it with HOME pathCString = path.c_str(); if(pathCString[0] == '~' && (pathCString[1] == '/' || pathCString[1] == '\0')) { const char* homeEnv = SystemTools::GetEnv("HOME"); if (homeEnv) { path.replace(0,1,homeEnv); } } #ifdef HAVE_GETPWNAM else if(pathCString[0] == '~') { kwsys_stl::string::size_type idx = path.find_first_of("/\0"); kwsys_stl::string user = path.substr(1, idx-1); passwd* pw = getpwnam(user.c_str()); if(pw) { path.replace(0, idx, pw->pw_dir); } } #endif // remove trailing slash if the path is more than // a single / pathCString = path.c_str(); size_t size = path.size(); if(size > 1 && *path.rbegin() == '/') { // if it is c:/ then do not remove the trailing slash if(!((size == 3 && pathCString[1] == ':'))) { path.resize(size - 1); } } } } #ifdef _WIN32 // Convert local paths to UNC style paths kwsys_stl::wstring SystemTools::ConvertToWindowsExtendedPath(const kwsys_stl::string &source) { kwsys_stl::wstring wsource = Encoding::ToWide(source); // Resolve any relative paths DWORD wfull_len; /* The +3 is a workaround for a bug in some versions of GetFullPathNameW that * won't return a large enough buffer size if the input is too small */ wfull_len = GetFullPathNameW(wsource.c_str(), 0, NULL, NULL) + 3; kwsys_stl::vector<wchar_t> wfull(wfull_len); GetFullPathNameW(wsource.c_str(), wfull_len, &wfull[0], NULL); /* This should get the correct size without any extra padding from the * previous size workaround. */ wfull_len = static_cast<DWORD>(wcslen(&wfull[0])); if(wfull_len >= 2 && isalpha(wfull[0]) && wfull[1] == L':') { /* C:\Foo\bar\FooBar.txt */ return L"\\\\?\\" + kwsys_stl::wstring(&wfull[0]); } else if(wfull_len >= 2 && wfull[0] == L'\\' && wfull[1] == L'\\') { /* Starts with \\ */ if(wfull_len >= 4 && wfull[2] == L'?' && wfull[3] == L'\\') { /* Starts with \\?\ */ if(wfull_len >= 8 && wfull[4] == L'U' && wfull[5] == L'N' && wfull[6] == L'C' && wfull[7] == L'\\') { /* \\?\UNC\Foo\bar\FooBar.txt */ return kwsys_stl::wstring(&wfull[0]); } else if(wfull_len >= 6 && isalpha(wfull[4]) && wfull[5] == L':') { /* \\?\C:\Foo\bar\FooBar.txt */ return kwsys_stl::wstring(&wfull[0]); } else if(wfull_len >= 5) { /* \\?\Foo\bar\FooBar.txt */ return L"\\\\?\\UNC\\" + kwsys_stl::wstring(&wfull[4]); } } else if(wfull_len >= 4 && wfull[2] == L'.' && wfull[3] == L'\\') { /* Starts with \\.\ a device name */ if(wfull_len >= 6 && isalpha(wfull[4]) && wfull[5] == L':') { /* \\.\C:\Foo\bar\FooBar.txt */ return L"\\\\?\\" + kwsys_stl::wstring(&wfull[4]); } else if(wfull_len >= 5) { /* \\.\Foo\bar\ Device name is left unchanged */ return kwsys_stl::wstring(&wfull[0]); } } else if(wfull_len >= 3) { /* \\Foo\bar\FooBar.txt */ return L"\\\\?\\UNC\\" + kwsys_stl::wstring(&wfull[2]); } } // If this case has been reached, then the path is invalid. Leave it // unchanged return Encoding::ToWide(source); } #endif // change // to /, and escape any spaces in the path kwsys_stl::string SystemTools::ConvertToUnixOutputPath(const kwsys_stl::string& path) { kwsys_stl::string ret = path; // remove // except at the beginning might be a cygwin drive kwsys_stl::string::size_type pos=1; while((pos = ret.find("//", pos)) != kwsys_stl::string::npos) { ret.erase(pos, 1); } // escape spaces and () in the path if(ret.find_first_of(" ") != kwsys_stl::string::npos) { kwsys_stl::string result = ""; char lastch = 1; for(const char* ch = ret.c_str(); *ch != '\0'; ++ch) { // if it is already escaped then don't try to escape it again if((*ch == ' ') && lastch != '\\') { result += '\\'; } result += *ch; lastch = *ch; } ret = result; } return ret; } kwsys_stl::string SystemTools::ConvertToOutputPath(const kwsys_stl::string& path) { #if defined(_WIN32) && !defined(__CYGWIN__) return SystemTools::ConvertToWindowsOutputPath(path); #else return SystemTools::ConvertToUnixOutputPath(path); #endif } // remove double slashes not at the start kwsys_stl::string SystemTools::ConvertToWindowsOutputPath(const kwsys_stl::string& path) { kwsys_stl::string ret; // make it big enough for all of path and double quotes ret.reserve(path.size()+3); // put path into the string ret = path; kwsys_stl::string::size_type pos = 0; // first convert all of the slashes while((pos = ret.find('/', pos)) != kwsys_stl::string::npos) { ret[pos] = '\\'; pos++; } // check for really small paths if(ret.size() < 2) { return ret; } // now clean up a bit and remove double slashes // Only if it is not the first position in the path which is a network // path on windows pos = 1; // start at position 1 if(ret[0] == '\"') { pos = 2; // if the string is already quoted then start at 2 if(ret.size() < 3) { return ret; } } while((pos = ret.find("\\\\", pos)) != kwsys_stl::string::npos) { ret.erase(pos, 1); } // now double quote the path if it has spaces in it // and is not already double quoted if(ret.find(' ') != kwsys_stl::string::npos && ret[0] != '\"') { ret.insert(static_cast<kwsys_stl::string::size_type>(0), static_cast<kwsys_stl::string::size_type>(1), '\"'); ret.append(1, '\"'); } return ret; } bool SystemTools::CopyFileIfDifferent(const kwsys_stl::string& source, const kwsys_stl::string& destination) { // special check for a destination that is a directory // FilesDiffer does not handle file to directory compare if(SystemTools::FileIsDirectory(destination)) { kwsys_stl::string new_destination = destination; SystemTools::ConvertToUnixSlashes(new_destination); new_destination += '/'; kwsys_stl::string source_name = source; new_destination += SystemTools::GetFilenameName(source_name); if(SystemTools::FilesDiffer(source, new_destination)) { return SystemTools::CopyFileAlways(source, destination); } else { // the files are the same so the copy is done return // true return true; } } // source and destination are files so do a copy if they // are different if(SystemTools::FilesDiffer(source, destination)) { return SystemTools::CopyFileAlways(source, destination); } // at this point the files must be the same so return true return true; } #define KWSYS_ST_BUFFER 4096 bool SystemTools::FilesDiffer(const kwsys_stl::string& source, const kwsys_stl::string& destination) { #if defined(_WIN32) WIN32_FILE_ATTRIBUTE_DATA statSource; if (GetFileAttributesExW( SystemTools::ConvertToWindowsExtendedPath(source).c_str(), GetFileExInfoStandard, &statSource) == 0) { return true; } WIN32_FILE_ATTRIBUTE_DATA statDestination; if (GetFileAttributesExW( SystemTools::ConvertToWindowsExtendedPath(destination).c_str(), GetFileExInfoStandard, &statDestination) == 0) { return true; } if(statSource.nFileSizeHigh != statDestination.nFileSizeHigh || statSource.nFileSizeLow != statDestination.nFileSizeLow) { return true; } if(statSource.nFileSizeHigh == 0 && statSource.nFileSizeLow == 0) { return false; } off_t nleft = ((__int64)statSource.nFileSizeHigh << 32) + statSource.nFileSizeLow; #else struct stat statSource; if (stat(source.c_str(), &statSource) != 0) { return true; } struct stat statDestination; if (stat(destination.c_str(), &statDestination) != 0) { return true; } if(statSource.st_size != statDestination.st_size) { return true; } if(statSource.st_size == 0) { return false; } off_t nleft = statSource.st_size; #endif #if defined(_WIN32) kwsys::ifstream finSource(source.c_str(), (kwsys_ios::ios::binary | kwsys_ios::ios::in)); kwsys::ifstream finDestination(destination.c_str(), (kwsys_ios::ios::binary | kwsys_ios::ios::in)); #else kwsys::ifstream finSource(source.c_str()); kwsys::ifstream finDestination(destination.c_str()); #endif if(!finSource || !finDestination) { return true; } // Compare the files a block at a time. char source_buf[KWSYS_ST_BUFFER]; char dest_buf[KWSYS_ST_BUFFER]; while(nleft > 0) { // Read a block from each file. kwsys_ios::streamsize nnext = (nleft > KWSYS_ST_BUFFER)? KWSYS_ST_BUFFER : static_cast<kwsys_ios::streamsize>(nleft); finSource.read(source_buf, nnext); finDestination.read(dest_buf, nnext); // If either failed to read assume they are different. if(static_cast<kwsys_ios::streamsize>(finSource.gcount()) != nnext || static_cast<kwsys_ios::streamsize>(finDestination.gcount()) != nnext) { return true; } // If this block differs the file differs. if(memcmp(static_cast<const void*>(source_buf), static_cast<const void*>(dest_buf), static_cast<size_t>(nnext)) != 0) { return true; } // Update the byte count remaining. nleft -= nnext; } // No differences found. return false; } //---------------------------------------------------------------------------- /** * Copy a file named by "source" to the file named by "destination". */ bool SystemTools::CopyFileAlways(const kwsys_stl::string& source, const kwsys_stl::string& destination) { // If files are the same do not copy if ( SystemTools::SameFile(source, destination) ) { return true; } mode_t perm = 0; bool perms = SystemTools::GetPermissions(source, perm); const int bufferSize = 4096; char buffer[bufferSize]; // If destination is a directory, try to create a file with the same // name as the source in that directory. kwsys_stl::string real_destination = destination; kwsys_stl::string destination_dir; if(SystemTools::FileExists(destination) && SystemTools::FileIsDirectory(destination)) { destination_dir = real_destination; SystemTools::ConvertToUnixSlashes(real_destination); real_destination += '/'; kwsys_stl::string source_name = source; real_destination += SystemTools::GetFilenameName(source_name); } else { destination_dir = SystemTools::GetFilenamePath(destination); } // Create destination directory SystemTools::MakeDirectory(destination_dir); // Open files #if defined(_WIN32) kwsys::ifstream fin(Encoding::ToNarrow( SystemTools::ConvertToWindowsExtendedPath(source)).c_str(), kwsys_ios::ios::in | kwsys_ios_binary); #else kwsys::ifstream fin(source.c_str(), kwsys_ios::ios::in | kwsys_ios_binary); #endif if(!fin) { return false; } // try and remove the destination file so that read only destination files // can be written to. // If the remove fails continue so that files in read only directories // that do not allow file removal can be modified. SystemTools::RemoveFile(real_destination); #if defined(_WIN32) kwsys::ofstream fout(Encoding::ToNarrow( SystemTools::ConvertToWindowsExtendedPath(real_destination)).c_str(), kwsys_ios::ios::out | kwsys_ios::ios::trunc | kwsys_ios_binary); #else kwsys::ofstream fout(real_destination.c_str(), kwsys_ios::ios::out | kwsys_ios::ios::trunc | kwsys_ios_binary); #endif if(!fout) { return false; } // This copy loop is very sensitive on certain platforms with // slightly broken stream libraries (like HPUX). Normally, it is // incorrect to not check the error condition on the fin.read() // before using the data, but the fin.gcount() will be zero if an // error occurred. Therefore, the loop should be safe everywhere. while(fin) { fin.read(buffer, bufferSize); if(fin.gcount()) { fout.write(buffer, fin.gcount()); } else { break; } } // Make sure the operating system has finished writing the file // before closing it. This will ensure the file is finished before // the check below. fout.flush(); fin.close(); fout.close(); if(!fout) { return false; } if ( perms ) { if ( !SystemTools::SetPermissions(real_destination, perm) ) { return false; } } return true; } //---------------------------------------------------------------------------- bool SystemTools::CopyAFile(const kwsys_stl::string& source, const kwsys_stl::string& destination, bool always) { if(always) { return SystemTools::CopyFileAlways(source, destination); } else { return SystemTools::CopyFileIfDifferent(source, destination); } } /** * Copy a directory content from "source" directory to the directory named by * "destination". */ bool SystemTools::CopyADirectory(const kwsys_stl::string& source, const kwsys_stl::string& destination, bool always) { Directory dir; #ifdef _WIN32 dir.Load(Encoding::ToNarrow( SystemTools::ConvertToWindowsExtendedPath(source))); #else dir.Load(source); #endif size_t fileNum; if ( !SystemTools::MakeDirectory(destination) ) { return false; } for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum) { if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") && strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),"..")) { kwsys_stl::string fullPath = source; fullPath += "/"; fullPath += dir.GetFile(static_cast<unsigned long>(fileNum)); if(SystemTools::FileIsDirectory(fullPath)) { kwsys_stl::string fullDestPath = destination; fullDestPath += "/"; fullDestPath += dir.GetFile(static_cast<unsigned long>(fileNum)); if (!SystemTools::CopyADirectory(fullPath, fullDestPath, always)) { return false; } } else { if(!SystemTools::CopyAFile(fullPath, destination, always)) { return false; } } } } return true; } // return size of file; also returns zero if no file exists unsigned long SystemTools::FileLength(const kwsys_stl::string& filename) { unsigned long length = 0; #ifdef _WIN32 WIN32_FILE_ATTRIBUTE_DATA fs; if (GetFileAttributesExW( SystemTools::ConvertToWindowsExtendedPath(filename).c_str(), GetFileExInfoStandard, &fs) != 0) { /* To support the full 64-bit file size, use fs.nFileSizeHigh * and fs.nFileSizeLow to construct the 64 bit size length = ((__int64)fs.nFileSizeHigh << 32) + fs.nFileSizeLow; */ length = static_cast<unsigned long>(fs.nFileSizeLow); } #else struct stat fs; if (stat(filename.c_str(), &fs) == 0) { length = static_cast<unsigned long>(fs.st_size); } #endif return length; } int SystemTools::Strucmp(const char *s1, const char *s2) { // lifted from Graphvis http://www.graphviz.org while ((*s1 != '\0') && (tolower(*s1) == tolower(*s2))) { s1++; s2++; } return tolower(*s1) - tolower(*s2); } // return file's modified time long int SystemTools::ModifiedTime(const kwsys_stl::string& filename) { long int mt = 0; #ifdef _WIN32 WIN32_FILE_ATTRIBUTE_DATA fs; if (GetFileAttributesExW( SystemTools::ConvertToWindowsExtendedPath(filename).c_str(), GetFileExInfoStandard, &fs) != 0) { mt = windows_filetime_to_posix_time(fs.ftLastWriteTime); } #else struct stat fs; if (stat(filename.c_str(), &fs) == 0) { mt = static_cast<long int>(fs.st_mtime); } #endif return mt; } // return file's creation time long int SystemTools::CreationTime(const kwsys_stl::string& filename) { long int ct = 0; #ifdef _WIN32 WIN32_FILE_ATTRIBUTE_DATA fs; if (GetFileAttributesExW( SystemTools::ConvertToWindowsExtendedPath(filename).c_str(), GetFileExInfoStandard, &fs) != 0) { ct = windows_filetime_to_posix_time(fs.ftCreationTime); } #else struct stat fs; if (stat(filename.c_str(), &fs) == 0) { ct = fs.st_ctime >= 0 ? static_cast<long int>(fs.st_ctime) : 0; } #endif return ct; } bool SystemTools::ConvertDateMacroString(const char *str, time_t *tmt) { if (!str || !tmt || strlen(str) > 11) { return false; } struct tm tmt2; // __DATE__ // The compilation date of the current source file. The date is a string // literal of the form Mmm dd yyyy. The month name Mmm is the same as for // dates generated by the library function asctime declared in TIME.H. // index: 012345678901 // format: Mmm dd yyyy // example: Dec 19 2003 static char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec"; char buffer[12]; strcpy(buffer, str); buffer[3] = 0; char *ptr = strstr(month_names, buffer); if (!ptr) { return false; } int month = static_cast<int>((ptr - month_names) / 3); int day = atoi(buffer + 4); int year = atoi(buffer + 7); tmt2.tm_isdst = -1; tmt2.tm_hour = 0; tmt2.tm_min = 0; tmt2.tm_sec = 0; tmt2.tm_wday = 0; tmt2.tm_yday = 0; tmt2.tm_mday = day; tmt2.tm_mon = month; tmt2.tm_year = year - 1900; *tmt = mktime(&tmt2); return true; } bool SystemTools::ConvertTimeStampMacroString(const char *str, time_t *tmt) { if (!str || !tmt || strlen(str) > 26) { return false; } struct tm tmt2; // __TIMESTAMP__ // The date and time of the last modification of the current source file, // expressed as a string literal in the form Ddd Mmm Date hh:mm:ss yyyy, /// where Ddd is the abbreviated day of the week and Date is an integer // from 1 to 31. // index: 0123456789 // 0123456789 // 0123456789 // format: Ddd Mmm Date hh:mm:ss yyyy // example: Fri Dec 19 14:34:58 2003 static char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec"; char buffer[27]; strcpy(buffer, str); buffer[7] = 0; char *ptr = strstr(month_names, buffer + 4); if (!ptr) { return false; } int month = static_cast<int>((ptr - month_names) / 3); int day = atoi(buffer + 8); int hour = atoi(buffer + 11); int min = atoi(buffer + 14); int sec = atoi(buffer + 17); int year = atoi(buffer + 20); tmt2.tm_isdst = -1; tmt2.tm_hour = hour; tmt2.tm_min = min; tmt2.tm_sec = sec; tmt2.tm_wday = 0; tmt2.tm_yday = 0; tmt2.tm_mday = day; tmt2.tm_mon = month; tmt2.tm_year = year - 1900; *tmt = mktime(&tmt2); return true; } kwsys_stl::string SystemTools::GetLastSystemError() { int e = errno; return strerror(e); } bool SystemTools::RemoveFile(const kwsys_stl::string& source) { #ifdef _WIN32 mode_t mode; if ( !SystemTools::GetPermissions(source, mode) ) { return false; } /* Win32 unlink is stupid --- it fails if the file is read-only */ SystemTools::SetPermissions(source, S_IWRITE); #endif #ifdef _WIN32 bool res = _wunlink(SystemTools::ConvertToWindowsExtendedPath(source).c_str()) == 0; #else bool res = unlink(source.c_str()) != 0 ? false : true; #endif #ifdef _WIN32 if ( !res ) { SystemTools::SetPermissions(source, mode); } #endif return res; } bool SystemTools::RemoveADirectory(const kwsys_stl::string& source) { // Add write permission to the directory so we can modify its // content to remove files and directories from it. mode_t mode; if(SystemTools::GetPermissions(source, mode)) { #if defined(_WIN32) && !defined(__CYGWIN__) mode |= S_IWRITE; #else mode |= S_IWUSR; #endif SystemTools::SetPermissions(source, mode); } Directory dir; #ifdef _WIN32 dir.Load(Encoding::ToNarrow( SystemTools::ConvertToWindowsExtendedPath(source))); #else dir.Load(source); #endif size_t fileNum; for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum) { if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") && strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),"..")) { kwsys_stl::string fullPath = source; fullPath += "/"; fullPath += dir.GetFile(static_cast<unsigned long>(fileNum)); if(SystemTools::FileIsDirectory(fullPath) && !SystemTools::FileIsSymlink(fullPath)) { if (!SystemTools::RemoveADirectory(fullPath)) { return false; } } else { if(!SystemTools::RemoveFile(fullPath)) { return false; } } } } return (Rmdir(source) == 0); } /** */ size_t SystemTools::GetMaximumFilePathLength() { return KWSYS_SYSTEMTOOLS_MAXPATH; } /** * Find the file the given name. Searches the given path and then * the system search path. Returns the full path to the file if it is * found. Otherwise, the empty string is returned. */ kwsys_stl::string SystemTools ::FindName(const kwsys_stl::string& name, const kwsys_stl::vector<kwsys_stl::string>& userPaths, bool no_system_path) { // Add the system search path to our path first kwsys_stl::vector<kwsys_stl::string> path; if (!no_system_path) { SystemTools::GetPath(path, "CMAKE_FILE_PATH"); SystemTools::GetPath(path); } // now add the additional paths { for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = userPaths.begin(); i != userPaths.end(); ++i) { path.push_back(*i); } } // Add a trailing slash to all paths to aid the search process. { for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin(); i != path.end(); ++i) { kwsys_stl::string& p = *i; if(p.empty() || *p.rbegin() != '/') { p += "/"; } } } // now look for the file kwsys_stl::string tryPath; for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin(); p != path.end(); ++p) { tryPath = *p; tryPath += name; if(SystemTools::FileExists(tryPath)) { return tryPath; } } // Couldn't find the file. return ""; } /** * Find the file the given name. Searches the given path and then * the system search path. Returns the full path to the file if it is * found. Otherwise, the empty string is returned. */ kwsys_stl::string SystemTools ::FindFile(const kwsys_stl::string& name, const kwsys_stl::vector<kwsys_stl::string>& userPaths, bool no_system_path) { kwsys_stl::string tryPath = SystemTools::FindName(name, userPaths, no_system_path); if(!tryPath.empty() && !SystemTools::FileIsDirectory(tryPath)) { return SystemTools::CollapseFullPath(tryPath); } // Couldn't find the file. return ""; } /** * Find the directory the given name. Searches the given path and then * the system search path. Returns the full path to the directory if it is * found. Otherwise, the empty string is returned. */ kwsys_stl::string SystemTools ::FindDirectory(const kwsys_stl::string& name, const kwsys_stl::vector<kwsys_stl::string>& userPaths, bool no_system_path) { kwsys_stl::string tryPath = SystemTools::FindName(name, userPaths, no_system_path); if(!tryPath.empty() && SystemTools::FileIsDirectory(tryPath)) { return SystemTools::CollapseFullPath(tryPath); } // Couldn't find the file. return ""; } /** * Find the executable with the given name. Searches the given path and then * the system search path. Returns the full path to the executable if it is * found. Otherwise, the empty string is returned. */ kwsys_stl::string SystemTools::FindProgram( const char* nameIn, const kwsys_stl::vector<kwsys_stl::string>& userPaths, bool no_system_path) { if(!nameIn || !*nameIn) { return ""; } return SystemTools::FindProgram(kwsys_stl::string(nameIn), userPaths, no_system_path); } kwsys_stl::string SystemTools::FindProgram( const kwsys_stl::string& name, const kwsys_stl::vector<kwsys_stl::string>& userPaths, bool no_system_path) { kwsys_stl::vector<kwsys_stl::string> extensions; #if defined (_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) bool hasExtension = false; // check to see if the name already has a .xxx at // the end of it if(name.size() > 3 && name[name.size()-4] == '.') { hasExtension = true; } // on windows try .com then .exe if(!hasExtension) { extensions.push_back(".com"); extensions.push_back(".exe"); } #endif kwsys_stl::string tryPath; // first try with extensions if the os supports them for(kwsys_stl::vector<kwsys_stl::string>::iterator i = extensions.begin(); i != extensions.end(); ++i) { tryPath = name; tryPath += *i; if(SystemTools::FileExists(tryPath) && !SystemTools::FileIsDirectory(tryPath)) { return SystemTools::CollapseFullPath(tryPath); } } // now try just the name tryPath = name; if(SystemTools::FileExists(tryPath) && !SystemTools::FileIsDirectory(tryPath)) { return SystemTools::CollapseFullPath(tryPath); } // now construct the path kwsys_stl::vector<kwsys_stl::string> path; // Add the system search path to our path. if (!no_system_path) { SystemTools::GetPath(path); } // now add the additional paths { for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = userPaths.begin(); i != userPaths.end(); ++i) { path.push_back(*i); } } // Add a trailing slash to all paths to aid the search process. { for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin(); i != path.end(); ++i) { kwsys_stl::string& p = *i; if(p.empty() || *p.rbegin() != '/') { p += "/"; } } } // Try each path for(kwsys_stl::vector<kwsys_stl::string>::iterator p = path.begin(); p != path.end(); ++p) { #ifdef _WIN32 // Remove double quotes from the path on windows SystemTools::ReplaceString(*p, "\"", ""); #endif // first try with extensions for(kwsys_stl::vector<kwsys_stl::string>::iterator ext = extensions.begin(); ext != extensions.end(); ++ext) { tryPath = *p; tryPath += name; tryPath += *ext; if(SystemTools::FileExists(tryPath) && !SystemTools::FileIsDirectory(tryPath)) { return SystemTools::CollapseFullPath(tryPath); } } // now try it without them tryPath = *p; tryPath += name; if(SystemTools::FileExists(tryPath) && !SystemTools::FileIsDirectory(tryPath)) { return SystemTools::CollapseFullPath(tryPath); } } // Couldn't find the program. return ""; } kwsys_stl::string SystemTools::FindProgram( const kwsys_stl::vector<kwsys_stl::string>& names, const kwsys_stl::vector<kwsys_stl::string>& path, bool noSystemPath) { for(kwsys_stl::vector<kwsys_stl::string>::const_iterator it = names.begin(); it != names.end() ; ++it) { // Try to find the program. kwsys_stl::string result = SystemTools::FindProgram(*it, path, noSystemPath); if ( !result.empty() ) { return result; } } return ""; } /** * Find the library with the given name. Searches the given path and then * the system search path. Returns the full path to the library if it is * found. Otherwise, the empty string is returned. */ kwsys_stl::string SystemTools ::FindLibrary(const kwsys_stl::string& name, const kwsys_stl::vector<kwsys_stl::string>& userPaths) { // See if the executable exists as written. if(SystemTools::FileExists(name) && !SystemTools::FileIsDirectory(name)) { return SystemTools::CollapseFullPath(name); } // Add the system search path to our path. kwsys_stl::vector<kwsys_stl::string> path; SystemTools::GetPath(path); // now add the additional paths { for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = userPaths.begin(); i != userPaths.end(); ++i) { path.push_back(*i); } } // Add a trailing slash to all paths to aid the search process. { for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin(); i != path.end(); ++i) { kwsys_stl::string& p = *i; if(p.empty() || *p.rbegin() != '/') { p += "/"; } } } kwsys_stl::string tryPath; for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin(); p != path.end(); ++p) { #if defined(__APPLE__) tryPath = *p; tryPath += name; tryPath += ".framework"; if(SystemTools::FileExists(tryPath) && SystemTools::FileIsDirectory(tryPath)) { return SystemTools::CollapseFullPath(tryPath); } #endif #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__MINGW32__) tryPath = *p; tryPath += name; tryPath += ".lib"; if(SystemTools::FileExists(tryPath) && !SystemTools::FileIsDirectory(tryPath)) { return SystemTools::CollapseFullPath(tryPath); } #else tryPath = *p; tryPath += "lib"; tryPath += name; tryPath += ".so"; if(SystemTools::FileExists(tryPath) && !SystemTools::FileIsDirectory(tryPath)) { return SystemTools::CollapseFullPath(tryPath); } tryPath = *p; tryPath += "lib"; tryPath += name; tryPath += ".a"; if(SystemTools::FileExists(tryPath) && !SystemTools::FileIsDirectory(tryPath)) { return SystemTools::CollapseFullPath(tryPath); } tryPath = *p; tryPath += "lib"; tryPath += name; tryPath += ".sl"; if(SystemTools::FileExists(tryPath) && !SystemTools::FileIsDirectory(tryPath)) { return SystemTools::CollapseFullPath(tryPath); } tryPath = *p; tryPath += "lib"; tryPath += name; tryPath += ".dylib"; if(SystemTools::FileExists(tryPath) && !SystemTools::FileIsDirectory(tryPath)) { return SystemTools::CollapseFullPath(tryPath); } tryPath = *p; tryPath += "lib"; tryPath += name; tryPath += ".dll"; if(SystemTools::FileExists(tryPath) && !SystemTools::FileIsDirectory(tryPath)) { return SystemTools::CollapseFullPath(tryPath); } #endif } // Couldn't find the library. return ""; } kwsys_stl::string SystemTools::GetRealPath(const kwsys_stl::string& path, kwsys_stl::string* errorMessage) { kwsys_stl::string ret; Realpath(path, ret, errorMessage); return ret; } bool SystemTools::FileIsDirectory(const kwsys_stl::string& inName) { if (inName.empty()) { return false; } size_t length = inName.size(); const char* name = inName.c_str(); // Remove any trailing slash from the name except in a root component. char local_buffer[KWSYS_SYSTEMTOOLS_MAXPATH]; std::string string_buffer; size_t last = length-1; if(last > 0 && (name[last] == '/' || name[last] == '\\') && strcmp(name, "/") != 0 && name[last-1] != ':') { if (last < sizeof(local_buffer)) { memcpy(local_buffer, name, last); local_buffer[last] = '\0'; name = local_buffer; } else { string_buffer.append(name, last); name = string_buffer.c_str(); } } // Now check the file node type. #if defined( _WIN32 ) DWORD attr = GetFileAttributesW( SystemTools::ConvertToWindowsExtendedPath(name).c_str()); if (attr != INVALID_FILE_ATTRIBUTES) { return (attr & FILE_ATTRIBUTE_DIRECTORY) != 0; #else struct stat fs; if(stat(name, &fs) == 0) { return S_ISDIR(fs.st_mode); #endif } else { return false; } } bool SystemTools::FileIsSymlink(const kwsys_stl::string& name) { #if defined( _WIN32 ) (void)name; return false; #else struct stat fs; if(lstat(name.c_str(), &fs) == 0) { return S_ISLNK(fs.st_mode); } else { return false; } #endif } #if defined(_WIN32) && !defined(__CYGWIN__) bool SystemTools::CreateSymlink(const kwsys_stl::string&, const kwsys_stl::string&) { return false; } #else bool SystemTools::CreateSymlink(const kwsys_stl::string& origName, const kwsys_stl::string& newName) { return symlink(origName.c_str(), newName.c_str()) >= 0; } #endif #if defined(_WIN32) && !defined(__CYGWIN__) bool SystemTools::ReadSymlink(const kwsys_stl::string&, kwsys_stl::string&) { return false; } #else bool SystemTools::ReadSymlink(const kwsys_stl::string& newName, kwsys_stl::string& origName) { char buf[KWSYS_SYSTEMTOOLS_MAXPATH+1]; int count = static_cast<int>(readlink(newName.c_str(), buf, KWSYS_SYSTEMTOOLS_MAXPATH)); if(count >= 0) { // Add null-terminator. buf[count] = 0; origName = buf; return true; } else { return false; } } #endif int SystemTools::ChangeDirectory(const kwsys_stl::string& dir) { return Chdir(dir); } kwsys_stl::string SystemTools::GetCurrentWorkingDirectory(bool collapse) { char buf[2048]; const char* cwd = Getcwd(buf, 2048); kwsys_stl::string path; if ( cwd ) { path = cwd; } if(collapse) { return SystemTools::CollapseFullPath(path); } return path; } kwsys_stl::string SystemTools::GetProgramPath(const kwsys_stl::string& in_name) { kwsys_stl::string dir, file; SystemTools::SplitProgramPath(in_name, dir, file); return dir; } bool SystemTools::SplitProgramPath(const kwsys_stl::string& in_name, kwsys_stl::string& dir, kwsys_stl::string& file, bool) { dir = in_name; file = ""; SystemTools::ConvertToUnixSlashes(dir); if(!SystemTools::FileIsDirectory(dir)) { kwsys_stl::string::size_type slashPos = dir.rfind("/"); if(slashPos != kwsys_stl::string::npos) { file = dir.substr(slashPos+1); dir = dir.substr(0, slashPos); } else { file = dir; dir = ""; } } if(!(dir.empty()) && !SystemTools::FileIsDirectory(dir)) { kwsys_stl::string oldDir = in_name; SystemTools::ConvertToUnixSlashes(oldDir); dir = in_name; return false; } return true; } bool SystemTools::FindProgramPath(const char* argv0, kwsys_stl::string& pathOut, kwsys_stl::string& errorMsg, const char* exeName, const char* buildDir, const char* installPrefix ) { kwsys_stl::vector<kwsys_stl::string> failures; kwsys_stl::string self = argv0 ? argv0 : ""; failures.push_back(self); SystemTools::ConvertToUnixSlashes(self); self = SystemTools::FindProgram(self); if(!SystemTools::FileExists(self)) { if(buildDir) { kwsys_stl::string intdir = "."; #ifdef CMAKE_INTDIR intdir = CMAKE_INTDIR; #endif self = buildDir; self += "/bin/"; self += intdir; self += "/"; self += exeName; self += SystemTools::GetExecutableExtension(); } } if(installPrefix) { if(!SystemTools::FileExists(self)) { failures.push_back(self); self = installPrefix; self += "/bin/"; self += exeName; } } if(!SystemTools::FileExists(self)) { failures.push_back(self); kwsys_ios::ostringstream msg; msg << "Can not find the command line program "; if (exeName) { msg << exeName; } msg << "\n"; if (argv0) { msg << " argv[0] = \"" << argv0 << "\"\n"; } msg << " Attempted paths:\n"; kwsys_stl::vector<kwsys_stl::string>::iterator i; for(i=failures.begin(); i != failures.end(); ++i) { msg << " \"" << *i << "\"\n"; } errorMsg = msg.str(); return false; } pathOut = self; return true; } kwsys_stl::string SystemTools::CollapseFullPath(const kwsys_stl::string& in_relative) { return SystemTools::CollapseFullPath(in_relative, 0); } void SystemTools::AddTranslationPath(const kwsys_stl::string& a, const kwsys_stl::string& b) { kwsys_stl::string path_a = a; kwsys_stl::string path_b = b; SystemTools::ConvertToUnixSlashes(path_a); SystemTools::ConvertToUnixSlashes(path_b); // First check this is a directory path, since we don't want the table to // grow too fat if( SystemTools::FileIsDirectory( path_a ) ) { // Make sure the path is a full path and does not contain no '..' // Ken--the following code is incorrect. .. can be in a valid path // for example /home/martink/MyHubba...Hubba/Src if( SystemTools::FileIsFullPath(path_b) && path_b.find("..") == kwsys_stl::string::npos ) { // Before inserting make sure path ends with '/' if(!path_a.empty() && *path_a.rbegin() != '/') { path_a += '/'; } if(!path_b.empty() && *path_b.rbegin() != '/') { path_b += '/'; } if( !(path_a == path_b) ) { SystemTools::TranslationMap->insert( SystemToolsTranslationMap::value_type(path_a, path_b)); } } } } void SystemTools::AddKeepPath(const kwsys_stl::string& dir) { kwsys_stl::string cdir; Realpath(SystemTools::CollapseFullPath(dir).c_str(), cdir); SystemTools::AddTranslationPath(cdir, dir); } void SystemTools::CheckTranslationPath(kwsys_stl::string & path) { // Do not translate paths that are too short to have meaningful // translations. if(path.size() < 2) { return; } // Always add a trailing slash before translation. It does not // matter if this adds an extra slash, but we do not want to // translate part of a directory (like the foo part of foo-dir). path += "/"; // In case a file was specified we still have to go through this: // Now convert any path found in the table back to the one desired: kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>::const_iterator it; for(it = SystemTools::TranslationMap->begin(); it != SystemTools::TranslationMap->end(); ++it ) { // We need to check of the path is a substring of the other path if(path.find( it->first ) == 0) { path = path.replace( 0, it->first.size(), it->second); } } // Remove the trailing slash we added before. path.erase(path.end()-1, path.end()); } static void SystemToolsAppendComponents( kwsys_stl::vector<kwsys_stl::string>& out_components, kwsys_stl::vector<kwsys_stl::string>::const_iterator first, kwsys_stl::vector<kwsys_stl::string>::const_iterator last) { static const kwsys_stl::string up = ".."; static const kwsys_stl::string cur = "."; for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = first; i != last; ++i) { if(*i == up) { if(out_components.size() > 1) { out_components.resize(out_components.size()-1); } } else if(!i->empty() && *i != cur) { out_components.push_back(*i); } } } kwsys_stl::string SystemTools::CollapseFullPath(const kwsys_stl::string& in_path, const char* in_base) { // Collect the output path components. kwsys_stl::vector<kwsys_stl::string> out_components; // Split the input path components. kwsys_stl::vector<kwsys_stl::string> path_components; SystemTools::SplitPath(in_path, path_components); // If the input path is relative, start with a base path. if(path_components[0].length() == 0) { kwsys_stl::vector<kwsys_stl::string> base_components; if(in_base) { // Use the given base path. SystemTools::SplitPath(in_base, base_components); } else { // Use the current working directory as a base path. char buf[2048]; if(const char* cwd = Getcwd(buf, 2048)) { SystemTools::SplitPath(cwd, base_components); } else { base_components.push_back(""); } } // Append base path components to the output path. out_components.push_back(base_components[0]); SystemToolsAppendComponents(out_components, base_components.begin()+1, base_components.end()); } // Append input path components to the output path. SystemToolsAppendComponents(out_components, path_components.begin(), path_components.end()); // Transform the path back to a string. kwsys_stl::string newPath = SystemTools::JoinPath(out_components); // Update the translation table with this potentially new path. I am not // sure why this line is here, it seems really questionable, but yet I // would put good money that if I remove it something will break, basically // from what I can see it created a mapping from the collapsed path, to be // replaced by the input path, which almost completely does the opposite of // this function, the only thing preventing this from happening a lot is // that if the in_path has a .. in it, then it is not added to the // translation table. So for most calls this either does nothing due to the // .. or it adds a translation between identical paths as nothing was // collapsed, so I am going to try to comment it out, and see what hits the // fan, hopefully quickly. // Commented out line below: //SystemTools::AddTranslationPath(newPath, in_path); SystemTools::CheckTranslationPath(newPath); #ifdef _WIN32 newPath = SystemTools::GetActualCaseForPath(newPath); SystemTools::ConvertToUnixSlashes(newPath); #endif // Return the reconstructed path. return newPath; } kwsys_stl::string SystemTools::CollapseFullPath(const kwsys_stl::string& in_path, const kwsys_stl::string& in_base) { // Collect the output path components. kwsys_stl::vector<kwsys_stl::string> out_components; // Split the input path components. kwsys_stl::vector<kwsys_stl::string> path_components; SystemTools::SplitPath(in_path, path_components); // If the input path is relative, start with a base path. if(path_components[0].length() == 0) { kwsys_stl::vector<kwsys_stl::string> base_components; // Use the given base path. SystemTools::SplitPath(in_base, base_components); // Append base path components to the output path. out_components.push_back(base_components[0]); SystemToolsAppendComponents(out_components, base_components.begin()+1, base_components.end()); } // Append input path components to the output path. SystemToolsAppendComponents(out_components, path_components.begin(), path_components.end()); // Transform the path back to a string. kwsys_stl::string newPath = SystemTools::JoinPath(out_components); // Update the translation table with this potentially new path. I am not // sure why this line is here, it seems really questionable, but yet I // would put good money that if I remove it something will break, basically // from what I can see it created a mapping from the collapsed path, to be // replaced by the input path, which almost completely does the opposite of // this function, the only thing preventing this from happening a lot is // that if the in_path has a .. in it, then it is not added to the // translation table. So for most calls this either does nothing due to the // .. or it adds a translation between identical paths as nothing was // collapsed, so I am going to try to comment it out, and see what hits the // fan, hopefully quickly. // Commented out line below: //SystemTools::AddTranslationPath(newPath, in_path); SystemTools::CheckTranslationPath(newPath); #ifdef _WIN32 newPath = SystemTools::GetActualCaseForPath(newPath); SystemTools::ConvertToUnixSlashes(newPath); #endif // Return the reconstructed path. return newPath; } // compute the relative path from here to there kwsys_stl::string SystemTools::RelativePath(const kwsys_stl::string& local, const kwsys_stl::string& remote) { if(!SystemTools::FileIsFullPath(local)) { return ""; } if(!SystemTools::FileIsFullPath(remote)) { return ""; } kwsys_stl::string l = SystemTools::CollapseFullPath(local); kwsys_stl::string r = SystemTools::CollapseFullPath(remote); // split up both paths into arrays of strings using / as a separator kwsys_stl::vector<kwsys::String> localSplit = SystemTools::SplitString(l, '/', true); kwsys_stl::vector<kwsys::String> remoteSplit = SystemTools::SplitString(r, '/', true); kwsys_stl::vector<kwsys::String> commonPath; // store shared parts of path in this array kwsys_stl::vector<kwsys::String> finalPath; // store the final relative path here // count up how many matching directory names there are from the start unsigned int sameCount = 0; while( ((sameCount <= (localSplit.size()-1)) && (sameCount <= (remoteSplit.size()-1))) && // for windows and apple do a case insensitive string compare #if defined(_WIN32) || defined(__APPLE__) SystemTools::Strucmp(localSplit[sameCount].c_str(), remoteSplit[sameCount].c_str()) == 0 #else localSplit[sameCount] == remoteSplit[sameCount] #endif ) { // put the common parts of the path into the commonPath array commonPath.push_back(localSplit[sameCount]); // erase the common parts of the path from the original path arrays localSplit[sameCount] = ""; remoteSplit[sameCount] = ""; sameCount++; } // If there is nothing in common at all then just return the full // path. This is the case only on windows when the paths have // different drive letters. On unix two full paths always at least // have the root "/" in common so we will return a relative path // that passes through the root directory. if(sameCount == 0) { return remote; } // for each entry that is not common in the local path // add a ../ to the finalpath array, this gets us out of the local // path into the remote dir for(unsigned int i = 0; i < localSplit.size(); ++i) { if(!localSplit[i].empty()) { finalPath.push_back("../"); } } // for each entry that is not common in the remote path add it // to the final path. for(kwsys_stl::vector<String>::iterator vit = remoteSplit.begin(); vit != remoteSplit.end(); ++vit) { if(!vit->empty()) { finalPath.push_back(*vit); } } kwsys_stl::string relativePath; // result string // now turn the array of directories into a unix path by puttint / // between each entry that does not already have one for(kwsys_stl::vector<String>::iterator vit1 = finalPath.begin(); vit1 != finalPath.end(); ++vit1) { if(!relativePath.empty() && *relativePath.rbegin() != '/') { relativePath += "/"; } relativePath += *vit1; } return relativePath; } #ifdef _WIN32 static int GetCasePathName(const kwsys_stl::string & pathIn, kwsys_stl::string & casePath) { kwsys_stl::vector<kwsys_stl::string> path_components; SystemTools::SplitPath(pathIn, path_components); if(path_components[0].empty()) // First component always exists. { // Relative paths cannot be converted. casePath = ""; return 0; } // Start with root component. kwsys_stl::vector<kwsys_stl::string>::size_type idx = 0; casePath = path_components[idx++]; const char* sep = ""; // If network path, fill casePath with server/share so FindFirstFile // will work after that. Maybe someday call other APIs to get // actual case of servers and shares. if(path_components.size() > 2 && path_components[0] == "//") { casePath += path_components[idx++]; casePath += "/"; casePath += path_components[idx++]; sep = "/"; } for(; idx < path_components.size(); idx++) { casePath += sep; sep = "/"; kwsys_stl::string test_str = casePath; test_str += path_components[idx]; // If path component contains wildcards, we skip matching // because these filenames are not allowed on windows, // and we do not want to match a different file. if(path_components[idx].find('*') != kwsys_stl::string::npos || path_components[idx].find('?') != kwsys_stl::string::npos) { casePath = ""; return 0; } WIN32_FIND_DATAW findData; HANDLE hFind = ::FindFirstFileW(Encoding::ToWide(test_str).c_str(), &findData); if (INVALID_HANDLE_VALUE != hFind) { casePath += Encoding::ToNarrow(findData.cFileName); ::FindClose(hFind); } else { casePath = ""; return 0; } } return (int)casePath.size(); } #endif //---------------------------------------------------------------------------- kwsys_stl::string SystemTools::GetActualCaseForPath(const kwsys_stl::string& p) { #ifndef _WIN32 return p; #else kwsys_stl::string casePath = p; // make sure drive letter is always upper case if(casePath.size() > 1 && casePath[1] == ':') { casePath[0] = toupper(casePath[0]); } // Check to see if actual case has already been called // for this path, and the result is stored in the LongPathMap SystemToolsTranslationMap::iterator i = SystemTools::LongPathMap->find(casePath); if(i != SystemTools::LongPathMap->end()) { return i->second; } int len = GetCasePathName(p, casePath); if(len == 0 || len > MAX_PATH+1) { return p; } (*SystemTools::LongPathMap)[p] = casePath; return casePath; #endif } //---------------------------------------------------------------------------- const char* SystemTools::SplitPathRootComponent(const std::string& p, kwsys_stl::string* root) { // Identify the root component. const char* c = p.c_str(); if((c[0] == '/' && c[1] == '/') || (c[0] == '\\' && c[1] == '\\')) { // Network path. if(root) { *root = "//"; } c += 2; } else if(c[0] == '/' || c[0] == '\\') { // Unix path (or Windows path w/out drive letter). if(root) { *root = "/"; } c += 1; } else if(c[0] && c[1] == ':' && (c[2] == '/' || c[2] == '\\')) { // Windows path. if(root) { (*root) = "_:/"; (*root)[0] = c[0]; } c += 3; } else if(c[0] && c[1] == ':') { // Path relative to a windows drive working directory. if(root) { (*root) = "_:"; (*root)[0] = c[0]; } c += 2; } else if(c[0] == '~') { // Home directory. The returned root should always have a // trailing slash so that appending components as // c[0]c[1]/c[2]/... works. The remaining path returned should // skip the first slash if it exists: // // "~" : root = "~/" , return "" // "~/ : root = "~/" , return "" // "~/x : root = "~/" , return "x" // "~u" : root = "~u/", return "" // "~u/" : root = "~u/", return "" // "~u/x" : root = "~u/", return "x" size_t n = 1; while(c[n] && c[n] != '/') { ++n; } if(root) { root->assign(c, n); *root += '/'; } if(c[n] == '/') { ++n; } c += n; } else { // Relative path. if(root) { *root = ""; } } // Return the remaining path. return c; } //---------------------------------------------------------------------------- void SystemTools::SplitPath(const std::string& p, kwsys_stl::vector<kwsys_stl::string>& components, bool expand_home_dir) { const char* c; components.clear(); // Identify the root component. { kwsys_stl::string root; c = SystemTools::SplitPathRootComponent(p, &root); // Expand home directory references if requested. if(expand_home_dir && !root.empty() && root[0] == '~') { kwsys_stl::string homedir; root = root.substr(0, root.size()-1); if(root.size() == 1) { #if defined(_WIN32) && !defined(__CYGWIN__) if(const char* userp = getenv("USERPROFILE")) { homedir = userp; } else #endif if(const char* h = getenv("HOME")) { homedir = h; } } #ifdef HAVE_GETPWNAM else if(passwd* pw = getpwnam(root.c_str()+1)) { if(pw->pw_dir) { homedir = pw->pw_dir; } } #endif if(!homedir.empty() && (*homedir.rbegin() == '/' || *homedir.rbegin() == '\\')) { homedir.resize(homedir.size() - 1); } SystemTools::SplitPath(homedir, components); } else { components.push_back(root); } } // Parse the remaining components. const char* first = c; const char* last = first; for(;*last; ++last) { if(*last == '/' || *last == '\\') { // End of a component. Save it. components.push_back(kwsys_stl::string(first, last)); first = last+1; } } // Save the last component unless there were no components. if(last != c) { components.push_back(kwsys_stl::string(first, last)); } } //---------------------------------------------------------------------------- kwsys_stl::string SystemTools::JoinPath(const kwsys_stl::vector<kwsys_stl::string>& components) { return SystemTools::JoinPath(components.begin(), components.end()); } //---------------------------------------------------------------------------- kwsys_stl::string SystemTools ::JoinPath(kwsys_stl::vector<kwsys_stl::string>::const_iterator first, kwsys_stl::vector<kwsys_stl::string>::const_iterator last) { // Construct result in a single string. kwsys_stl::string result; size_t len = 0; kwsys_stl::vector<kwsys_stl::string>::const_iterator i; for(i = first; i != last; ++i) { len += 1 + i->size(); } result.reserve(len); // The first two components do not add a slash. if(first != last) { result.append(*first++); } if(first != last) { result.append(*first++); } // All remaining components are always separated with a slash. while(first != last) { result.append("/"); result.append((*first++)); } // Return the concatenated result. return result; } //---------------------------------------------------------------------------- bool SystemTools::ComparePath(const kwsys_stl::string& c1, const kwsys_stl::string& c2) { #if defined(_WIN32) || defined(__APPLE__) # ifdef _MSC_VER return _stricmp(c1.c_str(), c2.c_str()) == 0; # elif defined(__APPLE__) || defined(__GNUC__) return strcasecmp(c1.c_str(), c2.c_str()) == 0; #else return SystemTools::Strucmp(c1.c_str(), c2.c_str()) == 0; # endif #else return c1 == c2; #endif } //---------------------------------------------------------------------------- bool SystemTools::Split(const kwsys_stl::string& str, kwsys_stl::vector<kwsys_stl::string>& lines, char separator) { kwsys_stl::string data(str); kwsys_stl::string::size_type lpos = 0; while(lpos < data.length()) { kwsys_stl::string::size_type rpos = data.find_first_of(separator, lpos); if(rpos == kwsys_stl::string::npos) { // Line ends at end of string without a newline. lines.push_back(data.substr(lpos)); return false; } else { // Line ends in a "\n", remove the character. lines.push_back(data.substr(lpos, rpos-lpos)); } lpos = rpos+1; } return true; } //---------------------------------------------------------------------------- bool SystemTools::Split(const kwsys_stl::string& str, kwsys_stl::vector<kwsys_stl::string>& lines) { kwsys_stl::string data(str); kwsys_stl::string::size_type lpos = 0; while(lpos < data.length()) { kwsys_stl::string::size_type rpos = data.find_first_of("\n", lpos); if(rpos == kwsys_stl::string::npos) { // Line ends at end of string without a newline. lines.push_back(data.substr(lpos)); return false; } if((rpos > lpos) && (data[rpos-1] == '\r')) { // Line ends in a "\r\n" pair, remove both characters. lines.push_back(data.substr(lpos, (rpos-1)-lpos)); } else { // Line ends in a "\n", remove the character. lines.push_back(data.substr(lpos, rpos-lpos)); } lpos = rpos+1; } return true; } /** * Return path of a full filename (no trailing slashes). * Warning: returned path is converted to Unix slashes format. */ kwsys_stl::string SystemTools::GetFilenamePath(const kwsys_stl::string& filename) { kwsys_stl::string fn = filename; SystemTools::ConvertToUnixSlashes(fn); kwsys_stl::string::size_type slash_pos = fn.rfind("/"); if(slash_pos != kwsys_stl::string::npos) { kwsys_stl::string ret = fn.substr(0, slash_pos); if(ret.size() == 2 && ret[1] == ':') { return ret + '/'; } if(ret.empty()) { return "/"; } return ret; } else { return ""; } } /** * Return file name of a full filename (i.e. file name without path). */ kwsys_stl::string SystemTools::GetFilenameName(const kwsys_stl::string& filename) { #if defined(_WIN32) kwsys_stl::string::size_type slash_pos = filename.find_last_of("/\\"); #else kwsys_stl::string::size_type slash_pos = filename.rfind('/'); #endif if(slash_pos != kwsys_stl::string::npos) { return filename.substr(slash_pos + 1); } else { return filename; } } /** * Return file extension of a full filename (dot included). * Warning: this is the longest extension (for example: .tar.gz) */ kwsys_stl::string SystemTools::GetFilenameExtension(const kwsys_stl::string& filename) { kwsys_stl::string name = SystemTools::GetFilenameName(filename); kwsys_stl::string::size_type dot_pos = name.find('.'); if(dot_pos != kwsys_stl::string::npos) { return name.substr(dot_pos); } else { return ""; } } /** * Return file extension of a full filename (dot included). * Warning: this is the shortest extension (for example: .gz of .tar.gz) */ kwsys_stl::string SystemTools::GetFilenameLastExtension(const kwsys_stl::string& filename) { kwsys_stl::string name = SystemTools::GetFilenameName(filename); kwsys_stl::string::size_type dot_pos = name.rfind('.'); if(dot_pos != kwsys_stl::string::npos) { return name.substr(dot_pos); } else { return ""; } } /** * Return file name without extension of a full filename (i.e. without path). * Warning: it considers the longest extension (for example: .tar.gz) */ kwsys_stl::string SystemTools::GetFilenameWithoutExtension(const kwsys_stl::string& filename) { kwsys_stl::string name = SystemTools::GetFilenameName(filename); kwsys_stl::string::size_type dot_pos = name.find('.'); if(dot_pos != kwsys_stl::string::npos) { return name.substr(0, dot_pos); } else { return name; } } /** * Return file name without extension of a full filename (i.e. without path). * Warning: it considers the last extension (for example: removes .gz * from .tar.gz) */ kwsys_stl::string SystemTools::GetFilenameWithoutLastExtension(const kwsys_stl::string& filename) { kwsys_stl::string name = SystemTools::GetFilenameName(filename); kwsys_stl::string::size_type dot_pos = name.rfind('.'); if(dot_pos != kwsys_stl::string::npos) { return name.substr(0, dot_pos); } else { return name; } } bool SystemTools::FileHasSignature(const char *filename, const char *signature, long offset) { if (!filename || !signature) { return false; } FILE *fp = Fopen(filename, "rb"); if (!fp) { return false; } fseek(fp, offset, SEEK_SET); bool res = false; size_t signature_len = strlen(signature); char *buffer = new char [signature_len]; if (fread(buffer, 1, signature_len, fp) == signature_len) { res = (!strncmp(buffer, signature, signature_len) ? true : false); } delete [] buffer; fclose(fp); return res; } SystemTools::FileTypeEnum SystemTools::DetectFileType(const char *filename, unsigned long length, double percent_bin) { if (!filename || percent_bin < 0) { return SystemTools::FileTypeUnknown; } FILE *fp = Fopen(filename, "rb"); if (!fp) { return SystemTools::FileTypeUnknown; } // Allocate buffer and read bytes unsigned char *buffer = new unsigned char [length]; size_t read_length = fread(buffer, 1, length, fp); fclose(fp); if (read_length == 0) { return SystemTools::FileTypeUnknown; } // Loop over contents and count size_t text_count = 0; const unsigned char *ptr = buffer; const unsigned char *buffer_end = buffer + read_length; while (ptr != buffer_end) { if ((*ptr >= 0x20 && *ptr <= 0x7F) || *ptr == '\n' || *ptr == '\r' || *ptr == '\t') { text_count++; } ptr++; } delete [] buffer; double current_percent_bin = (static_cast<double>(read_length - text_count) / static_cast<double>(read_length)); if (current_percent_bin >= percent_bin) { return SystemTools::FileTypeBinary; } return SystemTools::FileTypeText; } bool SystemTools::LocateFileInDir(const char *filename, const char *dir, kwsys_stl::string& filename_found, int try_filename_dirs) { if (!filename || !dir) { return false; } // Get the basename of 'filename' kwsys_stl::string filename_base = SystemTools::GetFilenameName(filename); // Check if 'dir' is really a directory // If win32 and matches something like C:, accept it as a dir kwsys_stl::string real_dir; if (!SystemTools::FileIsDirectory(dir)) { #if defined( _WIN32 ) size_t dir_len = strlen(dir); if (dir_len < 2 || dir[dir_len - 1] != ':') { #endif real_dir = SystemTools::GetFilenamePath(dir); dir = real_dir.c_str(); #if defined( _WIN32 ) } #endif } // Try to find the file in 'dir' bool res = false; if (!filename_base.empty() && dir) { size_t dir_len = strlen(dir); int need_slash = (dir_len && dir[dir_len - 1] != '/' && dir[dir_len - 1] != '\\'); kwsys_stl::string temp = dir; if (need_slash) { temp += "/"; } temp += filename_base; if (SystemTools::FileExists(temp)) { res = true; filename_found = temp; } // If not found, we can try harder by appending part of the file to // to the directory to look inside. // Example: if we were looking for /foo/bar/yo.txt in /d1/d2, then // try to find yo.txt in /d1/d2/bar, then /d1/d2/foo/bar, etc. else if (try_filename_dirs) { kwsys_stl::string filename_dir(filename); kwsys_stl::string filename_dir_base; kwsys_stl::string filename_dir_bases; do { filename_dir = SystemTools::GetFilenamePath(filename_dir); filename_dir_base = SystemTools::GetFilenameName(filename_dir); #if defined( _WIN32 ) if (filename_dir_base.empty() || *filename_dir_base.rbegin() == ':') #else if (filename_dir_base.empty()) #endif { break; } filename_dir_bases = filename_dir_base + "/" + filename_dir_bases; temp = dir; if (need_slash) { temp += "/"; } temp += filename_dir_bases; res = SystemTools::LocateFileInDir( filename_base.c_str(), temp.c_str(), filename_found, 0); } while (!res && !filename_dir_base.empty()); } } return res; } bool SystemTools::FileIsFullPath(const kwsys_stl::string& in_name) { return SystemTools::FileIsFullPath(in_name.c_str(), in_name.size()); } bool SystemTools::FileIsFullPath(const char* in_name) { return SystemTools::FileIsFullPath(in_name, in_name[0] ? (in_name[1] ? 2 : 1) : 0); } bool SystemTools::FileIsFullPath(const char* in_name, size_t len) { #if defined(_WIN32) || defined(__CYGWIN__) // On Windows, the name must be at least two characters long. if(len < 2) { return false; } if(in_name[1] == ':') { return true; } if(in_name[0] == '\\') { return true; } #else // On UNIX, the name must be at least one character long. if(len < 1) { return false; } #endif #if !defined(_WIN32) if(in_name[0] == '~') { return true; } #endif // On UNIX, the name must begin in a '/'. // On Windows, if the name begins in a '/', then it is a full // network path. if(in_name[0] == '/') { return true; } return false; } bool SystemTools::GetShortPath(const kwsys_stl::string& path, kwsys_stl::string& shortPath) { #if defined(WIN32) && !defined(__CYGWIN__) const int size = int(path.size()) +1; // size of return char *tempPath = new char[size]; // create a buffer DWORD ret; // if the path passed in has quotes around it, first remove the quotes if (!path.empty() && path[0] == '"' && *path.rbegin() == '"') { strcpy(tempPath,path.c_str()+1); tempPath[size-2] = '\0'; } else { strcpy(tempPath,path.c_str()); } kwsys_stl::wstring wtempPath = Encoding::ToWide(tempPath); kwsys_stl::vector<wchar_t> buffer(wtempPath.size()+1); buffer[0] = 0; ret = GetShortPathNameW(wtempPath.c_str(), &buffer[0], static_cast<DWORD>(wtempPath.size())); if(buffer[0] == 0 || ret > wtempPath.size()) { delete [] tempPath; return false; } else { shortPath = Encoding::ToNarrow(&buffer[0]); delete [] tempPath; return true; } #else shortPath = path; return true; #endif } void SystemTools::SplitProgramFromArgs(const kwsys_stl::string& path, kwsys_stl::string& program, kwsys_stl::string& args) { // see if this is a full path to a program // if so then set program to path and args to nothing if(SystemTools::FileExists(path)) { program = path; args = ""; return; } // Try to find the program in the path, note the program // may have spaces in its name so we have to look for it kwsys_stl::vector<kwsys_stl::string> e; kwsys_stl::string findProg = SystemTools::FindProgram(path, e); if(!findProg.empty()) { program = findProg; args = ""; return; } // Now try and peel off space separated chunks from the end of the string // so the largest path possible is found allowing for spaces in the path kwsys_stl::string dir = path; kwsys_stl::string::size_type spacePos = dir.rfind(' '); while(spacePos != kwsys_stl::string::npos) { kwsys_stl::string tryProg = dir.substr(0, spacePos); // See if the file exists if(SystemTools::FileExists(tryProg)) { program = tryProg; // remove trailing spaces from program kwsys_stl::string::size_type pos = program.size()-1; while(program[pos] == ' ') { program.erase(pos); pos--; } args = dir.substr(spacePos, dir.size()-spacePos); return; } // Now try and find the program in the path findProg = SystemTools::FindProgram(tryProg, e); if(!findProg.empty()) { program = findProg; // remove trailing spaces from program kwsys_stl::string::size_type pos = program.size()-1; while(program[pos] == ' ') { program.erase(pos); pos--; } args = dir.substr(spacePos, dir.size()-spacePos); return; } // move past the space for the next search spacePos--; spacePos = dir.rfind(' ', spacePos); } program = ""; args = ""; } kwsys_stl::string SystemTools::GetCurrentDateTime(const char* format) { char buf[1024]; time_t t; time(&t); strftime(buf, sizeof(buf), format, localtime(&t)); return kwsys_stl::string(buf); } kwsys_stl::string SystemTools::MakeCidentifier(const kwsys_stl::string& s) { kwsys_stl::string str(s); if (str.find_first_of("0123456789") == 0) { str = "_" + str; } kwsys_stl::string permited_chars("_" "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789"); kwsys_stl::string::size_type pos = 0; while ((pos = str.find_first_not_of(permited_chars, pos)) != kwsys_stl::string::npos) { str[pos] = '_'; } return str; } // Due to a buggy stream library on the HP and another on Mac OS X, we // need this very carefully written version of getline. Returns true // if any data were read before the end-of-file was reached. bool SystemTools::GetLineFromStream(kwsys_ios::istream& is, kwsys_stl::string& line, bool* has_newline /* = 0 */, long sizeLimit /* = -1 */) { const int bufferSize = 1024; char buffer[bufferSize]; bool haveData = false; bool haveNewline = false; // Start with an empty line. line = ""; long leftToRead = sizeLimit; // Early short circuit return if stream is no good. Just return // false and the empty line. (Probably means caller tried to // create a file stream with a non-existent file name...) // if(!is) { if(has_newline) { *has_newline = false; } return false; } // If no characters are read from the stream, the end of file has // been reached. Clear the fail bit just before reading. while(!haveNewline && leftToRead != 0 && (is.clear(is.rdstate() & ~kwsys_ios::ios::failbit), is.getline(buffer, bufferSize), is.gcount() > 0)) { // We have read at least one byte. haveData = true; // If newline character was read the gcount includes the character // but the buffer does not: the end of line has been reached. size_t length = strlen(buffer); if(length < static_cast<size_t>(is.gcount())) { haveNewline = true; } // Avoid storing a carriage return character. if(length > 0 && buffer[length-1] == '\r') { buffer[length-1] = 0; } // if we read too much then truncate the buffer if (leftToRead > 0) { if (static_cast<long>(length) > leftToRead) { buffer[leftToRead-1] = 0; leftToRead = 0; } else { leftToRead -= static_cast<long>(length); } } // Append the data read to the line. line.append(buffer); } // Return the results. if(has_newline) { *has_newline = haveNewline; } return haveData; } int SystemTools::GetTerminalWidth() { int width = -1; #ifdef HAVE_TTY_INFO struct winsize ws; char *columns; /* Unix98 environment variable */ if(ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col>0 && ws.ws_row>0) { width = ws.ws_col; } if(!isatty(STDOUT_FILENO)) { width = -1; } columns = getenv("COLUMNS"); if(columns && *columns) { long t; char *endptr; t = strtol(columns, &endptr, 0); if(endptr && !*endptr && (t>0) && (t<1000)) { width = static_cast<int>(t); } } if ( width < 9 ) { width = -1; } #endif return width; } bool SystemTools::GetPermissions(const char* file, mode_t& mode) { if ( !file ) { return false; } return SystemTools::GetPermissions(kwsys_stl::string(file), mode); } bool SystemTools::GetPermissions(const kwsys_stl::string& file, mode_t& mode) { #if defined(_WIN32) DWORD attr = GetFileAttributesW( SystemTools::ConvertToWindowsExtendedPath(file).c_str()); if(attr == INVALID_FILE_ATTRIBUTES) { return false; } if((attr & FILE_ATTRIBUTE_READONLY) != 0) { mode = (_S_IREAD | (_S_IREAD >> 3) | (_S_IREAD >> 6)); } else { mode = (_S_IWRITE | (_S_IWRITE >> 3) | (_S_IWRITE >> 6)) | (_S_IREAD | (_S_IREAD >> 3) | (_S_IREAD >> 6)); } if((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) { mode |= S_IFDIR | (_S_IEXEC | (_S_IEXEC >> 3) | (_S_IEXEC >> 6)); } else { mode |= S_IFREG; } size_t dotPos = file.rfind('.'); const char* ext = dotPos == file.npos ? 0 : (file.c_str() + dotPos); if(ext && (Strucmp(ext, ".exe") == 0 || Strucmp(ext, ".com") == 0 || Strucmp(ext, ".cmd") == 0 || Strucmp(ext, ".bat") == 0)) { mode |= (_S_IEXEC | (_S_IEXEC >> 3) | (_S_IEXEC >> 6)); } #else struct stat st; if ( stat(file.c_str(), &st) < 0 ) { return false; } mode = st.st_mode; #endif return true; } bool SystemTools::SetPermissions(const char* file, mode_t mode) { if ( !file ) { return false; } return SystemTools::SetPermissions(kwsys_stl::string(file), mode); } bool SystemTools::SetPermissions(const kwsys_stl::string& file, mode_t mode) { if ( !SystemTools::FileExists(file) ) { return false; } #ifdef _WIN32 if ( _wchmod(SystemTools::ConvertToWindowsExtendedPath(file).c_str(), mode) < 0 ) #else if ( chmod(file.c_str(), mode) < 0 ) #endif { return false; } return true; } kwsys_stl::string SystemTools::GetParentDirectory(const kwsys_stl::string& fileOrDir) { return SystemTools::GetFilenamePath(fileOrDir); } bool SystemTools::IsSubDirectory(const kwsys_stl::string& cSubdir, const kwsys_stl::string& cDir) { if(cDir.empty()) { return false; } kwsys_stl::string subdir = cSubdir; kwsys_stl::string dir = cDir; SystemTools::ConvertToUnixSlashes(subdir); SystemTools::ConvertToUnixSlashes(dir); if(subdir.size() > dir.size() && subdir[dir.size()] == '/') { std::string s = subdir.substr(0, dir.size()); return SystemTools::ComparePath(s, dir); } return false; } void SystemTools::Delay(unsigned int msec) { #ifdef _WIN32 Sleep(msec); #else // The sleep function gives 1 second resolution and the usleep // function gives 1e-6 second resolution but on some platforms has a // maximum sleep time of 1 second. This could be re-implemented to // use select with masked signals or pselect to mask signals // atomically. If select is given empty sets and zero as the max // file descriptor but a non-zero timeout it can be used to block // for a precise amount of time. if(msec >= 1000) { sleep(msec / 1000); usleep((msec % 1000) * 1000); } else { usleep(msec * 1000); } #endif } kwsys_stl::string SystemTools::GetOperatingSystemNameAndVersion() { kwsys_stl::string res; #ifdef _WIN32 char buffer[256]; OSVERSIONINFOEXA osvi; BOOL bOsVersionInfoEx; // Try calling GetVersionEx using the OSVERSIONINFOEX structure. // If that fails, try using the OSVERSIONINFO structure. ZeroMemory(&osvi, sizeof(OSVERSIONINFOEXA)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXA); #ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx # pragma warning (push) # ifdef __INTEL_COMPILER # pragma warning (disable:1478) # else # pragma warning (disable:4996) # endif #endif bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *)&osvi); if (!bOsVersionInfoEx) { osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); if (!GetVersionEx((OSVERSIONINFO *)&osvi)) { return 0; } } #ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx # pragma warning (pop) #endif switch (osvi.dwPlatformId) { // Test for the Windows NT product family. case VER_PLATFORM_WIN32_NT: // Test for the specific product family. if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0) { #if (_MSC_VER >= 1300) if (osvi.wProductType == VER_NT_WORKSTATION) { res += "Microsoft Windows Vista"; } else { res += "Microsoft Windows Server 2008 family"; } #else res += "Microsoft Windows Vista or Windows Server 2008"; #endif } if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) { res += "Microsoft Windows Server 2003 family"; } if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) { res += "Microsoft Windows XP"; } if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) { res += "Microsoft Windows 2000"; } if (osvi.dwMajorVersion <= 4) { res += "Microsoft Windows NT"; } // Test for specific product on Windows NT 4.0 SP6 and later. if (bOsVersionInfoEx) { // Test for the workstation type. #if (_MSC_VER >= 1300) if (osvi.wProductType == VER_NT_WORKSTATION) { if (osvi.dwMajorVersion == 4) { res += " Workstation 4.0"; } else if (osvi.dwMajorVersion == 5) { if (osvi.wSuiteMask & VER_SUITE_PERSONAL) { res += " Home Edition"; } else { res += " Professional"; } } } // Test for the server type. else if (osvi.wProductType == VER_NT_SERVER) { if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) { if (osvi.wSuiteMask & VER_SUITE_DATACENTER) { res += " Datacenter Edition"; } else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) { res += " Enterprise Edition"; } else if (osvi.wSuiteMask == VER_SUITE_BLADE) { res += " Web Edition"; } else { res += " Standard Edition"; } } else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) { if (osvi.wSuiteMask & VER_SUITE_DATACENTER) { res += " Datacenter Server"; } else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) { res += " Advanced Server"; } else { res += " Server"; } } else if (osvi.dwMajorVersion <= 4) // Windows NT 4.0 { if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) { res += " Server 4.0, Enterprise Edition"; } else { res += " Server 4.0"; } } } #endif // Visual Studio 7 and up } // Test for specific product on Windows NT 4.0 SP5 and earlier else { HKEY hKey; #define BUFSIZE 80 wchar_t szProductType[BUFSIZE]; DWORD dwBufLen=BUFSIZE; LONG lRet; lRet = RegOpenKeyExW( HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\ProductOptions", 0, KEY_QUERY_VALUE, &hKey); if (lRet != ERROR_SUCCESS) { return 0; } lRet = RegQueryValueExW(hKey, L"ProductType", NULL, NULL, (LPBYTE) szProductType, &dwBufLen); if ((lRet != ERROR_SUCCESS) || (dwBufLen > BUFSIZE)) { return 0; } RegCloseKey(hKey); if (lstrcmpiW(L"WINNT", szProductType) == 0) { res += " Workstation"; } if (lstrcmpiW(L"LANMANNT", szProductType) == 0) { res += " Server"; } if (lstrcmpiW(L"SERVERNT", szProductType) == 0) { res += " Advanced Server"; } res += " "; sprintf(buffer, "%ld", osvi.dwMajorVersion); res += buffer; res += "."; sprintf(buffer, "%ld", osvi.dwMinorVersion); res += buffer; } // Display service pack (if any) and build number. if (osvi.dwMajorVersion == 4 && lstrcmpiA(osvi.szCSDVersion, "Service Pack 6") == 0) { HKEY hKey; LONG lRet; // Test for SP6 versus SP6a. lRet = RegOpenKeyExW( HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009", 0, KEY_QUERY_VALUE, &hKey); if (lRet == ERROR_SUCCESS) { res += " Service Pack 6a (Build "; sprintf(buffer, "%ld", osvi.dwBuildNumber & 0xFFFF); res += buffer; res += ")"; } else // Windows NT 4.0 prior to SP6a { res += " "; res += osvi.szCSDVersion; res += " (Build "; sprintf(buffer, "%ld", osvi.dwBuildNumber & 0xFFFF); res += buffer; res += ")"; } RegCloseKey(hKey); } else // Windows NT 3.51 and earlier or Windows 2000 and later { res += " "; res += osvi.szCSDVersion; res += " (Build "; sprintf(buffer, "%ld", osvi.dwBuildNumber & 0xFFFF); res += buffer; res += ")"; } break; // Test for the Windows 95 product family. case VER_PLATFORM_WIN32_WINDOWS: if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0) { res += "Microsoft Windows 95"; if (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B') { res += " OSR2"; } } if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10) { res += "Microsoft Windows 98"; if (osvi.szCSDVersion[1] == 'A') { res += " SE"; } } if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90) { res += "Microsoft Windows Millennium Edition"; } break; case VER_PLATFORM_WIN32s: res += "Microsoft Win32s"; break; } #endif return res; } // ---------------------------------------------------------------------- bool SystemTools::ParseURLProtocol( const kwsys_stl::string& URL, kwsys_stl::string& protocol, kwsys_stl::string& dataglom ) { // match 0 entire url // match 1 protocol // match 2 dataglom following protocol:// kwsys::RegularExpression urlRe( VTK_URL_PROTOCOL_REGEX ); if ( ! urlRe.find( URL ) ) return false; protocol = urlRe.match( 1 ); dataglom = urlRe.match( 2 ); return true; } // ---------------------------------------------------------------------- bool SystemTools::ParseURL( const kwsys_stl::string& URL, kwsys_stl::string& protocol, kwsys_stl::string& username, kwsys_stl::string& password, kwsys_stl::string& hostname, kwsys_stl::string& dataport, kwsys_stl::string& database ) { kwsys::RegularExpression urlRe( VTK_URL_REGEX ); if ( ! urlRe.find( URL ) ) return false; // match 0 URL // match 1 protocol // match 2 mangled user // match 3 username // match 4 mangled password // match 5 password // match 6 hostname // match 7 mangled port // match 8 dataport // match 9 database name protocol = urlRe.match( 1 ); username = urlRe.match( 3 ); password = urlRe.match( 5 ); hostname = urlRe.match( 6 ); dataport = urlRe.match( 8 ); database = urlRe.match( 9 ); return true; } // ---------------------------------------------------------------------- // These must NOT be initialized. Default initialization to zero is // necessary. static unsigned int SystemToolsManagerCount; SystemToolsTranslationMap *SystemTools::TranslationMap; SystemToolsTranslationMap *SystemTools::LongPathMap; #ifdef __CYGWIN__ SystemToolsTranslationMap *SystemTools::Cyg2Win32Map; #endif // SystemToolsManager manages the SystemTools singleton. // SystemToolsManager should be included in any translation unit // that will use SystemTools or that implements the singleton // pattern. It makes sure that the SystemTools singleton is created // before and destroyed after all other singletons in CMake. SystemToolsManager::SystemToolsManager() { if(++SystemToolsManagerCount == 1) { SystemTools::ClassInitialize(); } } SystemToolsManager::~SystemToolsManager() { if(--SystemToolsManagerCount == 0) { SystemTools::ClassFinalize(); } } #if defined(__VMS) // On VMS we configure the run time C library to be more UNIX like. // http://h71000.www7.hp.com/doc/732final/5763/5763pro_004.html extern "C" int decc$feature_get_index(char *name); extern "C" int decc$feature_set_value(int index, int mode, int value); static int SetVMSFeature(char* name, int value) { int i; errno = 0; i = decc$feature_get_index(name); return i >= 0 && (decc$feature_set_value(i, 1, value) >= 0 || errno == 0); } #endif void SystemTools::ClassInitialize() { #ifdef __VMS SetVMSFeature("DECC$FILENAME_UNIX_ONLY", 1); #endif // Allocate the translation map first. SystemTools::TranslationMap = new SystemToolsTranslationMap; SystemTools::LongPathMap = new SystemToolsTranslationMap; #ifdef __CYGWIN__ SystemTools::Cyg2Win32Map = new SystemToolsTranslationMap; #endif // Add some special translation paths for unix. These are not added // for windows because drive letters need to be maintained. Also, // there are not sym-links and mount points on windows anyway. #if !defined(_WIN32) || defined(__CYGWIN__) // The tmp path is frequently a logical path so always keep it: SystemTools::AddKeepPath("/tmp/"); // If the current working directory is a logical path then keep the // logical name. if(const char* pwd = getenv("PWD")) { char buf[2048]; if(const char* cwd = Getcwd(buf, 2048)) { // The current working directory may be a logical path. Find // the shortest logical path that still produces the correct // physical path. kwsys_stl::string cwd_changed; kwsys_stl::string pwd_changed; // Test progressively shorter logical-to-physical mappings. kwsys_stl::string pwd_str = pwd; kwsys_stl::string cwd_str = cwd; kwsys_stl::string pwd_path; Realpath(pwd, pwd_path); while(cwd_str == pwd_path && cwd_str != pwd_str) { // The current pair of paths is a working logical mapping. cwd_changed = cwd_str; pwd_changed = pwd_str; // Strip off one directory level and see if the logical // mapping still works. pwd_str = SystemTools::GetFilenamePath(pwd_str); cwd_str = SystemTools::GetFilenamePath(cwd_str); Realpath(pwd_str.c_str(), pwd_path); } // Add the translation to keep the logical path name. if(!cwd_changed.empty() && !pwd_changed.empty()) { SystemTools::AddTranslationPath(cwd_changed, pwd_changed); } } } #endif } void SystemTools::ClassFinalize() { delete SystemTools::TranslationMap; delete SystemTools::LongPathMap; #ifdef __CYGWIN__ delete SystemTools::Cyg2Win32Map; #endif } } // namespace KWSYS_NAMESPACE #if defined(_MSC_VER) && defined(_DEBUG) # include <crtdbg.h> # include <stdio.h> # include <stdlib.h> namespace KWSYS_NAMESPACE { static int SystemToolsDebugReport(int, char* message, int*) { fprintf(stderr, "%s", message); fflush(stderr); return 1; // no further reporting required } void SystemTools::EnableMSVCDebugHook() { if (getenv("DART_TEST_FROM_DART") || getenv("DASHBOARD_TEST_FROM_CTEST")) { _CrtSetReportHook(SystemToolsDebugReport); } } } // namespace KWSYS_NAMESPACE #else namespace KWSYS_NAMESPACE { void SystemTools::EnableMSVCDebugHook() {} } // namespace KWSYS_NAMESPACE #endif
[ "wangzixuan828@gmail.com" ]
wangzixuan828@gmail.com
e44b8d5ba065a36a3408da0aa19cd8696a0e3d07
572c9859d07746ea3b109c7675dd68ee5b0f0f31
/src/vidf/common/interpolate.h
cc4ba2e65df6802557b38709a7d06fab047ce582
[ "MIT" ]
permissive
filami/vidf
ce13f447142406bb80d55657b732122c16c2a65c
f93498e7e29fb39e6624e6e13450d0f5dc37abb0
refs/heads/master
2021-01-18T23:12:56.508550
2020-01-29T22:16:50
2020-01-29T22:16:50
42,007,421
0
0
null
2016-10-25T18:43:08
2015-09-06T15:23:58
C++
UTF-8
C++
false
false
788
h
#pragma once namespace vidf { template<typename T> float Cubic(T y0, T y1, T y2, T y3, T mu) { T a0,a1,a2,a3,mu2; mu2 = mu*mu; a0 = y3 - y2 - y0 + y1; a1 = y0 - y1 - a0; a2 = y2 - y0; a3 = y1; return a0*mu*mu2 + a1*mu2 + a2*mu + a3; } template<typename T> T Hermite1(T x) { return 2 * x*x*x - 3 * x*x + 1; } template<typename T> T Hermite2(T x) { return -2 * x*x*x + 3 * x*x; } template<typename T> T Hermite3(T x) { return x*x*x - 2 * x*x + x; } template<typename T> T Hermite4(T x) { return x*x*x - x*x; } template<typename VT, typename XT> VT Hermite(VT vertex0, VT vertex1, VT control0, VT control1, XT x) { return vertex0*Hermite1(x) + vertex1*Hermite2(x) + control0*Hermite3(x) + control1*Hermite4(x); } }
[ "filipeamim@videmogroup.org" ]
filipeamim@videmogroup.org
1cc8848acc67e5b600ad105e12e2ff9ceb6c3f16
0200d7280c7487d5a679b73efa713ed06a53d95c
/exercise/chapter5/exercise1.cpp
8a5c14ba8228ba10f2195ec48d59c068dd39142c
[]
no_license
JimLgy/CplusLearning
08a848557b47845edba8644e176c4e41c3377a28
d27e0798efa60fb7e3a5ffb13f64e0bc82717452
refs/heads/master
2020-12-02T18:21:24.566460
2020-05-22T09:46:20
2020-05-22T09:46:20
231,077,198
0
0
null
null
null
null
UTF-8
C++
false
false
371
cpp
#include <iostream> int main() { using namespace std; cout << "Enter the small integer: "; int x, y, total = 0; cin >> x; cout << "Enter the large integer: "; cin >> y; for (int i = x; i <= y; i++) total += i; cout << "The sum of all integers between " << x << " and " << y << " = " << total << endl; return 0; }
[ "ubuntu@localhost.localdomain" ]
ubuntu@localhost.localdomain
bc1af245dfbef03b9e51abd1b96fff4438dd603e
536656cd89e4fa3a92b5dcab28657d60d1d244bd
/content/browser/plugin_private_storage_helper.h
8ac5bbd60fc5b072d200f4796fb68a5cf453c363
[ "BSD-3-Clause" ]
permissive
ECS-251-W2020/chromium
79caebf50443f297557d9510620bf8d44a68399a
ac814e85cb870a6b569e184c7a60a70ff3cb19f9
refs/heads/master
2022-08-19T17:42:46.887573
2020-03-18T06:08:44
2020-03-18T06:08:44
248,141,336
7
8
BSD-3-Clause
2022-07-06T20:32:48
2020-03-18T04:52:18
null
UTF-8
C++
false
false
1,502
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. #ifndef CONTENT_BROWSER_PLUGIN_PRIVATE_STORAGE_HELPER_H_ #define CONTENT_BROWSER_PLUGIN_PRIVATE_STORAGE_HELPER_H_ #include "ppapi/buildflags/buildflags.h" #if !BUILDFLAG(ENABLE_PLUGINS) #error This file should only be included when plugins are enabled. #endif #include "base/callback_forward.h" #include "base/memory/scoped_refptr.h" #include "base/time/time.h" #include "content/public/browser/storage_partition.h" #include "url/gurl.h" namespace storage { class FileSystemContext; class SpecialStoragePolicy; } namespace content { // Clear the plugin private filesystem data in |filesystem_context| for // |storage_origin| if any file has a last modified time between |begin| // and |end|. If |storage_origin| is not specified, then all available // origins are checked. |callback| is called when the operation is complete. // This must be called on the file task runner. void ClearPluginPrivateDataOnFileTaskRunner( scoped_refptr<storage::FileSystemContext> filesystem_context, const GURL& storage_origin, StoragePartition::OriginMatcherFunction origin_matcher, const scoped_refptr<storage::SpecialStoragePolicy>& special_storage_policy, const base::Time begin, const base::Time end, base::OnceClosure callback); } // namespace content #endif // CONTENT_BROWSER_PLUGIN_PRIVATE_STORAGE_HELPER_H_
[ "pcding@ucdavis.edu" ]
pcding@ucdavis.edu
9e7ad1883462cac170b58fe9f8835fb422a5df16
aff683534daacde945102e4648027dd8e806edbe
/src/bindings/bindings.cpp
483108e4d20410bcf293f2e55929cfc167dc7011
[ "MIT" ]
permissive
jtyow1/rhino3dm
6c80bedf52441b4d801d470e7a0dbd9787e12462
9f9d7a222723e24e258413d0205a081c0cc4402a
refs/heads/master
2020-04-13T06:32:42.301831
2018-12-18T00:16:42
2018-12-18T00:16:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,607
cpp
#include "bindings.h" #if defined(ON_PYTHON_COMPILE) namespace py = pybind11; PYBIND11_MODULE(_rhino3dm, m){ m.doc() = "rhino3dm python package. OpenNURBS wrappers with a RhinoCommon style"; #endif #if defined(ON_WASM_COMPILE) using namespace emscripten; EMSCRIPTEN_BINDINGS(rhino3dm) { void* m = nullptr; #endif ON::Begin(); initFileUtilitiesBindings(m); initDefines(m); init3dmSettingsBindings(m); initPolylineBindings(m); initObjectBindings(m); init3dmAttributesBindings(m); initBitmapBindings(m); initDimensionStyleBindings(m); initLayerBindings(m); initMaterialBindings(m); initTextureBindings(m); initTextureMappingBindings(m); initPointBindings(m); initXformBindings(m); initArcBindings(m); initBoundingBoxBindings(m); initBoxBindings(m); initGeometryBindings(m); initInstanceBindings(m); initHatchBindings(m); initPointCloudBindings(m); initPointGeometryBindings(m); initPointGridBindings(m); initCurveBindings(m); initCurveProxyBindings(m); initNurbsCurveBindings(m); initMeshBindings(m); initCircleBindings(m); initConeBindings(m); initCylinderBindings(m); initEllipseBindings(m); initFontBindings(m); initArcCurveBindings(m); initBezierBindings(m); initLineCurveBindings(m); initPolyCurveBindings(m); initPolylineCurveBindings(m); initSurfaceBindings(m); initRevSurfaceBindings(m); initSurfaceProxyBindings(m); initPlaneSurfaceBindings(m); initBrepBindings(m); initExtrusionBindings(m); initNurbsSurfaceBindings(m); initSphereBindings(m); initViewportBindings(m); initExtensionsBindings(m); }
[ "steve@mcneel.com" ]
steve@mcneel.com
f447b36ca005bf8494143533a6719990e4444db5
c071cc45036f090ab307f47a893ca46052f9acd8
/SiLib/CmdDispatcher.h
b3128ea76658049d915ec860f590603ae5413ca7
[]
no_license
sevlat/OrLogic
f0c3efe19fc5831c925431cea2d4f706269314ce
d2d8b533e6b01869cf803ddc86d456889fa29920
refs/heads/master
2020-05-30T19:45:10.943674
2013-06-12T21:37:06
2013-06-12T21:37:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,735
h
#ifndef CmdDispatcher_h_already_included__19_01_2013__731FC38 #define CmdDispatcher_h_already_included__19_01_2013__731FC38 // // SeVlaT, 19.01.2013 // #include "Types.h" #include "Commands.h" struct TProtCmdPacket; /////////////////////////////////////////////////////////////////////////////// template<typename DERIVED> class TSplitDisp { public: template<typename C> bool Try() { return Try((const C*)0); } private: template <TCmdCode CC> bool Try(const TCommandBase<CC, TagFwd>*) { return Self().CheckCode(CC) && Self().TryF<TCommand<CC, TagFwd> >(); } template <TCmdCode CC> bool Try(const TCommandBase<CC, TagBwd>*) { return Self().CheckCode(CC) && Self().TryB<TCommand<CC, TagBwd> >(); } template <TCmdCode CC> bool Try(const TCmdPair<CC>*) { return CheckCode(TCmdPair<CC>::ccF, TCmdPair<CC>::ccB) && Self().TryP<TCmdPair<CC> >(); } private: bool CheckCode(TCmdCode cc) { return Self().CheckCode(cc); } bool CheckCode(TCmdCode ccF, TCmdCode ccB) { if (ccF==ccB) return Self().CheckCode(ccF); return Self().CheckCode(ccF) || Self().CheckCode(ccB); } DERIVED& Self() { return static_cast<DERIVED&>(*this); } }; //////////////////////////////////////////////////////////////////////////////// template<typename FHANDLER, typename BHANDLER, typename RHANDLER> class TPacketDispFB: public TSplitDisp<TPacketDispFB<FHANDLER, BHANDLER, RHANDLER> > { public: explicit TPacketDispFB( FHANDLER &FHandler, BHANDLER &BHandler, RHANDLER &RHandler, const TProtCmdPacket &pkt) : m_FHandler(FHandler), m_BHandler(BHandler), m_RHandler(RHandler), m_pkt(pkt) {} bool CheckCode(TCmdCode cc) const { return m_pkt.cc==cc; } template <typename CMDP> bool TryP() const { return m_FHandler.Try<CMDP::TFCmd>(m_pkt) || m_BHandler.Try<CMDP::TBCmd>(m_pkt) || m_RHandler.Unhandled(m_pkt); } template <typename CMD> bool TryF() const { return m_FHandler.Try<CMD>(m_pkt) || m_RHandler.Unhandled(m_pkt); } template <typename CMD> bool TryB() const { return m_BHandler.Try<CMD>(m_pkt) || m_RHandler.Unhandled(m_pkt); } private: FHANDLER &m_FHandler; BHANDLER &m_BHandler; RHANDLER &m_RHandler; private: const TProtCmdPacket &m_pkt; }; //////////////////////////////////////////////////////////////////////////////// template<typename DIR, typename HANDLER, typename RHANDLER> class TPacketDisp; template<typename FHANDLER, typename RHANDLER> class TPacketDisp<TagFwd, FHANDLER, RHANDLER>: public TSplitDisp<TPacketDisp<TagFwd, FHANDLER, RHANDLER> > { public: explicit TPacketDisp( FHANDLER &FHandler, RHANDLER &RHandler, const TProtCmdPacket &pkt) : m_FHandler(FHandler), m_RHandler(RHandler), m_pkt(pkt) {} bool CheckCode(TCmdCode cc) const { return m_pkt.cc==cc; } template <typename CMDP> bool TryP() const { return m_FHandler.Try<CMDP::TFCmd>(m_pkt) || m_RHandler.Unhandled(m_pkt); } template <typename CMD> bool TryF() const { return m_FHandler.Try<CMD>(m_pkt) || m_RHandler.Unhandled(m_pkt); } template <typename CMD> bool TryB() const { return m_RHandler.Unhandled(m_pkt); } private: FHANDLER &m_FHandler; RHANDLER &m_RHandler; private: const TProtCmdPacket &m_pkt; }; //////////////////////////////////////////////////////////////////////////////// template<typename BHANDLER, typename RHANDLER> class TPacketDisp<TagBwd, BHANDLER, RHANDLER>: public TSplitDisp<TPacketDisp<TagBwd, BHANDLER, RHANDLER> > { public: explicit TPacketDisp( BHANDLER &BHandler, RHANDLER &RHandler, const TProtCmdPacket &pkt) : m_BHandler(BHandler), m_RHandler(RHandler), m_pkt(pkt) {} bool CheckCode(TCmdCode cc) const { return m_pkt.cc==cc; } template <typename CMDP> bool TryP() const { return m_BHandler.Try<CMDP::TBCmd>(m_pkt) || m_RHandler.Unhandled(m_pkt); } template <typename CMD> bool TryF() const { return m_RHandler.Unhandled(m_pkt); } template <typename CMD> bool TryB() const { return m_BHandler.Try<CMD>(m_pkt) || m_RHandler.Unhandled(m_pkt); } private: BHANDLER &m_BHandler; RHANDLER &m_RHandler; private: const TProtCmdPacket &m_pkt; }; //////////////////////////////////////////////////////////////////////////////// #endif
[ "sevlat@mail.ru" ]
sevlat@mail.ru
367e868321b09f20b7fad48d8d2aad108c751120
2ce5246d19d55211172d79b4091aeafd73e77a27
/Problems/boj17419.cpp
10a5d7785f7edbddd6b21da8500e7bd6188cd029
[]
no_license
MingNine9999/algorithm
49e76a1fbcdbeea8388491c793f31ee6866054ae
76be13e394e3e96cdcec0de9390f1fd573d442c5
refs/heads/master
2021-04-23T09:09:05.097401
2020-09-11T16:23:29
2020-09-11T16:23:29
249,915,663
2
0
null
null
null
null
UTF-8
C++
false
false
361
cpp
//Problem Number : 17419 //Problem Title : 비트가 넘쳐흘러 //Problem Link : https://www.acmicpc.net/problem/17419 #include <cstdio> using namespace std; char a[1111111]; int main(void) { int n = 0; scanf("%d", &n); scanf("%s", a); n = 0; for (int i = 0; a[i] != 0; i++) { if (a[i] == '1') { n++; } } printf("%d\n", n); return 0; }
[ "mingu.song@nhn.com" ]
mingu.song@nhn.com
7dc366ca35f549e21087b13233f5e650dffb3713
555b6971c92299b14ead2e4cfc90d499e6b971d5
/Competitive Programming/gym/Lista de Carnaval/l1/q7.cpp
ecf0e34fa6a6f7711dcc04a460b8297179c1740a
[]
no_license
M-Rodrigues/Programming
dc538cde56545c2477276093617e18385d2401cb
ebc782f721fca3a0ee81449dd78b75f7ef332f5f
refs/heads/master
2020-04-16T10:48:38.730265
2019-08-02T02:47:19
2019-08-02T02:47:19
165,517,658
0
0
null
null
null
null
UTF-8
C++
false
false
866
cpp
#include<stdio.h> int main() { int a[41][41],i,j,n; unsigned long int sum=0; scanf("%d",&n); for(i=0;i<=n;i++) { for(j=i;j>=0;j--) { if(i==0) { if(j==i) a[i][j]=1; } else if(i==1){ if(j==i) a[i][j]=1; if(j==0) a[i][j] = 1; } else { if(j==i) a[i][j]=1; if(j==i-1 && j>0) a[i][j] = a[i-1][j] + a[i-1][j-1]; if(j<i-1 && j>0) a[i][j] = a[i-1][j-1]+a[i-1][j]+a[i-1][j+1]; if(j==0) a[i][j] = a[i-1][j]+2*a[i-1][j+1]; } } } for(i=0;i<=n;i++) { for(j=0;j<=i;j++) { printf("%d ",a[i][j]); } printf("\n"); } sum = a[n][0]; for(i=1;i<=n;i++) { sum += 2*a[n][i]; } printf("%lu\n",sum); return 0; }
[ "matheus.rodrigues.ime@gmail.com" ]
matheus.rodrigues.ime@gmail.com
5ae45d0d8884bbb80033f0352c3f44be587a8034
31063d113776e35dbd80d355dfd24ac7d7f8b451
/Practicas C++/Ordenamiento de Vectores/ejercicio 7_2.cpp
e56c4d28d91a59c3f18b391427751dfdc0c3ed8f
[]
no_license
MezaMaximiliano/Practicas_Cplusplus
8550b3ae8ae1878d2926b86e196528b2c40818e6
0388684b4ad54e29fd20cb3e72d8447adc9b8c85
refs/heads/master
2023-07-24T19:06:46.133155
2021-09-07T22:07:51
2021-09-07T22:07:51
404,133,431
0
0
null
null
null
null
ISO-8859-1
C++
false
false
2,834
cpp
#include<stdlib.h> #include<iostream> #include<string.h> using namespace std; struct dato { char nombre[15]; int dia; int mes; int anio; int fecha; }; typedef dato vector[60]; void pedirDatos (vector,int &); void buscar(vector,int &,int & ); int main(){ setlocale(LC_ALL, "spanish"); vector persona; int nFinal=0,posicion=0,i=0; char nombreBusqueda[15]; int respuesta=1; pedirDatos(persona,nFinal); while (respuesta==1){ buscar(persona,nFinal,respuesta); } system("pause"); return 0; } void buscar(vector persona,int &nFinal,int &respuesta){ int posicion=0,i=0; char nombreBusqueda[15]; cout<<"Nombre a buscar: "; cin>>nombreBusqueda; if (((strcmp(nombreBusqueda,"fin"))!=0)){ while ( ((strcmp(persona[i].nombre,nombreBusqueda))!=0) and (i<=nFinal) ){ i++; if ( strcmp(persona[i].nombre,nombreBusqueda)==0 ){ posicion=i; } } if (i<=nFinal-1){ // cout<<persona[posicion].nombre<<" nacio "<<persona[posicion].anio<<endl; if (posicion<1){ cout<<"posicion "<<posicion<<endl; cout<<"nFinal "<<nFinal<<endl; cout<<"Nombre buscado: "<<persona[posicion].nombre<<" y nacio "<<persona[posicion].anio<<endl; cout<<"No hay una posicion anterior"<<endl; cout<<"Posicion siguiente: "<<persona[posicion+1].nombre<<" y nacio "<<persona[posicion+1].anio<<endl; }else if (posicion==nFinal-1){ cout<<"posicion "<<posicion<<endl; cout<<"nFinal "<<nFinal<<endl; cout<<"Nombre buscado: "<<persona[posicion].nombre<<" y nacio "<<persona[posicion].anio<<endl; cout<<"Posicion anterior: "<<persona[posicion-1].nombre<<" y nacio "<<persona[posicion-1].anio<<endl; cout<<"No hay Posicion siguiente: "<<endl; }else if ( (posicion>=1)and(posicion<nFinal-1) ){ cout<<"posicion "<<posicion<<endl; cout<<"nFinal "<<nFinal<<endl; cout<<"Nombre buscado: "<<persona[posicion].nombre<<" y nacio "<<persona[posicion].anio<<endl; cout<<"Posicion anterior: "<<persona[posicion-1].nombre<<" y nacio "<<persona[posicion-1].anio<<endl; cout<<"Posicion siguiente: "<<persona[posicion+1].nombre<<" y nacio "<<persona[posicion+1].anio<<endl; } }else{ cout<<"No se encontro el nombre."<<endl; } }else{ respuesta=0; } } void pedirDatos(vector persona, int &nFinal){ char seguir[]="s"; int i=0; int condicion=1; for(i ; condicion==1;i++){ cout<<"Ingrese nombre: "; cin>>persona[i].nombre; cout<<"Ingrese dia de nacimiento: "; cin>>persona[i].dia; cout<<"Ingrese mes de nacimiento: "; cin>>persona[i].mes; cout<<"Ingrese año de nacimiento: "; cin>>persona[i].anio; cout<<"¿Desea seguir ingresando personas? S/N: "; cin>>seguir; strlwr(seguir); if (strcmp(seguir,"s")==0){ condicion=1; }else{ condicion=0; } } nFinal=i; }
[ "meza.maximiliano364@gmail.com" ]
meza.maximiliano364@gmail.com
e78826169c227238cf0f7b5f1aeeaac8a2067ac3
9dd3fbb1fd33aff84a0519739cad1b957e82f538
/object_manipulator/include/object_manipulator/grasp_execution/reactive_grasp_executor.h
b4207ed804c8adaa21d3d300d1a99916c7b766a6
[]
no_license
ipa320/cob_object_manipulation
cf454708d467687dfc26526fd506ec8fbfc5c9a0
3dbb6add8f5bdd389113ec37d8e3a274143382eb
refs/heads/master
2016-09-09T21:08:26.839910
2012-07-06T13:20:16
2012-07-06T13:20:16
2,564,106
0
6
null
null
null
null
UTF-8
C++
false
false
2,945
h
/********************************************************************* * * Copyright (c) 2009, 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 the Willow Garage 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. *********************************************************************/ #ifndef _REACTIVE_GRASP_EXECUTOR_H_ #define _REACTIVE_GRASP_EXECUTOR_H_ #include "object_manipulator/grasp_execution/grasp_executor_with_approach.h" namespace object_manipulator { class ReactiveGraspExecutor : public GraspExecutorWithApproach { protected: //! Uses move_arm to get to pre-grasp, then reactive grasping to grasp virtual object_manipulation_msgs::GraspResult executeGrasp(const object_manipulation_msgs::PickupGoal &pickup_goal, const object_manipulation_msgs::Grasp &grasp); //! Open loop lift that just executes a pre-set trajectory virtual object_manipulation_msgs::GraspResult nonReactiveLift(const object_manipulation_msgs::PickupGoal &pickup_goal); //! Lifting based on fingertip forces virtual object_manipulation_msgs::GraspResult reactiveLift(const object_manipulation_msgs::PickupGoal &pickup_goal); public: //! Only calls super constructor ReactiveGraspExecutor(GraspMarkerPublisher *pub) : GraspExecutorWithApproach(pub) {} //! Lifts the object starting from current gripper pose virtual object_manipulation_msgs::GraspResult lift(const object_manipulation_msgs::PickupGoal &pickup_goal); }; } //namespace object_manipulator #endif
[ "alexander.bubeck@ipa.fraunhofer.de" ]
alexander.bubeck@ipa.fraunhofer.de
3092c6487356cb82dd01f792f156ec9f966e1b82
7114e3edfa9b724e554b34e8651e56b796c986e7
/Session01/NullExample.h
475517e6ee2a08c25ceef68beff1fa3799c6996e
[]
no_license
SarlotaKonvickova/cpp1
42c3ea4e1498fc389c18f1f59678e0ad9934213c
183a3cdf0fc31d8f80366b51e3657a223e0a3855
refs/heads/master
2020-08-06T20:44:06.650497
2019-12-04T14:17:10
2019-12-04T14:17:10
213,146,590
0
0
null
null
null
null
UTF-8
C++
false
false
395
h
#ifndef CPP1_NULLEXAMPLE_H #define CPP1_NULLEXAMPLE_H #include <iostream> #include "AllocationMemory.h" void Foo(int i) { std::cout << i << std::endl; } void Foo(int* i) { //null ukazuje do 0 na pamet 0 - nepovoleny pristup do pameti std::cout << i << std::endl; int id; std::cin >> id; } void Sample() { Foo(NULL); Foo(nullptr); } #endif //CPP1_NULLEXAMPLE_H
[ "konvickova@pineal.cz" ]
konvickova@pineal.cz
7a08f489623393680db528439b549ac3e3717abd
0de9688de651ee81660dee187291bd97e5da1ee2
/tool/code/trunk/cxx/GUI/Core/source/ccipdUpdateVTKImageSlice.cxx
b963745fcb10683bd44a20933e8a85bbd1b9146a
[]
no_license
zengruizhao/Radiomics
2845cd7f17a46fae95be5d68b135ceda76ed4e44
34c1f1bff12fb994c904eaab0691f33819067003
refs/heads/master
2022-04-26T11:56:59.338297
2020-05-01T08:15:12
2020-05-01T08:15:12
257,222,358
3
0
null
null
null
null
UTF-8
C++
false
false
2,268
cxx
////////////////////////////////////////////////////////////////////////////////////////// // ccipd includes #include "ccipdUpdateVTKImageSlice.h" // std includes #include <iostream> #include "ccipdDisableWarningsMacro.h" // vtk includes #include <vtkSmartPointer.h> #include <vtkImageSlice.h> // the actual image prop #include <vtkImageSliceMapper.h> // for changing slices #include "ccipdEnableWarningsMacro.h" ////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// using std::cout; using std::cerr; using std::endl; ////////////////////////////////////////////////////////////////////////////////////////// namespace ccipd { ////////////////////////////////////////////////////////////////////////////////////////// void UpdateVTKImageSlice( vtkPropPointer & imageProp, const unsigned int slice, const bool verbose ) { // simple error checking if ( !imageProp ) { if ( verbose ) cout << "Error: No image prop to update!" << endl; return; } // imageProp // first, try to cast it if ( verbose ) cout << "Casting to image slice:" << endl; vtkImageSlice * const imageSlice = dynamic_cast< vtkImageSlice * >( imageProp.GetPointer() ); if ( !imageSlice ) { if ( verbose ) cerr << "Error: Unable to cast to image slice." << endl; return; } // imageSlice if ( verbose ) cout << "Casting to image slice done." << endl; // now, extract the mapper if ( verbose ) cout << "Extracting mapper:" << endl; vtkImageSliceMapper * const mapper = dynamic_cast< vtkImageSliceMapper * >( imageSlice->GetMapper() ); if ( !mapper ) { if ( verbose ) cerr << "Unable to extract mapper!" << endl; return; } // mapper if ( verbose ) cout << "Extracting mapper done." << endl; // now, update the slice if ( verbose ) cout << "Changing mapper slice:" << endl; mapper->SetSliceNumber( slice ); if ( verbose ) cout << "Changing mapper slice done." << endl; // all done! } // UpdateVTKImageSlice ////////////////////////////////////////////////////////////////////////////////////////// } // namespace ccipd
[ "zzr_nuist@163.com" ]
zzr_nuist@163.com
d1cedebd07d58b9037a12f4b74a64351f6828c2e
ebf2fba7ad36fb22d73e18c7fbf66b7ef8fdb976
/texk/web2c/xetexdir/XeTeXFontMgr.h
ec087da90bfbd23487866c3f5e3c5fe0522225e5
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-public-domain" ]
permissive
00mjk/lib-tex
391cf554e24736a00fb9c33f2690b7af1d8a4a3b
b815a302235e78215c8706c98792471e197f8431
refs/heads/master
2023-01-06T09:39:24.745386
2020-11-02T17:16:23
2020-11-02T17:16:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,494
h
/****************************************************************************\ Part of the XeTeX typesetting system Copyright (c) 1994-2008 by SIL International Copyright (c) 2009 by Jonathan Kew Copyright (c) 2012, 2013 by Jiang Jiang SIL Author(s): Jonathan Kew 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 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. Except as contained in this notice, the name of the copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from the copyright holders. \****************************************************************************/ #ifndef __XETEX_FONT_MANAGER_H #define __XETEX_FONT_MANAGER_H #ifdef XETEX_MAC #ifndef __IPHONE__ #include <ApplicationServices/ApplicationServices.h> #else #include <CoreText/CoreText.h> #endif typedef CTFontDescriptorRef PlatformFontRef; #else #include <fontconfig/fontconfig.h> #include <ft2build.h> #include FT_FREETYPE_H typedef FcPattern* PlatformFontRef; #endif #include "XeTeX_ext.h" #include "XeTeXLayoutInterface.h" #ifdef __cplusplus /* allow inclusion in plain C files just to get the typedefs above */ #include <string> #include <map> #include <list> #include <vector> class XeTeXFontMgr { public: static XeTeXFontMgr* GetFontManager(); // returns the global fontmanager (creating it if necessary) static void Terminate(); // clean up (may be required if using the cocoa implementation) PlatformFontRef findFont(const char* name, char* variant, double ptSize); // 1st arg is name as specified by user (C string, UTF-8) // 2nd is /B/I/AAT/OT/ICU/GR/S=## qualifiers // 1. try name given as "full name" // 2. if there's a hyphen, split and try "family-style" // 3. try as PostScript name // 4. try name as family with "Regular/Plain/Normal" style // apply style qualifiers and optical sizing if present // SIDE EFFECT: sets sReqEngine to 'A' or 'O' or 'G' if appropriate, // else clears it to 0 // SIDE EFFECT: updates TeX variables /nameoffile/ and /namelength/, // to match the actual font found // SIDE EFFECT: edits /variant/ string in-place removing /B or /I const char* getFullName(PlatformFontRef font) const; // return the full name of the font, suitable for use in XeTeX source // without requiring style qualifiers double getDesignSize(XeTeXFont font); char getReqEngine() const { return sReqEngine; }; // return the requested rendering technology for the most recent findFont // or 0 if no specific technology was requested void setReqEngine(char reqEngine) const { sReqEngine = reqEngine; }; protected: static XeTeXFontMgr* sFontManager; static char sReqEngine; XeTeXFontMgr() { } virtual ~XeTeXFontMgr() { } virtual void initialize() = 0; virtual void terminate(); virtual std::string getPlatformFontDesc(PlatformFontRef font) const = 0; class Font; class Family; struct OpSizeRec { double designSize; double minSize; double maxSize; unsigned int subFamilyID; unsigned int nameCode; }; class Font { public: Font(PlatformFontRef ref) : m_fullName(NULL), m_psName(NULL), m_familyName(NULL), m_styleName(NULL) , parent(NULL) , fontRef(ref), weight(0), width(0), slant(0) , isReg(false), isBold(false), isItalic(false) { opSizeInfo.subFamilyID = 0; opSizeInfo.designSize = 10.0; } /* default to 10.0pt */ ~Font() { delete m_fullName; delete m_psName; } std::string* m_fullName; std::string* m_psName; std::string* m_familyName; // default family and style names that should locate this font std::string* m_styleName; Family* parent; PlatformFontRef fontRef; OpSizeRec opSizeInfo; uint16_t weight; uint16_t width; int16_t slant; bool isReg; bool isBold; bool isItalic; }; class Family { public: Family() : minWeight(0), maxWeight(0) , minWidth(0), maxWidth(0) , minSlant(0), maxSlant(0) { styles = new std::map<std::string,Font*>; } ~Family() { delete styles; } std::map<std::string,Font*>* styles; uint16_t minWeight; uint16_t maxWeight; uint16_t minWidth; uint16_t maxWidth; int16_t minSlant; int16_t maxSlant; }; class NameCollection { public: std::list<std::string> m_familyNames; std::list<std::string> m_styleNames; std::list<std::string> m_fullNames; std::string m_psName; std::string m_subFamily; }; std::map<std::string,Font*> m_nameToFont; // maps full name (as used in TeX source) to font record std::map<std::string,Family*> m_nameToFamily; std::map<PlatformFontRef,Font*> m_platformRefToFont; std::map<std::string,Font*> m_psNameToFont; // maps PS name (as used in .xdv) to font record int weightAndWidthDiff(const Font* a, const Font* b) const; int styleDiff(const Font* a, int wt, int wd, int slant) const; Font* bestMatchFromFamily(const Family* fam, int wt, int wd, int slant) const; void appendToList(std::list<std::string>* list, const char* str); void prependToList(std::list<std::string>* list, const char* str); void addToMaps(PlatformFontRef platformFont, const NameCollection* names); const OpSizeRec* getOpSize(XeTeXFont font); virtual void getOpSizeRecAndStyleFlags(Font* theFont); virtual void searchForHostPlatformFonts(const std::string& name) = 0; virtual NameCollection* readNames(PlatformFontRef fontRef) = 0; void die(const char*s, int i) const; /* for fatal internal errors! */ }; #endif /* __cplusplus */ #endif /* __XETEX_FONT_MANAGER_H */
[ "nicolas.holzschuch@inria.fr" ]
nicolas.holzschuch@inria.fr
a3abd4d67014550b905ed492df5d4ea0adf378aa
622974cd61d5a4c6cb90ce39775198989e0a2b4c
/apps/cloud_composer/tools/statistical_outlier_removal.cpp
1cf5440bf9273810b6878db19e4aa016fe28f48e
[ "BSD-3-Clause" ]
permissive
kalectro/pcl_groovy
bd996ad15a7f6581c79fedad94bc7aaddfbaea0a
10b2f11a1d3b10b4ffdd575950f8c1977f92a83c
refs/heads/master
2021-01-22T21:00:10.455119
2013-05-13T02:44:37
2013-05-13T02:44:37
8,296,825
2
0
null
null
null
null
UTF-8
C++
false
false
3,507
cpp
#include <pcl/apps/cloud_composer/tools/statistical_outlier_removal.h> #include <pcl/apps/cloud_composer/items/cloud_item.h> #include <pcl/filters/statistical_outlier_removal.h> #include <pcl/point_types.h> Q_EXPORT_PLUGIN2(cloud_composer_statistical_outlier_removal_tool, pcl::cloud_composer::StatisticalOutlierRemovalToolFactory) pcl::cloud_composer::StatisticalOutlierRemovalTool::StatisticalOutlierRemovalTool (PropertiesModel* parameter_model, QObject* parent) : ModifyItemTool (parameter_model, parent) { } pcl::cloud_composer::StatisticalOutlierRemovalTool::~StatisticalOutlierRemovalTool () { } QList <pcl::cloud_composer::CloudComposerItem*> pcl::cloud_composer::StatisticalOutlierRemovalTool::performAction (ConstItemList input_data, PointTypeFlags::PointType type) { QList <CloudComposerItem*> output; const CloudComposerItem* input_item; // Check input data length if ( input_data.size () == 0) { qCritical () << "Empty input in StatisticalOutlierRemovalTool!"; return output; } else if ( input_data.size () > 1) { qWarning () << "Input vector has more than one item in StatisticalOutlierRemovalTool"; } input_item = input_data.value (0); if ( !input_item->isSanitized () ) { qCritical () << "StatisticalOutlierRemovalTool requires sanitized input!"; return output; } if (input_item->type () == CloudComposerItem::CLOUD_ITEM ) { sensor_msgs::PointCloud2::ConstPtr input_cloud = input_item->data (ItemDataRole::CLOUD_BLOB).value <sensor_msgs::PointCloud2::ConstPtr> (); int mean_k = parameter_model_->getProperty("Mean K").toInt (); double std_dev_thresh = parameter_model_->getProperty ("Std Dev Thresh").toDouble (); //////////////// THE WORK - FILTERING OUTLIERS /////////////////// // Create the filtering object pcl::StatisticalOutlierRemoval<sensor_msgs::PointCloud2> sor; sor.setInputCloud (input_cloud); sor.setMeanK (mean_k); sor.setStddevMulThresh (std_dev_thresh); //Create output cloud sensor_msgs::PointCloud2::Ptr cloud_filtered (new sensor_msgs::PointCloud2); //Filter! sor.filter (*cloud_filtered); ////////////////////////////////////////////////////////////////// //Get copies of the original origin and orientation Eigen::Vector4f source_origin = input_item->data (ItemDataRole::ORIGIN).value<Eigen::Vector4f> (); Eigen::Quaternionf source_orientation = input_item->data (ItemDataRole::ORIENTATION).value<Eigen::Quaternionf> (); //Put the modified cloud into an item, stick in output CloudItem* cloud_item = new CloudItem (input_item->text () + tr (" sor filtered") , cloud_filtered , source_origin , source_orientation); output.append (cloud_item); } else { qDebug () << "Input item in StatisticalOutlierRemovalTool is not a cloud!!!"; } return output; } /////////////////// PARAMETER MODEL ///////////////////////////////// pcl::cloud_composer::PropertiesModel* pcl::cloud_composer::StatisticalOutlierRemovalToolFactory::createToolParameterModel (QObject* parent) { PropertiesModel* parameter_model = new PropertiesModel(parent); parameter_model->addProperty ("Mean K", 50, Qt::ItemIsEditable | Qt::ItemIsEnabled); parameter_model->addProperty ("Std Dev Thresh", 1.0, Qt::ItemIsEditable | Qt::ItemIsEnabled); return parameter_model; }
[ "jkammerl@rbh.willowgarage.com" ]
jkammerl@rbh.willowgarage.com
0540a24e98a44c96ac58eed741e7f01dedb6c3d0
6588dbf2b104d121ebecf3cdc4ad33587132428d
/quickjs/src/main/jni/JsMethodProxy.cpp
4961a42ea058bc57fce814feeaf787f172c646bc
[ "MIT", "Apache-2.0" ]
permissive
chenguandong/duktape-android
ed9596688631a7fd32d105aaabe2dc588eeb4ca3
ffab0fbf06eb9315fbaa9cde62c746e7c96ab3a9
refs/heads/master
2020-09-10T06:36:19.455124
2019-11-06T16:32:19
2019-11-06T16:32:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,789
cpp
/* * Copyright (C) 2019 Square, Inc. * * 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 "JsMethodProxy.h" #include <algorithm> #include "Context.h" JsMethodProxy::JsMethodProxy(const Context* context, const char* name, jobject method) : name(name), methodId(context->env->FromReflectedMethod(method)) { JNIEnv* env = context->env; const jclass methodClass = env->GetObjectClass(method); const jmethodID getReturnType = env->GetMethodID(methodClass, "getReturnType", "()Ljava/lang/Class;"); const auto returnedClass = static_cast<jclass>(env->CallObjectMethod(method, getReturnType)); resultLoader = context->getJsToJavaConverter(returnedClass, true); env->DeleteLocalRef(returnedClass); if (!env->ExceptionCheck()) { const jmethodID isVarArgsMethod = env->GetMethodID(methodClass, "isVarArgs", "()Z"); isVarArgs = env->CallBooleanMethod(method, isVarArgsMethod); const jmethodID getParameterTypes = env->GetMethodID(methodClass, "getParameterTypes", "()[Ljava/lang/Class;"); jobjectArray parameterTypes = static_cast<jobjectArray>(env->CallObjectMethod(method, getParameterTypes)); const jsize numArgs = env->GetArrayLength(parameterTypes); for (jsize i = 0; i < numArgs && !env->ExceptionCheck(); ++i) { auto parameterType = env->GetObjectArrayElement(parameterTypes, i); argumentLoaders.push_back( context->getJavaToJsConverter(static_cast<jclass>(parameterType), true)); env->DeleteLocalRef(parameterType); } env->DeleteLocalRef(parameterTypes); } env->DeleteLocalRef(methodClass); } jobject JsMethodProxy::call(Context* context, JSValue thisPointer, jobjectArray args) const { const auto totalArgs = std::min<int>(argumentLoaders.size(), context->env->GetArrayLength(args)); std::vector<JSValue> arguments; int numArgs; jvalue arg; for (numArgs = 0; numArgs < totalArgs && !context->env->ExceptionCheck(); numArgs++) { arg.l = context->env->GetObjectArrayElement(args, numArgs); if (!isVarArgs || numArgs < totalArgs - 1) { arguments.push_back(argumentLoaders[numArgs](context, arg)); } else { auto varArgs = argumentLoaders[numArgs](context, arg); if (JS_IsArray(context->jsContext, varArgs)) { auto len = JS_GetPropertyStr(context->jsContext, varArgs, "length"); for (int i = 0, e = JS_VALUE_GET_INT(len); i < e; i++) { arguments.push_back(JS_GetPropertyUint32(context->jsContext, varArgs, i)); } JS_FreeValue(context->jsContext, len); JS_FreeValue(context->jsContext, varArgs); } else { arguments.push_back(varArgs); } } context->env->DeleteLocalRef(arg.l); } jobject result; if (!context->env->ExceptionCheck()) { auto property = JS_NewAtom(context->jsContext, name.c_str()); JSValue callResult = JS_Invoke(context->jsContext, thisPointer, property, arguments.size(), arguments.data()); JS_FreeAtom(context->jsContext, property); result = resultLoader(context, callResult).l; JS_FreeValue(context->jsContext, callResult); } else { result = nullptr; } for (JSValue argument : arguments) { JS_FreeValue(context->jsContext, argument); } return result; }
[ "shawn.zurbrigg@gmail.com" ]
shawn.zurbrigg@gmail.com
9cae1a947f502dee460709141eb986f478e6d371
8d0e4668d60f6381752cd9f601d9096dab750379
/babysteps/03/lib/loggger.h
ea046095ddaee731d3c37c383ecaaf2a3f3aaa83
[]
no_license
cab13e/lightwalk-sim
faeb464e9d89862131c6484eedb0b916ea513752
a25c16c84730e67d3d8298e5a324957e8da3d9f3
refs/heads/master
2021-05-16T12:13:03.377721
2017-09-29T03:17:29
2017-09-29T03:17:29
105,224,643
0
0
null
2017-09-29T03:15:13
2017-09-29T03:15:13
null
UTF-8
C++
false
false
458
h
#ifndef Loggger_h #define Loggger_h #include "application.h" #define ACTIVE true #define INACTIVE false class Loggger { public: Loggger(bool active, String name) { _active = active; _name = name; if (_active) { Serial.begin(9600); } } void log(String message) { if (_active) { Serial.print("[" + String(_name) + "] "); Serial.println(message); } } private: bool _active; String _name; }; #endif
[ "brent@twinbear.com" ]
brent@twinbear.com
89248bfe789d769f8d31f1a5b24cfa86ea68dcd6
6f7134e83f5fec27dead00d217dbae3d3e1ca51e
/TransBitmapAux/stdafx.cpp
5bb7bd49f056d86bc4a3c04170294737ec39f0c8
[]
no_license
amos42/WideViewer
fdb2d454d83dfbe0e4634bedb8b4fe7503ddd239
ad45abf4492fc9d7cf49c1d7f0bede86f085cb88
refs/heads/master
2022-05-14T21:25:42.801853
2022-05-03T10:32:35
2022-05-03T10:32:35
166,665,126
0
0
null
null
null
null
UHC
C++
false
false
337
cpp
// stdafx.cpp : 표준 포함 파일만 들어 있는 소스 파일입니다. // TransBitmap.pch는 미리 컴파일된 헤더가 됩니다. // stdafx.obj에는 미리 컴파일된 형식 정보가 포함됩니다. #include "stdafx.h" // TODO: 필요한 추가 헤더는 // 이 파일이 아닌 STDAFX.H에서 참조합니다.
[ "jcmh74@gmail.com" ]
jcmh74@gmail.com
c62767758626b5f7bb20ea3bd579476cd31274c9
efc1751123bcf28b603bcbe870eee6ca85bf1932
/2015_09_11/1_BINOM/main.cpp
9a9b814762fccf3e88544e6982eb30e8e914ffc9
[]
no_license
wheredyoufindthis/algorithms
87141e0495677b34b191bc0a3f71943786bbfa67
e12046252016fb044d6912a3330a4b219e13ab97
refs/heads/master
2021-05-30T03:35:45.974225
2015-12-18T12:38:36
2015-12-18T12:38:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,547
cpp
#include <iostream> #include <queue> #include <algorithm> #include <numeric> #include <cstdlib> #include "binomial_queue.cpp" void fill(binomial_queue<int> &b_queue, std::priority_queue<int> &queue, int count) { std::vector<int> content(count, 0); std::iota(content.begin(), content.end(), 1); while (content.size()) { int value = content.at(rand() % content.size()); content.erase(std::find(content.begin(), content.end(), value)); queue.push(value); b_queue.push(value); } } void pop(binomial_queue<int> &b_queue, std::priority_queue<int> &queue, size_t count) { while (count) { if (b_queue.top() != queue.top() || b_queue.size() != queue.size()) throw std::runtime_error("top test failed"); b_queue.pop(); queue.pop(); count--; } } void doTest() { for (int i = 1000; i <= 10000; i += 1000) { binomial_queue<int> b_queue; std::priority_queue<int> queue; try { fill(b_queue, queue, i); pop(b_queue, queue, i/2); fill(b_queue, queue, i/3); pop(b_queue, queue, i/5); fill(b_queue, queue, i); pop(b_queue, queue, b_queue.size()); std::cout << "passed :" << i << std::endl; } catch (std::exception &e) { std::cout << e.what() << std::endl; } } } int main() { doTest(); return 0; }
[ "Тулин Даниил@27ab2815-0c4e-2c49-80cd-d2551c38e382" ]
Тулин Даниил@27ab2815-0c4e-2c49-80cd-d2551c38e382
d1ac0c8ee0000722aebf2961950272c24f305bdd
4b100e0519f3362554bac7434baac61a1d08ddd2
/third_party/ros_aarch64/include/sensor_msgs/Illuminance.h
0ca49eb7f18bc5b740254f24555ad5a9b35348d6
[ "Apache-2.0" ]
permissive
YapingLiao/apollo1.0
17002fefaf01e0ee9f79713fd436c8c3386208b6
6e725e8dd5013b769efa18f43e5ae675f4847fbd
refs/heads/master
2020-06-18T13:04:52.019242
2018-01-29T01:50:43
2018-01-29T01:50:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,379
h
// Generated by gencpp from file sensor_msgs/Illuminance.msg // DO NOT EDIT! #ifndef SENSOR_MSGS_MESSAGE_ILLUMINANCE_H #define SENSOR_MSGS_MESSAGE_ILLUMINANCE_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <std_msgs/Header.h> namespace sensor_msgs { template <class ContainerAllocator> struct Illuminance_ { typedef Illuminance_<ContainerAllocator> Type; Illuminance_() : header() , illuminance(0.0) , variance(0.0) { } Illuminance_(const ContainerAllocator& _alloc) : header(_alloc) , illuminance(0.0) , variance(0.0) { (void)_alloc; } typedef ::std_msgs::Header_<ContainerAllocator> _header_type; _header_type header; typedef double _illuminance_type; _illuminance_type illuminance; typedef double _variance_type; _variance_type variance; typedef boost::shared_ptr< ::sensor_msgs::Illuminance_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::sensor_msgs::Illuminance_<ContainerAllocator> const> ConstPtr; }; // struct Illuminance_ typedef ::sensor_msgs::Illuminance_<std::allocator<void> > Illuminance; typedef boost::shared_ptr< ::sensor_msgs::Illuminance > IlluminancePtr; typedef boost::shared_ptr< ::sensor_msgs::Illuminance const> IlluminanceConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::sensor_msgs::Illuminance_<ContainerAllocator> & v) { ros::message_operations::Printer< ::sensor_msgs::Illuminance_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace sensor_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': True} // {'std_msgs': ['/home/ubuntu/baidu/adu-lab/apollo/third_party/ros/share/std_msgs/cmake/../msg'], 'geometry_msgs': ['/home/ubuntu/baidu/adu-lab/apollo/third_party/ros/share/geometry_msgs/cmake/../msg'], 'sensor_msgs': ['/home/ubuntu/baidu/adu-lab/apollo/modules/ros/common_msgs/sensor_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< ::sensor_msgs::Illuminance_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::sensor_msgs::Illuminance_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::sensor_msgs::Illuminance_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::sensor_msgs::Illuminance_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::sensor_msgs::Illuminance_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::sensor_msgs::Illuminance_<ContainerAllocator> const> : TrueType { }; template<class ContainerAllocator> struct MD5Sum< ::sensor_msgs::Illuminance_<ContainerAllocator> > { static const char* value() { return "8cf5febb0952fca9d650c3d11a81a188"; } static const char* value(const ::sensor_msgs::Illuminance_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x8cf5febb0952fca9ULL; static const uint64_t static_value2 = 0xd650c3d11a81a188ULL; }; template<class ContainerAllocator> struct DataType< ::sensor_msgs::Illuminance_<ContainerAllocator> > { static const char* value() { return "sensor_msgs/Illuminance"; } static const char* value(const ::sensor_msgs::Illuminance_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::sensor_msgs::Illuminance_<ContainerAllocator> > { static const char* value() { return " # Single photometric illuminance measurement. Light should be assumed to be\n\ # measured along the sensor's x-axis (the area of detection is the y-z plane).\n\ # The illuminance should have a 0 or positive value and be received with\n\ # the sensor's +X axis pointing toward the light source.\n\ \n\ # Photometric illuminance is the measure of the human eye's sensitivity of the\n\ # intensity of light encountering or passing through a surface.\n\ \n\ # All other Photometric and Radiometric measurements should\n\ # not use this message.\n\ # This message cannot represent:\n\ # Luminous intensity (candela/light source output)\n\ # Luminance (nits/light output per area)\n\ # Irradiance (watt/area), etc.\n\ \n\ Header header # timestamp is the time the illuminance was measured\n\ # frame_id is the location and direction of the reading\n\ \n\ float64 illuminance # Measurement of the Photometric Illuminance in Lux.\n\ \n\ float64 variance # 0 is interpreted as variance unknown\n\ ================================================================================\n\ MSG: std_msgs/Header\n\ # Standard metadata for higher-level stamped data types.\n\ # This is generally used to communicate timestamped data \n\ # in a particular coordinate frame.\n\ # \n\ # sequence ID: consecutively increasing ID \n\ uint32 seq\n\ #Two-integer timestamp that is expressed as:\n\ # * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\ # * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\ # time-handling sugar is provided by the client library\n\ time stamp\n\ #Frame this data is associated with\n\ # 0: no frame\n\ # 1: global frame\n\ string frame_id\n\ "; } static const char* value(const ::sensor_msgs::Illuminance_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::sensor_msgs::Illuminance_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.header); stream.next(m.illuminance); stream.next(m.variance); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct Illuminance_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::sensor_msgs::Illuminance_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::sensor_msgs::Illuminance_<ContainerAllocator>& v) { s << indent << "header: "; s << std::endl; Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header); s << indent << "illuminance: "; Printer<double>::stream(s, indent + " ", v.illuminance); s << indent << "variance: "; Printer<double>::stream(s, indent + " ", v.variance); } }; } // namespace message_operations } // namespace ros #endif // SENSOR_MSGS_MESSAGE_ILLUMINANCE_H
[ "14552258@qq.com" ]
14552258@qq.com
cb06fc7f02b20724ea4a5075b9155f444555a23f
1923bc8737243124e9b519683e5274d26df1db6a
/HomeworkAvg/homeworkAverage.cpp
a9b2d054fc09db0d3eaa632840fcf8643fc51ecb
[]
no_license
mattmcguin/CS-4102
3becc82f9e6ed4adbc3de33a9fc11fd99d2e6c77
6a86c6547e06df27373087442f84c46d68dea272
refs/heads/master
2020-03-17T01:31:22.821275
2018-05-12T15:26:46
2018-05-12T15:26:46
133,156,483
1
0
null
null
null
null
UTF-8
C++
false
false
2,697
cpp
// Author: Matt McGuiness #include <stdio.h> #include <math.h> typedef struct { int hw[15]; int lab[15]; int midtermScore; int finalScore; char studentID[20]; char firstName[20]; char lastName[20]; } Student; double calcHWAverage(int n, Student *student); double calcLabAverage(int n, Student *student); double Average(double lab, double hw, int midtermScore, int finalScore); int main() { FILE *inFile; int status; inFile = fopen("grades_2017.csv","r"); if (inFile==NULL) { // exit program if file not found printf("Error: grades_2017.csv not found!!\n"); return 1; } Student array[3]; int count = 0; char buffer[1000]; fgets(buffer, 1000, inFile); while (1) { // read the lines of data status = fscanf(inFile,"%[^,],\"", &array[count].studentID); status = fscanf(inFile,"%[^,], ", &array[count].lastName); status = fscanf(inFile,"%[^\"]", &array[count].firstName); status = fscanf(inFile,"%[^,],", &array[count].hw[0]); for (int i = 0; i < 15; i++) { status = fscanf(inFile,"%[^,],", &array[count].hw[i]); } for (int i = 0; i < 15; i++) { status = fscanf(inFile,"%[^,],", &array[count].lab[i]); } status = fscanf(inFile,"%[^,],", &array[count].midtermScore); status = fscanf(inFile,"%[^\t]", &array[count].finalScore); if (status==EOF) break; printf("%s \n%s \n%s\n %d\n",array[count].studentID, array[count].lastName, array[count].firstName, array[count].hw[0]); // for (int i= 0; i < 15; i++) { // printf("%d\n", array[count].hw[i]); // } count++; } fclose(inFile); for (int j = 0; j < 3; j++) { double hw = calcHWAverage(15, *array[i]); double lab = calcLabAverage(15, *array[i]); double average = (lab, hw, array[i].midtermScore, array[i].finalScore); printf("The average is: %lf \n", average); } return 0; } double calcHWAverage(int n, Student *student) { double average = 0.0; for (int i = 0; i < 15; i++) { average += (*student).hw[i]; } return average / 15.0; } double calcLabAverage(int n, Student *student) { double average = 0.0; for (int i = 0; i < 15; i++) { average += (*student).lab[i]; } return average / 15.0; } double Average(double lab, double hw, int midtermScore, int finalScore) { double grade = 0; grade = grade + lab * .4; grade = grade + hw * .15; grade = grade + midtermScore * .2; grade = grade + finalScore * .25; return grade; }
[ "mattjmcguiness@gmail.com" ]
mattjmcguiness@gmail.com
01923e710c8a6ccc3bf4c535412cbeb4769a6631
b9fec5de8fc07b11688c86e1a69a5e8368279b0a
/CPP/OOP/CMaking/OOP_laba1/source_only/empl.h
120a30fb1da199d71c16537280ca3b757a1140a0
[]
no_license
qasqad/other_examples
1017269f59a21451e813cb254bc8b689eab6b452
e7afe5fff0f2feb76bbc109166bf3f023b186a13
refs/heads/master
2023-06-22T12:38:55.534124
2023-06-18T22:12:59
2023-06-18T22:12:59
238,759,813
0
0
null
null
null
null
UTF-8
C++
false
false
921
h
#pragma once #include <string> #include <iostream> using namespace std; class empl { string nm; // имя int age; // возраст string lv; // должность public: empl(); // конструктор без параметров empl(string nm2, int age2, string lv2); // конструктор с параметрами empl(const empl& em); // конструктор копирования ~empl(); // деструктор // селекторы string getNm() const; int getAge() const; string getLv() const; // модификаторы void setNm(string nm12); void setAge(int age12); void setLv(string lv12); void setempl(string nm3, int age3, string lv3); void shw() const; };
[ "en@noemail.com" ]
en@noemail.com
eeb6221b191db3f742b9c176e0eeb9ef8c0e350d
ea0033701bcdfe49eec621d9f15484f5745772f7
/c++11/mygrep/QueryResult.h
7bf8310032e20aeb8b10974ad4cc5a9f995d7def
[]
no_license
domyhero/Experiment
78e35422eec8983d4cb3b137a7b0e94edfab6fdc
5ef7bccc739fabc9283fdaf9e7130016f78f0a59
refs/heads/master
2021-06-15T08:04:15.507936
2017-03-31T16:16:32
2017-03-31T16:16:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,133
h
// ===================================================================================== // // Filename: QueryResult.h // // Description: // // Version: 1.0 // Created: 2013年11月04日 17时01分46秒 // Revision: none // Compiler: g++ // // Author: Hurley (LiuHuan), liuhuan1992@gmail.com // Company: Class 1107 of Computer Science and Technology // // ===================================================================================== #ifndef QUERYRESULT_INC #define QUERYRESULT_INC #include <memory> #include <vector> #include <set> #include <map> #include "QueryResult.h" class QueryResult { using line_no = std::vector<std::string>::size_type; friend std::ostream& print(std::ostream &, const QueryResult &); public: QueryResult(std::string s, std::shared_ptr<std::set<line_no>> p, std::shared_ptr<std::vector<std::string>> f) : sought(s), lines(p), file(f) {} private: std::string sought; std::shared_ptr<std::set<line_no>> lines; std::shared_ptr<std::vector<std::string>> file; }; #endif // ----- #ifndef QUERYRESULT_INC -----
[ "liuhuan1992@gmail.com" ]
liuhuan1992@gmail.com
4d8cb1e7df00ed49a3162ef870825c99e161749c
b534f120a3a1ec46b34bf4f1dba6208a25de205d
/src/lib/additup/messagefactory.cc
fd7546f4a27b049cc2308d436734c4257b81988e
[]
no_license
chinitadelrey/additup
b4e1a3e81cd936689b85e288d4895e67de5e9582
4f2813a0e87b8c507d072a42a8e1594dae75cdc9
refs/heads/master
2021-05-26T14:27:14.938775
2012-05-16T13:02:37
2012-05-16T13:53:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,010
cc
// ---------------------------------------------------------------------------- // Project: additup /// @file messagefactory.cc /// @author Andy Parkins // // Version Control // $Author$ // $Date$ // $Id$ // // Legal // Copyright 2011 Andy Parkins // // ---------------------------------------------------------------------------- // Module include #include "messagefactory.h" // -------------- Includes // --- C // --- C++ #include <sstream> #include <memory> // --- Qt // --- OS // --- Project libs #include <general/logstream.h> // --- Project #include "messages.h" #include "script.h" #include "peer.h" #include "bitcoinnetwork.h" // -------------- Namespace // -------------- Module Globals // -------------- World Globals (need "extern"s in header) // -------------- Template instantiations // -------------- Class declarations // // Function: TMessageFactory :: TMessageFactory // Description: // TMessageFactory::TMessageFactory() : Initialised( false ), Peer( NULL ) { } // // Function: TMessageFactory :: ~TMessageFactory // Description: // TMessageFactory::~TMessageFactory() { // Tidy up the template messages we made while( !Templates.empty() ) { delete Templates.front(); Templates.erase( Templates.begin() ); } } // // Function: TMessageFactory :: receive // Description: // receive() handles the conversion of raw bytes from the peer to a // TMessage child. // void TMessageFactory::receive( const string &s ) { list<const TMessage*>::const_iterator it; RXBuffer += s; istringstream iss( RXBuffer ); iss.exceptions( ios::eofbit | ios::failbit | ios::badbit ); // We should be initialised if we want the templates to be available if( !Initialised ) init(); streamoff sp = 0; if( Peer == NULL ) throw runtime_error("TMessageFactory::receive() is impossible without a known peer"); while( !iss.str().empty() && sp < iss.str().size() ) { TMessage *WorkingClone = NULL; // --- Sync string::size_type pos = findNextMagic(iss.str(), sp); if( pos == string::npos || pos >= iss.str().size() ) { // If there is no magic in the string, then there is no point // looking for a message in it. This buffer is nothing we // can read, so we discard all of it. // log() << "Discarding " << RXBuffer.size() << endl; RXBuffer.clear(); // XXX: What about the last 1-3 bytes? break; } else { // log() << "Ignoring " << pos << endl; // Anything before the magic has been read or isn't a // message RXBuffer = RXBuffer.substr( pos, RXBuffer.size() - pos ); // And now repoint the stringstream at this shortened buffer iss.str( RXBuffer ); iss.seekg( 0, ios::beg ); } // --- Try to read // bookmark position sp = iss.tellg(); // Test against each template message for( it = Templates.begin(); it != Templates.end(); it++ ) { // The clone gets automatically deleted unless we release // the auto_ptr auto_ptr<TMessage> AutoTidyClone( (*it)->clone() ); AutoTidyClone->setPeer( Peer ); // Clear outstanding exceptions iss.clear(); // Restore our bookmark iss.seekg( sp, ios::beg ); try { // Attempt read AutoTidyClone->read( iss ); } catch( ios::failure &e ) { // log() << "[FACT] Parser at byte " << sp << "/" << iss.str().size(); // log() << " D: "; // TLog::hexify( log(), iss.str() ); // log() << " - " << e.what() << ", " << (*it)->className() << endl; // If we run out of message from the source, then we // leave the pointer where it is, while in principle // this is identical to the underflow error, it only // gets thrown by body reads not header reads. Fail // during a body read means the packet was correctly // identified, there was just insufficient data. We // therefore return in the hopes that we'll get some // more return; } catch( message_parse_error_underflow &e ) { // log() << "[FACT] Parser at byte " << sp << "/" << iss.str().size(); // log() << " D: "; // TLog::hexify( log(), iss.str() ); // log() << " - " << e.what() << ", " << (*it)->className() << endl; // Same as above, but caught by the parser return; } catch( message_parse_error_magic &e ) { log() << "[FACT] Parser at byte " << sp << "/" << iss.str().size(); TLog::hexify( log(), iss.str() ); log() << " - " << e.what() << ", " << (*it)->className() << endl; // A magic error applies to all message types, so we // break out of this loop, there is no point trying // other templates break; } catch( message_parse_error_version &e ) { log() << "[FACT] Parser at byte " << sp << "/" << RXBuffer.size(); log() << " D: "; TLog::hexify( log(), RXBuffer ); log() << " - " << e.what() << ", " << (*it)->className() << endl; // Version errors shouldn't happen after versioning has // taken place, it means a TMessage_version_X was used // to read a version message that had a lower value than // it supported. When versioning is active (handshaking // mode in TBitcoinPeer), this is exactly the same error // as a type error: not a problem, and we simply try // the next template. continue; } catch( message_parse_error_type &e ) { // log() << "[FACT] Parser at byte " << sp << "/" << RXBuffer.size(); // log() << " D: "; // TLog::hexify( log(), RXBuffer ); // log() << " - " << e.what() << ", " << (*it)->className() << endl; // This incoming stream contains a message that is of a // different type than the template; this is perfectly // normal, most of the time the template won't be the // right type, we simply try next template with the same data continue; } catch( message_parse_error &e ) { log() << "[FACT] Parser at byte " << sp << "/" << RXBuffer.size(); log() << " D: "; TLog::hexify( log(), RXBuffer ); log() << " - " << e.what() << ", " << (*it)->className() << endl; // Any other error from the parser means we can't handle // this message sp += 1; continue; } // If there were no errors, we can release the auto_ptr, and // pass it out of the loop WorkingClone = AutoTidyClone.get(); AutoTidyClone.release(); break; } if( WorkingClone != NULL ) { // If the read successfully converted bytes into a TMessage // then push it onto the receive queue Peer->queueIncoming( WorkingClone ); // The data we've parsed can be removed from the stream sp = iss.tellg(); // log() << "Eaten " << sp << " to make " << *WorkingClone << endl; RXBuffer = RXBuffer.substr( sp, RXBuffer.size() - sp ); // Repoint the stringstream at this shortened buffer iss.str( RXBuffer ); // ... and point at the start sp = 0; if( !continuousParse() ) break; } else { // Not having found a message makes it harder to predict // were we should start the next search for the magic. The // best we can do is start one byte along and try again. sp += 1; } } } // // Function: TMessageFactory :: findNextMagic // Description: // string::size_type TMessageFactory::findNextMagic( const string &s, string::size_type start ) const { if( Peer == NULL || Peer->getNetworkParameters() == NULL ) { // If we have no peer, then we have no magic available, // which makes it hard to synchronise. We'll have // to fall back to moving one byte at a time // log() << "Magic search impossible" << endl; return start; } // Convert the magic to a string TLittleEndian32Element Magic; Magic = Peer->getNetworkParameters()->Magic; ostringstream oss; oss << Magic; // log() << "Next magic "; // TLog::hexify( log(), oss.str() ); // log() << " from " << start; start = s.find( oss.str(), start ); if( start == string::npos ) { // log() << " not found" << endl; return s.size(); } // log() << " found at buffer position " << start << endl; return start; } // // Function: TMessageFactory :: init // Description: // void TMessageFactory::init() { list<const TMessage*>::const_iterator it; // Set the template flag on any messages the child class created for( it = Templates.begin(); it != Templates.end(); it++ ) { (*it)->setTemplate( true ); } Initialised = true; } // --------- // // Function: TVersioningMessageFactory :: init // Description: // void TVersioningMessageFactory::init() { // Must be in reverse order of version so that the highest matches // first Templates.push_back( new TMessage_version_31402() ); Templates.push_back( new TMessage_version_20900() ); Templates.push_back( new TMessage_version_10600() ); Templates.push_back( new TMessage_version_1() ); TMessageFactory::init(); } // --------- // // Function: TMessageFactory_1 :: init // Description: // void TMessageFactory_1::init() { // Templates.push_back( new TMessage_version_1() ); Templates.push_back( new TMessage_verack() ); Templates.push_back( new TMessage_addr_1() ); Templates.push_back( new TMessage_inv() ); Templates.push_back( new TMessage_getdata() ); Templates.push_back( new TMessage_getblocks() ); Templates.push_back( new TMessage_tx() ); Templates.push_back( new TMessage_block() ); Templates.push_back( new TMessage_getaddr() ); Templates.push_back( new TMessage_checkorder() ); Templates.push_back( new TMessage_submitorder() ); Templates.push_back( new TMessage_reply() ); Templates.push_back( new TMessage_ping() ); Templates.push_back( new TMessage_alert() ); TMessageFactory::init(); } // // Function: TMessageFactory_1 :: createVersionedBitcoinScript // Description: // TBitcoinScript *TMessageFactory_1::createVersionedBitcoinScript() const { return new TBitcoinScript_1; } // --------- // // Function: TMessageFactory_10600 :: init // Description: // void TMessageFactory_10600::init() { // Templates.push_back( new TMessage_version_10600() ); Templates.push_back( new TMessage_verack() ); Templates.push_back( new TMessage_addr_1() ); Templates.push_back( new TMessage_inv() ); Templates.push_back( new TMessage_getdata() ); Templates.push_back( new TMessage_getblocks() ); Templates.push_back( new TMessage_tx() ); Templates.push_back( new TMessage_block() ); Templates.push_back( new TMessage_getaddr() ); Templates.push_back( new TMessage_checkorder() ); Templates.push_back( new TMessage_submitorder() ); Templates.push_back( new TMessage_reply() ); Templates.push_back( new TMessage_ping() ); Templates.push_back( new TMessage_alert() ); TMessageFactory::init(); } // // Function: TMessageFactory_10600 :: createVersionedBitcoinScript // Description: // TBitcoinScript *TMessageFactory_10600::createVersionedBitcoinScript() const { return new TBitcoinScript_1; } // --------- // // Function: TMessageFactory_20900 :: init // Description: // void TMessageFactory_20900::init() { // Templates.push_back( new TMessage_version_20900() ); Templates.push_back( new TMessage_verack() ); Templates.push_back( new TMessage_addr_1() ); Templates.push_back( new TMessage_inv() ); Templates.push_back( new TMessage_getdata() ); Templates.push_back( new TMessage_getblocks() ); Templates.push_back( new TMessage_tx() ); Templates.push_back( new TMessage_block() ); Templates.push_back( new TMessage_getaddr() ); Templates.push_back( new TMessage_checkorder() ); Templates.push_back( new TMessage_submitorder() ); Templates.push_back( new TMessage_reply() ); Templates.push_back( new TMessage_ping() ); Templates.push_back( new TMessage_alert() ); TMessageFactory::init(); } // // Function: TMessageFactory_20900 :: createVersionedBitcoinScript // Description: // TBitcoinScript *TMessageFactory_20900::createVersionedBitcoinScript() const { return new TBitcoinScript_1; } // --------- // // Function: TMessageFactory_31402 :: init // Description: // void TMessageFactory_31402::init() { // Templates.push_back( new TMessage_version_20900() ); Templates.push_back( new TMessage_verack() ); Templates.push_back( new TMessage_addr_31402() ); Templates.push_back( new TMessage_inv() ); Templates.push_back( new TMessage_getdata() ); Templates.push_back( new TMessage_getblocks() ); Templates.push_back( new TMessage_getheaders() ); Templates.push_back( new TMessage_tx() ); Templates.push_back( new TMessage_block() ); Templates.push_back( new TMessage_headers() ); Templates.push_back( new TMessage_getaddr() ); Templates.push_back( new TMessage_checkorder() ); Templates.push_back( new TMessage_submitorder() ); Templates.push_back( new TMessage_reply() ); Templates.push_back( new TMessage_ping() ); Templates.push_back( new TMessage_alert() ); TMessageFactory::init(); } // // Function: TMessageFactory_31402 :: createVersionedBitcoinScript // Description: // TBitcoinScript *TMessageFactory_31402::createVersionedBitcoinScript() const { return new TBitcoinScript_1; } // -------------- Class member definitions // -------------- Function definitions #ifdef UNITTEST #include <iostream> #include "unittest.h" #include <general/logstream.h> #include "peer.h" // -------------- main() int main( int argc, char *argv[] ) { try { TBitcoinPeer Peer; TVersioningMessageFactory PF; PF.setPeer( &Peer ); log() << "--- " << PF.className() << endl; const string *p = UNITTESTSampleMessages; while( !p->empty() ) { PF.receive( *p ); if( Peer.newestIncoming() != NULL ) { log() << "PF.queue() = " << *Peer.newestIncoming() << endl; } else { log() << "no packet yet" << endl; } p++; } } catch( exception &e ) { log() << e.what() << endl; return 255; } try { TBitcoinPeer Peer; TMessageFactory_31402 PF; PF.setPeer( &Peer ); log() << "--- " << PF.className() << endl; const string *p = UNITTESTSampleMessages; while( !p->empty() ) { PF.receive( *p ); if( Peer.newestIncoming() != NULL ) { log() << "PF.queue() = " << *Peer.newestIncoming() << endl; } else { log() << "no packet yet" << endl; } p++; } } catch( exception &e ) { log() << e.what() << endl; return 255; } return 0; } #endif
[ "andyparkins@gmail.com" ]
andyparkins@gmail.com
91fd367d6e462a8ed841c88eee798f35a3b3f432
cc5a1bf6996614009c6370ee36d3210da5cb7139
/runtime/mac/AirGame-desktop.app/Contents/Resources/res/ch23/LostRoutes/frameworks/cocos2d-x/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp
468b20219896099d67d847025b7f60c7b8e616b3
[ "MIT" ]
permissive
huangjin0/AirGame
fd8218f7bbe2f9ca394156d20ee1ff1f6c311826
0e8cb5d53b17fb701ea7fe34b2d87dde473053f3
refs/heads/master
2021-01-21T18:11:22.363750
2017-05-23T06:59:45
2017-05-23T06:59:45
92,020,449
0
0
null
null
null
null
UTF-8
C++
false
false
1,953
cpp
/**************************************************************************** Copyright (c) 2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "platform/android/jni/JniHelper.h" #include <string.h> #include "base/CCDirector.h" #include "../CCApplication.h" #include "platform/CCFileUtils.h" #include "base/ccUTF8.h" static const std::string className = "org/cocos2dx/lib/Cocos2dxBitmap"; using namespace cocos2d; int getFontSizeAccordingHeightJni(int height) { return JniHelper::callStaticIntMethod(className, "getFontSizeAccordingHeight", height); } std::string getStringWithEllipsisJni(const char* text, float width, float fontSize) { return JniHelper::callStaticStringMethod(className, "getStringWithEllipsis", text, width, fontSize); }
[ "772361448@qq.com" ]
772361448@qq.com
bcc73cbaaa39a553a847450ece4020fa6744018f
dd80a584130ef1a0333429ba76c1cee0eb40df73
/art/compiler/dex/quick/gen_common.cc
8e31a25d9299836def73693e9bacd6268aad1ebe
[ "Apache-2.0", "MIT" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
68,646
cc
/* * Copyright (C) 2012 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 "dex/compiler_ir.h" #include "dex/compiler_internals.h" #include "dex/quick/arm/arm_lir.h" #include "dex/quick/mir_to_lir-inl.h" #include "entrypoints/quick/quick_entrypoints.h" #include "mirror/array.h" #include "verifier/method_verifier.h" namespace art { /* * This source files contains "gen" codegen routines that should * be applicable to most targets. Only mid-level support utilities * and "op" calls may be used here. */ /* * Generate an kPseudoBarrier marker to indicate the boundary of special * blocks. */ void Mir2Lir::GenBarrier() { LIR* barrier = NewLIR0(kPseudoBarrier); /* Mark all resources as being clobbered */ barrier->def_mask = -1; } // FIXME: need to do some work to split out targets with // condition codes and those without LIR* Mir2Lir::GenCheck(ConditionCode c_code, ThrowKind kind) { DCHECK_NE(cu_->instruction_set, kMips); LIR* tgt = RawLIR(0, kPseudoThrowTarget, kind, current_dalvik_offset_); LIR* branch = OpCondBranch(c_code, tgt); // Remember branch target - will process later throw_launchpads_.Insert(tgt); return branch; } LIR* Mir2Lir::GenImmedCheck(ConditionCode c_code, int reg, int imm_val, ThrowKind kind) { LIR* tgt = RawLIR(0, kPseudoThrowTarget, kind, current_dalvik_offset_, reg, imm_val); LIR* branch; if (c_code == kCondAl) { branch = OpUnconditionalBranch(tgt); } else { branch = OpCmpImmBranch(c_code, reg, imm_val, tgt); } // Remember branch target - will process later throw_launchpads_.Insert(tgt); return branch; } /* Perform null-check on a register. */ LIR* Mir2Lir::GenNullCheck(int s_reg, int m_reg, int opt_flags) { if (!(cu_->disable_opt & (1 << kNullCheckElimination)) && opt_flags & MIR_IGNORE_NULL_CHECK) { return NULL; } return GenImmedCheck(kCondEq, m_reg, 0, kThrowNullPointer); } /* Perform check on two registers */ LIR* Mir2Lir::GenRegRegCheck(ConditionCode c_code, int reg1, int reg2, ThrowKind kind) { LIR* tgt = RawLIR(0, kPseudoThrowTarget, kind, current_dalvik_offset_, reg1, reg2); LIR* branch = OpCmpBranch(c_code, reg1, reg2, tgt); // Remember branch target - will process later throw_launchpads_.Insert(tgt); return branch; } void Mir2Lir::GenCompareAndBranch(Instruction::Code opcode, RegLocation rl_src1, RegLocation rl_src2, LIR* taken, LIR* fall_through) { ConditionCode cond; switch (opcode) { case Instruction::IF_EQ: cond = kCondEq; break; case Instruction::IF_NE: cond = kCondNe; break; case Instruction::IF_LT: cond = kCondLt; break; case Instruction::IF_GE: cond = kCondGe; break; case Instruction::IF_GT: cond = kCondGt; break; case Instruction::IF_LE: cond = kCondLe; break; default: cond = static_cast<ConditionCode>(0); LOG(FATAL) << "Unexpected opcode " << opcode; } // Normalize such that if either operand is constant, src2 will be constant if (rl_src1.is_const) { RegLocation rl_temp = rl_src1; rl_src1 = rl_src2; rl_src2 = rl_temp; cond = FlipComparisonOrder(cond); } rl_src1 = LoadValue(rl_src1, kCoreReg); // Is this really an immediate comparison? if (rl_src2.is_const) { // If it's already live in a register or not easily materialized, just keep going RegLocation rl_temp = UpdateLoc(rl_src2); if ((rl_temp.location == kLocDalvikFrame) && InexpensiveConstantInt(mir_graph_->ConstantValue(rl_src2))) { // OK - convert this to a compare immediate and branch OpCmpImmBranch(cond, rl_src1.low_reg, mir_graph_->ConstantValue(rl_src2), taken); OpUnconditionalBranch(fall_through); return; } } rl_src2 = LoadValue(rl_src2, kCoreReg); OpCmpBranch(cond, rl_src1.low_reg, rl_src2.low_reg, taken); OpUnconditionalBranch(fall_through); } void Mir2Lir::GenCompareZeroAndBranch(Instruction::Code opcode, RegLocation rl_src, LIR* taken, LIR* fall_through) { ConditionCode cond; rl_src = LoadValue(rl_src, kCoreReg); switch (opcode) { case Instruction::IF_EQZ: cond = kCondEq; break; case Instruction::IF_NEZ: cond = kCondNe; break; case Instruction::IF_LTZ: cond = kCondLt; break; case Instruction::IF_GEZ: cond = kCondGe; break; case Instruction::IF_GTZ: cond = kCondGt; break; case Instruction::IF_LEZ: cond = kCondLe; break; default: cond = static_cast<ConditionCode>(0); LOG(FATAL) << "Unexpected opcode " << opcode; } OpCmpImmBranch(cond, rl_src.low_reg, 0, taken); OpUnconditionalBranch(fall_through); } void Mir2Lir::GenIntToLong(RegLocation rl_dest, RegLocation rl_src) { RegLocation rl_result = EvalLoc(rl_dest, kCoreReg, true); if (rl_src.location == kLocPhysReg) { OpRegCopy(rl_result.low_reg, rl_src.low_reg); } else { LoadValueDirect(rl_src, rl_result.low_reg); } OpRegRegImm(kOpAsr, rl_result.high_reg, rl_result.low_reg, 31); StoreValueWide(rl_dest, rl_result); } void Mir2Lir::GenIntNarrowing(Instruction::Code opcode, RegLocation rl_dest, RegLocation rl_src) { rl_src = LoadValue(rl_src, kCoreReg); RegLocation rl_result = EvalLoc(rl_dest, kCoreReg, true); OpKind op = kOpInvalid; switch (opcode) { case Instruction::INT_TO_BYTE: op = kOp2Byte; break; case Instruction::INT_TO_SHORT: op = kOp2Short; break; case Instruction::INT_TO_CHAR: op = kOp2Char; break; default: LOG(ERROR) << "Bad int conversion type"; } OpRegReg(op, rl_result.low_reg, rl_src.low_reg); StoreValue(rl_dest, rl_result); } /* * Let helper function take care of everything. Will call * Array::AllocFromCode(type_idx, method, count); * Note: AllocFromCode will handle checks for errNegativeArraySize. */ void Mir2Lir::GenNewArray(uint32_t type_idx, RegLocation rl_dest, RegLocation rl_src) { FlushAllRegs(); /* Everything to home location */ ThreadOffset func_offset(-1); if (cu_->compiler_driver->CanAccessTypeWithoutChecks(cu_->method_idx, *cu_->dex_file, type_idx)) { func_offset = QUICK_ENTRYPOINT_OFFSET(pAllocArray); } else { func_offset= QUICK_ENTRYPOINT_OFFSET(pAllocArrayWithAccessCheck); } CallRuntimeHelperImmMethodRegLocation(func_offset, type_idx, rl_src, true); RegLocation rl_result = GetReturn(false); StoreValue(rl_dest, rl_result); } /* * Similar to GenNewArray, but with post-allocation initialization. * Verifier guarantees we're dealing with an array class. Current * code throws runtime exception "bad Filled array req" for 'D' and 'J'. * Current code also throws internal unimp if not 'L', '[' or 'I'. */ void Mir2Lir::GenFilledNewArray(CallInfo* info) { int elems = info->num_arg_words; int type_idx = info->index; FlushAllRegs(); /* Everything to home location */ ThreadOffset func_offset(-1); if (cu_->compiler_driver->CanAccessTypeWithoutChecks(cu_->method_idx, *cu_->dex_file, type_idx)) { func_offset = QUICK_ENTRYPOINT_OFFSET(pCheckAndAllocArray); } else { func_offset = QUICK_ENTRYPOINT_OFFSET(pCheckAndAllocArrayWithAccessCheck); } CallRuntimeHelperImmMethodImm(func_offset, type_idx, elems, true); FreeTemp(TargetReg(kArg2)); FreeTemp(TargetReg(kArg1)); /* * NOTE: the implicit target for Instruction::FILLED_NEW_ARRAY is the * return region. Because AllocFromCode placed the new array * in kRet0, we'll just lock it into place. When debugger support is * added, it may be necessary to additionally copy all return * values to a home location in thread-local storage */ LockTemp(TargetReg(kRet0)); // TODO: use the correct component size, currently all supported types // share array alignment with ints (see comment at head of function) size_t component_size = sizeof(int32_t); // Having a range of 0 is legal if (info->is_range && (elems > 0)) { /* * Bit of ugliness here. We're going generate a mem copy loop * on the register range, but it is possible that some regs * in the range have been promoted. This is unlikely, but * before generating the copy, we'll just force a flush * of any regs in the source range that have been promoted to * home location. */ for (int i = 0; i < elems; i++) { RegLocation loc = UpdateLoc(info->args[i]); if (loc.location == kLocPhysReg) { StoreBaseDisp(TargetReg(kSp), SRegOffset(loc.s_reg_low), loc.low_reg, kWord); } } /* * TUNING note: generated code here could be much improved, but * this is an uncommon operation and isn't especially performance * critical. */ int r_src = AllocTemp(); int r_dst = AllocTemp(); int r_idx = AllocTemp(); int r_val = INVALID_REG; switch (cu_->instruction_set) { case kThumb2: r_val = TargetReg(kLr); break; case kX86: FreeTemp(TargetReg(kRet0)); r_val = AllocTemp(); break; case kMips: r_val = AllocTemp(); break; default: LOG(FATAL) << "Unexpected instruction set: " << cu_->instruction_set; } // Set up source pointer RegLocation rl_first = info->args[0]; OpRegRegImm(kOpAdd, r_src, TargetReg(kSp), SRegOffset(rl_first.s_reg_low)); // Set up the target pointer OpRegRegImm(kOpAdd, r_dst, TargetReg(kRet0), mirror::Array::DataOffset(component_size).Int32Value()); // Set up the loop counter (known to be > 0) LoadConstant(r_idx, elems - 1); // Generate the copy loop. Going backwards for convenience LIR* target = NewLIR0(kPseudoTargetLabel); // Copy next element LoadBaseIndexed(r_src, r_idx, r_val, 2, kWord); StoreBaseIndexed(r_dst, r_idx, r_val, 2, kWord); FreeTemp(r_val); OpDecAndBranch(kCondGe, r_idx, target); if (cu_->instruction_set == kX86) { // Restore the target pointer OpRegRegImm(kOpAdd, TargetReg(kRet0), r_dst, -mirror::Array::DataOffset(component_size).Int32Value()); } } else if (!info->is_range) { // TUNING: interleave for (int i = 0; i < elems; i++) { RegLocation rl_arg = LoadValue(info->args[i], kCoreReg); StoreBaseDisp(TargetReg(kRet0), mirror::Array::DataOffset(component_size).Int32Value() + i * 4, rl_arg.low_reg, kWord); // If the LoadValue caused a temp to be allocated, free it if (IsTemp(rl_arg.low_reg)) { FreeTemp(rl_arg.low_reg); } } } if (info->result.location != kLocInvalid) { StoreValue(info->result, GetReturn(false /* not fp */)); } } void Mir2Lir::GenSput(uint32_t field_idx, RegLocation rl_src, bool is_long_or_double, bool is_object) { int field_offset; int ssb_index; bool is_volatile; bool is_referrers_class; bool fast_path = cu_->compiler_driver->ComputeStaticFieldInfo( field_idx, mir_graph_->GetCurrentDexCompilationUnit(), field_offset, ssb_index, is_referrers_class, is_volatile, true); if (fast_path && !SLOW_FIELD_PATH) { DCHECK_GE(field_offset, 0); int rBase; if (is_referrers_class) { // Fast path, static storage base is this method's class RegLocation rl_method = LoadCurrMethod(); rBase = AllocTemp(); LoadWordDisp(rl_method.low_reg, mirror::ArtMethod::DeclaringClassOffset().Int32Value(), rBase); if (IsTemp(rl_method.low_reg)) { FreeTemp(rl_method.low_reg); } } else { // Medium path, static storage base in a different class which requires checks that the other // class is initialized. // TODO: remove initialized check now that we are initializing classes in the compiler driver. DCHECK_GE(ssb_index, 0); // May do runtime call so everything to home locations. FlushAllRegs(); // Using fixed register to sync with possible call to runtime support. int r_method = TargetReg(kArg1); LockTemp(r_method); LoadCurrMethodDirect(r_method); rBase = TargetReg(kArg0); LockTemp(rBase); LoadWordDisp(r_method, mirror::ArtMethod::DexCacheInitializedStaticStorageOffset().Int32Value(), rBase); LoadWordDisp(rBase, mirror::Array::DataOffset(sizeof(mirror::Object*)).Int32Value() + sizeof(int32_t*) * ssb_index, rBase); // rBase now points at appropriate static storage base (Class*) // or NULL if not initialized. Check for NULL and call helper if NULL. // TUNING: fast path should fall through LIR* branch_over = OpCmpImmBranch(kCondNe, rBase, 0, NULL); LoadConstant(TargetReg(kArg0), ssb_index); CallRuntimeHelperImm(QUICK_ENTRYPOINT_OFFSET(pInitializeStaticStorage), ssb_index, true); if (cu_->instruction_set == kMips) { // For Arm, kRet0 = kArg0 = rBase, for Mips, we need to copy OpRegCopy(rBase, TargetReg(kRet0)); } LIR* skip_target = NewLIR0(kPseudoTargetLabel); branch_over->target = skip_target; FreeTemp(r_method); } // rBase now holds static storage base if (is_long_or_double) { rl_src = LoadValueWide(rl_src, kAnyReg); } else { rl_src = LoadValue(rl_src, kAnyReg); } if (is_volatile) { GenMemBarrier(kStoreStore); } if (is_long_or_double) { StoreBaseDispWide(rBase, field_offset, rl_src.low_reg, rl_src.high_reg); } else { StoreWordDisp(rBase, field_offset, rl_src.low_reg); } if (is_volatile) { GenMemBarrier(kStoreLoad); } if (is_object && !mir_graph_->IsConstantNullRef(rl_src)) { MarkGCCard(rl_src.low_reg, rBase); } FreeTemp(rBase); } else { FlushAllRegs(); // Everything to home locations ThreadOffset setter_offset = is_long_or_double ? QUICK_ENTRYPOINT_OFFSET(pSet64Static) : (is_object ? QUICK_ENTRYPOINT_OFFSET(pSetObjStatic) : QUICK_ENTRYPOINT_OFFSET(pSet32Static)); CallRuntimeHelperImmRegLocation(setter_offset, field_idx, rl_src, true); } } void Mir2Lir::GenSget(uint32_t field_idx, RegLocation rl_dest, bool is_long_or_double, bool is_object) { int field_offset; int ssb_index; bool is_volatile; bool is_referrers_class; bool fast_path = cu_->compiler_driver->ComputeStaticFieldInfo( field_idx, mir_graph_->GetCurrentDexCompilationUnit(), field_offset, ssb_index, is_referrers_class, is_volatile, false); if (fast_path && !SLOW_FIELD_PATH) { DCHECK_GE(field_offset, 0); int rBase; if (is_referrers_class) { // Fast path, static storage base is this method's class RegLocation rl_method = LoadCurrMethod(); rBase = AllocTemp(); LoadWordDisp(rl_method.low_reg, mirror::ArtMethod::DeclaringClassOffset().Int32Value(), rBase); } else { // Medium path, static storage base in a different class which requires checks that the other // class is initialized // TODO: remove initialized check now that we are initializing classes in the compiler driver. DCHECK_GE(ssb_index, 0); // May do runtime call so everything to home locations. FlushAllRegs(); // Using fixed register to sync with possible call to runtime support. int r_method = TargetReg(kArg1); LockTemp(r_method); LoadCurrMethodDirect(r_method); rBase = TargetReg(kArg0); LockTemp(rBase); LoadWordDisp(r_method, mirror::ArtMethod::DexCacheInitializedStaticStorageOffset().Int32Value(), rBase); LoadWordDisp(rBase, mirror::Array::DataOffset(sizeof(mirror::Object*)).Int32Value() + sizeof(int32_t*) * ssb_index, rBase); // rBase now points at appropriate static storage base (Class*) // or NULL if not initialized. Check for NULL and call helper if NULL. // TUNING: fast path should fall through LIR* branch_over = OpCmpImmBranch(kCondNe, rBase, 0, NULL); CallRuntimeHelperImm(QUICK_ENTRYPOINT_OFFSET(pInitializeStaticStorage), ssb_index, true); if (cu_->instruction_set == kMips) { // For Arm, kRet0 = kArg0 = rBase, for Mips, we need to copy OpRegCopy(rBase, TargetReg(kRet0)); } LIR* skip_target = NewLIR0(kPseudoTargetLabel); branch_over->target = skip_target; FreeTemp(r_method); } // rBase now holds static storage base RegLocation rl_result = EvalLoc(rl_dest, kAnyReg, true); if (is_volatile) { GenMemBarrier(kLoadLoad); } if (is_long_or_double) { LoadBaseDispWide(rBase, field_offset, rl_result.low_reg, rl_result.high_reg, INVALID_SREG); } else { LoadWordDisp(rBase, field_offset, rl_result.low_reg); } FreeTemp(rBase); if (is_long_or_double) { StoreValueWide(rl_dest, rl_result); } else { StoreValue(rl_dest, rl_result); } } else { FlushAllRegs(); // Everything to home locations ThreadOffset getterOffset = is_long_or_double ? QUICK_ENTRYPOINT_OFFSET(pGet64Static) :(is_object ? QUICK_ENTRYPOINT_OFFSET(pGetObjStatic) : QUICK_ENTRYPOINT_OFFSET(pGet32Static)); CallRuntimeHelperImm(getterOffset, field_idx, true); if (is_long_or_double) { RegLocation rl_result = GetReturnWide(rl_dest.fp); StoreValueWide(rl_dest, rl_result); } else { RegLocation rl_result = GetReturn(rl_dest.fp); StoreValue(rl_dest, rl_result); } } } void Mir2Lir::HandleSuspendLaunchPads() { int num_elems = suspend_launchpads_.Size(); ThreadOffset helper_offset = QUICK_ENTRYPOINT_OFFSET(pTestSuspend); for (int i = 0; i < num_elems; i++) { ResetRegPool(); ResetDefTracking(); LIR* lab = suspend_launchpads_.Get(i); LIR* resume_lab = reinterpret_cast<LIR*>(lab->operands[0]); current_dalvik_offset_ = lab->operands[1]; AppendLIR(lab); int r_tgt = CallHelperSetup(helper_offset); CallHelper(r_tgt, helper_offset, true /* MarkSafepointPC */); OpUnconditionalBranch(resume_lab); } } void Mir2Lir::HandleIntrinsicLaunchPads() { int num_elems = intrinsic_launchpads_.Size(); for (int i = 0; i < num_elems; i++) { ResetRegPool(); ResetDefTracking(); LIR* lab = intrinsic_launchpads_.Get(i); CallInfo* info = reinterpret_cast<CallInfo*>(lab->operands[0]); current_dalvik_offset_ = info->offset; AppendLIR(lab); // NOTE: GenInvoke handles MarkSafepointPC GenInvoke(info); LIR* resume_lab = reinterpret_cast<LIR*>(lab->operands[2]); if (resume_lab != NULL) { OpUnconditionalBranch(resume_lab); } } } void Mir2Lir::HandleThrowLaunchPads() { int num_elems = throw_launchpads_.Size(); for (int i = 0; i < num_elems; i++) { ResetRegPool(); ResetDefTracking(); LIR* lab = throw_launchpads_.Get(i); current_dalvik_offset_ = lab->operands[1]; AppendLIR(lab); ThreadOffset func_offset(-1); int v1 = lab->operands[2]; int v2 = lab->operands[3]; const bool target_x86 = cu_->instruction_set == kX86; const bool target_arm = cu_->instruction_set == kArm || cu_->instruction_set == kThumb2; const bool target_mips = cu_->instruction_set == kMips; switch (lab->operands[0]) { case kThrowNullPointer: func_offset = QUICK_ENTRYPOINT_OFFSET(pThrowNullPointer); break; case kThrowConstantArrayBounds: // v1 is length reg (for Arm/Mips), v2 constant index // v1 holds the constant array index. Mips/Arm uses v2 for length, x86 reloads. if (target_x86) { OpRegMem(kOpMov, TargetReg(kArg1), v1, mirror::Array::LengthOffset().Int32Value()); } else { OpRegCopy(TargetReg(kArg1), v1); } // Make sure the following LoadConstant doesn't mess with kArg1. LockTemp(TargetReg(kArg1)); LoadConstant(TargetReg(kArg0), v2); func_offset = QUICK_ENTRYPOINT_OFFSET(pThrowArrayBounds); break; case kThrowArrayBounds: // Move v1 (array index) to kArg0 and v2 (array length) to kArg1 if (v2 != TargetReg(kArg0)) { OpRegCopy(TargetReg(kArg0), v1); if (target_x86) { // x86 leaves the array pointer in v2, so load the array length that the handler expects OpRegMem(kOpMov, TargetReg(kArg1), v2, mirror::Array::LengthOffset().Int32Value()); } else { OpRegCopy(TargetReg(kArg1), v2); } } else { if (v1 == TargetReg(kArg1)) { // Swap v1 and v2, using kArg2 as a temp OpRegCopy(TargetReg(kArg2), v1); if (target_x86) { // x86 leaves the array pointer in v2; load the array length that the handler expects OpRegMem(kOpMov, TargetReg(kArg1), v2, mirror::Array::LengthOffset().Int32Value()); } else { OpRegCopy(TargetReg(kArg1), v2); } OpRegCopy(TargetReg(kArg0), TargetReg(kArg2)); } else { if (target_x86) { // x86 leaves the array pointer in v2; load the array length that the handler expects OpRegMem(kOpMov, TargetReg(kArg1), v2, mirror::Array::LengthOffset().Int32Value()); } else { OpRegCopy(TargetReg(kArg1), v2); } OpRegCopy(TargetReg(kArg0), v1); } } func_offset = QUICK_ENTRYPOINT_OFFSET(pThrowArrayBounds); break; case kThrowDivZero: func_offset = QUICK_ENTRYPOINT_OFFSET(pThrowDivZero); break; case kThrowNoSuchMethod: OpRegCopy(TargetReg(kArg0), v1); func_offset = QUICK_ENTRYPOINT_OFFSET(pThrowNoSuchMethod); break; case kThrowStackOverflow: { func_offset = QUICK_ENTRYPOINT_OFFSET(pThrowStackOverflow); // Restore stack alignment int r_tgt = 0; const int spill_size = (num_core_spills_ + num_fp_spills_) * 4; if (target_x86) { // - 4 to leave link register on stack. OpRegImm(kOpAdd, TargetReg(kSp), frame_size_ - 4); ClobberCalleeSave(); } else if (target_arm) { r_tgt = r12; LoadWordDisp(TargetReg(kSp), spill_size - 4, TargetReg(kLr)); OpRegImm(kOpAdd, TargetReg(kSp), spill_size); ClobberCalleeSave(); LoadWordDisp(rARM_SELF, func_offset.Int32Value(), r_tgt); } else { DCHECK(target_mips); DCHECK_EQ(num_fp_spills_, 0); // FP spills currently don't happen on mips. // LR is offset 0 since we push in reverse order. LoadWordDisp(TargetReg(kSp), 0, TargetReg(kLr)); OpRegImm(kOpAdd, TargetReg(kSp), spill_size); ClobberCalleeSave(); r_tgt = CallHelperSetup(func_offset); // Doesn't clobber LR. DCHECK_NE(r_tgt, TargetReg(kLr)); } CallHelper(r_tgt, func_offset, false /* MarkSafepointPC */, false /* UseLink */); continue; } default: LOG(FATAL) << "Unexpected throw kind: " << lab->operands[0]; } ClobberCalleeSave(); int r_tgt = CallHelperSetup(func_offset); CallHelper(r_tgt, func_offset, true /* MarkSafepointPC */, true /* UseLink */); } } void Mir2Lir::GenIGet(uint32_t field_idx, int opt_flags, OpSize size, RegLocation rl_dest, RegLocation rl_obj, bool is_long_or_double, bool is_object) { int field_offset; bool is_volatile; bool fast_path = FastInstance(field_idx, field_offset, is_volatile, false); if (fast_path && !SLOW_FIELD_PATH) { RegLocation rl_result; RegisterClass reg_class = oat_reg_class_by_size(size); DCHECK_GE(field_offset, 0); rl_obj = LoadValue(rl_obj, kCoreReg); if (is_long_or_double) { DCHECK(rl_dest.wide); GenNullCheck(rl_obj.s_reg_low, rl_obj.low_reg, opt_flags); if (cu_->instruction_set == kX86) { rl_result = EvalLoc(rl_dest, reg_class, true); GenNullCheck(rl_obj.s_reg_low, rl_obj.low_reg, opt_flags); LoadBaseDispWide(rl_obj.low_reg, field_offset, rl_result.low_reg, rl_result.high_reg, rl_obj.s_reg_low); if (is_volatile) { GenMemBarrier(kLoadLoad); } } else { int reg_ptr = AllocTemp(); OpRegRegImm(kOpAdd, reg_ptr, rl_obj.low_reg, field_offset); rl_result = EvalLoc(rl_dest, reg_class, true); LoadBaseDispWide(reg_ptr, 0, rl_result.low_reg, rl_result.high_reg, INVALID_SREG); if (is_volatile) { GenMemBarrier(kLoadLoad); } FreeTemp(reg_ptr); } StoreValueWide(rl_dest, rl_result); } else { rl_result = EvalLoc(rl_dest, reg_class, true); GenNullCheck(rl_obj.s_reg_low, rl_obj.low_reg, opt_flags); LoadBaseDisp(rl_obj.low_reg, field_offset, rl_result.low_reg, kWord, rl_obj.s_reg_low); if (is_volatile) { GenMemBarrier(kLoadLoad); } StoreValue(rl_dest, rl_result); } } else { ThreadOffset getterOffset = is_long_or_double ? QUICK_ENTRYPOINT_OFFSET(pGet64Instance) : (is_object ? QUICK_ENTRYPOINT_OFFSET(pGetObjInstance) : QUICK_ENTRYPOINT_OFFSET(pGet32Instance)); CallRuntimeHelperImmRegLocation(getterOffset, field_idx, rl_obj, true); if (is_long_or_double) { RegLocation rl_result = GetReturnWide(rl_dest.fp); StoreValueWide(rl_dest, rl_result); } else { RegLocation rl_result = GetReturn(rl_dest.fp); StoreValue(rl_dest, rl_result); } } } void Mir2Lir::GenIPut(uint32_t field_idx, int opt_flags, OpSize size, RegLocation rl_src, RegLocation rl_obj, bool is_long_or_double, bool is_object) { int field_offset; bool is_volatile; bool fast_path = FastInstance(field_idx, field_offset, is_volatile, true); if (fast_path && !SLOW_FIELD_PATH) { RegisterClass reg_class = oat_reg_class_by_size(size); DCHECK_GE(field_offset, 0); rl_obj = LoadValue(rl_obj, kCoreReg); if (is_long_or_double) { int reg_ptr; rl_src = LoadValueWide(rl_src, kAnyReg); GenNullCheck(rl_obj.s_reg_low, rl_obj.low_reg, opt_flags); reg_ptr = AllocTemp(); OpRegRegImm(kOpAdd, reg_ptr, rl_obj.low_reg, field_offset); if (is_volatile) { GenMemBarrier(kStoreStore); } StoreBaseDispWide(reg_ptr, 0, rl_src.low_reg, rl_src.high_reg); if (is_volatile) { GenMemBarrier(kLoadLoad); } FreeTemp(reg_ptr); } else { rl_src = LoadValue(rl_src, reg_class); GenNullCheck(rl_obj.s_reg_low, rl_obj.low_reg, opt_flags); if (is_volatile) { GenMemBarrier(kStoreStore); } StoreBaseDisp(rl_obj.low_reg, field_offset, rl_src.low_reg, kWord); if (is_volatile) { GenMemBarrier(kLoadLoad); } if (is_object && !mir_graph_->IsConstantNullRef(rl_src)) { MarkGCCard(rl_src.low_reg, rl_obj.low_reg); } } } else { ThreadOffset setter_offset = is_long_or_double ? QUICK_ENTRYPOINT_OFFSET(pSet64Instance) : (is_object ? QUICK_ENTRYPOINT_OFFSET(pSetObjInstance) : QUICK_ENTRYPOINT_OFFSET(pSet32Instance)); CallRuntimeHelperImmRegLocationRegLocation(setter_offset, field_idx, rl_obj, rl_src, true); } } void Mir2Lir::GenConstClass(uint32_t type_idx, RegLocation rl_dest) { RegLocation rl_method = LoadCurrMethod(); int res_reg = AllocTemp(); RegLocation rl_result = EvalLoc(rl_dest, kCoreReg, true); if (!cu_->compiler_driver->CanAccessTypeWithoutChecks(cu_->method_idx, *cu_->dex_file, type_idx)) { // Call out to helper which resolves type and verifies access. // Resolved type returned in kRet0. CallRuntimeHelperImmReg(QUICK_ENTRYPOINT_OFFSET(pInitializeTypeAndVerifyAccess), type_idx, rl_method.low_reg, true); RegLocation rl_result = GetReturn(false); StoreValue(rl_dest, rl_result); } else { // We're don't need access checks, load type from dex cache int32_t dex_cache_offset = mirror::ArtMethod::DexCacheResolvedTypesOffset().Int32Value(); LoadWordDisp(rl_method.low_reg, dex_cache_offset, res_reg); int32_t offset_of_type = mirror::Array::DataOffset(sizeof(mirror::Class*)).Int32Value() + (sizeof(mirror::Class*) * type_idx); LoadWordDisp(res_reg, offset_of_type, rl_result.low_reg); if (!cu_->compiler_driver->CanAssumeTypeIsPresentInDexCache(*cu_->dex_file, type_idx) || SLOW_TYPE_PATH) { // Slow path, at runtime test if type is null and if so initialize FlushAllRegs(); LIR* branch1 = OpCmpImmBranch(kCondEq, rl_result.low_reg, 0, NULL); // Resolved, store and hop over following code StoreValue(rl_dest, rl_result); /* * Because we have stores of the target value on two paths, * clobber temp tracking for the destination using the ssa name */ ClobberSReg(rl_dest.s_reg_low); LIR* branch2 = OpUnconditionalBranch(0); // TUNING: move slow path to end & remove unconditional branch LIR* target1 = NewLIR0(kPseudoTargetLabel); // Call out to helper, which will return resolved type in kArg0 CallRuntimeHelperImmReg(QUICK_ENTRYPOINT_OFFSET(pInitializeType), type_idx, rl_method.low_reg, true); RegLocation rl_result = GetReturn(false); StoreValue(rl_dest, rl_result); /* * Because we have stores of the target value on two paths, * clobber temp tracking for the destination using the ssa name */ ClobberSReg(rl_dest.s_reg_low); // Rejoin code paths LIR* target2 = NewLIR0(kPseudoTargetLabel); branch1->target = target1; branch2->target = target2; } else { // Fast path, we're done - just store result StoreValue(rl_dest, rl_result); } } } void Mir2Lir::GenConstString(uint32_t string_idx, RegLocation rl_dest) { /* NOTE: Most strings should be available at compile time */ int32_t offset_of_string = mirror::Array::DataOffset(sizeof(mirror::String*)).Int32Value() + (sizeof(mirror::String*) * string_idx); if (!cu_->compiler_driver->CanAssumeStringIsPresentInDexCache( *cu_->dex_file, string_idx) || SLOW_STRING_PATH) { // slow path, resolve string if not in dex cache FlushAllRegs(); LockCallTemps(); // Using explicit registers LoadCurrMethodDirect(TargetReg(kArg2)); LoadWordDisp(TargetReg(kArg2), mirror::ArtMethod::DexCacheStringsOffset().Int32Value(), TargetReg(kArg0)); // Might call out to helper, which will return resolved string in kRet0 int r_tgt = CallHelperSetup(QUICK_ENTRYPOINT_OFFSET(pResolveString)); LoadWordDisp(TargetReg(kArg0), offset_of_string, TargetReg(kRet0)); LoadConstant(TargetReg(kArg1), string_idx); if (cu_->instruction_set == kThumb2) { OpRegImm(kOpCmp, TargetReg(kRet0), 0); // Is resolved? GenBarrier(); // For testing, always force through helper if (!EXERCISE_SLOWEST_STRING_PATH) { OpIT(kCondEq, "T"); } OpRegCopy(TargetReg(kArg0), TargetReg(kArg2)); // .eq LIR* call_inst = OpReg(kOpBlx, r_tgt); // .eq, helper(Method*, string_idx) MarkSafepointPC(call_inst); FreeTemp(r_tgt); } else if (cu_->instruction_set == kMips) { LIR* branch = OpCmpImmBranch(kCondNe, TargetReg(kRet0), 0, NULL); OpRegCopy(TargetReg(kArg0), TargetReg(kArg2)); // .eq LIR* call_inst = OpReg(kOpBlx, r_tgt); MarkSafepointPC(call_inst); FreeTemp(r_tgt); LIR* target = NewLIR0(kPseudoTargetLabel); branch->target = target; } else { DCHECK_EQ(cu_->instruction_set, kX86); CallRuntimeHelperRegReg(QUICK_ENTRYPOINT_OFFSET(pResolveString), TargetReg(kArg2), TargetReg(kArg1), true); } GenBarrier(); StoreValue(rl_dest, GetReturn(false)); } else { RegLocation rl_method = LoadCurrMethod(); int res_reg = AllocTemp(); RegLocation rl_result = EvalLoc(rl_dest, kCoreReg, true); LoadWordDisp(rl_method.low_reg, mirror::ArtMethod::DexCacheStringsOffset().Int32Value(), res_reg); LoadWordDisp(res_reg, offset_of_string, rl_result.low_reg); StoreValue(rl_dest, rl_result); } } /* * Let helper function take care of everything. Will * call Class::NewInstanceFromCode(type_idx, method); */ void Mir2Lir::GenNewInstance(uint32_t type_idx, RegLocation rl_dest) { FlushAllRegs(); /* Everything to home location */ // alloc will always check for resolution, do we also need to verify // access because the verifier was unable to? ThreadOffset func_offset(-1); if (cu_->compiler_driver->CanAccessInstantiableTypeWithoutChecks( cu_->method_idx, *cu_->dex_file, type_idx)) { func_offset = QUICK_ENTRYPOINT_OFFSET(pAllocObject); } else { func_offset = QUICK_ENTRYPOINT_OFFSET(pAllocObjectWithAccessCheck); } CallRuntimeHelperImmMethod(func_offset, type_idx, true); RegLocation rl_result = GetReturn(false); StoreValue(rl_dest, rl_result); } void Mir2Lir::GenThrow(RegLocation rl_src) { FlushAllRegs(); CallRuntimeHelperRegLocation(QUICK_ENTRYPOINT_OFFSET(pDeliverException), rl_src, true); } // For final classes there are no sub-classes to check and so we can answer the instance-of // question with simple comparisons. void Mir2Lir::GenInstanceofFinal(bool use_declaring_class, uint32_t type_idx, RegLocation rl_dest, RegLocation rl_src) { RegLocation object = LoadValue(rl_src, kCoreReg); RegLocation rl_result = EvalLoc(rl_dest, kCoreReg, true); int result_reg = rl_result.low_reg; if (result_reg == object.low_reg) { result_reg = AllocTypedTemp(false, kCoreReg); } LoadConstant(result_reg, 0); // assume false LIR* null_branchover = OpCmpImmBranch(kCondEq, object.low_reg, 0, NULL); int check_class = AllocTypedTemp(false, kCoreReg); int object_class = AllocTypedTemp(false, kCoreReg); LoadCurrMethodDirect(check_class); if (use_declaring_class) { LoadWordDisp(check_class, mirror::ArtMethod::DeclaringClassOffset().Int32Value(), check_class); LoadWordDisp(object.low_reg, mirror::Object::ClassOffset().Int32Value(), object_class); } else { LoadWordDisp(check_class, mirror::ArtMethod::DexCacheResolvedTypesOffset().Int32Value(), check_class); LoadWordDisp(object.low_reg, mirror::Object::ClassOffset().Int32Value(), object_class); int32_t offset_of_type = mirror::Array::DataOffset(sizeof(mirror::Class*)).Int32Value() + (sizeof(mirror::Class*) * type_idx); LoadWordDisp(check_class, offset_of_type, check_class); } LIR* ne_branchover = NULL; if (cu_->instruction_set == kThumb2) { OpRegReg(kOpCmp, check_class, object_class); // Same? OpIT(kCondEq, ""); // if-convert the test LoadConstant(result_reg, 1); // .eq case - load true } else { ne_branchover = OpCmpBranch(kCondNe, check_class, object_class, NULL); LoadConstant(result_reg, 1); // eq case - load true } LIR* target = NewLIR0(kPseudoTargetLabel); null_branchover->target = target; if (ne_branchover != NULL) { ne_branchover->target = target; } FreeTemp(object_class); FreeTemp(check_class); if (IsTemp(result_reg)) { OpRegCopy(rl_result.low_reg, result_reg); FreeTemp(result_reg); } StoreValue(rl_dest, rl_result); } void Mir2Lir::GenInstanceofCallingHelper(bool needs_access_check, bool type_known_final, bool type_known_abstract, bool use_declaring_class, bool can_assume_type_is_in_dex_cache, uint32_t type_idx, RegLocation rl_dest, RegLocation rl_src) { FlushAllRegs(); // May generate a call - use explicit registers LockCallTemps(); LoadCurrMethodDirect(TargetReg(kArg1)); // kArg1 <= current Method* int class_reg = TargetReg(kArg2); // kArg2 will hold the Class* if (needs_access_check) { // Check we have access to type_idx and if not throw IllegalAccessError, // returns Class* in kArg0 CallRuntimeHelperImm(QUICK_ENTRYPOINT_OFFSET(pInitializeTypeAndVerifyAccess), type_idx, true); OpRegCopy(class_reg, TargetReg(kRet0)); // Align usage with fast path LoadValueDirectFixed(rl_src, TargetReg(kArg0)); // kArg0 <= ref } else if (use_declaring_class) { LoadValueDirectFixed(rl_src, TargetReg(kArg0)); // kArg0 <= ref LoadWordDisp(TargetReg(kArg1), mirror::ArtMethod::DeclaringClassOffset().Int32Value(), class_reg); } else { // Load dex cache entry into class_reg (kArg2) LoadValueDirectFixed(rl_src, TargetReg(kArg0)); // kArg0 <= ref LoadWordDisp(TargetReg(kArg1), mirror::ArtMethod::DexCacheResolvedTypesOffset().Int32Value(), class_reg); int32_t offset_of_type = mirror::Array::DataOffset(sizeof(mirror::Class*)).Int32Value() + (sizeof(mirror::Class*) * type_idx); LoadWordDisp(class_reg, offset_of_type, class_reg); if (!can_assume_type_is_in_dex_cache) { // Need to test presence of type in dex cache at runtime LIR* hop_branch = OpCmpImmBranch(kCondNe, class_reg, 0, NULL); // Not resolved // Call out to helper, which will return resolved type in kRet0 CallRuntimeHelperImm(QUICK_ENTRYPOINT_OFFSET(pInitializeType), type_idx, true); OpRegCopy(TargetReg(kArg2), TargetReg(kRet0)); // Align usage with fast path LoadValueDirectFixed(rl_src, TargetReg(kArg0)); /* reload Ref */ // Rejoin code paths LIR* hop_target = NewLIR0(kPseudoTargetLabel); hop_branch->target = hop_target; } } /* kArg0 is ref, kArg2 is class. If ref==null, use directly as bool result */ RegLocation rl_result = GetReturn(false); if (cu_->instruction_set == kMips) { // On MIPS rArg0 != rl_result, place false in result if branch is taken. LoadConstant(rl_result.low_reg, 0); } LIR* branch1 = OpCmpImmBranch(kCondEq, TargetReg(kArg0), 0, NULL); /* load object->klass_ */ DCHECK_EQ(mirror::Object::ClassOffset().Int32Value(), 0); LoadWordDisp(TargetReg(kArg0), mirror::Object::ClassOffset().Int32Value(), TargetReg(kArg1)); /* kArg0 is ref, kArg1 is ref->klass_, kArg2 is class */ LIR* branchover = NULL; if (type_known_final) { // rl_result == ref == null == 0. if (cu_->instruction_set == kThumb2) { OpRegReg(kOpCmp, TargetReg(kArg1), TargetReg(kArg2)); // Same? OpIT(kCondEq, "E"); // if-convert the test LoadConstant(rl_result.low_reg, 1); // .eq case - load true LoadConstant(rl_result.low_reg, 0); // .ne case - load false } else { LoadConstant(rl_result.low_reg, 0); // ne case - load false branchover = OpCmpBranch(kCondNe, TargetReg(kArg1), TargetReg(kArg2), NULL); LoadConstant(rl_result.low_reg, 1); // eq case - load true } } else { if (cu_->instruction_set == kThumb2) { int r_tgt = LoadHelper(QUICK_ENTRYPOINT_OFFSET(pInstanceofNonTrivial)); if (!type_known_abstract) { /* Uses conditional nullification */ OpRegReg(kOpCmp, TargetReg(kArg1), TargetReg(kArg2)); // Same? OpIT(kCondEq, "EE"); // if-convert the test LoadConstant(TargetReg(kArg0), 1); // .eq case - load true } OpRegCopy(TargetReg(kArg0), TargetReg(kArg2)); // .ne case - arg0 <= class OpReg(kOpBlx, r_tgt); // .ne case: helper(class, ref->class) FreeTemp(r_tgt); } else { if (!type_known_abstract) { /* Uses branchovers */ LoadConstant(rl_result.low_reg, 1); // assume true branchover = OpCmpBranch(kCondEq, TargetReg(kArg1), TargetReg(kArg2), NULL); } if (cu_->instruction_set != kX86) { int r_tgt = LoadHelper(QUICK_ENTRYPOINT_OFFSET(pInstanceofNonTrivial)); OpRegCopy(TargetReg(kArg0), TargetReg(kArg2)); // .ne case - arg0 <= class OpReg(kOpBlx, r_tgt); // .ne case: helper(class, ref->class) FreeTemp(r_tgt); } else { OpRegCopy(TargetReg(kArg0), TargetReg(kArg2)); OpThreadMem(kOpBlx, QUICK_ENTRYPOINT_OFFSET(pInstanceofNonTrivial)); } } } // TODO: only clobber when type isn't final? ClobberCalleeSave(); /* branch targets here */ LIR* target = NewLIR0(kPseudoTargetLabel); StoreValue(rl_dest, rl_result); branch1->target = target; if (branchover != NULL) { branchover->target = target; } } void Mir2Lir::GenInstanceof(uint32_t type_idx, RegLocation rl_dest, RegLocation rl_src) { bool type_known_final, type_known_abstract, use_declaring_class; bool needs_access_check = !cu_->compiler_driver->CanAccessTypeWithoutChecks(cu_->method_idx, *cu_->dex_file, type_idx, &type_known_final, &type_known_abstract, &use_declaring_class); bool can_assume_type_is_in_dex_cache = !needs_access_check && cu_->compiler_driver->CanAssumeTypeIsPresentInDexCache(*cu_->dex_file, type_idx); if ((use_declaring_class || can_assume_type_is_in_dex_cache) && type_known_final) { GenInstanceofFinal(use_declaring_class, type_idx, rl_dest, rl_src); } else { GenInstanceofCallingHelper(needs_access_check, type_known_final, type_known_abstract, use_declaring_class, can_assume_type_is_in_dex_cache, type_idx, rl_dest, rl_src); } } void Mir2Lir::GenCheckCast(uint32_t insn_idx, uint32_t type_idx, RegLocation rl_src) { bool type_known_final, type_known_abstract, use_declaring_class; bool needs_access_check = !cu_->compiler_driver->CanAccessTypeWithoutChecks(cu_->method_idx, *cu_->dex_file, type_idx, &type_known_final, &type_known_abstract, &use_declaring_class); // Note: currently type_known_final is unused, as optimizing will only improve the performance // of the exception throw path. DexCompilationUnit* cu = mir_graph_->GetCurrentDexCompilationUnit(); const MethodReference mr(cu->GetDexFile(), cu->GetDexMethodIndex()); if (!needs_access_check && cu_->compiler_driver->IsSafeCast(mr, insn_idx)) { // Verifier type analysis proved this check cast would never cause an exception. return; } FlushAllRegs(); // May generate a call - use explicit registers LockCallTemps(); LoadCurrMethodDirect(TargetReg(kArg1)); // kArg1 <= current Method* int class_reg = TargetReg(kArg2); // kArg2 will hold the Class* if (needs_access_check) { // Check we have access to type_idx and if not throw IllegalAccessError, // returns Class* in kRet0 // InitializeTypeAndVerifyAccess(idx, method) CallRuntimeHelperImmReg(QUICK_ENTRYPOINT_OFFSET(pInitializeTypeAndVerifyAccess), type_idx, TargetReg(kArg1), true); OpRegCopy(class_reg, TargetReg(kRet0)); // Align usage with fast path } else if (use_declaring_class) { LoadWordDisp(TargetReg(kArg1), mirror::ArtMethod::DeclaringClassOffset().Int32Value(), class_reg); } else { // Load dex cache entry into class_reg (kArg2) LoadWordDisp(TargetReg(kArg1), mirror::ArtMethod::DexCacheResolvedTypesOffset().Int32Value(), class_reg); int32_t offset_of_type = mirror::Array::DataOffset(sizeof(mirror::Class*)).Int32Value() + (sizeof(mirror::Class*) * type_idx); LoadWordDisp(class_reg, offset_of_type, class_reg); if (!cu_->compiler_driver->CanAssumeTypeIsPresentInDexCache(*cu_->dex_file, type_idx)) { // Need to test presence of type in dex cache at runtime LIR* hop_branch = OpCmpImmBranch(kCondNe, class_reg, 0, NULL); // Not resolved // Call out to helper, which will return resolved type in kArg0 // InitializeTypeFromCode(idx, method) CallRuntimeHelperImmReg(QUICK_ENTRYPOINT_OFFSET(pInitializeType), type_idx, TargetReg(kArg1), true); OpRegCopy(class_reg, TargetReg(kRet0)); // Align usage with fast path // Rejoin code paths LIR* hop_target = NewLIR0(kPseudoTargetLabel); hop_branch->target = hop_target; } } // At this point, class_reg (kArg2) has class LoadValueDirectFixed(rl_src, TargetReg(kArg0)); // kArg0 <= ref /* Null is OK - continue */ LIR* branch1 = OpCmpImmBranch(kCondEq, TargetReg(kArg0), 0, NULL); /* load object->klass_ */ DCHECK_EQ(mirror::Object::ClassOffset().Int32Value(), 0); LoadWordDisp(TargetReg(kArg0), mirror::Object::ClassOffset().Int32Value(), TargetReg(kArg1)); /* kArg1 now contains object->klass_ */ LIR* branch2 = NULL; if (!type_known_abstract) { branch2 = OpCmpBranch(kCondEq, TargetReg(kArg1), class_reg, NULL); } CallRuntimeHelperRegReg(QUICK_ENTRYPOINT_OFFSET(pCheckCast), TargetReg(kArg1), TargetReg(kArg2), true); /* branch target here */ LIR* target = NewLIR0(kPseudoTargetLabel); branch1->target = target; if (branch2 != NULL) { branch2->target = target; } } void Mir2Lir::GenLong3Addr(OpKind first_op, OpKind second_op, RegLocation rl_dest, RegLocation rl_src1, RegLocation rl_src2) { RegLocation rl_result; if (cu_->instruction_set == kThumb2) { /* * NOTE: This is the one place in the code in which we might have * as many as six live temporary registers. There are 5 in the normal * set for Arm. Until we have spill capabilities, temporarily add * lr to the temp set. It is safe to do this locally, but note that * lr is used explicitly elsewhere in the code generator and cannot * normally be used as a general temp register. */ MarkTemp(TargetReg(kLr)); // Add lr to the temp pool FreeTemp(TargetReg(kLr)); // and make it available } rl_src1 = LoadValueWide(rl_src1, kCoreReg); rl_src2 = LoadValueWide(rl_src2, kCoreReg); rl_result = EvalLoc(rl_dest, kCoreReg, true); // The longs may overlap - use intermediate temp if so if ((rl_result.low_reg == rl_src1.high_reg) || (rl_result.low_reg == rl_src2.high_reg)) { int t_reg = AllocTemp(); OpRegRegReg(first_op, t_reg, rl_src1.low_reg, rl_src2.low_reg); OpRegRegReg(second_op, rl_result.high_reg, rl_src1.high_reg, rl_src2.high_reg); OpRegCopy(rl_result.low_reg, t_reg); FreeTemp(t_reg); } else { OpRegRegReg(first_op, rl_result.low_reg, rl_src1.low_reg, rl_src2.low_reg); OpRegRegReg(second_op, rl_result.high_reg, rl_src1.high_reg, rl_src2.high_reg); } /* * NOTE: If rl_dest refers to a frame variable in a large frame, the * following StoreValueWide might need to allocate a temp register. * To further work around the lack of a spill capability, explicitly * free any temps from rl_src1 & rl_src2 that aren't still live in rl_result. * Remove when spill is functional. */ FreeRegLocTemps(rl_result, rl_src1); FreeRegLocTemps(rl_result, rl_src2); StoreValueWide(rl_dest, rl_result); if (cu_->instruction_set == kThumb2) { Clobber(TargetReg(kLr)); UnmarkTemp(TargetReg(kLr)); // Remove lr from the temp pool } } void Mir2Lir::GenShiftOpLong(Instruction::Code opcode, RegLocation rl_dest, RegLocation rl_src1, RegLocation rl_shift) { ThreadOffset func_offset(-1); switch (opcode) { case Instruction::SHL_LONG: case Instruction::SHL_LONG_2ADDR: func_offset = QUICK_ENTRYPOINT_OFFSET(pShlLong); break; case Instruction::SHR_LONG: case Instruction::SHR_LONG_2ADDR: func_offset = QUICK_ENTRYPOINT_OFFSET(pShrLong); break; case Instruction::USHR_LONG: case Instruction::USHR_LONG_2ADDR: func_offset = QUICK_ENTRYPOINT_OFFSET(pUshrLong); break; default: LOG(FATAL) << "Unexpected case"; } FlushAllRegs(); /* Send everything to home location */ CallRuntimeHelperRegLocationRegLocation(func_offset, rl_src1, rl_shift, false); RegLocation rl_result = GetReturnWide(false); StoreValueWide(rl_dest, rl_result); } void Mir2Lir::GenArithOpInt(Instruction::Code opcode, RegLocation rl_dest, RegLocation rl_src1, RegLocation rl_src2) { OpKind op = kOpBkpt; bool is_div_rem = false; bool check_zero = false; bool unary = false; RegLocation rl_result; bool shift_op = false; switch (opcode) { case Instruction::NEG_INT: op = kOpNeg; unary = true; break; case Instruction::NOT_INT: op = kOpMvn; unary = true; break; case Instruction::ADD_INT: case Instruction::ADD_INT_2ADDR: op = kOpAdd; break; case Instruction::SUB_INT: case Instruction::SUB_INT_2ADDR: op = kOpSub; break; case Instruction::MUL_INT: case Instruction::MUL_INT_2ADDR: op = kOpMul; break; case Instruction::DIV_INT: case Instruction::DIV_INT_2ADDR: check_zero = true; op = kOpDiv; is_div_rem = true; break; /* NOTE: returns in kArg1 */ case Instruction::REM_INT: case Instruction::REM_INT_2ADDR: check_zero = true; op = kOpRem; is_div_rem = true; break; case Instruction::AND_INT: case Instruction::AND_INT_2ADDR: op = kOpAnd; break; case Instruction::OR_INT: case Instruction::OR_INT_2ADDR: op = kOpOr; break; case Instruction::XOR_INT: case Instruction::XOR_INT_2ADDR: op = kOpXor; break; case Instruction::SHL_INT: case Instruction::SHL_INT_2ADDR: shift_op = true; op = kOpLsl; break; case Instruction::SHR_INT: case Instruction::SHR_INT_2ADDR: shift_op = true; op = kOpAsr; break; case Instruction::USHR_INT: case Instruction::USHR_INT_2ADDR: shift_op = true; op = kOpLsr; break; default: LOG(FATAL) << "Invalid word arith op: " << opcode; } if (!is_div_rem) { if (unary) { rl_src1 = LoadValue(rl_src1, kCoreReg); rl_result = EvalLoc(rl_dest, kCoreReg, true); OpRegReg(op, rl_result.low_reg, rl_src1.low_reg); } else { if (shift_op) { int t_reg = INVALID_REG; if (cu_->instruction_set == kX86) { // X86 doesn't require masking and must use ECX t_reg = TargetReg(kCount); // rCX LoadValueDirectFixed(rl_src2, t_reg); } else { rl_src2 = LoadValue(rl_src2, kCoreReg); t_reg = AllocTemp(); OpRegRegImm(kOpAnd, t_reg, rl_src2.low_reg, 31); } rl_src1 = LoadValue(rl_src1, kCoreReg); rl_result = EvalLoc(rl_dest, kCoreReg, true); OpRegRegReg(op, rl_result.low_reg, rl_src1.low_reg, t_reg); FreeTemp(t_reg); } else { rl_src1 = LoadValue(rl_src1, kCoreReg); rl_src2 = LoadValue(rl_src2, kCoreReg); rl_result = EvalLoc(rl_dest, kCoreReg, true); OpRegRegReg(op, rl_result.low_reg, rl_src1.low_reg, rl_src2.low_reg); } } StoreValue(rl_dest, rl_result); } else { if (cu_->instruction_set == kMips) { rl_src1 = LoadValue(rl_src1, kCoreReg); rl_src2 = LoadValue(rl_src2, kCoreReg); if (check_zero) { GenImmedCheck(kCondEq, rl_src2.low_reg, 0, kThrowDivZero); } rl_result = GenDivRem(rl_dest, rl_src1.low_reg, rl_src2.low_reg, op == kOpDiv); } else { ThreadOffset func_offset = QUICK_ENTRYPOINT_OFFSET(pIdivmod); FlushAllRegs(); /* Send everything to home location */ LoadValueDirectFixed(rl_src2, TargetReg(kArg1)); int r_tgt = CallHelperSetup(func_offset); LoadValueDirectFixed(rl_src1, TargetReg(kArg0)); if (check_zero) { GenImmedCheck(kCondEq, TargetReg(kArg1), 0, kThrowDivZero); } // NOTE: callout here is not a safepoint CallHelper(r_tgt, func_offset, false /* not a safepoint */); if (op == kOpDiv) rl_result = GetReturn(false); else rl_result = GetReturnAlt(); } StoreValue(rl_dest, rl_result); } } /* * The following are the first-level codegen routines that analyze the format * of each bytecode then either dispatch special purpose codegen routines * or produce corresponding Thumb instructions directly. */ static bool IsPowerOfTwo(int x) { return (x & (x - 1)) == 0; } // Returns true if no more than two bits are set in 'x'. static bool IsPopCountLE2(unsigned int x) { x &= x - 1; return (x & (x - 1)) == 0; } // Returns the index of the lowest set bit in 'x'. static int LowestSetBit(unsigned int x) { int bit_posn = 0; while ((x & 0xf) == 0) { bit_posn += 4; x >>= 4; } while ((x & 1) == 0) { bit_posn++; x >>= 1; } return bit_posn; } // Returns true if it added instructions to 'cu' to divide 'rl_src' by 'lit' // and store the result in 'rl_dest'. bool Mir2Lir::HandleEasyDivRem(Instruction::Code dalvik_opcode, bool is_div, RegLocation rl_src, RegLocation rl_dest, int lit) { if ((lit < 2) || ((cu_->instruction_set != kThumb2) && !IsPowerOfTwo(lit))) { return false; } // No divide instruction for Arm, so check for more special cases if ((cu_->instruction_set == kThumb2) && !IsPowerOfTwo(lit)) { return SmallLiteralDivRem(dalvik_opcode, is_div, rl_src, rl_dest, lit); } int k = LowestSetBit(lit); if (k >= 30) { // Avoid special cases. return false; } rl_src = LoadValue(rl_src, kCoreReg); RegLocation rl_result = EvalLoc(rl_dest, kCoreReg, true); if (is_div) { int t_reg = AllocTemp(); if (lit == 2) { // Division by 2 is by far the most common division by constant. OpRegRegImm(kOpLsr, t_reg, rl_src.low_reg, 32 - k); OpRegRegReg(kOpAdd, t_reg, t_reg, rl_src.low_reg); OpRegRegImm(kOpAsr, rl_result.low_reg, t_reg, k); } else { OpRegRegImm(kOpAsr, t_reg, rl_src.low_reg, 31); OpRegRegImm(kOpLsr, t_reg, t_reg, 32 - k); OpRegRegReg(kOpAdd, t_reg, t_reg, rl_src.low_reg); OpRegRegImm(kOpAsr, rl_result.low_reg, t_reg, k); } } else { int t_reg1 = AllocTemp(); int t_reg2 = AllocTemp(); if (lit == 2) { OpRegRegImm(kOpLsr, t_reg1, rl_src.low_reg, 32 - k); OpRegRegReg(kOpAdd, t_reg2, t_reg1, rl_src.low_reg); OpRegRegImm(kOpAnd, t_reg2, t_reg2, lit -1); OpRegRegReg(kOpSub, rl_result.low_reg, t_reg2, t_reg1); } else { OpRegRegImm(kOpAsr, t_reg1, rl_src.low_reg, 31); OpRegRegImm(kOpLsr, t_reg1, t_reg1, 32 - k); OpRegRegReg(kOpAdd, t_reg2, t_reg1, rl_src.low_reg); OpRegRegImm(kOpAnd, t_reg2, t_reg2, lit - 1); OpRegRegReg(kOpSub, rl_result.low_reg, t_reg2, t_reg1); } } StoreValue(rl_dest, rl_result); return true; } // Returns true if it added instructions to 'cu' to multiply 'rl_src' by 'lit' // and store the result in 'rl_dest'. bool Mir2Lir::HandleEasyMultiply(RegLocation rl_src, RegLocation rl_dest, int lit) { // Can we simplify this multiplication? bool power_of_two = false; bool pop_count_le2 = false; bool power_of_two_minus_one = false; if (lit < 2) { // Avoid special cases. return false; } else if (IsPowerOfTwo(lit)) { power_of_two = true; } else if (IsPopCountLE2(lit)) { pop_count_le2 = true; } else if (IsPowerOfTwo(lit + 1)) { power_of_two_minus_one = true; } else { return false; } rl_src = LoadValue(rl_src, kCoreReg); RegLocation rl_result = EvalLoc(rl_dest, kCoreReg, true); if (power_of_two) { // Shift. OpRegRegImm(kOpLsl, rl_result.low_reg, rl_src.low_reg, LowestSetBit(lit)); } else if (pop_count_le2) { // Shift and add and shift. int first_bit = LowestSetBit(lit); int second_bit = LowestSetBit(lit ^ (1 << first_bit)); GenMultiplyByTwoBitMultiplier(rl_src, rl_result, lit, first_bit, second_bit); } else { // Reverse subtract: (src << (shift + 1)) - src. DCHECK(power_of_two_minus_one); // TUNING: rsb dst, src, src lsl#LowestSetBit(lit + 1) int t_reg = AllocTemp(); OpRegRegImm(kOpLsl, t_reg, rl_src.low_reg, LowestSetBit(lit + 1)); OpRegRegReg(kOpSub, rl_result.low_reg, t_reg, rl_src.low_reg); } StoreValue(rl_dest, rl_result); return true; } void Mir2Lir::GenArithOpIntLit(Instruction::Code opcode, RegLocation rl_dest, RegLocation rl_src, int lit) { RegLocation rl_result; OpKind op = static_cast<OpKind>(0); /* Make gcc happy */ int shift_op = false; bool is_div = false; switch (opcode) { case Instruction::RSUB_INT_LIT8: case Instruction::RSUB_INT: { rl_src = LoadValue(rl_src, kCoreReg); rl_result = EvalLoc(rl_dest, kCoreReg, true); if (cu_->instruction_set == kThumb2) { OpRegRegImm(kOpRsub, rl_result.low_reg, rl_src.low_reg, lit); } else { OpRegReg(kOpNeg, rl_result.low_reg, rl_src.low_reg); OpRegImm(kOpAdd, rl_result.low_reg, lit); } StoreValue(rl_dest, rl_result); return; } case Instruction::SUB_INT: case Instruction::SUB_INT_2ADDR: lit = -lit; // Intended fallthrough case Instruction::ADD_INT: case Instruction::ADD_INT_2ADDR: case Instruction::ADD_INT_LIT8: case Instruction::ADD_INT_LIT16: op = kOpAdd; break; case Instruction::MUL_INT: case Instruction::MUL_INT_2ADDR: case Instruction::MUL_INT_LIT8: case Instruction::MUL_INT_LIT16: { if (HandleEasyMultiply(rl_src, rl_dest, lit)) { return; } op = kOpMul; break; } case Instruction::AND_INT: case Instruction::AND_INT_2ADDR: case Instruction::AND_INT_LIT8: case Instruction::AND_INT_LIT16: op = kOpAnd; break; case Instruction::OR_INT: case Instruction::OR_INT_2ADDR: case Instruction::OR_INT_LIT8: case Instruction::OR_INT_LIT16: op = kOpOr; break; case Instruction::XOR_INT: case Instruction::XOR_INT_2ADDR: case Instruction::XOR_INT_LIT8: case Instruction::XOR_INT_LIT16: op = kOpXor; break; case Instruction::SHL_INT_LIT8: case Instruction::SHL_INT: case Instruction::SHL_INT_2ADDR: lit &= 31; shift_op = true; op = kOpLsl; break; case Instruction::SHR_INT_LIT8: case Instruction::SHR_INT: case Instruction::SHR_INT_2ADDR: lit &= 31; shift_op = true; op = kOpAsr; break; case Instruction::USHR_INT_LIT8: case Instruction::USHR_INT: case Instruction::USHR_INT_2ADDR: lit &= 31; shift_op = true; op = kOpLsr; break; case Instruction::DIV_INT: case Instruction::DIV_INT_2ADDR: case Instruction::DIV_INT_LIT8: case Instruction::DIV_INT_LIT16: case Instruction::REM_INT: case Instruction::REM_INT_2ADDR: case Instruction::REM_INT_LIT8: case Instruction::REM_INT_LIT16: { if (lit == 0) { GenImmedCheck(kCondAl, 0, 0, kThrowDivZero); return; } if ((opcode == Instruction::DIV_INT) || (opcode == Instruction::DIV_INT_2ADDR) || (opcode == Instruction::DIV_INT_LIT8) || (opcode == Instruction::DIV_INT_LIT16)) { is_div = true; } else { is_div = false; } if (HandleEasyDivRem(opcode, is_div, rl_src, rl_dest, lit)) { return; } if (cu_->instruction_set == kMips) { rl_src = LoadValue(rl_src, kCoreReg); rl_result = GenDivRemLit(rl_dest, rl_src.low_reg, lit, is_div); } else { FlushAllRegs(); /* Everything to home location */ LoadValueDirectFixed(rl_src, TargetReg(kArg0)); Clobber(TargetReg(kArg0)); ThreadOffset func_offset = QUICK_ENTRYPOINT_OFFSET(pIdivmod); CallRuntimeHelperRegImm(func_offset, TargetReg(kArg0), lit, false); if (is_div) rl_result = GetReturn(false); else rl_result = GetReturnAlt(); } StoreValue(rl_dest, rl_result); return; } default: LOG(FATAL) << "Unexpected opcode " << opcode; } rl_src = LoadValue(rl_src, kCoreReg); rl_result = EvalLoc(rl_dest, kCoreReg, true); // Avoid shifts by literal 0 - no support in Thumb. Change to copy if (shift_op && (lit == 0)) { OpRegCopy(rl_result.low_reg, rl_src.low_reg); } else { OpRegRegImm(op, rl_result.low_reg, rl_src.low_reg, lit); } StoreValue(rl_dest, rl_result); } void Mir2Lir::GenArithOpLong(Instruction::Code opcode, RegLocation rl_dest, RegLocation rl_src1, RegLocation rl_src2) { RegLocation rl_result; OpKind first_op = kOpBkpt; OpKind second_op = kOpBkpt; bool call_out = false; bool check_zero = false; ThreadOffset func_offset(-1); int ret_reg = TargetReg(kRet0); switch (opcode) { case Instruction::NOT_LONG: rl_src2 = LoadValueWide(rl_src2, kCoreReg); rl_result = EvalLoc(rl_dest, kCoreReg, true); // Check for destructive overlap if (rl_result.low_reg == rl_src2.high_reg) { int t_reg = AllocTemp(); OpRegCopy(t_reg, rl_src2.high_reg); OpRegReg(kOpMvn, rl_result.low_reg, rl_src2.low_reg); OpRegReg(kOpMvn, rl_result.high_reg, t_reg); FreeTemp(t_reg); } else { OpRegReg(kOpMvn, rl_result.low_reg, rl_src2.low_reg); OpRegReg(kOpMvn, rl_result.high_reg, rl_src2.high_reg); } StoreValueWide(rl_dest, rl_result); return; case Instruction::ADD_LONG: case Instruction::ADD_LONG_2ADDR: if (cu_->instruction_set != kThumb2) { GenAddLong(rl_dest, rl_src1, rl_src2); return; } first_op = kOpAdd; second_op = kOpAdc; break; case Instruction::SUB_LONG: case Instruction::SUB_LONG_2ADDR: if (cu_->instruction_set != kThumb2) { GenSubLong(rl_dest, rl_src1, rl_src2); return; } first_op = kOpSub; second_op = kOpSbc; break; case Instruction::MUL_LONG: case Instruction::MUL_LONG_2ADDR: if (cu_->instruction_set == kThumb2) { GenMulLong(rl_dest, rl_src1, rl_src2); return; } else { call_out = true; ret_reg = TargetReg(kRet0); func_offset = QUICK_ENTRYPOINT_OFFSET(pLmul); } break; case Instruction::DIV_LONG: case Instruction::DIV_LONG_2ADDR: call_out = true; check_zero = true; ret_reg = TargetReg(kRet0); func_offset = QUICK_ENTRYPOINT_OFFSET(pLdiv); break; case Instruction::REM_LONG: case Instruction::REM_LONG_2ADDR: call_out = true; check_zero = true; func_offset = QUICK_ENTRYPOINT_OFFSET(pLdivmod); /* NOTE - for Arm, result is in kArg2/kArg3 instead of kRet0/kRet1 */ ret_reg = (cu_->instruction_set == kThumb2) ? TargetReg(kArg2) : TargetReg(kRet0); break; case Instruction::AND_LONG_2ADDR: case Instruction::AND_LONG: if (cu_->instruction_set == kX86) { return GenAndLong(rl_dest, rl_src1, rl_src2); } first_op = kOpAnd; second_op = kOpAnd; break; case Instruction::OR_LONG: case Instruction::OR_LONG_2ADDR: if (cu_->instruction_set == kX86) { GenOrLong(rl_dest, rl_src1, rl_src2); return; } first_op = kOpOr; second_op = kOpOr; break; case Instruction::XOR_LONG: case Instruction::XOR_LONG_2ADDR: if (cu_->instruction_set == kX86) { GenXorLong(rl_dest, rl_src1, rl_src2); return; } first_op = kOpXor; second_op = kOpXor; break; case Instruction::NEG_LONG: { GenNegLong(rl_dest, rl_src2); return; } default: LOG(FATAL) << "Invalid long arith op"; } if (!call_out) { GenLong3Addr(first_op, second_op, rl_dest, rl_src1, rl_src2); } else { FlushAllRegs(); /* Send everything to home location */ if (check_zero) { LoadValueDirectWideFixed(rl_src2, TargetReg(kArg2), TargetReg(kArg3)); int r_tgt = CallHelperSetup(func_offset); GenDivZeroCheck(TargetReg(kArg2), TargetReg(kArg3)); LoadValueDirectWideFixed(rl_src1, TargetReg(kArg0), TargetReg(kArg1)); // NOTE: callout here is not a safepoint CallHelper(r_tgt, func_offset, false /* not safepoint */); } else { CallRuntimeHelperRegLocationRegLocation(func_offset, rl_src1, rl_src2, false); } // Adjust return regs in to handle case of rem returning kArg2/kArg3 if (ret_reg == TargetReg(kRet0)) rl_result = GetReturnWide(false); else rl_result = GetReturnWideAlt(); StoreValueWide(rl_dest, rl_result); } } void Mir2Lir::GenConversionCall(ThreadOffset func_offset, RegLocation rl_dest, RegLocation rl_src) { /* * Don't optimize the register usage since it calls out to support * functions */ FlushAllRegs(); /* Send everything to home location */ if (rl_src.wide) { LoadValueDirectWideFixed(rl_src, rl_src.fp ? TargetReg(kFArg0) : TargetReg(kArg0), rl_src.fp ? TargetReg(kFArg1) : TargetReg(kArg1)); } else { LoadValueDirectFixed(rl_src, rl_src.fp ? TargetReg(kFArg0) : TargetReg(kArg0)); } CallRuntimeHelperRegLocation(func_offset, rl_src, false); if (rl_dest.wide) { RegLocation rl_result; rl_result = GetReturnWide(rl_dest.fp); StoreValueWide(rl_dest, rl_result); } else { RegLocation rl_result; rl_result = GetReturn(rl_dest.fp); StoreValue(rl_dest, rl_result); } } /* Check if we need to check for pending suspend request */ void Mir2Lir::GenSuspendTest(int opt_flags) { if (NO_SUSPEND || (opt_flags & MIR_IGNORE_SUSPEND_CHECK)) { return; } FlushAllRegs(); LIR* branch = OpTestSuspend(NULL); LIR* ret_lab = NewLIR0(kPseudoTargetLabel); LIR* target = RawLIR(current_dalvik_offset_, kPseudoSuspendTarget, reinterpret_cast<uintptr_t>(ret_lab), current_dalvik_offset_); branch->target = target; suspend_launchpads_.Insert(target); } /* Check if we need to check for pending suspend request */ void Mir2Lir::GenSuspendTestAndBranch(int opt_flags, LIR* target) { if (NO_SUSPEND || (opt_flags & MIR_IGNORE_SUSPEND_CHECK)) { OpUnconditionalBranch(target); return; } OpTestSuspend(target); LIR* launch_pad = RawLIR(current_dalvik_offset_, kPseudoSuspendTarget, reinterpret_cast<uintptr_t>(target), current_dalvik_offset_); FlushAllRegs(); OpUnconditionalBranch(launch_pad); suspend_launchpads_.Insert(launch_pad); } } // namespace art
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
c68a532d8906d33d370d5811e22f9d21fe85ea34
0a7a9e928211e508c1c87e24e57d6f204c7e0a73
/src/edit.cc
b657661fb14c6fd01e45c7b25000ee06d7c5a14d
[]
no_license
troyh/beercrush_php
e80d47ca21ea730c2c978b996e064f2f210f4ce5
13fac0487ca2bb25be2258e607c239c5691daf91
refs/heads/master
2016-08-06T11:15:24.568055
2010-11-17T22:31:42
2010-11-17T22:31:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,642
cc
#include <fcgi_stdio.h> extern "C" { #include <cgic.h> } #include <stdlib.h> #include <ctype.h> #include <string.h> // Boost stuff #include <boost/filesystem.hpp> #include <OAK/oak.h> #include <OAK/loginutils.h> #include "beercrush.h" using namespace std; namespace bfs=boost::filesystem; extern "C" void cgiInit() { } extern "C" void cgiUninit() { } bool validate_place_state(const char* s, bool* useOrigVal, char* newVal, size_t newValSize); bool validate_place_price_range(const char* s, bool* useOrigVal, char* newVal, size_t newValSize); bool validate_place_type(const char* s, bool* useOrigVal, char* newVal, size_t newValSize); bool validate_price(const char* s, bool* useOrigVal, char* newVal, size_t newValSize); bool validate_beer_upc(const char* s, bool* useOrigVal, char* newVal, size_t newValSize); bool validate_beer_bjcp_style_id(const char* s, bool* useOrigVal, char* newVal, size_t newValSize); EDITABLE_FIELDS place_editable_fields[]= { // IMPORTANT: These must be sorted! They are searched with a binary search. { "/place/@bottled_beer_to_go", EDITABLE_FIELDS::validate_yesno }, { "/place/@bottles", EDITABLE_FIELDS::validate_yesno }, { "/place/@brew_on_premises", EDITABLE_FIELDS::validate_yesno }, { "/place/@casks", EDITABLE_FIELDS::validate_uinteger }, { "/place/@growlers_to_go", EDITABLE_FIELDS::validate_yesno }, { "/place/@in_operation", EDITABLE_FIELDS::validate_yesno }, { "/place/@kegs_to_go", EDITABLE_FIELDS::validate_yesno }, { "/place/@kid_friendly", EDITABLE_FIELDS::validate_yesno }, { "/place/@music", EDITABLE_FIELDS::validate_yesno }, { "/place/@specializes_in_beer", EDITABLE_FIELDS::validate_yesno }, { "/place/@taps", EDITABLE_FIELDS::validate_uinteger }, { "/place/@tied", EDITABLE_FIELDS::validate_yesno }, { "/place/@wheelchair_accessible", EDITABLE_FIELDS::validate_yesno }, { "/place/@wifi", EDITABLE_FIELDS::validate_yesno }, { "/place/address/city", EDITABLE_FIELDS::validate_text }, { "/place/address/country", EDITABLE_FIELDS::validate_text }, { "/place/address/latitude", EDITABLE_FIELDS::validate_float }, { "/place/address/longitude", EDITABLE_FIELDS::validate_float }, { "/place/address/neighborhood", EDITABLE_FIELDS::validate_text }, { "/place/address/state", validate_place_state }, { "/place/address/street", EDITABLE_FIELDS::validate_text }, { "/place/address/zip", EDITABLE_FIELDS::validate_zipcode }, { "/place/description", EDITABLE_FIELDS::validate_text }, { "/place/established", EDITABLE_FIELDS::validate_uinteger }, { "/place/hours/open", EDITABLE_FIELDS::validate_text }, { "/place/hours/tasting", EDITABLE_FIELDS::validate_text }, { "/place/hours/tour", EDITABLE_FIELDS::validate_text }, { "/place/name", EDITABLE_FIELDS::validate_text }, { "/place/parking", EDITABLE_FIELDS::validate_text }, { "/place/phone", EDITABLE_FIELDS::validate_phone }, { "/place/restaurant/attire", EDITABLE_FIELDS::validate_text }, { "/place/restaurant/food_description", EDITABLE_FIELDS::validate_text }, { "/place/restaurant/menu_uri", EDITABLE_FIELDS::validate_uri }, { "/place/restaurant/price_range", validate_place_price_range }, { "/place/restaurant/waiter_service", EDITABLE_FIELDS::validate_yesno }, { "/place/tour_info", EDITABLE_FIELDS::validate_text }, { "/place/type", validate_place_type }, { "/place/uri", EDITABLE_FIELDS::validate_uri }, }; EDITABLE_FIELDS brewery_editable_fields[]= { // IMPORTANT: These must be sorted! They are searched with a binary search. { "/brewery/address/city", EDITABLE_FIELDS::validate_text }, { "/brewery/address/country", EDITABLE_FIELDS::validate_text }, { "/brewery/address/latitude", EDITABLE_FIELDS::validate_float }, { "/brewery/address/longitude", EDITABLE_FIELDS::validate_float }, { "/brewery/address/state", validate_place_state }, { "/brewery/address/street", EDITABLE_FIELDS::validate_text }, { "/brewery/address/zip", EDITABLE_FIELDS::validate_zipcode }, { "/brewery/name", EDITABLE_FIELDS::validate_text }, { "/brewery/phone", EDITABLE_FIELDS::validate_phone }, { "/brewery/uri", EDITABLE_FIELDS::validate_uri }, }; EDITABLE_FIELDS beer_editable_fields[]= { // IMPORTANT: These must be sorted! They are searched with a binary search. { "/beer/@abv", EDITABLE_FIELDS::validate_uinteger }, { "/beer/@brewery_id", EDITABLE_FIELDS::validate_text }, { "/beer/@calories_per_ml", EDITABLE_FIELDS::validate_float }, { "/beer/@ibu", EDITABLE_FIELDS::validate_uinteger }, { "/beer/availability", EDITABLE_FIELDS::validate_text }, { "/beer/description", EDITABLE_FIELDS::validate_text }, { "/beer/grains", EDITABLE_FIELDS::validate_text }, { "/beer/hops", EDITABLE_FIELDS::validate_text }, { "/beer/ingredients", EDITABLE_FIELDS::validate_text }, { "/beer/name", EDITABLE_FIELDS::validate_text }, { "/beer/otherings", EDITABLE_FIELDS::validate_text }, { "/beer/sizes/size/@upc", validate_beer_upc }, { "/beer/sizes/size/description", EDITABLE_FIELDS::validate_text }, { "/beer/sizes/size/distributor/deposit", validate_price }, { "/beer/sizes/size/distributor/item", EDITABLE_FIELDS::validate_text }, { "/beer/sizes/size/distributor/name", EDITABLE_FIELDS::validate_text }, { "/beer/sizes/size/distributor/net_case_price", validate_price }, { "/beer/sizes/size/distributor/post_off", EDITABLE_FIELDS::validate_text }, { "/beer/sizes/size/distributor/reg_price", validate_price }, { "/beer/sizes/size/distributor/unit_price", validate_price }, { "/beer/styles/@bjcp_style_id", validate_beer_bjcp_style_id }, { "/beer/yeast", EDITABLE_FIELDS::validate_text }, }; EDITABLE_DOCTYPES doctypes[]= { // IMPORTANT: These must be sorted! They are searched with a binary search. { "/beer" , "beer_id" , "beer" , beer_editable_fields , sizeof(beer_editable_fields)/sizeof(beer_editable_fields[0]) }, { "/brewery", "brewery_id", "brewery", brewery_editable_fields, sizeof(brewery_editable_fields)/sizeof(brewery_editable_fields[0]) }, { "/place" , "place_id" , "place" , place_editable_fields , sizeof(place_editable_fields)/sizeof(place_editable_fields[0]) }, }; int cgiMain() { if (!userIsValidated()) { cgiHeaderStatus(401,(char*)"User could not be validated"); return 0; } try { bfs::path xml_doc_dir("/home/troy/beerliberation/xml"); cgiHeaderContentType((char*)"text/plain"); char userid[MAX_USERID_LEN]; cgiCookieString((char*)"userid",userid,sizeof(userid)); // FCGI_printf("userid:%s\n",userid); // FCGI_printf("Path:%s\n",cgiPathInfo); int doctype_num=EDITABLE_DOCTYPES::find(cgiPathInfo, doctypes, sizeof(doctypes)/sizeof(doctypes[0])); if (doctype_num<0) throw BeerCrushException("Invalid document type"); char identifier[BEERCRUSH_MAX_PLACE_ID_LEN]; if (cgiFormString((char*)doctypes[doctype_num].id_field,identifier,sizeof(identifier))!=cgiFormSuccess) throw BeerCrushException("Unable to get identifier"); bfs::path xml_filename=xml_doc_dir / doctypes[doctype_num].xmldirpath / identifier; xml_filename=bfs::change_extension(xml_filename,".xml"); // FCGI_printf("XML doc:%s\n",place_filename.string().c_str()); // TODO: check if file exists editDoc(xml_filename,doctypes[doctype_num].editable_fields,doctypes[doctype_num].editable_fields_count,doctypes[doctype_num].id_field,cgiPathInfo); } catch (exception& x) { // TODO: report failure as XML FCGI_printf("Exception: %s\n",x.what()); } return 0; } bool validate_place_state(const char* s, bool* useOrigVal, char* newVal, size_t newValSize) { // We can't check every province in the world, so we just accept anything, even bad US state names (!) *useOrigVal=true; return true; } bool validate_place_price_range(const char* s, bool* useOrigVal, char* newVal, size_t newValSize) { *useOrigVal=true; return true; } bool validate_place_type(const char* s, bool* useOrigVal, char* newVal, size_t newValSize) { const char* acceptables[]= { "Bar", "Brewery", "Brewpub", "Restaurant", "Store", }; // Binary search the list int lo=0,hi=(sizeof(acceptables)/sizeof(acceptables[0]))-1,mid; while (lo<hi) { mid=(lo+hi)/2; int c=strcasecmp(s,acceptables[mid]); if (c==0) { // Copy the proper-cased version just to make sure *useOrigVal=false; strncpy(newVal,acceptables[mid],newValSize); return true; } else if (c<0) lo=mid+1; else hi=mid-1; } return false; } bool validate_price(const char* s, bool* useOrigVal, char* newVal, size_t newValSize) { // It's ok if all chars are digits or decimal point or '$' for(size_t i = 0,len=strlen(s); i < len; ++i) { if (!isdigit(s[i]) && s[i]!='.' && s[i]!='$') return false; } *useOrigVal=true; return true; } bool validate_beer_upc(const char* s, bool* useOrigVal, char* newVal, size_t newValSize) { // It's ok if all chars are digits or spaces or hyphens for(size_t i = 0,len=strlen(s); i < len; ++i) { if (!isdigit(s[i]) && !isspace(s[i]) && s[i]!='-') return false; } *useOrigVal=true; return true; } bool validate_beer_bjcp_style_id(const char* s, bool* useOrigVal, char* newVal, size_t newValSize) { // It's ok if all chars are digits followed by an optional letter for(size_t i = 0,len=strlen(s); i < len; ++i) { if (!isalnum(s[i])) return false; } // And the value must be between 1 and 23 (inclusive) int n=atoi(s); if (n<1 || n>23) return false; *useOrigVal=true; return true; }
[ "troy@c0f1bf54-08b6-4aeb-9e84-c69c557caba5" ]
troy@c0f1bf54-08b6-4aeb-9e84-c69c557caba5
8c33b847dd429b961126f6ede029e67e2984ca3b
86f8019eabea54665bf709725aaf7b2967206058
/engine/generators/source/MarshGenerator.cpp
95cd1745173a723519679682d5c634fbc9fbe7fb
[ "MIT", "Zlib" ]
permissive
cleancoindev/shadow-of-the-wyrm
ca5d21a0d412de88804467b92ec46b78fb1e3ef0
51b23e98285ecb8336324bfd41ebf00f67b30389
refs/heads/master
2022-07-13T22:03:50.687853
2020-02-16T14:39:43
2020-02-16T14:39:43
264,385,732
1
0
MIT
2020-05-16T07:45:16
2020-05-16T07:45:15
null
UTF-8
C++
false
false
2,394
cpp
#include "AllTiles.hpp" #include "ItemManager.hpp" #include "MarshGenerator.hpp" #include "TileGenerator.hpp" #include "RNG.hpp" using namespace std; const int MarshGenerator::PCT_CHANCE_BOG_IRON = 25; MarshGenerator::MarshGenerator(const std::string& new_map_exit_id) : Generator(new_map_exit_id, TileType::TILE_TYPE_MARSH) { } MapPtr MarshGenerator::generate(const Dimensions& dimensions) { MapPtr result_map = std::make_shared<Map>(dimensions); fill(result_map, TileType::TILE_TYPE_MARSH); add_random_trees_bushes_weeds_and_reeds(result_map); if (RNG::percent_chance(PCT_CHANCE_BOG_IRON)) { add_bog_iron(result_map); result_map->set_permanent(true); } return result_map; } TilePtr MarshGenerator::generate_tile(MapPtr current_map, const int row, const int col) { TilePtr result_tile; int rand = RNG::range(1, 100); if (rand <= 3) { result_tile = tg.generate(TileType::TILE_TYPE_WEEDS); } else if (rand <= 4) { result_tile = tg.generate(TileType::TILE_TYPE_BUSH); } else if (rand <= 10) { result_tile = tg.generate(TileType::TILE_TYPE_TREE); } else if (rand <= 28) { result_tile = tg.generate(TileType::TILE_TYPE_REEDS); } return result_tile; } void MarshGenerator::add_random_trees_bushes_weeds_and_reeds(MapPtr result_map) { if (result_map != nullptr) { Dimensions d = result_map->size(); int rows = d.get_y(); int cols = d.get_x(); for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { TilePtr tile = generate_tile(result_map, row, col); if (tile) { result_map->insert(row, col, tile); } } } } } void MarshGenerator::add_bog_iron(MapPtr result_map) { if (result_map != nullptr) { Dimensions d = result_map->size(); int rows = d.get_y(); int cols = d.get_x(); int num_iron = cols / 10; int rand_y = 0; int rand_x = 0; ItemPtr bog_iron; for (int i = 0; i < num_iron; i++) { bog_iron = ItemManager::create_item(ItemIdKeys::ITEM_ID_BOG_IRON, RNG::range(1, 2)); rand_y = RNG::range(0, rows - 1); rand_x = RNG::range(0, cols - 1); TilePtr tile = result_map->at(rand_y, rand_x); if (tile != nullptr) { tile->get_items()->merge_or_add(bog_iron, InventoryAdditionType::INVENTORY_ADDITION_BACK); } } } }
[ "jcd748@mail.usask.ca" ]
jcd748@mail.usask.ca
0faea895801c60e0c226e3998f74a852b6c14949
176c566e4ca31736149ecb87bb4861a5b97e6046
/NeoPixelTest/NeoPixelTest.ino
473a93955ce042bc66d3d7199b08730f0677e14e
[]
no_license
CCAHybridLab/ArduinoDemo
35d489d64ef1dd7baaff2aca5c05f4714be50bc6
cac818c91c9be932737f49fd162e03cf99df6502
refs/heads/main
2023-04-28T16:01:55.828479
2021-05-24T22:28:09
2021-05-24T22:28:09
368,319,379
0
1
null
null
null
null
UTF-8
C++
false
false
3,781
ino
// Code from: https://gist.github.com/dougalcampbell/7243998 #include <Adafruit_NeoPixel.h> #define PIN 11 #define STRIPSIZE 16 // Parameter 1 = number of pixels in strip // Parameter 2 = pin number (most are valid) // Parameter 3 = pixel type flags, add together as needed: // NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs) // NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers) // NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products) // NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2) Adafruit_NeoPixel strip = Adafruit_NeoPixel(STRIPSIZE, PIN, NEO_GRB + NEO_KHZ800); void setup() { strip.begin(); strip.setBrightness(10); // Lower brightness and save eyeballs! strip.show(); // Initialize all pixels to 'off' } void loop() { // Some example procedures showing how to display to the pixels: colorWipe(strip.Color(0,0,0), 25); // Black colorWipe(strip.Color(64, 0, 0), 100); // Red colorWipe(strip.Color(0, 64, 0), 100); // Green colorWipe(strip.Color(0, 0, 64), 100); // Blue colorWave(75); colorWipe(strip.Color(0,0,0), 100); // Black rainbow(15); colorWipe(strip.Color(0,0,0), 100); // Black rainbowCycle(15); colorWipe(strip.Color(0,0,0), 100); // Black colorWave(30); } // Fill the dots one after the other with a color void colorWipe(uint32_t c, uint8_t wait) { for(uint16_t i=0; i<strip.numPixels(); i++) { strip.setPixelColor(i, c); strip.show(); delay(wait); } } void rainbow(uint8_t wait) { uint16_t i, j; for(j=0; j<256; j++) { for(i=0; i<strip.numPixels(); i++) { strip.setPixelColor(i, Wheel((i+j) & 255)); } strip.show(); delay(wait); } } // Slightly different, this makes the rainbow equally distributed throughout void rainbowCycle(uint8_t wait) { uint16_t i, j; for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel for(i=0; i< strip.numPixels(); i++) { strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255)); } strip.show(); delay(wait); } } // Input a value 0 to 255 to get a color value. // The colours are a transition r - g - b - back to r. uint32_t Wheel(byte WheelPos) { if(WheelPos < 85) { return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0); } else if(WheelPos < 170) { WheelPos -= 85; return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3); } else { WheelPos -= 170; return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3); } } /** * ^ ^ ^ * ~~~~~ ColorWave ~~~~~ * V V V */ void colorWave(uint8_t wait) { int i, j, stripsize, cycle; float ang, rsin, gsin, bsin, offset; static int tick = 0; stripsize = strip.numPixels(); cycle = stripsize * 25; // times around the circle... while (++tick % cycle) { offset = map2PI(tick); for (i = 0; i < stripsize; i++) { ang = map2PI(i) - offset; rsin = sin(ang); gsin = sin(2.0 * ang / 3.0 + map2PI(int(stripsize/6))); bsin = sin(4.0 * ang / 5.0 + map2PI(int(stripsize/3))); strip.setPixelColor(i, strip.Color(trigScale(rsin), trigScale(gsin), trigScale(bsin))); } strip.show(); delay(wait); } } /** * Scale a value returned from a trig function to a byte value. * [-1, +1] -> [0, 254] * Note that we ignore the possible value of 255, for efficiency, * and because nobody will be able to differentiate between the * brightness levels of 254 and 255. */ byte trigScale(float val) { val += 1.0; // move range to [0.0, 2.0] val *= 127.0; // move range to [0.0, 254.0] return int(val) & 255; } /** * Map an integer so that [0, striplength] -> [0, 2PI] */ float map2PI(int i) { return PI*2.0*float(i) / float(strip.numPixels()); }
[ "dewen@cca.edu" ]
dewen@cca.edu
802f0dfbe24e40af8c5e8d9bf08aba25dea4c719
6276ee99caf2a4bfd5adeefa4e815a30b220075e
/Baekjoon/1759_암호_만들기.cpp
0ca4a6aaad649904b99b9555ccc18aba3f54c97c
[]
no_license
RokwonK/Problem_solving
ba95b71aac0567e1d321484d2ffd9809c8b6654e
92bf77b93fcbe9102a18fc30a9d539276b06ffc5
refs/heads/master
2022-12-05T00:10:21.709831
2020-08-13T05:44:17
2020-08-13T05:44:17
210,171,514
0
0
null
null
null
null
UTF-8
C++
false
false
1,069
cpp
#include<iostream> #include<algorithm> #include<vector> using namespace std; int L, C; vector<char> arr; vector<char> password; void print_password() { int col = 0; int conso = 0; for (int i = 0; i < L; i++) { char c = password[i]; if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') col++; else conso++; } if( col >= 1 && conso >= 2) { for (int i = 0; i < L; i++) cout << password[i]; cout << '\n'; } } void backtracking(int now_location) { if (password.size() == L) { print_password(); return; } for (int i = now_location; i < C; i++) { password.push_back(arr[i]); backtracking(i+1); password.pop_back(); } } int main(void) { ios_base :: sync_with_stdio(0); cin.tie(0); cin >> L >> C; char value; for (int i = 0; i < C; i++) { cin >> value; arr.push_back(value); } sort( arr.begin(),arr.end() ); backtracking(0); return 0; }
[ "wonrok97@naver.com" ]
wonrok97@naver.com
aa82746f31b4255b53459d0abfd564c332aeda90
b7f4b07b4ba4049e556757cd5712f2c0b4ad0fa8
/final/b_____up2.cpp
8fb45cc24c09f3cf3ebb14c8074795d743445362
[]
no_license
matt-fevold/Parallel_Projects
262ee90d706eaa8a9a8e613c7b90d560059c0036
5a462a5e080f3cb596e1d81a715b01073d09b298
refs/heads/master
2021-01-09T20:20:46.228767
2017-08-23T22:23:03
2017-08-23T22:23:03
81,269,722
0
0
null
null
null
null
UTF-8
C++
false
false
13,629
cpp
//This program is gonna be the shit. //to compile : g++ -O0 create_table.cpp -o create_table #include <stdio.h> #include <fstream> #include <stdlib.h> #include <iostream> #include <string.h> #include <cstring> #include <sstream> #include <cmath> #include <time.h> #include <sys/time.h> #include <pthread.h> //Init values - for lmnt hash #define INIT_A 0x67452301 #define INIT_B 0xefcdab89 #define INIT_C 0x98badcfe #define INIT_D 0x10325476 #define SQRT_2 0x5a827999 #define SQRT_3 0x6ed9eba1 unsigned int nt_buffer[16]; unsigned int output[4]; //end of stuff for lmnt hash pthread_mutex_t lock; using namespace std; struct thread_data { int thread_id; string password; string character_set; int len_min; int len_max; int table_index; int chain_length; int chain_number; }; // int get_index(int a); void * thread_action (void *); //void *create_hash_chain(void *arg); string create_hash_chain(string password,string character_set,int len_min, int len_max, int index,int chain_length, int chain_number); string hash_function(string); string reduction_function(string hashed_password,string char_set,int len_min,int len_max,int index, int step_number); string NTLM(string key); //string global_plaintext_password; //string global_hashed_password; //function - hash_algorithm charset plaintext_len_min plaintext_len_max //table_index chain_len chain_num part_index int chain_num; int thread_number = 1; int main(int argc, char **argv){ struct timeval start, end; gettimeofday(&start,NULL); //convert args into vars //char *hash_algorithm; int plaintext_len_min;// = 1; int plaintext_len_max;// = 7; int table_index;// = 1; int chain_len;// = 10; int chain_num;// = 20; string character_set;// = "0123456789"; //int thread_number = 1; //if no args use default if(argc<2){ plaintext_len_min = 1; plaintext_len_max = 7; table_index = 1; chain_len = 10; chain_num = 20; character_set = "0123456789"; thread_number = 1; } else{ plaintext_len_min = atoi(argv[1]); plaintext_len_max = atoi(argv[2]); table_index = atoi(argv[3]); chain_len = atoi(argv[4]); chain_num = atoi(argv[5]); character_set = argv[6]; thread_number = atoi(argv[7]); //cout<<character_set<<endl; } //char *filepath = "~/git-repos/projects/parallel/final/finaloutput.txt"; ofstream myfile; myfile.open("rainbow_table.txt"); if(!myfile){ cout<<"error"<<endl; } //this should just be a series of function calls myfile<<plaintext_len_min<<" "<<plaintext_len_max<<" "<<table_index<<" "<<chain_len<<" "<<chain_num<<" "<<character_set<<endl; pthread_t thread[thread_number]; struct thread_data data[thread_number]; //create hashchain //pass it a random password (could be a file/arg passed here??? :D ) //do this for as many chains as desired for(int i = 0; i < thread_number;i++){ //random starting password //int to string convert //double max_len = pow(10,plaintext_len_max); //int a = 1001*(table_index)*7*(i+1) % (int)max_len;// pow(10,plaintext_len_max); //stringstream ss; //cout<<a<<endl<<endl; //ss <<a ; //string str = ss.str(); //string original_plaintext_password =str; //string plaintext_password = original_plaintext_password; //cout<<endl<<"NEW CHAIN : Password :"<< plaintext_password <<endl; //write first password into file //pthread_mutex_lock(&lock); //myfile <<plaintext_password<< " "; //pthread time!!! data[i].thread_id = i; //data[i].password = plaintext_password; data[i].character_set = character_set; data[i].len_min = plaintext_len_min; data[i].len_max = plaintext_len_max; data[i].table_index = table_index; data[i].chain_length = chain_len; data[i].chain_number = chain_num; // cout<<data[i].thread_id<<endl; int rc = pthread_create(&thread[i],NULL,thread_action,(void *) &data[i]); if(rc){ cout<<"ERROR"<<endl; } else{ cout<<"thread created"<<endl; } //create hash chains! //string final_hashed_password = create_hash_chain(plaintext_password,character_set, plaintext_len_min,plaintext_len_max,table_index,chain_len,chain_num); // pthread_mutex_lock(&lock); // string final_hashed_password = "1234"; //myfile <<original_plaintext_password<<" "<<final_hashed_password<<endl; // pthread_mutex_unlock(&lock); } for(int i = 0; i < thread_number;i++){ pthread_join(thread[i],NULL); } myfile.close(); gettimeofday(&end,NULL); int second_to_microsecond = 1000000; int time = ((end.tv_sec * second_to_microsecond + end.tv_usec) - (start.tv_sec * second_to_microsecond + start.tv_usec)); cout<< "Execution Time in Micro Seconds: " << time<<endl; return 0; } //for determining where thread starts int get_index(int a ){ int index = a * ceil((1.0 * chain_num)/thread_number); return index; } void * thread_action(void *struct_data){ struct thread_data *data; data = (struct thread_data*) struct_data; int thread_id = struct_data->thread_id; string character_set = struct_data->character_set; int plaintext_len_min = struct_data->len_min; int plaintext_len_max = struct_data->len_max; int table_index = struct_data->table_index; int chain_len= struct_data->chain_length; int chain_num = struct_data->chain_number; int start = get_index(thread_id); int stop = get_index(thread_id+1); for(int i = start; i< stop;i++){ double max_len = pow(10,plaintext_len_max); int a = 1001*(table_index)*7*(i+1) % (int)max_len;// pow(10,plaintext_len_max); stringstream ss; //cout<<a<<endl<<endl; ss <<a ; string str = ss.str(); string original_plaintext_password =str; string plaintext_password = original_plaintext_password; string final_hashed_password = create_hash_chain(plaintext_password,character_set, plaintext_len_min,plaintext_len_max,table_index,chain_len,chain_num); ofstream myfile; pthread_mutex_lock(&lock); myfile.open("rainbow_table.txt"); if(!myfile){ cout<<"error"<<endl; } myfile<<original_plaintext_password<<" "<<final_hashed_password<<endl; pthread_mutex_unlock(&lock); myfile.close(); } } string create_hash_chain( string password,string char_set, int len_min, int len_max, int index,int chain_length, int chain_number){ //struct thread_data *data; //data = (struct thread_data*) arg; //int start=get_index(id); //int stop=get_index(id); //for(int i = start; i<stop;i++) //{ //create password //first turn password into hash //global_plaintext_password = password; string plaintext_password = password; string hashed_password="0"; int max_len = len_max; for(int i = 0; i < chain_length ; i++){ //for as many links as desired, hash and reduce in a loop hashed_password = hash_function(plaintext_password); plaintext_password = reduction_function(hashed_password,char_set,len_min,max_len,index,i); } //pthread_exit(NULL); //return "1234"; return hashed_password; } string reduction_function(string hashed_password,string char_set, int len_min,int len_max,int table_index, int step){ //because was getting seg faults since len_max was getting changed... int max_len = len_max; int current_step = step; string to_reduce[33];// = hashed_paret_value //reduction time!!! string character_set(char_set); string hash(hashed_password); int index_table = table_index; string ret_value(32,'0');//[hash.size()]; for(int i = 0;i<32;i++){ int flag = 0; for(int j = 0;j<10;j++){ string::size_type loc = hash.find(char_set[j],i); if(loc != string::npos && flag ==0){ if(hash[i]==hash[loc]){ flag = 1; ret_value[i]=hash[loc]; } } } if(flag ==0 ){ int a = (current_step + index_table) % 10; //convert to char char ch = (a + '0'); ret_value[i]= ch; } } int start = (hash.size()-step) %max_len; //starting point is between = 0 and max_len based on step!!! //this particular reduction func. could cause more collisions... but works string to_return = ret_value.substr(start,max_len); // cout<<to_return<<endl<<endl; return to_return; } string hash_function(string plaintext_password){ //NTLM(plaintext_password); string hashed_password = NTLM(plaintext_password); // cout<<hashed_password<<endl; return hashed_password; } //hash function NTLM (Windows authentication) //from source: give credit!!! string NTLM(string key) { char hex_format[33]; char itoa16[17] = "0123456789ABCDEF"; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Prepare the string for hash calculation //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ int i = 0; //int length = strlen(key); int length = key.size(); memset(nt_buffer, 0, 16*4); //The length of key need to be <= 27 for(; i<length/2; i++) nt_buffer[i] = key[2 * i] | (key[2 * i + 1] << 16); //padding if(length % 2 == 1) nt_buffer[i] = key[length - 1] | 0x800000; else nt_buffer[i] = 0x80; //put the length nt_buffer[14] = length << 4; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // NTLM hash calculation //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ unsigned int a = INIT_A; unsigned int b = INIT_B; unsigned int c = INIT_C; unsigned int d = INIT_D; /* Round 1 */ a += (d ^ (b & (c ^ d))) + nt_buffer[0] ;a = (a << 3 ) | (a >> 29); d += (c ^ (a & (b ^ c))) + nt_buffer[1] ;d = (d << 7 ) | (d >> 25); c += (b ^ (d & (a ^ b))) + nt_buffer[2] ;c = (c << 11) | (c >> 21); b += (a ^ (c & (d ^ a))) + nt_buffer[3] ;b = (b << 19) | (b >> 13); a += (d ^ (b & (c ^ d))) + nt_buffer[4] ;a = (a << 3 ) | (a >> 29); d += (c ^ (a & (b ^ c))) + nt_buffer[5] ;d = (d << 7 ) | (d >> 25); c += (b ^ (d & (a ^ b))) + nt_buffer[6] ;c = (c << 11) | (c >> 21); b += (a ^ (c & (d ^ a))) + nt_buffer[7] ;b = (b << 19) | (b >> 13); a += (d ^ (b & (c ^ d))) + nt_buffer[8] ;a = (a << 3 ) | (a >> 29); d += (c ^ (a & (b ^ c))) + nt_buffer[9] ;d = (d << 7 ) | (d >> 25); c += (b ^ (d & (a ^ b))) + nt_buffer[10] ;c = (c << 11) | (c >> 21); b += (a ^ (c & (d ^ a))) + nt_buffer[11] ;b = (b << 19) | (b >> 13); a += (d ^ (b & (c ^ d))) + nt_buffer[12] ;a = (a << 3 ) | (a >> 29); d += (c ^ (a & (b ^ c))) + nt_buffer[13] ;d = (d << 7 ) | (d >> 25); c += (b ^ (d & (a ^ b))) + nt_buffer[14] ;c = (c << 11) | (c >> 21); b += (a ^ (c & (d ^ a))) + nt_buffer[15] ;b = (b << 19) | (b >> 13); /* Round 2 */ a += ((b & (c | d)) | (c & d)) + nt_buffer[0] +SQRT_2; a = (a<<3 ) | (a>>29); d += ((a & (b | c)) | (b & c)) + nt_buffer[4] +SQRT_2; d = (d<<5 ) | (d>>27); c += ((d & (a | b)) | (a & b)) + nt_buffer[8] +SQRT_2; c = (c<<9 ) | (c>>23); b += ((c & (d | a)) | (d & a)) + nt_buffer[12]+SQRT_2; b = (b<<13) | (b>>19); a += ((b & (c | d)) | (c & d)) + nt_buffer[1] +SQRT_2; a = (a<<3 ) | (a>>29); d += ((a & (b | c)) | (b & c)) + nt_buffer[5] +SQRT_2; d = (d<<5 ) | (d>>27); c += ((d & (a | b)) | (a & b)) + nt_buffer[9] +SQRT_2; c = (c<<9 ) | (c>>23); b += ((c & (d | a)) | (d & a)) + nt_buffer[13]+SQRT_2; b = (b<<13) | (b>>19); a += ((b & (c | d)) | (c & d)) + nt_buffer[2] +SQRT_2; a = (a<<3 ) | (a>>29); d += ((a & (b | c)) | (b & c)) + nt_buffer[6] +SQRT_2; d = (d<<5 ) | (d>>27); c += ((d & (a | b)) | (a & b)) + nt_buffer[10]+SQRT_2; c = (c<<9 ) | (c>>23); b += ((c & (d | a)) | (d & a)) + nt_buffer[14]+SQRT_2; b = (b<<13) | (b>>19); a += ((b & (c | d)) | (c & d)) + nt_buffer[3] +SQRT_2; a = (a<<3 ) | (a>>29); d += ((a & (b | c)) | (b & c)) + nt_buffer[7] +SQRT_2; d = (d<<5 ) | (d>>27); c += ((d & (a | b)) | (a & b)) + nt_buffer[11]+SQRT_2; c = (c<<9 ) | (c>>23); b += ((c & (d | a)) | (d & a)) + nt_buffer[15]+SQRT_2; b = (b<<13) | (b>>19); /* Round 3 */ a += (d ^ c ^ b) + nt_buffer[0] + SQRT_3; a = (a << 3 ) | (a >> 29); d += (c ^ b ^ a) + nt_buffer[8] + SQRT_3; d = (d << 9 ) | (d >> 23); c += (b ^ a ^ d) + nt_buffer[4] + SQRT_3; c = (c << 11) | (c >> 21); b += (a ^ d ^ c) + nt_buffer[12] + SQRT_3; b = (b << 15) | (b >> 17); a += (d ^ c ^ b) + nt_buffer[2] + SQRT_3; a = (a << 3 ) | (a >> 29); d += (c ^ b ^ a) + nt_buffer[10] + SQRT_3; d = (d << 9 ) | (d >> 23); c += (b ^ a ^ d) + nt_buffer[6] + SQRT_3; c = (c << 11) | (c >> 21); b += (a ^ d ^ c) + nt_buffer[14] + SQRT_3; b = (b << 15) | (b >> 17); a += (d ^ c ^ b) + nt_buffer[1] + SQRT_3; a = (a << 3 ) | (a >> 29); d += (c ^ b ^ a) + nt_buffer[9] + SQRT_3; d = (d << 9 ) | (d >> 23); c += (b ^ a ^ d) + nt_buffer[5] + SQRT_3; c = (c << 11) | (c >> 21); b += (a ^ d ^ c) + nt_buffer[13] + SQRT_3; b = (b << 15) | (b >> 17); a += (d ^ c ^ b) + nt_buffer[3] + SQRT_3; a = (a << 3 ) | (a >> 29); d += (c ^ b ^ a) + nt_buffer[11] + SQRT_3; d = (d << 9 ) | (d >> 23); c += (b ^ a ^ d) + nt_buffer[7] + SQRT_3; c = (c << 11) | (c >> 21); b += (a ^ d ^ c) + nt_buffer[15] + SQRT_3; b = (b << 15) | (b >> 17); output[0] = a + INIT_A; output[1] = b + INIT_B; output[2] = c + INIT_C; output[3] = d + INIT_D; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Convert the hash to hex (for being readable) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ for(i=0; i<4; i++) { int j = 0; unsigned int n = output[i]; //iterate the bytes of the integer for(; j<4; j++) { unsigned int convert = n % 256; hex_format[i * 8 + j * 2 + 1] = itoa16[convert % 16]; convert = convert / 16; hex_format[i * 8 + j * 2 + 0] = itoa16[convert % 16]; n = n / 256; } } //return hex_format; //null terminate the string hex_format[32] = 0; string ret_value(hex_format); // cout<<ret_value<<endl; return ret_value; }
[ "mfevold@matt.fevold" ]
mfevold@matt.fevold
a0c6c480f52d85a5bd9f3e233d9780b35f3484ef
fc833788e798460d3fb153fbb150ea5263daf878
/boj/2000~2999/2512.cpp
d310534418a9f2ff6c5ae6d399173b7bdf08e890
[]
no_license
ydk1104/PS
a50afdc4dd15ad1def892368591d4bd1f84e9658
2c791b267777252ff4bf48a8f54c98bcdcd64af9
refs/heads/master
2021-07-18T08:19:34.671535
2020-09-02T17:45:59
2020-09-02T17:45:59
208,404,564
4
0
null
null
null
null
UTF-8
C++
false
false
382
cpp
#include<stdio.h> #include<algorithm> int main(void){ int N, M, a[10001], sum=0; scanf("%d", &N); for(int i=0; i<N; i++) scanf("%d", &a[i]), sum+=a[i]; a[N]=0; N++; std::sort(a, a+N); scanf("%d", &M); int r=N-1; if(M>=sum){ printf("%d", a[r]); return 0; } while(M<sum && r>0){ sum-=a[r]*(N-r); sum+=a[r-1]*(N-r); r--; } printf("%d\n", a[r]+(M-sum)/(N-r-1)); }
[ "ydk1104@naver.com" ]
ydk1104@naver.com
0057c72cbecc82cbe75d52fa2110ca24a61f185e
f4a454c286bb181c65205a46c28676461e72e1bd
/libretrodb/imagetools.cpp
28fd90ba2219791d019afc25accda2b9f1afa3a0
[]
no_license
meepingsnesroms/libretro-GameFinder
c8e2342403047dbb8cdab4f0711669a31d5a9153
b668e09b839e85e41c1963d030b35367db6076bb
refs/heads/master
2021-09-03T23:49:13.710508
2018-01-13T00:44:14
2018-01-13T00:44:14
111,157,819
0
1
null
null
null
null
UTF-8
C++
false
false
1,856
cpp
#include <stdint.h> #include <string.h> #include <formats/image.h> #include <string> void copy_rect(unsigned fb1_w, unsigned fb1_h, uint32_t* fb1_data, unsigned fb1_x, unsigned fb1_y, unsigned rect_w, unsigned rect_h, unsigned fb2_w, unsigned fb2_h, uint32_t* fb2_data, unsigned fb2_x, unsigned fb2_y) { for(unsigned y = 0; y < rect_h; y++) { for(unsigned x = 0; x < rect_w; x++) { fb2_data[fb2_w * (fb2_y + y) + fb2_x + x] = fb1_data[fb1_w * (fb1_y + y) + fb1_x + x]; } } } void simple_float_scale(unsigned w, unsigned h, uint32_t* data, unsigned out_w, unsigned out_h, uint32_t* output_buffer) { for(unsigned y = 0; y < out_h; y++) { for(unsigned x = 0; x < out_w; x++) { double scale_x = (double)x / (double)out_w * (double)w; double scale_y = (double)y / (double)out_h * (double)h; unsigned pixel_scale_x = (int)scale_x; unsigned pixel_scale_y = (int)scale_y; //prevent float inaccuracy from reading undefined memory if (pixel_scale_x > w) pixel_scale_x = w; if (pixel_scale_y > h) pixel_scale_y = h; output_buffer[y * out_w + x] = data[pixel_scale_y * w + pixel_scale_x]; } } } void get_file_thumbnail(std::string path, uint32_t* output_buffer, unsigned width, unsigned height) { struct texture_image thumbnail_file; bool worked; thumbnail_file.supports_rgba = false; worked = image_texture_load(&thumbnail_file, path.c_str()); if (worked) { simple_float_scale(thumbnail_file.width, thumbnail_file.height, thumbnail_file.pixels, width, height, output_buffer); image_texture_free(&thumbnail_file); } else { //return null buffer memset(output_buffer, 0x00, width * height * sizeof(uint32_t)); } }
[ "guicrith@gmail.com" ]
guicrith@gmail.com
45c6bcc95a06b0d27f13fca9f412aa21bf8fcb13
0cf8d6e3a2ac43e60d114045b62ffd1b6609b719
/code example/IF.ino
e7e3dbb8fa9c4298bcdd16d5ca1ed2d510127f1c
[]
no_license
WangHuancheng/Robot
94fcb48fe4cffe262ede61924dd251e81a1ce1a4
32ff7f2eae1224ba621bc412f6cfd7ff0116be91
refs/heads/master
2022-05-01T11:02:08.495617
2022-04-27T15:58:23
2022-04-27T15:58:23
136,593,361
0
0
null
null
null
null
UTF-8
C++
false
false
368
ino
void getEncoderL(void) { //Serial.println("L"); encodertime_L++; if(digitalRead(ENCODER_L1) == LOW) { if(digitalRead(ENCODER_L2) == LOW) { encoderVal_L--; } else { encoderVal_L++; } } else { if(digitalRead(ENCODER_L2) == LOW) { encoderVal_L++; } else { encoderVal_L--; } } }
[ "wangkang980930@outlook.com" ]
wangkang980930@outlook.com
a689a7c5dc855b19e41be03b26ddbb324fdf99eb
b72b78977fe074011ef6c2dc6080cc96c11308a3
/Learn Advanaced Modern C++/CRTP/main.cpp
d4eb9785c227870cf0ac8fe6910fd341aab56a1e
[]
no_license
christianyoedhana/CppPractice
9e16e3eac5eaa3fb23e11f8c63ca0265ef8cf1ce
5dda87c7227983263a2b256ccef9cc99e2dd8b26
refs/heads/main
2023-03-13T09:51:24.302045
2021-03-05T22:10:14
2021-03-05T22:10:14
342,725,957
0
0
null
null
null
null
UTF-8
C++
false
false
509
cpp
//The premise for using CRTP is knowing the type to use at compile time and wanting to do something about the interface #include "CRTPSub1.h" #include "CRTPSub2.h" #include "Malformed.h" #include <iostream> using namespace std; template <typename T> void executeTask(CRTPBase<T>& actors) { cout << __FUNCSIG__ << endl; actors.task1(); actors.task2(); } int main(int, const char*) { CRTPSub1 sub1; CRTPSub2 sub2; Malformed oops; executeTask(sub1); executeTask(sub2); executeTask(oops); return 0; }
[ "christian.yoedhana@gmail.com" ]
christian.yoedhana@gmail.com
36040a9ecc010134d870afb96892c2f9b7dc4ad3
ec77e636964027dece32ac921617f70532804cf7
/第6章-惯性导航解算及误差模型/06-imu-navigation/src/imu_integration/src/generator/activity.cpp
fb30208fc241502c7bbfcd9caf24c82dbe9b169a
[]
no_license
zxl19/sensor-fusion-1
c18c50b0f351bc14ec5ae8ddef6e455fb36a9f99
e70719165ac83eb65904a9057ee1db2dadcfcf96
refs/heads/main
2023-07-13T05:11:57.828772
2021-08-23T17:38:44
2021-08-23T17:38:44
399,796,740
1
0
null
2021-08-25T11:39:46
2021-08-25T11:39:45
null
UTF-8
C++
false
false
9,237
cpp
/* * @Description: IMU measurement generation activity * @Author: Ge Yao * @Date: 2020-11-10 14:25:03 */ #include "imu_integration/generator/node_constants.hpp" #include "imu_integration/generator/activity.hpp" #include "glog/logging.h" #include <eigen3/Eigen/src/Geometry/Quaternion.h> #include <math.h> namespace imu_integration { namespace generator { // 初始化数据生成器 Activity::Activity(void) : private_nh_("~"), // 标准正态分布: normal_distribution_(0.0, 1.0), // 重力加速度: G_(0, 0, -9.81), // 角速度偏差: angular_vel_bias_(0.0, 0.0, 0.0), // 线加速度偏差: linear_acc_bias_(0.0, 0.0, 0.0) {} void Activity::Init(void) { // 提取IMU配置文件: private_nh_.param("imu/device_name", imu_config_.device_name, std::string("GNSS_INS_SIM_IMU")); private_nh_.param("imu/topic_name", imu_config_.topic_name, std::string("/sim/sensor/imu")); private_nh_.param("imu/frame_id", imu_config_.frame_id, std::string("ENU")); // a. 重力常量: private_nh_.param("imu/gravity/x", imu_config_.gravity.x, 0.0); private_nh_.param("imu/gravity/y", imu_config_.gravity.y, 0.0); private_nh_.param("imu/gravity/z", imu_config_.gravity.z, -9.81); G_.x() = imu_config_.gravity.x; G_.y() = imu_config_.gravity.y; G_.z() = imu_config_.gravity.z; // b. 角速度偏差: private_nh_.param("imu/bias/angular_velocity/x", imu_config_.bias.angular_velocity.x, 0.0); private_nh_.param("imu/bias/angular_velocity/y", imu_config_.bias.angular_velocity.y, 0.0); private_nh_.param("imu/bias/angular_velocity/z", imu_config_.bias.angular_velocity.z, 0.0); angular_vel_bias_.x() = imu_config_.bias.angular_velocity.x; angular_vel_bias_.y() = imu_config_.bias.angular_velocity.y; angular_vel_bias_.z() = imu_config_.bias.angular_velocity.z; // c. 线加速度偏差: private_nh_.param("imu/bias/linear_acceleration/x", imu_config_.bias.linear_acceleration.x, 0.0); private_nh_.param("imu/bias/linear_acceleration/y", imu_config_.bias.linear_acceleration.y, 0.0); private_nh_.param("imu/bias/linear_acceleration/z", imu_config_.bias.linear_acceleration.z, 0.0); linear_acc_bias_.x() = imu_config_.bias.linear_acceleration.x; linear_acc_bias_.y() = imu_config_.bias.linear_acceleration.y; linear_acc_bias_.z() = imu_config_.bias.linear_acceleration.z; // d. 角速度随机噪声: private_nh_.param("imu/gyro/sigma_bias", imu_config_.gyro_bias_stddev, 5e-5); private_nh_.param("imu/gyro/sigma_noise", imu_config_.gyro_noise_stddev, 0.015); // e. 线加速度随机噪声: private_nh_.param("imu/acc/sigma_bias", imu_config_.acc_bias_stddev, 5e-4); private_nh_.param("imu/acc/sigma_noise", imu_config_.acc_noise_stddev, 0.019); // 里程计配置: private_nh_.param("pose/frame_id", odom_config_.frame_id, std::string("inertial")); private_nh_.param("pose/topic_name", odom_config_.topic_name.ground_truth, std::string("/pose/ground_truth")); // 初始化数据发布者: pub_imu_ = private_nh_.advertise<sensor_msgs::Imu>(imu_config_.topic_name, 500); pub_odom_ = private_nh_.advertise<nav_msgs::Odometry>(odom_config_.topic_name.ground_truth, 500); // init timestamp: timestamp_ = ros::Time::now(); } void Activity::Run(void) { // update timestamp: ros::Time timestamp = ros::Time::now(); double delta_t = timestamp.toSec() - timestamp_.toSec(); timestamp_ = timestamp; // 从运动方程中获取真实数据: GetGroundTruth(); // 更新偏差&&添加随机噪声: AddNoise(delta_t); // 生成ros消息: SetIMUMessage(); SetOdometryMessage(); // 发布ros消息: PublishMessages(); } void Activity::GetGroundTruth(void) { // 加速度: double timestamp_in_sec = timestamp_.toSec(); // xy平面的角速度 double sin_w_xy_t = sin(kOmegaXY*timestamp_in_sec); double cos_w_xy_t = cos(kOmegaXY*timestamp_in_sec); // z平面的角速度 double sin_w_z_t = sin(kOmegaZ*timestamp_in_sec); double cos_w_z_t = cos(kOmegaZ*timestamp_in_sec); double rho_x_w_xy = kRhoX*kOmegaXY; double rho_y_w_xy = kRhoY*kOmegaXY; double rho_z_w_z = kRhoZ*kOmegaZ; Eigen::Vector3d p( kRhoX*cos_w_xy_t, kRhoY*sin_w_xy_t, kRhoZ*sin_w_z_t ); Eigen::Vector3d v( -rho_x_w_xy*sin_w_xy_t, rho_y_w_xy*cos_w_xy_t, rho_z_w_z*cos_w_z_t ); Eigen::Vector3d a( -rho_x_w_xy*kOmegaXY*cos_w_xy_t, -rho_y_w_xy*kOmegaXY*sin_w_xy_t, -rho_z_w_z*kOmegaZ*sin_w_z_t ); // angular velocity: double sin_t = sin(timestamp_in_sec); double cos_t = cos(timestamp_in_sec); Eigen::Vector3d euler_angles( kRoll*cos_t, kPitch*sin_t, kYaw*timestamp_in_sec ); Eigen::Vector3d euler_angle_rates( -kRoll*sin_t, kPitch*cos_t, kYaw ); // transform to body frame: R_gt_ = EulerAnglesToRotation(euler_angles); t_gt_ = p; v_gt_ = v; // a. angular velocity: angular_vel_ = EulerAngleRatesToBodyAngleRates(euler_angles, euler_angle_rates); // b. linear acceleration: linear_acc_ = R_gt_.transpose() * (a + G_); } void Activity::AddNoise(double delta_t) { // TODO: add params to class attributes: double sqrt_delta_t = sqrt(delta_t); // a. update bias: angular_vel_bias_ += GetGaussianNoise(imu_config_.gyro_bias_stddev * sqrt_delta_t); linear_acc_bias_ += GetGaussianNoise(imu_config_.acc_bias_stddev * sqrt_delta_t); // b. get measurement noise: Eigen::Vector3d angular_vel_noise = GetGaussianNoise(imu_config_.gyro_noise_stddev / sqrt_delta_t); Eigen::Vector3d linear_acc_noise = GetGaussianNoise(imu_config_.acc_noise_stddev / sqrt_delta_t); // apply to measurement: angular_vel_ += angular_vel_bias_ + angular_vel_noise; linear_acc_ += linear_acc_bias_ + linear_acc_noise; } void Activity::SetIMUMessage(void) { // a. set header: message_imu_.header.stamp = timestamp_; message_imu_.header.frame_id = imu_config_.frame_id; // b. set orientation: Eigen::Quaterniond q(R_gt_); message_imu_.orientation.x = q.x(); message_imu_.orientation.y = q.y(); message_imu_.orientation.z = q.z(); message_imu_.orientation.w = q.w(); // c. set angular velocity: message_imu_.angular_velocity.x = angular_vel_.x(); message_imu_.angular_velocity.y = angular_vel_.y(); message_imu_.angular_velocity.z = angular_vel_.z(); // d. set linear acceleration: message_imu_.linear_acceleration.x = linear_acc_.x(); message_imu_.linear_acceleration.y = linear_acc_.y(); message_imu_.linear_acceleration.z = linear_acc_.z(); } void Activity::SetOdometryMessage(void) { // a. set header: message_odom_.header.stamp = timestamp_; message_odom_.header.frame_id = odom_config_.frame_id; // b. set child frame id: message_odom_.child_frame_id = odom_config_.frame_id; // b. set orientation: Eigen::Quaterniond q(R_gt_); message_odom_.pose.pose.orientation.x = q.x(); message_odom_.pose.pose.orientation.y = q.y(); message_odom_.pose.pose.orientation.z = q.z(); message_odom_.pose.pose.orientation.w = q.w(); // c. set position: message_odom_.pose.pose.position.x = t_gt_.x(); message_odom_.pose.pose.position.y = t_gt_.y(); message_odom_.pose.pose.position.z = t_gt_.z(); // d. set velocity: message_odom_.twist.twist.linear.x = v_gt_.x(); message_odom_.twist.twist.linear.y = v_gt_.y(); message_odom_.twist.twist.linear.z = v_gt_.z(); } void Activity::PublishMessages(void) { pub_imu_.publish(message_imu_); pub_odom_.publish(message_odom_); } Eigen::Vector3d Activity::GetGaussianNoise(double stddev) { return stddev * Eigen::Vector3d( normal_distribution_(normal_generator_), normal_distribution_(normal_generator_), normal_distribution_(normal_generator_) ); } Eigen::Matrix3d Activity::EulerAnglesToRotation( const Eigen::Vector3d &euler_angles ) { // parse Euler angles: double roll = euler_angles.x(); double pitch = euler_angles.y(); double yaw = euler_angles.z(); double cr = cos(roll); double sr = sin(roll); double cp = cos(pitch); double sp = sin(pitch); double cy = cos(yaw); double sy = sin(yaw); Eigen::Matrix3d R_ib; R_ib << cy*cp, cy*sp*sr - sy*cr, sy*sr + cy* cr*sp, sy*cp, cy *cr + sy*sr*sp, sp*sy*cr - cy*sr, -sp, cp*sr, cp*cr; return R_ib; } Eigen::Vector3d Activity::EulerAngleRatesToBodyAngleRates( const Eigen::Vector3d &euler_angles, const Eigen::Vector3d &euler_angle_rates ) { // parse euler angles: double roll = euler_angles(0); double pitch = euler_angles(1); double cr = cos(roll); double sr = sin(roll); double cp = cos(pitch); double sp = sin(pitch); Eigen::Matrix3d R; R << 1, 0, - sp, 0, cr, sr*cp, 0, -sr, cr*cp; return R * euler_angle_rates; } } // namespace generator } // namespace imu_integration
[ "18810521109@163.com" ]
18810521109@163.com
4e01bdf2a15357ed13d97f9d1b758ce716bf47fa
0ca8832a2818af66f1a584d7cf6c56abf0af8591
/src/thirdparty/boost/boost/date_time/date_formatting_limited.hpp
ea104024b65729f708685bdd8809df0d6eca9f21
[]
no_license
knobik/source-python
241e27d325d40fc8374fc9fb8f8311a146dc7e77
e57308a662c25110f1a1730199985a5f2cf11713
refs/heads/master
2021-01-10T08:28:55.402519
2013-09-12T04:00:12
2013-09-12T04:00:12
54,717,312
0
0
null
null
null
null
UTF-8
C++
false
false
3,629
hpp
#ifndef DATE_TIME_DATE_FORMATTING_LIMITED_HPP___ #define DATE_TIME_DATE_FORMATTING_LIMITED_HPP___ /* Copyright (c) 2002-2004 CrystalClear Software, Inc. * Use, modification and distribution is subject to the * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst * $Date: 2011-01-15 03:11:51 -0500 (Sat, 15 Jan 2011) $ */ #include "boost/date_time/iso_format.hpp" #include "boost/date_time/compiler_config.hpp" #include <string> #include <sstream> #include <iomanip> namespace boost { namespace date_time { //! Formats a month as as string into an ostream template<class month_type, class format_type> class month_formatter { public: //! Formats a month as as string into an ostream /*! This function demands that month_type provide * functions for converting to short and long strings * if that capability is used. */ static std::ostream& format_month(const month_type& month, std::ostream& os) { switch (format_type::month_format()) { case month_as_short_string: { os << month.as_short_string(); break; } case month_as_long_string: { os << month.as_long_string(); break; } case month_as_integer: { os << std::setw(2) << std::setfill('0') << month.as_number(); break; } } return os; } // format_month }; //! Convert ymd to a standard string formatting policies template<class ymd_type, class format_type> class ymd_formatter { public: //! Convert ymd to a standard string formatting policies /*! This is standard code for handling date formatting with * year-month-day based date information. This function * uses the format_type to control whether the string will * contain separator characters, and if so what the character * will be. In addtion, it can format the month as either * an integer or a string as controled by the formatting * policy */ static std::string ymd_to_string(ymd_type ymd) { typedef typename ymd_type::month_type month_type; std::ostringstream ss; ss << ymd.year; if (format_type::has_date_sep_chars()) { ss << format_type::month_sep_char(); } //this name is a bit ugly, oh well.... month_formatter<month_type,format_type>::format_month(ymd.month, ss); if (format_type::has_date_sep_chars()) { ss << format_type::day_sep_char(); } ss << std::setw(2) << std::setfill('0') << ymd.day; return ss.str(); } }; //! Convert a date to string using format policies template<class date_type, class format_type> class date_formatter { public: //! Convert to a date to standard string using format policies static std::string date_to_string(date_type d) { typedef typename date_type::ymd_type ymd_type; if (d.is_not_a_date()) { return format_type::not_a_date(); } if (d.is_neg_infinity()) { return format_type::neg_infinity(); } if (d.is_pos_infinity()) { return format_type::pos_infinity(); } ymd_type ymd = d.year_month_day(); return ymd_formatter<ymd_type, format_type>::ymd_to_string(ymd); } }; } } //namespace date_time #endif
[ "satoon101@gmail.com" ]
satoon101@gmail.com
ec245e64f1a18623429d55a237a34b64335778b7
bdb421953ea75cbe26387b33d9f93a789b83754c
/Modules/src/Scene/Node.h
4bfe206e3d403b9a0a897e523c7fa004a1b57b53
[]
no_license
deanamu/2DGraphics1PushPUsh
e442401b6ce6fa56678a37e07b9e875d85838c74
26a6e6d812134cdfd8d29e497d49df4acf823c32
refs/heads/master
2021-04-13T11:28:06.776960
2020-03-22T10:27:26
2020-03-22T10:27:26
249,159,684
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,991
h
#ifndef INCLUDED_GAMELIB_SCENE_NODE_H #define INCLUDED_GAMELIB_SCENE_NODE_H #include "GameLib/Math/Matrix34.h" #include "GameLib/Math/Matrix44.h" #include "GameLib/Math/Functions.h" #include "Scene/NodeTemplate.h" #include "Scene/AnimationNode.h" namespace GameLib{ namespace Scene{ using namespace GameLib::Math; class Node{ public: Node( const NodeTemplate* tmpl ) : mTranslation( 0.f, 0.f, 0.f ), mRotation( 0.f, 0.f, 0.f ), mScale( 1.f, 1.f, 1.f ), mChildren( 0 ), mChildNumber( 0 ), mTemplate( tmpl ), mAnimation( 0 ){ } ~Node(){ mTemplate = 0; //単なる参照 mAnimation = 0; } void setChildren( Node** children, int childNumber ){ mChildren = children; mChildNumber = childNumber; } void draw( const Matrix34& parentMatrix, const Vector3& color, float transparency ) const { //ワールド行列を作る Matrix34 w = parentMatrix; w.setMul( parentMatrix, mTemplate->mTransform ); //デフォルトをかけて、 w.translate( mTranslation ); w.rotateY( mRotation.y ); w.rotateX( mRotation.x ); w.rotateZ( mRotation.z ); w.scale( mScale ); if ( mTemplate->mBatch ){ //セット Graphics::Manager().setWorldMatrix( w ); //描画 mTemplate->mBatch->draw( color, transparency ); } for ( int i = 0; i < mChildNumber; ++i ){ mChildren[ i ]->draw( w, color, transparency ); } } void setAnimation( const AnimationNode* a ){ mAnimation = a; } void removeAnimation(){ mAnimation = 0; mTranslation.set( 0.f, 0.f, 0.f ); mRotation.set( 0.f, 0.f, 0.f ); mScale.set( 1.f, 1.f, 1.f ); } void updateAnimation( float t ){ if ( mAnimation ){ mAnimation->update( &mTranslation, &mRotation, &mScale, t ); } } const char* name() const { return mTemplate->mName; } private: Vector3 mTranslation; Vector3 mRotation; Vector3 mScale; Node** mChildren; int mChildNumber; const NodeTemplate* mTemplate; const AnimationNode* mAnimation; }; } //namespace Scene } //namespace GameLib #endif
[ "concept_sj@naver.com" ]
concept_sj@naver.com
51469e0a7f1efac463752fb91c6a01468a8849a2
63d59d93394cf1b3b0f4aa6f72420ec140e5bdcb
/src/LedModule.cpp
e6fe26f22186dbc08bb3ab97459802f92006101e
[]
no_license
aligator/LedControl
920ab597572e45d46b452fcbba30a46c796c507b
471bb8ef5ab7183dd174346af68967643c173c4f
refs/heads/master
2022-01-20T09:05:57.143636
2021-12-29T15:10:27
2021-12-29T15:10:27
221,569,793
0
0
null
null
null
null
UTF-8
C++
false
false
132
cpp
#include "LedModule.h" #include <Arduino.h> LedModule::LedModule(LedStrip* led) { this->led = led; } LedModule::~LedModule() { }
[ "aligator@suncraft-server.de" ]
aligator@suncraft-server.de
0c9ae46218cdf49d49b7ae1dfed460b5205396c5
b18ca0fce34a5fef6ff7aedd6d3cd5d3d73acf27
/mytool.cpp
731715c9c1ac1eec729cfa819b35ea2c07d04c73
[]
no_license
yaropro14/Acronis
6595e283d771e683fe45ac4dc968a190d36ba189
1b567877318a86e4d4d45a789f392e075b113942
refs/heads/master
2020-05-19T14:33:54.682625
2019-05-05T21:36:13
2019-05-05T21:36:13
185,062,714
0
0
null
null
null
null
UTF-8
C++
false
false
1,048
cpp
#include <stdio.h> #include <string.h> #include <vector> std::vector <int> MakePref(char * arg); int main(int argc, char * argv[]) { if(argc <= 1) { printf("ERROR: there is no string for replacing\n"); return 0; } std::vector <int> pf = MakePref(argv[1]); int c = getchar(); int i = 0; while(c != EOF) { putchar(c); while ((i > 0) && (argv[1][i] != c)) i = pf[i - 1]; if (argv[1][i] == c) i ++; if (i == strlen(argv[1])) { putchar('*'); i = 0; } c = getchar(); } return 0; } std::vector <int> MakePref(char * arg) { std::vector <int> pf (strlen(arg)); pf[0] = 0; for (int j = 0, i = 1; i < strlen(arg); ++ i) { while ((j > 0) && (arg[i] != arg[j])) j = pf[j - 1]; if (arg[i] == arg[j]) j ++; pf[i] = j; } return pf; }
[ "yaropro14@gmail.com" ]
yaropro14@gmail.com
2d4dcd52a33efbb49937de3077361eb47d872a20
8f0b030578f953f8661e4815618f8b03e768ba1d
/volumecontrol.cpp
70920986c9b162d1b7b146d02f879a0118f7a49b
[]
no_license
shinyawhy/QooMusicPlayer
7380ff457ff600b507114a0d07d49988c4488e2e
af8654109fd2df4e1addba8576f73ce957f434d4
refs/heads/master
2023-02-20T16:09:48.132170
2021-01-18T03:21:49
2021-01-18T03:21:49
315,882,470
10
3
null
null
null
null
UTF-8
C++
false
false
1,870
cpp
#include "volumecontrol.h" #include "ui_volumecontrol.h" volumecontrol::volumecontrol(QMediaPlayer *player, QSettings &settings, QWidget *parent) : QDialog(parent), ui(new Ui::volumecontrol), settings(settings), player(player) { ui->setupUi(this); setWindowFlags(Qt::Popup | Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint); int width = this->geometry().width(); int height = this->geometry().height(); this->setFixedSize(width, height); int volume = settings.value("music/volume", 50).toInt(); bool mute = settings.value("music/mute", false).toBool(); if (mute) { volume = 0; ui->volume_Button->setIcon(QIcon(":/icon/mute")); ui->volume_Slider->setSliderPosition(volume); } ui->volume_Slider->setSliderPosition(volume); player->setVolume(volume); } volumecontrol::~volumecontrol() { delete ui; } void volumecontrol::mousePressEvent(QMouseEvent *event) { setAttribute(Qt::WA_NoMouseReplay); QDialog::mousePressEvent(event); } void volumecontrol::on_volume_Button_clicked() { int volume = ui->volume_Slider->sliderPosition(); if (volume == 0) { volume = settings.value("music/volume", 50).toInt(); if(volume == 0) volume = 50; ui->volume_Button->setIcon(QIcon(":/icon/sound")); ui->volume_Slider->setSliderPosition(volume); settings.setValue("music/mute", false); settings.setValue("music/volume", volume); } else { volume = 0; ui->volume_Button->setIcon(QIcon(":/icon/mute")); ui->volume_Slider->setSliderPosition(0); settings.setValue("music/mute", true); } player->setVolume(volume); } void volumecontrol::on_volume_Slider_sliderMoved(int position) { player->setVolume(position); settings.setValue("music/volume", position); }
[ "46371594+shinyawhy@users.noreply.github.com" ]
46371594+shinyawhy@users.noreply.github.com
715d067888797c8479298ae18e85d5a10e406c83
3a4824694c944e97b44790bcdf2589e110e762f9
/HelloWorldWriter/main.cpp
9f442ff05e529cd56214b1cf4c8f54962406f14e
[]
no_license
juanmcloaiza/SmallCMakeProjectWithTests
60b9cdf4c2f50fab9a6cbf92a1fe7d849470ebfd
57e5f35d966ff8f8093a8a9e7f14df129e2e772a
refs/heads/master
2023-05-02T00:52:07.591802
2023-04-17T13:49:58
2023-04-17T13:49:58
131,190,189
0
0
null
null
null
null
UTF-8
C++
false
false
701
cpp
#include <iostream> #include <chrono> #include <thread> #include "HelloWorldWriter.h" using namespace std; int main() { HelloWorldWriter p; int x = 4; this_thread::sleep_for(std::chrono::seconds(1)); cout << "Hello World" << endl; this_thread::sleep_for(std::chrono::seconds(1)); cout << " x = " << x << endl; this_thread::sleep_for(std::chrono::seconds(2)); setToZero(x); cout << " x = " << x << endl; this_thread::sleep_for(std::chrono::seconds(2)); p.setToOne(x); cout << " x = " << x << endl; this_thread::sleep_for(std::chrono::seconds(2)); p.setToTwo(x); cout << " x = " << x << endl; this_thread::sleep_for(std::chrono::seconds(2)); cout << "Good Bye World" << endl; }
[ "j.carmona.loaiza@fz-juelich.de" ]
j.carmona.loaiza@fz-juelich.de
93e73e45a923ecdea8ced9400c88b64c38938616
e0c552a5429bc5549683efd6d9871cf2bac84b0b
/solution1-50/combinationSum2.cpp
bd142d27c9b2b8b7faf9c6998f88dd26bb424258
[]
no_license
Vious/leetCodeRepo
4e1569d510670cc7d69e2fa6401af1a44bdbb0bf
4596b8d2cea08f75dcacad7a5d6ee927f4db5bed
refs/heads/master
2020-03-23T14:17:55.011380
2019-01-05T02:07:03
2019-01-05T02:07:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,717
cpp
#include <iostream> #include <algorithm> #include <vector> #include <string> #include <bitset> #include <array> #include <assert.h> using namespace std; /* static int fast = []() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); return 0; }(); */ class Solution { public: void dfsCombSum(vector<int> &candidates, int target, int cumulate, vector<int> aSolu, vector <vector <int>> &results) { if (target == 0) { results.push_back(aSolu); return; } else { for (int i = cumulate; i < candidates.size(); ) { int value = candidates[i]; if (value <= target) { aSolu.push_back(value); dfsCombSum(candidates, target - value, i + 1, aSolu, results); i++; while ( i >= 1 && candidates[i] == candidates[i - 1]) i++; aSolu.pop_back(); } else { aSolu.pop_back(); break; } } } } vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { sort(candidates.begin(), candidates.end()); vector <vector <int>> results; vector<int> aSolu; dfsCombSum(candidates, target, 0, aSolu, results); return results; } }; int main() { Solution sl; vector <int> candidates; int target; int numOfCanndidates; cout << "Input target: "; cin >> target; cout << "Input numOf Candidates: "; cin >> numOfCanndidates; cout << "Input candidates: "; int tmp; for (int i = 0; i < numOfCanndidates; i++) { cin >> tmp; candidates.push_back(tmp); } /* for (auto a : candidates) cout << a << " "; cout << '\n'; */ vector<vector <int>> results = sl.combinationSum2(candidates, target); for (auto &res : results) { for (int &v : res) { cout << v << " "; } cout << '\n'; } return 0; }
[ "viousxie@outlook.com" ]
viousxie@outlook.com
3fd36425af7ee6dbc465e30461fc11a2adbd8847
71b6f2ae57ccca18a53d2e75cc543cdf44e3a02f
/剑指offer/21.cpp
48f92b2da85b00ec54c45f1fbd5156146368bcf6
[]
no_license
tangjiahua/all-my-code
bbaf00cd2f9341e75cba7c32e02be39f1251779c
62b8606372aeeae456087418a3213e7516ffa4c9
refs/heads/master
2023-06-01T14:52:02.333317
2021-06-14T19:01:17
2021-06-14T19:01:17
353,415,805
0
0
null
null
null
null
UTF-8
C++
false
false
469
cpp
class Solution { public: vector<int> exchange(vector<int>& nums) { int i = 0; int j = nums.size() - 1; while(i < j){ while(nums[i] % 2 == 1 && i < j){ i++; } while(nums[j] % 2 == 0 && i < j){ j--; } if(i >= j) break; int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; }; return nums; } };
[ "tangjiahuabit@qq.com" ]
tangjiahuabit@qq.com
f911e27576d2d34fbcc5a7ed36c0e5e7ac47452d
e33b790ec7b22a4c2cfc470d46794e954a2e4a7d
/lib/WaveformTracer.h
92dc9593df59d23a9d59927d0432bf7693fb5d7a
[ "LicenseRef-scancode-other-permissive" ]
permissive
caizikun/tool_axe
0ae4abf3e7d5feb6280f37bbafe0f5b4bf1d8d9a
c1d7c0ad8095abc6733eb8df3bc0f4f72b3852d6
refs/heads/master
2020-03-20T10:40:53.686373
2018-05-30T13:46:20
2018-05-30T13:46:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,034
h
// Copyright (c) 2011, Richard Osborne, All rights reserved // This software is freely distributable under a derivative of the // University of Illinois/NCSA Open Source License posted in // LICENSE.txt and at <http://github.xcore.com/> #ifndef _WaveformTracer_h_ #define _WaveformTracer_h_ #include <vector> #include <map> #include <fstream> #include <string> #include <queue> #include "PortInterface.h" #include "Signal.h" namespace axe { class Port; class WaveformTracer; class WaveformTracerPort : public PortInterface { WaveformTracer *parent; Port *port; std::string identifier; Signal prev; ticks_t time; public: WaveformTracerPort(WaveformTracer *w, Port *p, const std::string id) : parent(w), port(p), identifier(id), prev(0), time(0) {} void update(ticks_t time); void seePinsChange(const Signal &value, ticks_t time) override; Port *getPort() { return port; } const std::string &getIdentifier() const { return identifier; } }; class WaveformTracer { struct Event { WaveformTracerPort *port; ticks_t time; Event(WaveformTracerPort *p, ticks_t t) : port(p), time(t) {} bool operator<(const Event &other) const { return time > other.time; } }; std::priority_queue<Event> queue; std::fstream out; std::vector<WaveformTracerPort> ports; typedef std::map<std::string, std::vector<unsigned>> ModuleMap; ModuleMap modules; bool portsFinalized; uint32_t currentTime; std::string makeIdentifier(unsigned index); void emitDate(); void emitDeclarations(); void dumpPortValue(const std::string &identifer, Port *port, uint32_t value); void dumpInitialValues(); public: WaveformTracer(const std::string &name); void schedule(WaveformTracerPort *port, ticks_t time); void runUntil(ticks_t time); void add(const std::string &module, Port *port); void finalizePorts(); void seePinsChange(WaveformTracerPort *port, uint32_t newValue, ticks_t time); }; } // End axe namespace #endif // _WaveformTracer_h_
[ "richard@xmos.com" ]
richard@xmos.com
f536483f319e1b1d17ee111ea76a651ce999545b
21ede326b6cfcf5347ca6772d392d3acca80cfa0
/chrome/browser/page_load_metrics/page_load_tracker.h
da20db944c8b2ec37ff6018119d724b8453f0355
[ "BSD-3-Clause" ]
permissive
csagan5/kiwi
6eaab0ab4db60468358291956506ad6f889401f8
eb2015c28925be91b4a3130b3c2bee2f5edc91de
refs/heads/master
2020-04-04T17:06:54.003121
2018-10-24T08:20:01
2018-10-24T08:20:01
156,107,399
2
0
null
null
null
null
UTF-8
C++
false
false
16,559
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. #ifndef CHROME_BROWSER_PAGE_LOAD_METRICS_PAGE_LOAD_TRACKER_H_ #define CHROME_BROWSER_PAGE_LOAD_METRICS_PAGE_LOAD_TRACKER_H_ #include <memory> #include <vector> #include "base/macros.h" #include "base/optional.h" #include "base/time/time.h" #include "chrome/browser/page_load_metrics/page_load_metrics_observer.h" #include "chrome/browser/page_load_metrics/page_load_metrics_update_dispatcher.h" #include "chrome/browser/page_load_metrics/user_input_tracker.h" #include "chrome/common/page_load_metrics/page_load_timing.h" #include "components/ukm/ukm_source.h" #include "content/public/browser/global_request_id.h" #include "content/public/browser/web_contents_observer.h" #include "ui/base/page_transition_types.h" class GURL; namespace blink { class WebInputEvent; } // namespace blink namespace content { class NavigationHandle; } // namespace content namespace page_load_metrics { class PageLoadMetricsEmbedderInterface; namespace internal { extern const char kErrorEvents[]; extern const char kAbortChainSizeReload[]; extern const char kAbortChainSizeForwardBack[]; extern const char kAbortChainSizeNewNavigation[]; extern const char kAbortChainSizeNoCommit[]; extern const char kAbortChainSizeSameURL[]; extern const char kPageLoadCompletedAfterAppBackground[]; extern const char kPageLoadStartedInForeground[]; } // namespace internal // These errors are internal to the page_load_metrics subsystem and do not // reflect actual errors that occur during a page load. // // If you add elements to this enum, make sure you update the enum // value in histograms.xml. Only add elements to the end to prevent // inconsistencies between versions. enum InternalErrorLoadEvent { // A timing IPC was sent from the renderer that did not line up with previous // data we've received (i.e. navigation start is different or the timing // struct is somehow invalid). This error can only occur once the IPC is // vetted in other ways (see other errors). This error is deprecated as it has // been replaced by the more detailed ERR_BAD_TIMING_IPC_* error codes. DEPRECATED_ERR_BAD_TIMING_IPC, // The following IPCs are not mutually exclusive. // // We received an IPC when we weren't tracking a committed load. This will // often happen if we get an IPC from a bad URL scheme (that is, the renderer // sent us an IPC from a navigation we don't care about). ERR_IPC_WITH_NO_RELEVANT_LOAD, // Received a notification from a frame that has been navigated away from. ERR_IPC_FROM_WRONG_FRAME, // We received an IPC even through the last committed url from the browser // was not http/s. This can happen with the renderer sending IPCs for the // new tab page. This will often come paired with // ERR_IPC_WITH_NO_RELEVANT_LOAD. ERR_IPC_FROM_BAD_URL_SCHEME, // If we track a navigation, but the renderer sends us no IPCs. This could // occur if the browser filters loads less aggressively than the renderer. ERR_NO_IPCS_RECEIVED, // Tracks frequency with which we record an end time that occurred before // navigation start. This is expected to happen in some cases (see comments in // cc file for details). We use this error counter to understand how often it // happens. ERR_END_BEFORE_NAVIGATION_START, // A new navigation triggers abort updates in multiple trackers in // |aborted_provisional_loads_|, when usually there should only be one (the // navigation that just aborted because of this one). If this happens, the // latest aborted load is used to track the chain size. ERR_NAVIGATION_SIGNALS_MULIPLE_ABORTED_LOADS, // Received user input without a relevant load. This error type is deprecated, // as it is valid to receive user input without a relevant load. We leave the // enum value here since it's also used in histogram recording, so it's // important that we not re-use this enum entry for a different value. DEPRECATED_ERR_USER_INPUT_WITH_NO_RELEVANT_LOAD, // A TimeTicks value in the browser process has value less than // navigation_start_. This could happen if navigation_start_ was computed in // renderer process and the system clock has inter process time tick skew. ERR_INTER_PROCESS_TIME_TICK_SKEW, // At the time a PageLoadTracker was destroyed, we had received neither a // commit nor a failed provisional load. ERR_NO_COMMIT_OR_FAILED_PROVISIONAL_LOAD, // No page load end time was recorded for this page load. ERR_NO_PAGE_LOAD_END_TIME, // Received a timing update from a subframe (deprecated). DEPRECATED_ERR_TIMING_IPC_FROM_SUBFRAME, // A timing IPC was sent from the renderer that contained timing data which // was inconsistent with our timing data for the currently committed load. ERR_BAD_TIMING_IPC_INVALID_TIMING_DESCENDENT, // A timing IPC was sent from the renderer that contained loading behavior // data which was inconsistent with our loading behavior data for the // currently committed load. ERR_BAD_TIMING_IPC_INVALID_BEHAVIOR_DESCENDENT, // A timing IPC was sent from the renderer that contained invalid timing data // (e.g. out of order timings, or other issues). ERR_BAD_TIMING_IPC_INVALID_TIMING, // We received a navigation start for a child frame that is before the // navigation start of the main frame. ERR_SUBFRAME_NAVIGATION_START_BEFORE_MAIN_FRAME, // We received an IPC from a subframe when we weren't tracking a committed // load. We expect this error to happen, and track it so we can understand how // frequently this case is encountered. ERR_SUBFRAME_IPC_WITH_NO_RELEVANT_LOAD, // We received browser-process reported metrics when we weren't tracking a // committed load. We expect this error to happen, and track it so we can // understand how frequently this case is encountered. ERR_BROWSER_USAGE_WITH_NO_RELEVANT_LOAD, // Add values before this final count. ERR_LAST_ENTRY, }; // NOTE: these functions are shared by page_load_tracker.cc and // metrics_web_contents_observer.cc. They are declared here to allow both files // to access them. void RecordInternalError(InternalErrorLoadEvent event); PageEndReason EndReasonForPageTransition(ui::PageTransition transition); void LogAbortChainSameURLHistogram(int aborted_chain_size_same_url); bool IsNavigationUserInitiated(content::NavigationHandle* handle); // This class tracks a given page load, starting from navigation start / // provisional load, until a new navigation commits or the navigation fails. // MetricsWebContentsObserver manages a set of provisional PageLoadTrackers, as // well as a committed PageLoadTracker. class PageLoadTracker : public PageLoadMetricsUpdateDispatcher::Client { public: // Caller must guarantee that the embedder_interface pointer outlives this // class. The PageLoadTracker must not hold on to // currently_committed_load_or_null or navigation_handle beyond the scope of // the constructor. PageLoadTracker(bool in_foreground, PageLoadMetricsEmbedderInterface* embedder_interface, const GURL& currently_committed_url, content::NavigationHandle* navigation_handle, UserInitiatedInfo user_initiated_info, int aborted_chain_size, int aborted_chain_size_same_url); ~PageLoadTracker() override; // PageLoadMetricsUpdateDispatcher::Client implementation: void OnTimingChanged() override; void OnSubFrameTimingChanged(content::RenderFrameHost* rfh, const mojom::PageLoadTiming& timing) override; void OnMainFrameMetadataChanged() override; void OnSubframeMetadataChanged() override; void UpdateFeaturesUsage( const mojom::PageLoadFeatures& new_features) override; void Redirect(content::NavigationHandle* navigation_handle); void WillProcessNavigationResponse( content::NavigationHandle* navigation_handle); void Commit(content::NavigationHandle* navigation_handle); void DidCommitSameDocumentNavigation( content::NavigationHandle* navigation_handle); void DidFinishSubFrameNavigation( content::NavigationHandle* navigation_handle); void FailedProvisionalLoad(content::NavigationHandle* navigation_handle, base::TimeTicks failed_load_time); void WebContentsHidden(); void WebContentsShown(); void OnInputEvent(const blink::WebInputEvent& event); // Flush any buffered metrics, as part of the metrics subsystem persisting // metrics as the application goes into the background. The application may be // killed at any time after this method is invoked without further // notification. void FlushMetricsOnAppEnterBackground(); void NotifyClientRedirectTo(const PageLoadTracker& destination); void OnLoadedResource( const ExtraRequestCompleteInfo& extra_request_complete_info); // Signals that we should stop tracking metrics for the associated page load. // We may stop tracking a page load if it doesn't meet the criteria for // tracking metrics in DidFinishNavigation. void StopTracking(); int aborted_chain_size() const { return aborted_chain_size_; } int aborted_chain_size_same_url() const { return aborted_chain_size_same_url_; } PageEndReason page_end_reason() const { return page_end_reason_; } base::TimeTicks page_end_time() const { return page_end_time_; } void AddObserver(std::unique_ptr<PageLoadMetricsObserver> observer); // If the user performs some abort-like action while we are tracking this page // load, notify the tracker. Note that we may not classify this as an abort if // we've already performed a first paint. // is_certainly_browser_timestamp signifies if the timestamp passed is taken // in the // browser process or not. We need this to possibly clamp browser timestamp on // a machine with inter process time tick skew. void NotifyPageEnd(PageEndReason page_end_reason, UserInitiatedInfo user_initiated_info, base::TimeTicks timestamp, bool is_certainly_browser_timestamp); void UpdatePageEnd(PageEndReason page_end_reason, UserInitiatedInfo user_initiated_info, base::TimeTicks timestamp, bool is_certainly_browser_timestamp); // This method returns true if this page load has been aborted with type of // END_OTHER, and the |abort_cause_time| is within a sufficiently close // delta to when it was aborted. Note that only provisional loads can be // aborted with END_OTHER. While this heuristic is coarse, it works better // and is simpler than other feasible methods. See https://goo.gl/WKRG98. bool IsLikelyProvisionalAbort(base::TimeTicks abort_cause_time) const; bool MatchesOriginalNavigation(content::NavigationHandle* navigation_handle); bool did_commit() const { return did_commit_; } const GURL& url() const { return url_; } base::TimeTicks navigation_start() const { return navigation_start_; } PageLoadExtraInfo ComputePageLoadExtraInfo() const; ui::PageTransition page_transition() const { return page_transition_; } UserInitiatedInfo user_initiated_info() const { return user_initiated_info_; } UserInputTracker* input_tracker() { return &input_tracker_; } PageLoadMetricsUpdateDispatcher* metrics_update_dispatcher() { return &metrics_update_dispatcher_; } // Whether this PageLoadTracker has a navigation GlobalRequestID that matches // the given request_id. This method will return false before // WillProcessNavigationResponse has been invoked, as PageLoadTracker doesn't // know its GlobalRequestID until WillProcessNavigationResponse has been // invoked. bool HasMatchingNavigationRequestID( const content::GlobalRequestID& request_id) const; // Invoked when a media element starts playing. void MediaStartedPlaying( const content::WebContentsObserver::MediaPlayerInfo& video_type, bool is_in_main_frame); // Informs the observers that the event corresponding to |event_key| has // occurred. void BroadcastEventToObservers(const void* const event_key); private: // This function converts a TimeTicks value taken in the browser process // to navigation_start_ if: // - base::TimeTicks is not comparable across processes because the clock // is not system wide monotonic. // - *event_time < navigation_start_ void ClampBrowserTimestampIfInterProcessTimeTickSkew( base::TimeTicks* event_time); void UpdatePageEndInternal(PageEndReason page_end_reason, UserInitiatedInfo user_initiated_info, base::TimeTicks timestamp, bool is_certainly_browser_timestamp); // If |final_navigation| is null, then this is an "unparented" abort chain, // and represents a sequence of provisional aborts that never ends with a // committed load. void LogAbortChainHistograms(content::NavigationHandle* final_navigation); UserInputTracker input_tracker_; // Whether we stopped tracking this navigation after it was initiated. We may // stop tracking a navigation if it doesn't meet the criteria for tracking // metrics in DidFinishNavigation. bool did_stop_tracking_; // Whether the application went into the background when this PageLoadTracker // was active. This is a temporary boolean for UMA tracking. bool app_entered_background_; // The navigation start in TimeTicks, not the wall time reported by Blink. const base::TimeTicks navigation_start_; // The most recent URL of this page load. Updated at navigation start, upon // redirection, and at commit time. GURL url_; // The start URL for this page load (before redirects). GURL start_url_; // Whether this page load committed. bool did_commit_; std::unique_ptr<FailedProvisionalLoadInfo> failed_provisional_load_info_; // Will be END_NONE if we have not ended this load yet. Otherwise will // be the first page end reason encountered. PageEndReason page_end_reason_; // Whether the page end cause for this page load was user initiated. For // example, if this page load was ended by a new navigation, this field tracks // whether that new navigation was user-initiated. This field is only useful // if this page load's end reason is a value other than END_NONE. Note that // this value is currently experimental, and is subject to change. In // particular, this field is never set to true for some page end reasons, such // as stop and close, since we don't yet have sufficient instrumentation to // know if a stop or close was caused by a user action. UserInitiatedInfo page_end_user_initiated_info_; base::TimeTicks page_end_time_; // We record separate metrics for events that occur after a background, // because metrics like layout/paint are delayed artificially // when they occur in the background. base::TimeTicks background_time_; base::TimeTicks foreground_time_; bool started_in_foreground_; mojom::PageLoadTimingPtr last_dispatched_merged_page_timing_; ui::PageTransition page_transition_; base::Optional<content::GlobalRequestID> navigation_request_id_; // Whether this page load was user initiated. UserInitiatedInfo user_initiated_info_; // This is a subtle member. If a provisional load A gets aborted by // provisional load B, which gets aborted by C that eventually commits, then // there exists an abort chain of length 2, starting at A's navigation_start. // This is useful because it allows histograming abort chain lengths based on // what the last load's transition type is. i.e. holding down F-5 to spam // reload will produce a long chain with the RELOAD transition. const int aborted_chain_size_; // This member counts consecutive provisional aborts that share a url. It will // always be less than or equal to |aborted_chain_size_|. const int aborted_chain_size_same_url_; // Interface to chrome features. Must outlive the class. PageLoadMetricsEmbedderInterface* const embedder_interface_; std::vector<std::unique_ptr<PageLoadMetricsObserver>> observers_; PageLoadMetricsUpdateDispatcher metrics_update_dispatcher_; const ukm::SourceId source_id_; DISALLOW_COPY_AND_ASSIGN(PageLoadTracker); }; } // namespace page_load_metrics #endif // CHROME_BROWSER_PAGE_LOAD_METRICS_PAGE_LOAD_TRACKER_H_
[ "team@geometry.ee" ]
team@geometry.ee
7526c5be10da73571a71cc2422aecca5d498ebcb
54440e4a806367e5d16c9b1fabd91ab97e5a9156
/matrix4x4.cpp
83c6cdeccad9909e225f9bc486e8775f593c60bb
[]
no_license
Strauts/3D-programmering
85110067b203bc2e21dbbecd9ceeebac48cd61b0
f17fe027f967730a1b3e2f1822880064536348af
refs/heads/master
2022-07-25T16:02:47.723945
2020-05-20T09:00:46
2020-05-20T09:00:46
265,508,201
0
0
null
null
null
null
UTF-8
C++
false
false
9,060
cpp
#include "matrix4x4.h" #include <cmath> #include <utility> #include <cassert> #ifndef M_PI #define M_PI 3.14159265358979323846 //Visual Studio did not find it... #endif Matrix4x4::Matrix4x4(bool isIdentity) { if(isIdentity) { identity(); } else { for(int i = 0; i < 4; i++) for(int j = 0; j < 4; j++) matrix[i][j] = 0.f; } } Matrix4x4::Matrix4x4(std::initializer_list<std::initializer_list<float>> values) { // initialiser matrisen klassen på samme måte som en 2d-array int i = 0, j = 0; for(auto secondlevel : values) { for(auto thirdLevel : secondlevel) { matrix[i][j++] = thirdLevel; } i++; j = 0; } } Matrix4x4 Matrix4x4::identity() { int c = 0; for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { if(j == c) matrix[i][j] = 1.f; else matrix[i][j] = 0.f; } c++; } return *this; } void Matrix4x4::translateX(GLfloat x) { translate(x, 0.f, 0.f); } void Matrix4x4::translateY(GLfloat y) { translate(0.f, y, 0.f); } void Matrix4x4::translateZ(GLfloat z) { translate(0.f, 0.f, z); } void Matrix4x4::rotateX(GLfloat degrees) { GLfloat rad = (degrees * M_PI)/180; Matrix4x4 temp = { {1.f, 0.f, 0.f, 0.f}, {0.f, std::cos(rad), std::sin(rad), 0.f}, {0.f, -std::sin(rad), std::cos(rad), 0.f}, {0.f, 0.f, 0.f, 1.f} }; temp = (*this)*temp; memcpy(matrix, temp.matrix, 16*sizeof(GLfloat)); } void Matrix4x4::rotateY(GLfloat degrees) { GLfloat rad = (degrees * M_PI)/180; Matrix4x4 temp = { {std::cos(rad), 0.f, -std::sin(rad), 0.f}, { 0.f, 1.f, 0.f, 0.f}, {std::sin(rad), 0.f, std::cos(rad), 0.f}, { 0.f, 0.f, 0.f, 1.f} }; temp = (*this)*temp; memcpy(matrix, temp.matrix, 16*sizeof(GLfloat)); } void Matrix4x4::rotateZ(GLfloat degrees) { GLfloat rad = (degrees * M_PI)/180; Matrix4x4 temp = { {std::cos(rad), std::sin(rad), 0.f, 0.f}, {-std::sin(rad), std::cos(rad), 0.f, 0.f}, { 0.f, 0.f, 1.f, 0.f}, { 0.f, 0.f, 0.f, 1.f} }; temp = (*this)*temp; memcpy(matrix, temp.matrix, 16*sizeof(GLfloat)); } void Matrix4x4::scale(GLfloat uniformScale) { scale(uniformScale, uniformScale, uniformScale); } void Matrix4x4::scale(GLfloat scaleX, GLfloat scaleY, GLfloat scaleZ) { Matrix4x4 temp = { {scaleX, 0.f, 0.f, 0.f}, {0.f, scaleY, 0.f, 0.f}, {0.f, 0.f, scaleZ, 0.f}, {0.f, 0.f, 0.f, 1.f} }; temp = (*this)*temp; memcpy(matrix, temp.matrix, 16*sizeof(GLfloat)); } GLfloat *Matrix4x4::constData() { return &matrix[0][0]; } void Matrix4x4::transpose() { std::swap(matrix[0][1], matrix[1][0]); std::swap(matrix[0][2], matrix[2][0]); std::swap(matrix[0][3], matrix[3][0]); std::swap(matrix[1][2], matrix[2][1]); std::swap(matrix[1][3], matrix[3][1]); std::swap(matrix[2][3], matrix[3][2]); } void Matrix4x4::ortho(GLfloat l, GLfloat r, GLfloat b, GLfloat t, GLfloat nearPlane, GLfloat farPlane) { *this = { {2/(r-l), 0.f, 0.f, 0.f}, {0.f, 2/(t-b), 0.f, 0.f}, {0.f, 0.f, -2/(farPlane-nearPlane), 0.f}, {-(r+l)/(r-l), -(t+b)/(t-b), -(farPlane+nearPlane)/(farPlane-nearPlane), 1.f} }; } //https://stackoverflow.com/questions/18404890/how-to-build-perspective-projection-matrix-no-api void Matrix4x4::perspective(GLfloat verticalAngle, GLfloat aspectRatio, GLfloat nearPlane, GLfloat farPlane) { //checking numbers for no division on zero: if (verticalAngle <= 0.f) verticalAngle = 30.f; if (aspectRatio <= 0.f) aspectRatio = 1.3f; if (farPlane == nearPlane) { nearPlane = 1.f; farPlane = 100.f; } // finn right, og utled resten fra dette float scale = tan(verticalAngle * M_PI / 360) * nearPlane; float r = aspectRatio * scale; float t = scale; // Lag perspektiv-frustrum Matrix4x4 temp = { {nearPlane/r, 0.f, 0.f, 0.f}, {0.f, nearPlane/t, 0.f, 0.f}, {0.f, 0.f, -(farPlane+nearPlane)/(farPlane-nearPlane), -2*farPlane*nearPlane/(farPlane-nearPlane)}, {0.f, 0.f, -1.f, 0.f} }; memcpy(matrix, temp.matrix, 16*sizeof(GLfloat)); } void Matrix4x4::lookAt(const Vec3 &eye, const Vec3 &center, const Vec3 &up_axis) { Vec3 f = center-eye; f.normalize(); Vec3 s = f^up_axis; // kryssprodukt s.normalize(); Vec3 u = s^f; Matrix4x4 v = { { s.getX(), s.getY(), s.getZ(), -(s*eye)}, { u.getX(), u.getY(), u.getZ(), -(u*eye)}, {-f.getX(), -f.getY(), -f.getZ(), f*eye}, {0.f, 0.f, 0.f, 1.f} }; memcpy(matrix, v.matrix, 16*sizeof(GLfloat)); } void Matrix4x4::translate(GLfloat x, GLfloat y, GLfloat z) { Matrix4x4 temp = { {1.f, 0.f, 0.f, x}, {0.f, 1.f, 0.f, y}, {0.f, 0.f, 1.f, z}, {0.f, 0.f, 0.f, 1.f} }; temp = (*this)*temp; memcpy(matrix, temp.matrix, 16*sizeof(GLfloat)); } bool Matrix4x4::invertMatrix() { GLfloat m[16]; memcpy(m, matrix, 16*sizeof(GLfloat)); GLfloat inv[16], det; GLfloat invOut[16]; int i; inv[0] = m[5] * m[10] * m[15] - m[5] * m[11] * m[14] - m[9] * m[6] * m[15] + m[9] * m[7] * m[14] + m[13] * m[6] * m[11] - m[13] * m[7] * m[10]; inv[4] = -m[4] * m[10] * m[15] + m[4] * m[11] * m[14] + m[8] * m[6] * m[15] - m[8] * m[7] * m[14] - m[12] * m[6] * m[11] + m[12] * m[7] * m[10]; inv[8] = m[4] * m[9] * m[15] - m[4] * m[11] * m[13] - m[8] * m[5] * m[15] + m[8] * m[7] * m[13] + m[12] * m[5] * m[11] - m[12] * m[7] * m[9]; inv[12] = -m[4] * m[9] * m[14] + m[4] * m[10] * m[13] + m[8] * m[5] * m[14] - m[8] * m[6] * m[13] - m[12] * m[5] * m[10] + m[12] * m[6] * m[9]; inv[1] = -m[1] * m[10] * m[15] + m[1] * m[11] * m[14] + m[9] * m[2] * m[15] - m[9] * m[3] * m[14] - m[13] * m[2] * m[11] + m[13] * m[3] * m[10]; inv[5] = m[0] * m[10] * m[15] - m[0] * m[11] * m[14] - m[8] * m[2] * m[15] + m[8] * m[3] * m[14] + m[12] * m[2] * m[11] - m[12] * m[3] * m[10]; inv[9] = -m[0] * m[9] * m[15] + m[0] * m[11] * m[13] + m[8] * m[1] * m[15] - m[8] * m[3] * m[13] - m[12] * m[1] * m[11] + m[12] * m[3] * m[9]; inv[13] = m[0] * m[9] * m[14] - m[0] * m[10] * m[13] - m[8] * m[1] * m[14] + m[8] * m[2] * m[13] + m[12] * m[1] * m[10] - m[12] * m[2] * m[9]; inv[2] = m[1] * m[6] * m[15] - m[1] * m[7] * m[14] - m[5] * m[2] * m[15] + m[5] * m[3] * m[14] + m[13] * m[2] * m[7] - m[13] * m[3] * m[6]; inv[6] = -m[0] * m[6] * m[15] + m[0] * m[7] * m[14] + m[4] * m[2] * m[15] - m[4] * m[3] * m[14] - m[12] * m[2] * m[7] + m[12] * m[3] * m[6]; inv[10] = m[0] * m[5] * m[15] - m[0] * m[7] * m[13] - m[4] * m[1] * m[15] + m[4] * m[3] * m[13] + m[12] * m[1] * m[7] - m[12] * m[3] * m[5]; inv[14] = -m[0] * m[5] * m[14] + m[0] * m[6] * m[13] + m[4] * m[1] * m[14] - m[4] * m[2] * m[13] - m[12] * m[1] * m[6] + m[12] * m[2] * m[5]; inv[3] = -m[1] * m[6] * m[11] + m[1] * m[7] * m[10] + m[5] * m[2] * m[11] - m[5] * m[3] * m[10] - m[9] * m[2] * m[7] + m[9] * m[3] * m[6]; inv[7] = m[0] * m[6] * m[11] - m[0] * m[7] * m[10] - m[4] * m[2] * m[11] + m[4] * m[3] * m[10] + m[8] * m[2] * m[7] - m[8] * m[3] * m[6]; inv[11] = -m[0] * m[5] * m[11] + m[0] * m[7] * m[9] + m[4] * m[1] * m[11] - m[4] * m[3] * m[9] - m[8] * m[1] * m[7] + m[8] * m[3] * m[5]; inv[15] = m[0] * m[5] * m[10] - m[0] * m[6] * m[9] - m[4] * m[1] * m[10] + m[4] * m[2] * m[9] + m[8] * m[1] * m[6] - m[8] * m[2] * m[5]; det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12]; if (det == 0) return false; det = 1.0 / det; for (i = 0; i < 16; i++) invOut[i] = inv[i] * det; memcpy(matrix, invOut, 16*sizeof(GLfloat)); return true; }
[ "perkaasa92@gmail.com" ]
perkaasa92@gmail.com
68ffb0cd22ea49156ef551c394ac98a5d2964d02
8526ec13c88491690d60ef9abbc5e8d1817b8c22
/TextFileOOP/TextFile.cpp
ca2dbf5680f922e0b0fcc4771c6513870415ee2f
[]
no_license
petrshirin/TextFile
776ef3db7d4bdc8970fe648f032037aee823b992
be6050a38270d4fe5323053c02f0dbed59c904e8
refs/heads/master
2020-11-29T23:54:59.787723
2019-12-26T11:16:22
2019-12-26T11:16:22
230,244,915
0
0
null
null
null
null
UTF-8
C++
false
false
4,523
cpp
#include "pch.h" #include "TextFile.h" #include <string> TextFile::TextFile() { } bool compare_arrs(int* arr1, int* arr2, int len1, int len2) { int len; if (len1 < len2) len = len1; else len = len2; for (int i = 0; i < len; i++) { if (arr1[i] != arr2[i]) return false; } return true; } TextFile::TextFile(std::string path, int _type) { file_indent = path; type = _type; if (type == 0) { in.open(path); calculate_field(); } else out.open(path); } TextFile::TextFile(char* path, int _type) { file_indent = path; type = _type; if (type == 1) { in.open(path); calculate_field(); } else out.open(path); } void TextFile::calculate_field() { std::string row; std::getline(in, row, '\n'); int count = 1; for (int i = 0; i < row.length(); i++) { if ((row[i] == ' ') || (row[i] == '\t')) count += 1; } count_fields = count; in.seekg(0, std::ios::beg); } void TextFile::get_data() { int* row; while (true) { row = new int[count_fields]; for (int i = 0; i < count_fields; i++) in >> row[i]; if (!in.eof()) data_arr.push_back(row); else return; } } void TextFile::sort(int field_to_sort, bool reverse) { std::vector <int*> *data_ptr = new std::vector <int*>(data_arr.size()); if (!reverse) quicksort(data_arr, 0, data_arr.size() - 1, field_to_sort); else quicksort(data_arr, data_arr.size() - 1, 0, field_to_sort); } std::vector <int*> TextFile::quicksort(std::vector <int*> mas, int first, int last, int field_to_sort) { int mid; std::vector <int*> count; if (data_arr.size() == 0) return mas; count.push_back(data_arr[0]); count[0] = new int[count_fields]; int f = first, l = last; mid = mas[(f + l) / 2][field_to_sort]; do { while (mas[f][field_to_sort] < mid) f++; while (mas[l][field_to_sort] > mid) l--; if (f <= l) { count[0] = mas[f]; mas[f] = mas[l]; mas[l] = count[0]; f++; l--; } } while (f < l); if (first < l) mas = quicksort(mas, first, l, field_to_sort); if (f < last) mas = quicksort(mas, f, last, field_to_sort); data_arr = mas; return mas; } void TextFile::show_data() { for (int i = 0; i < data_arr.size(); i++) { for (int j = 0; j < count_fields; j++) { std::cout << data_arr[i][j] << " "; } std::cout << std::endl; } } void TextFile::write_file() { if (type == 0) throw "Error file open on read"; for (int i = 0; i < data_arr.size(); i++) { for (int j = 0; j < count_fields; j++) { out << data_arr[i][j] << "\t"; } out << "\n"; } } TextFile& TextFile::operator=(const TextFile& right) { data_arr = right.data_arr; count_fields = right.count_fields; return *this; } std::vector <int> TextFile::conside_cols(TextFile& right, int col) { int len; std::vector <int> vect; if (right.count_fields > count_fields) len = data_arr.size(); else len = right.data_arr.size(); for (int i = 0; i < len; i++) { vect.push_back(data_arr[i][col] + right.data_arr[i][col]); } return vect; } void TextFile::make_file(std::string new_path, TextFile& other, bool unic) { TextFile new_file(new_path, 1); new_file.count_fields = count_fields; sort(0); other.sort(0); new_file.data_arr = data_arr; for (int i = 0; i < other.data_arr.size(); i++) new_file.data_arr.push_back(other.data_arr[i]); new_file.sort(0); int j = 1; int i = 0; bool is_same; while (i != new_file.data_arr.size()){ j = 1; is_same = false; if (i + j >= new_file.data_arr.size()) { if((!compare_arrs(new_file.data_arr[i], new_file.data_arr[i - 1], count_fields, count_fields)) && (!unic)) new_file.data_arr.erase(new_file.data_arr.begin() + i); break; } while (compare_arrs(new_file.data_arr[i], new_file.data_arr[i + j], count_fields, count_fields)) { j++; is_same = true; if (i + j == new_file.data_arr.size()) { j--; break; } } if ((unic) && (is_same)) { for (j; j > 0; j--) { new_file.data_arr.erase(new_file.data_arr.begin() + i); } i--; } if ((!unic) && (!is_same)) { new_file.data_arr.erase(new_file.data_arr.begin() + i); i--; } i++; } new_file.sort(0); new_file.write_file(); } void TextFile::copy_data(std::string file_path_to) { std::ofstream out_tmp(file_path_to, std::ios::app); for (int i = 0; i < data_arr.size(); i++) { for (int j = 0; j < count_fields; j++) { out_tmp << data_arr[i][j] << "\t"; } out_tmp << "\n"; } out_tmp << "\0"; out_tmp.close(); } TextFile::~TextFile() { if (type != 0) { out << "\0"; out.close(); } else in.close(); }
[ "p.e.shirin@gmail.com" ]
p.e.shirin@gmail.com
4d9325fa301d062aa28d63754cfa2ea210715058
1a9652da55e21fd177f20f165b456c8297ee4738
/C++Save/Tmp/ProjectA/Core/GData/DreamerTable.cpp
c192ef5f0248300d8873681b9186381e3f64a9f4
[]
no_license
jingsia/three1
c65e7a65f1e3b34ffd0b3922b2043c097acddf06
9d568722f90e37ca92a4c7561fe808da58ec1c1c
refs/heads/master
2020-07-23T04:32:46.423865
2016-12-22T16:10:15
2016-12-22T16:10:15
73,817,286
0
1
null
null
null
null
UTF-8
C++
false
false
377
cpp
/************************************************************************* > File Name: DreamerTable.cpp > Author: yangjx > Mail: yangjx@126.com > Created Time: Wed 20 Apr 2016 07:38:41 AM CST ************************************************************************/ #include "Config.h" #include "DreamerTable.h" namespace GData { DreamerDataTable dreamerDataTable; }
[ "839172105@qq.com" ]
839172105@qq.com