blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
a20e17fbf68ca9004a399eef2c78ccdbe1d87b64
71986699935b3a1800e9701fb9d9ae1f2f5888dd
/Assignment_6_cb/main.cpp
ef303d855eb51491fc1f47de50a80340724cbc9c
[]
no_license
kburgon/CS3100_Assignment6
dff03962943db0751f583678e008b39bddfc5891
dd3a84510704192c2a6dacfa52302b7870eed772
refs/heads/master
2021-01-22T04:54:22.928356
2015-03-22T00:24:15
2015-03-22T00:24:15
30,978,937
0
0
null
null
null
null
UTF-8
C++
false
false
152
cpp
#include <iostream> #include "task.h" int main(void) { Task testP; testP.generateTask(false); testP.testBursts(); // testP.execute(); return 0; }
[ "buburgo@gmail.com" ]
buburgo@gmail.com
910d03d0c05d0501b5011731abb129fdef22b7e7
5a5239120e4022521ac140a56e22ad6f49422977
/dmopc14c2p5.cpp
5feb46080ed83796508e2a9d183506f71771dd7f
[]
no_license
sunny-lan/cpp-contest
0b26d8b6da8c72980de1eb98c7401385f9730a41
3eea062297e9374a8829b618954e9db46bfb4466
refs/heads/master
2020-03-22T04:14:01.203252
2018-07-02T19:04:43
2018-07-02T19:04:43
139,483,196
3
1
null
null
null
null
UTF-8
C++
false
false
532
cpp
#include <iostream> #include <vector> using namespace std; #define MAXN 1000001 int degrees[MAXN]; long double dp[MAXN]; int main() { int n,m; cin >> n>>m; vector<vector<int>> adj(n); for (int x = 0; x < m; x++) { int i, j; cin >> i >> j; i--, j--; adj[i].push_back(j); degrees[i]++; } dp[0] = 1; for (int i = 0; i < n; i++) { long double prob = dp[i] / adj[i].size(); for (int neight : adj[i]) { dp[neight] += prob; } if (degrees[i] == 0) printf("%.9Lg\n", dp[i]); } //cin >> n; return 0; }
[ "sunny.lan.coder@gmail.com" ]
sunny.lan.coder@gmail.com
dceabe1e98a02275b18eda2b72149a2fe20ee809
9bb1834dc85b27a34e804f9d8733b150dda44069
/tests/core/slot.test.c++
28731bb548969693da595b90d939aed9d0bd3746
[ "MIT" ]
permissive
zengqh/skui
c727b980e5d449a44d0d7cde0ce306f519a43997
ea679624efc5aff42fe2d34889da843bf5e79447
refs/heads/master
2020-03-19T07:26:22.185064
2018-05-14T22:12:52
2018-05-15T16:28:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,403
/** * The MIT License (MIT) * * Copyright © 2017-2018 Ruben Van Boxem * * 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 "test.h++" #include "core/slot.h++" namespace { using skui::test::check; using skui::core::implementation::callable_slot; using skui::core::implementation::member_function_slot; int f_called = 0; void f() { f_called = 1; } void f_arg(int i) { f_called = i; } int l_called = 0; const auto l = []() { l_called = 1; }; const auto l_arg = [](int i) { l_called = i; }; int f_return() { return 42; } const auto l_return = []() { return 43; }; struct mock { void m() { called = 1; } void m() const { const_called = 11; } void m_arg(int i) { called = i; } void m_arg(int i) const { const_called = i; } int m_return() { return 44; } int m_return() const { return 33; } int called = 0; mutable int const_called = 0; }; void test_callable_slot() { { callable_slot<decltype(&f), void> slot(&f); slot(nullptr); check(f_called == 1, "function called through slot."); callable_slot<decltype(&f_arg), void, int> slot_arg(&f_arg); slot_arg(nullptr, 2); check(f_called == 2, "function with argument called through slot."); callable_slot<decltype(&f), void, int> slot_arg_less(&f); slot_arg_less(nullptr, 3); check(f_called == 1, "function called through slot extra arguments ignored."); } { callable_slot<decltype(l), void> slot(l); slot(nullptr); check(l_called == 1, "lambda called through slot."); callable_slot<decltype(l_arg), void, int> slot_arg(l_arg); slot_arg(nullptr, 2); check(l_called == 2, "lambda with argument called through slot."); callable_slot<decltype(l), void, int> slot_arg_less(l); slot_arg_less(nullptr, 3); check(l_called == 1, "lambda called through slot extra arguments ignored."); } { int captured = 0; const auto cl = [&captured](int i) { captured = i; }; callable_slot<decltype(cl), void, int> slot(cl); slot(nullptr, 1); check(captured == 1, "Capturing lambda slot called."); } } void test_member_slot() { { mock object; member_function_slot<mock, void(mock::*)(), void> slot(&mock::m); slot(&object); check(object.called == 1, "member function called through slot."); member_function_slot<mock, void(mock::*)(int), void, int> slot_arg(&mock::m_arg); slot_arg(&object, 2); check(object.called == 2, "member function with argument called through slot."); member_function_slot<mock, void(mock::*)(), void, int> slot_arg_less(&mock::m); slot_arg_less(&object, 3); check(object.called == 1, "member function called through slot extra arguments ignored."); } { const mock object; const member_function_slot<mock, void(mock::*)() const, void> slot(&mock::m); slot(&object); check(object.const_called == 11, "const member function called through slot."); const member_function_slot<mock, void(mock::*)(int) const, void, int> slot_arg(&mock::m_arg); slot_arg(&object, 22); check(object.const_called == 22, "const member function with argument called through slot."); const member_function_slot<mock, void(mock::*)() const, void, int> slot_arg_less(&mock::m); slot_arg_less(&object, 33); check(object.const_called == 11, "const member function called through slot extra arguments ignored."); } } void test_return_value_slot() { callable_slot<decltype(&f_return), int> function_slot(f_return); check(function_slot(nullptr) == 42, "function slot returns correct return value."); callable_slot<decltype(l_return), int> lambda_slot(l_return); check(lambda_slot(nullptr) == 43, "lambda slot returns correct return value."); mock object; member_function_slot<mock, int(mock::*)(), int> member_slot(&mock::m_return); check(member_slot(&object) == 44, "member slot returns correct return value."); member_function_slot<mock, int(mock::*)() const, int> const_member_slot(&mock::m_return); check(const_member_slot(&object) == 33, "const member slot returns correct return value."); } } int main() { test_callable_slot(); test_member_slot(); test_return_value_slot(); return skui::test::exit_code; }
[ "vanboxem.ruben@gmail.com" ]
vanboxem.ruben@gmail.com
efd76456fa67c479562eb13673a4117f8d441882
d0fb46aecc3b69983e7f6244331a81dff42d9595
/cbn/include/alibabacloud/cbn/model/ListTransitRouterCidrAllocationResult.h
b6b4f39dc42437f656c0c110b7287dc72f7f8b6f
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
1,965
h
/* * Copyright 2009-2017 Alibaba Cloud 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 ALIBABACLOUD_CBN_MODEL_LISTTRANSITROUTERCIDRALLOCATIONRESULT_H_ #define ALIBABACLOUD_CBN_MODEL_LISTTRANSITROUTERCIDRALLOCATIONRESULT_H_ #include <string> #include <vector> #include <utility> #include <alibabacloud/core/ServiceResult.h> #include <alibabacloud/cbn/CbnExport.h> namespace AlibabaCloud { namespace Cbn { namespace Model { class ALIBABACLOUD_CBN_EXPORT ListTransitRouterCidrAllocationResult : public ServiceResult { public: struct TransitRouterCidrAllocation { std::string cidr; std::string attachmentName; std::string transitRouterCidrId; std::string allocatedCidrBlock; std::string attachmentId; }; ListTransitRouterCidrAllocationResult(); explicit ListTransitRouterCidrAllocationResult(const std::string &payload); ~ListTransitRouterCidrAllocationResult(); int getTotalCount()const; std::string getNextToken()const; int getMaxResults()const; std::vector<TransitRouterCidrAllocation> getTransitRouterCidrAllocations()const; protected: void parse(const std::string &payload); private: int totalCount_; std::string nextToken_; int maxResults_; std::vector<TransitRouterCidrAllocation> transitRouterCidrAllocations_; }; } } } #endif // !ALIBABACLOUD_CBN_MODEL_LISTTRANSITROUTERCIDRALLOCATIONRESULT_H_
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
c89028d09c1186a06b7fa70360230c6a2ce2a22f
8065bb7d78214ed60a3a7a0465e3e3b2aa6450df
/CourseWork/c_code/Parameters.h
6c06246b19a69a1d9fe41a3abeb8a110476a0ecd
[]
no_license
knaumova/CourseWork
ed613785103d3ad1620f83c97c4037a9faf6b1d6
170c31371584ada6087ad4d86d7a3cfac69bdbaf
refs/heads/master
2020-05-31T14:15:46.381812
2012-12-26T18:44:15
2012-12-26T18:44:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
51,420
h
// This file is part of Notepad++ project // Copyright (C)2003 Don HO <don.h@free.fr> // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // Note that the GPL places important restrictions on "derived works", yet // it does not provide a detailed definition of that term. To avoid // misunderstandings, we consider an application to constitute a // "derivative work" for the purpose of this license if it does any of the // following: // 1. Integrates source code from Notepad++. // 2. Integrates/includes/aggregates Notepad++ into a proprietary executable // installer, such as those produced by InstallShield. // 3. Links to a library or executes a program that does any of the above. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. #ifndef PARAMETERS_H #define PARAMETERS_H #ifndef TINYXMLA_INCLUDED #include "tinyxmlA.h" #endif //TINYXMLA_INCLUDED #ifndef TINYXML_INCLUDED #include "tinyxml.h" #endif //TINYXML_INCLUDED #ifndef SCINTILLA_H #include "Scintilla.h" #endif //SCINTILLA_H #ifndef SCINTILLA_REF_H #include "ScintillaRef.h" #endif //SCINTILLA_REF_H #ifndef TOOL_BAR_H #include "ToolBar.h" #endif //TOOL_BAR_H #ifndef USER_DEFINE_LANG_REFERENCE_H #include "UserDefineLangReference.h" #endif //USER_DEFINE_LANG_REFERENCE_H #ifndef COLORS_H #include "colors.h" #endif //COLORS_H #ifndef SHORTCUTS_H #include "shortcut.h" #endif //SHORTCUTS_H #ifndef CONTEXTMENU #include "ContextMenu.h" #endif //CONTEXTMENU class NativeLangSpeaker; using namespace std; const bool POS_VERTICAL = true; const bool POS_HORIZOTAL = false; const int UDD_SHOW = 1; // 0000 0001 const int UDD_DOCKED = 2; // 0000 0010 // 0 : 0000 0000 hide & undocked // 1 : 0000 0001 show & undocked // 2 : 0000 0010 hide & docked // 3 : 0000 0011 show & docked const int TAB_DRAWTOPBAR = 1; // 0000 0001 const int TAB_DRAWINACTIVETAB = 2; // 0000 0010 const int TAB_DRAGNDROP = 4; // 0000 0100 const int TAB_REDUCE = 8; // 0000 1000 const int TAB_CLOSEBUTTON = 16; // 0001 0000 const int TAB_DBCLK2CLOSE = 32; // 0010 0000 const int TAB_VERTICAL = 64; // 0100 0000 const int TAB_MULTILINE = 128; // 1000 0000 const int TAB_HIDE = 256; //1 0000 0000 enum formatType {WIN_FORMAT, MAC_FORMAT, UNIX_FORMAT}; enum UniMode {uni8Bit=0, uniUTF8=1, uni16BE=2, uni16LE=3, uniCookie=4, uni7Bit=5, uni16BE_NoBOM=6, uni16LE_NoBOM=7, uniEnd}; enum ChangeDetect {cdDisabled=0, cdEnabled=1, cdAutoUpdate=2, cdGo2end=3, cdAutoUpdateGo2end=4}; enum BackupFeature {bak_none = 0, bak_simple = 1, bak_verbose = 2}; enum OpenSaveDirSetting {dir_followCurrent = 0, dir_last = 1, dir_userDef = 2}; const int LANG_INDEX_INSTR = 0; const int LANG_INDEX_INSTR2 = 1; const int LANG_INDEX_TYPE = 2; const int LANG_INDEX_TYPE2 = 3; const int LANG_INDEX_TYPE3 = 4; const int LANG_INDEX_TYPE4 = 5; const int LANG_INDEX_TYPE5 = 6; const int COPYDATA_PARAMS = 0; const int COPYDATA_FILENAMESA = 1; const int COPYDATA_FILENAMESW = 2; const TCHAR fontSizeStrs[][3] = {TEXT(""), TEXT("5"), TEXT("6"), TEXT("7"), TEXT("8"), TEXT("9"), TEXT("10"), TEXT("11"), TEXT("12"), TEXT("14"), TEXT("16"), TEXT("18"), TEXT("20"), TEXT("22"), TEXT("24"), TEXT("26"), TEXT("28")}; const TCHAR localConfFile[] = TEXT("doLocalConf.xml"); const TCHAR allowAppDataPluginsFile[] = TEXT("allowAppDataPlugins.xml"); const TCHAR notepadStyleFile[] = TEXT("asNotepad.xml"); void cutString(const TCHAR *str2cut, vector<generic_string> & patternVect); /* struct HeaderLineState { HeaderLineState() : _headerLineNumber(0), _isCollapsed(false){}; HeaderLineState(int lineNumber, bool isFoldUp) : _headerLineNumber(lineNumber), _isCollapsed(isFoldUp){}; int _headerLineNumber; bool _isCollapsed; }; */ struct Position { int _firstVisibleLine; int _startPos; int _endPos; int _xOffset; int _selMode; int _scrollWidth; Position() : _firstVisibleLine(0), _startPos(0), _endPos(0), _xOffset(0), _scrollWidth(1), _selMode(0) {}; }; struct sessionFileInfo : public Position { sessionFileInfo(const TCHAR *fn, const TCHAR *ln, int encoding, Position pos) : _encoding(encoding), Position(pos) { if (fn) _fileName = fn; if (ln) _langName = ln; }; sessionFileInfo(generic_string fn) : _fileName(fn), _encoding(-1){}; generic_string _fileName; generic_string _langName; vector<size_t> marks; int _encoding; }; struct Session { size_t nbMainFiles() const {return _mainViewFiles.size();}; size_t nbSubFiles() const {return _subViewFiles.size();}; size_t _activeView; size_t _activeMainIndex; size_t _activeSubIndex; vector<sessionFileInfo> _mainViewFiles; vector<sessionFileInfo> _subViewFiles; }; struct CmdLineParams { bool _isNoPlugin; bool _isReadOnly; bool _isNoSession; bool _isNoTab; bool _isPreLaunch; bool _showLoadingTime; bool _alwaysOnTop; int _line2go; int _column2go; POINT _point; bool _isPointXValid; bool _isPointYValid; bool isPointValid() { return _isPointXValid && _isPointYValid; }; LangType _langType; CmdLineParams() : _isNoPlugin(false), _isReadOnly(false), _isNoSession(false), _isNoTab(false),_showLoadingTime(false),\ _isPreLaunch(false), _line2go(-1), _column2go(-1), _langType(L_EXTERNAL), _isPointXValid(false), _isPointYValid(false) { _point.x = 0; _point.y = 0; } }; struct FloatingWindowInfo { int _cont; RECT _pos; FloatingWindowInfo(int cont, int x, int y, int w, int h) : _cont(cont) { _pos.left = x; _pos.top = y; _pos.right = w; _pos.bottom = h; }; }; struct PluginDlgDockingInfo { generic_string _name; int _internalID; int _currContainer; int _prevContainer; bool _isVisible; PluginDlgDockingInfo(const TCHAR *pluginName, int id, int curr, int prev, bool isVis) : _internalID(id), _currContainer(curr), _prevContainer(prev), _isVisible(isVis), _name(pluginName){}; friend inline const bool operator==(const PluginDlgDockingInfo & a, const PluginDlgDockingInfo & b) { if ((a._name == b._name) && (a._internalID == b._internalID)) return true; else return false; }; }; struct ContainerTabInfo { int _cont; int _activeTab; ContainerTabInfo(int cont, int activeTab) : _cont(cont), _activeTab(activeTab) {}; }; struct DockingManagerData { int _leftWidth; int _rightWidth; int _topHeight; int _bottomHight; DockingManagerData() : _leftWidth(200), _rightWidth(200), _topHeight(200), _bottomHight(200) {}; vector<FloatingWindowInfo> _flaotingWindowInfo; vector<PluginDlgDockingInfo> _pluginDockInfo; vector<ContainerTabInfo> _containerTabInfo; bool getFloatingRCFrom(int floatCont, RECT & rc) { for (size_t i = 0 ; i < _flaotingWindowInfo.size() ; i++) { if (_flaotingWindowInfo[i]._cont == floatCont) { rc.left = _flaotingWindowInfo[i]._pos.left; rc.top = _flaotingWindowInfo[i]._pos.top; rc.right = _flaotingWindowInfo[i]._pos.right; rc.bottom = _flaotingWindowInfo[i]._pos.bottom; return true; } } return false; } }; const int FONTSTYLE_BOLD = 1; const int FONTSTYLE_ITALIC = 2; const int FONTSTYLE_UNDERLINE = 4; const int COLORSTYLE_FOREGROUND = 0x01; const int COLORSTYLE_BACKGROUND = 0x02; const int COLORSTYLE_ALL = COLORSTYLE_FOREGROUND|COLORSTYLE_BACKGROUND; struct Style { int _styleID; const TCHAR *_styleDesc; COLORREF _fgColor; COLORREF _bgColor; int _colorStyle; const TCHAR *_fontName; int _fontStyle; int _fontSize; int _keywordClass; generic_string *_keywords; Style():_styleID(-1), _styleDesc(NULL), _fgColor(COLORREF(-1)), _bgColor(COLORREF(-1)), _colorStyle(COLORSTYLE_ALL), _fontName(NULL), _fontStyle(-1), _fontSize(-1), _keywordClass(-1), _keywords(NULL){}; ~Style(){ if (_keywords) delete _keywords; }; Style(const Style & style) { _styleID = style._styleID; _styleDesc = style._styleDesc; _fgColor = style._fgColor; _bgColor = style._bgColor; _colorStyle = style._colorStyle; _fontName = style._fontName; _fontSize = style._fontSize; _fontStyle = style._fontStyle; _keywordClass = style._keywordClass; if (style._keywords) _keywords = new generic_string(*(style._keywords)); else _keywords = NULL; }; Style & operator=(const Style & style) { if (this != &style) { this->_styleID = style._styleID; this->_styleDesc = style._styleDesc; this->_fgColor = style._fgColor; this->_bgColor = style._bgColor; this->_colorStyle = style._colorStyle; this->_fontName = style._fontName; this->_fontSize = style._fontSize; this->_fontStyle = style._fontStyle; this->_keywordClass = style._keywordClass; if (!(this->_keywords) && style._keywords) this->_keywords = new generic_string(*(style._keywords)); else if (this->_keywords && style._keywords) this->_keywords->assign(*(style._keywords)); else if (this->_keywords && !(style._keywords)) { delete (this->_keywords); this->_keywords = NULL; } } return *this; }; void setKeywords(const TCHAR *str) { if (!_keywords) _keywords = new generic_string(str); else *_keywords = str; }; }; struct GlobalOverride { bool isEnable() const {return (enableFg || enableBg || enableFont || enableFontSize || enableBold || enableItalic || enableUnderLine);}; bool enableFg; bool enableBg; bool enableFont; bool enableFontSize; bool enableBold; bool enableItalic; bool enableUnderLine; GlobalOverride():enableFg(false), enableBg(false), enableFont(false), enableFontSize(false), enableBold(false), enableItalic(false), enableUnderLine(false) {}; }; const int MAX_STYLE = 30; struct StyleArray { public: StyleArray() : _nbStyler(0){}; StyleArray & operator=(const StyleArray & sa) { if (this != &sa) { this->_nbStyler = sa._nbStyler; for (int i = 0 ; i < _nbStyler ; i++) { this->_styleArray[i] = sa._styleArray[i]; } } return *this; } int getNbStyler() const {return _nbStyler;}; void setNbStyler(int nb) {_nbStyler = nb;}; Style & getStyler(int index) { assert(index != -1); return _styleArray[index]; }; bool hasEnoughSpace() {return (_nbStyler < MAX_STYLE);}; void addStyler(int styleID, TiXmlNode *styleNode); void addStyler(int styleID, TCHAR *styleName) { //ZeroMemory(&_styleArray[_nbStyler], sizeof(Style));; _styleArray[_nbStyler]._styleID = styleID; _styleArray[_nbStyler]._styleDesc = styleName; _styleArray[_nbStyler]._fgColor = black; _styleArray[_nbStyler]._bgColor = white; _nbStyler++; }; int getStylerIndexByID(int id) { for (int i = 0 ; i < _nbStyler ; i++) if (_styleArray[i]._styleID == id) return i; return -1; }; int getStylerIndexByName(const TCHAR *name) const { if (!name) return -1; for (int i = 0 ; i < _nbStyler ; i++) if (!lstrcmp(_styleArray[i]._styleDesc, name)) return i; return -1; }; protected: Style _styleArray[MAX_STYLE]; int _nbStyler; }; struct LexerStyler : public StyleArray { public : LexerStyler():StyleArray(){}; LexerStyler & operator=(const LexerStyler & ls) { if (this != &ls) { *((StyleArray *)this) = ls; this->_lexerName = ls._lexerName; this->_lexerDesc = ls._lexerDesc; this->_lexerUserExt = ls._lexerUserExt; } return *this; } void setLexerName(const TCHAR *lexerName) { _lexerName = lexerName; }; void setLexerDesc(const TCHAR *lexerDesc) { _lexerDesc = lexerDesc; }; void setLexerUserExt(const TCHAR *lexerUserExt) { _lexerUserExt = lexerUserExt; }; const TCHAR * getLexerName() const {return _lexerName.c_str();}; const TCHAR * getLexerDesc() const {return _lexerDesc.c_str();}; const TCHAR * getLexerUserExt() const {return _lexerUserExt.c_str();}; private : generic_string _lexerName; generic_string _lexerDesc; generic_string _lexerUserExt; }; const int MAX_LEXER_STYLE = 80; struct LexerStylerArray { public : LexerStylerArray() : _nbLexerStyler(0){}; LexerStylerArray & operator=(const LexerStylerArray & lsa) { if (this != &lsa) { this->_nbLexerStyler = lsa._nbLexerStyler; for (int i = 0 ; i < this->_nbLexerStyler ; i++) this->_lexerStylerArray[i] = lsa._lexerStylerArray[i]; } return *this; } int getNbLexer() const {return _nbLexerStyler;}; LexerStyler & getLexerFromIndex(int index) { return _lexerStylerArray[index]; }; const TCHAR * getLexerNameFromIndex(int index) const {return _lexerStylerArray[index].getLexerName();} const TCHAR * getLexerDescFromIndex(int index) const {return _lexerStylerArray[index].getLexerDesc();} LexerStyler * getLexerStylerByName(const TCHAR *lexerName) { if (!lexerName) return NULL; for (int i = 0 ; i < _nbLexerStyler ; i++) { if (!lstrcmp(_lexerStylerArray[i].getLexerName(), lexerName)) return &(_lexerStylerArray[i]); } return NULL; }; bool hasEnoughSpace() {return (_nbLexerStyler < MAX_LEXER_STYLE);}; void addLexerStyler(const TCHAR *lexerName, const TCHAR *lexerDesc, const TCHAR *lexerUserExt, TiXmlNode *lexerNode); void eraseAll(); private : LexerStyler _lexerStylerArray[MAX_LEXER_STYLE]; int _nbLexerStyler; }; struct NewDocDefaultSettings { formatType _format; UniMode _encoding; bool _openAnsiAsUtf8; LangType _lang; int _codepage; // -1 when not using NewDocDefaultSettings():_format(WIN_FORMAT), _encoding(uni8Bit), _openAnsiAsUtf8(false), _lang(L_TEXT), _codepage(-1){}; }; struct LangMenuItem { LangType _langType; int _cmdID; generic_string _langName; LangMenuItem(LangType lt, int cmdID = 0, generic_string langName = TEXT("")): _langType(lt), _cmdID(cmdID), _langName(langName){}; }; struct PrintSettings { bool _printLineNumber; int _printOption; generic_string _headerLeft; generic_string _headerMiddle; generic_string _headerRight; generic_string _headerFontName; int _headerFontStyle; int _headerFontSize; generic_string _footerLeft; generic_string _footerMiddle; generic_string _footerRight; generic_string _footerFontName; int _footerFontStyle; int _footerFontSize; RECT _marge; PrintSettings() : _printLineNumber(true), _printOption(SC_PRINT_NORMAL), _headerLeft(TEXT("")), _headerMiddle(TEXT("")), _headerRight(TEXT("")),\ _headerFontName(TEXT("")), _headerFontStyle(0), _headerFontSize(0), _footerLeft(TEXT("")), _footerMiddle(TEXT("")), _footerRight(TEXT("")),\ _footerFontName(TEXT("")), _footerFontStyle(0), _footerFontSize(0) { _marge.left = 0; _marge.top = 0; _marge.right = 0; _marge.bottom = 0; }; bool isHeaderPresent() const { return ((_headerLeft != TEXT("")) || (_headerMiddle != TEXT("")) || (_headerRight != TEXT(""))); }; bool isFooterPresent() const { return ((_footerLeft != TEXT("")) || (_footerMiddle != TEXT("")) || (_footerRight != TEXT(""))); }; bool isUserMargePresent() const { return ((_marge.left != 0) || (_marge.top != 0) || (_marge.right != 0) || (_marge.bottom != 0)); }; }; class Date { public: Date() : _year(2008), _month(4), _day(26){}; Date(unsigned long year, unsigned long month, unsigned long day) { assert(year > 0 && year <= 9999); // I don't think Notepad++ will last till AD 10000 :) assert(month > 0 && month <= 12); assert(day > 0 && day <= 31); assert(!(month == 2 && day > 29) && !(month == 4 && day > 30) && !(month == 6 && day > 30) && !(month == 9 && day > 30) && !(month == 11 && day > 30)); _year = year; _month = month; _day = day; }; Date(const TCHAR *dateStr) { // timeStr should be Notepad++ date format : YYYYMMDD assert(dateStr); if (lstrlen(dateStr) == 8) { generic_string ds(dateStr); generic_string yyyy(ds, 0, 4); generic_string mm(ds, 4, 2); generic_string dd(ds, 6, 2); int y = generic_atoi(yyyy.c_str()); int m = generic_atoi(mm.c_str()); int d = generic_atoi(dd.c_str()); if ((y > 0 && y <= 9999) && (m > 0 && m <= 12) && (d > 0 && d <= 31)) { _year = y; _month = m; _day = d; return; } } now(); }; // The constructor which makes the date of number of days from now // nbDaysFromNow could be negative if user want to make a date in the past // if the value of nbDaysFromNow is 0 then the date will be now Date(int nbDaysFromNow) { const time_t oneDay = (60 * 60 * 24); time_t rawtime; tm* timeinfo; time(&rawtime); rawtime += (nbDaysFromNow * oneDay); timeinfo = localtime(&rawtime); _year = timeinfo->tm_year+1900; _month = timeinfo->tm_mon+1; _day = timeinfo->tm_mday; } void now() { time_t rawtime; tm* timeinfo; time(&rawtime); timeinfo = localtime(&rawtime); _year = timeinfo->tm_year+1900; _month = timeinfo->tm_mon+1; _day = timeinfo->tm_mday; }; generic_string toString() { // Return Notepad++ date format : YYYYMMDD TCHAR dateStr[8+1]; wsprintf(dateStr, TEXT("%04d%02d%02d"), _year, _month, _day); return dateStr; }; bool operator<(const Date & compare) const { if (this->_year != compare._year) return (this->_year < compare._year); if (this->_month != compare._month) return (this->_month < compare._month); return (this->_day < compare._day); }; bool operator>(const Date & compare) const { if (this->_year != compare._year) return (this->_year > compare._year); if (this->_month != compare._month) return (this->_month > compare._month); return (this->_day > compare._day); }; bool operator==(const Date & compare) const { if (this->_year != compare._year) return false; if (this->_month != compare._month) return false; return (this->_day == compare._day); }; bool operator!=(const Date & compare) const { if (this->_year != compare._year) return true; if (this->_month != compare._month) return true; return (this->_day != compare._day); }; private: unsigned long _year; unsigned long _month; unsigned long _day; }; struct NppGUI { NppGUI() : _toolBarStatus(TB_LARGE), _toolbarShow(true), _statusBarShow(true), _menuBarShow(true),\ _tabStatus(TAB_DRAWTOPBAR | TAB_DRAWINACTIVETAB | TAB_DRAGNDROP), _splitterPos(POS_HORIZOTAL),\ _userDefineDlgStatus(UDD_DOCKED), _tabSize(8), _tabReplacedBySpace(false), _fileAutoDetection(cdEnabled), _fileAutoDetectionOriginalValue(_fileAutoDetection),\ _checkHistoryFiles(true) ,_enableSmartHilite(true), _disableSmartHiliteTmp(false), _enableTagsMatchHilite(true), _enableTagAttrsHilite(true), _enableHiliteNonHTMLZone(false),\ _isMaximized(false), _isMinimizedToTray(false), _rememberLastSession(true), _backup(bak_none), _useDir(false), _backupDir(TEXT("")),\ _doTaskList(true), _maitainIndent(true), _openSaveDir(dir_followCurrent), _styleMRU(true), _styleURL(0),\ _autocStatus(autoc_none), _autocFromLen(1), _funcParams(false), _definedSessionExt(TEXT("")),\ _doesExistUpdater(false), _caretBlinkRate(250), _caretWidth(1), _enableMultiSelection(false), _shortTitlebar(false), _themeName(TEXT("")), _isLangMenuCompact(false), _smartHiliteCaseSensitive(false) { _appPos.left = 0; _appPos.top = 0; _appPos.right = 700; _appPos.bottom = 500; _defaultDir[0] = 0; _defaultDirExp[0] = 0; }; toolBarStatusType _toolBarStatus; // small, large ou standard bool _toolbarShow; bool _statusBarShow; // show ou hide bool _menuBarShow; // 1st bit : draw top bar; // 2nd bit : draw inactive tabs // 3rd bit : enable drag & drop // 4th bit : reduce the height // 5th bit : enable vertical // 6th bit : enable multiline // 0:don't draw; 1:draw top bar 2:draw inactive tabs 3:draw both 7:draw both+drag&drop int _tabStatus; bool _splitterPos; // horizontal ou vertical int _userDefineDlgStatus; // (hide||show) && (docked||undocked) int _tabSize; bool _tabReplacedBySpace; ChangeDetect _fileAutoDetection; ChangeDetect _fileAutoDetectionOriginalValue; bool _checkHistoryFiles; RECT _appPos; bool _isMaximized; bool _isMinimizedToTray; bool _rememberLastSession; bool _doTaskList; bool _maitainIndent; bool _enableSmartHilite; bool _smartHiliteCaseSensitive; bool _disableSmartHiliteTmp; bool _enableTagsMatchHilite; bool _enableTagAttrsHilite; bool _enableHiliteNonHTMLZone; bool _styleMRU; // 0 : do nothing // 1 : don't draw underline // 2 : draw underline int _styleURL; NewDocDefaultSettings _newDocDefaultSettings; void setTabReplacedBySpace(bool b) {_tabReplacedBySpace = b;}; const NewDocDefaultSettings & getNewDocDefaultSettings() const {return _newDocDefaultSettings;}; vector<LangMenuItem> _excludedLangList; bool _isLangMenuCompact; PrintSettings _printSettings; BackupFeature _backup; bool _useDir; generic_string _backupDir; DockingManagerData _dockingData; GlobalOverride _globalOverride; enum AutocStatus{autoc_none, autoc_func, autoc_word}; AutocStatus _autocStatus; size_t _autocFromLen; bool _funcParams; generic_string _definedSessionExt; struct AutoUpdateOptions { bool _doAutoUpdate; int _intervalDays; Date _nextUpdateDate; AutoUpdateOptions(): _doAutoUpdate(true), _intervalDays(15), _nextUpdateDate(Date()) {}; } _autoUpdateOpt; bool _doesExistUpdater; int _caretBlinkRate; int _caretWidth; bool _enableMultiSelection; bool _shortTitlebar; OpenSaveDirSetting _openSaveDir; TCHAR _defaultDir[MAX_PATH]; TCHAR _defaultDirExp[MAX_PATH]; //expanded environment variables generic_string _themeName; }; struct ScintillaViewParams { ScintillaViewParams() : _lineNumberMarginShow(true), _bookMarkMarginShow(true),_borderWidth(2),\ _folderStyle(FOLDER_STYLE_BOX), _foldMarginShow(true), _indentGuideLineShow(true),\ _currentLineHilitingShow(true), _wrapSymbolShow(false), _doWrap(false), _edgeNbColumn(80),\ _zoom(0), _zoom2(0), _whiteSpaceShow(false), _eolShow(false), _lineWrapMethod(LINEWRAP_ALIGNED){}; bool _lineNumberMarginShow; bool _bookMarkMarginShow; //bool _docChangeStateMarginShow; folderStyle _folderStyle; //"simple", "arrow", "circle", "box" and "none" lineWrapMethod _lineWrapMethod; bool _foldMarginShow; bool _indentGuideLineShow; bool _currentLineHilitingShow; bool _wrapSymbolShow; bool _doWrap; int _edgeMode; int _edgeNbColumn; int _zoom; int _zoom2; bool _whiteSpaceShow; bool _eolShow; int _borderWidth; }; const int NB_LIST = 20; const int NB_MAX_LRF_FILE = 30; const int NB_MAX_USER_LANG = 30; const int NB_MAX_EXTERNAL_LANG = 30; const int NB_MAX_IMPORTED_UDL = 50; const int NB_MAX_FINDHISTORY_FIND = 30; const int NB_MAX_FINDHISTORY_REPLACE = 30; const int NB_MAX_FINDHISTORY_PATH = 30; const int NB_MAX_FINDHISTORY_FILTER = 20; const int MASK_ReplaceBySpc = 0x80; const int MASK_TabSize = 0x7F; struct Lang { LangType _langID; generic_string _langName; const TCHAR *_defaultExtList; const TCHAR *_langKeyWordList[NB_LIST]; const TCHAR *_pCommentLineSymbol; const TCHAR *_pCommentStart; const TCHAR *_pCommentEnd; bool _isTabReplacedBySpace; int _tabSize; Lang(): _langID(L_TEXT), _langName(TEXT("")), _defaultExtList(NULL), _pCommentLineSymbol(NULL), _pCommentStart(NULL), _pCommentEnd(NULL), _isTabReplacedBySpace(false), _tabSize(-1) { for (int i = 0 ; i < NB_LIST ; _langKeyWordList[i] = NULL ,i++); }; Lang(LangType langID, const TCHAR *name) : _langID(langID), _langName(name?name:TEXT("")),\ _defaultExtList(NULL), _pCommentLineSymbol(NULL), _pCommentStart(NULL),\ _pCommentEnd(NULL), _isTabReplacedBySpace(false), _tabSize(-1) { for (int i = 0 ; i < NB_LIST ; _langKeyWordList[i] = NULL ,i++); }; ~Lang() {}; void setDefaultExtList(const TCHAR *extLst){ _defaultExtList = extLst; }; void setCommentLineSymbol(const TCHAR *commentLine){ _pCommentLineSymbol = commentLine; }; void setCommentStart(const TCHAR *commentStart){ _pCommentStart = commentStart; }; void setCommentEnd(const TCHAR *commentEnd){ _pCommentEnd = commentEnd; }; void setTabInfo(int tabInfo) { if (tabInfo != -1 && tabInfo & MASK_TabSize) { _isTabReplacedBySpace = (tabInfo & MASK_ReplaceBySpc) != 0; _tabSize = tabInfo & MASK_TabSize; } }; const TCHAR * getDefaultExtList() const { return _defaultExtList; }; void setWords(const TCHAR *words, int index) { _langKeyWordList[index] = words; }; const TCHAR * getWords(int index) const { return _langKeyWordList[index]; }; LangType getLangID() const {return _langID;}; const TCHAR * getLangName() const {return _langName.c_str();}; int getTabInfo() const { if (_tabSize == -1) return -1; return (_isTabReplacedBySpace?0x80:0x00) | _tabSize; }; }; class UserLangContainer { friend class Notepad_plus; friend class ScintillaEditView; friend class NppParameters; friend class SharedParametersDialog; friend class FolderStyleDialog; friend class KeyWordsStyleDialog; friend class CommentStyleDialog; friend class SymbolsStyleDialog; friend class UserDefineDialog; public : UserLangContainer(){ _name = TEXT("new user define"); _ext = TEXT(""); _escapeChar[0] = '\0'; _escapeChar[1] = '\0'; // Keywords list of Delimiters (index 0) lstrcpy(_keywordLists[0], TEXT("000000")); for (int i = 1 ; i < nbKeywodList ; i++) *_keywordLists[i] = '\0'; }; UserLangContainer(const TCHAR *name, const TCHAR *ext) : _name(name), _ext(ext) { // Keywords list of Delimiters (index 0) lstrcpy(_keywordLists[0], TEXT("000000")); _escapeChar[0] = '\0'; _escapeChar[1] = '\0'; for (int j = 1 ; j < nbKeywodList ; j++) *_keywordLists[j] = '\0'; }; UserLangContainer & operator=(const UserLangContainer & ulc) { if (this != &ulc) { this->_name = ulc._name; this->_ext = ulc._ext; this->_escapeChar[0] = ulc._escapeChar[0]; this->_escapeChar[1] = '\0'; this->_isCaseIgnored = ulc._isCaseIgnored; this->_styleArray = ulc._styleArray; int nbStyler = this->_styleArray.getNbStyler(); for (int i = 0 ; i < nbStyler ; i++) { Style & st = this->_styleArray.getStyler(i); if (st._bgColor == COLORREF(-1)) st._bgColor = white; if (st._fgColor == COLORREF(-1)) st._fgColor = black; } for (int i = 0 ; i < nbKeywodList ; i++) lstrcpy(this->_keywordLists[i], ulc._keywordLists[i]); } return *this; }; int getNbKeywordList() {return nbKeywodList;}; const TCHAR * getName() {return _name.c_str();}; const TCHAR * getExtention() {return _ext.c_str();}; private: generic_string _name; generic_string _ext; StyleArray _styleArray; TCHAR _keywordLists[nbKeywodList][max_char]; bool _isCaseIgnored; bool _isCommentLineSymbol; bool _isCommentSymbol; bool _isPrefix[nbPrefixListAllowed]; TCHAR _escapeChar[2]; }; #define MAX_EXTERNAL_LEXER_NAME_LEN 16 #define MAX_EXTERNAL_LEXER_DESC_LEN 32 class ExternalLangContainer { public: TCHAR _name[MAX_EXTERNAL_LEXER_NAME_LEN]; TCHAR _desc[MAX_EXTERNAL_LEXER_DESC_LEN]; ExternalLangContainer(const TCHAR *name, const TCHAR *desc) { generic_strncpy(_name, name, MAX_EXTERNAL_LEXER_NAME_LEN); generic_strncpy(_desc, desc, MAX_EXTERNAL_LEXER_DESC_LEN); }; }; struct FindHistory { enum searchMode{normal, extended, regExpr}; enum transparencyMode{none, onLossingFocus, persistant}; FindHistory() : _nbMaxFindHistoryPath(10), _nbMaxFindHistoryFilter(10), _nbMaxFindHistoryFind(10), _nbMaxFindHistoryReplace(10),\ _isMatchWord(false), _isMatchCase(false),_isWrap(true),_isDirectionDown(true),\ _isFifRecuisive(true), _isFifInHiddenFolder(false), _isDlgAlwaysVisible(false),\ _isFilterFollowDoc(false), _isFolderFollowDoc(false),\ _searchMode(normal), _transparencyMode(onLossingFocus), _transparency(150), _dotMatchesNewline(false) {}; int _nbMaxFindHistoryPath; int _nbMaxFindHistoryFilter; int _nbMaxFindHistoryFind; int _nbMaxFindHistoryReplace; vector<generic_string> _findHistoryPaths; vector<generic_string> _findHistoryFilters; vector<generic_string> _findHistoryFinds; vector<generic_string> _findHistoryReplaces; bool _isMatchWord; bool _isMatchCase; bool _isWrap; bool _isDirectionDown; bool _dotMatchesNewline; bool _isFifRecuisive; bool _isFifInHiddenFolder; searchMode _searchMode; transparencyMode _transparencyMode; int _transparency; bool _isDlgAlwaysVisible; bool _isFilterFollowDoc; bool _isFolderFollowDoc; }; #ifdef UNICODE class LocalizationSwitcher { friend class NppParameters; public : LocalizationSwitcher() : _fileName("") {}; struct LocalizationDefinition { wchar_t *_langName; wchar_t *_xmlFileName; }; bool addLanguageFromXml(wstring xmlFullPath); wstring getLangFromXmlFileName(const wchar_t *fn) const; wstring getXmlFilePathFromLangName(const wchar_t *langName) const; bool switchToLang(wchar_t *lang2switch) const; size_t size() const { return _localizationList.size(); }; pair<wstring, wstring> getElementFromIndex(size_t index) { if (index >= _localizationList.size()) return pair<wstring, wstring>(TEXT(""), TEXT("")); return _localizationList[index]; }; void setFileName(const char *fn) { if (fn) _fileName = fn; }; string getFileName() const { return _fileName; }; private : vector< pair< wstring, wstring > > _localizationList; wstring _nativeLangPath; string _fileName; }; #endif class ThemeSwitcher { friend class NppParameters; public : ThemeSwitcher(){}; void addThemeFromXml(generic_string xmlFullPath) { _themeList.push_back(pair<generic_string, generic_string>(getThemeFromXmlFileName(xmlFullPath.c_str()), xmlFullPath)); }; void addDefaultThemeFromXml(generic_string xmlFullPath) { _themeList.push_back(pair<generic_string, generic_string>(TEXT("Default (stylers.xml)"), xmlFullPath)); }; generic_string getThemeFromXmlFileName(const TCHAR *fn) const; generic_string getXmlFilePathFromThemeName(const TCHAR *themeName) const { if (!themeName || themeName[0]) return TEXT(""); generic_string themePath = _stylesXmlPath; return themePath; }; bool themeNameExists(const TCHAR *themeName) { for (size_t i = 0; i < _themeList.size(); i++ ) { if (! (getElementFromIndex(i)).first.compare(themeName) ) return true; } return false; } size_t size() const { return _themeList.size(); }; pair<generic_string, generic_string> & getElementFromIndex(size_t index) { //if (index >= _themeList.size()) //return pair<generic_string, generic_string>(TEXT(""), TEXT("")); return _themeList[index]; }; private : vector< pair< generic_string, generic_string > > _themeList; generic_string _stylesXmlPath; }; class PluginList { public : void add(generic_string fn, bool isInBL){ _list.push_back(pair<generic_string, bool>(fn, isInBL)); }; private : vector<pair<generic_string, bool>>_list; }; const int NB_LANG = 80; const bool DUP = true; const bool FREE = false; const int RECENTFILES_SHOWFULLPATH = -1; const int RECENTFILES_SHOWONLYFILENAME = 0; class NppParameters { public: static NppParameters * getInstance() {return _pSelf;}; static LangType getLangIDFromStr(const TCHAR *langName); bool load(); bool reloadLang(); bool reloadStylers(TCHAR *stylePath = NULL); void destroyInstance(); bool _isTaskListRBUTTONUP_Active; int L_END; const NppGUI & getNppGUI() const { return _nppGUI; }; const TCHAR * getWordList(LangType langID, int typeIndex) const { Lang *pLang = getLangFromID(langID); if (!pLang) return NULL; return pLang->getWords(typeIndex); }; Lang * getLangFromID(LangType langID) const { for (int i = 0 ; i < _nbLang ; i++) { if ((_langList[i]->_langID == langID) || (!_langList[i])) return _langList[i]; } return NULL; }; Lang * getLangFromIndex(int i) const { if (i >= _nbLang) return NULL; return _langList[i]; }; int getNbLang() const {return _nbLang;}; LangType getLangFromExt(const TCHAR *ext); const TCHAR * getLangExtFromName(const TCHAR *langName) const { for (int i = 0 ; i < _nbLang ; i++) { if (_langList[i]->_langName == langName) return _langList[i]->_defaultExtList; } return NULL; }; const TCHAR * getLangExtFromLangType(LangType langType) const { for (int i = 0 ; i < _nbLang ; i++) { if (_langList[i]->_langID == langType) return _langList[i]->_defaultExtList; } return NULL; }; int getNbLRFile() const {return _nbRecentFile;}; generic_string *getLRFile(int index) const { return _LRFileList[index]; }; void setNbMaxRecentFile(int nb) { _nbMaxRecentFile = nb; }; int getNbMaxRecentFile() const {return _nbMaxRecentFile;}; void setPutRecentFileInSubMenu(bool doSubmenu) { _putRecentFileInSubMenu = doSubmenu; }; bool putRecentFileInSubMenu() const {return _putRecentFileInSubMenu;}; void setRecentFileCustomLength(int len) { _recentFileCustomLength = len; }; int getRecentFileCustomLength() const {return _recentFileCustomLength;}; const ScintillaViewParams & getSVP() const { return _svp; }; bool writeRecentFileHistorySettings(int nbMaxFile = -1) const; bool writeHistory(const TCHAR *fullpath); bool writeProjectPanelsSettings() const; TiXmlNode * getChildElementByAttribut(TiXmlNode *pere, const TCHAR *childName,\ const TCHAR *attributName, const TCHAR *attributVal) const; bool writeScintillaParams(const ScintillaViewParams & svp); bool writeGUIParams(); void writeStyles(LexerStylerArray & lexersStylers, StyleArray & globalStylers); bool insertTabInfo(const TCHAR *langName, int tabInfo); LexerStylerArray & getLStylerArray() {return _lexerStylerArray;}; StyleArray & getGlobalStylers() {return _widgetStyleArray;}; StyleArray & getMiscStylerArray() {return _widgetStyleArray;}; GlobalOverride & getGlobalOverrideStyle() {return _nppGUI._globalOverride;}; COLORREF getCurLineHilitingColour() { int i = _widgetStyleArray.getStylerIndexByName(TEXT("Current line background colour")); if (i == -1) return i; Style & style = _widgetStyleArray.getStyler(i); return style._bgColor; }; void setCurLineHilitingColour(COLORREF colour2Set) { int i = _widgetStyleArray.getStylerIndexByName(TEXT("Current line background colour")); if (i == -1) return; Style & style = _widgetStyleArray.getStyler(i); style._bgColor = colour2Set; }; void setFontList(HWND hWnd); const vector<generic_string> & getFontList() const {return _fontlist;}; int getNbUserLang() const {return _nbUserLang;}; UserLangContainer & getULCFromIndex(int i) {return *_userLangArray[i];}; UserLangContainer * getULCFromName(const TCHAR *userLangName) { for (int i = 0 ; i < _nbUserLang ; i++) if (!lstrcmp(userLangName, _userLangArray[i]->_name.c_str())) return _userLangArray[i]; //qui doit etre jamais passer return NULL; }; int getNbExternalLang() const {return _nbExternalLang;}; int getExternalLangIndexFromName(const TCHAR *externalLangName) const { for (int i = 0 ; i < _nbExternalLang ; i++) { if (!lstrcmp(externalLangName, _externalLangArray[i]->_name)) return i; } return -1; }; ExternalLangContainer & getELCFromIndex(int i) {return *_externalLangArray[i];}; bool ExternalLangHasRoom() const {return _nbExternalLang < NB_MAX_EXTERNAL_LANG;}; void getExternalLexerFromXmlTree(TiXmlDocument *doc); vector<TiXmlDocument *> * getExternalLexerDoc() { return &_pXmlExternalLexerDoc;}; void writeUserDefinedLang(); void writeShortcuts(); void writeSession(const Session & session, const TCHAR *fileName = NULL); bool writeFindHistory(); bool isExistingUserLangName(const TCHAR *newName) const { if ((!newName) || (!newName[0])) return true; for (int i = 0 ; i < _nbUserLang ; i++) { if (!lstrcmp(_userLangArray[i]->_name.c_str(), newName)) return true; } return false; }; const TCHAR * getUserDefinedLangNameFromExt(TCHAR *ext) { if ((!ext) || (!ext[0])) return NULL; for (int i = 0 ; i < _nbUserLang ; i++) { vector<generic_string> extVect; cutString(_userLangArray[i]->_ext.c_str(), extVect); for (size_t j = 0 ; j < extVect.size() ; j++) if (!generic_stricmp(extVect[j].c_str(), ext)) return _userLangArray[i]->_name.c_str(); } return NULL; }; int addUserLangToEnd(const UserLangContainer & userLang, const TCHAR *newName); void removeUserLang(int index); bool isExistingExternalLangName(const TCHAR *newName) const { if ((!newName) || (!newName[0])) return true; for (int i = 0 ; i < _nbExternalLang ; i++) { if (!lstrcmp(_externalLangArray[i]->_name, newName)) return true; } return false; }; int addExternalLangToEnd(ExternalLangContainer * externalLang); TiXmlDocumentA * getNativeLangA() const {return _pXmlNativeLangDocA;}; TiXmlDocument * getToolIcons() const {return _pXmlToolIconsDoc;}; bool isTransparentAvailable() const { return (_transparentFuncAddr != NULL); }; // 0 <= percent < 256 // if (percent == 255) then opacq void SetTransparent(HWND hwnd, int percent) { if (!_transparentFuncAddr) return; ::SetWindowLongPtr(hwnd, GWL_EXSTYLE, ::GetWindowLongPtrW(hwnd, GWL_EXSTYLE) | 0x00080000); if (percent > 255) percent = 255; if (percent < 0) percent = 0; _transparentFuncAddr(hwnd, 0, percent, 0x00000002); }; void removeTransparent(HWND hwnd) { ::SetWindowLongPtr(hwnd, GWL_EXSTYLE, ::GetWindowLongPtr(hwnd, GWL_EXSTYLE) & ~0x00080000); }; void setCmdlineParam(const CmdLineParams & cmdLineParams) { _cmdLineParams = cmdLineParams; }; CmdLineParams & getCmdLineParams() {return _cmdLineParams;}; void setFileSaveDlgFilterIndex(int ln) {_fileSaveDlgFilterIndex = ln;}; int getFileSaveDlgFilterIndex() const {return _fileSaveDlgFilterIndex;}; bool isRemappingShortcut() const {return _shortcuts.size() != 0;}; vector<CommandShortcut> & getUserShortcuts() {return _shortcuts;}; vector<int> & getUserModifiedShortcuts() {return _customizedShortcuts;}; void addUserModifiedIndex(int index); vector<MacroShortcut> & getMacroList() {return _macros;}; vector<UserCommand> & getUserCommandList() {return _userCommands;}; vector<PluginCmdShortcut> & getPluginCommandList() {return _pluginCommands;}; vector<int> & getPluginModifiedKeyIndices() {return _pluginCustomizedCmds;}; void addPluginModifiedIndex(int index); vector<ScintillaKeyMap> & getScintillaKeyList() {return _scintillaKeyCommands;}; vector<int> & getScintillaModifiedKeyIndices() {return _scintillaModifiedKeyIndices;}; void addScintillaModifiedIndex(int index); vector<MenuItemUnit> & getContextMenuItems() {return _contextMenuItems;}; const Session & getSession() const {return _session;}; bool hasCustomContextMenu() const {return !_contextMenuItems.empty();}; void setAccelerator(Accelerator *pAccel) {_pAccelerator = pAccel;}; Accelerator * getAccelerator() {return _pAccelerator;}; void setScintillaAccelerator(ScintillaAccelerator *pScintAccel) {_pScintAccelerator = pScintAccel;}; ScintillaAccelerator * getScintillaAccelerator() {return _pScintAccelerator;}; generic_string getNppPath() const {return _nppPath;}; generic_string getContextMenuPath() const {return _contextMenuPath;}; const TCHAR * getAppDataNppDir() const {return _appdataNppDir.c_str();}; const TCHAR * getWorkingDir() const {return _currentDirectory.c_str();}; const TCHAR * getworkSpaceFilePath(int i) const { if (i < 0 || i > 2) return NULL; return _workSpaceFilePathes[i].c_str(); }; void setWorkSpaceFilePath(int i, const TCHAR *wsFile) { if (i < 0 || i > 2 || !wsFile) return; _workSpaceFilePathes[i] = wsFile; }; void setWorkingDir(const TCHAR * newPath); bool loadSession(Session & session, const TCHAR *sessionFileName); int langTypeToCommandID(LangType lt) const; WNDPROC getEnableThemeDlgTexture() const {return _enableThemeDialogTextureFuncAddr;}; struct FindDlgTabTitiles { generic_string _find; generic_string _replace; generic_string _findInFiles; generic_string _mark; FindDlgTabTitiles() : _find(TEXT("")), _replace(TEXT("")), _findInFiles(TEXT("")), _mark(TEXT("")) {}; }; FindDlgTabTitiles & getFindDlgTabTitiles() { return _findDlgTabTitiles;}; bool asNotepadStyle() const {return _asNotepadStyle;}; bool reloadPluginCmds() { return getPluginCmdsFromXmlTree(); } bool getContextMenuFromXmlTree(HMENU mainMenuHadle, HMENU pluginsMenu); bool reloadContextMenuFromXmlTree(HMENU mainMenuHadle, HMENU pluginsMenu); winVer getWinVersion() { return _winVersion;}; FindHistory & getFindHistory() {return _findHistory;}; bool _isFindReplacing; // an on the fly variable for find/replace functions void safeWow64EnableWow64FsRedirection(BOOL Wow64FsEnableRedirection); #ifdef UNICODE LocalizationSwitcher & getLocalizationSwitcher() { return _localizationSwitcher; }; #endif ThemeSwitcher & getThemeSwitcher() { return _themeSwitcher; }; vector<generic_string> & getBlackList() {return _blacklist;}; bool isInBlackList(TCHAR *fn) { for (size_t i = 0 ; i < _blacklist.size() ; i++) if (_blacklist[i] == fn) return true; return false; }; PluginList & getPluginList() {return _pluginList;}; bool importUDLFromFile(generic_string sourceFile); bool exportUDLToFile(int langIndex2export, generic_string fileName2save); NativeLangSpeaker * getNativeLangSpeaker() { return _pNativeLangSpeaker; }; void setNativeLangSpeaker(NativeLangSpeaker *nls) { _pNativeLangSpeaker = nls; }; bool isLocal() const { return _isLocal; }; void saveConfig_xml() { _pXmlUserDoc->SaveFile(); }; private: NppParameters(); ~NppParameters(); static NppParameters *_pSelf; TiXmlDocument *_pXmlDoc, *_pXmlUserDoc, *_pXmlUserStylerDoc, *_pXmlUserLangDoc,\ *_pXmlToolIconsDoc, *_pXmlShortcutDoc, *_pXmlSessionDoc,\ *_pXmlBlacklistDoc; TiXmlDocument *_importedULD[NB_MAX_IMPORTED_UDL]; int _nbImportedULD; TiXmlDocumentA *_pXmlNativeLangDocA, *_pXmlContextMenuDocA; vector<TiXmlDocument *> _pXmlExternalLexerDoc; NppGUI _nppGUI; ScintillaViewParams _svp; Lang *_langList[NB_LANG]; int _nbLang; // Recent File History generic_string *_LRFileList[NB_MAX_LRF_FILE]; int _nbRecentFile; int _nbMaxRecentFile; bool _putRecentFileInSubMenu; int _recentFileCustomLength; // <0: Full File Path Name // =0: Only File Name // >0: Custom Entry Length FindHistory _findHistory; UserLangContainer *_userLangArray[NB_MAX_USER_LANG]; int _nbUserLang; generic_string _userDefineLangPath; ExternalLangContainer *_externalLangArray[NB_MAX_EXTERNAL_LANG]; int _nbExternalLang; CmdLineParams _cmdLineParams; int _fileSaveDlgFilterIndex; // All Styles (colours & fonts) LexerStylerArray _lexerStylerArray; StyleArray _widgetStyleArray; vector<generic_string> _fontlist; vector<generic_string> _blacklist; PluginList _pluginList; HMODULE _hUser32; HMODULE _hUXTheme; WNDPROC _transparentFuncAddr; WNDPROC _enableThemeDialogTextureFuncAddr; bool _isLocal; vector<CommandShortcut> _shortcuts; //main menu shortuts. Static size vector<int> _customizedShortcuts; //altered main menu shortcuts. Indices static. Needed when saving alterations vector<MacroShortcut> _macros; //macro shortcuts, dynamic size, defined on loading macros and adding/deleting them vector<UserCommand> _userCommands; //run shortcuts, dynamic size, defined on loading run commands and adding/deleting them vector<PluginCmdShortcut> _pluginCommands; //plugin commands, dynamic size, defined on loading plugins vector<int> _pluginCustomizedCmds; //plugincommands that have been altered. Indices determined after loading ALL plugins. Needed when saving alterations vector<ScintillaKeyMap> _scintillaKeyCommands; //scintilla keycommands. Static size vector<int> _scintillaModifiedKeyIndices; //modified scintilla keys. Indices static, determined by searching for commandId. Needed when saving alterations #ifdef UNICODE LocalizationSwitcher _localizationSwitcher; #endif ThemeSwitcher _themeSwitcher; //vector<generic_string> _noMenuCmdNames; vector<MenuItemUnit> _contextMenuItems; Session _session; generic_string _shortcutsPath; generic_string _contextMenuPath; generic_string _sessionPath; generic_string _blacklistPath; generic_string _nppPath; generic_string _userPath; generic_string _stylerPath; generic_string _appdataNppDir; // sentinel of the absence of "doLocalConf.xml" : (_appdataNppDir == TEXT(""))?"doLocalConf.xml present":"doLocalConf.xml absent" generic_string _currentDirectory; generic_string _workSpaceFilePathes[3]; Accelerator *_pAccelerator; ScintillaAccelerator * _pScintAccelerator; FindDlgTabTitiles _findDlgTabTitiles; bool _asNotepadStyle; winVer _winVersion; NativeLangSpeaker *_pNativeLangSpeaker; static int CALLBACK EnumFontFamExProc(ENUMLOGFONTEX *lpelfe, NEWTEXTMETRICEX *, int, LPARAM lParam) { vector<generic_string> *pStrVect = (vector<generic_string> *)lParam; size_t vectSize = pStrVect->size(); //Search through all the fonts, EnumFontFamiliesEx never states anything about order //Start at the end though, that's the most likely place to find a duplicate for(int i = vectSize - 1 ; i >= 0 ; i--) { if ( !lstrcmp((*pStrVect)[i].c_str(), (const TCHAR *)lpelfe->elfLogFont.lfFaceName) ) return 1; //we already have seen this typeface, ignore it } //We can add the font //Add the face name and not the full name, we do not care about any styles pStrVect->push_back((TCHAR *)lpelfe->elfLogFont.lfFaceName); return 1; // I want to get all fonts }; void getLangKeywordsFromXmlTree(); bool getUserParametersFromXmlTree(); bool getUserStylersFromXmlTree(); bool getUserDefineLangsFromXmlTree(TiXmlDocument *tixmldoc); bool getUserDefineLangsFromXmlTree() { return getUserDefineLangsFromXmlTree(_pXmlUserLangDoc); }; bool getShortcutsFromXmlTree(); bool getMacrosFromXmlTree(); bool getUserCmdsFromXmlTree(); bool getPluginCmdsFromXmlTree(); bool getScintKeysFromXmlTree(); bool getSessionFromXmlTree(TiXmlDocument *pSessionDoc = NULL, Session *session = NULL); bool getBlackListFromXmlTree(); void feedGUIParameters(TiXmlNode *node); void feedKeyWordsParameters(TiXmlNode *node); void feedFileListParameters(TiXmlNode *node); void feedScintillaParam(TiXmlNode *node); void feedDockingManager(TiXmlNode *node); void feedFindHistoryParameters(TiXmlNode *node); void feedProjectPanelsParameters(TiXmlNode *node); bool feedStylerArray(TiXmlNode *node); void getAllWordStyles(TCHAR *lexerName, TiXmlNode *lexerNode); bool feedUserLang(TiXmlNode *node); int getIndexFromKeywordListName(const TCHAR *name); void feedUserStyles(TiXmlNode *node); void feedUserKeywordList(TiXmlNode *node); void feedUserSettings(TiXmlNode *node); void feedShortcut(TiXmlNode *node); void feedMacros(TiXmlNode *node); void feedUserCmds(TiXmlNode *node); void feedPluginCustomizedCmds(TiXmlNode *node); void feedScintKeys(TiXmlNode *node); bool feedBlacklist(TiXmlNode *node); void getActions(TiXmlNode *node, Macro & macro); bool getShortcuts(TiXmlNode *node, Shortcut & sc); void writeStyle2Element(Style & style2Wite, Style & style2Sync, TiXmlElement *element); void insertUserLang2Tree(TiXmlNode *node, UserLangContainer *userLang); void insertCmd(TiXmlNode *cmdRoot, const CommandShortcut & cmd); void insertMacro(TiXmlNode *macrosRoot, const MacroShortcut & macro); void insertUserCmd(TiXmlNode *userCmdRoot, const UserCommand & userCmd); void insertScintKey(TiXmlNode *scintKeyRoot, const ScintillaKeyMap & scintKeyMap); void insertPluginCmd(TiXmlNode *pluginCmdRoot, const PluginCmdShortcut & pluginCmd); void stylerStrOp(bool op); TiXmlElement * insertGUIConfigBoolNode(TiXmlNode *r2w, const TCHAR *name, bool bVal); void insertDockingParamNode(TiXmlNode *GUIRoot); void writeExcludedLangList(TiXmlElement *element); void writePrintSetting(TiXmlElement *element); void initMenuKeys(); //initialise menu keys and scintilla keys. Other keys are initialized on their own void initScintillaKeys(); //these functions have to be called first before any modifications are loaded }; #endif //PARAMETERS_H
[ "knaumova@cogniance.com" ]
knaumova@cogniance.com
9ab45aee22efad0738916b2da4974cc939ca69ad
1fd33efcea837bb2ffcd32fcdceee78e246e1414
/bird/imgsensor/sp0718_yuv_GXM2031794_1370FM_M203/hal/feature_sp0718_yuv.cpp
7c4fbc42ba9d222a2bc8b8315186e28a614a6811
[]
no_license
rock12/android_kernel_xbasic
cda1c5a956cf8afdc6b9440cefd84644e4bfd7b5
38d09253ba7ef2e7e4ba2ee7f448a04457159ddb
refs/heads/master
2021-01-17T08:38:46.441103
2016-07-01T19:36:39
2016-07-01T19:36:39
62,417,176
2
0
null
2016-07-01T20:07:19
2016-07-01T20:07:19
null
UTF-8
C++
false
false
7,997
cpp
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein * is confidential and proprietary to MediaTek Inc. and/or its licensors. * Without the prior written permission of MediaTek inc. and/or its licensors, * any reproduction, modification, use or disclosure of MediaTek Software, * and information contained herein, in whole or in part, shall be strictly prohibited. */ /* MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek Software") * have been modified by MediaTek Inc. All revisions are subject to any receiver's * applicable license agreements with MediaTek Inc. */ /******************************************************************************************** * LEGAL DISCLAIMER * * (Header of MediaTek Software/Firmware Release or Documentation) * * BY OPENING OR USING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") RECEIVED * FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON AN "AS-IS" BASIS * ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR * A PARTICULAR PURPOSE OR NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY * WHATSOEVER WITH RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK * ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO * NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S SPECIFICATION * OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM. * * BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE LIABILITY WITH * RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE * FEES OR SERVICE CHARGE PAID BY BUYER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE WITH THE LAWS * OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF LAWS PRINCIPLES. ************************************************************************************************/ /******************************************************************************* * Configuration Info * (it's needed for sensor authors to specify the following info) *******************************************************************************/ // header file name where sensor features are specified; // it is included in this source file below. #define CFG_FTBL_FILENAME "cfg_ftbl_sp0718_yuv.h" // sensor id; the same as specified in SensorList[] in sensorlist.cpp. #define SENSOR_ID SP0718_SENSOR_ID // sensor name; just for debug log now. #define SENSOR_NAME "[sp0718_yuv]" /******************************************************************************* * *******************************************************************************/ #define LOG_TAG "feature_YUV" // #include <utils/Errors.h> #include <cutils/log.h> // #define USE_CAMERA_FEATURE_MACRO 1 //define before "camera_feature.h" #include "camera_feature.h" //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Local Define //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #define TOTAL_TABLE_SCENE_NUM static_cast<MUINT32>(NSFeature::ENumOfScene) /******************************************************************************* * MACRO Define: Scene Independent *******************************************************************************/ #define GETFINFO_SCENE_INDEP() _GETFINFO_SCENE_INDEP(SENSOR_NAME) #define END_GETFINFO_SCENE_INDEP() _END_GETFINFO_SCENE_INDEP(SENSOR_NAME) /******************************************************************************* * MACRO Define: Scene Dependent *******************************************************************************/ #define GETFINFO_SCENE_DEP() _GETFINFO_SCENE_DEP(SENSOR_NAME) #define END_GETFINFO_SCENE_DEP() _END_GETFINFO_SCENE_DEP(SENSOR_NAME) /******************************************************************************* * MACRO Define: Config Scene *******************************************************************************/ #define CONFIG_SCENE(_sid) _CONFIG_SCENE(_sid, SENSOR_NAME) #define END_CONFIG_SCENE() _END_CONFIG_SCENE(SENSOR_NAME) /******************************************************************************* * MACRO Define: Config Feature *******************************************************************************/ #define CHECK_FID_SI CHECK_FID_YUV_SI #define CHECK_FID_SD CHECK_FID_YUV_SD /******************************************************************************* * Implementation of Feature Tables *******************************************************************************/ namespace { using namespace NSFeature; #include CFG_FTBL_FILENAME } static inline NSFeature::PF_GETFINFO_SCENE_INDEP_T GetFInfo_YUV_SI() { return NSYUV::NSSceneIndep::GetFInfo; } static inline NSFeature::PF_GETFINFO_SCENE_DEP_T GetFInfo_YUV_SD() { return NSYUV::NSSceneDep::GetFInfo<TOTAL_TABLE_SCENE_NUM>; } /******************************************************************************* * Implementation of class SensorInfo *******************************************************************************/ #include "camera_custom_sensor.h" #include "kd_imgsensor.h" namespace NSFeature { typedef YUVSensorInfo<SENSOR_ID> SensorInfoSingleton_T; template <> SensorInfoBase* SensorInfoSingleton_T:: GetInstance() { static SensorInfoSingleton_T singleton; return &singleton; } template <> MBOOL SensorInfoSingleton_T:: GetFeatureProvider(FeatureInfoProvider_T& rFInfoProvider) { rFInfoProvider.pfGetFInfo_SceneIndep = GetFInfo_YUV_SI(); rFInfoProvider.pfGetFInfo_SceneDep = GetFInfo_YUV_SD(); return MTRUE; } }; // NSFeature
[ "yugers@gmail.com" ]
yugers@gmail.com
4eb1e0f40293573ce35ac0043c447a2d33d185a7
61254166d90f618c834d1852d891b16260401c7c
/player.hpp
0e4a833b6ff904ee519ded54c40417f66453291c
[]
no_license
NareszcieCosSieDzieje/HangMan
808bded0cbbc4c0059fddd71797097ee0bb8e503
8c059bcf5b74dad11502a13f8d13f805568d4d38
refs/heads/master
2020-12-20T18:27:51.082667
2020-01-30T11:27:34
2020-01-30T11:27:34
236,169,665
0
0
null
null
null
null
UTF-8
C++
false
false
382
hpp
#ifndef WISIELEC_PLAYER_HPP #define WISIELEC_PLAYER_HPP #include "string" class Player { private: char* nick; char* password; public: Player(); Player(char* nick, char* password); //~Player(); char *getNick() const; void setNick(char *nick); char *getPassword() const; void setPassword(char *password); }; #endif //WISIELEC_PLAYER_HPP
[ "paulcheater@gmail.com" ]
paulcheater@gmail.com
2ee58db5b87eb2f83f25823fc8b9e6e3376ae719
134435f173060021613db0c09a68848f787fc53f
/mcl/gui/TEditBox.cpp
a9a8863b98e1ce0fbc30ecf6601e4d5e18a60c18
[ "MIT" ]
permissive
hasaranga/MCL
334410d79397c911dead06b7c8c79c0fca3c9cc7
498bb591de3467700c35b008389335c925d1f46e
refs/heads/master
2020-07-07T07:42:41.379346
2020-02-20T03:19:09
2020-02-20T03:19:09
203,294,250
1
0
null
null
null
null
UTF-8
C++
false
false
3,958
cpp
/* MCL - TEditBox.cpp Copyright (C) 2019 CrownSoft This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../mcl.h" #include "TEditBox.h" TEditBox::TEditBox() { classNameProperty.assignStaticText(TXT_WITH_LEN("EDIT")); widthProperty = 100; heightProperty = 20; leftProperty = 0; topProperty = 0; readOnlyProperty = false; onChange = nullptr; styleProperty |= WS_TABSTOP | ES_AUTOHSCROLL; extendedStyleProperty = WS_EX_CLIENTEDGE | WS_EX_WINDOWEDGE; } bool TEditBox::notifyProcHandler(TMessage& message, LRESULT& result) { if ((message.msg == WM_COMMAND) && (HIWORD(message.wParam) == EN_CHANGE)) { if (onChange) onChange(this); } return TControl::notifyProcHandler(message, result); } bool TEditBox::isReadOnly() { return readOnlyProperty; } void TEditBox::setReadOnly(bool readOnly_) { bool destroyed = false; if (handleProperty) { this->getText(); // this will update textProperty. this->destroy(); destroyed = true; } readOnlyProperty = readOnly_; if (readOnlyProperty) this->setStyle(styleProperty | ES_READONLY); else this->setStyle(styleProperty & ~ES_READONLY); if (destroyed) this->create(); } void TEditBox::setLowercaseOnly(bool lowercaseOnly_) { bool destroyed = false; if (handleProperty) { this->getText(); // this will update textProperty. this->destroy(); destroyed = true; } if (styleProperty & ES_UPPERCASE) // remove upper case style if already set styleProperty &= ~ES_UPPERCASE; if (lowercaseOnly_) this->setStyle(styleProperty | ES_LOWERCASE); else this->setStyle(styleProperty & ~ES_LOWERCASE); if (destroyed) this->create(); } void TEditBox::setUppercaseOnly(bool uppercaseOnly_) { bool destroyed = false; if (handleProperty) { this->getText(); // this will update textProperty. this->destroy(); destroyed = true; } if (styleProperty & ES_LOWERCASE) // remove lower case style if already set styleProperty &= ~ES_LOWERCASE; if (uppercaseOnly_) this->setStyle(styleProperty | ES_UPPERCASE); else this->setStyle(styleProperty & ~ES_UPPERCASE); if (destroyed) this->create(); } TString TEditBox::getText() { if(handleProperty) { const int length = ::GetWindowTextLengthW(handleProperty); if(length) { const int size = (length + 1) * sizeof(wchar_t); wchar_t* text = (wchar_t*)::malloc(size); text[0] = 0; ::GetWindowTextW(handleProperty, text, size); textProperty = TString(text, TString::FREE_TEXT_WHEN_DONE); }else { textProperty = TString(); } } return textProperty; } bool TEditBox::create() { if (!parentProperty) // user must specify parent handle! return false; isRegistered = false; // we don't want to unregister this class. ::CreateMCLComponent(this); if (handleProperty) { ::SendMessageW(handleProperty, WM_SETFONT, (WPARAM)fontProperty, MAKELPARAM(true, 0)); // set font! ::EnableWindow(handleProperty, enabledProperty ? TRUE : FALSE); ::ShowWindow(handleProperty, visibleProperty ? SW_SHOW : SW_HIDE); if (cursorProperty) ::SetClassLongPtrW(handleProperty, GCLP_HCURSOR, (LONG_PTR)cursorProperty); return true; } return false; } TEditBox::~TEditBox() { }
[ "ruchira66@gmail.com" ]
ruchira66@gmail.com
95b49fadba8d1bceae1cc6821c7061a7e9823519
b6dd9881f34c08c21e75db63f0fdc13e36f9ab3b
/ImageVision/Image/include/Template.inl
45cf3b5174be7c391b1e3bbfed7ee7dbd053ade7
[]
no_license
MSerials/SB_Check
ea5dc9941a3619ffc8f160081eec2f3c6722301f
52036f6ee333b04047f73dfbabb6bc348cefb906
refs/heads/master
2021-08-28T21:31:48.414465
2017-12-13T06:24:25
2017-12-13T06:24:25
113,969,949
1
2
null
null
null
null
GB18030
C++
false
false
30,739
inl
// Template.cpp: implementation of the CTemplate class. // ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// #include "ImgPro.h" inline CTemplate::CTemplate() { m_hParent = NULL; m_hTmp = NULL; m_pTmp = NULL; m_nRowLength = 0; m_nWidth = 0; m_nHeight = 0; m_hSubsample = NULL; m_nStepSize = 3; m_nSampleCount = 0; m_pSample = NULL; m_maxContrast = 0; m_minContrast = 255 * 255; m_upperMeanGrayScale = 0; m_lowerMeanGrayScale = 255; m_meanGrayScale = 0; m_nAngularStepSize = 3; m_pExtraction = NULL; m_nHaltonSamplesCount = 0; } inline CTemplate::~CTemplate() { Destroy(); } inline BOOL CTemplate::Create(HBITMAP hParent, const CRect rect, BOOL bInitialize) { Destroy(); if(!hParent) return FALSE; CopyParent(hParent); if(!m_hParent) return FALSE; return PrivateCreate(rect, bInitialize); } inline void CTemplate::Destroy() { if(m_hTmp) { ::DeleteObject(m_hTmp); m_hTmp = NULL; m_pTmp = NULL; } if(m_hSubsample) { ::GlobalFree(m_hSubsample); m_hSubsample = NULL; } if(m_pSample) { delete [] m_pSample; m_pSample=NULL; m_nSampleCount=0; } if(m_hParent) { ::DeleteObject(m_hParent); m_hParent = NULL; } if(m_pExtraction) { delete [] m_pExtraction; m_pExtraction = NULL; } m_nRowLength = 0; m_nWidth = 0; m_nHeight = 0; m_nStepSize = 3; m_maxContrast = 0; m_minContrast = 255 * 255; m_upperMeanGrayScale = 0; m_lowerMeanGrayScale = 255; m_meanGrayScale = 0; m_nAngularStepSize = 3; m_nHaltonSamplesCount = 0; } inline BOOL CTemplate::Rotate(const double alpha) { if(!m_hParent || !m_hTmp) return FALSE; int nWidthImg; int nHeightImg; BYTE* pByteImg; int nRowBytesImg; CBitmap cbm; BITMAP bm; cbm.Attach(m_hParent); cbm.GetBitmap(&bm); nWidthImg = bm.bmWidth; nHeightImg = bm.bmHeight; pByteImg = (BYTE*)bm.bmBits;//原图像 nRowBytesImg = ((bm.bmWidth * bm.bmBitsPixel + 31) & ~31)>>3;; cbm.Detach(); // //Template window legality check. // double halfDiagonal = sqrt(pow(m_nWidth/2.0,2)+pow(m_nHeight/2.0,2)); double leftFarX = m_rectTmp.left + m_nWidth/2 - halfDiagonal; double rightFarX = m_rectTmp.left + m_nWidth/2 + halfDiagonal; double topFarY = m_rectTmp.top + m_nHeight/2 - halfDiagonal; double bottomFarY = m_rectTmp.top + m_nHeight/2 + halfDiagonal; if(leftFarX < 0 || rightFarX > nWidthImg - 1 || topFarY < 0 || bottomFarY > nHeightImg -1) return FALSE; int xA,yA; double xAs,yAs; CPoint pointA; double r,theta; double alfa= alpha*PI/180; int left,right,top,bottom; double a,b; // for(yA=0;yA<m_nHeight;yA++) for(xA=0;xA<m_nWidth;xA++) { pointA.x=xA-m_nWidth/2; pointA.y=yA-m_nHeight/2; r=sqrt(pow((float)pointA.x,2)+pow((float)pointA.y,2)); theta=atan2((float)pointA.y,(float)pointA.x); xAs=r*cos(theta-alfa)+m_rectTmp.left+m_nWidth/2; yAs=r*sin(theta-alfa)+m_nHeight/2+m_rectTmp.top; left=(int)floor(xAs); right=(int)ceil(xAs); bottom=(int)floor(yAs); top=(int)ceil(yAs); a=top-yAs; b=xAs-left; *(m_pTmp+yA*m_nRowLength+xA)=(BYTE)(a*b*(*(pByteImg+bottom*nRowBytesImg+right))+\ b*(1-a)*(*(pByteImg+top*nRowBytesImg+right))+\ a*(1-b)*(*(pByteImg+bottom*nRowBytesImg+left))+\ (1-a)*(1-b)*(*(pByteImg+top*nRowBytesImg+left))+0.5); } return TRUE; } inline BOOL CTemplate::SubSample(int nSampleCount) { if(m_hSubsample) { ::GlobalFree(m_hSubsample); m_hSubsample = NULL; } //特征点小于60不处理 if(nSampleCount<60) return FALSE; //模板图像不存在 if(!m_hTmp) return FALSE; m_hSubsample = ::GlobalAlloc(GPTR,sizeof(HaltonSample)+(nSampleCount-1)*sizeof(HaltonPoint)); if(!m_hSubsample) return FALSE; int nWidth = m_nWidth; int nHeight = m_nHeight; HaltonSample* pHaltonSample = (HaltonSample*)m_hSubsample; pHaltonSample->hsSize = sizeof(HaltonSample); pHaltonSample->hsWidth = nWidth; pHaltonSample->hsHeight = nHeight; pHaltonSample->hsSamplePointCount = nSampleCount; int digit = 0; double halton; int i,j,n; for(n = 1 ;n <= nSampleCount ; n++) { double half = 0.5; double thirds = 1.0/3.0; halton = 0.0; i = j = n; while(i) { digit = i % 2; halton += digit*half; i = (i-digit) / 2; half /= 2.0; } pHaltonSample->hsHaltonPoints[n-1].x = (int) (halton*(nWidth-1)+0.5); halton = 0.0; while(j) { digit = j % 3; halton += digit*thirds; j = (j-digit) / 3; thirds /= 3.0; } pHaltonSample->hsHaltonPoints[n-1].y = (int) (halton*(nHeight-1)+0.5); pHaltonSample->hsHaltonPoints[n-1].nStableSize = 1; } BOOL* pbHit=new BOOL[nWidth*nHeight]; for(j=0;j<nHeight;j++) for(i=0;i<nWidth;i++) *(pbHit+j*nWidth+i)=FALSE; //标志被选择点 for(n = 0 ;n < nSampleCount ; n++) *(pbHit+pHaltonSample->hsHaltonPoints[n].y*nWidth+\ pHaltonSample->hsHaltonPoints[n].x) = TRUE; n=0; for(j=0;j<nHeight;j++) for(i=0;i<nWidth;i++) if(*(pbHit+j*nWidth+i)) { pHaltonSample->hsHaltonPoints[n].x = i; pHaltonSample->hsHaltonPoints[n].y = j; n++; //记录坐标 } delete []pbHit; return TRUE; } inline HGLOBAL CTemplate::GetSubSample() { return m_hSubsample; } inline BOOL CTemplate::Learn(const LearnPatternOptions& learnoption) { if(m_pSample) { delete [] m_pSample; m_pSample=NULL; m_nSampleCount=0; } int nUpper = 0; int nLower = 0; int nMiddle = 0; //进位截取 nUpper = (int)ceil((double)learnoption.maxAngular/(double)learnoption.finalAngularAccuracy); //去尾截取 nLower = (int)floor((double)learnoption.minAngular/(double)learnoption.finalAngularAccuracy); m_nAngularStepSize = learnoption.initialAngularAccuracy / learnoption.finalAngularAccuracy; nMiddle = (nUpper+nLower)/2; m_nSampleCount = nUpper-nLower+1;//角度分度数 //大小为角度范围*每个角度方向特征点数量 m_pSample = new double[m_nSampleCount*(learnoption.initialSampleSize+1)]; m_pExtraction = new double[learnoption.initialSampleSize];//一次特征点数据 ASSERT(m_pSample); m_nHaltonSamplesCount = learnoption.initialSampleSize;//特征点数 if(SubSample(m_nHaltonSamplesCount)==FALSE)//特征点采样 { return FALSE; }; OptimizeStepSize();//优化步长大小 HaltonSample* pHaltonSample = (HaltonSample*)m_hSubsample;//模板数据 ASSERT(pHaltonSample); ASSERT(m_pTmp); int i = nMiddle+1; int j = nLower; int k = 0;//角度统计值 while(j<=nMiddle-1) { Rotate(j*learnoption.finalAngularAccuracy);//模板旋转 *(m_pSample+(learnoption.initialSampleSize+1)*k)=j*learnoption.finalAngularAccuracy; for(int n = 0;n < pHaltonSample->hsSamplePointCount;n++) *(m_pSample+(learnoption.initialSampleSize+1)*k+n+1)=\ *(m_pTmp+m_nRowLength*pHaltonSample->hsHaltonPoints[n].y+\ pHaltonSample->hsHaltonPoints[n].x); j++; k++; } Rotate(nMiddle*learnoption.finalAngularAccuracy); *(m_pSample+(learnoption.initialSampleSize+1)*k) = nMiddle*learnoption.finalAngularAccuracy; int n; for(n = 0;n < pHaltonSample->hsSamplePointCount;n++) *(m_pSample+(learnoption.initialSampleSize+1)*k+n+1)=\ *(m_pTmp+m_nRowLength*pHaltonSample->hsHaltonPoints[n].y+\ pHaltonSample->hsHaltonPoints[n].x); k++; while(i<=nUpper) { Rotate(i*learnoption.finalAngularAccuracy); *(m_pSample+(learnoption.initialSampleSize+1)*k)=i*learnoption.finalAngularAccuracy; for(int n = 0;n < pHaltonSample->hsSamplePointCount;n++) *(m_pSample+(learnoption.initialSampleSize+1)*k+n+1)=\ *(m_pTmp+m_nRowLength*pHaltonSample->hsHaltonPoints[n].y+\ pHaltonSample->hsHaltonPoints[n].x); i++; k++; } int contrast = 0; int mean = 0; m_maxContrast = 0; m_minContrast = 255 * 255; m_upperMeanGrayScale = 0; m_lowerMeanGrayScale = 255; m_meanGrayScale = 0; for(n = 0; n < m_nSampleCount; n++) { imageNormalize(m_pSample+n*(learnoption.initialSampleSize+1)+1,\ learnoption.initialSampleSize , &contrast , &mean); m_meanGrayScale += mean; if(mean > m_upperMeanGrayScale) m_upperMeanGrayScale = mean; if(mean < m_lowerMeanGrayScale) m_lowerMeanGrayScale = mean; if(contrast > m_maxContrast) m_maxContrast = contrast; if(contrast < m_minContrast) m_minContrast = contrast; } m_meanGrayScale /= m_nSampleCount; return TRUE; } inline BOOL CTemplate::DrawSample(CDC *pDC) { if(!pDC || !m_hSubsample) return FALSE; int left,top,right,bottom; CPen bluePen; CBrush blueBrush; blueBrush.CreateSolidBrush(RGB(0,255,0)); bluePen.CreatePen(PS_SOLID,1,RGB(0,255,0)); CPen* pOldPen =(CPen*)pDC->SelectObject(&bluePen); CBrush* pOldBrush =(CBrush*)pDC->SelectObject(&blueBrush); HaltonSample* pHaltonSample = (HaltonSample*)m_hSubsample; for(int i = 0;i<pHaltonSample->hsSamplePointCount;i++) { left = m_rectTmp.left+pHaltonSample->hsHaltonPoints[i].x-2; top = m_rectTmp.bottom-pHaltonSample->hsHaltonPoints[i].y-2; right = m_rectTmp.left+pHaltonSample->hsHaltonPoints[i].x+2; bottom = m_rectTmp.bottom-pHaltonSample->hsHaltonPoints[i].y+2; pDC->Ellipse(left,top,right,bottom); } pDC->SelectObject(pOldPen); pDC->SelectObject(pOldBrush); return TRUE; } inline BOOL imageNormalize(double *pVector, const int nCount , int* const pContrast , int* const pMean) { ASSERT(pVector && nCount>0); double sumVector = 0.0; double sumsqVector = 0.0; double temp = 0.0; int i=0; for(i=0;i<nCount;i++) { temp = *(pVector+i); sumVector += temp; sumsqVector += temp*temp; } sumVector /= nCount; if(pMean) *pMean = (int)sumVector; sumsqVector -= (nCount*sumVector*sumVector); sumsqVector = sqrt(sumsqVector); if(pContrast) *pContrast = (int)sumsqVector; if(sumsqVector == 0.0) { for(i=0;i<nCount;i++) *(pVector+i) = 0; } else { for(i=0;i<nCount;i++) *(pVector+i) = (*(pVector+i) - sumVector)/sumsqVector; } return TRUE; } inline int CTemplate::GetStepSize() { return m_nStepSize; } inline int CTemplate::GetAngularStepSize() { return m_nAngularStepSize; } inline void CTemplate::OptimizeStepSize() { HaltonSample* pHaltonSample = (HaltonSample*)m_hSubsample; int nSampleCount = pHaltonSample->hsSamplePointCount; HaltonSample* pHaltonSampleCopy = (HaltonSample*)::GlobalAlloc(GPTR,\ sizeof(HaltonSample)+(nSampleCount-1)*sizeof(HaltonPoint)); int minX = pHaltonSample->hsWidth - 1; int maxX = 0; int minY = pHaltonSample->hsHeight - 1; int maxY = 0; int n = 0; for(n = 0 ; n < nSampleCount ; n++) { if(pHaltonSample->hsHaltonPoints[n].x < minX) minX = pHaltonSample->hsHaltonPoints[n].x; if(pHaltonSample->hsHaltonPoints[n].x > maxX) maxX = pHaltonSample->hsHaltonPoints[n].x; if(pHaltonSample->hsHaltonPoints[n].y < minY) minY = pHaltonSample->hsHaltonPoints[n].y; if(pHaltonSample->hsHaltonPoints[n].y > maxY) maxY = pHaltonSample->hsHaltonPoints[n].y; } int lowerOffsetX = 0 - minX; int upperOffsetX = pHaltonSample->hsWidth - 1 - maxX; int lowerOffsetY = 0 - minY; int upperOffsetY = pHaltonSample->hsHeight - 1 - maxY; int mostStableXOffset = 0; int mostStableYOffset = 0; int nMaxStepSize = 1; int nStepSize = 1; for(int j = lowerOffsetY ; j <=upperOffsetY ; j++) for(int i = lowerOffsetX ; i <= upperOffsetX ; i++) { ::CopyMemory(pHaltonSampleCopy , pHaltonSample , \ sizeof(HaltonSample)+(nSampleCount-1)*sizeof(HaltonPoint)); OffsetSample(pHaltonSampleCopy , i , j); CalcStableSize(pHaltonSampleCopy , 10); nStepSize = CalcStepSize(pHaltonSampleCopy); if(nStepSize > nMaxStepSize){ nMaxStepSize = nStepSize; mostStableXOffset = i; mostStableYOffset = j; } } if(nMaxStepSize >= 3){ m_nStepSize = nMaxStepSize; OffsetSample(pHaltonSample , mostStableXOffset , mostStableYOffset); CalcStableSize(pHaltonSample , 10); } if(pHaltonSampleCopy) ::GlobalFree(pHaltonSampleCopy); } inline void CTemplate::CalcStableSize(HaltonSample * const pHaltonSample, int nNoiseLevel) { // //Get information of the image. // CBitmap cbm; BITMAP bm; cbm.Attach(m_hParent); cbm.GetBitmap(&bm); int nImageWidth = bm.bmWidth; int nImageHeight = bm.bmHeight; int nImageRowLength = ((bm.bmWidth * bm.bmBitsPixel + 31) & ~31)>>3; BYTE* pImage = (BYTE*)bm.bmBits; cbm.Detach(); // //Calculate template bottom left coordinates // int left = m_rectTmp.left; int bottom = nImageHeight - m_rectTmp.bottom - 1; int n = 0; int xCenter = 0; int yCenter = 0; int xStart = 0; int yStart = 0; int xEnd = 0; int yEnd = 0; int nMaxNoise = 0; int nNoise = 0; int x = 0; int y = 0; // //Calculate the stable size in 3X3,5X5 and 7X7 neighborhood // for(n = 0 ; n < pHaltonSample->hsSamplePointCount ; n++) { xCenter = left + pHaltonSample->hsHaltonPoints[n].x; yCenter = bottom + pHaltonSample->hsHaltonPoints[n].y; // //Check if the pixel intensity value is stable in 3X3 neighborhood. // xStart = max(xCenter - 1 , 0); yStart = max(yCenter - 1 , 0); xEnd = min(xCenter + 1 , nImageWidth - 1); yEnd = min(yCenter + 1 , nImageHeight - 1); // //Calculate pixel's (xCenter , yCenter) maximum noise in 3X3 neighborhood. // nMaxNoise = 0; for(y = yStart ; y <= yEnd ; y++) for(x = xStart ; x <= xEnd ; x++) { nNoise = abs(pImage[y * nImageRowLength + x] -\ pImage[yCenter * nImageRowLength + xCenter]); if(nNoise > nMaxNoise) nMaxNoise = nNoise; } if(nMaxNoise < nNoiseLevel){ pHaltonSample->hsHaltonPoints[n].nStableSize = 3; } else continue; // //Check if the pixel intensity value is stable in 5X5 neighborhood. // xStart = max(xCenter - 2 , 0); yStart = max(yCenter - 2 , 0); xEnd = min(xCenter + 2 , nImageWidth - 1); yEnd = min(yCenter + 2 , nImageHeight - 1); // //Calculate pixel's (xCenter , yCenter) maximum noise in 5X5 neighborhood. // nMaxNoise = 0; for(y = yStart ; y <= yEnd ; y++) for(x = xStart ; x <= xEnd ; x++) { nNoise = abs(pImage[y * nImageRowLength + x] -\ pImage[yCenter * nImageRowLength + xCenter]); if(nNoise > nMaxNoise) nMaxNoise = nNoise; } if(nMaxNoise < nNoiseLevel){ pHaltonSample->hsHaltonPoints[n].nStableSize = 5; } else continue; // //Check if the pixel intensity value is stable in 7X7 neighborhood. // xStart = max(xCenter - 3 , 0); yStart = max(yCenter - 3 , 0); xEnd = min(xCenter + 3 , nImageWidth - 1); yEnd = min(yCenter + 3 , nImageHeight - 1); // //Calculate pixel's (xCenter , yCenter) maximum noise in 7X7 neighborhood. // nMaxNoise = 0; for(y = yStart ; y <= yEnd ; y++) for(x = xStart ; x <= xEnd ; x++) { nNoise = abs(pImage[y * nImageRowLength + x] -\ pImage[yCenter * nImageRowLength + xCenter]); if(nNoise > nMaxNoise) nMaxNoise = nNoise; } if(nMaxNoise < nNoiseLevel){ pHaltonSample->hsHaltonPoints[n].nStableSize = 7; } else continue; } } inline int CTemplate::CalcStepSize(HaltonSample *pHaltonSample) { int n1Stable = 0; int n3Stable = 0; int n5Stable = 0; int n7Stable = 0; int nUnknown = 0; for(int n = 0 ; n < pHaltonSample->hsSamplePointCount ; n++) { switch(pHaltonSample->hsHaltonPoints[n].nStableSize) { case 7: n7Stable++; break; case 5: n5Stable++; break; case 3: n3Stable++; break; case 1: n1Stable++; break; default: nUnknown++; } } ASSERT(nUnknown == 0); float rate = (float)n7Stable / (float)pHaltonSample->hsSamplePointCount; if(rate > 0.8) return 7; rate = (float)n5Stable / (float)pHaltonSample->hsSamplePointCount; if(rate > 0.8) return 5; rate = (float)n3Stable / (float)pHaltonSample->hsSamplePointCount; if(rate > 0.8) return 3; return 1; } inline void CTemplate::OffsetSample(HaltonSample* const pHaltonSample , const int xOffset , const int yOffset) { for(int n = 0 ; n < pHaltonSample->hsSamplePointCount ; n++) { pHaltonSample->hsHaltonPoints[n].x += xOffset; pHaltonSample->hsHaltonPoints[n].y += yOffset; } } inline void CTemplate::CopyParent(HBITMAP hParentBitmap) { if(m_hParent) { ::DeleteObject(m_hParent); m_hParent = NULL; } ASSERT(hParentBitmap); CBitmap cbm; BITMAP bm; cbm.Attach(hParentBitmap); cbm.GetBitmap(&bm); cbm.Detach(); int nParentWidth = bm.bmWidth; int nParentHeight = bm.bmHeight; int nParentRowLength = ((bm.bmWidth * bm.bmBitsPixel + 31) & ~31)>>3; int nParentBitCount = bm.bmBitsPixel; BYTE* pParent = (BYTE*)bm.bmBits; BITMAPINFO* pParentBmi = (BITMAPINFO*) new BYTE[sizeof(BITMAPINFO) + 255*sizeof(RGBQUAD)]; pParentBmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); pParentBmi->bmiHeader.biWidth = nParentWidth; pParentBmi->bmiHeader.biHeight = nParentHeight; pParentBmi->bmiHeader.biPlanes = 1; pParentBmi->bmiHeader.biBitCount = nParentBitCount; pParentBmi->bmiHeader.biCompression = BI_RGB; pParentBmi->bmiHeader.biSizeImage = nParentRowLength * nParentHeight; pParentBmi->bmiHeader.biXPelsPerMeter = 0; pParentBmi->bmiHeader.biYPelsPerMeter = 0; pParentBmi->bmiHeader.biClrUsed = 0; pParentBmi->bmiHeader.biClrImportant = 0; for(int i = 0 ;i < 256 ; i++) { pParentBmi->bmiColors[i].rgbBlue = i; pParentBmi->bmiColors[i].rgbGreen = i; pParentBmi->bmiColors[i].rgbRed = i; pParentBmi->bmiColors[i].rgbReserved = 0; } BYTE* pParentCopy; m_hParent = ::CreateDIBSection(NULL,pParentBmi,DIB_RGB_COLORS,(void**)&pParentCopy,NULL,0); if(m_hParent) ::CopyMemory(pParentCopy , pParent , pParentBmi->bmiHeader.biSizeImage); delete [] pParentBmi; } inline void CTemplate::CopyParent(BYTE *pParent, int nWidth, int nHeight, int nBitCount, int nRowLength) { if(m_hParent) { ::DeleteObject(m_hParent); m_hParent = NULL; } ASSERT(pParent); int nParentWidth = nWidth; int nParentHeight = nHeight; int nParentRowLength = ((nWidth * nBitCount + 31) & ~31)>>3; int nParentBitCount = nBitCount; BITMAPINFO* pParentBmi = (BITMAPINFO*) new BYTE[sizeof(BITMAPINFO) + 255*sizeof(RGBQUAD)]; pParentBmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); pParentBmi->bmiHeader.biWidth = nParentWidth; pParentBmi->bmiHeader.biHeight = nParentHeight; pParentBmi->bmiHeader.biPlanes = 1; pParentBmi->bmiHeader.biBitCount = nParentBitCount; pParentBmi->bmiHeader.biCompression = BI_RGB; pParentBmi->bmiHeader.biSizeImage = nParentRowLength * nParentHeight; pParentBmi->bmiHeader.biXPelsPerMeter = 0; pParentBmi->bmiHeader.biYPelsPerMeter = 0; pParentBmi->bmiHeader.biClrUsed = 0; pParentBmi->bmiHeader.biClrImportant = 0; for(int i = 0 ;i < 256 ; i++) { pParentBmi->bmiColors[i].rgbBlue = i; pParentBmi->bmiColors[i].rgbGreen = i; pParentBmi->bmiColors[i].rgbRed = i; pParentBmi->bmiColors[i].rgbReserved = 0; } BYTE* pParentCopy; m_hParent = ::CreateDIBSection(NULL,pParentBmi,DIB_RGB_COLORS,(void**)&pParentCopy,NULL,0); if(m_hParent) { for(int n = 0 ; n < nParentHeight ; n++) ::CopyMemory(pParentCopy + n * nParentRowLength , pParent + n * nRowLength , nRowLength); } delete [] pParentBmi; } inline BOOL CTemplate::Create(BYTE *pParent, int nWidth, int nHeight, int nBitCount, int nRowLength, CRect rect, BOOL bInitialize) { Destroy(); if(!pParent) return FALSE; CopyParent(pParent , nWidth , nHeight , nBitCount , nRowLength); if(!m_hParent) return FALSE; return PrivateCreate(rect, bInitialize); } inline BOOL CTemplate::PrivateCreate(const CRect rect, BOOL bInitialize) { m_rectTmp = rect; m_nWidth = rect.Width()+1; m_nHeight = rect.Height()+1; m_nRowLength = ((m_nWidth * 8 + 31) & ~31)>>3; BITMAPINFO* pTmpBmi = (BITMAPINFO*) new BYTE[sizeof(BITMAPINFO) + 255*sizeof(RGBQUAD)]; pTmpBmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); pTmpBmi->bmiHeader.biWidth = m_nWidth; pTmpBmi->bmiHeader.biHeight = m_nHeight; pTmpBmi->bmiHeader.biPlanes = 1; pTmpBmi->bmiHeader.biBitCount = 8; pTmpBmi->bmiHeader.biCompression = BI_RGB; pTmpBmi->bmiHeader.biSizeImage = m_nRowLength * m_nHeight; pTmpBmi->bmiHeader.biXPelsPerMeter = 0; pTmpBmi->bmiHeader.biYPelsPerMeter = 0; pTmpBmi->bmiHeader.biClrUsed = 0; pTmpBmi->bmiHeader.biClrImportant = 0; int i; for(i = 0 ;i < 256 ; i++) { pTmpBmi->bmiColors[i].rgbBlue = i; pTmpBmi->bmiColors[i].rgbGreen = i; pTmpBmi->bmiColors[i].rgbRed = i; pTmpBmi->bmiColors[i].rgbReserved = 0; } m_hTmp = ::CreateDIBSection(NULL,pTmpBmi,DIB_RGB_COLORS,(void**)&m_pTmp,NULL,0); if(m_hTmp == NULL) { delete [] pTmpBmi; Destroy(); return FALSE; } CBitmap cbm; BITMAP bm; cbm.Attach(m_hParent); cbm.GetBitmap(&bm); int xStart = rect.left; int xEnd = rect.right; int yStart = rect.top; int yEnd = rect.bottom; if(xStart<0||xEnd>bm.bmWidth-1||yStart<0||yEnd>bm.bmHeight-1) { AfxMessageBox(_T("Template selection window out of image border")); delete [] pTmpBmi; Destroy(); cbm.Detach(); return FALSE; } int x,y,j; if(bInitialize) { BYTE* pBits = (BYTE*)bm.bmBits; long nRowLength = ((bm.bmWidth * bm.bmBitsPixel + 31) & ~31)>>3; for(y=yStart,j=0;y<=yEnd;y++,j++) for(x=xStart,i=0;x<=xEnd;x++,i++) *(m_pTmp+m_nRowLength*j+i)=*(pBits+y*nRowLength+x*(bm.bmBitsPixel/8)); } delete [] pTmpBmi; cbm.Detach(); return TRUE; } inline double* CTemplate::GetExtractionBuffer() { return m_pExtraction; } inline BOOL CTemplate::Save(LPCTSTR lpszFileName) { HaltonSample* pHaltonSample = (HaltonSample*)m_hSubsample; if(!m_pSample || !pHaltonSample || !m_hTmp || !m_hParent) return FALSE; CFile templateFile; CFileException ex; if(!templateFile.Open(lpszFileName , CFile::modeCreate | CFile::modeWrite |\ CFile::modeNoInherit | CFile::shareExclusive , &ex)) { CString strError; TCHAR szError[1024]; ex.GetErrorMessage(szError, 1024); strError = _T("Couldn't create template file: "); strError += szError; return FALSE; } // //Save template width. // templateFile.Write(&m_nWidth , sizeof(int)); // //Save template height. // templateFile.Write(&m_nHeight , sizeof(int)); // //Save template rect relative to source image. // templateFile.Write(&m_rectTmp.left , sizeof(int)); templateFile.Write(&m_rectTmp.top , sizeof(int)); templateFile.Write(&m_rectTmp.right , sizeof(int)); templateFile.Write(&m_rectTmp.bottom , sizeof(int)); // //Save template row length // templateFile.Write(&m_nRowLength , sizeof(int)); // //Save template mean gray scale. // templateFile.Write(&m_meanGrayScale , sizeof(int)); // //Save template lower mean gray scale. // templateFile.Write(&m_lowerMeanGrayScale , sizeof(int)); // //Save template upper mean gray scale. // templateFile.Write(&m_upperMeanGrayScale , sizeof(int)); // //Save template minimum contrast. // templateFile.Write(&m_minContrast , sizeof(int)); // //Save template maximum contrast. // templateFile.Write(&m_maxContrast , sizeof(int)); // //Save angular step size. // templateFile.Write(&m_nAngularStepSize , sizeof(int)); // //Save translation step size. // templateFile.Write(&m_nStepSize , sizeof(int)); // //Save Halton samples count. // templateFile.Write(&m_nHaltonSamplesCount , sizeof(int)); // //Save Halton samples structure. // templateFile.Write(pHaltonSample , sizeof(HaltonSample) + \ (m_nHaltonSamplesCount - 1) * sizeof(HaltonPoint)); // //Save template samples population count // templateFile.Write(&m_nSampleCount , sizeof(int)); // //Save template samples population // templateFile.Write(m_pSample , (m_nSampleCount * \ (m_nHaltonSamplesCount + 1)) * sizeof(double)); templateFile.Flush(); templateFile.Close(); return TRUE; } inline BOOL CTemplate::Load(LPCTSTR lpszFileName) { Destroy(); CFile templateFile; CFileException ex; if(!templateFile.Open(lpszFileName , CFile::modeRead |\ CFile::modeNoInherit | CFile::shareExclusive , &ex)) { CString strError; TCHAR szError[1024]; ex.GetErrorMessage(szError, 1024); strError = _T("Couldn't open template file: "); strError += szError; return FALSE; } // //Load template width. // templateFile.Read(&m_nWidth , sizeof(int)); // //Load template height. // templateFile.Read(&m_nHeight , sizeof(int)); // //Load template rect relative to source image. // templateFile.Read(&m_rectTmp.left , sizeof(int)); templateFile.Read(&m_rectTmp.top , sizeof(int)); templateFile.Read(&m_rectTmp.right , sizeof(int)); templateFile.Read(&m_rectTmp.bottom , sizeof(int)); // //Load template row length // templateFile.Read(&m_nRowLength , sizeof(int)); // //Load template mean gray scale. // templateFile.Read(&m_meanGrayScale , sizeof(int)); // //Load template lower mean gray scale. // templateFile.Read(&m_lowerMeanGrayScale , sizeof(int)); // //Load template upper mean gray scale. // templateFile.Read(&m_upperMeanGrayScale , sizeof(int)); // //Load template minimum contrast. // templateFile.Read(&m_minContrast , sizeof(int)); // //Load template maximum contrast. // templateFile.Read(&m_maxContrast , sizeof(int)); // //Load angular step size. // templateFile.Read(&m_nAngularStepSize , sizeof(int)); // //Load translation step size. // templateFile.Read(&m_nStepSize , sizeof(int)); // //Load Halton samples count. // templateFile.Read(&m_nHaltonSamplesCount , sizeof(int)); // //Load Halton samples structure. // m_hSubsample = ::GlobalAlloc(GPTR,\ sizeof(HaltonSample) + (m_nHaltonSamplesCount - 1) * sizeof(HaltonPoint)); if(!m_hSubsample) { Destroy(); return FALSE; } ::ZeroMemory(m_hSubsample ,\ sizeof(HaltonSample) + (m_nHaltonSamplesCount - 1) * sizeof(HaltonPoint)); templateFile.Read(m_hSubsample ,\ sizeof(HaltonSample) + (m_nHaltonSamplesCount - 1) * sizeof(HaltonPoint)); // //Load template samples population count // templateFile.Read(&m_nSampleCount , sizeof(int)); // //Load template samples population // m_pSample = new double[m_nSampleCount*(m_nHaltonSamplesCount+1)]; m_pExtraction = new double[m_nHaltonSamplesCount]; if(!m_pSample || !m_pExtraction) { Destroy(); return FALSE; } ::ZeroMemory(m_pSample , \ (m_nSampleCount * (m_nHaltonSamplesCount + 1)) * sizeof(double)); templateFile.Read(m_pSample , (m_nSampleCount * \ (m_nHaltonSamplesCount + 1)) * sizeof(double)); templateFile.Close(); return TRUE; } inline void CTemplate::KillParent() { if(m_hParent) { ::DeleteObject(m_hParent); m_hParent = NULL; } } inline BOOL CTemplate::imageNormalize(double *pVector, const int nCount , int* const pContrast , int* const pMean) { ASSERT(pVector && nCount>0); double sumVector = 0.0; double sumsqVector = 0.0; double temp = 0.0; int i=0; for(i=0;i<nCount;i++) { temp = *(pVector+i); sumVector += temp; sumsqVector += temp*temp; } //求和与平方和 sumVector /= nCount; if(pMean) *pMean = (int)sumVector;//平均值 sumsqVector -= (nCount*sumVector*sumVector);//平方和与均值平方和之差 sumsqVector = sqrt(sumsqVector);//开方 if(pContrast) *pContrast = (int)sumsqVector; if(sumsqVector == 0.0) { for(i=0;i<nCount;i++) *(pVector+i) = 0;//归一化 } else { for(i=0;i<nCount;i++) *(pVector+i) = (*(pVector+i) - sumVector)/sumsqVector;//归一化 } return TRUE; } inline BOOL SaveMatchPattern(LONG m_lHeight,LONG m_lWidth,LPBYTE m_lpBits,CRect rectTmp,int nCommand, CTemplate &m_objTemplate) { CString szPath; CString szPathTemp; BOOL bSaveOK=TRUE; //获得当前程序的全路径 GetModuleFileName(NULL,szPath.GetBufferSetLength (MAX_PATH+1),MAX_PATH); szPath.ReleaseBuffer(); int nPos; nPos=szPath.ReverseFind ('\\'); szPath=szPath.Left (nPos); szPath=szPath+L"\\"; int nImageWidth=m_lWidth; int nImageHeight=m_lHeight; if(rectTmp.Width()%2) rectTmp.right += 1; if(rectTmp.Height()%2) rectTmp.bottom += 1; int imageRowLength = ((nImageWidth * 8 + 31) & ~31)>>3; if(m_objTemplate.Create(m_lpBits,nImageWidth,nImageHeight,8,imageRowLength,rectTmp,FALSE)) { LearnPatternOptions lo; lo.bLearnForRotation = TRUE; lo.finalAngularAccuracy = 1; lo.initialAngularAccuracy = 3; lo.initialSampleSize = 480; lo.finalSampleSize =960; lo.initialStepSize = 3; lo.maxAngular = 180; lo.minAngular = 0; if(m_objTemplate.Learn(lo)) { AfxMessageBox(_T("Learn template successfully")); } else { AfxMessageBox(_T("Learn template failed")); bSaveOK=FALSE; } } else { AfxMessageBox(_T("Create template failed")); bSaveOK=FALSE; } szPathTemp.Format(L"Template%d.dat",nCommand); szPath=szPath+szPathTemp; if(m_objTemplate.Save(szPath)) AfxMessageBox(L"Template Saved Successfully!",MB_OK); else { AfxMessageBox(L"Template Saved Failed!",MB_OK); bSaveOK=FALSE; } return bSaveOK; } inline BOOL FindMatchPattern(LONG m_lHeight,LONG m_lWidth,LPBYTE m_lpBits,int nCommand, CRect SearchRect, MatchPatternOptions m_options,PatternMatch &m_PatternMatch) { CString szPath; CString szPathTemp; BOOL bFindMatchPattern=FALSE; double dMatchRate=0;//pDoc->m_objParameter.list.list0.match.m_iMatchRate; double dRate=0.0; CTemplate m_objTemplate; CImgPro m_objImageProc(m_lpBits,m_lWidth,m_lHeight); GetModuleFileName(NULL,szPath.GetBufferSetLength (MAX_PATH+1),MAX_PATH); szPath.ReleaseBuffer(); int nPos; nPos=szPath.ReverseFind ('\\'); szPath=szPath.Left (nPos); szPath=szPath+L"\\"; szPathTemp.Format(L"Template%d.dat",nCommand); //读取模板数据 BOOL bb=m_objTemplate.Load(szPath+szPathTemp); if(!bb) { AfxMessageBox(L"Load temp error!"); return FALSE; } m_options.size = sizeof(MatchPatternOptions); m_options.initialStepSize = 0; m_options.minMatchScore = -1; int nImageWidth=m_lWidth; int nImageHeight=m_lHeight; int nImageRowLength = ((nImageWidth * 8 + 31) & ~31)>>3; bFindMatchPattern=m_objImageProc.imageMatchPattern(m_lpBits, nImageWidth, nImageHeight, nImageRowLength, m_objTemplate, m_options, SearchRect, &m_PatternMatch, NULL); // delete [] m_pImageTemp; return bFindMatchPattern; }
[ "lux@DESKTOP-2SN49A7" ]
lux@DESKTOP-2SN49A7
b42aa0e510dc4cdccd3427ec166783ad1c986734
73ee941896043f9b3e2ab40028d24ddd202f695f
/external/chromium_org/dbus/bus.h
2e6db70174c6fade7a56a0057d6eff24f1ab6990
[ "BSD-3-Clause" ]
permissive
CyFI-Lab-Public/RetroScope
d441ea28b33aceeb9888c330a54b033cd7d48b05
276b5b03d63f49235db74f2c501057abb9e79d89
refs/heads/master
2022-04-08T23:11:44.482107
2016-09-22T20:15:43
2016-09-22T20:15:43
58,890,600
5
3
null
null
null
null
UTF-8
C++
false
false
30,214
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef DBUS_BUS_H_ #define DBUS_BUS_H_ #include <dbus/dbus.h> #include <map> #include <set> #include <string> #include <utility> #include <vector> #include "base/callback.h" #include "base/memory/ref_counted.h" #include "base/synchronization/waitable_event.h" #include "base/threading/platform_thread.h" #include "dbus/dbus_export.h" #include "dbus/object_path.h" namespace base { class SequencedTaskRunner; class SingleThreadTaskRunner; } namespace tracked_objects { class Location; } namespace dbus { class ExportedObject; class ObjectManager; class ObjectProxy; // Bus is used to establish a connection with D-Bus, create object // proxies, and export objects. // // For asynchronous operations such as an asynchronous method call, the // bus object will use a task runner to monitor the underlying file // descriptor used for D-Bus communication. By default, the bus will use // the current thread's task runner. If |dbus_task_runner| option is // specified, the bus will use that task runner instead. // // THREADING // // In the D-Bus library, we use the two threads: // // - The origin thread: the thread that created the Bus object. // - The D-Bus thread: the thread servicing |dbus_task_runner|. // // The origin thread is usually Chrome's UI thread. The D-Bus thread is // usually a dedicated thread for the D-Bus library. // // BLOCKING CALLS // // Functions that issue blocking calls are marked "BLOCKING CALL" and // these functions should be called in the D-Bus thread (if // supplied). AssertOnDBusThread() is placed in these functions. // // Note that it's hard to tell if a libdbus function is actually blocking // or not (ex. dbus_bus_request_name() internally calls // dbus_connection_send_with_reply_and_block(), which is a blocking // call). To err on the safe side, we consider all libdbus functions that // deal with the connection to dbus-daemon to be blocking. // // SHUTDOWN // // The Bus object must be shut down manually by ShutdownAndBlock() and // friends. We require the manual shutdown to make the operation explicit // rather than doing it silently in the destructor. // // EXAMPLE USAGE: // // Synchronous method call: // // dbus::Bus::Options options; // // Set up the bus options here. // ... // dbus::Bus bus(options); // // dbus::ObjectProxy* object_proxy = // bus.GetObjectProxy(service_name, object_path); // // dbus::MethodCall method_call(interface_name, method_name); // scoped_ptr<dbus::Response> response( // object_proxy.CallMethodAndBlock(&method_call, timeout_ms)); // if (response.get() != NULL) { // Success. // ... // } // // Asynchronous method call: // // void OnResponse(dbus::Response* response) { // // response is NULL if the method call failed. // if (!response) // return; // } // // ... // object_proxy.CallMethod(&method_call, timeout_ms, // base::Bind(&OnResponse)); // // Exporting a method: // // void Echo(dbus::MethodCall* method_call, // dbus::ExportedObject::ResponseSender response_sender) { // // Do something with method_call. // Response* response = Response::FromMethodCall(method_call); // // Build response here. // // Can send an immediate response here to implement a synchronous service // // or store the response_sender and send a response later to implement an // // asynchronous service. // response_sender.Run(response); // } // // void OnExported(const std::string& interface_name, // const ObjectPath& object_path, // bool success) { // // success is true if the method was exported successfully. // } // // ... // dbus::ExportedObject* exported_object = // bus.GetExportedObject(service_name, object_path); // exported_object.ExportMethod(interface_name, method_name, // base::Bind(&Echo), // base::Bind(&OnExported)); // // WHY IS THIS A REF COUNTED OBJECT? // // Bus is a ref counted object, to ensure that |this| of the object is // alive when callbacks referencing |this| are called. However, after the // bus is shut down, |connection_| can be NULL. Hence, callbacks should // not rely on that |connection_| is alive. class CHROME_DBUS_EXPORT Bus : public base::RefCountedThreadSafe<Bus> { public: // Specifies the bus type. SESSION is used to communicate with per-user // services like GNOME applications. SYSTEM is used to communicate with // system-wide services like NetworkManager. CUSTOM_ADDRESS is used to // communicate with an user specified address. enum BusType { SESSION = DBUS_BUS_SESSION, SYSTEM = DBUS_BUS_SYSTEM, CUSTOM_ADDRESS, }; // Specifies the connection type. PRIVATE should usually be used unless // you are sure that SHARED is safe for you, which is unlikely the case // in Chrome. // // PRIVATE gives you a private connection, that won't be shared with // other Bus objects. // // SHARED gives you a connection shared among other Bus objects, which // is unsafe if the connection is shared with multiple threads. enum ConnectionType { PRIVATE, SHARED, }; // Specifies whether the GetServiceOwnerAndBlock call should report or // suppress errors. enum GetServiceOwnerOption { REPORT_ERRORS, SUPPRESS_ERRORS, }; // Specifies service ownership options. // // REQUIRE_PRIMARY indicates that you require primary ownership of the // service name. // // ALLOW_REPLACEMENT indicates that you'll allow another connection to // steal ownership of this service name from you. // // REQUIRE_PRIMARY_ALLOW_REPLACEMENT does the obvious. enum ServiceOwnershipOptions { REQUIRE_PRIMARY = (DBUS_NAME_FLAG_DO_NOT_QUEUE | DBUS_NAME_FLAG_REPLACE_EXISTING), REQUIRE_PRIMARY_ALLOW_REPLACEMENT = (REQUIRE_PRIMARY | DBUS_NAME_FLAG_ALLOW_REPLACEMENT), }; // Options used to create a Bus object. struct CHROME_DBUS_EXPORT Options { Options(); ~Options(); BusType bus_type; // SESSION by default. ConnectionType connection_type; // PRIVATE by default. // If dbus_task_runner is set, the bus object will use that // task runner to process asynchronous operations. // // The thread servicing the task runner should meet the following // requirements: // 1) Already running. // 2) Has a MessageLoopForIO. scoped_refptr<base::SequencedTaskRunner> dbus_task_runner; // Specifies the server addresses to be connected. If you want to // communicate with non dbus-daemon such as ibus-daemon, set |bus_type| to // CUSTOM_ADDRESS, and |address| to the D-Bus server address you want to // connect to. The format of this address value is the dbus address style // which is described in // http://dbus.freedesktop.org/doc/dbus-specification.html#addresses // // EXAMPLE USAGE: // dbus::Bus::Options options; // options.bus_type = CUSTOM_ADDRESS; // options.address.assign("unix:path=/tmp/dbus-XXXXXXX"); // // Set up other options // dbus::Bus bus(options); // // // Do something. // std::string address; // If the connection with dbus-daemon is closed, |disconnected_callback| // will be called on the origin thread. This is also called when the // disonnection by ShutdownAndBlock. |disconnected_callback| can be null // callback base::Closure disconnected_callback; }; // Creates a Bus object. The actual connection will be established when // Connect() is called. explicit Bus(const Options& options); // Called when an ownership request is complete. // Parameters: // - the requested service name. // - whether ownership has been obtained or not. typedef base::Callback<void (const std::string&, bool)> OnOwnershipCallback; // Called when GetServiceOwner() completes. // |service_owner| is the return value from GetServiceOwnerAndBlock(). typedef base::Callback<void (const std::string& service_owner)> GetServiceOwnerCallback; // TODO(satorux): Remove the service name parameter as the caller of // RequestOwnership() knows the service name. // Gets the object proxy for the given service name and the object path. // The caller must not delete the returned object. // // Returns an existing object proxy if the bus object already owns the // object proxy for the given service name and the object path. // Never returns NULL. // // The bus will own all object proxies created by the bus, to ensure // that the object proxies are detached from remote objects at the // shutdown time of the bus. // // The object proxy is used to call methods of remote objects, and // receive signals from them. // // |service_name| looks like "org.freedesktop.NetworkManager", and // |object_path| looks like "/org/freedesktop/NetworkManager/Devices/0". // // Must be called in the origin thread. virtual ObjectProxy* GetObjectProxy(const std::string& service_name, const ObjectPath& object_path); // Same as above, but also takes a bitfield of ObjectProxy::Options. // See object_proxy.h for available options. virtual ObjectProxy* GetObjectProxyWithOptions( const std::string& service_name, const ObjectPath& object_path, int options); // Removes the previously created object proxy for the given service // name and the object path and releases its memory. // // If and object proxy for the given service name and object was // created with GetObjectProxy, this function removes it from the // bus object and detaches the ObjectProxy, invalidating any pointer // previously acquired for it with GetObjectProxy. A subsequent call // to GetObjectProxy will return a new object. // // All the object proxies are detached from remote objects at the // shutdown time of the bus, but they can be detached early to reduce // memory footprint and used match rules for the bus connection. // // |service_name| looks like "org.freedesktop.NetworkManager", and // |object_path| looks like "/org/freedesktop/NetworkManager/Devices/0". // |callback| is called when the object proxy is successfully removed and // detached. // // The function returns true when there is an object proxy matching the // |service_name| and |object_path| to remove, and calls |callback| when it // is removed. Otherwise, it returns false and the |callback| function is // never called. The |callback| argument must not be null. // // Must be called in the origin thread. virtual bool RemoveObjectProxy(const std::string& service_name, const ObjectPath& object_path, const base::Closure& callback); // Same as above, but also takes a bitfield of ObjectProxy::Options. // See object_proxy.h for available options. virtual bool RemoveObjectProxyWithOptions( const std::string& service_name, const ObjectPath& object_path, int options, const base::Closure& callback); // Gets the exported object for the given object path. // The caller must not delete the returned object. // // Returns an existing exported object if the bus object already owns // the exported object for the given object path. Never returns NULL. // // The bus will own all exported objects created by the bus, to ensure // that the exported objects are unregistered at the shutdown time of // the bus. // // The exported object is used to export methods of local objects, and // send signal from them. // // Must be called in the origin thread. virtual ExportedObject* GetExportedObject(const ObjectPath& object_path); // Unregisters the exported object for the given object path |object_path|. // // Getting an exported object for the same object path after this call // will return a new object, method calls on any remaining copies of the // previous object will not be called. // // Must be called in the origin thread. virtual void UnregisterExportedObject(const ObjectPath& object_path); // Gets an object manager for the given remote object path |object_path| // exported by the service |service_name|. // // Returns an existing object manager if the bus object already owns a // matching object manager, never returns NULL. // // The caller must not delete the returned object, the bus retains ownership // of all object managers. // // Must be called in the origin thread. virtual ObjectManager* GetObjectManager(const std::string& service_name, const ObjectPath& object_path); // Unregisters the object manager for the given remote object path // |object_path| exported by the srevice |service_name|. // // Getting an object manager for the same remote object after this call // will return a new object, method calls on any remaining copies of the // previous object are not permitted. // // Must be called in the origin thread. virtual void RemoveObjectManager(const std::string& service_name, const ObjectPath& object_path); // Instructs all registered object managers to retrieve their set of managed // objects from their respective remote objects. There is no need to call this // manually, this is called automatically by the D-Bus thread manager once // implementation classes are registered. virtual void GetManagedObjects(); // Shuts down the bus and blocks until it's done. More specifically, this // function does the following: // // - Unregisters the object paths // - Releases the service names // - Closes the connection to dbus-daemon. // // This function can be called multiple times and it is no-op for the 2nd time // calling. // // BLOCKING CALL. virtual void ShutdownAndBlock(); // Similar to ShutdownAndBlock(), but this function is used to // synchronously shut down the bus that uses the D-Bus thread. This // function is intended to be used at the very end of the browser // shutdown, where it makes more sense to shut down the bus // synchronously, than trying to make it asynchronous. // // BLOCKING CALL, but must be called in the origin thread. virtual void ShutdownOnDBusThreadAndBlock(); // Returns true if the shutdown has been completed. bool shutdown_completed() { return shutdown_completed_; } // // The public functions below are not intended to be used in client // code. These are used to implement ObjectProxy and ExportedObject. // // Connects the bus to the dbus-daemon. // Returns true on success, or the bus is already connected. // // BLOCKING CALL. virtual bool Connect(); // Disconnects the bus from the dbus-daemon. // Safe to call multiple times and no operation after the first call. // Do not call for shared connection it will be released by libdbus. // // BLOCKING CALL. virtual void ClosePrivateConnection(); // Requests the ownership of the service name given by |service_name|. // See also RequestOwnershipAndBlock(). // // |on_ownership_callback| is called when the service name is obtained // or failed to be obtained, in the origin thread. // // Must be called in the origin thread. virtual void RequestOwnership(const std::string& service_name, ServiceOwnershipOptions options, OnOwnershipCallback on_ownership_callback); // Requests the ownership of the given service name. // Returns true on success, or the the service name is already obtained. // // BLOCKING CALL. virtual bool RequestOwnershipAndBlock(const std::string& service_name, ServiceOwnershipOptions options); // Releases the ownership of the given service name. // Returns true on success. // // BLOCKING CALL. virtual bool ReleaseOwnership(const std::string& service_name); // Sets up async operations. // Returns true on success, or it's already set up. // This function needs to be called before starting async operations. // // BLOCKING CALL. virtual bool SetUpAsyncOperations(); // Sends a message to the bus and blocks until the response is // received. Used to implement synchronous method calls. // // BLOCKING CALL. virtual DBusMessage* SendWithReplyAndBlock(DBusMessage* request, int timeout_ms, DBusError* error); // Requests to send a message to the bus. The reply is handled with // |pending_call| at a later time. // // BLOCKING CALL. virtual void SendWithReply(DBusMessage* request, DBusPendingCall** pending_call, int timeout_ms); // Requests to send a message to the bus. The message serial number will // be stored in |serial|. // // BLOCKING CALL. virtual void Send(DBusMessage* request, uint32* serial); // Adds the message filter function. |filter_function| will be called // when incoming messages are received. Returns true on success. // // When a new incoming message arrives, filter functions are called in // the order that they were added until the the incoming message is // handled by a filter function. // // The same filter function associated with the same user data cannot be // added more than once. Returns false for this case. // // BLOCKING CALL. virtual bool AddFilterFunction(DBusHandleMessageFunction filter_function, void* user_data); // Removes the message filter previously added by AddFilterFunction(). // Returns true on success. // // BLOCKING CALL. virtual bool RemoveFilterFunction(DBusHandleMessageFunction filter_function, void* user_data); // Adds the match rule. Messages that match the rule will be processed // by the filter functions added by AddFilterFunction(). // // You cannot specify which filter function to use for a match rule. // Instead, you should check if an incoming message is what you are // interested in, in the filter functions. // // The same match rule can be added more than once and should be removed // as many times as it was added. // // The match rule looks like: // "type='signal', interface='org.chromium.SomeInterface'". // // See "Message Bus Message Routing" section in the D-Bus specification // for details about match rules: // http://dbus.freedesktop.org/doc/dbus-specification.html#message-bus-routing // // BLOCKING CALL. virtual void AddMatch(const std::string& match_rule, DBusError* error); // Removes the match rule previously added by AddMatch(). // Returns false if the requested match rule is unknown or has already been // removed. Otherwise, returns true and sets |error| accordingly. // // BLOCKING CALL. virtual bool RemoveMatch(const std::string& match_rule, DBusError* error); // Tries to register the object path. Returns true on success. // Returns false if the object path is already registered. // // |message_function| in |vtable| will be called every time when a new // |message sent to the object path arrives. // // The same object path must not be added more than once. // // See also documentation of |dbus_connection_try_register_object_path| at // http://dbus.freedesktop.org/doc/api/html/group__DBusConnection.html // // BLOCKING CALL. virtual bool TryRegisterObjectPath(const ObjectPath& object_path, const DBusObjectPathVTable* vtable, void* user_data, DBusError* error); // Unregister the object path. // // BLOCKING CALL. virtual void UnregisterObjectPath(const ObjectPath& object_path); // Posts |task| to the task runner of the D-Bus thread. On completion, |reply| // is posted to the origin thread. virtual void PostTaskToDBusThreadAndReply( const tracked_objects::Location& from_here, const base::Closure& task, const base::Closure& reply); // Posts the task to the task runner of the thread that created the bus. virtual void PostTaskToOriginThread( const tracked_objects::Location& from_here, const base::Closure& task); // Posts the task to the task runner of the D-Bus thread. If D-Bus // thread is not supplied, the task runner of the origin thread will be // used. virtual void PostTaskToDBusThread( const tracked_objects::Location& from_here, const base::Closure& task); // Posts the delayed task to the task runner of the D-Bus thread. If // D-Bus thread is not supplied, the task runner of the origin thread // will be used. virtual void PostDelayedTaskToDBusThread( const tracked_objects::Location& from_here, const base::Closure& task, base::TimeDelta delay); // Returns true if the bus has the D-Bus thread. virtual bool HasDBusThread(); // Check whether the current thread is on the origin thread (the thread // that created the bus). If not, DCHECK will fail. virtual void AssertOnOriginThread(); // Check whether the current thread is on the D-Bus thread. If not, // DCHECK will fail. If the D-Bus thread is not supplied, it calls // AssertOnOriginThread(). virtual void AssertOnDBusThread(); // Gets the owner for |service_name| via org.freedesktop.DBus.GetNameOwner. // Returns the owner name, if any, or an empty string on failure. // |options| specifies where to printing error messages or not. // // BLOCKING CALL. virtual std::string GetServiceOwnerAndBlock(const std::string& service_name, GetServiceOwnerOption options); // A non-blocking version of GetServiceOwnerAndBlock(). // Must be called in the origin thread. virtual void GetServiceOwner(const std::string& service_name, const GetServiceOwnerCallback& callback); // Whenever the owner for |service_name| changes, run |callback| with the // name of the new owner. If the owner goes away, then |callback| receives // an empty string. // // Any unique (service_name, callback) can be used. Duplicate are ignored. // |service_name| must not be empty and |callback| must not be null. // // Must be called in the origin thread. virtual void ListenForServiceOwnerChange( const std::string& service_name, const GetServiceOwnerCallback& callback); // Stop listening for |service_name| owner changes for |callback|. // Any unique (service_name, callback) can be used. Non-registered callbacks // for a given service name are ignored. // |service_name| must not be empty and |callback| must not be null. // // Must be called in the origin thread. virtual void UnlistenForServiceOwnerChange( const std::string& service_name, const GetServiceOwnerCallback& callback); // Returns true if the bus is connected to D-Bus. bool is_connected() { return connection_ != NULL; } protected: // This is protected, so we can define sub classes. virtual ~Bus(); private: friend class base::RefCountedThreadSafe<Bus>; // Helper function used for RemoveObjectProxy(). void RemoveObjectProxyInternal(scoped_refptr<dbus::ObjectProxy> object_proxy, const base::Closure& callback); // Helper function used for UnregisterExportedObject(). void UnregisterExportedObjectInternal( scoped_refptr<dbus::ExportedObject> exported_object); // Helper function used for ShutdownOnDBusThreadAndBlock(). void ShutdownOnDBusThreadAndBlockInternal(); // Helper function used for RequestOwnership(). void RequestOwnershipInternal(const std::string& service_name, ServiceOwnershipOptions options, OnOwnershipCallback on_ownership_callback); // Helper function used for GetServiceOwner(). void GetServiceOwnerInternal(const std::string& service_name, const GetServiceOwnerCallback& callback); // Helper function used for ListenForServiceOwnerChange(). void ListenForServiceOwnerChangeInternal( const std::string& service_name, const GetServiceOwnerCallback& callback); // Helper function used for UnListenForServiceOwnerChange(). void UnlistenForServiceOwnerChangeInternal( const std::string& service_name, const GetServiceOwnerCallback& callback); // Processes the all incoming data to the connection, if any. // // BLOCKING CALL. void ProcessAllIncomingDataIfAny(); // Called when a watch object is added. Used to start monitoring the // file descriptor used for D-Bus communication. dbus_bool_t OnAddWatch(DBusWatch* raw_watch); // Called when a watch object is removed. void OnRemoveWatch(DBusWatch* raw_watch); // Called when the "enabled" status of |raw_watch| is toggled. void OnToggleWatch(DBusWatch* raw_watch); // Called when a timeout object is added. Used to start monitoring // timeout for method calls. dbus_bool_t OnAddTimeout(DBusTimeout* raw_timeout); // Called when a timeout object is removed. void OnRemoveTimeout(DBusTimeout* raw_timeout); // Called when the "enabled" status of |raw_timeout| is toggled. void OnToggleTimeout(DBusTimeout* raw_timeout); // Called when the dispatch status (i.e. if any incoming data is // available) is changed. void OnDispatchStatusChanged(DBusConnection* connection, DBusDispatchStatus status); // Called when the connection is diconnected. void OnConnectionDisconnected(DBusConnection* connection); // Called when a service owner change occurs. void OnServiceOwnerChanged(DBusMessage* message); // Callback helper functions. Redirects to the corresponding member function. static dbus_bool_t OnAddWatchThunk(DBusWatch* raw_watch, void* data); static void OnRemoveWatchThunk(DBusWatch* raw_watch, void* data); static void OnToggleWatchThunk(DBusWatch* raw_watch, void* data); static dbus_bool_t OnAddTimeoutThunk(DBusTimeout* raw_timeout, void* data); static void OnRemoveTimeoutThunk(DBusTimeout* raw_timeout, void* data); static void OnToggleTimeoutThunk(DBusTimeout* raw_timeout, void* data); static void OnDispatchStatusChangedThunk(DBusConnection* connection, DBusDispatchStatus status, void* data); // Calls OnConnectionDisconnected if the Disconnected signal is received. static DBusHandlerResult OnConnectionDisconnectedFilter( DBusConnection* connection, DBusMessage* message, void* user_data); // Calls OnServiceOwnerChanged for a NameOwnerChanged signal. static DBusHandlerResult OnServiceOwnerChangedFilter( DBusConnection* connection, DBusMessage* message, void* user_data); const BusType bus_type_; const ConnectionType connection_type_; scoped_refptr<base::SequencedTaskRunner> dbus_task_runner_; base::WaitableEvent on_shutdown_; DBusConnection* connection_; scoped_refptr<base::SingleThreadTaskRunner> origin_task_runner_; base::PlatformThreadId origin_thread_id_; std::set<std::string> owned_service_names_; // The following sets are used to check if rules/object_paths/filters // are properly cleaned up before destruction of the bus object. // Since it's not an error to add the same match rule twice, the repeated // match rules are counted in a map. std::map<std::string, int> match_rules_added_; std::set<ObjectPath> registered_object_paths_; std::set<std::pair<DBusHandleMessageFunction, void*> > filter_functions_added_; // ObjectProxyTable is used to hold the object proxies created by the // bus object. Key is a pair; the first part is a concatenated string of // service name + object path, like // "org.chromium.TestService/org/chromium/TestObject". // The second part is the ObjectProxy::Options for the proxy. typedef std::map<std::pair<std::string, int>, scoped_refptr<dbus::ObjectProxy> > ObjectProxyTable; ObjectProxyTable object_proxy_table_; // ExportedObjectTable is used to hold the exported objects created by // the bus object. Key is a concatenated string of service name + // object path, like "org.chromium.TestService/org/chromium/TestObject". typedef std::map<const dbus::ObjectPath, scoped_refptr<dbus::ExportedObject> > ExportedObjectTable; ExportedObjectTable exported_object_table_; // ObjectManagerTable is used to hold the object managers created by the // bus object. Key is a concatenated string of service name + object path, // like "org.chromium.TestService/org/chromium/TestObject". typedef std::map<std::string, scoped_refptr<dbus::ObjectManager> > ObjectManagerTable; ObjectManagerTable object_manager_table_; // A map of NameOwnerChanged signals to listen for and the callbacks to run // on the origin thread when the owner changes. // Only accessed on the DBus thread. // Key: Service name // Value: Vector of callbacks. Unique and expected to be small. Not using // std::set here because base::Callbacks don't have a '<' operator. typedef std::map<std::string, std::vector<GetServiceOwnerCallback> > ServiceOwnerChangedListenerMap; ServiceOwnerChangedListenerMap service_owner_changed_listener_map_; bool async_operations_set_up_; bool shutdown_completed_; // Counters to make sure that OnAddWatch()/OnRemoveWatch() and // OnAddTimeout()/OnRemoveTimeou() are balanced. int num_pending_watches_; int num_pending_timeouts_; std::string address_; base::Closure on_disconnected_closure_; DISALLOW_COPY_AND_ASSIGN(Bus); }; } // namespace dbus #endif // DBUS_BUS_H_
[ "ProjectRetroScope@gmail.com" ]
ProjectRetroScope@gmail.com
09276a7361c4fec42f5ada521424da6837bb9ad9
72a146dad10c3330548f175643822e6cc2e2ccba
/components/ntp_snippets/ntp_snippets_service_unittest.cc
6370ce11373a220db603f0929fa0c5286a3d8541
[ "BSD-3-Clause" ]
permissive
daotianya/browser-android-tabs
bb6772394c2138e2f3859a83ec6e0860d01a6161
44e83a97eb1c7775944a04144e161d99cbb7de5b
refs/heads/master
2020-06-10T18:07:58.392087
2016-12-07T15:37:13
2016-12-07T15:37:13
75,914,703
1
0
null
2016-12-08T07:37:51
2016-12-08T07:37:51
null
UTF-8
C++
false
false
39,291
cc
// Copyright 2015 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 "components/ntp_snippets/ntp_snippets_service.h" #include <memory> #include <utility> #include <vector> #include "base/command_line.h" #include "base/files/file_path.h" #include "base/files/scoped_temp_dir.h" #include "base/json/json_reader.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/test/histogram_tester.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "components/image_fetcher/image_decoder.h" #include "components/image_fetcher/image_fetcher.h" #include "components/image_fetcher/image_fetcher_delegate.h" #include "components/ntp_snippets/category_factory.h" #include "components/ntp_snippets/ntp_snippet.h" #include "components/ntp_snippets/ntp_snippets_constants.h" #include "components/ntp_snippets/ntp_snippets_database.h" #include "components/ntp_snippets/ntp_snippets_fetcher.h" #include "components/ntp_snippets/ntp_snippets_scheduler.h" #include "components/ntp_snippets/ntp_snippets_test_utils.h" #include "components/ntp_snippets/switches.h" #include "components/prefs/testing_pref_service.h" #include "components/signin/core/browser/fake_profile_oauth2_token_service.h" #include "components/signin/core/browser/fake_signin_manager.h" #include "components/variations/variations_associated_data.h" #include "google_apis/google_api_keys.h" #include "net/url_request/test_url_fetcher_factory.h" #include "net/url_request/url_request_test_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_unittest_util.h" using image_fetcher::ImageFetcher; using image_fetcher::ImageFetcherDelegate; using testing::ElementsAre; using testing::Eq; using testing::InSequence; using testing::Invoke; using testing::IsEmpty; using testing::Mock; using testing::MockFunction; using testing::NiceMock; using testing::Return; using testing::SaveArg; using testing::SizeIs; using testing::StartsWith; using testing::WithArgs; using testing::_; namespace ntp_snippets { namespace { MATCHER_P(IdEq, value, "") { return arg->id() == value; } MATCHER_P(IsCategory, id, "") { return arg.id() == static_cast<int>(id); } const base::Time::Exploded kDefaultCreationTime = {2015, 11, 4, 25, 13, 46, 45}; const char kTestContentSuggestionsServerEndpoint[] = "https://localunittest-chromecontentsuggestions-pa.googleapis.com/v1/" "suggestions/fetch"; const char kTestContentSuggestionsServerFormat[] = "https://localunittest-chromecontentsuggestions-pa.googleapis.com/v1/" "suggestions/fetch?key=%s"; const char kSnippetUrl[] = "http://localhost/foobar"; const char kSnippetTitle[] = "Title"; const char kSnippetText[] = "Snippet"; const char kSnippetSalientImage[] = "http://localhost/salient_image"; const char kSnippetPublisherName[] = "Foo News"; const char kSnippetAmpUrl[] = "http://localhost/amp"; const char kSnippetUrl2[] = "http://foo.com/bar"; base::Time GetDefaultCreationTime() { base::Time out_time; EXPECT_TRUE(base::Time::FromUTCExploded(kDefaultCreationTime, &out_time)); return out_time; } base::Time GetDefaultExpirationTime() { return base::Time::Now() + base::TimeDelta::FromHours(1); } std::string GetTestJson(const std::vector<std::string>& snippets) { return base::StringPrintf( "{\n" " \"categories\": [{\n" " \"id\": 1,\n" " \"localizedTitle\": \"Articles for You\",\n" " \"suggestions\": [%s]\n" " }]\n" "}\n", base::JoinString(snippets, ", ").c_str()); } std::string GetMultiCategoryJson(const std::vector<std::string>& articles, const std::vector<std::string>& others) { return base::StringPrintf( "{\n" " \"categories\": [{\n" " \"id\": 1,\n" " \"localizedTitle\": \"Articles for You\",\n" " \"suggestions\": [%s]\n" " }, {\n" " \"id\": 2,\n" " \"localizedTitle\": \"Other Things\",\n" " \"suggestions\": [%s]\n" " }]\n" "}\n", base::JoinString(articles, ", ").c_str(), base::JoinString(others, ", ").c_str()); } std::string FormatTime(const base::Time& t) { base::Time::Exploded x; t.UTCExplode(&x); return base::StringPrintf("%04d-%02d-%02dT%02d:%02d:%02dZ", x.year, x.month, x.day_of_month, x.hour, x.minute, x.second); } std::string GetSnippetWithUrlAndTimesAndSource( const std::vector<std::string>& ids, const std::string& url, const base::Time& creation_time, const base::Time& expiry_time, const std::string& publisher, const std::string& amp_url) { const std::string ids_string = base::JoinString(ids, "\",\n \""); return base::StringPrintf( "{\n" " \"ids\": [\n" " \"%s\"\n" " ],\n" " \"title\": \"%s\",\n" " \"snippet\": \"%s\",\n" " \"fullPageUrl\": \"%s\",\n" " \"creationTime\": \"%s\",\n" " \"expirationTime\": \"%s\",\n" " \"attribution\": \"%s\",\n" " \"imageUrl\": \"%s\",\n" " \"ampUrl\": \"%s\"\n" " }", ids_string.c_str(), kSnippetTitle, kSnippetText, url.c_str(), FormatTime(creation_time).c_str(), FormatTime(expiry_time).c_str(), publisher.c_str(), kSnippetSalientImage, amp_url.c_str()); } std::string GetSnippetWithSources(const std::string& source_url, const std::string& publisher, const std::string& amp_url) { return GetSnippetWithUrlAndTimesAndSource( {kSnippetUrl}, source_url, GetDefaultCreationTime(), GetDefaultExpirationTime(), publisher, amp_url); } std::string GetSnippetWithUrlAndTimes(const std::string& url, const base::Time& content_creation_time, const base::Time& expiry_time) { return GetSnippetWithUrlAndTimesAndSource({url}, url, content_creation_time, expiry_time, kSnippetPublisherName, kSnippetAmpUrl); } std::string GetSnippetWithTimes(const base::Time& content_creation_time, const base::Time& expiry_time) { return GetSnippetWithUrlAndTimes(kSnippetUrl, content_creation_time, expiry_time); } std::string GetSnippetWithUrl(const std::string& url) { return GetSnippetWithUrlAndTimes(url, GetDefaultCreationTime(), GetDefaultExpirationTime()); } std::string GetSnippet() { return GetSnippetWithUrlAndTimes(kSnippetUrl, GetDefaultCreationTime(), GetDefaultExpirationTime()); } std::string GetSnippetN(int n) { return GetSnippetWithUrlAndTimes(base::StringPrintf("%s/%d", kSnippetUrl, n), GetDefaultCreationTime(), GetDefaultExpirationTime()); } std::string GetExpiredSnippet() { return GetSnippetWithTimes(GetDefaultCreationTime(), base::Time::Now()); } std::string GetInvalidSnippet() { std::string json_str = GetSnippet(); // Make the json invalid by removing the final closing brace. return json_str.substr(0, json_str.size() - 1); } std::string GetIncompleteSnippet() { std::string json_str = GetSnippet(); // Rename the "url" entry. The result is syntactically valid json that will // fail to parse as snippets. size_t pos = json_str.find("\"fullPageUrl\""); if (pos == std::string::npos) { NOTREACHED(); return std::string(); } json_str[pos + 1] = 'x'; return json_str; } void ServeOneByOneImage( const std::string& id, base::Callback<void(const std::string&, const gfx::Image&)> callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, id, gfx::test::CreateImage(1, 1))); } void ParseJson( const std::string& json, const ntp_snippets::NTPSnippetsFetcher::SuccessCallback& success_callback, const ntp_snippets::NTPSnippetsFetcher::ErrorCallback& error_callback) { base::JSONReader json_reader; std::unique_ptr<base::Value> value = json_reader.ReadToValue(json); if (value) { success_callback.Run(std::move(value)); } else { error_callback.Run(json_reader.GetErrorMessage()); } } // Factory for FakeURLFetcher objects that always generate errors. class FailingFakeURLFetcherFactory : public net::URLFetcherFactory { public: std::unique_ptr<net::URLFetcher> CreateURLFetcher( int id, const GURL& url, net::URLFetcher::RequestType request_type, net::URLFetcherDelegate* d) override { return base::MakeUnique<net::FakeURLFetcher>( url, d, /*response_data=*/std::string(), net::HTTP_NOT_FOUND, net::URLRequestStatus::FAILED); } }; class MockScheduler : public NTPSnippetsScheduler { public: MOCK_METHOD4(Schedule, bool(base::TimeDelta period_wifi_charging, base::TimeDelta period_wifi, base::TimeDelta period_fallback, base::Time reschedule_time)); MOCK_METHOD0(Unschedule, bool()); }; class MockImageFetcher : public ImageFetcher { public: MOCK_METHOD1(SetImageFetcherDelegate, void(ImageFetcherDelegate*)); MOCK_METHOD1(SetDataUseServiceName, void(DataUseServiceName)); MOCK_METHOD3( StartOrQueueNetworkRequest, void(const std::string&, const GURL&, base::Callback<void(const std::string&, const gfx::Image&)>)); }; class FakeContentSuggestionsProviderObserver : public ContentSuggestionsProvider::Observer { public: FakeContentSuggestionsProviderObserver() : loaded_(base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED) {} void OnNewSuggestions(ContentSuggestionsProvider* provider, Category category, std::vector<ContentSuggestion> suggestions) override { suggestions_[category] = std::move(suggestions); } void OnCategoryStatusChanged(ContentSuggestionsProvider* provider, Category category, CategoryStatus new_status) override { loaded_.Signal(); statuses_[category] = new_status; } void OnSuggestionInvalidated(ContentSuggestionsProvider* provider, Category category, const std::string& suggestion_id) override {} const std::map<Category, CategoryStatus, Category::CompareByID>& statuses() const { return statuses_; } CategoryStatus StatusForCategory(Category category) const { auto it = statuses_.find(category); if (it == statuses_.end()) { return CategoryStatus::NOT_PROVIDED; } return it->second; } const std::vector<ContentSuggestion>& SuggestionsForCategory( Category category) { return suggestions_[category]; } void WaitForLoad() { loaded_.Wait(); } bool Loaded() { return loaded_.IsSignaled(); } void Reset() { loaded_.Reset(); statuses_.clear(); } private: base::WaitableEvent loaded_; std::map<Category, CategoryStatus, Category::CompareByID> statuses_; std::map<Category, std::vector<ContentSuggestion>, Category::CompareByID> suggestions_; DISALLOW_COPY_AND_ASSIGN(FakeContentSuggestionsProviderObserver); }; } // namespace class NTPSnippetsServiceTest : public ::testing::Test { public: NTPSnippetsServiceTest() : params_manager_(ntp_snippets::kStudyName, {{"content_suggestions_backend", kTestContentSuggestionsServerEndpoint}}), fake_url_fetcher_factory_( /*default_factory=*/&failing_url_fetcher_factory_), test_url_(base::StringPrintf(kTestContentSuggestionsServerFormat, google_apis::GetAPIKey().c_str())), observer_(base::MakeUnique<FakeContentSuggestionsProviderObserver>()) { NTPSnippetsService::RegisterProfilePrefs(utils_.pref_service()->registry()); RequestThrottler::RegisterProfilePrefs(utils_.pref_service()->registry()); // Since no SuggestionsService is injected in tests, we need to force the // service to fetch from all hosts. base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kDontRestrict); EXPECT_TRUE(database_dir_.CreateUniqueTempDir()); } ~NTPSnippetsServiceTest() override { // We need to run the message loop after deleting the database, because // ProtoDatabaseImpl deletes the actual LevelDB asynchronously on the task // runner. Without this, we'd get reports of memory leaks. base::RunLoop().RunUntilIdle(); } std::unique_ptr<NTPSnippetsService> MakeSnippetsService() { CHECK(!observer_->Loaded()); scoped_refptr<base::SingleThreadTaskRunner> task_runner( base::ThreadTaskRunnerHandle::Get()); scoped_refptr<net::TestURLRequestContextGetter> request_context_getter = new net::TestURLRequestContextGetter(task_runner.get()); utils_.ResetSigninManager(); std::unique_ptr<NTPSnippetsFetcher> snippets_fetcher = base::MakeUnique<NTPSnippetsFetcher>( utils_.fake_signin_manager(), fake_token_service_.get(), std::move(request_context_getter), utils_.pref_service(), &category_factory_, base::Bind(&ParseJson), /*is_stable_channel=*/true); utils_.fake_signin_manager()->SignIn("foo@bar.com"); snippets_fetcher->SetPersonalizationForTesting( NTPSnippetsFetcher::Personalization::kNonPersonal); auto image_fetcher = base::MakeUnique<NiceMock<MockImageFetcher>>(); image_fetcher_ = image_fetcher.get(); // Add an initial fetch response, as the service tries to fetch when there // is nothing in the DB. SetUpFetchResponse(GetTestJson(std::vector<std::string>())); auto service = base::MakeUnique<NTPSnippetsService>( observer_.get(), &category_factory_, utils_.pref_service(), nullptr, "fr", &scheduler_, std::move(snippets_fetcher), std::move(image_fetcher), /*image_decoder=*/nullptr, base::MakeUnique<NTPSnippetsDatabase>(database_dir_.path(), task_runner), base::MakeUnique<NTPSnippetsStatusService>(utils_.fake_signin_manager(), utils_.pref_service())); base::RunLoop().RunUntilIdle(); observer_->WaitForLoad(); return service; } void ResetSnippetsService(std::unique_ptr<NTPSnippetsService>* service) { service->reset(); observer_ = base::MakeUnique<FakeContentSuggestionsProviderObserver>(); *service = MakeSnippetsService(); } std::string MakeArticleID(const NTPSnippetsService& service, const std::string& within_category_id) { return service.MakeUniqueID(articles_category(), within_category_id); } Category articles_category() { return category_factory_.FromKnownCategory(KnownCategories::ARTICLES); } std::string MakeOtherID(const NTPSnippetsService& service, const std::string& within_category_id) { return service.MakeUniqueID(other_category(), within_category_id); } Category other_category() { return category_factory_.FromRemoteCategory(2); } protected: const GURL& test_url() { return test_url_; } FakeContentSuggestionsProviderObserver& observer() { return *observer_; } MockScheduler& mock_scheduler() { return scheduler_; } NiceMock<MockImageFetcher>* image_fetcher() { return image_fetcher_; } // Provide the json to be returned by the fake fetcher. void SetUpFetchResponse(const std::string& json) { fake_url_fetcher_factory_.SetFakeResponse(test_url_, json, net::HTTP_OK, net::URLRequestStatus::SUCCESS); } void LoadFromJSONString(NTPSnippetsService* service, const std::string& json) { SetUpFetchResponse(json); service->FetchSnippets(true); base::RunLoop().RunUntilIdle(); } private: variations::testing::VariationParamsManager params_manager_; test::NTPSnippetsTestUtils utils_; base::MessageLoop message_loop_; FailingFakeURLFetcherFactory failing_url_fetcher_factory_; // Instantiation of factory automatically sets itself as URLFetcher's factory. net::FakeURLFetcherFactory fake_url_fetcher_factory_; const GURL test_url_; std::unique_ptr<OAuth2TokenService> fake_token_service_; NiceMock<MockScheduler> scheduler_; std::unique_ptr<FakeContentSuggestionsProviderObserver> observer_; CategoryFactory category_factory_; NiceMock<MockImageFetcher>* image_fetcher_; base::ScopedTempDir database_dir_; DISALLOW_COPY_AND_ASSIGN(NTPSnippetsServiceTest); }; TEST_F(NTPSnippetsServiceTest, ScheduleOnStart) { EXPECT_CALL(mock_scheduler(), Schedule(_, _, _, _)); auto service = MakeSnippetsService(); // When we have no snippets are all, loading the service initiates a fetch. base::RunLoop().RunUntilIdle(); ASSERT_EQ("OK", service->snippets_fetcher()->last_status()); } TEST_F(NTPSnippetsServiceTest, Full) { std::string json_str(GetTestJson({GetSnippet()})); EXPECT_CALL(mock_scheduler(), Schedule(_, _, _, _)); auto service = MakeSnippetsService(); LoadFromJSONString(service.get(), json_str); ASSERT_THAT(observer().SuggestionsForCategory(articles_category()), SizeIs(1)); ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); const ContentSuggestion& suggestion = observer().SuggestionsForCategory(articles_category()).front(); EXPECT_EQ(MakeArticleID(*service, kSnippetUrl), suggestion.id()); EXPECT_EQ(kSnippetTitle, base::UTF16ToUTF8(suggestion.title())); EXPECT_EQ(kSnippetText, base::UTF16ToUTF8(suggestion.snippet_text())); // EXPECT_EQ(GURL(kSnippetSalientImage), suggestion.salient_image_url()); EXPECT_EQ(GetDefaultCreationTime(), suggestion.publish_date()); EXPECT_EQ(kSnippetPublisherName, base::UTF16ToUTF8(suggestion.publisher_name())); EXPECT_EQ(GURL(kSnippetAmpUrl), suggestion.amp_url()); } TEST_F(NTPSnippetsServiceTest, MultipleCategories) { std::string json_str( GetMultiCategoryJson({GetSnippetN(0)}, {GetSnippetN(1)})); EXPECT_CALL(mock_scheduler(), Schedule(_, _, _, _)); auto service = MakeSnippetsService(); LoadFromJSONString(service.get(), json_str); ASSERT_THAT(observer().statuses(), Eq(std::map<Category, CategoryStatus, Category::CompareByID>{ {articles_category(), CategoryStatus::AVAILABLE}, {other_category(), CategoryStatus::AVAILABLE}, })); EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); EXPECT_THAT(service->GetSnippetsForTesting(other_category()), SizeIs(1)); ASSERT_THAT(observer().SuggestionsForCategory(articles_category()), SizeIs(1)); ASSERT_THAT(observer().SuggestionsForCategory(other_category()), SizeIs(1)); { const ContentSuggestion& suggestion = observer().SuggestionsForCategory(articles_category()).front(); EXPECT_EQ(MakeArticleID(*service, std::string(kSnippetUrl) + "/0"), suggestion.id()); EXPECT_EQ(kSnippetTitle, base::UTF16ToUTF8(suggestion.title())); EXPECT_EQ(kSnippetText, base::UTF16ToUTF8(suggestion.snippet_text())); EXPECT_EQ(GetDefaultCreationTime(), suggestion.publish_date()); EXPECT_EQ(kSnippetPublisherName, base::UTF16ToUTF8(suggestion.publisher_name())); EXPECT_EQ(GURL(kSnippetAmpUrl), suggestion.amp_url()); } { const ContentSuggestion& suggestion = observer().SuggestionsForCategory(other_category()).front(); EXPECT_EQ(MakeOtherID(*service, std::string(kSnippetUrl) + "/1"), suggestion.id()); EXPECT_EQ(kSnippetTitle, base::UTF16ToUTF8(suggestion.title())); EXPECT_EQ(kSnippetText, base::UTF16ToUTF8(suggestion.snippet_text())); EXPECT_EQ(GetDefaultCreationTime(), suggestion.publish_date()); EXPECT_EQ(kSnippetPublisherName, base::UTF16ToUTF8(suggestion.publisher_name())); EXPECT_EQ(GURL(kSnippetAmpUrl), suggestion.amp_url()); } } TEST_F(NTPSnippetsServiceTest, Clear) { EXPECT_CALL(mock_scheduler(), Schedule(_, _, _, _)); auto service = MakeSnippetsService(); std::string json_str(GetTestJson({GetSnippet()})); LoadFromJSONString(service.get(), json_str); EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); service->ClearCachedSuggestions(articles_category()); EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); } TEST_F(NTPSnippetsServiceTest, InsertAtFront) { EXPECT_CALL(mock_scheduler(), Schedule(_, _, _, _)); auto service = MakeSnippetsService(); std::string first("http://first"); LoadFromJSONString(service.get(), GetTestJson({GetSnippetWithUrl(first)})); EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), ElementsAre(IdEq(first))); std::string second("http://second"); LoadFromJSONString(service.get(), GetTestJson({GetSnippetWithUrl(second)})); // The snippet loaded last should be at the first position in the list now. EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), ElementsAre(IdEq(second), IdEq(first))); } TEST_F(NTPSnippetsServiceTest, LimitNumSnippets) { auto service = MakeSnippetsService(); int max_snippet_count = NTPSnippetsService::GetMaxSnippetCountForTesting(); int snippets_per_load = max_snippet_count / 2 + 1; char url_format[] = "http://localhost/%i"; std::vector<std::string> snippets1; std::vector<std::string> snippets2; for (int i = 0; i < snippets_per_load; i++) { snippets1.push_back(GetSnippetWithUrl(base::StringPrintf(url_format, i))); snippets2.push_back(GetSnippetWithUrl( base::StringPrintf(url_format, snippets_per_load + i))); } LoadFromJSONString(service.get(), GetTestJson(snippets1)); ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(snippets1.size())); LoadFromJSONString(service.get(), GetTestJson(snippets2)); EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(max_snippet_count)); } TEST_F(NTPSnippetsServiceTest, LoadInvalidJson) { auto service = MakeSnippetsService(); LoadFromJSONString(service.get(), GetTestJson({GetInvalidSnippet()})); EXPECT_THAT(service->snippets_fetcher()->last_status(), StartsWith("Received invalid JSON")); EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); } TEST_F(NTPSnippetsServiceTest, LoadInvalidJsonWithExistingSnippets) { auto service = MakeSnippetsService(); LoadFromJSONString(service.get(), GetTestJson({GetSnippet()})); ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); ASSERT_EQ("OK", service->snippets_fetcher()->last_status()); LoadFromJSONString(service.get(), GetTestJson({GetInvalidSnippet()})); EXPECT_THAT(service->snippets_fetcher()->last_status(), StartsWith("Received invalid JSON")); // This should not have changed the existing snippets. EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); } TEST_F(NTPSnippetsServiceTest, LoadIncompleteJson) { auto service = MakeSnippetsService(); LoadFromJSONString(service.get(), GetTestJson({GetIncompleteSnippet()})); EXPECT_EQ("Invalid / empty list.", service->snippets_fetcher()->last_status()); EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); } TEST_F(NTPSnippetsServiceTest, LoadIncompleteJsonWithExistingSnippets) { auto service = MakeSnippetsService(); LoadFromJSONString(service.get(), GetTestJson({GetSnippet()})); ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); LoadFromJSONString(service.get(), GetTestJson({GetIncompleteSnippet()})); EXPECT_EQ("Invalid / empty list.", service->snippets_fetcher()->last_status()); // This should not have changed the existing snippets. EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); } TEST_F(NTPSnippetsServiceTest, Dismiss) { EXPECT_CALL(mock_scheduler(), Schedule(_, _, _, _)).Times(2); auto service = MakeSnippetsService(); std::string json_str( GetTestJson({GetSnippetWithSources("http://site.com", "Source 1", "")})); LoadFromJSONString(service.get(), json_str); ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); // Dismissing a non-existent snippet shouldn't do anything. service->DismissSuggestion(MakeArticleID(*service, "http://othersite.com")); EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); // Dismiss the snippet. service->DismissSuggestion(MakeArticleID(*service, kSnippetUrl)); EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); // Make sure that fetching the same snippet again does not re-add it. LoadFromJSONString(service.get(), json_str); EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); // The snippet should stay dismissed even after re-creating the service. ResetSnippetsService(&service); LoadFromJSONString(service.get(), json_str); EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); // The snippet can be added again after clearing dismissed snippets. service->ClearDismissedSuggestionsForDebugging(articles_category()); EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); LoadFromJSONString(service.get(), json_str); EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); } TEST_F(NTPSnippetsServiceTest, GetDismissed) { auto service = MakeSnippetsService(); LoadFromJSONString(service.get(), GetTestJson({GetSnippet()})); service->DismissSuggestion(MakeArticleID(*service, kSnippetUrl)); service->GetDismissedSuggestionsForDebugging( articles_category(), base::Bind( [](NTPSnippetsService* service, NTPSnippetsServiceTest* test, std::vector<ContentSuggestion> dismissed_suggestions) { EXPECT_EQ(1u, dismissed_suggestions.size()); for (auto& suggestion : dismissed_suggestions) { EXPECT_EQ(test->MakeArticleID(*service, kSnippetUrl), suggestion.id()); } }, service.get(), this)); base::RunLoop().RunUntilIdle(); // There should be no dismissed snippet after clearing the list. service->ClearDismissedSuggestionsForDebugging(articles_category()); service->GetDismissedSuggestionsForDebugging( articles_category(), base::Bind( [](NTPSnippetsService* service, NTPSnippetsServiceTest* test, std::vector<ContentSuggestion> dismissed_suggestions) { EXPECT_EQ(0u, dismissed_suggestions.size()); }, service.get(), this)); base::RunLoop().RunUntilIdle(); } TEST_F(NTPSnippetsServiceTest, CreationTimestampParseFail) { auto service = MakeSnippetsService(); std::string json = GetSnippetWithTimes(GetDefaultCreationTime(), GetDefaultExpirationTime()); base::ReplaceFirstSubstringAfterOffset( &json, 0, FormatTime(GetDefaultCreationTime()), "aaa1448459205"); std::string json_str(GetTestJson({json})); LoadFromJSONString(service.get(), json_str); EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); } TEST_F(NTPSnippetsServiceTest, RemoveExpiredContent) { auto service = MakeSnippetsService(); std::string json_str(GetTestJson({GetExpiredSnippet()})); LoadFromJSONString(service.get(), json_str); EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); } TEST_F(NTPSnippetsServiceTest, TestSingleSource) { auto service = MakeSnippetsService(); std::string json_str(GetTestJson({GetSnippetWithSources( "http://source1.com", "Source 1", "http://source1.amp.com")})); LoadFromJSONString(service.get(), json_str); ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); const NTPSnippet& snippet = *service->GetSnippetsForTesting(articles_category()).front(); EXPECT_EQ(snippet.sources().size(), 1u); EXPECT_EQ(snippet.id(), kSnippetUrl); EXPECT_EQ(snippet.best_source().url, GURL("http://source1.com")); EXPECT_EQ(snippet.best_source().publisher_name, std::string("Source 1")); EXPECT_EQ(snippet.best_source().amp_url, GURL("http://source1.amp.com")); } TEST_F(NTPSnippetsServiceTest, TestSingleSourceWithMalformedUrl) { auto service = MakeSnippetsService(); std::string json_str(GetTestJson({GetSnippetWithSources( "ceci n'est pas un url", "Source 1", "http://source1.amp.com")})); LoadFromJSONString(service.get(), json_str); EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); } TEST_F(NTPSnippetsServiceTest, TestSingleSourceWithMissingData) { auto service = MakeSnippetsService(); std::string json_str( GetTestJson({GetSnippetWithSources("http://source1.com", "", "")})); LoadFromJSONString(service.get(), json_str); EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); } TEST_F(NTPSnippetsServiceTest, LogNumArticlesHistogram) { auto service = MakeSnippetsService(); base::HistogramTester tester; LoadFromJSONString(service.get(), GetTestJson({GetInvalidSnippet()})); EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticles"), ElementsAre(base::Bucket(/*min=*/0, /*count=*/1))); // Invalid JSON shouldn't contribute to NumArticlesFetched. EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticlesFetched"), IsEmpty()); // Valid JSON with empty list. LoadFromJSONString(service.get(), GetTestJson(std::vector<std::string>())); EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticles"), ElementsAre(base::Bucket(/*min=*/0, /*count=*/2))); EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticlesFetched"), ElementsAre(base::Bucket(/*min=*/0, /*count=*/1))); // Snippet list should be populated with size 1. LoadFromJSONString(service.get(), GetTestJson({GetSnippet()})); EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticles"), ElementsAre(base::Bucket(/*min=*/0, /*count=*/2), base::Bucket(/*min=*/1, /*count=*/1))); EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticlesFetched"), ElementsAre(base::Bucket(/*min=*/0, /*count=*/1), base::Bucket(/*min=*/1, /*count=*/1))); // Duplicate snippet shouldn't increase the list size. LoadFromJSONString(service.get(), GetTestJson({GetSnippet()})); EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticles"), ElementsAre(base::Bucket(/*min=*/0, /*count=*/2), base::Bucket(/*min=*/1, /*count=*/2))); EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticlesFetched"), ElementsAre(base::Bucket(/*min=*/0, /*count=*/1), base::Bucket(/*min=*/1, /*count=*/2))); EXPECT_THAT( tester.GetAllSamples("NewTabPage.Snippets.NumArticlesZeroDueToDiscarded"), IsEmpty()); // Dismissing a snippet should decrease the list size. This will only be // logged after the next fetch. service->DismissSuggestion(MakeArticleID(*service, kSnippetUrl)); LoadFromJSONString(service.get(), GetTestJson({GetSnippet()})); EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticles"), ElementsAre(base::Bucket(/*min=*/0, /*count=*/3), base::Bucket(/*min=*/1, /*count=*/2))); // Dismissed snippets shouldn't influence NumArticlesFetched. EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticlesFetched"), ElementsAre(base::Bucket(/*min=*/0, /*count=*/1), base::Bucket(/*min=*/1, /*count=*/3))); EXPECT_THAT( tester.GetAllSamples("NewTabPage.Snippets.NumArticlesZeroDueToDiscarded"), ElementsAre(base::Bucket(/*min=*/1, /*count=*/1))); // There is only a single, dismissed snippet in the database, so recreating // the service will require us to re-fetch. tester.ExpectTotalCount("NewTabPage.Snippets.NumArticlesFetched", 4); ResetSnippetsService(&service); EXPECT_EQ(observer().StatusForCategory(articles_category()), CategoryStatus::AVAILABLE); tester.ExpectTotalCount("NewTabPage.Snippets.NumArticlesFetched", 5); EXPECT_THAT( tester.GetAllSamples("NewTabPage.Snippets.NumArticlesZeroDueToDiscarded"), ElementsAre(base::Bucket(/*min=*/1, /*count=*/2))); // But if there's a non-dismissed snippet in the database, recreating it // shouldn't trigger a fetch. LoadFromJSONString( service.get(), GetTestJson({GetSnippetWithUrl("http://not-dismissed.com")})); tester.ExpectTotalCount("NewTabPage.Snippets.NumArticlesFetched", 6); ResetSnippetsService(&service); tester.ExpectTotalCount("NewTabPage.Snippets.NumArticlesFetched", 6); } TEST_F(NTPSnippetsServiceTest, DismissShouldRespectAllKnownUrls) { auto service = MakeSnippetsService(); const base::Time creation = GetDefaultCreationTime(); const base::Time expiry = GetDefaultExpirationTime(); const std::vector<std::string> source_urls = { "http://mashable.com/2016/05/11/stolen", "http://www.aol.com/article/2016/05/stolen-doggie"}; const std::vector<std::string> publishers = {"Mashable", "AOL"}; const std::vector<std::string> amp_urls = { "http://mashable-amphtml.googleusercontent.com/1", "http://t2.gstatic.com/images?q=tbn:3"}; // Add the snippet from the mashable domain. LoadFromJSONString(service.get(), GetTestJson({GetSnippetWithUrlAndTimesAndSource( source_urls, source_urls[0], creation, expiry, publishers[0], amp_urls[0])})); ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); // Dismiss the snippet via the mashable source corpus ID. service->DismissSuggestion(MakeArticleID(*service, source_urls[0])); EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); // The same article from the AOL domain should now be detected as dismissed. LoadFromJSONString(service.get(), GetTestJson({GetSnippetWithUrlAndTimesAndSource( source_urls, source_urls[1], creation, expiry, publishers[1], amp_urls[1])})); EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); } TEST_F(NTPSnippetsServiceTest, StatusChanges) { { InSequence s; EXPECT_CALL(mock_scheduler(), Schedule(_, _, _, _)); EXPECT_CALL(mock_scheduler(), Unschedule()); EXPECT_CALL(mock_scheduler(), Schedule(_, _, _, _)); } auto service = MakeSnippetsService(); // Simulate user signed out SetUpFetchResponse(GetTestJson({GetSnippet()})); service->OnDisabledReasonChanged(DisabledReason::SIGNED_OUT); base::RunLoop().RunUntilIdle(); EXPECT_THAT(observer().StatusForCategory(articles_category()), Eq(CategoryStatus::SIGNED_OUT)); EXPECT_THAT(NTPSnippetsService::State::DISABLED, Eq(service->state_)); EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); // No fetch should be made. // Simulate user sign in. The service should be ready again and load snippets. SetUpFetchResponse(GetTestJson({GetSnippet()})); service->OnDisabledReasonChanged(DisabledReason::NONE); EXPECT_THAT(observer().StatusForCategory(articles_category()), Eq(CategoryStatus::AVAILABLE_LOADING)); base::RunLoop().RunUntilIdle(); EXPECT_THAT(observer().StatusForCategory(articles_category()), Eq(CategoryStatus::AVAILABLE)); EXPECT_THAT(NTPSnippetsService::State::READY, Eq(service->state_)); EXPECT_FALSE(service->GetSnippetsForTesting(articles_category()).empty()); } TEST_F(NTPSnippetsServiceTest, ImageReturnedWithTheSameId) { auto service = MakeSnippetsService(); LoadFromJSONString(service.get(), GetTestJson({GetSnippet()})); gfx::Image image; MockFunction<void(const std::string&, const gfx::Image&)> image_fetched; { InSequence s; EXPECT_CALL(*image_fetcher(), StartOrQueueNetworkRequest(_, _, _)) .WillOnce(WithArgs<0, 2>(Invoke(ServeOneByOneImage))); EXPECT_CALL(image_fetched, Call(_, _)).WillOnce(SaveArg<1>(&image)); } service->FetchSuggestionImage( MakeArticleID(*service, kSnippetUrl), base::Bind(&MockFunction<void(const std::string&, const gfx::Image&)>::Call, base::Unretained(&image_fetched))); base::RunLoop().RunUntilIdle(); // Check that the image by ServeOneByOneImage is really served. EXPECT_EQ(1, image.Width()); } TEST_F(NTPSnippetsServiceTest, EmptyImageReturnedForNonExistentId) { auto service = MakeSnippetsService(); // Create a non-empty image so that we can test the image gets updated. gfx::Image image = gfx::test::CreateImage(1, 1); MockFunction<void(const std::string&, const gfx::Image&)> image_fetched; EXPECT_CALL(image_fetched, Call(_, _)).WillOnce(SaveArg<1>(&image)); service->FetchSuggestionImage( MakeArticleID(*service, kSnippetUrl2), base::Bind(&MockFunction<void(const std::string&, const gfx::Image&)>::Call, base::Unretained(&image_fetched))); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(image.IsEmpty()); } TEST_F(NTPSnippetsServiceTest, ClearHistoryRemovesAllSuggestions) { auto service = MakeSnippetsService(); std::string first_snippet = GetSnippetWithUrl("http://url1.com"); std::string second_snippet = GetSnippetWithUrl("http://url2.com"); std::string json_str = GetTestJson({first_snippet, second_snippet}); LoadFromJSONString(service.get(), json_str); ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(2)); service->DismissSuggestion(MakeArticleID(*service, "http://url1.com")); ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); ASSERT_THAT(service->GetDismissedSnippetsForTesting(articles_category()), SizeIs(1)); base::Time begin = base::Time::FromTimeT(123), end = base::Time::FromTimeT(456); base::Callback<bool(const GURL& url)> filter; service->ClearHistory(begin, end, filter); EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); EXPECT_THAT(service->GetDismissedSnippetsForTesting(articles_category()), IsEmpty()); } } // namespace ntp_snippets
[ "serg.zhukovsky@gmail.com" ]
serg.zhukovsky@gmail.com
d76075632f75aa1f21312c7692284519f0704ddd
5f582843fefb2cd854e46449b079fcc8a2a57b92
/Find the Median.cpp
f9c458b8717315fcc414172c7c1d313244f14196
[]
no_license
mylo2202/HackerRank
e5830f0d6a22d773e8e2e745066757681bb077de
681ffdd74c3ee781281400f129c6c1409184a045
refs/heads/master
2020-07-28T16:51:26.089198
2019-10-31T15:52:30
2019-10-31T15:52:30
209,471,222
0
0
null
null
null
null
UTF-8
C++
false
false
419
cpp
#include <bits/stdc++.h> using namespace std; int main() { int size, entry, sum = 0; cin >> size; vector<int> v(20001); for (int i = 0; i < size; i++) { cin >> entry; v[entry+10000]++; } for (int i = 0 ; i < v.size(); i++) { sum += v[i]; if (sum > size/2) { cout << i - 10000 << endl; break; } } return 0; }
[ "48115847+mylo2202@users.noreply.github.com" ]
48115847+mylo2202@users.noreply.github.com
d480cdc39dac7e2e6b2b358bd651ae3df6c18920
c00b7f058dd09a805acb01bef7a89a35b76697d4
/src/optimization/InstructionScheduler.cpp
dd38a857251de6e79099409758c788f0e0e3e21f
[ "MIT" ]
permissive
rigred/VC4C
2613d25c2cbca013a30cd494224d52ef8c35f180
6c900c0e2fae2cbdd22c5adb044f385ae005468a
refs/heads/master
2022-09-24T19:19:19.683395
2020-06-02T12:02:52
2020-06-02T12:02:52
268,788,649
0
0
MIT
2020-06-02T11:59:40
2020-06-02T11:59:39
null
UTF-8
C++
false
false
15,095
cpp
/* * Author: doe300 * * See the file "LICENSE" for the full license governing this code. */ #include "InstructionScheduler.h" #include "../InstructionWalker.h" #include "../Profiler.h" #include "../analysis/DependencyGraph.h" #include "../intermediate/IntermediateInstruction.h" #include "log.h" using namespace vc4c; using namespace vc4c::optimizations; struct NodeSorter : public std::less<intermediate::IntermediateInstruction*> { static int ratePriority(intermediate::IntermediateInstruction* inst) { int priority = 0; // prioritizing conditional instructions keeps setting flags and their uses together if(inst->hasConditionalExecution()) { priority += 100; } // prioritize setting of TMU_NO_SWAP to make the best of the delays required before loading if(inst->writesRegister(REG_TMU_NOSWAP)) priority += 100; // prioritize unlocking mutex to keep critical section as small as possible if(inst->writesRegister(REG_MUTEX)) priority += 80; // XXX give reading of work-item info (as well as parameters) a high priority (minimizes their local's // life-time) if(std::any_of(inst->getArguments().begin(), inst->getArguments().end(), [](const Value& val) -> bool { return val.checkLocal() && val.local()->is<Parameter>(); })) priority += 50; // writing TMU address gets higher priority, to leave enough space for utilizing the delay to actually read the // value if(inst->writesRegister(REG_TMU0_ADDRESS) || inst->writesRegister(REG_TMU1_ADDRESS)) priority += 40; // prioritize triggering read of TMU and reading from TMU to be directly scheduled after the delay is up to free // queue space if(inst->getSignal().triggersReadOfR4() || inst->readsRegister(REG_TMU_OUT)) priority += 30; // Increasing semaphores gets higher priority, decreasing it lower to reduce stall time auto semaphore = dynamic_cast<const intermediate::SemaphoreAdjustment*>(inst); if(semaphore) { if(semaphore->increase) priority += 20; else priority -= 20; } // Triggering of TMU reads gets lower priority to leave enough space between setting address and reading value // to utilize delay if(inst->getSignal().triggersReadOfR4()) priority -= 30; // give vector rotations lower priority to make the usage-range of the accumulator used smaller if(dynamic_cast<const intermediate::VectorRotation*>(inst) && dynamic_cast<const intermediate::VectorRotation*>(inst)->isFullRotationAllowed()) priority -= 50; // for conditional instructions setting flags themselves not preceding the other instructions depending on same // flags if(inst->doesSetFlag()) priority -= 60; // loading/calculation of literals get smaller priority, since they are used mostly locally if(std::all_of(inst->getArguments().begin(), inst->getArguments().end(), [](const Value& val) -> bool { return val.getLiteralValue() || val.hasRegister(REG_ELEMENT_NUMBER) || val.hasRegister(REG_QPU_NUMBER); })) priority -= 80; // given branches a lower priority moves them to the end of the block where they belong if(dynamic_cast<const intermediate::Branch*>(inst)) priority -= 90; // mutex_acquire gets the lowest priority to not extend the critical section if(inst->readsRegister(REG_MUTEX)) priority -= 100; return -priority; } bool operator()(intermediate::IntermediateInstruction* x, intermediate::IntermediateInstruction* y) { int prioX; auto it = priorities.find(x); if(it != priorities.end()) prioX = it->second; else prioX = priorities[x] = ratePriority(x); int prioY; it = priorities.find(y); if(it != priorities.end()) prioY = it->second; else prioY = priorities[y] = ratePriority(y); if(prioX == prioY) return x < y; return prioX < prioY; } // caches priorities per instruction, so we do not have to re-calculate them FastMap<intermediate::IntermediateInstruction*, int> priorities; explicit NodeSorter(std::size_t numEntries) { priorities.reserve(numEntries); } }; // TODO OpenSet leaks all pending instructions if exception is thrown using OpenSet = SortedSet<intermediate::IntermediateInstruction*, NodeSorter>; using DelaysMap = FastMap<const intermediate::IntermediateInstruction*, std::size_t>; static constexpr int DEFAULT_PRIORITY = 1000; // needs to be larger then the default priority to disregard in any case static constexpr int MIN_PRIORITY = 2000; static int calculateSchedulingPriority(analysis::DependencyEdge& dependency, BasicBlock& block) { PROFILE_START(calculateSchedulingPriority); int latencyLeft = static_cast<int>(dependency.data.numDelayCycles); auto it = --block.end(); while(it != block.begin() && latencyLeft > 0) { if(it->get() == dependency.getInput().key) // we found the dependent instruction break; if(*it && (*it)->mapsToASMInstruction()) --latencyLeft; --it; } if(latencyLeft <= 0 && !dependency.data.isMandatoryDelay) { auto instr = dependency.getOutput().key; // also value instructions freeing resources (e.g. reading periphery/releasing mutex/last read of locals) // and devalue instructions locking resources and using new registers, as well as instructions only depending on // literals if(instr->writesRegister(REG_MUTEX) || instr->writesRegister(REG_VPM_DMA_LOAD_ADDR) || instr->writesRegister(REG_VPM_DMA_STORE_ADDR)) latencyLeft -= 3; if(instr->readsRegister(REG_TMU_OUT) || instr->readsRegister(REG_VPM_IO) || instr->writesRegister(REG_TMU0_ADDRESS) || instr->writesRegister(REG_TMU1_ADDRESS)) latencyLeft -= 4; if(instr->readsRegister(REG_VPM_DMA_LOAD_WAIT) || instr->readsRegister(REG_VPM_DMA_STORE_WAIT) || instr->readsRegister(REG_MUTEX)) latencyLeft += 2; if(std::any_of(instr->getArguments().begin(), instr->getArguments().end(), [&](const Value& arg) -> bool { return arg.checkLocal() && arg.local()->getUsers(LocalUse::Type::READER).size() == 1; })) --latencyLeft; if(instr->checkOutputLocal() && instr->getOutput()->getSingleWriter() == instr) latencyLeft += 2; if(std::all_of(instr->getArguments().begin(), instr->getArguments().end(), [&](const Value& arg) -> bool { return arg.getLiteralValue() || arg.hasRegister(REG_QPU_NUMBER) || arg.hasRegister(REG_ELEMENT_NUMBER); })) ++latencyLeft; } // if variable latency, return remaining latency (to achieving best case) // otherwise, return MIN_PRIORITY PROFILE_END(calculateSchedulingPriority); return (latencyLeft > 0 && dependency.data.isMandatoryDelay) ? MIN_PRIORITY : latencyLeft; // TODO also look into the future and keep some instructions (e.g. vector rotations/arithmetics) close to their // use?? (would need to calculate priority of uses and deduct distance) // or look into the future and calculate the maximum mandatory (+preferred) delay between this instruction and the // end of block (e.g. maximum path for all dependent delays) -> prefer maximum mandatory delay > maximum preferred // delay > any other. Or directly calculate remaining delay into priority mandatory/preferred. Delay "behind" // instruction can be calculated once per instruction?! } static int checkDependenciesMet(analysis::DependencyNode& entry, BasicBlock& block, OpenSet& openNodes) { if(!entry.hasIncomingDependencies()) return true; int schedulingPriority = 0; entry.forAllIncomingEdges([&](analysis::DependencyNode& neighbor, analysis::DependencyEdge& edge) -> bool { if(openNodes.find(const_cast<intermediate::IntermediateInstruction*>(neighbor.key)) != openNodes.end()) { // the dependent instruction was not yet scheduled, cannot schedule schedulingPriority = MIN_PRIORITY; return false; } // at this point, the dependent instruction is already scheduled else if(edge.data.numDelayCycles == 0) { // simple dependency to maintain order, is already given -> check other dependencies return true; } else { int priority = calculateSchedulingPriority(edge, block); if(priority == 0) { // dependency is completely met -> check other dependencies return true; } schedulingPriority += priority; } return true; }); return schedulingPriority; } static OpenSet::const_iterator selectInstruction(OpenSet& openNodes, analysis::DependencyGraph& graph, BasicBlock& block, const DelaysMap& successiveMandatoryDelays, const DelaysMap& successiveDelays) { // iterate open-set until entry with no more dependencies auto it = openNodes.begin(); std::pair<OpenSet::const_iterator, int> selected = std::make_pair(openNodes.end(), DEFAULT_PRIORITY); auto lastInstruction = block.walkEnd().previousInBlock(); PROFILE_START(SelectInstruction); while(it != openNodes.end()) { // select first entry (with highest priority) for which all dependencies are fulfilled (with latency) int priority = checkDependenciesMet(graph.assertNode(*it), block, openNodes); if(priority < MIN_PRIORITY) priority -= static_cast<int>(successiveMandatoryDelays.at(*it)); // TODO use preferred delays? // TODO remove adding/removing priorities in calculateSchedulingPriority? // TODO remove extra cases here? // TODO need to combine more instructions! // TODO success rate (i.e. emulation tests) is good, need to optimize performance // TODO is putting too much pressure on mutex lock (15% more than before) if(priority < std::get<1>(selected) || // keep instructions writing the same local together to be combined more easily // TODO make better/check result (priority == std::get<1>(selected) && lastInstruction->checkOutputLocal() && (*it)->writesLocal(lastInstruction->getOutput()->local())) || // keep vector rotations close to their use by devaluing them after all other equal-priority instructions (priority == std::get<1>(selected) && lastInstruction.get<intermediate::VectorRotation>() && dynamic_cast<const intermediate::VectorRotation*>(*it) == nullptr) || // prefer reading of r4 to free up space in TMU queue/allow other triggers to write to r4 (priority == std::get<1>(selected) && (*it)->readsRegister(REG_TMU_OUT)) || // prefer anything over locking mutex (priority == std::get<1>(selected) && std::get<0>(selected) != openNodes.end() && (*std::get<0>(selected))->readsRegister(REG_MUTEX))) { std::get<0>(selected) = it; std::get<1>(selected) = priority; } // TODO some more efficient version? E.g. caching priorities, check from lowest, update, take new lowest ++it; } PROFILE_END(SelectInstruction); if(std::get<0>(selected) != openNodes.end()) { CPPLOG_LAZY(logging::Level::DEBUG, log << "Selected '" << (*std::get<0>(selected))->to_string() << "' as next instruction with remaining latency of " << std::get<1>(selected) << logging::endl); return std::get<0>(selected); } return openNodes.end(); } // FIXME largely extends usage-ranges and increases pressure on registers // FIXME increases mutex-ranges!! // TODO make sure no more than 4(8?) TMU requests/responds are queued at any time (per TMU?) // - Specification documents 8 entries of single row (for general memory query), but does not specify whether one queue // or per TMU // - Tests show that up to 8 requests per TMU run (whether result is correct not tested!!), 9+ hang QPU /* * Select an instruction which does not depend on any instruction (not yet scheduled) anymore and insert it into the * basic block */ static void selectInstructions(analysis::DependencyGraph& graph, BasicBlock& block, const DelaysMap& successiveMandatoryDelays, const DelaysMap& successiveDelays) { // 1. "empty" basic block without deleting the instructions, skipping the label auto it = block.walk().nextInBlock(); OpenSet openNodes(NodeSorter(block.size())); while(!it.isEndOfBlock()) { if(it.has() && !(it.get<intermediate::Nop>() && !it->hasSideEffects() && it.get<const intermediate::Nop>()->type != intermediate::DelayType::THREAD_END)) // remove all non side-effect NOPs openNodes.emplace(it.release()); it.erase(); } // 2. fill again with reordered instructions while(!openNodes.empty()) { auto inst = selectInstruction(openNodes, graph, block, successiveMandatoryDelays, successiveDelays); if(inst == openNodes.end()) { // no instruction could be scheduled not violating the fixed latency, insert NOPs CPPLOG_LAZY(logging::Level::DEBUG, log << "Failed to schedule an instruction, falling back to inserting NOP" << logging::endl); block.walkEnd().emplace(new intermediate::Nop(intermediate::DelayType::WAIT_REGISTER)); } else { block.walkEnd().emplace(*inst); openNodes.erase(inst); } } } bool optimizations::reorderInstructions(const Module& module, Method& kernel, const Configuration& config) { for(BasicBlock& bb : kernel) { auto dependencies = analysis::DependencyGraph::createGraph(bb); // calculate required and recommended successive delays for all instructions DelaysMap successiveMandatoryDelays; DelaysMap successiveDelays; PROFILE_START(CalculateCriticalPath); for(const auto& node : dependencies->getNodes()) { // since we cache all delays (also for all intermediate results), it is only calculated once per node node.second.calculateSucceedingCriticalPathLength(true, &successiveMandatoryDelays); node.second.calculateSucceedingCriticalPathLength(false, &successiveDelays); } PROFILE_END(CalculateCriticalPath); selectInstructions(*dependencies, bb, successiveMandatoryDelays, successiveDelays); } return false; }
[ "stadeldani@web.de" ]
stadeldani@web.de
3b10932986b78cfe9b9ba00999e1f17de41461db
dd5b5e5ee5476d1eeffc4987e1aeec94e047e6dd
/testCase/cavity/0.1315/currentcloudofpoints
c8f902851c9de823456c36f29a73ff0ad5ea6624
[]
no_license
Cxb1993/IBM-3D
5d4feca0321090d570089259a558585a67a512ec
2fceceb2abf1fc9e80cb2c449cc14a8d54e41b89
refs/heads/master
2020-05-24T01:14:02.684839
2018-10-23T13:15:20
2018-10-23T13:15:20
186,721,487
1
0
null
2019-05-15T00:39:55
2019-05-15T00:39:55
null
UTF-8
C++
false
false
64,774
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v1806 | | \\ / A nd | Web: www.OpenFOAM.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class vectorField; location "0.1315"; object currentcloudofpoints; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // 2409 ( (1.40817 1.62496 1.46488) (0.608978 1.36629 1.224) (1.26563 1.14782 1.31298) (1.65058 1.71803 0.768521) (1.3098 1.80687 1.18062) (1.40282 1.43146 0.726661) (1.451 1.24806 1.30651) (0.881215 1.18145 0.792413) (1.44197 1.05641 0.993373) (0.935045 0.900532 0.832127) (1.18981 1.13338 1.53423) (1.34254 1.02134 1.41338) (1.67188 1.36981 1.20757) (1.43525 1.4806 1.08311) (1.36647 1.05632 1.27084) (1.17839 1.11866 1.39781) (1.39041 1.02068 1.39768) (1.3836 1.66361 0.880729) (1.73791 1.36392 1.19604) (1.47368 1.23198 1.39726) (0.435815 0.931259 1.15701) (0.671624 1.54693 1.11704) (1.52972 1.27754 1.58165) (1.50852 1.64744 1.2285) (0.467331 1.35179 1.11345) (0.746294 1.04268 1.53112) (0.454626 1.16976 1.31941) (0.876395 1.48217 1.65268) (1.27275 1.44627 1.41667) (1.32118 1.55718 0.622938) (0.821872 1.26588 0.790153) (1.42334 1.42014 0.626835) (0.937725 1.32655 0.717384) (0.804609 1.39015 0.893136) (1.19541 1.09774 0.642876) (1.4115 1.16551 0.904927) (1.40357 1.44745 0.629012) (1.54463 1.24033 0.562654) (0.976786 1.22331 0.365081) (0.764353 1.17422 0.507388) (0.738698 1.36458 0.828708) (1.03854 0.865244 0.932873) (1.3523 1.2179 0.811509) (1.50537 1.19797 0.520705) (0.643975 1.17916 0.564293) (0.865223 1.40899 0.381317) (0.945376 1.37512 0.466614) (1.53327 1.66438 1.20735) (1.31227 1.26671 1.67229) (1.2897 1.47531 1.51134) (0.779167 1.10453 1.04431) (1.54949 1.64432 1.17289) (1.54012 1.59706 1.49228) (1.29573 1.35927 1.57844) (1.69844 1.30298 1.20192) (1.22308 1.43291 1.51458) (1.20355 1.0136 1.18929) (1.43011 1.61891 0.501992) (1.15992 1.77827 1.00946) (1.17786 1.5832 0.437051) (1.49119 1.61863 0.998932) (0.711039 1.40151 0.74712) (1.27288 1.37647 0.789055) (0.574512 1.5531 0.886183) (1.4975 1.26867 0.618763) (1.13468 1.03417 1.16056) (1.40303 1.61298 1.29216) (1.65045 1.48986 1.28824) (1.41885 1.38627 0.684924) (1.40711 1.64663 1.15898) (0.48639 0.942092 1.14134) (1.54383 1.71741 1.16272) (0.762608 1.30606 1.36962) (1.23261 1.74203 0.747304) (1.29354 1.28581 0.57478) (1.73255 1.11606 1.14275) (1.66615 1.11371 1.22839) (1.24497 1.18355 1.40858) (0.747281 1.20484 1.05363) (1.78928 1.3737 1.35965) (1.6488 1.0816 1.20148) (1.78832 1.0822 1.13831) (1.27753 1.15645 1.3721) (0.613223 1.07703 1.14943) (0.547725 1.36721 1.29478) (0.783204 1.0982 1.47957) (1.20903 1.40392 1.61939) (0.97036 1.07894 1.60098) (0.928424 1.01074 1.57391) (1.49764 1.09779 1.474) (0.792227 0.967523 1.412) (0.487965 1.27454 1.42451) (0.497785 1.54626 1.3025) (1.06625 1.33287 1.57599) (0.915169 1.03068 1.51303) (0.950745 1.30512 1.34403) (1.17259 1.75096 1.35856) (1.26091 1.18032 1.53495) (0.939708 1.3543 1.53508) (1.2637 1.04177 1.50739) (1.06679 1.14766 1.38193) (1.31188 1.05412 1.33115) (1.23225 1.07946 1.37465) (1.09592 1.28902 0.938008) (1.44627 1.05676 1.04644) (1.36303 1.02457 1.57845) (0.906529 1.35748 1.38506) (1.20885 1.06016 1.4319) (1.05332 1.12443 1.29155) (1.24275 1.06754 1.36265) (1.2728 1.29233 1.28167) (1.32673 1.14757 1.00217) (1.4594 1.03137 1.02499) (0.889185 0.791652 0.812402) (0.626963 1.5505 1.08323) (0.815113 1.40503 0.57701) (0.706133 1.73388 0.80875) (0.845519 1.29842 0.566316) (1.13941 1.02078 0.408194) (1.03514 1.04942 0.355595) (1.00905 1.09274 1.07919) (1.12253 1.22904 0.281859) (0.984109 1.72919 0.977966) (0.931964 1.25602 1.19454) (1.07411 0.914058 0.491562) (0.673065 1.33377 0.659689) (1.16419 1.04413 0.487337) (1.06469 1.27429 0.40193) (1.39497 1.09311 0.948397) (1.13358 1.19749 0.963702) (0.794421 1.23235 0.829456) (1.43537 1.40274 0.880596) (1.19013 1.40153 0.508291) (1.14043 1.36849 0.59349) (1.11491 1.01045 0.676456) (1.41802 1.07494 0.968677) (1.28286 1.1779 0.906211) (1.00406 1.05014 0.995402) (0.742531 1.4373 0.622082) (1.21701 1.36076 0.408421) (1.21661 1.31478 0.45219) (1.17724 1.33919 0.613042) (1.26048 1.06664 0.399776) (1.58864 1.64731 1.31864) (1.3131 1.71653 1.43005) (1.4904 1.43898 1.40858) (1.20234 1.54892 1.12192) (0.900001 1.22734 1.4781) (0.750636 0.882135 1.08769) (1.38185 1.12486 1.06293) (1.30999 1.72925 1.23832) (1.2729 1.3908 0.853223) (1.44081 1.34808 0.506909) (1.58703 1.41964 1.40007) (1.318 1.66698 1.34024) (1.15141 1.34284 1.67338) (0.81493 0.873113 1.15617) (1.48546 1.06268 1.25234) (1.47139 1.76182 0.585913) (1.41903 1.72751 0.606805) (1.57353 1.79971 0.714372) (1.31589 1.33339 0.923207) (1.27407 1.66058 0.469233) (0.767715 1.28536 0.700627) (0.972878 1.51688 0.42855) (1.15814 1.48024 1.11109) (1.35524 1.68271 0.708085) (1.42846 1.70287 0.598642) (1.42815 1.80195 0.754026) (1.23662 1.73489 0.504845) (1.10605 1.55516 0.377168) (1.26393 1.05793 0.411123) (1.27324 1.08506 0.400475) (0.908205 0.830432 0.795881) (1.47114 1.42272 0.883328) (1.10127 1.70232 1.44408) (1.29691 1.61479 0.888694) (1.46225 1.23062 1.41325) (1.40592 1.44619 1.19943) (0.784766 1.36788 1.21236) (1.11965 1.73812 0.775731) (0.951043 1.70562 0.983897) (1.35447 1.71726 0.609868) (0.927514 1.42647 0.345238) (1.74984 1.45891 1.35204) (1.50083 1.06915 1.34637) (0.834275 1.07071 1.07912) (0.721283 1.31923 1.333) (1.36508 1.31051 0.754388) (1.54339 1.32573 1.25233) (1.33621 1.27762 0.794048) (1.58823 1.19651 1.0572) (1.74418 1.30062 1.14411) (1.54244 1.25098 1.23572) (1.20013 1.29757 0.99401) (1.59094 1.34442 1.33747) (1.13497 1.40873 1.57988) (1.80163 1.30708 1.23879) (1.34674 1.30022 0.821783) (1.63008 1.206 1.25547) (1.73192 1.30439 1.13952) (1.27029 1.23827 1.06749) (1.35736 1.16947 0.987686) (1.14521 1.55144 0.485624) (1.18947 1.22471 0.48348) (0.923876 1.21978 0.837979) (1.15074 1.3475 1.31954) (1.47115 1.67096 1.30102) (0.726647 1.28449 1.31258) (0.506441 1.53315 0.718277) (0.671842 1.20521 0.424388) (0.604445 1.66164 0.811576) (1.21042 1.67172 0.633234) (1.31997 1.27195 0.576897) (0.887553 1.33702 0.755559) (1.40765 1.26803 1.05251) (1.36645 1.36304 1.05079) (1.55881 1.78025 1.08485) (1.65018 1.04751 1.24281) (1.14301 1.31645 1.52752) (1.46621 1.0981 1.16415) (1.53037 1.07875 1.11614) (1.5844 0.988999 1.2656) (1.13605 1.68883 1.13905) (1.70561 1.24203 0.931913) (1.80978 1.39782 1.04289) (1.44486 1.30376 0.497229) (1.67727 1.09875 1.04814) (1.64934 0.994157 1.20546) (1.17079 1.17719 0.877487) (1.54086 1.18638 1.30175) (1.59763 1.02766 1.24452) (1.63263 1.04683 1.16411) (1.21887 1.61903 1.03206) (0.894546 1.39973 1.3985) (1.44294 1.29655 1.55606) (1.32501 1.30411 0.795958) (1.15109 1.30387 0.959239) (1.53701 1.63797 1.10685) (1.27662 1.38599 0.908811) (1.6503 1.67584 1.07159) (1.46502 1.07454 1.2973) (1.72338 1.37021 1.05805) (1.22626 1.58405 1.02235) (0.787192 1.29479 1.26828) (1.46558 1.1528 1.08475) (1.55068 1.74086 1.09055) (1.16294 1.5553 0.623635) (1.50862 1.23336 1.22744) (1.63836 1.19627 0.948296) (1.84232 1.14887 1.16706) (0.905991 1.2367 1.51071) (1.13894 1.15404 1.4224) (1.02221 1.14611 1.25194) (0.939527 0.97331 1.33037) (0.891966 1.31726 1.54444) (1.35964 1.05293 1.16109) (1.36709 1.11787 1.05758) (1.38682 1.09212 1.25385) (1.39196 1.10975 1.07724) (1.40505 1.06716 1.18284) (1.64426 1.09909 1.29577) (1.40792 1.09152 1.11154) (1.24515 1.24045 1.00281) (1.59473 1.11423 1.33509) (1.17023 1.27827 1.03446) (1.2016 1.39965 1.04669) (1.42123 1.10634 1.15181) (1.38935 1.12105 1.03317) (1.4677 1.10585 1.06907) (1.40461 1.08903 1.05682) (1.46261 1.08791 1.04652) (1.43214 1.10189 1.01323) (1.53457 1.13089 1.14945) (1.32953 1.20663 1.03163) (1.49462 1.2744 1.15479) (1.43126 1.39933 1.05776) (1.24013 1.59145 1.02114) (1.42505 1.38687 1.08598) (1.57183 1.58064 1.23165) (1.25724 1.79897 1.18832) (1.27732 1.72988 1.20613) (1.56479 1.60778 1.26733) (1.7734 1.43786 1.03238) (1.63238 1.20789 0.986431) (1.16309 1.75001 1.48459) (1.67141 1.03934 1.19099) (1.62964 1.18225 1.13505) (1.8472 1.27477 1.26964) (1.68425 1.32431 1.08701) (1.55956 1.27647 1.25776) (1.67427 1.06452 1.21431) (1.48652 1.16554 1.14422) (1.53515 1.2602 1.21695) (1.58222 1.18553 1.30573) (1.55754 1.1755 1.23793) (1.31853 1.76861 1.20517) (1.32071 1.77393 1.13428) (1.29869 1.7657 1.11659) (1.41953 1.33128 1.07652) (1.59109 1.78713 1.13518) (1.27694 1.77694 1.15006) (1.28401 1.36153 0.885303) (1.72153 1.18648 0.98381) (1.57368 1.37912 0.892491) (1.46309 1.39702 1.62473) (1.6273 1.10562 1.30128) (1.65433 1.19794 1.39925) (1.20631 1.11958 1.41464) (1.56983 1.05585 1.25137) (1.66288 1.14805 1.06998) (1.51313 1.31913 0.981007) (1.37615 1.15828 1.39182) (0.838532 1.20825 1.35456) (1.10426 1.35985 1.5299) (0.608658 1.30172 1.26106) (1.68075 1.49465 1.07364) (1.67141 1.12296 1.25968) (1.65621 1.01047 1.21588) (1.58762 1.22824 1.02597) (1.7616 1.36027 1.02975) (1.64287 1.21337 1.31769) (1.83233 1.23487 1.1247) (1.61887 1.00767 1.2477) (1.64306 1.00564 1.22054) (1.62304 0.999026 1.24108) (1.63881 1.01412 1.17564) (1.7405 1.43516 1.06875) (1.68173 1.58858 1.37763) (1.17497 1.75262 1.07803) (1.25933 1.86439 1.15006) (1.36534 1.79962 1.21402) (1.15445 1.47769 1.14194) (1.24502 1.62266 1.09286) (1.36109 1.34997 0.800609) (1.11003 1.58215 1.4656) (1.35666 1.65815 1.43506) (1.20518 1.48796 0.582191) (1.09244 1.6402 1.16819) (1.23397 1.35171 0.554843) (1.60765 1.41192 1.40482) (0.807319 1.26952 0.809085) (1.32558 1.06004 0.765044) (1.46021 1.38189 1.36276) (1.49901 1.45308 1.40378) (1.25999 1.77729 0.717497) (1.06361 1.64441 1.53308) (1.37344 1.43728 0.728739) (1.05192 1.13716 1.54729) (1.35488 1.1474 1.03894) (1.42791 1.09629 1.12934) (0.900771 1.34562 1.34301) (0.796563 1.20152 1.03721) (1.35439 1.7902 1.32204) (1.56935 1.40481 1.35614) (1.27609 1.76136 1.17084) (1.62628 1.6359 1.13754) (1.44733 1.17189 1.39631) (1.56847 1.29242 0.891218) (1.57177 1.16044 1.23665) (0.598809 1.30506 1.2336) (0.802356 1.34482 1.24631) (1.02969 1.52549 1.29019) (0.725842 1.59598 1.12957) (1.77564 1.52026 1.06202) (1.58283 1.02216 1.15049) (1.53607 1.00283 1.16552) (1.44776 1.03781 1.12688) (1.6036 1.13632 1.19903) (1.56686 1.00346 1.21465) (1.66291 1.3664 0.936683) (1.49928 1.092 1.25603) (1.18908 1.71695 1.09654) (1.67299 1.59004 1.34414) (1.50861 1.3861 1.06707) (1.74347 1.41435 1.09094) (1.68843 1.14685 1.04441) (1.62038 1.23691 0.939453) (1.66152 1.42442 1.12415) (1.58279 1.0767 1.21621) (1.06437 1.23262 1.63751) (0.624808 1.53901 1.31261) (0.706276 1.27095 1.16448) (0.533225 1.34657 1.40976) (0.704248 1.42358 1.51973) (1.12806 1.41488 1.65604) (0.491443 1.03135 1.33687) (1.45921 1.48202 0.726161) (1.0271 1.09049 1.39935) (1.31791 1.32732 1.66078) (0.836905 1.09682 1.507) (1.34105 1.43225 0.720619) (0.865118 1.19919 1.63593) (0.542316 1.33349 1.21121) (1.16241 1.54297 1.62496) (0.847928 1.19477 0.933374) (0.467602 1.40707 1.29717) (1.04096 1.16087 1.6572) (0.292504 1.19939 1.14371) (0.708208 1.18726 1.61651) (1.10624 1.23255 1.61291) (1.05683 1.69627 1.27483) (1.16799 1.43768 1.64333) (0.839874 1.07032 1.49605) (1.00305 1.23904 1.39227) (1.42337 1.56653 1.2396) (1.42498 1.29589 1.32703) (0.611429 1.47628 1.34118) (0.571331 1.2563 1.12915) (0.586933 1.35935 1.10179) (0.780534 1.16038 1.37615) (0.77555 0.948198 1.54686) (1.24395 1.15529 1.23598) (1.27678 0.99943 1.40766) (0.716994 1.58226 0.975746) (1.30254 1.46907 1.33) (1.55506 1.53801 1.34285) (0.342304 0.978513 1.12383) (0.362605 1.14779 1.26884) (0.890044 1.03424 1.37338) (0.90172 1.42729 1.53924) (0.250603 1.23181 0.921965) (0.587863 1.34597 1.38982) (0.493287 1.41874 1.27634) (0.709241 1.12374 1.1959) (0.276935 1.38266 1.07872) (0.281413 1.18855 1.09587) (0.51657 1.39527 1.28283) (0.971113 1.02368 1.57538) (1.41606 1.28794 1.06314) (1.11753 1.12311 1.6607) (0.912288 0.971009 1.42254) (0.593444 1.38128 1.04303) (1.51211 1.07744 1.22701) (1.47504 1.07898 1.13406) (1.22597 1.43935 1.60398) (0.901664 1.31742 1.07333) (0.842806 1.32115 1.09742) (0.791195 1.43588 1.46331) (0.912992 1.39732 1.0423) (1.06487 1.45647 1.2476) (0.493573 1.51159 1.41759) (0.609961 1.51656 1.23928) (1.30466 1.75726 1.37283) (0.793863 1.6221 1.54652) (0.646022 1.31352 1.59114) (1.24057 1.50679 1.37956) (0.812422 1.20502 1.47793) (0.437668 0.870757 1.18487) (0.280816 1.27997 1.17398) (0.510587 1.36616 1.46577) (0.90211 1.14108 1.24593) (1.39107 1.39003 0.71978) (0.869722 0.825962 0.683167) (0.730276 1.59571 1.30721) (1.4169 1.6647 1.10104) (0.848639 1.58304 1.03551) (1.32002 1.70125 1.44272) (1.56104 1.75038 0.713377) (1.23596 1.37499 0.777699) (1.03096 1.20759 1.66907) (0.899361 1.24554 1.50642) (1.54662 1.73853 1.10797) (1.1667 1.45587 1.63491) (1.30681 1.66985 1.48573) (1.15079 1.44055 1.65127) (1.11853 1.52032 1.66007) (1.16953 1.28802 1.60046) (1.08265 1.50445 1.66633) (0.631975 1.29932 1.56091) (1.05566 1.11933 1.65704) (0.857169 1.31158 1.53804) (0.964459 1.13087 1.61725) (0.591419 1.3522 1.07556) (0.993036 1.15476 1.64267) (1.07051 1.21294 1.64428) (1.006 1.15784 1.65376) (0.773143 0.936506 1.12953) (1.09378 1.23531 1.65325) (1.3904 1.74493 1.38119) (1.29221 1.42612 1.12785) (1.21214 1.35072 1.63236) (1.19808 1.43391 1.59708) (1.19971 1.38758 1.62411) (1.16827 1.32808 1.64734) (1.25993 1.41994 0.689452) (1.30643 1.75588 1.35326) (0.857127 0.870851 1.1838) (0.473079 1.21648 1.03622) (1.34719 1.54512 1.01192) (0.591035 1.36033 1.09212) (1.12171 1.13738 1.51576) (0.929294 1.31683 1.37677) (1.20284 1.13619 1.59688) (0.929197 1.43306 1.24863) (1.15284 1.3925 1.66511) (1.37569 1.61565 1.08431) (0.502084 1.42805 1.38875) (0.940686 1.62188 1.50896) (1.01375 1.23478 1.14739) (0.649737 1.42791 1.20855) (1.52059 1.49614 1.30706) (0.79469 1.17557 1.04212) (0.867262 1.20154 1.50285) (1.4607 1.48057 0.711426) (1.19831 1.65026 0.993858) (1.59529 1.61774 1.31767) (1.41848 1.47402 0.992243) (1.18669 1.5042 1.37467) (1.14296 1.26564 1.58845) (0.870268 0.889107 1.15996) (0.673473 1.35214 1.5541) (0.82837 1.43735 1.64824) (1.00026 1.60806 1.30471) (1.08464 0.842396 0.708933) (0.843009 1.56655 1.12574) (0.976476 1.42627 1.22397) (1.21927 1.46943 1.21198) (1.48319 1.60571 1.11454) (1.56316 1.53169 0.982412) (1.38465 1.63083 1.18156) (0.735651 1.42117 1.24361) (0.82086 1.55115 1.62141) (0.831244 1.37241 1.64089) (1.62504 1.40697 1.44579) (1.15025 1.46392 1.37524) (0.937415 1.18992 1.63951) (0.929762 1.1857 1.61562) (1.33257 1.53934 0.520705) (0.864925 1.52987 1.56655) (0.982475 1.38665 1.71152) (0.864607 1.06363 1.50914) (0.745852 1.29937 1.67424) (0.828937 1.66208 1.44395) (0.570104 1.23938 1.14578) (1.15169 1.28339 1.61834) (0.672692 1.32555 1.59005) (0.884186 1.28571 1.20264) (0.998522 1.30279 1.5297) (0.878137 1.76983 0.817638) (1.15204 1.6432 1.15624) (0.538413 1.57974 1.28673) (0.568685 1.49367 1.48704) (0.626071 1.56141 1.33547) (1.43646 1.57547 1.01543) (0.9275 1.41381 0.920502) (0.668945 1.19832 1.64959) (0.907538 1.13959 1.41333) (0.559105 1.18635 1.49877) (0.470913 1.66171 0.782661) (1.17335 1.72302 0.948063) (1.15395 1.04978 0.678171) (0.420534 1.34749 0.640679) (1.39673 1.70366 0.913621) (1.27459 1.72862 0.669641) (1.21835 1.75396 0.818059) (1.03087 1.32478 0.367631) (0.534015 1.11067 0.57445) (1.57831 1.73395 0.736738) (1.50531 1.69656 0.748192) (1.17777 1.54042 0.639784) (0.882864 1.83027 0.776749) (0.410152 1.6069 0.790352) (0.454565 1.2381 0.582106) (1.4224 1.63735 0.680281) (0.921133 1.49869 0.413464) (0.455857 1.49107 0.686932) (0.942941 0.899503 0.652742) (0.715161 1.33185 0.383236) (0.71467 1.7357 0.895906) (0.52919 1.58856 0.563377) (0.968407 1.27267 0.984897) (0.522997 1.46446 0.642493) (1.46448 1.59895 0.618152) (0.749117 1.19287 0.386951) (0.909951 1.05296 0.664582) (0.994564 0.873029 1.21527) (1.03683 1.61521 0.430202) (0.862403 1.76625 1.04074) (0.906308 1.36982 0.233297) (1.25912 1.45106 0.558978) (1.41407 1.80731 0.64505) (0.839913 1.49702 0.384296) (0.885762 1.68543 0.457075) (1.3827 1.30672 0.355617) (0.5049 1.63246 1.00352) (0.461176 1.46782 0.765607) (1.02507 0.828146 0.776296) (1.07733 1.07187 0.902736) (0.499134 1.49768 0.669025) (0.983634 1.26918 1.08849) (1.408 1.5646 0.640402) (0.436162 1.40624 0.616999) (0.923968 1.3624 0.646847) (0.881304 1.27974 0.278342) (1.10166 1.40733 0.434673) (0.826428 1.41163 0.64824) (1.29627 1.64702 0.528935) (0.726575 1.61998 1.03046) (1.13986 1.43701 0.448452) (1.03045 1.53562 0.376276) (0.739573 1.34635 0.346899) (0.752721 1.73415 0.877233) (1.33272 1.62736 0.573271) (1.28973 1.6167 0.726431) (0.958342 1.66224 1.03031) (0.846143 1.50248 0.319392) (1.05219 1.25134 0.306657) (1.15507 1.20261 0.532476) (1.18108 0.996818 0.672119) (1.38938 1.72086 0.62811) (1.19376 1.80269 0.621322) (1.16173 1.80422 0.582403) (1.34911 1.61763 0.743562) (1.44388 1.64221 0.655381) (1.37526 1.3059 0.701197) (1.42557 1.29783 0.611105) (1.4566 1.63177 0.594755) (1.33525 1.74081 0.709457) (1.31465 1.60849 0.928857) (1.411 1.79741 0.790676) (1.35797 1.80582 0.805129) (1.04953 0.869699 0.509877) (0.896949 1.06817 0.360258) (1.09446 1.6531 0.531402) (1.17066 1.70025 0.500586) (1.03405 1.22667 0.309821) (0.565205 1.47762 0.637975) (0.733014 1.33503 0.416609) (0.873988 1.20483 0.541862) (1.03738 1.25112 1.15324) (0.603156 1.12174 0.492199) (1.09146 1.06106 0.653585) (1.1447 1.31669 0.473565) (1.0122 1.0566 0.37879) (0.437788 1.62367 0.932512) (1.16627 1.78715 0.576875) (0.777819 1.68061 0.797268) (0.912275 1.66237 0.890071) (1.37781 1.62476 0.719614) (0.839348 1.37467 0.986142) (0.833672 1.5003 0.744657) (1.19271 1.79026 0.549577) (0.893295 1.74988 0.984748) (0.852112 1.33751 0.366345) (1.13128 1.37093 1.16017) (0.58729 1.56821 1.0875) (0.589062 1.72031 0.71423) (0.937543 1.46915 0.26177) (1.2233 1.62675 0.558836) (1.08039 1.34021 0.387739) (1.47231 1.23587 0.540769) (0.638203 1.39502 0.993624) (0.857237 1.22693 0.573926) (1.13012 1.71884 0.938665) (1.42156 1.60478 0.680566) (1.14581 1.54945 0.637189) (1.67982 1.58426 0.70934) (1.4358 1.69079 0.748729) (1.55963 1.7409 0.667046) (1.08858 1.53534 0.390317) (1.33989 1.69517 0.514649) (0.672711 1.14941 0.418454) (1.16928 1.59113 0.592007) (1.15561 1.64446 0.559805) (0.888205 1.32298 0.9324) (1.28152 1.72334 0.624127) (1.34537 1.30403 0.764244) (1.06506 1.16743 0.393937) (0.913334 1.59431 0.556962) (0.883304 1.75381 0.995929) (1.06397 1.15267 0.407795) (1.21662 1.61251 0.499283) (0.419 1.46125 0.611249) (0.447973 1.38644 0.73485) (1.14623 0.876621 0.74151) (0.492181 1.63562 0.744345) (0.447329 1.59445 0.718986) (0.908833 1.32933 0.993005) (0.81351 1.10053 0.9313) (0.795388 1.29236 0.413169) (0.80449 1.33619 1.4271) (1.39045 1.49476 0.894006) (0.581205 1.59161 0.633752) (0.62959 1.58321 1.08793) (1.24551 1.12562 1.2927) (0.410122 1.2888 0.839502) (0.744533 1.38948 0.513989) (1.64031 1.42927 0.70985) (1.20967 1.50804 1.12767) (0.885305 1.4579 0.877513) (0.839372 0.786928 0.596605) (0.90657 1.2763 0.695961) (1.09913 0.787542 0.844348) (0.741773 0.878095 0.592886) (1.34883 1.53555 0.535561) (1.33638 1.55389 0.601664) (0.976259 1.38961 0.454208) (1.60624 1.46135 1.36625) (1.10908 1.42765 0.468825) (0.813616 1.37085 0.924663) (1.39535 1.28745 0.69583) (1.40772 1.30736 0.683787) (0.797699 1.54176 1.01504) (1.26262 1.65143 0.766527) (1.2833 1.73817 0.815116) (1.12657 1.64312 0.653142) (1.32404 1.65233 0.82987) (0.911789 1.26966 0.989331) (0.754617 0.815408 0.625452) (0.703153 1.37093 0.393861) (0.688367 1.26388 0.407783) (0.797362 1.74146 0.853451) (0.591737 1.66296 0.996591) (1.70067 1.674 0.66781) (1.47081 1.82164 0.847608) (1.61126 0.99456 0.822453) (0.759715 1.60218 1.03281) (1.35575 1.76246 0.749624) (1.45464 1.10194 0.936718) (0.656284 1.45661 0.770583) (1.53024 1.09585 0.689611) (1.55363 1.75903 0.924074) (1.58633 1.79088 0.899835) (1.37579 1.70967 0.650345) (1.59933 1.11241 0.799936) (1.50905 1.19711 0.713276) (1.54654 1.27733 0.611179) (1.67197 1.32918 0.844613) (1.12044 1.16051 0.598586) (1.39921 1.12428 0.914594) (0.65107 1.67622 0.882827) (1.45705 1.34435 0.852455) (1.27822 1.26255 1.0067) (1.53383 1.21858 0.964612) (1.56655 1.02667 0.776864) (1.40023 1.44475 0.869629) (1.45014 1.71219 0.591238) (1.6536 1.56469 0.924707) (1.60815 1.16833 0.720352) (1.36402 1.50035 0.746251) (1.17346 1.42124 0.499033) (1.34623 1.81698 0.986347) (1.40746 1.1395 0.977525) (0.920598 1.03945 0.756575) (1.69461 1.2848 0.748801) (1.46292 1.22214 0.947057) (1.24469 1.10487 0.701144) (1.38109 1.75324 0.64619) (1.31206 1.61098 1.27595) (1.29935 1.24393 0.952212) (1.41006 1.10992 0.981483) (1.43367 1.08682 0.956922) (1.67437 1.83194 0.86184) (1.53032 1.86617 0.788515) (1.70412 1.81417 0.825329) (1.58948 1.74643 0.813436) (1.69875 1.64123 0.655646) (1.72801 1.57762 0.635566) (1.63039 1.67473 0.891813) (1.71493 1.60984 0.89326) (1.70482 1.44378 0.828156) (1.68002 1.43964 0.615542) (1.69078 1.31047 0.743961) (1.7005 1.29682 0.794282) (1.34231 1.12968 0.618428) (1.01652 1.1781 0.910897) (1.36178 1.79862 1.00341) (1.03218 1.67314 0.616377) (1.34896 1.75863 1.0536) (1.53757 1.33405 0.887013) (1.53942 1.12145 0.859497) (1.41674 1.47561 0.754203) (1.5318 1.13486 0.867913) (1.61824 1.14672 0.755425) (1.70952 1.18715 0.809182) (0.946664 1.36325 0.76958) (1.26334 1.0842 0.726684) (1.72179 1.17548 0.783698) (1.19915 1.38216 0.992981) (1.52542 1.19119 1.13226) (1.37519 1.24163 1.00462) (1.28001 1.23846 1.06767) (1.19978 1.30364 0.95018) (1.42899 1.21301 1.05806) (1.35242 1.20474 0.983555) (0.877404 0.854676 0.502509) (1.24332 1.21946 0.285653) (1.07667 1.08217 0.788355) (1.47219 1.69361 0.63521) (1.37791 1.6477 0.735032) (1.27191 1.61633 1.06049) (1.52859 1.6122 0.560478) (1.34138 1.60346 0.774875) (1.40323 1.73746 0.639905) (1.25412 1.80212 1.07866) (1.23807 1.8141 1.02987) (1.41054 1.76874 0.935953) (1.42474 1.7544 0.679163) (1.51124 1.06811 0.912643) (1.50609 1.06412 0.869842) (1.42088 1.11064 0.919835) (1.19112 1.20687 0.904585) (1.33115 1.14405 0.926221) (1.43656 1.15337 0.978883) (1.43164 1.12165 0.959856) (1.49798 1.13908 0.984799) (1.41222 1.10521 0.942741) (1.33692 1.68404 0.712751) (1.48351 1.82058 0.755242) (1.63919 1.50165 0.660075) (1.36815 1.68386 0.681827) (1.17822 1.5653 0.685789) (1.12179 1.7272 0.474537) (1.53531 1.83396 0.78762) (1.4469 1.74255 1.0537) (1.19454 1.59245 0.673746) (1.36461 1.76325 0.547144) (1.08678 1.25883 0.641614) (1.1911 1.17901 0.469071) (0.857559 1.32803 0.744829) (1.06849 0.989395 0.78189) (0.749653 1.40815 0.726762) (1.7841 1.52455 0.816218) (1.42397 1.67884 0.903331) (1.35907 1.49341 0.497509) (1.50582 1.27619 0.64581) (0.81103 1.3001 0.75006) (0.807188 1.02054 1.10712) (1.61987 1.76897 0.762594) (1.31368 1.49242 0.496984) (1.34318 1.63725 0.820802) (1.45721 1.62249 0.953164) (1.76975 1.55069 0.861048) (1.1575 1.85294 0.710026) (1.51643 1.84855 0.714229) (0.962562 1.19566 0.626698) (1.33435 1.69483 0.7191) (0.643 1.42008 0.769315) (0.725801 1.47169 0.665113) (1.09545 1.35 0.684501) (1.34757 1.08393 0.553418) (0.663192 1.45779 0.73713) (1.08629 1.20597 0.769548) (1.15758 1.36215 0.655396) (0.977278 1.16306 0.924947) (1.27118 1.15083 0.886792) (1.13937 1.24489 0.605839) (0.858665 1.32543 0.708145) (1.49329 1.21647 0.98383) (1.29735 1.53941 0.701393) (1.52835 1.69284 1.01103) (1.44353 1.25635 0.732692) (1.35228 1.70565 0.682993) (1.6843 1.09248 0.845256) (1.56764 1.19139 0.67013) (1.61862 1.04353 0.726676) (1.46201 1.2184 1.01551) (1.60238 1.13352 0.655847) (1.36565 1.18463 0.814129) (1.61559 1.19021 0.765498) (1.18245 1.38476 0.932903) (1.32881 1.24914 0.886902) (1.45442 1.15116 0.944406) (0.682456 1.40843 0.77046) (0.990241 1.16512 0.931511) (1.57479 1.02277 0.745886) (1.15304 1.15814 0.623203) (1.18811 1.50903 0.728404) (0.799475 1.6076 0.836343) (0.677931 1.47517 0.747724) (0.752345 1.55654 0.968807) (1.59049 1.07356 0.930689) (1.66287 1.04322 0.838736) (1.65911 1.07201 0.86061) (1.65856 1.02405 0.739569) (1.39263 1.35977 0.843918) (0.948087 1.17041 0.899084) (1.1493 1.17312 0.599869) (0.592321 1.49154 0.873446) (1.10062 0.901716 0.689174) (1.29388 1.46538 1.36072) (1.44318 1.64021 1.16203) (1.30641 1.61867 1.54178) (1.42387 1.24205 1.50474) (1.46663 1.48965 1.46893) (1.51636 1.53598 1.46124) (1.35943 1.65648 1.3166) (1.26125 1.82524 1.18002) (1.22278 0.932428 1.23118) (1.39882 1.56422 1.25489) (1.51079 1.41628 1.6257) (1.18874 0.928644 1.24981) (0.641685 1.22649 1.02) (0.971298 0.883237 1.04142) (0.648579 1.51946 0.843762) (1.13204 1.48629 1.39896) (1.70873 1.3553 1.44301) (1.31474 1.15482 1.675) (0.680724 1.63171 1.18555) (0.587063 1.46857 1.30726) (0.790213 1.0628 1.61233) (1.49877 1.48956 1.0507) (0.514424 0.84027 1.20883) (1.27622 1.08667 1.20223) (1.36015 1.35314 1.39887) (1.37998 1.30175 1.56423) (1.26925 0.945523 1.17729) (0.664985 1.63046 1.26733) (0.866451 1.3746 1.37686) (1.27471 1.41085 1.36009) (1.02363 1.29789 1.1648) (0.471547 1.49142 1.42355) (1.57626 1.39817 1.38205) (1.41004 1.52922 1.22915) (1.4782 1.59169 1.08014) (1.67895 1.45914 1.31496) (1.01703 1.37717 1.24781) (1.28378 1.42529 1.53119) (1.36528 1.39096 1.39535) (1.3002 1.24366 1.6762) (0.779798 1.3261 1.20382) (1.51517 1.55994 1.43822) (1.56957 1.35933 1.08636) (0.851976 1.26971 1.57134) (1.56744 1.53155 1.29112) (1.24952 1.35273 1.5866) (1.30016 1.07823 1.16031) (1.14458 1.24931 0.793632) (1.56755 1.33932 1.38841) (0.667434 1.31712 0.985286) (0.98267 1.44791 1.44241) (0.522749 1.46957 1.29164) (1.40378 1.64216 1.31862) (1.3783 1.61004 1.05523) (1.31434 1.58782 1.0324) (1.3364 1.47091 1.36757) (1.49425 1.46967 1.53761) (1.42351 1.32624 1.64723) (1.53325 1.583 1.29944) (1.39602 1.26706 1.66849) (0.977667 1.61725 1.54899) (0.798142 1.29611 0.803737) (1.44447 1.51021 1.08936) (1.52426 1.65022 1.18014) (1.39743 1.36083 1.63817) (1.22661 1.39355 0.511241) (1.15357 1.18584 1.11366) (1.41948 1.35195 1.59621) (1.41784 1.54536 1.12869) (0.912987 1.49031 1.32513) (1.31397 1.24562 0.748953) (1.76712 1.53421 0.993113) (1.80529 1.37682 1.30404) (1.6271 1.11711 1.0355) (1.62342 1.19406 1.13735) (1.62203 1.30792 1.34203) (1.59398 1.41989 0.983746) (1.83748 1.18852 1.11992) (1.59655 1.27309 1.3929) (1.33466 1.06102 1.42037) (1.73248 1.03317 1.05506) (1.63537 1.32759 1.33258) (1.50653 1.3633 1.02698) (1.45504 1.19679 1.5622) (1.50723 1.56034 1.53878) (1.66845 1.19488 1.29399) (1.74149 1.06358 1.12435) (1.82124 1.26836 1.21922) (1.80649 1.19058 1.05692) (1.6366 1.14708 1.08277) (1.32728 1.10285 0.785764) (1.64749 1.07635 1.08005) (1.41143 1.10518 0.770771) (1.78062 1.29155 0.987309) (1.44193 1.2025 0.610938) (1.42462 1.26211 0.583654) (1.62998 1.16607 1.09123) (0.592047 1.24815 1.01308) (1.08009 1.48028 1.43705) (1.21569 1.38503 0.455128) (1.41736 1.07541 0.639907) (1.32483 1.52425 0.48323) (1.74618 1.32841 1.00109) (1.386 1.05998 1.42435) (1.67261 1.1465 1.20914) (1.31581 1.04918 1.41194) (1.29308 1.23407 1.5162) (1.62671 1.31968 1.38761) (1.48799 1.21262 1.37238) (1.29833 1.83962 1.24342) (1.14647 1.3315 0.707641) (1.65688 1.06821 1.03027) (1.59538 1.32201 1.42786) (1.58131 1.59424 1.3807) (1.64025 1.62275 1.08404) (1.4081 1.41682 1.59719) (1.69109 1.47905 1.37405) (1.33271 1.74196 1.26858) (1.60629 1.32973 1.44501) (1.42035 1.24031 1.25106) (1.35726 1.06309 1.36631) (1.68214 1.46506 1.37226) (1.05427 1.24887 0.845304) (1.6615 1.03037 1.05788) (1.61118 1.08795 1.07505) (0.731653 1.5238 0.921149) (1.7413 1.43624 1.39919) (1.49325 1.33644 1.3325) (1.34161 1.51069 1.52885) (1.3199 1.28117 0.77944) (1.49177 1.37306 1.01582) (1.6298 1.3035 1.51641) (1.5283 1.13369 1.34728) (1.2609 1.10943 1.39982) (1.76343 1.06429 1.13755) (1.78312 1.07542 1.13839) (0.910397 1.44403 0.822699) (1.59422 1.11961 1.0999) (1.65472 1.10047 1.22973) (1.7798 1.10678 1.09474) (1.86606 1.20499 1.13185) (1.81362 1.11281 1.13632) (1.23886 1.10678 0.764186) (1.70598 1.01848 1.14862) (1.24924 1.20177 0.738825) (1.48233 1.12281 0.78106) (1.63697 1.05459 0.758454) (1.66361 1.08092 1.1889) (0.78434 0.863496 0.709301) (1.16931 1.12855 0.661498) (1.27812 1.55848 0.440515) (1.45646 1.23517 1.37276) (1.68946 1.18966 1.17095) (1.48228 1.1461 0.757771) (1.71583 1.32073 1.21833) (1.24182 1.3232 0.451335) (1.1931 1.18805 0.898795) (0.587559 1.47226 0.817905) (0.638562 1.36682 0.798785) (0.573969 1.50168 0.83106) (1.24893 1.1364 0.62943) (0.990874 0.787108 1.1446) (0.940391 1.72274 0.525044) (1.06687 0.905012 1.25179) (1.14221 1.3895 0.267822) (0.749506 1.04354 0.536345) (1.66801 1.61927 0.76894) (1.04204 1.20036 0.784202) (1.40551 1.45861 0.619472) (1.24746 1.13848 0.608998) (1.58833 1.70217 0.801774) (1.56163 1.7373 0.825268) (0.986062 1.20215 0.894736) (0.562017 1.49823 0.568371) (1.69503 1.52781 0.923819) (1.04382 1.76643 0.558862) (0.726043 1.35865 0.844397) (0.624609 1.60429 0.88855) (1.39718 1.49607 0.640794) (1.57012 1.13754 0.707863) (0.93532 1.18785 0.870632) (1.4463 1.16006 0.777353) (1.66688 1.56442 0.883669) (1.55155 1.19708 0.54642) (1.39092 1.19096 0.899316) (1.24183 1.19948 0.856665) (1.62056 1.2997 1.23937) (1.46615 1.37851 0.802572) (1.60237 1.23262 0.89311) (1.31933 1.24626 0.845882) (1.7755 1.21518 0.881224) (1.14184 1.13829 0.702266) (1.72493 1.1937 0.838078) (1.43481 1.41685 0.689357) (1.53341 1.4789 1.05573) (1.82125 1.14105 1.09659) (1.68947 1.04386 1.16556) (1.15496 1.19295 0.739762) (1.29923 1.49341 0.705468) (0.943603 1.23678 0.833542) (1.64202 1.18217 1.25475) (1.63951 1.10773 1.19173) (1.16544 1.37282 0.608611) (1.55631 1.12064 0.760114) (1.32086 1.13013 1.40972) (1.72993 1.08172 1.1404) (1.75153 1.16511 1.18448) (1.63184 1.28941 1.27691) (1.14868 1.23564 0.752428) (1.60894 1.24912 1.21722) (0.734043 1.42747 0.394619) (0.837879 1.27526 0.396212) (1.39244 1.56459 0.806162) (0.826379 1.38768 0.314278) (1.6596 1.55146 0.878595) (1.29677 1.30338 0.296634) (1.12829 0.962111 0.817599) (1.40358 1.75897 0.860898) (0.551683 1.56462 0.547192) (1.5842 1.53216 0.919036) (1.33976 1.46053 0.438721) (1.50297 1.58815 0.930549) (1.41678 1.49104 0.759318) (1.31488 1.60126 1.33031) (1.32027 1.69278 0.493668) (1.04128 1.15846 0.958124) (1.38188 1.23721 0.415611) (0.80953 0.875089 0.741545) (1.06094 1.68705 0.603689) (1.43111 1.55387 0.515012) (0.903815 1.09027 0.589766) (1.42699 1.38461 0.463475) (1.14218 1.28703 0.474827) (0.791846 0.884102 0.949484) (0.733016 1.63935 0.814809) (0.475217 1.50009 0.532684) (0.787669 1.69912 0.986367) (0.96547 1.41321 0.401578) (1.21833 1.64464 0.585295) (0.837317 1.79949 0.899472) (0.661171 1.29463 1.13949) (0.705192 1.40521 0.452067) (1.58837 1.53968 1.06468) (1.52478 1.39945 0.765351) (0.944908 1.41808 0.346009) (0.415616 1.30092 0.865768) (1.15543 0.983387 0.826816) (0.757951 1.31021 0.929702) (0.921867 1.4444 0.401295) (0.798023 1.01699 0.813321) (1.30128 1.45723 0.537585) (1.4696 1.80429 0.771709) (0.916005 1.79265 0.760157) (1.21679 1.40066 0.823004) (1.54514 1.46876 0.738829) (0.777755 1.09774 0.603432) (1.22126 1.1184 1.19481) (1.28138 1.41003 0.660135) (0.755768 0.982429 0.709152) (1.33094 1.65679 0.599784) (1.35664 1.31794 0.657246) (1.2497 1.45822 0.608598) (0.887003 1.03658 0.495035) (1.34557 1.52827 0.606174) (0.603446 1.70318 0.83069) (0.687083 1.4457 0.635076) (1.3625 1.53192 0.616852) (0.973484 1.40203 0.378779) (1.48918 1.12537 0.630989) (0.763579 1.23426 1.13775) (1.28069 1.42395 0.910815) (0.890517 1.45537 0.721044) (1.30272 1.51086 0.42418) (1.22862 1.71098 0.990577) (1.41216 1.25961 0.986076) (1.12261 1.04854 0.962653) (0.882419 1.15954 1.08596) (0.865145 1.78867 0.814223) (0.868315 1.36062 0.454748) (0.826241 1.66259 1.07665) (1.40743 1.72836 0.848953) (0.932285 1.41651 0.461893) (1.13309 0.856836 0.727876) (0.814699 1.48809 0.309317) (1.05184 1.03312 0.344246) (1.02662 1.42629 0.693585) (1.38596 1.09083 0.472318) (0.806009 1.0378 0.769206) (1.11505 1.05157 0.866947) (1.38739 1.71957 1.09199) (0.856129 1.28497 1.20868) (0.357588 1.14078 0.803483) (0.513765 1.05043 0.929583) (1.1488 0.927343 0.804794) (0.34489 1.38905 0.949644) (0.861205 1.05318 0.677871) (0.685981 1.5211 0.899525) (1.02743 1.06731 1.10033) (0.495605 1.47288 0.726705) (0.359245 1.34865 0.999825) (0.945293 1.46563 0.860139) (1.2329 1.02951 1.1687) (1.25018 1.72274 0.521178) (1.43292 1.58344 0.556349) (1.10822 1.35459 0.360962) (0.905587 1.61382 0.578227) (1.58403 1.51389 0.841113) (0.785288 1.55019 0.898225) (1.04177 1.40477 0.282244) (1.13512 1.03495 0.43544) (1.0776 1.10732 0.671019) (1.046 1.39002 0.389415) (1.02466 1.29967 0.389149) (0.875567 1.60158 1.00478) (0.897808 1.09053 0.415957) (1.05392 0.961327 0.597206) (1.13568 0.884241 0.536116) (0.811219 1.15872 0.477556) (1.49242 1.35925 0.839056) (1.43544 1.60606 0.86349) (1.34097 1.26908 0.343782) (1.63951 1.6141 0.761954) (0.979856 1.48778 0.326771) (1.07996 1.29793 0.387547) (0.954237 1.06645 0.318291) (0.752799 0.967695 0.51215) (0.9937 1.06344 0.441563) (1.36946 1.34431 0.835136) (0.802774 1.5463 1.05608) (1.58819 1.59835 0.66503) (0.341071 1.32818 0.792968) (0.674063 1.45768 0.563672) (0.864491 1.32246 1.65626) (1.29207 1.26932 0.448978) (0.934713 1.06843 1.51333) (1.47873 1.02193 1.37448) (0.626394 1.06483 1.14761) (0.625433 1.4309 1.28956) (0.929111 0.994005 1.36634) (0.524275 1.32809 1.11079) (1.23417 1.51133 1.58586) (0.822707 1.16002 1.40447) (0.691853 1.51195 1.1179) (0.836175 1.13011 1.59877) (0.932061 0.79952 1.32724) (1.42963 1.37333 1.49167) (0.733474 0.888342 1.16076) (0.557368 1.36104 1.19474) (0.678049 1.19393 1.03457) (0.874842 1.53188 1.62) (1.34703 1.66876 1.29396) (1.50801 1.45369 1.07689) (1.54063 1.31988 1.45293) (1.24003 1.07854 1.55283) (0.816904 1.53005 1.06147) (1.65074 1.41825 1.36059) (1.24108 1.34781 1.34116) (1.3038 1.18335 1.00509) (1.46994 1.03656 1.41172) (0.457723 0.917691 1.10264) (0.940387 1.40285 1.53987) (0.368684 1.38655 1.21147) (0.584887 1.36039 1.31579) (0.792058 0.994728 1.27489) (1.07279 1.3621 1.51009) (1.4398 1.55347 1.3682) (0.744899 1.5429 0.977562) (1.59799 1.45301 1.42202) (1.52191 1.35934 1.43852) (1.34045 1.73057 1.27902) (1.04679 1.59648 1.44424) (0.645388 1.08852 1.34974) (0.598393 1.4957 0.931283) (0.607964 1.47093 1.53437) (0.633765 1.49999 1.06834) (0.377006 1.43003 1.20994) (0.724733 1.20523 1.40108) (1.293 1.15444 1.63166) (1.48257 1.46405 1.05877) (0.682594 1.49931 0.884784) (0.358309 1.14653 1.26337) (0.720987 1.31182 1.25426) (1.41452 1.02571 1.5448) (1.34845 1.07372 1.3908) (1.18675 1.14155 0.709514) (1.31879 1.1093 1.66171) (1.39016 1.34146 1.42246) (1.39616 1.01623 1.29889) (1.39247 1.02908 1.24526) (1.27736 1.23815 1.55002) (1.47084 1.27108 1.39792) (1.37368 1.06768 1.40452) (1.48539 1.02652 1.25366) (1.2455 1.06181 1.39018) (1.32813 1.04473 1.40671) (1.27395 1.26726 1.55119) (1.47593 1.08734 1.4322) (1.40231 1.05048 1.40794) (1.09863 1.23234 0.812379) (1.46159 1.06484 1.37038) (1.27699 1.32153 0.929225) (1.40472 1.02392 1.23879) (1.16825 1.05606 1.34778) (1.57692 1.33793 1.39952) (1.4036 1.03306 1.35089) (1.33463 1.49736 1.5132) (1.18727 1.3687 1.49041) (0.90375 1.36361 1.35324) (1.24347 1.23725 1.70882) (1.41025 1.15748 1.67967) (1.33091 1.02281 1.28153) (1.15046 1.1744 1.43572) (0.933646 1.2364 1.48399) (1.38222 1.06713 1.62304) (1.38711 1.02082 1.25146) (1.38952 1.02742 1.26369) (1.31194 1.06204 1.35878) (1.44604 1.02299 1.18748) (1.53969 1.30011 1.34632) (1.31665 1.05472 1.38015) (1.30189 1.20904 1.26137) (1.19275 1.36495 0.755863) (1.31211 1.09334 1.37225) (1.29737 1.06328 1.39401) (1.26072 1.06104 1.38885) (0.946436 1.28196 0.831783) (1.26125 1.26002 1.08673) (1.61066 1.37384 1.04938) (1.25251 1.28974 1.52673) (1.21399 1.23282 1.15235) (1.50003 1.16711 1.43912) (1.335 1.43645 1.49876) (1.00574 1.14446 0.924863) (1.41696 1.53406 0.548483) (1.18731 1.20657 0.884598) (0.622897 1.61871 0.799246) (1.18411 1.53649 0.590896) (1.3673 1.51859 0.715454) (1.30153 1.4368 0.502351) (0.736113 1.49696 0.816233) (1.57914 1.4374 0.83892) (0.946694 1.17991 0.893637) (1.21538 1.21025 0.775345) (1.14745 1.68896 0.643289) (1.28214 1.54669 0.484001) (1.41569 1.30362 0.85642) (1.41001 1.13771 0.871973) (1.06698 1.22779 0.922735) (1.15181 1.40922 0.562822) (1.13735 1.17309 0.624117) (1.52017 1.1092 0.62827) (1.38447 1.07309 0.609211) (1.33279 1.05242 0.772148) (1.69263 1.57146 0.950303) (1.52106 1.76417 0.750874) (1.53319 1.73547 0.722974) (1.32429 1.24715 0.491637) (0.998857 1.03072 0.691175) (1.32819 1.11935 0.600288) (1.30999 1.53777 0.665362) (0.980582 1.34638 0.739284) (1.27502 1.48956 0.522496) (1.05736 1.15681 0.964906) (0.61229 1.53551 0.870645) (0.687553 1.53244 0.783786) (0.7903 1.57304 0.640137) (0.828368 1.27027 0.595427) (1.41401 1.33072 0.869239) (1.38319 1.38486 0.852781) (1.2542 1.2792 0.416119) (0.945059 1.32481 0.741018) (0.684611 1.48257 0.823776) (0.891194 1.58177 0.689763) (1.05009 1.21478 0.814216) (1.09824 1.1811 0.947673) (1.40312 1.33847 0.8598) (0.940329 1.66604 0.612564) (1.4765 1.51133 0.637911) (0.742795 1.15077 0.490316) (1.55293 1.44383 0.779498) (0.881114 1.34831 0.825281) (1.22149 1.39165 0.427693) (1.31954 1.15977 1.12608) (1.46209 1.23336 1.25204) (1.8358 1.31444 1.30566) (1.46471 1.36376 1.17512) (0.736695 0.853538 0.659124) (0.759013 1.29565 1.19332) (0.961466 1.50452 1.57996) (0.593667 1.58473 0.874007) (1.26401 1.13723 0.877472) (1.06136 1.66073 1.35706) (1.18736 1.48792 1.54524) (1.5792 1.63365 1.10675) (1.42415 1.16242 1.30624) (0.738952 0.831889 0.634479) (0.522649 1.47633 0.610846) (1.55998 1.48265 1.28493) (1.36702 1.06096 1.28902) (1.13065 1.24824 0.413451) (1.29588 1.74131 0.646244) (1.21589 1.72208 1.35935) (0.415515 1.09101 0.811138) (1.46426 1.28342 1.37409) (1.53377 1.10205 0.820333) (1.48745 1.62147 1.2558) (1.42573 1.14393 1.56354) (1.1351 1.51051 0.48071) (1.26408 1.70358 0.847007) (1.40106 1.1818 1.39435) (1.48571 1.26075 0.514329) (1.31852 1.50908 0.528343) (1.26863 1.25364 1.10436) (1.72958 1.29011 0.80799) (1.45186 1.61588 0.755941) (1.13084 1.46631 0.75594) (1.22686 1.53178 1.4041) (1.5922 1.11016 1.06655) (1.4677 1.58302 1.52715) (0.991739 1.61012 1.48846) (1.53977 1.25914 1.2009) (1.18151 1.80081 1.09077) (1.20666 1.4066 1.53269) (1.23505 1.58308 1.24798) (0.961034 1.39159 0.479169) (1.40745 1.17506 1.55629) (0.950068 1.56415 1.53607) (1.25699 1.80805 0.726391) (1.16928 1.41665 0.700252) (1.38822 1.16501 1.11865) (1.20233 1.32237 0.439771) (1.4088 1.72903 0.716601) (1.83207 1.28393 1.1313) (0.95999 1.3733 1.27162) (1.45928 1.23095 0.985845) (1.2095 1.44208 0.526505) (1.49352 1.17851 0.850884) (1.58462 1.07264 0.924634) (1.62842 1.14975 0.739133) (1.15283 1.32492 1.08527) (1.18713 0.971014 0.920323) (0.894755 1.07681 1.01112) (1.20188 1.03019 0.882324) (1.02773 1.12216 0.493127) (0.896924 0.918348 0.739235) (1.1492 1.03527 0.993564) (0.673292 1.22508 0.450345) (0.3561 1.38675 1.03421) (0.398279 1.42752 0.929039) (1.26639 1.36805 0.632047) (0.752334 1.21452 1.47812) (1.81402 1.40383 1.02212) (1.57919 1.23483 0.910963) (1.74813 1.31321 1.16547) (1.53704 1.15183 0.866163) (0.829802 1.46834 0.841382) (1.68406 1.10466 0.800878) (1.52927 1.24194 0.870371) (0.873849 1.28039 0.352412) (0.904376 1.31039 0.375816) (1.58999 1.13973 0.822696) (1.3923 1.21282 0.854111) (0.763725 1.48586 0.931089) (0.616189 1.35964 0.811475) (1.06653 1.55991 0.64701) (1.45955 1.47608 0.659857) (0.906904 1.7912 0.827798) (1.39637 1.18174 1.11624) (1.63003 1.30205 1.17827) (1.70985 1.34956 1.11845) (1.03261 1.27627 1.17782) (0.413803 1.51513 0.648337) (0.815642 1.35177 0.605982) (1.13646 1.5681 0.738296) (1.4087 1.65949 0.621501) (1.76484 1.40677 0.775854) (0.845577 1.52053 1.06279) (1.52366 1.29348 1.337) (1.55639 1.74054 1.07339) (1.37166 1.11911 0.781017) (1.73811 1.33858 1.0083) (1.53565 1.28721 1.33591) (0.828519 1.62118 0.821186) (0.535807 1.33641 0.744511) (0.914667 1.26275 0.978568) (0.61785 1.13136 0.522009) (0.939426 0.961622 0.670093) (0.811326 1.09881 0.931306) (1.75616 1.26295 0.813813) (1.56792 1.1107 0.750356) (1.76436 1.54725 0.917077) (1.37564 1.65524 1.28989) (0.453656 1.40199 0.76037) (0.667346 1.38481 0.868998) (0.887762 1.3018 1.00458) (0.888389 1.07176 0.507061) (1.4425 1.60567 0.805673) (0.669713 1.25678 0.405164) (0.838487 1.36953 0.920668) (1.64349 1.19994 0.911886) (1.74529 1.36636 0.810981) (1.75411 1.29655 0.834304) (1.38184 1.07014 1.10838) (1.43578 1.1098 1.11773) (1.06618 1.15186 1.40744) (1.47557 1.10227 1.17815) (1.46937 1.33822 0.898616) (0.929468 1.2655 1.07832) (0.744435 1.28341 0.409999) (1.045 0.907031 0.672371) (0.654448 1.33889 0.383482) (0.575919 1.56822 1.08005) (1.35046 1.21859 1.06578) (0.951017 0.91781 0.480039) (0.521331 1.39307 1.29155) (0.900458 1.38473 1.49176) (0.606429 1.03222 1.49425) (0.519471 0.939694 1.00655) (0.726158 1.08033 1.46847) (0.717023 1.6775 1.03153) (0.900553 1.29458 0.46792) (0.902918 1.48683 1.03414) (0.730645 1.49087 0.944236) (1.29391 1.74643 1.39451) (1.34887 1.73313 1.44259) (1.31132 1.7591 1.21896) (1.50975 1.70332 1.30092) (1.1864 1.26571 1.55827) (0.786035 1.08608 0.509709) (1.06753 0.930853 0.885708) (1.23198 1.02868 1.17484) (1.32386 1.2873 0.570751) (0.91604 0.780158 0.66917) (1.48237 1.20129 0.480573) (1.14038 1.44976 1.3664) (0.563454 1.14338 0.740928) (1.22066 1.17284 1.17219) (1.10843 0.971488 0.770235) (0.939423 0.834919 0.918817) (1.14955 1.31649 0.448785) (0.849866 1.70164 0.498552) (1.27347 1.50238 0.546657) (0.884216 1.3397 1.04505) (0.845169 1.04361 1.08032) (1.41213 1.66171 0.548949) (1.46546 1.68564 1.19189) (0.73228 1.42006 1.25288) (0.858514 1.30531 1.58316) (0.891223 1.3114 0.817488) (0.862444 1.11678 1.61225) (0.741956 1.32483 1.0189) (1.48335 1.16797 1.19687) (1.26143 1.4444 0.575097) (1.35016 1.45873 0.715204) (1.50886 1.50102 1.4692) (1.13149 0.940998 0.968552) (1.72918 1.26379 0.966564) (1.54217 1.42859 1.16627) (1.57 1.63833 0.979637) (1.74625 1.55283 0.968978) (0.311722 1.3198 0.913274) (0.999452 1.28733 1.0955) (0.936226 1.01222 0.447372) (0.765886 1.13043 1.16619) (1.48312 1.64829 0.832621) (1.00856 1.45143 0.735095) (0.560974 1.38607 1.02994) (1.4575 1.01841 1.42283) (1.35196 1.36152 1.00086) (0.623576 1.18811 0.708363) (0.823038 1.23531 1.6815) (0.857219 0.793941 1.18782) (1.31107 1.54865 1.04044) (0.463641 1.36978 1.23997) (0.837634 1.14977 1.61249) (0.687583 1.21502 1.58171) (1.33273 1.24555 0.768968) (0.501958 1.20993 0.989814) (0.715513 0.984798 1.16104) (0.626558 1.24885 1.5325) (1.26102 1.29755 1.05028) (1.15974 1.18719 1.16014) (0.632111 1.4439 0.54171) (1.06822 1.23222 0.464982) (1.03359 1.1449 0.736102) (1.09434 1.24444 0.42176) (1.1519 1.8043 0.663338) (0.975595 1.49002 0.69035) (1.07837 1.57426 0.446936) (1.49751 1.58115 0.92052) (1.3039 1.34023 1.26831) (1.37513 1.33014 1.39921) (0.953767 1.17189 1.52435) (0.89039 1.35524 1.26194) (1.45256 1.65645 1.19378) (1.71819 1.30473 1.13905) (1.22034 1.1247 0.627284) (1.6822 1.11677 1.08047) (1.61295 1.25932 1.05189) (1.72329 1.4527 1.01595) (1.16011 1.79621 0.557406) (1.27273 1.21549 0.836422) (1.59594 1.13365 1.11811) (1.33079 1.70046 1.32978) (1.60412 1.7084 0.788814) (1.43629 1.78504 0.902128) (1.27633 1.57418 0.549299) (1.3698 1.72071 0.689079) (1.62569 1.66054 0.775292) (0.927581 1.61137 0.435889) (1.06068 1.22415 0.435622) (1.23039 1.47331 0.362505) (1.29721 1.08797 1.57923) (0.570154 1.3864 0.822604) (0.997889 0.792557 0.805101) (1.44151 1.77143 1.37014) (1.00104 1.15224 0.499398) (0.760819 1.41178 0.367784) (1.43411 1.45315 1.04118) (0.804333 1.41267 1.03841) (1.3954 1.53433 0.662698) (1.47432 1.67822 0.987755) (1.65541 1.54748 1.32959) (1.5522 1.60116 1.48201) (1.31618 1.73369 1.33551) (1.40982 1.32969 1.58752) (1.39452 1.65692 1.41116) (1.7431 1.30624 1.00165) (1.49805 1.03509 1.29463) (1.72286 1.29955 1.42472) (1.3179 1.09888 1.41183) (1.37912 1.0965 1.18988) (1.6468 1.15087 1.29437) (1.70784 1.06605 1.07763) (1.58744 1.11973 1.21743) (0.475295 1.32168 0.623195) (0.91949 1.44738 0.861032) (0.98815 1.60705 0.618104) (1.1587 1.22746 0.788895) (1.15427 1.13773 0.730399) (1.41644 1.49439 0.845781) (0.948967 1.3863 0.783998) (1.27557 1.24861 1.1046) (0.961955 0.780234 0.856654) (1.23088 1.57892 1.49842) (0.397409 1.42216 1.15053) (0.355657 1.32889 1.31345) (1.736 1.04265 1.09876) (1.58122 1.17038 1.05716) (1.06414 1.37108 1.28362) (1.14642 1.43003 1.34557) (1.28842 1.50588 1.11151) (0.938791 1.66493 1.45647) (1.42833 1.73955 1.38441) (1.48286 1.38201 1.06342) (1.02571 1.20359 1.48178) (0.787398 1.52903 1.41222) (1.12398 1.13932 1.5676) (0.898787 1.37794 1.46004) (1.37192 1.29579 1.54148) (1.30787 1.63817 0.877459) (0.630807 1.42593 1.15028) (0.968339 1.28398 1.40062) (1.27262 1.74692 0.684855) (1.10963 1.39306 0.435645) (1.63315 1.53357 1.32958) (1.61506 1.47734 1.53733) (1.07936 1.35198 1.26896) (1.38192 1.09566 1.09454) (1.53722 1.07623 1.30765) (0.946939 0.78017 0.688537) (0.660331 1.60585 1.22894) (0.707759 0.894935 0.603809) (0.706007 1.21712 1.51884) (1.29452 1.57565 0.608847) (1.53494 1.26164 1.33887) (1.38822 1.16394 0.452736) (1.52846 1.21104 1.10194) (1.45622 1.36239 1.64937) (1.59326 1.12551 1.06593) (1.3682 1.37777 0.474957) (0.791661 0.907212 1.10873) (0.846278 1.38533 0.753564) (1.63967 1.22816 1.09803) (1.41396 1.05287 1.20497) (1.26816 1.12698 1.4532) (1.36224 1.38222 1.45511) (1.43389 1.22425 0.955507) (1.0852 1.64618 0.670208) (1.14532 1.47153 0.54451) (1.50446 1.72159 0.594438) (1.72615 1.67119 0.694953) (1.39297 1.47532 1.52792) (1.15097 1.42293 1.57265) (1.47255 1.00488 1.3539) (0.860185 0.824582 1.20493) (1.26208 1.49325 1.55472) (1.36667 1.38991 1.63243) (1.00029 1.47169 0.356969) (0.982135 1.06581 0.396307) (1.63083 1.32029 1.26257) (1.37614 1.07947 1.27828) (1.43043 1.34667 0.667275) (1.49987 1.23349 0.51653) (1.02214 1.23395 0.780981) (1.17377 1.2564 0.720429) (1.26672 1.3588 1.65106) (1.16691 1.67677 1.15556) (1.2666 1.30592 1.51804) (1.08362 1.54625 0.723399) (0.936281 1.28839 1.01444) (0.945264 1.24332 0.991091) (1.54009 1.31112 1.08526) (1.06153 1.35781 1.1853) (0.841933 1.19088 1.5592) (1.2025 1.73638 1.26987) (1.40447 1.29927 1.66449) (0.825785 1.25137 0.978035) (1.42638 1.52024 1.06126) (0.841416 1.3034 1.15488) (1.38258 1.14032 1.44857) (0.88511 1.22843 1.52439) (1.09317 1.1683 0.608837) (1.23806 1.09297 0.596416) (1.18994 1.35861 1.31922) (1.41667 1.13833 1.12336) (1.43007 1.11723 1.19645) (1.1177 0.875251 0.780349) (1.05903 0.807512 0.654591) (1.0892 0.831842 0.821422) (1.24999 1.63572 1.32548) (1.42205 1.66151 1.1609) (0.894873 1.25438 1.67685) (1.31062 1.54361 1.09858) (1.04522 1.2938 1.64138) (1.1912 1.65099 1.56868) (1.71081 1.50268 1.37619) (1.69829 1.07917 1.11099) (1.76298 1.17377 1.16034) (1.66772 1.0831 1.21625) (1.87989 1.31598 1.14515) (1.47366 1.20925 1.38933) (1.06596 1.52499 1.4441) (0.987722 1.089 1.11955) (1.20155 1.42276 0.488115) (1.38629 1.11576 0.842909) (1.16935 1.13829 0.566737) (0.760798 1.56899 0.921401) (1.4604 1.70893 0.910865) (1.46813 1.14658 0.547123) (0.627408 1.4717 0.875664) (1.25432 1.51342 0.702117) (1.13596 1.53641 0.584728) (1.19946 1.26363 1.09284) (0.859934 1.25471 1.59587) (0.680954 1.25456 1.55701) (1.15005 1.24236 1.42507) (1.21481 1.32852 1.22431) (1.09912 1.52082 1.36213) (1.3587 1.79303 0.72781) (1.61912 1.67472 0.779818) (0.758343 0.959594 0.727695) (1.36928 1.13966 0.448201) (0.697079 1.21255 0.395672) (0.845063 1.13307 1.08526) (0.814645 0.830276 0.706936) (1.62722 1.63116 0.748419) (1.51397 1.48166 0.70431) (0.987104 1.32134 0.725845) (1.13772 1.25558 0.768781) (1.26569 1.11207 0.599323) (0.654629 0.85162 0.783964) (0.853882 1.19966 0.83137) (1.70949 1.23751 1.1322) (1.17529 1.19673 0.773784) (0.799406 1.41689 0.802118) (0.829857 1.51848 1.62396) (1.31293 1.23001 1.34728) (1.53328 1.31955 1.19657) (0.995886 1.10211 1.595) (1.54532 1.59966 1.46198) (1.55167 1.13158 0.917863) (1.75546 1.28372 1.03916) (1.7972 1.38815 0.947771) (1.2714 1.29151 0.978777) (1.60911 1.22111 1.08724) (1.714 1.20189 1.24988) (1.64833 1.06285 1.20049) (0.772435 1.67101 1.17493) (0.871982 1.33907 1.36818) (0.621864 1.30527 1.22037) (0.847382 1.37515 1.56255) (1.2267 1.13139 1.39661) (1.31513 1.25576 1.35407) (1.53445 1.57837 0.746658) (1.66916 1.53886 0.935595) (1.62147 1.24653 1.06915) (1.636 1.12378 1.27641) (1.76203 1.10676 1.07752) (1.62702 1.16035 1.13072) (1.74548 1.15811 0.931004) (1.63059 1.30016 1.03349) (1.62127 1.14147 1.08697) (1.4104 1.3277 1.02911) (1.37391 1.09202 1.17842) (1.29573 1.29795 0.991168) (1.07916 0.792328 0.740693) (1.19916 1.14357 1.46551) (1.32901 0.993991 1.39981) (0.810235 1.13857 1.27874) (1.73739 1.4631 1.35174) (0.65192 1.47183 0.887606) (0.785835 1.28752 0.986199) (0.683366 1.17519 1.29888) (1.60652 1.10142 1.27088) (1.00164 1.32722 0.998131) (1.25044 1.52071 1.44791) (1.25902 1.36871 1.0898) (1.61955 1.15617 1.11228) (1.45549 1.35811 1.08246) (1.47133 1.72939 1.0374) (1.67963 1.47601 1.06329) (1.74055 1.09805 1.11619) (1.74964 1.23766 0.949787) (1.61286 1.28325 0.960192) (1.26388 1.24732 1.02376) (1.17046 1.32653 0.991808) (1.19714 1.28135 0.87414) (1.12718 1.24869 0.84753) (1.30627 1.2043 1.17968) (1.71256 1.22016 1.04642) (1.45721 1.08689 0.744813) (1.43579 1.49476 1.18228) (1.09557 1.33498 1.51065) (1.17903 1.36879 1.01654) (1.41893 1.72818 1.32844) (1.41649 1.03898 1.26009) (1.72417 1.38017 1.43026) (1.37553 1.39142 1.03847) (1.49417 1.51704 1.56962) (1.42056 1.37853 1.06846) (1.53731 1.47628 0.885157) (1.67868 1.42494 1.08659) (1.29733 1.07113 1.16183) (1.30413 1.50215 0.56571) (1.04443 1.6581 1.35722) (0.850979 0.967465 0.436961) (0.967254 1.70448 0.572437) (1.65458 1.30725 1.07252) (1.59441 1.15577 1.26002) (1.7653 1.12643 1.10638) (0.998017 1.32499 0.799574) (1.37702 1.71186 0.694806) (1.51785 1.29143 1.30073) (0.666413 1.15223 1.03353) (1.54222 1.54488 1.27159) (0.87165 1.22712 0.845163) (1.53442 1.20899 0.641515) (1.47024 1.42792 1.34933) (0.695262 1.10481 0.46063) (1.07278 1.57499 0.648963) (0.878116 1.36978 0.819395) (1.36079 1.51672 0.466259) (1.12951 1.53871 1.56885) (1.55218 1.55115 1.28221) (1.66392 1.57785 0.799601) (0.580609 1.52109 0.904036) (1.0892 1.19034 0.834559) (1.62727 1.70087 0.655659) (1.36154 1.48393 0.51538) (1.28137 1.68342 0.465906) (1.51054 1.74314 0.884445) (1.41961 1.68921 0.565744) (1.70502 1.41606 1.00682) (1.62316 1.62372 0.971982) (1.52553 1.66198 1.12502) (1.50764 1.23146 0.63369) (1.23215 1.74244 1.19577) (1.46785 1.755 0.614791) (0.672266 1.31795 0.369095) (0.622641 1.42505 0.827967) (0.964901 1.43568 1.2498) (0.281138 1.35344 1.14565) (0.877656 1.17799 1.07611) (1.53844 1.42308 0.731556) (1.24122 1.13975 0.611018) (1.12963 1.53643 0.583868) (1.23742 1.31483 0.386939) (1.11068 1.17208 0.656138) (1.5424 1.52523 0.823108) (1.3055 1.74995 1.30234) (1.42924 1.67218 0.838147) (0.690379 1.61195 0.933615) (0.966111 1.14093 0.931919) (1.18486 1.17558 0.694275) (0.793526 1.37413 0.749234) (1.15414 1.34242 1.29941) (1.20696 1.04274 1.51931) (0.767359 1.32728 0.76009) (1.50216 1.78172 0.831911) (0.584193 1.0858 0.497913) (1.0358 1.6515 0.671259) (1.76394 1.26973 0.888036) (1.67217 1.07697 0.730334) (1.44848 1.30475 0.627106) (1.38069 1.71051 0.690659) (1.23535 1.11016 1.56481) (1.24743 1.26402 0.563262) (1.76178 1.21297 1.10534) (1.44238 1.13869 1.2247) (1.54101 1.49055 1.29397) (0.745969 1.4831 0.989233) (1.37756 1.62653 0.446591) (1.65153 1.64061 0.832114) (1.00774 1.22613 0.796452) (1.51108 1.39844 0.93903) (1.45146 1.03069 0.704067) (1.39994 1.4393 0.623325) (1.2339 1.50051 0.789861) (0.648171 0.90061 0.640881) (1.46568 1.62782 0.703151) (0.984977 1.53155 1.54144) (1.45235 1.07196 0.715497) (1.36865 1.28004 1.68035) (0.904419 1.36564 1.13893) (1.46587 1.16101 1.4866) (0.780058 1.51496 1.03399) (1.74068 1.37954 1.33116) (1.69564 1.52256 0.91987) (1.33213 1.63765 0.560339) (1.50927 1.50059 0.862752) (1.4646 1.38975 0.775719) (1.5416 1.5022 0.949067) (1.04773 1.12279 1.46818) (1.33554 1.69271 0.738241) (1.26302 1.46934 1.12494) (1.48725 1.63924 1.23377) (1.27219 1.375 1.01223) (1.27982 1.29646 0.525007) (1.40422 1.57266 1.09802) (1.48267 1.29918 0.572042) (1.30936 1.78255 1.25622) (1.10456 1.21782 0.910199) (1.41837 1.52792 0.561651) (0.807026 1.67836 0.964661) (1.44718 1.30618 0.626431) (1.33238 1.1285 1.57163) (1.28118 1.13466 1.37127) (1.2209 1.64411 1.20381) (1.3998 1.1503 0.527638) (0.914865 1.23694 0.831241) (0.965487 1.01649 0.574787) (0.957817 0.991201 0.570859) (1.10067 1.7808 0.533661) (1.10083 1.2032 0.424075) (1.12403 1.43285 0.579293) (1.72016 1.19005 0.938886) (0.864689 1.32617 1.35515) (0.539349 1.28015 1.40566) (1.22858 1.57795 0.525185) (0.596832 1.63648 0.853077) (1.56683 1.47863 1.47696) (1.56515 1.12202 0.91727) (1.61224 1.1137 0.821604) (1.39568 1.21912 0.919366) (1.6183 1.59996 0.822912) (1.39185 1.49831 0.71082) (0.564014 1.55059 0.901427) (1.61714 1.62042 0.834355) (0.901861 1.61407 0.448287) (1.50043 1.11447 1.30492) (1.56472 1.1199 1.33215) (1.69965 1.21765 1.22049) (1.47351 1.58063 0.980261) (1.66868 1.48045 1.32271) (1.83754 1.29635 1.06508) (0.817842 1.14477 1.60206) (1.16834 1.54759 0.451671) (1.27231 1.55815 0.421725) (1.20169 1.19923 0.737679) (1.4808 1.71318 0.818852) (1.45866 1.22848 1.36947) (1.15849 1.29734 1.10118) (1.17938 1.25573 0.710299) (1.01362 1.09165 0.509475) (1.13219 1.3136 0.398971) (1.56362 1.56008 0.79691) (1.27305 1.1452 0.693435) (1.30246 1.24155 1.05474) (1.4973 1.16056 1.30287) (1.50075 1.15897 1.28524) (1.55977 1.15369 1.33106) (0.840212 1.12185 1.07284) (1.20523 1.30354 1.43819) (1.25872 1.23514 0.800687) (1.56513 1.07431 0.841568) (1.43522 1.15412 1.14629) (1.0936 1.17261 0.412237) (1.03078 0.86381 1.2488) (0.972725 0.818209 1.05514) (0.734369 1.27371 1.32402) (1.1893 1.5516 1.61668) (1.15403 1.25736 1.40132) (1.31976 1.26578 0.582176) (1.58271 1.10856 1.29253) (1.73457 1.29319 1.06753) (1.62853 1.18933 1.08659) (0.899638 1.36576 1.38096) (0.660194 1.32206 1.31703) (0.786688 1.21757 1.07279) (0.670639 1.24033 0.519119) (1.46298 1.41167 0.62836) (1.29732 1.54228 0.447661) (1.35526 1.43272 0.420184) (1.27894 1.4513 0.468605) (1.71256 1.59896 1.02509) (0.860393 0.974652 0.71004) (1.30089 1.47992 0.471032) (0.483664 1.40802 1.43906) (1.05781 1.39618 1.19359) (1.32618 1.21093 1.62623) (1.31888 1.29811 1.41078) (1.19601 1.63495 1.15864) (1.50005 1.61391 1.24591) (1.51989 1.2322 1.36773) (1.59056 1.68376 1.01077) (1.50588 1.04397 1.35965) (1.34118 1.7262 1.26291) (1.56926 1.09774 1.36091) (0.923804 1.60533 0.601536) (0.604682 1.58716 0.846616) (1.40242 1.78055 0.66934) (1.18815 1.6418 1.19886) (1.35251 1.4425 1.23504) (1.27316 1.80236 0.694218) (0.869152 1.20586 1.4596) (0.600707 1.46205 1.25932) (1.35728 1.20677 1.17881) (1.46682 1.41729 1.50708) (1.6181 1.61257 0.624932) (0.874987 1.49382 0.359504) (0.947901 0.981484 0.569092) (0.941601 1.00319 1.42684) (1.43738 1.08899 1.09928) (0.971053 1.29239 1.02349) (0.898371 1.63579 0.966284) (0.796376 1.18882 1.69225) (0.468481 1.00774 0.890242) (1.49404 1.12137 1.44646) (1.37937 1.43067 1.57657) (1.31956 1.72924 1.24473) (1.10744 1.39316 1.05703) (0.848472 1.23843 0.419773) (1.03052 1.59157 0.417431) (1.31009 1.28764 1.66233) (1.29506 1.70891 0.5819) (1.50239 1.45696 0.933608) (1.26198 1.32021 0.571016) (1.35447 1.51448 1.57389) (1.43432 1.50335 1.57513) (1.4612 1.24127 1.47536) (0.767505 1.27571 1.17738) (1.42546 1.24633 0.924607) (1.14692 1.37944 0.611742) (1.54428 1.15448 0.81061) (1.26273 1.24556 0.900403) (1.15836 1.35002 0.782563) (0.860881 1.39182 0.792956) (1.15511 1.4033 0.69923) (1.19452 1.38384 0.530588) (1.71492 1.12131 1.17027) (1.05817 1.15123 0.425633) (0.907923 1.28189 0.259907) (1.22622 1.61615 0.91777) (1.65564 1.38446 1.38878) (1.34964 1.45158 0.569729) (1.53631 1.42601 0.894977) (1.17605 0.929987 0.670442) (1.20287 1.04342 1.28467) (1.45333 1.38949 0.777346) (1.06147 1.19912 0.855881) (1.38373 1.43859 1.5348) (1.64879 1.69863 1.13589) (1.48562 1.34011 1.38761) (1.3986 1.04241 1.23147) (1.35236 1.15777 1.63649) (1.49475 1.66694 1.27155) (1.6018 1.24438 1.36586) (1.34149 1.76015 1.08829) (1.42561 1.76933 1.12358) (1.21273 1.35145 0.44121) (1.61955 1.44873 0.908479) (1.21899 1.50969 0.532251) (1.3227 1.31977 0.381666) (1.33786 1.53279 0.720012) (1.29951 1.48536 0.551849) (1.29831 1.19678 0.711928) (1.37061 1.44403 1.54308) (0.512568 1.4072 1.43209) (1.43537 1.28582 0.866256) (1.23088 1.09423 0.641239) (0.819918 0.988124 1.31414) (0.831826 1.43279 1.67369) (0.884411 1.4092 1.47143) (1.15166 1.38079 1.13536) (0.948284 1.68638 1.31672) (0.85135 1.22189 1.64694) (1.01106 1.56788 0.571703) (0.46039 1.58446 0.759542) (0.772365 1.40495 1.4708) (0.926125 1.36488 1.30301) (1.24903 1.36459 0.753468) (1.05661 1.59866 1.3451) (1.08628 1.50944 1.17728) (1.05431 1.467 1.2365) (1.49285 1.41846 1.24131) (1.30209 1.20843 1.57136) (1.23239 1.27817 0.901662) (1.19037 1.65757 0.584711) (0.910577 1.33922 0.858369) (1.32814 1.5327 1.5865) (1.14736 1.54873 0.432061) (1.50973 1.55331 0.815973) (1.06304 1.31424 0.321125) (1.44367 1.10738 1.38596) (1.38377 1.70323 0.48972) (1.68233 1.6575 0.730951) (1.3201 1.4806 0.599157) (1.00041 1.09087 0.789003) (1.32065 1.46829 1.53338) (1.49189 1.47269 1.53771) (1.15346 1.19104 0.685738) (0.807704 1.28774 0.893835) (1.17573 1.75442 0.640591) (1.22141 1.37087 1.08624) (1.18708 1.35331 1.03947) (0.904382 1.57297 1.27439) (1.1107 1.20566 1.14399) (0.62237 1.26013 1.55423) (1.23009 1.25686 1.40876) (1.43901 1.39181 1.17942) (1.45328 1.66546 1.35477) (1.11027 1.44367 0.654818) (1.49146 1.80682 0.732755) (1.4894 1.53629 0.834517) (0.75135 1.22001 1.0795) (1.22099 1.09416 1.50814) (1.0127 1.41497 0.665867) (0.681347 1.4351 1.10538) (1.32898 1.14876 1.3908) (1.4562 1.02965 1.26904) (1.47062 1.10606 0.747478) (1.51869 1.33019 0.97843) (1.3903 1.17911 0.85264) (1.25713 1.33509 1.11693) (1.53642 1.13887 0.973219) (1.57313 1.767 0.745314) (0.674241 1.67355 1.04372) (1.58965 1.64499 0.642944) (1.45036 1.56528 0.626644) (1.63734 1.03707 0.760076) (1.75744 1.23204 0.875023) (1.05833 1.54352 0.556735) (0.380495 1.20356 1.348) (1.48039 1.19871 1.0161) (1.49637 1.53522 1.1703) (1.23256 1.63758 1.06535) (1.41934 1.46852 1.53249) (1.11683 1.64818 0.495429) (1.51043 1.48162 0.896828) (0.975736 1.18738 0.806151) (1.28072 1.21371 1.10315) (1.60885 1.14598 0.695292) (1.00708 1.06412 0.685979) (1.03358 1.10626 0.278537) (1.48191 1.46138 0.722815) (1.47085 1.49038 1.17235) (1.56579 1.70298 0.805171) (1.0379 1.76558 0.905431) (1.15783 1.79155 0.588648) (1.01114 1.6615 0.974208) (1.14322 1.61056 0.770476) (1.59022 1.53309 0.979576) (1.27988 1.57531 0.698218) (1.64006 1.13959 1.09658) (1.30578 1.63919 1.5719) (1.40699 1.47962 1.55074) (1.39638 1.52152 1.56908) (1.2568 1.37038 0.585635) (1.30397 1.64947 1.41463) (1.46243 1.67301 1.26795) (1.29625 1.71872 1.40836) (1.11482 1.21022 1.50134) (1.24712 1.49207 0.959655) (1.40411 1.47875 1.54829) (1.26604 1.37949 1.63603) (0.721157 1.56688 1.60043) (0.815742 1.54375 1.12996) (0.472916 1.64936 0.780557) (1.34764 1.64627 1.43183) (1.3244 1.52593 1.55444) (0.928711 1.62876 0.878206) (0.951824 1.31439 0.297169) (1.38474 1.66367 0.911109) (1.56778 1.52211 1.27186) (1.30778 1.24072 1.67378) (1.34711 1.37483 0.743106) (1.24606 1.27161 0.870987) (1.47702 1.3457 0.903896) (1.59573 1.66377 1.30941) (1.26651 1.87643 1.00824) (1.33291 1.36816 1.21722) (1.66324 1.59192 0.778398) (1.29179 1.30143 0.994219) (1.37239 1.34013 1.405) (0.863058 1.02894 1.25843) (0.717788 1.42032 1.22138) (1.28881 1.30303 0.862924) (1.04807 1.23613 1.43669) (1.34313 1.59489 1.15811) (1.47037 1.53635 1.2823) (1.22222 1.48209 0.435882) (1.35871 1.5032 1.56481) (0.985102 1.46955 1.15833) (0.730411 1.58792 1.18966) (1.76105 1.27706 1.11902) (1.26671 1.6054 1.34743) (1.40527 1.48575 1.52493) (1.31437 1.61891 1.05552) (1.34429 1.40062 1.3302) (1.50853 1.41845 0.836324) (1.57287 1.60213 1.13537) (1.03708 1.22068 0.860077) (0.802497 0.934299 0.682246) (1.22689 1.65491 0.602837) (0.922174 1.35039 1.05781) (0.468532 1.2631 1.24889) (0.931119 1.66601 1.45817) (1.12052 1.24117 0.837883) (1.28873 1.2201 1.25467) (1.14033 1.3189 0.782567) (1.18479 1.33689 0.752518) (1.12978 1.5302 0.719418) (1.61649 1.76293 0.729978) (1.34336 1.68292 0.750693) (1.34627 1.68553 0.744063) (1.22699 1.76917 0.79676) (1.3669 1.62126 1.18515) (1.7047 1.20009 0.874636) (1.62096 1.09995 1.07158) (1.25152 1.33642 0.893557) (1.64056 1.16723 1.32716) (1.45585 1.06874 1.14193) (1.59851 1.28724 1.37116) (1.66377 1.37123 1.18948) (1.48192 1.30077 1.35338) (1.33214 1.57166 0.497604) (1.12925 1.54172 0.586015) (0.901417 1.31338 1.01876) (0.64283 1.4857 0.877601) (1.35847 1.52908 1.34303) (1.54341 1.71764 1.16459) (1.34488 1.27853 1.02645) (0.918684 0.882017 0.923898) (0.694161 1.24262 1.0406) (1.10025 0.99703 1.17711) (1.53744 1.77138 1.06118) (1.50181 1.77972 0.762119) (1.43405 1.69975 1.31999) (1.19565 1.03008 0.815021) (0.72929 1.42326 1.25019) (1.61425 1.31508 1.45915) (1.08219 1.60213 0.608493) (1.41699 1.43032 1.54094) (1.21813 1.70135 1.35931) (1.33244 1.43111 0.724236) (1.51615 1.25893 1.25673) (1.1741 1.72037 0.808998) (0.945469 1.45417 0.653386) (1.30765 1.29626 0.679188) (1.58913 1.76045 0.702417) (1.67698 1.54153 0.693077) (1.43481 1.35573 0.733877) (1.08181 1.48933 0.781416) (1.04099 1.41178 0.352246) (0.855332 1.27866 0.712833) (0.919181 1.28089 1.65796) (0.681231 1.31991 1.28757) (0.799708 1.17052 1.08676) (1.44875 1.73004 0.823326) (1.63437 1.60419 0.684187) (0.724466 1.28422 1.17295) (1.51082 1.36194 0.96574) (0.715946 1.3256 1.55958) (1.06328 1.42483 1.692) (0.916821 1.21643 1.50312) (1.38734 1.39023 1.32692) (0.775822 1.32122 1.51738) (1.23225 1.41768 1.02129) (1.45216 1.67169 1.13679) (1.53345 1.64153 1.30269) (1.42752 1.03817 0.715581) (1.28398 1.37607 0.39144) (1.26756 1.30333 1.36062) (0.851527 1.66238 1.04785) (1.04217 1.5224 1.17397) (0.90763 1.00194 0.485813) (1.18806 1.59076 0.760836) (1.66642 1.3663 1.2277) (0.572721 1.59499 0.880262) (0.938106 1.02568 0.451194) (1.49351 1.43774 0.627935) (1.34648 1.7295 0.67167) (1.20462 1.39964 0.775565) (1.64124 1.13471 1.07011) (1.10627 1.17204 1.50174) (1.43679 1.28167 0.862615) (1.08618 1.26465 0.422763) (1.48676 1.44804 1.24884) (1.70786 1.08035 1.04455) (1.25166 1.73113 1.28748) (1.22227 1.8078 1.0726) (1.5215 1.47545 0.741874) (1.38098 1.50033 1.38188) (1.4518 1.21929 1.41904) (1.70655 1.31498 1.11728) (1.3855 1.41624 1.00136) (0.736104 1.34476 1.25301) (0.466525 1.27625 1.1824) (1.20548 1.23836 1.13098) (1.41166 1.22108 0.619773) (1.47094 1.22436 1.56884) (0.643469 0.811674 0.607173) (1.35988 1.79979 1.04866) (0.879824 1.05028 1.52481) (0.87042 1.09396 0.524743) (0.665487 1.62107 0.905425) (1.36819 1.44739 0.660686) (0.691366 1.3413 0.804362) (0.885114 1.0858 0.452978) (0.94722 1.19546 1.54556) (1.33196 1.66807 0.786808) (0.96429 1.52919 1.56025) (1.18347 1.17659 0.310605) (0.928187 1.44656 1.66054) (0.850515 1.54208 1.01384) (1.36489 1.28527 0.843883) (1.00092 1.08827 0.320696) (1.40997 1.53826 1.35837) (1.57187 1.11232 1.34792) (1.54032 0.997782 1.25772) (0.593919 1.50781 0.773266) (1.33853 1.02556 1.44297) (0.745298 1.36828 1.28316) (0.612182 1.60858 0.903126) (1.0692 1.6558 1.3333) (1.06607 1.30511 0.304923) (1.05302 1.59086 0.521353) (0.549979 1.66744 0.702706) (1.61578 1.30983 1.34991) (1.61024 1.12568 1.10827) (1.71805 1.47994 1.35456) (1.0216 1.35405 0.823276) (1.2798 1.8335 1.29981) (1.47205 1.04709 1.24138) (1.43766 1.11578 0.487567) (0.867798 1.32874 0.427247) (1.18231 1.80193 0.600535) (1.44562 1.46126 0.606544) (1.07261 1.4209 1.5503) (1.1682 1.65623 1.3139) (1.34753 1.35168 0.827865) (1.00468 1.42142 0.831091) (1.27106 1.28605 0.678749) (0.630732 1.51195 0.63121) (0.862118 1.43554 0.380024) (1.48169 1.43649 1.61772) (1.3975 1.32421 0.859837) (0.969613 0.99771 0.900345) (1.23547 1.16843 1.32318) (1.59133 1.56523 1.47732) (1.29451 1.29636 1.1479) (1.43411 1.1875 1.47112) (1.16711 1.35562 0.78144) (1.38528 1.30288 0.728322) (1.65747 1.11392 1.045) (1.05166 1.68005 1.32629) (1.69661 1.26832 1.09808) (1.37527 1.40848 0.893068) (1.33677 1.3362 1.24153) (1.01322 1.33812 0.386545) (1.41901 1.63371 0.772558) (1.18027 1.23319 0.797497) (1.24711 1.27789 0.837336) (0.988201 1.46211 0.659826) (1.25112 1.70295 1.09758) (0.658502 0.924602 0.638466) (1.34887 1.25053 0.575502) (1.28408 1.39945 0.433331) (1.52617 1.09645 0.752447) (1.28476 1.68655 1.54258) (1.16018 1.39847 0.519276) (1.2217 1.86001 1.03462) (1.08753 1.69491 1.36176) (1.31187 1.46444 1.29315) (1.3625 1.31382 0.489144) (1.60379 1.55329 0.654049) (1.34283 1.21273 0.813417) (1.68427 1.033 1.06091) (1.502 1.53546 0.913) (1.04169 1.20977 0.908608) (0.958187 1.32946 0.731475) (1.31814 1.5681 0.611731) (1.30449 1.64785 1.27134) (1.29673 1.3832 0.665155) (0.815428 1.21153 1.69075) (1.58375 1.54228 1.09551) (1.15808 1.23812 0.819478) (0.505825 1.03499 1.33382) (0.951148 1.05279 0.87443) (0.806164 1.61075 0.849544) (1.70454 1.31728 1.17617) (1.18832 1.43454 0.546507) (1.19121 1.48694 0.708724) (0.781796 1.36268 0.722509) (1.12726 1.17203 0.954523) (1.51727 1.0818 0.658691) (0.332669 1.14024 1.20312) ) // ************************************************************************* //
[ "you@example.com" ]
you@example.com
7cfafc44b539bc766ffa7fa9890a921ef8944af2
5bdf6ec443fce02bb4db3ef5cfc7f813363a3bd5
/Motion_Logger.ino
27307c9e4eb02447bd70ef457b970021f3d83bd5
[]
no_license
osamuta/Motion_Logger
c354c6b99bb02d7980e718fcfe0b9417165aaa13
edfe0b161efdc8a3e476dd6cb3efc322e2d673df
refs/heads/master
2022-04-27T13:54:33.779974
2020-04-27T14:20:54
2020-04-27T14:20:54
258,720,228
0
0
null
null
null
null
UTF-8
C++
false
false
6,007
ino
// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // Version 2, December 2004 // // Copyright (C) 2020 Kawakami Shuta <rivertop.osamuta@gmail.com> // // Everyone is permitted to copy and distribute verbatim or modified // copies of this license document, and changing it is allowed as long // as the name is changed. // // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION // // 0. You just DO WHAT THE FUCK YOU WANT TO. // Debug symbol #define DEBUG #include "ToolBox.h" #include "MagneticSensor.h" #include "MotionSensor.h" #define LICENSE F(" DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE \n Version 2, December 2004 \n Copyright (C) 2020 Kawakami Shuta <rivertop.osamuta@gmail.com> \n Everyone is permitted to copy and distribute verbatim or modified \n copies of this license document, and changing it is allowed as long \n as the name is changed. \n DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE \n TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION \n 0. You just DO WHAT THE FUCK YOU WANT TO.\n\n") #define DATA_FORMAT F("Time[milliSec],Temperature sensored by magnetic sensor[C],True azimuth XY[°],True azimuth XZ[°],True azimuth YZ[°],Temperature sensored by motion sensor[C],Gyro sensor X[°],Gyro sensor Y[°],Gyro sensor Z[°],Acceleration X[Meter Per Second Sqaure],Acceleration Y[Meter Per Second Sqaure],Acceleration Z[Meter Per Second Sqaure],\n") class Interface { private: Stopwatch _stopwatch; DigitalPin _button; DigitalPin _led; boolean _ledState; public: Interface() { _ledState = false; } void initialize() { _button.initialize(9, INPUT_PULLUP); _led.initialize(8, OUTPUT); _stopwatch.startMillis(); } boolean isButtonPressed() { if (!_button.read()) { if (_stopwatch.lapMillis() > 1000) { _stopwatch.stopMillis(); _stopwatch.startMillis(); return true; } else return false; } else return false; } void LED(boolean ledState) { _ledState = ledState; _led.write(ledState); } void blinkLED() { if (_stopwatch.lapMillis() > 583) { _ledState = !_ledState; _led.write(_ledState); _stopwatch.stopMillis(); _stopwatch.startMillis(); } } }; class CanSatellite { private: Stopwatch _timStamp; I2C _i2c; Storage _storage; MagneticSensor _magneticSensor; MotionSensor _motionSensor; String _fileName; const String TOKEN; public: CanSatellite() : TOKEN(",") {} Error initialize() { _i2c.initialize(400000); if (!_magneticSensor.initialize(&_i2c, DATARATE_200HZ, SAMPLES_512, RANGE_2GA).isSucceeded()) return Error(FATAL_ERROR, F("FATAL_ERROR : Error occured in initializing magnetic sensor!\n")); if (!_motionSensor.initialize(&_i2c, GYRO_FULL_SCALE_RANGE_2000_DEGEREE_PER_SEC, ACCEL_FULL_SCALE_RANGE_16G).isSucceeded()) return Error(FATAL_ERROR, F("FATAL_ERROR : Error occured in initializing motion sensor!\n")); if (!_storage.initialize(&SD, 10).isSucceeded()) return Error(FATAL_ERROR, F("FATAL_ERROR : Error occured in initializing micro SD card!\n")); return Error(SUCCEEDED, F("SUCCEEDED : Can satellite was initialized correctly.\n")); } Error prepare() { size_t size = String(DATA_FORMAT).length(); for (int i = 0; SD.exists(_fileName = String(F("DATA_")) + i + String(F(".CSV"))); i++) {} if (_storage.writeBOM(_fileName) != 3) return Error(FATAL_ERROR, F("FATAL_ERROR : Error occured in writing Byte Order Mark!\n")); if (_storage.printString(_fileName, DATA_FORMAT) != size) return Error(FATAL_ERROR, F("FATAL_ERROR : Error occured in writing Data format!\n")); _timStamp.startMillis(); return Error(SUCCEEDED, F("SUCCEEDED : Preparing for recording was finished correctly.\n")); } Error record() { String data; unsigned long timestamp; float temperature1, temperature2; Angle xy, xz, yz; XYZ gyro, accel; timestamp = _timStamp.lapMillis(); temperature1 = _magneticSensor.getTemperature(); _magneticSensor.getTrueAzimuth(&xy, &xz, &yz); temperature2 = _motionSensor.getTemperature(); gyro = _motionSensor.getGyroXYZDegreePerSec(); accel = _motionSensor.getAccelerationXYZMeterPerSecSquared(); data.reserve(240); data += timestamp; data += TOKEN; data += temperature1; data += TOKEN; data += xy.getAngleDegree(); data += TOKEN; data += xz.getAngleDegree(); data += TOKEN; data += yz.getAngleDegree(); data += TOKEN; data += temperature2; data += TOKEN; data += gyro.x; data += TOKEN; data += gyro.y; data += TOKEN; data += gyro.z; data += TOKEN; data += accel.x; data += TOKEN; data += accel.y; data += TOKEN; data += accel.z; data += "\n"; if (_storage.printString(_fileName, data) == data.length()) return Error(SUCCEEDED, F("SUCCEEDED : wrote data correctly.\n")); else return Error(FATAL_ERROR, F("FATAL_ERROR : Error occured in writing data!\n")); } }; Interface interface; CanSatellite canSat; boolean errored = false; boolean logging = false; void setup() { #ifdef DEBUG Serial.begin(9600); Serial.print(LICENSE); #endif interface.initialize(); if (!canSat.initialize().isSucceeded()) errored = true; } void loop() { if (!errored) { if (interface.isButtonPressed()) { if (!logging) { if (!canSat.prepare().isSucceeded()) errored = true; } logging = !logging; } if (logging) { if (!canSat.record().isSucceeded()) errored = true; } interface.LED(logging); } else { interface.blinkLED(); } }
[ "rivertop.osamuta@gmail.com" ]
rivertop.osamuta@gmail.com
55d9eff062b94349649a6fe779213896e1283c6d
29d2c31c5284c51a7ce0f2fcce6dbb65eeb2f2b7
/BaseballProject/3rdParty/qtxlsx/xlsx/xlsxworksheet.cpp
f0a5803e21bd4d7782e029430a3d79dd6cacd4df
[]
no_license
cs1d-baseballproject/Baseball-Project---CS1D
ea782d69489b07fff61938cca97af6ad5fe086d0
1269b806a522cf8de8c119d9dea861bf4e33a46f
refs/heads/master
2020-05-04T20:55:12.239296
2019-05-06T22:16:11
2019-05-06T22:16:11
179,456,867
0
0
null
null
null
null
UTF-8
C++
false
false
85,725
cpp
/**************************************************************************** ** Copyright (c) 2013-2014 Debao Zhang <hello@debao.me> ** All right reserved. ** ** 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 "xlsxrichstring.h" #include "xlsxcellreference.h" #include "xlsxworksheet.h" #include "xlsxworksheet_p.h" #include "xlsxworkbook.h" #include "xlsxformat.h" #include "xlsxformat_p.h" #include "xlsxutility_p.h" #include "xlsxsharedstrings_p.h" #include "xlsxdrawing_p.h" #include "xlsxstyles_p.h" #include "xlsxcell.h" #include "xlsxcell_p.h" #include "xlsxcellrange.h" #include "xlsxconditionalformatting_p.h" #include "xlsxdrawinganchor_p.h" #include "xlsxchart.h" #include "xlsxcellformula.h" #include "xlsxcellformula_p.h" #include <QVariant> #include <QDateTime> #include <QPoint> #include <QFile> #include <QUrl> #include <QRegularExpression> #include <QDebug> #include <QBuffer> #include <QXmlStreamWriter> #include <QXmlStreamReader> #include <QTextDocument> #include <QDir> #include <math.h> QT_BEGIN_NAMESPACE_XLSX WorksheetPrivate::WorksheetPrivate(Worksheet *p, Worksheet::CreateFlag flag) : AbstractSheetPrivate(p, flag) , windowProtection(false), showFormulas(false), showGridLines(true), showRowColHeaders(true) , showZeros(true), rightToLeft(false), tabSelected(false), showRuler(false) , showOutlineSymbols(true), showWhiteSpace(true), urlPattern(QStringLiteral("^([fh]tt?ps?://)|(mailto:)|(file://)")) , topPageMargin(0.7875), leftPageMargin(0.7875), rightPageMargin(0.7875), bottomPageMargin(0.7875) , headerPageMargin(0.393750), footerPageMargin(0.393750) { previous_row = 0; outline_row_level = 0; outline_col_level = 0; default_row_height = 15; default_row_zeroed = false; } WorksheetPrivate::~WorksheetPrivate() { } /* Calculate the "spans" attribute of the <row> tag. This is an XLSX optimisation and isn't strictly required. However, it makes comparing files easier. The span is the same for each block of 16 rows. */ void WorksheetPrivate::calculateSpans() const { row_spans.clear(); int span_min = XLSX_COLUMN_MAX+1; int span_max = -1; for (int row_num = dimension.firstRow(); row_num <= dimension.lastRow(); row_num++) { if (cellTable.contains(row_num)) { for (int col_num = dimension.firstColumn(); col_num <= dimension.lastColumn(); col_num++) { if (cellTable[row_num].contains(col_num)) { if (span_max == -1) { span_min = col_num; span_max = col_num; } else { if (col_num < span_min) span_min = col_num; else if (col_num > span_max) span_max = col_num; } } } } if (comments.contains(row_num)) { for (int col_num = dimension.firstColumn(); col_num <= dimension.lastColumn(); col_num++) { if (comments[row_num].contains(col_num)) { if (span_max == -1) { span_min = col_num; span_max = col_num; } else { if (col_num < span_min) span_min = col_num; else if (col_num > span_max) span_max = col_num; } } } } if (row_num%16 == 0 || row_num == dimension.lastRow()) { if (span_max != -1) { row_spans[row_num / 16] = QStringLiteral("%1:%2").arg(span_min).arg(span_max); span_min = XLSX_COLUMN_MAX+1; span_max = -1; } } } } QString WorksheetPrivate::generateDimensionString() const { if (!dimension.isValid()) return QStringLiteral("A1"); else return dimension.toString(); } /* Check that row and col are valid and store the max and min values for use in other methods/elements. The ignore_row / ignore_col flags is used to indicate that we wish to perform the dimension check without storing the value. The ignore flags are use by setRow() and dataValidate. */ int WorksheetPrivate::checkDimensions(int row, int col, bool ignore_row, bool ignore_col) { Q_ASSERT_X(row!=0, "checkDimensions", "row should start from 1 instead of 0"); Q_ASSERT_X(col!=0, "checkDimensions", "column should start from 1 instead of 0"); if (row > XLSX_ROW_MAX || row < 1 || col > XLSX_COLUMN_MAX || col < 1) return -1; if (!ignore_row) { if (row < dimension.firstRow() || dimension.firstRow() == -1) dimension.setFirstRow(row); if (row > dimension.lastRow()) dimension.setLastRow(row); } if (!ignore_col) { if (col < dimension.firstColumn() || dimension.firstColumn() == -1) dimension.setFirstColumn(col); if (col > dimension.lastColumn()) dimension.setLastColumn(col); } return 0; } /*! \class Worksheet \inmodule QtXlsx \brief Represent one worksheet in the workbook. */ /*! * \internal */ Worksheet::Worksheet(const QString &name, int id, Workbook *workbook, CreateFlag flag) :AbstractSheet(name, id, workbook, new WorksheetPrivate(this, flag)) { if (!workbook) //For unit test propose only. Ignore the memery leak. d_func()->workbook = new Workbook(flag); } /*! * \internal * * Make a copy of this sheet. */ Worksheet *Worksheet::copy(const QString &distName, int distId) const { Q_D(const Worksheet); Worksheet *sheet = new Worksheet(distName, distId, d->workbook, F_NewFromScratch); WorksheetPrivate *sheet_d = sheet->d_func(); sheet_d->dimension = d->dimension; QMapIterator<int, QMap<int, QSharedPointer<Cell> > > it(d->cellTable); while (it.hasNext()) { it.next(); int row = it.key(); QMapIterator<int, QSharedPointer<Cell> > it2(it.value()); while (it2.hasNext()) { it2.next(); int col = it2.key(); QSharedPointer<Cell> cell(new Cell(it2.value().data())); cell->d_ptr->parent = sheet; if (cell->cellType() == Cell::SharedStringType) d->workbook->sharedStrings()->addSharedString(cell->d_ptr->richString); sheet_d->cellTable[row][col] = cell; } } sheet_d->merges = d->merges; // sheet_d->rowsInfo = d->rowsInfo; // sheet_d->colsInfo = d->colsInfo; // sheet_d->colsInfoHelper = d->colsInfoHelper; // sheet_d->dataValidationsList = d->dataValidationsList; // sheet_d->conditionalFormattingList = d->conditionalFormattingList; return sheet; } /*! * Destroys this workssheet. */ Worksheet::~Worksheet() { } /*! * Returns whether sheet is protected. */ bool Worksheet::isWindowProtected() const { Q_D(const Worksheet); return d->windowProtection; } /*! * Protects/unprotects the sheet based on \a protect. */ void Worksheet::setWindowProtected(bool protect) { Q_D(Worksheet); d->windowProtection = protect; } /*! * Return whether formulas instead of their calculated results shown in cells */ bool Worksheet::isFormulasVisible() const { Q_D(const Worksheet); return d->showFormulas; } /*! * Show formulas in cells instead of their calculated results when \a visible is true. */ void Worksheet::setFormulasVisible(bool visible) { Q_D(Worksheet); d->showFormulas = visible; } /*! * Return whether gridlines is shown or not. */ bool Worksheet::isGridLinesVisible() const { Q_D(const Worksheet); return d->showGridLines; } /*! * Show or hide the gridline based on \a visible */ void Worksheet::setGridLinesVisible(bool visible) { Q_D(Worksheet); d->showGridLines = visible; } /*! * Return whether is row and column headers is vislbe. */ bool Worksheet::isRowColumnHeadersVisible() const { Q_D(const Worksheet); return d->showRowColHeaders; } /*! * Show or hide the row column headers based on \a visible */ void Worksheet::setRowColumnHeadersVisible(bool visible) { Q_D(Worksheet); d->showRowColHeaders = visible; } /*! * Return whether the sheet is shown right-to-left or not. */ bool Worksheet::isRightToLeft() const { Q_D(const Worksheet); return d->rightToLeft; } /*! * Enable or disable the right-to-left based on \a enable. */ void Worksheet::setRightToLeft(bool enable) { Q_D(Worksheet); d->rightToLeft = enable; } /*! * Return whether is cells that have zero value show a zero. */ bool Worksheet::isZerosVisible() const { Q_D(const Worksheet); return d->showZeros; } /*! * Show a zero in cells that have zero value if \a visible is true. */ void Worksheet::setZerosVisible(bool visible) { Q_D(Worksheet); d->showZeros = visible; } /*! * Return whether this tab is selected. */ bool Worksheet::isSelected() const { Q_D(const Worksheet); return d->tabSelected; } /*! * Select this sheet if \a select is true. */ void Worksheet::setSelected(bool select) { Q_D(Worksheet); d->tabSelected = select; } /*! * Return whether is ruler is shown. */ bool Worksheet::isRulerVisible() const { Q_D(const Worksheet); return d->showRuler; } /*! * Show or hide the ruler based on \a visible. */ void Worksheet::setRulerVisible(bool visible) { Q_D(Worksheet); d->showRuler = visible; } /*! * Return whether is outline symbols is shown. */ bool Worksheet::isOutlineSymbolsVisible() const { Q_D(const Worksheet); return d->showOutlineSymbols; } /*! * Show or hide the outline symbols based ib \a visible. */ void Worksheet::setOutlineSymbolsVisible(bool visible) { Q_D(Worksheet); d->showOutlineSymbols = visible; } /*! * Return whether is white space is shown. */ bool Worksheet::isWhiteSpaceVisible() const { Q_D(const Worksheet); return d->showWhiteSpace; } /*! * Show or hide the white space based on \a visible. */ void Worksheet::setWhiteSpaceVisible(bool visible) { Q_D(Worksheet); d->showWhiteSpace = visible; } /*! * Return top page margin */ double Worksheet::topPageMargin() { Q_D(Worksheet); return d->topPageMargin; } /*! * Set top page margin */ void Worksheet::setTopPageMargin(double topPageMargin) { Q_D(Worksheet); d->topPageMargin = topPageMargin; } /*! * Return left page margin */ double Worksheet::leftPageMargin() { Q_D(Worksheet); return d->leftPageMargin; } /*! * Set left page margin */ void Worksheet::setLeftPageMargin(double leftPageMargin) { Q_D(Worksheet); d->leftPageMargin = leftPageMargin; } /*! * Return right page margin */ double Worksheet::rightPageMargin() { Q_D(Worksheet); return d->rightPageMargin; } /*! * Set right page margin */ void Worksheet::setRightPageMargin(double rightPageMargin) { Q_D(Worksheet); d->rightPageMargin = rightPageMargin; } /*! * Return bottom page margin */ double Worksheet::bottomPageMargin() { Q_D(Worksheet); return d->bottomPageMargin; } /*! * Set bottom page margin */ void Worksheet::setBottomPageMargin(double bottomPageMargin) { Q_D(Worksheet); d->bottomPageMargin = bottomPageMargin; } /*! * Return header page margin */ double Worksheet::headerPageMargin() { Q_D(Worksheet); return d->headerPageMargin; } /*! * Set header page margin */ void Worksheet::setHeaderPageMargin(double headerPageMargin) { Q_D(Worksheet); d->headerPageMargin = headerPageMargin; } /*! * Return footer page margin */ double Worksheet::footerPageMargin() { Q_D(Worksheet); return d->footerPageMargin; } /*! * Set footer page margin */ void Worksheet::setFooterPageMargin(double footerPageMargin) { Q_D(Worksheet); d->footerPageMargin = footerPageMargin; } /*! * Write \a value to cell (\a row, \a column) with the \a format. * Both \a row and \a column are all 1-indexed value. * * Returns true on success. */ bool Worksheet::write(int row, int column, const QVariant &value, const Format &format) { Q_D(Worksheet); if (d->checkDimensions(row, column)) return false; bool ret = true; if (value.isNull()) { //Blank ret = writeBlank(row, column, format); } else if (value.userType() == QMetaType::QString) { //String QString token = value.toString(); bool ok; if (token.startsWith(QLatin1String("="))) { //convert to formula ret = writeFormula(row, column, CellFormula(token), format); } else if (d->workbook->isStringsToHyperlinksEnabled() && token.contains(d->urlPattern)) { //convert to url ret = writeHyperlink(row, column, QUrl(token)); } else if (d->workbook->isStringsToNumbersEnabled() && (value.toDouble(&ok), ok)) { //Try convert string to number if the flag enabled. ret = writeString(row, column, value.toString(), format); } else { //normal string now ret = writeString(row, column, token, format); } } else if (value.userType() == qMetaTypeId<RichString>()) { ret = writeString(row, column, value.value<RichString>(), format); } else if (value.userType() == QMetaType::Int || value.userType() == QMetaType::UInt || value.userType() == QMetaType::LongLong || value.userType() == QMetaType::ULongLong || value.userType() == QMetaType::Double || value.userType() == QMetaType::Float) { //Number ret = writeNumeric(row, column, value.toDouble(), format); } else if (value.userType() == QMetaType::Bool) { //Bool ret = writeBool(row,column, value.toBool(), format); } else if (value.userType() == QMetaType::QDateTime || value.userType() == QMetaType::QDate) { //DateTime, Date // note that, QTime cann't convert to QDateTime ret = writeDateTime(row, column, value.toDateTime(), format); } else if (value.userType() == QMetaType::QTime) { //Time ret = writeTime(row, column, value.toTime(), format); } else if (value.userType() == QMetaType::QUrl) { //Url ret = writeHyperlink(row, column, value.toUrl(), format); } else { //Wrong type return false; } return ret; } /*! * \overload * Write \a value to cell \a row_column with the \a format. * Both row and column are all 1-indexed value. * Returns true on success. */ bool Worksheet::write(const CellReference &row_column, const QVariant &value, const Format &format) { if (!row_column.isValid()) return false; return write(row_column.row(), row_column.column(), value, format); } /*! \overload Return the contents of the cell \a row_column. */ QVariant Worksheet::read(const CellReference &row_column) const { if (!row_column.isValid()) return QVariant(); return read(row_column.row(), row_column.column()); } /*! Return the contents of the cell (\a row, \a column). */ QVariant Worksheet::read(int row, int column) const { Q_D(const Worksheet); Cell *cell = cellAt(row, column); if (!cell) return QVariant(); if (cell->hasFormula()) { if (cell->formula().formulaType() == CellFormula::NormalType) { return QVariant(QLatin1String("=")+cell->formula().formulaText()); } else if (cell->formula().formulaType() == CellFormula::SharedType) { if (!cell->formula().formulaText().isEmpty()) { return QVariant(QLatin1String("=")+cell->formula().formulaText()); } else { const CellFormula &rootFormula = d->sharedFormulaMap[cell->formula().sharedIndex()]; CellReference rootCellRef = rootFormula.reference().topLeft(); QString rootFormulaText = rootFormula.formulaText(); QString newFormulaText = convertSharedFormula(rootFormulaText, rootCellRef, CellReference(row, column)); return QVariant(QLatin1String("=")+newFormulaText); } } } const QVariant rawValue = cell->value(); if (!rawValue.isValid()) return QVariant(); if (cell->isDateTime()) { double val = cell->value().toDouble(); QDateTime dt = cell->dateTime(); if (val < 1) return dt.time(); if (fmod(val, 1.0) < 1.0/(1000*60*60*24)) //integer return dt.date(); return dt; } return rawValue; } /*! * Returns the cell at the given \a row_column. If there * is no cell at the specified position, the function returns 0. */ Cell *Worksheet::cellAt(const CellReference &row_column) const { if (!row_column.isValid()) return NULL; return cellAt(row_column.row(), row_column.column()); } /*! * Returns the cell at the given \a row and \a column. If there * is no cell at the specified position, the function returns 0. */ Cell *Worksheet::cellAt(int row, int column) const { Q_D(const Worksheet); if (!d->cellTable.contains(row)) return NULL; if (!d->cellTable[row].contains(column)) return NULL; return d->cellTable[row][column].data(); } Format WorksheetPrivate::cellFormat(int row, int col) const { if (!cellTable.contains(row)) return Format(); if (!cellTable[row].contains(col)) return Format(); return cellTable[row][col]->format(); } /*! \overload Write string \a value to the cell \a row_column with the \a format. Returns true on success. */ bool Worksheet::writeString(const CellReference &row_column, const RichString &value, const Format &format) { if (!row_column.isValid()) return false; return writeString(row_column.row(), row_column.column(), value, format); } /*! Write string \a value to the cell (\a row, \a column) with the \a format. Returns true on success. */ bool Worksheet::writeString(int row, int column, const RichString &value, const Format &format) { Q_D(Worksheet); // QString content = value.toPlainString(); if (d->checkDimensions(row, column)) return false; // if (content.size() > d->xls_strmax) { // content = content.left(d->xls_strmax); // error = -2; // } d->sharedStrings()->addSharedString(value); Format fmt = format.isValid() ? format : d->cellFormat(row, column); if (value.fragmentCount() == 1 && value.fragmentFormat(0).isValid()) fmt.mergeFormat(value.fragmentFormat(0)); d->workbook->styles()->addXfFormat(fmt); QSharedPointer<Cell> cell = QSharedPointer<Cell>(new Cell(value.toPlainString(), Cell::SharedStringType, fmt, this)); cell->d_ptr->richString = value; d->cellTable[row][column] = cell; return true; } /*! \overload Write string \a value to the cell \a row_column with the \a format. */ bool Worksheet::writeString(const CellReference &row_column, const QString &value, const Format &format) { if (!row_column.isValid()) return false; return writeString(row_column.row(), row_column.column(), value, format); } /*! \overload Write string \a value to the cell (\a row, \a column) with the \a format. Returns true on success. */ bool Worksheet::writeString(int row, int column, const QString &value, const Format &format) { Q_D(Worksheet); if (d->checkDimensions(row, column)) return false; RichString rs; if (d->workbook->isHtmlToRichStringEnabled() && Qt::mightBeRichText(value)) rs.setHtml(value); else rs.addFragment(value, Format()); return writeString(row, column, rs, format); } /*! \overload Write string \a value to the cell \a row_column with the \a format */ bool Worksheet::writeInlineString(const CellReference &row_column, const QString &value, const Format &format) { if (!row_column.isValid()) return false; return writeInlineString(row_column.row(), row_column.column(), value, format); } /*! Write string \a value to the cell (\a row, \a column) with the \a format. Returns true on success. */ bool Worksheet::writeInlineString(int row, int column, const QString &value, const Format &format) { Q_D(Worksheet); //int error = 0; QString content = value; if (d->checkDimensions(row, column)) return false; if (value.size() > XLSX_STRING_MAX) { content = value.left(XLSX_STRING_MAX); //error = -2; } Format fmt = format.isValid() ? format : d->cellFormat(row, column); d->workbook->styles()->addXfFormat(fmt); d->cellTable[row][column] = QSharedPointer<Cell>(new Cell(value, Cell::InlineStringType, fmt, this)); return true; } /*! \overload Write numeric \a value to the cell \a row_column with the \a format. Returns true on success. */ bool Worksheet::writeNumeric(const CellReference &row_column, double value, const Format &format) { if (!row_column.isValid()) return false; return writeNumeric(row_column.row(), row_column.column(), value, format); } /*! Write numeric \a value to the cell (\a row, \a column) with the \a format. Returns true on success. */ bool Worksheet::writeNumeric(int row, int column, double value, const Format &format) { Q_D(Worksheet); if (d->checkDimensions(row, column)) return false; Format fmt = format.isValid() ? format : d->cellFormat(row, column); d->workbook->styles()->addXfFormat(fmt); d->cellTable[row][column] = QSharedPointer<Cell>(new Cell(value, Cell::NumberType, fmt, this)); return true; } /*! \overload Write \a formula to the cell \a row_column with the \a format and \a result. Returns true on success. */ bool Worksheet::writeFormula(const CellReference &row_column, const CellFormula &formula, const Format &format, double result) { if (!row_column.isValid()) return false; return writeFormula(row_column.row(), row_column.column(), formula, format, result); } /*! Write \a formula_ to the cell (\a row, \a column) with the \a format and \a result. Returns true on success. */ bool Worksheet::writeFormula(int row, int column, const CellFormula &formula_, const Format &format, double result) { Q_D(Worksheet); if (d->checkDimensions(row, column)) return false; Format fmt = format.isValid() ? format : d->cellFormat(row, column); d->workbook->styles()->addXfFormat(fmt); CellFormula formula = formula_; formula.d->ca = true; if (formula.formulaType() == CellFormula::SharedType) { //Assign proper shared index for shared formula int si=0; while(d->sharedFormulaMap.contains(si)) ++si; formula.d->si = si; d->sharedFormulaMap[si] = formula; } QSharedPointer<Cell> data = QSharedPointer<Cell>(new Cell(result, Cell::NumberType, fmt, this)); data->d_ptr->formula = formula; d->cellTable[row][column] = data; CellRange range = formula.reference(); if (formula.formulaType() == CellFormula::SharedType) { CellFormula sf(QString(), CellFormula::SharedType); sf.d->si = formula.sharedIndex(); for (int r=range.firstRow(); r<=range.lastRow(); ++r) { for (int c=range.firstColumn(); c<=range.lastColumn(); ++c) { if (!(r==row && c==column)) { if(Cell *cell = cellAt(r, c)) { cell->d_ptr->formula = sf; } else { QSharedPointer<Cell> newCell = QSharedPointer<Cell>(new Cell(result, Cell::NumberType, fmt, this)); newCell->d_ptr->formula = sf; d->cellTable[r][c] = newCell; } } } } } else if (formula.formulaType() == CellFormula::SharedType) { } return true; } /*! \overload Write a empty cell \a row_column with the \a format. Returns true on success. */ bool Worksheet::writeBlank(const CellReference &row_column, const Format &format) { if (!row_column.isValid()) return false; return writeBlank(row_column.row(), row_column.column(), format); } /*! Write a empty cell (\a row, \a column) with the \a format. Returns true on success. */ bool Worksheet::writeBlank(int row, int column, const Format &format) { Q_D(Worksheet); if (d->checkDimensions(row, column)) return false; Format fmt = format.isValid() ? format : d->cellFormat(row, column); d->workbook->styles()->addXfFormat(fmt); //Note: NumberType with an invalid QVariant value means blank. d->cellTable[row][column] = QSharedPointer<Cell>(new Cell(QVariant(), Cell::NumberType, fmt, this)); return true; } /*! \overload Write a bool \a value to the cell \a row_column with the \a format. Returns true on success. */ bool Worksheet::writeBool(const CellReference &row_column, bool value, const Format &format) { if (!row_column.isValid()) return false; return writeBool(row_column.row(), row_column.column(), value, format); } /*! Write a bool \a value to the cell (\a row, \a column) with the \a format. Returns true on success. */ bool Worksheet::writeBool(int row, int column, bool value, const Format &format) { Q_D(Worksheet); if (d->checkDimensions(row, column)) return false; Format fmt = format.isValid() ? format : d->cellFormat(row, column); d->workbook->styles()->addXfFormat(fmt); d->cellTable[row][column] = QSharedPointer<Cell>(new Cell(value, Cell::BooleanType, fmt, this)); return true; } /*! \overload Write a QDateTime \a dt to the cell \a row_column with the \a format. Returns true on success. */ bool Worksheet::writeDateTime(const CellReference &row_column, const QDateTime &dt, const Format &format) { if (!row_column.isValid()) return false; return writeDateTime(row_column.row(), row_column.column(), dt, format); } /*! Write a QDateTime \a dt to the cell (\a row, \a column) with the \a format. Returns true on success. */ bool Worksheet::writeDateTime(int row, int column, const QDateTime &dt, const Format &format) { Q_D(Worksheet); if (d->checkDimensions(row, column)) return false; Format fmt = format.isValid() ? format : d->cellFormat(row, column); if (!fmt.isValid() || !fmt.isDateTimeFormat()) fmt.setNumberFormat(d->workbook->defaultDateFormat()); d->workbook->styles()->addXfFormat(fmt); double value = datetimeToNumber(dt, d->workbook->isDate1904()); d->cellTable[row][column] = QSharedPointer<Cell>(new Cell(value, Cell::NumberType, fmt, this)); return true; } /*! \overload Write a QTime \a t to the cell \a row_column with the \a format. Returns true on success. */ bool Worksheet::writeTime(const CellReference &row_column, const QTime &t, const Format &format) { if (!row_column.isValid()) return false; return writeTime(row_column.row(), row_column.column(), t, format); } /*! Write a QTime \a t to the cell (\a row, \a column) with the \a format. Returns true on success. */ bool Worksheet::writeTime(int row, int column, const QTime &t, const Format &format) { Q_D(Worksheet); if (d->checkDimensions(row, column)) return false; Format fmt = format.isValid() ? format : d->cellFormat(row, column); if (!fmt.isValid() || !fmt.isDateTimeFormat()) fmt.setNumberFormat(QStringLiteral("hh:mm:ss")); d->workbook->styles()->addXfFormat(fmt); d->cellTable[row][column] = QSharedPointer<Cell>(new Cell(timeToNumber(t), Cell::NumberType, fmt, this)); return true; } /*! \overload Write a QUrl \a url to the cell \a row_column with the given \a format \a display and \a tip. Returns true on success. */ bool Worksheet::writeHyperlink(const CellReference &row_column, const QUrl &url, const Format &format, const QString &display, const QString &tip) { if (!row_column.isValid()) return false; return writeHyperlink(row_column.row(), row_column.column(), url, format, display, tip); } /*! Write a QUrl \a url to the cell (\a row, \a column) with the given \a format \a display and \a tip. Returns true on success. */ bool Worksheet::writeHyperlink(int row, int column, const QUrl &url, const Format &format, const QString &display, const QString &tip) { Q_D(Worksheet); if (d->checkDimensions(row, column)) return false; //int error = 0; QString urlString = url.toString(); //Generate proper display string QString displayString = display.isEmpty() ? urlString : display; if (displayString.startsWith(QLatin1String("mailto:"))) displayString.replace(QLatin1String("mailto:"), QString()); if (displayString.size() > XLSX_STRING_MAX) { displayString = displayString.left(XLSX_STRING_MAX); //error = -2; } /* Location within target. If target is a workbook (or this workbook) this shall refer to a sheet and cell or a defined name. Can also be an HTML anchor if target is HTML file. c:\temp\file.xlsx#Sheet!A1 http://a.com/aaa.html#aaaaa */ QString locationString; if (url.hasFragment()) { locationString = url.fragment(); urlString = url.toString(QUrl::RemoveFragment); } Format fmt = format.isValid() ? format : d->cellFormat(row, column); //Given a default style for hyperlink if (!fmt.isValid()) { fmt.setFontColor(Qt::blue); fmt.setFontUnderline(Format::FontUnderlineSingle); } d->workbook->styles()->addXfFormat(fmt); //Write the hyperlink string as normal string. d->sharedStrings()->addSharedString(displayString); d->cellTable[row][column] = QSharedPointer<Cell>(new Cell(displayString, Cell::SharedStringType, fmt, this)); //Store the hyperlink data in a separate table d->urlTable[row][column] = QSharedPointer<XlsxHyperlinkData>(new XlsxHyperlinkData(XlsxHyperlinkData::External, urlString, locationString, QString(), tip)); return true; } /*! * Add one DataValidation \a validation to the sheet. * Returns true on success. */ bool Worksheet::addDataValidation(const DataValidation &validation) { Q_D(Worksheet); if (validation.ranges().isEmpty() || validation.validationType()==DataValidation::None) return false; d->dataValidationsList.append(validation); return true; } /*! * Add one ConditionalFormatting \a cf to the sheet. * Returns true on success. */ bool Worksheet::addConditionalFormatting(const ConditionalFormatting &cf) { Q_D(Worksheet); if (cf.ranges().isEmpty()) return false; for (int i=0; i<cf.d->cfRules.size(); ++i) { const QSharedPointer<XlsxCfRuleData> &rule = cf.d->cfRules[i]; if (!rule->dxfFormat.isEmpty()) d->workbook->styles()->addDxfFormat(rule->dxfFormat); rule->priority = 1; } d->conditionalFormattingList.append(cf); return true; } /*! * Insert an \a image at the position \a row, \a column * Returns true on success. */ bool Worksheet::insertImage(int row, int column, const QImage &image) { Q_D(Worksheet); if (image.isNull()) return false; if (!d->drawing) d->drawing = QSharedPointer<Drawing>(new Drawing(this, F_NewFromScratch)); DrawingOneCellAnchor *anchor = new DrawingOneCellAnchor(d->drawing.data(), DrawingAnchor::Picture); /* The size are expressed as English Metric Units (EMUs). There are 12,700 EMUs per point. Therefore, 12,700 * 3 /4 = 9,525 EMUs per pixel */ anchor->from = XlsxMarker(row, column, 0, 0); anchor->ext = QSize(image.width() * 9525, image.height() * 9525); anchor->setObjectPicture(image); return true; } /*! * Creates an chart with the given \a size and insert * at the position \a row, \a column. * The chart will be returned. */ Chart *Worksheet::insertChart(int row, int column, const QSize &size) { Q_D(Worksheet); if (!d->drawing) d->drawing = QSharedPointer<Drawing>(new Drawing(this, F_NewFromScratch)); DrawingOneCellAnchor *anchor = new DrawingOneCellAnchor(d->drawing.data(), DrawingAnchor::Picture); /* The size are expressed as English Metric Units (EMUs). There are 12,700 EMUs per point. Therefore, 12,700 * 3 /4 = 9,525 EMUs per pixel */ anchor->from = XlsxMarker(row, column, 0, 0); anchor->ext = size * 9525; QSharedPointer<Chart> chart = QSharedPointer<Chart>(new Chart(this, F_NewFromScratch)); anchor->setObjectGraphicFrame(chart); return chart.data(); } /*! Merge a \a range of cells. The first cell should contain the data and the others should be blank. All cells will be applied the same style if a valid \a format is given. Returns true on success. \note All cells except the top-left one will be cleared. */ bool Worksheet::mergeCells(const CellRange &range, const Format &format) { Q_D(Worksheet); if (range.rowCount() < 2 && range.columnCount() < 2) return false; if (d->checkDimensions(range.firstRow(), range.firstColumn())) return false; if (format.isValid()) d->workbook->styles()->addXfFormat(format); for (int row = range.firstRow(); row <= range.lastRow(); ++row) { for (int col = range.firstColumn(); col <= range.lastColumn(); ++col) { if (row == range.firstRow() && col == range.firstColumn()) { Cell *cell = cellAt(row, col); if (cell) { if (format.isValid()) cell->d_ptr->format = format; } else { writeBlank(row, col, format); } } else { writeBlank(row, col, format); } } } d->merges.append(range); return true; } /*! Unmerge the cells in the \a range. Returns true on success. */ bool Worksheet::unmergeCells(const CellRange &range) { Q_D(Worksheet); if (!d->merges.contains(range)) return false; d->merges.removeOne(range); return true; } /*! Returns all the merged cells. */ QList<CellRange> Worksheet::mergedCells() const { Q_D(const Worksheet); return d->merges; } /*! * \internal */ void Worksheet::saveToXmlFile(QIODevice *device) const { Q_D(const Worksheet); d->relationships->clear(); QXmlStreamWriter writer(device); writer.writeStartDocument(QStringLiteral("1.0"), true); writer.writeStartElement(QStringLiteral("worksheet")); writer.writeAttribute(QStringLiteral("xmlns"), QStringLiteral("http://schemas.openxmlformats.org/spreadsheetml/2006/main")); writer.writeAttribute(QStringLiteral("xmlns:r"), QStringLiteral("http://schemas.openxmlformats.org/officeDocument/2006/relationships")); //for Excel 2010 // writer.writeAttribute("xmlns:mc", "http://schemas.openxmlformats.org/markup-compatibility/2006"); // writer.writeAttribute("xmlns:x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"); // writer.writeAttribute("mc:Ignorable", "x14ac"); writer.writeStartElement(QStringLiteral("dimension")); writer.writeAttribute(QStringLiteral("ref"), d->generateDimensionString()); writer.writeEndElement();//dimension writer.writeStartElement(QStringLiteral("sheetViews")); writer.writeStartElement(QStringLiteral("sheetView")); if (d->windowProtection) writer.writeAttribute(QStringLiteral("windowProtection"), QStringLiteral("1")); if (d->showFormulas) writer.writeAttribute(QStringLiteral("showFormulas"), QStringLiteral("1")); if (!d->showGridLines) writer.writeAttribute(QStringLiteral("showGridLines"), QStringLiteral("0")); if (!d->showRowColHeaders) writer.writeAttribute(QStringLiteral("showRowColHeaders"), QStringLiteral("0")); if (!d->showZeros) writer.writeAttribute(QStringLiteral("showZeros"), QStringLiteral("0")); if (d->rightToLeft) writer.writeAttribute(QStringLiteral("rightToLeft"), QStringLiteral("1")); if (d->tabSelected) writer.writeAttribute(QStringLiteral("tabSelected"), QStringLiteral("1")); if (!d->showRuler) writer.writeAttribute(QStringLiteral("showRuler"), QStringLiteral("0")); if (!d->showOutlineSymbols) writer.writeAttribute(QStringLiteral("showOutlineSymbols"), QStringLiteral("0")); if (!d->showWhiteSpace) writer.writeAttribute(QStringLiteral("showWhiteSpace"), QStringLiteral("0")); writer.writeAttribute(QStringLiteral("workbookViewId"), QStringLiteral("0")); writer.writeEndElement();//sheetView writer.writeEndElement();//sheetViews writer.writeStartElement(QStringLiteral("sheetFormatPr")); writer.writeAttribute(QStringLiteral("defaultRowHeight"), QString::number(d->default_row_height)); if (d->default_row_height != 15) writer.writeAttribute(QStringLiteral("customHeight"), QStringLiteral("1")); if (d->default_row_zeroed) writer.writeAttribute(QStringLiteral("zeroHeight"), QStringLiteral("1")); if (d->outline_row_level) writer.writeAttribute(QStringLiteral("outlineLevelRow"), QString::number(d->outline_row_level)); if (d->outline_col_level) writer.writeAttribute(QStringLiteral("outlineLevelCol"), QString::number(d->outline_col_level)); //for Excel 2010 // writer.writeAttribute("x14ac:dyDescent", "0.25"); writer.writeEndElement();//sheetFormatPr if (!d->colsInfo.isEmpty()) { writer.writeStartElement(QStringLiteral("cols")); QMapIterator<int, QSharedPointer<XlsxColumnInfo> > it(d->colsInfo); while (it.hasNext()) { it.next(); QSharedPointer<XlsxColumnInfo> col_info = it.value(); writer.writeStartElement(QStringLiteral("col")); writer.writeAttribute(QStringLiteral("min"), QString::number(col_info->firstColumn)); writer.writeAttribute(QStringLiteral("max"), QString::number(col_info->lastColumn)); if (col_info->width) writer.writeAttribute(QStringLiteral("width"), QString::number(col_info->width, 'g', 15)); if (!col_info->format.isEmpty()) writer.writeAttribute(QStringLiteral("style"), QString::number(col_info->format.xfIndex())); if (col_info->hidden) writer.writeAttribute(QStringLiteral("hidden"), QStringLiteral("1")); if (col_info->width) writer.writeAttribute(QStringLiteral("customWidth"), QStringLiteral("1")); if (col_info->outlineLevel) writer.writeAttribute(QStringLiteral("outlineLevel"), QString::number(col_info->outlineLevel)); if (col_info->collapsed) writer.writeAttribute(QStringLiteral("collapsed"), QStringLiteral("1")); writer.writeEndElement();//col } writer.writeEndElement();//cols } writer.writeStartElement(QStringLiteral("sheetData")); if (d->dimension.isValid()) d->saveXmlSheetData(writer); writer.writeEndElement();//sheetData d->saveXmlMergeCells(writer); foreach (const ConditionalFormatting cf, d->conditionalFormattingList) cf.saveToXml(writer); d->saveXmlDataValidations(writer); d->saveXmlHyperlinks(writer); d->saveXmlDrawings(writer); writer.writeStartElement(QStringLiteral("pageMargins")); writer.writeAttribute(QStringLiteral("left"), QString::number(d->leftPageMargin, 'g', 15)); writer.writeAttribute(QStringLiteral("right"), QString::number(d->rightPageMargin, 'g', 15)); writer.writeAttribute(QStringLiteral("top"), QString::number(d->topPageMargin, 'g', 15)); writer.writeAttribute(QStringLiteral("bottom"), QString::number(d->bottomPageMargin, 'g', 15)); writer.writeAttribute(QStringLiteral("header"), QString::number(d->headerPageMargin, 'g', 15)); writer.writeAttribute(QStringLiteral("footer"), QString::number(d->footerPageMargin, 'g', 15)); writer.writeEndElement();//pagemargins writer.writeEndElement();//worksheet writer.writeEndDocument(); } void WorksheetPrivate::saveXmlSheetData(QXmlStreamWriter &writer) const { calculateSpans(); for (int row_num = dimension.firstRow(); row_num <= dimension.lastRow(); row_num++) { if (!(cellTable.contains(row_num) || comments.contains(row_num) || rowsInfo.contains(row_num))) { //Only process rows with cell data / comments / formatting continue; } int span_index = (row_num-1) / 16; QString span; if (row_spans.contains(span_index)) span = row_spans[span_index]; writer.writeStartElement(QStringLiteral("row")); writer.writeAttribute(QStringLiteral("r"), QString::number(row_num)); if (!span.isEmpty()) writer.writeAttribute(QStringLiteral("spans"), span); if (rowsInfo.contains(row_num)) { QSharedPointer<XlsxRowInfo> rowInfo = rowsInfo[row_num]; if (!rowInfo->format.isEmpty()) { writer.writeAttribute(QStringLiteral("s"), QString::number(rowInfo->format.xfIndex())); writer.writeAttribute(QStringLiteral("customFormat"), QStringLiteral("1")); } //!Todo: support customHeight from info struct //!Todo: where does this magic number '15' come from? if (rowInfo->customHeight) { writer.writeAttribute(QStringLiteral("ht"), QString::number(rowInfo->height)); writer.writeAttribute(QStringLiteral("customHeight"), QStringLiteral("1")); } else { writer.writeAttribute(QStringLiteral("customHeight"), QStringLiteral("0")); } if (rowInfo->hidden) writer.writeAttribute(QStringLiteral("hidden"), QStringLiteral("1")); if (rowInfo->outlineLevel > 0) writer.writeAttribute(QStringLiteral("outlineLevel"), QString::number(rowInfo->outlineLevel)); if (rowInfo->collapsed) writer.writeAttribute(QStringLiteral("collapsed"), QStringLiteral("1")); } //Write cell data if row contains filled cells if (cellTable.contains(row_num)) { for (int col_num = dimension.firstColumn(); col_num <= dimension.lastColumn(); col_num++) { if (cellTable[row_num].contains(col_num)) { saveXmlCellData(writer, row_num, col_num, cellTable[row_num][col_num]); } } } writer.writeEndElement(); //row } } void WorksheetPrivate::saveXmlCellData(QXmlStreamWriter &writer, int row, int col, QSharedPointer<Cell> cell) const { //This is the innermost loop so efficiency is important. QString cell_pos = CellReference(row, col).toString(); writer.writeStartElement(QStringLiteral("c")); writer.writeAttribute(QStringLiteral("r"), cell_pos); //Style used by the cell, row or col if (!cell->format().isEmpty()) writer.writeAttribute(QStringLiteral("s"), QString::number(cell->format().xfIndex())); else if (rowsInfo.contains(row) && !rowsInfo[row]->format.isEmpty()) writer.writeAttribute(QStringLiteral("s"), QString::number(rowsInfo[row]->format.xfIndex())); else if (colsInfoHelper.contains(col) && !colsInfoHelper[col]->format.isEmpty()) writer.writeAttribute(QStringLiteral("s"), QString::number(colsInfoHelper[col]->format.xfIndex())); if (cell->cellType() == Cell::SharedStringType) { int sst_idx; if (cell->isRichString()) sst_idx = sharedStrings()->getSharedStringIndex(cell->d_ptr->richString); else sst_idx = sharedStrings()->getSharedStringIndex(cell->value().toString()); writer.writeAttribute(QStringLiteral("t"), QStringLiteral("s")); writer.writeTextElement(QStringLiteral("v"), QString::number(sst_idx)); } else if (cell->cellType() == Cell::InlineStringType) { writer.writeAttribute(QStringLiteral("t"), QStringLiteral("inlineStr")); writer.writeStartElement(QStringLiteral("is")); if (cell->isRichString()) { //Rich text string RichString string = cell->d_ptr->richString; for (int i=0; i<string.fragmentCount(); ++i) { writer.writeStartElement(QStringLiteral("r")); if (string.fragmentFormat(i).hasFontData()) { writer.writeStartElement(QStringLiteral("rPr")); //:Todo writer.writeEndElement();// rPr } writer.writeStartElement(QStringLiteral("t")); if (isSpaceReserveNeeded(string.fragmentText(i))) writer.writeAttribute(QStringLiteral("xml:space"), QStringLiteral("preserve")); writer.writeCharacters(string.fragmentText(i)); writer.writeEndElement();// t writer.writeEndElement(); // r } } else { writer.writeStartElement(QStringLiteral("t")); QString string = cell->value().toString(); if (isSpaceReserveNeeded(string)) writer.writeAttribute(QStringLiteral("xml:space"), QStringLiteral("preserve")); writer.writeCharacters(string); writer.writeEndElement(); // t } writer.writeEndElement();//is } else if (cell->cellType() == Cell::NumberType){ if (cell->hasFormula()) cell->formula().saveToXml(writer); if (cell->value().isValid()) {//note that, invalid value means 'v' is blank double value = cell->value().toDouble(); writer.writeTextElement(QStringLiteral("v"), QString::number(value, 'g', 15)); } } else if (cell->cellType() == Cell::StringType) { writer.writeAttribute(QStringLiteral("t"), QStringLiteral("str")); if (cell->hasFormula()) cell->formula().saveToXml(writer); writer.writeTextElement(QStringLiteral("v"), cell->value().toString()); } else if (cell->cellType() == Cell::BooleanType) { writer.writeAttribute(QStringLiteral("t"), QStringLiteral("b")); writer.writeTextElement(QStringLiteral("v"), cell->value().toBool() ? QStringLiteral("1") : QStringLiteral("0")); } writer.writeEndElement(); //c } void WorksheetPrivate::saveXmlMergeCells(QXmlStreamWriter &writer) const { if (merges.isEmpty()) return; writer.writeStartElement(QStringLiteral("mergeCells")); writer.writeAttribute(QStringLiteral("count"), QString::number(merges.size())); foreach (CellRange range, merges) { writer.writeEmptyElement(QStringLiteral("mergeCell")); writer.writeAttribute(QStringLiteral("ref"), range.toString()); } writer.writeEndElement(); //mergeCells } void WorksheetPrivate::saveXmlDataValidations(QXmlStreamWriter &writer) const { if (dataValidationsList.isEmpty()) return; writer.writeStartElement(QStringLiteral("dataValidations")); writer.writeAttribute(QStringLiteral("count"), QString::number(dataValidationsList.size())); foreach (DataValidation validation, dataValidationsList) validation.saveToXml(writer); writer.writeEndElement(); //dataValidations } void WorksheetPrivate::saveXmlHyperlinks(QXmlStreamWriter &writer) const { if (urlTable.isEmpty()) return; writer.writeStartElement(QStringLiteral("hyperlinks")); QMapIterator<int, QMap<int, QSharedPointer<XlsxHyperlinkData> > > it(urlTable); while (it.hasNext()) { it.next(); int row = it.key(); QMapIterator <int, QSharedPointer<XlsxHyperlinkData> > it2(it.value()); while (it2.hasNext()) { it2.next(); int col = it2.key(); QSharedPointer<XlsxHyperlinkData> data = it2.value(); QString ref = CellReference(row, col).toString(); writer.writeEmptyElement(QStringLiteral("hyperlink")); writer.writeAttribute(QStringLiteral("ref"), ref); if (data->linkType == XlsxHyperlinkData::External) { //Update relationships relationships->addWorksheetRelationship(QStringLiteral("/hyperlink"), data->target, QStringLiteral("External")); writer.writeAttribute(QStringLiteral("r:id"), QStringLiteral("rId%1").arg(relationships->count())); } if (!data->location.isEmpty()) writer.writeAttribute(QStringLiteral("location"), data->location); if (!data->display.isEmpty()) writer.writeAttribute(QStringLiteral("display"), data->display); if (!data->tooltip.isEmpty()) writer.writeAttribute(QStringLiteral("tooltip"), data->tooltip); } } writer.writeEndElement();//hyperlinks } void WorksheetPrivate::saveXmlDrawings(QXmlStreamWriter &writer) const { if (!drawing) return; int idx = workbook->drawings().indexOf(drawing.data()); relationships->addWorksheetRelationship(QStringLiteral("/drawing"), QStringLiteral("../drawings/drawing%1.xml").arg(idx+1)); writer.writeEmptyElement(QStringLiteral("drawing")); writer.writeAttribute(QStringLiteral("r:id"), QStringLiteral("rId%1").arg(relationships->count())); } void WorksheetPrivate::splitColsInfo(int colFirst, int colLast) { // Split current columnInfo, for example, if "A:H" has been set, // we are trying to set "B:D", there should be "A", "B:D", "E:H". // This will be more complex if we try to set "C:F" after "B:D". { QMapIterator<int, QSharedPointer<XlsxColumnInfo> > it(colsInfo); while (it.hasNext()) { it.next(); QSharedPointer<XlsxColumnInfo> info = it.value(); if (colFirst > info->firstColumn && colFirst <= info->lastColumn) { //split the range, QSharedPointer<XlsxColumnInfo> info2(new XlsxColumnInfo(*info)); info->lastColumn = colFirst - 1; info2->firstColumn = colFirst; colsInfo.insert(colFirst, info2); for (int c = info2->firstColumn; c <= info2->lastColumn; ++c) colsInfoHelper[c] = info2; break; } } } { QMapIterator<int, QSharedPointer<XlsxColumnInfo> > it(colsInfo); while (it.hasNext()) { it.next(); QSharedPointer<XlsxColumnInfo> info = it.value(); if (colLast >= info->firstColumn && colLast < info->lastColumn) { QSharedPointer<XlsxColumnInfo> info2(new XlsxColumnInfo(*info)); info->lastColumn = colLast; info2->firstColumn = colLast + 1; colsInfo.insert(colLast + 1, info2); for (int c = info2->firstColumn; c <= info2->lastColumn; ++c) colsInfoHelper[c] = info2; break; } } } } bool WorksheetPrivate::isColumnRangeValid(int colFirst, int colLast) { bool ignore_row = true; bool ignore_col = false; if (colFirst > colLast) return false; if (checkDimensions(1, colLast, ignore_row, ignore_col)) return false; if (checkDimensions(1, colFirst, ignore_row, ignore_col)) return false; return true; } QList<int> WorksheetPrivate ::getColumnIndexes(int colFirst, int colLast) { splitColsInfo(colFirst, colLast); QList<int> nodes; nodes.append(colFirst); for (int col = colFirst; col <= colLast; ++col) { if (colsInfo.contains(col)) { if (nodes.last() != col) nodes.append(col); int nextCol = colsInfo[col]->lastColumn + 1; if (nextCol <= colLast) nodes.append(nextCol); } } return nodes; } /*! Sets width in characters of a \a range of columns to \a width. Returns true on success. */ bool Worksheet::setColumnWidth(const CellRange &range, double width) { if (!range.isValid()) return false; return setColumnWidth(range.firstColumn(), range.lastColumn(), width); } /*! Sets format property of a \a range of columns to \a format. Columns are 1-indexed. Returns true on success. */ bool Worksheet::setColumnFormat(const CellRange& range, const Format &format) { if (!range.isValid()) return false; return setColumnFormat(range.firstColumn(), range.lastColumn(), format); } /*! Sets hidden property of a \a range of columns to \a hidden. Columns are 1-indexed. Hidden columns are not visible. Returns true on success. */ bool Worksheet::setColumnHidden(const CellRange &range, bool hidden) { if (!range.isValid()) return false; return setColumnHidden(range.firstColumn(), range.lastColumn(), hidden); } /*! Sets width in characters for columns [\a colFirst, \a colLast] to \a width. Columns are 1-indexed. Returns true on success. */ bool Worksheet::setColumnWidth(int colFirst, int colLast, double width) { Q_D(Worksheet); QList <QSharedPointer<XlsxColumnInfo> > columnInfoList = d->getColumnInfoList(colFirst, colLast); foreach(QSharedPointer<XlsxColumnInfo> columnInfo, columnInfoList) columnInfo->width = width; return (columnInfoList.count() > 0); } /*! Sets format property of a range of columns [\a colFirst, \a colLast] to \a format. Columns are 1-indexed. Returns true on success. */ bool Worksheet::setColumnFormat(int colFirst, int colLast, const Format &format) { Q_D(Worksheet); QList <QSharedPointer<XlsxColumnInfo> > columnInfoList = d->getColumnInfoList(colFirst, colLast); foreach(QSharedPointer<XlsxColumnInfo> columnInfo, columnInfoList) columnInfo->format = format; if(columnInfoList.count() > 0) { d->workbook->styles()->addXfFormat(format); return true; } return false; } /*! Sets hidden property of a range of columns [\a colFirst, \a colLast] to \a hidden. Columns are 1-indexed. Returns true on success. */ bool Worksheet::setColumnHidden(int colFirst, int colLast, bool hidden) { Q_D(Worksheet); QList <QSharedPointer<XlsxColumnInfo> > columnInfoList = d->getColumnInfoList(colFirst, colLast); foreach(QSharedPointer<XlsxColumnInfo> columnInfo, columnInfoList) columnInfo->hidden = hidden; return (columnInfoList.count() > 0); } /*! Returns width of the \a column in characters of the normal font. Columns are 1-indexed. */ double Worksheet::columnWidth(int column) { Q_D(Worksheet); QList <QSharedPointer<XlsxColumnInfo> > columnInfoList = d->getColumnInfoList(column, column); if (columnInfoList.count() == 1) return columnInfoList.at(0)->width ; return d->sheetFormatProps.defaultColWidth; } /*! Returns formatting of the \a column. Columns are 1-indexed. */ Format Worksheet::columnFormat(int column) { Q_D(Worksheet); QList <QSharedPointer<XlsxColumnInfo> > columnInfoList = d->getColumnInfoList(column, column); if (columnInfoList.count() == 1) return columnInfoList.at(0)->format; return Format(); } /*! Returns true if \a column is hidden. Columns are 1-indexed. */ bool Worksheet::isColumnHidden(int column) { Q_D(Worksheet); QList <QSharedPointer<XlsxColumnInfo> > columnInfoList = d->getColumnInfoList(column, column); if (columnInfoList.count() == 1) return columnInfoList.at(0)->hidden; return false; } /*! Sets the \a height of the rows including and between \a rowFirst and \a rowLast. Row height measured in point size. Rows are 1-indexed. Returns true if success. */ bool Worksheet::setRowHeight(int rowFirst,int rowLast, double height) { Q_D(Worksheet); QList <QSharedPointer<XlsxRowInfo> > rowInfoList = d->getRowInfoList(rowFirst,rowLast); foreach(QSharedPointer<XlsxRowInfo> rowInfo, rowInfoList) { rowInfo->height = height; rowInfo->customHeight = true; } return rowInfoList.count() > 0; } /*! Sets the \a format of the rows including and between \a rowFirst and \a rowLast. Rows are 1-indexed. Returns true if success. */ bool Worksheet::setRowFormat(int rowFirst,int rowLast, const Format &format) { Q_D(Worksheet); QList <QSharedPointer<XlsxRowInfo> > rowInfoList = d->getRowInfoList(rowFirst,rowLast); foreach(QSharedPointer<XlsxRowInfo> rowInfo, rowInfoList) rowInfo->format = format; d->workbook->styles()->addXfFormat(format); return rowInfoList.count() > 0; } /*! Sets the \a hidden proeprty of the rows including and between \a rowFirst and \a rowLast. Rows are 1-indexed. If hidden is true rows will not be visible. Returns true if success. */ bool Worksheet::setRowHidden(int rowFirst,int rowLast, bool hidden) { Q_D(Worksheet); QList <QSharedPointer<XlsxRowInfo> > rowInfoList = d->getRowInfoList(rowFirst,rowLast); foreach(QSharedPointer<XlsxRowInfo> rowInfo, rowInfoList) rowInfo->hidden = hidden; return rowInfoList.count() > 0; } /*! Returns height of \a row in points. */ double Worksheet::rowHeight(int row) { Q_D(Worksheet); int min_col = d->dimension.isValid() ? d->dimension.firstColumn() : 1; if (d->checkDimensions(row, min_col, false, true) || !d->rowsInfo.contains(row)) return d->sheetFormatProps.defaultRowHeight; //return default on invalid row return d->rowsInfo[row]->height; } /*! Returns format of \a row. */ Format Worksheet::rowFormat(int row) { Q_D(Worksheet); int min_col = d->dimension.isValid() ? d->dimension.firstColumn() : 1; if (d->checkDimensions(row, min_col, false, true) || !d->rowsInfo.contains(row)) return Format(); //return default on invalid row return d->rowsInfo[row]->format; } /*! Returns true if \a row is hidden. */ bool Worksheet::isRowHidden(int row) { Q_D(Worksheet); int min_col = d->dimension.isValid() ? d->dimension.firstColumn() : 1; if (d->checkDimensions(row, min_col, false, true) || !d->rowsInfo.contains(row)) return false; //return default on invalid row return d->rowsInfo[row]->hidden; } /*! Groups rows from \a rowFirst to \a rowLast with the given \a collapsed. Returns false if error occurs. */ bool Worksheet::groupRows(int rowFirst, int rowLast, bool collapsed) { Q_D(Worksheet); for (int row=rowFirst; row<=rowLast; ++row) { if (d->rowsInfo.contains(row)) { d->rowsInfo[row]->outlineLevel += 1; } else { QSharedPointer<XlsxRowInfo> info(new XlsxRowInfo); info->outlineLevel += 1; d->rowsInfo.insert(row, info); } if (collapsed) d->rowsInfo[row]->hidden = true; } if (collapsed) { if (!d->rowsInfo.contains(rowLast+1)) d->rowsInfo.insert(rowLast+1, QSharedPointer<XlsxRowInfo>(new XlsxRowInfo)); d->rowsInfo[rowLast+1]->collapsed = true; } return true; } /*! \overload Groups columns with the given \a range and \a collapsed. */ bool Worksheet::groupColumns(const CellRange &range, bool collapsed) { if (!range.isValid()) return false; return groupColumns(range.firstColumn(), range.lastColumn(), collapsed); } /*! Groups columns from \a colFirst to \a colLast with the given \a collapsed. Returns false if error occurs. */ bool Worksheet::groupColumns(int colFirst, int colLast, bool collapsed) { Q_D(Worksheet); d->splitColsInfo(colFirst, colLast); QList<int> nodes; nodes.append(colFirst); for (int col = colFirst; col <= colLast; ++col) { if (d->colsInfo.contains(col)) { if (nodes.last() != col) nodes.append(col); int nextCol = d->colsInfo[col]->lastColumn + 1; if (nextCol <= colLast) nodes.append(nextCol); } } for (int idx = 0; idx < nodes.size(); ++idx) { int colStart = nodes[idx]; if (d->colsInfo.contains(colStart)) { QSharedPointer<XlsxColumnInfo> info = d->colsInfo[colStart]; info->outlineLevel += 1; if (collapsed) info->hidden = true; } else { int colEnd = (idx == nodes.size() - 1) ? colLast : nodes[idx+1] - 1; QSharedPointer<XlsxColumnInfo> info(new XlsxColumnInfo(colStart, colEnd)); info->outlineLevel += 1; d->colsInfo.insert(colFirst, info); if (collapsed) info->hidden = true; for (int c = colStart; c <= colEnd; ++c) d->colsInfoHelper[c] = info; } } if (collapsed) { int col = colLast+1; d->splitColsInfo(col, col); if (d->colsInfo.contains(col)) d->colsInfo[col]->collapsed = true; else { QSharedPointer<XlsxColumnInfo> info(new XlsxColumnInfo(col, col)); info->collapsed = true; d->colsInfo.insert(col, info); d->colsInfoHelper[col] = info; } } return false; } /*! Return the range that contains cell data. */ CellRange Worksheet::dimension() const { Q_D(const Worksheet); return d->dimension; } /* Convert the height of a cell from user's units to pixels. If the height hasn't been set by the user we use the default value. If the row is hidden it has a value of zero. */ int WorksheetPrivate::rowPixelsSize(int row) const { double height; if (row_sizes.contains(row)) height = row_sizes[row]; else height = default_row_height; return static_cast<int>(4.0 / 3.0 *height); } /* Convert the width of a cell from user's units to pixels. Excel rounds the column width to the nearest pixel. If the width hasn't been set by the user we use the default value. If the column is hidden it has a value of zero. */ int WorksheetPrivate::colPixelsSize(int col) const { double max_digit_width = 7.0; //For Calabri 11 double padding = 5.0; int pixels = 0; if (col_sizes.contains(col)) { double width = col_sizes[col]; if (width < 1) pixels = static_cast<int>(width * (max_digit_width + padding) + 0.5); else pixels = static_cast<int>(width * max_digit_width + 0.5) + padding; } else { pixels = 64; } return pixels; } void WorksheetPrivate::loadXmlSheetData(QXmlStreamReader &reader) { Q_Q(Worksheet); Q_ASSERT(reader.name() == QLatin1String("sheetData")); while (!reader.atEnd() && !(reader.name() == QLatin1String("sheetData") && reader.tokenType() == QXmlStreamReader::EndElement)) { if (reader.readNextStartElement()) { if (reader.name() == QLatin1String("row")) { QXmlStreamAttributes attributes = reader.attributes(); if (attributes.hasAttribute(QLatin1String("customFormat")) || attributes.hasAttribute(QLatin1String("customHeight")) || attributes.hasAttribute(QLatin1String("hidden")) || attributes.hasAttribute(QLatin1String("outlineLevel")) || attributes.hasAttribute(QLatin1String("collapsed"))) { QSharedPointer<XlsxRowInfo> info(new XlsxRowInfo); if (attributes.hasAttribute(QLatin1String("customFormat")) && attributes.hasAttribute(QLatin1String("s"))) { int idx = attributes.value(QLatin1String("s")).toString().toInt(); info->format = workbook->styles()->xfFormat(idx); } if (attributes.hasAttribute(QLatin1String("customHeight"))) { info->customHeight = attributes.value(QLatin1String("customHeight")) == QLatin1String("1"); //Row height is only specified when customHeight is set if(attributes.hasAttribute(QLatin1String("ht"))) { info->height = attributes.value(QLatin1String("ht")).toString().toDouble(); } } //both "hidden" and "collapsed" default are false info->hidden = attributes.value(QLatin1String("hidden")) == QLatin1String("1"); info->collapsed = attributes.value(QLatin1String("collapsed")) == QLatin1String("1"); if (attributes.hasAttribute(QLatin1String("outlineLevel"))) info->outlineLevel = attributes.value(QLatin1String("outlineLevel")).toString().toInt(); //"r" is optional too. if (attributes.hasAttribute(QLatin1String("r"))) { int row = attributes.value(QLatin1String("r")).toString().toInt(); rowsInfo[row] = info; } } } else if (reader.name() == QLatin1String("c")) { //Cell QXmlStreamAttributes attributes = reader.attributes(); QString r = attributes.value(QLatin1String("r")).toString(); CellReference pos(r); //get format Format format; if (attributes.hasAttribute(QLatin1String("s"))) { //"s" == style index int idx = attributes.value(QLatin1String("s")).toString().toInt(); format = workbook->styles()->xfFormat(idx); ////Empty format exists in styles xf table of real .xlsx files, see issue #65. //if (!format.isValid()) // qDebug()<<QStringLiteral("<c s=\"%1\">Invalid style index: ").arg(idx)<<idx; } Cell::CellType cellType = Cell::NumberType; if (attributes.hasAttribute(QLatin1String("t"))) { QString typeString = attributes.value(QLatin1String("t")).toString(); if (typeString == QLatin1String("s")) cellType = Cell::SharedStringType; else if (typeString == QLatin1String("inlineStr")) cellType = Cell::InlineStringType; else if (typeString == QLatin1String("str")) cellType = Cell::StringType; else if (typeString == QLatin1String("b")) cellType = Cell::BooleanType; else if (typeString == QLatin1String("e")) cellType = Cell::ErrorType; else cellType = Cell::NumberType; } QSharedPointer<Cell> cell(new Cell(QVariant() ,cellType, format, q)); while (!reader.atEnd() && !(reader.name() == QLatin1String("c") && reader.tokenType() == QXmlStreamReader::EndElement)) { if (reader.readNextStartElement()) { if (reader.name() == QLatin1String("f")) { CellFormula &formula = cell->d_func()->formula; formula.loadFromXml(reader); if (formula.formulaType() == CellFormula::SharedType && !formula.formulaText().isEmpty()) { sharedFormulaMap[formula.sharedIndex()] = formula; } } else if (reader.name() == QLatin1String("v")) { QString value = reader.readElementText(); if (cellType == Cell::SharedStringType) { int sst_idx = value.toInt(); sharedStrings()->incRefByStringIndex(sst_idx); RichString rs = sharedStrings()->getSharedString(sst_idx); cell->d_func()->value = rs.toPlainString(); if (rs.isRichString()) cell->d_func()->richString = rs; } else if (cellType == Cell::NumberType) { if (value.contains(QLatin1Char('.'))) cell->d_func()->value = value.toDouble(); else cell->d_func()->value = value.toInt(); } else if (cellType == Cell::BooleanType) { cell->d_func()->value = value.toInt() ? true : false; } else { //Cell::ErrorType and Cell::StringType cell->d_func()->value = value; } } else if (reader.name() == QLatin1String("is")) { while (!reader.atEnd() && !(reader.name() == QLatin1String("is") && reader.tokenType() == QXmlStreamReader::EndElement)) { if (reader.readNextStartElement()) { //:Todo, add rich text read support if (reader.name() == QLatin1String("t")) { cell->d_func()->value = reader.readElementText(); } } } } else if (reader.name() == QLatin1String("extLst")) { //skip extLst element while (!reader.atEnd() && !(reader.name() == QLatin1String("extLst") && reader.tokenType() == QXmlStreamReader::EndElement)) { reader.readNextStartElement(); } } } } cellTable[pos.row()][pos.column()] = cell; } } } } void WorksheetPrivate::loadXmlColumnsInfo(QXmlStreamReader &reader) { Q_ASSERT(reader.name() == QLatin1String("cols")); while (!reader.atEnd() && !(reader.name() == QLatin1String("cols") && reader.tokenType() == QXmlStreamReader::EndElement)) { reader.readNextStartElement(); if (reader.tokenType() == QXmlStreamReader::StartElement) { if (reader.name() == QLatin1String("col")) { QSharedPointer<XlsxColumnInfo> info(new XlsxColumnInfo); QXmlStreamAttributes colAttrs = reader.attributes(); int min = colAttrs.value(QLatin1String("min")).toString().toInt(); int max = colAttrs.value(QLatin1String("max")).toString().toInt(); info->firstColumn = min; info->lastColumn = max; //Flag indicating that the column width for the affected column(s) is different from the // default or has been manually set if(colAttrs.hasAttribute(QLatin1String("customWidth"))) { info->customWidth = colAttrs.value(QLatin1String("customWidth")) == QLatin1String("1"); } //Note, node may have "width" without "customWidth" if (colAttrs.hasAttribute(QLatin1String("width"))) { double width = colAttrs.value(QLatin1String("width")).toString().toDouble(); info->width = width; } info->hidden = colAttrs.value(QLatin1String("hidden")) == QLatin1String("1"); info->collapsed = colAttrs.value(QLatin1String("collapsed")) == QLatin1String("1"); if (colAttrs.hasAttribute(QLatin1String("style"))) { int idx = colAttrs.value(QLatin1String("style")).toString().toInt(); info->format = workbook->styles()->xfFormat(idx); } if (colAttrs.hasAttribute(QLatin1String("outlineLevel"))) info->outlineLevel = colAttrs.value(QLatin1String("outlineLevel")).toString().toInt(); colsInfo.insert(min, info); for (int col=min; col<=max; ++col) colsInfoHelper[col] = info; } } } } void WorksheetPrivate::loadXmlMergeCells(QXmlStreamReader &reader) { Q_ASSERT(reader.name() == QLatin1String("mergeCells")); QXmlStreamAttributes attributes = reader.attributes(); int count = attributes.value(QLatin1String("count")).toString().toInt(); while (!reader.atEnd() && !(reader.name() == QLatin1String("mergeCells") && reader.tokenType() == QXmlStreamReader::EndElement)) { reader.readNextStartElement(); if (reader.tokenType() == QXmlStreamReader::StartElement) { if (reader.name() == QLatin1String("mergeCell")) { QXmlStreamAttributes attrs = reader.attributes(); QString rangeStr = attrs.value(QLatin1String("ref")).toString(); merges.append(CellRange(rangeStr)); } } } if (merges.size() != count) qDebug("read merge cells error"); } void WorksheetPrivate::loadXmlDataValidations(QXmlStreamReader &reader) { Q_ASSERT(reader.name() == QLatin1String("dataValidations")); QXmlStreamAttributes attributes = reader.attributes(); int count = attributes.value(QLatin1String("count")).toString().toInt(); while (!reader.atEnd() && !(reader.name() == QLatin1String("dataValidations") && reader.tokenType() == QXmlStreamReader::EndElement)) { reader.readNextStartElement(); if (reader.tokenType() == QXmlStreamReader::StartElement && reader.name() == QLatin1String("dataValidation")) { dataValidationsList.append(DataValidation::loadFromXml(reader)); } } if (dataValidationsList.size() != count) qDebug("read data validation error"); } void WorksheetPrivate::loadXmlSheetViews(QXmlStreamReader &reader) { Q_ASSERT(reader.name() == QLatin1String("sheetViews")); while (!reader.atEnd() && !(reader.name() == QLatin1String("sheetViews") && reader.tokenType() == QXmlStreamReader::EndElement)) { reader.readNextStartElement(); if (reader.tokenType() == QXmlStreamReader::StartElement && reader.name() == QLatin1String("sheetView")) { QXmlStreamAttributes attrs = reader.attributes(); //default false windowProtection = attrs.value(QLatin1String("windowProtection")) == QLatin1String("1"); showFormulas = attrs.value(QLatin1String("showFormulas")) == QLatin1String("1"); rightToLeft = attrs.value(QLatin1String("rightToLeft")) == QLatin1String("1"); tabSelected = attrs.value(QLatin1String("tabSelected")) == QLatin1String("1"); //default true showGridLines = attrs.value(QLatin1String("showGridLines")) != QLatin1String("0"); showRowColHeaders = attrs.value(QLatin1String("showRowColHeaders")) != QLatin1String("0"); showZeros = attrs.value(QLatin1String("showZeros")) != QLatin1String("0"); showRuler = attrs.value(QLatin1String("showRuler")) != QLatin1String("0"); showOutlineSymbols = attrs.value(QLatin1String("showOutlineSymbols")) != QLatin1String("0"); showWhiteSpace = attrs.value(QLatin1String("showWhiteSpace")) != QLatin1String("0"); } } } void WorksheetPrivate::loadXmlSheetFormatProps(QXmlStreamReader &reader) { Q_ASSERT(reader.name() == QLatin1String("sheetFormatPr")); QXmlStreamAttributes attributes = reader.attributes(); XlsxSheetFormatProps formatProps; //Retain default values foreach (QXmlStreamAttribute attrib, attributes) { if(attrib.name() == QLatin1String("baseColWidth") ) { formatProps.baseColWidth = attrib.value().toString().toInt(); } else if(attrib.name() == QLatin1String("customHeight")) { formatProps.customHeight = attrib.value() == QLatin1String("1"); } else if(attrib.name() == QLatin1String("defaultColWidth")) { formatProps.defaultColWidth = attrib.value().toString().toDouble(); } else if(attrib.name() == QLatin1String("defaultRowHeight")) { formatProps.defaultRowHeight = attrib.value().toString().toDouble(); } else if(attrib.name() == QLatin1String("outlineLevelCol")) { formatProps.outlineLevelCol = attrib.value().toString().toInt(); } else if(attrib.name() == QLatin1String("outlineLevelRow")) { formatProps.outlineLevelRow = attrib.value().toString().toInt(); } else if(attrib.name() == QLatin1String("thickBottom")) { formatProps.thickBottom = attrib.value() == QLatin1String("1"); } else if(attrib.name() == QLatin1String("thickTop")) { formatProps.thickTop = attrib.value() == QLatin1String("1"); } else if(attrib.name() == QLatin1String("zeroHeight")) { formatProps.zeroHeight = attrib.value() == QLatin1String("1"); } } if(formatProps.defaultColWidth == 0.0) { //not set formatProps.defaultColWidth = WorksheetPrivate::calculateColWidth(formatProps.baseColWidth); } } double WorksheetPrivate::calculateColWidth(int characters) { //!Todo //Take normal style' font maximum width and add padding and margin pixels return characters + 0.5; } void WorksheetPrivate::loadXmlHyperlinks(QXmlStreamReader &reader) { Q_ASSERT(reader.name() == QLatin1String("hyperlinks")); while (!reader.atEnd() && !(reader.name() == QLatin1String("hyperlinks") && reader.tokenType() == QXmlStreamReader::EndElement)) { reader.readNextStartElement(); if (reader.tokenType() == QXmlStreamReader::StartElement && reader.name() == QLatin1String("hyperlink")) { QXmlStreamAttributes attrs = reader.attributes(); CellReference pos(attrs.value(QLatin1String("ref")).toString()); if (pos.isValid()) { //Valid QSharedPointer<XlsxHyperlinkData> link(new XlsxHyperlinkData); link->display = attrs.value(QLatin1String("display")).toString(); link->tooltip = attrs.value(QLatin1String("tooltip")).toString(); link->location = attrs.value(QLatin1String("location")).toString(); if (attrs.hasAttribute(QLatin1String("r:id"))) { link->linkType = XlsxHyperlinkData::External; XlsxRelationship ship = relationships->getRelationshipById(attrs.value(QLatin1String("r:id")).toString()); link->target = ship.target; } else { link->linkType = XlsxHyperlinkData::Internal; } urlTable[pos.row()][pos.column()] = link; } } } } QList <QSharedPointer<XlsxColumnInfo> > WorksheetPrivate::getColumnInfoList(int colFirst, int colLast) { QList <QSharedPointer<XlsxColumnInfo> > columnsInfoList; if(isColumnRangeValid(colFirst,colLast)) { QList<int> nodes = getColumnIndexes(colFirst, colLast); for (int idx = 0; idx < nodes.size(); ++idx) { int colStart = nodes[idx]; if (colsInfo.contains(colStart)) { QSharedPointer<XlsxColumnInfo> info = colsInfo[colStart]; columnsInfoList.append(info); } else { int colEnd = (idx == nodes.size() - 1) ? colLast : nodes[idx+1] - 1; QSharedPointer<XlsxColumnInfo> info(new XlsxColumnInfo(colStart, colEnd)); colsInfo.insert(colFirst, info); columnsInfoList.append(info); for (int c = colStart; c <= colEnd; ++c) colsInfoHelper[c] = info; } } } return columnsInfoList; } QList <QSharedPointer<XlsxRowInfo> > WorksheetPrivate::getRowInfoList(int rowFirst, int rowLast) { QList <QSharedPointer<XlsxRowInfo> > rowInfoList; int min_col = dimension.firstColumn() < 1 ? 1 : dimension.firstColumn(); for(int row = rowFirst; row <= rowLast; ++row) { if (checkDimensions(row, min_col, false, true)) continue; QSharedPointer<XlsxRowInfo> rowInfo; if ((rowsInfo[row]).isNull()){ rowsInfo[row] = QSharedPointer<XlsxRowInfo>(new XlsxRowInfo()); } rowInfoList.append(rowsInfo[row]); } return rowInfoList; } bool Worksheet::loadFromXmlFile(QIODevice *device) { Q_D(Worksheet); QXmlStreamReader reader(device); while (!reader.atEnd()) { reader.readNextStartElement(); if (reader.tokenType() == QXmlStreamReader::StartElement) { if (reader.name() == QLatin1String("dimension")) { QXmlStreamAttributes attributes = reader.attributes(); QString range = attributes.value(QLatin1String("ref")).toString(); d->dimension = CellRange(range); } else if (reader.name() == QLatin1String("pageMargins")){ QXmlStreamAttributes attributes = reader.attributes(); setTopPageMargin(attributes.value(QLatin1String("top")).toDouble()); setLeftPageMargin(attributes.value(QLatin1String("left")).toDouble()); setRightPageMargin(attributes.value(QLatin1String("right")).toDouble()); setBottomPageMargin(attributes.value(QLatin1String("bottom")).toDouble()); } else if (reader.name() == QLatin1String("sheetViews")) { d->loadXmlSheetViews(reader); } else if (reader.name() == QLatin1String("sheetFormatPr")) { d->loadXmlSheetFormatProps(reader); } else if (reader.name() == QLatin1String("cols")) { d->loadXmlColumnsInfo(reader); } else if (reader.name() == QLatin1String("sheetData")) { d->loadXmlSheetData(reader); } else if (reader.name() == QLatin1String("mergeCells")) { d->loadXmlMergeCells(reader); } else if (reader.name() == QLatin1String("dataValidations")) { d->loadXmlDataValidations(reader); } else if (reader.name() == QLatin1String("conditionalFormatting")) { ConditionalFormatting cf; cf.loadFromXml(reader, workbook()->styles()); d->conditionalFormattingList.append(cf); } else if (reader.name() == QLatin1String("hyperlinks")) { d->loadXmlHyperlinks(reader); } else if (reader.name() == QLatin1String("drawing")) { QString rId = reader.attributes().value(QStringLiteral("r:id")).toString(); QString name = d->relationships->getRelationshipById(rId).target; QString path = QDir::cleanPath(splitPath(filePath())[0] + QLatin1String("/") + name); d->drawing = QSharedPointer<Drawing>(new Drawing(this, F_LoadFromExists)); d->drawing->setFilePath(path); } else if (reader.name() == QLatin1String("extLst")) { //Todo: add extLst support while (!reader.atEnd() && !(reader.name() == QLatin1String("extLst") && reader.tokenType() == QXmlStreamReader::EndElement)) { reader.readNextStartElement(); } } } } d->validateDimension(); return true; } /* * Documents imported from Google Docs does not contain dimension data. */ void WorksheetPrivate::validateDimension() { if (dimension.isValid() || cellTable.isEmpty()) return; int firstRow = cellTable.constBegin().key(); int lastRow = (cellTable.constEnd()-1).key(); int firstColumn = -1; int lastColumn = -1; for (QMap<int, QMap<int, QSharedPointer<Cell> > >::const_iterator it = cellTable.begin(); it != cellTable.end(); ++it) { Q_ASSERT(!it.value().isEmpty()); if (firstColumn == -1 || it.value().constBegin().key() < firstColumn) firstColumn = it.value().constBegin().key(); if (lastColumn == -1 || (it.value().constEnd()-1).key() > lastColumn) lastColumn = (it.value().constEnd()-1).key(); } CellRange cr(firstRow, firstColumn, lastRow, lastColumn); if (cr.isValid()) dimension = cr; } /*! * \internal * Unit test can use this member to get sharedString object. */ SharedStrings *WorksheetPrivate::sharedStrings() const { return workbook->sharedStrings(); } QT_END_NAMESPACE_XLSX
[ "rbradt1@saddleback.edu" ]
rbradt1@saddleback.edu
7733f450c4f9ec42e2e3f859b5ea52536e96e325
fac52aacf1a7145d46f420bb2991528676e3be3f
/SDK/Hiking_Boots_04_classes.h
1f573bf20af9af20020da39f49123cc3b0bf1ab4
[]
no_license
zH4x-SDK/zSCUM-SDK
2342afd6ee54f4f0b14b0a0e9e3920d75bdb4fed
711376eb272b220521fec36d84ca78fc11d4802a
refs/heads/main
2023-07-15T16:02:22.649492
2021-08-27T13:44:21
2021-08-27T13:44:21
400,522,163
2
0
null
null
null
null
UTF-8
C++
false
false
628
h
#pragma once // Name: SCUM, Version: 4.20.3 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Hiking_Boots_04.Hiking_Boots_04_C // 0x0000 (0x0928 - 0x0928) class AHiking_Boots_04_C : public AClothesItem { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Hiking_Boots_04.Hiking_Boots_04_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
cf7b7b8e9257c7eada43685ce053e6a5e72cc002
f8b1dfccaef5a8f75567b527fc7c2f0a34e3877b
/hiho/hiho21.cpp
43cccce2e1bf150558f8fa23825e1ce7ba4541c9
[]
no_license
bamboohiko/problemSolve
e7e2a2c6e46a4d10ccfa54cffff3c9895b3ddb1b
cd3e9e5986325f5def4efe01975a950f6eaa6015
refs/heads/master
2021-01-17T06:39:42.502176
2017-09-13T14:30:08
2017-09-13T14:30:08
47,928,189
0
0
null
null
null
null
UTF-8
C++
false
false
1,488
cpp
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<algorithm> #include<cmath> using namespace std; struct line{ int x,y; }; map<int,int> f; set<int> ans; vector<int> sav; int tree[800100]; line a[100100]; void add(int x) { if (!f.count(x)) { f[x] = 0; f[x] = f.size(); } } void updata(int l,int r,int p,int x,int y,int num) { if (x <= l && r <= y) { tree[p] = num; return; } int mid = (l + r) >> 1; if (tree[p]) tree[p*2] = tree[p*2+1] = tree[p]; if (x <= mid) updata(l,mid,p*2,x,y,num); if (y > mid) updata(mid+1,r,p*2+1,x,y,num); if (tree[p*2] == tree[p*2+1]) tree[p] = tree[p*2]; else tree[p] = 0; } void cou(int l,int r,int p) { //printf("%d %d %d\n",l,r,tree[p]); if (tree[p]) { if (!ans.count(tree[p])) ans.insert(tree[p]); return; } int mid = (l + r) >> 1; cou(l,mid,p*2); cou(mid+1,r,p*2+1); } int main() { int n,m,l; scanf("%d%d",&n,&l); for (int i = 0;i < n; i++) { scanf("%d%d",&a[i].x,&a[i].y); sav.push_back(a[i].x); sav.push_back(a[i].y); } sort(sav.begin(),sav.end()); for (vector<int>::iterator i = sav.begin();i != sav.end(); ++i) add(*i); m = f.size(); for (int i = 0;i < n; i++) { updata(1,m,1,f[a[i].x],f[a[i].y],i+1); //cout << f[a[i].x] << " " << f[a[i].y] << endl; } cou(1,m,1); printf("%d\n",ans.size()); return 0; }
[ "bamboohiko@163.com" ]
bamboohiko@163.com
bfcc052fa2db2b3babc89f19c936541c31ba73f4
18d5e9b3aa66a788387d65460bf66977fb340b5d
/Template Codes/ClosestPairPoints.cpp
5dd1dc22f5c6e9ad36bf11e281c0109dac9c65f2
[ "MIT" ]
permissive
SajibTalukder2k16/competitive-programming
430e7a8845ae0c5ae61bf965c114d9674ecf9484
9932371c937be34d29d495e9a39ecdcad5c1b448
refs/heads/master
2020-09-27T21:29:04.953313
2019-11-25T22:24:26
2019-11-25T22:24:26
226,613,903
1
0
MIT
2019-12-08T04:25:41
2019-12-08T04:25:40
null
UTF-8
C++
false
false
1,358
cpp
#include <bits/stdc++.h> #define SQR(a) ((a)*(a)) using namespace std; #define LL long long const LL inf = (LL)1e18; struct point { LL x, y; int id; point() {} point (LL a, LL b) : x(a), y(b) {} }; LL dist(point p1,point p2) { return (SQR(p1.x - p2.x) + SQR(p1.y - p2.y)); } vector<point>vp; LL closest(int L, int R ) { if( L == R ) return inf; if( L + 1 == R ) return dist( vp[L], vp[R] ); int mid = ( L + R ) / 2; LL d = min( closest( L, mid ), closest( mid + 1, R ) ); vector < int > br; for( int i=L; i<=R; i++ ) { if( SQR( vp[mid].x - vp[i].x ) <= d ) br.push_back( i ); } sort( br.begin(), br.end(), []( const int& a, const int& b ) -> bool { return vp[a].y < vp[b].y; } ); for( int i=0; i<(int)(br.size()); i++ ) { for( int j=i+1; j<(int)(br.size()) && j - i <= 7; j++ ) { d = min( d, dist( vp[br[i]], vp[br[j]] ) ); } } return d; } const LL N = 100005; LL n,ara[N],cum[N]; int main() { cin >> n; for(LL i = 0;i < n;i++)cin >> ara[i]; LL s = 0; for(LL i = 0;i < n;i++)s = s + ara[i],cum[i] = s; for(LL i = 0;i < n;i++)vp.push_back({i,cum[i]}); LL ans = closest(0,n - 1); cout << ans << "\n"; }
[ "noreply@github.com" ]
noreply@github.com
4530b636354bddf972549e6d8883e59d38f76834
6dcda60c0c9e0913106453f13c565dcccaecf3bf
/Assignment03/BadWizard.h
c53fff9475f278e516a3d9413c70558ec7f6236f
[]
no_license
mattskel/TxtQuestFIT2071
307bbf13b577d33f061bcf5a26993f5e1e07dda6
256d1e91670f055c42210b89db66ad9a66a6a6db
refs/heads/master
2016-09-12T23:14:56.980225
2016-05-26T13:16:40
2016-05-26T13:16:40
59,096,431
0
0
null
null
null
null
UTF-8
C++
false
false
247
h
#ifndef BADWIZARD_H #define BADWIZARD_H #include "Enemy.h" #include <string> #include <vector> class BadWizard : public Enemy { public: BadWizard(int roundMod); ~BadWizard(); virtual void Attack(vector<Character*> attackVector); }; #endif
[ "matthewskelley@dyn-118-139-84-121.its.monash.edu.au" ]
matthewskelley@dyn-118-139-84-121.its.monash.edu.au
f3a22f83adc4034dd5bb50e239a7fb82f291ec44
666e30325c97d4297e5d6a707399cdee4f8b1fd5
/src/crypter.cpp
abfbf56766770e5a57224f295b196de61c1a09ae
[ "MIT" ]
permissive
saikocoin/saikocoin
109d7e7fa0c7942471cfb196f20de0dd77a0c0ce
c0bde8b9382de1a0b5f068b7c12dc5df0d07fa5d
refs/heads/master
2023-04-20T21:35:44.556805
2021-05-07T01:35:14
2021-05-07T01:35:14
365,081,676
0
0
null
null
null
null
UTF-8
C++
false
false
14,971
cpp
// Copyright (c) 2009-2013 The Bitcoin developers // Copyright (c) 2017-2019 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "crypter.h" #include "script/script.h" #include "script/standard.h" #include "util.h" #include "init.h" #include "uint256.h" #include <openssl/aes.h> #include <openssl/evp.h> #include "wallet/wallet.h" bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod) { if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE) return false; int i = 0; if (nDerivationMethod == 0) i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0], (unsigned char*)&strKeyData[0], strKeyData.size(), nRounds, chKey, chIV); if (i != (int)WALLET_CRYPTO_KEY_SIZE) { memory_cleanse(chKey, sizeof(chKey)); memory_cleanse(chIV, sizeof(chIV)); return false; } fKeySet = true; return true; } bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV) { if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_KEY_SIZE) return false; memcpy(&chKey[0], &chNewKey[0], sizeof chKey); memcpy(&chIV[0], &chNewIV[0], sizeof chIV); fKeySet = true; return true; } bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char>& vchCiphertext) { if (!fKeySet) return false; // max ciphertext len for a n bytes of plaintext is // n + AES_BLOCK_SIZE - 1 bytes int nLen = vchPlaintext.size(); int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0; vchCiphertext = std::vector<unsigned char>(nCLen); bool fOk = true; EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); if (fOk) fOk = EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, chKey, chIV) != 0; if (fOk) fOk = EVP_EncryptUpdate(ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen) != 0; if (fOk) fOk = EVP_EncryptFinal_ex(ctx, (&vchCiphertext[0]) + nCLen, &nFLen) != 0; EVP_CIPHER_CTX_free(ctx); if (!fOk) return false; vchCiphertext.resize(nCLen + nFLen); return true; } bool CCrypter::Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext) { if (!fKeySet) return false; // plaintext will always be equal to or lesser than length of ciphertext int nLen = vchCiphertext.size(); int nPLen = nLen, nFLen = 0; vchPlaintext = CKeyingMaterial(nPLen); bool fOk = true; EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); if (fOk) fOk = EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, chKey, chIV) != 0; if (fOk) fOk = EVP_DecryptUpdate(ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen) != 0; if (fOk) fOk = EVP_DecryptFinal_ex(ctx, (&vchPlaintext[0]) + nPLen, &nFLen) != 0; EVP_CIPHER_CTX_free(ctx); if (!fOk) return false; vchPlaintext.resize(nPLen + nFLen); return true; } bool EncryptSecret(const CKeyingMaterial& vMasterKey, const CKeyingMaterial& vchPlaintext, const uint256& nIV, std::vector<unsigned char>& vchCiphertext) { CCrypter cKeyCrypter; std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE); memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE); if (!cKeyCrypter.SetKey(vMasterKey, chIV)) return false; return cKeyCrypter.Encrypt(*((const CKeyingMaterial*)&vchPlaintext), vchCiphertext); } // General secure AES 256 CBC encryption routine bool EncryptAES256(const SecureString& sKey, const SecureString& sPlaintext, const std::string& sIV, std::string& sCiphertext) { // max ciphertext len for a n bytes of plaintext is // n + AES_BLOCK_SIZE - 1 bytes int nLen = sPlaintext.size(); int nCLen = nLen + AES_BLOCK_SIZE; int nFLen = 0; // Verify key sizes if (sKey.size() != 32 || sIV.size() != AES_BLOCK_SIZE) { LogPrintf("crypter EncryptAES256 - Invalid key or block size: Key: %d sIV:%d\n", sKey.size(), sIV.size()); return false; } // Prepare output buffer sCiphertext.resize(nCLen); // Perform the encryption EVP_CIPHER_CTX* ctx; bool fOk = true; ctx = EVP_CIPHER_CTX_new(); if (fOk) fOk = EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (const unsigned char*)&sKey[0], (const unsigned char*)&sIV[0]); if (fOk) fOk = EVP_EncryptUpdate(ctx, (unsigned char*)&sCiphertext[0], &nCLen, (const unsigned char*)&sPlaintext[0], nLen); if (fOk) fOk = EVP_EncryptFinal_ex(ctx, (unsigned char*)(&sCiphertext[0]) + nCLen, &nFLen); EVP_CIPHER_CTX_free(ctx); if (!fOk) return false; sCiphertext.resize(nCLen + nFLen); return true; } bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const uint256& nIV, CKeyingMaterial& vchPlaintext) { CCrypter cKeyCrypter; std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE); memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE); if (!cKeyCrypter.SetKey(vMasterKey, chIV)) return false; return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext)); } bool DecryptAES256(const SecureString& sKey, const std::string& sCiphertext, const std::string& sIV, SecureString& sPlaintext) { // plaintext will always be equal to or lesser than length of ciphertext int nLen = sCiphertext.size(); int nPLen = nLen, nFLen = 0; // Verify key sizes if (sKey.size() != 32 || sIV.size() != AES_BLOCK_SIZE) { LogPrintf("crypter DecryptAES256 - Invalid key or block size\n"); return false; } sPlaintext.resize(nPLen); EVP_CIPHER_CTX* ctx; bool fOk = true; ctx = EVP_CIPHER_CTX_new(); if (fOk) fOk = EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (const unsigned char*)&sKey[0], (const unsigned char*)&sIV[0]); if (fOk) fOk = EVP_DecryptUpdate(ctx, (unsigned char*)&sPlaintext[0], &nPLen, (const unsigned char*)&sCiphertext[0], nLen); if (fOk) fOk = EVP_DecryptFinal_ex(ctx, (unsigned char*)(&sPlaintext[0]) + nPLen, &nFLen); EVP_CIPHER_CTX_free(ctx); if (!fOk) return false; sPlaintext.resize(nPLen + nFLen); return true; } bool CCryptoKeyStore::SetCrypted() { LOCK(cs_KeyStore); if (fUseCrypto) return true; if (!mapKeys.empty()) return false; fUseCrypto = true; return true; } bool CCryptoKeyStore::Lock() { if (!SetCrypted()) return false; { LOCK(cs_KeyStore); vMasterKey.clear(); pwalletMain->zwalletMain->Lock(); } NotifyStatusChanged(this); return true; } bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn) { { LOCK(cs_KeyStore); if (!SetCrypted()) return false; bool keyPass = false; bool keyFail = false; CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin(); for (; mi != mapCryptedKeys.end(); ++mi) { const CPubKey& vchPubKey = (*mi).second.first; const std::vector<unsigned char>& vchCryptedSecret = (*mi).second.second; CKeyingMaterial vchSecret; if (!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret)) { keyFail = true; break; } if (vchSecret.size() != 32) { keyFail = true; break; } CKey key; key.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed()); if (key.GetPubKey() != vchPubKey) { keyFail = true; break; } keyPass = true; if (fDecryptionThoroughlyChecked) break; } if (keyPass && keyFail) { LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all."); assert(false); } if (keyFail || !keyPass) return false; vMasterKey = vMasterKeyIn; fDecryptionThoroughlyChecked = true; uint256 hashSeed; if (CWalletDB(pwalletMain->strWalletFile).ReadCurrentSeedHash(hashSeed)) { uint256 nSeed; if (!GetDeterministicSeed(hashSeed, nSeed)) { return error("Failed to read zSIO seed from DB. Wallet is probably corrupt."); } pwalletMain->zwalletMain->SetMasterSeed(nSeed, false); } else { // First time this wallet has been unlocked with dzSIO // Borrow random generator from the key class so that we don't have to worry about randomness CKey key; key.MakeNewKey(true); uint256 seed = key.GetPrivKey_256(); LogPrintf("%s: first run of zsio wallet detected, new seed generated. Seedhash=%s\n", __func__, Hash(seed.begin(), seed.end()).GetHex()); pwalletMain->zwalletMain->SetMasterSeed(seed, true); pwalletMain->zwalletMain->GenerateMintPool(); } } NotifyStatusChanged(this); return true; } bool CCryptoKeyStore::AddKeyPubKey(const CKey& key, const CPubKey& pubkey) { { LOCK(cs_KeyStore); if (!IsCrypted()) return CBasicKeyStore::AddKeyPubKey(key, pubkey); if (IsLocked()) return false; std::vector<unsigned char> vchCryptedSecret; CKeyingMaterial vchSecret(key.begin(), key.end()); if (!EncryptSecret(vMasterKey, vchSecret, pubkey.GetHash(), vchCryptedSecret)) return false; if (!AddCryptedKey(pubkey, vchCryptedSecret)) return false; } return true; } bool CCryptoKeyStore::AddCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret) { { LOCK(cs_KeyStore); if (!SetCrypted()) return false; mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret); } return true; } bool CCryptoKeyStore::GetKey(const CKeyID& address, CKey& keyOut) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return CBasicKeyStore::GetKey(address, keyOut); CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address); if (mi != mapCryptedKeys.end()) { const CPubKey& vchPubKey = (*mi).second.first; const std::vector<unsigned char>& vchCryptedSecret = (*mi).second.second; CKeyingMaterial vchSecret; if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret)) return false; if (vchSecret.size() != 32) return false; keyOut.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed()); return true; } } return false; } bool CCryptoKeyStore::GetPubKey(const CKeyID& address, CPubKey& vchPubKeyOut) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return CKeyStore::GetPubKey(address, vchPubKeyOut); CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address); if (mi != mapCryptedKeys.end()) { vchPubKeyOut = (*mi).second.first; return true; } } return false; } bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn) { { LOCK(cs_KeyStore); if (!mapCryptedKeys.empty() || IsCrypted()) return false; fUseCrypto = true; for (KeyMap::value_type& mKey : mapKeys) { const CKey& key = mKey.second; CPubKey vchPubKey = key.GetPubKey(); CKeyingMaterial vchSecret(key.begin(), key.end()); std::vector<unsigned char> vchCryptedSecret; if (!EncryptSecret(vMasterKeyIn, vchSecret, vchPubKey.GetHash(), vchCryptedSecret)) return false; if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; } mapKeys.clear(); } return true; } bool CCryptoKeyStore::AddDeterministicSeed(const uint256& seed) { CWalletDB db(pwalletMain->strWalletFile); string strErr; uint256 hashSeed = Hash(seed.begin(), seed.end()); if(IsCrypted()) { if (!IsLocked()) { //if we have password CKeyingMaterial kmSeed(seed.begin(), seed.end()); vector<unsigned char> vchSeedSecret; //attempt encrypt if (EncryptSecret(vMasterKey, kmSeed, hashSeed, vchSeedSecret)) { //write to wallet with hashSeed as unique key if (db.WriteZSIOSeed(hashSeed, vchSeedSecret)) { return true; } } strErr = "encrypt seed"; } strErr = "save since wallet is locked"; } else { //wallet not encrypted if (db.WriteZSIOSeed(hashSeed, ToByteVector(seed))) { return true; } strErr = "save zsioseed to wallet"; } //the use case for this is no password set seed, mint dzSIO, return error("s%: Failed to %s\n", __func__, strErr); } bool CCryptoKeyStore::GetDeterministicSeed(const uint256& hashSeed, uint256& seedOut) { CWalletDB db(pwalletMain->strWalletFile); string strErr; if (IsCrypted()) { if(!IsLocked()) { //if we have password vector<unsigned char> vchCryptedSeed; //read encrypted seed if (db.ReadZSIOSeed(hashSeed, vchCryptedSeed)) { uint256 seedRetrieved = uint256(ReverseEndianString(HexStr(vchCryptedSeed))); //this checks if the hash of the seed we just read matches the hash given, meaning it is not encrypted //the use case for this is when not crypted, seed is set, then password set, the seed not yet crypted in memory if(hashSeed == Hash(seedRetrieved.begin(), seedRetrieved.end())) { seedOut = seedRetrieved; return true; } CKeyingMaterial kmSeed; //attempt decrypt if (DecryptSecret(vMasterKey, vchCryptedSeed, hashSeed, kmSeed)) { seedOut = uint256(ReverseEndianString(HexStr(kmSeed))); return true; } strErr = "decrypt seed"; } else { strErr = "read seed from wallet"; } } else { strErr = "read seed; wallet is locked"; } } else { vector<unsigned char> vchSeed; // wallet not crypted if (db.ReadZSIOSeed(hashSeed, vchSeed)) { seedOut = uint256(ReverseEndianString(HexStr(vchSeed))); return true; } strErr = "read seed from wallet"; } return error("%s: Failed to %s\n", __func__, strErr); // return error("Failed to decrypt deterministic seed %s", IsLocked() ? "Wallet is locked!" : ""); }
[ "root@vmi571901.contaboserver.net" ]
root@vmi571901.contaboserver.net
9cb6c3bda93d26c8031a9f05d639bc735d6d26f8
61aa319732d3fa7912e28f5ff7768498f8dda005
/src/arch/arm/insts/pred_inst.cc
517d511c3ea2f153a51b67afb66fc7228d83c54f
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license", "LGPL-2.0-or-later", "MIT" ]
permissive
TeCSAR-UNCC/gem5-SALAM
37f2f7198c93b4c18452550df48c1a2ab14b14fb
c14c39235f4e376e64dc68b81bd2447e8a47ff65
refs/heads/main
2023-06-08T22:16:25.260792
2023-05-31T16:43:46
2023-05-31T16:43:46
154,335,724
62
22
BSD-3-Clause
2023-05-31T16:43:48
2018-10-23T13:45:44
C++
UTF-8
C++
false
false
4,500
cc
/* * Copyright (c) 2010 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2007-2008 The Florida State University * 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 copyright holders 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. */ #include "arch/arm/insts/pred_inst.hh" namespace gem5 { namespace ArmISA { std::string PredIntOp::generateDisassembly( Addr pc, const loader::SymbolTable *symtab) const { std::stringstream ss; unsigned rotate = machInst.rotate * 2; uint32_t imm = machInst.imm; imm = (imm << (32 - rotate)) | (imm >> rotate); printDataInst(ss, false, machInst.opcode4 == 0, machInst.sField, (IntRegIndex)(uint32_t)machInst.rd, (IntRegIndex)(uint32_t)machInst.rn, (IntRegIndex)(uint32_t)machInst.rm, (IntRegIndex)(uint32_t)machInst.rs, machInst.shiftSize, (ArmShiftType)(uint32_t)machInst.shift, imm); return ss.str(); } std::string PredImmOp::generateDisassembly( Addr pc, const loader::SymbolTable *symtab) const { std::stringstream ss; printDataInst(ss, true, machInst.opcode4 == 0, machInst.sField, (IntRegIndex)(uint32_t)machInst.rd, (IntRegIndex)(uint32_t)machInst.rn, (IntRegIndex)(uint32_t)machInst.rm, (IntRegIndex)(uint32_t)machInst.rs, machInst.shiftSize, (ArmShiftType)(uint32_t)machInst.shift, imm); return ss.str(); } std::string DataImmOp::generateDisassembly( Addr pc, const loader::SymbolTable *symtab) const { std::stringstream ss; printDataInst(ss, true, false, /*XXX not really s*/ false, dest, op1, INTREG_ZERO, INTREG_ZERO, 0, LSL, imm); return ss.str(); } std::string DataRegOp::generateDisassembly( Addr pc, const loader::SymbolTable *symtab) const { std::stringstream ss; printDataInst(ss, false, true, /*XXX not really s*/ false, dest, op1, op2, INTREG_ZERO, shiftAmt, shiftType, 0); return ss.str(); } std::string DataRegRegOp::generateDisassembly( Addr pc, const loader::SymbolTable *symtab) const { std::stringstream ss; printDataInst(ss, false, false, /*XXX not really s*/ false, dest, op1, op2, shift, 0, shiftType, 0); return ss.str(); } std::string PredMacroOp::generateDisassembly( Addr pc, const loader::SymbolTable *symtab) const { std::stringstream ss; ccprintf(ss, "%-10s ", mnemonic); return ss.str(); } } // namespace ArmISA } // namespace gem5
[ "sroger48@uncc.edu" ]
sroger48@uncc.edu
e2d237c5e8b6b0c2f63a154d18275c6a4f15c7d3
2cb5646fdded8ea162fce7c171eb891d9a9495ac
/exportNF/release/windows/obj/include/flixel/input/actions/FlxActionInputDigital.h
83ad32b72819307a8e1ec9fced0b443075aa5b43
[ "BSD-3-Clause" ]
permissive
roythearsonist/NekoFreakMod-FridayNightFunkin
89b815177c82ef21e09d81268fb8aeff0e8baf01
232bcb08234cfe881fd6d52b13e6ae443e105fd1
refs/heads/main
2023-04-23T08:22:18.886103
2021-05-17T07:13:05
2021-05-17T07:13:05
null
0
0
null
null
null
null
UTF-8
C++
false
true
2,199
h
// Generated by Haxe 4.2.1+bf9ff69 #ifndef INCLUDED_flixel_input_actions_FlxActionInputDigital #define INCLUDED_flixel_input_actions_FlxActionInputDigital #ifndef HXCPP_H #include <hxcpp.h> #endif #ifndef INCLUDED_flixel_input_actions_FlxActionInput #include <flixel/input/actions/FlxActionInput.h> #endif HX_DECLARE_CLASS3(flixel,input,actions,FlxActionInput) HX_DECLARE_CLASS3(flixel,input,actions,FlxActionInputDigital) HX_DECLARE_CLASS3(flixel,input,actions,FlxInputDevice) HX_DECLARE_CLASS2(flixel,util,IFlxDestroyable) namespace flixel{ namespace input{ namespace actions{ class HXCPP_CLASS_ATTRIBUTES FlxActionInputDigital_obj : public ::flixel::input::actions::FlxActionInput_obj { public: typedef ::flixel::input::actions::FlxActionInput_obj super; typedef FlxActionInputDigital_obj OBJ_; FlxActionInputDigital_obj(); public: enum { _hx_ClassId = 0x1600da07 }; void __construct( ::flixel::input::actions::FlxInputDevice Device,int InputID,int Trigger,::hx::Null< int > __o_DeviceID); inline void *operator new(size_t inSize, bool inContainer=true,const char *inName="flixel.input.actions.FlxActionInputDigital") { return ::hx::Object::operator new(inSize,inContainer,inName); } inline void *operator new(size_t inSize, int extra) { return ::hx::Object::operator new(inSize+extra,true,"flixel.input.actions.FlxActionInputDigital"); } static ::hx::ObjectPtr< FlxActionInputDigital_obj > __new( ::flixel::input::actions::FlxInputDevice Device,int InputID,int Trigger,::hx::Null< int > __o_DeviceID); static ::hx::ObjectPtr< FlxActionInputDigital_obj > __alloc(::hx::Ctx *_hx_ctx, ::flixel::input::actions::FlxInputDevice Device,int InputID,int Trigger,::hx::Null< int > __o_DeviceID); static void * _hx_vtable; static Dynamic __CreateEmpty(); static Dynamic __Create(::hx::DynamicArray inArgs); //~FlxActionInputDigital_obj(); HX_DO_RTTI_ALL; static void __register(); bool _hx_isInstanceOf(int inClassId); ::String __ToString() const { return HX_("FlxActionInputDigital",b6,7e,22,62); } }; } // end namespace flixel } // end namespace input } // end namespace actions #endif /* INCLUDED_flixel_input_actions_FlxActionInputDigital */
[ "mrzushiofficial@gmail.com" ]
mrzushiofficial@gmail.com
8688c911c6a57a3b0dc431f2a7426f0dc2714fea
fff9c2e019113a9fb146d3d7c169846e320733db
/OM/Release/uic/ui_nipao.h
d2e41196c8fe4c12964c5d9d9fd24111b7fb87a7
[]
no_license
lllliiiiran/OM
c186f345ff9f78cca55a9ac7a467deef9183464c
379f1d50d26c0a1c58d6c4dc695d5745164fadea
refs/heads/master
2022-11-10T19:55:22.956160
2020-07-08T03:54:00
2020-07-08T03:54:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,530
h
/******************************************************************************** ** Form generated from reading UI file 'nipao.ui' ** ** Created by: Qt User Interface Compiler version 5.15.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_NIPAO_H #define UI_NIPAO_H #include <QtCore/QVariant> #include <QtWidgets/QApplication> #include <QtWidgets/QDialog> #include <QtWidgets/QGroupBox> #include <QtWidgets/QPushButton> QT_BEGIN_NAMESPACE class Ui_nipao { public: QGroupBox *groupBox; QPushButton *pushButton; QPushButton *pushButton_2; QPushButton *pushButton_3; QPushButton *pushButton_4; QPushButton *pushButton_5; QPushButton *pushButton_6; void setupUi(QDialog *nipao) { if (nipao->objectName().isEmpty()) nipao->setObjectName(QString::fromUtf8("nipao")); nipao->resize(342, 300); groupBox = new QGroupBox(nipao); groupBox->setObjectName(QString::fromUtf8("groupBox")); groupBox->setGeometry(QRect(10, 10, 321, 241)); pushButton = new QPushButton(groupBox); pushButton->setObjectName(QString::fromUtf8("pushButton")); pushButton->setGeometry(QRect(20, 30, 91, 23)); pushButton_2 = new QPushButton(groupBox); pushButton_2->setObjectName(QString::fromUtf8("pushButton_2")); pushButton_2->setGeometry(QRect(200, 30, 75, 23)); pushButton_3 = new QPushButton(groupBox); pushButton_3->setObjectName(QString::fromUtf8("pushButton_3")); pushButton_3->setGeometry(QRect(20, 180, 75, 23)); pushButton_4 = new QPushButton(groupBox); pushButton_4->setObjectName(QString::fromUtf8("pushButton_4")); pushButton_4->setGeometry(QRect(210, 180, 75, 23)); pushButton_5 = new QPushButton(groupBox); pushButton_5->setObjectName(QString::fromUtf8("pushButton_5")); pushButton_5->setGeometry(QRect(20, 110, 75, 23)); pushButton_6 = new QPushButton(groupBox); pushButton_6->setObjectName(QString::fromUtf8("pushButton_6")); pushButton_6->setGeometry(QRect(210, 110, 75, 23)); retranslateUi(nipao); QObject::connect(pushButton, SIGNAL(pressed()), nipao, SLOT(Relay9Pressed())); QObject::connect(pushButton, SIGNAL(released()), nipao, SLOT(Relay9Released())); QObject::connect(pushButton_2, SIGNAL(pressed()), nipao, SLOT(Relay10Pressed())); QObject::connect(pushButton_2, SIGNAL(released()), nipao, SLOT(Relay9Released())); QObject::connect(pushButton_5, SIGNAL(pressed()), nipao, SLOT(Relay11Pressed())); QObject::connect(pushButton_5, SIGNAL(released()), nipao, SLOT(Relay11Released())); QObject::connect(pushButton_6, SIGNAL(pressed()), nipao, SLOT(Relay12Pressed())); QObject::connect(pushButton_6, SIGNAL(released()), nipao, SLOT(Relay12Released())); QObject::connect(pushButton_3, SIGNAL(pressed()), nipao, SLOT(Relay27Pressed())); QObject::connect(pushButton_3, SIGNAL(released()), nipao, SLOT(Relay27Released())); QObject::connect(pushButton_4, SIGNAL(pressed()), nipao, SLOT(Relay28Pressed())); QObject::connect(pushButton_4, SIGNAL(released()), nipao, SLOT(Relay28Released())); QMetaObject::connectSlotsByName(nipao); } // setupUi void retranslateUi(QDialog *nipao) { nipao->setWindowTitle(QCoreApplication::translate("nipao", "\346\263\245\347\202\256", nullptr)); groupBox->setTitle(QCoreApplication::translate("nipao", "\346\263\245\347\202\256\344\275\215\347\275\256\345\276\256\350\260\203", nullptr)); pushButton->setText(QCoreApplication::translate("nipao", "\346\263\245\347\202\256\345\211\215\350\277\233", nullptr)); pushButton_2->setText(QCoreApplication::translate("nipao", "\346\263\245\347\202\256\345\220\216\351\200\200", nullptr)); pushButton_3->setText(QCoreApplication::translate("nipao", "\345\267\246\347\247\273", nullptr)); pushButton_4->setText(QCoreApplication::translate("nipao", "\345\217\263\347\247\273", nullptr)); pushButton_5->setText(QCoreApplication::translate("nipao", "\346\214\244\346\263\245", nullptr)); pushButton_6->setText(QCoreApplication::translate("nipao", "\345\241\253\346\263\245", nullptr)); } // retranslateUi }; namespace Ui { class nipao: public Ui_nipao {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_NIPAO_H
[ "1406939971@qq.com" ]
1406939971@qq.com
8100fff78f5a7b4ea8e704e9f325905ec52828aa
a0239111f1365833a8d3f0ce99ba0a15590b2371
/Include/FileParser/UGFileParserTile.h
ff215ef65a186a9650942a99d5f1336b169f7a09
[]
no_license
SuperMap/OGDC
71c9f629e3e6ccde604446f1504d07a809ee82ae
c4e3fe509dd8772794d144fe0d906cfd123e5f66
refs/heads/master
2023-09-06T08:44:59.595550
2022-03-15T08:23:59
2022-03-15T08:23:59
6,771,763
30
15
null
null
null
null
GB18030
C++
false
false
4,927
h
////////////////////////////////////////////////////////////////////////// // _ _ ____ ____ // Project | | | | / ___) / ___) // | | | || | __ | | // | |_| || |_\ || \___ // \____/ \____| \ ___) 6.0 // //! \file headerfile.h //! \brief //! \details //! \author //! \attention //! Copyright (c) 1996-2010 SuperMap Software Co., Ltd. <br> //! All Rights Reserved. //! \version 6.0 ////////////////////////////////////////////////////////////////////////// #if !defined(AFX_UGFILEPARSERTILE_H__54B13918_6164_49A5_9255_99DD4740622F__INCLUDED_) #define AFX_UGFILEPARSERTILE_H__54B13918_6164_49A5_9255_99DD4740622F__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "Base3D/UGModelNodeShells.h" namespace UGC { class FILEPARSER_API UGTileStuff { public: //! \brief 下层Tile信息:切换距离和Tile名 typedef std::pair<UGdouble, UGString> PagedInfo; typedef std::vector<PagedInfo> PagedInfos; typedef std::pair<UGModelPagedPatch*, PagedInfos> PatchData; typedef std::vector<PatchData> PatchDatas; public: UGTileStuff(); ~UGTileStuff(); //! \brief 清理内存 void Clear(); //! \brief 添加一个Patch,暂无子节点信息 void AddOnePatch(UGModelPagedPatch* pPatch); //! \brief 添加一个Patch及子节点信息 void AddPatchInfo(UGModelPagedPatch* pPatch, PagedInfo& info); //! \brief 获取所有Patch void GetPatches(std::vector<UGModelPagedPatch*>& vecPatches, UGbool bDelegate); //! \brief 获取所有PagedInfos PagedInfos GetPagedInfos(); //! \brief 获取所有PagedDatas,并托管 void DelegatePatchDatas(PatchDatas& patchdatas); //! \brief 设置RangeMode void SetRangeMode(UGRangeMode rangeMode); //! \brief 获取RangeMode UGRangeMode GetRangeMode(); //! \brief 根据pPatch设置Tile名 void SetTileName(UGModelPagedPatch* pPatch); //! \brief 获取Tile名 UGString GetTileName(); //! \brief 计算包围盒 UGBoundingBox GetBoundingBox(); //! \brief 设置包围盒 void SetBoundingBox(UGBoundingBox &bbox); private: //! \brief 切换模式 UGRangeMode m_rangeMode; //! \brief 所有的Patch PatchDatas m_vecPatchDatas; //! \brief 自身的包围盒 UGBoundingBox m_bbox; //! \brief Tile名 UGString m_strTileName; }; //! \brief 单个模型文件解析 class FILEPARSER_API UGFileParserTile { public: UGFileParserTile(); ~UGFileParserTile(); //! \brief 打开文件 virtual UGbool Open(const UGString& strDir, const UGString& strTile); //! \brief 关闭文件 virtual void Close(); //! \brief 是否解析材质。提取PagedLOD信息时不需要解析材质 virtual void SetParseMaterial(UGbool bParseMaterial); //! \brief 设置obj解析时绕X轴的旋转方式.仅支持osgb插件的obj void SetRotateOption(UGint obj_opt); //! \brief 获取patch数据 virtual void GetPatches(std::vector<UGModelPagedPatch*> &vecPatches, UGbool bDelegate); //! \brief 获取解析数据 UGTileStuff* GetTileStuff(); //! \brief 获取解析数据 UGTileStuff::PatchDatas DelegatePatchDatas(); //! \brief 获取本层的数据范围 //! \brief bForce 当pagedlod信息中包围盒为空,是否强制读数据 UGBoundingBox GetBoundingBox(); //! \brief 获取本层的切换模式 UGRangeMode GetRangeMode(); //! \brief 文件的全局矩阵(目前给dae的单位用) UGMatrix4d GetMatrixGloble(); //! \brief 用来设置压缩参数(全部解压\不压缩(0);其他参照VertexCompressOptions各个位的意义) void SetVertexCompressOptions(UGint nVertexCompressOptions); //! \brief 加载时是否强制解压顶点 void SetForceUnzip(UGbool bForceUnzip); protected: //! \brief 文件夹 UGString m_strDir; //! \brief 文件名 UGString m_strTile; //! \brief 给文件生成一个唯一标示,骨架名使用 UGString m_strFileUUID; //! \brief 是否解析材质。提取PagedLOD信息时不需要解析材质 UGbool m_bParseMaterial; //! \brief 字符集 UGString::Charset m_charset; //! \brief obj文件解析选项 UGint m_objRotateOpt; //! \brief 文件的全局矩阵(目前给dae的单位用) UGMatrix4d m_matGloble; //! \brief 压缩参数(全部解压\不压缩(0);其他参照VertexCompressOptions各个位的意义) UGint m_nVertexCompressOptions; //! \brief 解析时是否强制解压顶点 UGbool m_bForceUnzip; //! \brief 一个Tile解析出来的多个Patch,为保留与下一层的对应关系,Patch不能合并 //! \brief PagedLOD信息: Patch 及其对应的 下一层切换距离和文件名 UGTileStuff* m_pTileStuff; }; } #endif // !defined(AFX_UGFILEPARSERTILE_H__54B13918_6164_49A5_9255_99DD4740622F__INCLUDED_)
[ "heqian@supermap.com" ]
heqian@supermap.com
722980af8a32701cc36cba78b3604225be45417a
308be50d5747de8546fcd677bfb241f21e69c14d
/divide and conquer/Binary_search_a[in]_greater_or_equal_tar.cpp
e2f1e81d500100e59546584e148c38de36532f13
[]
no_license
samnoon1971/CP
40ecfc863a72236313d0206f4267b6cffd3a6aea
412510342536c948ddac6df53df68637dd6faea2
refs/heads/master
2022-03-08T09:14:58.646105
2019-10-24T14:27:48
2019-10-24T14:27:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,103
cpp
#include<bits/stdc++.h> using namespace std; /** ******************************************************************** ******************* Author:Bisnu sarkar **************************** ******************************************************************** **/ #define ull unsigned long long #define ll long long #define vi vector<int> #define pb push_back #define mp make_pair #define pii pair<int,int> #define vit vector<int> :: iterator #define sit set<int> :: iterator #define vrit vector<int> :: reverse iterator #define ff first #define ss second #define what_is(x) cerr << #x << " is " << x << endl; ///*....Debugger....*/ #define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); } void err(istream_iterator<string> it) { cout << endl ; } template<typename T, typename... Args> void err(istream_iterator<string> it, T a, Args... args) { cerr << *it << " = " << a << ' ' ; err(++it, args...); } int dx[8]= {1,0,-1,0,-1,-1,1,1}; int dy[8]= {0,1,0,-1,-1,1,-1,1}; int ini() { int x; scanf("%d",&x); return x; } long long inl() { long long x; scanf("%lld",&x); return x; } int set_1(int n,int pos){return n = (n | (1<<pos));} int reset_0(int n,int pos){return n= n & ~(1<<pos);} bool check_bit(int n,int pos){return n = n & (1<<pos);} const int N = (int) 1e6 + 5; const int M = (int) 1e9 + 7; const double pi=2* acos(0.0); int a[N]; int bs(int n,int tar){ int l=0,r=n-1; int ans=-1; while(l<=r){ int mid = l + (r-l)/2; if(a[mid]>=tar){ ans=mid; r=mid-1; } else{ l=mid+1; } } return ans; } int main() { int n=ini(); for (int i = 0; i < n; ++i) { cin>>a[i]; } int x=ini(); int in=bs(n,x); if(in==-1){ cout<<"Not found"<<endl; } else{ cout<<in<<endl; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
41882e588255c7eec96aaf2e45981c5135c16046
04facfc8b44b1ccdaaeadc2793d981af285f5df3
/LeetCode/C++/General/Medium/MaximumScoreFromPerformingMultiplicationOperations/solution.cpp
6027e608cdbfda01eb422edbd36665391860a31a
[ "MIT" ]
permissive
busebd12/InterviewPreparation
4423d72d379eb55bd9930685b12fcecc7046354b
78c9caca7b208ec54f6d9fa98304c7f90fe9f603
refs/heads/master
2022-11-02T23:51:46.335420
2022-10-29T06:45:40
2022-10-29T06:45:40
46,381,491
0
0
null
null
null
null
UTF-8
C++
false
false
2,476
cpp
#include <algorithm> #include <limits> #include <vector> using namespace std; /* Solution: inspired by these posts 1) https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/2583868/Naive-Recursion-greater-Better-Rec-greater-Memo-greater-Tabulation-greater-Space-Optimization 2) https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/1075496/C%2B%2BPython-Classic-DP Time complexity: O(m^2) [where m is the length of multipliers] Space complexity: O(m^2) */ class Solution { public: int maximumScore(vector<int> & nums, vector<int> & multipliers) { int result=0; int n=nums.size(); int m=multipliers.size(); vector<vector<int>> memo(1001, vector<int>(1001, numeric_limits<int>::min())); int front=0; int back=n - 1; int index=0; result=helper(nums, multipliers, memo, n, m, front, back, index); return result; } int helper(vector<int> & nums, vector<int> & multipliers, vector<vector<int>> & memo, int n, int m, int front, int back, int index) { if(index > m - 1) { return 0; } if(front > n - 1) { return 0; } if(back < 0) { return 0; } if(front > back) { return 0; } if(memo[front][index]!=numeric_limits<int>::min()) { return memo[front][index]; } int subproblemSolution=0; int frontOperation=nums[front] * multipliers[index]; int takeFrontNumber=frontOperation + helper(nums, multipliers, memo, n, m, front + 1, back, index + 1); int backOperation=nums[back] * multipliers[index]; int takeBackNumber=backOperation + helper(nums, multipliers, memo, n, m, front, back - 1, index + 1); subproblemSolution=max(takeFrontNumber, takeBackNumber); memo[front][index]=subproblemSolution; return subproblemSolution; } };
[ "brendan.busey@alumni.wfu.edu" ]
brendan.busey@alumni.wfu.edu
abf5ed5fd1f76de946782c88497b08f9e612d8ef
e56cc6178c66d13ab43b5aca0f9d1972b3dcba7f
/Biblioteka/biblioteka.h
78f22cff4f62faf9c076a26b5fda43aa056390b8
[]
no_license
MateuszGrabarczyk/System-biblioteczny
de4f860854866f9e4fe36ff91f5aeedd1d91ddb3
a9163ed0d052d38ac1a333bfb7bc7396a00afe60
refs/heads/main
2023-07-11T10:16:38.993276
2021-08-17T17:41:21
2021-08-17T17:41:21
397,341,134
0
0
null
null
null
null
UTF-8
C++
false
false
842
h
#pragma once #include "baza_studentow.h" #include "baza_ksiazek.h" #include "student.h" #include "ksiazka.h" #include "powitanie.h" #include <iostream> #include <string> #include <vector> using namespace std; /** * @brief Klasa, ktora posiada wszystkie dane w bibliotece, czyli liste ksiazke, studentow oraz wypozyczonych ksiazek */ class Biblioteka : public Baza_ksiazek, public Baza_studentow, public Powitanie { public: vector<pair<Ksiazka, Student>> wypozyczone_ksiazki; public: Biblioteka(); ~Biblioteka(); void nadpisz_plik(); void dodaj_ksiazke(); void dodaj_studenta(); void wyswietl_ksiazki(); void wyswietl_studentow(); void usun_ksiazke(); void usun_studenta(); void wyszukaj_ksiazke(); void wypozycz_ksiazke(Student S); void oddaj_ksiazke(Student S); void wypisz(); void wyswietl_ksiazki_wypozyczone(Student S); };
[ "noreply@github.com" ]
noreply@github.com
6b4961c69f7ff1b009492743ba411fcb54371635
a83349cd334786e0f555318a6979c4ec23ec8978
/JuFo DCMotor/src/main.cpp
fec82d4b4a4d023a7c094b1233fe1a587872756c
[]
no_license
Suebaen/Jugendforscht-GitarrenTuner
07a0b82a5230014750ed999709a9051d10863975
117a8550099f7da0f755598d0a4e7b3c982d098c
refs/heads/main
2023-03-26T10:49:27.435700
2021-03-24T21:15:19
2021-03-24T21:15:19
306,705,184
0
0
null
null
null
null
UTF-8
C++
false
false
12,969
cpp
#include <Arduino.h> #include <SoftwareSerial.h> #include <Wire.h> #include <LiquidCrystal_I2C.h> // Motor für das G int MotorG_R = 2; int MotorG_L = 3; // Motor für das F int MotorF_R = 4; int MotorF_L = 5; // Motor für das A int MotorA_L = 6; int MotorA_R = 7; // Motor für das C int MotorC_L = 8; int MotorC_R = 9; // Motor für das D int MotorD_R = 10; int MotorD_L = 11; // Motor für das E int MotorE_R = 12; int MotorE_L = 13; SoftwareSerial serial_connection(0, 1); LiquidCrystal_I2C lcd(0x27, 16, 2); #define BUFFER_SIZE 64 const int stepsPerRevolution = 50; char inData[BUFFER_SIZE]; char inChar=-1; int count=0; int i = 0; int winkel = 90; int warten = 100; int UmWievielSichDerServoDrehenSOll = 200; int first_bytes; int remainf_bytes=0; byte byte_count; int stepCount = 0; int steps = 3; // das sind die Wichtigsten Funfktionen für das LCD_Display void Bildschirm() { lcd.begin(); lcd.backlight(); lcd.noBacklight(); lcd.setCursor(0, 1); // damit kann man den Cursor setzten lcd.print("das ist ein test"); // das ist nur ein Test lcd.clear(); } void setup() { Serial.begin(9600); serial_connection.begin(9600); serial_connection.println("Ready!!"); Serial.println("Started"); Bildschirm(); } void loop() { byte_count=serial_connection.available(); if (byte_count){ Serial.println("Incoming Data"); first_bytes=byte_count; remainf_bytes=0; if (first_bytes>=BUFFER_SIZE-1){ remainf_bytes=byte_count-(BUFFER_SIZE-1); } for (i = 0; i < first_bytes; i++){ inChar=serial_connection.read(); inData[i]=inChar; Serial.println(first_bytes); } inData[i]='\0'; // Motor für das F if (String(inData)=="N"){ Serial.println(inData); digitalWrite(MotorF_R, HIGH); digitalWrite(MotorF_L, LOW); Serial.print("steps:"); Serial.println("clockwise"); delay(warten); } if (String(inData)=="NNN"){ Serial.println(inData); digitalWrite(MotorF_R, HIGH); digitalWrite(MotorF_L, LOW); Serial.print("steps:"); Serial.println("clockwise"); delay(warten); } if (String(inData)=="NNNN"){ Serial.println(inData); digitalWrite(MotorF_R, HIGH); digitalWrite(MotorF_L, LOW); Serial.print("steps:"); Serial.println("clockwise"); delay(warten); } if (String(inData)=="FN"){ Serial.println(inData); digitalWrite(MotorF_R, HIGH); digitalWrite(MotorF_L, LOW); Serial.print("steps:"); Serial.println("clockwise"); delay(warten); } if (String(inData)=="NFN"){ Serial.println(inData); digitalWrite(MotorF_R, HIGH); digitalWrite(MotorF_L, LOW); Serial.print("steps:"); Serial.println("clockwise"); delay(warten); } if (String(inData)=="NNNNNN"){ Serial.println(inData); digitalWrite(MotorF_R, HIGH); digitalWrite(MotorF_L, LOW); Serial.print("steps:"); Serial.println("clockwise"); delay(warten); } if (String(inData)=="F"){ Serial.println(inData); digitalWrite(MotorF_R, LOW); digitalWrite(MotorF_L, HIGH); Serial.print("steps:"); Serial.println("counterclockwise"); delay(warten); } if (String(inData)=="FF"){ digitalWrite(MotorF_R, LOW); digitalWrite(MotorF_L, HIGH); Serial.print("steps:"); Serial.println("counterclockwise"); delay(warten); } if (String(inData)=="FFF"){ digitalWrite(MotorF_R, LOW); digitalWrite(MotorF_L, HIGH); Serial.print("steps:"); Serial.println("counterclockwise"); delay(warten); } // Motor für das A if (String(inData)=="A"){ Serial.println(inData); digitalWrite(MotorA_L, HIGH); digitalWrite(MotorA_R, LOW); Serial.print("steps:"); Serial.println("clockwise"); delay(warten); } if (String(inData)=="AA"){ Serial.println(inData); digitalWrite(MotorA_L, HIGH); digitalWrite(MotorA_R, LOW); Serial.print("steps:"); Serial.println("clockwise"); delay(warten); } if (String(inData)=="ABA"){ Serial.println(inData); digitalWrite(MotorA_L, HIGH); digitalWrite(MotorA_R, LOW); Serial.print("steps:"); Serial.println("clockwise"); delay(warten); } if (String(inData)=="AAA"){ Serial.println(inData); digitalWrite(MotorA_L, HIGH); digitalWrite(MotorA_R, LOW); Serial.print("steps:"); Serial.println("clockwise"); delay(warten); } if (String(inData)=="AAAAAAA"){ Serial.println(inData); digitalWrite(MotorA_L, HIGH); digitalWrite(MotorA_R, LOW); Serial.print("steps:"); Serial.println("clockwise"); delay(warten); } if (String(inData)=="B"){ Serial.println(inData); digitalWrite(MotorA_L, LOW); digitalWrite(MotorA_R, HIGH); Serial.print("steps:"); Serial.println("counterclockwise"); delay(warten); } if (String(inData)=="BB"){ digitalWrite(MotorA_L, LOW); digitalWrite(MotorA_R, HIGH); Serial.print("steps:"); Serial.println("counterclockwise"); delay(warten); } if (String(inData)=="BBB"){ digitalWrite(MotorA_L, LOW); digitalWrite(MotorA_R, HIGH); Serial.print("steps:"); Serial.println("counterclockwise"); delay(warten); } if (String(inData)=="BBBB"){ digitalWrite(MotorA_L, LOW); digitalWrite(MotorA_R, HIGH); Serial.print("steps:"); Serial.println("counterclockwise"); delay(warten); } // Motor für das C if (String(inData)=="C"){ Serial.println(inData); digitalWrite(MotorF_R, HIGH); digitalWrite(MotorF_L, LOW); Serial.print("steps:"); Serial.println("clockwise"); delay(warten); } if (String(inData)=="CC"){ Serial.println(inData); digitalWrite(MotorF_R, HIGH); digitalWrite(MotorF_L, LOW); Serial.print("steps:"); Serial.println("clockwise"); delay(warten); } if (String(inData)=="CCC"){ Serial.println(inData); digitalWrite(MotorF_R, HIGH); digitalWrite(MotorF_L, LOW); Serial.print("steps:"); Serial.println("clockwise"); delay(warten); } if (String(inData)=="CCCC"){ Serial.println(inData); digitalWrite(MotorF_R, HIGH); digitalWrite(MotorF_L, LOW); Serial.print("steps:"); Serial.println("clockwise"); delay(warten); } if (String(inData)=="L"){ Serial.println(inData); digitalWrite(MotorF_R, LOW); digitalWrite(MotorF_L, HIGH); Serial.print("steps:"); Serial.println("counterclockwise"); delay(warten); } if (String(inData)=="LL"){ digitalWrite(MotorF_R, LOW); digitalWrite(MotorF_L, HIGH); Serial.print("steps:"); Serial.println("counterclockwise"); delay(warten); } if (String(inData)=="LLL"){ digitalWrite(MotorF_R, LOW); digitalWrite(MotorF_L, HIGH); Serial.print("steps:"); Serial.println("counterclockwise"); delay(warten); } if (String(inData)=="LLLL"){ digitalWrite(MotorF_R, LOW); digitalWrite(MotorF_L, HIGH); Serial.print("steps:"); Serial.println("counterclockwise"); delay(warten); } //Motor für das G if (String(inData)=="G"){ digitalWrite(MotorG_R, HIGH); digitalWrite(MotorG_L, LOW); Serial.print("steps:"); delay(warten); } if (String(inData)=="GG"){ digitalWrite(MotorG_R, HIGH); digitalWrite(MotorG_L, LOW); Serial.print("steps:"); delay(warten); } if (String(inData)=="GGG"){ digitalWrite(MotorG_R, HIGH); digitalWrite(MotorG_L, LOW); Serial.print("steps:"); delay(warten); } if (String(inData)=="GGGG"){ digitalWrite(MotorG_R, HIGH); digitalWrite(MotorG_L, LOW); Serial.print("steps:"); delay(warten); } if (String(inData)=="K"){ digitalWrite(MotorG_R, LOW); digitalWrite(MotorG_L, HIGH); Serial.print("steps:"); delay(warten); } if (String(inData)=="KK"){ digitalWrite(MotorG_R, LOW); digitalWrite(MotorG_L, HIGH); Serial.print("steps:"); delay(warten); } if (String(inData)=="KKK"){ //das KKK steht NICHT for den Ku-Klux-Klan digitalWrite(MotorG_R, LOW); digitalWrite(MotorG_L, HIGH); Serial.print("steps:"); delay(warten); } if (String(inData)=="KKKK"){ digitalWrite(MotorG_R, LOW); digitalWrite(MotorG_L, HIGH); Serial.print("steps:"); delay(warten); } //Motor für das E if(String(inData)=="E"){ digitalWrite(MotorE_R, HIGH); digitalWrite(MotorE_L, LOW); Serial.print("steps:"); delay(warten); } if(String(inData)=="EE"){ digitalWrite(MotorE_R, HIGH); digitalWrite(MotorE_L, LOW); Serial.print("steps:"); delay(warten); } if(String(inData)=="EEE"){ digitalWrite(MotorE_R, HIGH); digitalWrite(MotorE_L, LOW); Serial.print("steps:"); delay(warten); } if(String(inData)=="EEEE"){ digitalWrite(MotorE_R, HIGH); digitalWrite(MotorE_L, LOW); Serial.print("steps:"); delay(warten); } if(String(inData)=="Q"){ digitalWrite(MotorE_R, LOW); digitalWrite(MotorE_L, HIGH); Serial.print("steps:"); delay(warten); } if(String(inData)=="QQ"){ digitalWrite(MotorE_R, LOW); digitalWrite(MotorE_L, HIGH); Serial.print("steps:"); delay(warten); } if(String(inData)=="QQQ"){ digitalWrite(MotorE_R, LOW); digitalWrite(MotorE_L, HIGH); Serial.print("steps:"); delay(warten); } if(String(inData)=="QQQQ"){ digitalWrite(MotorE_R, LOW); digitalWrite(MotorE_L, HIGH); Serial.print("steps:"); delay(warten); } //Motr für das D if(String(inData)=="D"){ digitalWrite(MotorD_R, HIGH); digitalWrite(MotorD_L, LOW); Serial.print("steps:"); delay(warten); } if(String(inData)=="D"){ digitalWrite(MotorD_R, HIGH); digitalWrite(MotorD_L, LOW); Serial.print("steps:"); delay(warten); } if(String(inData)=="DD"){ digitalWrite(MotorD_R, HIGH); digitalWrite(MotorD_L, LOW); Serial.print("steps:"); delay(warten); } if(String(inData)=="DDD"){ digitalWrite(MotorD_R, HIGH); digitalWrite(MotorD_L, LOW); Serial.print("steps:"); delay(warten); } if(String(inData)=="U"){ digitalWrite(MotorD_R, LOW); digitalWrite(MotorD_L, HIGH); Serial.print("steps:"); delay(warten); } if(String(inData)=="UU"){ digitalWrite(MotorD_R, LOW); digitalWrite(MotorD_L, HIGH); Serial.print("steps:"); delay(warten); } if(String(inData)=="UUU"){ digitalWrite(MotorD_R, LOW); digitalWrite(MotorD_L, HIGH); Serial.print("steps:"); delay(warten); } for ( i = 0; i < remainf_bytes; i++){ inChar=serial_connection.read(); } //das hier ist der Notfall Stop der eigentlich nie verwedet werden muss // if (String(inData)=="P"){ // digitalWrite(MotorA_L, LOW); // digitalWrite(MotorA_R, LOW); // Serial.print("steps:"); // Serial.println("counterclockwise"); // delay(warten); // } Serial.println(inData); Serial.println(inData); // F aus digitalWrite(MotorF_R, LOW); digitalWrite(MotorF_L, LOW); // A aus digitalWrite(MotorA_L, LOW); digitalWrite(MotorA_R, LOW); // D aus digitalWrite(MotorD_L, LOW); digitalWrite(MotorD_R, LOW); // E aus digitalWrite(MotorE_L, LOW); digitalWrite(MotorE_R, LOW); // C aus digitalWrite(MotorC_L, LOW); digitalWrite(MotorC_R, LOW); // G aus digitalWrite(MotorG_L, LOW); digitalWrite(MotorG_R, LOW); } }
[ "noreply@github.com" ]
noreply@github.com
7744f1d592f025a7f038d4dc877a502e03862388
cc7404f1a7d850273fcd302bfaabccfbfb5c953e
/ajaxSample/node_modules/nodegit/src/nodegit.cc
bd18fccd90ae6fd8765df03ffa2eb2a8321b7093
[ "MIT" ]
permissive
soicem/nodegitServer
0916cea7f30021aac6facc1820c3b8fa676cb390
9aee58b9576812146bffd97a8141b131d95933e7
refs/heads/master
2023-01-27T11:36:26.753664
2019-11-06T05:09:15
2019-11-06T05:09:15
210,338,626
1
0
null
2023-01-04T11:13:50
2019-09-23T11:31:45
JavaScript
UTF-8
C++
false
false
17,897
cc
// This is a generated file, modify: generate/templates/templates/nodegit.cc #include <node.h> #include <v8.h> #include <git2.h> #include <map> #include <algorithm> #include <set> #include <openssl/crypto.h> #include "../include/init_ssh2.h" #include "../include/lock_master.h" #include "../include/nodegit.h" #include "../include/wrapper.h" #include "../include/promise_completion.h" #include "../include/functions/copy.h" #include "../include/annotated_commit.h" #include "../include/apply.h" #include "../include/apply_options.h" #include "../include/apply_options.h" #include "../include/attr.h" #include "../include/blame.h" #include "../include/blame_hunk.h" #include "../include/blame_options.h" #include "../include/blob.h" #include "../include/blob_filter_options.h" #include "../include/blob_filter_options.h" #include "../include/branch.h" #include "../include/branch_iterator.h" #include "../include/buf.h" #include "../include/cert.h" #include "../include/cert_hostkey.h" #include "../include/cert_x509.h" #include "../include/checkout.h" #include "../include/checkout_options.h" #include "../include/checkout_perfdata.h" #include "../include/cherrypick.h" #include "../include/cherrypick_options.h" #include "../include/clone.h" #include "../include/clone_options.h" #include "../include/commit.h" #include "../include/config.h" #include "../include/config_entry.h" #include "../include/config_entry.h" #include "../include/config_iterator.h" #include "../include/configmap.h" #include "../include/cred.h" #include "../include/describe_format_options.h" #include "../include/describe_format_options.h" #include "../include/describe_options.h" #include "../include/describe_options.h" #include "../include/describe_result.h" #include "../include/diff.h" #include "../include/diff_binary.h" #include "../include/diff_binary_file.h" #include "../include/diff_delta.h" #include "../include/diff_file.h" #include "../include/diff_find_options.h" #include "../include/diff_hunk.h" #include "../include/diff_line.h" #include "../include/diff_options.h" #include "../include/diff_patchid_options.h" #include "../include/diff_perfdata.h" #include "../include/diff_stats.h" #include "../include/error.h" #include "../include/fetch.h" #include "../include/fetch_options.h" #include "../include/fetch_options.h" #include "../include/filter.h" #include "../include/filter.h" #include "../include/filter_list.h" #include "../include/filter_source.h" #include "../include/graph.h" #include "../include/hashsig.h" #include "../include/ignore.h" #include "../include/index.h" #include "../include/index_conflict_iterator.h" #include "../include/index_entry.h" #include "../include/index_iterator.h" #include "../include/index_name_entry.h" #include "../include/index_reuc_entry.h" #include "../include/index_time.h" #include "../include/indexer_progress.h" #include "../include/libgit2.h" #include "../include/mailmap.h" #include "../include/merge.h" #include "../include/merge_file_input.h" #include "../include/merge_file_options.h" #include "../include/merge_options.h" #include "../include/note.h" #include "../include/note_iterator.h" #include "../include/object.h" #include "../include/odb.h" #include "../include/odb_object.h" #include "../include/oid.h" #include "../include/oid_shorten.h" #include "../include/oidarray.h" #include "../include/packbuilder.h" #include "../include/patch.h" #include "../include/path.h" #include "../include/pathspec.h" #include "../include/pathspec_match_list.h" #include "../include/proxy.h" #include "../include/proxy_options.h" #include "../include/push_options.h" #include "../include/push_update.h" #include "../include/rebase.h" #include "../include/rebase_operation.h" #include "../include/rebase_options.h" #include "../include/rebase_options.h" #include "../include/refdb.h" #include "../include/reference.h" #include "../include/reflog.h" #include "../include/reflog_entry.h" #include "../include/refspec.h" #include "../include/remote.h" #include "../include/remote_callbacks.h" #include "../include/remote_callbacks.h" #include "../include/remote_create_options.h" #include "../include/remote_create_options.h" #include "../include/remote_head.h" #include "../include/remote_head.h" #include "../include/repository.h" #include "../include/repository_init_options.h" #include "../include/reset.h" #include "../include/revert.h" #include "../include/revert_options.h" #include "../include/revparse.h" #include "../include/revwalk.h" #include "../include/signature.h" #include "../include/stash.h" #include "../include/stash_apply_options.h" #include "../include/stash_apply_options.h" #include "../include/status.h" #include "../include/status_entry.h" #include "../include/status_list.h" #include "../include/status_options.h" #include "../include/status_options.h" #include "../include/strarray.h" #include "../include/submodule.h" #include "../include/submodule_update_options.h" #include "../include/tag.h" #include "../include/time.h" #include "../include/trace.h" #include "../include/transaction.h" #include "../include/transport.h" #include "../include/tree.h" #include "../include/tree_entry.h" #include "../include/tree_update.h" #include "../include/treebuilder.h" #include "../include/worktree.h" #include "../include/worktree_add_options.h" #include "../include/worktree_add_options.h" #include "../include/worktree_prune_options.h" #include "../include/worktree_prune_options.h" #include "../include/writestream.h" #include "../include/convenient_patch.h" #include "../include/convenient_hunk.h" #include "../include/filter_registry.h" #if (NODE_MODULE_VERSION > 48) v8::Local<v8::Value> GetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key) { v8::Local<v8::Value> value; Nan::Maybe<bool> result = Nan::HasPrivate(object, key); if (!(result.IsJust() && result.FromJust())) return v8::Local<v8::Value>(); if (Nan::GetPrivate(object, key).ToLocal(&value)) return value; return v8::Local<v8::Value>(); } void SetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key, v8::Local<v8::Value> value) { if (value.IsEmpty()) return; Nan::SetPrivate(object, key, value); } #else v8::Local<v8::Value> GetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key) { return object->GetHiddenValue(key); } void SetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key, v8::Local<v8::Value> value) { object->SetHiddenValue(key, value); } #endif void LockMasterEnable(const FunctionCallbackInfo<Value>& info) { LockMaster::Enable(); } void LockMasterSetStatus(const FunctionCallbackInfo<Value>& info) { Nan::HandleScope scope; // convert the first argument to Status if(info.Length() >= 0 && info[0]->IsNumber()) { v8::Local<v8::Int32> value = Nan::To<v8::Int32>(info[0]).ToLocalChecked(); LockMaster::Status status = static_cast<LockMaster::Status>(value->Value()); if(status >= LockMaster::Disabled && status <= LockMaster::Enabled) { LockMaster::SetStatus(status); return; } } // argument error Nan::ThrowError("Argument must be one 0, 1 or 2"); } void LockMasterGetStatus(const FunctionCallbackInfo<Value>& info) { info.GetReturnValue().Set(Nan::New(LockMaster::GetStatus())); } void LockMasterGetDiagnostics(const FunctionCallbackInfo<Value>& info) { LockMaster::Diagnostics diagnostics(LockMaster::GetDiagnostics()); // return a plain JS object with properties v8::Local<v8::Object> result = Nan::New<v8::Object>(); Nan::Set(result, Nan::New("storedMutexesCount").ToLocalChecked(), Nan::New(diagnostics.storedMutexesCount)); info.GetReturnValue().Set(result); } static uv_mutex_t *opensslMutexes; void OpenSSL_LockingCallback(int mode, int type, const char *, int) { if (mode & CRYPTO_LOCK) { uv_mutex_lock(&opensslMutexes[type]); } else { uv_mutex_unlock(&opensslMutexes[type]); } } void OpenSSL_IDCallback(CRYPTO_THREADID *id) { CRYPTO_THREADID_set_numeric(id, (unsigned long)uv_thread_self()); } void OpenSSL_ThreadSetup() { opensslMutexes=(uv_mutex_t *)malloc(CRYPTO_num_locks() * sizeof(uv_mutex_t)); for (int i=0; i<CRYPTO_num_locks(); i++) { uv_mutex_init(&opensslMutexes[i]); } CRYPTO_set_locking_callback(OpenSSL_LockingCallback); CRYPTO_THREADID_set_callback(OpenSSL_IDCallback); } ThreadPool libgit2ThreadPool(10, uv_default_loop()); extern "C" void init(v8::Local<v8::Object> target) { // Initialize thread safety in openssl and libssh2 OpenSSL_ThreadSetup(); init_ssh2(); // Initialize libgit2. git_libgit2_init(); Nan::HandleScope scope; Wrapper::InitializeComponent(target); PromiseCompletion::InitializeComponent(); GitAnnotatedCommit::InitializeComponent(target); GitApply::InitializeComponent(target); GitApplyOptions::InitializeComponent(target); GitApplyOptions::InitializeComponent(target); GitAttr::InitializeComponent(target); GitBlame::InitializeComponent(target); GitBlameHunk::InitializeComponent(target); GitBlameOptions::InitializeComponent(target); GitBlob::InitializeComponent(target); GitBlobFilterOptions::InitializeComponent(target); GitBlobFilterOptions::InitializeComponent(target); GitBranch::InitializeComponent(target); GitBranchIterator::InitializeComponent(target); GitBuf::InitializeComponent(target); GitCert::InitializeComponent(target); GitCertHostkey::InitializeComponent(target); GitCertX509::InitializeComponent(target); GitCheckout::InitializeComponent(target); GitCheckoutOptions::InitializeComponent(target); GitCheckoutPerfdata::InitializeComponent(target); GitCherrypick::InitializeComponent(target); GitCherrypickOptions::InitializeComponent(target); GitClone::InitializeComponent(target); GitCloneOptions::InitializeComponent(target); GitCommit::InitializeComponent(target); GitConfig::InitializeComponent(target); GitConfigEntry::InitializeComponent(target); GitConfigEntry::InitializeComponent(target); GitConfigIterator::InitializeComponent(target); GitConfigmap::InitializeComponent(target); GitCred::InitializeComponent(target); GitDescribeFormatOptions::InitializeComponent(target); GitDescribeFormatOptions::InitializeComponent(target); GitDescribeOptions::InitializeComponent(target); GitDescribeOptions::InitializeComponent(target); GitDescribeResult::InitializeComponent(target); GitDiff::InitializeComponent(target); GitDiffBinary::InitializeComponent(target); GitDiffBinaryFile::InitializeComponent(target); GitDiffDelta::InitializeComponent(target); GitDiffFile::InitializeComponent(target); GitDiffFindOptions::InitializeComponent(target); GitDiffHunk::InitializeComponent(target); GitDiffLine::InitializeComponent(target); GitDiffOptions::InitializeComponent(target); GitDiffPatchidOptions::InitializeComponent(target); GitDiffPerfdata::InitializeComponent(target); GitDiffStats::InitializeComponent(target); GitError::InitializeComponent(target); GitFetch::InitializeComponent(target); GitFetchOptions::InitializeComponent(target); GitFetchOptions::InitializeComponent(target); GitFilter::InitializeComponent(target); GitFilter::InitializeComponent(target); GitFilterList::InitializeComponent(target); GitFilterSource::InitializeComponent(target); GitGraph::InitializeComponent(target); GitHashsig::InitializeComponent(target); GitIgnore::InitializeComponent(target); GitIndex::InitializeComponent(target); GitIndexConflictIterator::InitializeComponent(target); GitIndexEntry::InitializeComponent(target); GitIndexIterator::InitializeComponent(target); GitIndexNameEntry::InitializeComponent(target); GitIndexReucEntry::InitializeComponent(target); GitIndexTime::InitializeComponent(target); GitIndexerProgress::InitializeComponent(target); GitLibgit2::InitializeComponent(target); GitMailmap::InitializeComponent(target); GitMerge::InitializeComponent(target); GitMergeFileInput::InitializeComponent(target); GitMergeFileOptions::InitializeComponent(target); GitMergeOptions::InitializeComponent(target); GitNote::InitializeComponent(target); GitNoteIterator::InitializeComponent(target); GitObject::InitializeComponent(target); GitOdb::InitializeComponent(target); GitOdbObject::InitializeComponent(target); GitOid::InitializeComponent(target); GitOidShorten::InitializeComponent(target); GitOidarray::InitializeComponent(target); GitPackbuilder::InitializeComponent(target); GitPatch::InitializeComponent(target); GitPath::InitializeComponent(target); GitPathspec::InitializeComponent(target); GitPathspecMatchList::InitializeComponent(target); GitProxy::InitializeComponent(target); GitProxyOptions::InitializeComponent(target); GitPushOptions::InitializeComponent(target); GitPushUpdate::InitializeComponent(target); GitRebase::InitializeComponent(target); GitRebaseOperation::InitializeComponent(target); GitRebaseOptions::InitializeComponent(target); GitRebaseOptions::InitializeComponent(target); GitRefdb::InitializeComponent(target); GitRefs::InitializeComponent(target); GitReflog::InitializeComponent(target); GitReflogEntry::InitializeComponent(target); GitRefspec::InitializeComponent(target); GitRemote::InitializeComponent(target); GitRemoteCallbacks::InitializeComponent(target); GitRemoteCallbacks::InitializeComponent(target); GitRemoteCreateOptions::InitializeComponent(target); GitRemoteCreateOptions::InitializeComponent(target); GitRemoteHead::InitializeComponent(target); GitRemoteHead::InitializeComponent(target); GitRepository::InitializeComponent(target); GitRepositoryInitOptions::InitializeComponent(target); GitReset::InitializeComponent(target); GitRevert::InitializeComponent(target); GitRevertOptions::InitializeComponent(target); GitRevparse::InitializeComponent(target); GitRevwalk::InitializeComponent(target); GitSignature::InitializeComponent(target); GitStash::InitializeComponent(target); GitStashApplyOptions::InitializeComponent(target); GitStashApplyOptions::InitializeComponent(target); GitStatus::InitializeComponent(target); GitStatusEntry::InitializeComponent(target); GitStatusList::InitializeComponent(target); GitStatusOptions::InitializeComponent(target); GitStatusOptions::InitializeComponent(target); GitStrarray::InitializeComponent(target); GitSubmodule::InitializeComponent(target); GitSubmoduleUpdateOptions::InitializeComponent(target); GitTag::InitializeComponent(target); GitTime::InitializeComponent(target); GitTrace::InitializeComponent(target); GitTransaction::InitializeComponent(target); GitTransport::InitializeComponent(target); GitTree::InitializeComponent(target); GitTreeEntry::InitializeComponent(target); GitTreeUpdate::InitializeComponent(target); GitTreebuilder::InitializeComponent(target); GitWorktree::InitializeComponent(target); GitWorktreeAddOptions::InitializeComponent(target); GitWorktreeAddOptions::InitializeComponent(target); GitWorktreePruneOptions::InitializeComponent(target); GitWorktreePruneOptions::InitializeComponent(target); GitWritestream::InitializeComponent(target); ConvenientHunk::InitializeComponent(target); ConvenientPatch::InitializeComponent(target); GitFilterRegistry::InitializeComponent(target); NODE_SET_METHOD(target, "enableThreadSafety", LockMasterEnable); NODE_SET_METHOD(target, "setThreadSafetyStatus", LockMasterSetStatus); NODE_SET_METHOD(target, "getThreadSafetyStatus", LockMasterGetStatus); NODE_SET_METHOD(target, "getThreadSafetyDiagnostics", LockMasterGetDiagnostics); v8::Local<v8::Object> threadSafety = Nan::New<v8::Object>(); Nan::Set(threadSafety, Nan::New("DISABLED").ToLocalChecked(), Nan::New((int)LockMaster::Disabled)); Nan::Set(threadSafety, Nan::New("ENABLED_FOR_ASYNC_ONLY").ToLocalChecked(), Nan::New((int)LockMaster::EnabledForAsyncOnly)); Nan::Set(threadSafety, Nan::New("ENABLED").ToLocalChecked(), Nan::New((int)LockMaster::Enabled)); Nan::Set(target, Nan::New("THREAD_SAFETY").ToLocalChecked(), threadSafety); LockMaster::Initialize(); } NODE_MODULE(nodegit, init)
[ "knq512412@gmail.com" ]
knq512412@gmail.com
335cece233c4da0f3afa11fe8f7e00419f8f7692
0f7a4119185aff6f48907e8a5b2666d91a47c56b
/sstd_utility/windows_boost/boost/math/tools/detail/polynomial_horner2_8.hpp
d19fec6711ce9e6d241dd7778c3ce40670a867af
[]
no_license
jixhua/QQmlQuickBook
6636c77e9553a86f09cd59a2e89a83eaa9f153b6
782799ec3426291be0b0a2e37dc3e209006f0415
refs/heads/master
2021-09-28T13:02:48.880908
2018-11-17T10:43:47
2018-11-17T10:43:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,477
hpp
// (C) Copyright John Maddock 2007. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // This file is machine generated, do not edit by hand // Polynomial evaluation using second order Horners rule #ifndef BOOST_MATH_TOOLS_POLY_EVAL_8_HPP #define BOOST_MATH_TOOLS_POLY_EVAL_8_HPP namespace boost{ namespace math{ namespace tools{ namespace detail{ template <class T, class V> inline V evaluate_polynomial_c_imp(const T*, const V&, const mpl::int_<0>*) BOOST_MATH_NOEXCEPT(V) { return static_cast<V>(0); } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V&, const mpl::int_<1>*) BOOST_MATH_NOEXCEPT(V) { return static_cast<V>(a[0]); } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<2>*) BOOST_MATH_NOEXCEPT(V) { return static_cast<V>(a[1] * x + a[0]); } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<3>*) BOOST_MATH_NOEXCEPT(V) { return static_cast<V>((a[2] * x + a[1]) * x + a[0]); } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<4>*) BOOST_MATH_NOEXCEPT(V) { return static_cast<V>(((a[3] * x + a[2]) * x + a[1]) * x + a[0]); } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<5>*) BOOST_MATH_NOEXCEPT(V) { V x2 = x * x; return static_cast<V>((a[4] * x2 + a[2]) * x2 + a[0] + (a[3] * x2 + a[1]) * x); } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<6>*) BOOST_MATH_NOEXCEPT(V) { V x2 = x * x; return static_cast<V>(((a[5] * x2 + a[3]) * x2 + a[1]) * x + (a[4] * x2 + a[2]) * x2 + a[0]); } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<7>*) BOOST_MATH_NOEXCEPT(V) { V x2 = x * x; return static_cast<V>(((a[6] * x2 + a[4]) * x2 + a[2]) * x2 + a[0] + ((a[5] * x2 + a[3]) * x2 + a[1]) * x); } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<8>*) BOOST_MATH_NOEXCEPT(V) { V x2 = x * x; return static_cast<V>((((a[7] * x2 + a[5]) * x2 + a[3]) * x2 + a[1]) * x + ((a[6] * x2 + a[4]) * x2 + a[2]) * x2 + a[0]); } }}}} // namespaces #endif // include guard
[ "nanguazhude@vip.qq.com" ]
nanguazhude@vip.qq.com
50f9bfd77e7d16805fe4a135aad99516455e5912
4c61f990edc273628629f79bb5a23f0205c59551
/Computer Graphics/3DCubeTransformation/main.cpp
66bf2c78d9b9ab5517f9e3cea2816fe722790111
[]
no_license
Sakshi-25/WhyNotAcademics
844c0705a39571394ee9d647b61f08f0e94b4c62
41328cd1aec93c299948428ccc8e031a6bc22a0d
refs/heads/master
2023-02-06T05:43:39.646673
2020-12-20T18:04:44
2020-12-20T18:04:44
294,505,529
1
0
null
null
null
null
WINDOWS-1250
C++
false
false
8,668
cpp
#include<iostream> #include<graphics.h> #include<conio.h> #include<math.h> # define f 0.3 # define projection_angle 45 using namespace std; void apply_translation(int[8][3],const int,const int,const int); void apply_scaling(int edge_points[8][3],const float sx,const float sy,const float sz); void apply_rotation_x(int edge_points[5][3],const int tx); void apply_rotation_y(int edge_points[5][3],const int tx); void apply_rotation_z(int edge_points[5][3],const int tx); void draw_pyramid(int points[5][3]); void multiply_matrices(const float[4],const float[4][4],float[4]); void draw_cube(int [8][3]); void get_projected_point(int&,int&,int&); void Line(const int,const int,const int,const int); int main(){ int gd=DETECT,tx,ty,tz; float sx,sy,sz; int gm,ch; char op=’y’; initgraph(&gd,&gm,””); do{ int cube[8][3]={{270,200,50}, {370,200,50}, {370,300,50}, {270,300,50}, {270,200,-50}, {370,200,-50}, {370,300,-50}, {270,300,-50}}; int pyramid[5][3]={ {280,130,50}, {360,130,50}, {360,130,-50}, {280,130,-50}, {320,20,0} }; cout<<“Select Your Choice for 3d Transformation\n”; cout<<“1.Translate\n2.Scale\n3.Rotation along x-axis\n4.Rotation along yaxis\ n5.Rotation along z-axis\n”; cin>>ch; switch(ch) { case 1: setcolor(15); draw_cube(cube); cout<<“Enter the tx,ty and tz values: “; cin>>tx>>ty>>tz; apply_translation(cube,tx,ty,tz); setcolor(9); draw_cube(cube); break; case 2: setcolor(15); draw_cube(cube); cout<<“Enter the sx,sy and sz values: “; cin>>sx>>sy>>sz; apply_scaling(cube,sx,sy,sz); setcolor(9); draw_cube(cube); break; case 3: setcolor(15); draw_pyramid(pyramid); cout<<“Enter the rotation angle tx: “; cin>>tx; apply_rotation_x(pyramid,tx); break; case 4: setcolor(15); draw_pyramid(pyramid); cout<<“Enter the rotation angle tx: “; cin>>tx; apply_rotation_y(pyramid,tx); break; case 5: setcolor(15); draw_pyramid(pyramid); cout<<“Enter the rotation angle tx: “; cin>>tx; apply_rotation_z(pyramid,tx); break; } cout<<“\nDo you want to continue: (y/n): “; cin>>op; cleardevice(); } while(op==’y’); getch(); closegraph(); return 0;} void apply_translation(int edge_points[8][3],const int tx,const int ty,const int tz){ for(int count=0;count<8;count++) { floatmatrix_a[4]={edge_points[count][0],edge_points[count][1], edge_points[count][2],1}; float matrix_b[4][4]={{1,0,0,0},{0,1,0,0},{0,0,1,0},{tx,ty,tz,1}}; float matrix_c[4]={0}; multiply_matrices(matrix_a,matrix_b,matrix_c); edge_points[count][0]=(int)(matrix_c[0]+0.5); edge_points[count][1]=(int)(matrix_c[1]+0.5); edge_points[count][2]=(int)(matrix_c[2]+0.5); }} void apply_scaling(int edge_points[8][3],const float sx,const float sy,const float sz){ for(int count=0;count<8;count++) { float matrix_a[4]={edge_points[count][0],edge_points[count][1], edge_points[count][2],1}; float matrix_b[4][4]={{sx,0,0,0},{0,sy,0,0},{0,0,sz,0},{0,0,0,1}}; float matrix_c[4]={0}; multiply_matrices(matrix_a,matrix_b,matrix_c); edge_points[count][0]=(int)(matrix_c[0]+0.5); edge_points[count][1]=(int)(matrix_c[1]+0.5); edge_points[count][2]=(int)(matrix_c[2]+0.5); }} void apply_rotation_x(int control_points[5][3],const int theta){ int edge_points[5][3]={0}; float angle=(theta*(M_PI/180)); for(int count=0;count<5;count++) { edge_points[count][0]=control_points[count][0]; edge_points[count][1]=control_points[count][1]; edge_points[count][2]=control_points[count][2]; float matrix_a[4]={edge_points[count][0],edge_points[count][1], edge_points[count][2],1}; float matrix_b[4][4]={ { 1,0,0,0 } ,{ 0,cos(angle),sin(angle),0 } , { 0,-sin(angle),cos(angle),0 } ,{ 0,0,0,1 }}; float matrix_c[4]={0}; multiply_matrices(matrix_a,matrix_b,matrix_c); edge_points[count][0]=(int)(matrix_c[0]+0.5); edge_points[count][1]=(int)(matrix_c[1]+0.5); edge_points[count][2]=(int)(matrix_c[2]+0.5); } setcolor(10); draw_pyramid(edge_points);} void apply_rotation_y(int control_points[5][3],const int theta){ int edge_points[5][3]={0}; float angle=(theta*(M_PI/180)); for(int count=0;count<5;count++) { edge_points[count][0]=control_points[count][0]; edge_points[count][1]=control_points[count][1]; edge_points[count][2]=control_points[count][2]; float matrix_a[4]={edge_points[count][0], edge_points[count][1], edge_points[count][2],1}; float matrix_b[4][4]={ { cos(angle),0,sin(angle),0 } , { 0,1,0,0 } , { -sin(angle),0,cos(angle),0 } , { 0,0,0,1 }}; float matrix_c[4]={0}; multiply_matrices(matrix_a,matrix_b,matrix_c); edge_points[count][0]=(int)(matrix_c[0]+0.5); edge_points[count][1]=(int)(matrix_c[1]+0.5); edge_points[count][2]=(int)(matrix_c[2]+0.5); } setcolor(10); draw_pyramid(edge_points);} void apply_rotation_z(int control_points[5][3],const int theta) j{ int edge_points[5][3]={0}; float angle=(theta*(M_PI/180)); for(int count=0;count<5;count++) { edge_points[count][0]=control_points[count][0]; edge_points[count][1]=control_points[count][1]; edge_points[count][2]=control_points[count][2]; float matrix_a[4]={edge_points[count][0],edge_points[count][1], edge_points[count][2],1}; float matrix_b[4][4]={ { cos(angle),-sin(angle),0,0} , { sin(angle),cos(angle),0,0 } , { 0,0,1,0 } , { 0,0,0,1 } }; float matrix_c[4]={0}; multiply_matrices(matrix_a,matrix_b,matrix_c); edge_points[count][0]=(int)(matrix_c[0]+0.5); edge_points[count][1]=(int)(matrix_c[1]+0.5); edge_points[count][2]=(int)(matrix_c[2]+0.5); } setcolor(10); draw_pyramid(edge_points);} void multiply_matrices(const float matrix_1[4],const float matrix_2[4][4],float matrix_3[4]){ for(int count_1=0;count_1<4;count_1++) { for(int count_2=0;count_2<4;count_2++) matrix_3[count_1]+=(matrix_1[count_2]*matrix_2[count_2][count_1]); } } void draw_cube(int edge_points[8][3]){ for(int i=0;i<8;i++) get_projected_point(edge_points[i][0],edge_points[i][1],edge_points[i][2]); Line(edge_points[0][0],edge_points[0][1],edge_points[1][0],edge_points[1][1]); Line(edge_points[1][0],edge_points[1][1],edge_points[2][0],edge_points[2][1]); Line(edge_points[2][0],edge_points[2][1],edge_points[3][0],edge_points[3][1]); Line(edge_points[3][0],edge_points[3][1],edge_points[0][0],edge_points[0][1]); Line(edge_points[4][0],edge_points[4][1],edge_points[5][0],edge_points[5][1]); Line(edge_points[5][0],edge_points[5][1],edge_points[6][0],edge_points[6][1]); Line(edge_points[6][0],edge_points[6][1],edge_points[7][0],edge_points[7][1]); Line(edge_points[7][0],edge_points[7][1],edge_points[4][0],edge_points[4][1]); Line(edge_points[0][0],edge_points[0][1],edge_points[4][0],edge_points[4][1]); Line(edge_points[1][0],edge_points[1][1],edge_points[5][0],edge_points[5][1]); Line(edge_points[2][0],edge_points[2][1],edge_points[6][0],edge_points[6][1]); Line(edge_points[3][0],edge_points[3][1],edge_points[7][0],edge_points[7][1]);} void draw_pyramid(int points[5][3]) { int edge_points[5][3]; for(int i=0;i<5;i++) { edge_points[i][0]=points[i][0]; edge_points[i][1]=points[i][1]; edge_points[i][2]=points[i][2]; get_projected_point(edge_points[i][0], edge_points[i][1],edge_points[i][2]); edge_points[i][1]+=240; } Line(edge_points[0][0],edge_points[0][1], edge_points[1][0],edge_points[1][1]); Line(edge_points[1][0],edge_points[1][1], edge_points[2][0],edge_points[2][1]); Line(edge_points[2][0],edge_points[2][1], edge_points[3][0],edge_points[3][1]); Line(edge_points[3][0],edge_points[3][1], edge_points[0][0],edge_points[0][1]); Line(edge_points[0][0],edge_points[0][1], edge_points[4][0],edge_points[4][1]); Line(edge_points[1][0],edge_points[1][1], edge_points[4][0],edge_points[4][1]); Line(edge_points[2][0],edge_points[2][1], edge_points[4][0],edge_points[4][1]); Line(edge_points[3][0],edge_points[3][1],edge_points[4][0],edge_points[4][1]);} void get_projected_point(int& x,int& y,int& z){ float fcos0=(f*cos(projection_angle*(M_PI/180))); float fsin0=(f*sin(projection_angle*(M_PI/180))); float Par_v[4][4]={{1,0,0,0},{0,1,0,0},{fcos0,fsin0,0,0},{0,0,0,1}}; float xy[4]={x,y,z,1}; float new_xy[4]={0}; multiply_matrices(xy,Par_v,new_xy); x=(int)(new_xy[0]+0.5); y=(int)(new_xy[1]+0.5); z=(int)(new_xy[2]+0.5); } void Line(const int x_1,const int y_1,const int x_2,const int y_2) { int color=getcolor( ); int x1=x_1; int y1=y_1; int x2=x_2; int y2=y_2; if(x_1>x_2) { x1=x_2; y1=y_2; x2=x_1; y2=y_1; } int dx=abs(x2-x1); int dy=abs(y2-y1); int inc_dec=((y2>=y1)?1:-1); if(dx>dy) { int two_dy=(2*dy); int two_dy_dx=(2*(dy-dx)); int p=((2*dy)-dx); int x=x1; int y=y1; putpixel(x,y,color); while(x<x2) { x++; if(p<0) p+=two_dy; else { y+=inc_dec; p+=two_dy_dx; } putpixel(x,y,color); } } else { int two_dx=(2*dx); int two_dx_dy=(2*(dx-dy)); int p=((2*dx)-dy); int x=x1; int y=y1; putpixel(x,y,color); while(y!=y2) { y+=inc_dec; if(p<0) p+=two_dx; else { x++; p+=two_dx_dy; } putpixel(x,y,color); } } }
[ "sakshijangra111000@gmail.com" ]
sakshijangra111000@gmail.com
9202c61280214629a80db4087715bcbfa5236aaa
5ed15f758da0aec98fbab593ea497656f92cba26
/Filters/HitOrMiss2D.hh
98b4f32cbf721e948c571388f939fecdf3daf795
[]
no_license
meroJamjoom/MDA_win
777fdb0d2d175ff73f28be8b8800f53924def899
bf14a47cdc54428620f26e479a19e9ccf0acf129
refs/heads/master
2020-05-22T06:43:01.534736
2016-09-14T01:39:46
2016-09-14T01:39:46
64,056,480
0
0
null
null
null
null
UTF-8
C++
false
false
5,065
hh
// ========================================================================== // $Id: HitOrMiss2D.hh 372 2009-09-20 18:57:38Z heidrich $ // hit-or-miss transform // ========================================================================== // License: Internal use at UBC only! External use is a copyright violation! // ========================================================================== // (C)opyright: // // 2007-, UBC // // Creator: heidrich () // Email: heidrich@cs.ubc.ca // ========================================================================== #ifndef FILTERS_HITORMISS_H #define FILTERS_HITORMISS_H /*! \file HitOrMiss2D.hh \brief hit-or-miss transform */ #ifdef _WIN32 // this header file must be included before all the others #define NOMINMAX #include <windows.h> #endif #include <string.h> #include "MDA/Threading/SMPJob.hh" #include "Filter.hh" namespace MDA { // forward declaration template <class T> class HitOrMissLineJob; /** \class HitOrMiss2D HitOrMiss2D.hh A 2D hit-and-miss transform (with radius 1) The class can be used as the usual 3x3 HOM transform, or as a general 3x3 pattern matching, with an arbitrary double-valued result depending on the neighborhood configuration. */ template<class T> class HitOrMiss2D: public Filter<T> { public: #if defined(_WIN32) || defined(_WIN64) #define bzero(p, l) memset(p, 0, l) #endif /** constructor from provided case table */ HitOrMiss2D( double *cases= NULL, bool _preserveMisses= false, T _hitValue= 1.0, T _missValue= 0.0 ) : preserveMisses( _preserveMisses ), hitValue( _hitValue ), missValue( _missValue ) { caseTable= new double[512]; if( cases!= NULL ) memcpy( caseTable, cases, 512*sizeof( double ) ); else bzero( caseTable, 512*sizeof( double ) ); } /** constructor from a traditional structural element (&mask) * this constructor can automatically generate symmetry cases if * desired. */ HitOrMiss2D( bool structureElem[9], bool mask[9], bool rotate= false, bool reflect= false, bool preserveMisses= false, T hitValue= 1.0, T missValue= 0.0 ); /** destructor */ ~HitOrMiss2D() { delete [] caseTable; } /** apply the filter to a number of dimensions and channels */ virtual bool apply( Array<T> &a, BoundaryMethod boundary, ChannelList &channels, AxisList &axes ); /** combine with another hit&miss transform by or-ing the case table */ inline HitOrMiss2D<T> &operator|=( const HitOrMiss2D<T> &other ) { for( unsigned i= 0 ; i< 512 ; i++ ) { caseTable[i]= (caseTable[i]> 0.0 || other.caseTable[i]> 0.0) ? 1.0:0.0; } return *this; } /** combine with another hit&miss transform by and-ing the case table */ inline HitOrMiss2D<T> &operator&=( const HitOrMiss2D<T> &other ) { for( unsigned i= 0 ; i< 512 ; i++ ) caseTable[i]= (caseTable[i]> 0.0 && other.caseTable[i]> 0.0) ? 1.0:0.0; return *this; } /** negate the case table */ inline HitOrMiss2D<T> &operator!() { for( unsigned i= 0 ; i< 512 ; i++ ) caseTable[i]= (caseTable[i] > 0.0) ? 0.0 : 1.0; return *this; } protected: /** convert a neighborhood bit vector to a table index */ unsigned neighborhoodToIndex( const bool neighborhood[9] ); /** convert a table index to a neighborhood bit vector */ void indexToNeighborhood( unsigned index, bool neighborhood[9] ); /** rotate a table index by 90 degrees ccw */ unsigned rotate( unsigned ind ); /** reflect a table index horizontally */ unsigned reflect( unsigned ind ); /** whether to preserve the original array content for a miss, or repace it with the miss value */ bool preserveMisses; /** new pixel value for hits */ T hitValue; /** new pixel value for misses (unless preserveMisses is true) */ T missValue; /** case table */ double *caseTable; /** apply to a single scanline */ void apply( bool* currLine, T* dst, unsigned long numElements ); /** HitOrMissLineJob can execute apply method */ friend class HitOrMissLineJob<T>; }; /** \class HitOrMissLineJob HitOrMiss2D.hh A single line in an HMT */ template<class T> class HitOrMissLineJob: public SMPJob { public: /** constructor */ inline HitOrMissLineJob( HitOrMiss2D<T> *_filter, bool* _currLine, T* _dst, unsigned long _numElements ) : SMPJob( _numElements*3 ), filter( _filter ), currLine( _currLine ), dst( _dst ), numElements( _numElements ) {} /** execute line job */ virtual void execute( int jobID ); protected: /** the filter */ HitOrMiss2D<T> *filter; /** pointer to a buffer containign the current line as bools */ bool *currLine; /** result pointer */ T* dst; unsigned long numElements; }; } /* namespace */ #endif /* FILTERS_HITORMISS_H */
[ "msjamjoom@effat.edu.sa" ]
msjamjoom@effat.edu.sa
4ced61035e0221dd9d710dd06ea014562f50610d
7174bbeaf7729dda4e529fb47a374cd959e91c05
/Ticket-Seller/seller.h
f880ff4d27d2fdcc56c2c8dc20f3e3574d9c661d
[]
no_license
bk44271/Ticketseller
77fd2a9c2ed357ec9c50c3ad7c00ad20b649de72
a22dbc10e378619ad4831bcb5181a4c43e8c006a
refs/heads/master
2022-10-18T03:15:54.242246
2020-06-15T08:43:15
2020-06-15T08:43:15
262,981,266
0
0
null
null
null
null
UTF-8
C++
false
false
297
h
#include <exception> using namespace std; #ifndef __seller_h__ #define __seller_h__ // #include "Transakcja.h" #include "user.h" class Transakcja; // class user; class seller; class seller: public user { public: Transakcja* _unnamed_Transakcja_; seller(); }; #endif
[ "noreply@github.com" ]
noreply@github.com
d3598f2f38bb87e0c1dc562b48d52e12d0dd23e4
f91d31ee12e6c4260e374b2a1e3d3b1967d956bf
/lib/cef/libcef_dll/ctocpp/menu_model_ctocpp.cc
52877e5b76b5bc53aee4262ad7bab670ec0e9249
[ "MIT" ]
permissive
vnmc/zephyros
631969bf6ec1b7cfd17cd62c125ffd2ef9e0ef8b
3f39c9168eebdb80ad1207acf6594668c277d0af
refs/heads/master
2021-04-09T17:49:34.837823
2019-01-18T14:10:22
2019-01-18T14:10:22
18,600,032
11
2
null
2018-04-08T11:51:57
2014-04-09T14:20:39
C++
UTF-8
C++
false
false
23,990
cc
// Copyright (c) 2017 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. // // --------------------------------------------------------------------------- // // This file was generated by the CEF translator tool. If making changes by // hand only do so within the body of existing method and function // implementations. See the translator.README.txt file in the tools directory // for more information. // #include "libcef_dll/cpptoc/menu_model_delegate_cpptoc.h" #include "libcef_dll/ctocpp/menu_model_ctocpp.h" // STATIC METHODS - Body may be edited by hand. CefRefPtr<CefMenuModel> CefMenuModel::CreateMenuModel( CefRefPtr<CefMenuModelDelegate> delegate) { // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Verify param: delegate; type: refptr_diff DCHECK(delegate.get()); if (!delegate.get()) return NULL; // Execute cef_menu_model_t* _retval = cef_menu_model_create( CefMenuModelDelegateCppToC::Wrap(delegate)); // Return type: refptr_same return CefMenuModelCToCpp::Wrap(_retval); } // VIRTUAL METHODS - Body may be edited by hand. bool CefMenuModelCToCpp::Clear() { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, clear)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->clear(_struct); // Return type: bool return _retval?true:false; } int CefMenuModelCToCpp::GetCount() { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, get_count)) return 0; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->get_count(_struct); // Return type: simple return _retval; } bool CefMenuModelCToCpp::AddSeparator() { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, add_separator)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->add_separator(_struct); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::AddItem(int command_id, const CefString& label) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, add_item)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Verify param: label; type: string_byref_const DCHECK(!label.empty()); if (label.empty()) return false; // Execute int _retval = _struct->add_item(_struct, command_id, label.GetStruct()); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::AddCheckItem(int command_id, const CefString& label) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, add_check_item)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Verify param: label; type: string_byref_const DCHECK(!label.empty()); if (label.empty()) return false; // Execute int _retval = _struct->add_check_item(_struct, command_id, label.GetStruct()); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::AddRadioItem(int command_id, const CefString& label, int group_id) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, add_radio_item)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Verify param: label; type: string_byref_const DCHECK(!label.empty()); if (label.empty()) return false; // Execute int _retval = _struct->add_radio_item(_struct, command_id, label.GetStruct(), group_id); // Return type: bool return _retval?true:false; } CefRefPtr<CefMenuModel> CefMenuModelCToCpp::AddSubMenu(int command_id, const CefString& label) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, add_sub_menu)) return NULL; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Verify param: label; type: string_byref_const DCHECK(!label.empty()); if (label.empty()) return NULL; // Execute cef_menu_model_t* _retval = _struct->add_sub_menu(_struct, command_id, label.GetStruct()); // Return type: refptr_same return CefMenuModelCToCpp::Wrap(_retval); } bool CefMenuModelCToCpp::InsertSeparatorAt(int index) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, insert_separator_at)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->insert_separator_at(_struct, index); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::InsertItemAt(int index, int command_id, const CefString& label) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, insert_item_at)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Verify param: label; type: string_byref_const DCHECK(!label.empty()); if (label.empty()) return false; // Execute int _retval = _struct->insert_item_at(_struct, index, command_id, label.GetStruct()); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::InsertCheckItemAt(int index, int command_id, const CefString& label) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, insert_check_item_at)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Verify param: label; type: string_byref_const DCHECK(!label.empty()); if (label.empty()) return false; // Execute int _retval = _struct->insert_check_item_at(_struct, index, command_id, label.GetStruct()); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::InsertRadioItemAt(int index, int command_id, const CefString& label, int group_id) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, insert_radio_item_at)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Verify param: label; type: string_byref_const DCHECK(!label.empty()); if (label.empty()) return false; // Execute int _retval = _struct->insert_radio_item_at(_struct, index, command_id, label.GetStruct(), group_id); // Return type: bool return _retval?true:false; } CefRefPtr<CefMenuModel> CefMenuModelCToCpp::InsertSubMenuAt(int index, int command_id, const CefString& label) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, insert_sub_menu_at)) return NULL; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Verify param: label; type: string_byref_const DCHECK(!label.empty()); if (label.empty()) return NULL; // Execute cef_menu_model_t* _retval = _struct->insert_sub_menu_at(_struct, index, command_id, label.GetStruct()); // Return type: refptr_same return CefMenuModelCToCpp::Wrap(_retval); } bool CefMenuModelCToCpp::Remove(int command_id) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, remove)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->remove(_struct, command_id); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::RemoveAt(int index) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, remove_at)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->remove_at(_struct, index); // Return type: bool return _retval?true:false; } int CefMenuModelCToCpp::GetIndexOf(int command_id) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, get_index_of)) return 0; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->get_index_of(_struct, command_id); // Return type: simple return _retval; } int CefMenuModelCToCpp::GetCommandIdAt(int index) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, get_command_id_at)) return 0; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->get_command_id_at(_struct, index); // Return type: simple return _retval; } bool CefMenuModelCToCpp::SetCommandIdAt(int index, int command_id) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, set_command_id_at)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->set_command_id_at(_struct, index, command_id); // Return type: bool return _retval?true:false; } CefString CefMenuModelCToCpp::GetLabel(int command_id) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, get_label)) return CefString(); // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute cef_string_userfree_t _retval = _struct->get_label(_struct, command_id); // Return type: string CefString _retvalStr; _retvalStr.AttachToUserFree(_retval); return _retvalStr; } CefString CefMenuModelCToCpp::GetLabelAt(int index) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, get_label_at)) return CefString(); // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute cef_string_userfree_t _retval = _struct->get_label_at(_struct, index); // Return type: string CefString _retvalStr; _retvalStr.AttachToUserFree(_retval); return _retvalStr; } bool CefMenuModelCToCpp::SetLabel(int command_id, const CefString& label) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, set_label)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Verify param: label; type: string_byref_const DCHECK(!label.empty()); if (label.empty()) return false; // Execute int _retval = _struct->set_label(_struct, command_id, label.GetStruct()); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::SetLabelAt(int index, const CefString& label) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, set_label_at)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Verify param: label; type: string_byref_const DCHECK(!label.empty()); if (label.empty()) return false; // Execute int _retval = _struct->set_label_at(_struct, index, label.GetStruct()); // Return type: bool return _retval?true:false; } CefMenuModel::MenuItemType CefMenuModelCToCpp::GetType(int command_id) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, get_type)) return MENUITEMTYPE_NONE; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute cef_menu_item_type_t _retval = _struct->get_type(_struct, command_id); // Return type: simple return _retval; } CefMenuModel::MenuItemType CefMenuModelCToCpp::GetTypeAt(int index) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, get_type_at)) return MENUITEMTYPE_NONE; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute cef_menu_item_type_t _retval = _struct->get_type_at(_struct, index); // Return type: simple return _retval; } int CefMenuModelCToCpp::GetGroupId(int command_id) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, get_group_id)) return 0; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->get_group_id(_struct, command_id); // Return type: simple return _retval; } int CefMenuModelCToCpp::GetGroupIdAt(int index) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, get_group_id_at)) return 0; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->get_group_id_at(_struct, index); // Return type: simple return _retval; } bool CefMenuModelCToCpp::SetGroupId(int command_id, int group_id) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, set_group_id)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->set_group_id(_struct, command_id, group_id); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::SetGroupIdAt(int index, int group_id) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, set_group_id_at)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->set_group_id_at(_struct, index, group_id); // Return type: bool return _retval?true:false; } CefRefPtr<CefMenuModel> CefMenuModelCToCpp::GetSubMenu(int command_id) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, get_sub_menu)) return NULL; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute cef_menu_model_t* _retval = _struct->get_sub_menu(_struct, command_id); // Return type: refptr_same return CefMenuModelCToCpp::Wrap(_retval); } CefRefPtr<CefMenuModel> CefMenuModelCToCpp::GetSubMenuAt(int index) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, get_sub_menu_at)) return NULL; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute cef_menu_model_t* _retval = _struct->get_sub_menu_at(_struct, index); // Return type: refptr_same return CefMenuModelCToCpp::Wrap(_retval); } bool CefMenuModelCToCpp::IsVisible(int command_id) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, is_visible)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->is_visible(_struct, command_id); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::IsVisibleAt(int index) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, is_visible_at)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->is_visible_at(_struct, index); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::SetVisible(int command_id, bool visible) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, set_visible)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->set_visible(_struct, command_id, visible); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::SetVisibleAt(int index, bool visible) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, set_visible_at)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->set_visible_at(_struct, index, visible); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::IsEnabled(int command_id) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, is_enabled)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->is_enabled(_struct, command_id); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::IsEnabledAt(int index) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, is_enabled_at)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->is_enabled_at(_struct, index); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::SetEnabled(int command_id, bool enabled) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, set_enabled)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->set_enabled(_struct, command_id, enabled); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::SetEnabledAt(int index, bool enabled) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, set_enabled_at)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->set_enabled_at(_struct, index, enabled); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::IsChecked(int command_id) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, is_checked)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->is_checked(_struct, command_id); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::IsCheckedAt(int index) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, is_checked_at)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->is_checked_at(_struct, index); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::SetChecked(int command_id, bool checked) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, set_checked)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->set_checked(_struct, command_id, checked); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::SetCheckedAt(int index, bool checked) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, set_checked_at)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->set_checked_at(_struct, index, checked); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::HasAccelerator(int command_id) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, has_accelerator)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->has_accelerator(_struct, command_id); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::HasAcceleratorAt(int index) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, has_accelerator_at)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->has_accelerator_at(_struct, index); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::SetAccelerator(int command_id, int key_code, bool shift_pressed, bool ctrl_pressed, bool alt_pressed) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, set_accelerator)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->set_accelerator(_struct, command_id, key_code, shift_pressed, ctrl_pressed, alt_pressed); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::SetAcceleratorAt(int index, int key_code, bool shift_pressed, bool ctrl_pressed, bool alt_pressed) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, set_accelerator_at)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->set_accelerator_at(_struct, index, key_code, shift_pressed, ctrl_pressed, alt_pressed); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::RemoveAccelerator(int command_id) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, remove_accelerator)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->remove_accelerator(_struct, command_id); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::RemoveAcceleratorAt(int index) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, remove_accelerator_at)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute int _retval = _struct->remove_accelerator_at(_struct, index); // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::GetAccelerator(int command_id, int& key_code, bool& shift_pressed, bool& ctrl_pressed, bool& alt_pressed) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, get_accelerator)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Translate param: shift_pressed; type: bool_byref int shift_pressedInt = shift_pressed; // Translate param: ctrl_pressed; type: bool_byref int ctrl_pressedInt = ctrl_pressed; // Translate param: alt_pressed; type: bool_byref int alt_pressedInt = alt_pressed; // Execute int _retval = _struct->get_accelerator(_struct, command_id, &key_code, &shift_pressedInt, &ctrl_pressedInt, &alt_pressedInt); // Restore param:shift_pressed; type: bool_byref shift_pressed = shift_pressedInt?true:false; // Restore param:ctrl_pressed; type: bool_byref ctrl_pressed = ctrl_pressedInt?true:false; // Restore param:alt_pressed; type: bool_byref alt_pressed = alt_pressedInt?true:false; // Return type: bool return _retval?true:false; } bool CefMenuModelCToCpp::GetAcceleratorAt(int index, int& key_code, bool& shift_pressed, bool& ctrl_pressed, bool& alt_pressed) { cef_menu_model_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, get_accelerator_at)) return false; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Translate param: shift_pressed; type: bool_byref int shift_pressedInt = shift_pressed; // Translate param: ctrl_pressed; type: bool_byref int ctrl_pressedInt = ctrl_pressed; // Translate param: alt_pressed; type: bool_byref int alt_pressedInt = alt_pressed; // Execute int _retval = _struct->get_accelerator_at(_struct, index, &key_code, &shift_pressedInt, &ctrl_pressedInt, &alt_pressedInt); // Restore param:shift_pressed; type: bool_byref shift_pressed = shift_pressedInt?true:false; // Restore param:ctrl_pressed; type: bool_byref ctrl_pressed = ctrl_pressedInt?true:false; // Restore param:alt_pressed; type: bool_byref alt_pressed = alt_pressedInt?true:false; // Return type: bool return _retval?true:false; } // CONSTRUCTOR - Do not edit by hand. CefMenuModelCToCpp::CefMenuModelCToCpp() { } template<> cef_menu_model_t* CefCToCpp<CefMenuModelCToCpp, CefMenuModel, cef_menu_model_t>::UnwrapDerived(CefWrapperType type, CefMenuModel* c) { NOTREACHED() << "Unexpected class type: " << type; return NULL; } #if DCHECK_IS_ON() template<> base::AtomicRefCount CefCToCpp<CefMenuModelCToCpp, CefMenuModel, cef_menu_model_t>::DebugObjCt = 0; #endif template<> CefWrapperType CefCToCpp<CefMenuModelCToCpp, CefMenuModel, cef_menu_model_t>::kWrapperType = WT_MENU_MODEL;
[ "christen@vanamco.com" ]
christen@vanamco.com
63c8250bce386f33cc827ae8335d9c43a5876b13
017f6714f8068d03f4078c4b6fa5680a7d966ed9
/ESEP/src/test/ft/master/system.h
3a98b5c980412c7e0cf814f4233dcc8627243a32
[]
no_license
davekessener/SE2-Project
fa635fc8be7103d5f2d28c9fb2da6c0f9678585d
8099119cddfc7dc169b16c1f41656157b5ca2866
refs/heads/master
2020-03-21T05:50:00.446941
2018-06-21T12:07:09
2018-06-21T12:07:09
138,183,878
1
0
null
null
null
null
UTF-8
C++
false
false
1,728
h
#ifndef ESEP_TEST_FN_MASTER_SYSTEM_H #define ESEP_TEST_FN_MASTER_SYSTEM_H #include <array> #include <vector> #include "lib/writer.h" #include "lib/reader.h" #include "communication/packet.h" #include "test/ft/master/station.h" #include "master/master.h" namespace esep { namespace test { namespace functional { namespace m { class System : private communication::IRecipient { typedef std::vector<std::string> args_t; typedef communication::Packet Packet; typedef communication::Packet_ptr Packet_ptr; typedef communication::Message Message; typedef Packet::Location Location; enum { S_M1_START, S_M1_HS, S_M1_SWITCH, S_M1_END, S_M2_START, S_M2_HS, S_M2_SWITCH, S_M2_END, S_STATIONS }; public: System(lib::Reader_ptr, lib::Writer_ptr); ~System( ); void run( ); private: void flush( ); void accept(Packet_ptr) override; void printHelp(const args_t&); void quit(const args_t&); void newItem(const args_t&); void printStatus(const args_t&); void switch2Run(const args_t&); void advance(const args_t&); void list(const args_t&); void remove(const args_t&); private: lib::Reader_ptr mIn; lib::Writer_ptr mOut; std::array<Station *, S_STATIONS> mStations; bool mRunning; master::Master mMaster; std::vector<Packet_ptr> mInBuf, mOutBuf; bool mBeltActive[2]; Item::id_t mNextItemID; std::vector<Item_ptr> mOldItems; std::map<Item::id_t, int> mItems; }; } } } } #endif
[ "davekessener@gmail.com" ]
davekessener@gmail.com
2dbbfe17f2e2761d18fb4844e81ae3c1c330cbbc
b071923654ae5cb144ab35fcde0814fcb230ead4
/5/Priority Queue/pqueue-heap.cpp
1e3c018b4d27f2879e833b7eb39d3b57fcece494
[]
no_license
loc-trinh/Programming-Abstraction
40e057b165a6ffffa66c7d9bde318212b88f4a64
0f61953ed722a392a2056337e5f2c9a5fa3a5dd1
refs/heads/master
2020-12-26T04:05:16.676034
2014-09-20T07:38:47
2014-09-20T07:38:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,955
cpp
/************************************************************* * File: pqueue-heap.cpp * * Implementation file for the HeapPriorityQueue * class. */ #include "pqueue-heap.h" #include "error.h" HeapPriorityQueue::HeapPriorityQueue() { arry = new string[10]; numAllocated = 10; numUsed = 0; } HeapPriorityQueue::~HeapPriorityQueue() { delete[] arry; } int HeapPriorityQueue::size() { return numUsed; } bool HeapPriorityQueue::isEmpty() { return (numUsed == 0); } void HeapPriorityQueue::Swap(string& cell1, string& cell2) { string temp = cell1; cell1 = cell2; cell2 = temp; } void HeapPriorityQueue::bubbleUp(int index){ int parent; if(index == 0) return; else if(index%2 == 0) parent = index/2-1; else parent = index/2; if(arry[index] < arry[parent]) Swap(arry[index], arry[parent]); else return; bubbleUp(parent); } void HeapPriorityQueue::bubbleDown(int index){ int child, child1 = index*2+1, child2 = index*2+2; if(child1 >= size() && child2 >= size()) return; else if(child1 < size() && child2 >= size()) child = child1; else if(child1 >= size() && child2 < size()) child = child2; else{ if(arry[child1] <= arry[child2]) child = child1; else child = child2; } if(arry[child] < arry[index]) Swap(arry[child], arry[index]); else return; bubbleDown(child); } void HeapPriorityQueue::enqueue(string value) { if(numUsed == numAllocated) expandArry(); arry[numUsed++] = value; bubbleUp(numUsed-1); } void HeapPriorityQueue::expandArry() { string *newArry = new string[numAllocated*2]; for(int i = 0; i < numUsed; i++) newArry[i] = arry[i]; delete[] arry; arry = newArry; numAllocated *= 2; } string HeapPriorityQueue::peek() { if(isEmpty()) error("empty queue"); else return arry[0]; } string HeapPriorityQueue::dequeueMin() { if(isEmpty()) error("empty queue"); else{ string word = arry[0]; Swap(arry[0], arry[size()-1]); numUsed--; bubbleDown(0); return word; } }
[ "loctrinh@Locs-MacBook-Pro.local" ]
loctrinh@Locs-MacBook-Pro.local
03b8e83092199589f6ebc0df0833520a5fa964cb
970257a171e54b56ee482c8e010dd1f88f5f946e
/Strela/TStrawCham.cxx
3387f119d649110a6b3c99a9a814c60ab135f677
[]
no_license
musinsky/strela
81b40988d5ef2cf61b29cfbc935b8ade8ec88b4a
c1d97748003dbc73b12f00963ac865692e78f23e
refs/heads/master
2021-07-22T19:18:11.953567
2020-06-24T22:20:00
2020-06-24T22:20:00
1,075,343
0
0
null
null
null
null
UTF-8
C++
false
false
13,436
cxx
// @Author Jan Musinsky <musinsky@gmail.com> // @Date 25 Nov 2016 #include <TSQLServer.h> #include <TSQLResult.h> #include <TSQLRow.h> #include <TMath.h> #include <TH1.h> #include <TROOT.h> #include <TCanvas.h> #include "TStrawCham.h" #include "TStrawTracker.h" #include "TGemEvent.h" #include "TEventTdc.h" #include "THitTdc.h" #include "TStrawMulti.h" #include "TVME.h" Int_t TStrawCham::fgTrigNadc = -1; Int_t TStrawCham::fgShiftAdc = 0; Int_t TStrawCham::fgTracking = 1; Int_t TStrawCham::fgIter = 0; ClassImp(TStrawCham) //______________________________________________________________________________ TStrawCham::TStrawCham() { // Info("TStrawCham", "Default constructor"); fTrackers = 0; fLayers = 0; fMulties = 0; fTubes = 0; fTubesI = 0; } //______________________________________________________________________________ TStrawCham::TStrawCham(const char *name, const char *title) : TStrelaBase(name, title) { // Info("TStrawCham", "Normal constructor"); fTrackers = 0; fLayers = 0; fMulties = 0; fTubes = 0; fTubesI = 0; fContainer = new TClonesArray("TStrawTrack", 50); fBranchName = "tracks"; } //______________________________________________________________________________ TStrawCham::~TStrawCham() { Info("~TStrawCham", "Destructor"); DeleteArrays(); } //______________________________________________________________________________ void TStrawCham::Print(Option_t *option) const { if (!fLayers) return; TStrawTracker *tracker = 0; TStrawLayer *layer; TStrawTube *tube; TIter nextLayer(fLayers); while ((layer = (TStrawLayer *)nextLayer())) { if (tracker != layer->GetTracker()) { tracker = layer->GetTracker(); Printf("=======> %s <=======", tracker->GetName()); } Printf("[%2d] %s", layer->GetNumb(), layer->GetName()); if (strcmp(option, "all") || !fTubes) continue; for (Int_t i = 0; i < layer->Tubes()->GetSize(); i++) { tube = (TStrawTube *)layer->Tubes()->At(i); Printf(" %2d) %s %8.2f %8.2f (%3d)", i + 1, gVME->GetChannelInfo(tube->GetNadc()), tube->GetCenter(), tube->GetZ(), fTubes->BinarySearch(tube)); } } Printf("\ntrig %s", gVME->GetChannelInfo(fgTrigNadc)); } //______________________________________________________________________________ void TStrawCham::DeleteArrays() { if (fTrackers) fTrackers->Delete(); delete fTrackers; fTrackers = 0; if (fMulties) fMulties->Delete(); delete fMulties; fMulties = 0; if (fLayers) fLayers->Delete(); // at last delete (recursive) tubes & layers delete fLayers; fLayers = 0; delete fTubes; fTubes = 0; delete [] fTubesI; } //______________________________________________________________________________ Bool_t TStrawCham::ReadSQL(TSQLServer *ser) { DeleteArrays(); Clear(); const char *table; TSQLResult *res; TSQLRow *row; TStrawTracker *tracker = 0; TStrawLayer *layer = 0; TStrawTube *tube = 0; Int_t ntubes = 0; // make trackers, layers, tubes table = "layers"; res = ser->Query(Form("SELECT `Tracker`, `Numb`, `Name`, `NChan`, `Delta`, `Direct`, `Z`, `Shift`, `Range` FROM `%s` WHERE `Tracker` > 0 ORDER BY `Tracker`, `Numb`", table)); // important only "ORDER BY Tracker" if (res) { if (res->GetRowCount() > 0) { fTrackers = new TList(); fLayers = new TList(); Int_t newId = 0; // "WHERE Tracker > 0" while ((row = res->Next())) { // make trackers if (newId != atoi(row->GetField(0))) { newId = atoi(row->GetField(0)); tracker = new TStrawTracker(newId); fTrackers->Add(tracker); } // make layers, tubes layer = new TStrawLayer(atoi(row->GetField(1)), row->GetField(2)); fLayers->Add(layer); layer->MakeTubes(atoi(row->GetField(3)), atof(row->GetField(4)), atoi(row->GetField(5))); layer->SetZ(atof(row->GetField(6))); layer->Shift(atof(row->GetField(7))); layer->SetRange(atof(row->GetField(8))); layer->SetTracker(tracker); layer->SetTitle(Form("from %s", tracker->GetName())); ntubes += layer->Tubes()->GetSize(); delete row; } } delete res; } if (!fTrackers) { Info("ReadSQL", "working without any straws"); delete ser; return kFALSE; } // set tubes properties table = "channels"; fMulties = new TList(); // "manually" add tubes fTubes = new TObjArray(ntubes); TIter next(fLayers); while ((layer = (TStrawLayer *)next())) { for (Int_t i = 0; i < layer->Tubes()->GetSize(); i++) { tube = (TStrawTube *)layer->Tubes()->At(i); fTubes->Add(tube); // order is not imoportant, will be sorted res = ser->Query(Form("SELECT `Nadc`, `T0`, `TMax` FROM `%s` WHERE `DetNumb` = %d AND `DetChan` = %d", table, layer->GetNumb(), i+1)); if (res) { Int_t nchan = res->GetRowCount(); if (nchan == 1) { row = res->Next(); tube->SetNadc(atoi(row->GetField(0))); tube->SetT0(atoi(row->GetField(1))); tube->SetTMinMax(atoi(row->GetField(1)), atoi(row->GetField(2))); delete row; } else if (nchan == 0) Warning("ReadSQL", "channel %02d, %s(%02d) %s does not exist", i+1, layer->GetName(), layer->GetNumb(), layer->GetTitle()); else Warning("ReadSQL", "channel %02d, %s(%02d) %s is not unique", i+1, layer->GetName(), layer->GetNumb(), layer->GetTitle()); delete res; } } } delete ser; fTubes->Sort(); // sort by increasing Nadc if (fTubes->GetEntries() != fTubes->GetEntriesFast()) { Error("ReadSQL", "problem with fTubes entries/size"); return kFALSE; } ntubes = fTubes->GetEntriesFast(); fTubesI = new Int_t[ntubes]; for (Int_t i = 0; i < ntubes; i++) fTubesI[i] = GetTube(i)->GetNadc(); TIter nextt(fTrackers); while ((tracker = (TStrawTracker *)nextt())) tracker->AllocateLayers(); return kTRUE; } //______________________________________________________________________________ TStrawTube *TStrawCham::SearchTube(Int_t nadc) const { Int_t pos = TMath::BinarySearch(fTubes->GetEntriesFast(), fTubesI, nadc); if ((pos >= 0) && (GetTube(pos)->GetNadc() == nadc)) return GetTube(pos); // Error("SearchTube", "nadc %4d not found", nadc); return 0; } //______________________________________________________________________________ void TStrawCham::SetTubesTimes(Int_t x, Int_t t1, Int_t t2) const { Int_t ntubes = fTubes->GetEntriesFast(); static Bool_t first = kTRUE; static TArrayI defaultT0(ntubes); if (first) { for (Int_t i = 0; i < ntubes; i++) defaultT0[i] = GetTube(i)->GetT0(); first = kFALSE; } TStrawTube *tube; Int_t t0; for (Int_t i = 0; i < ntubes; i++) { tube = GetTube(i); t0 = tube->GetT0(); // TMin, TMax if (x == 0) tube->SetTMinMax(t1, t2, kFALSE); // directly else if (x == 1) tube->SetTMinMax(t1, t2, kTRUE); // from previous value else if (x == 2) tube->SetTMinMax(t0 + t1, t0 + t2); // from T0 // T0 else if ((x == 3) && (t2 == 0)) tube->SetT0(t1); // directly else if (x == -1) tube->SetT0(defaultT0[i]); // default else Warning("SetTubesTimes", "wrong parameter(s)"); } } //______________________________________________________________________________ void TStrawCham::AnalyzeBegin() { ; } //______________________________________________________________________________ void TStrawCham::AnalyzeEntry() { Clear(); TIter next(fTrackers); TStrawTracker *tracker; while ((tracker = (TStrawTracker *)next())) tracker->ResetHits(); for (Int_t it = 0; it < fTubes->GetEntriesFast(); it++) GetTube(it)->ResetHits(); TEventTdc *event = gStrela->EventTdc(); THitTdc *hit; Int_t channel, time, delta, pos, trigTime = 0; // must be 0 TStrawTube *tube; /* // first find trigger channel (only if is necessary) // in mostly cases trigger is first hit (quick) if (fgTrigNadc > 0) { Bool_t foundTrig = kFALSE; for (Int_t ih = 0; ih < event->GetNHits(); ih++) { hit = event->GetHitTdc(ih); if (hit->GetChannel() == fgTrigNadc) { trigTime = hit->GetTime() - fgShiftAdc; foundTrig = kTRUE; break; } } if (!foundTrig) { Warning("AnalyzeEntry", "not found trigger hit"); Printf("%s", gStrela->GetEventInfo()); return; } } */ if (fgTrigNadc > 0) trigTime = event->GetTrigTime() - fgShiftAdc; for (Int_t ih = 0; ih < event->GetNHits(); ih++) { hit = event->GetHitTdc(ih); channel = hit->GetChannel(); time = hit->GetTime(); delta = hit->GetDelta(); time -= trigTime; // only if trigTime, otherwise time without change pos = TMath::BinarySearch(fTubes->GetEntriesFast(), fTubesI, channel); if (pos < 0) continue; tube = GetTube(pos); if (channel != tube->GetNadc()) continue; tube->AddHit(); if (tube->GetNHits() > TStrawTube::GetOnlyFirstNHits()) continue; // only first N hits of tube tube->HisTime1()->Fill(time); if (delta != 0) tube->HisDelta()->Fill(delta); if (tube->IsDisabled()) continue; if ((time < tube->GetTMin()) || (time > tube->GetTMax())) continue; tube->GetTracker()->AddHit(pos, tube->TInT0(time)); } if (fgTracking == 0) return; next.Reset(); if (fgTracking == -1) while ((tracker = (TStrawTracker *)next())) tracker->PureTrackHits(); else while ((tracker = (TStrawTracker *)next())) tracker->FindTracks(); } //______________________________________________________________________________ void TStrawCham::AnalyzeTerminate() { EfficiencyTubes(); TCanvas *c; c = (TCanvas *)gROOT->GetListOfCanvases()->FindObject("c_tracker"); if (c) FindTracker(c->GetTitle())->ShowHistograms(); c = (TCanvas *)gROOT->GetListOfCanvases()->FindObject("c_tube"); if (c) { TString title = c->GetTitle(); if (title.IsNull()) return; // see TStrawTube::GetTitle and TVME::GetChannelInfo title.Remove(0, 6); title.Remove(4, 99); SearchTube(title.Atoi())->ShowHistograms(); } } //______________________________________________________________________________ void TStrawCham::IterNext(Int_t ne) { if (!fMulties || fMulties->IsEmpty()) { Warning("IterFirst", "working without any multies"); return; } // gStrela->HistoManager("tube_*", "reset"); // gStrela->HistoManager("tracker_*", "reset"); gStrela->HistoManager("*", "reset"); if ((ne == 0) || (ne > gStrela->GetEntries())) ne = gStrela->GetEntries(); Printf("Iteration number = %2d, entries = %d", fgIter, ne); AnalyzeBegin(); for (Int_t i = 0; i < ne; i++) { gStrela->GetChain()->GetEntry(i); AnalyzeEntry(); } AnalyzeTerminate(); TIter next(fMulties); TStrawMulti *multi; while ((multi = (TStrawMulti *)next())) multi->IterNext(); fgIter++; } //______________________________________________________________________________ void TStrawCham::EfficiencyTubes() const { TIter next(fTubes); TStrawTube *tube; while ((tube = (TStrawTube *)next())) { tube->HisEffi()->Divide(tube->HisDis1(), tube->HisDis2(), 1, 1, "b"); tube->HisEffi()->SetMaximum(1.1); tube->HisEffi()->SetMinimum(0.0); tube->HisEffi()->SetStats(kFALSE); } } //______________________________________________________________________________ void TStrawCham::AnalyzeEntryGemEvent() { Clear(); TIter next(fTrackers); TStrawTracker *tracker; while ((tracker = (TStrawTracker *)next())) tracker->ResetHits(); for (Int_t it = 0; it < fTubes->GetEntriesFast(); it++) GetTube(it)->ResetHits(); TGemEvent *gemEvent = gStrela->GemEvent(); TAdcHit1 *adcHit1; Int_t nadc, adc, pos, trigAdc = 0; // must be 0 TStrawTube *tube; // first find trigger tdc (quick), in mostly cases trigger is first hit // starting from the seance 2009_12 is no longer necessary if (fgTrigNadc > 0) { Bool_t findTrig = kFALSE; for (Int_t ih = 0; ih < gemEvent->GetNumOfAdcHits1(); ih++) { adcHit1 = gemEvent->GetAdcHit1(ih); if (adcHit1->GetNadc() == fgTrigNadc) { trigAdc = adcHit1->GetAdc() - fgShiftAdc; findTrig = kTRUE; break; } } if (!findTrig) { Warning("AnalyzeEntry", "not found trigger hit"); Printf("%s", gStrela->GetEventInfo()); return; } } for (Int_t ih = 0; ih < gemEvent->GetNumOfAdcHits1(); ih++) { adcHit1 = gemEvent->GetAdcHit1(ih); nadc = adcHit1->GetNadc(); adc = adcHit1->GetAdc(); adc -= trigAdc; // (only if exist trigAdc, otherwise adc without change) pos = TMath::BinarySearch(fTubes->GetEntriesFast(), fTubesI, nadc); if (pos < 0) continue; tube = GetTube(pos); if (nadc != tube->GetNadc()) continue; tube->AddHit(); if (tube->GetNHits() > TStrawTube::GetOnlyFirstNHits()) continue; // only first N hits of tube tube->HisTime1()->Fill(adc); if (tube->IsDisabled()) continue; if ((adc < tube->GetTMin()) || (adc > tube->GetTMax())) continue; tube->GetTracker()->AddHit(pos, tube->TInT0(adc)); } if (fgTracking == 0) return; next.Reset(); if (fgTracking == -1) while ((tracker = (TStrawTracker *)next())) tracker->PureTrackHits(); else while ((tracker = (TStrawTracker *)next())) tracker->FindTracks(); }
[ "musinsky@gmail.com" ]
musinsky@gmail.com
a10af47f96081d8a1dd4ee7e24217d055b600912
9c451121eaa5e0131110ad0b969d75d9e6630adb
/Codeforces/Codeforces Round 879/1834C - Game with Reversing.cpp
716ba4204f96b6d5ea76db8c0da57e977bd39135
[]
no_license
tokitsu-kaze/ACM-Solved-Problems
69e16c562a1c72f2a0d044edd79c0ab949cc76e3
77af0182401904f8d2f8570578e13d004576ba9e
refs/heads/master
2023-09-01T11:25:12.946806
2023-08-25T03:26:50
2023-08-25T03:26:50
138,472,754
5
1
null
null
null
null
UTF-8
C++
false
false
4,763
cpp
#include <bits/stdc++.h> using namespace std; namespace fastIO{ #define BUF_SIZE 100000 #define OUT_SIZE 100000 //fread->read bool IOerror=0; //inline char nc(){char ch=getchar();if(ch==-1)IOerror=1;return ch;} inline char nc(){ static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE; if(p1==pend){ p1=buf;pend=buf+fread(buf,1,BUF_SIZE,stdin); if(pend==p1){IOerror=1;return -1;} } return *p1++; } inline bool blank(char ch){return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';} template<class T> inline bool read(T &x){ bool sign=0;char ch=nc();x=0; for(;blank(ch);ch=nc()); if(IOerror)return false; if(ch=='-')sign=1,ch=nc(); for(;ch>='0'&&ch<='9';ch=nc())x=x*10+ch-'0'; if(sign)x=-x; return true; } inline bool read(double &x){ bool sign=0;char ch=nc();x=0; for(;blank(ch);ch=nc()); if(IOerror)return false; if(ch=='-')sign=1,ch=nc(); for(;ch>='0'&&ch<='9';ch=nc())x=x*10+ch-'0'; if(ch=='.'){ double tmp=1; ch=nc(); for(;ch>='0'&&ch<='9';ch=nc())tmp/=10.0,x+=tmp*(ch-'0'); } if(sign)x=-x; return true; } inline bool read(char *s){ char ch=nc(); for(;blank(ch);ch=nc()); if(IOerror)return false; for(;!blank(ch)&&!IOerror;ch=nc())*s++=ch; *s=0; return true; } inline bool read_line(char *s){ char ch=nc(); for(;blank(ch);ch=nc()); if(IOerror)return false; for(;ch!='\n'&&!IOerror;ch=nc())*s++=ch; *s=0; return true; } inline bool read(char &c){ for(c=nc();blank(c);c=nc()); if(IOerror){c=-1;return false;} return true; } template<class T,class... U>bool read(T& h,U&... t){return read(h)&&read(t...);} #undef OUT_SIZE #undef BUF_SIZE }; using namespace fastIO; /************* debug begin *************/ string to_string(string s){return '"'+s+'"';} string to_string(const char* s){return to_string((string)s);} string to_string(const bool& b){return(b?"true":"false");} template<class T>string to_string(T x){ostringstream sout;sout<<x;return sout.str();} template<class A,class B>string to_string(pair<A,B> p){return "("+to_string(p.first)+", "+to_string(p.second)+")";} template<class A>string to_string(const vector<A> v){ int f=1;string res="{";for(const auto x:v){if(!f)res+= ", ";f=0;res+=to_string(x);}res+="}"; return res; } void debug_out(){puts("");} template<class T,class... U>void debug_out(const T& h,const U&... t){cout<<" "<<to_string(h);debug_out(t...);} #ifdef tokitsukaze #define debug(...) cout<<"["<<#__VA_ARGS__<<"]:",debug_out(__VA_ARGS__); #else #define debug(...) 233; #endif /************* debug end *************/ #define mem(a,b) memset((a),(b),sizeof(a)) #define MP make_pair #define pb push_back #define fi first #define se second #define sz(x) ((int)x.size()) #define all(x) x.begin(),x.end() #define sqr(x) ((x)*(x)) typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> PII; typedef pair<ll,ll> PLL; typedef pair<int,ll> PIL; typedef pair<ll,int> PLI; typedef vector<int> VI; typedef vector<ll> VL; typedef vector<PII> VPII; typedef vector<PLL> VPLL; typedef vector<string> VS; typedef vector<VI> VVI; typedef vector<VL> VVL; typedef vector<VS> VVS; typedef vector<VPII> VVPII; /************* define end *************/ #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/hash_policy.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; /********* gp_hash_table end **********/ void read(int *x,int l,int r){for(int i=l;i<=r;i++) read(x[i]);} void read(ll *x,int l,int r){for(int i=l;i<=r;i++) read(x[i]);} void read(double *x,int l,int r){for(int i=l;i<=r;i++) read(x[i]);} void println(VI x){for(int i=0;i<sz(x);i++) printf("%d%c",x[i]," \n"[i==sz(x)-1]);} void println(VL x){for(int i=0;i<sz(x);i++) printf("%lld%c",x[i]," \n"[i==sz(x)-1]);} void println(int *x,int l,int r){for(int i=l;i<=r;i++) printf("%d%c",x[i]," \n"[i==r]);} void println(ll *x,int l,int r){for(int i=l;i<=r;i++) printf("%lld%c",x[i]," \n"[i==r]);} /*************** IO end ***************/ void go(); int main(){ #ifdef tokitsukaze freopen("TEST.txt","r",stdin); #endif go();return 0; } const int INF=0x3f3f3f3f; const ll LLINF=0x3f3f3f3f3f3f3f3fLL; const double PI=acos(-1.0); const double eps=1e-6; const int MAX=2e5+10; const ll mod=1e9+7; /********************************* head *********************************/ char a[MAX],b[MAX]; void go() { int t,n,i,ans,now; read(t); while(t--) { read(n); read(a+1); read(b+1); now=0; for(i=1;i<=n;i++) now+=(a[i]!=b[i]); if(now==0) { puts("0"); continue; } if(now&1) ans=(now-1)*2+1; else ans=now*2; reverse(a+1,a+1+n); now=0; for(i=1;i<=n;i++) now+=(a[i]!=b[i]); if(now==0) { puts("2"); continue; } if(now&1) ans=min(ans,now*2); else ans=min(ans,(now-1)*2+1); printf("%d\n",ans); } }
[ "861794979@qq.com" ]
861794979@qq.com
9e3ccc326ce40f1393e216e2a62054bbfe9189ec
8860cf601d96fb838d0c9914abc9fa142325be2e
/Automatic-rotating-fan/project_main/person_detector.ino
c6f8ec9c0cee6f3a48d1bbe1ccded62147f4c6a8
[]
no_license
DNHewavitharana/Test_Tax_Payment_Application
84f46c6bd780c01d432d352c0f075bd58fedff34
ad497aaa51933b8685291ad5aee1c1104699662c
refs/heads/master
2021-01-01T06:36:57.679157
2017-09-26T10:19:46
2017-09-26T10:19:46
97,470,213
0
0
null
null
null
null
UTF-8
C++
false
false
1,296
ino
void person_detect_mode(){ while(state2){ if (pir_L()== HIGH && pir_M()== LOW && pir_R()== LOW ){ led_blink(); motor_fixed_rotate(motor_control, angle); } else if(pir_L()== LOW && pir_M()== HIGH && pir_R()== LOW){ led_blink(); motor_fixed_rotate(motor_control,angle); } else if(pir_L()== LOW && pir_M()== LOW && pir_R()== HIGH){ led_blink(); motor_fixed_rotate(motor_control,angle); } else if(pir_L()== HIGH && pir_M()== HIGH && pir_R()== LOW){ led_blink(); motor_rotation_two_areas(motor_control, angle_start, angle_end); } else if(pir_L()== LOW && pir_M()== HIGH && pir_R()== HIGH){ led_blink(); motor_rotation_two_areas(motor_control, angle_start, angle_end); } else if(pir_L()== HIGH && pir_M()== LOW && pir_R()== HIGH){ led_blink(); motor_rotation_two_areas(motor_control, angle_start,angle_end); } else if(pir_L()== HIGH && pir_M()== HIGH && pir_R()== HIGH){ led_blink(); motor_rotation_three_areas(motor_control, angle_start, angle_mid, angle_end); }else{ digitalWrite(led,LOW); } } } void angle_calculator(){ angle_start=30; angle_end=60; angle_mid=45; angle= 90; }
[ "dilshan.15@cse.mrt.ac.lk" ]
dilshan.15@cse.mrt.ac.lk
38d49c36ddae2e17cb781ea1e11269a2daef6f53
99249e222a2f35ac11a7fd93bff10a3a13f6f948
/ros2_mod_ws/build/robobo_msgs_aux/rosidl_typesupport_introspection_cpp/robobo_msgs_aux/msg/set_led_topic__type_support.cpp
0751c644e9ae3952652e8c7d9e9631a3a47902c2
[ "Apache-2.0" ]
permissive
mintforpeople/robobo-ros2-ios-port
87aec17a0c89c3fc5a42411822a18f08af8a5b0f
1a5650304bd41060925ebba41d6c861d5062bfae
refs/heads/master
2020-08-31T19:41:01.124753
2019-10-31T16:01:11
2019-10-31T16:01:11
218,764,551
1
0
null
null
null
null
UTF-8
C++
false
false
3,497
cpp
// generated from rosidl_typesupport_introspection_cpp/resource/msg__type_support.cpp.em // generated code does not contain a copyright notice // providing offsetof() #include <cstddef> #include <vector> #include "rosidl_generator_c/message_type_support_struct.h" #include "rosidl_typesupport_cpp/message_type_support.hpp" #include "rosidl_typesupport_interface/macros.h" #include "robobo_msgs_aux/msg/set_led_topic__struct.hpp" #include "rosidl_typesupport_introspection_cpp/field_types.hpp" #include "rosidl_typesupport_introspection_cpp/identifier.hpp" #include "rosidl_typesupport_introspection_cpp/message_introspection.hpp" #include "rosidl_typesupport_introspection_cpp/message_type_support_decl.hpp" #include "rosidl_typesupport_introspection_cpp/visibility_control.h" namespace robobo_msgs_aux { namespace msg { namespace rosidl_typesupport_introspection_cpp { static const ::rosidl_typesupport_introspection_cpp::MessageMember SetLedTopic_message_member_array[2] = { { "id", // name ::rosidl_typesupport_introspection_cpp::ROS_TYPE_STRING, // type 0, // upper bound of string nullptr, // members of sub message false, // is array 0, // array size false, // is upper bound offsetof(robobo_msgs_aux::msg::SetLedTopic, id), // bytes offset in struct nullptr, // default value nullptr, // size() function pointer nullptr, // get_const(index) function pointer nullptr, // get(index) function pointer nullptr // resize(index) function pointer }, { "color", // name ::rosidl_typesupport_introspection_cpp::ROS_TYPE_STRING, // type 0, // upper bound of string nullptr, // members of sub message false, // is array 0, // array size false, // is upper bound offsetof(robobo_msgs_aux::msg::SetLedTopic, color), // bytes offset in struct nullptr, // default value nullptr, // size() function pointer nullptr, // get_const(index) function pointer nullptr, // get(index) function pointer nullptr // resize(index) function pointer } }; static const ::rosidl_typesupport_introspection_cpp::MessageMembers SetLedTopic_message_members = { "robobo_msgs_aux", // package name "SetLedTopic", // message name 2, // number of fields sizeof(robobo_msgs_aux::msg::SetLedTopic), SetLedTopic_message_member_array // message members }; static const rosidl_message_type_support_t SetLedTopic_message_type_support_handle = { ::rosidl_typesupport_introspection_cpp::typesupport_identifier, &SetLedTopic_message_members, get_message_typesupport_handle_function, }; } // namespace rosidl_typesupport_introspection_cpp } // namespace msg } // namespace robobo_msgs_aux namespace rosidl_typesupport_introspection_cpp { template<> ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC const rosidl_message_type_support_t * get_message_type_support_handle<robobo_msgs_aux::msg::SetLedTopic>() { return &::robobo_msgs_aux::msg::rosidl_typesupport_introspection_cpp::SetLedTopic_message_type_support_handle; } } // namespace rosidl_typesupport_introspection_cpp #ifdef __cplusplus extern "C" { #endif ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC const rosidl_message_type_support_t * ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_introspection_cpp, robobo_msgs_aux, msg, SetLedTopic)() { return &::robobo_msgs_aux::msg::rosidl_typesupport_introspection_cpp::SetLedTopic_message_type_support_handle; } #ifdef __cplusplus } #endif
[ "lfllamas93@gmail.com" ]
lfllamas93@gmail.com
d72c98c022d1b85b81e9b491fc5bf04054c8dd78
d53314137d9f8fc0a1a954632164e6bb72398d8b
/network/reflect/Enum.cpp
802e1358ce0622eda44444ae24e02e0c0190219d
[ "MIT" ]
permissive
hbccdf/network-core
81f47a4195610427be15f6945b8e4842a62b4242
37cbf03829bffd9c0903a1e755ce1f96f46e3dfa
refs/heads/master
2022-11-24T16:37:15.267219
2020-08-04T08:16:02
2020-08-04T08:16:02
284,646,374
0
0
null
null
null
null
UTF-8
C++
false
false
1,726
cpp
#include "Enum.h" #include "Variant.h" namespace cytx { namespace meta { Enum::Enum(const EnumBase *base) : base_( base ) { } bool Enum::IsValid(void) const { return base_ != nullptr; } Enum::operator bool(void) const { return base_ != nullptr; } bool Enum::operator==(const Enum &rhs) const { return base_ == rhs.base_; } bool Enum::operator!=(const Enum &rhs) const { return base_ != rhs.base_; } std::string Enum::GetName(void) const { return base_ ? base_->GetName( ) : std::string( ); } Type Enum::GetType(void) const { return base_ ? base_->GetType( ) : Type::Invalid( ); } Type Enum::GetParentType(void) const { return base_ ? base_->GetParentType( ) : Type::Invalid( ); } Type Enum::GetUnderlyingType(void) const { return base_ ? base_->GetUnderlyingType( ) : Type::Invalid( ); } std::vector<std::string> Enum::GetKeys(void) const { return base_ ? base_->GetKeys( ) : std::vector<std::string>( ); } std::vector<Variant> Enum::GetValues(void) const { return base_ ? base_->GetValues( ) : std::vector<Variant>( ); } std::string Enum::GetKey(const Argument &value) const { return base_ ? base_->GetKey( value ) : std::string( ); } Variant Enum::GetValue(const std::string &key) const { return base_ ? base_->GetValue( key ) : Variant( ); } } }
[ "xing.wang@cytxcn.com" ]
xing.wang@cytxcn.com
c2610f493a6baa36eeafbd8a83e92a2f8e811cd7
d35797da2cce95700d28b4ba5f6ce9656e0e8d40
/SousVide.h
17be8840909adb9c5e4a3266d88b481d934adcad
[ "MIT" ]
permissive
rogerzrc/arduino-sous-vide-library
bd18bff823018f47d780664b388255566b1b15eb
e43baa63d59c05bc6d0d48f5cce87a1bc1e0a96c
refs/heads/master
2020-07-22T21:39:38.949404
2015-01-17T13:27:25
2015-01-17T13:27:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,726
h
#ifndef SOUS_VIDE_H #define SOUS_VIDE_H // Libraries for the DS18B20 Temperature Sensor #include "../OneWire/OneWire.h" #include "../DallasTemperature/DallasTemperature.h" // PID Library #include "../PID_v1/PID_v1.h" #include "../PID_AutoTune_v0/PID_AutoTune_v0.h" // EEPROM addresses for persisted data const int SpAddress = 0; const int KpAddress = 8; const int KiAddress = 16; const int KdAddress = 24; const int WindowSize = 10000; // 10 second Time Proportional Output window // Abstract class to represent an Internal state of the machine class State { public: // must be called at least virtual void run(); virtual void do_control(); }; class OffState : public State {}; class RunState : public State {}; class AutoTuneState : public RunState { private: PID_ATune aTune; public: AutoTuneState() : aTune(&input, &output) (){}; }; class Cooker { friend class State; // Internal State classes have access to the class private: int relay_pin; // The output relay that drive the physical cooker State* internal_state; double output, temperature, setpoint, Kp, Ki, Kd;; // variables for the PID OneWire oneWire; DallasTemperature sensors; DeviceAddress tempSensor; PID myPID; public: Cooker(int relay_pin = 13, int one_wire_pin = 2) : relay_pin(relay_pin), oneWire(one_wire_pin), sensors(&oneWire) { pinMode(relay_pin, OUTPUT); pinMode(one_wire_pin, INPUT); load_parameters(); myPID = PID (&temperature, &output, &setpoint, Kp, Ki, Kd, DIRECT); myPID.SetTunings(Kp,Ki,Kd); myPID.SetSampleTime(1000); myPID.SetOutputLimits(0, WindowSize); set_state(new OffState()); // Start up the DS18B20 One Wire Temperature Sensor sensors.begin(); if (!sensors.getAddress(tempSensor, 0)) Serial.println("Sensor Error"); sensors.setResolution(tempSensor, 12); sensors.setWaitForConversion(false); } private: // Update the temparature if some data is available from the sensor void update_temperature() { // Read the input: if (sensors.isConversionAvailable(0)) { temperature = sensors.getTempC(tempSensor); sensors.requestTemperatures(); // prime the pump for the next one - but don't wait } } void set_state(State *state); const double get_Kp() {return Kp;} void set_Kp(const double value) {Kp = value;}; const double get_Ki() {return Ki;} void set_Ki(const double value) {Ki = value;}; const double get_Kd() {return Kd;} void set_Kd(const double value) {Kd = value;}; const double get_Temperature() {return setpoint;} void set_Temperature(const double value) {setpoint = value;}; private: void load_parameters(); void save_parameters(); }; #endif // SOUS_VIDE_H
[ "julien@flajollet.fr" ]
julien@flajollet.fr
8f07cddffb9c5f530339d62b35698f87cfe41d6a
27d67033be684de775fa75f9cfe2409f68344f56
/Dark_Hypersquare_v0-41.cpp
5eae8dee661d44416a6a07db2e925d972e8f8f3f
[]
no_license
janderkkotlarski/Dark_Hypersquare
3e0765c16902bdba6938c526054c5861e09a4c2c
550e174cf4f622c0f8df81292635bf24e1e243aa
refs/heads/master
2021-01-20T09:55:32.657818
2019-09-26T15:44:32
2019-09-26T15:44:32
90,304,165
2
2
null
2017-05-10T08:49:40
2017-05-04T19:56:43
C++
UTF-8
C++
false
false
156,305
cpp
#include <iostream> #include <string> #include <cmath> #include <chrono> #include <thread> #include <random> #include <SFML/Graphics.hpp> #include "Fiboinit.h" #include "Fiborand.h" #include "Colorize.h" #include "Exit_Multicolor.h" #include "Blinker.h" #include "Background_Blinker.h" #include "Color_Picker.h" #include "Square_Draw.h" #include "Dark_Maze_PRNG.h" #include "Clear_Maze_PRNG.h" /// g++ -std=c++11 -o "%e" "%f" -lsfml-graphics -lsfml-audio -lsfml-window -lsfml-system int main() { std::string amazad_var = "Dark Hypersquare V0.41"; int max_level = 100, max_side = 2*max_level + 1, square_matrix[201][201]; int size_level = 20, level_side, level_pass = 0, max_view = 6; int level_max = 29, level_threshold = 16, level_init = 29; int delaz = 10, delay_flip = 0, coord_a_sub, coord_b_sub; bool delay_flipping = false; int crunchy_number = 0, crunched = 0, max_pow = 20; int dosh = 0, dosh_increase = 0; bool start_screen = true, testing = false; bool level_change = false, level_back = false, level_reset = false, level_recet = false; bool level_begin = false, pause = false, view_glitch = false, glitch_excempt = false; bool up_movement = false, down_movement = false, right_movement = false, left_movement = false; bool moving = false, turn_right = false, turn_left = false, roturning = false; bool action = false, dark_setback = false, dark_flicker = false; bool dark_backed = false, first_dark_back = false, timecop = false; bool inhale = false, exhale = false, building = false; bool turning = false, exchange = false, build = false, timeshift = false; bool one_turn_uplight = false, two_turn_uplight = false; bool key_up_uplight = false, key_right_uplight= false, key_down_uplight = false, key_left_uplight = false; bool key_d_uplight = false, key_a_uplight = false, key_w_uplight = false, key_x_uplight = false; bool key_r_uplight = false, key_v_uplight = false; double inhale_move_x = 0, inhale_move_y = 0; int absorbed = 0, assimilated = 0, nullvoid = 0; int transitions = 20; double pi = 2*acos(0), theta = 0, delta_theta = pi/(2*transitions); int squarep = 50, window_x = 12*squarep, window_y = 12*squarep, squarrel = 20; int half_wind = 6*squarep, max_transp = 255, square_transp, bat_transp, full_intensity = 255; int colours[3], karasu[3], kolours[3], transp, toransupu = max_transp, intro_transp = max_transp; int color_black[3] = {0, 0, 0}, color_white[3] = {full_intensity, full_intensity, full_intensity}, key_colour[3], background_colour[3], shadow_colours[3]; int uplight_transp; int pacman = 0; double dark_transp = 0, dark_mult = 3; int exit_colors[3] = {full_intensity, 0, 0}; int dir_up[2] = {0, -1}, dir_down[2] = {0, 1}, dir_right[2] = {1, 0}, dir_left[2] = {-1, 0}; int dir_move[2] = {0, 0}, dir_direct[2] = {0, 0}; double dir_mult = 2.5, final_move[2] = {0, 0}, cumu_move[2] = {0, 0}; int rot_right = -1, rot_left = 1; double rot_mult = 4.5, final_rot = 0, paruto = 1, paruto_sub = 0.05, scale = 1, scale_mult = 1.17, scale_rot = 18; int turn_right_matrix[2][2] = {0, -1, 1, 0}, turn_left_matrix[2][2] = {0, 1, -1, 0}; double pos_x = 0, pos_y = 0, pos_i = 0, pos_j = 0; double scan_pos_x = 0, scan_pos_y = -50, level_pot_x, level_pot_y; int local_x = 0, local_y = -1, pot_x = 0, pot_y = 0, qot_x = 0, qot_y = 0, radius_max_2 = 72; int possible_triggers = 0, actual_triggers = 0; int fib_val[3], max_val = 1000000000, fractal = (max_val - 2); int blink = max_transp, background_blink = 0, blink_min = 32, blink_delta = 4; bool blink_on = true, background_blink_on = false, position_declare = true; sf::Vector2i mouse_position; int mouse_pos_x, mouse_pos_y; int mouse_pressed = false; int level_loop_counter = 0; double red_candy_frac = 0.50, yellow_candy_frac = 0.10, green_candy_frac = 0.02, blue_candy_frac = 0.005; double wall_frac = 0.40, dark_frac = 0.1, exit_frac = 0.03; double candy_frac = red_candy_frac + yellow_candy_frac + green_candy_frac + blue_candy_frac; bool wall_exist = false, pillars_exist = false, dark_exist = false, exit_exist = false; bool wall_concrete = false, half_gone = false, zero_wall = false; int clear_radius = 4; Fiboinit(fib_val, max_val, fractal); std::string start_screen_img = "Start_Screen_a.png"; std::string start_shadow_img = "Start_Shadow_a.png"; std::string scanner_img = "A-M4Z2-D_Scanner.png"; std::string arrow_img = "Arrow_Mini.png"; std::string compass_back_img = "Compass_Back_Mini.png"; std::string compass_img = "Compass_Mini.png"; std::string bitmask_img = "Bit_Mask_40e.png"; std::string bitsquare_img = "Bit_Square_40e.png"; std::string bitshadow_img = "Bit_Shadow_40--e.png"; std::string bitshine_img = "Bit_Shine_40e.png"; std::string bitmask_key_up_file = "Key_Up_Icon.png"; std::string bitmask_key_right_file = "Key_Right_Icon.png"; std::string bitmask_key_down_file = "Key_Down_Icon.png"; std::string bitmask_key_left_file = "Key_Left_Icon.png"; std::string bitmask_key_d_file = "Key_D_Icon.png"; std::string bitmask_key_right_turn_file = "Key_Turn_Right_Icon.png"; std::string bitmask_key_a_file = "Key_A_Icon.png"; std::string bitmask_key_left_turn_file = "Key_Turn_Left_Icon.png"; std::string bitmask_key_w_file = "Key_W_Icon.png"; std::string bitmask_exchange_file = "Exchange_Icon.png"; std::string bitmask_key_x_file = "Key_X_Icon.png"; std::string bitmask_build_file = "Build_Icon.png"; std::string bitmask_key_r_file = "Key_R_Icon.png"; std::string bitmask_reset_file = "Reset_Icon.png"; std::string bitmask_key_v_file = "Key_V_Icon.png"; std::string bitmask_timeshift_file = "Timeshift_Icon.png"; std::string bitmask_key_esc_file = "Key_Esc_Icon.png"; std::string bitmask_key_s_file = "Key_S_Icon.png"; std::string bitmask_level_file = "L3V3L_Icon.png"; int number_max = 11; std::string bitmask_number_file[number_max]; bitmask_number_file[0] = "Number_0_Icon.png"; bitmask_number_file[1] = "Number_1_Icon.png"; bitmask_number_file[2] = "Number_2_Icon.png"; bitmask_number_file[3] = "Number_3_Icon.png"; bitmask_number_file[4] = "Number_4_Icon.png"; bitmask_number_file[5] = "Number_5_Icon.png"; bitmask_number_file[6] = "Number_6_Icon.png"; bitmask_number_file[7] = "Number_7_Icon.png"; bitmask_number_file[8] = "Number_8_Icon.png"; bitmask_number_file[9] = "Number_9_Icon.png"; bitmask_number_file[10] = "Number_Minus_Icon.png"; std::string bitmask_dollar_file = "Number_Dollar_Icon.png"; sf::Texture start_screen_tex; if (!start_screen_tex.loadFromFile(start_screen_img)) { std::cout << start_screen_img << " not found!\n"; } sf::Sprite start_screen_sprite; start_screen_sprite.setTexture(start_screen_tex); start_screen_sprite.setOrigin(sf::Vector2f(half_wind, half_wind)); start_screen_sprite.setPosition(sf::Vector2f(0, -squarep)); start_screen_sprite.setColor(sf::Color(full_intensity, full_intensity, full_intensity, max_transp)); int shadow_blink = 0; bool shadow_blink_up = true; sf::Texture start_shadow_tex; if (!start_shadow_tex.loadFromFile(start_shadow_img)) { std::cout << start_shadow_img << " not found!\n"; } sf::Sprite start_shadow_sprite; start_shadow_sprite.setTexture(start_shadow_tex); start_shadow_sprite.setOrigin(sf::Vector2f(half_wind, half_wind)); start_shadow_sprite.setPosition(sf::Vector2f(0, -squarep)); start_shadow_sprite.setColor(sf::Color(0, 0, 0, max_transp)); sf::Texture scanner_tex; if (!scanner_tex.loadFromFile(scanner_img)) { std::cout << scanner_img << " not found!\n"; } sf::Sprite scanner_sprite; scanner_sprite.setTexture(scanner_tex); scanner_sprite.setOrigin(sf::Vector2f(half_wind, half_wind)); scanner_sprite.setPosition(sf::Vector2f(0, -squarep)); scanner_sprite.setColor(sf::Color(full_intensity, full_intensity, full_intensity, 1*max_transp)); sf::VertexArray squanner(sf::Quads, 4); squanner[0].position = sf::Vector2f(-half_wind, -half_wind); squanner[0].color = sf::Color(full_intensity, full_intensity, full_intensity, max_transp); squanner[1].position = sf::Vector2f(half_wind, -half_wind); squanner[1].color = sf::Color(full_intensity, full_intensity, full_intensity, max_transp); squanner[2].position = sf::Vector2f(half_wind, half_wind); squanner[2].color = sf::Color(full_intensity, full_intensity, full_intensity, max_transp); squanner[3].position = sf::Vector2f(-half_wind, half_wind); squanner[3].color = sf::Color(full_intensity, full_intensity, full_intensity, max_transp); squanner[0].texCoords = sf::Vector2f(0, 0); squanner[1].texCoords = sf::Vector2f(2*half_wind, 0); squanner[2].texCoords = sf::Vector2f(2*half_wind, 2*half_wind); squanner[3].texCoords = sf::Vector2f(0, 2*half_wind); sf::Texture compass_back_tex; if (!compass_back_tex.loadFromFile(compass_back_img)) { std::cout << compass_back_img << " not found!\n"; } sf::Sprite compass_back_sprite; compass_back_sprite.setTexture(compass_back_tex); compass_back_sprite.setOrigin(sf::Vector2f(12, 12)); compass_back_sprite.setPosition(sf::Vector2f(0, -squarep)); sf::Texture compass_tex; if (!compass_tex.loadFromFile(compass_img)) { std::cout << compass_img << " not found!\n"; } sf::Sprite compass_sprite; compass_sprite.setTexture(compass_tex); compass_sprite.setOrigin(sf::Vector2f(12, 12)); compass_sprite.setPosition(sf::Vector2f(0, -squarep)); sf::Texture arrow_tex; if (!arrow_tex.loadFromFile(arrow_img)) { std::cout << arrow_img << " not found!\n"; } sf::Sprite arrow_sprite; arrow_sprite.setTexture(arrow_tex); arrow_sprite.setOrigin(sf::Vector2f(12, 12)); arrow_sprite.setPosition(sf::Vector2f(0, -squarep)); sf::Texture bitmask_tex; if (!bitmask_tex.loadFromFile(bitmask_img)) { std::cout << bitmask_img << " not found!\n"; } sf::Sprite bitmask_sprite; bitmask_sprite.setTexture(bitmask_tex); bitmask_sprite.setOrigin(sf::Vector2f(25, 25)); bitmask_sprite.setPosition(sf::Vector2f(0, 0)); sf::Texture bitsquare_tex; if (!bitsquare_tex.loadFromFile(bitsquare_img)) { std::cout << bitsquare_img << " not found!\n"; } sf::Sprite bitsquare_sprite; bitsquare_sprite.setTexture(bitsquare_tex); bitsquare_sprite.setOrigin(sf::Vector2f(25, 25)); bitsquare_sprite.setPosition(sf::Vector2f(0, 0)); sf::Texture bitshadow_tex; if (!bitshadow_tex.loadFromFile(bitshadow_img)) { std::cout << bitshadow_img << " not found!\n"; } sf::Sprite bitshadow_sprite; bitshadow_sprite.setTexture(bitshadow_tex); bitshadow_sprite.setOrigin(sf::Vector2f(25, 25)); bitshadow_sprite.setPosition(sf::Vector2f(0, 0)); sf::Texture bitshine_tex; if (!bitshine_tex.loadFromFile(bitshine_img)) { std::cout << bitshine_img << " not found!\n"; } sf::Sprite bitshine_sprite; bitshine_sprite.setTexture(bitshine_tex); bitshine_sprite.setOrigin(sf::Vector2f(25, 25)); bitshine_sprite.setPosition(sf::Vector2f(0, 0)); sf::Sprite bitomasuku_supuraito; bitomasuku_supuraito.setTexture(bitmask_tex); bitomasuku_supuraito.setOrigin(sf::Vector2f(25, 25)); bitomasuku_supuraito.setPosition(sf::Vector2f(0, 0)); sf::Sprite pitmask_sprite; pitmask_sprite.setTexture(bitmask_tex); pitmask_sprite.setOrigin(sf::Vector2f(25, 25)); pitmask_sprite.setPosition(sf::Vector2f(0, 0)); sf::Texture bitmask_key_up; if (!bitmask_key_up.loadFromFile(bitmask_key_up_file)) { std::cout << bitmask_key_up_file << " not found!\n"; } sf::Sprite key_up_sprite; key_up_sprite.setTexture(bitmask_key_up); key_up_sprite.setOrigin(sf::Vector2f(-3.5*squarep, -3.5*squarep)); key_up_sprite.setPosition(sf::Vector2f(0, -squarep)); sf::Texture bitmask_key_right; if (!bitmask_key_right.loadFromFile(bitmask_key_right_file)) { std::cout << bitmask_key_right_file << " not found!\n"; } sf::Sprite key_right_sprite; key_right_sprite.setTexture(bitmask_key_right); key_right_sprite.setOrigin(sf::Vector2f(-4.5*squarep, -4.5*squarep)); key_right_sprite.setPosition(sf::Vector2f(0, -squarep)); sf::Texture bitmask_key_down; if (!bitmask_key_down.loadFromFile(bitmask_key_down_file)) { std::cout << bitmask_key_down_file << " not found!\n"; } sf::Sprite key_down_sprite; key_down_sprite.setTexture(bitmask_key_down); key_down_sprite.setOrigin(sf::Vector2f(-3.5*squarep, -4.5*squarep)); key_down_sprite.setPosition(sf::Vector2f(0, -squarep)); sf::Texture bitmask_key_left; if (!bitmask_key_left.loadFromFile(bitmask_key_left_file)) { std::cout << bitmask_key_left_file << " not found!\n"; } sf::Sprite key_left_sprite; key_left_sprite.setTexture(bitmask_key_left); key_left_sprite.setOrigin(sf::Vector2f(-2.5*squarep, -4.5*squarep)); key_left_sprite.setPosition(sf::Vector2f(0, -squarep)); sf::Texture bitmask_key_d; if (!bitmask_key_d.loadFromFile(bitmask_key_d_file)) { std::cout << bitmask_key_d_file << " not found!\n"; } sf::Sprite key_d_sprite; key_d_sprite.setTexture(bitmask_key_d); key_d_sprite.setOrigin(sf::Vector2f(4.5*squarep, -4.5*squarep)); key_d_sprite.setPosition(sf::Vector2f(0, -squarep)); sf::Texture bitmask_key_right_turn; if (!bitmask_key_right_turn.loadFromFile(bitmask_key_right_turn_file)) { std::cout << bitmask_key_right_turn_file << " not found!\n"; } sf::Sprite key_right_turn_sprite; key_right_turn_sprite.setTexture(bitmask_key_right_turn); key_right_turn_sprite.setOrigin(sf::Vector2f(4.5*squarep, -3.5*squarep)); key_right_turn_sprite.setPosition(sf::Vector2f(0, -squarep)); sf::Texture bitmask_key_a; if (!bitmask_key_a.loadFromFile(bitmask_key_a_file)) { std::cout << bitmask_key_a_file << " not found!\n"; } sf::Sprite key_a_sprite; key_a_sprite.setTexture(bitmask_key_a); key_a_sprite.setOrigin(sf::Vector2f(5.5*squarep, -4.5*squarep)); key_a_sprite.setPosition(sf::Vector2f(0, -squarep)); sf::Texture bitmask_key_left_turn; if (!bitmask_key_left_turn.loadFromFile(bitmask_key_left_turn_file)) { std::cout << bitmask_key_left_turn_file << " not found!\n"; } sf::Sprite key_left_turn_sprite; key_left_turn_sprite.setTexture(bitmask_key_left_turn); key_left_turn_sprite.setOrigin(sf::Vector2f(5.5*squarep, -3.5*squarep)); key_left_turn_sprite.setPosition(sf::Vector2f(0, -squarep)); sf::Texture bitmask_key_w; if (!bitmask_key_w.loadFromFile(bitmask_key_w_file)) { std::cout << bitmask_key_w_file << " not found!\n"; } sf::Sprite key_w_sprite; key_w_sprite.setTexture(bitmask_key_w); key_w_sprite.setOrigin(sf::Vector2f(3*squarep, -4.5*squarep)); key_w_sprite.setPosition(sf::Vector2f(0, -squarep)); sf::Texture bitmask_exchange; if (!bitmask_exchange.loadFromFile(bitmask_exchange_file)) { std::cout << bitmask_exchange_file << " not found!\n"; } sf::Sprite exchange_sprite; exchange_sprite.setTexture(bitmask_exchange); exchange_sprite.setOrigin(sf::Vector2f(3*squarep, -3.5*squarep)); exchange_sprite.setPosition(sf::Vector2f(0, -squarep)); sf::Texture bitmask_key_x; if (!bitmask_key_x.loadFromFile(bitmask_key_x_file)) { std::cout << bitmask_key_x_file << " not found!\n"; } sf::Sprite key_x_sprite; key_x_sprite.setTexture(bitmask_key_x); key_x_sprite.setOrigin(sf::Vector2f(2*squarep, -4.5*squarep)); key_x_sprite.setPosition(sf::Vector2f(0, -squarep)); sf::Texture bitmask_build; if (!bitmask_build.loadFromFile(bitmask_build_file)) { std::cout << bitmask_build_file << " not found!\n"; } sf::Sprite build_sprite; build_sprite.setTexture(bitmask_build); build_sprite.setOrigin(sf::Vector2f(2*squarep, -3.5*squarep)); build_sprite.setPosition(sf::Vector2f(0, -squarep)); sf::Texture bitmask_key_v; if (!bitmask_key_v.loadFromFile(bitmask_key_v_file)) { std::cout << bitmask_key_v_file << " not found!\n"; } sf::Sprite key_v_sprite; key_v_sprite.setTexture(bitmask_key_v); key_v_sprite.setOrigin(sf::Vector2f(0.5*squarep, -4.5*squarep)); key_v_sprite.setPosition(sf::Vector2f(0, -squarep)); sf::Texture bitmask_timeshift; if (!bitmask_timeshift.loadFromFile(bitmask_timeshift_file)) { std::cout << bitmask_timeshift_file << " not found!\n"; } sf::Sprite timeshift_sprite; timeshift_sprite.setTexture(bitmask_timeshift); timeshift_sprite.setOrigin(sf::Vector2f(0.5*squarep, -3.5*squarep)); timeshift_sprite.setPosition(sf::Vector2f(0, -squarep)); sf::Texture bitmask_key_r; if (!bitmask_key_r.loadFromFile(bitmask_key_r_file)) { std::cout << bitmask_key_r_file << " not found!\n"; } sf::Sprite key_r_sprite; key_r_sprite.setTexture(bitmask_key_r); key_r_sprite.setOrigin(sf::Vector2f(-1*squarep, -4.5*squarep)); key_r_sprite.setPosition(sf::Vector2f(0, -squarep)); sf::Texture bitmask_reset; if (!bitmask_reset.loadFromFile(bitmask_reset_file)) { std::cout << bitmask_reset_file << " not found!\n"; } sf::Sprite reset_sprite; reset_sprite.setTexture(bitmask_reset); reset_sprite.setOrigin(sf::Vector2f(-1*squarep, -3.5*squarep)); reset_sprite.setPosition(sf::Vector2f(0, -squarep)); sf::Texture bitmask_key_esc; if (!bitmask_key_esc.loadFromFile(bitmask_key_esc_file)) { std::cout << bitmask_key_esc_file << " not found!\n"; } sf::Sprite key_esc_sprite; key_esc_sprite.setTexture(bitmask_key_esc); key_esc_sprite.setOrigin(sf::Vector2f(5.5*squarep, 5.5*squarep)); key_esc_sprite.setPosition(sf::Vector2f(0, -squarep)); sf::Texture bitmask_key_s; if (!bitmask_key_s.loadFromFile(bitmask_key_s_file)) { std::cout << bitmask_key_s_file << " not found!\n"; } sf::Sprite key_s_sprite; key_s_sprite.setTexture(bitmask_key_s); key_s_sprite.setOrigin(sf::Vector2f(0.5*squarep, -3.5*squarep)); key_s_sprite.setPosition(sf::Vector2f(0, -squarep)); sf::Texture bitmask_level; if (!bitmask_level.loadFromFile(bitmask_level_file)) { std::cout << bitmask_level_file << " not found!\n"; } sf::Sprite level_sprite[max_pow + 1]; for (int b_sub = 0; b_sub <= max_pow; b_sub++) { level_sprite[b_sub].setTexture(bitmask_level); level_sprite[b_sub].setOrigin(sf::Vector2f(-4.5*squarep + (b_sub + 1)*18, 5.5*squarep)); level_sprite[b_sub].setPosition(sf::Vector2f(0, -squarep)); } sf::Texture bitmask_number[number_max]; for (int a_sub = 0; a_sub < number_max; a_sub++) { if (!bitmask_number[a_sub].loadFromFile(bitmask_number_file[a_sub])) { std::cout << bitmask_number_file[a_sub] << " not found!\n"; } } sf::Sprite number_sprite[number_max][max_pow + 1]; for (int a_sub = 0; a_sub < number_max; a_sub++) { for (int b_sub = 0; b_sub <= max_pow; b_sub++) { number_sprite[a_sub][b_sub].setTexture(bitmask_number[a_sub]); number_sprite[a_sub][b_sub].setOrigin(sf::Vector2f(-4.5*squarep + (b_sub - 2)*18, 5.5*squarep + 1)); number_sprite[a_sub][b_sub].setPosition(sf::Vector2f(0, -squarep)); } } sf::Texture bitmask_dollar; if (!bitmask_dollar.loadFromFile(bitmask_dollar_file)) { std::cout << bitmask_dollar_file << " not found!\n"; } sf::Sprite dollar_sprite[max_pow + 1]; for (int b_sub = 0; b_sub <= max_pow; b_sub++) { dollar_sprite[b_sub].setTexture(bitmask_dollar); dollar_sprite[b_sub].setOrigin(sf::Vector2f(-4.5*squarep + (b_sub + 0)*18, -1.5*squarep)); dollar_sprite[b_sub].setPosition(sf::Vector2f(0, -squarep)); } sf::Sprite dosh_sprite[number_max][max_pow + 1]; for (int a_sub = 0; a_sub < number_max; a_sub++) { for (int b_sub = 0; b_sub <= max_pow; b_sub++) { dosh_sprite[a_sub][b_sub].setTexture(bitmask_number[a_sub]); dosh_sprite[a_sub][b_sub].setOrigin(sf::Vector2f(-4.5*squarep + (b_sub - 2)*18, -1.5*squarep + 1)); dosh_sprite[a_sub][b_sub].setPosition(sf::Vector2f(0, -squarep)); } } std::chrono::milliseconds delay(delaz); sf::RectangleShape squaree(sf::Vector2f(2*squarrel, 2*squarrel)); Color_Picker(8, colours, exit_colors); squaree = Square_Draw(squaree, colours, blink, pos_x, pos_y, squarrel, squarrel); sf::RectangleShape sukuwarii(sf::Vector2f(2*squarrel, 2*squarrel)); Color_Picker(8, karasu, exit_colors); sukuwarii = Square_Draw(sukuwarii, karasu, blink, pos_x, pos_y, squarrel, squarrel); sf::RectangleShape squarei(sf::Vector2f(2*squarrel, 2*squarrel)); Color_Picker(0, kolours, exit_colors); squarei = Square_Draw(squarei, kolours, max_transp, local_x*squarep, local_y*squarep - squarep, squarrel, squarrel); sf::RectangleShape infobox(sf::Vector2f(2*half_wind, half_wind - 0.5*squarep)); Color_Picker(0, color_black, exit_colors); infobox.setOrigin(sf::Vector2f(half_wind, -0.5*squarep)); infobox = Square_Draw(infobox, color_black, 1*max_transp, 0, -squarep, 0, 0); sf::RectangleShape exit_filler(sf::Vector2f(2*squarrel, 2*squarrel)); Color_Picker(0, karasu, exit_colors); exit_filler.setOrigin(squarrel, squarrel); exit_filler = Square_Draw(exit_filler, karasu, max_transp, pos_x, pos_y, 0, 0); sf::RectangleShape intro_filler(sf::Vector2f(2*squarrel, 2*squarrel)); Color_Picker(0, karasu, exit_colors); intro_filler.setOrigin(squarrel, squarrel); intro_filler = Square_Draw(intro_filler, karasu, max_transp, pos_x, pos_y, 0, 0); intro_filler.scale(18, 18); Color_Picker(2, key_colour, exit_colors); sf::Font font; if (!font.loadFromFile("Carlito-Regular.ttf")) { // error... } sf::Text text; text.setFont(font); text.setCharacterSize(18); text.setColor(sf::Color::White); text.setPosition(50, 350); sf::RenderWindow window(sf::VideoMode(window_x, window_y), amazad_var, sf::Style::Default); sf::View view(sf::Vector2f(0, -squarep), sf::Vector2f(window_x, window_x)); view.setViewport(sf::FloatRect(0, 0, 1, 1)); window.setView(view); int outro = 255; while (window.isOpen()) { key_s_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], 0)); start_shadow_sprite.setColor(sf::Color(0, 0, 0, background_blink/4)); start_screen_sprite.setColor(sf::Color(0, 0, 0, max_transp)); for (int b_sub = 1; b_sub <= 255; b_sub = b_sub + 2) { window.clear(sf::Color(color_black[0], color_black[1], color_black[2])); window.draw(start_shadow_sprite); window.draw(start_screen_sprite); // window.draw(key_esc_sprite); window.draw(key_s_sprite); window.display(); key_s_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], b_sub)); start_shadow_sprite.setColor(sf::Color(b_sub, b_sub, b_sub, background_blink)); start_screen_sprite.setColor(sf::Color(b_sub, b_sub, b_sub, max_transp)); Color_Picker(2, key_colour, exit_colors); for (int a_sub = 0; a_sub <= 2; a_sub++) { key_colour[a_sub] = 128 + key_colour[a_sub]/2; } Exit_Multicolor(exit_colors); Background_Blinker(background_blink_on, background_blink, max_transp); if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) { mouse_position = sf::Mouse::getPosition(window); mouse_pos_x = mouse_position.x; mouse_pos_y = mouse_position.y; mouse_pressed = true; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::S) || (mouse_pressed && (mouse_pos_x > 275) && (mouse_pos_x < 325) && (mouse_pos_y > 475) && (mouse_pos_y < 525))) { start_screen = false; sf::Mouse::setPosition(sf::Vector2i(half_wind, half_wind), window); mouse_pressed = false; outro = b_sub; b_sub = 255; } std::this_thread::sleep_for(delay); } while (start_screen) { window.clear(sf::Color(color_black[0], color_black[1], color_black[2])); window.draw(start_shadow_sprite); window.draw(start_screen_sprite); // window.draw(key_esc_sprite); window.draw(key_s_sprite); window.display(); key_s_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); start_shadow_sprite.setColor(sf::Color(full_intensity, full_intensity, full_intensity, background_blink)); start_screen_sprite.setColor(sf::Color(full_intensity, full_intensity, full_intensity, max_transp)); Color_Picker(2, key_colour, exit_colors); for (int a_sub = 0; a_sub <= 2; a_sub++) { key_colour[a_sub] = 128 + key_colour[a_sub]/2; } Exit_Multicolor(exit_colors); Background_Blinker(background_blink_on, background_blink, max_transp); if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) { mouse_position = sf::Mouse::getPosition(window); mouse_pos_x = mouse_position.x; mouse_pos_y = mouse_position.y; mouse_pressed = true; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::S) || (mouse_pressed && (mouse_pos_x > 275) && (mouse_pos_x < 325) && (mouse_pos_y > 475) && (mouse_pos_y < 525))) { start_screen = false; sf::Mouse::setPosition(sf::Vector2i(half_wind, half_wind), window); mouse_pressed = false; } std::this_thread::sleep_for(delay); } for (int b_sub = outro; b_sub >= 0; b_sub = b_sub - 2) { if (b_sub < 0) { b_sub = 0; } window.clear(sf::Color(color_black[0], color_black[1], color_black[2])); window.draw(start_shadow_sprite); window.draw(start_screen_sprite); // window.draw(key_esc_sprite); window.draw(key_s_sprite); window.display(); key_s_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], b_sub)); start_shadow_sprite.setColor(sf::Color(b_sub, b_sub, b_sub, background_blink)); start_screen_sprite.setColor(sf::Color(b_sub, b_sub, b_sub, max_transp)); Color_Picker(2, key_colour, exit_colors); for (int a_sub = 0; a_sub <= 2; a_sub++) { key_colour[a_sub] = 128 + key_colour[a_sub]/2; } Exit_Multicolor(exit_colors); Background_Blinker(background_blink_on, background_blink, max_transp); std::this_thread::sleep_for(delay); } for (int level = level_init; level <= level_max; level++) { level_change = false; if (level < level_threshold) { size_level = 5; } if (level >= level_threshold) { size_level = level; } level_side = 2*size_level + 1; for (int a_sub = -max_level; a_sub <= max_level; a_sub++) { for (int b_sub = -max_level; b_sub <= max_level; b_sub++) { square_matrix[a_sub + max_level][b_sub + max_level] = 1; } } if (level < level_threshold) { for (int a_sub = -size_level; a_sub <= size_level; a_sub++) { for (int b_sub = -size_level; b_sub <= size_level; b_sub++) { square_matrix[a_sub + max_level][b_sub + max_level] = 1; if (level <= 8) { square_matrix[a_sub + max_level][b_sub + max_level] = 10; if (testing) { square_matrix[a_sub + max_level][b_sub + max_level] = 6; } } } } } if (level >= level_threshold) { wall_frac = 0.3 + level/100; dark_frac = 0.1; exit_frac = 0.3/level; wall_exist = false; pillars_exist = false; dark_exist = false; exit_exist = false; half_gone = false; zero_wall = false; if (level == 16) { wall_exist = true; zero_wall = true; } if (level == 17) { wall_exist = true; pillars_exist = true; zero_wall = true; } if (level == 18) { wall_exist = true; wall_concrete = true; zero_wall = true; } if (level == 19) { wall_exist = true; pillars_exist = true; wall_concrete = true; zero_wall = true; } if (level == 20) { wall_exist = true; wall_concrete = true; dark_exist = true; zero_wall = true; } if (level == 21) { wall_exist = true; pillars_exist = true; wall_concrete = true; dark_exist = true; zero_wall = true; } if (level == 22) { pillars_exist = true; wall_concrete = true; dark_exist = true; exit_exist = true; half_gone = true; } if (level == 23) { pillars_exist = true; wall_exist = true; wall_concrete = true; exit_exist = true; dark_exist = true; half_gone = true; } if (level == 24) { wall_concrete = true; dark_exist = true; } if (level == 25) { wall_concrete = true; dark_exist = true; exit_exist = true; } if (level == 28) { wall_exist = true; pillars_exist = true; wall_concrete = true; dark_exist = true; half_gone = true; } Dark_Maze_PRNG(square_matrix, max_level, size_level, clear_radius, half_gone, pillars_exist, wall_exist, zero_wall, wall_concrete, exit_exist, dark_exist, fib_val, max_val, fractal, wall_frac, dark_frac, exit_frac, candy_frac, red_candy_frac, yellow_candy_frac, green_candy_frac, blue_candy_frac); if (level == 26) { Clear_Maze_PRNG(square_matrix, max_level, size_level); } if (level == 27) { Clear_Maze_PRNG(square_matrix, max_level, size_level); } if (level == 28) { Clear_Maze_PRNG(square_matrix, max_level, size_level/2 + 2); } if (level == 29) { Clear_Maze_PRNG(square_matrix, max_level, size_level); } } if (level == 1) { for (int a_sub = -size_level; a_sub <= size_level; a_sub++) { square_matrix[max_level][a_sub + max_level] = 0; } } if (testing && (level >= 2) && (level <= level_threshold) && false) { for (int a_sub = -2; a_sub <= 2; a_sub++) { // square_matrix[max_level - 2][a_sub + max_level] = 4; // square_matrix[max_level - 4][a_sub + max_level] = 1; // square_matrix[max_level + 4][a_sub + max_level] = 10; } for (int a_sub = 2; a_sub <= size_level; a_sub++) { for (int b_sub = -3; b_sub <= 1; b_sub++) { square_matrix[max_level + a_sub][max_level + b_sub] = 3; square_matrix[max_level - a_sub][max_level + b_sub] = 3; } } } if ((level == 2) && !testing) { // up for (int a_sub = -size_level; a_sub <= 1; a_sub++) { square_matrix[max_level][a_sub + max_level] = 0; } // right for (int a_sub = 0; a_sub <= size_level; a_sub++) { square_matrix[a_sub + max_level][-size_level + max_level] = 0; } // up for (int a_sub = 2; a_sub <= size_level; a_sub++) { square_matrix[size_level + max_level][a_sub + max_level] = 0; } // right for (int a_sub = -size_level; a_sub <= 0; a_sub++) { square_matrix[a_sub + max_level][2 + max_level] = 0; } } if (level == 3) { // up for (int a_sub = -size_level; a_sub <= 1; a_sub++) { square_matrix[max_level][a_sub + max_level] = 0; } // left for (int a_sub = -size_level; a_sub <= 0; a_sub++) { square_matrix[a_sub + max_level][-size_level + max_level] = 0; } // up for (int a_sub = 2; a_sub <= size_level; a_sub++) { square_matrix[-size_level + max_level][a_sub + max_level] = 0; } // left for (int a_sub = 0; a_sub <= size_level; a_sub++) { square_matrix[a_sub + max_level][2 + max_level] = 0; } } if (level == 4) { for (int a_sub = -size_level; a_sub <= size_level; a_sub++) { square_matrix[max_level][a_sub + max_level] = 0; } } if (level == 5) { square_matrix[+ max_level][-1 + max_level] = 0; // left for (int a_sub = -2; a_sub <= 0; a_sub++) { square_matrix[a_sub + max_level][-2 + max_level] = 0; } //down for (int a_sub = -2; a_sub <= 4; a_sub++) { square_matrix[-2 + max_level][a_sub + max_level] = 0; } // right for (int a_sub = -2; a_sub <= size_level; a_sub++) { square_matrix[a_sub + max_level][4 + max_level] = 0; } square_matrix[size_level + max_level][2 + max_level] = 0; square_matrix[size_level + max_level][0 + max_level] = 0; square_matrix[size_level + max_level][-2 + max_level] = 0; square_matrix[size_level + max_level][-4 + max_level] = 0; square_matrix[-size_level + max_level][4 + max_level] = 0; square_matrix[-size_level + max_level][2 + max_level] = 0; square_matrix[-size_level + max_level][0 + max_level] = 0; square_matrix[-size_level + max_level][-2 + max_level] = 0; for (int a_sub = 2; a_sub <= 4; a_sub++) { square_matrix[-4 + max_level][a_sub + max_level] = 0; } for (int a_sub = 0; a_sub <= 2; a_sub++) { square_matrix[4 + max_level][a_sub + max_level] = 0; } for (int a_sub = -2; a_sub <= 0; a_sub++) { square_matrix[-4 + max_level][a_sub + max_level] = 0; } for (int a_sub = -4; a_sub <= -2; a_sub++) { square_matrix[4 + max_level][a_sub + max_level] = 0; } // right for (int a_sub = -size_level; a_sub <= 2; a_sub++) { square_matrix[a_sub + max_level][-4 + max_level] = 0; } //down for (int a_sub = -4; a_sub <= 2; a_sub++) { square_matrix[2 + max_level][a_sub + max_level] = 0; } square_matrix[1 + max_level][2 + max_level] = 0; square_matrix[max_level][2 + max_level] = 0; square_matrix[max_level][max_level + 1] = 2; } if (level == 6) { square_matrix[+ max_level][-1 + max_level] = 0; // left for (int a_sub = 0; a_sub <= 2; a_sub++) { square_matrix[a_sub + max_level][-2 + max_level] = 0; } //down for (int a_sub = -2; a_sub <= 4; a_sub++) { square_matrix[2 + max_level][a_sub + max_level] = 0; } // right for (int a_sub = -size_level; a_sub <= 2; a_sub++) { square_matrix[a_sub + max_level][4 + max_level] = 0; } square_matrix[-size_level + max_level][2 + max_level] = 0; square_matrix[-size_level + max_level][0 + max_level] = 0; square_matrix[-size_level + max_level][-2 + max_level] = 0; square_matrix[-size_level + max_level][-4 + max_level] = 0; square_matrix[size_level + max_level][4 + max_level] = 0; square_matrix[size_level + max_level][2 + max_level] = 0; square_matrix[size_level + max_level][0 + max_level] = 0; square_matrix[size_level + max_level][-2 + max_level] = 0; for (int a_sub = 2; a_sub <= 4; a_sub++) { square_matrix[4 + max_level][a_sub + max_level] = 0; } for (int a_sub = 0; a_sub <= 2; a_sub++) { square_matrix[-4 + max_level][a_sub + max_level] = 0; } for (int a_sub = -2; a_sub <= 0; a_sub++) { square_matrix[4 + max_level][a_sub + max_level] = 0; } for (int a_sub = -4; a_sub <= -2; a_sub++) { square_matrix[-4 + max_level][a_sub + max_level] = 0; } // right for (int a_sub = -2; a_sub <= size_level; a_sub++) { square_matrix[a_sub + max_level][-4 + max_level] = 0; } //down for (int a_sub = -4; a_sub <= 2; a_sub++) { square_matrix[-2 + max_level][a_sub + max_level] = 0; } square_matrix[-1 + max_level][2 + max_level] = 0; square_matrix[max_level][2 + max_level] = 0; square_matrix[max_level][max_level + 1] = 2; } if (level == 7) { // y = -1, 1 for (int a_sub = -1; a_sub <= 1; a_sub++) { square_matrix[max_level + a_sub][max_level - 1] = 0; square_matrix[max_level + a_sub][max_level + 1] = 0; } // y = 0 for (int a_sub = -size_level; a_sub <= size_level; a_sub++) { square_matrix[max_level + a_sub][max_level] = 0; } // y = -2, 2 for (int a_sub = 2; a_sub <= size_level; a_sub++) { square_matrix[a_sub + max_level][-2 + max_level] = 0; square_matrix[-a_sub + max_level][-2 + max_level] = 0; square_matrix[a_sub + max_level][2 + max_level] = 0; square_matrix[-a_sub + max_level][2 + max_level] = 0; } square_matrix[max_level][-2 + max_level] = 0; square_matrix[max_level][2 + max_level] = 0; // y = -3, 3 for (int a_sub = -2; a_sub <= 2; a_sub++) { square_matrix[a_sub + max_level][-3 + max_level] = 0; square_matrix[a_sub + max_level][3 + max_level] = 0; } // y = -4, 4 for (int a_sub = -size_level; a_sub <= -3; a_sub++) { square_matrix[a_sub + max_level][-4 + max_level] = 0; square_matrix[a_sub + max_level][4 + max_level] = 0; } square_matrix[-3 + max_level][-size_level + max_level] = 0; square_matrix[-3 + max_level][size_level + max_level] = 0; // c = -1, 1 for (int a_sub = 4; a_sub <= size_level; a_sub++) { square_matrix[-1 + max_level][a_sub + max_level] = 0; square_matrix[1 + max_level][a_sub + max_level] = 0; square_matrix[-1 + max_level][-a_sub + max_level] = 0; square_matrix[1 + max_level][-a_sub + max_level] = 0; } square_matrix[4 + max_level][-3 + max_level] = 0; square_matrix[4 + max_level][-4 + max_level] = 0; square_matrix[3 + max_level][-4 + max_level] = 0; square_matrix[3 + max_level][-size_level + max_level] = 0; square_matrix[5 + max_level][4 + max_level] = 0; square_matrix[4 + max_level][4 + max_level] = 0; square_matrix[4 + max_level][size_level + max_level] = 0; square_matrix[3 + max_level][size_level + max_level] = 0; square_matrix[max_level - size_level][max_level - size_level] = 2; } if (level == 8) { // vertical for (int a_sub = -4; a_sub <= 4; a_sub++) { square_matrix[max_level][max_level + a_sub] = 0; square_matrix[max_level - 4][max_level + a_sub] = 0; } // horizontal for (int a_sub = 0; a_sub <= 4; a_sub++) { square_matrix[max_level - a_sub][max_level - 4] = 0; square_matrix[max_level + a_sub][max_level + 4] = 0; } square_matrix[max_level + size_level][max_level + 4] = 0; square_matrix[max_level - size_level][max_level + 4] = 0; square_matrix[max_level - 4][max_level] = 10; square_matrix[max_level][max_level + 1] = 2; } if (level == 9) { // vertical for (int a_sub = -4; a_sub <= 4; a_sub++) { square_matrix[max_level][max_level + a_sub] = 0; square_matrix[max_level + 4][max_level + a_sub] = 0; } // horizontal for (int a_sub = 0; a_sub <= 4; a_sub++) { square_matrix[max_level + a_sub][max_level - 4] = 0; square_matrix[max_level - a_sub][max_level + 4] = 0; } square_matrix[max_level + size_level][max_level + 4] = 0; square_matrix[max_level - size_level][max_level + 4] = 0; square_matrix[max_level + 4][max_level] = 10; square_matrix[max_level][max_level + 1] = 2; } if (level == 10) { // cross for (int a_sub = -size_level; a_sub <= size_level; a_sub++) { square_matrix[max_level][max_level + a_sub] = 0; square_matrix[max_level + a_sub][max_level] = 0; } square_matrix[max_level + 1][max_level + 1] = 0; square_matrix[max_level - 1][max_level + 1] = 0; square_matrix[max_level + 1][max_level - 1] = 0; square_matrix[max_level - 1][max_level - 1] = 0; } if (level == 11) { // cross for (int a_sub = 1; a_sub <= size_level; a_sub++) { square_matrix[max_level - a_sub][max_level + 1] = 0; square_matrix[max_level - a_sub][max_level + 2] = 0; square_matrix[max_level - a_sub][max_level + 4] = 0; square_matrix[max_level - a_sub][max_level - 1] = 0; square_matrix[max_level - a_sub][max_level - 3] = 0; square_matrix[max_level - a_sub][max_level - 5] = 0; square_matrix[max_level + a_sub][max_level + 1] = 0; square_matrix[max_level + a_sub][max_level + 4] = 0; square_matrix[max_level + a_sub][max_level - 1] = 0; square_matrix[max_level + a_sub][max_level - 3] = 0; square_matrix[max_level + a_sub][max_level - 5] = 0; square_matrix[max_level + 1][max_level + a_sub] = 1; square_matrix[max_level + a_sub][max_level + 2] = 0; square_matrix[max_level + 1][max_level - a_sub] = 1; } square_matrix[max_level][max_level - 1] = 0; square_matrix[max_level + 2][max_level - 2] = 0; square_matrix[max_level][max_level - 3] = 0; square_matrix[max_level][max_level - 4] = 0; square_matrix[max_level][max_level - 5] = 0; square_matrix[max_level + 2][max_level + 5] = 0; square_matrix[max_level + 1][max_level + 2] = 0; square_matrix[max_level - 2][max_level + 3] = 0; square_matrix[max_level - 4][max_level + 2] = 1; square_matrix[max_level - 3][max_level + 2] = 1; square_matrix[max_level - 1][max_level + 2] = 1; square_matrix[max_level + 3][max_level + 2] = 1; square_matrix[max_level - 1][max_level + 1] = 1; square_matrix[max_level + 5][max_level + 1] = 1; square_matrix[max_level + 3][max_level - 5] = 3; square_matrix[max_level - 2][max_level - 3] = 3; square_matrix[max_level - 2][max_level + 1] = 3; square_matrix[max_level + 4][max_level + 1] = 3; square_matrix[max_level - 4][max_level + 4] = 3; square_matrix[max_level][max_level + 2] = 2; } if (level == 12) { // cross for (int a_sub = 1; a_sub <= size_level; a_sub++) { square_matrix[max_level + a_sub][max_level + 1] = 0; square_matrix[max_level + a_sub][max_level + 2] = 0; square_matrix[max_level + a_sub][max_level + 4] = 0; square_matrix[max_level + a_sub][max_level - 1] = 0; square_matrix[max_level + a_sub][max_level - 3] = 0; square_matrix[max_level + a_sub][max_level - 5] = 0; square_matrix[max_level - a_sub][max_level + 1] = 0; square_matrix[max_level - a_sub][max_level + 4] = 0; square_matrix[max_level - a_sub][max_level - 1] = 0; square_matrix[max_level - a_sub][max_level - 3] = 0; square_matrix[max_level - a_sub][max_level - 5] = 0; square_matrix[max_level - 1][max_level + a_sub] = 1; square_matrix[max_level - a_sub][max_level + 2] = 0; square_matrix[max_level - 1][max_level - a_sub] = 1; } square_matrix[max_level][max_level - 1] = 0; square_matrix[max_level - 2][max_level - 2] = 0; square_matrix[max_level][max_level - 3] = 0; square_matrix[max_level][max_level - 4] = 0; square_matrix[max_level][max_level - 5] = 0; square_matrix[max_level - 2][max_level + 5] = 0; square_matrix[max_level - 1][max_level + 2] = 0; square_matrix[max_level + 2][max_level + 3] = 0; square_matrix[max_level + 4][max_level + 2] = 1; square_matrix[max_level + 3][max_level + 2] = 1; square_matrix[max_level + 1][max_level + 2] = 1; square_matrix[max_level - 3][max_level + 2] = 1; square_matrix[max_level + 1][max_level + 1] = 1; square_matrix[max_level - 5][max_level + 1] = 1; square_matrix[max_level - 4][max_level - 5] = 3; square_matrix[max_level + 2][max_level - 3] = 3; square_matrix[max_level + 2][max_level + 2] = 3; square_matrix[max_level - 2][max_level + 1] = 3; square_matrix[max_level + 4][max_level + 4] = 3; square_matrix[max_level + 1][max_level - 1] = 5; square_matrix[max_level + 3][max_level - 1] = 5; square_matrix[max_level + 5][max_level - 1] = 5; square_matrix[max_level - 4][max_level - 1] = 5; square_matrix[max_level - 2][max_level - 1] = 5; square_matrix[max_level - 4][max_level - 3] = 5; square_matrix[max_level + 5][max_level - 3] = 5; square_matrix[max_level + 3][max_level - 3] = 5; square_matrix[max_level + 1][max_level - 3] = 5; square_matrix[max_level + 1][max_level - 5] = 5; square_matrix[max_level + 4][max_level - 5] = 5; square_matrix[max_level - 5][max_level - 5] = 5; square_matrix[max_level - 2][max_level - 5] = 5; square_matrix[max_level - 2][max_level + 4] = 5; square_matrix[max_level - 5][max_level + 4] = 5; square_matrix[max_level + 3][max_level + 4] = 5; square_matrix[max_level + 2][max_level + 1] = 5; square_matrix[max_level + 5][max_level + 1] = 5; square_matrix[max_level - 3][max_level + 1] = 5; square_matrix[max_level - 4][max_level + 2] = 5; square_matrix[max_level][max_level + 2] = 2; } if (level == 13) { square_matrix[max_level][max_level - 1] = 0; for (int a_sub = -5; a_sub <= 5; a_sub++) { square_matrix[max_level + a_sub][max_level - 2] = 0; square_matrix[max_level + a_sub][max_level + 5] = 0; } for (int a_sub = 3; a_sub <= 5; a_sub++) { square_matrix[max_level - 4][max_level - a_sub] = 0; square_matrix[max_level - 2][max_level - a_sub] = 0; square_matrix[max_level][max_level - a_sub] = 0; square_matrix[max_level + 2][max_level - a_sub] = 0; square_matrix[max_level + 4][max_level - a_sub] = 0; square_matrix[max_level - a_sub][max_level] = 0; square_matrix[max_level + a_sub][max_level] = 0; } for (int a_sub = -1; a_sub <= 1; a_sub++) { square_matrix[max_level + a_sub][max_level + 3] = 0; } for (int a_sub = 0; a_sub <= 3; a_sub++) { square_matrix[max_level - 2][max_level + a_sub] = 0; square_matrix[max_level + 2][max_level + a_sub] = 0; square_matrix[max_level - 4][max_level + a_sub + 1] = 0; square_matrix[max_level + 4][max_level + a_sub + 1] = 0; } for (int a_sub = -4; a_sub <= 4; a_sub = a_sub + 2) { square_matrix[max_level + a_sub][max_level - 5] = 3; square_matrix[max_level + a_sub][max_level - 3] = 3; square_matrix[max_level + a_sub][max_level] = 3; square_matrix[max_level + a_sub][max_level + 5] = 3; } square_matrix[max_level - 4][max_level + 2] = 3; square_matrix[max_level + 4][max_level + 2] = 3; square_matrix[max_level - 4][max_level + 4] = 3; square_matrix[max_level + 4][max_level + 4] = 3; square_matrix[max_level - 2][max_level + 3] = 3; square_matrix[max_level][max_level + 3] = 3; square_matrix[max_level + 2][max_level + 3] = 3; square_matrix[max_level - 4][max_level - 4] = 7; square_matrix[max_level - 2][max_level - 4] = 6; square_matrix[max_level][max_level - 4] = 5; square_matrix[max_level + 2][max_level - 4] = 6; square_matrix[max_level + 4][max_level - 4] = 7; square_matrix[max_level - 5][max_level - 2] = 7; square_matrix[max_level - 3][max_level - 2] = 6; square_matrix[max_level - 1][max_level - 2] = 5; square_matrix[max_level + 1][max_level - 2] = 5; square_matrix[max_level + 3][max_level - 2] = 6; square_matrix[max_level + 5][max_level - 2] = 7; square_matrix[max_level - 3][max_level] = 8; square_matrix[max_level + 3][max_level] = 8; square_matrix[max_level - 2][max_level + 1] = 7; square_matrix[max_level + 2][max_level + 1] = 7; square_matrix[max_level - 2][max_level + 2] = 7; square_matrix[max_level + 2][max_level + 2] = 7; square_matrix[max_level - 1][max_level + 3] = 8; square_matrix[max_level + 1][max_level + 3] = 8; square_matrix[max_level - 5][max_level + 5] = 6; square_matrix[max_level - 3][max_level + 5] = 7; square_matrix[max_level - 1][max_level + 5] = 8; square_matrix[max_level + 1][max_level + 5] = 8; square_matrix[max_level + 3][max_level + 5] = 7; square_matrix[max_level + 5][max_level + 5] = 6; square_matrix[max_level][max_level + 2] = 2; } if (level == 14) { for (int a_sub = -5; a_sub <= 5; a_sub++) { for (int b_sub = 1; b_sub <= 5; b_sub++) { square_matrix[max_level + a_sub][max_level - b_sub] = 0; square_matrix[max_level + a_sub][max_level + b_sub] = 0; } square_matrix[max_level + a_sub][max_level] = 1; } square_matrix[max_level][max_level + 1] = 0; for (int a_sub = 2; a_sub <= 5; a_sub++) { square_matrix[max_level - 3][max_level - a_sub] = 3; square_matrix[max_level - 1][max_level - a_sub] = 3; square_matrix[max_level + 1][max_level - a_sub] = 3; square_matrix[max_level + 3][max_level - a_sub] = 3; square_matrix[max_level - 3][max_level + a_sub] = 3; square_matrix[max_level + 3][max_level + a_sub] = 3; } for (int a_sub = -2; a_sub <= 2; a_sub++) { square_matrix[max_level + a_sub][max_level + 2] = 3; } square_matrix[max_level - 1][max_level + 5] = 3; square_matrix[max_level + 1][max_level + 5] = 3; square_matrix[max_level - 1][max_level + 4] = 3; square_matrix[max_level + 1][max_level + 4] = 3; square_matrix[max_level - 5][max_level + 5] = 3; square_matrix[max_level + 5][max_level + 5] = 3; square_matrix[max_level - 5][max_level + 1] = 3; square_matrix[max_level + 5][max_level + 1] = 3; square_matrix[max_level - 5][max_level - 2] = 3; square_matrix[max_level + 5][max_level - 2] = 3; square_matrix[max_level - 4][max_level + 3] = 3; square_matrix[max_level + 4][max_level + 3] = 3; square_matrix[max_level - 4][max_level - 4] = 3; square_matrix[max_level + 4][max_level - 4] = 3; square_matrix[max_level - 1][max_level - 1] = 3; square_matrix[max_level + 1][max_level - 1] = 3; square_matrix[max_level][max_level + 1] = 2; } if (level == 15) { for (int a_sub = 1; a_sub <= 5; a_sub++) { square_matrix[max_level - a_sub][max_level + 1] = 0; square_matrix[max_level + a_sub][max_level + 3] = 0; square_matrix[max_level][max_level - a_sub] = 0; } for (int a_sub = 0; a_sub <= 2; a_sub++) { square_matrix[max_level + 5][max_level - 5 + a_sub] = 0; square_matrix[max_level + 5][max_level - 1 + a_sub] = 0; square_matrix[max_level - 2][max_level + 3 + a_sub] = 0; square_matrix[max_level][max_level + 3 + a_sub] = 0; square_matrix[max_level - 5 + a_sub][max_level + 3] = 0; square_matrix[max_level - 5 + a_sub][max_level + 5] = 0; } square_matrix[max_level + 5][max_level + 5] = 0; square_matrix[max_level][max_level - 4] = 10; square_matrix[max_level][max_level + 3] = 10; square_matrix[max_level][max_level + 5] = 10; square_matrix[max_level - 5][max_level + 3] = 10; square_matrix[max_level - 3][max_level + 3] = 10; square_matrix[max_level - 5][max_level + 5] = 10; square_matrix[max_level - 3][max_level + 5] = 10; square_matrix[max_level + 2][max_level + 3] = 10; square_matrix[max_level + 4][max_level + 3] = 10; square_matrix[max_level - 2][max_level + 4] = 10; square_matrix[max_level][max_level - 5] = 3; square_matrix[max_level][max_level + 4] = 3; square_matrix[max_level - 4][max_level + 3] = 3; square_matrix[max_level - 2][max_level + 3] = 3; square_matrix[max_level - 4][max_level + 5] = 3; square_matrix[max_level - 2][max_level + 5] = 3; square_matrix[max_level + 1][max_level + 3] = 3; square_matrix[max_level + 3][max_level + 3] = 3; square_matrix[max_level + 5][max_level + 3] = 3; square_matrix[max_level - 5][max_level + 1] = 5; square_matrix[max_level - 4][max_level + 1] = 6; square_matrix[max_level - 3][max_level + 1] = 7; square_matrix[max_level - 2][max_level + 1] = 8; square_matrix[max_level - 1][max_level + 1] = 2; } if ((level >= level_threshold) && (level <= 21)) { square_matrix[max_level - 1][max_level + 1] = 1; square_matrix[max_level][max_level + 1] = 1; square_matrix[max_level + 1][max_level + 1] = 1; square_matrix[max_level][max_level + 2] = 2; } if ((level >= 22) && (level <= 25)) { square_matrix[max_level - 1][max_level + 1] = 1; square_matrix[max_level][max_level + 1] = 1; square_matrix[max_level + 1][max_level + 1] = 1; square_matrix[max_level - 1][max_level] = 1; square_matrix[max_level + 1][max_level] = 1; square_matrix[max_level - 1][max_level - 1] = 1; square_matrix[max_level + 1][max_level - 1] = 1; } if (level == 26) { square_matrix[max_level + size_level/2][max_level] = 1; square_matrix[max_level + size_level/2 - 1][max_level] = 10; square_matrix[max_level + size_level/2 + 1][max_level] = 10; square_matrix[max_level + size_level/2][max_level + 1] = 10; square_matrix[max_level + size_level/2][max_level - 1] = 10; square_matrix[max_level - size_level/2][max_level] = 1; square_matrix[max_level - size_level/2 + 1][max_level] = 10; square_matrix[max_level - size_level/2 - 1][max_level] = 10; square_matrix[max_level - size_level/2][max_level + 1] = 10; square_matrix[max_level - size_level/2][max_level - 1] = 10; square_matrix[max_level][max_level + size_level/2] = 1; square_matrix[max_level][max_level + size_level/2 - 1] = 10; square_matrix[max_level][max_level + size_level/2 + 1] = 10; square_matrix[max_level + 1][max_level + size_level/2] = 10; square_matrix[max_level - 1][max_level + size_level/2] = 10; square_matrix[max_level][max_level - size_level/2] = 1; square_matrix[max_level][max_level - size_level/2 + 1] = 10; square_matrix[max_level][max_level - size_level/2 - 1] = 10; square_matrix[max_level + 1][max_level - size_level/2] = 10; square_matrix[max_level - 1][max_level - size_level/2] = 10; } if (level == 27) { for (int a_sub = -27; a_sub <= 27; a_sub += 6) { for (int b_sub = -size_level; b_sub <= size_level; b_sub++) { square_matrix[max_level + a_sub][max_level + b_sub] = 1; square_matrix[max_level + b_sub][max_level + a_sub] = 1; } } for (int a_sub = -24; a_sub <= 24; a_sub += 6) { for (int b_sub = -24; b_sub <= 24; b_sub += 6) { square_matrix[max_level + a_sub][max_level + b_sub] = 5; } } square_matrix[max_level - 1][max_level + 1] = 1; square_matrix[max_level][max_level + 1] = 1; square_matrix[max_level + 1][max_level + 1] = 1; square_matrix[max_level - 1][max_level] = 1; square_matrix[max_level + 1][max_level] = 1; square_matrix[max_level - 1][max_level - 1] = 1; square_matrix[max_level + 1][max_level - 1] = 1; square_matrix[max_level + 3][max_level] = 0; square_matrix[max_level - 3][max_level] = 0; square_matrix[max_level][max_level + 3] = 0; square_matrix[max_level][max_level - 3] = 0; square_matrix[max_level + 27][max_level + 27] = 2; square_matrix[max_level - 27][max_level + 27] = 8; square_matrix[max_level + 27][max_level - 27] = 8; square_matrix[max_level - 27][max_level - 27] = 8; square_matrix[max_level + 26][max_level + 27] = 7; square_matrix[max_level + 27][max_level + 26] = 7; square_matrix[max_level - 26][max_level + 27] = 7; square_matrix[max_level - 27][max_level + 26] = 7; square_matrix[max_level + 26][max_level - 27] = 7; square_matrix[max_level + 27][max_level - 26] = 7; square_matrix[max_level - 26][max_level - 27] = 7; square_matrix[max_level - 27][max_level - 26] = 7; } if (level == 28) { for (int a_sub = 27; a_sub <= 28; a_sub++) { for (int b_sub = 27; b_sub <= 28; b_sub++) { square_matrix[max_level + a_sub][max_level + b_sub] = 6; square_matrix[max_level - a_sub][max_level + b_sub] = 6; square_matrix[max_level + a_sub][max_level - b_sub] = 6; square_matrix[max_level - a_sub][max_level - b_sub] = 6; } } square_matrix[max_level + 28][max_level + 28] = 2; square_matrix[max_level - 28][max_level - 28] = 4; for (int a_sub = -15; a_sub <= 15; a_sub += 6) { for (int b_sub = -16; b_sub <= 16; b_sub++) { square_matrix[max_level + a_sub][max_level + b_sub] = 1; square_matrix[max_level + b_sub][max_level + a_sub] = 1; } } for (int a_sub = -12; a_sub <= 12; a_sub += 6) { for (int b_sub = -12; b_sub <= 12; b_sub += 6) { square_matrix[max_level + a_sub][max_level + b_sub] = 5; } } } if (level == 29) { for (int a_sub = 28; a_sub <= 29; a_sub++) { for (int b_sub = 28; b_sub <= 29; b_sub++) { square_matrix[max_level + a_sub][max_level + b_sub] = 7; square_matrix[max_level - a_sub][max_level + b_sub] = 7; square_matrix[max_level + a_sub][max_level - b_sub] = 7; square_matrix[max_level - a_sub][max_level - b_sub] = 7; } } square_matrix[max_level + 29][max_level + 29] = 2; } if (!(level == 28)) { square_matrix[max_level][max_level] = 4; } if (level <= 7) { square_matrix[max_level][max_level] = 10; } if (level <= 3) { square_matrix[max_level][max_level + 1] = 2; } if (level == 4) { square_matrix[max_level][max_level] = 0; square_matrix[max_level][max_level - 2] = 10; square_matrix[max_level][max_level - 3] = 2; } if ((level >= level_threshold) && false) { square_matrix[max_level][1 + max_level] = 1; for (int a_sub = -1; a_sub <= 1; a_sub = a_sub + 2) { for (int b_sub = -1; b_sub <= 1; b_sub++) { square_matrix[a_sub + max_level][b_sub + max_level] = 1; } } } if (level != 26) { for (int a_sub = -size_level - 2; a_sub <= size_level + 2; a_sub++) { for (int b_sub = -size_level - 2; b_sub <= size_level + 2; b_sub++) { // std::cout << square_matrix[a_sub + max_level][b_sub + max_level] << " "; if (square_matrix[a_sub + max_level][b_sub + max_level] < 10) { // std::cout << " "; } } // std::cout << "\n"; } } // std::cout << "\n"; up_movement = false; right_movement = false; down_movement = false; left_movement = false; turning = false; exchange = false; build = false; timeshift = false; timeshift = true; if (level >= 1) { if (testing) { right_movement = true; down_movement = true; left_movement = true; turning = true; exchange = true; build = true; timeshift = true; } } if (level >= 1) { up_movement = true; } if (level == 2) { up_movement = true; right_movement = true; } if (level == 3) { up_movement = true; left_movement = true; } if (level == 4) { down_movement = true; } if (level == 5) { right_movement = true; left_movement = true; down_movement = true; up_movement = true; } if (level == 6) { right_movement = false; left_movement = false; down_movement = true; up_movement = true; turning = true; } if (level == 7) { right_movement = true; left_movement = true; down_movement = true; up_movement = true; turning = true; build = true; } if (level == 8) { right_movement = true; left_movement = true; down_movement = true; up_movement = true; turning = true; exchange = true; build = true; } if (level == 9) { right_movement = true; left_movement = true; down_movement = true; up_movement = true; turning = true; exchange = true; build = true; } if (level == 10) { right_movement = true; left_movement = true; down_movement = true; up_movement = true; turning = true; exchange = true; build = true; } if (level == 11) { right_movement = true; left_movement = true; down_movement = true; up_movement = true; turning = true; exchange = true; build = true; } if (level == 12) { right_movement = true; left_movement = true; down_movement = true; up_movement = true; turning = true; exchange = true; build = true; } if (level == 13) { right_movement = true; left_movement = true; down_movement = true; up_movement = true; turning = true; // exchange = true; build = true; } if (level == 14) { right_movement = true; left_movement = true; down_movement = true; up_movement = true; turning = true; // exchange = true; build = true; } if (level == 15) { right_movement = true; left_movement = true; down_movement = true; up_movement = true; turning = true; exchange = true; build = true; } if ((level >= 16) && (level <= 22)) { right_movement = true; left_movement = true; down_movement = true; up_movement = true; turning = true; exchange = true; build = true; } if (level == 23) { right_movement = true; left_movement = true; down_movement = true; up_movement = true; turning = true; build = true; } if ((level >= 24) && (level < 25)) { right_movement = true; left_movement = true; down_movement = true; up_movement = true; turning = true; exchange = true; build = true; } if (level == 25) { right_movement = true; left_movement = true; down_movement = true; up_movement = true; turning = true; build = true; } if (level == 26) { right_movement = true; left_movement = true; down_movement = true; up_movement = true; turning = true; build = true; } if (level == 27) { right_movement = true; left_movement = true; down_movement = true; up_movement = true; exchange = true; turning = true; build = true; } if (level == 28) { right_movement = true; left_movement = true; down_movement = true; up_movement = true; turning = true; build = true; } if (level == 29) { right_movement = true; left_movement = true; down_movement = true; up_movement = true; turning = true; build = true; } if (level > 50) { timeshift = true; } // square_matrix[max_level][-3 + max_level] = 3; local_x = 0; local_y = -1; view.setCenter(0, -squarep); view.setRotation(0); scanner_sprite.setPosition(sf::Vector2f(0, -squarep)); scanner_sprite.setRotation(0); compass_back_sprite.setOrigin(sf::Vector2f(12, 12)); compass_back_sprite.setPosition(sf::Vector2f(0, -squarep)); compass_back_sprite.setRotation(0); compass_sprite.setOrigin(sf::Vector2f(12, 12)); compass_sprite.setPosition(sf::Vector2f(0, -squarep)); compass_sprite.setRotation(0); arrow_sprite.setOrigin(sf::Vector2f(12, 12)); arrow_sprite.setPosition(sf::Vector2f(0, -squarep)); arrow_sprite.setRotation(0); infobox.setPosition(sf::Vector2f(0, -squarep)); infobox.setRotation(0); key_up_sprite.setPosition(sf::Vector2f(0, -squarep)); key_up_sprite.setRotation(0); key_right_sprite.setPosition(sf::Vector2f(0, -squarep)); key_right_sprite.setRotation(0); key_down_sprite.setPosition(sf::Vector2f(0, -squarep)); key_down_sprite.setRotation(0); key_left_sprite.setPosition(sf::Vector2f(0, -squarep)); key_left_sprite.setRotation(0); key_d_sprite.setPosition(sf::Vector2f(0, -squarep)); key_d_sprite.setRotation(0); key_right_turn_sprite.setPosition(sf::Vector2f(0, -squarep)); key_right_turn_sprite.setRotation(0); key_a_sprite.setPosition(sf::Vector2f(0, -squarep)); key_a_sprite.setRotation(0); key_left_turn_sprite.setPosition(sf::Vector2f(0, -squarep)); key_left_turn_sprite.setRotation(0); key_w_sprite.setPosition(sf::Vector2f(0, -squarep)); key_w_sprite.setRotation(0); exchange_sprite.setPosition(sf::Vector2f(0, -squarep)); exchange_sprite.setRotation(0); key_x_sprite.setPosition(sf::Vector2f(0, -squarep)); key_x_sprite.setRotation(0); build_sprite.setPosition(sf::Vector2f(0, -squarep)); build_sprite.setRotation(0); key_v_sprite.setPosition(sf::Vector2f(0, -squarep)); key_v_sprite.setRotation(0); timeshift_sprite.setPosition(sf::Vector2f(0, -squarep)); timeshift_sprite.setRotation(0); key_r_sprite.setPosition(sf::Vector2f(0, -squarep)); key_r_sprite.setRotation(0); reset_sprite.setPosition(sf::Vector2f(0, -squarep)); reset_sprite.setRotation(0); key_esc_sprite.setPosition(sf::Vector2f(0, -squarep)); key_esc_sprite.setRotation(0); for (int b_sub = 0; b_sub <= max_pow; b_sub++) { level_sprite[b_sub].setPosition(sf::Vector2f(0, -squarep)); level_sprite[b_sub].setRotation(0); dollar_sprite[b_sub].setPosition(sf::Vector2f(0, -squarep)); dollar_sprite[b_sub].setRotation(0); } for (int a_sub = 0; a_sub < number_max; a_sub++) { for (int b_sub = 0; b_sub <= max_pow; b_sub++) { number_sprite[a_sub][b_sub].setPosition(sf::Vector2f(0, -squarep)); number_sprite[a_sub][b_sub].setRotation(0); dosh_sprite[a_sub][b_sub].setPosition(sf::Vector2f(0, -squarep)); dosh_sprite[a_sub][b_sub].setRotation(0); } } if (!two_turn_uplight) { key_up_uplight = false; key_right_uplight= false; key_down_uplight = false; key_left_uplight = false; key_d_uplight = false; key_a_uplight = false; key_w_uplight = false; key_x_uplight = false; key_r_uplight = false; key_v_uplight = false; } action = true; final_move[0] = 0; final_move[1] = 0; dir_up[0] = 0; dir_up[1] = -1; dir_down[0] = 0; dir_down[1] = 1; dir_right[0] = 1; dir_right[1] = 0; dir_left[0] = -1; dir_left[1] = 0; dir_direct[0] = 0; dir_direct[1] = 0; scan_pos_x = 0; scan_pos_y = -squarep; view_glitch = true; position_declare = true; dark_backed = false; first_dark_back = false; mouse_pressed = false; // std::cout << level_pass << "\n"; if (level_reset && false) { std::cout << "Level reset!" << "\n"; } window.setView(view); while (!level_change) { if (delay_flipping) { delay_flip -= 2; } if (inhale) { exhale = true; inhale = false; } if ((level == 1) && !glitch_excempt) { view_glitch = false; } glitch_excempt = false; dark_flicker = false; if (dark_setback) { level_recet = true; view_glitch = true; action = true; dark_flicker = true; local_x = 0; local_y = -1; view.setCenter(0, -squarep); scanner_sprite.setPosition(sf::Vector2f(0, -squarep)); compass_back_sprite.setOrigin(sf::Vector2f(12, 12)); compass_back_sprite.setPosition(sf::Vector2f(0, -squarep)); compass_sprite.setOrigin(sf::Vector2f(12, 12)); compass_sprite.setPosition(sf::Vector2f(0, -squarep)); arrow_sprite.setOrigin(sf::Vector2f(12, 12)); arrow_sprite.setPosition(sf::Vector2f(0, -squarep)); infobox.setPosition(sf::Vector2f(0, -squarep)); key_up_sprite.setPosition(sf::Vector2f(0, -squarep)); key_right_sprite.setPosition(sf::Vector2f(0, -squarep)); key_down_sprite.setPosition(sf::Vector2f(0, -squarep)); key_left_sprite.setPosition(sf::Vector2f(0, -squarep)); key_d_sprite.setPosition(sf::Vector2f(0, -squarep)); key_right_turn_sprite.setPosition(sf::Vector2f(0, -squarep)); key_a_sprite.setPosition(sf::Vector2f(0, -squarep)); key_left_turn_sprite.setPosition(sf::Vector2f(0, -squarep)); key_w_sprite.setPosition(sf::Vector2f(0, -squarep)); exchange_sprite.setPosition(sf::Vector2f(0, -squarep)); key_x_sprite.setPosition(sf::Vector2f(0, -squarep)); build_sprite.setPosition(sf::Vector2f(0, -squarep)); key_v_sprite.setPosition(sf::Vector2f(0, -squarep)); timeshift_sprite.setPosition(sf::Vector2f(0, -squarep)); key_r_sprite.setPosition(sf::Vector2f(0, -squarep)); reset_sprite.setPosition(sf::Vector2f(0, -squarep)); key_esc_sprite.setPosition(sf::Vector2f(0, -squarep)); for (int b_sub = 0; b_sub <= max_pow; b_sub++) { level_sprite[b_sub].setPosition(sf::Vector2f(0, -squarep)); dollar_sprite[b_sub].setPosition(sf::Vector2f(0, -squarep)); } for (int a_sub = 0; a_sub < number_max; a_sub++) { for (int b_sub = 0; b_sub <= max_pow; b_sub++) { number_sprite[a_sub][b_sub].setPosition(sf::Vector2f(0, -squarep)); dosh_sprite[a_sub][b_sub].setPosition(sf::Vector2f(0, -squarep)); } } final_move[0] = 0; final_move[1] = 0; dir_direct[0] = 0; dir_direct[1] = 0; scan_pos_x = 0; scan_pos_y = -squarep; window.setView(view); } if (!view_glitch && !exhale) { window.clear(sf::Color(color_black[0], color_black[1], color_black[2])); // window.clear(sf::Color(255, 255, 255)); for (int a_sub = -max_view; a_sub <= max_view; a_sub++) { pot_x = local_x + a_sub; pos_x = pot_x*squarep; if (pot_x > size_level) { pot_x = pot_x - level_side; } if (pot_x < -size_level) { pot_x = pot_x + level_side; } for (int b_sub = -max_view; b_sub <= max_view; b_sub++) { pot_y = local_y + b_sub; pos_y = pot_y*squarep; if (pot_y > size_level) { pot_y = pot_y - level_side; } if (pot_y < -size_level) { pot_y = pot_y + level_side; } Color_Picker(square_matrix[pot_x + max_level][pot_y + max_level], colours, exit_colors); if ((square_matrix[pot_x + max_level][pot_y + max_level] <= 4) || (square_matrix[pot_x + max_level][pot_y + max_level] == 10)) { square_transp = max_transp; } else { square_transp = blink; } if (square_matrix[pot_x + max_level][pot_y + max_level] == 3) { dark_transp = exp(-sqrt(1.0*a_sub*a_sub + 1.0*b_sub*b_sub)/(dark_mult)); } // dark_transp = 1; // qot_x = a_sub + local_x + c_sub*level_side; // qot_y = b_sub + local_y + d_sub*level_side; bitsquare_sprite.setPosition(pos_x, pos_y); if (square_matrix[pot_x + max_level][pot_y + max_level] == 0) { bitsquare_sprite.setColor(sf::Color(color_black[0], color_black[1], color_black[2], max_transp)); } if (square_matrix[pot_x + max_level][pot_y + max_level] == 3) { bitsquare_sprite.setColor(sf::Color(colours[0], colours[1], colours[2], round(dark_transp*max_transp))); } if ((square_matrix[pot_x + max_level][pot_y + max_level] == 0) || (square_matrix[pot_x + max_level][pot_y + max_level] == 3)) { window.draw(bitsquare_sprite); } // squaree = Square_Draw(squaree, colours, 128, pos_x, pos_y, squarrel, squarrel); // window.draw(squaree); if ((square_matrix[pot_x + max_level][pot_y + max_level] != 0) && (square_matrix[pot_x + max_level][pot_y + max_level] != 3)) { bitshadow_sprite.setPosition(pos_x, pos_y); bitshadow_sprite.setColor(sf::Color(background_blink, background_blink, background_blink, blink)); if ((square_matrix[pot_x + max_level][pot_y + max_level] == 1) || (square_matrix[pot_x + max_level][pot_y + max_level] == 2) || (square_matrix[pot_x + max_level][pot_y + max_level] == 4) || (square_matrix[pot_x + max_level][pot_y + max_level] == 10)) { bitshadow_sprite.setColor(sf::Color(background_blink, background_blink, background_blink, max_transp)); } window.draw(bitshadow_sprite); bitmask_sprite.setPosition(pos_x, pos_y); bitmask_sprite.setColor(sf::Color(colours[0], colours[1], colours[2], blink)); if ((square_matrix[pot_x + max_level][pot_y + max_level] == 1) || (square_matrix[pot_x + max_level][pot_y + max_level] == 4) || (square_matrix[pot_x + max_level][pot_y + max_level] == 10)) { bitmask_sprite.setColor(sf::Color(colours[0], colours[1], colours[2], max_transp)); } if (square_matrix[pot_x + max_level][pot_y + max_level] == 2) { bitmask_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); } // bitmask_sprite.setColor(sf::Color(colours[0], colours[1], colours[2], 128)); window.draw(bitmask_sprite); } } } window.draw(scanner_sprite); Color_Picker(2, colours, exit_colors); // squaree = Square_Draw(squaree, colours, max_transp, local_x*squarep, (local_x + 1)*squarep, squarrel, squarrel); // window.draw(squaree); compass_back_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); window.draw(compass_back_sprite); window.draw(compass_sprite); window.draw(arrow_sprite); if (level_recet) { Color_Picker(0, karasu, exit_colors); intro_filler = Square_Draw(intro_filler, karasu, toransupu, local_x*squarep, local_y*squarep, squarrel, squarrel); window.draw(intro_filler); action = true; } window.draw(infobox); if ((one_turn_uplight || two_turn_uplight) && (uplight_transp >= 0)) { if (key_up_uplight) { key_up_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], uplight_transp)); } if (key_right_uplight) { key_right_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], uplight_transp)); } if (key_down_uplight) { key_down_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], uplight_transp)); } if (key_left_uplight) { key_left_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], uplight_transp)); } if (key_down_uplight) { key_down_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], uplight_transp)); } if (key_d_uplight) { key_d_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], uplight_transp)); } if (key_a_uplight) { key_a_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], uplight_transp)); } if (key_w_uplight) { key_w_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], uplight_transp)); } if (key_x_uplight) { key_x_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], uplight_transp)); } if (key_v_uplight) { key_v_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], uplight_transp)); } if (key_r_uplight) { key_r_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], uplight_transp)); } // std::cout << uplight_transp << "\n"; } else { key_up_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_right_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_down_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_left_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_d_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_a_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_w_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_x_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_v_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_r_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); } key_esc_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); if (up_movement) { window.draw(key_up_sprite); } if (right_movement) { window.draw(key_right_sprite); } if (down_movement) { window.draw(key_down_sprite); } if (left_movement) { window.draw(key_left_sprite); } if (turning) { window.draw(key_d_sprite); window.draw(key_right_turn_sprite); window.draw(key_a_sprite); window.draw(key_left_turn_sprite); } if (exchange) { window.draw(key_w_sprite); window.draw(exchange_sprite); } if (build) { window.draw(key_x_sprite); window.draw(build_sprite); } if (timeshift) { window.draw(key_v_sprite); window.draw(timeshift_sprite); } window.draw(key_r_sprite); window.draw(reset_sprite); window.draw(key_esc_sprite); crunchy_number = level; crunched = 0; while (abs(crunchy_number) > 0) { window.draw(number_sprite[abs(crunchy_number) % 10][crunched]); crunchy_number = crunchy_number/10; crunched++; } window.draw(level_sprite[crunched]); for (int b_sub = 0; b_sub <= max_pow; b_sub++) { dollar_sprite[b_sub].setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], blink)); } crunchy_number = dosh; crunched = 0; if (crunchy_number == 0) { window.draw(dosh_sprite[crunchy_number][crunched]); crunched++; } while (abs(crunchy_number) > 0) { window.draw(dosh_sprite[abs(crunchy_number) % 10][crunched]); crunchy_number = crunchy_number/10; crunched++; } if (dosh < 0) { window.draw(dosh_sprite[10][crunched]); } window.draw(dollar_sprite[crunched]); window.display(); Color_Picker(level, kolours, exit_colors); Color_Picker(2, key_colour, exit_colors); for (int a_sub = 0; a_sub <= 2; a_sub++) { key_colour[a_sub] = 128 + key_colour[a_sub]/2; } Exit_Multicolor(exit_colors); if (blink_on) { if (blink < max_transp) { blink = blink + blink_delta; if (blink > max_transp) { blink = max_transp; } } else { blink_on = false; } } if (!blink_on) { if (blink > blink_min) { blink = blink - blink_delta; if (blink < blink_min) { blink = blink_min; } } else { blink_on = true; blink = blink + blink_delta; } } Background_Blinker(background_blink_on, background_blink, max_transp); } if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) { mouse_position = sf::Mouse::getPosition(window); mouse_pos_x = mouse_position.x; mouse_pos_y = mouse_position.y; mouse_pressed = true; // sf::Mouse::setPosition(sf::Vector2i(half_wind, half_wind), window); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape) || (mouse_pressed && (mouse_pos_x > 25) && (mouse_pos_x < 75) && (mouse_pos_y > 25) && (mouse_pos_y < 75))) { window.close(); return(0); } if (level_reset) { toransupu = 0; action = true; } dark_setback = false; inhale = false; timecop = false; if ((sf::Keyboard::isKeyPressed(sf::Keyboard::V) || (mouse_pressed && (mouse_pos_x > 275) && (mouse_pos_x < 325) && (mouse_pos_y > 525) && (mouse_pos_y < 575))) && timeshift && !exhale && !action) { action = true; timecop = true; key_v_uplight = true; one_turn_uplight = true; dir_direct[0] = 0; dir_direct[1] = 0; final_move[0] = dir_mult*dir_direct[0]; final_move[1] = dir_mult*dir_direct[1]; inhale_move_x = dir_direct[0]; inhale_move_y = dir_direct[1]; } if ((sf::Keyboard::isKeyPressed(sf::Keyboard::W) || (mouse_pressed && (mouse_pos_x > 150) && (mouse_pos_x < 200) && (mouse_pos_y > 525) && (mouse_pos_y < 575))) && exchange && !exhale && !action) { inhale = true; } if ((sf::Keyboard::isKeyPressed(sf::Keyboard::X) || (mouse_pressed && (mouse_pos_x > 200) && (mouse_pos_x < 250) && (mouse_pos_y > 525) && (mouse_pos_y < 575))) && build && !inhale && !exhale && !action) { building = true; } if ((inhale || building) && !exhale && !action && !(level_reset || level_recet)) { dir_direct[0] = dir_up[0]; dir_direct[1] = dir_up[1]; final_move[0] = dir_mult*dir_direct[0]; final_move[1] = dir_mult*dir_direct[1]; inhale_move_x = dir_direct[0]; inhale_move_y = dir_direct[1]; if ((abs(local_x + dir_direct[0]) <= size_level) && (abs(local_y + dir_direct[1]) <= size_level) && (square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] + max_level] != 1)) { if (inhale) { absorbed = square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] + max_level]; square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] + max_level] = assimilated; action = true; } if (building && !inhale && (square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] + max_level] == 0)) { square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] + max_level] = 10; action = true; } } if (((local_x + dir_direct[0]) > size_level) && (square_matrix[local_x + dir_direct[0] - level_side + max_level][local_y + dir_direct[1] + max_level] != 1)) { if (inhale) { absorbed = square_matrix[local_x + dir_direct[0] - level_side + max_level][local_y + dir_direct[1] + max_level]; square_matrix[local_x + dir_direct[0] - level_side + max_level][local_y + dir_direct[1] + max_level] = assimilated; action = true; } if (building && !inhale && (square_matrix[local_x + dir_direct[0] - level_side + max_level][local_y + dir_direct[1] + max_level] == 0)) { square_matrix[local_x + dir_direct[0] - level_side + max_level][local_y + dir_direct[1] + max_level] = 10; action = true; } } if (((local_x + dir_direct[0]) < -size_level) && (square_matrix[local_x + dir_direct[0] + level_side + max_level][local_y + dir_direct[1] + max_level] != 1)) { if (inhale) { absorbed = square_matrix[local_x + dir_direct[0] + level_side + max_level][local_y + dir_direct[1] + max_level]; square_matrix[local_x + dir_direct[0] + level_side + max_level][local_y + dir_direct[1] + max_level] = assimilated; action = true; } if (building && !inhale && (square_matrix[local_x + dir_direct[0] + level_side + max_level][local_y + dir_direct[1] + max_level] == 0)) { square_matrix[local_x + dir_direct[0] + level_side + max_level][local_y + dir_direct[1] + max_level] = 10; action = true; } } if (((local_y + dir_direct[1]) > size_level) && (square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] - level_side + max_level] != 1)) { if (inhale) { absorbed = square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] - level_side + max_level]; square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] - level_side + max_level] = assimilated; action = true; } if (building && !inhale && (square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] - level_side + max_level] == 0)) { square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] - level_side + max_level] = 10; action = true; } } if (((local_y + dir_direct[1]) < -size_level) && (square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] + level_side + max_level] != 1)) { if (inhale) { absorbed = square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] + level_side + max_level]; square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] + level_side + max_level] = assimilated; action = true; } if (building && !inhale && (square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] + level_side + max_level] == 0)) { square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] + level_side + max_level] = 10; action = true; } } if (inhale && action) { pacman = absorbed; one_turn_uplight = true; two_turn_uplight = true; key_w_uplight = true; } if (building && !inhale && action) { pacman = 10; one_turn_uplight = true; key_x_uplight = true; toransupu = 0; } if (!action) { inhale = false; building = false; } Color_Picker(pacman, karasu, exit_colors); } if (exhale && exchange && !action && !(level_reset || level_recet)) { dir_direct[0] = dir_up[0]; dir_direct[1] = dir_up[1]; final_move[0] = dir_mult*dir_direct[0]; final_move[1] = dir_mult*dir_direct[1]; inhale_move_x = dir_direct[0]; inhale_move_y = dir_direct[1]; pacman = assimilated; assimilated = absorbed; toransupu = 0; action = true; Color_Picker(pacman, karasu, exit_colors); } if (((sf::Keyboard::isKeyPressed(sf::Keyboard::Up) || (mouse_pressed && (mouse_pos_x > 475) && (mouse_pos_x < 525) && (mouse_pos_y > 475) && (mouse_pos_y < 525))) || (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) || (mouse_pressed && (mouse_pos_x > 475) && (mouse_pos_x < 525) && (mouse_pos_y > 525) && (mouse_pos_y < 575))) || (sf::Keyboard::isKeyPressed(sf::Keyboard::Right) || (mouse_pressed && (mouse_pos_x > 525) && (mouse_pos_x < 575) && (mouse_pos_y > 525) && (mouse_pos_y < 575))) || (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) || (mouse_pressed && (mouse_pos_x > 425) && (mouse_pos_x < 475) && (mouse_pos_y > 525) && (mouse_pos_y < 575)))) && !action && !(level_reset || level_recet)) { dir_direct[0] = 0; dir_direct[1] = 0; if ((sf::Keyboard::isKeyPressed(sf::Keyboard::Up) || (mouse_pressed && (mouse_pos_x > 475) && (mouse_pos_x < 525) && (mouse_pos_y > 475) && (mouse_pos_y < 525))) && up_movement) { dir_direct[0] = dir_up[0]; dir_direct[1] = dir_up[1]; one_turn_uplight = true; key_up_uplight = true; } if ((sf::Keyboard::isKeyPressed(sf::Keyboard::Down) || (mouse_pressed && (mouse_pos_x > 475) && (mouse_pos_x < 525) && (mouse_pos_y > 525) && (mouse_pos_y < 575))) && down_movement) { dir_direct[0] = dir_down[0]; dir_direct[1] = dir_down[1]; one_turn_uplight = true; key_down_uplight = true; } if ((sf::Keyboard::isKeyPressed(sf::Keyboard::Right) || (mouse_pressed && (mouse_pos_x > 525) && (mouse_pos_x < 575) && (mouse_pos_y > 525) && (mouse_pos_y < 575))) && right_movement) { dir_direct[0] = dir_right[0]; dir_direct[1] = dir_right[1]; one_turn_uplight = true; key_right_uplight = true; } if ((sf::Keyboard::isKeyPressed(sf::Keyboard::Left) || (mouse_pressed && (mouse_pos_x > 425) && (mouse_pos_x < 475) && (mouse_pos_y > 525) && (mouse_pos_y < 575))) && left_movement) { dir_direct[0] = dir_left[0]; dir_direct[1] = dir_left[1]; one_turn_uplight = true; key_left_uplight = true; } position_declare = true; if (position_declare) { for (int a_sub = -size_level - 2; a_sub <= size_level + 2; a_sub++) { for (int b_sub = -size_level - 2; b_sub <= size_level + 2; b_sub++) { // std::cout << square_matrix[a_sub + max_level][b_sub + max_level] << " "; if (square_matrix[a_sub + max_level][b_sub + max_level] < 10) { // std::cout << " "; } } // std::cout << "\n"; } // std::cout << "\n"; // std::cout << "[~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~]" << "\n"; // std::cout << "[" << local_x << "," << local_y << "]:" << square_matrix[local_x + max_level][local_y + max_level] << "\n"; // std::cout << "[" << local_x + dir_direct[0] << "," << local_y + dir_direct[1] << "]:" << square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] + max_level] << "\n"; // std::cout << "[" << local_x + dir_direct[0] - level_side << "," << local_y + dir_direct[1] << "]:" << square_matrix[local_x + dir_direct[0] - level_side + max_level][local_y + dir_direct[1] + max_level] << "\n"; // std::cout << "[" << local_x + dir_direct[0] + level_side << "," << local_y + dir_direct[1] << "]:" << square_matrix[local_x + dir_direct[0] + level_side + max_level][local_y + dir_direct[1] + max_level] << "\n"; // std::cout << "[" << local_x + dir_direct[0] << "," << local_y + dir_direct[1] - level_side << "]:" << square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] - level_side + max_level] << "\n"; // std::cout << "[" << local_x + dir_direct[0] << "," << local_y + dir_direct[1] + level_side << "]:" << square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] + level_side + max_level] << "\n"; // std::cout << "[~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~]" << "\n" << "\n"; } if ((abs(local_x + dir_direct[0]) <= size_level) && (abs(local_y + dir_direct[1]) <= size_level) && (square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] + max_level] != 1) && (square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] + max_level] != 10)) { moving = true; action = true; final_move[0] = dir_mult*dir_direct[0]; final_move[1] = dir_mult*dir_direct[1]; local_x = local_x + dir_direct[0]; local_y = local_y + dir_direct[1]; } if ((((local_x + dir_direct[0]) > size_level) && (square_matrix[local_x + dir_direct[0] - level_side + max_level][local_y + dir_direct[1] + max_level] != 1) && (square_matrix[local_x + dir_direct[0] - level_side + max_level][local_y + dir_direct[1] + max_level] != 10)) && !action) { moving = true; action = true; final_move[0] = dir_mult*dir_direct[0]; final_move[1] = dir_mult*dir_direct[1]; local_x = local_x + dir_direct[0]; local_y = local_y + dir_direct[1]; local_x = local_x - level_side; view.move(-level_side*squarep, 0); scanner_sprite.move(sf::Vector2f(-level_side*squarep, 0)); compass_back_sprite.move(sf::Vector2f(-level_side*squarep, 0)); compass_sprite.move(sf::Vector2f(-level_side*squarep, 0)); arrow_sprite.move(sf::Vector2f(-level_side*squarep, 0)); infobox.move(sf::Vector2f(-level_side*squarep, 0)); key_up_sprite.move(sf::Vector2f(-level_side*squarep, 0)); key_right_sprite.move(sf::Vector2f(-level_side*squarep, 0)); key_down_sprite.move(sf::Vector2f(-level_side*squarep, 0)); key_left_sprite.move(sf::Vector2f(-level_side*squarep, 0)); key_d_sprite.move(sf::Vector2f(-level_side*squarep, 0)); key_right_turn_sprite.move(sf::Vector2f(-level_side*squarep, 0)); key_a_sprite.move(sf::Vector2f(-level_side*squarep, 0)); key_left_turn_sprite.move(sf::Vector2f(-level_side*squarep, 0)); key_w_sprite.move(sf::Vector2f(-level_side*squarep, 0)); exchange_sprite.move(sf::Vector2f(-level_side*squarep, 0)); key_x_sprite.move(sf::Vector2f(-level_side*squarep, 0)); build_sprite.move(sf::Vector2f(-level_side*squarep, 0)); key_v_sprite.move(sf::Vector2f(-level_side*squarep, 0)); timeshift_sprite.move(sf::Vector2f(-level_side*squarep, 0)); key_r_sprite.move(sf::Vector2f(-level_side*squarep, 0)); reset_sprite.move(sf::Vector2f(-level_side*squarep, 0)); key_esc_sprite.move(sf::Vector2f(-level_side*squarep, 0)); for (int b_sub = 0; b_sub <= max_pow; b_sub++) { level_sprite[b_sub].move(sf::Vector2f(-level_side*squarep, 0)); dollar_sprite[b_sub].move(sf::Vector2f(-level_side*squarep, 0)); } for (int a_sub = 0; a_sub < number_max; a_sub++) { for (int b_sub = 0; b_sub <= max_pow; b_sub++) { number_sprite[a_sub][b_sub].move(sf::Vector2f(-level_side*squarep, 0)); dosh_sprite[a_sub][b_sub].move(sf::Vector2f(-level_side*squarep, 0)); } } scan_pos_x = scan_pos_x - level_side*squarep; } if ((((local_x + dir_direct[0]) < -size_level) && (square_matrix[local_x + dir_direct[0] + level_side + max_level][local_y + dir_direct[1] + max_level] != 1) && (square_matrix[local_x + dir_direct[0] + level_side + max_level][local_y + dir_direct[1] + max_level] != 10)) && !action) { moving = true; action = true; final_move[0] = dir_mult*dir_direct[0]; final_move[1] = dir_mult*dir_direct[1]; local_x = local_x + dir_direct[0]; local_y = local_y + dir_direct[1]; local_x = local_x + level_side; view.move(level_side*squarep, 0); scanner_sprite.move(sf::Vector2f(level_side*squarep, 0)); compass_back_sprite.move(sf::Vector2f(level_side*squarep, 0)); compass_sprite.move(sf::Vector2f(level_side*squarep, 0)); arrow_sprite.move(sf::Vector2f(level_side*squarep, 0)); infobox.move(sf::Vector2f(level_side*squarep, 0)); key_up_sprite.move(sf::Vector2f(level_side*squarep, 0)); key_right_sprite.move(sf::Vector2f(level_side*squarep, 0)); key_down_sprite.move(sf::Vector2f(level_side*squarep, 0)); key_left_sprite.move(sf::Vector2f(level_side*squarep, 0)); key_d_sprite.move(sf::Vector2f(level_side*squarep, 0)); key_right_turn_sprite.move(sf::Vector2f(level_side*squarep, 0)); key_a_sprite.move(sf::Vector2f(level_side*squarep, 0)); key_left_turn_sprite.move(sf::Vector2f(level_side*squarep, 0)); key_w_sprite.move(sf::Vector2f(level_side*squarep, 0)); exchange_sprite.move(sf::Vector2f(level_side*squarep, 0)); key_x_sprite.move(sf::Vector2f(level_side*squarep, 0)); build_sprite.move(sf::Vector2f(level_side*squarep, 0)); key_v_sprite.move(sf::Vector2f(level_side*squarep, 0)); timeshift_sprite.move(sf::Vector2f(level_side*squarep, 0)); key_r_sprite.move(sf::Vector2f(level_side*squarep, 0)); reset_sprite.move(sf::Vector2f(level_side*squarep, 0)); key_esc_sprite.move(sf::Vector2f(level_side*squarep, 0)); for (int b_sub = 0; b_sub <= max_pow; b_sub++) { level_sprite[b_sub].move(sf::Vector2f(level_side*squarep, 0)); dollar_sprite[b_sub].move(sf::Vector2f(level_side*squarep, 0)); } for (int a_sub = 0; a_sub < number_max; a_sub++) { for (int b_sub = 0; b_sub <= max_pow; b_sub++) { number_sprite[a_sub][b_sub].move(sf::Vector2f(level_side*squarep, 0)); dosh_sprite[a_sub][b_sub].move(sf::Vector2f(level_side*squarep, 0)); } } scan_pos_x = scan_pos_x + level_side*squarep; } if ((((local_y + dir_direct[1]) > size_level) && (square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] - level_side + max_level] != 1) && (square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] - level_side + max_level] != 10)) && !action) { moving = true; action = true; final_move[0] = dir_mult*dir_direct[0]; final_move[1] = dir_mult*dir_direct[1]; local_x = local_x + dir_direct[0]; local_y = local_y + dir_direct[1]; local_y = local_y - level_side; view.move(0, -level_side*squarep); scanner_sprite.move(sf::Vector2f(0, -level_side*squarep)); compass_back_sprite.move(sf::Vector2f(0, -level_side*squarep)); compass_sprite.move(sf::Vector2f(0, -level_side*squarep)); arrow_sprite.move(sf::Vector2f(0, -level_side*squarep)); infobox.move(sf::Vector2f(0, -level_side*squarep)); key_up_sprite.move(sf::Vector2f(0, -level_side*squarep)); key_right_sprite.move(sf::Vector2f(0, -level_side*squarep)); key_down_sprite.move(sf::Vector2f(0, -level_side*squarep)); key_left_sprite.move(sf::Vector2f(0, -level_side*squarep)); key_d_sprite.move(sf::Vector2f(0, -level_side*squarep)); key_right_turn_sprite.move(sf::Vector2f(0, -level_side*squarep)); key_a_sprite.move(sf::Vector2f(0, -level_side*squarep)); key_left_turn_sprite.move(sf::Vector2f(0, -level_side*squarep)); key_w_sprite.move(sf::Vector2f(0, -level_side*squarep)); exchange_sprite.move(sf::Vector2f(0, -level_side*squarep)); key_x_sprite.move(sf::Vector2f(0, -level_side*squarep)); build_sprite.move(sf::Vector2f(0, -level_side*squarep)); key_v_sprite.move(sf::Vector2f(0, -level_side*squarep)); timeshift_sprite.move(sf::Vector2f(0, -level_side*squarep)); key_r_sprite.move(sf::Vector2f(0, -level_side*squarep)); reset_sprite.move(sf::Vector2f(0, -level_side*squarep)); key_esc_sprite.move(sf::Vector2f(0, -level_side*squarep)); for (int b_sub = 0; b_sub <= max_pow; b_sub++) { level_sprite[b_sub].move(sf::Vector2f(0, -level_side*squarep)); dollar_sprite[b_sub].move(sf::Vector2f(0, -level_side*squarep)); } for (int a_sub = 0; a_sub < number_max; a_sub++) { for (int b_sub = 0; b_sub <= max_pow; b_sub++) { number_sprite[a_sub][b_sub].move(sf::Vector2f(0, -level_side*squarep)); dosh_sprite[a_sub][b_sub].move(sf::Vector2f(0, -level_side*squarep)); } } scan_pos_y = scan_pos_y - level_side*squarep; } if ((((local_y + dir_direct[1]) < -size_level) && (square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] + level_side + max_level] != 1) && (square_matrix[local_x + dir_direct[0] + max_level][local_y + dir_direct[1] + level_side + max_level] != 10)) && !action) { moving = true; action = true; final_move[0] = dir_mult*dir_direct[0]; final_move[1] = dir_mult*dir_direct[1]; local_x = local_x + dir_direct[0]; local_y = local_y + dir_direct[1]; local_y = local_y + level_side; view.move(0, level_side*squarep); scanner_sprite.move(sf::Vector2f(0, level_side*squarep)); compass_back_sprite.move(sf::Vector2f(0, level_side*squarep)); compass_sprite.move(sf::Vector2f(0, level_side*squarep)); arrow_sprite.move(sf::Vector2f(0, level_side*squarep)); infobox.move(sf::Vector2f(0, level_side*squarep)); key_up_sprite.move(sf::Vector2f(0, level_side*squarep)); key_right_sprite.move(sf::Vector2f(0, level_side*squarep)); key_down_sprite.move(sf::Vector2f(0, level_side*squarep)); key_left_sprite.move(sf::Vector2f(0, level_side*squarep)); key_d_sprite.move(sf::Vector2f(0, level_side*squarep)); key_right_turn_sprite.move(sf::Vector2f(0, level_side*squarep)); key_a_sprite.move(sf::Vector2f(0, level_side*squarep)); key_left_turn_sprite.move(sf::Vector2f(0, level_side*squarep)); key_w_sprite.move(sf::Vector2f(0, level_side*squarep)); exchange_sprite.move(sf::Vector2f(0, level_side*squarep)); key_x_sprite.move(sf::Vector2f(0, level_side*squarep)); build_sprite.move(sf::Vector2f(0, level_side*squarep)); key_v_sprite.move(sf::Vector2f(0, level_side*squarep)); timeshift_sprite.move(sf::Vector2f(0, level_side*squarep)); key_r_sprite.move(sf::Vector2f(0, level_side*squarep)); reset_sprite.move(sf::Vector2f(0, level_side*squarep)); key_esc_sprite.move(sf::Vector2f(0, level_side*squarep)); for (int b_sub = 0; b_sub <= max_pow; b_sub++) { level_sprite[b_sub].move(sf::Vector2f(0, level_side*squarep)); dollar_sprite[b_sub].move(sf::Vector2f(0, level_side*squarep)); } for (int a_sub = 0; a_sub < number_max; a_sub++) { for (int b_sub = 0; b_sub <= max_pow; b_sub++) { number_sprite[a_sub][b_sub].move(sf::Vector2f(0, level_side*squarep)); dosh_sprite[a_sub][b_sub].move(sf::Vector2f(0, level_side*squarep)); } } scan_pos_y = scan_pos_y + level_side*squarep; } if ((dir_direct[0] == 0) && (dir_direct[1] == 0)) { action = false; moving = false; } if (action && moving) { if (square_matrix[local_x + max_level][local_y + max_level] == 2) { level_change = true; two_turn_uplight = true; } if (square_matrix[local_x + max_level][local_y + max_level] == 3) { dark_setback = true; two_turn_uplight = true; } if (square_matrix[local_x + max_level][local_y + max_level] == 4) { level_back = true; two_turn_uplight = true; } pacman = square_matrix[local_x + max_level][local_y + max_level]; Color_Picker(pacman, karasu, exit_colors); square_matrix[local_x + max_level][local_y + max_level] = 0; if (pacman == 2) { dosh_increase = 100; } if (pacman == 3) { dosh_increase = -50; } if (pacman == 4) { dosh_increase = -150; } if (pacman == 5) { dosh_increase = 1; } if (pacman == 6) { dosh_increase = 5; } if (pacman == 7) { dosh_increase = 25; } if (pacman == 8) { dosh_increase = 125; } } } if ((sf::Keyboard::isKeyPressed(sf::Keyboard::A) || (mouse_pressed && (mouse_pos_x > 25) && (mouse_pos_x < 75) && (mouse_pos_y > 525) && (mouse_pos_y < 575))) && !action && !(level_reset || level_recet) && turning) { turn_right = true; action = true; one_turn_uplight = true; key_a_uplight = true; for (int a_sub = 0; a_sub <= 1; a_sub++) { dir_move[a_sub] = dir_up[a_sub]; dir_up[a_sub] = dir_left[a_sub]; dir_left[a_sub] = dir_down[a_sub]; dir_down[a_sub] = dir_right[a_sub]; dir_right[a_sub] = dir_move[a_sub]; } final_rot = rot_mult*rot_right; } if ((sf::Keyboard::isKeyPressed(sf::Keyboard::D) || (mouse_pressed && (mouse_pos_x > 75) && (mouse_pos_x < 125) && (mouse_pos_y > 525) && (mouse_pos_y < 575))) && !action && !(level_reset || level_recet) && turning) { turn_left = true; action = true; one_turn_uplight = true; key_d_uplight = true; for (int a_sub = 0; a_sub <= 1; a_sub++) { dir_move[a_sub] = dir_up[a_sub]; dir_up[a_sub] = dir_right[a_sub]; dir_right[a_sub] = dir_down[a_sub]; dir_down[a_sub] = dir_left[a_sub]; dir_left[a_sub] = dir_move[a_sub]; } final_rot = rot_mult*rot_left; } if (one_turn_uplight) { uplight_transp = -12; if (!two_turn_uplight) { uplight_transp = -6; } } if ((level == 26) && !delay_flipping) { // square_matrix[max_level][max_level + 1] = 2; if ((square_matrix[max_level][max_level] == 4) && (square_matrix[max_level + 1][max_level] == 10) && (square_matrix[max_level - 1][max_level] == 10) && (square_matrix[max_level][max_level + 1] == 10) && (square_matrix[max_level][max_level - 1] == 10)) { // square_matrix[max_level][max_level] = 2; delay_flip = 2; delay_flipping = true; } } if (((level == 27) || (level == 28)) && !delay_flipping) { // square_matrix[max_level][max_level + 1] = 2; for (int a_sub = -24; a_sub <= 24; a_sub += 6) { for (int b_sub = -24; b_sub <= 24; b_sub += 6) { if (((square_matrix[max_level + a_sub][max_level + b_sub] == 5) || (square_matrix[max_level + a_sub][max_level + b_sub] == 6) || (square_matrix[max_level + a_sub][max_level + b_sub] == 7) || (square_matrix[max_level + a_sub][max_level + b_sub] == 8)) && (square_matrix[max_level + a_sub + 1][max_level + b_sub] == 10) && (square_matrix[max_level + a_sub - 1][max_level + b_sub] == 10) && (square_matrix[max_level + a_sub][max_level + b_sub + 1] == 10) && (square_matrix[max_level + a_sub][max_level + b_sub - 1] == 10)) { // square_matrix[max_level][max_level] = 2; delay_flip = 2; delay_flipping = true; coord_a_sub = a_sub; coord_b_sub = b_sub; } } } } if (action) { cumu_move[0] = 0; cumu_move[1] = 0; if (exhale || building) { paruto = 0.08; } for (int actions = 1; actions <= transitions; actions++) { std::this_thread::sleep_for(delay); if (level_reset || exhale || building) { if (toransupu < 255) { toransupu = toransupu + 12; } if (toransupu > 255) { toransupu = 255; } } if (!level_reset && !exhale && !building) { if (toransupu > 0) { toransupu = toransupu - 12; } if (toransupu < 0) { toransupu = 0; } } if (one_turn_uplight && !two_turn_uplight) { uplight_transp = uplight_transp + 12; } if (two_turn_uplight) { uplight_transp = uplight_transp + 6; } if (uplight_transp > 255) { uplight_transp = 255; } if (!level_change && !level_back) { paruto = paruto - 0.04; if (exhale || building) { paruto = paruto + 0.08; } sukuwarii.setSize(sf::Vector2f(2*paruto*squarrel, 2*paruto*squarrel)); bitomasuku_supuraito.setScale(sf::Vector2f(paruto, paruto)); } if (inhale) { inhale_move_x = inhale_move_x - final_move[0]; inhale_move_y = inhale_move_y - final_move[1]; } if ((exhale || building) && (actions > 2)) { inhale_move_x = inhale_move_x + final_move[0]; inhale_move_y = inhale_move_y + final_move[1]; } if (moving) { if (level_change) { exit_filler.rotate(scale_rot/4); exit_filler.scale(scale_mult, scale_mult); pitmask_sprite.rotate(scale_rot/4); pitmask_sprite.scale(scale_mult, scale_mult); } if (level_back) { exit_filler.rotate(-scale_rot/4); exit_filler.scale(scale_mult, scale_mult); pitmask_sprite.rotate(-scale_rot/4); pitmask_sprite.scale(scale_mult, scale_mult); } if (dark_setback) { exit_filler.scale(scale_mult, scale_mult); } if (actions <= 21) { cumu_move[0] = cumu_move[0] + final_move[0]; cumu_move[1] = cumu_move[1] + final_move[1]; view.move(final_move[0], final_move[1]); scanner_sprite.move(sf::Vector2f(final_move[0], final_move[1])); compass_back_sprite.move(sf::Vector2f(final_move[0], final_move[1])); compass_sprite.move(sf::Vector2f(final_move[0], final_move[1])); arrow_sprite.move(sf::Vector2f(final_move[0], final_move[1])); infobox.move(sf::Vector2f(final_move[0], final_move[1])); key_up_sprite.move(sf::Vector2f(final_move[0], final_move[1])); key_right_sprite.move(sf::Vector2f(final_move[0], final_move[1])); key_down_sprite.move(sf::Vector2f(final_move[0], final_move[1])); key_left_sprite.move(sf::Vector2f(final_move[0], final_move[1])); key_d_sprite.move(sf::Vector2f(final_move[0], final_move[1])); key_right_turn_sprite.move(sf::Vector2f(final_move[0], final_move[1])); key_a_sprite.move(sf::Vector2f(final_move[0], final_move[1])); key_left_turn_sprite.move(sf::Vector2f(final_move[0], final_move[1])); key_w_sprite.move(sf::Vector2f(final_move[0], final_move[1])); exchange_sprite.move(sf::Vector2f(final_move[0], final_move[1])); key_x_sprite.move(sf::Vector2f(final_move[0], final_move[1])); build_sprite.move(sf::Vector2f(final_move[0], final_move[1])); key_v_sprite.move(sf::Vector2f(final_move[0], final_move[1])); timeshift_sprite.move(sf::Vector2f(final_move[0], final_move[1])); key_r_sprite.move(sf::Vector2f(final_move[0], final_move[1])); reset_sprite.move(sf::Vector2f(final_move[0], final_move[1])); key_esc_sprite.move(sf::Vector2f(final_move[0], final_move[1])); for (int b_sub = 0; b_sub <= max_pow; b_sub++) { level_sprite[b_sub].move(sf::Vector2f(final_move[0], final_move[1])); dollar_sprite[b_sub].move(sf::Vector2f(final_move[0], final_move[1])); } for (int a_sub = 0; a_sub < number_max; a_sub++) { for (int b_sub = 0; b_sub <= max_pow; b_sub++) { number_sprite[a_sub][b_sub].move(sf::Vector2f(final_move[0], final_move[1])); dosh_sprite[a_sub][b_sub].move(sf::Vector2f(final_move[0], final_move[1])); } } scan_pos_x = scan_pos_x + final_move[0]; scan_pos_y = scan_pos_y + final_move[1]; } else { cumu_move[0] = cumu_move[0] - final_move[0]; cumu_move[1] = cumu_move[1] - final_move[1]; view.move(-final_move[0], -final_move[1]); scanner_sprite.move(sf::Vector2f(-final_move[0], -final_move[1])); compass_back_sprite.move(-final_move[0], -final_move[1]); compass_sprite.move(-final_move[0], -final_move[1]); arrow_sprite.move(-final_move[0], -final_move[1]); infobox.move(sf::Vector2f(-final_move[0], -final_move[1])); key_up_sprite.move(sf::Vector2f(-final_move[0], -final_move[1])); key_right_sprite.move(sf::Vector2f(-final_move[0], -final_move[1])); key_down_sprite.move(sf::Vector2f(-final_move[0], -final_move[1])); key_left_sprite.move(sf::Vector2f(-final_move[0], -final_move[1])); key_d_sprite.move(sf::Vector2f(-final_move[0], -final_move[1])); key_right_turn_sprite.move(sf::Vector2f(-final_move[0], -final_move[1])); key_a_sprite.move(sf::Vector2f(-final_move[0], -final_move[1])); key_left_turn_sprite.move(sf::Vector2f(-final_move[0], -final_move[1])); key_w_sprite.move(sf::Vector2f(-final_move[0], -final_move[1])); exchange_sprite.move(sf::Vector2f(-final_move[0], -final_move[1])); key_x_sprite.move(sf::Vector2f(-final_move[0], -final_move[1])); build_sprite.move(sf::Vector2f(-final_move[0], -final_move[1])); key_v_sprite.move(sf::Vector2f(-final_move[0], -final_move[1])); timeshift_sprite.move(sf::Vector2f(-final_move[0], -final_move[1])); key_r_sprite.move(sf::Vector2f(-final_move[0], -final_move[1])); reset_sprite.move(sf::Vector2f(-final_move[0], -final_move[1])); key_esc_sprite.move(sf::Vector2f(-final_move[0], -final_move[1])); for (int b_sub = 0; b_sub <= max_pow; b_sub++) { level_sprite[b_sub].move(sf::Vector2f(-final_move[0], -final_move[1])); dollar_sprite[b_sub].move(sf::Vector2f(-final_move[0], -final_move[1])); } for (int a_sub = 0; a_sub < number_max; a_sub++) { for (int b_sub = 0; b_sub <= max_pow; b_sub++) { number_sprite[a_sub][b_sub].move(sf::Vector2f(-final_move[0], -final_move[1])); dosh_sprite[a_sub][b_sub].move(sf::Vector2f(-final_move[0], -final_move[1])); } } scan_pos_x = scan_pos_x - final_move[0]; scan_pos_y = scan_pos_y - final_move[1]; } } if (turn_right || turn_left) { // std::cout << actions << " ~ " << "[" << kompass_x - qompass_x << ":" << kompass_y - qompass_y << "]" << "\n"; if (actions <= 21) { view.rotate(final_rot); scanner_sprite.rotate(final_rot); compass_back_sprite.rotate(final_rot); compass_sprite.rotate(final_rot); infobox.rotate(final_rot); key_up_sprite.rotate(final_rot); key_right_sprite.rotate(final_rot); key_down_sprite.rotate(final_rot); key_left_sprite.rotate(final_rot); key_d_sprite.rotate(final_rot); key_right_turn_sprite.rotate(final_rot); key_a_sprite.rotate(final_rot); key_left_turn_sprite.rotate(final_rot); key_w_sprite.rotate(final_rot); exchange_sprite.rotate(final_rot); key_x_sprite.rotate(final_rot); build_sprite.rotate(final_rot); key_v_sprite.rotate(final_rot); timeshift_sprite.rotate(final_rot); key_r_sprite.rotate(final_rot); reset_sprite.rotate(final_rot); key_esc_sprite.rotate(final_rot); for (int b_sub = 0; b_sub <= max_pow; b_sub++) { level_sprite[b_sub].rotate(final_rot); dollar_sprite[b_sub].rotate(final_rot); } for (int a_sub = 0; a_sub < number_max; a_sub++) { for (int b_sub = 0; b_sub <= max_pow; b_sub++) { number_sprite[a_sub][b_sub].rotate(final_rot); dosh_sprite[a_sub][b_sub].rotate(final_rot); } } } else { view.rotate(-final_rot); scanner_sprite.rotate(-final_rot); compass_back_sprite.rotate(-final_rot); compass_sprite.rotate(-final_rot); infobox.rotate(-final_rot); key_up_sprite.rotate(-final_rot); key_right_sprite.rotate(-final_rot); key_down_sprite.rotate(-final_rot); key_left_sprite.rotate(-final_rot); key_d_sprite.rotate(-final_rot); key_right_turn_sprite.rotate(-final_rot); key_a_sprite.rotate(-final_rot); key_left_turn_sprite.rotate(-final_rot); key_w_sprite.rotate(-final_rot); exchange_sprite.rotate(-final_rot); key_x_sprite.rotate(-final_rot); build_sprite.rotate(-final_rot); key_v_sprite.rotate(-final_rot); timeshift_sprite.rotate(-final_rot); key_r_sprite.rotate(-final_rot); reset_sprite.rotate(-final_rot); key_esc_sprite.rotate(-final_rot); for (int b_sub = 0; b_sub <= max_pow; b_sub++) { level_sprite[b_sub].rotate(-final_rot); dollar_sprite[b_sub].rotate(-final_rot); } for (int a_sub = 0; a_sub < number_max; a_sub++) { for (int b_sub = 0; b_sub <= max_pow; b_sub++) { number_sprite[a_sub][b_sub].rotate(-final_rot); dosh_sprite[a_sub][b_sub].rotate(-final_rot); } } } // std::cout << actions << " ~ " << "[" << compass_x << ":" << compass_y << "] [" << compass_x_d << ":" << compass_y_d << "]" << "\n"; } window.setView(view); window.clear(sf::Color(color_black[0], color_black[1], color_black[2])); // window.clear(sf::Color(255, 255, 255)); possible_triggers = 0; actual_triggers = 0; for (int a_sub = -max_view; a_sub <= max_view; a_sub++) { pot_x = local_x + a_sub; pos_x = pot_x*squarep; if (pot_x > size_level) { pot_x = pot_x - level_side; } if (pot_x < -size_level) { pot_x = pot_x + level_side; } for (int b_sub = -max_view; b_sub <= max_view; b_sub++) { pot_y = local_y + b_sub; pos_y = pot_y*squarep; if (pot_y > size_level) { pot_y = pot_y - level_side; } if (pot_y < -size_level) { pot_y = pot_y + level_side; } /// /////////////////////////////////////////////////// // //////////////////////////////////////////////////// /// /////////////////////////////////////////////////// Color_Picker(square_matrix[pot_x + max_level][pot_y + max_level], colours, exit_colors); if ((square_matrix[pot_x + max_level][pot_y + max_level] <= 4) || (square_matrix[pot_x + max_level][pot_y + max_level] == 10)) { square_transp = max_transp; } else { square_transp = blink; } dark_transp = dark_transp = exp(-sqrt(1.0*a_sub*a_sub + 1.0*b_sub*b_sub)/(dark_mult)); if ((square_matrix[pot_x + max_level][pot_y + max_level] == 3) && moving) { dark_transp = exp(-sqrt(1.0*(a_sub + dir_direct[0] - 1*cumu_move[0]/squarep)*(a_sub + dir_direct[0] - 1*cumu_move[0]/squarep) + 1.0*(b_sub + dir_direct[1] - 1*cumu_move[1]/squarep)*(b_sub + dir_direct[1] - 1*cumu_move[1]/squarep))/(dark_mult)); } // dark_transp = 1; // qot_x = a_sub + local_x + c_sub*level_side; // qot_y = b_sub + local_y + d_sub*level_side; if ((a_sub == 0) && (b_sub == 0) && timecop) { bitshine_sprite.setPosition(pos_x, pos_y); bitshine_sprite.setColor(sf::Color(full_intensity, full_intensity, full_intensity, max_transp)); window.draw(bitshine_sprite); // bitsquare_sprite.setPosition(pos_x, pos_y); // bitsquare_sprite.setColor(sf::Color(color_black[0], color_black[1], color_black[2], 0)); // window.draw(bitsquare_sprite); } bitsquare_sprite.setPosition(pos_x, pos_y); if (square_matrix[pot_x + max_level][pot_y + max_level] == 0) { bitsquare_sprite.setColor(sf::Color(color_black[0], color_black[1], color_black[2], max_transp)); } if (square_matrix[pot_x + max_level][pot_y + max_level] == 3) { bitsquare_sprite.setColor(sf::Color(colours[0], colours[1], colours[2], round(dark_transp*max_transp))); } if ((square_matrix[pot_x + max_level][pot_y + max_level] == 0) || (square_matrix[pot_x + max_level][pot_y + max_level] == 3)) { window.draw(bitsquare_sprite); } // squaree = Square_Draw(squaree, colours, 128, pos_x, pos_y, squarrel, squarrel); // window.draw(squaree); if ((square_matrix[pot_x + max_level][pot_y + max_level] != 0) && (square_matrix[pot_x + max_level][pot_y + max_level] != 3)) { bitshadow_sprite.setPosition(pos_x, pos_y); bitshadow_sprite.setColor(sf::Color(background_blink, background_blink, background_blink, blink)); if ((square_matrix[pot_x + max_level][pot_y + max_level] == 1) || (square_matrix[pot_x + max_level][pot_y + max_level] == 2) || (square_matrix[pot_x + max_level][pot_y + max_level] == 4) || (square_matrix[pot_x + max_level][pot_y + max_level] == 10)) { bitshadow_sprite.setColor(sf::Color(background_blink, background_blink, background_blink,max_transp)); } window.draw(bitshadow_sprite); bitmask_sprite.setPosition(pos_x, pos_y); bitmask_sprite.setColor(sf::Color(colours[0], colours[1], colours[2], blink)); if ((square_matrix[pot_x + max_level][pot_y + max_level] == 1) || (square_matrix[pot_x + max_level][pot_y + max_level] == 4) || (square_matrix[pot_x + max_level][pot_y + max_level] == 10)) { bitmask_sprite.setColor(sf::Color(colours[0], colours[1], colours[2], max_transp)); } if (square_matrix[pot_x + max_level][pot_y + max_level] == 2) { bitmask_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); } // bitmask_sprite.setColor(sf::Color(colours[0], colours[1], colours[2], 128)); window.draw(bitmask_sprite); } /// /////////////////////////////////////////////////// // //////////////////////////////////////////////////// /// /////////////////////////////////////////////////// if ((moving && (a_sub == 0) && (b_sub == 0)) && !level_change && !level_back && !(dark_setback || dark_flicker)) { bat_transp = 1.0*blink*toransupu/max_transp; if ((pacman == 2) || (pacman == 3) || (pacman == 10)) { bat_transp = toransupu; } if ((pacman != 0) && (pacman != 3)) { bitshine_sprite.setPosition(pos_x, pos_y); bitshine_sprite.setColor(sf::Color(full_intensity, full_intensity, full_intensity, max_transp)); window.draw(bitshine_sprite); bitsquare_sprite.setPosition(pos_x, pos_y); bitsquare_sprite.setColor(sf::Color(color_black[0], color_black[1], color_black[2], max_transp)); window.draw(bitsquare_sprite); bitomasuku_supuraito.setPosition(pos_x, pos_y); bitomasuku_supuraito.setColor(sf::Color(karasu[0], karasu[1], karasu[2], blink)); if ((pacman == 1) || (pacman == 10)) { bitomasuku_supuraito.setColor(sf::Color(karasu[0], karasu[1], karasu[2], max_transp)); } // bitomasuku_supuraito.setColor(sf::Color(karasu[0], karasu[1], karasu[2], 128)); window.draw(bitomasuku_supuraito); } } } } if ((inhale || exhale || building) && !level_change && !level_back && !(dark_setback || dark_flicker)) { Color_Picker(nullvoid, karasu, exit_colors); if ((pacman != 0) && (pacman != 3) && false) { bitsquare_sprite.setPosition(scan_pos_x + dir_direct[0]*squarep, scan_pos_y + dir_direct[1]*squarep); bitsquare_sprite.setColor(sf::Color(karasu[0], karasu[1], karasu[2], max_transp)); window.draw(bitsquare_sprite); } bat_transp = 1.0*blink*toransupu/max_transp; Color_Picker(pacman, karasu, exit_colors); if (building) { // std::cout << pacman << "\n"; } if ((pacman <= 4) || (pacman == 10)) { bat_transp = toransupu; } dark_transp = exp(-1/dark_mult); bitshine_sprite.setPosition(scan_pos_x + dir_up[0]*squarep, scan_pos_y + dir_up[1]*squarep); bitshine_sprite.setColor(sf::Color(full_intensity, full_intensity, full_intensity, max_transp)); window.draw(bitshine_sprite); bitsquare_sprite.setPosition(scan_pos_x + dir_up[0]*squarep, scan_pos_y + dir_up[1]*squarep); bitsquare_sprite.setColor(sf::Color(color_black[0], color_black[1], color_black[2], max_transp)); window.draw(bitsquare_sprite); if (((pacman == 0) || (pacman == 3)) && false) { if (inhale) { sukuwarii = Square_Draw(sukuwarii, karasu, bat_transp, scan_pos_x + dir_direct[0]*squarep + inhale_move_x, scan_pos_y + dir_direct[1]*squarep + inhale_move_y, paruto*squarrel, paruto*squarrel); } if (exhale || building) { sukuwarii = Square_Draw(sukuwarii, color_black, bat_transp, scan_pos_x + inhale_move_x, scan_pos_y + inhale_move_y, paruto*squarrel, paruto*squarrel); } window.draw(sukuwarii); } if ((pacman != 0) && (pacman != 3)) { if (inhale) { bitomasuku_supuraito.setPosition(scan_pos_x + dir_direct[0]*squarep + inhale_move_x, scan_pos_y + dir_direct[1]*squarep + inhale_move_y); } if (exhale || building) { bitomasuku_supuraito.setPosition(scan_pos_x + inhale_move_x, scan_pos_y + inhale_move_y); } bitomasuku_supuraito.setColor(sf::Color(karasu[0], karasu[1], karasu[2], bat_transp)); window.draw(bitomasuku_supuraito); } } window.draw(scanner_sprite); Color_Picker(2, colours, exit_colors); compass_back_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); window.draw(compass_back_sprite); window.draw(compass_sprite); window.draw(arrow_sprite); if (moving && level_change && !(level_reset || level_recet)) { Color_Picker(0, karasu, exit_colors); if (actions % 2 == 1) { Color_Picker(actions/2, karasu, exit_colors); } exit_filler = Square_Draw(exit_filler, karasu, max_transp, local_x*squarep, local_y*squarep, 0, 0); if (actions % 2 != 1) { // exit_filler = Square_Draw(exit_filler, key_colour, max_transp, local_x*squarep, local_y*squarep, 0, 0); } window.draw(exit_filler); Color_Picker(2, karasu, exit_colors); pitmask_sprite.setPosition(local_x*squarep, local_y*squarep); pitmask_sprite.setColor(sf::Color(karasu[0], karasu[1], karasu[2], toransupu)); window.draw(pitmask_sprite); } if (moving && level_back && !(level_reset || level_recet)) { Color_Picker(4, karasu, exit_colors); if (actions % 2 == 1) { Color_Picker(9, karasu, exit_colors); } exit_filler = Square_Draw(exit_filler, karasu, max_transp, local_x*squarep, local_y*squarep, 0, 0); window.draw(exit_filler); pitmask_sprite.setPosition(local_x*squarep, local_y*squarep); pitmask_sprite.setColor(sf::Color(color_black[0], color_black[1], color_black[2], toransupu)); window.draw(pitmask_sprite); } if (dark_setback && !(level_reset || level_recet)) { Color_Picker(0, karasu, exit_colors); if (actions % 2 == 1) { Color_Picker(5, karasu, exit_colors); } exit_filler = Square_Draw(exit_filler, karasu, max_transp, local_x*squarep, local_y*squarep, 0, 0); window.draw(exit_filler); } if (view_glitch && !(level_reset || level_recet)) { Color_Picker(2, karasu, exit_colors); intro_filler = Square_Draw(intro_filler, key_colour, toransupu, local_x*squarep, local_y*squarep, 0, 0); if (actions % 2 == 1) { Color_Picker(actions/2, karasu, exit_colors); intro_filler = Square_Draw(intro_filler, karasu, toransupu, local_x*squarep, local_y*squarep, 0, 0); } window.draw(intro_filler); } if (level_reset || level_recet) { Color_Picker(0, karasu, exit_colors); if ((actions % 2 == 1) && dark_flicker) { Color_Picker(5, karasu, exit_colors); } intro_filler = Square_Draw(intro_filler, karasu, toransupu, local_x*squarep, local_y*squarep, 0, 0); window.draw(intro_filler); } window.draw(infobox); if (one_turn_uplight || two_turn_uplight) { if (key_up_uplight) { key_up_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], uplight_transp)); } if (key_right_uplight) { key_right_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], uplight_transp)); } if (key_down_uplight) { key_down_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], uplight_transp)); } if (key_left_uplight) { key_left_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], uplight_transp)); } if (key_down_uplight) { key_down_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], uplight_transp)); } if (key_d_uplight) { key_d_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], uplight_transp)); } if (key_a_uplight) { key_a_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], uplight_transp)); } if (key_w_uplight) { key_w_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], uplight_transp)); } if (key_x_uplight) { key_x_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], uplight_transp)); } if (key_v_uplight) { key_v_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], uplight_transp)); } if (key_r_uplight) { key_r_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], uplight_transp)); } // std::cout << actions << " : " << uplight_transp << "\n"; } else { key_up_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_right_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_down_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_left_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_d_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_a_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_w_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_x_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_v_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_r_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); } key_esc_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); if (up_movement) { window.draw(key_up_sprite); } if (right_movement) { window.draw(key_right_sprite); } if (down_movement) { window.draw(key_down_sprite); } if (left_movement) { window.draw(key_left_sprite); } if (turning) { window.draw(key_d_sprite); window.draw(key_right_turn_sprite); window.draw(key_a_sprite); window.draw(key_left_turn_sprite); } if (exchange) { window.draw(key_w_sprite); window.draw(exchange_sprite); } if (build) { window.draw(key_x_sprite); window.draw(build_sprite); } if (timeshift) { window.draw(key_v_sprite); window.draw(timeshift_sprite); } window.draw(key_r_sprite); window.draw(reset_sprite); window.draw(key_esc_sprite); crunchy_number = level; crunched = 0; while (abs(crunchy_number) > 0) { window.draw(number_sprite[abs(crunchy_number) % 10][crunched]); crunchy_number = crunchy_number/10; crunched++; } window.draw(level_sprite[crunched]); for (int b_sub = 0; b_sub <= max_pow; b_sub++) { dollar_sprite[b_sub].setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], blink)); } crunchy_number = dosh; crunched = 0; if (crunchy_number == 0) { window.draw(dosh_sprite[crunchy_number][crunched]); crunched++; } while (abs(crunchy_number) > 0) { window.draw(dosh_sprite[abs(crunchy_number) % 10][crunched]); crunchy_number = crunchy_number/10; crunched++; } if (dosh < 0) { window.draw(dosh_sprite[10][crunched]); } window.draw(dollar_sprite[crunched]); window.display(); Color_Picker(level, kolours, exit_colors); Color_Picker(2, key_colour, exit_colors); for (int a_sub = 0; a_sub <= 2; a_sub++) { key_colour[a_sub] = 128 + key_colour[a_sub]/2; } Exit_Multicolor(exit_colors); if (blink_on) { if (blink < max_transp) { blink = blink + blink_delta; if (blink > max_transp) { blink = max_transp; } } else { blink_on = false; } } if (!blink_on) { if (blink > blink_min) { blink = blink - blink_delta; if (blink < blink_min) { blink = blink_min; } } else { blink_on = true; blink = blink + blink_delta; } } Background_Blinker(background_blink_on, background_blink, max_transp); } position_declare = true; // std::cout << " ~ " << "[" << compass_x_c << ":" << compass_y_d << "] [" << compass_x_d << ":" << compass_y_d << "]" << "\n"; } // std::cout << " ~ " << "[" << compass_x_c << ":" << compass_y_d << "] [" << compass_x_d << ":" << compass_y_d << "]" << "\n"; if ((level == 26) && delay_flipping && (delay_flip == -2)) { // square_matrix[max_level][max_level + 1] = 2; if ((square_matrix[max_level][max_level] == 4) && (square_matrix[max_level + 1][max_level] == 10) && (square_matrix[max_level - 1][max_level] == 10) && (square_matrix[max_level][max_level + 1] == 10) && (square_matrix[max_level][max_level - 1] == 10)) { square_matrix[max_level][max_level] = 2; square_matrix[max_level + 1][max_level] = 8; square_matrix[max_level - 1][max_level] = 8; square_matrix[max_level][max_level + 1] = 8; square_matrix[max_level][max_level - 1] = 8; delay_flip = 0; delay_flipping = false; } } if (((level == 27) || (level == 28)) && delay_flipping && (delay_flip == -2)) { // square_matrix[max_level][max_level + 1] = 2; if (((square_matrix[max_level + coord_a_sub][max_level + coord_b_sub] == 5) || (square_matrix[max_level + coord_a_sub][max_level + coord_b_sub] == 6) || (square_matrix[max_level + coord_a_sub][max_level + coord_b_sub] == 7) || (square_matrix[max_level + coord_a_sub][max_level + coord_b_sub] == 8)) && (square_matrix[max_level + coord_a_sub + 1][max_level + coord_b_sub] == 10) && (square_matrix[max_level + coord_a_sub - 1][max_level + coord_b_sub] == 10) && (square_matrix[max_level + coord_a_sub][max_level + coord_b_sub + 1] == 10) && (square_matrix[max_level + coord_a_sub][max_level + coord_b_sub - 1] == 10)) { square_matrix[max_level + coord_a_sub + 1][max_level + coord_b_sub] = 0; square_matrix[max_level + coord_a_sub - 1][max_level + coord_b_sub] = 0; square_matrix[max_level + coord_a_sub][max_level + coord_b_sub + 1] = 0; square_matrix[max_level + coord_a_sub][max_level + coord_b_sub - 1] = 0; delay_flip = 0; delay_flipping = false; if (square_matrix[max_level + coord_a_sub][max_level + coord_b_sub] == 8) { square_matrix[max_level + coord_a_sub][max_level + coord_b_sub] = 10; } if (square_matrix[max_level + coord_a_sub][max_level + coord_b_sub] == 7) { square_matrix[max_level + coord_a_sub][max_level + coord_b_sub] = 8; } if (square_matrix[max_level + coord_a_sub][max_level + coord_b_sub] == 6) { square_matrix[max_level + coord_a_sub][max_level + coord_b_sub] = 7; } if (square_matrix[max_level + coord_a_sub][max_level + coord_b_sub] == 5) { square_matrix[max_level + coord_a_sub][max_level + coord_b_sub] = 6; } /// meganisuto Fiborand(fib_val, max_val, fractal); if (fib_val[0] < 0.25*max_val) { square_matrix[max_level + coord_a_sub + 3][max_level + coord_b_sub] = 8; } if ((fib_val[0] >= 0.25*max_val) && (fib_val[0] < 0.5*max_val)) { square_matrix[max_level + coord_a_sub][max_level + coord_b_sub + 3] = 8; } if ((fib_val[0] >= 0.5*max_val) && (fib_val[0] < 0.75*max_val)) { square_matrix[max_level + coord_a_sub - 3][max_level + coord_b_sub] = 8; } if (fib_val[0] >= 0.75*max_val) { square_matrix[max_level + coord_a_sub][max_level + coord_b_sub - 3] = 8; } } } view_glitch = false; level_recet = false; if (level_reset) { level--; level_recet = true; level_change = true; glitch_excempt = true; } level_reset = false; if (level_back) { level--; level--; level_change = true; glitch_excempt = true; } level_back = false; if (two_turn_uplight && !one_turn_uplight) { two_turn_uplight = false; } one_turn_uplight = false; if (sf::Keyboard::isKeyPressed(sf::Keyboard::R) || (mouse_pressed && (mouse_pos_x > 350) && (mouse_pos_x < 400) && (mouse_pos_y > 525) && (mouse_pos_y < 575))) { // level--; // level_change = true; level_reset = true; one_turn_uplight = true; two_turn_uplight = true; key_r_uplight = true; uplight_transp = -6; if (mouse_pressed) { sf::Mouse::setPosition(sf::Vector2i(375, 500), window); } } if (!two_turn_uplight) { key_up_uplight = false; key_right_uplight= false; key_down_uplight = false; key_left_uplight = false; key_d_uplight = false; key_a_uplight = false; key_w_uplight = false; key_x_uplight = false; key_r_uplight = false; key_v_uplight = false; } key_up_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_right_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_down_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_left_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_d_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_a_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_w_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_x_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_v_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_r_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); key_esc_sprite.setColor(sf::Color(key_colour[0], key_colour[1], key_colour[2], max_transp)); moving = false; turn_right = false; turn_left = false; action = false; exhale = false; building = false; mouse_pressed = false; timecop = false; toransupu = max_transp; paruto = 1; if (!inhale) { sukuwarii.setSize(sf::Vector2f(2*squarrel, 2*squarrel)); bitomasuku_supuraito.setScale(sf::Vector2f(1, 1)); } exit_filler.setScale(1, 1); exit_filler.setRotation(0); pitmask_sprite.setScale(1, 1); pitmask_sprite.setRotation(0); std::this_thread::sleep_for(delay); position_declare = false; dosh = dosh + dosh_increase; dosh_increase = 0; } level_pass++; if ((level >= level_max) && level_change) { level = 0; } } window.close(); return(0); } }
[ "j.d.kotlarski@gmx.com" ]
j.d.kotlarski@gmx.com
61cfbd7692b0217e7b07003eda507c226c39cc5a
25c45acc26682a392e6b16480c6ef8d3ac52ad9e
/Project9/heinemannlib.inc
b46eb904720806c84b31edd8ef2385f2fe30c326
[ "Apache-2.0" ]
permissive
idoheinemann/Assembly-Snake
16d691d768d24a0d87a0a7fc6b1fa5a789a51130
bbd25fe26684bd53274a6d6a09c77449378b3e77
refs/heads/master
2022-07-16T00:00:46.346946
2020-05-18T18:07:06
2020-05-18T18:07:06
265,020,870
1
0
null
null
null
null
UTF-8
C++
false
false
7,781
inc
;;;;;;;;;;;; CREATED BY IDO HEINEMANN ;;;;;;;;;;;; ;;;;;;;;;;;; SOURCE CODE AND MORE AVAILABLE AT https://github.com/idoheinemann ;;;;;;;;;;;; .686 .data ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; MATH FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; MACROS ;;;; fstp_reg MACRO reg ; fstp to a register sub esp, 4 fstp dword ptr [esp] pop reg ENDM fst_reg MACRO reg ; fst to a register sub esp, 4 fst dword ptr [esp] pop reg ENDM fld_reg MACRO reg ; name also self-explaining push reg fld DWORD PTR [esp] pop reg ENDM f_add MACRO x,y ;x += y for float fld REAL4 PTR x fadd REAL4 PTR y fstp REAL4 PTR x endm f_sub MACRO x,y ; x -= y for float fld REAL4 PTR x fsub REAL4 PTR y fstp REAL4 PTR x endm f_mul MACRO x,y ; x *= y for float fld REAL4 PTR x fmul REAL4 PTR y fstp REAL4 PTR x endm f_div MACRO x,y ; x /= y for float fld REAL4 PTR x fdiv REAL4 PTR y fstp REAL4 PTR x endm f_mod MACRO x,y ; x %= y for float fld REAL4 PTR x fld REAL4 PTR y fprem st(1),st fstp st(0) ; pop fstp REAL4 PTR x endm f_to_int MACRO x,y ; x = (int)y ; for x is int, y is float fld REAL4 PTR y fistp DWORD PTR x endm f_to_float MACRO x,y ; x = (float)y ; for x is float, y is int fild DWORD PTR y fstp REAL4 PTR x endm ;;;;;;;;;; NOTE!! ALL MATH FUNCTIONS RETURN REAL4 VALUES THROUGH EAX ;;;;;;;;; ;;;; SERIES ;;;; factor PROTO x:REAL4 ;;;; LOGARITHMS AND EXPONENTIALS log2 PROTO x:REAL4 ln PROTO x:REAL4 exp PROTO x:REAL4 pow PROTO x:REAL4,y:REAL4 ; x to the power of y log PROTO x:REAL4,y:REAL4 ; logarithm base x of y ;;;; TRIGONOMETRY ;;;; cos PROTO x:REAL4 sin PROTO x:REAL4 tan PROTO x:REAL4 tanh PROTO x:REAL4 cosh PROTO x:REAL4 sinh PROTO x:REAL4 acos PROTO x:REAL4 asin PROTO x:REAL4 atan PROTO x:REAL4 atanh PROTO x:REAL4 acosh PROTO x:REAL4 asinh PROTO x:REAL4 ;;;; NOT SURE HOW TO DESCRIBE THIS ;;;; random PROTO ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; END OF MATH FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; STRING FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; str_length PROTO string:DWORD parse_int PROTO string:DWORD ; eax = (int)string int_to_string PROTO number:DWORD ; eax = pointer to a new string , (string)number concat PROTO str1:DWORD,str2:DWORD ; eax = pointer to a new string, str1+str2 compare PROTO str1:DWORD,str2:DWORD ; eax = (str1 == str2) , 0 if false 1 if true index_of PROTO str1:DWORD,substr1:DWORD ; tries to locate the sub string substr1 in str1 and returns the first index where it was found, returns -1 if substring wasn't found ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; END OF STRING FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; DATA STRUCTURES AND FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Node STRUCT value DWORD ? ; value of the node next DWORD ? ; pointer to the next node Node ENDS Queue STRUCT head DWORD ? ; first out (Node*) tail DWORD ? ; last in (Node*) count DWORD ? ; guess (unsigned int) Queue ENDS Stack STRUCT pointer DWORD ? ; Node* count DWORD ? ; unsigned int Stack ENDS List STRUCT items DWORD ? ; pointer to array count DWORD ? ; unsigned int List ENDS ;;;; NODE ;;;; new_node PROTO value:DWORD,next:DWORD ; creates a new node with the given value and next node, both can be NULL delete_node PROTO node:DWORD ; safe delete the node and all it's children ;;;; QUEUE ;;;; queue_push PROTO queue:DWORD, value:DWORD queue_pop PROTO queue:DWORD delete_queue PROTO queue:DWORD ; safe delete the queue ;;;; STACK ;;;; stack_push PROTO queue:DWORD, value:DWORD stack_pop PROTO queue:DWORD delete_stack PROTO queue:DWORD ; safe delete the stack ;;;; BOTH STACK AND QUEUE peek PROTO object:DWORD ; can accept both the offset of a queue and the offset of a stack ;;;; LIST ;;;; list_insert PROTO list:DWORD,value:DWORD ; list.insert(value), appends the value to the end of the list and increases list.count list_set PROTO list:DWORD, index:DWORD, value:DWORD ; list[index] = value list_index_of PROTO list:DWORD, item:DWORD ; gets the first index for which list[index] == item list_delete_at PROTO list:DWORD, index:DWORD ; removes the item at list[index] from list_get_item PROTO list:DWORD, index:DWORD ; eax = list[index] delete_list PROTO list:DWORD ; safe delete the list ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; END OF DATA STRUCTURES ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; LINEAR ALGEBRA ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Matrix STRUCT elements DWORD ? ; pointers to the first element in each row rows DWORD ? columns DWORD ? Matrix ends matrix_delete PROTO mat:DWORD ; safe delete a matrix zero_matrix PROTO rows:DWORD,columns:DWORD ; returns a pointer to a new zero matrix matrix_get_row PROTO mat:DWORD,row:DWORD ; returns a pointer to the first element in the row matrix_get_element PROTO mat:DWORD,row:DWORD,col:DWORD ; returns mat[row,col] matrix_set_element PROTO mat:DWORD,row:DWORD,col:DWORD,value:DWORD ; mat[row,col] = value matrix_set_row PROTO mat:DWORD,row:DWORD,reprow:DWORD ; copies the row specified by the row pointer reprow to the row of the matrix matrix_load PROTO dst:DWORD,src:DWORD ; copies the destination matrix to the source matrix matrix_add PROTO dst:DWORD,src:DWORD ; += instruction for matrices, dst += src matrix_plus PROTO dst:DWORD,src:DWORD ; +, returns a pointer to the new matrix dst+src matrix_sub PROTO dst:DWORD,src:DWORD ; -= instruction for matrices, dst-= src matrix_minus PROTO dst:DWORD,src:DWORD ; -, returns a pointer to the new matrix dst-src matrix_elementwize_mul PROTO dst:DWORD,src:DWORD ; *=, multiply dst by src elementwize matrix_elementwize_times PROTO dst:DWORD,src:DWORD ; *, returns a pointer to the new matrix src*dst (elementwize multiplication) matrix_mul PROTO mat1:DWORD,mat2:DWORD ; matrix multiplication, returns pointer to a new matrix matrix_scalar_mul PROTO mat:DWORD,scl:REAL4 ; matrix multiplication by a scalar, mat *= scl matrix_scalar_times PROTO mat:DWORD,scl:REAL4 ; *, returns a new matrix (scalar multiplication) matrix_elementwize PROTO mat:DWORD,func:DWORD ; function must be stdcall, and take one REAL4 argument; equivalent to element = f(element) for every element matrix_element_function PROTO mat:DWORD,func:DWORD ; function must be stdcall, and take one REAL4 argument; returns f(element) for each element random_matrix PROTO rows:DWORD,columns:DWORD ; returns a new matrix R(rows,columns) of random values between 0 and 1 ones_matrix PROTO rows:DWORD,columns:DWORD ; returns a matrix R(rows,columns) of ones identity_matrix PROTO rows:DWORD,columns:DWORD ; returns the identity_matrix by the dimensions R(rows,columns) matrix_transpose PROTO mat:DWORD ; returns the transpose of the matrix through eax matrix_concat_rows PROTO mat1:DWORD, mat2:DWORD ; concat mat1 and mat2 by the rows, mat1 is R(n,m), mat2 is R(k,m), return is R(n+k,m) matrix_concat_columns PROTO mat1:DWORD,mat2:DWORD ; concat mat1 and mat2 by the columns, mat1 is R(n,m), mat2 is R(n,k), return is R(n,m+k) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; END OF LINEAR ALGEBRA ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; EXTRA LIST METHODS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; bubble_sort PROTO list:DWORD ; sorts the list from smallest item to largest using bubble sort insert_sorted PROTO list:DWORD,value:DWORD ; inserts the new value to the list while keeping it sorted from smallest to largest list_map PROTO list:DWORD,func:DWORD ; returns a new list, function must be cdecl and can accept item,index list_filter PROTO list:DWORD,func:DWORD ; returns a new list, function must be cdecl and can accept item,index list_concat PROTO l1:DWORD,l2:DWORD ; returns a new list ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; END OF EXTRA LIST METHODS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
[ "idohaineman@gmail.com" ]
idohaineman@gmail.com
57ce71600ff6b0d1e26dfd9e6c6db33769134304
3054ded5d75ec90aac29ca5d601e726cf835f76c
/Contests/Others/RPC/2016/10th Contest/J.cpp
1b1fc2dc9701f762cfc8563b0de60439c9c31fe1
[]
no_license
Yefri97/Competitive-Programming
ef8c5806881bee797deeb2ef12416eee83c03add
2b267ded55d94c819e720281805fb75696bed311
refs/heads/master
2022-11-09T20:19:00.983516
2022-04-29T21:29:45
2022-04-29T21:29:45
60,136,956
10
0
null
null
null
null
UTF-8
C++
false
false
2,160
cpp
/* * RPC 10-th Contest 2016 * Problem J: Progressions * Status: Accepted */ #include <bits/stdc++.h> #define endl '\n' using namespace std; const int MAX_N = 1000; int maxAreaHist(int hist[], int n) { int maxArea = 0; stack<int> s; s.push(0); for (int i = 1; i < n; i++) { while (hist[i] < hist[s.top()]) { int t = s.top(); s.pop(); int area = hist[t] * (i - s.top() - 1); maxArea = max(maxArea, area); } s.push(i); } return maxArea; } int maxAreaMat(int mat[][MAX_N + 10], int n, int m) { int ans = 0; int row[MAX_N + 10]; memset(row, 0, sizeof row); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (mat[i][j] || mat[i][j + 1]) { if (i > 0 && row[j + 1] == 0) row[j + 1]++; row[j + 1]++; } else { row[j + 1] = 0; } } ans = max(ans, maxAreaHist(row, m + 2)); } return ans; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, m; while (cin >> n >> m) { int board[MAX_N + 10][MAX_N + 10]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) cin >> board[i][j]; int mat[MAX_N + 10][MAX_N + 10]; memset(mat, 0, sizeof mat); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { int a = 1, b = 1, c = 1; if (i > 0) a = (board[i][j] == board[i - 1][j] + 1); if (j > 0) b = (board[i][j] == board[i][j - 1] + 1); if (i > 0 && j > 0) c = (board[i][j] == board[i - 1][j - 1] + 2); mat[i][j] = (a && b && c); } int ans = 0; for (int i = 0; i < n; i++) { int cont = 1; for (int j = 1; j < m; j++) { if (board[i][j] == board[i][j - 1] + 1) cont++; else { ans = max(ans, cont); cont = 1; } } ans = max(ans, cont); } for (int j = 0; j < m; j++) { int cont = 1; for (int i = 1; i < n; i++) { if (board[i][j] == board[i - 1][j] + 1) cont++; else { ans = max(ans, cont); cont = 1; } } ans = max(ans, cont); } ans = max(ans, maxAreaMat(mat, n, m)); cout << ans << endl; } return 0; }
[ "yefri.gaitan97@gmail.com" ]
yefri.gaitan97@gmail.com
f522213a57193a37faa54d69dc8a3f6a61c9ac7b
89416910e56dfe16a75a4a02781585d369cde45b
/Zockete_dll/Zockete_Inet_Client_ICMP.cpp
a39b5d41a23f0f2838adcefcf9a65d86394d4440
[]
no_license
GabrielReusRodriguez/ICMP_win
8bc54966c2fb31a76fa26d2e473bcf2d77bffa71
26d8a504cd9a3e991105b1f76732ee2f643e0886
refs/heads/master
2020-07-29T08:39:14.935019
2019-10-08T20:10:25
2019-10-08T20:10:25
209,732,689
0
1
null
null
null
null
ISO-8859-3
C++
false
false
4,416
cpp
#include "pch.h" #include "Zockete_Inet_Client_ICMP.h" #include <ws2tcpip.h> Zockete_Inet_Client_ICMP::Zockete_Inet_Client_ICMP(const std::string host) : Zockete_Inet_Client(host) { this->limpiaRecvBuffer(); } Zockete_Inet_Client_ICMP::~Zockete_Inet_Client_ICMP() { } void Zockete_Inet_Client_ICMP::version() { std::cout << "Version libreria: " << ZOCKETE_LIB_VERSION << std::endl; } void Zockete_Inet_Client_ICMP::about() { std::cout << "Zockete Library v " << ZOCKETE_LIB_VERSION << " Class " << ZOCKETE_INET_CLIENT_ICMP_CLASS << std::endl; } void Zockete_Inet_Client_ICMP::creaSocket() { //Limpiamos la memoria de la dirección del servidor. //ZeroMemory(&(this->direccionServidor),sizeof(this->direccionServidor)); //https://docs.microsoft.com/en-us/windows/win32/api/ws2tcpip/nf-ws2tcpip-getaddrinfo int iResult; struct addrinfo queryServidor = { 0 }; struct addrinfo *ptr = NULL; struct addrinfo *resultadoServidor = NULL; int connectedSocket = INVALID_SOCKET; //PADDRINFOA resultadoServidor = nullptr; //PCSTR host = this->host.c_str(); ZeroMemory(&queryServidor, sizeof(queryServidor)); ZeroMemory(&(this->direccionServidor), sizeof(this->direccionServidor)); //ZeroMemory(resultadoServidor, sizeof(*resultadoServidor)); //memset(&(this->direccionServidor), 0, sizeof(this->direccionServidor)); queryServidor = createAddrInfo(AF_UNSPEC, SOCK_RAW, IPPROTO_ICMP); //queryServidor = createAddrInfo(AF_INET, SOCK_RAW, IPPROTO_ICMP); iResult = getaddrinfo(this->host.c_str(),nullptr,&queryServidor,&resultadoServidor); //iResult = getaddrinfo("www.google.es", "80", &queryServidor, &resultadoServidor); //iResult = getaddrinfo("www.google.es", "80", &queryServidor, &resultadoServidor); //iResult = getaddrinfo("www.google.es", "80", &queryServidor, &resultadoServidor); //iResult = getaddrinfo(host, nullptr, &queryServidor, &resultadoServidor); if (iResult != 0) { //Error => retornamos. WCHAR* mesg = gai_strerror(iResult); return; } this->direccionServidor = *resultadoServidor; //Probamos diferentes direcciones. for (ptr = resultadoServidor; ptr != NULL; ptr = ptr->ai_next) { //for (ptr = &(this->direccionServidor); ptr != NULL; ptr = ptr->ai_next) { connectedSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol); if (connectedSocket == INVALID_SOCKET) { printf("socket failed with error: %ld\n", WSAGetLastError()); //WSACleanup(); //return 1; continue; } else { this->sd = connectedSocket; //this->direccionServidor = *ptr; //this->direccionServidor = *(ptr->ai_next); BOOL bOptVal = TRUE; int bOptLen = sizeof(BOOL); iResult = setsockopt(connectedSocket, SOL_SOCKET, SO_BROADCAST, (char*)&bOptVal, bOptLen); if (iResult == SOCKET_ERROR) { wprintf(L"setsockopt for SO_KEEPALIVE failed with error: %u\n", WSAGetLastError()); } else wprintf(L"Set SO_KEEPALIVE: ON\n"); return; } } //this->direccionServidor.ai_family = AF_INET; //this->direccionServidor.ai_socktype = SOCK_RAW; } void Zockete_Inet_Client_ICMP::envia(std::string sendBuffer) { int iResult = SOCKET_ERROR; if (this->sd == INVALID_SOCKET) { //error return; } iResult = send(this->sd, sendBuffer.c_str(), int(strlen(sendBuffer.c_str())), 0); //iResult = sendto(this->sd, sendBuffer.c_str(), strlen(sendBuffer.c_str()), 0,this->direccionServidor.ai_next->ai_addr, 0); if (iResult == SOCKET_ERROR) { wprintf(L"send failed with error: %d\n", WSAGetLastError()); return; } } void Zockete_Inet_Client_ICMP::recibe() { int recvbuflen = 1024; char recvbuf[1024]; char* payload = NULL; int iResult; char* nullChar = NULL; do { nullChar = NULL; iResult = recv(this->sd, recvbuf, recvbuflen, 0); if (iResult > 0){ payload = new char[iResult+1]; strncpy_s(payload, iResult+1, recvbuf, iResult); nullChar = strchr(payload, '\0'); //nullChar = strchr(recvbuf, '\0'); this->recvBuffer.push_back(payload); printf("Bytes received: %d payload: %s\n", iResult, payload); delete payload; } else if (iResult == 0) printf("Connection closed\n"); else printf("recv failed: %d\n", WSAGetLastError()); } while (iResult > 0 && nullChar == NULL); /* const char* p = str; std::vector<std::string> vector; do { vector.push_back(std::string(p)); p += vector.back().size() + 1; } while ( // whatever condition applies ); */ }
[ "gabrielin@gmail.com" ]
gabrielin@gmail.com
0f96dadae9ee1156f48c8a940e814fe6a46e36cf
12b0490737789f12296177bb8642c32f1158ebcb
/CppBasics/MD5/md5class.h
cff7a4d13dbc820c51596e3f25f34c1c1567d1a3
[]
no_license
dinodragon/mygooglecode
ef2775f09bed4fd583eec4524e3675bca150e5e3
1a5525ec6ef1b88f94af55a101d520e1aab83100
refs/heads/master
2021-01-10T12:05:09.301836
2013-03-25T04:02:32
2013-03-25T04:02:32
36,418,668
2
1
null
null
null
null
UTF-8
C++
false
false
4,134
h
// md5class.h: interface for the CMD5 class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_MD51_H__2A1EA377_D065_11D4_A8C8_0050DAC6D85C__INCLUDED_) #define AFX_MD51_H__2A1EA377_D065_11D4_A8C8_0050DAC6D85C__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 /*************************************************************************** This class is a utility wrapper for 'C' code contained in internet RFC 1321, "The MD5 Message-Digest Algorithm". It calculates a cryptological hash value, called a "digest" from a character string. For every unique character string the MD5 hash is guaranteed to be unique. The MD5 hash has the property that given the digest, it's thought to be impossible to get back to the plain text string with existing technology. In this implementation the digest is always a 32 digit hex number, regardless of the length of the input plaintext. This class is helpful for programs which store passwords. Rather than storing the password directly, the programmer should store the MD5 digest of the password. Then when the user enters a password, compute the MD5 digest of the input password. If it is identical to the stored digest, then the user has entered the correct password. It doesn't matter if an evil person sees the digest, since he or she can't get from the digest to the password. At least not unless the user enters a word out of the dictionary, since the evil person could hash the whole dictionary. One way to defeat a dictionary attack is to append a non-text character onto the password, so that even if the user enters a dumb password like "password", you just append some non alpha character to the entered password, i.e. password = "password" + "$". By always appending a nonalpha character, your stored digest isn't in the attacker's dictionary. You can then safely post the digest of the password on a highway billboard. Example pseudocode: { std::string storedPasswordDigest = GetPasswordDigestFromStorage(); std::string passwordEnteredbyUser; cout << "Enter password:" ; cin >> passwordEnteredbyUser; CMD5 md5(passwordEnteredbyUser.c_str()); //note c_str() returns a pointer to the std::string's character buffer, just like CString's "GetBuffer" member function. if(md5.getMD5Digest != storedPasswordDigest) { //user has entered an invalid password cout << "Incorrect password!"; exit(1); } //if we get here, then the user entered a valid password } ************************************************************************** Use this code as you see fit. It is provided "as is" without express or implied warranty of any kind. Jim Howard, jnhtx@jump.net ***************************************************************************/ class CMD5 { public: CMD5(); //default ctor CMD5(const char* plainText); //set plaintext in ctor void setPlainText(const char* plainText); //set plaintext with a mutator, it's ok to //to call this multiple times, the digest is recalculated after each call. const char* getMD5Digest(); //access message digest (aka hash), return 0 if plaintext has not been set virtual ~CMD5(); private: bool calcDigest(); //this function computes the digest by calling the RFC 1321 'C' code bool m_digestValid; //false until the plaintext has been set and digest computed unsigned char m_digest[16]; //the numerical value of the digest char m_digestString[33]; //Null terminated string value of the digest expressed in hex digits char* m_plainText; //a pointer to the plain text. If casting away the const-ness //worries you, you could either make a local copy of the plain //text string instead of just pointing at the user's string or //modify the RFC 1321 code to take 'const' plaintext. }; #endif // !defined(AFX_MD51_H__2A1EA377_D065_11D4_A8C8_0050DAC6D85C__INCLUDED_)
[ "yfsuoyou@3338bcd4-1a09-11de-8120-8d224146dbbc" ]
yfsuoyou@3338bcd4-1a09-11de-8120-8d224146dbbc
260addccc58876ca2e73445b0d0303fbdf53ee1b
4b539c6c996323a8f7d6644c566c535906b2babe
/src/singleEntry.cpp
82ccaac933be1cd23f371eb7c1f322abc1e513b6
[]
no_license
BigBobsky/mpala
849e6c154a3ce7f79d822588e306c6b91ada6bc6
1e37ada6094fc133f6bc6b0f8fa6650efb6109db
refs/heads/master
2023-07-23T02:37:51.913988
2021-09-05T12:44:06
2021-09-05T12:44:06
283,446,457
0
0
null
null
null
null
UTF-8
C++
false
false
4,003
cpp
/* This file is part of MPALA. MPALA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MPALA is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MPALA. If not, see <http://www.gnu.org/licenses/>. */ /* Author : Jean-Luc TRESSET Contact : bigbobsky@gmail.com Creation date : 09/09/14 */ #include <memory> #include <iostream> #include "labels.hpp" #include "singleEntry.hpp" namespace mpala { SingleEntry::SingleEntry() : Gtk::Box(), _listener(0) { std::cout << "SingleEntry page created" << std::endl; frameAD.set_label(LABEL_AD); frameDEC.set_label(LABEL_DEC); frameAD.set_border_width(2); frameDEC.set_border_width(2); adHours.set_digits(0); adHours.set_increments(1.0, 3.0); adHours.set_range(0, 23); boxAD.pack_start(adHours); adMinutes.set_digits(0); adMinutes.set_increments(1.0, 10.0); adMinutes.set_range(0, 59); boxAD.pack_start(adMinutes); adSeconds.set_digits(0); adSeconds.set_increments(1.0, 10.0); adSeconds.set_range(0, 59); boxAD.pack_start(adSeconds); decDegrees.set_digits(0); decDegrees.set_increments(1.0, 10.0); decDegrees.set_range(-90, 90); boxDEC.pack_start(decDegrees); decMinutes.set_digits(0); decMinutes.set_increments(1.0, 10.0); decMinutes.set_range(-59, 59); boxDEC.pack_start(decMinutes); decSeconds.set_digits(0); decSeconds.set_increments(1.0, 10.0); decSeconds.set_range(-59, 59); boxDEC.pack_start(decSeconds); frameAD.add(boxAD); frameDEC.add(boxDEC); box.pack_start(frameAD); box.pack_start(frameDEC); setButton.set_label(LABEL_VALIDATE); setButton.signal_clicked().connect(sigc::mem_fun(*this, &SingleEntry::onEntryValidated)); box.pack_end(setButton); // set vega values decDegrees.set_value(38); decMinutes.set_value(47); decSeconds.set_value(1); adHours.set_value(18); adMinutes.set_value(36); adSeconds.set_value(56); this->pack_end(box); } void SingleEntry::setListener(StarEntryListener* listener) { this->_listener = listener; } void SingleEntry::onEntryValidated() { std::cout << "new single entry registered" << std::endl; if (_listener != 0) { int d; int m; int s; double ra; double dec; // dec to degrees d = (int)decDegrees.get_value(); m = ::abs((int)decMinutes.get_value()); s = ::abs((int)decSeconds.get_value()); dec = (double)d + (double)m / 60.0 + (double)s / 3600.0; std::cout << "dec degrees = " << dec << std::endl; d = (int)(adHours.get_value() * 360.0 / 24.0); m = ::abs((int)(adMinutes.get_value() * 360.0 / 24.0)); s = ::abs((int)(adSeconds.get_value() * 360.0 / 24.0)); ra = (double)d + (double)m / 60.0 + (double)s / 3600.0; _listener->onMeasure(this, ra, dec); std::cout << "ra degrees = " << ra << std::endl; } } SingleEntry::~SingleEntry() { std::cout << "StarEntry page destroyed" << std::endl; } }
[ "jean-luc.tresset@luceor.com" ]
jean-luc.tresset@luceor.com
1c16b730410eb5d105f81ead38528e913a9250f7
5ac691580c49d8cf494d5b98c342bb11f3ff6514
/Baekjoon/2491/2491.cpp
bac504338632d0eea1dd9bcc32939fe070cd186c
[]
no_license
sweatpotato13/Algorithm-Solving
e68411a4f430d0517df4ae63fc70d1a014d8b3ba
b2f8cbb914866d2055727b9872f65d7d270ba31b
refs/heads/master
2023-03-29T23:44:53.814519
2023-03-21T23:09:59
2023-03-21T23:09:59
253,355,531
3
0
null
null
null
null
UTF-8
C++
false
false
1,318
cpp
#pragma warning(disable : 4996) #include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() using namespace std; typedef long long ll; typedef long double ld; typedef vector<ll> vll; typedef pair<ll, ll> pll; typedef pair<ld, ld> pld; typedef tuple<ll, ll, ll> tl3; #define FOR(a, b, c) for (int(a) = (b); (a) < (c); ++(a)) #define FORN(a, b, c) for (int(a) = (b); (a) <= (c); ++(a)) #define rep(i, n) FOR(i, 0, n) #define repn(i, n) FORN(i, 1, n) #define tc(t) while (t--) // https://www.acmicpc.net/problem/2491 ll n; vll num; ll two_pointer() { ll left = 0; ll right = 0; ll last_value = 0; ll ret = 0; while (true) { if (left == right) { last_value = num[right]; right++; ret = max(ret, right - left); } else if (right == n) break; else if (num[right] >= last_value) { last_value = num[right]; right++; ret= max(ret, right - left); } else left++; } return ret; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n; num = vll(n); for (int i = 0; i < n; i++) cin >> num[i]; ll answer = two_pointer(); reverse(num.begin(), num.end()); answer = max(answer, two_pointer()); cout << answer; return 0; }
[ "sweatpotato13@gmail.com" ]
sweatpotato13@gmail.com
9ac176388d3b4cb6f20bcf0322f10baaf22a412d
844a2bae50e141915a8ebbcf97920af73718d880
/Between Demo 4.1 and Demo 4.32/legacy_130_src/HARDWARE/R_D3D/R_d3d.cpp
52112897adae0f500a76e60e41806790c7f652b8
[]
no_license
KrazeeTobi/SRB2-OldSRC
0d5a79c9fe197141895a10acc65863c588da580f
a6be838f3f9668e20feb64ba224720805d25df47
refs/heads/main
2023-03-24T15:30:06.921308
2021-03-21T06:41:06
2021-03-21T06:41:06
349,902,734
0
0
null
null
null
null
UTF-8
C++
false
false
98,725
cpp
// Emacs style mode select -*- C++ -*- //----------------------------------------------------------------------------- // // $Id: R_d3d.cpp,v 1.2 2000/02/27 00:42:11 hurdler Exp $ // // Copyright (C) 1998-2000 by DooM Legacy Team. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // // $Log: R_d3d.cpp,v $ // Revision 1.2 2000/02/27 00:42:11 hurdler // fix CR+LF problem // // Revision 1.1.1.1 2000/02/22 20:32:33 hurdler // Initial import into CVS (v1.29 pr3) // // // DESCRIPTION: // Direct 3D Immediate mode driver // //----------------------------------------------------------------------------- #include <windows.h> #include <windowsx.h> #define D3D_OVERLOADS #include <d3d.h> #define _CREATE_DLL_ #include "../hw_drv.h" #include "../../screen.h" #include <math.h> // ************************************************************************** // PROTOS // ************************************************************************** static void D3D_FormCreate(void); static void D3D_FormResize(int w, int h); static void D3D_SetupPixelFormat(void); static void D3D_Text(unsigned x, unsigned y, unsigned scale, char* format, ...); static int D3D_SetMode (viddef_t *lvid, vmode_t *pcurrentmode) ; static void D3D_DownloadCorona(void); static void D3D_ClearMipmapCache (void); static void D3D_InitMipmapCache (void); static void D3D_BufferClear (void); static BOOL D3D_InitStates (LPDIRECT3DDEVICE3 pd3dDevice, LPDIRECT3DVIEWPORT3 pvViewport); static char* DDErr(HRESULT hresult); // ************************************************************************** // DEFINES // ************************************************************************** #undef DEBUG_TO_FILE #define DEBUG_TO_FILE //output debugging msgs to ogllog.txt #define MAX_VIDEO_MODES 20 #define DYNLIGHT_TEX_NUM 15477 #define SAFE_RELEASE(p) if(p != NULL) { p->Release(); p = NULL; } #define SAFE_DELETE(p) if(p != NULL) { delete p; p = NULL; } #define RELEASE(p) {if(p) p->Release();} // ************************************************************************** // TYPES // ************************************************************************** typedef struct { unsigned char red; unsigned char green; unsigned char blue; unsigned char alpha; } RGBA_t; typedef struct { float red; float green; float blue; float alpha; } RGBA_ft; typedef struct { unsigned char alpha; unsigned char red; unsigned char green; unsigned char blue; } ARGB_t; // ************************************************************************** // GLOBALS // ************************************************************************** #ifdef DEBUG_TO_FILE static HANDLE logstream; static unsigned long nb_frames=0; #endif LPDIRECTDRAW lpDD; LPDIRECTDRAW4 lpDD4; LPDIRECTDRAWSURFACE4 lpDDSRender = NULL; LPDIRECTDRAWSURFACE4 lpDDSPrimary = NULL; LPDIRECTDRAWSURFACE4 lpDDSBackBuffer = NULL; LPDIRECT3D3 lpD3D = NULL; LPDIRECT3DDEVICE3 lpD3DDevice = NULL; LPDIRECT3DVIEWPORT3 lpD3DViewport = NULL; RECT rcScreenRect; RECT rcViewportRect; //testing D3DVERTEX pvTriangleVertices[6]; static viddef_t* viddef; static unsigned long myPaletteData[256]; // 256 ARGB entries // ************************************************************************** // DLL ENTRY POINT // ************************************************************************** BOOL APIENTRY DllMain( HANDLE hModule, // handle to DLL module DWORD fdwReason, // reason for calling function LPVOID lpReserved ) // reserved { // Perform actions based on the reason for calling. switch( fdwReason ) { case DLL_PROCESS_ATTACH: // Initialize once for each new process. // Return FALSE to fail DLL load. #ifdef DEBUG_TO_FILE logstream = INVALID_HANDLE_VALUE; logstream = CreateFile ("r_d3dlog.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_WRITE_THROUGH, NULL); if (logstream == INVALID_HANDLE_VALUE) return FALSE; #endif break; case DLL_THREAD_ATTACH: // Do thread-specific initialization. break; case DLL_THREAD_DETACH: // Do thread-specific cleanup. break; case DLL_PROCESS_DETACH: // Perform any necessary cleanup. #ifdef DEBUG_TO_FILE if ( logstream != INVALID_HANDLE_VALUE ) { CloseHandle ( logstream ); logstream = INVALID_HANDLE_VALUE; } #endif break; } return TRUE; // Successful DLL_PROCESS_ATTACH. } // ---------- // DBG_Printf // Output error messages to debug log if DEBUG_TO_FILE is defined, // else do nothing // ---------- void DBG_Printf (LPCTSTR lpFmt, ...) { #ifdef DEBUG_TO_FILE char str[1024]; va_list arglist; DWORD bytesWritten; va_start (arglist, lpFmt); vsprintf (str, lpFmt, arglist); va_end (arglist); if ( logstream != INVALID_HANDLE_VALUE ) WriteFile (logstream, str, lstrlen(str), &bytesWritten, NULL); #endif } // ========================================================================== // Initialise // ========================================================================== EXPORT BOOL HWRAPI( Init ) (void) { HRESULT hr; // create file for development debugging DBG_Printf ("Init() r_d3d.DLL development mode log file\n"); //------------------------------------------------------------------------- // Create DirectDraw //------------------------------------------------------------------------- hr = DirectDrawCreate (NULL, &lpDD, NULL); if (FAILED (hr)) { DBG_Printf (DDErr(hr)); return FALSE; } // get the DirectX 6 interface hr = lpDD->QueryInterface (IID_IDirectDraw4, (VOID**)&lpDD4 ); if (FAILED(hr)) { DBG_Printf (DDErr(hr)); return FALSE; } //------------------------------------------------------------------------- // Query DirectDraw for access to Direct3D //------------------------------------------------------------------------- lpDD4->QueryInterface( IID_IDirect3D3, (VOID**)&lpD3D ); if (FAILED(hr)) { DBG_Printf (DDErr(hr)); return FALSE; } // setup mipmap download cache //InitMipmapCache (); return TRUE; } // ========================================================================== // // ========================================================================== EXPORT void HWRAPI( Shutdown ) (void) { if (viddef->buffer) { free (viddef->buffer); viddef->buffer = NULL; } // shutdown 3d display here // release DirectDraw object // Release the DDraw and D3D objects used by the app SAFE_RELEASE( lpD3DViewport ) SAFE_RELEASE( lpD3D ) SAFE_RELEASE( lpDDSBackBuffer ) SAFE_RELEASE( lpDDSPrimary ) SAFE_RELEASE( lpDD4 ) // Do a safe check for releasing the D3DDEVICE. RefCount should be zero. if( lpD3DDevice ) if( 0 < lpD3DDevice->Release() ) DBG_Printf ("RefCount error releasing lpD3DDevice\r\n"); // Do a safe check for releasing DDRAW. RefCount should be zero. if( lpDD ) if( 0 < lpDD->Release() ) DBG_Printf ("RefCount error releasing lpDD\r\n"); lpD3DDevice = NULL; lpDD = NULL; } // ************************************************************************** // D3D DISPLAY MODES DRIVER // ************************************************************************** #define NUMD3DVIDMODES 1 vmode_t d3dvidmodes[NUMD3DVIDMODES] = { { NULL, "320x200", 320, 200, //(200.0/320.0)*(320.0/240.0), 320, 1, // rowbytes, bytes per pixel ... NOTE bpp is 1 but we never write to the LFB 0, 2, NULL, &D3D_SetMode } }; // -------------------------------------------------------------------------- // // -------------------------------------------------------------------------- #define MAX_DEVICE_NAME 128 #define MAX_DEVICE_DESC 128 DWORD dwDeviceBitDepth = 0; GUID guidDevice; char szDeviceName[MAX_DEVICE_NAME+1]; char szDeviceDesc[MAX_DEVICE_DESC+1]; D3DDEVICEDESC d3dHWDeviceDesc; static HRESULT WINAPI GetModeListCallback( LPGUID lpGUID, LPSTR lpszDeviceDesc, LPSTR lpszDeviceName, LPD3DDEVICEDESC lpd3dHWDeviceDesc, LPD3DDEVICEDESC lpd3dSWDeviceDesc, LPVOID lpUserArg ) { BOOL fIsHardware; LPD3DDEVICEDESC lpd3dDeviceDesc; // If there is no hardware support the color model is zero. fIsHardware = (lpd3dHWDeviceDesc->dcmColorModel != 0); lpd3dDeviceDesc = (fIsHardware ? lpd3dHWDeviceDesc : lpd3dSWDeviceDesc); DBG_Printf ("%s %s depth: %d\r\n", lpszDeviceDesc, lpszDeviceName, lpd3dDeviceDesc->dwDeviceRenderBitDepth); // Does the device render at the depth we want? if (!(lpd3dDeviceDesc->dwDeviceRenderBitDepth & dwDeviceBitDepth)) { // If not, skip this device. return D3DENUMRET_OK; } // The device must support Gouraud-shaded triangles. if (D3DCOLOR_MONO == lpd3dDeviceDesc->dcmColorModel) { if (!(lpd3dDeviceDesc->dpcTriCaps.dwShadeCaps & D3DPSHADECAPS_COLORGOURAUDMONO)) { // No Gouraud shading. Skip this device. return D3DENUMRET_OK; } } else { if (!(lpd3dDeviceDesc->dpcTriCaps.dwShadeCaps & D3DPSHADECAPS_COLORGOURAUDRGB)) { // No Gouraud shading. Skip this device. return D3DENUMRET_OK; } } // Reject software devices, and monochromatic if (!fIsHardware || (lpd3dDeviceDesc->dcmColorModel != D3DCOLOR_RGB)) { return D3DENUMRET_OK; } // // This is a device we are interested in. Save the details. // *((BOOL*)lpUserArg) = TRUE; CopyMemory(&guidDevice, lpGUID, sizeof(GUID)); strncpy(szDeviceDesc, lpszDeviceDesc, MAX_DEVICE_DESC); strncpy(szDeviceName, lpszDeviceName, MAX_DEVICE_NAME); CopyMemory(&d3dHWDeviceDesc, lpd3dHWDeviceDesc, sizeof(D3DDEVICEDESC)); //CopyMemory(&d3dSWDeviceDesc, lpd3dSWDeviceDesc, sizeof(D3DDEVICEDESC)); // If this is a hardware device, we have found // what we are looking for. if (fIsHardware) return D3DENUMRET_CANCEL; // Otherwise, keep looking. return D3DENUMRET_OK; } // -------------------------------------------------------------------------- // Get the list of available display modes // -------------------------------------------------------------------------- EXPORT void HWRAPI( GetModeList ) (void** pvidmodes, int* numvidmodes) { BOOL fDeviceFound = FALSE; HRESULT hr; DBG_Printf ("GetModeList(): "); // In this code fragment, the variable lpd3d contains a valid // pointer to the IDirect3D3 interface that the application obtained // prior to executing this code. hr = lpD3D->EnumDevices(GetModeListCallback, &fDeviceFound); if (FAILED(hr)) { // Code to handle the error goes here. DBG_Printf ("EnumDevices FAILED\r\n"); DBG_Printf (DDErr(hr)); *numvidmodes = 0; return; } /*if (!fDeviceFound) { // Code to handle the error goes here. DBG_Printf ("no device found\r\n"); *numvidmodes = 0; return; } */ // add first the default mode d3dvidmodes[NUMD3DVIDMODES-1].pnext = NULL; *((vmode_t**)pvidmodes) = &d3dvidmodes[0]; *numvidmodes = NUMD3DVIDMODES; } // ========================================================================== // Set video mode routine for GLIDE display modes // Out: 1 ok, // 0 hardware could not set mode, // -1 no mem // ========================================================================== // current hack to allow the software view to co-exist for development static BOOL VID_FreeAndAllocVidbuffer (viddef_t *lvid) { int vidbuffersize; vidbuffersize = (lvid->width * lvid->height * lvid->bpp * 4/*numscreens*/) + (lvid->width * 32/*st_height*/ * lvid->bpp); //status bar // allocate the new screen buffer if( (lvid->buffer = (byte *) malloc(vidbuffersize))==NULL ) return FALSE; // initially clear the video buffer memset (lvid->buffer, 0, vidbuffersize); return TRUE; } // ========================================================================== // CreateNewSurface // ========================================================================== LPDIRECTDRAWSURFACE4 CreateNewSurface(int dwWidth, int dwHeight, int dwSurfaceCaps) { DDSURFACEDESC2 ddsd; HRESULT hr; // DDCOLORKEY ddck; LPDIRECTDRAWSURFACE4 psurf; ZeroMemory(&ddsd, sizeof(ddsd)); ddsd.dwSize = sizeof(ddsd); ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT |DDSD_WIDTH; ddsd.ddsCaps.dwCaps = dwSurfaceCaps; ddsd.dwHeight = dwHeight; ddsd.dwWidth = dwWidth; hr = lpDD4->CreateSurface (&ddsd, &psurf, NULL); if (FAILED(hr)) { DBG_Printf (DDErr(hr)); psurf = NULL; } else { psurf->Restore(); //hr = ScreenReal->lpVtbl->GetColorKey(DDCKEY_SRCBLT, &ddck); //psurf->SetColorKey(DDCKEY_SRCBLT, &ddck); } return psurf; } // ========================================================================== // Set display mode // ========================================================================== static boolean d3d_display = false; static BOOL fullScreen = FALSE; #define DIMW 640 #define DIMH 480 int D3D_SetMode (viddef_t *lvid, vmode_t *pcurrentmode) { DWORD dwStyle; HRESULT hr; if (d3d_display) return 1; // say we're double-buffering, although this value isn't used.. lvid->numpages = 2; //TODO: release stuff from previous Glide mode... if (!VID_FreeAndAllocVidbuffer (lvid)) return -1; //------------------------------------------------------------------------- // Change window attributes //------------------------------------------------------------------------- HWND appWin = lvid->WndParent; //GetActiveWindow (); if (appWin == NULL) { DBG_Printf ("GetActiveWindow FAILED\r\n"); return FALSE; } if (fullScreen) { dwStyle = WS_POPUP | WS_VISIBLE; SetWindowLong (appWin, GWL_STYLE, dwStyle); SetWindowPos (appWin, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER); } else { RECT rect; rect.top = 0; rect.left = 0; rect.bottom = DIMW - 1; rect.right = DIMH - 1; dwStyle = GetWindowStyle(appWin); dwStyle &= ~WS_POPUP; dwStyle |= WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION; SetWindowLong(appWin, GWL_STYLE, dwStyle); // Resize the window so that the client area is the requested width/height AdjustWindowRectEx (&rect, GetWindowStyle(appWin), GetMenu(appWin) != NULL, GetWindowExStyle(appWin)); // Just in case the window was moved off the visible area of the screen. SetWindowPos(appWin, NULL, 0, 0, rect.right-rect.left, rect.bottom-rect.top, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE); SetWindowPos(appWin, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE); } // just in case.. ShowWindow(appWin, SW_SHOW); //------------------------------------------------------------------------- // Set the Windows cooperative level. //------------------------------------------------------------------------- hr = lpDD4->SetCooperativeLevel (appWin, (fullScreen ? DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN | DDSCL_ALLOWREBOOT : DDSCL_NORMAL) ); if (FAILED(hr)) { DBG_Printf ("SetCooperativeLevel FAILED\r\n"); DBG_Printf (DDErr(hr)); return FALSE; } //------------------------------------------------------------------------- // Create DirectDraw surfaces used for rendering //------------------------------------------------------------------------- DDSURFACEDESC2 ddsd; ZeroMemory (&ddsd, sizeof(ddsd)); ddsd.dwSize = sizeof(ddsd); ddsd.dwFlags = DDSD_CAPS; ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE; // for fullscreen we use page flipping, for windowed mode, we blit the hidden surface to // the visible surface, in both cases we have a visible (or 'real') surface, and a hidden // (or 'virtual', or 'backbuffer') surface. if (fullScreen) { ddsd.dwFlags |= DDSD_BACKBUFFERCOUNT; ddsd.dwBackBufferCount = 1; ddsd.ddsCaps.dwCaps |= DDSCAPS_FLIP | DDSCAPS_COMPLEX; } hr = lpDD4->CreateSurface( &ddsd, &lpDDSPrimary, NULL ); if (FAILED(hr)) { DBG_Printf ("CreateSurface Primary Screen FAILED"); DBG_Printf (DDErr(hr)); return FALSE; } if (fullScreen) { // Get a pointer to the back buffer DDSCAPS2 ddscaps; ddscaps.dwCaps = DDSCAPS_BACKBUFFER;// | DDSCAPS_3DDEVICE; hr = lpDDSPrimary->GetAttachedSurface (&ddscaps, &lpDDSBackBuffer); if (FAILED(hr)) { DBG_Printf ("GetAttachedSurface FAILED"); DBG_Printf (DDErr(hr)); return FALSE; } } else { GetClientRect( appWin, &rcScreenRect ); GetClientRect( appWin, &rcViewportRect ); ClientToScreen( appWin, (POINT*)&rcScreenRect.left ); ClientToScreen( appWin, (POINT*)&rcScreenRect.right ); // Create a back buffer for offscreen rendering, this will be used to // blt to the primary lpDDSBackBuffer = CreateNewSurface(DIMW, DIMH, DDSCAPS_OFFSCREENPLAIN | DDSCAPS_3DDEVICE); if (lpDDSBackBuffer == NULL) { DBG_Printf ("CreateSurface Secondary Screen FAILED"); return FALSE; } } if (!fullScreen) { LPDIRECTDRAWCLIPPER pcClipper; hr = lpDD4->CreateClipper( 0, &pcClipper, NULL ); if (FAILED(hr)) { DBG_Printf (DDErr(hr)); return FALSE; } pcClipper->SetHWnd( 0, appWin ); lpDDSPrimary->SetClipper( pcClipper ); pcClipper->Release(); } //------------------------------------------------------------------------- // Create the Direct3D interfaces //------------------------------------------------------------------------- // Query DirectDraw for access to Direct3D // see Init() // Before creating the device, check that we are NOT in a palettized // display. That case will cause CreateDevice() to fail, don't bother // with palettes.. ddsd.dwSize = sizeof(ddsd); lpDD4->GetDisplayMode( &ddsd ); if( ddsd.ddpfPixelFormat.dwRGBBitCount <= 8 ) { DBG_Printf ("Screen palettized format not supported\r\n"); return FALSE; } // Create the device. The GUID is hardcoded for now, but should come from // device enumeration, which is the topic of a future tutorial. The device // is created off of our back buffer, which becomes the render target for // the newly created device. hr = lpD3D->CreateDevice( IID_IDirect3DHALDevice, lpDDSBackBuffer, &lpD3DDevice, NULL ); if( FAILED( hr ) ) { DBG_Printf ("Create Device FAILED\r\n"); DBG_Printf (DDErr(hr)); return FALSE; } //------------------------------------------------------------------------- // Create the viewport //------------------------------------------------------------------------- // Set up the viewport data parameters D3DVIEWPORT2 vdData; ZeroMemory( &vdData, sizeof(vdData) ); vdData.dwSize = sizeof(vdData); vdData.dwWidth = DIMW; vdData.dwHeight = DIMH; vdData.dvClipX = -1.0f; vdData.dvClipWidth = 2.0f; vdData.dvClipY = 1.0f; vdData.dvClipHeight = 2.0f; vdData.dvMaxZ = 1.0f; // Create the viewport hr = lpD3D->CreateViewport( &lpD3DViewport, NULL ); if( FAILED( hr ) ) { DBG_Printf ("lpD3D->CreateViewport FAILED\r\n"); DBG_Printf (DDErr(hr)); return FALSE; } // Associate the viewport with the D3DDEVICE object lpD3DDevice->AddViewport( lpD3DViewport ); // Set the parameters to the new viewport lpD3DViewport->SetViewport2( &vdData ); // Set the viewport as current for the device lpD3DDevice->SetCurrentViewport( lpD3DViewport ); //------------------------------------------------------------------------- // We're done and ready to set up our scene //------------------------------------------------------------------------- // set initial state of d3d D3D_InitStates (lpD3DDevice, lpD3DViewport); lvid->direct = NULL; d3d_display = true; //save lvid to free software vidbuffer on shutdown viddef = lvid; DBG_Printf("SetD3DMode() succesfull\r\n"); return 1; } // -------------------------------------------------------------------------- // Checks for lost surfaces and restores them if lost. // -------------------------------------------------------------------------- void RestoreSurfaces() { // Check/restore the primary surface if( lpDDSPrimary ) if( lpDDSPrimary->IsLost() ) lpDDSPrimary->Restore(); // Check/restore the back buffer if( lpDDSBackBuffer ) if( lpDDSBackBuffer->IsLost() ) lpDDSBackBuffer->Restore(); } // -------------------------------------------------------------------------- // Swap front and back buffers // -------------------------------------------------------------------------- EXPORT void HWRAPI( FinishUpdate ) (void) { HRESULT hr; if (!lpDDSPrimary) return; // show fps? // draw software view ? // page flip D3D_BufferClear (); if ( FAILED( lpD3DDevice->BeginScene() ) ) return; lpD3DDevice->DrawPrimitive( D3DPT_TRIANGLELIST, D3DFVF_VERTEX, pvTriangleVertices, 6, NULL ); // End the scene. lpD3DDevice->EndScene(); // We are in windowed mode, so perform a blit from the backbuffer to the // correct position on the primary surface if (fullScreen) { } else { hr = lpDDSPrimary->Blt( &rcScreenRect, lpDDSBackBuffer, &rcViewportRect, DDBLT_WAIT, NULL ); if (hr == DDERR_SURFACELOST) RestoreSurfaces (); } } // -------------------------------------------------------------------------- // Moves the screen rect for windowed renderers // -------------------------------------------------------------------------- void OnWindowMove( int x, int y ) { DWORD dwWidth = rcScreenRect.right - rcScreenRect.left; DWORD dwHeight = rcScreenRect.bottom - rcScreenRect.top; SetRect( &rcScreenRect, x, y, x + dwWidth, y + dwHeight ); } // -------------------------------------------------------------------------- // // -------------------------------------------------------------------------- //TODO: do the chroma key stuff out of here EXPORT void HWRAPI( SetPalette ) (PALETTEENTRY* pal, RGBA_t *gamma) { int i; if (!d3d_display) return; // create the palette in the format used for downloading to 3Dfx card for (i=0; i<256; i++) myPaletteData[i] = (0xFF << 24) | //alpha (pal[i].peRed<<16) | (pal[i].peGreen<<8) | pal[i].peBlue; // make sure the chromakey color is always the same value myPaletteData[HWR_PATCHES_CHROMAKEY_COLORINDEX] = HWR_PATCHES_CHROMAKEY_COLORVALUE; // download palette } // ************************************************************************** // // ************************************************************************** // -------------------------------------------------------------------------- // Do a full buffer clear including color / alpha / and Z buffers // -------------------------------------------------------------------------- static void D3D_BufferClear (void) { // clear color/alpha and depth buffers if (lpD3DViewport) lpD3DViewport->Clear2( 1UL, (D3DRECT*)&rcViewportRect, D3DCLEAR_TARGET, 0x000000ff, 0L, 0L ); } // -------------------------------------------------------------------------- // Set initial state of 3d card settings // -------------------------------------------------------------------------- static BOOL D3D_InitStates (LPDIRECT3DDEVICE3 pd3dDevice, LPDIRECT3DVIEWPORT3 pvViewport) { DBG_Printf ("InitD3DStates()...\r\n"); // Get a ptr to the ID3D object to create materials and/or lights. LPDIRECT3D3 pD3D; if( FAILED( pd3dDevice->GetDirect3D( &pD3D ) ) ) return FALSE; pD3D->Release(); // Data for the geometry of the triangle. Note that this tutorial only // uses ambient lighting, so the vertices' normals are not actually used. D3DVECTOR p1( 0.0f, 3.0f, 0.0f ); D3DVECTOR p2( 3.0f,-3.0f, 0.0f ); D3DVECTOR p3(-3.0f,-3.0f, 0.0f ); D3DVECTOR vNormal( 0.0f, 0.0f, 1.0f ); // Initialize the 3 vertices for the front of the triangle pvTriangleVertices[0] = D3DVERTEX( p1, vNormal, 0, 0 ); pvTriangleVertices[1] = D3DVERTEX( p2, vNormal, 0, 0 ); pvTriangleVertices[2] = D3DVERTEX( p3, vNormal, 0, 0 ); // Initialize the 3 vertices for the back of the triangle pvTriangleVertices[3] = D3DVERTEX( p1, -vNormal, 0, 0 ); pvTriangleVertices[4] = D3DVERTEX( p3, -vNormal, 0, 0 ); pvTriangleVertices[5] = D3DVERTEX( p2, -vNormal, 0, 0 ); // get min/max w buffer range values // set my vertex format (the one of wallVert2D hwr_data.h) // set coord space // set W buffer // depth buffer func cmp_less // enable depth buffer // Ambient lighting on to full white. pd3dDevice->SetLightState( D3DLIGHTSTATE_AMBIENT, 0xffffffff ); D3D_BufferClear(); return TRUE; } // ************************************************************************** // TEXTURE CACHE MANAGEMENT // ************************************************************************** static DWORD gr_cachemin; static DWORD gr_cachemax; static DWORD gr_cachetailpos; // manage a cycling cache for mipmaps static DWORD gr_cachepos; static GlideMipmap_t* gr_cachetail; static GlideMipmap_t* gr_cachehead; // -------------------------------------------------------------------------- // This must be done once only for all program execution // -------------------------------------------------------------------------- static void D3D_ClearMipmapCache (void) { DBG_Printf ("ClearMipmapCache() \r\n"); while (gr_cachetail) { gr_cachetail->downloaded = false; gr_cachetail = gr_cachetail->next; } gr_cachetail = NULL; gr_cachehead = NULL; gr_cachetailpos = gr_cachepos = gr_cachemin; } static void D3D_InitMipmapCache (void) { DBG_Printf ("InitMipmapCache() \r\n"); /* gr_cachemin = grTexMinAddress(GR_TMU0); gr_cachemax = grTexMaxAddress(GR_TMU0); */ //testing.. //gr_cachemax = gr_cachemin + (1024<<10); gr_cachetail = NULL; D3D_ClearMipmapCache(); //CONS_Printf ("HWR_InitMipmapCache() : %d kb\n", (gr_cachemax-gr_cachemin)>>10); } static void D3D_FlushMipmap (GlideMipmap_t* mipmap) { mipmap->downloaded = false; gr_cachetail = mipmap->next; // should never happen if (!mipmap->next) // I_Error ("This just CAN'T HAPPEN!!! So you think you're different eh ?"); D3D_ClearMipmapCache (); else gr_cachetailpos = mipmap->next->cachepos; } // -------------------------------------------------------------------------- // Download a 'surface' into the graphics card memory // -------------------------------------------------------------------------- void D3D_DownloadMipmap (GlideMipmap_t* grMipmap) { DWORD mipmapSize; DWORD freespace; if (grMipmap->downloaded) return; DBG_Printf ("Downloading mipmap\r\n"); return; /* //if (grMipmap->grInfo.data == NULL) // I_Error ("info.data is NULL\n"); // (re-)download the texture data //mipmapSize = grTexTextureMemRequired(GR_MIPMAPLEVELMASK_BOTH, &grMipmap->grInfo); //CONS_Printf ("DOWNLOAD\n"); // flush out older mipmaps to make space //CONS_Printf ("HWR_DownloadTexture: texture too big for TMU0\n"); if (gr_cachehead) { while (1) { if (gr_cachetailpos >= gr_cachepos) freespace = gr_cachetailpos - gr_cachepos; else freespace = gr_cachemax - gr_cachepos; if (freespace >= mipmapSize) break; //CONS_Printf (" tail: %#07d pos: %#07d\n" // " size: %#07d free: %#07d\n", // gr_cachetailpos, gr_cachepos, mipmapSize, freespace); // not enough space in the end of the buffer if (gr_cachepos > gr_cachetailpos) { gr_cachepos = gr_cachemin; //CONS_Printf (" cycle over\n"); } else{ FlushMipmap (gr_cachetail); } } } grMipmap->startAddress = gr_cachepos; //gr_cachepos += mipmapSize; grMipmap->mipmapSize = mipmapSize; //grTexDownloadMipMap (GR_TMU0, grMipmap->startAddress, GR_MIPMAPLEVELMASK_BOTH, &grMipmap->grInfo); grMipmap->downloaded = true; // store pointer to downloaded mipmap if (gr_cachehead) gr_cachehead->next = grMipmap; else { gr_cachetail = gr_cachehead = grMipmap; } grMipmap->cachepos = gr_cachepos; grMipmap->next = NULL; //debug (not used) gr_cachepos += mipmapSize; gr_cachehead = grMipmap; */ } void D3D_DownloadCorona(void) { RGBA_t tex[128][128]; int i, j; for (i=0; i<128; i++) for (j=0; j<128; j++) { int pos = ((i-64)*(i-64))+((j-64)*(j-64)); if (pos <= 63*63) { tex[i][j].red = 0xff; tex[i][j].green = 0xff; tex[i][j].blue = 0xff; tex[i][j].alpha = 255-(unsigned char)(4*sqrt(pos)); } else { tex[i][j].red = 0x00; tex[i][j].green = 0x00; tex[i][j].blue = 0x00; tex[i][j].alpha = 0x00; } } // load Texture in D3D Memory } // ========================================================================== // The mipmap becomes the current texture source // ========================================================================== EXPORT void HWRAPI( SetTexture ) (GlideMipmap_t* grMipmap) { if (!grMipmap->downloaded) D3D_DownloadMipmap (grMipmap); //grTexSource (GR_TMU0, grMipmap->startAddress, GR_MIPMAPLEVELMASK_BOTH, &grMipmap->grInfo); } // ========================================================================== // // ========================================================================== EXPORT void HWRAPI( SetState ) (hwdstate_t IdState, int Value) { /* switch (IdState) { // set depth buffer on/off case HWD_SET_DEPTHMASK: grDepthMask (Value); break; case HWD_SET_COLORMASK: grColorMask (Value, FXTRUE); //! alpha buffer true break; case HWD_SET_CULLMODE: grCullMode (Value ? GR_CULL_POSITIVE : GR_CULL_DISABLE); break; case HWD_SET_CONSTANTCOLOR: grConstantColorValue (Value); break; case HWD_SET_COLORSOURCE: if (Value == HWD_COLORSOURCE_CONSTANT) { grColorCombine( GR_COMBINE_FUNCTION_ZERO, GR_COMBINE_FACTOR_ZERO, GR_COMBINE_LOCAL_CONSTANT, GR_COMBINE_OTHER_NONE, FXFALSE ); } else if (Value == HWD_COLORSOURCE_ITERATED) { grColorCombine(GR_COMBINE_FUNCTION_LOCAL, GR_COMBINE_FACTOR_NONE, GR_COMBINE_LOCAL_ITERATED, GR_COMBINE_OTHER_NONE, FXFALSE ); } else if (Value == HWD_COLORSOURCE_TEXTURE) { grColorCombine( GR_COMBINE_FUNCTION_SCALE_OTHER, GR_COMBINE_FACTOR_ONE, GR_COMBINE_LOCAL_NONE, GR_COMBINE_OTHER_TEXTURE, FXFALSE ); } else if (Value == HWD_COLORSOURCE_CONSTANTALPHA_SCALE_TEXTURE) { grColorCombine( GR_COMBINE_FUNCTION_SCALE_OTHER, // factor * Color other GR_COMBINE_FACTOR_LOCAL_ALPHA, GR_COMBINE_LOCAL_CONSTANT, //ITERATED // local is constant color GR_COMBINE_OTHER_TEXTURE, // color from texture map FXFALSE ); } break; case HWD_SET_ALPHABLEND: if (Value == HWD_ALPHABLEND_NONE) { grAlphaBlendFunction(GR_BLEND_ONE, GR_BLEND_ZERO, GR_BLEND_ONE, GR_BLEND_ZERO); grAlphaTestFunction (GR_CMP_ALWAYS); } else if (Value == HWD_ALPHABLEND_TRANSLUCENT) { grAlphaBlendFunction (GR_BLEND_SRC_ALPHA, GR_BLEND_ONE_MINUS_SRC_ALPHA, GR_BLEND_ONE, GR_BLEND_ZERO ); } break; case HWD_SET_TEXTURECLAMP: if (Value == HWD_TEXTURE_CLAMP_XY) { grTexClampMode (GR_TMU0, GR_TEXTURECLAMP_CLAMP, GR_TEXTURECLAMP_CLAMP); } else if (Value == HWD_TEXTURE_WRAP_XY) { grTexClampMode (GR_TMU0, GR_TEXTURECLAMP_WRAP, GR_TEXTURECLAMP_WRAP); } break; case HWD_SET_TEXTURECOMBINE: if (Value == HWD_TEXTURECOMBINE_NORMAL) { grTexCombine (GR_TMU0, GR_COMBINE_FUNCTION_LOCAL, GR_COMBINE_FACTOR_NONE, GR_COMBINE_FUNCTION_LOCAL, GR_COMBINE_FACTOR_NONE, FXFALSE, FXFALSE ); } break; case HWD_SET_TEXTUREFILTERMODE: if (Value == HWD_SET_TEXTUREFILTER_BILINEAR) { grTexFilterMode (GR_TMU0, GR_TEXTUREFILTER_BILINEAR, GR_TEXTUREFILTER_BILINEAR); } else if (Value == HWD_SET_TEXTUREFILTER_POINTSAMPLED) { grTexFilterMode (GR_TMU0, GR_TEXTUREFILTER_POINT_SAMPLED, GR_TEXTUREFILTER_POINT_SAMPLED); } break; case HWD_SET_MIPMAPMODE: if (Value == HWD_MIPMAP_DISABLE) { grTexMipMapMode (GR_TMU0, GR_MIPMAP_DISABLE, // no mipmaps based on depth FXFALSE ); } break; //!!!hardcoded 3Dfx Value!!! case HWD_SET_ALPHATESTFUNC: grAlphaTestFunction (Value); break; //!!!hardcoded 3Dfx Value!!! case HWD_SET_ALPHATESTREFVALUE: grAlphaTestReferenceValue ((unsigned char)Value); break; case HWD_SET_ALPHASOURCE: if (Value == HWD_ALPHASOURCE_CONSTANT) { // constant color alpha grAlphaCombine( GR_COMBINE_FUNCTION_LOCAL_ALPHA, GR_COMBINE_FACTOR_NONE, GR_COMBINE_LOCAL_CONSTANT, GR_COMBINE_OTHER_NONE, FXFALSE ); } else if (Value == HWD_ALPHASOURCE_TEXTURE) { // 1 * texture alpha channel grAlphaCombine( GR_COMBINE_FUNCTION_SCALE_OTHER, GR_COMBINE_FACTOR_ONE, GR_COMBINE_LOCAL_NONE, GR_COMBINE_OTHER_TEXTURE, FXFALSE ); } break; case HWD_ENABLE: if (Value == HWD_SHAMELESS_PLUG) grEnable (GR_SHAMELESS_PLUG); break; case HWD_DISABLE: if (Value == HWD_SHAMELESS_PLUG) grDisable (GR_SHAMELESS_PLUG); break; case HWD_SET_FOG_TABLE: grFogTable ((unsigned char *)Value); break; case HWD_SET_FOG_COLOR: grFogColorValue (Value); break; case HWD_SET_FOG_MODE: if (Value == HWD_FOG_DISABLE) grFogMode (GR_FOG_DISABLE); else if (Value == HWD_FOG_ENABLE) grFogMode (GR_FOG_WITH_TABLE_ON_Q); break; case HWD_SET_CHROMAKEY_MODE: if (Value == HWD_CHROMAKEY_ENABLE) grChromakeyMode (GR_CHROMAKEY_ENABLE); break; case HWD_SET_CHROMAKEY_VALUE: grChromakeyValue (Value); break; default: break; } */ } // ========================================================================== // Read a rectangle region of the truecolor framebuffer // store pixels as 16bit 565 RGB // ========================================================================== EXPORT void HWRAPI( ReadRect ) (int x, int y, int width, int height, int dst_stride, unsigned short * dst_data) { DBG_Printf ("ReadRect()\r\n"); //grLfbReadRegion (GR_BUFFER_FRONTBUFFER, // x, y, width, height, dst_stride, dst_data); } // ========================================================================== // Defines the 2D hardware clipping window // ========================================================================== EXPORT void HWRAPI( ClipRect ) (int minx, int miny, int maxx, int maxy) { DBG_Printf ("ClipRect()\r\n"); //grClipWindow ( (DWORD)minx, (DWORD)miny, (DWORD)maxx, (DWORD)maxy); } // ========================================================================== // Clear the color/alpha/depth buffer(s) // ========================================================================== EXPORT void HWRAPI( ClearBuffer ) (int color, int alpha, hwdcleardepth_t depth) { DBG_Printf ("ClearBuffer()\r\n"); //grBufferClear ((GrColor_t)color, (GrAlpha_t)alpha, gr_wrange[depth]); } // ========================================================================== // // ========================================================================== EXPORT void HWRAPI( DrawLine ) (wallVert2D* v1, wallVert2D* v2) { //grDrawLine (v1, v2); } // ========================================================================== // // ========================================================================== EXPORT void HWRAPI( GetState ) (hwdgetstate_t IdState, void* dest) { DBG_Printf ("GetState()\r\n"); /* if (IdState == HWD_GET_FOGTABLESIZE) { grGet (GR_FOG_TABLE_ENTRIES, 4, dest); } */ } // ========================================================================== // Draw a triangulated polygon // ========================================================================== EXPORT void HWRAPI( DrawPolygon ) (wallVert2D *projVerts, int nClipVerts, unsigned long col) { /* int nTris; int i; if (nClipVerts < 3) return; nTris = nClipVerts-2; // triangles fan for(i=0; i < nTris; i++) { // set some weird colours projVerts[0].argb = col; projVerts[i+1].argb = col | 0x80; projVerts[i+2].argb = col | 0xf0; //FIXME: 3Dfx : check for 'crash' coordinates if not clipped if (projVerts[0].x > 1280.0f || projVerts[0].x < -640.0f) goto skip; if (projVerts[0].y > 900.0f || projVerts[0].y < -500.0f) goto skip; if (projVerts[i+1].x > 1280.0f || projVerts[i+1].x < -640.0f) goto skip; if (projVerts[i+1].y > 900.0f || projVerts[i+1].y < -500.0f) goto skip; if (projVerts[i+2].x > 1280.0f || projVerts[i+2].x < -640.0f) goto skip; if (projVerts[i+2].y > 900.0f || projVerts[i+2].y < -500.0f) goto skip; grDrawTriangle ( projVerts, &projVerts[i + 1], &projVerts[i + 2] ); skip: col = col + 0x002000; } */ } //**************************************************************************** // D3D_Text * //**************************************************************************** void D3D_Text(unsigned x, unsigned y, unsigned scale, char* format, ...) { va_list args; char buffer[1024]; va_start(args, format); vsprintf(buffer, format, args); va_end(args); // Print to D3D output } /* //--------------------------------------------------------------------------- // Set to flat shading. // This code fragment assumes that lpDev3 is a valid pointer to // an IDirect3DDevice3 interface. hr = lpDev3->SetRenderState(D3DRENDERSTATE_SHADEMODE, D3DSHADE_FLAT); if(FAILED(hr)) { // Code to handle the error goes here. } // Set to Gouraud shading (this is the default for Direct3D). hr = lpDev3->SetRenderState(D3DRENDERSTATE_SHADEMODE, D3DSHADE_GOURAUD); if(FAILED(hr)) { // Code to handle the error goes here. } //--------------------------------------------------------------------------- D3DVERTEX lpVertices[3]; // A vertex can be specified one structure member at a time. lpVertices[0].x = 0; lpVertices[0].y = 5; lpVertices[0].z = 5; lpVertices[0].nx = 0; // X component of the normal vector. lpVertices[0].ny = 0; // Y component of the normal vector. lpVertices[0].nz = -1; // Points the normal back at the origin. lpVertices[0].tu = 0; // Only used if a texture is being used. lpVertices[0].tv = 0; // Only used if a texture is being used. // Vertices can also by specified on one line of code for each vertex // by using some of the D3DOVERLOADS macros. lpVertices[1] = D3DVERTEX(D3DVECTOR(-5,-5,5),D3DVECTOR(0,0,-1),0,0); lpVertices[2] = D3DVERTEX(D3DVECTOR(5,-5,5),D3DVECTOR(0,0,-1),0,0); //---------------------------------------------------------------------------- An application uses the dwShadeCaps member of the D3DPRIMCAPS structure to determine what forms of interpolation the current device driver supports. //---------------------------------------------------------------------------- DirectDrawCreate You can call the IDirect3D3::CreateDevice method to create a Direct3DDevice object and retrieve an IDirect3DDevice3 interface. //---------------------------------------------------------------------------- The Direct3D Immediate Mode API consists primarily of the following COM interfaces: IDirect3D3 Root interface, used to obtain other interfaces IDirect3DDevice 3D Device for execute-buffer based programming IDirect3DDevice3 3D Device for DrawPrimitive-based programming IDirect3DLight Interface used to work with lights IDirect3DMaterial3 Surface-material interface IDirect3DTexture2 Texture-map interface IDirect3DVertexBuffer Interface used to work with vertex buffers. IDirect3DViewport3 Interface to define the viewport's characteristics. IDirect3DExecuteBuffer Interface for working with execute buffers */ static char* DDErr(HRESULT hresult) { static char errmsg[128]; static char msgtxt[128]; switch(hresult) { case DD_OK: strcpy(errmsg,"The request completed successfully."); break; case DDERR_ALREADYINITIALIZED: strcpy(errmsg,"The object has already been initialized."); break; case DDERR_BLTFASTCANTCLIP: strcpy(errmsg,"A DirectDrawClipper object is attached to a source surface that has passed into a call to the IDirectDrawSurface2::BltFast method."); break; case DDERR_CANNOTATTACHSURFACE: strcpy(errmsg,"A surface cannot be attached to another requested surface."); break; case DDERR_CANNOTDETACHSURFACE: strcpy(errmsg,"A surface cannot be detached from another requested surface."); break; case DDERR_CANTCREATEDC: strcpy(errmsg,"Windows cannot create any more device contexts (DCs)."); break; case DDERR_CANTDUPLICATE: strcpy(errmsg,"Primary and 3D surfaces, or surfaces that are implicitly created, cannot be duplicated."); break; case DDERR_CANTLOCKSURFACE: strcpy(errmsg,"Access to this surface is refused because an attempt was made to lock the primary surface without DCI support."); break; case DDERR_CANTPAGELOCK: strcpy(errmsg,"An attempt to page lock a surface failed. Page lock will not work on a display-memory surface or an emulated primary surface."); break; case DDERR_CANTPAGEUNLOCK: strcpy(errmsg,"An attempt to page unlock a surface failed. Page unlock will not work on a display-memory surface or an emulated primary surface."); break; case DDERR_CLIPPERISUSINGHWND: strcpy(errmsg,"An attempt was made to set a clip list for a DirectDrawClipper object that is already monitoring a window handle."); break; case DDERR_COLORKEYNOTSET: strcpy(errmsg,"No source color key is specified for this operation."); break; case DDERR_CURRENTLYNOTAVAIL: strcpy(errmsg,"No support is currently available."); break; case DDERR_DCALREADYCREATED: strcpy(errmsg,"A device context (DC) has already been returned for this surface. Only one DC can be retrieved for each surface."); break; case DDERR_DIRECTDRAWALREADYCREATED: strcpy(errmsg,"A DirectDraw object representing this driver has already been created for this process."); break; case DDERR_EXCEPTION: strcpy(errmsg,"An exception was encountered while performing the requested operation."); break; case DDERR_EXCLUSIVEMODEALREADYSET: strcpy(errmsg,"An attempt was made to set the cooperative level when it was already set to exclusive."); break; case DDERR_GENERIC: strcpy(errmsg,"There is an undefined error condition."); break; case DDERR_HEIGHTALIGN: strcpy(errmsg,"The height of the provided rectangle is not a multiple of the required alignment."); break; case DDERR_HWNDALREADYSET: strcpy(errmsg,"The DirectDraw cooperative level window handle has already been set. It cannot be reset while the process has surfaces or palettes created."); break; case DDERR_HWNDSUBCLASSED: strcpy(errmsg,"DirectDraw is prevented from restoring state because the DirectDraw cooperative level window handle has been subclassed."); break; case DDERR_IMPLICITLYCREATED: strcpy(errmsg,"The surface cannot be restored because it is an implicitly created surface."); break; case DDERR_INCOMPATIBLEPRIMARY: strcpy(errmsg,"The primary surface creation request does not match with the existing primary surface."); break; case DDERR_INVALIDCAPS: strcpy(errmsg,"One or more of the capability bits passed to the callback function are incorrect."); break; case DDERR_INVALIDCLIPLIST: strcpy(errmsg,"DirectDraw does not support the provided clip list."); break; case DDERR_INVALIDDIRECTDRAWGUID: strcpy(errmsg,"The globally unique identifier (GUID) passed to the DirectDrawCreate function is not a valid DirectDraw driver identifier."); break; case DDERR_INVALIDMODE: strcpy(errmsg,"DirectDraw does not support the requested mode."); break; case DDERR_INVALIDOBJECT: strcpy(errmsg,"DirectDraw received a pointer that was an invalid DirectDraw object."); break; case DDERR_INVALIDPARAMS: strcpy(errmsg,"One or more of the parameters passed to the method are incorrect."); break; case DDERR_INVALIDPIXELFORMAT: strcpy(errmsg,"The pixel format was invalid as specified."); break; case DDERR_INVALIDPOSITION: strcpy(errmsg,"The position of the overlay on the destination is no longer legal."); break; case DDERR_INVALIDRECT: strcpy(errmsg,"The provided rectangle was invalid."); break; case DDERR_INVALIDSURFACETYPE: strcpy(errmsg,"The requested operation could not be performed because the surface was of the wrong type."); break; case DDERR_LOCKEDSURFACES: strcpy(errmsg,"One or more surfaces are locked, causing the failure of the requested operation."); break; case DDERR_NO3D: strcpy(errmsg,"No 3D hardware or emulation is present."); break; case DDERR_NOALPHAHW: strcpy(errmsg,"No alpha acceleration hardware is present or available, causing the failure of the requested operation."); break; case DDERR_NOBLTHW: strcpy(errmsg,"No blitter hardware is present."); break; case DDERR_NOCLIPLIST: strcpy(errmsg,"No clip list is available."); break; case DDERR_NOCLIPPERATTACHED: strcpy(errmsg,"No DirectDrawClipper object is attached to the surface object."); break; case DDERR_NOCOLORCONVHW: strcpy(errmsg,"The operation cannot be carried out because no color-conversion hardware is present or available."); break; case DDERR_NOCOLORKEY: strcpy(errmsg,"The surface does not currently have a color key."); break; case DDERR_NOCOLORKEYHW: strcpy(errmsg,"The operation cannot be carried out because there is no hardware support for the destination color key."); break; case DDERR_NOCOOPERATIVELEVELSET: strcpy(errmsg,"A create function is called without the IDirectDraw2::SetCooperativeLevel method being called."); break; case DDERR_NODC: strcpy(errmsg,"No DC has ever been created for this surface."); break; case DDERR_NODDROPSHW: strcpy(errmsg,"No DirectDraw raster operation (ROP) hardware is available."); break; case DDERR_NODIRECTDRAWHW: strcpy(errmsg,"Hardware-only DirectDraw object creation is not possible; the driver does not support any hardware."); break; case DDERR_NODIRECTDRAWSUPPORT: strcpy(errmsg,"DirectDraw support is not possible with the current display driver."); break; case DDERR_NOEMULATION: strcpy(errmsg,"Software emulation is not available."); break; case DDERR_NOEXCLUSIVEMODE: strcpy(errmsg,"The operation requires the application to have exclusive mode, but the application does not have exclusive mode."); break; case DDERR_NOFLIPHW: strcpy(errmsg,"Flipping visible surfaces is not supported."); break; case DDERR_NOGDI: strcpy(errmsg,"No GDI is present."); break; case DDERR_NOHWND: strcpy(errmsg,"Clipper notification requires a window handle, or no window handle has been previously set as the cooperative level window handle."); break; case DDERR_NOMIPMAPHW: strcpy(errmsg,"The operation cannot be carried out because no mipmap texture mapping hardware is present or available."); break; case DDERR_NOMIRRORHW: strcpy(errmsg,"The operation cannot be carried out because no mirroring hardware is present or available."); break; case DDERR_NOOVERLAYDEST: strcpy(errmsg,"The IDirectDrawSurface2::GetOverlayPosition method is called on an overlay that the IDirectDrawSurface2::UpdateOverlay method has not been called on to establish a destination."); break; case DDERR_NOOVERLAYHW: strcpy(errmsg,"The operation cannot be carried out because no overlay hardware is present or available."); break; case DDERR_NOPALETTEATTACHED: strcpy(errmsg,"No palette object is attached to this surface."); break; case DDERR_NOPALETTEHW: strcpy(errmsg,"There is no hardware support for 16- or 256-color palettes."); break; case DDERR_NORASTEROPHW: strcpy(errmsg,"The operation cannot be carried out because no appropriate raster operation hardware is present or available."); break; case DDERR_NOROTATIONHW: strcpy(errmsg,"The operation cannot be carried out because no rotation hardware is present or available."); break; case DDERR_NOSTRETCHHW: strcpy(errmsg,"The operation cannot be carried out because there is no hardware support for stretching."); break; case DDERR_NOT4BITCOLOR: strcpy(errmsg,"The DirectDrawSurface object is not using a 4-bit color palette and the requested operation requires a 4-bit color palette."); break; case DDERR_NOT4BITCOLORINDEX: strcpy(errmsg,"The DirectDrawSurface object is not using a 4-bit color index palette and the requested operation requires a 4-bit color index palette."); break; case DDERR_NOT8BITCOLOR: strcpy(errmsg,"The DirectDrawSurface object is not using an 8-bit color palette and the requested operation requires an 8-bit color palette."); break; case DDERR_NOTAOVERLAYSURFACE: strcpy(errmsg,"An overlay component is called for a non-overlay surface."); break; case DDERR_NOTEXTUREHW: strcpy(errmsg,"The operation cannot be carried out because no texture-mapping hardware is present or available."); break; case DDERR_NOTFLIPPABLE: strcpy(errmsg,"An attempt has been made to flip a surface that cannot be flipped."); break; case DDERR_NOTFOUND: strcpy(errmsg,"The requested item was not found."); break; case DDERR_NOTINITIALIZED: strcpy(errmsg,"An attempt was made to call an interface method of a DirectDraw object created by CoCreateInstance before the object was initialized."); break; case DDERR_NOTLOCKED: strcpy(errmsg,"An attempt is made to unlock a surface that was not locked."); break; case DDERR_NOTPAGELOCKED: strcpy(errmsg,"An attempt is made to page unlock a surface with no outstanding page locks."); break; case DDERR_NOTPALETTIZED: strcpy(errmsg,"The surface being used is not a palette-based surface."); break; case DDERR_NOVSYNCHW: strcpy(errmsg,"The operation cannot be carried out because there is no hardware support for vertical blank synchronized operations."); break; case DDERR_NOZBUFFERHW: strcpy(errmsg,"The operation to create a z-buffer in display memory or to perform a blit using a z-buffer cannot be carried out because there is no hardware support for z-buffers."); break; case DDERR_NOZOVERLAYHW: strcpy(errmsg,"The overlay surfaces cannot be z-layered based on the z-order because the hardware does not support z-ordering of overlays."); break; case DDERR_OUTOFCAPS: strcpy(errmsg,"The hardware needed for the requested operation has already been allocated."); break; case DDERR_OUTOFMEMORY: strcpy(errmsg,"DirectDraw does not have enough memory to perform the operation."); break; case DDERR_OUTOFVIDEOMEMORY: strcpy(errmsg,"DirectDraw does not have enough display memory to perform the operation."); break; case DDERR_OVERLAYCANTCLIP: strcpy(errmsg,"The hardware does not support clipped overlays."); break; case DDERR_OVERLAYCOLORKEYONLYONEACTIVE: strcpy(errmsg,"An attempt was made to have more than one color key active on an overlay."); break; case DDERR_OVERLAYNOTVISIBLE: strcpy(errmsg,"The IDirectDrawSurface2::GetOverlayPosition method is called on a hidden overlay."); break; case DDERR_PALETTEBUSY: strcpy(errmsg,"Access to this palette is refused because the palette is locked by another thread."); break; case DDERR_PRIMARYSURFACEALREADYEXISTS: strcpy(errmsg,"This process has already created a primary surface."); break; case DDERR_REGIONTOOSMALL: strcpy(errmsg,"The region passed to the IDirectDrawClipper::GetClipList method is too small."); break; case DDERR_SURFACEALREADYATTACHED: strcpy(errmsg,"An attempt was made to attach a surface to another surface to which it is already attached."); break; case DDERR_SURFACEALREADYDEPENDENT: strcpy(errmsg,"An attempt was made to make a surface a dependency of another surface to which it is already dependent."); break; case DDERR_SURFACEBUSY: strcpy(errmsg,"Access to the surface is refused because the surface is locked by another thread."); break; case DDERR_SURFACEISOBSCURED: strcpy(errmsg,"Access to the surface is refused because the surface is obscured."); break; case DDERR_SURFACELOST: strcpy(errmsg,"Access to the surface is refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have the IDirectDrawSurface2::Restore method called on it."); break; case DDERR_SURFACENOTATTACHED: strcpy(errmsg,"The requested surface is not attached."); break; case DDERR_TOOBIGHEIGHT: strcpy(errmsg,"The height requested by DirectDraw is too large."); break; case DDERR_TOOBIGSIZE: strcpy(errmsg,"The size requested by DirectDraw is too large. However, the individual height and width are OK."); break; case DDERR_TOOBIGWIDTH: strcpy(errmsg,"The width requested by DirectDraw is too large."); break; case DDERR_UNSUPPORTED: strcpy(errmsg,"The operation is not supported."); break; case DDERR_UNSUPPORTEDFORMAT: strcpy(errmsg,"The FourCC format requested is not supported by DirectDraw."); break; case DDERR_UNSUPPORTEDMASK: strcpy(errmsg,"The bitmask in the pixel format requested is not supported by DirectDraw."); break; case DDERR_UNSUPPORTEDMODE: strcpy(errmsg,"The display is currently in an unsupported mode."); break; case DDERR_VERTICALBLANKINPROGRESS: strcpy(errmsg,"A vertical blank is in progress."); break; case DDERR_WASSTILLDRAWING: strcpy(errmsg,"The previous blit operation that is transferring information to or from this surface is incomplete."); break; case DDERR_WRONGMODE: strcpy(errmsg,"This surface cannot be restored because it was created in a different mode."); break; case DDERR_XALIGN: strcpy(errmsg,"The provided rectangle was not horizontally aligned on a required boundary."); break; default: wsprintf(errmsg, "Unknown Error Code : %04X", hresult); break; } wsprintf(msgtxt, "DDraw Error: %s\n", errmsg); return msgtxt; } /* EXPORT void HWRAPI ( DrvWndProc ) (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { return; } */ /* Stupid D3D sample #define STRICT #include <windows.h> #include <time.h> #include <stdio.h> #include <d3d.h> #include "resource.h" //----------------------------------------------------------------------------- // Local variables for the DirectDraw and Direct3D interface. // // Note: A real programmer would not use global variables for these objects, // and use encapsulation instead. As it turns out, after initialization, any // Direct3D app can make do with only a LPDIRECT3DDEVICE3 parameter, and deduct // all other interfaces from that. //----------------------------------------------------------------------------- static LPDIRECTDRAW g_pDD1 = NULL; static LPDIRECTDRAW4 g_pDD4 = NULL; static LPDIRECTDRAWSURFACE4 g_pddsPrimary = NULL; static LPDIRECTDRAWSURFACE4 g_pddsBackBuffer = NULL; static LPDIRECTDRAWSURFACE4 g_pddsZBuffer = NULL; // Z-buffer surface (new) static LPDIRECT3D3 g_pD3D = NULL; static LPDIRECT3DDEVICE3 g_pd3dDevice = NULL; static LPDIRECT3DVIEWPORT3 g_pvViewport = NULL; static RECT g_rcScreenRect; static RECT g_rcViewportRect; //----------------------------------------------------------------------------- // Local variables for the Windows portion of the app //----------------------------------------------------------------------------- static BOOL g_bActive = FALSE; // Whether the app is active (not minimized) static BOOL g_bReady = FALSE; // Whether the app is ready to render frames //----------------------------------------------------------------------------- // Local function-prototypes //----------------------------------------------------------------------------- HRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM ); HRESULT CreateEverything( HWND ); HRESULT Initialize3DEnvironment( HWND, GUID*, const GUID* ); HRESULT Cleanup3DEnvironment(); HRESULT Render3DEnvironment(); VOID OnMove( INT, INT ); HRESULT ShowFrame(); HRESULT RestoreSurfaces(); //----------------------------------------------------------------------------- // External function-prototypes //----------------------------------------------------------------------------- VOID App_DeleteDeviceObjects( LPDIRECT3DDEVICE3, LPDIRECT3DVIEWPORT3 ); HRESULT App_InitDeviceObjects( LPDIRECT3DDEVICE3, LPDIRECT3DVIEWPORT3 ); HRESULT App_FrameMove( LPDIRECT3DDEVICE3, FLOAT ); HRESULT App_Render( LPDIRECT3DDEVICE3, LPDIRECT3DVIEWPORT3, D3DRECT* ); //----------------------------------------------------------------------------- // Name: WinMain() // Desc: Entry point to the program. Initializes everything, and goes into a // message-processing loop. Idle time is used to render the scene. //----------------------------------------------------------------------------- INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT ) { // Register the window class WNDCLASS wndClass = { CS_HREDRAW | CS_VREDRAW, WndProc, 0, 0, hInst, LoadIcon( hInst, MAKEINTRESOURCE(IDI_MAIN_ICON)), LoadCursor(NULL, IDC_ARROW), (HBRUSH)GetStockObject(WHITE_BRUSH), NULL, TEXT("Render Window") }; RegisterClass( &wndClass ); // Create our main window HWND hWnd = CreateWindow( TEXT("Render Window"), TEXT("D3D Tutorial: Adding a Z-buffer"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 300, 300, 0L, 0L, hInst, 0L ); ShowWindow( hWnd, SW_SHOWNORMAL ); UpdateWindow( hWnd ); // Load keyboard accelerators HACCEL hAccel = LoadAccelerators( hInst, MAKEINTRESOURCE(IDR_MAIN_ACCEL) ); // Initialize the app specifics. This is where all the DirectDraw/Direct3D // initialization happens, so see this function for the real purpose of // this tutorial if( FAILED( CreateEverything( hWnd ) ) ) return 0; // Now we're ready to recieve and process Windows messages. BOOL bGotMsg; MSG msg; PeekMessage( &msg, NULL, 0U, 0U, PM_NOREMOVE ); g_bReady = TRUE; while( WM_QUIT != msg.message ) { // Use PeekMessage() if the app is active, so we can use idle time to // render the scene. Else, use GetMessage() to avoid eating CPU time. if( g_bActive ) bGotMsg = PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ); else bGotMsg = GetMessage( &msg, NULL, 0U, 0U ); if( bGotMsg ) { // Translate and dispatch the message if( 0 == TranslateAccelerator( hWnd, hAccel, &msg ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } } else { // Render a frame during idle time (no messages are waiting) if( g_bActive && g_bReady ) Render3DEnvironment(); } } return msg.wParam; } //----------------------------------------------------------------------------- // Name: WndProc() // Desc: This is the basic Windows-programming function that processes // Windows messages. We need to handle window movement, painting, // and destruction. //----------------------------------------------------------------------------- LRESULT CALLBACK WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { switch( uMsg ) { case WM_PAINT: // If we get WM_PAINT messages, it usually means our window was // covered up, so we need to refresh it by re-showing the contents // of the current frame. ShowFrame(); break; case WM_MOVE: // Move messages need to be tracked to update the screen rects // used for blitting the backbuffer to the primary. if( g_bActive && g_bReady ) OnMove( (SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam) ); break; case WM_SIZE: // Check to see if we are losing or gaining our window. Set the // active flag to match. if( SIZE_MAXHIDE==wParam || SIZE_MINIMIZED==wParam ) g_bActive = FALSE; else g_bActive = TRUE; // A new window size will require a new backbuffer size. The // easiest way to achieve this is to release and re-create // everything. Note: if the window gets too big, we may run out // of video memory and need to exit. This simple app exits // without displaying error messages, but a real app would behave // itself much better. if( g_bActive && g_bReady ) { g_bReady = FALSE; // Cleanup the environment and recreate everything if( FAILED( CreateEverything( hWnd) ) ) DestroyWindow( hWnd ); g_bReady = TRUE; } break; case WM_GETMINMAXINFO: // Prevent the window from going smaller than some minimum size ((MINMAXINFO*)lParam)->ptMinTrackSize.x = 100; ((MINMAXINFO*)lParam)->ptMinTrackSize.y = 100; break; case WM_CLOSE: DestroyWindow( hWnd ); return 0; case WM_DESTROY: Cleanup3DEnvironment(); PostQuitMessage(0); return 0L; } return DefWindowProc( hWnd, uMsg, wParam, lParam ); } //----------------------------------------------------------------------------- // Note: From this point on, the code is DirectX specific support for the app. //----------------------------------------------------------------------------- HRESULT CreateEverything( HWND hWnd ) { // Cleanup any objects that might've been created before if( FAILED( Cleanup3DEnvironment() ) ) return E_FAIL; // Create the D3D environment, at first, trying the HAL if( SUCCEEDED( Initialize3DEnvironment( hWnd, NULL, &IID_IDirect3DHALDevice ) ) ) return S_OK; // Else, cleanup objects potentially created during the failed // initialization attempt. Cleanup3DEnvironment(); if( SUCCEEDED( Initialize3DEnvironment( hWnd, NULL, &IID_IDirect3DRGBDevice ) ) ) return S_OK; // Else, return failure. This simple tutorial will exit ungracefully. return E_FAIL; } //----------------------------------------------------------------------------- // Name: EnumZBufferCallback() // Desc: Enumeration function to report valid pixel formats for z-buffers. //----------------------------------------------------------------------------- static HRESULT WINAPI EnumZBufferCallback( DDPIXELFORMAT* pddpf, VOID* pddpfDesired ) { // For this tutorial, we are only interested in z-buffers, so ignore any // other formats (e.g. DDPF_STENCILBUFFER) that get enumerated. An app // could also check the depth of the z-buffer (16-bit, etc,) and make a // choice based on that, as well. For this tutorial, we'll take the first // one we get. if( pddpf->dwFlags == DDPF_ZBUFFER ) { memcpy( pddpfDesired, pddpf, sizeof(DDPIXELFORMAT) ); // Return with D3DENUMRET_CANCEL to end the search. return D3DENUMRET_CANCEL; } // Return with D3DENUMRET_OK to continue the search. return D3DENUMRET_OK; } //----------------------------------------------------------------------------- // Name: Initialize3DEnvironment() // Desc: This function initializes all the DirectDraw/Direct3D objects used for // 3D-rendering. This code is expanded from the Step 1 tutorial, in that // it adds a z-buffer. //----------------------------------------------------------------------------- HRESULT Initialize3DEnvironment( HWND hWnd, GUID* pDriverGUID, const GUID* pDeviceGUID ) { HRESULT hr; // Create the IDirectDraw interface. The first parameter is the GUID, // which is allowed to be NULL. If there are more than one DirectDraw // drivers on the system, a NULL guid requests the primary driver. For // non-GDI hardware cards like the 3DFX and PowerVR, the guid would need // to be explicity specified . (Note: these guids are normally obtained // from enumeration, which is convered in a subsequent tutorial.) hr = DirectDrawCreate( pDriverGUID, &g_pDD1, NULL ); if( FAILED( hr ) ) return hr; // Get a ptr to an IDirectDraw4 interface. This interface to DirectDraw // represents the DX6 version of the API. hr = g_pDD1->QueryInterface( IID_IDirectDraw4, (VOID**)&g_pDD4 ); if( FAILED( hr ) ) return hr; // Set the Windows cooperative level. This is where we tell the system // whether wew will be rendering in fullscreen mode or in a window. Note // that some hardware (non-GDI) may not be able to render into a window. // The flag DDSCL_NORMAL specifies windowed mode. Using fullscreen mode // is the topic of a subsequent tutorial. The DDSCL_FPUSETUP flag is a // hint to DirectX to optomize floating points calculations. See the docs // for more info on this. Note: this call could fail if another application // already controls a fullscreen, exclusive mode. hr = g_pDD4->SetCooperativeLevel( hWnd, DDSCL_NORMAL ); if( FAILED( hr ) ) return hr; // Initialize a surface description structure for the primary surface. The // primary surface represents the entire display, with dimensions and a // pixel format of the display. Therefore, none of that information needs // to be specified in order to create the primary surface. DDSURFACEDESC2 ddsd; ZeroMemory( &ddsd, sizeof(DDSURFACEDESC2) ); ddsd.dwSize = sizeof(DDSURFACEDESC2); ddsd.dwFlags = DDSD_CAPS; ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE; // Create the primary surface. hr = g_pDD4->CreateSurface( &ddsd, &g_pddsPrimary, NULL ); if( FAILED( hr ) ) return hr; // Setup a surface description to create a backbuffer. This is an // offscreen plain surface with dimensions equal to our window size. // The DDSCAPS_3DDEVICE is needed so we can later query this surface // for an IDirect3DDevice interface. ddsd.dwFlags = DDSD_WIDTH | DDSD_HEIGHT | DDSD_CAPS; ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_3DDEVICE; // Set the dimensions of the backbuffer. Note that if our window changes // size, we need to destroy this surface and create a new one. GetClientRect( hWnd, &g_rcScreenRect ); GetClientRect( hWnd, &g_rcViewportRect ); ClientToScreen( hWnd, (POINT*)&g_rcScreenRect.left ); ClientToScreen( hWnd, (POINT*)&g_rcScreenRect.right ); ddsd.dwWidth = g_rcScreenRect.right - g_rcScreenRect.left; ddsd.dwHeight = g_rcScreenRect.bottom - g_rcScreenRect.top; // Create the backbuffer. The most likely reason for failure is running // out of video memory. (A more sophisticated app should handle this.) hr = g_pDD4->CreateSurface( &ddsd, &g_pddsBackBuffer, NULL ); if( FAILED( hr ) ) return hr; // Note: if using a z-buffer, the zbuffer surface creation would go around // here. However, z-buffer usage is the topic of a subsequent tutorial. // Create a clipper object which handles all our clipping for cases when // our window is partially obscured by other windows. This is not needed // for apps running in fullscreen mode. LPDIRECTDRAWCLIPPER pcClipper; hr = g_pDD4->CreateClipper( 0, &pcClipper, NULL ); if( FAILED( hr ) ) return hr; // Associate the clipper with our window. Note that, afterwards, the // clipper is internally referenced by the primary surface, so it is safe // to release our local reference to it. pcClipper->SetHWnd( 0, hWnd ); g_pddsPrimary->SetClipper( pcClipper ); pcClipper->Release(); // Query DirectDraw for access to Direct3D g_pDD4->QueryInterface( IID_IDirect3D3, (VOID**)&g_pD3D ); if( FAILED( hr) ) return hr; //------------------------------------------------------------------------- // Create the z-buffer AFTER creating the backbuffer and BEFORE creating // the d3ddevice. // // Note: before creating the z-buffer, apps may want to check the device // caps for the D3DPRASTERCAPS_ZBUFFERLESSHSR flag. This flag is true for // certain hardware that can do HSR (hidden-surface-removal) without a // z-buffer. For those devices, there is no need to create a z-buffer. //------------------------------------------------------------------------- DDPIXELFORMAT ddpfZBuffer; g_pD3D->EnumZBufferFormats( *pDeviceGUID, EnumZBufferCallback, (VOID*)&ddpfZBuffer ); // If we found a good zbuffer format, then the dwSize field will be // properly set during enumeration. Else, we have a problem and will exit. if( sizeof(DDPIXELFORMAT) != ddpfZBuffer.dwSize ) return E_FAIL; // Get z-buffer dimensions from the render target // Setup the surface desc for the z-buffer. ddsd.dwFlags = DDSD_CAPS|DDSD_WIDTH|DDSD_HEIGHT|DDSD_PIXELFORMAT; ddsd.ddsCaps.dwCaps = DDSCAPS_ZBUFFER; ddsd.dwWidth = g_rcScreenRect.right - g_rcScreenRect.left; ddsd.dwHeight = g_rcScreenRect.bottom - g_rcScreenRect.top; memcpy( &ddsd.ddpfPixelFormat, &ddpfZBuffer, sizeof(DDPIXELFORMAT) ); // For hardware devices, the z-buffer should be in video memory. For // software devices, create the z-buffer in system memory if( IsEqualIID( *pDeviceGUID, IID_IDirect3DHALDevice ) ) ddsd.ddsCaps.dwCaps |= DDSCAPS_VIDEOMEMORY; else ddsd.ddsCaps.dwCaps |= DDSCAPS_SYSTEMMEMORY; // Create and attach a z-buffer. Real apps should be able to handle an // error here (DDERR_OUTOFVIDEOMEMORY may be encountered). For this // tutorial, though, we are simply going to exit ungracefully. if( FAILED( hr = g_pDD4->CreateSurface( &ddsd, &g_pddsZBuffer, NULL ) ) ) return hr; // Attach the z-buffer to the back buffer. if( FAILED( hr = g_pddsBackBuffer->AddAttachedSurface( g_pddsZBuffer ) ) ) return hr; //------------------------------------------------------------------------- // End of z-buffer creation code. // // Before rendering, don't forget to enable the z-buffer with the // appropiate D3DRENDERSTATE's. //------------------------------------------------------------------------- // Before creating the device, check that we are NOT in a palettized // display. That case will cause CreateDevice() to fail, since this simple // tutorial does not bother with palettes. ddsd.dwSize = sizeof(DDSURFACEDESC2); g_pDD4->GetDisplayMode( &ddsd ); if( ddsd.ddpfPixelFormat.dwRGBBitCount <= 8 ) return DDERR_INVALIDMODE; // Create the device. The device is created off of our back buffer, which // becomes the render target for the newly created device. Note that the // z-buffer must be created BEFORE the device if( FAILED( hr = g_pD3D->CreateDevice( *pDeviceGUID, g_pddsBackBuffer, &g_pd3dDevice, NULL ) ) ) { // This call could fail for many reasons. The most likely cause is // that we specifically requested a hardware device, without knowing // whether there is even a 3D card installed in the system. Another // possibility is the hardware is incompatible with the current display // mode (the correct implementation would use enumeration for this.) return hr; } // Set up the viewport data parameters D3DVIEWPORT2 vdData; ZeroMemory( &vdData, sizeof(D3DVIEWPORT2) ); vdData.dwSize = sizeof(D3DVIEWPORT2); vdData.dwWidth = g_rcScreenRect.right - g_rcScreenRect.left; vdData.dwHeight = g_rcScreenRect.bottom - g_rcScreenRect.top; vdData.dvClipX = -1.0f; vdData.dvClipWidth = 2.0f; vdData.dvClipY = 1.0f; vdData.dvClipHeight = 2.0f; vdData.dvMaxZ = 1.0f; // Create the viewport hr = g_pD3D->CreateViewport( &g_pvViewport, NULL ); if( FAILED( hr ) ) return hr; // Associate the viewport with the D3DDEVICE object g_pd3dDevice->AddViewport( g_pvViewport ); // Set the parameters to the new viewport g_pvViewport->SetViewport2( &vdData ); // Set the viewport as current for the device g_pd3dDevice->SetCurrentViewport( g_pvViewport ); // Finish by setting up our scene return App_InitDeviceObjects( g_pd3dDevice, g_pvViewport ); } //----------------------------------------------------------------------------- // Name: Cleanup3DEnvironment() // Desc: Releases all the resources used by the app. Note the check for // reference counts when releasing the D3DDevice and DDraw objects. If // these ref counts are non-zero, then something was not cleaned up // correctly. //----------------------------------------------------------------------------- HRESULT Cleanup3DEnvironment() { // Cleanup any objects created for the scene App_DeleteDeviceObjects( g_pd3dDevice, g_pvViewport ); // Release the DDraw and D3D objects used by the app if( g_pvViewport ) g_pvViewport->Release(); if( g_pddsZBuffer ) g_pddsZBuffer->Release(); if( g_pD3D ) g_pD3D->Release(); if( g_pddsBackBuffer ) g_pddsBackBuffer->Release(); if( g_pddsPrimary ) g_pddsPrimary->Release(); if( g_pDD4 ) g_pDD4->Release(); // Do a safe check for releasing the D3DDEVICE. RefCount should be zero. if( g_pd3dDevice ) if( 0 < g_pd3dDevice->Release() ) return E_FAIL; // Do a safe check for releasing DDRAW. RefCount should be zero. if( g_pDD1 ) if( 0 < g_pDD1->Release() ) return E_FAIL; g_pvViewport = NULL; g_pddsZBuffer = NULL; g_pd3dDevice = NULL; g_pD3D = NULL; g_pddsBackBuffer = NULL; g_pddsPrimary = NULL; g_pDD4 = NULL; g_pDD1 = NULL; return S_OK; } //----------------------------------------------------------------------------- // Name: Render3DEnvironment() // Desc: Draws the scene. There are three steps here: // (1) Animate the scene // (2) Render the scene // (3) Show the frame (copy backbuffer contents to the primary). //----------------------------------------------------------------------------- HRESULT Render3DEnvironment() { // Call the app specific function to framemove (animate) the scene App_FrameMove( g_pd3dDevice, ((FLOAT)clock())/CLOCKS_PER_SEC ); // Call the app specific function to render the scene App_Render( g_pd3dDevice, g_pvViewport, (D3DRECT*)&g_rcViewportRect ); // Show the frame on the primary surface. Note: this is the best place to // check for "lost" surfaces. Surfaces can be lost if something caused // them to temporary lose their video memory. "Lost" surfaces simply // need to be restored before continuing. if( DDERR_SURFACELOST == ShowFrame() ) RestoreSurfaces(); return S_OK; } //----------------------------------------------------------------------------- // Name: ShowFrame() // Desc: Show the frame on the primary surface //----------------------------------------------------------------------------- HRESULT ShowFrame() { if( NULL == g_pddsPrimary ) return E_FAIL; // We are in windowed mode, so perform a blit from the backbuffer to the // correct position on the primary surface return g_pddsPrimary->Blt( &g_rcScreenRect, g_pddsBackBuffer, &g_rcViewportRect, DDBLT_WAIT, NULL ); } //----------------------------------------------------------------------------- // Name: RestoreSurfaces() // Desc: Checks for lost surfaces and restores them if lost. //----------------------------------------------------------------------------- HRESULT RestoreSurfaces() { // Check/restore the primary surface if( g_pddsPrimary ) if( g_pddsPrimary->IsLost() ) g_pddsPrimary->Restore(); // Check/restore the back buffer if( g_pddsBackBuffer ) if( g_pddsBackBuffer->IsLost() ) g_pddsBackBuffer->Restore(); // Check/restore the z-buffer if( g_pddsZBuffer ) if( g_pddsZBuffer->IsLost() ) g_pddsZBuffer->Restore(); return S_OK; } //----------------------------------------------------------------------------- // Name: OnMove() // Desc: Moves the screen rect for windowed renderers //----------------------------------------------------------------------------- VOID OnMove( INT x, INT y ) { DWORD dwWidth = g_rcScreenRect.right - g_rcScreenRect.left; DWORD dwHeight = g_rcScreenRect.bottom - g_rcScreenRect.top; SetRect( &g_rcScreenRect, x, y, x + dwWidth, y + dwHeight ); } //----------------------------------------------------------------------------- // File: Z-buffer.cpp // // Desc: Simple tutorial code to show how to enable z-buffering. The z-buffer // itself is created in the winmain.cpp file. This file controls // rendering and the setting of renderstates (some of which affect // z-buffering). // // Copyright (c) 1998 Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #define STRICT #define D3D_OVERLOADS #include <math.h> #include <d3d.h> //----------------------------------------------------------------------------- // Defines, constants, and global variables //----------------------------------------------------------------------------- #define NUM_OBJECTS 4 D3DMATRIX g_matLocal[NUM_OBJECTS]; LPDIRECT3DMATERIAL3 g_pmtrlObjectMtrl = NULL; D3DVERTEX g_pvTriangleVertices[6]; //----------------------------------------------------------------------------- // Name: App_InitDeviceObjects() // Desc: Initialize scene objects. This function is called after all the // DirectDraw and Direct3D objects have been initialized. It makes sense // to structure code this way, separating the DDraw/D3D initialization // code from the app-specific intialization code. //----------------------------------------------------------------------------- HRESULT App_InitDeviceObjects( LPDIRECT3DDEVICE3 pd3dDevice, LPDIRECT3DVIEWPORT3 pvViewport ) { // Data for the geometry of the triangle. Note that this tutorial only // uses ambient lighting, so the vertices' normals are not actually used. D3DVECTOR p1( 0.0f, 3.0f, 0.0f ); D3DVECTOR p2( 3.0f,-3.0f, 0.0f ); D3DVECTOR p3(-3.0f,-3.0f, 0.0f ); D3DVECTOR vNormal( 0.0f, 0.0f, 1.0f ); // Initialize the 3 vertices for the front of the triangle g_pvTriangleVertices[0] = D3DVERTEX( p1, vNormal, 0.0f, 0.0f ); g_pvTriangleVertices[1] = D3DVERTEX( p2, vNormal, 0.0f, 0.0f ); g_pvTriangleVertices[2] = D3DVERTEX( p3, vNormal, 0.0f, 0.0f ); // Initialize the 3 vertices for the back of the triangle g_pvTriangleVertices[3] = D3DVERTEX( p1, -vNormal, 0.0f, 0.0f ); g_pvTriangleVertices[4] = D3DVERTEX( p3, -vNormal, 0.0f, 0.0f ); g_pvTriangleVertices[5] = D3DVERTEX( p2, -vNormal, 0.0f, 0.0f ); // Get a ptr to the ID3D object to create materials and/or lights. Note: // the Release() call just serves to decrease the ref count. LPDIRECT3D3 pD3D; if( FAILED( pd3dDevice->GetDirect3D( &pD3D ) ) ) return E_FAIL; pD3D->Release(); // Create the object material. This material will be used to draw the // triangle. Note: that when we use textures, the object material is // usually omitted or left as white. if( FAILED( pD3D->CreateMaterial( &g_pmtrlObjectMtrl, NULL ) ) ) return E_FAIL; // Set the object material as yellow. We're setting the ambient color here // since this tutorial only uses ambient lighting. For apps that use real // lights, the diffuse and specular values should be set. (In addition, the // polygons' vertices need normals for true lighting.) D3DMATERIAL mtrl; D3DMATERIALHANDLE hmtrl; ZeroMemory( &mtrl, sizeof(D3DMATERIAL) ); mtrl.dwSize = sizeof(D3DMATERIAL); mtrl.dcvAmbient.r = 1.0f; mtrl.dcvAmbient.g = 1.0f; mtrl.dcvAmbient.b = 1.0f; g_pmtrlObjectMtrl->SetMaterial( &mtrl ); // Put the object material into effect. Direct3D is a state machine, and // calls like this set the current state. After this call, any polygons // rendered will be drawn using this material. g_pmtrlObjectMtrl->GetHandle( pd3dDevice, &hmtrl ); pd3dDevice->SetLightState( D3DLIGHTSTATE_MATERIAL, hmtrl ); // The ambient lighting value is another state to set. Here, we are turning // ambient lighting on to full white. pd3dDevice->SetLightState( D3DLIGHTSTATE_AMBIENT, 0xffffffff ); // Set the transform matrices. Direct3D uses three independant matrices: // the world matrix, the view matrix, and the projection matrix. For // convienence, we are first setting up an identity matrix. D3DMATRIX mat; mat._11 = mat._22 = mat._33 = mat._44 = 1.0f; mat._12 = mat._13 = mat._14 = mat._41 = 0.0f; mat._21 = mat._23 = mat._24 = mat._42 = 0.0f; mat._31 = mat._32 = mat._34 = mat._43 = 0.0f; // The world matrix controls the position and orientation of the polygons // in world space. We'll use it later to spin the triangle. D3DMATRIX matWorld = mat; pd3dDevice->SetTransform( D3DTRANSFORMSTATE_WORLD, &matWorld ); // The view matrix defines the position and orientation of the camera. // Here, we are just moving it back along the z-axis by 10 units. D3DMATRIX matView = mat; matView._43 = 10.0f; pd3dDevice->SetTransform( D3DTRANSFORMSTATE_VIEW, &matView ); // The projection matrix defines how the 3D scene is "projected" onto the // 2D render target (the backbuffer surface). Refer to the docs for more // info about projection matrices. D3DMATRIX matProj = mat; matProj._11 = 2.0f; matProj._22 = 2.0f; matProj._34 = 1.0f; matProj._43 = -1.0f; matProj._44 = 0.0f; pd3dDevice->SetTransform( D3DTRANSFORMSTATE_PROJECTION, &matProj ); return S_OK; } //----------------------------------------------------------------------------- // Name: App_FrameMove() // Desc: Called once per frame, the call is used for animating the scene. The // device is used for changing various render states, and the timekey is // used for timing of the dynamics of the scene. //----------------------------------------------------------------------------- HRESULT App_FrameMove( LPDIRECT3DDEVICE3 pd3dDevice, FLOAT fTimeKey ) { // For this tutorial, we are rotating several triangles about the y-axis. // (Note: the triangles are meant to intersect, to show how z-buffering // handles hidden-surface removal.) // For each object, set up a local rotation matrix to be applied right // before rendering the object's polygons. for( int i=0; i<NUM_OBJECTS; i++ ) { ZeroMemory( &g_matLocal[i], sizeof(D3DMATRIX) ); g_matLocal[i]._11 = (FLOAT)cos( fTimeKey + (3.14159*i)/NUM_OBJECTS ); g_matLocal[i]._33 = (FLOAT)cos( fTimeKey + (3.14159*i)/NUM_OBJECTS ); g_matLocal[i]._13 = (FLOAT)sin( fTimeKey + (3.14159*i)/NUM_OBJECTS ); g_matLocal[i]._31 = (FLOAT)sin( fTimeKey + (3.14159*i)/NUM_OBJECTS ); g_matLocal[i]._22 = g_matLocal[i]._44 = 1.0f; } return S_OK; } //----------------------------------------------------------------------------- // Name: App_Render() // Desc: Renders the scene. This tutorial draws a bunch of intersecting // triangles that are rotating about the y-axis. Without z-buffering, // the polygons could not be drawn correctly (unless the app performed // complex polygon-division routines and sorted the polygons in back-to- // front order.) //----------------------------------------------------------------------------- HRESULT App_Render( LPDIRECT3DDEVICE3 pd3dDevice, LPDIRECT3DVIEWPORT3 pvViewport, D3DRECT* prcViewportRect ) { // Clear the viewport to a blue color. Also "clear" the z-buffer to the // value 1.0 (which represents the far clipping plane). pvViewport->Clear2( 1UL, prcViewportRect, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, 0x000000ff, 1.0f, 0L ); // Begin the scene if( FAILED( pd3dDevice->BeginScene() ) ) return E_FAIL; // Enable z-buffering. (Note: we don't really need to do this every frame.) pd3dDevice->SetRenderState( D3DRENDERSTATE_ZENABLE, TRUE ); // Draw all the objects. Note: you can tweak the above statement to disable // the z-buffer, and compare the difference in output. With z-buffering, // the inter-penetrating triangles are drawn correctly. for( int i=0; i<NUM_OBJECTS; i++ ) { // Alternate the color of every other object DWORD dwColor = ( i%2 ) ? 0x0000ff00 : 0x00ffff00; pd3dDevice->SetLightState( D3DLIGHTSTATE_AMBIENT, dwColor ); // Set the local matrix for the object pd3dDevice->SetTransform( D3DTRANSFORMSTATE_WORLD, &g_matLocal[i] ); // Draw the object. (Note: Subsequent tutorials will go into more // detail on the various calls for drawing polygons.) pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, D3DFVF_VERTEX, g_pvTriangleVertices, 6, NULL ); } // End the scene. pd3dDevice->EndScene(); return S_OK; } //----------------------------------------------------------------------------- // Name: App_DeleteDeviceObjects() // Desc: Called when the device is being deleted, this function deletes any // device dependant objects. //----------------------------------------------------------------------------- VOID App_DeleteDeviceObjects( LPDIRECT3DDEVICE3 pd3dDevice, LPDIRECT3DVIEWPORT3 pvViewport ) { // Release the material that was created earlier. if( g_pmtrlObjectMtrl ) g_pmtrlObjectMtrl->Release(); g_pmtrlObjectMtrl = NULL; } */
[ "67659553+KrazeeTobi@users.noreply.github.com" ]
67659553+KrazeeTobi@users.noreply.github.com
f37c204e3bc80e077d7f36ad3f09e21bfe77bdef
730b9b15a4d70a76f5cef101c9cc0f8fc5265008
/source/common/clip_map/bsp46/patch.cpp
555c6a688278585d075b4c32a0b4a35dd1a82a17
[]
no_license
msfwaifu/jlquake
23e7350a122aa91cae84c21f4f01f9628a5dbf7c
69498ea1ea09482b096f06ab7b433e715b7802a8
refs/heads/master
2021-01-23T06:35:48.219738
2014-05-10T22:49:20
2014-05-10T22:49:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
49,737
cpp
//************************************************************************** //** //** See jlquake.txt for copyright info. //** //** This program is free software; you can redistribute it and/or //** modify it under the terms of the GNU General Public License //** as published by the Free Software Foundation; either version 3 //** of the License, or (at your option) any later version. //** //** This program is distributed in the hope that it will be useful, //** but WITHOUT ANY WARRANTY; without even the implied warranty of //** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //** included (gnu.txt) GNU General Public License for more details. //** //************************************************************************** /* Issues for collision against curved surfaces: Surface edges need to be handled differently than surface planes Plane expansion causes raw surfaces to expand past expanded bounding box Position test of a volume against a surface is tricky. Position test of a point against a surface is not well defined, because the surface has no volume. Tracing leading edge points instead of volumes? Position test by tracing corner to corner? (8*7 traces -- ouch) coplanar edges triangulated patches degenerate patches endcaps degenerate WARNING: this may misbehave with meshes that have rows or columns that only degenerate a few triangles. Completely degenerate rows and columns are handled properly. */ // HEADER FILES ------------------------------------------------------------ #include "../../Common.h" #include "../../common_defs.h" #include "../../console_variable.h" #include "local.h" // MACROS ------------------------------------------------------------------ #define SUBDIVIDE_DISTANCE 16 //4 // never more than this units away from curve #define WRAP_POINT_EPSILON 0.1 #define POINT_EPSILON 0.1 #define NORMAL_EPSILON 0.0001 #define DIST_EPSILON 0.02 // TYPES ------------------------------------------------------------------- // EXTERNAL FUNCTION PROTOTYPES -------------------------------------------- // PUBLIC FUNCTION PROTOTYPES ---------------------------------------------- // PRIVATE FUNCTION PROTOTYPES --------------------------------------------- // EXTERNAL DATA DECLARATIONS ---------------------------------------------- // PUBLIC DATA DEFINITIONS ------------------------------------------------- // PRIVATE DATA DEFINITIONS ------------------------------------------------ static int cm_patch_numFacets; static facet_t cm_patch_facets[ MAX_PATCH_PLANES ]; //maybe MAX_FACETS ?? static int cm_patch_numPlanes; static patchPlane_t cm_patch_planes[ MAX_PATCH_PLANES ]; static bool debugBlock; static const patchCollide_t* debugPatchCollide; static const facet_t* debugFacet; static vec3_t debugBlockPoints[ 4 ]; // CODE -------------------------------------------------------------------- //========================================================================== // // QClipMap46::ClearLevelPatches // //========================================================================== void QClipMap46::ClearLevelPatches() { debugPatchCollide = NULL; debugFacet = NULL; } /* ================================================================================ GRID SUBDIVISION ================================================================================ */ //========================================================================== // // cGrid_t::SetWrapWidth // // If the left and right columns are exactly equal, set grid->wrapWidth true // //========================================================================== void cGrid_t::SetWrapWidth() { int i; for ( i = 0; i < height; i++ ) { int j; for ( j = 0; j < 3; j++ ) { float d = points[ 0 ][ i ][ j ] - points[ width - 1 ][ i ][ j ]; if ( d < -WRAP_POINT_EPSILON || d > WRAP_POINT_EPSILON ) { break; } } if ( j != 3 ) { break; } } if ( i == height ) { wrapWidth = true; } else { wrapWidth = false; } } //========================================================================== // // cGrid_t::SubdivideColumns // // Adds columns as necessary to the grid until all the aproximating points // are within SUBDIVIDE_DISTANCE from the true curve // //========================================================================== void cGrid_t::SubdivideColumns() { for ( int i = 0; i < width - 2; ) { // grid->points[i][x] is an interpolating control point // grid->points[i+1][x] is an aproximating control point // grid->points[i+2][x] is an interpolating control point // // first see if we can collapse the aproximating collumn away // int j; for ( j = 0; j < height; j++ ) { if ( NeedsSubdivision( points[ i ][ j ], points[ i + 1 ][ j ], points[ i + 2 ][ j ] ) ) { break; } } if ( j == height ) { // all of the points were close enough to the linear midpoints // that we can collapse the entire column away for ( j = 0; j < height; j++ ) { // remove the column for ( int k = i + 2; k < width; k++ ) { VectorCopy( points[ k ][ j ], points[ k - 1 ][ j ] ); } } width--; // go to the next curve segment i++; continue; } // // we need to subdivide the curve // for ( j = 0; j < height; j++ ) { vec3_t prev, mid, next; // save the control points now VectorCopy( points[ i ][ j ], prev ); VectorCopy( points[ i + 1 ][ j ], mid ); VectorCopy( points[ i + 2 ][ j ], next ); // make room for two additional columns in the grid // columns i+1 will be replaced, column i+2 will become i+4 // i+1, i+2, and i+3 will be generated for ( int k = width - 1; k > i + 1; k-- ) { VectorCopy( points[ k ][ j ], points[ k + 2 ][ j ] ); } // generate the subdivided points Subdivide( prev, mid, next, points[ i + 1 ][ j ], points[ i + 2 ][ j ], points[ i + 3 ][ j ] ); } width += 2; // the new aproximating point at i+1 may need to be removed // or subdivided farther, so don't advance i } } //========================================================================== // // cGrid_t::NeedsSubdivision // // Returns true if the given quadratic curve is not flat enough for our // collision detection purposes // //========================================================================== bool cGrid_t::NeedsSubdivision( vec3_t a, vec3_t b, vec3_t c ) { vec3_t cmid; vec3_t lmid; vec3_t delta; // calculate the linear midpoint for ( int i = 0; i < 3; i++ ) { lmid[ i ] = 0.5 * ( a[ i ] + c[ i ] ); } // calculate the exact curve midpoint for ( int i = 0; i < 3; i++ ) { cmid[ i ] = 0.5 * ( 0.5 * ( a[ i ] + b[ i ] ) + 0.5 * ( b[ i ] + c[ i ] ) ); } // see if the curve is far enough away from the linear mid VectorSubtract( cmid, lmid, delta ); float dist = VectorLength( delta ); return dist >= SUBDIVIDE_DISTANCE; } //========================================================================== // // cGrid_t::Subdivide // // a, b, and c are control points. // the subdivided sequence will be: a, out1, out2, out3, c // //========================================================================== void cGrid_t::Subdivide( vec3_t a, vec3_t b, vec3_t c, vec3_t out1, vec3_t out2, vec3_t out3 ) { for ( int i = 0; i < 3; i++ ) { out1[ i ] = 0.5 * ( a[ i ] + b[ i ] ); out3[ i ] = 0.5 * ( b[ i ] + c[ i ] ); out2[ i ] = 0.5 * ( out1[ i ] + out3[ i ] ); } } //========================================================================== // // cGrid_t::RemoveDegenerateColumns // // If there are any identical columns, remove them // //========================================================================== void cGrid_t::RemoveDegenerateColumns() { for ( int i = 0; i < width - 1; i++ ) { int j; for ( j = 0; j < height; j++ ) { if ( !ComparePoints( points[ i ][ j ], points[ i + 1 ][ j ] ) ) { break; } } if ( j != height ) { continue; // not degenerate } for ( j = 0; j < height; j++ ) { // remove the column for ( int k = i + 2; k < width; k++ ) { VectorCopy( points[ k ][ j ], points[ k - 1 ][ j ] ); } } width--; // check against the next column i--; } } //========================================================================== // // cGrid_t::ComparePoints // //========================================================================== bool cGrid_t::ComparePoints( const float* a, const float* b ) { float d = a[ 0 ] - b[ 0 ]; if ( d < -POINT_EPSILON || d > POINT_EPSILON ) { return false; } d = a[ 1 ] - b[ 1 ]; if ( d < -POINT_EPSILON || d > POINT_EPSILON ) { return false; } d = a[ 2 ] - b[ 2 ]; if ( d < -POINT_EPSILON || d > POINT_EPSILON ) { return false; } return true; } //========================================================================== // // cGrid_t::Transpose // // Swaps the rows and columns in place // //========================================================================== void cGrid_t::Transpose() { if ( width > height ) { for ( int i = 0; i < height; i++ ) { for ( int j = i + 1; j < width; j++ ) { if ( j < height ) { // swap the value vec3_t temp; VectorCopy( points[ i ][ j ], temp ); VectorCopy( points[ j ][ i ], points[ i ][ j ] ); VectorCopy( temp, points[ j ][ i ] ); } else { // just copy VectorCopy( points[ j ][ i ], points[ i ][ j ] ); } } } } else { for ( int i = 0; i < width; i++ ) { for ( int j = i + 1; j < height; j++ ) { if ( j < width ) { // swap the value vec3_t temp; VectorCopy( points[ j ][ i ], temp ); VectorCopy( points[ i ][ j ], points[ j ][ i ] ); VectorCopy( temp, points[ i ][ j ] ); } else { // just copy VectorCopy( points[ i ][ j ], points[ j ][ i ] ); } } } } int l = width; width = height; height = l; bool tempWrap = wrapWidth; wrapWidth = wrapHeight; wrapHeight = tempWrap; } /* ================================================================================ PATCH COLLIDE GENERATION ================================================================================ */ //========================================================================== // // QClipMap46::GeneratePatchCollide // // Creates an internal structure that will be used to perform // collision detection with a patch mesh. // // Points is packed as concatenated rows. // //========================================================================== patchCollide_t* QClipMap46::GeneratePatchCollide( int width, int height, vec3_t* points ) { if ( width <= 2 || height <= 2 || !points ) { common->Error( "CM_GeneratePatchFacets: bad parameters: (%i, %i, %p)", width, height, points ); } if ( !( width & 1 ) || !( height & 1 ) ) { common->Error( "CM_GeneratePatchFacets: even sizes are invalid for quadratic meshes" ); } if ( width > MAX_GRID_SIZE || height > MAX_GRID_SIZE ) { common->Error( "CM_GeneratePatchFacets: source is > MAX_GRID_SIZE" ); } // build a grid cGrid_t grid; grid.width = width; grid.height = height; grid.wrapWidth = false; grid.wrapHeight = false; for ( int i = 0; i < width; i++ ) { for ( int j = 0; j < height; j++ ) { VectorCopy( points[ j * width + i ], grid.points[ i ][ j ] ); } } // subdivide the grid grid.SetWrapWidth(); grid.SubdivideColumns(); grid.RemoveDegenerateColumns(); grid.Transpose(); grid.SetWrapWidth(); grid.SubdivideColumns(); grid.RemoveDegenerateColumns(); // we now have a grid of points exactly on the curve // the aproximate surface defined by these points will be // collided against patchCollide_t* pf = new patchCollide_t; Com_Memset( pf, 0, sizeof ( *pf ) ); ClearBounds( pf->bounds[ 0 ], pf->bounds[ 1 ] ); for ( int i = 0; i < grid.width; i++ ) { for ( int j = 0; j < grid.height; j++ ) { AddPointToBounds( grid.points[ i ][ j ], pf->bounds[ 0 ], pf->bounds[ 1 ] ); } } // generate a bsp tree for the surface pf->FromGrid( &grid ); // expand by one unit for epsilon purposes pf->bounds[ 0 ][ 0 ] -= 1; pf->bounds[ 0 ][ 1 ] -= 1; pf->bounds[ 0 ][ 2 ] -= 1; pf->bounds[ 1 ][ 0 ] += 1; pf->bounds[ 1 ][ 1 ] += 1; pf->bounds[ 1 ][ 2 ] += 1; return pf; } //========================================================================== // // patchCollide_t::FromGrid // //========================================================================== void patchCollide_t::FromGrid( cGrid_t* grid ) { enum edgeName_t { EN_TOP, EN_RIGHT, EN_BOTTOM, EN_LEFT }; cm_patch_numPlanes = 0; cm_patch_numFacets = 0; // find the planes for each triangle of the grid int gridPlanes[ MAX_GRID_SIZE ][ MAX_GRID_SIZE ][ 2 ]; for ( int i = 0; i < grid->width - 1; i++ ) { for ( int j = 0; j < grid->height - 1; j++ ) { float* p1 = grid->points[ i ][ j ]; float* p2 = grid->points[ i + 1 ][ j ]; float* p3 = grid->points[ i + 1 ][ j + 1 ]; gridPlanes[ i ][ j ][ 0 ] = FindPlane( p1, p2, p3 ); p1 = grid->points[ i + 1 ][ j + 1 ]; p2 = grid->points[ i ][ j + 1 ]; p3 = grid->points[ i ][ j ]; gridPlanes[ i ][ j ][ 1 ] = FindPlane( p1, p2, p3 ); } } // create the borders for each facet for ( int i = 0; i < grid->width - 1; i++ ) { for ( int j = 0; j < grid->height - 1; j++ ) { int borders[ 4 ]; int noAdjust[ 4 ]; borders[ EN_TOP ] = -1; if ( j > 0 ) { borders[ EN_TOP ] = gridPlanes[ i ][ j - 1 ][ 1 ]; } else if ( grid->wrapHeight ) { borders[ EN_TOP ] = gridPlanes[ i ][ grid->height - 2 ][ 1 ]; } noAdjust[ EN_TOP ] = ( borders[ EN_TOP ] == gridPlanes[ i ][ j ][ 0 ] ); if ( borders[ EN_TOP ] == -1 || noAdjust[ EN_TOP ] ) { borders[ EN_TOP ] = EdgePlaneNum( grid, gridPlanes, i, j, 0 ); } borders[ EN_BOTTOM ] = -1; if ( j < grid->height - 2 ) { borders[ EN_BOTTOM ] = gridPlanes[ i ][ j + 1 ][ 0 ]; } else if ( grid->wrapHeight ) { borders[ EN_BOTTOM ] = gridPlanes[ i ][ 0 ][ 0 ]; } noAdjust[ EN_BOTTOM ] = ( borders[ EN_BOTTOM ] == gridPlanes[ i ][ j ][ 1 ] ); if ( borders[ EN_BOTTOM ] == -1 || noAdjust[ EN_BOTTOM ] ) { borders[ EN_BOTTOM ] = EdgePlaneNum( grid, gridPlanes, i, j, 2 ); } borders[ EN_LEFT ] = -1; if ( i > 0 ) { borders[ EN_LEFT ] = gridPlanes[ i - 1 ][ j ][ 0 ]; } else if ( grid->wrapWidth ) { borders[ EN_LEFT ] = gridPlanes[ grid->width - 2 ][ j ][ 0 ]; } noAdjust[ EN_LEFT ] = ( borders[ EN_LEFT ] == gridPlanes[ i ][ j ][ 1 ] ); if ( borders[ EN_LEFT ] == -1 || noAdjust[ EN_LEFT ] ) { borders[ EN_LEFT ] = EdgePlaneNum( grid, gridPlanes, i, j, 3 ); } borders[ EN_RIGHT ] = -1; if ( i < grid->width - 2 ) { borders[ EN_RIGHT ] = gridPlanes[ i + 1 ][ j ][ 1 ]; } else if ( grid->wrapWidth ) { borders[ EN_RIGHT ] = gridPlanes[ 0 ][ j ][ 1 ]; } noAdjust[ EN_RIGHT ] = ( borders[ EN_RIGHT ] == gridPlanes[ i ][ j ][ 0 ] ); if ( borders[ EN_RIGHT ] == -1 || noAdjust[ EN_RIGHT ] ) { borders[ EN_RIGHT ] = EdgePlaneNum( grid, gridPlanes, i, j, 1 ); } if ( cm_patch_numFacets == MAX_FACETS ) { common->Error( "MAX_FACETS" ); } facet_t* facet = &cm_patch_facets[ cm_patch_numFacets ]; Com_Memset( facet, 0, sizeof ( *facet ) ); if ( gridPlanes[ i ][ j ][ 0 ] == gridPlanes[ i ][ j ][ 1 ] ) { if ( gridPlanes[ i ][ j ][ 0 ] == -1 ) { continue; // degenrate } facet->surfacePlane = gridPlanes[ i ][ j ][ 0 ]; facet->numBorders = 4; facet->borderPlanes[ 0 ] = borders[ EN_TOP ]; facet->borderNoAdjust[ 0 ] = noAdjust[ EN_TOP ]; facet->borderPlanes[ 1 ] = borders[ EN_RIGHT ]; facet->borderNoAdjust[ 1 ] = noAdjust[ EN_RIGHT ]; facet->borderPlanes[ 2 ] = borders[ EN_BOTTOM ]; facet->borderNoAdjust[ 2 ] = noAdjust[ EN_BOTTOM ]; facet->borderPlanes[ 3 ] = borders[ EN_LEFT ]; facet->borderNoAdjust[ 3 ] = noAdjust[ EN_LEFT ]; SetBorderInward( facet, grid, gridPlanes, i, j, -1 ); if ( ValidateFacet( facet ) ) { AddFacetBevels( facet ); cm_patch_numFacets++; } } else { // two seperate triangles facet->surfacePlane = gridPlanes[ i ][ j ][ 0 ]; facet->numBorders = 3; facet->borderPlanes[ 0 ] = borders[ EN_TOP ]; facet->borderNoAdjust[ 0 ] = noAdjust[ EN_TOP ]; facet->borderPlanes[ 1 ] = borders[ EN_RIGHT ]; facet->borderNoAdjust[ 1 ] = noAdjust[ EN_RIGHT ]; facet->borderPlanes[ 2 ] = gridPlanes[ i ][ j ][ 1 ]; if ( facet->borderPlanes[ 2 ] == -1 ) { facet->borderPlanes[ 2 ] = borders[ EN_BOTTOM ]; if ( facet->borderPlanes[ 2 ] == -1 ) { facet->borderPlanes[ 2 ] = EdgePlaneNum( grid, gridPlanes, i, j, 4 ); } } SetBorderInward( facet, grid, gridPlanes, i, j, 0 ); if ( ValidateFacet( facet ) ) { AddFacetBevels( facet ); cm_patch_numFacets++; } if ( cm_patch_numFacets == MAX_FACETS ) { common->Error( "MAX_FACETS" ); } facet = &cm_patch_facets[ cm_patch_numFacets ]; Com_Memset( facet, 0, sizeof ( *facet ) ); facet->surfacePlane = gridPlanes[ i ][ j ][ 1 ]; facet->numBorders = 3; facet->borderPlanes[ 0 ] = borders[ EN_BOTTOM ]; facet->borderNoAdjust[ 0 ] = noAdjust[ EN_BOTTOM ]; facet->borderPlanes[ 1 ] = borders[ EN_LEFT ]; facet->borderNoAdjust[ 1 ] = noAdjust[ EN_LEFT ]; facet->borderPlanes[ 2 ] = gridPlanes[ i ][ j ][ 0 ]; if ( facet->borderPlanes[ 2 ] == -1 ) { facet->borderPlanes[ 2 ] = borders[ EN_TOP ]; if ( facet->borderPlanes[ 2 ] == -1 ) { facet->borderPlanes[ 2 ] = EdgePlaneNum( grid, gridPlanes, i, j, 5 ); } } SetBorderInward( facet, grid, gridPlanes, i, j, 1 ); if ( ValidateFacet( facet ) ) { AddFacetBevels( facet ); cm_patch_numFacets++; } } } } // copy the results out this->numPlanes = cm_patch_numPlanes; this->numFacets = cm_patch_numFacets; this->facets = new facet_t[ cm_patch_numFacets ]; Com_Memcpy( this->facets, cm_patch_facets, cm_patch_numFacets * sizeof ( *this->facets ) ); this->planes = new patchPlane_t[ cm_patch_numPlanes ]; Com_Memcpy( this->planes, cm_patch_planes, cm_patch_numPlanes * sizeof ( *this->planes ) ); } //========================================================================== // // patchCollide_t::FindPlane // //========================================================================== int patchCollide_t::FindPlane( float* p1, float* p2, float* p3 ) { float plane[ 4 ]; if ( !PlaneFromPoints( plane, p1, p2, p3 ) ) { return -1; } // see if the points are close enough to an existing plane for ( int i = 0; i < cm_patch_numPlanes; i++ ) { if ( DotProduct( plane, cm_patch_planes[ i ].plane ) < 0 ) { continue; // allow backwards planes? } float d = DotProduct( p1, cm_patch_planes[ i ].plane ) - cm_patch_planes[ i ].plane[ 3 ]; if ( d < -PLANE_TRI_EPSILON || d > PLANE_TRI_EPSILON ) { continue; } d = DotProduct( p2, cm_patch_planes[ i ].plane ) - cm_patch_planes[ i ].plane[ 3 ]; if ( d < -PLANE_TRI_EPSILON || d > PLANE_TRI_EPSILON ) { continue; } d = DotProduct( p3, cm_patch_planes[ i ].plane ) - cm_patch_planes[ i ].plane[ 3 ]; if ( d < -PLANE_TRI_EPSILON || d > PLANE_TRI_EPSILON ) { continue; } // found it return i; } // add a new plane if ( cm_patch_numPlanes == MAX_PATCH_PLANES ) { common->Error( "MAX_PATCH_PLANES" ); } Vector4Copy( plane, cm_patch_planes[ cm_patch_numPlanes ].plane ); cm_patch_planes[ cm_patch_numPlanes ].signbits = SignbitsForNormal( plane ); cm_patch_numPlanes++; return cm_patch_numPlanes - 1; } //========================================================================== // // patchCollide_t::SignbitsForNormal // //========================================================================== int patchCollide_t::SignbitsForNormal( vec3_t normal ) { int bits = 0; for ( int j = 0; j < 3; j++ ) { if ( normal[ j ] < 0 ) { bits |= 1 << j; } } return bits; } //========================================================================== // // patchCollide_t::EdgePlaneNum // //========================================================================== int patchCollide_t::EdgePlaneNum( cGrid_t* grid, int gridPlanes[ MAX_GRID_SIZE ][ MAX_GRID_SIZE ][ 2 ], int i, int j, int k ) { float* p1, * p2; vec3_t up; int p; switch ( k ) { case 0: // top border p1 = grid->points[ i ][ j ]; p2 = grid->points[ i + 1 ][ j ]; p = GridPlane( gridPlanes, i, j, 0 ); VectorMA( p1, 4, cm_patch_planes[ p ].plane, up ); return FindPlane( p1, p2, up ); case 2: // bottom border p1 = grid->points[ i ][ j + 1 ]; p2 = grid->points[ i + 1 ][ j + 1 ]; p = GridPlane( gridPlanes, i, j, 1 ); VectorMA( p1, 4, cm_patch_planes[ p ].plane, up ); return FindPlane( p2, p1, up ); case 3: // left border p1 = grid->points[ i ][ j ]; p2 = grid->points[ i ][ j + 1 ]; p = GridPlane( gridPlanes, i, j, 1 ); VectorMA( p1, 4, cm_patch_planes[ p ].plane, up ); return FindPlane( p2, p1, up ); case 1: // right border p1 = grid->points[ i + 1 ][ j ]; p2 = grid->points[ i + 1 ][ j + 1 ]; p = GridPlane( gridPlanes, i, j, 0 ); VectorMA( p1, 4, cm_patch_planes[ p ].plane, up ); return FindPlane( p1, p2, up ); case 4: // diagonal out of triangle 0 p1 = grid->points[ i + 1 ][ j + 1 ]; p2 = grid->points[ i ][ j ]; p = GridPlane( gridPlanes, i, j, 0 ); VectorMA( p1, 4, cm_patch_planes[ p ].plane, up ); return FindPlane( p1, p2, up ); case 5: // diagonal out of triangle 1 p1 = grid->points[ i ][ j ]; p2 = grid->points[ i + 1 ][ j + 1 ]; p = GridPlane( gridPlanes, i, j, 1 ); VectorMA( p1, 4, cm_patch_planes[ p ].plane, up ); return FindPlane( p1, p2, up ); } common->Error( "CM_EdgePlaneNum: bad k" ); return -1; } //========================================================================== // // patchCollide_t::GridPlane // //========================================================================== int patchCollide_t::GridPlane( int gridPlanes[ MAX_GRID_SIZE ][ MAX_GRID_SIZE ][ 2 ], int i, int j, int tri ) { int p = gridPlanes[ i ][ j ][ tri ]; if ( p != -1 ) { return p; } p = gridPlanes[ i ][ j ][ !tri ]; if ( p != -1 ) { return p; } // should never happen common->Printf( "WARNING: CM_GridPlane unresolvable\n" ); return -1; } //========================================================================== // // patchCollide_t::SetBorderInward // //========================================================================== void patchCollide_t::SetBorderInward( facet_t* facet, cGrid_t* grid, int gridPlanes[ MAX_GRID_SIZE ][ MAX_GRID_SIZE ][ 2 ], int i, int j, int which ) { float* points[ 4 ]; int numPoints; switch ( which ) { case -1: points[ 0 ] = grid->points[ i ][ j ]; points[ 1 ] = grid->points[ i + 1 ][ j ]; points[ 2 ] = grid->points[ i + 1 ][ j + 1 ]; points[ 3 ] = grid->points[ i ][ j + 1 ]; numPoints = 4; break; case 0: points[ 0 ] = grid->points[ i ][ j ]; points[ 1 ] = grid->points[ i + 1 ][ j ]; points[ 2 ] = grid->points[ i + 1 ][ j + 1 ]; numPoints = 3; break; case 1: points[ 0 ] = grid->points[ i + 1 ][ j + 1 ]; points[ 1 ] = grid->points[ i ][ j + 1 ]; points[ 2 ] = grid->points[ i ][ j ]; numPoints = 3; break; default: common->FatalError( "CM_SetBorderInward: bad parameter" ); } for ( int k = 0; k < facet->numBorders; k++ ) { int front = 0; int back = 0; for ( int l = 0; l < numPoints; l++ ) { int side = PointOnPlaneSide( points[ l ], facet->borderPlanes[ k ] ); if ( side == SIDE_FRONT ) { front++; } if ( side == SIDE_BACK ) { back++; } } if ( front && !back ) { facet->borderInward[ k ] = true; } else if ( back && !front ) { facet->borderInward[ k ] = false; } else if ( !front && !back ) { // flat side border facet->borderPlanes[ k ] = -1; } else { // bisecting side border common->DPrintf( "WARNING: CM_SetBorderInward: mixed plane sides\n" ); facet->borderInward[ k ] = false; if ( !debugBlock ) { debugBlock = true; VectorCopy( grid->points[ i ][ j ], debugBlockPoints[ 0 ] ); VectorCopy( grid->points[ i + 1 ][ j ], debugBlockPoints[ 1 ] ); VectorCopy( grid->points[ i + 1 ][ j + 1 ], debugBlockPoints[ 2 ] ); VectorCopy( grid->points[ i ][ j + 1 ], debugBlockPoints[ 3 ] ); } } } } //========================================================================== // // patchCollide_t::PointOnPlaneSide // //========================================================================== int patchCollide_t::PointOnPlaneSide( const float* p, int planeNum ) { if ( planeNum == -1 ) { return SIDE_ON; } const float* plane = cm_patch_planes[ planeNum ].plane; float d = DotProduct( p, plane ) - plane[ 3 ]; if ( d > PLANE_TRI_EPSILON ) { return SIDE_FRONT; } if ( d < -PLANE_TRI_EPSILON ) { return SIDE_BACK; } return SIDE_ON; } //========================================================================== // // patchCollide_t::ValidateFacet // // If the facet isn't bounded by its borders, we screwed up. // //========================================================================== bool patchCollide_t::ValidateFacet( facet_t* facet ) { float plane[ 4 ]; vec3_t bounds[ 2 ]; if ( facet->surfacePlane == -1 ) { return false; } Vector4Copy( cm_patch_planes[ facet->surfacePlane ].plane, plane ); winding_t* w = CM46_BaseWindingForPlane( plane, plane[ 3 ] ); for ( int j = 0; j < facet->numBorders && w; j++ ) { if ( facet->borderPlanes[ j ] == -1 ) { CM46_FreeWinding( w ); return false; } Vector4Copy( cm_patch_planes[ facet->borderPlanes[ j ] ].plane, plane ); if ( !facet->borderInward[ j ] ) { VectorSubtract( oldvec3_origin, plane, plane ); plane[ 3 ] = -plane[ 3 ]; } CM46_ChopWindingInPlace( &w, plane, plane[ 3 ], 0.1f ); } if ( !w ) { return false; // winding was completely chopped away } // see if the facet is unreasonably large CM46_WindingBounds( w, bounds[ 0 ], bounds[ 1 ] ); CM46_FreeWinding( w ); for ( int j = 0; j < 3; j++ ) { if ( bounds[ 1 ][ j ] - bounds[ 0 ][ j ] > MAX_MAP_BOUNDS ) { return false; // we must be missing a plane } if ( bounds[ 0 ][ j ] >= MAX_MAP_BOUNDS ) { return false; } if ( bounds[ 1 ][ j ] <= -MAX_MAP_BOUNDS ) { return false; } } return true; // winding is fine } //========================================================================== // // patchCollide_t::AddFacetBevels // //========================================================================== void patchCollide_t::AddFacetBevels( facet_t* facet ) { float plane[ 4 ]; Vector4Copy( cm_patch_planes[ facet->surfacePlane ].plane, plane ); winding_t* w = CM46_BaseWindingForPlane( plane, plane[ 3 ] ); for ( int j = 0; j < facet->numBorders && w; j++ ) { if ( facet->borderPlanes[ j ] == facet->surfacePlane ) { continue; } Vector4Copy( cm_patch_planes[ facet->borderPlanes[ j ] ].plane, plane ); if ( !facet->borderInward[ j ] ) { VectorSubtract( oldvec3_origin, plane, plane ); plane[ 3 ] = -plane[ 3 ]; } CM46_ChopWindingInPlace( &w, plane, plane[ 3 ], 0.1f ); } if ( !w ) { return; } vec3_t mins, maxs; CM46_WindingBounds( w, mins, maxs ); // add the axial planes int order = 0; for ( int axis = 0; axis < 3; axis++ ) { for ( int dir = -1; dir <= 1; dir += 2, order++ ) { VectorClear( plane ); plane[ axis ] = dir; if ( dir == 1 ) { plane[ 3 ] = maxs[ axis ]; } else { plane[ 3 ] = -mins[ axis ]; } //if it's the surface plane int flipped; if ( PlaneEqual( &cm_patch_planes[ facet->surfacePlane ], plane, &flipped ) ) { continue; } // see if the plane is allready present int i; for ( i = 0; i < facet->numBorders; i++ ) { if ( GGameType & GAME_ET ) { if ( dir > 0 ) { if ( cm_patch_planes[ facet->borderPlanes[ i ] ].plane[ axis ] >= 0.9999f ) { break; } } else { if ( cm_patch_planes[ facet->borderPlanes[ i ] ].plane[ axis ] <= -0.9999f ) { break; } } } else { if ( PlaneEqual( &cm_patch_planes[ facet->borderPlanes[ i ] ], plane, &flipped ) ) { break; } } } if ( i == facet->numBorders ) { if ( facet->numBorders > 4 + 6 + 16 ) { common->Printf( "ERROR: too many bevels\n" ); } facet->borderPlanes[ facet->numBorders ] = FindPlane2( plane, &flipped ); facet->borderNoAdjust[ facet->numBorders ] = 0; facet->borderInward[ facet->numBorders ] = flipped; facet->numBorders++; } } } // // add the edge bevels // // test the non-axial plane edges for ( int j = 0; j < w->numpoints; j++ ) { int k = ( j + 1 ) % w->numpoints; vec3_t vec; VectorSubtract( w->p[ j ], w->p[ k ], vec ); //if it's a degenerate edge if ( VectorNormalize( vec ) < 0.5 ) { continue; } CM_SnapVector( vec ); for ( k = 0; k < 3; k++ ) { if ( vec[ k ] == -1 || vec[ k ] == 1 || ( vec[ k ] == 0.0f && vec[ ( k + 1 ) % 3 ] == 0.0f ) ) { break; // axial } } if ( k < 3 ) { continue; // only test non-axial edges } // try the six possible slanted axials from this edge for ( int axis = 0; axis < 3; axis++ ) { for ( int dir = -1; dir <= 1; dir += 2 ) { // construct a plane vec3_t vec2; VectorClear( vec2 ); vec2[ axis ] = dir; CrossProduct( vec, vec2, plane ); if ( VectorNormalize( plane ) < 0.5 ) { continue; } plane[ 3 ] = DotProduct( w->p[ j ], plane ); // if all the points of the facet winding are // behind this plane, it is a proper edge bevel int l; float minBack = 0.0f; for ( l = 0; l < w->numpoints; l++ ) { float d = DotProduct( w->p[ l ], plane ) - plane[ 3 ]; if ( d > 0.1 ) { break; // point in front } if ( d < minBack ) { minBack = d; } } // if some point was at the front if ( l < w->numpoints ) { continue; } // if no points at the back then the winding is on the bevel plane if ( minBack > -0.1f ) { break; } //if it's the surface plane int flipped; if ( PlaneEqual( &cm_patch_planes[ facet->surfacePlane ], plane, &flipped ) ) { continue; } // see if the plane is allready present int i; for ( i = 0; i < facet->numBorders; i++ ) { if ( PlaneEqual( &cm_patch_planes[ facet->borderPlanes[ i ] ], plane, &flipped ) ) { break; } } if ( i == facet->numBorders ) { if ( facet->numBorders > 4 + 6 + 16 ) { common->Printf( "ERROR: too many bevels\n" ); } facet->borderPlanes[ facet->numBorders ] = FindPlane2( plane, &flipped ); for ( k = 0; k < facet->numBorders; k++ ) { if ( facet->borderPlanes[ facet->numBorders ] == facet->borderPlanes[ k ] ) { common->Printf( "WARNING: bevel plane already used\n" ); } } facet->borderNoAdjust[ facet->numBorders ] = 0; facet->borderInward[ facet->numBorders ] = flipped; // winding_t* w2 = CM46_CopyWinding( w ); float newplane[ 4 ]; Vector4Copy( cm_patch_planes[ facet->borderPlanes[ facet->numBorders ] ].plane, newplane ); if ( !facet->borderInward[ facet->numBorders ] ) { VectorNegate( newplane, newplane ); newplane[ 3 ] = -newplane[ 3 ]; } CM46_ChopWindingInPlace( &w2, newplane, newplane[ 3 ], 0.1f ); if ( !w2 ) { common->DPrintf( "WARNING: CM_AddFacetBevels... invalid bevel\n" ); continue; } else { CM46_FreeWinding( w2 ); } // facet->numBorders++; //already got a bevel // break; } } } } CM46_FreeWinding( w ); //add opposite plane facet->borderPlanes[ facet->numBorders ] = facet->surfacePlane; facet->borderNoAdjust[ facet->numBorders ] = 0; facet->borderInward[ facet->numBorders ] = true; facet->numBorders++; } //========================================================================== // // patchCollide_t::PlaneEqual // //========================================================================== bool patchCollide_t::PlaneEqual( patchPlane_t* p, float plane[ 4 ], int* flipped ) { if ( idMath::Fabs( p->plane[ 0 ] - plane[ 0 ] ) < NORMAL_EPSILON && idMath::Fabs( p->plane[ 1 ] - plane[ 1 ] ) < NORMAL_EPSILON && idMath::Fabs( p->plane[ 2 ] - plane[ 2 ] ) < NORMAL_EPSILON && idMath::Fabs( p->plane[ 3 ] - plane[ 3 ] ) < DIST_EPSILON ) { *flipped = false; return true; } float invplane[ 4 ]; VectorNegate( plane, invplane ); invplane[ 3 ] = -plane[ 3 ]; if ( idMath::Fabs( p->plane[ 0 ] - invplane[ 0 ] ) < NORMAL_EPSILON && idMath::Fabs( p->plane[ 1 ] - invplane[ 1 ] ) < NORMAL_EPSILON && idMath::Fabs( p->plane[ 2 ] - invplane[ 2 ] ) < NORMAL_EPSILON && idMath::Fabs( p->plane[ 3 ] - invplane[ 3 ] ) < DIST_EPSILON ) { *flipped = true; return true; } return false; } //========================================================================== // // patchCollide_t::FindPlane2 // //========================================================================== int patchCollide_t::FindPlane2( float plane[ 4 ], int* flipped ) { // see if the points are close enough to an existing plane for ( int i = 0; i < cm_patch_numPlanes; i++ ) { if ( PlaneEqual( &cm_patch_planes[ i ], plane, flipped ) ) { return i; } } // add a new plane if ( cm_patch_numPlanes == MAX_PATCH_PLANES ) { common->Error( "MAX_PATCH_PLANES" ); } Vector4Copy( plane, cm_patch_planes[ cm_patch_numPlanes ].plane ); cm_patch_planes[ cm_patch_numPlanes ].signbits = SignbitsForNormal( plane ); cm_patch_numPlanes++; *flipped = false; return cm_patch_numPlanes - 1; } //========================================================================== // // patchCollide_t::CM_SnapVector // //========================================================================== void patchCollide_t::CM_SnapVector( vec3_t normal ) { for ( int i = 0; i < 3; i++ ) { if ( idMath::Fabs( normal[ i ] - 1 ) < NORMAL_EPSILON ) { VectorClear( normal ); normal[ i ] = 1; break; } if ( idMath::Fabs( normal[ i ] - -1 ) < NORMAL_EPSILON ) { VectorClear( normal ); normal[ i ] = -1; break; } } } /* ================================================================================ TRACE TESTING ================================================================================ */ //========================================================================== // // patchCollide_t::TraceThrough // //========================================================================== void patchCollide_t::TraceThrough( traceWork_t* tw ) const { static Cvar* cv; if ( tw->isPoint ) { TracePointThrough( tw ); return; } float bestplane[ 4 ]; const facet_t* facet = facets; for ( int i = 0; i < numFacets; i++, facet++ ) { float enterFrac = -1.0; float leaveFrac = 1.0; int hitnum = -1; const patchPlane_t* planes = &this->planes[ facet->surfacePlane ]; float plane[ 4 ]; VectorCopy( planes->plane, plane ); plane[ 3 ] = planes->plane[ 3 ]; vec3_t startp, endp; if ( tw->sphere.use ) { // adjust the plane distance apropriately for radius plane[ 3 ] += tw->sphere.radius; // find the closest point on the capsule to the plane float t = DotProduct( plane, tw->sphere.offset ); if ( t > 0.0f ) { VectorSubtract( tw->start, tw->sphere.offset, startp ); VectorSubtract( tw->end, tw->sphere.offset, endp ); } else { VectorAdd( tw->start, tw->sphere.offset, startp ); VectorAdd( tw->end, tw->sphere.offset, endp ); } } else { float offset = DotProduct( tw->offsets[ planes->signbits ], plane ); plane[ 3 ] -= offset; VectorCopy( tw->start, startp ); VectorCopy( tw->end, endp ); } int hit; if ( !CheckFacetPlane( plane, startp, endp, &enterFrac, &leaveFrac, &hit ) ) { continue; } if ( hit ) { Vector4Copy( plane, bestplane ); } int j; for ( j = 0; j < facet->numBorders; j++ ) { planes = &this->planes[ facet->borderPlanes[ j ] ]; if ( facet->borderInward[ j ] ) { VectorNegate( planes->plane, plane ); plane[ 3 ] = -planes->plane[ 3 ]; } else { VectorCopy( planes->plane, plane ); plane[ 3 ] = planes->plane[ 3 ]; } if ( tw->sphere.use ) { // adjust the plane distance apropriately for radius plane[ 3 ] += tw->sphere.radius; // find the closest point on the capsule to the plane float t = DotProduct( plane, tw->sphere.offset ); if ( t > 0.0f ) { VectorSubtract( tw->start, tw->sphere.offset, startp ); VectorSubtract( tw->end, tw->sphere.offset, endp ); } else { VectorAdd( tw->start, tw->sphere.offset, startp ); VectorAdd( tw->end, tw->sphere.offset, endp ); } } else { // NOTE: this works even though the plane might be flipped because the bbox is centered float offset = DotProduct( tw->offsets[ planes->signbits ], plane ); plane[ 3 ] += idMath::Fabs( offset ); VectorCopy( tw->start, startp ); VectorCopy( tw->end, endp ); } if ( !CheckFacetPlane( plane, startp, endp, &enterFrac, &leaveFrac, &hit ) ) { break; } if ( hit ) { hitnum = j; Vector4Copy( plane, bestplane ); } } if ( j < facet->numBorders ) { continue; } //never clip against the back side if ( hitnum == facet->numBorders - 1 ) { continue; } if ( enterFrac < leaveFrac && enterFrac >= 0 ) { if ( enterFrac < tw->trace.fraction ) { if ( enterFrac < 0 ) { enterFrac = 0; } if ( !cv ) { cv = Cvar_Get( "r_debugSurfaceUpdate", "1", 0 ); } if ( cv && cv->integer ) { debugPatchCollide = this; debugFacet = facet; } tw->trace.fraction = enterFrac; VectorCopy( bestplane, tw->trace.plane.normal ); tw->trace.plane.dist = bestplane[ 3 ]; } } } } //========================================================================== // // patchCollide_t::TracePointThrough // // special case for point traces because the patch collide "brushes" have no volume // //========================================================================== void patchCollide_t::TracePointThrough( traceWork_t* tw ) const { static Cvar* cv; if ( GGameType & ( GAME_WolfMP | GAME_ET ) ) { if ( !cm_playerCurveClip->integer && !tw->isPoint ) { // FIXME: until I get player sized clipping working right return; } } else { if ( !cm_playerCurveClip->integer || !tw->isPoint ) { return; } } // determine the trace's relationship to all planes const patchPlane_t* planes = this->planes; bool frontFacing[ MAX_PATCH_PLANES ]; float intersection[ MAX_PATCH_PLANES ]; for ( int i = 0; i < numPlanes; i++, planes++ ) { float offset = DotProduct( tw->offsets[ planes->signbits ], planes->plane ); float d1 = DotProduct( tw->start, planes->plane ) - planes->plane[ 3 ] + offset; float d2 = DotProduct( tw->end, planes->plane ) - planes->plane[ 3 ] + offset; if ( d1 <= 0 ) { frontFacing[ i ] = false; } else { frontFacing[ i ] = true; } if ( d1 == d2 ) { intersection[ i ] = 99999; } else { intersection[ i ] = d1 / ( d1 - d2 ); if ( intersection[ i ] <= 0 ) { intersection[ i ] = 99999; } } } // see if any of the surface planes are intersected const facet_t* facet = facets; for ( int i = 0; i < numFacets; i++, facet++ ) { if ( !frontFacing[ facet->surfacePlane ] ) { continue; } float intersect = intersection[ facet->surfacePlane ]; if ( intersect < 0 ) { continue; // surface is behind the starting point } if ( intersect > tw->trace.fraction ) { continue; // already hit something closer } int j; for ( j = 0; j < facet->numBorders; j++ ) { int k = facet->borderPlanes[ j ]; if ( frontFacing[ k ] ^ facet->borderInward[ j ] ) { if ( intersection[ k ] > intersect ) { break; } } else { if ( intersection[ k ] < intersect ) { break; } } } if ( j == facet->numBorders ) { // we hit this facet if ( !cv ) { cv = Cvar_Get( "r_debugSurfaceUpdate", "1", 0 ); } if ( cv->integer ) { debugPatchCollide = this; debugFacet = facet; } planes = &this->planes[ facet->surfacePlane ]; // calculate intersection with a slight pushoff float offset = DotProduct( tw->offsets[ planes->signbits ], planes->plane ); float d1 = DotProduct( tw->start, planes->plane ) - planes->plane[ 3 ] + offset; float d2 = DotProduct( tw->end, planes->plane ) - planes->plane[ 3 ] + offset; tw->trace.fraction = ( d1 - SURFACE_CLIP_EPSILON ) / ( d1 - d2 ); if ( tw->trace.fraction < 0 ) { tw->trace.fraction = 0; } VectorCopy( planes->plane, tw->trace.plane.normal ); tw->trace.plane.dist = planes->plane[ 3 ]; } } } //========================================================================== // // patchCollide_t::CheckFacetPlane // //========================================================================== int patchCollide_t::CheckFacetPlane( float* plane, vec3_t start, vec3_t end, float* enterFrac, float* leaveFrac, int* hit ) { *hit = false; float d1 = DotProduct( start, plane ) - plane[ 3 ]; float d2 = DotProduct( end, plane ) - plane[ 3 ]; // if completely in front of face, no intersection with the entire facet if ( d1 > 0 && ( d2 >= SURFACE_CLIP_EPSILON || d2 >= d1 ) ) { return false; } // if it doesn't cross the plane, the plane isn't relevent if ( d1 <= 0 && d2 <= 0 ) { return true; } // crosses face if ( d1 > d2 ) { // enter float f = ( d1 - SURFACE_CLIP_EPSILON ) / ( d1 - d2 ); if ( f < 0 ) { f = 0; } //always favor previous plane hits and thus also the surface plane hit if ( f > *enterFrac ) { *enterFrac = f; *hit = true; } } else { // leave float f = ( d1 + SURFACE_CLIP_EPSILON ) / ( d1 - d2 ); if ( f > 1 ) { f = 1; } if ( f < *leaveFrac ) { *leaveFrac = f; } } return true; } /* ======================================================================= POSITION TEST ======================================================================= */ //========================================================================== // // patchCollide_t::PositionTest // //========================================================================== bool patchCollide_t::PositionTest( traceWork_t* tw ) const { if ( GGameType & GAME_WolfMP ) { return PositionTestWolfMP( tw ); } if ( tw->isPoint ) { return false; } const facet_t* facet = facets; for ( int i = 0; i < numFacets; i++, facet++ ) { const patchPlane_t* planes = &this->planes[ facet->surfacePlane ]; float plane[ 4 ]; VectorCopy( planes->plane, plane ); plane[ 3 ] = planes->plane[ 3 ]; vec3_t startp; if ( tw->sphere.use ) { // adjust the plane distance apropriately for radius plane[ 3 ] += tw->sphere.radius; // find the closest point on the capsule to the plane float t = DotProduct( plane, tw->sphere.offset ); if ( t > 0 ) { VectorSubtract( tw->start, tw->sphere.offset, startp ); } else { VectorAdd( tw->start, tw->sphere.offset, startp ); } } else { float offset = DotProduct( tw->offsets[ planes->signbits ], plane ); plane[ 3 ] -= offset; VectorCopy( tw->start, startp ); } if ( DotProduct( plane, startp ) - plane[ 3 ] > 0.0f ) { continue; } int j; for ( j = 0; j < facet->numBorders; j++ ) { planes = &this->planes[ facet->borderPlanes[ j ] ]; if ( facet->borderInward[ j ] ) { VectorNegate( planes->plane, plane ); plane[ 3 ] = -planes->plane[ 3 ]; } else { VectorCopy( planes->plane, plane ); plane[ 3 ] = planes->plane[ 3 ]; } if ( tw->sphere.use ) { // adjust the plane distance apropriately for radius plane[ 3 ] += tw->sphere.radius; // find the closest point on the capsule to the plane float t = DotProduct( plane, tw->sphere.offset ); if ( t > 0.0f ) { VectorSubtract( tw->start, tw->sphere.offset, startp ); } else { VectorAdd( tw->start, tw->sphere.offset, startp ); } } else { // NOTE: this works even though the plane might be flipped because the bbox is centered float offset = DotProduct( tw->offsets[ planes->signbits ], plane ); plane[ 3 ] += idMath::Fabs( offset ); VectorCopy( tw->start, startp ); } if ( DotProduct( plane, startp ) - plane[ 3 ] > 0.0f ) { break; } } if ( j < facet->numBorders ) { continue; } // inside this patch facet return true; } return false; } bool patchCollide_t::PositionTestWolfMP( traceWork_t* tw ) const { enum { BOX_FRONT, BOX_BACK, BOX_CROSS }; for ( int i = 0; i < 3; i++ ) { if ( tw->bounds[ 0 ][ i ] > bounds[ 1 ][ i ] || tw->bounds[ 1 ][ i ] < bounds[ 0 ][ i ] ) { return false; } } // determine if the box is in front, behind, or crossing each plane int cross[ MAX_PATCH_PLANES ]; const patchPlane_t* planes = this->planes; for ( int i = 0; i < numPlanes; i++, planes++ ) { float d = DotProduct( tw->start, planes->plane ) - planes->plane[ 3 ]; float offset = idMath::Fabs( DotProduct( tw->offsets[ planes->signbits ], planes->plane ) ); if ( d < -offset ) { cross[ i ] = BOX_FRONT; } else if ( d > offset ) { cross[ i ] = BOX_BACK; } else { cross[ i ] = BOX_CROSS; } } // see if any of the surface planes are intersected const facet_t* facet = facets; for ( int i = 0; i < numFacets; i++, facet++ ) { // the facet plane must be in a cross state if ( cross[ facet->surfacePlane ] != BOX_CROSS ) { continue; } // all of the boundaries must be either cross or back int j; for ( j = 0; j < facet->numBorders; j++ ) { int k = facet->borderPlanes[ j ]; if ( cross[ k ] == BOX_CROSS ) { continue; } if ( cross[ k ] ^ facet->borderInward[ j ] ) { break; } } // if we passed all borders, we are definately in this facet if ( j == facet->numBorders ) { return true; } } return false; } /* ======================================================================= DEBUGGING ======================================================================= */ //========================================================================== // // QClipMap46::DrawDebugSurface // // Called from the renderer // //========================================================================== void QClipMap46::DrawDebugSurface( void ( * drawPoly )( int color, int numPoints, float* points ) ) { static Cvar* cv; const patchCollide_t* pc; facet_t* facet; winding_t* w; int i, j, k, n; int curplanenum, planenum, curinward, inward; float plane[ 4 ]; vec3_t mins = {-15, -15, -28}, maxs = {15, 15, 28}; //vec3_t mins = {0, 0, 0}, maxs = {0, 0, 0}; vec3_t v1, v2; if ( !debugPatchCollide ) { return; } if ( !cv ) { cv = Cvar_Get( "cm_debugSize", "2", 0 ); } pc = debugPatchCollide; for ( i = 0, facet = pc->facets; i < pc->numFacets; i++, facet++ ) { for ( k = 0; k < facet->numBorders + 1; k++ ) { // if ( k < facet->numBorders ) { planenum = facet->borderPlanes[ k ]; inward = facet->borderInward[ k ]; } else { planenum = facet->surfacePlane; inward = false; //continue; } Vector4Copy( pc->planes[ planenum ].plane, plane ); //planenum = facet->surfacePlane; if ( inward ) { VectorSubtract( oldvec3_origin, plane, plane ); plane[ 3 ] = -plane[ 3 ]; } plane[ 3 ] += cv->value; //* for ( n = 0; n < 3; n++ ) { if ( plane[ n ] > 0 ) { v1[ n ] = maxs[ n ]; } else { v1[ n ] = mins[ n ]; } } //end for VectorNegate( plane, v2 ); plane[ 3 ] += idMath::Fabs( DotProduct( v1, v2 ) ); //*/ w = CM46_BaseWindingForPlane( plane, plane[ 3 ] ); for ( j = 0; j < facet->numBorders + 1 && w; j++ ) { // if ( j < facet->numBorders ) { curplanenum = facet->borderPlanes[ j ]; curinward = facet->borderInward[ j ]; } else { curplanenum = facet->surfacePlane; curinward = false; //continue; } // if ( curplanenum == planenum ) { continue; } Vector4Copy( pc->planes[ curplanenum ].plane, plane ); if ( !curinward ) { VectorSubtract( oldvec3_origin, plane, plane ); plane[ 3 ] = -plane[ 3 ]; } // if ( !facet->borderNoAdjust[j] ) { plane[ 3 ] -= cv->value; // } for ( n = 0; n < 3; n++ ) { if ( plane[ n ] > 0 ) { v1[ n ] = maxs[ n ]; } else { v1[ n ] = mins[ n ]; } } //end for VectorNegate( plane, v2 ); plane[ 3 ] -= idMath::Fabs( DotProduct( v1, v2 ) ); CM46_ChopWindingInPlace( &w, plane, plane[ 3 ], 0.1f ); } if ( w ) { if ( facet == debugFacet ) { drawPoly( 4, w->numpoints, w->p[ 0 ] ); //common->Printf("blue facet has %d border planes\n", facet->numBorders); } else { drawPoly( 1, w->numpoints, w->p[ 0 ] ); } CM46_FreeWinding( w ); } else { common->Printf( "winding chopped away by border planes\n" ); } } } // draw the debug block { vec3_t v[ 3 ]; VectorCopy( debugBlockPoints[ 0 ], v[ 0 ] ); VectorCopy( debugBlockPoints[ 1 ], v[ 1 ] ); VectorCopy( debugBlockPoints[ 2 ], v[ 2 ] ); drawPoly( 2, 3, v[ 0 ] ); VectorCopy( debugBlockPoints[ 2 ], v[ 0 ] ); VectorCopy( debugBlockPoints[ 3 ], v[ 1 ] ); VectorCopy( debugBlockPoints[ 0 ], v[ 2 ] ); drawPoly( 2, 3, v[ 0 ] ); } #if 0 vec3_t v[ 4 ]; v[ 0 ][ 0 ] = pc->bounds[ 1 ][ 0 ]; v[ 0 ][ 1 ] = pc->bounds[ 1 ][ 1 ]; v[ 0 ][ 2 ] = pc->bounds[ 1 ][ 2 ]; v[ 1 ][ 0 ] = pc->bounds[ 1 ][ 0 ]; v[ 1 ][ 1 ] = pc->bounds[ 0 ][ 1 ]; v[ 1 ][ 2 ] = pc->bounds[ 1 ][ 2 ]; v[ 2 ][ 0 ] = pc->bounds[ 0 ][ 0 ]; v[ 2 ][ 1 ] = pc->bounds[ 0 ][ 1 ]; v[ 2 ][ 2 ] = pc->bounds[ 1 ][ 2 ]; v[ 3 ][ 0 ] = pc->bounds[ 0 ][ 0 ]; v[ 3 ][ 1 ] = pc->bounds[ 1 ][ 1 ]; v[ 3 ][ 2 ] = pc->bounds[ 1 ][ 2 ]; drawPoly( 4, v[ 0 ] ); #endif }
[ "legzdinsjanis@gmail.com" ]
legzdinsjanis@gmail.com
5cefd19b8ef15789a968a555b72687be8f1ff3b8
c8de642900372d4fc4a61653d7e85d8ca0e2cca7
/route-between-two-nodes-in-graph.cpp
8f6766cf148bf346008b5a625909c29ac41ffc4a
[]
no_license
ShenJack/jack_in_lintcode
4341a0a65a93ef01f307bf4c7270ca9d838c655c
3a61462df23ea1ffe811e3c434e3a4a2681850c0
refs/heads/master
2021-07-23T09:28:08.227015
2017-11-03T12:11:56
2017-11-03T12:11:56
108,419,765
0
0
null
null
null
null
UTF-8
C++
false
false
1,436
cpp
#include <iostream> #include <vector> #include <queue> #include <map> using namespace std; /* * 如下图: A----->B----->C \ | \ | \ | \ v ->D----->E for s = B and t = E, return true for s = D and t = C, return false*/ struct DirectedGraphNode { int label; vector<DirectedGraphNode *> neighbors; DirectedGraphNode(int x) : label(x) {}; }; /* * @param graph: A list of Directed graph node * * @param s: the starting Directed graph node * * @param t: the terminal Directed graph node * * @return: a boolean value * */ bool hasRoute(vector<DirectedGraphNode *> graph, DirectedGraphNode *starting, DirectedGraphNode *terminal) { // write your code here queue<DirectedGraphNode*> q; map<DirectedGraphNode*,bool> visited; q.push(starting); visited[starting]=true; while(!q.empty()) { DirectedGraphNode* cur = q.front(); q.pop(); /*到达终点*/ if(cur==terminal){ return true; } /*for each*//*遍历neighbors 未访问的进入待访问队列 在 之后进行访问 并且记录当前的已经访问*/ for(auto neighbour:cur->neighbors) { if(!visited[neighbour]) { q.push(neighbour); visited[neighbour]=true; } } } return false; } int main() { return 0; }
[ "357875929@qq.com" ]
357875929@qq.com
4bb27bc4cd2e70abd932475b35e2f52b77ae8e43
7259374852e01ec2b3353164e6cc804164fb70bb
/line_tracker_PlatformIO/src/main.cpp
a384f011c803af0a257d5ae7484d19fd629d6fdc
[ "BSD-3-Clause" ]
permissive
Briancbn/line_follower
82934e5547e9d24f657aa520b467dd13d9d53f8b
1dfc3501735199f7268dd29c40cf0ef8b7071501
refs/heads/master
2021-04-03T06:40:04.333418
2018-07-04T20:35:24
2018-07-04T20:35:24
124,444,811
0
0
null
null
null
null
UTF-8
C++
false
false
3,066
cpp
/** * * Line Following Robot * Author: Chen Bainian * E-mail: brian97cbn@gmail.com * * **/ #include "Arduino.h" #include "Config.h" #include "Motor.h" #include "PID.h" #include "Adafruit_NeoPixel.h" #ifdef __AVR__ #include <avr/power.h> #endif // Initialize motor controller Motor robot; // Initialize pid controller PID pid_controller(KP, KI, KD); // Initialize LED strip Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUM_LEDS, LED, NEO_GRB + NEO_KHZ800); // Initialize Functions void LDR_trigger(); void LED_write(int r_value, int g_value, int b_value); void print_sensor_readings(int16_t R2_reading, int16_t R1_reading, int16_t M_reading, int16_t L1_reading, int16_t L2_reading); void setup() { // Initialize Serial Monitor Serial.begin(115200); // Initialize LDR Pin pinMode(LDR, INPUT); // Initialize IR Sensors pinMode(R_IR2, INPUT); pinMode(R_IR1, INPUT); pinMode(M_IR, INPUT); pinMode(L_IR1, INPUT); pinMode(L_IR2, INPUT); // Initialize pixel LED stip pixels.begin(); LED_write(0,0,255); // Trigger the movement when there is light shine on the LDR sensor if(LIGHT_ACTIVATION){ LDR_trigger(); } LED_write(255,0,0); } void loop() { // Read IR sensor readings int16_t R2_reading = analogRead(R_IR2)/IR_RATIO; //Manual calibration int16_t R1_reading = analogRead(R_IR1)/IR_RATIO; int16_t M_reading = analogRead(M_IR)/IR_RATIO; int16_t L1_reading = analogRead(L_IR1)/IR_RATIO; int16_t L2_reading = analogRead(L_IR2)/IR_RATIO; // Calculate error int16_t err = ERROR_DIRECTION * (2 * R2_reading + R1_reading - L1_reading - 2 * L2_reading); // pid controller calculate the correct linear and angular command based on input error pid_controller.load_err(err); // control the robot with the calculate linear and angular command robot.write(pid_controller.get_linear(), pid_controller.get_angular()); // print out sensor readings // print_sensor_readings(R2_reading, R1_reading, M_reading, L1_reading, L2_reading); delay(6); } void LDR_trigger(){ // break the dead loop when the LDR resistance is low enough while (true){ uint16_t LDR_reading = analogRead(LDR); Serial.println(LDR_reading); if(LDR_reading < THRESHOLD){ break; } } } void LED_write(int r_value, int g_value, int b_value){ for(int i=0;i<NUM_LEDS;i++){ // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255 pixels.setPixelColor(i, pixels.Color(r_value, g_value, b_value)); } pixels.show(); } void print_sensor_readings(int16_t R2_reading, int16_t R1_reading, int16_t M_reading, int16_t L1_reading, int16_t L2_reading){ // print out the readings for Serial.print(L2_reading); Serial.print(" "); Serial.print(L1_reading); Serial.print(" "); Serial.print(M_reading); Serial.print(" "); Serial.print(R1_reading); Serial.print(" "); Serial.println(R2_reading); }
[ "brian97cbn@DESKTOP-5O4MLO9.localdomain" ]
brian97cbn@DESKTOP-5O4MLO9.localdomain
745798b82eeea8c7ff62445d831514d27ba70ccd
7288b4fe55a02c5cbce982c81c394666adc17a06
/ros_lib_melodic_dagoz_calman/dgz_msgs/HardwareState.h
5055a1639676942f77152efbb879b302efb7bf15
[]
no_license
AgapeDsky/bc_kirchhoff_three_thread
8c02ba35f0ff29a0d719c21cca36cd9ed879b60a
3152d375286674ac3c32cfa9da596f6345f9d6d4
refs/heads/main
2023-08-05T09:43:19.244039
2021-09-19T04:54:30
2021-09-19T04:54:30
408,034,435
0
2
null
null
null
null
UTF-8
C++
false
false
21,026
h
#ifndef _ROS_dgz_msgs_HardwareState_h #define _ROS_dgz_msgs_HardwareState_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" namespace dgz_msgs { class HardwareState : public ros::Msg { public: typedef int32_t _base_motor_1_pulse_delta_type; _base_motor_1_pulse_delta_type base_motor_1_pulse_delta; typedef int32_t _base_motor_2_pulse_delta_type; _base_motor_2_pulse_delta_type base_motor_2_pulse_delta; typedef int32_t _base_motor_3_pulse_delta_type; _base_motor_3_pulse_delta_type base_motor_3_pulse_delta; typedef int32_t _base_motor_4_pulse_delta_type; _base_motor_4_pulse_delta_type base_motor_4_pulse_delta; typedef int32_t _base_encoder_1_pulse_delta_type; _base_encoder_1_pulse_delta_type base_encoder_1_pulse_delta; typedef int32_t _base_encoder_2_pulse_delta_type; _base_encoder_2_pulse_delta_type base_encoder_2_pulse_delta; typedef int32_t _base_encoder_3_pulse_delta_type; _base_encoder_3_pulse_delta_type base_encoder_3_pulse_delta; typedef int32_t _dribbler_motor_l_pulse_delta_type; _dribbler_motor_l_pulse_delta_type dribbler_motor_l_pulse_delta; typedef int32_t _dribbler_motor_r_pulse_delta_type; _dribbler_motor_r_pulse_delta_type dribbler_motor_r_pulse_delta; typedef double _dribbler_potentio_l_reading_type; _dribbler_potentio_l_reading_type dribbler_potentio_l_reading; typedef double _dribbler_potentio_r_reading_type; _dribbler_potentio_r_reading_type dribbler_potentio_r_reading; typedef double _compass_reading_type; _compass_reading_type compass_reading; typedef double _ir_reading_type; _ir_reading_type ir_reading; HardwareState(): base_motor_1_pulse_delta(0), base_motor_2_pulse_delta(0), base_motor_3_pulse_delta(0), base_motor_4_pulse_delta(0), base_encoder_1_pulse_delta(0), base_encoder_2_pulse_delta(0), base_encoder_3_pulse_delta(0), dribbler_motor_l_pulse_delta(0), dribbler_motor_r_pulse_delta(0), dribbler_potentio_l_reading(0), dribbler_potentio_r_reading(0), compass_reading(0), ir_reading(0) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; union { int32_t real; uint32_t base; } u_base_motor_1_pulse_delta; u_base_motor_1_pulse_delta.real = this->base_motor_1_pulse_delta; *(outbuffer + offset + 0) = (u_base_motor_1_pulse_delta.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_base_motor_1_pulse_delta.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_base_motor_1_pulse_delta.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_base_motor_1_pulse_delta.base >> (8 * 3)) & 0xFF; offset += sizeof(this->base_motor_1_pulse_delta); union { int32_t real; uint32_t base; } u_base_motor_2_pulse_delta; u_base_motor_2_pulse_delta.real = this->base_motor_2_pulse_delta; *(outbuffer + offset + 0) = (u_base_motor_2_pulse_delta.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_base_motor_2_pulse_delta.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_base_motor_2_pulse_delta.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_base_motor_2_pulse_delta.base >> (8 * 3)) & 0xFF; offset += sizeof(this->base_motor_2_pulse_delta); union { int32_t real; uint32_t base; } u_base_motor_3_pulse_delta; u_base_motor_3_pulse_delta.real = this->base_motor_3_pulse_delta; *(outbuffer + offset + 0) = (u_base_motor_3_pulse_delta.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_base_motor_3_pulse_delta.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_base_motor_3_pulse_delta.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_base_motor_3_pulse_delta.base >> (8 * 3)) & 0xFF; offset += sizeof(this->base_motor_3_pulse_delta); union { int32_t real; uint32_t base; } u_base_motor_4_pulse_delta; u_base_motor_4_pulse_delta.real = this->base_motor_4_pulse_delta; *(outbuffer + offset + 0) = (u_base_motor_4_pulse_delta.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_base_motor_4_pulse_delta.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_base_motor_4_pulse_delta.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_base_motor_4_pulse_delta.base >> (8 * 3)) & 0xFF; offset += sizeof(this->base_motor_4_pulse_delta); union { int32_t real; uint32_t base; } u_base_encoder_1_pulse_delta; u_base_encoder_1_pulse_delta.real = this->base_encoder_1_pulse_delta; *(outbuffer + offset + 0) = (u_base_encoder_1_pulse_delta.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_base_encoder_1_pulse_delta.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_base_encoder_1_pulse_delta.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_base_encoder_1_pulse_delta.base >> (8 * 3)) & 0xFF; offset += sizeof(this->base_encoder_1_pulse_delta); union { int32_t real; uint32_t base; } u_base_encoder_2_pulse_delta; u_base_encoder_2_pulse_delta.real = this->base_encoder_2_pulse_delta; *(outbuffer + offset + 0) = (u_base_encoder_2_pulse_delta.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_base_encoder_2_pulse_delta.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_base_encoder_2_pulse_delta.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_base_encoder_2_pulse_delta.base >> (8 * 3)) & 0xFF; offset += sizeof(this->base_encoder_2_pulse_delta); union { int32_t real; uint32_t base; } u_base_encoder_3_pulse_delta; u_base_encoder_3_pulse_delta.real = this->base_encoder_3_pulse_delta; *(outbuffer + offset + 0) = (u_base_encoder_3_pulse_delta.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_base_encoder_3_pulse_delta.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_base_encoder_3_pulse_delta.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_base_encoder_3_pulse_delta.base >> (8 * 3)) & 0xFF; offset += sizeof(this->base_encoder_3_pulse_delta); union { int32_t real; uint32_t base; } u_dribbler_motor_l_pulse_delta; u_dribbler_motor_l_pulse_delta.real = this->dribbler_motor_l_pulse_delta; *(outbuffer + offset + 0) = (u_dribbler_motor_l_pulse_delta.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_dribbler_motor_l_pulse_delta.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_dribbler_motor_l_pulse_delta.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_dribbler_motor_l_pulse_delta.base >> (8 * 3)) & 0xFF; offset += sizeof(this->dribbler_motor_l_pulse_delta); union { int32_t real; uint32_t base; } u_dribbler_motor_r_pulse_delta; u_dribbler_motor_r_pulse_delta.real = this->dribbler_motor_r_pulse_delta; *(outbuffer + offset + 0) = (u_dribbler_motor_r_pulse_delta.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_dribbler_motor_r_pulse_delta.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_dribbler_motor_r_pulse_delta.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_dribbler_motor_r_pulse_delta.base >> (8 * 3)) & 0xFF; offset += sizeof(this->dribbler_motor_r_pulse_delta); union { double real; uint64_t base; } u_dribbler_potentio_l_reading; u_dribbler_potentio_l_reading.real = this->dribbler_potentio_l_reading; *(outbuffer + offset + 0) = (u_dribbler_potentio_l_reading.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_dribbler_potentio_l_reading.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_dribbler_potentio_l_reading.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_dribbler_potentio_l_reading.base >> (8 * 3)) & 0xFF; *(outbuffer + offset + 4) = (u_dribbler_potentio_l_reading.base >> (8 * 4)) & 0xFF; *(outbuffer + offset + 5) = (u_dribbler_potentio_l_reading.base >> (8 * 5)) & 0xFF; *(outbuffer + offset + 6) = (u_dribbler_potentio_l_reading.base >> (8 * 6)) & 0xFF; *(outbuffer + offset + 7) = (u_dribbler_potentio_l_reading.base >> (8 * 7)) & 0xFF; offset += sizeof(this->dribbler_potentio_l_reading); union { double real; uint64_t base; } u_dribbler_potentio_r_reading; u_dribbler_potentio_r_reading.real = this->dribbler_potentio_r_reading; *(outbuffer + offset + 0) = (u_dribbler_potentio_r_reading.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_dribbler_potentio_r_reading.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_dribbler_potentio_r_reading.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_dribbler_potentio_r_reading.base >> (8 * 3)) & 0xFF; *(outbuffer + offset + 4) = (u_dribbler_potentio_r_reading.base >> (8 * 4)) & 0xFF; *(outbuffer + offset + 5) = (u_dribbler_potentio_r_reading.base >> (8 * 5)) & 0xFF; *(outbuffer + offset + 6) = (u_dribbler_potentio_r_reading.base >> (8 * 6)) & 0xFF; *(outbuffer + offset + 7) = (u_dribbler_potentio_r_reading.base >> (8 * 7)) & 0xFF; offset += sizeof(this->dribbler_potentio_r_reading); union { double real; uint64_t base; } u_compass_reading; u_compass_reading.real = this->compass_reading; *(outbuffer + offset + 0) = (u_compass_reading.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_compass_reading.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_compass_reading.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_compass_reading.base >> (8 * 3)) & 0xFF; *(outbuffer + offset + 4) = (u_compass_reading.base >> (8 * 4)) & 0xFF; *(outbuffer + offset + 5) = (u_compass_reading.base >> (8 * 5)) & 0xFF; *(outbuffer + offset + 6) = (u_compass_reading.base >> (8 * 6)) & 0xFF; *(outbuffer + offset + 7) = (u_compass_reading.base >> (8 * 7)) & 0xFF; offset += sizeof(this->compass_reading); union { double real; uint64_t base; } u_ir_reading; u_ir_reading.real = this->ir_reading; *(outbuffer + offset + 0) = (u_ir_reading.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_ir_reading.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_ir_reading.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_ir_reading.base >> (8 * 3)) & 0xFF; *(outbuffer + offset + 4) = (u_ir_reading.base >> (8 * 4)) & 0xFF; *(outbuffer + offset + 5) = (u_ir_reading.base >> (8 * 5)) & 0xFF; *(outbuffer + offset + 6) = (u_ir_reading.base >> (8 * 6)) & 0xFF; *(outbuffer + offset + 7) = (u_ir_reading.base >> (8 * 7)) & 0xFF; offset += sizeof(this->ir_reading); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; union { int32_t real; uint32_t base; } u_base_motor_1_pulse_delta; u_base_motor_1_pulse_delta.base = 0; u_base_motor_1_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_base_motor_1_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_base_motor_1_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_base_motor_1_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->base_motor_1_pulse_delta = u_base_motor_1_pulse_delta.real; offset += sizeof(this->base_motor_1_pulse_delta); union { int32_t real; uint32_t base; } u_base_motor_2_pulse_delta; u_base_motor_2_pulse_delta.base = 0; u_base_motor_2_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_base_motor_2_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_base_motor_2_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_base_motor_2_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->base_motor_2_pulse_delta = u_base_motor_2_pulse_delta.real; offset += sizeof(this->base_motor_2_pulse_delta); union { int32_t real; uint32_t base; } u_base_motor_3_pulse_delta; u_base_motor_3_pulse_delta.base = 0; u_base_motor_3_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_base_motor_3_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_base_motor_3_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_base_motor_3_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->base_motor_3_pulse_delta = u_base_motor_3_pulse_delta.real; offset += sizeof(this->base_motor_3_pulse_delta); union { int32_t real; uint32_t base; } u_base_motor_4_pulse_delta; u_base_motor_4_pulse_delta.base = 0; u_base_motor_4_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_base_motor_4_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_base_motor_4_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_base_motor_4_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->base_motor_4_pulse_delta = u_base_motor_4_pulse_delta.real; offset += sizeof(this->base_motor_4_pulse_delta); union { int32_t real; uint32_t base; } u_base_encoder_1_pulse_delta; u_base_encoder_1_pulse_delta.base = 0; u_base_encoder_1_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_base_encoder_1_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_base_encoder_1_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_base_encoder_1_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->base_encoder_1_pulse_delta = u_base_encoder_1_pulse_delta.real; offset += sizeof(this->base_encoder_1_pulse_delta); union { int32_t real; uint32_t base; } u_base_encoder_2_pulse_delta; u_base_encoder_2_pulse_delta.base = 0; u_base_encoder_2_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_base_encoder_2_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_base_encoder_2_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_base_encoder_2_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->base_encoder_2_pulse_delta = u_base_encoder_2_pulse_delta.real; offset += sizeof(this->base_encoder_2_pulse_delta); union { int32_t real; uint32_t base; } u_base_encoder_3_pulse_delta; u_base_encoder_3_pulse_delta.base = 0; u_base_encoder_3_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_base_encoder_3_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_base_encoder_3_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_base_encoder_3_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->base_encoder_3_pulse_delta = u_base_encoder_3_pulse_delta.real; offset += sizeof(this->base_encoder_3_pulse_delta); union { int32_t real; uint32_t base; } u_dribbler_motor_l_pulse_delta; u_dribbler_motor_l_pulse_delta.base = 0; u_dribbler_motor_l_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_dribbler_motor_l_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_dribbler_motor_l_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_dribbler_motor_l_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->dribbler_motor_l_pulse_delta = u_dribbler_motor_l_pulse_delta.real; offset += sizeof(this->dribbler_motor_l_pulse_delta); union { int32_t real; uint32_t base; } u_dribbler_motor_r_pulse_delta; u_dribbler_motor_r_pulse_delta.base = 0; u_dribbler_motor_r_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_dribbler_motor_r_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_dribbler_motor_r_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_dribbler_motor_r_pulse_delta.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->dribbler_motor_r_pulse_delta = u_dribbler_motor_r_pulse_delta.real; offset += sizeof(this->dribbler_motor_r_pulse_delta); union { double real; uint64_t base; } u_dribbler_potentio_l_reading; u_dribbler_potentio_l_reading.base = 0; u_dribbler_potentio_l_reading.base |= ((uint64_t) (*(inbuffer + offset + 0))) << (8 * 0); u_dribbler_potentio_l_reading.base |= ((uint64_t) (*(inbuffer + offset + 1))) << (8 * 1); u_dribbler_potentio_l_reading.base |= ((uint64_t) (*(inbuffer + offset + 2))) << (8 * 2); u_dribbler_potentio_l_reading.base |= ((uint64_t) (*(inbuffer + offset + 3))) << (8 * 3); u_dribbler_potentio_l_reading.base |= ((uint64_t) (*(inbuffer + offset + 4))) << (8 * 4); u_dribbler_potentio_l_reading.base |= ((uint64_t) (*(inbuffer + offset + 5))) << (8 * 5); u_dribbler_potentio_l_reading.base |= ((uint64_t) (*(inbuffer + offset + 6))) << (8 * 6); u_dribbler_potentio_l_reading.base |= ((uint64_t) (*(inbuffer + offset + 7))) << (8 * 7); this->dribbler_potentio_l_reading = u_dribbler_potentio_l_reading.real; offset += sizeof(this->dribbler_potentio_l_reading); union { double real; uint64_t base; } u_dribbler_potentio_r_reading; u_dribbler_potentio_r_reading.base = 0; u_dribbler_potentio_r_reading.base |= ((uint64_t) (*(inbuffer + offset + 0))) << (8 * 0); u_dribbler_potentio_r_reading.base |= ((uint64_t) (*(inbuffer + offset + 1))) << (8 * 1); u_dribbler_potentio_r_reading.base |= ((uint64_t) (*(inbuffer + offset + 2))) << (8 * 2); u_dribbler_potentio_r_reading.base |= ((uint64_t) (*(inbuffer + offset + 3))) << (8 * 3); u_dribbler_potentio_r_reading.base |= ((uint64_t) (*(inbuffer + offset + 4))) << (8 * 4); u_dribbler_potentio_r_reading.base |= ((uint64_t) (*(inbuffer + offset + 5))) << (8 * 5); u_dribbler_potentio_r_reading.base |= ((uint64_t) (*(inbuffer + offset + 6))) << (8 * 6); u_dribbler_potentio_r_reading.base |= ((uint64_t) (*(inbuffer + offset + 7))) << (8 * 7); this->dribbler_potentio_r_reading = u_dribbler_potentio_r_reading.real; offset += sizeof(this->dribbler_potentio_r_reading); union { double real; uint64_t base; } u_compass_reading; u_compass_reading.base = 0; u_compass_reading.base |= ((uint64_t) (*(inbuffer + offset + 0))) << (8 * 0); u_compass_reading.base |= ((uint64_t) (*(inbuffer + offset + 1))) << (8 * 1); u_compass_reading.base |= ((uint64_t) (*(inbuffer + offset + 2))) << (8 * 2); u_compass_reading.base |= ((uint64_t) (*(inbuffer + offset + 3))) << (8 * 3); u_compass_reading.base |= ((uint64_t) (*(inbuffer + offset + 4))) << (8 * 4); u_compass_reading.base |= ((uint64_t) (*(inbuffer + offset + 5))) << (8 * 5); u_compass_reading.base |= ((uint64_t) (*(inbuffer + offset + 6))) << (8 * 6); u_compass_reading.base |= ((uint64_t) (*(inbuffer + offset + 7))) << (8 * 7); this->compass_reading = u_compass_reading.real; offset += sizeof(this->compass_reading); union { double real; uint64_t base; } u_ir_reading; u_ir_reading.base = 0; u_ir_reading.base |= ((uint64_t) (*(inbuffer + offset + 0))) << (8 * 0); u_ir_reading.base |= ((uint64_t) (*(inbuffer + offset + 1))) << (8 * 1); u_ir_reading.base |= ((uint64_t) (*(inbuffer + offset + 2))) << (8 * 2); u_ir_reading.base |= ((uint64_t) (*(inbuffer + offset + 3))) << (8 * 3); u_ir_reading.base |= ((uint64_t) (*(inbuffer + offset + 4))) << (8 * 4); u_ir_reading.base |= ((uint64_t) (*(inbuffer + offset + 5))) << (8 * 5); u_ir_reading.base |= ((uint64_t) (*(inbuffer + offset + 6))) << (8 * 6); u_ir_reading.base |= ((uint64_t) (*(inbuffer + offset + 7))) << (8 * 7); this->ir_reading = u_ir_reading.real; offset += sizeof(this->ir_reading); return offset; } virtual const char * getType() { return "dgz_msgs/HardwareState"; }; virtual const char * getMD5() { return "98eb1d85bcb259a05db1004f284168b1"; }; }; } #endif
[ "ikanblackghost@gmail.com" ]
ikanblackghost@gmail.com
4e1fbc3ae00e431cf42f33c909b3403cbafbeac5
55263cf5b3e6e727d46e39a0f9a5bba050a2e090
/ode/newton.hh
02a8ae6f1db111458018d51ea70b3c2108d32673
[]
no_license
qooldeel/adonis
a6fc4d2fc3cb23211ccd4830891b4dc599d53f9d
7222cb3d298306944548a8617a1db79d9333baab
refs/heads/master
2021-01-20T18:33:06.985900
2016-06-15T20:33:00
2016-06-15T20:33:00
61,237,667
0
0
null
null
null
null
UTF-8
C++
false
false
8,456
hh
#ifndef NEWTON_METHOD_HH #define NEWTON_METHOD_HH #include <iostream> #include "../common/typeselector.hh" #include "../linalg/linearsystemsolvers.hh" #include "../misc/operations4randomaccesscontainers.hh" #include "../common/globalfunctions.hh" #include "../common/typeadapter.hh" #include "../common/elementaryoperations.hh" #include "../misc/misctmps.hh" #include "../misc/useful.hh" //============= TODO: (un)comment the follwing line ================== //#define EVALUATE_FUN_AT_YPREV_IN_FCT_AGAIN_4_TRAPEZOIDAL_METH //==================================================================== namespace Adonis{ /** * \brief Non Linear Equation which arise when <B>implicit</B> methods are to be solved. Currently only two one-step methods are implemented but it is easy to overload function for general purpose Linear Multistep Methods (LMMs) * \tparam N Order of the method * \tparam F &quot original function &quot, i.e. the right hand side of the (autonomous) ode \f[ y'(t) = f(y(t))\f] */ template<unsigned N, class F> class NLEQ4ImplicitMethod; //! nonlinear equation for implicit Euler ( template<class F> class NLEQ4ImplicitMethod<1,F>{ public: typedef typename F::value_type value_type; typedef NLEQ4ImplicitMethod<1,F> NLEQType; //ThisType template<class V> static inline void resize(size_t n, V& fprev){} //do nothing //! this form is needed by Newton's method (the RHS) template<class Y, class X> static inline Y& negative_equation(Y& g, value_type& h, const X& xn, const X& xprev, F& fun, Y& fprev, unsigned& count){ //! the last argument is not needed here return (g = -1.*xn + xprev + h*fun(xn)); } //! this form is needed by the natual criterion function for the damping strategy template<class Y, class X> static inline Y& equation(Y& g, value_type& h, const X& xn, const X& xprev, F& fun, Y& fprev, unsigned& count){ //! the last argument is not needed here return (g = xn - xprev - h*fun(xn)); } //! check also for stationarity of solution template<class Y, class X> static inline Y& equation(bool& isStationary, Y& g, value_type& h, const X& xn, const X& xprev, F& fun, Y& fprev, unsigned& count){ typedef typename TypeAdapter<typename Y::value_type>::BaseType BaseType; g = fun(xn); //only one function evaluation needed if(is_zero(Norm<'2',BaseType>::norm(g))) isStationary = true; return (g = xn - xprev - h*g); } static inline value_type a0() {return 1.;} static inline value_type b0() {return 1.;} }; /** * Nonlinear equation for implicit trapezoidal method * Note, despite being A-stable, the trapezoidal method does not have an * overall-stability, because it damps rapidly decaying components only very * mildly. In other words the trapezoidal method is not L-stable, whereas * the implicit Euler is. * * Actually, this is a special kind of \f$ \theta \f$-method, i.e. \f[ u_{n+1} = \theta F(u_{n+1}) + (1 - \theta)F(u_n),\f] * where \f$ \theta = 0.5.\f$ * Some practitioners use, e.g., \f$ \theta = 0.51\f$ to make the procedure * behave more like the implicit Euler */ template<class F> class NLEQ4ImplicitMethod<2,F>{ public: typedef typename F::value_type value_type; typedef NLEQ4ImplicitMethod<2,F> NLEQType; //ThisType template<class V> static inline void resize(size_t n, V& fprev){ (fprev.size() == 0) ? fprev.resize(n) : do_nothing(); } //! Recall that xprev is const during Newton iteration, so is fun_(xprev) template<class Y, class X> static inline Y& negative_equation(Y& g, value_type& h, const X& xn, const X& xprev, F& fun, Y& fprev, unsigned& count){ g = fun(xn); #ifndef EVALUATE_FUN_AT_YPREV_IN_FCT_AGAIN_4_TRAPEZOIDAL_METH if(count == 0) fprev = g; //xn has been seeded with xprev as starting val for Newton #endif //! ... + fprev does not yield good res. g = -1.*xn + xprev + 0.5*h*( g + #ifdef EVALUATE_FUN_AT_YPREV_IN_FCT_AGAIN_4_TRAPEZOIDAL_METH fun(xprev) #else fprev #endif ); return g; } template<class Y, class X> static inline Y& equation(Y& g, value_type& h, const X& xn, const X& xprev, F& fun, Y& fprev, unsigned& count){ g = fun(xn); #ifndef EVALUATE_FUN_AT_YPREV_IN_FCT_AGAIN_4_TRAPEZOIDAL_METH if(count == 0) fprev = g; #endif //! ... + fprev does not yield good res. g = xn - xprev - 0.5*h*( g + #ifdef EVALUATE_FUN_AT_YPREV_IN_FCT_AGAIN_4_TRAPEZOIDAL_METH fun(xprev) #else fprev #endif ); //std::cout << "fprev = "<< std::setprecision(16)<< fprev << "fun(x) = "<< fun(xprev) << std::endl; return g; } //! check also for stationarity of solution template<class Y, class X> static inline Y& equation(bool& isStationary, Y& g, value_type& h, const X& xn, const X& xprev, F& fun, Y& fprev, unsigned& count){ typedef typename TypeAdapter<typename Y::value_type>::BaseType BaseType; g = fun(xn); //only one function evaluation needed #ifndef EVALUATE_FUN_AT_YPREV_IN_FCT_AGAIN_4_TRAPEZOIDAL_METH if(count == 0) fprev = g; #endif if(is_zero(Norm<'2',BaseType>::norm(g))) isStationary = true; return (g = xn - xprev - 0.5*h*(g + #ifdef EVALUATE_FUN_AT_YPREV_IN_FCT_AGAIN_4_TRAPEZOIDAL_METH fun(xprev) #else fprev #endif )); } static inline value_type a0() {return 1.;} static inline value_type b0() {return 0.5;} }; /** * \brief Every <I> implicit </I> one step, lmm as well as bdf method possesses an iteration matrix of the form \f[ a_0 I - b_0 h f_y(y_n), \quad a_0, b_0 \not= 0 \f] * \tparam NLEQ type of nonlinear equation (only needed for correct assignment of parameters \f$ a_0\f$ and \f$ b_0.\f$ * \tparam JV type of iteration matrix (Jacobian at input) stored as random access container */ template<class NLEQ, class JV> class DyNLEQ{ public: typedef typename JV::value_type value_type; //! mind the reference to stepsize h !! template<class INT> static inline void form_iteration_matrix(JV& iterationMatrix, value_type& h, const INT& cols, const value_type& a0, const value_type& b0){ //! implicit euler: \f$ a_0 = b_0 = 1\f$, implicit trapezoidal: \f$ a_0 = 1, b_0 = 0.5 \f$ iterationMatrix *= -(NLEQ::NLEQType::b0()*h); update_diagonal<AddBasicElements>(iterationMatrix,cols,NLEQ::NLEQType::a0()); } //! if you've already devided by a0, then this function may be appropriate //! mind the reference to stepsize h !! template<class INT> //!JV jacobian stored as random access cont. static inline void form_iteration_matrix(JV& iterationMatrix, value_type& h, const INT& cols, const value_type& b0deva0){ iterationMatrix *= -h; update_diagonal<AddBasicElements>(iterationMatrix,cols,b0deva0); } }; /** * \brief This class wraps the above implementation to get something of the form \f$ F(x) = 0, \f$ i.e. we are able to use it in a more * <I>mathematical</I> form. * * \tparam N accuracy of nonlinear equation * \tparam OFU original function entering the nonlinear equation * \tparam V the this stores \f$ F(x) \f$ * \tparam X argument of F */ template<unsigned N, class OFU, class V, class X = V> class NonLinearEquationForImplicitONEStepMethods{ public: typedef typename X::value_type value_type; typedef NLEQ4ImplicitMethod<N,OFU> NLEQType; typedef V VType; typedef X XType; enum{ORDER = N}; //!access via <TT> ::ORDER </TT> NonLinearEquationForImplicitONEStepMethods(V& g, const X& xprev, value_type& h, OFU& fun, X& fprev, unsigned& count):g_(g),xprev_(xprev),h_(h),fun_(fun),fprev_(fprev),count_(count){} V& operator()(const X& yn){ return NLEQType::equation(g_,h_,yn,xprev_,fun_,fprev_,count_); } //! check for stationarity, i.e. \f$ fun_(xn) ~ 0\f$ V& operator()(const X& yn, bool& isStationary){ return NLEQType::equation(isStationary,g_,h_,yn,xprev_,fun_,fprev_,count_); } private: V& g_; //store references only! const X& xprev_; value_type& h_; OFU& fun_; X& fprev_; unsigned& count_; }; }//end namespace #endif
[ "mfein@debian" ]
mfein@debian
a37d57eaf87c24bc1a18134e166a76aaa9e91cb3
d9af6ca49774c009c4b277c24fb78f796fe8476b
/src/qt/bantablemodel.h
509ab9296c0c8d44ca2c2a845daedf42c8e267fa
[ "MIT" ]
permissive
loxevesavu/Ingenuity
7924abf996ca1b96885b961b924a565b7fd41312
f57a4d8f089c245d0d7ea676dd4573bb30c05300
refs/heads/master
2020-04-25T22:34:05.740695
2018-12-11T05:56:01
2018-12-11T05:56:01
173,115,384
0
0
null
2019-02-28T13:17:58
2019-02-28T13:17:57
null
UTF-8
C++
false
false
1,900
h
// Copyright (c) 2011-2013 The Bitcoin Core developers // Copyright (c) 2018 The Ingenuity developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_BANTABLEMODEL_H #define BITCOIN_QT_BANTABLEMODEL_H #include "net.h" #include <QAbstractTableModel> #include <QStringList> class ClientModel; class BanTablePriv; struct CCombinedBan { CSubNet subnet; CBanEntry banEntry; }; class BannedNodeLessThan { public: BannedNodeLessThan(int nColumn, Qt::SortOrder fOrder) : column(nColumn), order(fOrder) {} bool operator()(const CCombinedBan& left, const CCombinedBan& right) const; private: int column; Qt::SortOrder order; }; /** Qt model providing information about connected peers, similar to the "getpeerinfo" RPC call. Used by the rpc console UI. */ class BanTableModel : public QAbstractTableModel { Q_OBJECT public: explicit BanTableModel(ClientModel *parent = 0); ~BanTableModel(); void startAutoRefresh(); void stopAutoRefresh(); enum ColumnIndex { Address = 0, Bantime = 1 }; /** @name Methods overridden from QAbstractTableModel @{*/ int rowCount(const QModelIndex &parent) const; int columnCount(const QModelIndex &parent) const; QVariant data(const QModelIndex &index, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const; QModelIndex index(int row, int column, const QModelIndex &parent) const; Qt::ItemFlags flags(const QModelIndex &index) const; void sort(int column, Qt::SortOrder order); bool shouldShow(); /*@}*/ public Q_SLOTS: void refresh(); private: ClientModel *clientModel; QStringList columns; std::unique_ptr<BanTablePriv> priv; }; #endif // BITCOIN_QT_BANTABLEMODEL_H
[ "44764450+IngenuityCoin@users.noreply.github.com" ]
44764450+IngenuityCoin@users.noreply.github.com
cc9b8b0c65082d9f3d24d8f6aa4038fb8d224a0b
ce7816c109bf85c1b3d6d1b6dc29c825151f3fec
/archived/sol1-4/main.cpp
131ab8c458fcd7c34ee589fd62e49fabc7310ac5
[]
no_license
pettan0818/book_algo_rust
4a800c8df99c076b74e613484597d09406849860
13833c128d93e16b93886b787f8a8b41d4d49880
refs/heads/main
2023-03-18T15:31:32.810336
2021-03-19T21:16:53
2021-03-19T21:16:53
344,346,457
0
0
null
null
null
null
UTF-8
C++
false
false
4,382
cpp
#include <iostream> #include <string> #include <vector> #include <cmath> using namespace std; int get_specific_digit(int source, int digit_num) { int floored = source / (int)pow(10.0, (float)(digit_num - 1)); return floored % 10; } int get_len_int(int check_target) { if (check_target == 0) { return 1; } return (int)log10((float)check_target) + 1; } bool check_first_digit(int check_target) { //cout << 'len: ' << get_len_int(check_target) << endl; if (get_len_int(check_target) != 6) // 桁数チェック { return false; } //cout << 'passed' << endl; return true; if (get_specific_digit(check_target, 6) != 6) { return false; } if (get_specific_digit(check_target, 5) != 6) { return false; } return true; } bool check_second_digit(int check_target) { if (get_len_int(check_target) != 6) // 桁数チェック { return false; } if (get_specific_digit(check_target, 6) != 6) { return false; } return true; } bool check_third_digit(int check_target) { if (get_len_int(check_target) != 7) // 桁数チェック { return false; } if (get_specific_digit(check_target, 3) != 6) { return false; } if (get_specific_digit(check_target, 4) != 6) { return false; } if (get_specific_digit(check_target, 5) != 6) { return false; } return true; } bool check_forth_digit(int check_target) { if (get_len_int(check_target) != 6) // 桁数チェック { return false; } if (get_specific_digit(check_target, 1) != 6) { return false; } if (get_specific_digit(check_target, 4) != 6) { return false; } return true; } bool check_final_res(int check_target) { if (get_len_int(check_target) != 10) // 桁数チェック { return false; } if (get_specific_digit(check_target, 5) != 6) { return false; } if (get_specific_digit(check_target, 6) != 6) { return false; } return true; } int main(void) { setlocale(LC_ALL, ""); for (int multipler = 1000; multipler < 10000; multipler++) { for (int source = 100000; source < 1000000; source++) { int res = 0; // 1st. // multipler per digit x source... int digit_1 = get_specific_digit(multipler, 1); int tester_first = source * digit_1; //cout << source << '*' << digit_1 << '=' << tester_first << endl; if (check_first_digit(tester_first)) { res += tester_first; //cout << "passed_1: " << source << '*' << multipler << endl; } else { continue; } // 2nd. int digit_2 = get_specific_digit(multipler, 2); int tester_second = source * digit_2; if (check_second_digit(tester_second)) { res += tester_second * 10; //cout << "passed_2: " << source << '*' << multipler << endl; } else { continue; } // 3rd. int digit_3 = get_specific_digit(multipler, 3); int tester_third = source * digit_3; if (check_third_digit(tester_third)) { res += tester_second * 100; cout << "passed_3: " << source << '*' << multipler << endl; } else { continue; } // 4th. int digit_4 = get_specific_digit(multipler, 4); int tester_forth = source * digit_4; if (check_forth_digit(tester_forth)) { res += tester_second * 1000; cout << "passed_4: " << source << '*' << multipler << endl; } else { continue; } // check final res. if (check_final_res(multipler * source)) { cout << multipler << '*' << source << endl; return 0; } else { continue; } } cout << multipler << endl; } }
[ "woden0818@gmail.com" ]
woden0818@gmail.com
cd428aafb65fc11164deccdb1f3495e77d66907c
5733997d04c9bf22724466d862ebaded2c1a3b67
/ThanksgivingMenu/ThanksgivingMenu/MenuItem.h
f581229491fbe556b0197772a99005c07fb7d093
[]
no_license
CliffHanger311/intro-C-Plus-Plus
eb4042130d098b6358bb2f51d0ac2eea637c39a3
f36878a527e6eebd52dd90cf7d53c764b0799751
refs/heads/master
2020-05-02T17:47:11.389869
2012-12-20T01:19:25
2012-12-20T01:19:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
434
h
#include <iostream> #include <string> using namespace std; class MenuItem { private: string _Name; int _Quantity; string _Course; public: MenuItem(); MenuItem(string, int, string); void Add(int); void Remove(int); int Total(); string ToString(); friend ostream& operator << (ostream& output, MenuItem&); //MenuItem(int width); //MenuItem(); //friend ostream& operator<<(ostream&, const box&); };
[ "cliffhangerthefirst@gmail.com" ]
cliffhangerthefirst@gmail.com
e33dc840abe43f55ae45e4c7d430d19423106953
fa92db7c5c85900d68dee2a20eed3e9e90e8b806
/CIS108QT/Calc/calculator.cpp
4619a8788541a4b58893fd6bc0787940aa004684
[]
no_license
curtisagain/CIS_FinalProject
53f1d3275708d834f7d61d57319cb0896f768093
d6836072d9685c5b32972c78f52f7816dc62b330
refs/heads/master
2020-05-18T15:27:02.124194
2019-05-02T00:22:59
2019-05-02T00:22:59
184,499,012
0
0
null
null
null
null
UTF-8
C++
false
false
7,158
cpp
#include "calculator.h" #include "ui_calculator.h" double calcVal = 0.0; double memVal = 0.0; bool divTrigger = false; bool multTrigger = false; bool addTrigger = false; bool subTrigger = false; Calculator::Calculator(QWidget *parent) : QMainWindow(parent), ui(new Ui::Calculator) { ui->setupUi(this); ui->Display->setText(QString::number(calcVal)); QPushButton *numButtons[10]; for(int i = 0; i < 10; ++i){ QString butName = "Button" + QString::number(i); numButtons[i] = Calculator::findChild<QPushButton *>(butName); connect(numButtons[i], SIGNAL(released()), this, SLOT(NumPressed())); } // Connects ui to functions connect(ui->Add, SIGNAL(released()), this, SLOT(MathButtonPressed())); connect(ui->Subtract, SIGNAL(released()), this, SLOT(MathButtonPressed())); connect(ui->Multiply, SIGNAL(released()), this, SLOT(MathButtonPressed())); connect(ui->Divide, SIGNAL(released()), this, SLOT(MathButtonPressed())); connect(ui->Equal, SIGNAL(released()), this, SLOT(EqualButtonPressed())); connect(ui->ChangeSign, SIGNAL(released()), this, SLOT(ChangeNumberSign())); connect(ui->Point, SIGNAL(released()), this, SLOT(PointPressed())); connect(ui->Tangent, SIGNAL(released()), this, SLOT(TanPressed())); connect(ui->Sine, SIGNAL(released()), this, SLOT(SinPressed())); connect(ui->Cosine, SIGNAL(released()), this, SLOT(CosPressed())); connect(ui->Logarithm, SIGNAL(released()), this, SLOT(LogPressed())); connect(ui->SquareRoot, SIGNAL(released()), this, SLOT(SqrtPressed())); connect(ui->Clear, SIGNAL(released()), this, SLOT(ClearPressed())); connect(ui->Mem, SIGNAL(released()), this, SLOT(MemPressed())); connect(ui->MemAdd, SIGNAL(released()), this, SLOT(MemAddPressed())); connect(ui->MemClear, SIGNAL(released()), this, SLOT(MemClearPressed())); } Calculator::~Calculator() { delete ui; } void Calculator::NumPressed(){ QPushButton *button = (QPushButton *)sender(); QString butVal = button->text(); QString displayVal = ui->Display->text(); if((displayVal.toDouble() == 0)){ ui->Display->setText(butVal); } else { QString newVal = displayVal + butVal;//truncates as string double dblNewVal = newVal.toDouble(); ui->Display->setText(QString::number(dblNewVal, 'g', 16));//changes val to double, also handles . operator } } void Calculator::MathButtonPressed(){ divTrigger = false; multTrigger = false; addTrigger = false; subTrigger = false; QString displayVal = ui->Display->text(); calcVal = displayVal.toDouble(); QPushButton *button = (QPushButton *)sender(); QString butVal = button->text(); if(QString::compare(butVal, "/", Qt::CaseInsensitive) == 0){ divTrigger = true; } else if(QString::compare(butVal, "*", Qt::CaseInsensitive) == 0){ multTrigger = true; } else if(QString::compare(butVal, "+", Qt::CaseInsensitive) == 0){ addTrigger = true; } else { subTrigger = true; } ui->Display->setText("");//grabs second number } void Calculator::EqualButtonPressed(){ double solution = 0.0; QString displayVal = ui->Display->text(); double dblDisplayVal = displayVal.toDouble(); if(addTrigger || subTrigger || multTrigger || divTrigger ){ //case handling for basic functions if(addTrigger){ solution = calcVal + dblDisplayVal; } else if(subTrigger){ solution = calcVal - dblDisplayVal; } else if(multTrigger){ solution = calcVal * dblDisplayVal; } else { solution = calcVal / dblDisplayVal; } } ui->Display->setText(QString::number(solution)); } void Calculator::ChangeNumberSign(){ QString displayVal = ui->Display->text(); QRegExp reg("[-+]?[0-9.]*"); //checks for regular expression if(reg.exactMatch(displayVal)){ double dblDisplayVal = displayVal.toDouble(); double dblDisplayValSign = -1 * dblDisplayVal; ui->Display->setText(QString::number(dblDisplayValSign)); } } void Calculator::PointPressed(){ QString displayVal = ui->Display->text(); if((displayVal.toDouble() == 0)){ ui->Display->setText("0."); } else { QString newVal = displayVal + "."; ui->Display->setText(newVal); //setting this to double instead of text negates the period when it breaks from function } } // All of these functions are Copy/Paste but could be combined to one if it parses text before 'pressed'. void Calculator::LogPressed(){ QString displayVal = ui->Display->text(); QRegExp reg("[-+]?[0-9.]*"); if(reg.exactMatch(displayVal)){ double dblDisplayVal = displayVal.toDouble(); double dblDisplayValLog = log(dblDisplayVal); ui->Display->setText(QString::number(dblDisplayValLog)); } } void Calculator::SinPressed(){ QString displayVal = ui->Display->text(); QRegExp reg("[-+]?[0-9.]*"); if(reg.exactMatch(displayVal)){ double dblDisplayVal = displayVal.toDouble(); double dblDisplayValSin = sin(dblDisplayVal); ui->Display->setText(QString::number(dblDisplayValSin)); } } void Calculator::CosPressed(){ QString displayVal = ui->Display->text(); QRegExp reg("[-+]?[0-9.]*"); if(reg.exactMatch(displayVal)){ double dblDisplayVal = displayVal.toDouble(); double dblDisplayValCos = cos(dblDisplayVal); ui->Display->setText(QString::number(dblDisplayValCos)); } } void Calculator::TanPressed(){ QString displayVal = ui->Display->text(); QRegExp reg("[-+]?[0-9.]*"); if(reg.exactMatch(displayVal)){ double dblDisplayVal = displayVal.toDouble(); double dblDisplayValTan = tan(dblDisplayVal); ui->Display->setText(QString::number(dblDisplayValTan)); } } void Calculator::SqrtPressed(){ QString displayVal = ui->Display->text(); QRegExp reg("[-+]?[0-9.]*"); if(reg.exactMatch(displayVal)){ double dblDisplayVal = displayVal.toDouble(); double dblDisplayValSqrt = sqrt(dblDisplayVal); ui->Display->setText(QString::number(dblDisplayValSqrt)); } } //exchanging vals from display to memory void Calculator::ClearPressed(){ ui->Display->setText("0"); memVal = 0; } void Calculator::MemPressed(){ QString displayVal = ui->Display->text(); memVal = displayVal.toDouble(); ui->Display->setText(""); } void Calculator::MemClearPressed(){ ui->Display->setText(""); memVal = 0; } void Calculator::MemAddPressed(){ ui->Display->setText(QString::number(memVal)); }
[ "noreply@github.com" ]
noreply@github.com
845524d4181fe097e2d9f0755b06875294c0d426
bc3cbf1f7a0804f0329e4680a4719ab3d4e020e1
/Assignment 6/1/Operand.hpp
2cecd8932f84b0644f333d7a48e31276b496c07e
[]
no_license
MrAliTheGreat/AdvancedProgramming
9586e4e84b3bd63bd3a3ab51a77f7cc098f2b5cb
35674d373484995343e3300c1d9cefea819ede8a
refs/heads/master
2023-07-11T14:36:49.114192
2021-08-22T10:54:17
2021-08-22T10:54:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
263
hpp
#ifndef __OPERAND_H__ #define __OPERAND_H__ class Operand { public: Operand(int _id , int _parent_id , int _value); int get_ID(){ return id; }; int get_parent_ID(){ return parent_id; }; double calculate(); private: int id , parent_id; int value; }; #endif
[ "alibahari007@gmail.com" ]
alibahari007@gmail.com
f4099845fde9aa5d088c6f49ec725d7665ecfacb
b012b15ec5edf8a52ecf3d2f390adc99633dfb82
/branches-public/moos-ivp-12.2mit/ivp/src/lib_geometry/XYPolygon.cpp
cc21cc9c0583d58fea515b3ab750e3446976cb6f
[]
no_license
crosslore/moos-ivp-aro
cbe697ba3a842961d08b0664f39511720102342b
cf2f1abe0e27ccedd0bbc66e718be950add71d9b
refs/heads/master
2022-12-06T08:14:18.641803
2020-08-18T06:39:14
2020-08-18T06:39:14
263,586,714
1
0
null
null
null
null
UTF-8
C++
false
false
22,824
cpp
/*****************************************************************/ /* NAME: Michael Benjamin, Henrik Schmidt, and John Leonard */ /* ORGN: Dept of Mechanical Eng / CSAIL, MIT Cambridge MA */ /* FILE: XYPolygon.cpp */ /* DATE: Apr 20th, 2005 */ /* */ /* This program is free software; you can redistribute it and/or */ /* modify it under the terms of the GNU General Public License */ /* as published by the Free Software Foundation; either version */ /* 2 of the License, or (at your option) any later version. */ /* */ /* This program is distributed in the hope that it will be */ /* useful, but WITHOUT ANY WARRANTY; without even the implied */ /* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR */ /* PURPOSE. See the GNU General Public License for more details. */ /* */ /* You should have received a copy of the GNU General Public */ /* License along with this program; if not, write to the Free */ /* Software Foundation, Inc., 59 Temple Place - Suite 330, */ /* Boston, MA 02111-1307, USA. */ /*****************************************************************/ #include <cmath> #include "XYPolygon.h" #include "MBUtils.h" #include "GeomUtils.h" #include "AngleUtils.h" using namespace std; #ifdef _WIN32 #define strncasecmp _strnicmp #endif //--------------------------------------------------------------- // Procedure: Constructor XYPolygon::XYPolygon() { m_convex_state = false; m_transparency = 0.5; } //--------------------------------------------------------------- // Procedure: add_vertex // o A call to "determine_convexity()" is made since this // operation may result in a change in the convexity. // o The check_convexity option allows a bunch of vertices to be // added and then just check for convexity at the end. bool XYPolygon::add_vertex(double x, double y, bool check_convexity) { XYSegList::add_vertex(x,y); m_side_xy.push_back(-1); // With new vertex, we don't know if the new polygon is valid if(check_convexity) { determine_convexity(); return(m_convex_state); } else return(true); } //--------------------------------------------------------------- // Procedure: add_vertex // o A call to "determine_convexity()" is made since this // operation may result in a change in the convexity. // o The check_convexity option allows a bunch of vertices to be // added and then just check for convexity at the end. bool XYPolygon::add_vertex(double x, double y, double z, bool check_convexity) { XYSegList::add_vertex(x,y,z); m_side_xy.push_back(-1); // With new vertex, we don't know if the new polygon is valid if(check_convexity) { determine_convexity(); return(m_convex_state); } else return(true); } //--------------------------------------------------------------- // Procedure: add_vertex // o A call to "determine_convexity()" may be made since this // operation may result in a change in the convexity. // o The check_convexity option allows a bunch of vertices to be // added and then just check for convexity at the end. bool XYPolygon::add_vertex(double x, double y, double z, string property, bool check_convexity) { XYSegList::add_vertex(x, y, z, property); m_side_xy.push_back(-1); // With new vertex, we don't know if the new polygon is valid if(check_convexity) { determine_convexity(); return(m_convex_state); } else return(true); } //--------------------------------------------------------------- // Procedure: alter_vertex // Purpose: Given a new vertex, find the existing vertex that is // closest, and replace it with the new one. // Note: A call to "determine_convexity()" is made since this // operation may result in a change in the convexity. bool XYPolygon::alter_vertex(double x, double y, double z) { XYSegList::alter_vertex(x,y); determine_convexity(); return(m_convex_state); } //--------------------------------------------------------------- // Procedure: grow_by_pct // Note: A call to "determine_convexity()" is made since this // operation may result in a change in the convexity. void XYPolygon::grow_by_pct(double pct) { XYSegList::grow_by_pct(pct); determine_convexity(); } //--------------------------------------------------------------- // Procedure: grow_by_amt // Note: A call to "determine_convexity()" is made since this // operation may result in a change in the convexity. void XYPolygon::grow_by_amt(double amt) { XYSegList::grow_by_amt(amt); determine_convexity(); } //--------------------------------------------------------------- // Procedure: delete_vertex // Purpose: Given a new vertex, find the existing vertex that is // closest, and delete it. // Note: A call to "determine_convexity()" is made since this // operation may result in a change in the convexity. bool XYPolygon::delete_vertex(double x, double y) { unsigned int vsize = m_vx.size(); if(vsize == 0) return(false); unsigned int i, ix = closest_vertex(x, y); vector<int> new_xy; for(i=0; i<ix; i++) new_xy.push_back(m_side_xy[i]); for(i=ix+1; i<vsize; i++) new_xy.push_back(m_side_xy[i]); m_side_xy = new_xy; XYSegList::delete_vertex(x,y); determine_convexity(); return(m_convex_state); } //--------------------------------------------------------------- // Procedure: insert_vertex // Purpose: Given a new vertex, find the existing segment that is // closest, and add the vertex between points // Note: A call to "determine_convexity()" is made since this // operation may result in a change in the convexity. bool XYPolygon::insert_vertex(double x, double y, double z) { unsigned int vsize = m_vx.size(); if(vsize <= 1) return(add_vertex(x, y, z)); unsigned int i, ix = XYPolygon::closest_segment(x, y); vector<int> new_xy; for(i=0; i<=ix; i++) new_xy.push_back(m_side_xy[i]); new_xy.push_back(2); for(i=ix+1; i<vsize; i++) new_xy.push_back(m_side_xy[i]); m_side_xy = new_xy; XYSegList::insert_vertex(x,y,z); determine_convexity(); return(m_convex_state); } //--------------------------------------------------------------- // Procedure: clear void XYPolygon::clear() { XYSegList::clear(); m_side_xy.clear(); m_convex_state = false; } //--------------------------------------------------------------- // Procedure: is_clockwise() // Note: Determine if the ordering of points in the internal // vector of stored points constitutes a clockwise walk // around the polygon. Algorithm base on progression of // relative angle from the center. Result is somewhat // undefined if the polygon is not convex. If it is // "nearly" convex, it should still be accurate. bool XYPolygon::is_clockwise() const { unsigned int i, vsize = m_vx.size(); if(vsize < 3) return(false); int inc_count = 0; int dec_count = 0; double cx = get_center_x(); double cy = get_center_y(); for(i=0; i<vsize; i++) { unsigned int j = i+1; if(j == vsize) j = 0; double relative_angle_1 = relAng(cx, cy, m_vx[i], m_vy[i]); double relative_angle_2 = relAng(cx, cy, m_vx[j], m_vy[j]); if(relative_angle_2 > relative_angle_1) inc_count++; else dec_count++; } bool clockwise; if(inc_count > dec_count) clockwise = true; else clockwise = false; return(clockwise); } //--------------------------------------------------------------- // Procedure: apply_snap // Note: A call to "determine_convexity()" is made since this // operation may result in a change in the convexity. // Note: Will not allow a snap that changes the convexity state // from TRUE to FALSE // Returns: true if the snap was successfully bool XYPolygon::apply_snap(double snapval) { vector<double> tmp_m_vx = m_vx; vector<double> tmp_m_vy = m_vy; // Determine if it is convex prior to applying the snapval bool start_convex = is_convex(); XYSegList::apply_snap(snapval); determine_convexity(); if(is_convex() || !start_convex) return(true); else { m_vx = tmp_m_vx; m_vy = tmp_m_vy; determine_convexity(); return(false); } } //--------------------------------------------------------------- // Procedure: reverse // Note: A call to "determine_convexity()" is made since this // operation needs to have m_side_xy[i] reset for each i. void XYPolygon::reverse() { XYSegList::reverse(); determine_convexity(); } //--------------------------------------------------------------- // Procedure: rotate // Note: A call to "determine_convexity()" is made since this // operation needs to have m_side_xy[i] reset for each i. void XYPolygon::rotate(double val) { XYSegList::rotate(val); determine_convexity(); } //--------------------------------------------------------------- // Procedure: contains bool XYPolygon::contains(double x, double y) const { if(!m_convex_state) return(false); unsigned int ix, vsize = m_vx.size(); if(vsize == 0) return(false); double x1, y1, x2, y2 = 0; for(ix=0; ix<vsize; ix++) { x1 = m_vx[ix]; y1 = m_vy[ix]; int ixx = ix+1; if(ix == vsize-1) ixx = 0; x2 = m_vx[ixx]; y2 = m_vy[ixx]; int vside = side(x1, y1, x2, y2, x, y); if((vside != 2) && (vside != m_side_xy[ix])) return(false); } return(true); } //--------------------------------------------------------------- // Procedure: intersects bool XYPolygon::intersects(const XYPolygon &poly) const { unsigned int this_size = m_vx.size(); unsigned int poly_size = poly.size(); if(this_size == 0) return(false); if(poly_size == 0) return(false); // First check that no vertices from "this" polygon are // contained in the given polygon unsigned int i; for(i=0; i<this_size; i++) { double x = m_vx[i]; double y = m_vy[i]; if(poly.contains(x, y)) return(true); } // Then check that no vertices from the given polygon are // contained in "this" polygon for(i=0; i<poly_size; i++) { double x = poly.get_vx(i); double y = poly.get_vy(i); if(this->contains(x, y)) return(true); } // Then check that no segments from "this" polygon intersect // the given polygon for(i=0; i<this_size; i++) { double x1 = this->get_vx(i); double y1 = this->get_vy(i); double x2 = this->get_vx(0); double y2 = this->get_vy(0); if((i+1) < this_size) { x2 = this->get_vx(i+1); y2 = this->get_vy(i+1); } if(poly.seg_intercepts(x1,y1,x2,y2)) return(true); } return(false); } //--------------------------------------------------------------- // Procedure: dist_to_poly double XYPolygon::dist_to_poly(double px, double py) const { unsigned int ix, vsize = m_vx.size(); if(vsize == 0) return(-1); if(vsize == 1) return(distPointToPoint(px, py, m_vx[0], m_vy[0])); if(vsize == 2) return(distPointToSeg(m_vx[0], m_vy[0], m_vx[1], m_vy[1], px, py)); // Distance to poly is given by the shortest distance to any // one of the edges. double x1, y1, x2, y2; double dist = 0; for(ix=0; ix<vsize; ix++) { x1 = m_vx[ix]; y1 = m_vy[ix]; int ixx = ix+1; if(ix == vsize-1) ixx = 0; x2 = m_vx[ixx]; y2 = m_vy[ixx]; double idist = distPointToSeg(m_vx[ix], m_vy[ix], m_vx[ixx], m_vy[ixx], px, py); if((ix==0) || (idist < dist)) dist = idist; } return(dist); } //--------------------------------------------------------------- // Procedure: dist_to_poly // Note: Determine the distance between the line segment given // by x3,y3,x4,y4 to the polygon. An edge-by-edge check // is performed and the minimum returned. double XYPolygon::dist_to_poly(double x3, double y3, double x4, double y4) const { unsigned int ix, vsize = m_vx.size(); if(vsize == 0) return(-1); if(vsize == 1) return(distPointToSeg(x3,y3,x4,y4, m_vx[0], m_vy[0])); if(vsize == 2) return(distSegToSeg(m_vx[0], m_vy[0], m_vx[1], m_vy[1], x3,y3,x4,y4)); // Distance to poly is given by the shortest distance to any // one of the edges. double x1, y1, x2, y2; double dist = 0; for(ix=0; ix<vsize; ix++) { x1 = m_vx[ix]; y1 = m_vy[ix]; int ixx = ix+1; if(ix == vsize-1) ixx = 0; x2 = m_vx[ixx]; y2 = m_vy[ixx]; double idist = distSegToSeg(m_vx[ix], m_vy[ix], m_vx[ixx], m_vy[ixx], x3, y3, x4, y4); if((ix==0) || (idist < dist)) dist = idist; } return(dist); } //--------------------------------------------------------------- // Procedure: dist_to_poly // Note: Determine the distance between the point given by px,py // to the polygon along a given angle. An edge-by-edge check // is performed and the minimum returned. // Returns: -1 if given ray doesn't intersect the polygon double XYPolygon::dist_to_poly(double px, double py, double angle) const { unsigned int ix, vsize = m_vx.size(); if(vsize == 0) return(-1); if(vsize == 1) return(distPointToSeg(m_vx[0], m_vy[0], m_vx[0], m_vy[0], px,py,angle)); if(vsize == 2) return(distPointToSeg(m_vx[0], m_vy[0], m_vx[1], m_vy[1], px,py,angle)); // Distance to poly is given by the shortest distance to any // one of the edges. double dist = -1; bool first_hit = true; for(ix=0; ix<vsize; ix++) { double x1 = m_vx[ix]; double y1 = m_vy[ix]; int ixx = ix+1; if(ix == vsize-1) ixx = 0; double x2 = m_vx[ixx]; double y2 = m_vy[ixx]; double idist = distPointToSeg(x1,y1,x2,y2,px,py, angle); if(idist != -1) if(first_hit || (idist < dist)) { dist = idist; first_hit = false; } } return(dist); } //--------------------------------------------------------------- // Procedure: seg_intercepts // Purpose: Return true if the given segment intercepts the // polygon. Checks are made whether the segment crosses // any of the polygon edges. Intersection is also true // if the segment is entirely within the polygon. bool XYPolygon::seg_intercepts(double x1, double y1, double x2, double y2) const { unsigned int ix, vsize = m_vx.size(); if(vsize == 0) return(false); double x3,y3,x4,y4; if(vsize == 1) { x3 = x4 = m_vx[0]; y3 = y4 = m_vy[0]; return(segmentsCross(x1,y1,x2,y2,x3,y3,x4,y4)); } // Special case 2 vertices, otherwise the single edge will be checked // twice if handled by the general case. if(vsize == 2) { x3 = m_vx[0]; y3 = m_vy[0]; x4 = m_vx[1]; y4 = m_vy[1]; return(segmentsCross(x1,y1,x2,y2,x3,y3,x4,y4)); } // Now handle the general case of more than two vertices // First check if one of the ends of the segment are contained // in the polygon if(contains(x1,y1) || contains(x2,y2)) return(true); // Next check if the segment intersects any of the polgyon edges. for(ix=0; ix<vsize; ix++) { unsigned int ixx = ix+1; if(ix == vsize-1) ixx = 0; x3 = m_vx[ix]; y3 = m_vy[ix]; x4 = m_vx[ixx]; y4 = m_vy[ixx]; bool result = segmentsCross(x1,y1,x2,y2,x3,y3,x4,y4); if(result == true) return(true); } return(false); } //--------------------------------------------------------------- // Procedure: vertex_is_viewable // Purpose: Determine if the line segment given by the vertex ix, // and the point x1,y1, intersects the polygon *only* // at the vertex. If so, we say that the vertex is // "viewable" from the given point. // Note: We return false if the given point is contained in // the polygon bool XYPolygon::vertex_is_viewable(unsigned int ix, double x1, double y1) const { unsigned int vsize = m_vx.size(); if(vsize == 0) return(false); // Simple Range check if(ix >= vsize) return(false); // Special case, poly has one vertex, viewable from any point. if(vsize == 1) return(true); double x2,y2; x2 = m_vx[ix]; y2 = m_vy[ix]; // Special case, the query point and query vertex are the same if((x1==x2) && (y1==y2)) return(true); // Special case, the query point is contained by (or *on*) the // polygon, return false. (except of course for the special case // handled above where the query vertex and point are the same) if(contains(x1,y1)) return(false); // Special case, 2 vertices. Tricky since the general case does not // properly handle a point that lays on the line, but not the line // segment, given by the one edge in the polygon. if(vsize == 2) { int ixx = 0; if(ix == 0) // set index of the "other" vertex. ixx = 1; double x = m_vx[ixx]; double y = m_vy[ixx]; // if the other vertex point is on the query line segment, false if(segmentsCross(x1,y1,x2,y2,x,y,x,y)) return(false); return(true); } // Now handle the general case of more than two vertices // Next check how many polygon edges intersect the query segment. // Answer should be at least two since the query segment will // interesct the two edges that share the query vertex. // If the query segment intersects more, it must have passed thru // the polygon, so we declare false. unsigned int i, count = 0; double x3, y3, x4, y4; for(i=0; ((i<vsize) && (count <= 2)); i++) { unsigned int j = i+1; if(i == vsize-1) j = 0; x3 = m_vx[i]; y3 = m_vy[i]; x4 = m_vx[j]; y4 = m_vy[j]; bool res = segmentsCross(x1,y1,x2,y2,x3,y3,x4,y4); if(res) count++; } if(count > 2) return(false); else return(true); } //--------------------------------------------------------------- // Procedure: side // Purpose: determines which "side" of the line given by x1,y1 // x2,y2 the point x3,y3 lies on. Returns either 0, 1, 2. // 0 indicates the point is below. // 1 indicates the point is above. // 2 indicates the point is on the line. // For vertical lines, we declare the right is "below". // If the given line is a point, we say the point is on the line // // x x // / | // 1 / 0 1 | 0 // / | // / | // x x // int XYPolygon::side(double x1, double y1, double x2, double y2, double x3, double y3) const { // Handle special cases if(x1 == x2) { if(y1 == y2) return(2); else { if(x3 > x1) return(0); if(x3 < x1) return(1); if(x3 == x1) return(2); } } // Find the line equation y = mx + b double rise = y2 - y1; double run = x2 - x1; double m = rise / run; double b = y2 - (m * x2); // calculate the value of y on the line for x3 double y = (m * x3) + b; // Determine which side the point lies on if(y > y3) return(0); else if(y < y3) return(1); else // if(y == y3) return(2); } //--------------------------------------------------------------- // Procedure: set_side // Note: An edge given by index ix is the edge from ix to ix+1 // When ix is the last vertex, the edge is from ix to 0 // Note: If an edge in a polygon is valid, all other vertices // in the polygon on are the same side. This function // determines which side that is. // Returns: 0 if all points are on the 0 side // 1 if all points are on the 1 side // -1 if not all points are on the same side, OR, if all // points are *on* the segment. // Note: This function serves as more than a convexity test. // The side of each each is an intermediate value that // is used in the dist_to_poly() and contains() function. void XYPolygon::set_side(int ix) { int vsize = m_vx.size(); if((ix < 0) || (ix >= vsize)) return; // Handle special cases if(vsize == 1) m_side_xy[0] = -1; if(vsize == 2) m_side_xy[1] = -1; if(vsize <= 2) return; double x1,y1,x2,y2,x3,y3; x1 = m_vx[ix]; y1 = m_vy[ix]; int ixx = ix+1; if(ix == vsize-1) ixx = 0; x2 = m_vx[ixx]; y2 = m_vy[ixx]; m_side_xy[ix] = -1; bool fresh = true; for(int j=0; j<vsize; j++) { if((j!=ix) && (j!=ixx)) { x3 = m_vx[j]; y3 = m_vy[j]; int iside = side(x1,y1,x2,y2,x3,y3); if(iside != 2) { if(fresh) { m_side_xy[ix] = iside; fresh = false; } else if(iside != m_side_xy[ix]) { m_side_xy[ix] = -1; } } } } } //--------------------------------------------------------------- // Procedure: determine_convexity // Purpose: determine whether the object represents a convex // polygon. We declare that a polygon is *not* convex // unless it contains at least three points. // Most of the work is done by the calls to set_side(). // void XYPolygon::determine_convexity() { unsigned int i; for(i=0; i<size(); i++) set_side(i); m_convex_state = (size() >= 3); for(i=0; i<size(); i++) m_convex_state = m_convex_state && (m_side_xy[i] != -1); } //--------------------------------------------------------------- // Procedure: exportSegList // Purpose: Build an XYSegList from the polygon. Make the first // point in the XYSegList the point in the polygon // that is closest to the x,y point. XYSegList XYPolygon::exportSegList(double x, double y) { unsigned int start_index = 0; double shortest_dist = -1; unsigned int i, vsize = m_vx.size(); for(i=0; i<vsize; i++) { double vx = m_vx[i]; double vy = m_vy[i]; double dist = hypot((x-vx), (y-vy)); if((i==0) || (dist < shortest_dist)) { shortest_dist = dist; start_index = i; } } XYSegList new_segl; unsigned int count = 0; while(count < vsize) { unsigned int index = start_index + count; if(index >= vsize) index -= vsize; new_segl.add_vertex(m_vx[index], m_vy[index]); count++; } return(new_segl); }
[ "zouxueson@hotmail.com" ]
zouxueson@hotmail.com
fa69c51e7cc13de187980ee96c14262f9ac014d3
41c34a4645ce3d4f89a1d6fea57c84cf758f91ed
/core/worldstate.h
62fa5e9e02b34f958e876d6daf6b2a249dee37e0
[]
no_license
microchips-n-dip/cellsim
916306e853cf57a648bc75090983ee12d3c8120b
4bb96f62e001e14cb43fe83dcd7b28d03bff7d64
refs/heads/master
2020-03-17T11:09:17.554932
2018-05-15T13:11:33
2018-05-15T13:11:33
133,540,137
0
0
null
null
null
null
UTF-8
C++
false
false
1,358
h
#ifndef CELLSIM_WORLDSTATE_H #define CELLSIM_WORLDSTATE_H #include <vector> #include <iostream> #include <functional> #include <queue> #include "cellsim/core/status.h" #include "cellsim/core/valid_iterator.h" #include "cellsim/dna/dna.h" #include "cellsim/rna/rna.h" #include "cellsim/proteins/protein_base.h" #include "cellsim/proteins/dnapolymerase.h" #include "cellsim/proteins/rnapolymerase.h" #include "cellsim/proteins/ribosome.h" #include "cellsim/proteins/flagellum.h" namespace cellsim { struct WorldState { void Run(); void reset(); WorldState(); void AddDNA(DNA* dna); void AddRNA(RNA* rna); void AddProtein(Protein* protein); unsigned int GetDNASize() { return dna_.size(); } unsigned int GetRNASize() { return rna_.size(); } unsigned int GetProteinsSize() { return proteins_.size(); } void EnqueueDNA(DNA* dna); void EnqueueRNA(RNA* rna); void EnqueueProtein(Protein* protein); void FlushQueues(); void PrintDNA(); std::vector<DNA*> dna_; ValidIterator<DNA*> active_dna_it; std::vector<RNA*> rna_; ValidIterator<RNA*> active_rna_it; std::vector<Protein*> proteins_; std::queue<DNA*> dna_queue_; std::queue<RNA*> rna_queue_; std::queue<Protein*> protein_queue_; int n_rsrc; unsigned int n_flagella; }; } #endif
[ "xisavariable52@gmail.com" ]
xisavariable52@gmail.com
8fa8bc613c4382daa5420b7757dd9b37c8ac376e
7b56df42fab0847a318038c7aeb14e41c812896c
/engine/include/rev/gl/Texture.h
4cdd41aefe0916fce0b1423d22a8dbfeff7bae88
[ "MIT" ]
permissive
eyebrowsoffire/rev
864946801c0d59fbb4008fbcdcfe543abeabb265
d8abdf0a0016e309942932c9af9df1f8a2b02448
refs/heads/master
2020-03-31T03:07:19.669193
2020-03-15T17:00:53
2020-03-15T17:00:53
151,853,627
0
0
MIT
2019-01-27T22:07:32
2018-10-06T15:30:01
C++
UTF-8
C++
false
false
919
h
#pragma once #include "rev/gl/Context.h" #include "rev/gl/Resource.h" namespace rev { using Texture = Resource<singleCreate<gl::genTextures>, singleDestroy<gl::deleteTextures>>; template <GLenum target> class TextureContext : public ResourceContext<Texture, enumTargetBindFunction<gl::bindTexture, target>> { public: using ResourceContext< Texture, enumTargetBindFunction<gl::bindTexture, target>>::ResourceContext; void setParameter(GLenum name, GLint value) { glTexParameteri(target, name, value); } void setImage(GLint level, GLenum internalFormat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels) { glTexImage2D(target, level, internalFormat, width, height, border, format, type, pixels); } }; using Texture2DContext = TextureContext<GL_TEXTURE_2D>; } // namespace rev
[ "eyebrowsoffire@gmail.com" ]
eyebrowsoffire@gmail.com
f8a414cfa6f79790403b0ef4af1bc63ab538eb31
eae743ab965993d91686ecd6d6f4a1f9dd8adbfb
/Project3/Project3/car.cpp
199397f3fb12ed0842a3e5e7629305e01445ddeb
[ "MIT" ]
permissive
DanielTongAwesome/System_Software_Projects
19088b1a70130d091b05fff66f327982d46213c0
5ce29e35f8906965c4c6a98d6abc5b5f15cfef36
refs/heads/master
2021-09-27T14:35:54.367258
2018-11-09T04:13:41
2018-11-09T04:13:41
150,636,089
0
0
null
null
null
null
UTF-8
C++
false
false
642
cpp
#include <stdio.h> #include "car.h" CarClass::CarClass(int input_car_number) { car_number = input_car_number; printf("Car %d has been created \n", car_number); } void CarClass::Accelerate(int acceleration) { car_accelerate = acceleration; printf("Car %d starts to accelerate ! Accelearation = %d \n", car_number, car_accelerate); } void CarClass::Cruise() { car_accelerate = 0; printf("Car %d starts to curise control, speed = %d \n", car_number, car_speed); } void CarClass::Stop() { car_speed = 0; car_accelerate = 0; printf("Car %d stop ... \n", car_number); } CarClass::~CarClass() { }
[ "danieltongubc@gmail.com" ]
danieltongubc@gmail.com
9157a6ac1aae75cba871a4cc631ffa40066a998f
2126713bc594585d2a9704fc47b93d8494b85d6e
/数组/33.搜索旋转排序数组.cpp
1a210df041e0be35a1bb71a050a7caf4ba2d2f0a
[]
no_license
JINGbw/LeetcodeLeetcode
e92e36e4883440831a47ab1f42fbea3de0f6baf6
fa5f722596fd3041d510d6ad43f2d9b8c68b8b0d
refs/heads/master
2020-06-24T23:14:16.141425
2020-03-27T09:47:16
2020-03-27T09:47:16
199,121,198
1
0
null
null
null
null
UTF-8
C++
false
false
1,503
cpp
class Solution { public: int search(vector<int>& nums, int target) { //题目:在旋转前是升序的旋转数组中寻找目标值,返回目标值的索引 //思路:直接用二分法 //1.[mid]==target,找到了 //mid在有序的一侧/无序的一侧 //2. [mid]<[r] // target在有序的一侧 //target在无序的一侧 //3. [mid]>[l] // target在有序的一侧 //target在无序的一侧 //时间复杂度:O(logN) //空间复杂度:O(1) if(nums.empty()) return -1; int left = 0; int right = nums.size()-1; while(left<=right){ int mid = left+(right-left)/2; if(nums[mid]==target) return mid; //1. mid在有序的一侧还是无序的一侧 //2. 目标在mid左边还是右边 if(nums[mid]<nums[right]){ //mid在有序的一侧 if (nums[mid]<target&&target<=nums[right]) //目标在mid右边 left = mid+1; else //目标在mid左边 right = mid-1; } else { //mid在无序的一边 if(nums[mid]>target&&target>=nums[left]) right = mid-1; else left = mid+1; } } return -1; } };
[ "noreply@github.com" ]
noreply@github.com
0a217d2cbdeb5ea98366228b6fb2c787b57124fa
3159d8a420a15031a9024ab3db1799c0216b8d97
/piece.cpp
f318084d1307a5a7ebe1811a9930c2fb944fce0a
[]
no_license
CuadrosNicolas/LeoinTillValhalar
9f5647a5e4ef7e55faafc97a512ea0b153199702
9527d0c7d93c82069fd4f5599455564a6aa9ab2e
refs/heads/master
2020-04-22T01:14:44.998219
2019-02-10T17:59:29
2019-02-10T17:59:29
170,008,302
0
0
null
null
null
null
ISO-8859-1
C++
false
false
610
cpp
#include "piece.h" piece::piece(float posX,float posY) : hitBox(posX,posY,50,46) { //charge le sprite(position et texture) this->m_sprite.setTexture(generalTexture::textureList["piece"]); this->m_sprite.setPosition(posX,posY); //et active la pièce this->m_isActive = true; } sf::Sprite& piece::getSprite() { return this->m_sprite; } bool piece::isActive() { return this->m_isActive; } void piece::desactive() { this->m_isActive = false;//désactive la pièce pour ne plus l'afficher et tester les collisions avec } piece::~piece() { //dtor }
[ "nicolas.cuadros@etu.univ-nantes.fr" ]
nicolas.cuadros@etu.univ-nantes.fr
8f73aee86554c1d1848c6b30c857ba7549f5947a
aaff0a475ba8195d622b6989c089ba057f180d54
/backup/2/codewars/c++/maximum-gap.cpp
d00d0c6c0d2c32b127ff9707dfa9b33445d1d22c
[ "Apache-2.0" ]
permissive
DandelionLU/code-camp
328b2660391f1b529f1187a87c41e15a3eefb3ee
0fd18432d0d2c4123b30a660bae156283a74b930
refs/heads/master
2023-08-24T00:01:48.900746
2021-10-30T06:37:42
2021-10-30T06:37:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
836
cpp
// Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site . // For this specific algothmic problem, visit my Youtube Video : . // It's fascinating to solve algothmic problems, follow Yanzhan to learn more! // Blog URL for this problem: https://yanzhan.site/codewars/maximum-gap.html . #include <vector> using namespace std; int maxGap(vector<int> numbers) { sort(numbers.begin(), numbers.end()); int res = 0; for (int i = 1; i < numbers.size(); i++) { res = max(res, abs(numbers[i] - numbers[i - 1])); } return res; }
[ "yangyanzhan@gmail.com" ]
yangyanzhan@gmail.com
4cc5481d23ff6c6fa5569a3a0706700fc392b63e
06ecb76973dc61c651c9d13c3d88d83677e20ead
/Compito_06_07_11/Stringa_06_07_11.cpp
55f04472c1931f3a1ca401a58b28b67d93ccc71c
[]
no_license
FrankieV/Fondamenti-di-Informatica
cb39bce8e9a6ad225db372ababc7565a26a6a330
ce2977e15247e2df5c4d9c49b0594143a0e233b5
refs/heads/master
2016-09-09T22:34:37.771788
2014-08-31T11:29:28
2014-08-31T11:29:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,849
cpp
#include <iostream> #include <cstring> using namespace std; bool increasing_sentence( char A[], int dim) { char B[dim]; strcpy( B, A); char *tokenPtr; char *tokenPtr2; int word_compare; tokenPtr = strtok( B," "); tokenPtr2 = tokenPtr; while( tokenPtr != NULL) { word_compare = strcmp( tokenPtr2, tokenPtr); if( word_compare > 0) return false; tokenPtr2 = tokenPtr; tokenPtr = strtok( NULL, " "); } return true; } void shortest_word(char A[], int dim) { char B[dim]; strcpy( B, A); char *tokenPtr; char *token_min_lenght; int lenght; int min_lenght; tokenPtr = strtok( B, " "); token_min_lenght = tokenPtr; min_lenght = strlen( tokenPtr); while( tokenPtr != NULL) { if(( strlen( tokenPtr)) < min_lenght) { min_lenght = strlen( tokenPtr); token_min_lenght = tokenPtr; } tokenPtr = strtok( NULL, " "); } cout << "Parola piu' corta : " << token_min_lenght << " con lunghezza " << min_lenght << endl; } void scarto_media( char A[], int dim) { char B[dim]; strcpy( B, A); char *tokenPtr; char *tokenPtr2; int cont = 0; int somma = 0; int media; tokenPtr = strtok( B, " "); while( tokenPtr != NULL) { tokenPtr2 = tokenPtr; somma += strlen( tokenPtr2); cont++; tokenPtr = strtok( NULL, " "); } media = somma / cont; cout << "Media delle lunghezze : " << media << " scarti : "; tokenPtr = strtok( A, " "); while( tokenPtr != NULL) { int word_lenght = strlen ( tokenPtr); cout << tokenPtr << " " << media - word_lenght << ", "; tokenPtr = strtok ( NULL, " "); } cout << endl; } int main() { const int dim = 100; char A[dim]; cin.getline( A, dim); if ( increasing_sentence( A , dim)) cout << "Frase Crescente " << endl; else cout << "Frase NON Crescente " << endl; shortest_word( A, dim); scarto_media( A, dim); return 0; }
[ "armnd.6793@gmail.com" ]
armnd.6793@gmail.com
020ae2441d29f4f0802d9761b9518ebc89508982
891eca7ee0570cdadad46576dbd38b579b2339a1
/STL_Recap/sequential/deques/deque_push_back_front.cpp
2bcb39ac5c90f6390c1afc12a260f0076b12bf34
[]
no_license
girim/cplusplusPrimerExamples
c5caa0b47630c4afb221a1db78bbd492c9ae2f48
87223e8273d2fdebf91571a794038cfe5a483ec3
refs/heads/master
2021-01-17T20:43:12.655554
2018-09-08T11:07:50
2019-02-17T18:30:22
65,602,150
0
0
null
null
null
null
UTF-8
C++
false
false
647
cpp
#include <iostream> #include <deque> #include "point.hpp" #include "printSeqContainer.hpp" int main(int argc, char const *argv[]) { Point pt1, pt2(1, 1), pt3(2, 2), pt4(3, 3); std::deque<Point> points; points.push_back(pt1); printSequentialContainer(points); points.push_back(pt1); points.push_front(pt2); printSequentialContainer(points); points.push_back(pt3); printSequentialContainer(points); points.push_front(pt4); printSequentialContainer(points); points.pop_back(); printSequentialContainer(points); points.pop_front(); printSequentialContainer(points); return 0; }
[ "girishmb04@gmail.com" ]
girishmb04@gmail.com
da1ff4d04017f44d1b5fe44dd3f3c0612f8cb8e2
66364d4c6644944cf9fee0ac952bbb0f74e7a011
/src/chainparams.h
50b348c47e6de53e00dfa82848609d260a2366b2
[ "MIT" ]
permissive
WBTC-Reborn/WBTC-Reborn-source
9b51270b796549cf7670c0bd4735a9e4ae943948
b2024a7329d4cefcd25f10fed053badf8e46d19f
refs/heads/master
2020-04-21T14:51:07.906910
2019-02-08T12:52:42
2019-02-08T12:52:42
169,648,668
1
0
null
null
null
null
UTF-8
C++
false
false
8,074
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The WBTC Core developers // Copyright (c) 2019 The WBTC Core 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 <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 * WBTC 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; } int SubsidyHalvingInterval() const { return nSubsidyHalvingInterval; } /** 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; } /** Headers first syncing is disabled */ bool HeadersFirstSyncingActive() const { return fHeadersFirstSyncingActive; }; /** 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 LAST_POW_BLOCK() const { return nLastPOWBlock; } int COINBASE_MATURITY() const { return nMaturity; } int ModifierUpgradeBlock() const { return nModifierUpdateBlock; } 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; } std::string SporkKey() const { return strSporkKey; } std::string MasternodePoolDummyAddress() const { return strMasternodePoolDummyAddress; } int64_t StartMasternodePayments() const { return nStartMasternodePayments; } int64_t Budget_Fee_Confirmations() const { return nBudget_Fee_Confirmations; } CBaseChainParams::Network NetworkID() const { return networkID; } 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 nSubsidyHalvingInterval; int nEnforceBlockUpgradeMajority; int nRejectBlockOutdatedMajority; int nToCheckBlockUpgradeMajority; int64_t nTargetTimespan; int64_t nTargetSpacing; int nLastPOWBlock; 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; bool fHeadersFirstSyncingActive; int nPoolMaxTransactions; std::string strSporkKey; std::string strMasternodePoolDummyAddress; int64_t nStartMasternodePayments; int64_t nBudget_Fee_Confirmations; }; /** * 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 setSubsidyHalvingInterval(int anSubsidyHalvingInterval) = 0; 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
[ "wbtcreborn@gmail.com" ]
wbtcreborn@gmail.com
7b84a2dff14823af19d7bbfd9fb82b6ea08d6f44
921282e89ffaafb41019b634391b608909779e29
/test/gtest/common/distributed_vector.cpp
ffe05930277e8525dc907232e913c8d1e7a5c63b
[ "BSD-3-Clause" ]
permissive
kilobyte/distributed-ranges
1c9b198cc4fe1448d5246b927ecf0d94c734d79a
9271e7bbd18df1dcdda4761c5f1735937e093260
refs/heads/main
2023-07-21T09:29:39.951745
2023-05-09T13:21:40
2023-05-09T13:21:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,999
cpp
// SPDX-FileCopyrightText: Intel Corporation // // SPDX-License-Identifier: BSD-3-Clause #include "xhp-tests.hpp" // Fixture template <typename T> class DistributedVectorAllTypes : public testing::Test { public: }; TYPED_TEST_SUITE(DistributedVectorAllTypes, AllTypes); TYPED_TEST(DistributedVectorAllTypes, Requirements) { TypeParam dv(10); static_assert(rng::random_access_range<decltype(dv.segments())>); static_assert(rng::random_access_range<decltype(dv.segments()[0])>); static_assert(rng::viewable_range<decltype(dv.segments())>); static_assert(std::forward_iterator<decltype(dv.begin())>); static_assert(dr::distributed_iterator<decltype(dv.begin())>); static_assert(rng::forward_range<decltype(dv)>); static_assert(rng::random_access_range<decltype(dv)>); static_assert(dr::distributed_contiguous_range<decltype(dv)>); } // gtest support TYPED_TEST(DistributedVectorAllTypes, Stream) { Ops1<TypeParam> ops(10); std::ostringstream os; os << ops.dist_vec; EXPECT_EQ(os.str(), "{ 100, 101, 102, 103, 104, 105, 106, 107, 108, 109 }"); } // gtest support TYPED_TEST(DistributedVectorAllTypes, Equality) { Ops1<TypeParam> ops(10); iota(ops.dist_vec, 100); rng::iota(ops.vec, 100); EXPECT_TRUE(ops.dist_vec == ops.vec); EXPECT_EQ(ops.vec, ops.dist_vec); } TEST(DistributedVector, ConstructorBasic) { xhp::distributed_vector<int> dist_vec(10); iota(dist_vec, 100); std::vector<int> local_vec(10); rng::iota(local_vec, 100); EXPECT_EQ(local_vec, dist_vec); } TEST(DistributedVector, ConstructorFill) { xhp::distributed_vector<int> dist_vec(10, 1); std::vector<int> local_vec(10, 1); EXPECT_EQ(local_vec, dist_vec); } TEST(DistributedVector, ConstructorBasicAOS) { OpsAOS ops(10); EXPECT_EQ(ops.vec, ops.dist_vec); } TEST(DistributedVector, ConstructorFillAOS) { AOS_Struct fill_value{1, 2}; OpsAOS::dist_vec_type dist_vec(10, fill_value); OpsAOS::vec_type local_vec(10, fill_value); EXPECT_EQ(local_vec, dist_vec); }
[ "noreply@github.com" ]
noreply@github.com
8afd720ccd1e68219c502162d76ae0383c81b106
4c20bae79bea47a3554ad7bf679129232c05488e
/main.cpp
cea23a78923d8f46f5769bdfade22fd6fad82944
[]
no_license
scottey24/CIS2013_Week04_Homework
e3c6969443a39b6bf0a13115b4f5a3411f092a03
923e4e433c6429a49cb2b4c47151dc93d926398a
refs/heads/master
2020-04-23T07:30:51.809026
2019-02-16T21:33:37
2019-02-16T21:33:37
171,008,472
0
0
null
null
null
null
UTF-8
C++
false
false
1,761
cpp
#include <iostream> #include <string> using namespace std; double getHatSize(double hght, double wght) { double sizeOfHat; sizeOfHat = (wght/hght) * 2.9; return sizeOfHat; } double getJacketSize (double hght, double wght, int age) { double sizeOfJacket; int newAge; int tens; sizeOfJacket = hght * wght/288; if (age > 30) { newAge = age-30; tens = newAge / 10; sizeOfJacket = sizeOfJacket + (tens * (1.0 / 8.0 )); } return sizeOfJacket; } double getWaiastSize( double hght, double wght, int age) { double sizeOfWaiast; int newAge; int twos; sizeOfWaiast = wght / 5.7; if (age > 28) { newAge = age - 28; twos = newAge / 2; sizeOfWaiast = sizeOfWaiast + (twos * (1.0 / 10.0)); } return sizeOfWaiast; } double getHatSize(double, double); double getJacketSize(double, double, int); double getWaiastSize(double, double, int); int main () { double userHeight; double userWeight; int userAge; char userChoice; double hatSize; double jacketSize; double waist; cout.setf(ios::showpoint); cout.precision(2); do { cout << "Enter the height in inches:"; cin >> userHeight; cout << "Enter the weight in pounds:"; cin >> userWeight; cout << "Enter your age:"; cin >> userAge; hatSize = getHatSize(userHeight, userWeight); jacketSize = getJacketSize(userHeight, userWeight, userAge); waist = getWaiastSize(userHeight, userWeight, userAge); cout<< "\nThe size of the hat in inches:" << hatSize << endl; cout << " The size of the jacket in inches:" << jacketSize << endl; cout << " The size of the waist in inches:" << waist << endl; cout << "Repeat these calculations? (Y/N):"; cin >> userChoice; cout << endl; }while(userChoice == 'Y' || userChoice == 'y'); return 0; }
[ "scot.r.culp@hotmail.com" ]
scot.r.culp@hotmail.com
cfe2e57fcb5e81636930572da212b35d3c83bd53
9a23237af33eddcc149703b897b0120778f05ee6
/Beginning_with_CPP/program-e5.cpp
31c64daf9edf066ad82d773ff0c9cb2517ad55dd
[]
no_license
AtuManikraoBhagat/OOP_with_CPP_Bala
2793c6bfb6a26459749d31e3768189a77344b8f3
6098b32d99ca5a0230fc80f56a7ff6d6b80220f1
refs/heads/master
2021-01-22T19:36:31.822700
2017-03-17T05:34:44
2017-03-17T05:34:44
85,220,990
0
0
null
null
null
null
UTF-8
C++
false
false
292
cpp
/* This program is written by "Atul M. Bhagat" */ #include <iostream> using namespace std; int main() { double f, c; cout << "Enter temperature in Fahrenheit : "; cin >> f; c = (5.0/9.0)*(f-32.0); cout << "Temperature in degree Celcius is '" << c << "'." << endl; return 0; }
[ "atul.git.repo@gmail.com" ]
atul.git.repo@gmail.com
516a1645a4b4233959c93514f2299c69959387a0
60967da6cd7e424542f8bd03fe5a39abcfed627d
/figures.cpp
6369eb6c0d570fc86cae242277ad930cdb4e6561
[]
no_license
kittycat1194/figures
5bcbce2c9a0b1a74242d3096ac227c9f9ee744dc
81a9dcef198c12d51f4d9e8fbf8648e4b33a9608
refs/heads/master
2020-12-29T13:56:16.262591
2020-02-06T07:19:13
2020-02-06T07:19:13
238,629,870
0
1
null
null
null
null
UTF-8
C++
false
false
4,209
cpp
#include <iostream> #include <conio.h> using namespace std; void main() { char option, symbol = '*'; int i, j, side=7; cout << "Please enter a letter to choose an option: \n"; cout << "\"a\" for upper right triangle\n"; cout << "\"b\" for lower left triangle\n"; cout << "\"c\" for upper central triangle\n"; cout << "\"d\" for lower central triangle\n"; cout << "\"e\" for upper and lower central triangles\n"; cout << "\"f\" for left and right central triangles\n"; cout << "\"g\" for central left triangle\n"; cout << "\"h\" for central right triangle\n"; cout << "\"k\" for upper left triangle\n"; cout << "\"l\" for lower right triangle\n"; cout << "\"m\" for rhombus\n"; cout << "\"n\" for outside of the rhombus\n"; cin >> option; switch (option) { case 'a': for (i = 0; i < side; i++) { for (j = 0; j < side; j++) { if (i <= j) { cout << symbol << " "; } else { cout << " "; } } cout << endl; } break; case 'b': for (i = 0; i < side; i++) { for (j = 0; j < side; j++) { if (i >= j) { cout << symbol << " "; } else { cout << " "; } } cout << endl; } break; case 'c': for (i = 0; i < side; i++) { for (j = 0; j < side; j++) { if (i <= j && (i+j)<=(side-1)) { cout << symbol << " "; } else { cout << " "; } } cout << endl; } break; case 'd': for (i = 0; i < side; i++) { for (j = 0; j < side; j++) { if (i >= j && (i + j) >= (side - 1)) { cout << symbol << " "; } else { cout << " "; } } cout << endl; } break; case 'e': for (i = 0; i < side; i++) { for (j = 0; j < side; j++) { if (i <= j && (i + j) <= (side - 1) || (i >= j && (i + j) >= (side - 1))) { cout << symbol << " "; } else { cout << " "; } } cout << endl; } break; case 'f': for (i = 0; i < side; i++) { for (j = 0; j < side; j++) { if (i < j && (i + j) < (side - 1) || (i > j && (i + j) > (side - 1))) { cout << " "; } else { cout << symbol << " "; } } cout << endl; } break; case 'g': for (i = 0; i < side; i++) { for (j = 0; j < side; j++) { if (i >= j && (i + j) <= (side - 1)) { cout << symbol << " "; } else { cout << " "; } } cout << endl; } break; case 'h': for (i = 0; i < side; i++) { for (j = 0; j < side; j++) { if (i >= j && (i + j) <= (side - 1)) { cout << symbol << " "; } else { cout << " "; } } cout << endl; } break; case 'k': for (i = 0; i < side; i++) { for (j = 0; j < side; j++) { if ((i+j) <= (side-1)) { cout << symbol << " "; } else { cout << " "; } } cout << endl; } break; case 'l': for (i = 0; i < side; i++) { for (j = 0; j < side; j++) { if ((i + j) >= (side - 1)) { cout << symbol << " "; } else { cout << " "; } } cout << endl; } break; case 'm': for (i = 0; i < side; i++) { for (j = 0; j < side; j++) { if (((i + j) >= (side/2)) && ((i - j) <= (side / 2)) && ((j - i) <= (side / 2)) && ((j + i) <= (side - 1 +side / 2))) { cout << symbol << " "; } else { cout << " "; } } cout << endl; } break; case 'n': for (i = 0; i < side; i++) { for (j = 0; j < side; j++) { //таким образом вырезается ромб, равный по размеру ромбу из варианта 'm': if (((i + j) >= (side / 2)) && ((i - j) <= (side / 2)) && ((j - i) <= (side / 2)) && ((j + i) <= (side - 1 + side / 2))) { //если необходимо вырезать размером меньше на один символ (не включая диагонали): //if (((i + j) > (side / 2)) && ((i - j) < (side / 2)) && ((j - i) < (side / 2)) && ((j + i) < (side - 1 + side / 2))) { cout << " "; } else { cout << symbol << " "; } } cout << endl; } break; } _getch(); }
[ "noreply@github.com" ]
noreply@github.com
52efb7436dca6b6d1bb78ac5b21e2d05f565e3fe
2ee80e0944fa3f6ecc178fae315f55d99d181d9e
/TOE1.cpp
c0aaaa0c778f9d7158bfcdf1af403d611c62d56c
[]
no_license
prashantkhurana/Algorithms_Questions
e4b812627889af11f93c37aed4a73fdfcf00777a
0792566cd95c043cf3cbbbf530e736b308171751
refs/heads/master
2020-04-15T23:50:16.936007
2017-02-07T05:05:09
2017-02-07T05:05:09
15,850,425
0
0
null
null
null
null
UTF-8
C++
false
false
1,429
cpp
#include <cstdio> #include <vector> #include <cmath> using namespace std; int count(char a[][3], char t) { int c = 0; for(int i=0;i<3;i++) for(int j=0;j<3;j++) if(a[i][j]==t) c++; return c; } bool win(char a[][3], char t) { if(a[0][0]==t&&a[0][1]==t&&a[0][2]==t) return true; if(a[1][0]==t&&a[1][1]==t&&a[1][2]==t) return true; if(a[2][0]==t&&a[2][1]==t&&a[2][2]==t) return true; if(a[0][0]==t&&a[1][0]==t&&a[2][0]==t) return true; if(a[0][1]==t&&a[1][1]==t&&a[2][1]==t) return true; if(a[0][2]==t&&a[1][2]==t&&a[2][2]==t) return true; if(a[0][0]==t&&a[1][1]==t&&a[2][2]==t) return true; if(a[2][0]==t&&a[1][1]==t&&a[0][2]==t) return true; return false; } int main() { int n; scanf("%d",&n); char a[3][3]; char dummy; int countx,counto; int i=n; while(i-->0) { bool flag = 0; for(int j=0;j<3;j++) scanf("%s",a[j]); countx = count(a,'X'); counto = count(a,'O'); if(countx<counto||countx-counto>1) { printf("no\n"); flag = 1; } if(countx==counto) { if(win(a,'X')) { printf("no\n"); flag = 1; } } if(countx>counto) { if(win(a,'O')) { printf("no\n"); flag = 1; } } if(flag==0) printf("yes\n"); } return 0; }
[ "prashant.khurana@cs.rutgers.edu" ]
prashant.khurana@cs.rutgers.edu
ffec5e5e71da2ea53cf8545fb6f76cc339f62f45
2f814827ffab9d8d9cc23cb4c3622feb45fa5770
/PWGJE/EMCALJetTasks/UserTasks/AliAnalysisTaskEmcalJetHUtils.cxx
87b1e3bde1908b08b36c3292f5576af63410ee99
[]
permissive
urasantonio/AliPhysics
dd3a851f84674846e45f4b1fdea65700dee80223
8ca4a9abc72a6b94e75048d08748a1debf41873e
refs/heads/master
2022-12-17T21:54:22.246566
2020-09-11T14:04:20
2020-09-11T14:04:20
268,796,481
1
0
BSD-3-Clause
2020-09-11T13:50:03
2020-06-02T12:35:23
C++
UTF-8
C++
false
false
160,171
cxx
// // Utilities class for Jet-Hadron correlation analysis // #include "AliAnalysisTaskEmcalJetHUtils.h" // Require to use AliLog streams with some types #include <iostream> #include <cmath> #include <TObjArray.h> #include <TObjString.h> #include <TMath.h> #include <AliLog.h> #include "AliEmcalJet.h" #include "AliEmcalContainerUtils.h" #include "AliEmcalContainer.h" #include "AliParticleContainer.h" #include "AliTrackContainer.h" #include "AliClusterContainer.h" #include "AliEmcalParticleJetConstituent.h" #include "AliEmcalClusterJetConstituent.h" // Flow vector corrections #include "AliQnCorrectionsProfileCorrelationComponents.h" #include "AliQnCorrectionsProfile3DCorrelations.h" #include "AliQnCorrectionsEventClassVariablesSet.h" #include "AliQnCorrectionsCutWithin.h" #include "AliQnCorrectionsDataVector.h" #include "AliQnCorrectionsQnVector.h" #include "AliQnCorrectionsDetector.h" #include "AliQnCorrectionsDetectorConfigurationTracks.h" #include "AliQnCorrectionsDetectorConfigurationChannels.h" #include "AliQnCorrectionsManager.h" #include "AliQnCorrectionsInputGainEqualization.h" #include "AliQnCorrectionsQnVectorRecentering.h" #include "AliQnCorrectionsQnVectorAlignment.h" #include "AliQnCorrectionsQnVectorTwistAndRescale.h" #include "AliAnalysisTaskFlowVectorCorrections.h" namespace PWGJE { namespace EMCALJetTasks { const std::map<std::string, AliAnalysisTaskEmcalJetHUtils::ELeadingHadronBiasType_t> AliAnalysisTaskEmcalJetHUtils::fgkLeadingHadronBiasMap = { { "kCharged", AliAnalysisTaskEmcalJetHUtils::kCharged}, { "kNeutral", AliAnalysisTaskEmcalJetHUtils::kNeutral}, { "kBoth", AliAnalysisTaskEmcalJetHUtils::kBoth} }; const std::map<std::string, AliEmcalJet::JetAcceptanceType> AliAnalysisTaskEmcalJetHUtils::fgkJetAcceptanceMap = { {"kTPC", AliEmcalJet::kTPC}, {"kTPCfid", AliEmcalJet::kTPCfid}, {"kEMCAL", AliEmcalJet::kEMCAL}, {"kEMCALfid", AliEmcalJet::kEMCALfid}, {"kDCAL", AliEmcalJet::kDCAL}, {"kDCALfid", AliEmcalJet::kDCALfid}, {"kDCALonly", AliEmcalJet::kDCALonly}, {"kDCALonlyfid", AliEmcalJet::kDCALonlyfid}, {"kPHOS", AliEmcalJet::kPHOS}, {"kPHOSfid", AliEmcalJet::kPHOSfid}, {"kUser", AliEmcalJet::kUser} }; const std::map<std::string, AliAnalysisTaskEmcalJetHUtils::EEfficiencyPeriodIdentifier_t> AliAnalysisTaskEmcalJetHUtils::fgkEfficiencyPeriodIdentifier = { { "DisableEff", AliAnalysisTaskEmcalJetHUtils::kDisableEff}, { "LHC11h", AliAnalysisTaskEmcalJetHUtils::kLHC11h}, { "LHC15o", AliAnalysisTaskEmcalJetHUtils::kLHC15o}, { "LHC18q", AliAnalysisTaskEmcalJetHUtils::kLHC18qr}, { "LHC18r", AliAnalysisTaskEmcalJetHUtils::kLHC18qr}, { "LHC11a", AliAnalysisTaskEmcalJetHUtils::kLHC11a}, { "pA", AliAnalysisTaskEmcalJetHUtils::kpA }, { "pp", AliAnalysisTaskEmcalJetHUtils::kpp } }; // LHC11h efficiency parameters for good runs // 0-10% centrality const double AliAnalysisTaskEmcalJetHUtils::LHC11hParam_0_10[17] = { 0.971679, 0.0767571, 1.13355, -0.0274484, 0.856652, 0.00536795, 3.90795e-05, 1.06889, 0.011007, 0.447046, -0.146626, 0.919777, 0.192601, -0.268515, 1.00243, 0.00620849, 0.709477 }; // 10-30% centrality const double AliAnalysisTaskEmcalJetHUtils::LHC11hParam_10_30[17] = { 0.97929, 0.0776039, 1.12213, -0.0300645, 0.844722, 0.0134788, -0.0012333, 1.07955, 0.0116835, 0.456608, -0.132743, 0.930964, 0.174175, -0.267154, 0.993118, 0.00574892, 0.765256 }; // 30-50% centrality const double AliAnalysisTaskEmcalJetHUtils::LHC11hParam_30_50[17] = { 0.997696, 0.0816769, 1.14341, -0.0353734, 0.752151, 0.0744259, -0.0102926, 1.01561, 0.00713274, 0.57203, -0.0640248, 0.947747, 0.102007, -0.194698, 0.999164, 0.00568476, 0.7237 }; // 50-90% centrality const double AliAnalysisTaskEmcalJetHUtils::LHC11hParam_50_90[17] = { 0.97041, 0.0813559, 1.12151, -0.0368797, 0.709327, 0.0701501, -0.00784043, 1.06276, 0.00676173, 0.53607, -0.0703117, 0.982534, 0.0947881, -0.18073, 1.03229, 0.00580109, 0.737801 }; // For pt parameters, first 5 are low pt, next 5 are high pt // For eta parameters, first 6 are eta =< -0.04 (eta left in Eliane's def), next 6 are => -0.04 (eta right // in Eliane's def). The last parameter normalizes the eta values such that their maximum is 1. This was apparently // part of their definition, but was implementing by normalizing a TF1 afterwards. My implementation approach here // is more useful when not using a TF1. // 0-10% centrality const double AliAnalysisTaskEmcalJetHUtils::LHC15oParam_0_10_pt[10] = { 0.8350, 0.0621, 0.0986, 0.2000, 1.0124, 0.7568, 0.0277, -0.0034, 0.1506 * 0.001, -0.0023 * 0.001 }; const double AliAnalysisTaskEmcalJetHUtils::LHC15oParam_0_10_eta[13] = { 1.0086, 0.0074, 0.2404, -0.1230, -0.0107, 0.0427, 0.8579, 0.0088, 0.4697, 0.0772, -0.0352, 0.0645, 0.7716 }; // 10-30% centrality const double AliAnalysisTaskEmcalJetHUtils::LHC15oParam_10_30_pt[10] = { 0.8213, 0.0527, 0.0867, 0.1970, 1.1518, 0.7469, 0.0300, -0.0038, 0.1704 * 0.001, -0.0026 * 0.001 }; const double AliAnalysisTaskEmcalJetHUtils::LHC15oParam_10_30_eta[13] = { 0.9726, 0.0066, 0.2543, -0.1167, -0.0113, 0.0400, 0.8729, 0.0122, 0.4537, 0.0965, -0.0328, 0.0623, 0.7658 }; // 30-50% centrality const double AliAnalysisTaskEmcalJetHUtils::LHC15oParam_30_50_pt[10] = { 0.8381, 0.0648, 0.1052, 0.1478, 1.0320, 0.7628, 0.0263, -0.0032, 0.1443 * 0.001, -0.0023 * 0.001 }; const double AliAnalysisTaskEmcalJetHUtils::LHC15oParam_30_50_eta[13] = { 0.9076, 0.0065, 0.3216, -0.1130, -0.0107, 0.0456, 0.8521, 0.0073, 0.4764, 0.0668, -0.0363, 0.0668, 0.7748 }; // 50-90% centrality const double AliAnalysisTaskEmcalJetHUtils::LHC15oParam_50_90_pt[10] = { 0.8437, 0.0668, 0.1083, 0.2000, 0.9741, 0.7677, 0.0255, -0.0030, 0.1260 * 0.001, -0.0019 * 0.001 }; const double AliAnalysisTaskEmcalJetHUtils::LHC15oParam_50_90_eta[13] = { 1.1259, 0.0105, 0.1961, -0.1330, -0.0103, 0.0440, 0.8421, 0.0066, 0.5061, 0.0580, -0.0379, 0.0651, 0.7786 }; /** * Determine leading hadron pt in a jet. This is inspired by AliJetContainer::GetLeadingHadronMomentum(), but * that particular function is avoided because the cluster energy retrieved is always the raw E while the * cluster energy used in creating the jet would be preferred. One could create a cluster container and go * through all of those steps, but there is a simpler approach: the leading charged and neutral momenta * are stored in AliEmcalJet while performing jet finding. * * @param[in] jet Jet from which the leading hadron pt should be extracted * @param[in] leadingHadronType Type of leading hadron pt to retrieve * * @return Value of the leading hadron pt */ double AliAnalysisTaskEmcalJetHUtils::GetLeadingHadronPt(AliEmcalJet * jet, AliAnalysisTaskEmcalJetHUtils::ELeadingHadronBiasType_t leadingHadronType) { double maxTrackPt = 0; double maxClusterPt = 0; if (leadingHadronType == kCharged || leadingHadronType == kBoth) { auto particle = jet->GetLeadingParticleConstituent(); if (particle) { maxTrackPt = particle->Pt(); } } if (leadingHadronType == kNeutral || leadingHadronType == kBoth) { // NOTE: We don't want to use jet->MaxNeutralPt() because this uses energy // from the neutral particles at the particle level. While this is not // strictly wrong, it can be rather misleading to have a leading neutral // particle value when we are really interested in the cluster pt that is // only meaningful at detector level. auto cluster = jet->GetLeadingClusterConstituent(); if (cluster) { // Uses the energy definition that was used when the constituent was created // to calculate the Pt(). Usually, this would be the hadronic corrected energy maxClusterPt = cluster->Pt(); } } // The max value will be 0 unless it was filled. Thus, it will only be greater if // it was requested. return (maxTrackPt > maxClusterPt) ? maxTrackPt : maxClusterPt; } /** * Function to calculate angle between jet and EP in the 1st quadrant (0,Pi/2). * Adapted from AliAnalysisTaskEmcalJetHadEPpid. * * @param jetAngle Phi angle of the jet (could be any particle) * @param epAngle Event plane angle * * @return Angle between jet and EP in the 1st quadrant (0,Pi/2) */ double AliAnalysisTaskEmcalJetHUtils::RelativeEPAngle(double jetAngle, double epAngle) { double dphi = (epAngle - jetAngle); // ran into trouble with a few dEP<-Pi so trying this... if( dphi<-1*TMath::Pi() ) { dphi = dphi + 1*TMath::Pi(); } // this assumes we are doing full jets currently if( (dphi>0) && (dphi<1*TMath::Pi()/2) ) { // Do nothing! we are in quadrant 1 } else if ( (dphi>1*TMath::Pi()/2) && (dphi<1*TMath::Pi()) ) { dphi = 1*TMath::Pi() - dphi; } else if ( (dphi<0) && (dphi>-1*TMath::Pi()/2) ) { dphi = std::abs(dphi); } else if ( (dphi<-1*TMath::Pi()/2) && (dphi>-1*TMath::Pi()) ) { dphi = dphi + 1*TMath::Pi(); } // Warn if we are not in the proper range if ( dphi < 0 || dphi > TMath::Pi()/2 ) { AliWarningGeneralStream("AliAnalysisTaskEmcalJetHUtils") << ": dPHI not in range [0, 0.5*Pi]!\n"; } return dphi; // dphi in [0, Pi/2] } /** * Configure an AliEventCuts object with the options in the given AliYAMLConfiguration object and the task trigger mask. * * @param[in] eventCuts AliEventCuts object to configure. * @param[in] yamlConfig %YAML configuration object to be used in configuring the event cuts object. * @param[in] offlineTriggerMask Trigger mask (set via SelectCollisionCandidates()) from the task. The value can be updated by values in the YAML config. * @param[in] baseName Name under which the settings should be looked for in the %YAML config. * @param[in] taskName Name of the analysis task for which this function was called. This is to make it clear which task is being configured. */ void AliAnalysisTaskEmcalJetHUtils::ConfigureEventCuts(AliEventCuts & eventCuts, PWG::Tools::AliYAMLConfiguration & yamlConfig, const UInt_t offlineTriggerMask, const std::string & baseName, const std::string & taskName) { // The trigger can be set regardless of event cuts settings. // Event cuts trigger selection. bool useEventCutsAutomaticTriggerSelection = false; bool res = yamlConfig.GetProperty(std::vector<std::string>({baseName, "useAutomaticTriggerSelection"}), useEventCutsAutomaticTriggerSelection, false); if (res && useEventCutsAutomaticTriggerSelection) { // Use the automatic selection. Nothing to be done. AliInfoGeneralStream(taskName.c_str()) << "Using the automatic trigger selection from AliEventCuts.\n"; } else { // Use the cuts selected by SelectCollisionCandidates() (or via YAML) AliInfoGeneralStream(taskName.c_str()) << "Using the trigger selection specified with SelectCollisionCandidates() or via YAML. Value: " << offlineTriggerMask << "\n"; eventCuts.OverrideAutomaticTriggerSelection(offlineTriggerMask, true); } // Manual mode bool manualMode = false; yamlConfig.GetProperty({baseName, "manualMode"}, manualMode, false); if (manualMode) { AliInfoGeneralStream(taskName.c_str()) << "Configuring manual event cuts.\n"; eventCuts.SetManualMode(); // Configure manual mode via YAML // Select the period typedef void (AliEventCuts::*MFP)(); std::map<std::string, MFP> eventCutsPeriods = { std::make_pair("LHC11h", &AliEventCuts::SetupRun1PbPb), std::make_pair("LHC15o", &AliEventCuts::SetupLHC15o), std::make_pair("LHC18qr", &AliEventCuts::SetupPbPb2018) }; std::string manualCutsPeriod = ""; yamlConfig.GetProperty({ baseName, "cutsPeriod" }, manualCutsPeriod, true); auto eventCutsPeriod = eventCutsPeriods.find(manualCutsPeriod); if (eventCutsPeriod != eventCutsPeriods.end()) { // Call event cuts period setup. (eventCuts.*eventCutsPeriod->second)(); AliDebugGeneralStream(taskName.c_str(), 3) << "Configuring event cuts with period \"" << manualCutsPeriod << "\"\n"; } else { AliFatalGeneralF(taskName.c_str(), "Period %s was not found in the event cuts period map.", manualCutsPeriod.c_str()); } // Additional settings must be after setting the period to ensure that the settings aren't overwritten. // Centrality std::pair<double, double> centRange; res = yamlConfig.GetProperty({ baseName, "centralityRange" }, centRange, false); if (res) { AliDebugGeneralStream(taskName.c_str(), 3) << "Setting centrality range of (" << centRange.first << ", " << centRange.second << ").\n"; eventCuts.SetCentralityRange(centRange.first, centRange.second); } // MC bool mc = false; yamlConfig.GetProperty({ baseName, "MC" }, mc, false); eventCuts.fMC = mc; // Set the 15o pileup cuts. Defaults to on. if (manualCutsPeriod == "LHC15o") { bool enablePileupCuts = true; yamlConfig.GetProperty({ baseName, "enablePileupCuts" }, enablePileupCuts, false); AliDebugGeneralStream(taskName.c_str(), 3) << "Setting 15o pileup cuts to " << std::boolalpha << enablePileupCuts << ".\n"; eventCuts.fUseVariablesCorrelationCuts = enablePileupCuts; } } } /** * Utility function to create a particle or track container given the collection name of the desired container. * * @param[in] collectionName Name of the particle or track collection name. * * @return A newly created particle or track container. */ AliParticleContainer * AliAnalysisTaskEmcalJetHUtils::CreateParticleOrTrackContainer(const std::string & collectionName) { AliParticleContainer * partCont = nullptr; if (collectionName == AliEmcalContainerUtils::DetermineUseDefaultName(AliEmcalContainerUtils::kTrack)) { AliTrackContainer * trackCont = new AliTrackContainer(collectionName.c_str()); partCont = trackCont; } else if (collectionName != "") { partCont = new AliParticleContainer(collectionName.c_str()); } return partCont; } /** * Configure an EMCal container according to the specified YAML configuration. * * @param[in] baseName Name under which the config is stored, with the container name included. * @param[in] containerName Name of the container. * @param[in] cont Existing particle container. * @param[in] yamlConfig YAML configuration to be used. * @param[in] taskName Name of the task which is calling this function (for logging purposes). */ void AliAnalysisTaskEmcalJetHUtils::ConfigureEMCalContainersFromYAMLConfig(std::vector<std::string> baseName, std::string containerName, AliEmcalContainer* cont, PWG::Tools::AliYAMLConfiguration& yamlConfig, std::string taskName) { // Initial setup cont->SetName(containerName.c_str()); // Set the properties double tempDouble = -1.0; bool tempBool = false; std::vector<double> tempRange; // Min Pt bool result = yamlConfig.GetProperty(baseName, "minPt", tempDouble, false); if (result) { AliDebugGeneralStream(taskName.c_str(), 2) << cont->GetName() << ": Setting minPt of " << tempDouble << "\n"; cont->SetMinPt(tempDouble); } // Min E result = yamlConfig.GetProperty(baseName, "minE", tempDouble, false); if (result) { AliDebugGeneralStream(taskName.c_str(), 2) << cont->GetName() << ": Setting minE of " << tempDouble << "\n"; cont->SetMinE(tempDouble); } // Eta min, max result = yamlConfig.GetProperty(baseName, "etaLimits", tempRange, false); if (result) { if (tempRange.size() != 2) { AliErrorGeneralStream(taskName.c_str()) << "Passed eta range with " << tempRange.size() << " entries, but 2 values are required. Ignoring values.\n"; } else { AliDebugGeneralStream(taskName.c_str(), 2) << "Setting eta range to [" << tempRange.at(0) << ", " << tempRange.at(1) << "]\n"; cont->SetEtaLimits(tempRange.at(0), tempRange.at(1)); } } // Phi min, max result = yamlConfig.GetProperty(baseName, "phiLimits", tempRange, false); if (result) { if (tempRange.size() != 2) { AliErrorGeneralStream(taskName.c_str()) << "Passed phi range with " << tempRange.size() << " entries, but 2 values are required. Ignoring values.\n"; } else { AliDebugGeneralStream(taskName.c_str(), 2) << "Setting phi range to [" << tempRange.at(0) << ", " << tempRange.at(1) << "]\n"; cont->SetPhiLimits(tempRange.at(0), tempRange.at(1)); } } // Embedded result = yamlConfig.GetProperty(baseName, "embedding", tempBool, false); if (result) { AliDebugGeneralStream(taskName.c_str(), 2) << cont->GetName() << ": Setting embedding to " << (tempBool ? "enabled" : "disabled") << "\n"; cont->SetIsEmbedding(tempBool); } } /** * Configure a track container according to the specified YAML configuration. * * @param[in] baseNameWithhContainer Name under which the config is stored, with the container name included. * @param[in] trackCont Existing particle container. * @param[in] yamlConfig YAML configuration to be used. * @param[in] taskName Name of the task which is calling this function (for logging purposes). */ void AliAnalysisTaskEmcalJetHUtils::ConfigureTrackContainersFromYAMLConfig( std::vector<std::string> baseNameWithContainer, AliTrackContainer* trackCont, PWG::Tools::AliYAMLConfiguration& yamlConfig, std::string taskName) { // Initial setup std::string tempString = ""; // Track selection // AOD Filter bits as a sequence std::vector<UInt_t> filterBitsVector; bool result = yamlConfig.GetProperty(baseNameWithContainer, "aodFilterBits", filterBitsVector, false); if (result) { UInt_t filterBits = 0; for (int filterBit : filterBitsVector) { filterBits += filterBit; } AliDebugGeneralStream(taskName.c_str(), 2) << trackCont->GetName() << ": Setting filterBits of " << filterBits << "\n"; trackCont->SetAODFilterBits(filterBits); } // SetTrackFilterType enum result = yamlConfig.GetProperty(baseNameWithContainer, "trackFilterType", tempString, false); if (result) { // Need to get the enumeration AliEmcalTrackSelection::ETrackFilterType_t trackFilterType = AliTrackContainer::fgkTrackFilterTypeMap.at(tempString); AliDebugGeneralStream(taskName.c_str(), 2) << trackCont->GetName() << ": Setting trackFilterType of " << trackFilterType << " (" << tempString << ")\n"; trackCont->SetTrackFilterType(trackFilterType); } // Track cuts period result = yamlConfig.GetProperty(baseNameWithContainer, "trackCutsPeriod", tempString, false); if (result) { // Need to get the enumeration AliDebugGeneralStream(taskName.c_str(), 2) << trackCont->GetName() << ": Setting track cuts period to " << tempString << "\n"; trackCont->SetTrackCutsPeriod(tempString.c_str()); } } /** * Configure a cluster container according to the specified YAML configuration. * * @param[in] baseNameWithhContainer Name under which the config is stored, with the container name included. * @param[in] clusterCont Existing cluster container. * @param[in] yamlConfig YAML configuration to be used. * @param[in] taskName Name of the task which is calling this function (for logging purposes). */ void AliAnalysisTaskEmcalJetHUtils::ConfigureClusterContainersFromYAMLConfig( std::vector<std::string> baseNameWithContainer, AliClusterContainer* clusterCont, PWG::Tools::AliYAMLConfiguration& yamlConfig, std::string taskName) { // Initial setup double tempDouble = 0; std::string tempString = ""; bool tempBool = false; // Default energy bool result = yamlConfig.GetProperty(baseNameWithContainer, "defaultClusterEnergy", tempString, false); if (result) { // Need to get the enumeration AliVCluster::VCluUserDefEnergy_t clusterEnergyType = AliClusterContainer::fgkClusterEnergyTypeMap.at(tempString); AliDebugGeneralStream(taskName.c_str(), 2) << clusterCont->GetName() << ": Setting cluster energy type to " << clusterEnergyType << "\n"; clusterCont->SetDefaultClusterEnergy(clusterEnergyType); } // NonLinCorrEnergyCut result = yamlConfig.GetProperty(baseNameWithContainer, "clusNonLinCorrEnergyCut", tempDouble, false); if (result) { AliDebugGeneralStream(taskName.c_str(), 2) << clusterCont->GetName() << ": Setting clusNonLinCorrEnergyCut of " << tempDouble << "\n"; clusterCont->SetClusNonLinCorrEnergyCut(tempDouble); } // HadCorrEnergyCut result = yamlConfig.GetProperty(baseNameWithContainer, "clusHadCorrEnergyCut", tempDouble, false); if (result) { AliDebugGeneralStream(taskName.c_str(), 2) << clusterCont->GetName() << ": Setting clusHadCorrEnergyCut of " << tempDouble << "\n"; clusterCont->SetClusHadCorrEnergyCut(tempDouble); } // SetIncludePHOS result = yamlConfig.GetProperty(baseNameWithContainer, "includePHOS", tempBool, false); if (result) { AliDebugGeneralStream(taskName.c_str(), 2) << clusterCont->GetName() << ": Setting Include PHOS to " << (tempBool ? "enabled" : "disabled") << "\n"; clusterCont->SetIncludePHOS(tempBool); } } /** * Determines the jet acceptance that is retrieved from a YAML configuration. Note that the result is an OR of * all of the individual acceptances selected in the input. * * @return The desired jet acceptance. Note that a `UInt_t` is explicitly passed for the acceptance, so it's fine to return it here. */ UInt_t AliAnalysisTaskEmcalJetHUtils::DetermineJetAcceptanceFromYAML(const std::vector<std::string> & selections) { UInt_t jetAcceptance = 0; for (auto selection : selections) { auto sel = fgkJetAcceptanceMap.find(selection); AliDebugGeneralStream("AliAnalysisTaskEmcalJetHUtils", 3) << "Adding jet acceptance: " << selection << "\n"; if (sel != fgkJetAcceptanceMap.end()) { jetAcceptance |= sel->second; } else { AliFatalGeneralF("AliAnalysisTaskEmcalJetHUtils", "Could not find jet acceptance with key \"%s\"", selection.c_str()); } } return jetAcceptance; } /** * AddTask for Qn flow vector corrections. The AddTask `AddTaskFlowQnVectorCorrectionsNewDetConfig.C` * provides the right options, but it enables the calibration and event histograms, apparently without * the ability to turn them off. This is problematic, because the output size is quite large. This AddTask * will allow for the additional histograms to be turned off. The only purpose of this AddTask is to make * those options configurable. * * In order to make this AddTask compileable, a number of other minor changes were required. * * Note that this function uses a YAML configuration file instead of the frameworks configuration method. * This is done solely for convenience and to cut down on the options that don't matter when just running * the task on the LEGO train. * * @param[in] configFilename Filename and path of the YAML configuration file. * @returns AliAnalysisTaskFlowVectorCorrections object configured to provide corrected Qn vectors. */ AliAnalysisTaskFlowVectorCorrections* AliAnalysisTaskEmcalJetHUtils::AddTaskFlowQnVectorCorrections( const std::string& configFilename) { AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskFlowQnVectorCorrections", "No analysis manager found."); return 0; } // Create the correction task and manager AliQnCorrectionsManager* QnManager = new AliQnCorrectionsManager(); AliAnalysisTaskFlowVectorCorrections* taskQnCorrections = new AliAnalysisTaskFlowVectorCorrections("FlowQnVectorCorrections"); // Determine the task configuration PWG::Tools::AliYAMLConfiguration yamlConfig; yamlConfig.AddConfiguration(configFilename, "config"); std::string baseName = ""; // General configuration // Use VZERO centrality or multiplicity percentile for centrality determination // Use centrality for 2010 (and 2011?), use multiplicity of 2015 (ie. run 2) bool useMultiplicityPercentileForCentralityDetermination = true; yamlConfig.GetProperty("useMultiplicityPercentileForCentralityDetermination", useMultiplicityPercentileForCentralityDetermination, true); AliQnCorrectionsVarManagerTask::Variables varForEventMultiplicity = AliQnCorrectionsVarManagerTask::kCentVZERO; if (useMultiplicityPercentileForCentralityDetermination) { varForEventMultiplicity = AliQnCorrectionsVarManagerTask::kVZEROMultPercentile; } // Select the Z vertex, centrality for when to calibrate (and correct?). std::pair<double, double> zVertexRange; yamlConfig.GetProperty("zVertex", zVertexRange, true); std::pair<double, double> centRange; yamlConfig.GetProperty("centrality", centRange, true); // Select only events validated for centrality calibration // Check information about your runs of interest in // https://twiki.cern.ch/twiki/bin/viewauth/ALICE/AliMultSelectionCalibStatus. // Learn more about its usage in https://twiki.cern.ch/twiki/bin/viewauth/ALICE/CentralityCodeSnippets bool useOnlyCentralityCalibratedEvents = false; yamlConfig.GetProperty("useOnlyCentralityCalibratedEvents", useOnlyCentralityCalibratedEvents, true); // Select runs to use when gather calibration data. std::vector<std::string> listOfRuns; yamlConfig.GetProperty("runsToUseDuringCalibration", listOfRuns, false); // Physics selection. Defaults to kAnyINT std::vector<std::string> physicsSelection; bool res = yamlConfig.GetProperty("physicsSelection", physicsSelection, false); if (res) { taskQnCorrections->SelectCollisionCandidates( AliEmcalContainerUtils::DeterminePhysicsSelectionFromYAML(physicsSelection)); } else { // Defaults to using kAnyINT taskQnCorrections->SelectCollisionCandidates(AliVEvent::kAnyINT); } // Location of correction histograms baseName = "correctionHistograms"; std::string correctionsSource = ""; yamlConfig.GetProperty({ baseName, "source" }, correctionsSource, true); std::string correctionsFilePath = ""; yamlConfig.GetProperty({ baseName, "path" }, correctionsFilePath, true); std::string correctionsFileName = ""; yamlConfig.GetProperty({ baseName, "filename" }, correctionsFileName, true); // Detector configuration (optional - all are off by default) baseName = "detectors"; bool useTPC = false; yamlConfig.GetProperty({ baseName, "TPC" }, useTPC, false); bool useSPD = false; yamlConfig.GetProperty({ baseName, "SPD" }, useSPD, false); bool useVZERO = false; yamlConfig.GetProperty({ baseName, "VZERO" }, useVZERO, false); bool useTZERO = false; yamlConfig.GetProperty({ baseName, "TZERO" }, useTZERO, false); bool useFMD = false; yamlConfig.GetProperty({ baseName, "FMD" }, useFMD, false); bool useRawFMD = false; yamlConfig.GetProperty({ baseName, "RawFMD" }, useRawFMD, false); bool useZDC = false; yamlConfig.GetProperty({ baseName, "ZDC" }, useZDC, false); // Outputs configuration baseName = "outputs"; bool fillQVectorTree = false; yamlConfig.GetProperty({ baseName, "QVectorTree" }, fillQVectorTree, false); bool fillQAHistograms = true; yamlConfig.GetProperty({ baseName, "QAHistograms" }, fillQAHistograms, false); bool fillNveQAHistograms = true; yamlConfig.GetProperty({ baseName, "NveQAHistograms" }, fillNveQAHistograms, false); bool fillOutputHistograms = true; yamlConfig.GetProperty({ baseName, "OutputHistograms" }, fillOutputHistograms, false); bool fillExchangeContainerWithQvectors = true; yamlConfig.GetProperty({ baseName, "ExchangeContainerWithQvectors" }, fillExchangeContainerWithQvectors, false); bool fillEventQA = true; yamlConfig.GetProperty({ baseName, "EventQA" }, fillEventQA, false); // Create a string to describe the configuration. // It allows the user to verify that the configuration was accessed successfully and that the // values were extracted into the proper variables. std::stringstream tempSS; tempSS << std::boolalpha; tempSS << "Flow Qn vector corrections configuration:\n"; tempSS << "Use multiplicity percentile for centrality determination: " << useMultiplicityPercentileForCentralityDetermination << "\n"; tempSS << "Z vertex: [" << zVertexRange.first << ", " << zVertexRange.second << "]\n"; tempSS << "Centrality: [" << centRange.first << ", " << centRange.second << "]\n"; tempSS << "Use only centrality calibrated events: " << useOnlyCentralityCalibratedEvents << "\n"; tempSS << "Runs to use during calibration:\n"; bool atLeastOneRun = false; for (const auto& run : listOfRuns) { atLeastOneRun = true; tempSS << "\t" << run << "\n"; } if (!atLeastOneRun) { tempSS << "\tNone\n"; } tempSS << "Physics selection: " << taskQnCorrections->GetCollisionCandidates() << "\n"; tempSS << "Correction histograms:\n"; tempSS << "\tSource: " << correctionsSource << "\n"; tempSS << "\tPath: " << correctionsFilePath << "\n"; tempSS << "\tName: " << correctionsFileName << "\n"; tempSS << "Detectors:\n"; tempSS << "\tTPC: " << useTPC << "\n"; tempSS << "\tSPD: " << useSPD << "\n"; tempSS << "\tVZERO: " << useVZERO << "\n"; tempSS << "\tTZERO: " << useTZERO << "\n"; tempSS << "\tFMD: " << useFMD << "\n"; tempSS << "\tRaw FMD: " << useRawFMD << "\n"; tempSS << "\tZDC: " << useZDC << "\n"; tempSS << "Outputs:\n"; tempSS << "\tQ vector tree: " << fillQVectorTree << "\n"; tempSS << "\tQA histograms: " << fillQAHistograms << "\n"; tempSS << "\tNve QA histograms: " << fillNveQAHistograms << "\n"; tempSS << "\tOutput histograms: " << fillOutputHistograms << "\n"; tempSS << "\tExchange containers with Q vectors: " << fillExchangeContainerWithQvectors << "\n"; tempSS << "\tEvent QA: " << fillEventQA << "\n"; // Print the task configuration // Print outside of the ALICE Log system to ensure that it is always available! std::cout << tempSS.str(); // Convert list of runs from vector to TObjArray so they can be passed to the task. // Allocate using new so we can pass it into the class. Otherwise, it will segfault because the task attempts // to access the object after it's gone out of scope (instead of copying the TObjArray). TObjArray* listOfRunsTOBJ = new TObjArray(); listOfRunsTOBJ->SetOwner(kTRUE); for (const auto& run : listOfRuns) { listOfRunsTOBJ->Add(new TObjString(run.c_str())); } /* let's establish the event cuts for event selection */ AliQnCorrectionsCutsSet* eventCuts = new AliQnCorrectionsCutsSet(); eventCuts->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kVtxZ, zVertexRange.first, zVertexRange.second)); eventCuts->Add(new AliQnCorrectionsCutWithin(varForEventMultiplicity, centRange.first, centRange.second)); taskQnCorrections->SetEventCuts(eventCuts); taskQnCorrections->SetUseOnlyCentCalibEvents(useOnlyCentralityCalibratedEvents); TString histClass = ""; histClass += "Event_NoCuts;"; histClass += "Event_Analysis;"; histClass += "TrackQA_NoCuts;"; /* add the selected detectors */ if (useTPC) { FlowVectorCorrections::AddTPC(taskQnCorrections, QnManager, varForEventMultiplicity); histClass += "TrackQA_TPC;"; } if (useSPD) { FlowVectorCorrections::AddSPD(taskQnCorrections, QnManager, varForEventMultiplicity); histClass += "TrackletQA_SPD;"; } if (useVZERO) { FlowVectorCorrections::AddVZERO(taskQnCorrections, QnManager, varForEventMultiplicity); } if (useTZERO) { FlowVectorCorrections::AddTZERO(taskQnCorrections, QnManager, varForEventMultiplicity); } if (useFMD) { FlowVectorCorrections::AddFMD(taskQnCorrections, QnManager, varForEventMultiplicity); } if (useRawFMD) { FlowVectorCorrections::AddRawFMD(taskQnCorrections, QnManager, varForEventMultiplicity); } if (useZDC) { FlowVectorCorrections::AddZDC(taskQnCorrections, QnManager, varForEventMultiplicity); } QnManager->SetShouldFillQnVectorTree(fillQVectorTree); QnManager->SetShouldFillQAHistograms(fillQAHistograms); QnManager->SetShouldFillNveQAHistograms(fillNveQAHistograms); QnManager->SetShouldFillOutputHistograms(fillOutputHistograms); taskQnCorrections->SetFillExchangeContainerWithQvectors(fillExchangeContainerWithQvectors); taskQnCorrections->SetFillEventQA(fillEventQA); taskQnCorrections->SetAliQnCorrectionsManager(QnManager); taskQnCorrections->DefineInOutput(); taskQnCorrections->SetRunsLabels(listOfRunsTOBJ); /* let's handle the calibration file */ AliInfoGeneralStream("PWGJE::EMCALJetTasks::AddTaskFlowQnVectorCorrections") << "=================== CALIBRATION FILE =============================================\n"; std::string inputCalibrationFilename = correctionsFilePath + "/" + correctionsFileName; if (correctionsSource == "local") { AliInfoGeneralStream("PWGJE::EMCALJetTasks::AddTaskFlowQnVectorCorrections") << "\t File " << inputCalibrationFilename << "\n\t being taken locally when building the task object.\n"; taskQnCorrections->SetCalibrationHistogramsFile(AliAnalysisTaskFlowVectorCorrections::CALIBSRC_local, inputCalibrationFilename.c_str()); } else if (correctionsSource == "aliensingle") { AliInfoGeneralStream("PWGJE::EMCALJetTasks::AddTaskFlowQnVectorCorrections") << "\t File " << inputCalibrationFilename << " being taken from alien in the execution nodes\n"; taskQnCorrections->SetCalibrationHistogramsFile(AliAnalysisTaskFlowVectorCorrections::CALIBSRC_aliensingle, inputCalibrationFilename.c_str()); } else if (correctionsSource == "alienmultiple") { AliInfoGeneralStream("PWGJE::EMCALJetTasks::AddTaskFlowQnVectorCorrections") << "\t File " << inputCalibrationFilename << " being taken from alien in the execution nodes on a per run basis\n"; taskQnCorrections->SetCalibrationHistogramsFile(AliAnalysisTaskFlowVectorCorrections::CALIBSRC_alienmultiple, inputCalibrationFilename.c_str()); } else if (correctionsSource == "OADBsingle") { AliInfoGeneralStream("PWGJE::EMCALJetTasks::AddTaskFlowQnVectorCorrections") << "\t File " << inputCalibrationFilename << " being taken from OADB in the execution nodes\n"; taskQnCorrections->SetCalibrationHistogramsFile(AliAnalysisTaskFlowVectorCorrections::CALIBSRC_OADBsingle, inputCalibrationFilename.c_str()); } else if (correctionsSource == "OADBmultiple") { AliInfoGeneralStream("PWGJE::EMCALJetTasks::AddTaskFlowQnVectorCorrections") << "\t File " << inputCalibrationFilename << " being taken from OADB in the execution nodes on a per run basis\n"; taskQnCorrections->SetCalibrationHistogramsFile(AliAnalysisTaskFlowVectorCorrections::CALIBSRC_OADBmultiple, inputCalibrationFilename.c_str()); } else { AliErrorGeneralStream("AddTaskFlowQnVectorCorrections") << "\t CALIBRATION FILE SOURCE NOT SUPPORTED. ABORTING!!!"; return NULL; } AliInfoGeneralStream("PWGJE::EMCALJetTasks::AddTaskFlowQnVectorCorrections") << "==================================================================================\n"; AliQnCorrectionsHistos* hists = taskQnCorrections->GetEventHistograms(); FlowVectorCorrections::DefineHistograms(QnManager, hists, histClass); mgr->AddTask(taskQnCorrections); mgr->ConnectInput(taskQnCorrections, 0, mgr->GetCommonInputContainer()); // create output containers if (QnManager->GetShouldFillOutputHistograms()) { AliAnalysisDataContainer* cOutputHist = mgr->CreateContainer(QnManager->GetCalibrationHistogramsContainerName(), TList::Class(), AliAnalysisManager::kOutputContainer, "CalibrationHistograms.root"); mgr->ConnectOutput(taskQnCorrections, taskQnCorrections->OutputSlotHistQn(), cOutputHist); } if (QnManager->GetShouldFillQnVectorTree()) { AliAnalysisDataContainer* cOutputQvec = mgr->CreateContainer( "CalibratedQvector", TTree::Class(), AliAnalysisManager::kOutputContainer, "QvectorsTree.root"); mgr->ConnectOutput(taskQnCorrections, taskQnCorrections->OutputSlotTree(), cOutputQvec); } if (QnManager->GetShouldFillQAHistograms()) { AliAnalysisDataContainer* cOutputHistQA = mgr->CreateContainer(QnManager->GetCalibrationQAHistogramsContainerName(), TList::Class(), AliAnalysisManager::kOutputContainer, "CalibrationQA.root"); mgr->ConnectOutput(taskQnCorrections, taskQnCorrections->OutputSlotHistQA(), cOutputHistQA); } if (QnManager->GetShouldFillNveQAHistograms()) { AliAnalysisDataContainer* cOutputHistNveQA = mgr->CreateContainer(QnManager->GetCalibrationNveQAHistogramsContainerName(), TList::Class(), AliAnalysisManager::kOutputContainer, "CalibrationQA.root"); mgr->ConnectOutput(taskQnCorrections, taskQnCorrections->OutputSlotHistNveQA(), cOutputHistNveQA); } if (taskQnCorrections->GetFillEventQA()) { AliAnalysisDataContainer* cOutputQnEventQA = mgr->CreateContainer("QnEventQA", TList::Class(), AliAnalysisManager::kOutputContainer, "QnEventQA.root"); mgr->ConnectOutput(taskQnCorrections, taskQnCorrections->OutputSlotEventQA(), cOutputQnEventQA); } AliAnalysisDataContainer* cOutputQvecList = mgr->CreateContainer( "CalibratedQvectorList", TList::Class(), AliAnalysisManager::kExchangeContainer, "QvectorsList.root"); if (taskQnCorrections->GetFillExchangeContainerWithQvectors()) mgr->ConnectOutput(taskQnCorrections, taskQnCorrections->OutputSlotGetListQnVectors(), cOutputQvecList); return taskQnCorrections; } /** * Get the background subtracted jet pt. * * @param[in] jet Jet to be subtracted. * @param[in] rho Rho value for the jet collection. * @returns The rho corrected jet pt (or just the raw jet pt if no rho value is provided). */ double AliAnalysisTaskEmcalJetHUtils::GetJetPt(const AliEmcalJet* jet, const double rho) { double pT = jet->Pt() - rho * jet->Area(); return pT; } /** * Calculate the tracking efficiency for LHC11h - run 1 PbPb at 2.76 TeV. See Joel's jet-hadron analysis note. * * @param[in] trackPt Track pt * @param[in] trackEta Track eta * @param[in] centralityBin Centrality bin of the current event. * @param[in] taskName Name of the task which is calling this function (for logging purposes). * @returns The efficiency of measuring the given single track. */ double AliAnalysisTaskEmcalJetHUtils::LHC11hTrackingEfficiency(const double trackPt, const double trackEta, const int centralityBin, const std::string & taskName) { // Setup double etaAxis = 0; double ptAxis = 0; double efficiency = 1; // Assumes that the centrality bins follow (as defined in AliAnalysisTaskEmcal) // 0 = 0-10% // 1 = 10-30% // 2 = 30-50% // 3 = 50-90% switch (centralityBin) { case 0 : // Parameter values for GOOD TPC (LHC11h) runs (0-10%): ptAxis = (trackPt < 2.9) * (LHC11hParam_0_10[0] * exp(-pow(LHC11hParam_0_10[1] / trackPt, LHC11hParam_0_10[2])) + LHC11hParam_0_10[3] * trackPt) + (trackPt >= 2.9) * (LHC11hParam_0_10[4] + LHC11hParam_0_10[5] * trackPt + LHC11hParam_0_10[6] * trackPt * trackPt); etaAxis = (trackEta < 0.0) * (LHC11hParam_0_10[7] * exp(-pow(LHC11hParam_0_10[8] / std::abs(trackEta + 0.91), LHC11hParam_0_10[9])) + LHC11hParam_0_10[10] * trackEta) + (trackEta >= 0.0 && trackEta <= 0.4) * (LHC11hParam_0_10[11] + LHC11hParam_0_10[12] * trackEta + LHC11hParam_0_10[13] * trackEta * trackEta) + (trackEta > 0.4) * (LHC11hParam_0_10[14] * exp(-pow(LHC11hParam_0_10[15] / std::abs(-trackEta + 0.91), LHC11hParam_0_10[16]))); efficiency = ptAxis * etaAxis; break; case 1: // Parameter values for GOOD TPC (LHC11h) runs (10-30%): ptAxis = (trackPt < 2.9) * (LHC11hParam_10_30[0] * exp(-pow(LHC11hParam_10_30[1] / trackPt, LHC11hParam_10_30[2])) + LHC11hParam_10_30[3] * trackPt) + (trackPt >= 2.9) * (LHC11hParam_10_30[4] + LHC11hParam_10_30[5] * trackPt + LHC11hParam_10_30[6] * trackPt * trackPt); etaAxis = (trackEta < 0.0) * (LHC11hParam_10_30[7] * exp(-pow(LHC11hParam_10_30[8] / std::abs(trackEta + 0.91), LHC11hParam_10_30[9])) + LHC11hParam_10_30[10] * trackEta) + (trackEta >= 0.0 && trackEta <= 0.4) * (LHC11hParam_10_30[11] + LHC11hParam_10_30[12] * trackEta + LHC11hParam_10_30[13] * trackEta * trackEta) + (trackEta > 0.4) * (LHC11hParam_10_30[14] * exp(-pow(LHC11hParam_10_30[15] / std::abs(-trackEta + 0.91), LHC11hParam_10_30[16]))); efficiency = ptAxis * etaAxis; break; case 2: // Parameter values for GOOD TPC (LHC11h) runs (30-50%): ptAxis = (trackPt < 2.9) * (LHC11hParam_30_50[0] * exp(-pow(LHC11hParam_30_50[1] / trackPt, LHC11hParam_30_50[2])) + LHC11hParam_30_50[3] * trackPt) + (trackPt >= 2.9) * (LHC11hParam_30_50[4] + LHC11hParam_30_50[5] * trackPt + LHC11hParam_30_50[6] * trackPt * trackPt); etaAxis = (trackEta < 0.0) * (LHC11hParam_30_50[7] * exp(-pow(LHC11hParam_30_50[8] / std::abs(trackEta + 0.91), LHC11hParam_30_50[9])) + LHC11hParam_30_50[10] * trackEta) + (trackEta >= 0.0 && trackEta <= 0.4) * (LHC11hParam_30_50[11] + LHC11hParam_30_50[12] * trackEta + LHC11hParam_30_50[13] * trackEta * trackEta) + (trackEta > 0.4) * (LHC11hParam_30_50[14] * exp(-pow(LHC11hParam_30_50[15] / std::abs(-trackEta + 0.91), LHC11hParam_30_50[16]))); efficiency = ptAxis * etaAxis; break; case 3: // Parameter values for GOOD TPC (LHC11h) runs (50-90%): ptAxis = (trackPt < 2.9) * (LHC11hParam_50_90[0] * exp(-pow(LHC11hParam_50_90[1] / trackPt, LHC11hParam_50_90[2])) + LHC11hParam_50_90[3] * trackPt) + (trackPt >= 2.9) * (LHC11hParam_50_90[4] + LHC11hParam_50_90[5] * trackPt + LHC11hParam_50_90[6] * trackPt * trackPt); etaAxis = (trackEta < 0.0) * (LHC11hParam_50_90[7] * exp(-pow(LHC11hParam_50_90[8] / std::abs(trackEta + 0.91), LHC11hParam_50_90[9])) + LHC11hParam_50_90[10] * trackEta) + (trackEta >= 0.0 && trackEta <= 0.4) * (LHC11hParam_50_90[11] + LHC11hParam_50_90[12] * trackEta + LHC11hParam_50_90[13] * trackEta * trackEta) + (trackEta > 0.4) * (LHC11hParam_50_90[14] * exp(-pow(LHC11hParam_50_90[15] / std::abs(-trackEta + 0.91), LHC11hParam_50_90[16]))); efficiency = ptAxis * etaAxis; break; default: AliErrorGeneralStream(taskName.c_str()) << "Invalid centrality for determine tracking efficiency.\n"; efficiency = 0; } return efficiency; } /** * Determine the pt efficiency axis for LHC15o. This is the main interface * for getting the efficiency. * * @param[in] trackEta Track eta. * @param[in] params Parameters for use with the function. * @returns The efficiency associated with the eta parameterization. */ double AliAnalysisTaskEmcalJetHUtils::LHC15oPtEfficiency(const double trackPt, const double params[10]) { return ((trackPt <= 3.5) * LHC15oLowPtEfficiencyImpl(trackPt, params, 0) + (trackPt > 3.5) * LHC15oHighPtEfficiencyImpl(trackPt, params, 5)); } /** * Determine the pt efficiency axis for low pt tracks in LHC15o. Implementation function. * * @param[in] trackEta Track eta. * @param[in] params Parameters for use with the function. * @param[in] index Index where it should begin accessing the parameters. * @returns The efficiency associated with the eta parameterization. */ double AliAnalysisTaskEmcalJetHUtils::LHC15oLowPtEfficiencyImpl(const double trackPt, const double params[10], const int index) { return (params[index + 0] + -1.0 * params[index + 1] / trackPt) + params[index + 2] * TMath::Gaus(trackPt, params[index + 3], params[index + 4]); } /** * Determine the pt efficiency axis for high pt tracks in LHC15o. Implementation function. * * @param[in] trackEta Track eta. * @param[in] params Parameters for use with the function. * @param[in] index Index where it should begin accessing the parameters. * @returns The efficiency associated with the eta parameterization. */ double AliAnalysisTaskEmcalJetHUtils::LHC15oHighPtEfficiencyImpl(const double trackPt, const double params[10], const int index) { return params[index + 0] + params[index + 1] * trackPt + params[index + 2] * std::pow(trackPt, 2) + params[index + 3] * std::pow(trackPt, 3) + params[index + 4] * std::pow(trackPt, 4); } /** * Determine the eta efficiency axis for LHC15o. * * @param[in] trackEta Track eta. * @param[in] params Parameters for use with the function. * @returns The efficiency associated with the eta parameterization. */ double AliAnalysisTaskEmcalJetHUtils::LHC15oEtaEfficiency(const double trackEta, const double params[13]) { // Just modify the arguments - the function is the same. return ((trackEta <= -0.04) * LHC15oEtaEfficiencyImpl(trackEta, params, 0) + (trackEta > -0.04) * LHC15oEtaEfficiencyImpl(trackEta, params, 6)); } /** * Determine the eta efficiency axis for LHC15o. Implementation function. * * @param[in] trackEta Track eta. * @param[in] params Parameters for use with the function. * @param[in] index Index where it should begin accessing the parameters. * @returns The efficiency associated with the eta parameterization. */ double AliAnalysisTaskEmcalJetHUtils::LHC15oEtaEfficiencyImpl(const double trackEta, const double params[13], const int index) { // We need to multiply the track eta by -1 if we are looking at eta > 0 (which corresponds to // the second set of parameters, such that the index is greater than 0). int sign = index > 0 ? -1 : 1; return (params[index + 0] * std::exp(-1.0 * std::pow(params[index + 1] / std::abs(sign * trackEta + 0.91), params[index + 2])) + params[index + 3] * trackEta + params[index + 4] * TMath::Gaus(trackEta, -0.04, params[index + 5])) / params[12]; } /** * Calculate the track efficiency for LHC15o - PbPb at 5.02 TeV. See the gamma-hadron analysis (from Eliane via Michael). * * @param[in] trackPt Track pt * @param[in] trackEta Track eta * @param[in] centralityBin Centrality bin of the current event. * @param[in] taskName Name of the task which is calling this function (for logging purposes). * @returns The efficiency of measuring the given single track. */ double AliAnalysisTaskEmcalJetHUtils::LHC15oTrackingEfficiency(const double trackPt, const double trackEta, const int centralityBin, const std::string & taskName) { // We use the switch to determine the parameters needed to call the functions. // Assumes that the centrality bins follow (as defined in AliAnalysisTaskEmcal) // 0 = 0-10% // 1 = 10-30% // 2 = 30-50% // 3 = 50-90% const double* ptParams = nullptr; const double* etaParams = nullptr; switch (centralityBin) { case 0: ptParams = LHC15oParam_0_10_pt; etaParams = LHC15oParam_0_10_eta; break; case 1: ptParams = LHC15oParam_10_30_pt; etaParams = LHC15oParam_10_30_eta; break; case 2: ptParams = LHC15oParam_30_50_pt; etaParams = LHC15oParam_30_50_eta; break; case 3: ptParams = LHC15oParam_50_90_pt; etaParams = LHC15oParam_50_90_eta; break; default: AliFatalGeneral(taskName.c_str(), "Invalid centrality for determine tracking efficiency.\n"); } // Calculate the efficiency using the parameters. double ptAxis = LHC15oPtEfficiency(trackPt, ptParams); double etaAxis = LHC15oEtaEfficiency(trackEta, etaParams); double efficiency = ptAxis * etaAxis; return efficiency; } /** * Calculate the track efficiency for LHC11a - pp at 2.76 TeV. Calculated using LHC12f1a. See the jet-hadron * analysis note for more details. * * @param[in] trackPt Track pt * @param[in] trackEta Track eta * @param[in] centralityBin Centrality bin of the current event. * @param[in] taskName Name of the task which is calling this function (for logging purposes). * @returns The efficiency of measuring the given single track. */ double AliAnalysisTaskEmcalJetHUtils::LHC11aTrackingEfficiency(const double trackPt, const double trackEta, const int centralityBin, const std::string & taskName) { // Pt axis // If the trackPt > 6 GeV, then all we need is this coefficient Double_t coefficient = 0.898052; // p6 if (trackPt < 6) { coefficient = (1 + -0.442232 * trackPt // p0 + 0.501831 * std::pow(trackPt, 2) // p1 + -0.252024 * std::pow(trackPt, 3) // p2 + 0.062964 * std::pow(trackPt, 4) // p3 + -0.007681 * std::pow(trackPt, 5) // p4 + 0.000365 * std::pow(trackPt, 6)); // p5 } // Eta axis double efficiency = coefficient * (1 + 0.402825 * std::abs(trackEta) // p7 + -2.213152 * std::pow(trackEta, 2) // p8 + 4.311098 * std::abs(std::pow(trackEta, 3)) // p9 + -2.778200 * std::pow(trackEta, 4)); // p10 return efficiency; } /** * Note that this function relies on the user taking advantage of the centrality binning in ``AliAnalysisTaskEmcal``. If it's * not used, the proper centrality dependent efficiency may not be applied. * * @param[in] trackPt Track pt * @param[in] trackEta Track eta * @param[in] centralityBin Centrality bin of the current event. * @param[in] efficiencyPeriodIdentifier Identifies the efficiency which should be applied. * @param[in] taskName Name of the task which is calling this function (for logging purposes). * @returns The efficiency of measuring the given single track. */ double AliAnalysisTaskEmcalJetHUtils::DetermineTrackingEfficiency( const double trackPt, const double trackEta, const int centralityBin, const EEfficiencyPeriodIdentifier_t efficiencyPeriodIdentifier, const std::string& taskName) { // Efficiency is determined entirely based on the given efficiency period. double efficiency = 1; switch (efficiencyPeriodIdentifier) { case AliAnalysisTaskEmcalJetHUtils::kDisableEff: efficiency = 1; break; case AliAnalysisTaskEmcalJetHUtils::kLHC11h: efficiency = LHC11hTrackingEfficiency(trackPt, trackEta, centralityBin, taskName); break; case AliAnalysisTaskEmcalJetHUtils::kLHC15o: efficiency = LHC15oTrackingEfficiency(trackPt, trackEta, centralityBin, taskName); break; case AliAnalysisTaskEmcalJetHUtils::kLHC11a: efficiency = LHC11aTrackingEfficiency(trackPt, trackEta, centralityBin, taskName); break; case AliAnalysisTaskEmcalJetHUtils::kLHC18qr: case AliAnalysisTaskEmcalJetHUtils::kpA: case AliAnalysisTaskEmcalJetHUtils::kpp: // Intetionally fall through for LHC18, kpA AliFatalGeneral(taskName.c_str(), TString::Format("Tracking efficiency for period identifier %d is not yet implemented.", efficiencyPeriodIdentifier)); break; default: // No efficiency period option selected. Notify the user. // ie. The efficiency correction is disabled. AliErrorGeneralStream(taskName.c_str()) << "No single track efficiency setting selected! Please select one.\n"; efficiency = 0.; } return efficiency; } /** * Add the VZERO configuration. Copied directly from ``AddTaskFlowQnVectorCorrectionsNewDetConfig.h``. */ void FlowVectorCorrections::AddVZERO(AliAnalysisTaskFlowVectorCorrections* task, AliQnCorrectionsManager* QnManager, AliQnCorrectionsVarManagerTask::Variables varForEventMultiplicity) { Bool_t VZEROchannels[4][64]; for (Int_t iv0 = 0; iv0 < 4; iv0++) for (Int_t ich = 0; ich < 64; ich++) VZEROchannels[iv0][ich] = kFALSE; for (Int_t ich = 32; ich < 64; ich++) VZEROchannels[0][ich] = kTRUE; // channel list: kTRUE if channel should be used for (Int_t ich = 0; ich < 32; ich++) VZEROchannels[1][ich] = kTRUE; for (Int_t ich = 0; ich < 64; ich++) VZEROchannels[2][ich] = kTRUE; Int_t channelGroups[64]; for (Int_t ich = 0; ich < 64; ich++) channelGroups[ich] = Int_t(ich / 8); //----------------------------------------------------------- // Our event classes for V0 // const Int_t nVZEROdim = 2; AliQnCorrectionsEventClassVariablesSet* CorrEventClasses = new AliQnCorrectionsEventClassVariablesSet(nVZEROdim); Double_t VtxZbinning[][2] = { { -10.0, 4 }, { -7.0, 1 }, { 7.0, 8 }, { 10.0, 1 } }; Double_t Ctbinning[][2] = { { 0.0, 2 }, { 100.0, 100 } }; CorrEventClasses->Add(new AliQnCorrectionsEventClassVariable( AliQnCorrectionsVarManagerTask::kVtxZ, task->VarName(AliQnCorrectionsVarManagerTask::kVtxZ), VtxZbinning)); CorrEventClasses->Add(new AliQnCorrectionsEventClassVariable( varForEventMultiplicity, Form("Centrality (%s)", task->VarName(varForEventMultiplicity)), Ctbinning)); ////////// end of binning /* the VZERO detector */ AliQnCorrectionsDetector* VZERO = new AliQnCorrectionsDetector("VZERO", AliQnCorrectionsVarManagerTask::kVZERO); /* the VZEROA detector configuration */ AliQnCorrectionsDetectorConfigurationChannels* VZEROAconf = new AliQnCorrectionsDetectorConfigurationChannels("VZEROAQoverM", CorrEventClasses, 64, /* number of channels */ 4); /* number of harmonics: 1, 2, 3 and 4 */ VZEROAconf->SetChannelsScheme(VZEROchannels[0], channelGroups); /* let's configure the Q vector calibration */ VZEROAconf->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverM); /* lets configure the equalization of input data */ AliQnCorrectionsInputGainEqualization* eqA = new AliQnCorrectionsInputGainEqualization(); eqA->SetEqualizationMethod(AliQnCorrectionsInputGainEqualization::GEQUAL_averageEqualization); eqA->SetShift(1.0); eqA->SetScale(0.1); eqA->SetUseChannelGroupsWeights(kTRUE); VZEROAconf->AddCorrectionOnInputData(eqA); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ VZEROAconf->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector alignment correction step */ AliQnCorrectionsQnVectorAlignment* alignA = new AliQnCorrectionsQnVectorAlignment(); alignA->SetHarmonicNumberForAlignment(2); alignA->SetReferenceConfigurationForAlignment("TPCQoverM"); VZEROAconf->AddCorrectionOnQnVector(alignA); /* lets configrure the QA histograms */ VZEROAconf->SetQACentralityVar(varForEventMultiplicity); VZEROAconf->SetQAMultiplicityAxis(100, 0.0, 500.0); /* let's configure the twist and rescale correction step */ AliQnCorrectionsQnVectorTwistAndRescale* twScaleA = new AliQnCorrectionsQnVectorTwistAndRescale(); twScaleA->SetApplyTwist(kTRUE); twScaleA->SetApplyRescale(kTRUE); twScaleA->SetTwistAndRescaleMethod(AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_correlations); twScaleA->SetReferenceConfigurationsForTwistAndRescale("TPCQoverM", "VZEROCQoverM"); /* now we add it to the detector configuration */ VZEROAconf->AddCorrectionOnQnVector(twScaleA); /* add the configuration to the detector */ VZERO->AddDetectorConfiguration(VZEROAconf); /* the VZEROC detector configuration */ AliQnCorrectionsDetectorConfigurationChannels* VZEROCconf = new AliQnCorrectionsDetectorConfigurationChannels("VZEROCQoverM", CorrEventClasses, 64, /* number of channels */ 4); /* number of harmonics: 1, 2, 3 and 4 */ VZEROCconf->SetChannelsScheme(VZEROchannels[1], channelGroups); /* let's configure the Q vector calibration */ VZEROCconf->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverM); /* lets configure the equalization of input data */ AliQnCorrectionsInputGainEqualization* eqC = new AliQnCorrectionsInputGainEqualization(); eqC->SetEqualizationMethod(AliQnCorrectionsInputGainEqualization::GEQUAL_averageEqualization); eqC->SetShift(1.0); eqC->SetScale(0.1); eqC->SetUseChannelGroupsWeights(kTRUE); VZEROCconf->AddCorrectionOnInputData(eqC); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ VZEROCconf->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector alignment correction step */ AliQnCorrectionsQnVectorAlignment* alignC = new AliQnCorrectionsQnVectorAlignment(); alignC->SetHarmonicNumberForAlignment(2); alignC->SetReferenceConfigurationForAlignment("TPCQoverM"); VZEROCconf->AddCorrectionOnQnVector(alignC); /* lets configrure the QA histograms */ VZEROCconf->SetQACentralityVar(varForEventMultiplicity); VZEROCconf->SetQAMultiplicityAxis(100, 0.0, 500.0); /* let's configure the twist and rescale correction step */ AliQnCorrectionsQnVectorTwistAndRescale* twScaleC = new AliQnCorrectionsQnVectorTwistAndRescale(); twScaleC->SetApplyTwist(kTRUE); twScaleC->SetApplyRescale(kTRUE); twScaleC->SetTwistAndRescaleMethod(AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_correlations); twScaleC->SetReferenceConfigurationsForTwistAndRescale("TPCQoverM", "VZEROAQoverM"); /* now we add it to the detector configuration */ VZEROCconf->AddCorrectionOnQnVector(twScaleC); /* add the configuration to the detector */ VZERO->AddDetectorConfiguration(VZEROCconf); /* the full VZERO detector configuration */ AliQnCorrectionsDetectorConfigurationChannels* VZEROconf = new AliQnCorrectionsDetectorConfigurationChannels("VZEROQoverM", CorrEventClasses, 64, /* number of channels */ 4); /* number of harmonics: 1, 2, 3 and 4 */ VZEROconf->SetChannelsScheme(VZEROchannels[2], channelGroups); /* let's configure the Q vector calibration */ VZEROconf->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverM); /* lets configure the equalization of input data */ AliQnCorrectionsInputGainEqualization* eq = new AliQnCorrectionsInputGainEqualization(); eq->SetEqualizationMethod(AliQnCorrectionsInputGainEqualization::GEQUAL_averageEqualization); eq->SetShift(1.0); eq->SetScale(0.1); eq->SetUseChannelGroupsWeights(kTRUE); VZEROconf->AddCorrectionOnInputData(eq); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ VZEROconf->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector alignment correction step */ AliQnCorrectionsQnVectorAlignment* align = new AliQnCorrectionsQnVectorAlignment(); align->SetHarmonicNumberForAlignment(2); align->SetReferenceConfigurationForAlignment("TPCQoverM"); VZEROconf->AddCorrectionOnQnVector(align); /* lets configrure the QA histograms */ VZEROconf->SetQACentralityVar(varForEventMultiplicity); VZEROconf->SetQAMultiplicityAxis(100, 0.0, 500.0); /* let's configure the twist and rescale correction step */ AliQnCorrectionsQnVectorTwistAndRescale* twScale = new AliQnCorrectionsQnVectorTwistAndRescale(); twScale->SetApplyTwist(kTRUE); twScale->SetApplyRescale(kTRUE); twScale->SetTwistAndRescaleMethod(AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_correlations); twScale->SetReferenceConfigurationsForTwistAndRescale("TPCQoverM", "VZEROCQoverM"); /* now we add it to the detector configuration */ VZEROconf->AddCorrectionOnQnVector(twScale); /* add the configuration to the detector */ VZERO->AddDetectorConfiguration(VZEROconf); /* the VZEROA detector configuration */ AliQnCorrectionsDetectorConfigurationChannels* VZEROAconfQoverQlength = new AliQnCorrectionsDetectorConfigurationChannels("VZEROAQoverQlength", CorrEventClasses, 64, /* number of channels */ 4); /* number of harmonics: 1, 2, 3 and 4 */ VZEROAconfQoverQlength->SetChannelsScheme(VZEROchannels[0], channelGroups); /* let's configure the Q vector calibration */ VZEROAconfQoverQlength->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverQlength); /* lets configure the equalization of input data */ AliQnCorrectionsInputGainEqualization* eqAQoverQlength = new AliQnCorrectionsInputGainEqualization(); eqAQoverQlength->SetEqualizationMethod(AliQnCorrectionsInputGainEqualization::GEQUAL_averageEqualization); eqAQoverQlength->SetShift(1.0); eqAQoverQlength->SetScale(0.1); eqAQoverQlength->SetUseChannelGroupsWeights(kTRUE); VZEROAconfQoverQlength->AddCorrectionOnInputData(eqAQoverQlength); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ VZEROAconfQoverQlength->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector alignment correction step */ AliQnCorrectionsQnVectorAlignment* alignAQoverQlength = new AliQnCorrectionsQnVectorAlignment(); alignAQoverQlength->SetHarmonicNumberForAlignment(2); alignAQoverQlength->SetReferenceConfigurationForAlignment("TPCQoverQlength"); VZEROAconfQoverQlength->AddCorrectionOnQnVector(alignAQoverQlength); /* lets configrure the QA histograms */ VZEROAconfQoverQlength->SetQACentralityVar(varForEventMultiplicity); VZEROAconfQoverQlength->SetQAMultiplicityAxis(100, 0.0, 500.0); /* let's configure the twist and rescale correction step */ AliQnCorrectionsQnVectorTwistAndRescale* twScaleAQoverQlength = new AliQnCorrectionsQnVectorTwistAndRescale(); twScaleAQoverQlength->SetApplyTwist(kTRUE); twScaleAQoverQlength->SetApplyRescale(kTRUE); twScaleAQoverQlength->SetTwistAndRescaleMethod(AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_correlations); twScaleAQoverQlength->SetReferenceConfigurationsForTwistAndRescale("TPCQoverQlength", "VZEROCQoverQlength"); /* now we add it to the detector configuration */ VZEROAconfQoverQlength->AddCorrectionOnQnVector(twScaleAQoverQlength); /* add the configuration to the detector */ VZERO->AddDetectorConfiguration(VZEROAconfQoverQlength); /* the VZEROC detector configuration */ AliQnCorrectionsDetectorConfigurationChannels* VZEROCconfQoverQlength = new AliQnCorrectionsDetectorConfigurationChannels("VZEROCQoverQlength", CorrEventClasses, 64, /* number of channels */ 4); /* number of harmonics: 1, 2, 3 and 4 */ VZEROCconfQoverQlength->SetChannelsScheme(VZEROchannels[1], channelGroups); /* let's configure the Q vector calibration */ VZEROCconfQoverQlength->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverQlength); /* lets configure the equalization of input data */ eqAQoverQlength = new AliQnCorrectionsInputGainEqualization(); eqAQoverQlength->SetEqualizationMethod(AliQnCorrectionsInputGainEqualization::GEQUAL_averageEqualization); eqAQoverQlength->SetShift(1.0); eqAQoverQlength->SetScale(0.1); eqAQoverQlength->SetUseChannelGroupsWeights(kTRUE); VZEROCconfQoverQlength->AddCorrectionOnInputData(eqAQoverQlength); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ VZEROCconfQoverQlength->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector alignment correction step */ alignAQoverQlength = new AliQnCorrectionsQnVectorAlignment(); alignAQoverQlength->SetHarmonicNumberForAlignment(2); alignAQoverQlength->SetReferenceConfigurationForAlignment("TPCQoverQlength"); VZEROCconfQoverQlength->AddCorrectionOnQnVector(alignAQoverQlength); /* lets configrure the QA histograms */ VZEROCconfQoverQlength->SetQACentralityVar(varForEventMultiplicity); VZEROCconfQoverQlength->SetQAMultiplicityAxis(100, 0.0, 500.0); /* let's configure the twist and rescale correction step */ twScaleAQoverQlength = new AliQnCorrectionsQnVectorTwistAndRescale(); twScaleAQoverQlength->SetApplyTwist(kTRUE); twScaleAQoverQlength->SetApplyRescale(kTRUE); twScaleAQoverQlength->SetTwistAndRescaleMethod(AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_correlations); twScaleAQoverQlength->SetReferenceConfigurationsForTwistAndRescale("TPCQoverQlength", "VZEROAQoverQlength"); /* now we add it to the detector configuration */ VZEROCconfQoverQlength->AddCorrectionOnQnVector(twScaleAQoverQlength); /* add the configuration to the detector */ VZERO->AddDetectorConfiguration(VZEROCconfQoverQlength); /* the full VZERO detector configuration */ AliQnCorrectionsDetectorConfigurationChannels* VZEROconfQoverQlength = new AliQnCorrectionsDetectorConfigurationChannels("VZEROQoverQlength", CorrEventClasses, 64, /* number of channels */ 4); /* number of harmonics: 1, 2, 3 and 4 */ VZEROconfQoverQlength->SetChannelsScheme(VZEROchannels[2], channelGroups); /* let's configure the Q vector calibration */ VZEROconfQoverQlength->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverQlength); /* lets configure the equalization of input data */ AliQnCorrectionsInputGainEqualization* eqQoverQlength = new AliQnCorrectionsInputGainEqualization(); eqQoverQlength->SetEqualizationMethod(AliQnCorrectionsInputGainEqualization::GEQUAL_averageEqualization); eqQoverQlength->SetShift(1.0); eqQoverQlength->SetScale(0.1); eqQoverQlength->SetUseChannelGroupsWeights(kTRUE); VZEROconfQoverQlength->AddCorrectionOnInputData(eqQoverQlength); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ VZEROconfQoverQlength->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector alignment correction step */ AliQnCorrectionsQnVectorAlignment* alignQoverQlength = new AliQnCorrectionsQnVectorAlignment(); alignQoverQlength->SetHarmonicNumberForAlignment(2); alignQoverQlength->SetReferenceConfigurationForAlignment("TPCQoverQlength"); VZEROconfQoverQlength->AddCorrectionOnQnVector(alignQoverQlength); /* lets configrure the QA histograms */ VZEROconfQoverQlength->SetQACentralityVar(varForEventMultiplicity); VZEROconfQoverQlength->SetQAMultiplicityAxis(100, 0.0, 500.0); /* let's configure the twist and rescale correction step */ AliQnCorrectionsQnVectorTwistAndRescale* twScaleQoverQlength = new AliQnCorrectionsQnVectorTwistAndRescale(); twScaleQoverQlength->SetApplyTwist(kTRUE); twScaleQoverQlength->SetApplyRescale(kTRUE); twScaleQoverQlength->SetTwistAndRescaleMethod(AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_correlations); twScaleQoverQlength->SetReferenceConfigurationsForTwistAndRescale("TPCQoverQlength", "VZEROCQoverQlength"); /* now we add it to the detector configuration */ VZEROconfQoverQlength->AddCorrectionOnQnVector(twScaleQoverQlength); /* add the configuration to the detector */ VZERO->AddDetectorConfiguration(VZEROconfQoverQlength); /* the VZEROA detector configuration */ AliQnCorrectionsDetectorConfigurationChannels* VZEROAconfQoverSqrtM = new AliQnCorrectionsDetectorConfigurationChannels("VZEROAQoverSqrtM", CorrEventClasses, 64, /* number of channels */ 4); /* number of harmonics: 1, 2, 3 and 4 */ VZEROAconfQoverSqrtM->SetChannelsScheme(VZEROchannels[0], channelGroups); /* let's configure the Q vector calibration */ VZEROAconfQoverSqrtM->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverSqrtM); /* lets configure the equalization of input data */ AliQnCorrectionsInputGainEqualization* eqAQoverSqrtM = new AliQnCorrectionsInputGainEqualization(); eqAQoverSqrtM->SetEqualizationMethod(AliQnCorrectionsInputGainEqualization::GEQUAL_averageEqualization); eqAQoverSqrtM->SetShift(1.0); eqAQoverSqrtM->SetScale(0.1); eqAQoverSqrtM->SetUseChannelGroupsWeights(kTRUE); VZEROAconfQoverSqrtM->AddCorrectionOnInputData(eqAQoverSqrtM); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ VZEROAconfQoverSqrtM->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector alignment correction step */ AliQnCorrectionsQnVectorAlignment* alignAQoverSqrtM = new AliQnCorrectionsQnVectorAlignment(); alignAQoverSqrtM->SetHarmonicNumberForAlignment(2); alignAQoverSqrtM->SetReferenceConfigurationForAlignment("TPCQoverSqrtM"); VZEROAconfQoverSqrtM->AddCorrectionOnQnVector(alignAQoverSqrtM); /* lets configrure the QA histograms */ VZEROAconfQoverSqrtM->SetQACentralityVar(varForEventMultiplicity); VZEROAconfQoverSqrtM->SetQAMultiplicityAxis(100, 0.0, 500.0); /* let's configure the twist and rescale correction step */ AliQnCorrectionsQnVectorTwistAndRescale* twScaleAQoverSqrtM = new AliQnCorrectionsQnVectorTwistAndRescale(); twScaleAQoverSqrtM->SetApplyTwist(kTRUE); twScaleAQoverSqrtM->SetApplyRescale(kTRUE); twScaleAQoverSqrtM->SetTwistAndRescaleMethod(AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_correlations); twScaleAQoverSqrtM->SetReferenceConfigurationsForTwistAndRescale("TPCQoverSqrtM", "VZEROCQoverSqrtM"); /* now we add it to the detector configuration */ VZEROAconfQoverSqrtM->AddCorrectionOnQnVector(twScaleAQoverSqrtM); /* add the configuration to the detector */ VZERO->AddDetectorConfiguration(VZEROAconfQoverSqrtM); /* the VZEROC detector configuration */ AliQnCorrectionsDetectorConfigurationChannels* VZEROCconfQoverSqrtM = new AliQnCorrectionsDetectorConfigurationChannels("VZEROCQoverSqrtM", CorrEventClasses, 64, /* number of channels */ 4); /* number of harmonics: 1, 2, 3 and 4 */ VZEROCconfQoverSqrtM->SetChannelsScheme(VZEROchannels[1], channelGroups); /* let's configure the Q vector calibration */ VZEROCconfQoverSqrtM->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverSqrtM); /* lets configure the equalization of input data */ eqAQoverSqrtM = new AliQnCorrectionsInputGainEqualization(); eqAQoverSqrtM->SetEqualizationMethod(AliQnCorrectionsInputGainEqualization::GEQUAL_averageEqualization); eqAQoverSqrtM->SetShift(1.0); eqAQoverSqrtM->SetScale(0.1); eqAQoverSqrtM->SetUseChannelGroupsWeights(kTRUE); VZEROCconfQoverSqrtM->AddCorrectionOnInputData(eqAQoverSqrtM); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ VZEROCconfQoverSqrtM->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector alignment correction step */ alignAQoverSqrtM = new AliQnCorrectionsQnVectorAlignment(); alignAQoverSqrtM->SetHarmonicNumberForAlignment(2); alignAQoverSqrtM->SetReferenceConfigurationForAlignment("TPCQoverSqrtM"); VZEROCconfQoverSqrtM->AddCorrectionOnQnVector(alignAQoverSqrtM); /* lets configrure the QA histograms */ VZEROCconfQoverSqrtM->SetQACentralityVar(varForEventMultiplicity); VZEROCconfQoverSqrtM->SetQAMultiplicityAxis(100, 0.0, 500.0); /* let's configure the twist and rescale correction step */ twScaleAQoverSqrtM = new AliQnCorrectionsQnVectorTwistAndRescale(); twScaleAQoverSqrtM->SetApplyTwist(kTRUE); twScaleAQoverSqrtM->SetApplyRescale(kTRUE); twScaleAQoverSqrtM->SetTwistAndRescaleMethod(AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_correlations); twScaleAQoverSqrtM->SetReferenceConfigurationsForTwistAndRescale("TPCQoverSqrtM", "VZEROAQoverSqrtM"); /* now we add it to the detector configuration */ VZEROCconfQoverSqrtM->AddCorrectionOnQnVector(twScaleAQoverSqrtM); /* add the configuration to the detector */ VZERO->AddDetectorConfiguration(VZEROCconfQoverSqrtM); /* the full VZERO detector configuration */ AliQnCorrectionsDetectorConfigurationChannels* VZEROconfQoverSqrtM = new AliQnCorrectionsDetectorConfigurationChannels("VZEROQoverSqrtM", CorrEventClasses, 64, /* number of channels */ 4); /* number of harmonics: 1, 2, 3 and 4 */ VZEROconfQoverSqrtM->SetChannelsScheme(VZEROchannels[2], channelGroups); /* let's configure the Q vector calibration */ VZEROconfQoverSqrtM->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverSqrtM); /* lets configure the equalization of input data */ AliQnCorrectionsInputGainEqualization* eqQoverSqrtM = new AliQnCorrectionsInputGainEqualization(); eqQoverSqrtM->SetEqualizationMethod(AliQnCorrectionsInputGainEqualization::GEQUAL_averageEqualization); eqQoverSqrtM->SetShift(1.0); eqQoverSqrtM->SetScale(0.1); eqQoverSqrtM->SetUseChannelGroupsWeights(kTRUE); VZEROconfQoverSqrtM->AddCorrectionOnInputData(eqQoverSqrtM); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ VZEROconfQoverSqrtM->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector alignment correction step */ AliQnCorrectionsQnVectorAlignment* alignQoverQoverSqrtM = new AliQnCorrectionsQnVectorAlignment(); alignQoverQoverSqrtM->SetHarmonicNumberForAlignment(2); alignQoverQoverSqrtM->SetReferenceConfigurationForAlignment("TPCQoverSqrtM"); VZEROconfQoverSqrtM->AddCorrectionOnQnVector(alignQoverQoverSqrtM); /* lets configrure the QA histograms */ VZEROconfQoverSqrtM->SetQACentralityVar(varForEventMultiplicity); VZEROconfQoverSqrtM->SetQAMultiplicityAxis(100, 0.0, 500.0); /* let's configure the twist and rescale correction step */ AliQnCorrectionsQnVectorTwistAndRescale* twScaleQoverSqrtM = new AliQnCorrectionsQnVectorTwistAndRescale(); twScaleQoverSqrtM->SetApplyTwist(kTRUE); twScaleQoverSqrtM->SetApplyRescale(kTRUE); twScaleQoverSqrtM->SetTwistAndRescaleMethod(AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_correlations); twScaleQoverSqrtM->SetReferenceConfigurationsForTwistAndRescale("TPCQoverSqrtM", "VZEROCQoverM"); /* now we add it to the detector configuration */ VZEROconfQoverSqrtM->AddCorrectionOnQnVector(twScaleQoverSqrtM); /* add the configuration to the detector */ VZERO->AddDetectorConfiguration(VZEROconfQoverSqrtM); /* finally add the detector to the framework manager */ QnManager->AddDetector(VZERO); } /** * Add the TPC configuration. Copied directly from ``AddTaskFlowQnVectorCorrectionsNewDetConfig.h``. */ void FlowVectorCorrections::AddTPC(AliAnalysisTaskFlowVectorCorrections* task, AliQnCorrectionsManager* QnManager, AliQnCorrectionsVarManagerTask::Variables varForEventMultiplicity) { /////////////// Add TPC subdetectors /////////////////// //----------------------------------------------------------- // Our event classes for TPC // const Int_t nTPCdim = 2; AliQnCorrectionsEventClassVariablesSet* CorrEventClasses = new AliQnCorrectionsEventClassVariablesSet(nTPCdim); Double_t VtxZbinning[][2] = { { -10.0, 4 }, { -7.0, 1 }, { 7.0, 8 }, { 10.0, 1 } }; Double_t Ctbinning[][2] = { { 0.0, 2 }, { 100.0, 100 } }; CorrEventClasses->Add(new AliQnCorrectionsEventClassVariable( AliQnCorrectionsVarManagerTask::kVtxZ, task->VarName(AliQnCorrectionsVarManagerTask::kVtxZ), VtxZbinning)); CorrEventClasses->Add(new AliQnCorrectionsEventClassVariable( varForEventMultiplicity, Form("Centrality (%s)", task->VarName(varForEventMultiplicity)), Ctbinning)); ////////// end of binning /* the TPC detector */ AliQnCorrectionsDetector* TPC = new AliQnCorrectionsDetector("TPC", AliQnCorrectionsVarManagerTask::kTPC); /* the TPC detector configuration */ AliQnCorrectionsDetectorConfigurationTracks* TPCconf = new AliQnCorrectionsDetectorConfigurationTracks( "TPCQoverM", CorrEventClasses, 4); /* number of harmonics: 1, 2, 3 and 4 */ /* let's configure the Q vector calibration */ TPCconf->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverM); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ TPCconf->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector twist correction step */ AliQnCorrectionsQnVectorTwistAndRescale* twScale = new AliQnCorrectionsQnVectorTwistAndRescale(); twScale->SetApplyTwist(kTRUE); twScale->SetApplyRescale(kFALSE); twScale->SetTwistAndRescaleMethod(AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_doubleHarmonic); TPCconf->AddCorrectionOnQnVector(twScale); /* define the cuts to apply */ AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager(); Bool_t isESD = mgr->GetInputEventHandler()->IsA() == AliESDInputHandler::Class(); AliQnCorrectionsCutsSet* cutsTPC = new AliQnCorrectionsCutsSet(); if (!isESD) { cutsTPC->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kFilterBitMask768, 0.5, 1.5)); cutsTPC->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, -0.8, 0.8)); cutsTPC->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); } else { Bool_t UseTPConlyTracks = kFALSE; // Use of TPC standalone tracks or Global tracks (only for ESD analysis) task->SetUseTPCStandaloneTracks(UseTPConlyTracks); if (UseTPConlyTracks) { cutsTPC->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaXY, -3.0, 3.0)); cutsTPC->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaZ, -3.0, 3.0)); cutsTPC->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, -0.8, 0.8)); cutsTPC->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); cutsTPC->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCnclsIter1, 70.0, 161.0)); cutsTPC->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCchi2Iter1, 0.2, 4.0)); } else { cutsTPC->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaXY, -0.3, 0.3)); cutsTPC->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaZ, -0.3, 0.3)); cutsTPC->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, -0.8, 0.8)); cutsTPC->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); cutsTPC->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCncls, 70.0, 161.0)); cutsTPC->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCchi2, 0.2, 4.0)); } } TPCconf->SetCuts(cutsTPC); /* add the configuration to the detector */ TPC->AddDetectorConfiguration(TPCconf); /* the TPC -- negative eta -- detector configuration */ AliQnCorrectionsDetectorConfigurationTracks* TPCNegEtaconf = new AliQnCorrectionsDetectorConfigurationTracks( "TPCNegEtaQoverM", CorrEventClasses, 4); /* number of harmonics: 1, 2, 3 and 4 */ /* let's configure the Q vector calibration */ TPCNegEtaconf->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverM); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ TPCNegEtaconf->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector twist correction step */ AliQnCorrectionsQnVectorTwistAndRescale* twScaleNegEta = new AliQnCorrectionsQnVectorTwistAndRescale(); twScaleNegEta->SetApplyTwist(kTRUE); twScaleNegEta->SetApplyRescale(kFALSE); twScaleNegEta->SetTwistAndRescaleMethod(AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_doubleHarmonic); TPCNegEtaconf->AddCorrectionOnQnVector(twScaleNegEta); /* define the cuts to apply */ isESD = mgr->GetInputEventHandler()->IsA() == AliESDInputHandler::Class(); AliQnCorrectionsCutsSet* cutsTPCNegEta = new AliQnCorrectionsCutsSet(); if (!isESD) { cutsTPCNegEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kFilterBitMask768, 0.5, 1.5)); cutsTPCNegEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, -0.8, 0.)); cutsTPCNegEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); } else { Bool_t UseTPConlyTracks = kFALSE; // Use of TPC standalone tracks or Global tracks (only for ESD analysis) task->SetUseTPCStandaloneTracks(UseTPConlyTracks); if (UseTPConlyTracks) { cutsTPCNegEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaXY, -3.0, 3.0)); cutsTPCNegEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaZ, -3.0, 3.0)); cutsTPCNegEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, -0.8, 0.)); cutsTPCNegEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); cutsTPCNegEta->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCnclsIter1, 70.0, 161.0)); cutsTPCNegEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCchi2Iter1, 0.2, 4.0)); } else { cutsTPCNegEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaXY, -0.3, 0.3)); cutsTPCNegEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaZ, -0.3, 0.3)); cutsTPCNegEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, -0.8, 0.)); cutsTPCNegEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); cutsTPCNegEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCncls, 70.0, 161.0)); cutsTPCNegEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCchi2, 0.2, 4.0)); } } TPCNegEtaconf->SetCuts(cutsTPCNegEta); /* add the configuration to the detector */ TPC->AddDetectorConfiguration(TPCNegEtaconf); /* the TPC -- negative eta -- detector configuration */ AliQnCorrectionsDetectorConfigurationTracks* TPCPosEtaconf = new AliQnCorrectionsDetectorConfigurationTracks( "TPCPosEtaQoverM", CorrEventClasses, 4); /* number of harmonics: 1, 2, 3 and 4 */ /* let's configure the Q vector calibration */ TPCPosEtaconf->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverM); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ TPCPosEtaconf->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector twist correction step */ AliQnCorrectionsQnVectorTwistAndRescale* twScalePosEta = new AliQnCorrectionsQnVectorTwistAndRescale(); twScalePosEta->SetApplyTwist(kTRUE); twScalePosEta->SetApplyRescale(kFALSE); twScalePosEta->SetTwistAndRescaleMethod(AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_doubleHarmonic); TPCPosEtaconf->AddCorrectionOnQnVector(twScalePosEta); /* define the cuts to apply */ isESD = mgr->GetInputEventHandler()->IsA() == AliESDInputHandler::Class(); AliQnCorrectionsCutsSet* cutsTPCPosEta = new AliQnCorrectionsCutsSet(); if (!isESD) { cutsTPCPosEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kFilterBitMask768, 0.5, 1.5)); cutsTPCPosEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, 0., 0.8)); cutsTPCPosEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); } else { Bool_t UseTPConlyTracks = kFALSE; // Use of TPC standalone tracks or Global tracks (only for ESD analysis) task->SetUseTPCStandaloneTracks(UseTPConlyTracks); if (UseTPConlyTracks) { cutsTPCPosEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaXY, -3.0, 3.0)); cutsTPCPosEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaZ, -3.0, 3.0)); cutsTPCPosEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, 0., 0.8)); cutsTPCPosEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); cutsTPCPosEta->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCnclsIter1, 70.0, 161.0)); cutsTPCPosEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCchi2Iter1, 0.2, 4.0)); } else { cutsTPCPosEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaXY, -0.3, 0.3)); cutsTPCPosEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaZ, -0.3, 0.3)); cutsTPCPosEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, 0., 0.8)); cutsTPCPosEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); cutsTPCPosEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCncls, 70.0, 161.0)); cutsTPCPosEta->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCchi2, 0.2, 4.0)); } } TPCPosEtaconf->SetCuts(cutsTPCPosEta); /* add the configuration to the detector */ TPC->AddDetectorConfiguration(TPCPosEtaconf); /* the TPC detector configuration */ AliQnCorrectionsDetectorConfigurationTracks* TPCconfQoverQlength = new AliQnCorrectionsDetectorConfigurationTracks( "TPCQoverQlength", CorrEventClasses, 4); /* number of harmonics: 1, 2, 3 and 4 */ /* let's configure the Q vector calibration */ TPCconfQoverQlength->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverQlength); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ TPCconfQoverQlength->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector twist correction step */ AliQnCorrectionsQnVectorTwistAndRescale* twScaleQoverQlength = new AliQnCorrectionsQnVectorTwistAndRescale(); twScaleQoverQlength->SetApplyTwist(kTRUE); twScaleQoverQlength->SetApplyRescale(kFALSE); twScaleQoverQlength->SetTwistAndRescaleMethod(AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_doubleHarmonic); TPCconfQoverQlength->AddCorrectionOnQnVector(twScaleQoverQlength); /* define the cuts to apply */ isESD = mgr->GetInputEventHandler()->IsA() == AliESDInputHandler::Class(); AliQnCorrectionsCutsSet* cutsTPCQoverQlength = new AliQnCorrectionsCutsSet(); if (!isESD) { cutsTPCQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kFilterBitMask768, 0.5, 1.5)); cutsTPCQoverQlength->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, -0.8, 0.8)); cutsTPCQoverQlength->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); } else { Bool_t UseTPConlyTracks = kFALSE; // Use of TPC standalone tracks or Global tracks (only for ESD analysis) task->SetUseTPCStandaloneTracks(UseTPConlyTracks); if (UseTPConlyTracks) { cutsTPCQoverQlength->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaXY, -3.0, 3.0)); cutsTPCQoverQlength->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaZ, -3.0, 3.0)); cutsTPCQoverQlength->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, -0.8, 0.8)); cutsTPCQoverQlength->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); cutsTPCQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCnclsIter1, 70.0, 161.0)); cutsTPCQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCchi2Iter1, 0.2, 4.0)); } else { cutsTPCQoverQlength->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaXY, -0.3, 0.3)); cutsTPCQoverQlength->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaZ, -0.3, 0.3)); cutsTPCQoverQlength->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, -0.8, 0.8)); cutsTPCQoverQlength->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); cutsTPCQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCncls, 70.0, 161.0)); cutsTPCQoverQlength->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCchi2, 0.2, 4.0)); } } TPCconfQoverQlength->SetCuts(cutsTPCQoverQlength); /* add the configuration to the detector */ TPC->AddDetectorConfiguration(TPCconfQoverQlength); /* the TPC eta < 0 detector configuration */ AliQnCorrectionsDetectorConfigurationTracks* TPCNegEtaconfQoverQlength = new AliQnCorrectionsDetectorConfigurationTracks("TPCNegEtaQoverQlength", CorrEventClasses, 4); /* number of harmonics: 1, 2, 3 and 4 */ /* let's configure the Q vector calibration */ TPCNegEtaconfQoverQlength->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverQlength); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ TPCNegEtaconfQoverQlength->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector twist correction step */ AliQnCorrectionsQnVectorTwistAndRescale* twScaleNegEtaQoverQlength = new AliQnCorrectionsQnVectorTwistAndRescale(); twScaleNegEtaQoverQlength->SetApplyTwist(kTRUE); twScaleNegEtaQoverQlength->SetApplyRescale(kFALSE); twScaleNegEtaQoverQlength->SetTwistAndRescaleMethod( AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_doubleHarmonic); TPCNegEtaconfQoverQlength->AddCorrectionOnQnVector(twScaleNegEtaQoverQlength); /* define the cuts to apply */ isESD = mgr->GetInputEventHandler()->IsA() == AliESDInputHandler::Class(); AliQnCorrectionsCutsSet* cutsTPCNegEtaQoverQlength = new AliQnCorrectionsCutsSet(); if (!isESD) { cutsTPCNegEtaQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kFilterBitMask768, 0.5, 1.5)); cutsTPCNegEtaQoverQlength->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, -0.8, 0.)); cutsTPCNegEtaQoverQlength->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); } else { Bool_t UseTPConlyTracks = kFALSE; // Use of TPC standalone tracks or Global tracks (only for ESD analysis) task->SetUseTPCStandaloneTracks(UseTPConlyTracks); if (UseTPConlyTracks) { cutsTPCNegEtaQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaXY, -3.0, 3.0)); cutsTPCNegEtaQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaZ, -3.0, 3.0)); cutsTPCNegEtaQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, -0.8, 0.)); cutsTPCNegEtaQoverQlength->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); cutsTPCNegEtaQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCnclsIter1, 70.0, 161.0)); cutsTPCNegEtaQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCchi2Iter1, 0.2, 4.0)); } else { cutsTPCNegEtaQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaXY, -0.3, 0.3)); cutsTPCNegEtaQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaZ, -0.3, 0.3)); cutsTPCNegEtaQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, -0.8, 0.)); cutsTPCNegEtaQoverQlength->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); cutsTPCNegEtaQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCncls, 70.0, 161.0)); cutsTPCNegEtaQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCchi2, 0.2, 4.0)); } } TPCNegEtaconfQoverQlength->SetCuts(cutsTPCNegEtaQoverQlength); TPC->AddDetectorConfiguration(TPCNegEtaconfQoverQlength); /* the TPC eta > 0 detector configuration */ AliQnCorrectionsDetectorConfigurationTracks* TPCPosEtaconfQoverQlength = new AliQnCorrectionsDetectorConfigurationTracks("TPCPosEtaQoverQlength", CorrEventClasses, 4); /* number of harmonics: 1, 2, 3 and 4 */ /* let's configure the Q vector calibration */ TPCPosEtaconfQoverQlength->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverQlength); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ TPCPosEtaconfQoverQlength->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector twist correction step */ AliQnCorrectionsQnVectorTwistAndRescale* twScalePosEtaQoverQlength = new AliQnCorrectionsQnVectorTwistAndRescale(); twScalePosEtaQoverQlength->SetApplyTwist(kTRUE); twScalePosEtaQoverQlength->SetApplyRescale(kFALSE); twScalePosEtaQoverQlength->SetTwistAndRescaleMethod( AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_doubleHarmonic); TPCPosEtaconfQoverQlength->AddCorrectionOnQnVector(twScalePosEtaQoverQlength); /* define the cuts to apply */ isESD = mgr->GetInputEventHandler()->IsA() == AliESDInputHandler::Class(); AliQnCorrectionsCutsSet* cutsTPCPosEtaQoverQlength = new AliQnCorrectionsCutsSet(); if (!isESD) { cutsTPCPosEtaQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kFilterBitMask768, 0.5, 1.5)); cutsTPCPosEtaQoverQlength->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, 0., 0.8)); cutsTPCPosEtaQoverQlength->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); } else { Bool_t UseTPConlyTracks = kFALSE; // Use of TPC standalone tracks or Global tracks (only for ESD analysis) task->SetUseTPCStandaloneTracks(UseTPConlyTracks); if (UseTPConlyTracks) { cutsTPCPosEtaQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaXY, -3.0, 3.0)); cutsTPCPosEtaQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaZ, -3.0, 3.0)); cutsTPCPosEtaQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, 0., 0.8)); cutsTPCPosEtaQoverQlength->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); cutsTPCPosEtaQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCnclsIter1, 70.0, 161.0)); cutsTPCPosEtaQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCchi2Iter1, 0.2, 4.0)); } else { cutsTPCPosEtaQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaXY, -0.3, 0.3)); cutsTPCPosEtaQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaZ, -0.3, 0.3)); cutsTPCPosEtaQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, 0., 0.8)); cutsTPCPosEtaQoverQlength->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); cutsTPCPosEtaQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCncls, 70.0, 161.0)); cutsTPCPosEtaQoverQlength->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCchi2, 0.2, 4.0)); } } TPCPosEtaconfQoverQlength->SetCuts(cutsTPCPosEtaQoverQlength); /* add the configuration to the detector */ TPC->AddDetectorConfiguration(TPCPosEtaconfQoverQlength); /* the TPC detector configuration */ AliQnCorrectionsDetectorConfigurationTracks* TPCconfQoverSqrtM = new AliQnCorrectionsDetectorConfigurationTracks( "TPCQoverSqrtM", CorrEventClasses, 4); /* number of harmonics: 1, 2, 3 and 4 */ /* let's configure the Q vector calibration */ TPCconfQoverSqrtM->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverSqrtM); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ TPCconfQoverSqrtM->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector twist correction step */ AliQnCorrectionsQnVectorTwistAndRescale* twScaleQoverSqrtM = new AliQnCorrectionsQnVectorTwistAndRescale(); twScaleQoverSqrtM->SetApplyTwist(kTRUE); twScaleQoverSqrtM->SetApplyRescale(kFALSE); twScaleQoverSqrtM->SetTwistAndRescaleMethod(AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_doubleHarmonic); TPCconfQoverSqrtM->AddCorrectionOnQnVector(twScaleQoverSqrtM); /* define the cuts to apply */ isESD = mgr->GetInputEventHandler()->IsA() == AliESDInputHandler::Class(); AliQnCorrectionsCutsSet* cutsTPCQoverSqrtM = new AliQnCorrectionsCutsSet(); if (!isESD) { cutsTPCQoverSqrtM->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kFilterBitMask768, 0.5, 1.5)); cutsTPCQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, -0.8, 0.8)); cutsTPCQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); } else { Bool_t UseTPConlyTracks = kFALSE; // Use of TPC standalone tracks or Global tracks (only for ESD analysis) task->SetUseTPCStandaloneTracks(UseTPConlyTracks); if (UseTPConlyTracks) { cutsTPCQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaXY, -3.0, 3.0)); cutsTPCQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaZ, -3.0, 3.0)); cutsTPCQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, -0.8, 0.8)); cutsTPCQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); cutsTPCQoverSqrtM->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCnclsIter1, 70.0, 161.0)); cutsTPCQoverSqrtM->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCchi2Iter1, 0.2, 4.0)); } else { cutsTPCQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaXY, -0.3, 0.3)); cutsTPCQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaZ, -0.3, 0.3)); cutsTPCQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, -0.8, 0.8)); cutsTPCQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); cutsTPCQoverSqrtM->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCncls, 70.0, 161.0)); cutsTPCQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCchi2, 0.2, 4.0)); } } TPCconfQoverSqrtM->SetCuts(cutsTPCQoverSqrtM); /* add the configuration to the detector */ TPC->AddDetectorConfiguration(TPCconfQoverSqrtM); /* the TPC detector configuration */ AliQnCorrectionsDetectorConfigurationTracks* TPCNegEtaconfQoverSqrtM = new AliQnCorrectionsDetectorConfigurationTracks("TPCNegEtaQoverSqrtM", CorrEventClasses, 4); /* number of harmonics: 1, 2, 3 and 4 */ /* let's configure the Q vector calibration */ TPCNegEtaconfQoverSqrtM->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverSqrtM); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ TPCNegEtaconfQoverSqrtM->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector twist correction step */ AliQnCorrectionsQnVectorTwistAndRescale* twScaleNegEtaQoverSqrtM = new AliQnCorrectionsQnVectorTwistAndRescale(); twScaleNegEtaQoverSqrtM->SetApplyTwist(kTRUE); twScaleNegEtaQoverSqrtM->SetApplyRescale(kFALSE); twScaleNegEtaQoverSqrtM->SetTwistAndRescaleMethod( AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_doubleHarmonic); TPCNegEtaconfQoverSqrtM->AddCorrectionOnQnVector(twScaleNegEtaQoverSqrtM); /* define the cuts to apply */ isESD = mgr->GetInputEventHandler()->IsA() == AliESDInputHandler::Class(); AliQnCorrectionsCutsSet* cutsTPCNegEtaQoverSqrtM = new AliQnCorrectionsCutsSet(); if (!isESD) { cutsTPCNegEtaQoverSqrtM->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kFilterBitMask768, 0.5, 1.5)); cutsTPCNegEtaQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, -0.8, 0.)); cutsTPCNegEtaQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); } else { Bool_t UseTPConlyTracks = kFALSE; // Use of TPC standalone tracks or Global tracks (only for ESD analysis) task->SetUseTPCStandaloneTracks(UseTPConlyTracks); if (UseTPConlyTracks) { cutsTPCNegEtaQoverSqrtM->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaXY, -3.0, 3.0)); cutsTPCNegEtaQoverSqrtM->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaZ, -3.0, 3.0)); cutsTPCNegEtaQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, -0.8, 0.)); cutsTPCNegEtaQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); cutsTPCNegEtaQoverSqrtM->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCnclsIter1, 70.0, 161.0)); cutsTPCNegEtaQoverSqrtM->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCchi2Iter1, 0.2, 4.0)); } else { cutsTPCNegEtaQoverSqrtM->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaXY, -0.3, 0.3)); cutsTPCNegEtaQoverSqrtM->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaZ, -0.3, 0.3)); cutsTPCNegEtaQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, -0.8, 0.)); cutsTPCNegEtaQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); cutsTPCNegEtaQoverSqrtM->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCncls, 70.0, 161.0)); cutsTPCNegEtaQoverSqrtM->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCchi2, 0.2, 4.0)); } } TPCNegEtaconfQoverSqrtM->SetCuts(cutsTPCNegEtaQoverSqrtM); /* add the configuration to the detector */ TPC->AddDetectorConfiguration(TPCNegEtaconfQoverSqrtM); /* the TPC detector configuration */ AliQnCorrectionsDetectorConfigurationTracks* TPCPosEtaconfQoverSqrtM = new AliQnCorrectionsDetectorConfigurationTracks("TPCPosEtaQoverSqrtM", CorrEventClasses, 4); /* number of harmonics: 1, 2, 3 and 4 */ /* let's configure the Q vector calibration */ TPCPosEtaconfQoverSqrtM->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverSqrtM); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ TPCPosEtaconfQoverSqrtM->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector twist correction step */ AliQnCorrectionsQnVectorTwistAndRescale* twScalePosEtaQoverSqrtM = new AliQnCorrectionsQnVectorTwistAndRescale(); twScalePosEtaQoverSqrtM->SetApplyTwist(kTRUE); twScalePosEtaQoverSqrtM->SetApplyRescale(kFALSE); twScalePosEtaQoverSqrtM->SetTwistAndRescaleMethod( AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_doubleHarmonic); TPCPosEtaconfQoverSqrtM->AddCorrectionOnQnVector(twScalePosEtaQoverSqrtM); /* define the cuts to apply */ isESD = mgr->GetInputEventHandler()->IsA() == AliESDInputHandler::Class(); AliQnCorrectionsCutsSet* cutsTPCPosEtaQoverSqrtM = new AliQnCorrectionsCutsSet(); if (!isESD) { cutsTPCPosEtaQoverSqrtM->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kFilterBitMask768, 0.5, 1.5)); cutsTPCPosEtaQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, 0., 0.8)); cutsTPCPosEtaQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); } else { Bool_t UseTPConlyTracks = kFALSE; // Use of TPC standalone tracks or Global tracks (only for ESD analysis) task->SetUseTPCStandaloneTracks(UseTPConlyTracks); if (UseTPConlyTracks) { cutsTPCPosEtaQoverSqrtM->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaXY, -3.0, 3.0)); cutsTPCPosEtaQoverSqrtM->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaZ, -3.0, 3.0)); cutsTPCPosEtaQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, 0., 0.8)); cutsTPCPosEtaQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); cutsTPCPosEtaQoverSqrtM->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCnclsIter1, 70.0, 161.0)); cutsTPCPosEtaQoverSqrtM->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCchi2Iter1, 0.2, 4.0)); } else { cutsTPCPosEtaQoverSqrtM->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaXY, -0.3, 0.3)); cutsTPCPosEtaQoverSqrtM->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kDcaZ, -0.3, 0.3)); cutsTPCPosEtaQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kEta, 0., 0.8)); cutsTPCPosEtaQoverSqrtM->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kPt, 0.2, 5.)); cutsTPCPosEtaQoverSqrtM->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCncls, 70.0, 161.0)); cutsTPCPosEtaQoverSqrtM->Add( new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kTPCchi2, 0.2, 4.0)); } } TPCPosEtaconfQoverSqrtM->SetCuts(cutsTPCPosEtaQoverSqrtM); /* add the configuration to the detector */ TPC->AddDetectorConfiguration(TPCPosEtaconfQoverSqrtM); /* finally add the detector to the framework manager */ QnManager->AddDetector(TPC); } /** * Add the SPD configuration. Copied directly from ``AddTaskFlowQnVectorCorrectionsNewDetConfig.h``. */ void FlowVectorCorrections::AddSPD(AliAnalysisTaskFlowVectorCorrections* task, AliQnCorrectionsManager* QnManager, AliQnCorrectionsVarManagerTask::Variables varForEventMultiplicity) { /////////////// Add SPD subdetectors /////////////////// //----------------------------------------------------------- // Our event classes for SPD // const Int_t nSPDdim = 2; AliQnCorrectionsEventClassVariablesSet* CorrEventClasses = new AliQnCorrectionsEventClassVariablesSet(nSPDdim); Double_t VtxZbinning[][2] = { { -10.0, 4 }, { -7.0, 1 }, { 7.0, 8 }, { 10.0, 1 } }; Double_t Ctbinning[][2] = { { 0.0, 2 }, { 100.0, 100 } }; CorrEventClasses->Add(new AliQnCorrectionsEventClassVariable( AliQnCorrectionsVarManagerTask::kVtxZ, task->VarName(AliQnCorrectionsVarManagerTask::kVtxZ), VtxZbinning)); CorrEventClasses->Add(new AliQnCorrectionsEventClassVariable( varForEventMultiplicity, Form("Centrality (%s)", task->VarName(varForEventMultiplicity)), Ctbinning)); ////////// end of binning /* the SPD detector */ AliQnCorrectionsDetector* SPD = new AliQnCorrectionsDetector("SPD", AliQnCorrectionsVarManagerTask::kSPD); /* the SPD detector configuration */ AliQnCorrectionsDetectorConfigurationTracks* SPDconf = new AliQnCorrectionsDetectorConfigurationTracks( "SPD", CorrEventClasses, 4); /* number of harmonics: 1, 2, 3 and 4 */ /* let's configure the Q vector calibration */ SPDconf->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverM); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ SPDconf->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector twist correction step */ AliQnCorrectionsQnVectorTwistAndRescale* twScale = new AliQnCorrectionsQnVectorTwistAndRescale(); twScale->SetApplyTwist(kTRUE); twScale->SetApplyRescale(kFALSE); twScale->SetTwistAndRescaleMethod(AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_doubleHarmonic); SPDconf->AddCorrectionOnQnVector(twScale); /* add the configuration to the detector */ SPD->AddDetectorConfiguration(SPDconf); /* finally add the detector to the framework manager */ QnManager->AddDetector(SPD); } /** * Add the TZERO configuration. Copied directly from ``AddTaskFlowQnVectorCorrectionsNewDetConfig.h``. */ void FlowVectorCorrections::AddTZERO(AliAnalysisTaskFlowVectorCorrections* task, AliQnCorrectionsManager* QnManager, AliQnCorrectionsVarManagerTask::Variables varForEventMultiplicity) { /////////////// Add TZERO subdetectors /////////////////// Bool_t TZEROchannels[2][24]; for (Int_t iv0 = 0; iv0 < 2; iv0++) for (Int_t ich = 0; ich < 24; ich++) TZEROchannels[iv0][ich] = kFALSE; for (Int_t ich = 12; ich < 24; ich++) TZEROchannels[0][ich] = kTRUE; // channel list: value 1 if channel should be used for (Int_t ich = 0; ich < 12; ich++) TZEROchannels[1][ich] = kTRUE; Int_t channelGroups[24]; for (Int_t ich = 0; ich < 24; ich++) channelGroups[ich] = Int_t(ich / 12); //----------------------------------------------------------- // Our event classes for TZERO // const Int_t nTZEROdim = 2; AliQnCorrectionsEventClassVariablesSet* CorrEventClasses = new AliQnCorrectionsEventClassVariablesSet(nTZEROdim); Double_t VtxZbinning[][2] = { { -10.0, 4 }, { -7.0, 1 }, { 7.0, 8 }, { 10.0, 1 } }; Double_t Ctbinning[][2] = { { 0.0, 2 }, { 100.0, 100 } }; CorrEventClasses->Add(new AliQnCorrectionsEventClassVariable( AliQnCorrectionsVarManagerTask::kVtxZ, task->VarName(AliQnCorrectionsVarManagerTask::kVtxZ), VtxZbinning)); CorrEventClasses->Add(new AliQnCorrectionsEventClassVariable( varForEventMultiplicity, Form("Centrality (%s)", task->VarName(varForEventMultiplicity)), Ctbinning)); ////////// end of binning /* the TZERO detector */ AliQnCorrectionsDetector* TZERO = new AliQnCorrectionsDetector("TZERO", AliQnCorrectionsVarManagerTask::kTZERO); /* the TZEROA detector configuration */ AliQnCorrectionsDetectorConfigurationChannels* TZEROAconf = new AliQnCorrectionsDetectorConfigurationChannels("TZEROA", CorrEventClasses, 24, /* number of channels */ 4); /* number of harmonics: 1, 2, 3 and 4 */ TZEROAconf->SetChannelsScheme(TZEROchannels[0], channelGroups); /* let's configure the Q vector calibration */ TZEROAconf->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverM); /* lets configure the equalization of input data */ AliQnCorrectionsInputGainEqualization* eqA = new AliQnCorrectionsInputGainEqualization(); eqA->SetEqualizationMethod(AliQnCorrectionsInputGainEqualization::GEQUAL_averageEqualization); eqA->SetShift(1.0); eqA->SetScale(0.1); eqA->SetUseChannelGroupsWeights(kFALSE); TZEROAconf->AddCorrectionOnInputData(eqA); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ TZEROAconf->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector alignment correction step */ AliQnCorrectionsQnVectorAlignment* alignA = new AliQnCorrectionsQnVectorAlignment(); alignA->SetHarmonicNumberForAlignment(2); alignA->SetReferenceConfigurationForAlignment("TPC"); TZEROAconf->AddCorrectionOnQnVector(alignA); /* let's configure the QA histograms */ TZEROAconf->SetQACentralityVar(varForEventMultiplicity); TZEROAconf->SetQAMultiplicityAxis(100, 0.0, 150.0); /* let's configure the twist and rescale correction step */ AliQnCorrectionsQnVectorTwistAndRescale* twScaleA = new AliQnCorrectionsQnVectorTwistAndRescale(); twScaleA->SetApplyTwist(kTRUE); twScaleA->SetApplyRescale(kTRUE); twScaleA->SetTwistAndRescaleMethod(AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_correlations); twScaleA->SetReferenceConfigurationsForTwistAndRescale("TPC", "TZEROC"); /* now we add it to the detector configuration */ TZEROAconf->AddCorrectionOnQnVector(twScaleA); /* add the configuration to the detector */ TZERO->AddDetectorConfiguration(TZEROAconf); /* the TZEROC detector configuration */ AliQnCorrectionsDetectorConfigurationChannels* TZEROCconf = new AliQnCorrectionsDetectorConfigurationChannels("TZEROC", CorrEventClasses, 24, /* number of channels */ 4); /* number of harmonics: 1, 2, 3 and 4 */ TZEROCconf->SetChannelsScheme(TZEROchannels[1], channelGroups); /* let's configure the Q vector calibration */ TZEROCconf->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverM); /* lets configure the equalization of input data */ AliQnCorrectionsInputGainEqualization* eqC = new AliQnCorrectionsInputGainEqualization(); eqC->SetEqualizationMethod(AliQnCorrectionsInputGainEqualization::GEQUAL_averageEqualization); eqC->SetShift(1.0); eqC->SetScale(0.1); eqC->SetUseChannelGroupsWeights(kFALSE); TZEROCconf->AddCorrectionOnInputData(eqC); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ TZEROCconf->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector alignment correction step */ AliQnCorrectionsQnVectorAlignment* alignC = new AliQnCorrectionsQnVectorAlignment(); alignC->SetHarmonicNumberForAlignment(2); alignC->SetReferenceConfigurationForAlignment("TPC"); TZEROCconf->AddCorrectionOnQnVector(alignC); /* let's configure the QA histograms */ TZEROCconf->SetQACentralityVar(varForEventMultiplicity); TZEROCconf->SetQAMultiplicityAxis(100, 0.0, 150.0); /* let's configure the twist and rescale correction step */ AliQnCorrectionsQnVectorTwistAndRescale* twScaleC = new AliQnCorrectionsQnVectorTwistAndRescale(); twScaleC->SetApplyTwist(kTRUE); twScaleC->SetApplyRescale(kTRUE); twScaleC->SetTwistAndRescaleMethod(AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_correlations); twScaleC->SetReferenceConfigurationsForTwistAndRescale("TPC", "TZEROA"); /* now we add it to the detector configuration */ TZEROCconf->AddCorrectionOnQnVector(twScaleC); /* add the configuration to the detector */ TZERO->AddDetectorConfiguration(TZEROCconf); /* finally add the detector to the framework manager */ QnManager->AddDetector(TZERO); } /** * Add the ZDC configuration. Copied directly from ``AddTaskFlowQnVectorCorrectionsNewDetConfig.h``. */ void FlowVectorCorrections::AddZDC(AliAnalysisTaskFlowVectorCorrections* task, AliQnCorrectionsManager* QnManager, AliQnCorrectionsVarManagerTask::Variables varForEventMultiplicity) { /////////////// Add ZDC subdetectors /////////////////// Bool_t ZDCchannels[2][10]; for (Int_t iv0 = 0; iv0 < 2; iv0++) for (Int_t ich = 0; ich < 10; ich++) ZDCchannels[iv0][ich] = kFALSE; for (Int_t ich = 6; ich < 10; ich++) ZDCchannels[0][ich] = kTRUE; for (Int_t ich = 1; ich < 5; ich++) ZDCchannels[1][ich] = kTRUE; //----------------------------------------------------------- // Our event classes for ZDC // const Int_t nZDCdim = 3; AliQnCorrectionsEventClassVariablesSet* CorrEventClasses = new AliQnCorrectionsEventClassVariablesSet(nZDCdim); Double_t VtxXbinning[][2] = { { -0.3, 2 }, { 0.3, 10 } }; Double_t VtxYbinning[][2] = { { -0.3, 2 }, { 0.3, 10 } }; Double_t Ctbinning[][2] = { { 0.0, 2 }, { 100.0, 100 } }; CorrEventClasses->Add(new AliQnCorrectionsEventClassVariable( AliQnCorrectionsVarManagerTask::kVtxX, task->VarName(AliQnCorrectionsVarManagerTask::kVtxX), VtxXbinning)); CorrEventClasses->Add(new AliQnCorrectionsEventClassVariable( AliQnCorrectionsVarManagerTask::kVtxY, task->VarName(AliQnCorrectionsVarManagerTask::kVtxY), VtxYbinning)); CorrEventClasses->Add(new AliQnCorrectionsEventClassVariable( varForEventMultiplicity, Form("Centrality (%s)", task->VarName(varForEventMultiplicity)), Ctbinning)); ////////// end of binning /* the ZDC detector */ AliQnCorrectionsDetector* ZDC = new AliQnCorrectionsDetector("ZDC", AliQnCorrectionsVarManagerTask::kZDC); /* the ZDCA detector configuration */ AliQnCorrectionsDetectorConfigurationChannels* ZDCAconf = new AliQnCorrectionsDetectorConfigurationChannels("ZDCA", CorrEventClasses, 10, /* number of channels */ 3); /* number of harmonics: 1, 2 and 3 */ ZDCAconf->SetChannelsScheme(ZDCchannels[0], NULL /* no groups */); /* let's configure the Q vector calibration */ ZDCAconf->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverM); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ ZDCAconf->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* add the configuration to the detector */ ZDC->AddDetectorConfiguration(ZDCAconf); /* the ZDCC detector configuration */ AliQnCorrectionsDetectorConfigurationChannels* ZDCCconf = new AliQnCorrectionsDetectorConfigurationChannels("ZDCC", CorrEventClasses, 10, /* number of channels */ 3); /* number of harmonics: 1, 2 and 3 */ ZDCCconf->SetChannelsScheme(ZDCchannels[1], NULL /* no groups */); /* let's configure the Q vector calibration */ ZDCCconf->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverM); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ ZDCCconf->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* add the configuration to the detector */ ZDC->AddDetectorConfiguration(ZDCCconf); /* finally add the detector to the framework manager */ QnManager->AddDetector(ZDC); } /** * Add the FMD configuration. Copied directly from ``AddTaskFlowQnVectorCorrectionsNewDetConfig.h``. */ void FlowVectorCorrections::AddFMD(AliAnalysisTaskFlowVectorCorrections* task, AliQnCorrectionsManager* QnManager, AliQnCorrectionsVarManagerTask::Variables varForEventMultiplicity) { AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager(); Bool_t isESD = mgr->GetInputEventHandler()->IsA() == AliESDInputHandler::Class(); if (isESD) { AliFatalGeneral("PWGJE::EMCALJetTasks::FlowVectorCorrections::AddFMD", "ESD analysis is not supported for the FMD."); } Bool_t FMDchannels[2][4000]; for (Int_t iv0 = 0; iv0 < 2; iv0++) for (Int_t ich = 0; ich < 4000; ich++) FMDchannels[iv0][ich] = kFALSE; for (Int_t ich = 2000; ich < 4000; ich++) FMDchannels[0][ich] = kTRUE; // channel list: value 1 if channel should be used for (Int_t ich = 0; ich < 2000; ich++) FMDchannels[1][ich] = kTRUE; //----------------------------------------------------------- // Our event classes for FMD // const Int_t nFMDdim = 2; AliQnCorrectionsEventClassVariablesSet* CorrEventClasses = new AliQnCorrectionsEventClassVariablesSet(nFMDdim); Double_t VtxZbinning[][2] = { { -10.0, 4 }, { -7.0, 1 }, { 7.0, 8 }, { 10.0, 1 } }; Double_t Ctbinning[][2] = { { 0.0, 2 }, { 100.0, 100 } }; CorrEventClasses->Add(new AliQnCorrectionsEventClassVariable( AliQnCorrectionsVarManagerTask::kVtxZ, task->VarName(AliQnCorrectionsVarManagerTask::kVtxZ), VtxZbinning)); CorrEventClasses->Add(new AliQnCorrectionsEventClassVariable( varForEventMultiplicity, Form("Centrality (%s)", task->VarName(varForEventMultiplicity)), Ctbinning)); ////////// end of binning /* the FMD detector */ AliQnCorrectionsDetector* FMD = new AliQnCorrectionsDetector("FMD", AliQnCorrectionsVarManagerTask::kFMD); /* the FMDA detector configuration */ AliQnCorrectionsDetectorConfigurationChannels* FMDAconf = new AliQnCorrectionsDetectorConfigurationChannels("FMDA", CorrEventClasses, 4000, /* number of channels */ 4); /* number of harmonics: 1, 2 and 3 */ FMDAconf->SetChannelsScheme(FMDchannels[0], NULL /* no groups */); /* let's configure the Q vector calibration */ FMDAconf->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverM); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ FMDAconf->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector alignment correction step */ AliQnCorrectionsQnVectorAlignment* alignA = new AliQnCorrectionsQnVectorAlignment(); alignA->SetHarmonicNumberForAlignment(2); alignA->SetReferenceConfigurationForAlignment("TPC"); FMDAconf->AddCorrectionOnQnVector(alignA); /* let's configure the twist and rescale correction step */ AliQnCorrectionsQnVectorTwistAndRescale* twScaleA = new AliQnCorrectionsQnVectorTwistAndRescale(); twScaleA->SetApplyTwist(kTRUE); twScaleA->SetApplyRescale(kTRUE); twScaleA->SetTwistAndRescaleMethod(AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_correlations); twScaleA->SetReferenceConfigurationsForTwistAndRescale("TPC", "FMDC"); /* now we add it to the detector configuration */ FMDAconf->AddCorrectionOnQnVector(twScaleA); /* add the configuration to the detector */ FMD->AddDetectorConfiguration(FMDAconf); /* the FMDC detector configuration */ AliQnCorrectionsDetectorConfigurationChannels* FMDCconf = new AliQnCorrectionsDetectorConfigurationChannels("FMDC", CorrEventClasses, 4000, /* number of channels */ 4); /* number of harmonics: 1, 2, 3 and 4 */ FMDCconf->SetChannelsScheme(FMDchannels[1], NULL /* no groups */); /* let's configure the Q vector calibration */ FMDCconf->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverM); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ FMDCconf->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector alignment correction step */ AliQnCorrectionsQnVectorAlignment* alignC = new AliQnCorrectionsQnVectorAlignment(); alignC->SetHarmonicNumberForAlignment(2); alignC->SetReferenceConfigurationForAlignment("TPC"); FMDCconf->AddCorrectionOnQnVector(alignC); /* let's configure the twist and rescale correction step */ AliQnCorrectionsQnVectorTwistAndRescale* twScaleC = new AliQnCorrectionsQnVectorTwistAndRescale(); twScaleC->SetApplyTwist(kTRUE); twScaleC->SetApplyRescale(kTRUE); twScaleC->SetTwistAndRescaleMethod(AliQnCorrectionsQnVectorTwistAndRescale::TWRESCALE_correlations); twScaleC->SetReferenceConfigurationsForTwistAndRescale("TPC", "FMDA"); /* now we add it to the detector configuration */ FMDCconf->AddCorrectionOnQnVector(twScaleC); /* add the configuration to the detector */ FMD->AddDetectorConfiguration(FMDCconf); /* finally add the detector to the framework manager */ QnManager->AddDetector(FMD); } /** * Add the raw FMD configuration. Copied directly from ``AddTaskFlowQnVectorCorrectionsNewDetConfig.h``. */ void FlowVectorCorrections::AddRawFMD(AliAnalysisTaskFlowVectorCorrections* task, AliQnCorrectionsManager* QnManager, AliQnCorrectionsVarManagerTask::Variables varForEventMultiplicity) { /////////////// Add FMD subdetectors /////////////////// /* FMD1 and FMD2 make FMDA and FMD3 make FMDC */ const Int_t nNoOfDetectors = 3; ///< the number of FMD detectors const Int_t detectorNumber[] = { 1, 2, 3 }; ///< the number of the FMD detector const Int_t nNoOfRings[] = { 1, 2, 2 }; ///< the number of rings for each detector const Int_t ringNoOfSectors[] = { 20, 40 }; ///< ring number of sectors const Int_t nTotalNoOfChannels = ringNoOfSectors[0] * 3 + ringNoOfSectors[1] * 2; ///< three inner sectors plus two outer ones // const Int_t nTotalNoOfGroups = nNoOfRings[0] + nNoOfRings[1] + nNoOfRings[2]; ///< each ring one channel // group const Int_t FMDCdetectorNumber = 3; ///< the number of the detector associated to FMDC Int_t nSectorId = 0; ///< the sector id used as channel number Int_t nRingId = 0; ///< the ring id (0..4) used as group number Bool_t FMDchannels[2][nTotalNoOfChannels]; ///< the assignment of channels to each subdetector Int_t FMDchannelGroups[nTotalNoOfChannels]; ///< the group associated to each channel for (Int_t i = 0; i < 2; i++) for (Int_t c = 0; c < nTotalNoOfChannels; c++) FMDchannels[i][c] = kFALSE; for (Int_t detector = 0; detector < nNoOfDetectors; detector++) { for (Int_t ring = 0; ring < nNoOfRings[detector]; ring++) { for (Int_t sector = 0; sector < ringNoOfSectors[ring]; sector++) { FMDchannels[0][nSectorId] = ((detectorNumber[detector] != FMDCdetectorNumber) ? kTRUE : kFALSE); FMDchannels[1][nSectorId] = ((detectorNumber[detector] != FMDCdetectorNumber) ? kFALSE : kTRUE); FMDchannelGroups[nSectorId] = nRingId; nSectorId++; } nRingId++; } } //----------------------------------------------------------- // Our event classes for FMD // const Int_t nFMDdim = 2; AliQnCorrectionsEventClassVariablesSet* CorrEventClasses = new AliQnCorrectionsEventClassVariablesSet(nFMDdim); Double_t VtxZbinning[][2] = { { -10.0, 4 }, { -7.0, 1 }, { 7.0, 8 }, { 10.0, 1 } }; Double_t Ctbinning[][2] = { { 0.0, 2 }, { 100.0, 100 } }; CorrEventClasses->Add(new AliQnCorrectionsEventClassVariable( AliQnCorrectionsVarManagerTask::kVtxZ, task->VarName(AliQnCorrectionsVarManagerTask::kVtxZ), VtxZbinning)); CorrEventClasses->Add(new AliQnCorrectionsEventClassVariable( varForEventMultiplicity, Form("Centrality (%s)", task->VarName(varForEventMultiplicity)), Ctbinning)); ////////// end of binning AliQnCorrectionsCutsSet* cutFMDA = new AliQnCorrectionsCutsSet(); cutFMDA->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kFMDEta, 0.0, 6.0)); AliQnCorrectionsCutsSet* cutFMDC = new AliQnCorrectionsCutsSet(); cutFMDC->Add(new AliQnCorrectionsCutWithin(AliQnCorrectionsVarManagerTask::kFMDEta, -6.0, 0.0)); /* the FMD detector */ AliQnCorrectionsDetector* FMDraw = new AliQnCorrectionsDetector("FMDraw", AliQnCorrectionsVarManagerTask::kFMDraw); /* the FMDAraw detector configuration */ AliQnCorrectionsDetectorConfigurationChannels* FMDArawconf = new AliQnCorrectionsDetectorConfigurationChannels( "FMDAraw", CorrEventClasses, nTotalNoOfChannels, 4); /* number of harmonics: 1, 2, 3 and 4 */ FMDArawconf->SetChannelsScheme(FMDchannels[0], FMDchannelGroups); /* let's configure the Q vector calibration */ FMDArawconf->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverM); /* lets configure the equalization of input data */ AliQnCorrectionsInputGainEqualization* eqA = new AliQnCorrectionsInputGainEqualization(); eqA->SetEqualizationMethod(AliQnCorrectionsInputGainEqualization::GEQUAL_averageEqualization); eqA->SetShift(1.0); eqA->SetScale(0.1); eqA->SetUseChannelGroupsWeights(kTRUE); FMDArawconf->AddCorrectionOnInputData(eqA); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ FMDArawconf->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector alignment correction step */ AliQnCorrectionsQnVectorAlignment* alignA = new AliQnCorrectionsQnVectorAlignment(); alignA->SetHarmonicNumberForAlignment(2); alignA->SetReferenceConfigurationForAlignment("TPC"); FMDArawconf->AddCorrectionOnQnVector(alignA); /* and add the cuts */ FMDArawconf->SetCuts(cutFMDA); /* add the configuration to the detector */ FMDraw->AddDetectorConfiguration(FMDArawconf); /* the FMDCraw detector configuration */ AliQnCorrectionsDetectorConfigurationChannels* FMDCrawconf = new AliQnCorrectionsDetectorConfigurationChannels( "FMDCraw", CorrEventClasses, nTotalNoOfChannels, 4); /* number of harmonics: 1, 2, 3 and 4 */ FMDCrawconf->SetChannelsScheme(FMDchannels[1], FMDchannelGroups); /* let's configure the Q vector calibration */ FMDCrawconf->SetQVectorNormalizationMethod(AliQnCorrectionsQnVector::QVNORM_QoverM); /* lets configure the equalization of input data */ AliQnCorrectionsInputGainEqualization* eqC = new AliQnCorrectionsInputGainEqualization(); eqC->SetEqualizationMethod(AliQnCorrectionsInputGainEqualization::GEQUAL_averageEqualization); eqC->SetShift(1.0); eqC->SetScale(0.1); eqC->SetUseChannelGroupsWeights(kTRUE); FMDCrawconf->AddCorrectionOnInputData(eqC); /* let's add the Q vector recentering correction step */ /* we don't configure it, so we create it anonymous */ FMDCrawconf->AddCorrectionOnQnVector(new AliQnCorrectionsQnVectorRecentering()); /* let's add the Q vector alignment correction step */ AliQnCorrectionsQnVectorAlignment* alignC = new AliQnCorrectionsQnVectorAlignment(); alignC->SetHarmonicNumberForAlignment(2); alignC->SetReferenceConfigurationForAlignment("TPC"); FMDCrawconf->AddCorrectionOnQnVector(alignC); /* and add the cuts */ FMDCrawconf->SetCuts(cutFMDC); /* add the configuration to the detector */ FMDraw->AddDetectorConfiguration(FMDCrawconf); /* finally add the detector to the framework manager */ QnManager->AddDetector(FMDraw); } /** * Define Qn vector histograms. Copied directly from ``AddTaskFlowQnVectorCorrectionsNewDetConfig.h``. */ void FlowVectorCorrections::DefineHistograms(AliQnCorrectionsManager* QnManager, AliQnCorrectionsHistos* histos, TString histClass) { // // define the histograms // const Char_t* histClasses = histClass.Data(); AliInfoGeneralStream("PWGJE::EMCALJetTasks::FlowVectorCorrections::DefineHistograms") << "Defining histograms ...\n"; AliInfoGeneralStream("PWGJE::EMCALJetTasks::FlowVectorCorrections::DefineHistograms") << "histogram classes: " << histClass << "\n"; // fHistosFile=new TFile(output,"RECREATE"); TString classesStr(histClasses); TObjArray* arr = classesStr.Tokenize(";"); const Int_t kNRunBins = 3000; Double_t runHistRange[2] = { 137000., 140000. }; for (Int_t iclass = 0; iclass < arr->GetEntries(); ++iclass) { TString classStr = arr->At(iclass)->GetName(); AliInfoGeneralStream("PWGJE::EMCALJetTasks::FlowVectorCorrections::DefineHistograms") << "hist class: " << classStr.Data() << "\n"; // Event wise histograms if (classStr.Contains("Event")) { histos->AddHistClass(classStr.Data()); histos->AddHistogram(classStr.Data(), "RunNo", "Run numbers;Run", kFALSE, kNRunBins, runHistRange[0], runHistRange[1], AliQnCorrectionsVarManagerTask::kRunNo); histos->AddHistogram(classStr.Data(), "BC", "Bunch crossing;BC", kFALSE, 3000, 0., 3000., AliQnCorrectionsVarManagerTask::kBC); histos->AddHistogram(classStr.Data(), "IsPhysicsSelection", "Physics selection flag;;", kFALSE, 2, -0.5, 1.5, AliQnCorrectionsVarManagerTask::kIsPhysicsSelection, 0, 0.0, 0.0, AliQnCorrectionsVarManagerTask::kNothing, 0, 0.0, 0.0, AliQnCorrectionsVarManagerTask::kNothing, "off;on"); histos->AddHistogram(classStr.Data(), "VtxZ", "Vtx Z;vtx Z (cm)", kFALSE, 300, -30.0, 30.0, AliQnCorrectionsVarManagerTask::kVtxZ); // histos->AddHistogram(classStr.Data(),"VtxZ","Vtx Z;vtx Z (cm)", // kFALSE,300,-15.,15.,AliQnCorrectionsVarManagerTask::kVtxZ); histos->AddHistogram(classStr.Data(), "VtxX", "Vtx X;vtx X (cm)", kFALSE, 300, -1., 1., AliQnCorrectionsVarManagerTask::kVtxX); histos->AddHistogram(classStr.Data(), "VtxY", "Vtx Y;vtx Y (cm)", kFALSE, 300, -1., 1., AliQnCorrectionsVarManagerTask::kVtxY); histos->AddHistogram( classStr.Data(), "CentVZEROvsMultPVZERO", "Multiplicity percentile (VZERO);multiplicity VZERO (percents);centrality VZERO (percents)", kFALSE, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kVZEROMultPercentile, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentVZERO); histos->AddHistogram(classStr.Data(), "CentVZEROvsCentSPD", "Centrality(VZERO);centrality VZERO (percents);centrality SPD (percents)", kFALSE, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentVZERO, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentSPD); histos->AddHistogram(classStr.Data(), "CentTPCvsCentSPD", "Centrality(TPC);centrality TPC (percents);centrality SPD (percents)", kFALSE, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentTPC, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentSPD); histos->AddHistogram(classStr.Data(), "CentTPCvsCentVZERO", "Centrality(TPC);centrality TPC (percents);centrality VZERO (percents)", kFALSE, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentTPC, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentVZERO); histos->AddHistogram(classStr.Data(), "CentTPCvsCentZDC", "Centrality(TPC);centrality TPC (percents);centrality ZDC (percents)", kFALSE, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentTPC, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentZDC); histos->AddHistogram(classStr.Data(), "CentZDCvsCentVZERO", "Centrality(ZDC);centrality ZDC (percents);centrality VZERO (percents)", kFALSE, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentZDC, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentVZERO); histos->AddHistogram(classStr.Data(), "CentZDCvsCentSPD", "Centrality(ZDC);centrality ZDC (percents);centrality SPD (percents)", kFALSE, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentZDC, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentSPD); histos->AddHistogram(classStr.Data(), "MultVZEROvsCentVZERO", "Multiplicity;multiplicity VZERO;VZERO centrality", kFALSE, 100, 0.0, 32000.0, AliQnCorrectionsVarManagerTask::kVZEROTotalMult, 100, 0., 100., AliQnCorrectionsVarManagerTask::kCentVZERO); histos->AddHistogram(classStr.Data(), "MultSPDvsCentPSD", "Multiplicity;SPD tracklets;SPD centrality", kFALSE, 100, 0.0, 3000.0, AliQnCorrectionsVarManagerTask::kSPDntracklets, 100, 0., 100., AliQnCorrectionsVarManagerTask::kCentSPD); histos->AddHistogram(classStr.Data(), "MultTPCvsCentSPD", "Multiplicity;TPC selected tracks;TPC centrality", kFALSE, 100, 0.0, 3500.0, AliQnCorrectionsVarManagerTask::kNtracksSelected, 100, 0., 100., AliQnCorrectionsVarManagerTask::kCentTPC); histos->AddHistogram(classStr.Data(), "MultZDCvsCentZDC", "Multiplicity;multiplicity ZDC;ZDC centrality", kFALSE, 100, 0.0, 300000.0, AliQnCorrectionsVarManagerTask::kZDCTotalEnergy, 100, 0., 100., AliQnCorrectionsVarManagerTask::kCentZDC); histos->AddHistogram(classStr.Data(), "MultTPCvsMultVZERO", "Multiplicity;tracks TPC;multiplicity VZERO", kFALSE, 100, 0.0, 3500.0, AliQnCorrectionsVarManagerTask::kNtracksSelected, 100, 0.0, 32000.0, AliQnCorrectionsVarManagerTask::kVZEROTotalMult); histos->AddHistogram(classStr.Data(), "MultTPCvsMultSPD", "Multiplicity;tracklets SPD;tracks TPC", kFALSE, 100, 0.0, 3500.0, AliQnCorrectionsVarManagerTask::kNtracksSelected, 100, 0.0, 3000.0, AliQnCorrectionsVarManagerTask::kSPDntracklets); histos->AddHistogram(classStr.Data(), "MultSPDvsMultVZERO", "Multiplicity;tracklets SPD;multiplicity VZERO", kFALSE, 100, 0.0, 32000.0, AliQnCorrectionsVarManagerTask::kVZEROTotalMult, 100, 0.0, 3000.0, AliQnCorrectionsVarManagerTask::kSPDntracklets); histos->AddHistogram(classStr.Data(), "MultTPCvsMultZDC", "Multiplicity;tracks TPC;energy ZDC", kFALSE, 100, 0.0, 3500.0, AliQnCorrectionsVarManagerTask::kNtracksSelected, 100, 0.0, 300000.0, AliQnCorrectionsVarManagerTask::kZDCTotalEnergy); histos->AddHistogram(classStr.Data(), "MultVZEROvsMultZDC", "Multiplicity;multiplicity VZERO;energy ZDC", kFALSE, 100, 0.0, 32000.0, AliQnCorrectionsVarManagerTask::kVZEROTotalMult, 100, 0.0, 300000.0, AliQnCorrectionsVarManagerTask::kZDCTotalEnergy); histos->AddHistogram(classStr.Data(), "MultSPDvsMultZDC", "Multiplicity;tracklets SPD;energy ZDC", kFALSE, 100, 0.0, 3000.0, AliQnCorrectionsVarManagerTask::kSPDntracklets, 100, 0.0, 300000.0, AliQnCorrectionsVarManagerTask::kZDCTotalEnergy); histos->AddHistogram(classStr.Data(), "MultVZERO", "Multiplicity;multiplicity VZERO", kFALSE, 320, 0.0, 25000.0, AliQnCorrectionsVarManagerTask::kVZEROTotalMult); histos->AddHistogram(classStr.Data(), "MultVZEROA", "Multiplicity;multiplicity VZEROA", kFALSE, 250, 0.0, 9500.0, AliQnCorrectionsVarManagerTask::kVZEROATotalMult); // 10000.0 histos->AddHistogram(classStr.Data(), "MultVZEROC", "Multiplicity;multiplicity VZEROC", kFALSE, 250, 0.0, 16000.0, AliQnCorrectionsVarManagerTask::kVZEROCTotalMult); // 15000.0 histos->AddHistogram(classStr.Data(), "MultZDC", "Multiplicity;multiplicity ZDC", kFALSE, 200, 0.0, 300000.0, AliQnCorrectionsVarManagerTask::kZDCTotalEnergy); histos->AddHistogram(classStr.Data(), "MultZDCA", "Multiplicity;multiplicity ZDCA", kFALSE, 200, 0.0, 150000.0, AliQnCorrectionsVarManagerTask::kZDCATotalEnergy); histos->AddHistogram(classStr.Data(), "MultZDCC", "Multiplicity;multiplicity ZDCC", kFALSE, 200, 0.0, 150000.0, AliQnCorrectionsVarManagerTask::kZDCCTotalEnergy); histos->AddHistogram(classStr.Data(), "MultFMD1", "Multiplicity;multiplicity FMD1", kFALSE, 300, 0.0, 10000.0, AliQnCorrectionsVarManagerTask::kFMD1TotalMult); histos->AddHistogram(classStr.Data(), "MultFMD2I", "Multiplicity;multiplicity FMD2I", kFALSE, 300, 0.0, 10000.0, AliQnCorrectionsVarManagerTask::kFMD2ITotalMult); histos->AddHistogram(classStr.Data(), "MultFMD2O", "Multiplicity;multiplicity FMD2O", kFALSE, 300, 0.0, 10000.0, AliQnCorrectionsVarManagerTask::kFMD2OTotalMult); histos->AddHistogram(classStr.Data(), "MultFMD3I", "Multiplicity;multiplicity FMD3I", kFALSE, 300, 0.0, 10000.0, AliQnCorrectionsVarManagerTask::kFMD3ITotalMult); histos->AddHistogram(classStr.Data(), "MultFMD3O", "Multiplicity;multiplicity FMD3O", kFALSE, 300, 0.0, 10000.0, AliQnCorrectionsVarManagerTask::kFMD3OTotalMult); histos->AddHistogram(classStr.Data(), "MultTZEROA", "Multiplicity;multiplicity TZEROA", kFALSE, 300, 0.0, 3000.0, AliQnCorrectionsVarManagerTask::kTZEROATotalMult); histos->AddHistogram(classStr.Data(), "MultTZEROC", "Multiplicity;multiplicity TZEROC", kFALSE, 300, 0.0, 3000.0, AliQnCorrectionsVarManagerTask::kTZEROCTotalMult); histos->AddHistogram(classStr.Data(), "MultPercentVZERO", "Multiplicity percentile (VZERO);multiplicity VZERO (percents)", kFALSE, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kVZEROMultPercentile); histos->AddHistogram(classStr.Data(), "CentVZERO", "Centrality(VZERO);centrality VZERO (percents)", kFALSE, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentVZERO); histos->AddHistogram(classStr.Data(), "CentSPD", "Centrality(SPD);centrality SPD (percents)", kFALSE, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentSPD); histos->AddHistogram(classStr.Data(), "CentTPC", "Centrality(TPC);centrality TPC (percents)", kFALSE, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentTPC); histos->AddHistogram(classStr.Data(), "CentZDC", "Centrality(ZDC);centrality ZDC (percents)", kFALSE, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentZDC); histos->AddHistogram(classStr.Data(), "CentQuality", "Centrality quality;centrality quality", kFALSE, 100, -50.5, 49.5, AliQnCorrectionsVarManagerTask::kCentQuality); histos->AddHistogram(classStr.Data(), "CentVZERO_Run_prof", "<Centrality(VZERO)> vs run;Run; centrality VZERO (%)", kTRUE, kNRunBins, runHistRange[0], runHistRange[1], AliQnCorrectionsVarManagerTask::kRunNo, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentVZERO); histos->AddHistogram(classStr.Data(), "CentSPD_Run_prof", "<Centrality(SPD)> vs run;Run; centrality SPD (%)", kTRUE, kNRunBins, runHistRange[0], runHistRange[1], AliQnCorrectionsVarManagerTask::kRunNo, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentSPD); histos->AddHistogram(classStr.Data(), "CentTPC_Run_prof", "<Centrality(TPC)> vs run;Run; centrality TPC (%)", kTRUE, kNRunBins, runHistRange[0], runHistRange[1], AliQnCorrectionsVarManagerTask::kRunNo, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentTPC); histos->AddHistogram(classStr.Data(), "CentZDC_Run_prof", "<Centrality(ZDC)> vs run;Run; centrality ZDC (%)", kTRUE, kNRunBins, runHistRange[0], runHistRange[1], AliQnCorrectionsVarManagerTask::kRunNo, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentZDC); histos->AddHistogram(classStr.Data(), "NV0sTotal", "Number of V0 candidates per event;# pairs", kFALSE, 1000, 0., 30000., AliQnCorrectionsVarManagerTask::kNV0total); histos->AddHistogram(classStr.Data(), "NV0sSelected", "Number of selected V0 candidates per event;# pairs", kFALSE, 1000, 0., 10000., AliQnCorrectionsVarManagerTask::kNV0selected); histos->AddHistogram(classStr.Data(), "NPairs", "Number of candidates per event;# pairs", kFALSE, 5000, 0., 5000., AliQnCorrectionsVarManagerTask::kNdielectrons); histos->AddHistogram(classStr.Data(), "NPairsSelected", "Number of selected pairs per event; #pairs", kFALSE, 5000, 0., 5000., AliQnCorrectionsVarManagerTask::kNpairsSelected); histos->AddHistogram(classStr.Data(), "NTracksTotal", "Number of total tracks per event;# tracks", kFALSE, 1000, 0., 30000., AliQnCorrectionsVarManagerTask::kNtracksTotal); histos->AddHistogram(classStr.Data(), "NTracksSelected", "Number of selected tracks per event;# tracks", kFALSE, 1000, 0., 30000., AliQnCorrectionsVarManagerTask::kNtracksSelected); histos->AddHistogram(classStr.Data(), "SPDntracklets", "SPD #tracklets; tracklets", kFALSE, 3000, -0.5, 2999.5, AliQnCorrectionsVarManagerTask::kSPDntracklets); histos->AddHistogram(classStr.Data(), "SPDnSingleClusters", "SPD #single clusters; tracklets", kFALSE, 3000, -0.5, 2999.5, AliQnCorrectionsVarManagerTask::kSPDnSingleClusters); histos->AddHistogram(classStr.Data(), "NV0total_Run_prof", "<Number of total V0s> per run; Run; #tracks", kTRUE, kNRunBins, runHistRange[0], runHistRange[1], AliQnCorrectionsVarManagerTask::kRunNo, 100, 0., 10000., AliQnCorrectionsVarManagerTask::kNV0total); histos->AddHistogram(classStr.Data(), "NV0selected_Run_prof", "<Number of selected V0s> per run; Run; #tracks", kTRUE, kNRunBins, runHistRange[0], runHistRange[1], AliQnCorrectionsVarManagerTask::kRunNo, 100, 0., 10000., AliQnCorrectionsVarManagerTask::kNV0selected); histos->AddHistogram(classStr.Data(), "Ndielectrons_Run_prof", "<Number of dielectrons> per run; Run; #tracks", kTRUE, kNRunBins, runHistRange[0], runHistRange[1], AliQnCorrectionsVarManagerTask::kRunNo, 100, 0., 10000., AliQnCorrectionsVarManagerTask::kNdielectrons); histos->AddHistogram(classStr.Data(), "NpairsSelected_Run_prof", "<Number of selected pairs> per run; Run; #tracks", kTRUE, kNRunBins, runHistRange[0], runHistRange[1], AliQnCorrectionsVarManagerTask::kRunNo, 100, 0., 10000., AliQnCorrectionsVarManagerTask::kNpairsSelected); histos->AddHistogram(classStr.Data(), "NTracksTotal_Run_prof", "<Number of tracks> per run; Run; #tracks", kTRUE, kNRunBins, runHistRange[0], runHistRange[1], AliQnCorrectionsVarManagerTask::kRunNo, 100, 0., 10000., AliQnCorrectionsVarManagerTask::kNtracksTotal); histos->AddHistogram(classStr.Data(), "NTracksSelected_Run_prof", "<Number of selected tracks> per run; Run; #tracks", kTRUE, kNRunBins, runHistRange[0], runHistRange[1], AliQnCorrectionsVarManagerTask::kRunNo, 100, 0., 10000., AliQnCorrectionsVarManagerTask::kNtracksSelected); histos->AddHistogram(classStr.Data(), "SPDntracklets_Run_prof", "<SPD ntracklets> per run; Run; #tracks", kTRUE, kNRunBins, runHistRange[0], runHistRange[1], AliQnCorrectionsVarManagerTask::kRunNo, 100, 0., 10000., AliQnCorrectionsVarManagerTask::kSPDntracklets); histos->AddHistogram(classStr.Data(), "VtxZ_CentVZERO", "Centrality(VZERO) vs vtx. Z;vtx Z (cm); centrality VZERO (%)", kFALSE, 300, -15., 15., AliQnCorrectionsVarManagerTask::kVtxZ, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentVZERO); histos->AddHistogram(classStr.Data(), "VtxZ_CentSPD", "Centrality(SPD) vs vtx. Z;vtx Z (cm); centrality SPD (%)", kFALSE, 300, -15., 15., AliQnCorrectionsVarManagerTask::kVtxZ, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentSPD); histos->AddHistogram(classStr.Data(), "VtxZ_CentTPC", "Centrality(TPC) vs vtx. Z;vtx Z (cm); centrality TPC (%)", kFALSE, 300, -15., 15., AliQnCorrectionsVarManagerTask::kVtxZ, 100, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentTPC); continue; } // end if className contains "Event" // Offline trigger histograms if (classStr.Contains("OfflineTriggers")) { histos->AddHistClass(classStr.Data()); TString triggerNames = ""; for (Int_t i = 0; i < 64; ++i) { triggerNames += Form("%s", AliQnCorrectionsVarManagerTask::fOfflineTriggerNames[i]); triggerNames += ";"; } histos->AddHistogram(classStr.Data(), "Triggers", "Offline triggers fired; ; ;", kFALSE, 64, -0.5, 63.5, AliQnCorrectionsVarManagerTask::kOfflineTrigger, 2, -0.5, 1.5, AliQnCorrectionsVarManagerTask::kOfflineTriggerFired, 0, 0.0, 0.0, AliQnCorrectionsVarManagerTask::kNothing, triggerNames.Data(), "off;on"); histos->AddHistogram(classStr.Data(), "Triggers2", "Offline triggers fired; ; ;", kFALSE, 64, -0.5, 63.5, AliQnCorrectionsVarManagerTask::kOfflineTriggerFired2, 0, 0.0, 0.0, AliQnCorrectionsVarManagerTask::kNothing, 0, 0.0, 0.0, AliQnCorrectionsVarManagerTask::kNothing, triggerNames.Data()); histos->AddHistogram(classStr.Data(), "CentVZERO_Triggers2", "Offline triggers fired vs centrality VZERO; ; centrality VZERO;", kFALSE, 64, -0.5, 63.5, AliQnCorrectionsVarManagerTask::kOfflineTriggerFired2, 20, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentVZERO, 0, 0.0, 0.0, AliQnCorrectionsVarManagerTask::kNothing, triggerNames.Data()); histos->AddHistogram(classStr.Data(), "CentTPC_Triggers2", "Offline triggers fired vs centrality TPC; ; centrality TPC;", kFALSE, 64, -0.5, 63.5, AliQnCorrectionsVarManagerTask::kOfflineTriggerFired2, 20, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentTPC, 0, 0.0, 0.0, AliQnCorrectionsVarManagerTask::kNothing, triggerNames.Data()); histos->AddHistogram(classStr.Data(), "CentSPD_Triggers2", "Offline triggers fired vs centrality SPD; ; centrality SPD;", kFALSE, 64, -0.5, 63.5, AliQnCorrectionsVarManagerTask::kOfflineTriggerFired2, 20, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentSPD, 0, 0.0, 0.0, AliQnCorrectionsVarManagerTask::kNothing, triggerNames.Data()); histos->AddHistogram(classStr.Data(), "CentZDC_Triggers2", "Offline triggers fired vs centrality ZDC; ; centrality ZDC;", kFALSE, 64, -0.5, 63.5, AliQnCorrectionsVarManagerTask::kOfflineTriggerFired2, 20, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentZDC, 0, 0.0, 0.0, AliQnCorrectionsVarManagerTask::kNothing, triggerNames.Data()); histos->AddHistogram(classStr.Data(), "VtxZ_Triggers2", "Offline triggers fired vs vtxZ; ; vtx Z (cm.);", kFALSE, 64, -0.5, 63.5, AliQnCorrectionsVarManagerTask::kOfflineTriggerFired2, 200, -20.0, 20.0, AliQnCorrectionsVarManagerTask::kVtxZ, 0, 0.0, 0.0, AliQnCorrectionsVarManagerTask::kNothing, triggerNames.Data()); continue; } // Track histograms if (classStr.Contains("Tracks")) { histos->AddHistClass(classStr.Data()); for (Int_t ih = 0; ih < 6; ++ih) { histos->AddHistogram( classStr.Data(), Form("Cos%dPhi_CentVZERO", ih + 1), Form("<cos%d #varphi> vs (CentVZERO); centrality VZERO; <cos%d #varphi>", ih + 1, ih + 1), kTRUE, 20, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentVZERO, 500, -1., 1., AliQnCorrectionsVarManagerTask::kCosNPhi + ih); histos->AddHistogram( classStr.Data(), Form("Sin%dPhi_CentVZERO", ih + 1), Form("<sin%d #varphi> vs (CentVZERO); centrality VZERO; <sin%d #varphi>", ih + 1, ih + 1), kTRUE, 20, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentVZERO, 500, -1.0, 1.0, AliQnCorrectionsVarManagerTask::kSinNPhi + ih); } } // Track histograms if (classStr.Contains("TrackQA")) { histos->AddHistClass(classStr.Data()); histos->AddHistogram(classStr.Data(), "Pt", "p_{T} distribution; p_{T} (GeV/c^{2});", kFALSE, 1000, 0.0, 50.0, AliQnCorrectionsVarManagerTask::kPt); histos->AddHistogram(classStr.Data(), "Eta", "#eta illumination; #eta;", kFALSE, 1000, -1.5, 1.5, AliQnCorrectionsVarManagerTask::kEta); histos->AddHistogram(classStr.Data(), "Phi", "#varphi illumination; #varphi;", kFALSE, 1000, 0.0, 6.3, AliQnCorrectionsVarManagerTask::kPhi); histos->AddHistogram(classStr.Data(), "DCAxy", "DCAxy; DCAxy (cm.)", kFALSE, 1000, -10.0, 10.0, AliQnCorrectionsVarManagerTask::kDcaXY); histos->AddHistogram(classStr.Data(), "DCAz", "DCAz; DCAz (cm.)", kFALSE, 1000, -10.0, 10.0, AliQnCorrectionsVarManagerTask::kDcaZ); histos->AddHistogram(classStr.Data(), "TPCncls", "TPCncls; TPCncls", kFALSE, 160, 0.0, 160.0, AliQnCorrectionsVarManagerTask::kTPCncls); histos->AddHistogram(classStr.Data(), "TPCsa_TPCncls", "TPC standalone TPCncls; TPCncls", kFALSE, 160, 0.0, 160.0, AliQnCorrectionsVarManagerTask::kTPCnclsIter1); // run dependence histos->AddHistogram(classStr.Data(), "Pt_Run", "<p_{T}> vs run; run;", kTRUE, kNRunBins, runHistRange[0], runHistRange[1], AliQnCorrectionsVarManagerTask::kRunNo, 1000, 0.0, 50.0, AliQnCorrectionsVarManagerTask::kPt); histos->AddHistogram(classStr.Data(), "Eta_Run", "<#eta> vs run; run;", kTRUE, kNRunBins, runHistRange[0], runHistRange[1], AliQnCorrectionsVarManagerTask::kRunNo, 1000, -1.5, 1.5, AliQnCorrectionsVarManagerTask::kEta); histos->AddHistogram(classStr.Data(), "Phi_Run", "<#varphi> vs run; run;", kTRUE, kNRunBins, runHistRange[0], runHistRange[1], AliQnCorrectionsVarManagerTask::kRunNo, 1000, 0.0, 6.3, AliQnCorrectionsVarManagerTask::kPhi); histos->AddHistogram(classStr.Data(), "DCAxy_Run", "<DCAxy> vs run; run;", kTRUE, kNRunBins, runHistRange[0], runHistRange[1], AliQnCorrectionsVarManagerTask::kRunNo, 1000, -10.0, 10.0, AliQnCorrectionsVarManagerTask::kDcaXY); histos->AddHistogram(classStr.Data(), "DCAz_Run", "<DCAz> vs run; run;", kTRUE, kNRunBins, runHistRange[0], runHistRange[1], AliQnCorrectionsVarManagerTask::kRunNo, 1000, -10.0, 10.0, AliQnCorrectionsVarManagerTask::kDcaZ); // correlations between parameters histos->AddHistogram(classStr.Data(), "Eta_Pt_prof", "<p_{T}> vs #eta; #eta; p_{T} (GeV/c);", kTRUE, 300, -1.5, +1.5, AliQnCorrectionsVarManagerTask::kEta, 100, 0.0, 10.0, AliQnCorrectionsVarManagerTask::kPt); histos->AddHistogram(classStr.Data(), "Phi_Pt", "p_{T} vs #varphi; #varphi (rad.); p_{T} (GeV/c)", kFALSE, 300, -0.01, 6.3, AliQnCorrectionsVarManagerTask::kPhi, 100, 0.0, 2.2, AliQnCorrectionsVarManagerTask::kPt); histos->AddHistogram(classStr.Data(), "Phi_Pt_prof", "<p_{T}> vs #varphi; #varphi (rad.); p_{T} (GeV/c)", kTRUE, 300, 0.0, 6.3, AliQnCorrectionsVarManagerTask::kPhi, 100, 0.0, 10.0, AliQnCorrectionsVarManagerTask::kPt); histos->AddHistogram(classStr.Data(), "Eta_Phi", "#varphi vs #eta; #eta; #varphi (rad.);", kFALSE, 200, -1.0, +1.0, AliQnCorrectionsVarManagerTask::kEta, 100, 0.0, 6.3, AliQnCorrectionsVarManagerTask::kPhi); histos->AddHistogram( classStr.Data(), "TPCncls_Eta_Phi_prof", "<TPC ncls> vs #varphi vs #eta; #eta; #varphi (rad.);TPC ncls", kTRUE, 200, -1.0, +1.0, AliQnCorrectionsVarManagerTask::kEta, 100, 0.0, 6.3, AliQnCorrectionsVarManagerTask::kPhi, 10, 0.0, 200., AliQnCorrectionsVarManagerTask::kTPCncls); histos->AddHistogram( classStr.Data(), "DCAxy_Eta_Phi_prof", "<DCAxy> vs #varphi vs #eta; #eta; #varphi (rad.);DCAxy (cm)", kTRUE, 200, -1.0, +1.0, AliQnCorrectionsVarManagerTask::kEta, 100, 0.0, 6.3, AliQnCorrectionsVarManagerTask::kPhi, 10, 0.0, 200., AliQnCorrectionsVarManagerTask::kDcaXY); histos->AddHistogram( classStr.Data(), "DCAz_Eta_Phi_prof", "<DCAz> vs #varphi vs #eta; #eta; #varphi (rad.);DCAz (cm)", kTRUE, 200, -1.0, +1.0, AliQnCorrectionsVarManagerTask::kEta, 100, 0.0, 6.3, AliQnCorrectionsVarManagerTask::kPhi, 10, 0.0, 200., AliQnCorrectionsVarManagerTask::kDcaZ); histos->AddHistogram(classStr.Data(), "Pt_DCAxy", "DCAxy vs p_{T}; p_{T} (GeV/c); DCA_{xy} (cm)", kFALSE, 100, 0.0, 10.0, AliQnCorrectionsVarManagerTask::kPt, 500, -2.0, 2.0, AliQnCorrectionsVarManagerTask::kDcaXY); histos->AddHistogram(classStr.Data(), "Pt_DCAz", "DCAz vs p_{T}; p_{T} (GeV/c); DCA_{z} (cm)", kFALSE, 100, 0.0, 10.0, AliQnCorrectionsVarManagerTask::kPt, 500, -2.0, 2.0, AliQnCorrectionsVarManagerTask::kDcaZ); histos->AddHistogram(classStr.Data(), "Eta_DCAxy", "DCAxy vs #eta; #eta; DCA_{xy} (cm)", kFALSE, 100, -1.0, 1.0, AliQnCorrectionsVarManagerTask::kEta, 500, -2.0, 2.0, AliQnCorrectionsVarManagerTask::kDcaXY); histos->AddHistogram(classStr.Data(), "Eta_DCAz", "DCAz vs #eta; #eta; DCA_{z} (cm)", kFALSE, 100, -1.0, 1.0, AliQnCorrectionsVarManagerTask::kEta, 500, -2.0, 2.0, AliQnCorrectionsVarManagerTask::kDcaZ); for (Int_t ih = 0; ih < 6; ++ih) { // histos->AddHistogram(classStr.Data(), Form("Cos%dPhi_CentVZERO",ih+1), Form("<cos%d #varphi> vs // (CentVZERO); centrality VZERO; <cos%d #varphi>", ih+1, ih+1), kTRUE, // 20, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentVZERO, 500, -1., 1., // AliQnCorrectionsVarManagerTask::kCosNPhi+ih); // histos->AddHistogram(classStr.Data(), Form("Sin%dPhi_CentVZERO",ih+1), Form("<sin%d #varphi> vs // (CentVZERO); centrality VZERO; <sin%d #varphi>", ih+1, ih+1), kTRUE, // 20, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentVZERO, 500, -1.0, 1.0, // AliQnCorrectionsVarManagerTask::kSinNPhi+ih); histos->AddHistogram( classStr.Data(), Form("Cos%dPhi_Pt_Eta", ih + 1), Form("<cos%d #varphi> vs (#eta,p_{T}); #eta; p_{T} (GeV/c); <cos%d #varphi>", ih + 1, ih + 1), kTRUE, 20, -1.0, 1.0, AliQnCorrectionsVarManagerTask::kEta, 30, 0.0, 3.0, AliQnCorrectionsVarManagerTask::kPt, 500, -1.0, 1.0, AliQnCorrectionsVarManagerTask::kCosNPhi + ih); histos->AddHistogram( classStr.Data(), Form("Sin%dPhi_Pt_Eta", ih + 1), Form("<sin%d #varphi> vs (#eta,p_{T}); #eta; p_{T} (GeV/c); <sin%d #varphi>", ih + 1, ih + 1), kTRUE, 20, -1.0, 1.0, AliQnCorrectionsVarManagerTask::kEta, 30, 0.0, 3.0, AliQnCorrectionsVarManagerTask::kPt, 500, -1.0, 1.0, AliQnCorrectionsVarManagerTask::kSinNPhi + ih); histos->AddHistogram( classStr.Data(), Form("Cos%dPhi_CentVZERO_VtxZ", ih + 1), Form("<cos%d #varphi> vs (CentVZERO,VtxZ); Z (cm.); centrality VZERO; <cos%d #varphi>", ih + 1, ih + 1), kTRUE, 30, -15.0, 15.0, AliQnCorrectionsVarManagerTask::kVtxZ, 20, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentVZERO, 500, -1., 1., AliQnCorrectionsVarManagerTask::kCosNPhi + ih); histos->AddHistogram( classStr.Data(), Form("Sin%dPhi_CentVZERO_VtxZ", ih + 1), Form("<sin%d #varphi> vs (CentVZERO,VtxZ); Z (cm.); centrality VZERO; <sin%d #varphi>", ih + 1, ih + 1), kTRUE, 30, -15.0, 15.0, AliQnCorrectionsVarManagerTask::kVtxZ, 20, 0.0, 100.0, AliQnCorrectionsVarManagerTask::kCentVZERO, 500, -1.0, 1.0, AliQnCorrectionsVarManagerTask::kSinNPhi + ih); } } // Tracklet histograms if (classStr.Contains("TrackletQA")) { histos->AddHistClass(classStr.Data()); histos->AddHistogram(classStr.Data(), "Eta", "#eta illumination; #eta;", kFALSE, 1000, -3.0, 3.0, AliQnCorrectionsVarManagerTask::kSPDtrackletEta); histos->AddHistogram(classStr.Data(), "Phi", "#varphi illumination; #varphi;", kFALSE, 300, -0.01, 6.3, AliQnCorrectionsVarManagerTask::kSPDtrackletPhi); histos->AddHistogram(classStr.Data(), "Eta_Phi", "#varphi vs #eta; #eta; #varphi (rad.);", kFALSE, 200, -3.0, +3.0, AliQnCorrectionsVarManagerTask::kSPDtrackletEta, 100, 0.0, 6.3, AliQnCorrectionsVarManagerTask::kSPDtrackletPhi); } } AliInfoGeneralStream("PWGJE::EMCALJetTasks::FlowVectorCorrections::DefineHistograms") << " done\n"; } } /* namespace EMCALJetTasks */ } /* namespace PWGJE */
[ "raymond.ehlers@gmail.com" ]
raymond.ehlers@gmail.com
68b57e9c0f561e49477f484c58ec6a7578559356
997f127729c9d2e4a4597e5d8a007bd4d4af1cde
/Source/TestDll2/TestDll2.cpp
b2fd0c34057f355e85b10945bd086d3336dcf8b5
[]
no_license
tainguyen197/MouseHook
2cee92c3f275d2c75a7db01a6e94324fec081e77
27fd379ccd13f912ea2bc244028424e24990dcbf
refs/heads/master
2021-05-06T16:32:17.764280
2017-12-10T15:58:16
2017-12-10T15:58:16
113,756,080
0
0
null
null
null
null
UTF-8
C++
false
false
6,384
cpp
// TestHookWithDll.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "TestDll2.h" #define MAX_LOADSTRING 100 // Global Variables: HINSTANCE hInst; // current instance TCHAR szTitle[MAX_LOADSTRING]; // The title bar text TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name #define REMOVE 10000 #define SETUP 10001 void doInstallHook(HWND hWnd); void doRemoveHook(HWND hWnd); // Forward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: Place code here. MSG msg; HACCEL hAccelTable; // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_TESTDLL2, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance(hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_TESTDLL2)); // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int)msg.wParam; } // // FUNCTION: MyRegisterClass() // // PURPOSE: Registers the window class. // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_TESTDLL2)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_TESTDLL2); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } // // FUNCTION: InitInstance(HINSTANCE, int) // // PURPOSE: Saves instance handle and creates main window // // COMMENTS: // // In this function, we save the instance handle in a global variable and // create and display the main program window. // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd, hwnd; hInst = hInstance; // Store instance handle in our global variable hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, 400,100,300,300, NULL, NULL, hInstance, NULL); //InitCommonControls(); hwnd = CreateWindowEx(0, L"STATIC", L"Cài đặt hook -->", WS_CHILD | WS_VISIBLE, 30, 50, 106, 23, hWnd, NULL, hInst, NULL); hwnd = CreateWindowEx(0, L"STATIC", L"Gỡ cài đặt hook -->", WS_CHILD | WS_VISIBLE, 30, 150, 130, 23, hWnd, NULL, hInst, NULL); hwnd = CreateWindowEx(0, L"BUTTON", L"Setup", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 200, 50, 50, 23, hWnd, (HMENU)SETUP, hInst, NULL); hwnd = CreateWindowEx(0, L"BUTTON", L"Remove", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 200, 150, 60, 23, hWnd, (HMENU) REMOVE, hInst, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, SW_SHOW); //ShowWindow(hWnd, SW_HIDE); // MessageBox(hWnd, L"Hook đã được cài đặt, bấm Ctrl + Chuột phải để bắt đầu", L"Thành công", 0); UpdateWindow(hWnd); return TRUE; } // // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // bool isHook = false; LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; //doInstallHook(hWnd); switch (message) { case WM_CTLCOLORSTATIC: // dùng để thay đổi màu lớp static SetBkMode((HDC)wParam, TRANSPARENT); return (LRESULT)GetStockObject(NULL_BRUSH); break; case WM_COMMAND: if (LOWORD(wParam) == SETUP){ doInstallHook(hWnd); break; } if (LOWORD(wParam) == REMOVE){ doRemoveHook(hWnd); break; } switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); // TODO: Add any drawing code here... EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // Message handler for about box. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; } void doInstallHook(HWND hWnd) { // gọi hàm DLL theo kiểu Run-time // Định nghĩa prototype của hàm typedef VOID(*MYPROC)(HWND); HINSTANCE hinstLib; MYPROC ProcAddr; // load DLL và lấy handle của DLL module hinstLib = LoadLibrary(L"DllHook1.dll"); // Nếu load thành công, lấy địa chỉ của hàm DrawCircle trong DLL if (hinstLib != NULL) { ProcAddr = (MYPROC)GetProcAddress(hinstLib, "_doInstallHook"); // Nếu lấy được địa chỉ hàm, gọi thực hiện hàm if (ProcAddr != NULL) ProcAddr(hWnd); } } void doRemoveHook(HWND hWnd) { // gọi hàm DLL theo kiểu Run-time // Định nghĩa prototype của hàm typedef VOID(*MYPROC)(HWND); HINSTANCE hinstLib; MYPROC ProcAddr; // load DLL và lấy handle của DLL module hinstLib = LoadLibrary(L"DllHook1.dll"); // Nếu load thành công, lấy địa chỉ của hàm DrawCircle trong DLL if (hinstLib != NULL) { ProcAddr = (MYPROC)GetProcAddress(hinstLib, "_doRemoveHook"); // Nếu lấy được địa chỉ hàm, gọi thực hiện hàm if (ProcAddr != NULL) ProcAddr(hWnd); } }
[ "tainguyen197.ntt@gmail.com" ]
tainguyen197.ntt@gmail.com
006467255caa1c150a267957cf2f2814bbb47c71
784c77cfdeb1bbb293905cf6b305f5fc286b5bed
/Assignment2/Weather.cpp
10f2c5e3c23e1dd6398ec55ce88066bc92c880fd
[]
no_license
Veggipuppet/WeatherTime
bb4fb222ccfc6d071d9e08464f4bbf97929b30e1
ee2804655091920289c69b71b29f5b97f3c00d09
refs/heads/master
2021-07-12T19:10:15.835055
2017-09-28T01:23:30
2017-09-28T01:23:30
104,907,594
0
0
null
null
null
null
UTF-8
C++
false
false
3,231
cpp
#include "Weather.h" Weather::Weather() { count = 0; } Weather::~Weather() { //dtor } int Weather::GetCount() const { return count; } void Weather::SetCount( unsigned ct ) { count = ct; } const Data& Weather::GetData(unsigned count) const { //return Array.retrieveAt(count); } void Weather::SetData(const Data& Da, unsigned count) { YearDateMap[Da.GetDate().GetYear()][Da.GetDate().GetMonth()].push_back(Da); //Array.insertEnd(Da); } void Weather::MaxWindSpeed( int month, int year, void maxx(Data & da)) { //maxWSpeed = 0; binaryTreeType<Data> DataTree; for(unsigned j=0; j <YearDateMap[year][month].size(); j++) { DataTree.insert(YearDateMap[year][month].at(j)); } DataTree.inorderTraversal( maxx); //DataTree.preorderTraversal(); } void Weather::AverageWindSpeed(float tempAvWSpeed[], int year) { float AveWSpeed; int counter; for(int i=0; i<12; i++) { AveWSpeed = 0; counter = 0; for(unsigned j=0; j <YearDateMap[year][i+1].size(); j++) { AveWSpeed = AveWSpeed + YearDateMap[year][i+1].at(j).GetWindSpeed(); counter++; } if(counter != 0) { tempAvWSpeed[i] = (AveWSpeed/counter); } else { tempAvWSpeed[i] = 0; } } } void Weather::TotalSolarRadiation(float TotSolarRad[], int year) { float TSR = 0; for(int i=0; i<12; i++) { TSR = 0; for(unsigned j=0; j <YearDateMap[year][i+1].size(); j++) { if(YearDateMap[year][i+1].at(j).GetSolarRadiation()>80) { TSR = TSR + YearDateMap[year][i+1].at(j).GetSolarRadiation(); } } if(TSR != 0) { TSR = (TSR/6000); TotSolarRad[i] = TSR; } else { TotSolarRad[i] = 0; } } } float Weather::MaxSolarRadiation( int day, int month, int year, vector<int>* VectorInt) { float MaxSolarRad=0; for(unsigned j=0; j <YearDateMap[year][month].size(); j++) { if(day == YearDateMap[year][month].at(j).GetDate().GetDay()) { if(MaxSolarRad < YearDateMap[year][month].at(j).GetSolarRadiation()) { MaxSolarRad = YearDateMap[year][month].at(j).GetSolarRadiation(); } } } for(unsigned j=0; j <YearDateMap[year][month].size(); j++) { if(YearDateMap[year][month].at(j).GetDate().GetDay() == day) { if(MaxSolarRad == YearDateMap[year][month].at(j).GetSolarRadiation()) { VectorInt->push_back(YearDateMap[year][month].at(j).GetTime().GetHour()); VectorInt->push_back(YearDateMap[year][month].at(j).GetTime().GetMinute()); } } } return MaxSolarRad; } istream & operator >>( istream & input, Weather & W ) { string tempString; static Data Dataobj; unsigned count = W.GetCount(); getline(input,tempString); while(!input.eof()) { input >> Dataobj; W.SetData(Dataobj, count); count++; W.SetCount(count); } return input; }
[ "33014212@student.murdoch.edu.au" ]
33014212@student.murdoch.edu.au
6d9de7bca601d87573a90c811901792b6f2c156e
63a043c4a9fa2a7079b844d59d4d3dddc31b5655
/client.cpp
b9a75df1af8e6d45edc74d331e428154012e1e23
[]
no_license
nevermore3/chatroom_client
b0fed0afc880d0485193d76b21b75d94f62e0fd2
04c3c6b2d4a5e06dc2e014c54b50ff1259e18b27
refs/heads/master
2021-05-25T16:12:26.102778
2020-04-07T14:49:41
2020-04-07T14:49:41
253,820,834
0
0
null
null
null
null
UTF-8
C++
false
false
4,511
cpp
// // Created by jmq on 2020/4/7. // #include "client.h" #include <iostream> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/epoll.h> #include <fcntl.h> #include <cerrno> #include <unistd.h> #include <cstdio> #include <cstdlib> #include <cstring> using namespace std; Client::Client(const char *serverIp, int port) { bzero(&serverAddr_, sizeof(serverAddr_)); serverAddr_.sin_family = PF_INET; serverAddr_.sin_port = htons(port); serverAddr_.sin_addr.s_addr = inet_addr(serverIp); sock_ = socket(PF_INET, SOCK_STREAM, 0); if (sock_ < 0) { perror("create sock error"); exit(-1); } epFd_ = epoll_create(1000); if (epFd_ < 0) { perror("epoll_create error"); exit(-1); } } void Client::Start() { if (connect(sock_, (struct sockaddr *)&serverAddr_, sizeof(serverAddr_)) < 0) { perror("connect error"); exit(-1); } /* * 子进程: 1.等待用户输入信息 2. 将聊天信息写入到管道pipe中,并发送给父进程 * 父进程 1.使用epoll机制接受服务端发来的信息,并显示给用户 2.将子进程发的信息从管道中读出,并发送给服务器 */ //pipeFd[0] 父进程读, pipeFd[1] 子进程写 int pipeFd[2]; if (pipe(pipeFd) < 0) { perror("create pipe error"); exit(-1); } struct epoll_event events[2]; AddFd(sock_); // 有数据读时,通知 AddFd(pipeFd[0]); char message[BUF_SIZE] = {0}; // bool run = true; int pid = fork(); if (pid < 0) { perror("fork error"); exit(-1); } else if (pid == 0) { //子进程:1.等待用户输入信息 2. 将聊天信息写入到管道pipe中,并发送给父进程 close(pipeFd[0]); cout<<"Enter string to send "<<endl; while(run) { bzero(message, BUF_SIZE); cin.getline(message, BUF_SIZE); // 将消息写入管道 if (write(pipeFd[1], message, strlen(message)) < 0) { perror("write error"); exit(-1); } if (!strcmp(message, "exit")) { sleep(1); break; } } } else { //父进程:1.使用epoll机制接受服务端发来的信息,并显示给用户 2.将子进程发的信息从管道中读出,并发送给服务器 close(pipeFd[1]); while (run) { int readyNum = epoll_wait(epFd_, events, 2, -1); if (readyNum < 0) { perror("epoll_wait error"); exit(-1); } for (int i = 0; i < readyNum; i++) { bzero(message, BUF_SIZE); if (events[i].data.fd == sock_) { // 服务器发来的消息 int ret = recv(sock_, message, BUF_SIZE, 0); if (ret == 0) { //服务端关闭 close(sock_); run = false; } else { cout << string(message) << endl; } } else { //来自子进程的消息 int ret = read(events[i].data.fd, message, BUF_SIZE); if (ret == 0) { run = false; } else { if (send(sock_, message, strlen(message), 0) < 0) { perror("send error"); exit(-1); } if (!strcmp(message, "exit")) { sleep(1); return; } } } } } } } /* * enable : 决定epoll是LT或者ET模式 */ void Client::AddFd( int fd) { struct epoll_event ev; ev.data.fd = fd; // true : 边缘模式, 一次读不完下次不在读直到有消息再来 bool enable = true; ev.events = EPOLLIN; if (enable) { ev.events = EPOLLIN | EPOLLET; } if (epoll_ctl(epFd_, EPOLL_CTL_ADD, fd, &ev) == -1) { perror("epoll_ctl Error"); exit(-1); } //设置socket为非阻塞 fcntl(fd, F_SETFL, fcntl(fd, F_GETFD, 0) | O_NONBLOCK); cout<< fd << " 加入到 EPOLL中" << endl; } Client::~Client() { close(sock_); }
[ "58863790@qq.com" ]
58863790@qq.com
9e4fa24c773960b1ff1e8ce1f8bd742ede51baa5
844dae580af988899a9ee5e577906fb05852e541
/Building_Escape/Source/Building_Escape/PositionReporter.h
ea5ca516d4878d4d7aa1c0bb49556b89c67eec61
[]
no_license
MuntaseerHafizSazid/Building-Escape
8fc80597f173f54793a7020565d3e166d490fb3b
1ced8b52f7249c91ae4aa6858f69bc76c5840578
refs/heads/main
2023-04-20T08:23:03.058009
2021-05-07T05:07:49
2021-05-07T05:07:49
365,118,439
0
0
null
null
null
null
UTF-8
C++
false
false
686
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/ActorComponent.h" #include "PositionReporter.generated.h" UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) ) class BUILDING_ESCAPE_API UPositionReporter : public UActorComponent { GENERATED_BODY() public: // Sets default values for this component's properties UPositionReporter(); protected: // Called when the game starts virtual void BeginPlay() override; public: // Called every frame virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override; };
[ "48057151+MuntaseerHafizSazid@users.noreply.github.com" ]
48057151+MuntaseerHafizSazid@users.noreply.github.com
cdd008d6c7a12a2b8f3c3b74a80155865c9ac348
6c32bba01c7c497da481d3f1450f1282425058ff
/ex2.14/ex2.14.cpp
7ae79a799a5de0aa506f5d485409b28df8b97418
[]
no_license
jjlytle/CppPrimer
dc684dcc58bebda2c3f3148c11b601341ca653a5
bcfc2cdd6e0ce7359ad86c429c148c48612a868d
refs/heads/master
2022-12-06T05:18:08.871402
2020-09-04T18:48:03
2020-09-04T18:48:03
292,922,588
0
0
null
null
null
null
UTF-8
C++
false
false
203
cpp
#include <iostream> int main(int argc, char *argv[]) { int i = 100, sum = 0; for (int i = 0; i != 10; ++i) { sum += i; } std::cout << i << " " << sum << std::endl; }
[ "jlytle63704@hotmail.com" ]
jlytle63704@hotmail.com
b89c8905e82e8c7e432a4ee733c3982ebc3713e0
ed4294eb2dff039df8e60e4af7300df7a39d771d
/kmers/src/kmers/fasta.hpp
eca00d11447d12d50357742fbce089ff1e23834e
[ "BSD-3-Clause" ]
permissive
jgabry/case-studies
76ffec19ee8eba2996febd4c275727a9bd8831a9
6d3f6a2703ea955ff0af355e4794abacecfb5bf7
refs/heads/master
2023-01-15T21:45:47.019699
2020-11-01T16:53:31
2020-11-01T16:53:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,058
hpp
#ifndef FASTA_HPP #define FASTA_HPP #include <cmath> #include <cstdint> #include <exception> #include <fstream> #include <iostream> #include <map> #include <numeric> #include <sstream> #include <Eigen/Dense> #include <Eigen/Sparse> /** * A structure to hold a map from k-mer indexes to k-mer counts. */ struct counter { std::map<size_t, size_t> counts_; /** * Increment the count for the specified key by one. * * @param key key whose count is incremented */ void increment(size_t key) { if (counts_.find(key) == counts_.end()) counts_[key] = 0; ++counts_[key]; } /** * Return the sum of the values of all of the keys. */ size_t count() const { size_t y = 0; for (const auto& key_count : counts_) y += key_count.second; return y; } }; /** * Return the identifier in the range 0-3 for the specified base. * The mapping is defined alphabetically, indexing from zero, so that * 'A' maps to 0, 'C' maps to 1, 'G' maps to 2, and 'T' maps to 3, * with any other input throwing an exception. * * @param c character representing a base * @return numerical identifier for the base * @throw std::runtime_error if c is not one of 'A', 'C', 'G', or * 'T'. */ std::size_t base_id(char c) { switch (c) { case 'A' : return 0; case 'C' : return 1; case 'G' : return 2; case 'T' : return 3; default: throw std::runtime_error("argument to base_id must be one of:" "'A', 'C', 'G', 'T'"); } } /** * Return a numerical identifier for the specified kmer. Each k-mer * is read as a base-4 number given the base_id() for each k-mer. * Thus uniqueness is only guaranteed if two kmers are of the same length. * * @param kmer string representing a k-mer * @return identifier for the k-mer. * @throw std::runtime_error if there are characters in kmer other * than 'A', 'C', 'G', or 'T'. */ std::size_t kmer_id(const std::string& kmer) { size_t id = 0; for (auto it = kmer.cbegin(); it != kmer.cend(); ++it) id = 4 * id + base_id(*it); return id; } /** * A holder mapping sequence ids to their sequence and k-mers. */ struct seq_map { using mat_t = Eigen::SparseMatrix<double, Eigen::RowMajor>; using trip_t = Eigen::Triplet<double>; using trips_t = std::vector<trip_t>; std::map<std::string, std::string> id_to_seq_; int64_t K_; /** * Return the number of sequences in the domain of the map. * * @return number of sequences being mapped */ int64_t size() const { return id_to_seq_.size(); } /** * Return the total number of bases in the range of the map. * * @return total number of bases in the map */ int64_t total_bases() const { return std::accumulate(id_to_seq_.begin(), id_to_seq_.end(), 0, [](const auto& tot, const auto& seq) { return tot + seq.second.size(); }); } /** * Return the total number of unique k-mers using this map's k-mer * size. * * @return total number of unique k-mers */ int64_t kmers() const { return pow(4, K_); } /** * Return a vector of strings corresponding to the sequences in the * domain of this map. * * @return the identifiers being mapped */ std::vector<std::string> identifiers() const { std::vector<std::string> ids; for (const auto& id_seq : id_to_seq_) { ids.push_back(id_seq.first); } return ids; } /** */ mat_t kmer_gene_matrix() const { size_t num_kmers = kmers(); mat_t m(kmers(), size()); trips_t trips; size_t id = 0; for (const auto& id_seq : id_to_seq_) { std::string seq = id_seq.second; counter c; for (size_t i = 0; i + K_ < seq.size(); ++i) { auto kmer = seq.substr(i, K_); auto k_id = kmer_id(kmer); c.increment(k_id); } double seq_sz = c.count(); for (const auto& kmerid_count : c.counts_) trips.push_back(trip_t(kmerid_count.first, id, kmerid_count.second / seq_sz)); ++id; } m.setFromTriplets(trips.begin(), trips.end()); return m; } /** * Read FASTA formatted data from file with specified name. * @param K length of K-mers * @param filename name of file from which to read */ seq_map(int64_t K, const std::string& filename) : K_(K) { std::ifstream in(filename, std::ifstream::in); std::string line; int64_t count = 0; int64_t total_bases = 0; while (std::getline(in, line)) { if (line.length() == 0 || line[0] != '>') continue; if (line[0] == '>') { std::string id = line.substr(2); std::stringstream val; while (std::getline(in, line) && line.length() > 0) val << line; std::string bp_seq = val.str(); id_to_seq_[id] = bp_seq; total_bases += bp_seq.size(); } } in.close(); } }; Eigen::VectorXd softmax(const Eigen::VectorXd& alpha) { auto alpha_exp = alpha.array().exp(); return alpha_exp / alpha_exp.sum(); } struct log_posterior_gradient { const double lambda_; const Eigen::VectorXd& y_; // 4^K x 1 const seq_map::mat_t& x_; // 4^K x G log_posterior_gradient(double lambda, const Eigen::VectorXd& y, const seq_map::mat_t& x) : lambda_(lambda), y_(y), x_(x) { } double operator()(const Eigen::VectorXd& alpha, Eigen::VectorXd& grad) { // implementation lifted and lightly refactored from matrixcalculus.org Eigen::VectorXd t0 = alpha.array().exp(); double t1 = t0.array().sum(); Eigen::VectorXd t2 = x_.transpose() * (y_.array() * (1 / t1 * x_ * t0).array()).matrix(); double lpd = y_.transpose() * (x_ * t0 / t1) + alpha.dot(alpha) / (2 * lambda_); grad = (((1 / t1) * t2).array() * t0.array()).matrix() - 1 / (t1 * t1) * t0.transpose() * t2 * t0 - 1 / lambda_ * alpha; return lpd; } }; // (y).dot(np.log(t_1)) - ((a).dot(a) / (2 * s)) #endif
[ "carp@alias-i.com" ]
carp@alias-i.com
c2ed6db1d61e9544f88320902813845e79ca0f19
9f2f386a692a6ddeb7670812d1395a0b0009dad9
/paddle/phi/kernels/cpu/elementwise_add_kernel.cc
5019b9f57062874b5f78a002dbf1cdd411bc4e9c
[ "Apache-2.0" ]
permissive
sandyhouse/Paddle
2f866bf1993a036564986e5140e69e77674b8ff5
86e0b07fe7ee6442ccda0aa234bd690a3be2cffa
refs/heads/develop
2023-08-16T22:59:28.165742
2022-06-03T05:23:39
2022-06-03T05:23:39
181,423,712
0
7
Apache-2.0
2022-08-15T08:46:04
2019-04-15T06:15:22
C++
UTF-8
C++
false
false
2,716
cc
// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/phi/kernels/cpu/elementwise.h" #include "paddle/phi/api/ext/dispatch.h" #include "paddle/phi/backends/cpu/cpu_context.h" #include "paddle/phi/common/bfloat16.h" #include "paddle/phi/common/complex.h" #include "paddle/phi/core/kernel_registry.h" #include "paddle/phi/kernels/impl/elementwise_kernel_impl.h" namespace phi { // Create the definition of Add DEFINE_CPU_ELEMENTWISE_OP(Add) template <typename T, typename Context> void AddKernel(const Context& dev_ctx, const DenseTensor& x, const DenseTensor& y, DenseTensor* out) { int axis = -1; AddRawKernel<T>(dev_ctx, x, y, axis, out); } template <typename T, typename Context> void GradAddKernel(const Context& dev_ctx, const DenseTensor& x, const DenseTensor& y, DenseTensor* out) { AddKernel<T>(dev_ctx, x, y, out); } } // namespace phi using complex64 = ::phi::dtype::complex<float>; using complex128 = ::phi::dtype::complex<double>; // NOTE(chenweihang): using bfloat16 will cause redefine with xpu bfloat16 // using bfloat16 = ::phi::dtype::bfloat16; PD_REGISTER_KERNEL(add_raw, CPU, ALL_LAYOUT, phi::AddRawKernel, float, double, int16_t, int, int64_t, complex64, complex128) {} PD_REGISTER_KERNEL(add, CPU, ALL_LAYOUT, phi::AddKernel, float, double, int16_t, int, int64_t, complex64, complex128) {} PD_REGISTER_KERNEL(grad_add, CPU, ALL_LAYOUT, phi::GradAddKernel, float, double, int16_t, int, int64_t, complex64, complex128) {}
[ "noreply@github.com" ]
noreply@github.com
eff0989b8de25eb4532118bbbd75330c1347b830
a2cdee2002d22ab8812157e0c0513441976c7e2c
/algorithm/cpp/462.cpp
d6ec6b913a68f28e354ede577562b8ed45759944
[]
no_license
authuir/leetcode
065c205cbc6a2498aa4919a32b167ed64605a1ca
9fe479fbcf0e64ed1a132bc0b6986a8f0c82581c
refs/heads/master
2021-01-20T14:31:11.091259
2018-09-19T15:58:25
2018-09-19T15:58:25
90,624,148
1
0
null
null
null
null
UTF-8
C++
false
false
335
cpp
#include <stdlib.h> class Solution { public: int minMoves2(vector<int>& nums) { sort(nums.begin(), nums.end()); int len = nums.size(); if (len % 2 == 1) { len = len - 1; } len = len / 2; int ev = nums[len]; int rtn = 0; for (int i = 0; i< nums.size(); i++) { rtn += abs(nums[i] - ev); } return rtn; } };
[ "authuir@authuir.com" ]
authuir@authuir.com
0ff99a6483836c24d99b25a65144de8029b2fb54
a07d24ea79608189dd5957981fa6c458c23a0d32
/ReachAGivenScore.cpp
a5e551810d16d5dbef4291d1f0e23d7ac1690f3d
[]
no_license
yyyashikaaa/Solutions-to-Basic-Dynamic-Programming-Questions
412bbfb988dc60178ac32cb7a92ea7205796447f
5f28946ed119ca37d7c5454e0d87d3592ef4aa21
refs/heads/master
2020-09-16T14:16:28.432529
2019-11-24T19:13:40
2019-11-24T19:13:40
223,796,097
0
0
null
null
null
null
UTF-8
C++
false
false
548
cpp
#include<iostream> #include<bits/stdc++.h> using namespace std; int f(int a[],int n,int sum,int dp[][5000]) { if(sum==0) return 1; if(sum<=0 || n<=0) return 0; if(dp[n][sum]!=0) return dp[n][sum]; else { dp[n][sum]=f(a,n-1,sum,dp)+f(a,n,sum-a[n-1],dp); return dp[n][sum]; } } int main() { int t; cin>>t; while(t--) { int a[]={3,5,10}; int n=3; int sum; cin>>sum; int dp[n+1][5000]; memset(dp,0,sizeof(dp)); cout<<f(a,n,sum,dp)<<endl; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
41f98d3de83ec671dfc11786cccc61460b88ce46
58ac7ce414dcbe875e26bb6fae692e3c74f39c4e
/net/tools/content_decoder_tool/content_decoder_tool.cc
809c559f590c5da13eeeeced3581136a343cfb97
[]
no_license
markthomas93/tempwork
f4ba7b4620c1cb806aef40a66692115140b42c90
93c852f3d14c95b2d73077b00e7284ea6f416d84
refs/heads/master
2021-12-10T10:35:39.230466
2016-08-11T12:00:33
2016-08-11T12:00:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,759
cc
// 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. #include <iostream> #include "base/command_line.h" #include "net/base/io_buffer.h" #include "net/filter/filter.h" #include "net/filter/mock_filter_context.h" using net::Filter; namespace { // Print the command line help. void PrintHelp(const char* command_line_name) { std::cout << command_line_name << " content_encoding [content_encoding]..." << std::endl << std::endl; std::cout << "Decodes the stdin into the stdout using an content_encoding " << "list given in arguments. This list is expected to be the " << "Content-Encoding HTTP response header's value split by ','." << std::endl; } } // namespace int main(int argc, char* argv[]) { base::CommandLine::Init(argc, argv); const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); std::vector<std::string> content_encodings = command_line.GetArgs(); if (content_encodings.size() == 0) { PrintHelp(argv[0]); return 1; } std::vector<Filter::FilterType> filter_types; for (const auto& content_encoding : content_encodings) { Filter::FilterType filter_type = Filter::ConvertEncodingToType(content_encoding); if (filter_type == Filter::FILTER_TYPE_UNSUPPORTED) { std::cerr << "Unsupported decoder '" << content_encoding << "'." << std::endl; return 1; } filter_types.push_back(filter_type); } net::MockFilterContext filter_context; std::unique_ptr<Filter> filter(Filter::Factory(filter_types, filter_context)); if (!filter) { std::cerr << "Couldn't create the decoder." << std::endl; return 1; } net::IOBuffer* pre_filter_buf = filter->stream_buffer(); int pre_filter_buf_len = filter->stream_buffer_size(); while (std::cin) { std::cin.read(pre_filter_buf->data(), pre_filter_buf_len); int pre_filter_data_len = std::cin.gcount(); filter->FlushStreamBuffer(pre_filter_data_len); while (true) { const int kPostFilterBufLen = 4096; char post_filter_buf[kPostFilterBufLen]; int post_filter_data_len = kPostFilterBufLen; Filter::FilterStatus filter_status = filter->ReadData(post_filter_buf, &post_filter_data_len); std::cout.write(post_filter_buf, post_filter_data_len); if (filter_status == Filter::FILTER_ERROR) { std::cerr << "Couldn't decode stdin." << std::endl; return 1; } else if (filter_status != Filter::FILTER_OK) { break; } } } return 0; }
[ "gaoxiaojun@gmail.com" ]
gaoxiaojun@gmail.com
6092fe653391a6f542f8d6debe4d36e904626550
6c995ecd08083b3af81d2dd2361e6f20920852d2
/Visual C++ Compatible Version/C++_Project_STU_GRD_MGT_SYS/C++_Project_STU_GRD_MGT_SYS/stdafx.cpp
56a9066d26bf0b3cd84b39b97029d9a55acd8280
[]
no_license
ChulanKumara/Student-Grade-Management-System
f174b1e1c6223a2e99a6a5aef904f2d7d763622e
d912e1387f29e7d879b13653d9413225eea4f919
refs/heads/master
2021-01-12T08:54:22.461643
2016-12-17T08:20:13
2016-12-17T08:20:13
76,712,337
1
0
null
null
null
null
UTF-8
C++
false
false
306
cpp
// stdafx.cpp : source file that includes just the standard includes // C++_Project_STU_GRD_MGT_SYS.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "chulankotudurage@gmail.com" ]
chulankotudurage@gmail.com
746816953cc097d9f7181c0a96b1e6e781ec0942
09dc5a251982bef01de5ae149757d299f62dc3e2
/Constants/WorldSetupValues.hpp
099aa834f8ddff02c5e41e7e18f0b3018ce5f389
[ "Apache-2.0" ]
permissive
Dr-Dan/GOAP-Agent-System
8a11fbef8c29108f8ca05df5ae4d2ef1b7962b4e
fe888fb9e79e547116833c16b23698865dfd662e
refs/heads/master
2021-01-18T21:45:09.256597
2016-10-20T13:48:13
2016-10-20T13:48:13
42,303,383
2
0
null
null
null
null
UTF-8
C++
false
false
283
hpp
// // WorldSetupValues.hpp // grid_agent_refactor // // Created by D J Clarke on 10/09/2016. // // #ifndef WorldSetupValues_hpp #define WorldSetupValues_hpp #include <stdio.h> class WorldSetupValues{ public: static const int NUM_AGENTS{5}; }; #endif /* WorldSetupValues_hpp */
[ "danclarkeman@gmail.com" ]
danclarkeman@gmail.com
ef9dd25947dd644aed6e598bb7d33582d75051b9
2932ddb1e7d23c213e2b682fcaa862657b9a634c
/3DEngine/CoreEngine/Input.h
2204eec5a2c278379c772ff5005b25d41e7bb528
[]
no_license
DSayers21/Mini-Golf
99bd6110563685c419c0bec7f593f7784bf8def0
25912d35df699e5ead9095e2bd4fa2a2feb9bfb6
refs/heads/master
2021-10-02T05:33:08.788295
2018-01-07T18:44:14
2018-01-07T18:44:14
109,312,832
0
0
null
null
null
null
UTF-8
C++
false
false
11,716
h
#pragma once //Includes #include <SDL2/SDL.h> #include "Window.h" #include "Vector2f.h" #include <glm/glm.hpp> namespace D3DEngine { //Number of Keys static const int NUM_KEYS = 512; //Number of mouse buttons static const int NUM_MOUSEBUTTONS = 256; //MouseCodes for SDL2 enum { MOUSE_LEFT_BUTTON = 1, MOUSE_MIDDLE_BUTTON = 2, MOUSE_RIGHT_BUTTON = 3, MOUSE_WHEEL_UP = 4, MOUSE_WHEEL_DOWN = 5 }; //KeyCodes for SDL2 enum { KEY_UNKNOWN = 0, /** * \name Usage page 0x07 * * These values are from usage page 0x07 (USB keyboard page). */ /*@{*/ KEY_A = 4, KEY_B = 5, KEY_C = 6, KEY_D = 7, KEY_E = 8, KEY_F = 9, KEY_G = 10, KEY_H = 11, KEY_I = 12, KEY_J = 13, KEY_K = 14, KEY_L = 15, KEY_M = 16, KEY_N = 17, KEY_O = 18, KEY_P = 19, KEY_Q = 20, KEY_R = 21, KEY_S = 22, KEY_T = 23, KEY_U = 24, KEY_V = 25, KEY_W = 26, KEY_X = 27, KEY_Y = 28, KEY_Z = 29, KEY_1 = 30, KEY_2 = 31, KEY_3 = 32, KEY_4 = 33, KEY_5 = 34, KEY_6 = 35, KEY_7 = 36, KEY_8 = 37, KEY_9 = 38, KEY_0 = 39, KEY_RETURN = 40, KEY_ESCAPE = 41, KEY_BACKSPACE = 42, KEY_TAB = 43, KEY_SPACE = 44, KEY_MINUS = 45, KEY_EQUALS = 46, KEY_LEFTBRACKET = 47, KEY_RIGHTBRACKET = 48, KEY_BACKSLASH = 49, /**< Located at the lower left of the return * key on ISO keyboards and at the right end * of the QWERTY row on ANSI keyboards. * Produces REVERSE SOLIDUS (backslash) and * VERTICAL LINE in a US layout, REVERSE * SOLIDUS and VERTICAL LINE in a UK Mac * layout, NUMBER SIGN and TILDE in a UK * Windows layout, DOLLAR SIGN and POUND SIGN * in a Swiss German layout, NUMBER SIGN and * APOSTROPHE in a German layout, GRAVE * ACCENT and POUND SIGN in a French Mac * layout, and ASTERISK and MICRO SIGN in a * French Windows layout. */ KEY_NONUSHASH = 50, /**< ISO USB keyboards actually use this code * instead of 49 for the same key, but all * OSes I've seen treat the two codes * identically. So, as an implementor, unless * your keyboard generates both of those * codes and your OS treats them differently, * you should generate KEY_BACKSLASH * instead of this code. As a user, you * should not rely on this code because SDL * will never generate it with most (all?) * keyboards. */ KEY_SEMICOLON = 51, KEY_APOSTROPHE = 52, KEY_GRAVE = 53, /**< Located in the top left corner (on both ANSI * and ISO keyboards). Produces GRAVE ACCENT and * TILDE in a US Windows layout and in US and UK * Mac layouts on ANSI keyboards, GRAVE ACCENT * and NOT SIGN in a UK Windows layout, SECTION * SIGN and PLUS-MINUS SIGN in US and UK Mac * layouts on ISO keyboards, SECTION SIGN and * DEGREE SIGN in a Swiss German layout (Mac: * only on ISO keyboards), CIRCUMFLEX ACCENT and * DEGREE SIGN in a German layout (Mac: only on * ISO keyboards), SUPERSCRIPT TWO and TILDE in a * French Windows layout, COMMERCIAL AT and * NUMBER SIGN in a French Mac layout on ISO * keyboards, and LESS-THAN SIGN and GREATER-THAN * SIGN in a Swiss German, German, or French Mac * layout on ANSI keyboards. */ KEY_COMMA = 54, KEY_PERIOD = 55, KEY_SLASH = 56, KEY_CAPSLOCK = 57, KEY_F1 = 58, KEY_F2 = 59, KEY_F3 = 60, KEY_F4 = 61, KEY_F5 = 62, KEY_F6 = 63, KEY_F7 = 64, KEY_F8 = 65, KEY_F9 = 66, KEY_F10 = 67, KEY_F11 = 68, KEY_F12 = 69, KEY_PRINTSCREEN = 70, KEY_SCROLLLOCK = 71, KEY_PAUSE = 72, KEY_INSERT = 73, /**< insert on PC, help on some Mac keyboards (but does send code 73, not 117) */ KEY_HOME = 74, KEY_PAGEUP = 75, KEY_DELETE = 76, KEY_END = 77, KEY_PAGEDOWN = 78, KEY_RIGHT = 79, KEY_LEFT = 80, KEY_DOWN = 81, KEY_UP = 82, KEY_NUMLOCKCLEAR = 83, /**< num lock on PC, clear on Mac keyboards */ KEY_KP_DIVIDE = 84, KEY_KP_MULTIPLY = 85, KEY_KP_MINUS = 86, KEY_KP_PLUS = 87, KEY_KP_ENTER = 88, KEY_KP_1 = 89, KEY_KP_2 = 90, KEY_KP_3 = 91, KEY_KP_4 = 92, KEY_KP_5 = 93, KEY_KP_6 = 94, KEY_KP_7 = 95, KEY_KP_8 = 96, KEY_KP_9 = 97, KEY_KP_0 = 98, KEY_KP_PERIOD = 99, KEY_NONUSBACKSLASH = 100, /**< This is the additional key that ISO * keyboards have over ANSI ones, * located between left shift and Y. * Produces GRAVE ACCENT and TILDE in a * US or UK Mac layout, REVERSE SOLIDUS * (backslash) and VERTICAL LINE in a * US or UK Windows layout, and * LESS-THAN SIGN and GREATER-THAN SIGN * in a Swiss German, German, or French * layout. */ KEY_APPLICATION = 101, /**< windows contextual menu, compose */ KEY_POWER = 102, /**< The USB document says this is a status flag, * not a physical key - but some Mac keyboards * do have a power key. */ KEY_KP_EQUALS = 103, KEY_F13 = 104, KEY_F14 = 105, KEY_F15 = 106, KEY_F16 = 107, KEY_F17 = 108, KEY_F18 = 109, KEY_F19 = 110, KEY_F20 = 111, KEY_F21 = 112, KEY_F22 = 113, KEY_F23 = 114, KEY_F24 = 115, KEY_EXECUTE = 116, KEY_HELP = 117, KEY_MENU = 118, KEY_SELECT = 119, KEY_STOP = 120, KEY_AGAIN = 121, /**< redo */ KEY_UNDO = 122, KEY_CUT = 123, KEY_COPY = 124, KEY_PASTE = 125, KEY_FIND = 126, KEY_MUTE = 127, KEY_VOLUMEUP = 128, KEY_VOLUMEDOWN = 129, /* not sure whether there's a reason to enable these */ /* KEY_LOCKINGCAPSLOCK = 130, */ /* KEY_LOCKINGNUMLOCK = 131, */ /* KEY_LOCKINGSCROLLLOCK = 132, */ KEY_KP_COMMA = 133, KEY_KP_EQUALSAS400 = 134, KEY_INTERNATIONAL1 = 135, /**< used on Asian keyboards, see footnotes in USB doc */ KEY_INTERNATIONAL2 = 136, KEY_INTERNATIONAL3 = 137, /**< Yen */ KEY_INTERNATIONAL4 = 138, KEY_INTERNATIONAL5 = 139, KEY_INTERNATIONAL6 = 140, KEY_INTERNATIONAL7 = 141, KEY_INTERNATIONAL8 = 142, KEY_INTERNATIONAL9 = 143, KEY_LANG1 = 144, /**< Hangul/English toggle */ KEY_LANG2 = 145, /**< Hanja conversion */ KEY_LANG3 = 146, /**< Katakana */ KEY_LANG4 = 147, /**< Hiragana */ KEY_LANG5 = 148, /**< Zenkaku/Hankaku */ KEY_LANG6 = 149, /**< reserved */ KEY_LANG7 = 150, /**< reserved */ KEY_LANG8 = 151, /**< reserved */ KEY_LANG9 = 152, /**< reserved */ KEY_ALTERASE = 153, /**< Erase-Eaze */ KEY_SYSREQ = 154, KEY_CANCEL = 155, KEY_CLEAR = 156, KEY_PRIOR = 157, KEY_RETURN2 = 158, KEY_SEPARATOR = 159, KEY_OUT = 160, KEY_OPER = 161, KEY_CLEARAGAIN = 162, KEY_CRSEL = 163, KEY_EXSEL = 164, KEY_KP_00 = 176, KEY_KP_000 = 177, KEY_THOUSANDSSEPARATOR = 178, KEY_DECIMALSEPARATOR = 179, KEY_CURRENCYUNIT = 180, KEY_CURRENCYSUBUNIT = 181, KEY_KP_LEFTPAREN = 182, KEY_KP_RIGHTPAREN = 183, KEY_KP_LEFTBRACE = 184, KEY_KP_RIGHTBRACE = 185, KEY_KP_TAB = 186, KEY_KP_BACKSPACE = 187, KEY_KP_A = 188, KEY_KP_B = 189, KEY_KP_C = 190, KEY_KP_D = 191, KEY_KP_E = 192, KEY_KP_F = 193, KEY_KP_XOR = 194, KEY_KP_POWER = 195, KEY_KP_PERCENT = 196, KEY_KP_LESS = 197, KEY_KP_GREATER = 198, KEY_KP_AMPERSAND = 199, KEY_KP_DBLAMPERSAND = 200, KEY_KP_VERTICALBAR = 201, KEY_KP_DBLVERTICALBAR = 202, KEY_KP_COLON = 203, KEY_KP_HASH = 204, KEY_KP_SPACE = 205, KEY_KP_AT = 206, KEY_KP_EXCLAM = 207, KEY_KP_MEMSTORE = 208, KEY_KP_MEMRECALL = 209, KEY_KP_MEMCLEAR = 210, KEY_KP_MEMADD = 211, KEY_KP_MEMSUBTRACT = 212, KEY_KP_MEMMULTIPLY = 213, KEY_KP_MEMDIVIDE = 214, KEY_KP_PLUSMINUS = 215, KEY_KP_CLEAR = 216, KEY_KP_CLEARENTRY = 217, KEY_KP_BINARY = 218, KEY_KP_OCTAL = 219, KEY_KP_DECIMAL = 220, KEY_KP_HEXADECIMAL = 221, KEY_LCTRL = 224, KEY_LSHIFT = 225, KEY_LALT = 226, /**< alt, option */ KEY_LGUI = 227, /**< windows, command (apple), meta */ KEY_RCTRL = 228, KEY_RSHIFT = 229, KEY_RALT = 230, /**< alt gr, option */ KEY_RGUI = 231, /**< windows, command (apple), meta */ KEY_MODE = 257, /**< I'm not sure if this is really not covered * by any of the above, but since there's a * special KMOD_MODE for it I'm adding it here */ /*@}*//*Usage page 0x07*/ /** * \name Usage page 0x0C * * These values are mapped from usage page 0x0C (USB consumer page). */ /*@{*/ KEY_AUDIONEXT = 258, KEY_AUDIOPREV = 259, KEY_AUDIOSTOP = 260, KEY_AUDIOPLAY = 261, KEY_AUDIOMUTE = 262, KEY_MEDIASELECT = 263, KEY_WWW = 264, KEY_MAIL = 265, KEY_CALCULATOR = 266, KEY_COMPUTER = 267, KEY_AC_SEARCH = 268, KEY_AC_HOME = 269, KEY_AC_BACK = 270, KEY_AC_FORWARD = 271, KEY_AC_STOP = 272, KEY_AC_REFRESH = 273, KEY_AC_BOOKMARKS = 274, /*@}*//*Usage page 0x0C*/ /** * \name Walther keys * * These are values that Christian Walther added (for mac keyboard?). */ /*@{*/ KEY_BRIGHTNESSDOWN = 275, KEY_BRIGHTNESSUP = 276, KEY_DISPLAYSWITCH = 277, /**< display mirroring/dual display switch, video mode switch */ KEY_KBDILLUMTOGGLE = 278, KEY_KBDILLUMDOWN = 279, KEY_KBDILLUMUP = 280, KEY_EJECT = 281, KEY_SLEEP = 282, KEY_APP1 = 283, KEY_APP2 = 284, }; class GetInput { public: //Constructor GetInput(Window* Window); //Destructor ~GetInput(); //Poll for input events SDL_Event PollEvent(); //Update the input void Update(); //Set the cursor to either visible or invisible void SetCursor(bool Visible); //Set the position of the mouse void SetMousePosition(Vector2f Ppos); inline bool GetKey(int keyCode) const { return m_Inputs[keyCode]; } //Get status of key inline bool GetKeyDown(int keyCode) const { return m_DownKeys[keyCode]; } //Get status of key down inline bool GetKeyUp(int keyCode) const { return m_UpKeys[keyCode]; } //Get status of key up inline bool GetMouse(int keyCode) const { return m_MouseInput[keyCode]; } //Get status of mouse key inline bool GetMouseDown(int keyCode) const { return m_DownMouse[keyCode]; } //Get status of mouse key down inline bool GetMouseUp(int keyCode) const { return m_UpMouse[keyCode]; } //Get status of mouse up inline bool GetIsClosed() const { return m_isClosed; } //Check if the window has been closed inline bool GetIsWarpMouse() const { return m_warpMouse; } //Check if mouse needs to be warped inline void SetIsWarpMouse(bool WarpMouse) { m_warpMouse = WarpMouse; } //Set mouse warped //Get mouse positons inline Vector2f GetMousePos() const { return Vector2f(m_MouseX, m_MouseY); } inline Vector2f GetWarpMousePos() const { return m_WarpMousePos; } //Get the window inline Window* GetWindow() const { return m_Window; } private: //SDL event access; SDL_Event e; //Mouse Position int m_MouseX = 0; int m_MouseY = 0; //Bool arrays representing the key states bool m_Inputs[NUM_KEYS]; bool m_DownKeys[NUM_KEYS]; bool m_UpKeys[NUM_KEYS]; //Bool arrays representing the mouse key states bool m_MouseInput[NUM_MOUSEBUTTONS]; bool m_DownMouse[NUM_MOUSEBUTTONS]; bool m_UpMouse[NUM_MOUSEBUTTONS]; //Is the window closed bool m_isClosed = false; //Does the mouse need to be warped bool m_warpMouse = false; //Warp mouse position Vector2f m_WarpMousePos; //Pointer to the window Window* m_Window; }; }
[ "dsayers77@gmail.com" ]
dsayers77@gmail.com
5608741d977e5eea46d47d51e0e5350a2aea4a61
e18d35e0c5f7c6a690cef21286450d921ee1d9c8
/Filter.h
ca2c5fe17bde7d8260a62e8cef01a395cd3132a6
[]
no_license
AleksZaporozhets/Synth-VST
2db111545d524b3919a38c4e8e818092925b5542
e33c9d42a050dea3c4fea4861db6d29e22fa5193
refs/heads/master
2022-10-19T07:24:53.741642
2020-06-06T20:37:24
2020-06-06T20:37:24
270,056,205
0
0
null
null
null
null
UTF-8
C++
false
false
1,240
h
#ifndef __Synthesis__Filter__ #define __Synthesis__Filter__ #include <cmath> class Filter { public: enum FilterMode { FILTER_MODE_LOWPASS = 0, FILTER_MODE_HIGHPASS, FILTER_MODE_BANDPASS, kNumFilterModes }; Filter() : cutoff(0.99), resonance(0.0), cutoffMod(0.0), mode(FILTER_MODE_LOWPASS), buf0(0.0), buf1(0.0), buf2(0.0), buf3(0.0) { calculateFeedbackAmount(); }; double process(double inputValue); inline void setCutoff(double newCutoff) { cutoff = newCutoff; calculateFeedbackAmount(); }; inline void setResonance(double newResonance) { resonance = newResonance; calculateFeedbackAmount(); }; inline void setFilterMode(FilterMode newMode) { mode = newMode; } inline void setCutoffMod(double newCutoffMod) { cutoffMod = newCutoffMod; calculateFeedbackAmount(); } private: double cutoff; double resonance; FilterMode mode; double feedbackAmount; inline void calculateFeedbackAmount() { feedbackAmount = resonance + resonance / (1.0 - getCalculatedCutoff()); } double buf0; double buf1; double buf2; double buf3; double cutoffMod; inline double getCalculatedCutoff() const { return fmax(fmin(cutoff + cutoffMod, 0.99), 0.01); }; }; #endif /* defined(__Synthesis__Filter__) */
[ "noreply@github.com" ]
noreply@github.com
d0577947a9255de2fd23214f23f42a0bba5719b7
0fccd1748ee7be55039e7bbfb4820197b5a85f0b
/2D Game Engine/2D Game Engine/GoldDrop.h
5c4141c6ad369b2e2145f3c058e577dcfe6bbf40
[]
no_license
AustinChayka/C-Game
11d297ac5fd38a280da4701ec16c5e18f8680c58
56bd96fddc38cb4bfca6f69c37748b1417a51d8a
refs/heads/master
2022-02-13T02:39:14.724679
2019-05-30T22:10:43
2019-05-30T22:10:43
167,856,869
1
1
null
null
null
null
UTF-8
C++
false
false
363
h
#ifndef GoldDrop_h #define GoldDrop_h #include "GameObject.h" class GoldDrop : public GameObject { public: GoldDrop(float x, float y, int init_value); ~GoldDrop(); void Update(LevelManager * game); void RenderObject(); void OnCollision(GameObject * go, LevelManager * game); bool OverrideCollision(GameObject * go); private: int value; }; #endif
[ "austinchayka@gmail.com" ]
austinchayka@gmail.com
8ad1c55368593e59fd5b1fe0c634e42758d2db78
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5738606668808192_1/C++/sagorika1996/Untitled1.cpp
e8184436b762cabdf56aebf4fe213102a66f8291
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
13,751
cpp
// Author : SAGORIKA DAS // Google Code Jam // C. Coin Jam #include<iostream> #include<vector> #include<set> #include<map> #include<utility> #include<stack> #include<queue> #include<list> #include<algorithm> #include<cmath> #include<cstring> #include<cstdio> #include<string> #define ull unsigned long long #define ll long long #define F first #define S second #define MOD 1000000007 #define inf 1000000006 #define pb push_back #define MAX 100002 #define REP(i,n) for(int i=0;i<n;i++) #define FOR(i,a,b) for(int i=a;i<b;i++) #define mp make_pair #define CLEAR(a) memset(a,0,sizeof a) #define pii pair< int , int > #define piii pair< int , pii > #define piiii pair< int, piii > #include <vector> #include <cstdlib> #include <iostream> #include <iomanip> #include <string> #include <complex> #include <ctime> #include <cstdio> using namespace std; ///////////////////////////////////////////// Biginteger ////////////////////////////////////////////////////////// // base and base_digits must be consistent const int base = 1000000000; const int base_digits = 9; struct bigint { vector<int> a; int sign; bigint() : sign(1) { } bigint(long long v) { *this = v; } bigint(const string &s) { read(s); } void operator=(const bigint &v) { sign = v.sign; a = v.a; } void operator=(long long v) { sign = 1; if (v < 0) sign = -1, v = -v; a.clear(); for (; v > 0; v = v / base) a.push_back(v % base); } bigint operator+(const bigint &v) const { if (sign == v.sign) { bigint res = v; for (int i = 0, carry = 0; i < (int) max(a.size(), v.a.size()) || carry; ++i) { if (i == (int) res.a.size()) res.a.push_back(0); res.a[i] += carry + (i < (int) a.size() ? a[i] : 0); carry = res.a[i] >= base; if (carry) res.a[i] -= base; } return res; } return *this - (-v); } bigint operator-(const bigint &v) const { if (sign == v.sign) { if (abs() >= v.abs()) { bigint res = *this; for (int i = 0, carry = 0; i < (int) v.a.size() || carry; ++i) { res.a[i] -= carry + (i < (int) v.a.size() ? v.a[i] : 0); carry = res.a[i] < 0; if (carry) res.a[i] += base; } res.trim(); return res; } return -(v - *this); } return *this + (-v); } void operator*=(int v) { if (v < 0) sign = -sign, v = -v; for (int i = 0, carry = 0; i < (int) a.size() || carry; ++i) { if (i == (int) a.size()) a.push_back(0); long long cur = a[i] * (long long) v + carry; carry = (int) (cur / base); a[i] = (int) (cur % base); } trim(); } bigint operator*(int v) const { bigint res = *this; res *= v; return res; } friend pair<bigint, bigint> divmod(const bigint &a1, const bigint &b1) { int norm = base / (b1.a.back() + 1); bigint a = a1.abs() * norm; bigint b = b1.abs() * norm; bigint q, r; q.a.resize(a.a.size()); for (int i = a.a.size() - 1; i >= 0; i--) { r *= base; r += a.a[i]; int s1 = r.a.size() <= b.a.size() ? 0 : r.a[b.a.size()]; int s2 = r.a.size() <= b.a.size() - 1 ? 0 : r.a[b.a.size() - 1]; int d = ((long long) base * s1 + s2) / b.a.back(); r -= b * d; while (r < 0) r += b, --d; q.a[i] = d; } q.sign = a1.sign * b1.sign; r.sign = a1.sign; q.trim(); r.trim(); return make_pair(q, r / norm); } bigint operator/(const bigint &v) const { return divmod(*this, v).first; } bigint operator%(const bigint &v) const { return divmod(*this, v).second; } void operator/=(int v) { if (v < 0) sign = -sign, v = -v; for (int i = (int) a.size() - 1, rem = 0; i >= 0; --i) { long long cur = a[i] + rem * (long long) base; a[i] = (int) (cur / v); rem = (int) (cur % v); } trim(); } bigint operator/(int v) const { bigint res = *this; res /= v; return res; } int operator%(int v) const { if (v < 0) v = -v; int m = 0; for (int i = a.size() - 1; i >= 0; --i) m = (a[i] + m * (long long) base) % v; return m * sign; } void operator+=(const bigint &v) { *this = *this + v; } void operator-=(const bigint &v) { *this = *this - v; } void operator*=(const bigint &v) { *this = *this * v; } void operator/=(const bigint &v) { *this = *this / v; } bool operator<(const bigint &v) const { if (sign != v.sign) return sign < v.sign; if (a.size() != v.a.size()) return a.size() * sign < v.a.size() * v.sign; for (int i = a.size() - 1; i >= 0; i--) if (a[i] != v.a[i]) return a[i] * sign < v.a[i] * sign; return false; } bool operator>(const bigint &v) const { return v < *this; } bool operator<=(const bigint &v) const { return !(v < *this); } bool operator>=(const bigint &v) const { return !(*this < v); } bool operator==(const bigint &v) const { return !(*this < v) && !(v < *this); } bool operator!=(const bigint &v) const { return *this < v || v < *this; } void trim() { while (!a.empty() && a.back() == 0) a.pop_back(); if (a.empty()) sign = 1; } bool isZero() const { return a.empty() || (a.size() == 1 && !a[0]); } bigint operator-() const { bigint res = *this; res.sign = -sign; return res; } bigint abs() const { bigint res = *this; res.sign *= res.sign; return res; } long long longValue() const { long long res = 0; for (int i = a.size() - 1; i >= 0; i--) res = res * base + a[i]; return res * sign; } friend bigint gcd(const bigint &a, const bigint &b) { return b.isZero() ? a : gcd(b, a % b); } friend bigint lcm(const bigint &a, const bigint &b) { return a / gcd(a, b) * b; } void read(const string &s) { sign = 1; a.clear(); int pos = 0; while (pos < (int) s.size() && (s[pos] == '-' || s[pos] == '+')) { if (s[pos] == '-') sign = -sign; ++pos; } for (int i = s.size() - 1; i >= pos; i -= base_digits) { int x = 0; for (int j = max(pos, i - base_digits + 1); j <= i; j++) x = x * 10 + s[j] - '0'; a.push_back(x); } trim(); } friend istream& operator>>(istream &stream, bigint &v) { string s; stream >> s; v.read(s); return stream; } friend ostream& operator<<(ostream &stream, const bigint &v) { if (v.sign == -1) stream << '-'; stream << (v.a.empty() ? 0 : v.a.back()); for (int i = (int) v.a.size() - 2; i >= 0; --i) stream << setw(base_digits) << setfill('0') << v.a[i]; return stream; } static vector<int> convert_base(const vector<int> &a, int old_digits, int new_digits) { vector<long long> p(max(old_digits, new_digits) + 1); p[0] = 1; for (int i = 1; i < (int) p.size(); i++) p[i] = p[i - 1] * 10; vector<int> res; long long cur = 0; int cur_digits = 0; for (int i = 0; i < (int) a.size(); i++) { cur += a[i] * p[cur_digits]; cur_digits += old_digits; while (cur_digits >= new_digits) { res.push_back(int(cur % p[new_digits])); cur /= p[new_digits]; cur_digits -= new_digits; } } res.push_back((int) cur); while (!res.empty() && res.back() == 0) res.pop_back(); return res; } void fft(vector<complex<double> > & a, bool invert) const { int n = (int) a.size(); for (int i = 1, j = 0; i < n; ++i) { int bit = n >> 1; for (; j >= bit; bit >>= 1) j -= bit; j += bit; if (i < j) swap(a[i], a[j]); } for (int len = 2; len <= n; len <<= 1) { double ang = 2 * 3.14159265358979323846 / len * (invert ? -1 : 1); complex<double> wlen(cos(ang), sin(ang)); for (int i = 0; i < n; i += len) { complex<double> w(1); for (int j = 0; j < len / 2; ++j) { complex<double> u = a[i + j]; complex<double> v = a[i + j + len / 2] * w; a[i + j] = u + v; a[i + j + len / 2] = u - v; w *= wlen; } } } if (invert) for (int i = 0; i < n; ++i) a[i] /= n; } void multiply_fft(const vector<int> &a, const vector<int> &b, vector<int> &res) const { vector<complex<double> > fa(a.begin(), a.end()); vector<complex<double> > fb(b.begin(), b.end()); int n = 1; while (n < (int) max(a.size(), b.size())) n <<= 1; n <<= 1; fa.resize(n); fb.resize(n); fft(fa, false); fft(fb, false); for (int i = 0; i < n; ++i) fa[i] *= fb[i]; fft(fa, true); res.resize(n); for (int i = 0, carry = 0; i < n; ++i) { res[i] = int(fa[i].real() + 0.5) + carry; carry = res[i] / 1000; res[i] %= 1000; } } bigint operator*(const bigint &v) const { bigint res; res.sign = sign * v.sign; multiply_fft(convert_base(a, base_digits, 3), convert_base(v.a, base_digits, 3), res.a); res.a = convert_base(res.a, 3, base_digits); res.trim(); return res; } bigint mul_simple(const bigint &v) const { bigint res; res.sign = sign * v.sign; res.a.resize(a.size() + v.a.size()); for (int i = 0; i < (int) a.size(); ++i) if (a[i]) for (int j = 0, carry = 0; j < (int) v.a.size() || carry; ++j) { long long cur = res.a[i + j] + (long long) a[i] * (j < (int) v.a.size() ? v.a[j] : 0) + carry; carry = (int) (cur / base); res.a[i + j] = (int) (cur % base); } res.trim(); return res; } }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int d[9]; bigint convert(string s,int base){ bigint res = 1, b = base; for(int i=s.size()-2;i>=0;i--){ if(s[i] == '1') res += b; b = b*base; } return res; } string add(string s){ for(int i=s.size()-2;i>=1;i--){ if(s[i] =='1') s[i] = '0'; else{ s[i] = '1'; break; } } return s; } bool check(string s){ REP(i,s.size()){ if(s[i] =='0') return false; } return true; } int prime[MAX]; vector<int> pp; void seive(int n) { for(int i=0;i<n;i++) prime[i]=1; prime[0]=0; prime[1]=0; for(int i=2;i*i<=n;i++) { if(prime[i]) { for(int k=2;k*i<=n;k++) prime[k*i]=0; } } REP(i,n) if(prime[i]) pp.pb(i); } int isPrime(bigint number,int j) { REP(i,pp.size()) { if (number % pp[i] == 0){d[j-2] = pp[i]; return 0;} } return 1; } int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); seive(MAX); int T; scanf("%d",&T); while(T--){ int n,m; scanf("%d %d",&n,&m); string s = "1"; REP(i,n-2) s+='0'; s+='1'; printf("Case #1:\n"); while(1){ if(m <=0) break; int f = 1; for(int j=2;j<=10;j++){ bigint final = convert(s,j); if(isPrime(final,j)) {f = 0; break;} } // if s is a jam coin then print if(f == 1){ cout<<s<<" "; REP(i,9) printf("%d ",d[i]); printf("\n"); m--; } // if all bits are set then exit if(check(s))break; // add 1 to s s = add(s); } } return 0; }
[ "alexandra1.back@gmail.com" ]
alexandra1.back@gmail.com
fd2c18389069b3f96ac262f64d0ebf14bb0569ae
38f42e0aa2511057ffe0585bba8bd5a0e36f82d1
/lab_puzzles/common_words.cpp
54a631b6ee5135b6677635e712f362dc58744b96
[]
no_license
diditong/UIUC-CS225-FA2018
149f4b8dd5d869e5cfda15861a2a9cd97358f437
280a02f2d32ebd104a80512b1a82e13f3e66841c
refs/heads/master
2020-12-13T14:10:13.120463
2020-01-17T00:33:09
2020-01-17T00:33:09
234,437,920
1
0
null
null
null
null
UTF-8
C++
false
false
3,131
cpp
/** * @file common_words.cpp * Implementation of the CommonWords class. * * @author Zach Widder * @date Fall 2014 */ #include "common_words.h" #include <fstream> #include <string> #include <vector> #include <iostream> #include <iterator> #include <algorithm> using std::string; using std::vector; using std::ifstream; using std::cout; using std::endl; using std::feof; string remove_punct(const string& str) { string ret; std::remove_copy_if(str.begin(), str.end(), std::back_inserter(ret), std::ptr_fun<int, int>(&std::ispunct)); return ret; } CommonWords::CommonWords(const vector<string>& filenames) { // initialize all member variables init_file_word_maps(filenames); init_common(); } void CommonWords::init_file_word_maps(const vector<string>& filenames) { // make the length of file_word_maps the same as the length of filenames file_word_maps.resize(filenames.size()); // go through all files for (size_t i = 0; i < filenames.size(); i++) { // get the corresponding vector of words that represents the current // file vector<string> words = file_to_vector(filenames[i]); map<string, unsigned int> & word_map = file_word_maps[i]; for(vector<string>::iterator it = words.begin(); it != words.end(); it++) { map<string, unsigned int>::iterator lookup = word_map.find(*it); if (lookup != word_map.end()) { word_map[*it]++; } else { word_map[*it] = 1; } } } } void CommonWords::init_common() { for(std::pair<const string, unsigned int>& it : file_word_maps[0]) { int flag_common = 1; unsigned int count = it.second; for (size_t i = 1; i < file_word_maps.size(); i++) { map<string, unsigned int>::iterator lookup = file_word_maps[i].find(it.first); if (lookup == file_word_maps[i].end()) { flag_common = 0; break; } else if (lookup->second < count) { count = lookup->second; } } if (flag_common == 1) common[it.first] = count; } } /** * @param n The number of times to word has to appear. * @return A vector of strings. The vector contains all words that appear * in each file >= n times. */ vector<string> CommonWords::get_common_words(unsigned int n) const { vector<string> out; for(std::pair<const string, unsigned int> const it : common) { if(it.second >= n) out.push_back(it.first); } return out; } /** * Takes a filename and transforms it to a vector of all words in that file. * @param filename The name of the file that will fill the vector */ vector<string> CommonWords::file_to_vector(const string& filename) const { ifstream words(filename); vector<string> out; if (words.is_open()) { std::istream_iterator<string> word_iter(words); while (!words.eof()) { out.push_back(remove_punct(*word_iter)); ++word_iter; } } return out; }
[ "jtong8@illinois.edu" ]
jtong8@illinois.edu
3998b42a4e9ce7c07b42e64864f5ad60568e10ab
2fc2eb5befec70dfe962a8a48ee727dc876ca32c
/src/ChemicalSystemTools/ChemicalSystem.h
e8cc1d3eda06115b2a9ab55b1f0ac042f44292bc
[]
no_license
ludovicadelpop/MultiRate_SparseMatrix
8c3e0b43b54697f88609cc470e67e5d50535f1f4
ae30c628598dc485e2e40ac1b381b51f8c7c28da
refs/heads/master
2021-01-10T07:36:59.778128
2016-02-16T10:29:56
2016-02-16T10:29:56
51,826,608
0
1
null
null
null
null
UTF-8
C++
false
false
944
h
/* * ChemicalSystem.h * * Created on: 9 d�c. 2015 * Author: delpopol */ #ifndef CHEMICALSYSTEM_H_ #define CHEMICALSYSTEM_H_ #include "ChemicalPhase.h" #include "ChemicalSpecies.h" #include "ChemicalReaction.h" //! Class to store the system in the Geochemistry problem class ChemicalSystem { public: ChemicalSystem(); virtual ~ChemicalSystem(); const std::vector<ChemicalPhase>& getPhase() const; const std::vector<ChemicalReaction>& getReaction() const; const std::vector<ChemicalSpecies>& getSpecies() const; void addPhase(ChemicalPhase phase); void addSpecies(ChemicalSpecies species); void addReaction(ChemicalReaction reaction); private: std::vector<ChemicalPhase> Phase; /*!< Phases present in the system */ std::vector<ChemicalSpecies> Species; /*!< Species present in the system */ std::vector<ChemicalReaction> Reaction; /*!< Reactions present in the system */ }; #endif /* CHEMICALSYSTEM_H_ */
[ "ludovica.delpop92@gmail.com" ]
ludovica.delpop92@gmail.com
89f137db663614972240dafafbb67553c081e3ad
002b059af1f45258cc245e9a2d8def7afb76ea17
/workspace/GACTX_bank3/vivado_rtl_kernel/GACTX_bank3_ex/GACTX_bank3_ex.ip_user_files/sim_scripts/control_GACTX_bank3_vip/questa/control_GACTX_bank3_vip_sc.h
b0d07f6286a974a48f6ce341a7d3b1be6768681a
[ "MIT" ]
permissive
mfkiwl/Darwin-WGA-array-coprocessor
9dd57f8d2c8110dfa6b08c6cddcb9ad74b39d214
e67513ba4fea273fa9b08ddaa148a2ea39805ccb
refs/heads/master
2022-11-29T16:20:36.185926
2020-08-07T13:32:00
2020-08-07T13:32:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,213
h
#ifndef IP_CONTROL_GACTX_BANK3_VIP_SC_H_ #define IP_CONTROL_GACTX_BANK3_VIP_SC_H_ // (c) Copyright 1995-2020 Xilinx, Inc. All rights reserved. // // This file contains confidential and proprietary information // of Xilinx, Inc. and is protected under U.S. and // international copyright and other intellectual property // laws. // // DISCLAIMER // This disclaimer is not a license and does not grant any // rights to the materials distributed herewith. Except as // otherwise provided in a valid license issued to you by // Xilinx, and to the maximum extent permitted by applicable // law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND // WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES // AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING // BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON- // INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and // (2) Xilinx shall not be liable (whether in contract or tort, // including negligence, or under any other theory of // liability) for any loss or damage of any kind or nature // related to, arising under or in connection with these // materials, including for any direct, or any indirect, // special, incidental, or consequential loss or damage // (including loss of data, profits, goodwill, or any type of // loss or damage suffered as a result of any action brought // by a third party) even if such damage or loss was // reasonably foreseeable or Xilinx had been advised of the // possibility of the same. // // CRITICAL APPLICATIONS // Xilinx products are not designed or intended to be fail- // safe, or for use in any application requiring fail-safe // performance, such as life-support or safety devices or // systems, Class III medical devices, nuclear facilities, // applications related to the deployment of airbags, or any // other applications that could lead to death, personal // injury, or severe property or environmental damage // (individually and collectively, "Critical // Applications"). Customer assumes the sole risk and // liability of any use of Xilinx products in Critical // Applications, subject only to applicable laws and // regulations governing limitations on product liability. // // THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS // PART OF THIS FILE AT ALL TIMES. // // DO NOT MODIFY THIS FILE. #ifndef XTLM #include "xtlm.h" #endif #ifndef SYSTEMC_INCLUDED #include <systemc> #endif #if defined(_MSC_VER) #define DllExport __declspec(dllexport) #elif defined(__GNUC__) #define DllExport __attribute__ ((visibility("default"))) #else #define DllExport #endif class axi_vip; class DllExport control_GACTX_bank3_vip_sc : public sc_core::sc_module { public: control_GACTX_bank3_vip_sc(const sc_core::sc_module_name& nm); virtual ~control_GACTX_bank3_vip_sc(); public: // module socket-to-socket TLM interface xtlm::xtlm_aximm_initiator_socket* M_INITIATOR_rd_socket; xtlm::xtlm_aximm_initiator_socket* M_INITIATOR_wr_socket; protected: axi_vip* mp_impl; private: control_GACTX_bank3_vip_sc(const control_GACTX_bank3_vip_sc&); const control_GACTX_bank3_vip_sc& operator=(const control_GACTX_bank3_vip_sc&); }; #endif // IP_CONTROL_GACTX_BANK3_VIP_SC_H_
[ "cn.ramachandra@gmail.com" ]
cn.ramachandra@gmail.com
dc183e8d0acb8a8cd99c2a04a3ab60d9fc5c4c51
729f5397fa300c5d50db9ac89c6416a3fcbe65a6
/AI/connect4/source/Position.h
cedaf48ec694b3d387610f5662d41766a0923207
[]
no_license
andrewthenintendrone/AI-Project
66c7f43f6c494bf97948851ab929e701352f7c0c
b232e2ed7ec21d47fdc8ba616b3bcc520123bebf
refs/heads/master
2020-12-13T19:57:15.542732
2017-08-06T23:56:54
2017-08-06T23:56:54
95,515,231
0
0
null
null
null
null
UTF-8
C++
false
false
424
h
#pragma once enum class TILESTATE { EMPTY, RED, YELLOW }; class Position { public: static const int WIDTH = 7; static const int HEIGHT = 6; Position(); Position(Position& P); bool canPlay(int column) const; void play(int column); bool isWinningMove(int column) const; TILESTATE m_grid[WIDTH][HEIGHT]; int m_heights[WIDTH]; unsigned int m_numMoves = 0; bool m_won = false; };
[ "andrewfitzpatrick@y7mail.com" ]
andrewfitzpatrick@y7mail.com
1de885c5dd938caa6bae1c124a948c054ba01688
98cd8b5de79224c47a211013b437f6cecb3b254e
/nrf_receive_update.ino
acbaf6531987a4ed8fc2e0e40e82c5159f71dda0
[]
no_license
Theo-Sirius/arduino_nrf_receive
6f8d2d19432fdbbc5f302ba169674732e65ce9e4
10fcb6d322a67732edfca8967e27ac29c8c6760f
refs/heads/master
2020-08-14T21:49:22.415590
2019-10-15T07:41:02
2019-10-15T07:41:02
215,236,953
0
0
null
null
null
null
UTF-8
C++
false
false
686
ino
#include <SPI.h> #include <nRF24L01.h> #include <RF24.h> RF24 radio(9, 10); // CE, CSN const byte address[6] = "00001"; int LEDPin = A4; boolean switch1 = 0; void setup() { Serial.begin(9600); pinMode(LEDPin, OUTPUT); radio.begin(); radio.openReadingPipe(0, address); radio.setPALevel(RF24_PA_MIN); radio.startListening(); } void loop() { if (radio.available()) { char text[32] = ""; radio.read(&text, sizeof(text)); radio.read(&switch1, sizeof(switch1)); if (switch1 == 1) { digitalWrite(LEDPin, HIGH); Serial.println(text); } else { digitalWrite(LEDPin, LOW); } } else { Serial.println("no"); } delay(5); }
[ "noreply@github.com" ]
noreply@github.com
96ab50d5852c3d11529baf59a3e6172111da3837
85805f1666e1db54536eb6790d4111c994629634
/2_janitor.h
eb3b1d80fae670e0d5ab032b353d21c755359710
[]
no_license
rabrightwell/WillieTheJanitor
7d2f823e42d0322e4eec6b1f48275bfc73b07099
705d95ead47b3b5adab6555389e3bf5f10469211
refs/heads/main
2023-01-30T17:02:22.242356
2020-12-18T02:35:37
2020-12-18T02:35:37
322,456,603
0
0
null
null
null
null
UTF-8
C++
false
false
1,860
h
#ifndef JANITOR_H #define JANITOR_H #include <iostream> #include <string> #include <list> #include "_coord.h" using namespace std ; class school; class lunch ; class drink ; class janitor { private: //Variables float bac ; //blood alchohol content int bruises ; //num of bruises coord location ; //coordinates to be streamed to map coord toLocation ; //where Janitor will move to next //State Bools bool defenestrated ; //T if janitor out window, F if not bool drunk ; //T if drunk, F if sober bool dead ; //T if dead, F if alive bool hungry ; //T if lunch not caught, F if caught //Movements void moveSober(lunch & l) ; void moveDrunk() ; //Interactions void effectMovement(school & mySchool, drink container[]) ; void moveTo_() ; void moveToW() ; void moveToL() ; void moveToD(drink container[]) ; void moveToB(school & mySchool) ; void moveToT() ; drink chooseDrink(drink container[]) ; public : //Variables char representation ; string name ; //Constructors janitor(string n = "Willie", char r = 'J') ; //Accessor inline coord getLocation() {return location ;} ; bool getHungry() {return hungry ;} ; bool getDead() {return dead ;} ; bool getDefenestrated() {return defenestrated ;} ; inline int getBruises() {return bruises ;} ; inline float getBAC() {return bac ;} ; //State void checkDrunk() ; void checkDead() ; //Assignment void initJanitor(school & mySchool) ; //Move Simulation void nextMove(school & mySchool, lunch & l, drink drinkContainer[]) ; //Friends friend ostream& operator<< (ostream& out, janitor j) ; // a print() function or overloaded insertion operator. } ; #endif
[ "noreply@github.com" ]
noreply@github.com
c0d207ef16f044cc826284944824836cb3faaaa1
4da10f2a791fb24fb63af12f72b29d9eced78e3b
/sfb2/RectangleFixture.hpp
caf0375a025f599735652f1486e46b94f3bf692b
[]
no_license
arm32x/sfb2
3bcdd723e847e782ae47dad740d133b522d47c65
f8eae484831c4ad411d34dd6552f62f9c24ae4b4
refs/heads/master
2020-05-04T11:07:11.556159
2019-04-02T21:02:03
2019-04-02T21:22:23
179,101,158
0
0
null
null
null
null
UTF-8
C++
false
false
1,025
hpp
#pragma once #include <Box2D/Box2D.h> #include <SFML/Graphics.hpp> using namespace sf; class Fixture; #include "Fixture.hpp" class RectangleFixture : public Fixture, private RectangleShape { friend class Body; public: using RectangleShape::getFillColor; using RectangleShape::setFillColor; using RectangleShape::getOutlineColor; using RectangleShape::setOutlineColor; using RectangleShape::getOutlineThickness; using RectangleShape::setOutlineThickness; using RectangleShape::getSize; using RectangleShape::getTransform; using RectangleShape::getTexture; using RectangleShape::setTexture; using RectangleShape::getTextureRect; using RectangleShape::setTextureRect; protected: RectangleFixture(Body& body, float x, float y, float width, float height); RectangleFixture(Body& body, const Vector2f& position, const Vector2f& size); RectangleFixture(Body& body, const FloatRect& rect); virtual void update(); void draw(RenderTarget& target, RenderStates states) const; };
[ "arm32.x@gmail.com" ]
arm32.x@gmail.com