hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
77k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
8416064ba4d7477f450641def58f3b03edb4f096
8,294
cpp
C++
HPCSimulation.cpp
iray-tno/hal2015
c84643472b31efbcd7622867dcc4e71c80541274
[ "FSFAP" ]
null
null
null
HPCSimulation.cpp
iray-tno/hal2015
c84643472b31efbcd7622867dcc4e71c80541274
[ "FSFAP" ]
null
null
null
HPCSimulation.cpp
iray-tno/hal2015
c84643472b31efbcd7622867dcc4e71c80541274
[ "FSFAP" ]
null
null
null
//------------------------------------------------------------------------------ /// @file /// @brief HPCSimulation.hpp の実装 /// @author ハル研究所プログラミングコンテスト実行委員会 /// /// @copyright Copyright (c) 2015 HAL Laboratory, Inc. /// @attention このファイルの利用は、同梱のREADMEにある /// 利用条件に従ってください //------------------------------------------------------------------------------ #include "HPCSimulation.hpp" #include <cstring> #include <cstdlib> #include "HPCCommon.hpp" #include "HPCMath.hpp" #include "HPCTimer.hpp" namespace { /// 入力を受けるコマンド enum Command { Command_Debug, ///< デバッガ起動 Command_OutputJson, ///< JSON 出力 Command_Exit, ///< 終わる }; //------------------------------------------------------------------------------ /// 入力を受けます。 Command SelectInput() { while (true) { HPC_PRINT("[d]ebug | output [j]son | [e]xit: "); // 入力待ち const char key = getchar(); if (key == 0x0a) { return Command_Exit; } while (getchar() != 0x0a){} // 改行待ち switch (key) { case 'd': return Command_Debug; case 'j': return Command_OutputJson; case 'e': return Command_Exit; default: break; } } return Command_Exit; } /// 入力を受けるコマンド enum DebugCommand { DebugCommand_Next, ///< 次へ DebugCommand_Prev, ///< 前へ DebugCommand_Jump, ///< 指定番号のステージにジャンプ DebugCommand_Show, ///< 再度 DebugCommand_Help, ///< ヘルプを表示 DebugCommand_Exit, ///< 終わる DebugCommand_TERM }; /// 入力を受けるコマンドのセット struct DebugCommandSet { DebugCommand command; int arg1; int arg2; DebugCommandSet() : command(DebugCommand_TERM) , arg1(0) , arg2(0) { } DebugCommandSet(DebugCommand aCmd, int aArg1, int aArg2) : command(aCmd) , arg1(aArg1) , arg2(aArg2) { HPC_ENUM_ASSERT(DebugCommand, aCmd); } }; //------------------------------------------------------------------------------ /// 入力を受けます。 /// /// 入力は次の3要素から構成されます。 /// - コマンド /// - 引数1 /// - 引数2 /// /// 引数1, 引数2 を省略した場合は、0 が設定されます。 DebugCommandSet SelectInputDebugger(int stage) { while (true) { HPC_PRINT("[Stage: %d ('h' for help)]> ", stage); // 入力待ち static const int LineBufferSize = 20; // 20文字くらいあれば十分 char line[LineBufferSize]; { char* ptr = std::fgets(line, LineBufferSize, stdin); (void)ptr; } // コマンドを読む const char* cmdStr = std::strtok(line, " \n\0"); if (!cmdStr) { continue; } const char* arg1Str = std::strtok(0, " \n\0"); const char* arg2Str = std::strtok(0, " \n\0"); const int arg1 = arg1Str ? std::atoi(arg1Str) : 0; const int arg2 = arg2Str ? std::atoi(arg2Str) : 0; switch (cmdStr[0]) { case 'n': return DebugCommandSet(DebugCommand_Next, arg1, arg2); case 'p': return DebugCommandSet(DebugCommand_Prev, arg1, arg2); case 'd': return DebugCommandSet(DebugCommand_Show, arg1, arg2); case 'j': return DebugCommandSet(DebugCommand_Jump, arg1, arg2); case 'h': return DebugCommandSet(DebugCommand_Help, arg1, arg2); case 'e': return DebugCommandSet(DebugCommand_Exit, arg1, arg2); default: break; } } return DebugCommandSet(DebugCommand_Next, 0, 0); } //------------------------------------------------------------------------------ /// デバッガのヘルプを表示します。 void ShowHelp() { HPC_PRINT(" n : Go to the next stage.\n"); HPC_PRINT(" p : Go to the prev stage.\n"); HPC_PRINT(" j [stage=0] : Go to the designated stage.\n"); HPC_PRINT(" d : Show the result of this stage.\n"); HPC_PRINT(" h : Show Help.\n"); HPC_PRINT(" e : Exit debugger.\n"); } } namespace hpc { //------------------------------------------------------------------------------ /// @brief Simulation クラスのインスタンスを生成します。 Simulation::Simulation() : mRandom() , mGame(mRandom) , mTimer(Parameter::GameTimeLimitSec) { } //------------------------------------------------------------------------------ /// @brief ゲームを実行します。 void Simulation::run() { // 制限時間と制限ターン数 mTimer.start(); while (mGame.isValidStage()) { mGame.startStage(mTimer.isInTime()); while (mGame.state() == StageState_Playing && mTimer.isInTime()) { mGame.runTurn(); } mGame.onStageDone(); } } //------------------------------------------------------------------------------ /// スコアを取得します。 int Simulation::score() const { return mGame.record().score() / Parameter::RepeatCount; } //------------------------------------------------------------------------------ /// 表示用時間を取得します。 double Simulation::pastTimeSecForPrint()const { return mTimer.pastSecForPrint() / Parameter::RepeatCount; } //------------------------------------------------------------------------------ /// 結果を表示します。 void Simulation::outputResult()const { HPC_PRINT("Done.\n"); HPC_PRINT("%8s:%8d\n", "Score", score()); HPC_PRINT("%8s:%8.4f\n", "Time", pastTimeSecForPrint()); } //------------------------------------------------------------------------------ /// @brief ゲームをデバッグ実行します。 void Simulation::debug() { // デバッグ前にデバッグをするかどうかを判断する。 // 入力待ち switch (SelectInput()) { case Command_Debug: runDebugger(); break; case Command_OutputJson: // 時間切れの場合は、JSONが不完全になるので出力を行わない。 if (mTimer.isInTime()) { mGame.record().dumpJson(true); } break; case Command_Exit: break; default: HPC_SHOULD_NOT_REACH_HERE(); break; } } //------------------------------------------------------------------------------ /// JSON データを出力します。 void Simulation::outputJson(bool isCompressed)const { // 時間切れの場合は、JSONが不完全になるので出力を行わない。 if (mTimer.isInTime()) { mGame.record().dumpJson(isCompressed); } } //------------------------------------------------------------------------------ /// デバッグ実行を行います。 void Simulation::runDebugger() { int stage = 0; bool doInput = true; // ステージ終了時に入力待ち するか。 do { if (doInput) { const DebugCommandSet commandSet = SelectInputDebugger(stage); switch(commandSet.command) { case DebugCommand_Next: ++stage; break; case DebugCommand_Prev: stage = Math::Max(stage - 1, 0); break; case DebugCommand_Show: mGame.record().dumpStage(stage); break; case DebugCommand_Jump: stage = Math::LimitMinMax(commandSet.arg1, 0, Parameter::GameStageCount - 1); break; case DebugCommand_Help: ShowHelp(); break; case DebugCommand_Exit: stage = Parameter::GameStageCount; break; default: HPC_SHOULD_NOT_REACH_HERE(); break; } } else { ++stage; } } while (stage < Parameter::GameStageCount); } } //------------------------------------------------------------------------------ // EOF
29.204225
97
0.420666
84192b3897572770dbce377b3e7d0bec703cbff4
998
cpp
C++
tests/kernel/globalinit.cpp
v8786339/NyuziProcessor
34854d333d91dbf69cd5625505fb81024ec4f785
[ "Apache-2.0" ]
1,388
2015-02-05T17:16:17.000Z
2022-03-31T07:17:08.000Z
tests/kernel/globalinit.cpp
czvf/NyuziProcessor
31f74e43a785fa66d244f1e9744ca0ca9b8a1fad
[ "Apache-2.0" ]
176
2015-02-02T02:54:06.000Z
2022-02-01T06:00:21.000Z
tests/kernel/globalinit.cpp
czvf/NyuziProcessor
31f74e43a785fa66d244f1e9744ca0ca9b8a1fad
[ "Apache-2.0" ]
271
2015-02-18T02:19:04.000Z
2022-03-28T13:30:25.000Z
// // Copyright 2016 Jeff Bush // // 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 <stdio.h> // // Make sure global constructors/destructors are called properly by crt0 // class Foo { public: Foo() { printf("Foo::Foo\n"); } ~Foo() { printf("Foo::~Foo\n"); } }; Foo f; int main() { // CHECK: Foo::Foo printf("main\n"); // CHECK: main // CHECK: Foo::~Foo return 0; } // CHECK: init process has exited, shutting down
20.791667
75
0.654309
841a59e25202ef8d5756d6c2ab19834648bbcfb8
100,646
cpp
C++
game/tools/guieditor/source/guieditorgui.cpp
justinctlam/MarbleStrike
64fe36a5a4db2b299983b0e2556ab1cd8126259b
[ "MIT" ]
null
null
null
game/tools/guieditor/source/guieditorgui.cpp
justinctlam/MarbleStrike
64fe36a5a4db2b299983b0e2556ab1cd8126259b
[ "MIT" ]
null
null
null
game/tools/guieditor/source/guieditorgui.cpp
justinctlam/MarbleStrike
64fe36a5a4db2b299983b0e2556ab1cd8126259b
[ "MIT" ]
2
2019-03-08T03:02:45.000Z
2019-05-14T08:41:26.000Z
/////////////////////////////////////////////////////////////////////////// // C++ code generated with wxFormBuilder (version Sep 8 2010) // http://www.wxformbuilder.org/ // // PLEASE DO "NOT" EDIT THIS FILE! /////////////////////////////////////////////////////////////////////////// #include "OGLCanvas.hpp" #include "timelinewidget.hpp" #include "guieditorgui.h" /////////////////////////////////////////////////////////////////////////// GuiEditorGui::GuiEditorGui( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxFrame( parent, id, title, pos, size, style ) { this->SetSizeHints( wxSize( 1200,800 ), wxSize( -1,-1 ) ); mMenuBar = new wxMenuBar( 0 ); mMenuFile = new wxMenu(); wxMenuItem* mNewMenuItem; mNewMenuItem = new wxMenuItem( mMenuFile, wxID_ANY, wxString( wxT("New") ) , wxEmptyString, wxITEM_NORMAL ); mMenuFile->Append( mNewMenuItem ); wxMenuItem* mOpenMenuItem; mOpenMenuItem = new wxMenuItem( mMenuFile, wxID_ANY, wxString( wxT("Open") ) , wxEmptyString, wxITEM_NORMAL ); mMenuFile->Append( mOpenMenuItem ); wxMenuItem* m_separator1; m_separator1 = mMenuFile->AppendSeparator(); wxMenuItem* mSaveAsMenuItem; mSaveAsMenuItem = new wxMenuItem( mMenuFile, wxID_ANY, wxString( wxT("Save As") ) , wxEmptyString, wxITEM_NORMAL ); mMenuFile->Append( mSaveAsMenuItem ); wxMenuItem* mSaveMenuItem; mSaveMenuItem = new wxMenuItem( mMenuFile, wxID_ANY, wxString( wxT("Save") ) , wxEmptyString, wxITEM_NORMAL ); mMenuFile->Append( mSaveMenuItem ); mMenuBar->Append( mMenuFile, wxT("File") ); mMenuEdit = new wxMenu(); wxMenuItem* m_menuItem23; m_menuItem23 = new wxMenuItem( mMenuEdit, EDIT_UNDO, wxString( wxT("Undo") ) , wxEmptyString, wxITEM_NORMAL ); mMenuEdit->Append( m_menuItem23 ); wxMenuItem* m_separator2; m_separator2 = mMenuEdit->AppendSeparator(); wxMenuItem* mMenuItemEditCopy; mMenuItemEditCopy = new wxMenuItem( mMenuEdit, EDIT_COPY, wxString( wxT("Copy") ) + wxT('\t') + wxT("CTRL+c"), wxEmptyString, wxITEM_NORMAL ); mMenuEdit->Append( mMenuItemEditCopy ); wxMenuItem* mMenuItemEditCut; mMenuItemEditCut = new wxMenuItem( mMenuEdit, EDIT_CUT, wxString( wxT("Cut") ) , wxEmptyString, wxITEM_NORMAL ); mMenuEdit->Append( mMenuItemEditCut ); wxMenuItem* mMenuItemEditPaste; mMenuItemEditPaste = new wxMenuItem( mMenuEdit, EDIT_PASTE, wxString( wxT("Paste") ) + wxT('\t') + wxT("CTRL+v"), wxEmptyString, wxITEM_NORMAL ); mMenuEdit->Append( mMenuItemEditPaste ); wxMenuItem* m_separator7; m_separator7 = mMenuEdit->AppendSeparator(); wxMenuItem* mMenuitemEditCopySize; mMenuitemEditCopySize = new wxMenuItem( mMenuEdit, EDIT_COPY_SIZE_DATA, wxString( wxT("Copy Size") ) , wxEmptyString, wxITEM_NORMAL ); mMenuEdit->Append( mMenuitemEditCopySize ); wxMenuItem* mMenuitemEditCopyPosition; mMenuitemEditCopyPosition = new wxMenuItem( mMenuEdit, EDIT_COPY_POSITION_DATA, wxString( wxT("Copy Position") ) , wxEmptyString, wxITEM_NORMAL ); mMenuEdit->Append( mMenuitemEditCopyPosition ); wxMenuItem* mMenuitemEditPasteSize; mMenuitemEditPasteSize = new wxMenuItem( mMenuEdit, EDIT_PASTE_SIZE_DATA, wxString( wxT("Paste Size") ) , wxEmptyString, wxITEM_NORMAL ); mMenuEdit->Append( mMenuitemEditPasteSize ); wxMenuItem* mMenuitemEditPastePosition; mMenuitemEditPastePosition = new wxMenuItem( mMenuEdit, EDIT_PASTE_POSITION_DATA, wxString( wxT("Paste Position") ) , wxEmptyString, wxITEM_NORMAL ); mMenuEdit->Append( mMenuitemEditPastePosition ); wxMenuItem* m_separator3; m_separator3 = mMenuEdit->AppendSeparator(); wxMenuItem* mMenuItemEditDelete; mMenuItemEditDelete = new wxMenuItem( mMenuEdit, EDIT_DELETE, wxString( wxT("Delete") ) , wxEmptyString, wxITEM_NORMAL ); mMenuEdit->Append( mMenuItemEditDelete ); wxMenuItem* m_separator4; m_separator4 = mMenuEdit->AppendSeparator(); wxMenuItem* mMenuItemEditShowHide; mMenuItemEditShowHide = new wxMenuItem( mMenuEdit, EDIT_SHOW_HIDE, wxString( wxT("Show/Hide") ) + wxT('\t') + wxT("CTRL+h"), wxEmptyString, wxITEM_NORMAL ); mMenuEdit->Append( mMenuItemEditShowHide ); mMenuBar->Append( mMenuEdit, wxT("Edit") ); mMenuRenderer = new wxMenu(); wxMenuItem* mMenuItemOpenGL; mMenuItemOpenGL = new wxMenuItem( mMenuRenderer, MENU_RENDERER_OPENGL, wxString( wxT("OpenGL") ) , wxEmptyString, wxITEM_RADIO ); mMenuRenderer->Append( mMenuItemOpenGL ); wxMenuItem* mMenuItemD3D; mMenuItemD3D = new wxMenuItem( mMenuRenderer, MENU_RENDERER_D3D, wxString( wxT("Direct3D") ) , wxEmptyString, wxITEM_RADIO ); mMenuRenderer->Append( mMenuItemD3D ); mMenuBar->Append( mMenuRenderer, wxT("Renderer") ); mMenuEditor = new wxMenu(); mMenuScreenSize = new wxMenu(); wxMenuItem* mMenuItemPortrait320x480; mMenuItemPortrait320x480 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_PORTRAIT_320_480, wxString( wxT("Portrait (320x480)") ) , wxEmptyString, wxITEM_RADIO ); mMenuScreenSize->Append( mMenuItemPortrait320x480 ); mMenuItemPortrait320x480->Check( true ); wxMenuItem* mMenuItemLandscape480x320; mMenuItemLandscape480x320 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_LANDSCAPE_480_320, wxString( wxT("Landscape (480x320)") ) , wxEmptyString, wxITEM_RADIO ); mMenuScreenSize->Append( mMenuItemLandscape480x320 ); wxMenuItem* mMenuItemPortrait640x960; mMenuItemPortrait640x960 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_PORTRAIT_640_960, wxString( wxT("Portrait (640x960)") ) , wxEmptyString, wxITEM_RADIO ); mMenuScreenSize->Append( mMenuItemPortrait640x960 ); mMenuItemPortrait640x960->Check( true ); wxMenuItem* mMenuItemLandscape960x640; mMenuItemLandscape960x640 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_LANDSCAPE_960_640, wxString( wxT("Landscape (9640x640)") ) , wxEmptyString, wxITEM_RADIO ); mMenuScreenSize->Append( mMenuItemLandscape960x640 ); wxMenuItem* mMenuItemPortrait640x1136; mMenuItemPortrait640x1136 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_PORTRAIT_640_1136, wxString( wxT("Portrait (640x1136)") ) , wxEmptyString, wxITEM_RADIO ); mMenuScreenSize->Append( mMenuItemPortrait640x1136 ); mMenuItemPortrait640x1136->Check( true ); wxMenuItem* mMenuItemLandscape1136x640; mMenuItemLandscape1136x640 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_LANDSCAPE_1136_640, wxString( wxT("Landscape (1136x640)") ) , wxEmptyString, wxITEM_RADIO ); mMenuScreenSize->Append( mMenuItemLandscape1136x640 ); wxMenuItem* mMenuItemPortrait720x1280; mMenuItemPortrait720x1280 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_PORTRAIT_720_1280, wxString( wxT("Portrait (720x1280)") ) , wxEmptyString, wxITEM_RADIO ); mMenuScreenSize->Append( mMenuItemPortrait720x1280 ); mMenuItemPortrait720x1280->Check( true ); wxMenuItem* mMenuItemLandscape1280x720; mMenuItemLandscape1280x720 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_LANDSCAPE_1280_720, wxString( wxT("Landscape (1280x720)") ) , wxEmptyString, wxITEM_RADIO ); mMenuScreenSize->Append( mMenuItemLandscape1280x720 ); wxMenuItem* mMenuItemPortrait768x1024; mMenuItemPortrait768x1024 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_PORTRAIT_768_1024, wxString( wxT("Portrait (768x1024)") ) , wxEmptyString, wxITEM_RADIO ); mMenuScreenSize->Append( mMenuItemPortrait768x1024 ); mMenuItemPortrait768x1024->Check( true ); wxMenuItem* mMenuItemLandscape1024x768; mMenuItemLandscape1024x768 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_LANDSCAPE_1024_768, wxString( wxT("Landscape (1024x768)") ) , wxEmptyString, wxITEM_RADIO ); mMenuScreenSize->Append( mMenuItemLandscape1024x768 ); wxMenuItem* mMenuItemPortrait1536x2048; mMenuItemPortrait1536x2048 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_PORTRAIT_1536_2048, wxString( wxT("Portrait (1536x2048)") ) , wxEmptyString, wxITEM_RADIO ); mMenuScreenSize->Append( mMenuItemPortrait1536x2048 ); mMenuItemPortrait1536x2048->Check( true ); wxMenuItem* mMenuItemLandscape2048x1536; mMenuItemLandscape2048x1536 = new wxMenuItem( mMenuScreenSize, SCREEN_SIZE_LANDSCAPE_2048_1536, wxString( wxT("Landscape (2048x1536)") ) , wxEmptyString, wxITEM_RADIO ); mMenuScreenSize->Append( mMenuItemLandscape2048x1536 ); mMenuEditor->Append( -1, wxT("Screen Size"), mMenuScreenSize ); wxMenuItem* m_separator5; m_separator5 = mMenuEditor->AppendSeparator(); wxMenuItem* mMenuInsertStatic; mMenuInsertStatic = new wxMenuItem( mMenuEditor, EDITOR_MENU_INSERT_STATIC, wxString( wxT("Insert Static") ) , wxEmptyString, wxITEM_NORMAL ); mMenuEditor->Append( mMenuInsertStatic ); wxMenuItem* mMenuInsertButton; mMenuInsertButton = new wxMenuItem( mMenuEditor, EDITOR_MENU_INSERT_BUTTON, wxString( wxT("Insert Button") ) , wxEmptyString, wxITEM_NORMAL ); mMenuEditor->Append( mMenuInsertButton ); wxMenuItem* mMenuInsertSlider; mMenuInsertSlider = new wxMenuItem( mMenuEditor, EDITOR_MENU_INSERT_SLIDER, wxString( wxT("Insert Slider") ) , wxEmptyString, wxITEM_NORMAL ); mMenuEditor->Append( mMenuInsertSlider ); wxMenuItem* mMenuInsertSprite; mMenuInsertSprite = new wxMenuItem( mMenuEditor, EDITOR_MENU_INSERT_SPRITE, wxString( wxT("Insert Sprite") ) , wxEmptyString, wxITEM_NORMAL ); mMenuEditor->Append( mMenuInsertSprite ); wxMenuItem* m_separator6; m_separator6 = mMenuEditor->AppendSeparator(); wxMenuItem* mMenuMoveBack; mMenuMoveBack = new wxMenuItem( mMenuEditor, EDITOR_MENU_MOVE_BACK, wxString( wxT("Move Back") ) + wxT('\t') + wxT("CTRL+b"), wxEmptyString, wxITEM_NORMAL ); mMenuEditor->Append( mMenuMoveBack ); wxMenuItem* mMenuMoveFront; mMenuMoveFront = new wxMenuItem( mMenuEditor, EDITOR_MENU_MOVE_FRONT, wxString( wxT("Move Front") ) + wxT('\t') + wxT("CTRL+f"), wxEmptyString, wxITEM_NORMAL ); mMenuEditor->Append( mMenuMoveFront ); mMenuBar->Append( mMenuEditor, wxT("Editor") ); mMenuAnimation = new wxMenu(); wxMenuItem* mMenuAnimationPlay; mMenuAnimationPlay = new wxMenuItem( mMenuAnimation, EDITOR_MENU_ANIMATION_PLAY, wxString( wxT("Play") ) , wxEmptyString, wxITEM_NORMAL ); mMenuAnimation->Append( mMenuAnimationPlay ); wxMenuItem* mMenuAnimationStop; mMenuAnimationStop = new wxMenuItem( mMenuAnimation, EDITOR_MENU_ANIMATION_STOP, wxString( wxT("Stop") ) , wxEmptyString, wxITEM_NORMAL ); mMenuAnimation->Append( mMenuAnimationStop ); wxMenuItem* mMenuAnimationAddKeyFrame; mMenuAnimationAddKeyFrame = new wxMenuItem( mMenuAnimation, EDITOR_MENU_ANIMATION_ADD_KEYFRAME, wxString( wxT("Add Key Frame") ) , wxEmptyString, wxITEM_NORMAL ); mMenuAnimation->Append( mMenuAnimationAddKeyFrame ); wxMenuItem* mMenuAnimationDeleteKeyFrame; mMenuAnimationDeleteKeyFrame = new wxMenuItem( mMenuAnimation, EDITOR_MENU_ANIMATION_DELETE_KEYFRAME, wxString( wxT("Delete Key Frame") ) , wxEmptyString, wxITEM_NORMAL ); mMenuAnimation->Append( mMenuAnimationDeleteKeyFrame ); mMenuBar->Append( mMenuAnimation, wxT("Animation") ); this->SetMenuBar( mMenuBar ); wxBoxSizer* bSizer18; bSizer18 = new wxBoxSizer( wxVERTICAL ); m_panel7 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxFlexGridSizer* fgSizer38; fgSizer38 = new wxFlexGridSizer( 1, 12, 0, 0 ); fgSizer38->SetFlexibleDirection( wxBOTH ); fgSizer38->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); wxString mRadioBoxTransformChoices[] = { wxT("X"), wxT("Y"), wxT("X-Y") }; int mRadioBoxTransformNChoices = sizeof( mRadioBoxTransformChoices ) / sizeof( wxString ); mRadioBoxTransform = new wxRadioBox( m_panel7, wxID_ANY, wxT("Transform"), wxDefaultPosition, wxDefaultSize, mRadioBoxTransformNChoices, mRadioBoxTransformChoices, 1, wxRA_SPECIFY_ROWS ); mRadioBoxTransform->SetSelection( 2 ); fgSizer38->Add( mRadioBoxTransform, 0, wxALL, 5 ); m_staticline1 = new wxStaticLine( m_panel7, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); fgSizer38->Add( m_staticline1, 0, wxEXPAND | wxALL, 5 ); m_button10 = new wxButton( m_panel7, LAYOUT_VERTICAL_CENTRE, wxT("Centre Vertical"), wxDefaultPosition, wxSize( -1,-1 ), 0 ); fgSizer38->Add( m_button10, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 ); m_button111 = new wxButton( m_panel7, LAYOUT_HORIZONTAL_CENTRE, wxT("Centre Horizontal"), wxDefaultPosition, wxSize( -1,-1 ), 0 ); fgSizer38->Add( m_button111, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 ); m_staticline2 = new wxStaticLine( m_panel7, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); fgSizer38->Add( m_staticline2, 0, wxEXPAND | wxALL, 5 ); m_staticText27 = new wxStaticText( m_panel7, wxID_ANY, wxT("Bounding Box Color:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText27->Wrap( -1 ); fgSizer38->Add( m_staticText27, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); mColorPickerBoundingBox = new wxColourPickerCtrl( m_panel7, COLOR_PICK_BOUNDING_BOX, *wxBLACK, wxDefaultPosition, wxSize( -1,-1 ), wxCLRP_DEFAULT_STYLE ); fgSizer38->Add( mColorPickerBoundingBox, 0, wxALIGN_CENTER_VERTICAL, 5 ); m_staticline3 = new wxStaticLine( m_panel7, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); fgSizer38->Add( m_staticline3, 0, wxEXPAND | wxALL, 5 ); m_staticText28 = new wxStaticText( m_panel7, wxID_ANY, wxT("Bounding Box Select Color:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText28->Wrap( -1 ); fgSizer38->Add( m_staticText28, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); mColorPickerBoundingBoxSelect = new wxColourPickerCtrl( m_panel7, COLOR_PICK_BOUNDING_BOX_SELECT, *wxBLACK, wxDefaultPosition, wxDefaultSize, wxCLRP_DEFAULT_STYLE ); fgSizer38->Add( mColorPickerBoundingBoxSelect, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); m_staticText281 = new wxStaticText( m_panel7, wxID_ANY, wxT("Background Color:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText281->Wrap( -1 ); fgSizer38->Add( m_staticText281, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); mColorPickerBackground = new wxColourPickerCtrl( m_panel7, COLOR_PICK_BOUNDING_BOX_SELECT, *wxBLACK, wxDefaultPosition, wxDefaultSize, wxCLRP_DEFAULT_STYLE ); fgSizer38->Add( mColorPickerBackground, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); m_panel7->SetSizer( fgSizer38 ); m_panel7->Layout(); fgSizer38->Fit( m_panel7 ); bSizer18->Add( m_panel7, 0, wxEXPAND, 5 ); wxFlexGridSizer* fgSizer11; fgSizer11 = new wxFlexGridSizer( 1, 3, 0, 0 ); fgSizer11->AddGrowableCol( 0 ); fgSizer11->AddGrowableRow( 0 ); fgSizer11->SetFlexibleDirection( wxBOTH ); fgSizer11->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); wxBoxSizer* bSizer31; bSizer31 = new wxBoxSizer( wxVERTICAL ); mNotebook = new wxNotebook( this, wxID_ANY, wxDefaultPosition, wxSize( -1,-1 ), 0 ); m_panel2 = new wxPanel( mNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxBoxSizer* bSizer1; bSizer1 = new wxBoxSizer( wxVERTICAL ); mSceneGraphTree = new wxTreeCtrl( m_panel2, wxID_ANY, wxDefaultPosition, wxSize( -1,-1 ), wxTR_DEFAULT_STYLE|wxTR_HIDE_ROOT|wxTR_MULTIPLE ); mSceneGraphTree->SetMinSize( wxSize( 250,800 ) ); bSizer1->Add( mSceneGraphTree, 1, wxALL|wxEXPAND, 5 ); m_panel2->SetSizer( bSizer1 ); m_panel2->Layout(); bSizer1->Fit( m_panel2 ); mNotebook->AddPage( m_panel2, wxT("Scene Graph"), false ); bSizer31->Add( mNotebook, 0, 0, 10 ); fgSizer11->Add( bSizer31, 0, 0, 5 ); wxBoxSizer* bSizer7; bSizer7 = new wxBoxSizer( wxVERTICAL ); mButtonProperties = new wxScrolledWindow( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxHSCROLL|wxVSCROLL ); mButtonProperties->SetScrollRate( 5, 5 ); mButtonProperties->Hide(); mButtonProperties->SetMinSize( wxSize( 250,800 ) ); wxFlexGridSizer* fgSizer19; fgSizer19 = new wxFlexGridSizer( 2, 1, 0, 0 ); fgSizer19->SetFlexibleDirection( wxBOTH ); fgSizer19->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); wxStaticBoxSizer* sbSizer7; sbSizer7 = new wxStaticBoxSizer( new wxStaticBox( mButtonProperties, wxID_ANY, wxEmptyString ), wxVERTICAL ); wxGridSizer* gSizer1; gSizer1 = new wxGridSizer( 8, 2, 0, 0 ); m_staticText38 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("Name:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText38->Wrap( -1 ); gSizer1->Add( m_staticText38, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); mTextButtonName = new wxTextCtrl( mButtonProperties, TEXT_BUTTON_NAME, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer1->Add( mTextButtonName, 0, wxALL, 5 ); m_staticText391 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("Width:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText391->Wrap( -1 ); gSizer1->Add( m_staticText391, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); mTextButtonWidth = new wxTextCtrl( mButtonProperties, TEXT_BUTTON_WIDTH, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer1->Add( mTextButtonWidth, 0, wxALL, 5 ); m_staticText3911 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("Height:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText3911->Wrap( -1 ); gSizer1->Add( m_staticText3911, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); mTextButtonHeight = new wxTextCtrl( mButtonProperties, TEXT_BUTTON_HEIGHT, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer1->Add( mTextButtonHeight, 0, wxALL, 5 ); m_staticText411 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("x:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText411->Wrap( -1 ); gSizer1->Add( m_staticText411, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); mTextButtonX = new wxTextCtrl( mButtonProperties, TEXT_BUTTON_X, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer1->Add( mTextButtonX, 0, wxALL, 5 ); m_staticText4111 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("y:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText4111->Wrap( -1 ); gSizer1->Add( m_staticText4111, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); mTextButtonY = new wxTextCtrl( mButtonProperties, TEXT_BUTTON_Y, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer1->Add( mTextButtonY, 0, wxALL, 5 ); m_staticText341 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("Text:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText341->Wrap( -1 ); gSizer1->Add( m_staticText341, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); mTextButtonText = new wxTextCtrl( mButtonProperties, TEXT_BUTTON_TEXT, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer1->Add( mTextButtonText, 0, wxALL, 5 ); m_staticText35 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("Colour:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText35->Wrap( -1 ); gSizer1->Add( m_staticText35, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); mColorPickerButton = new wxColourPickerCtrl( mButtonProperties, COLOR_PICKER_BUTTON, *wxBLACK, wxDefaultPosition, wxDefaultSize, wxCLRP_DEFAULT_STYLE ); gSizer1->Add( mColorPickerButton, 0, wxALL|wxEXPAND, 5 ); m_staticText57 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("Transparency:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText57->Wrap( -1 ); gSizer1->Add( m_staticText57, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); mSliderButtonAlpha = new wxSlider( mButtonProperties, SLIDER_BUTTON_ALPHA, 255, 0, 255, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL ); gSizer1->Add( mSliderButtonAlpha, 0, wxALL, 5 ); sbSizer7->Add( gSizer1, 0, 0, 5 ); fgSizer19->Add( sbSizer7, 0, wxALL, 5 ); wxStaticBoxSizer* sbSizer61; sbSizer61 = new wxStaticBoxSizer( new wxStaticBox( mButtonProperties, wxID_ANY, wxEmptyString ), wxVERTICAL ); m_staticText36 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("Texture:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText36->Wrap( -1 ); sbSizer61->Add( m_staticText36, 0, wxALL, 5 ); mFilePickButtonTexture = new wxFilePickerCtrl( mButtonProperties, FILE_PICK_BUTTON_TEXTURE, wxEmptyString, wxT("Select a file"), wxT("*.png"), wxDefaultPosition, wxSize( -1,-1 ), wxFLP_DEFAULT_STYLE ); sbSizer61->Add( mFilePickButtonTexture, 0, wxALL, 5 ); wxFlexGridSizer* fgSizer1221; fgSizer1221 = new wxFlexGridSizer( 2, 2, 0, 0 ); fgSizer1221->SetFlexibleDirection( wxBOTH ); fgSizer1221->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); mButtonButtonClearTexture = new wxButton( mButtonProperties, BUTTON_BUTTON_CLEAR_TEXTURE, wxT("Clear"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer1221->Add( mButtonButtonClearTexture, 0, wxALL, 5 ); mButtonButtonCreateUV = new wxButton( mButtonProperties, BUTTON_BUTTON_CREATE_UV, wxT("Create UV"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer1221->Add( mButtonButtonCreateUV, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 ); sbSizer61->Add( fgSizer1221, 0, 0, 5 ); mOnPressTextureLabel = new wxStaticText( mButtonProperties, wxID_ANY, wxT("OnPress Texture:"), wxDefaultPosition, wxDefaultSize, 0 ); mOnPressTextureLabel->Wrap( -1 ); sbSizer61->Add( mOnPressTextureLabel, 0, wxALL, 5 ); mFilePickButtonOnPressTexture = new wxFilePickerCtrl( mButtonProperties, FILE_PICK_BUTTON_ONPRESS_TEXTURE, wxEmptyString, wxT("Select a file"), wxT("*.png"), wxDefaultPosition, wxDefaultSize, wxFLP_DEFAULT_STYLE ); sbSizer61->Add( mFilePickButtonOnPressTexture, 0, wxALL, 5 ); wxFlexGridSizer* fgSizer12213; fgSizer12213 = new wxFlexGridSizer( 2, 2, 0, 0 ); fgSizer12213->SetFlexibleDirection( wxBOTH ); fgSizer12213->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); mButtonButtonClearOnPressTexture = new wxButton( mButtonProperties, BUTTON_BUTTON_ONPRESS_CLEAR_TEXTURE, wxT("Clear"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer12213->Add( mButtonButtonClearOnPressTexture, 0, wxALL, 5 ); mButtonButtonOnPressCreateUV = new wxButton( mButtonProperties, BUTTON_BUTTON_ONPRESS_CREATE_UV, wxT("Create UV"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer12213->Add( mButtonButtonOnPressCreateUV, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 ); sbSizer61->Add( fgSizer12213, 1, wxEXPAND, 5 ); m_staticText37 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("Font:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText37->Wrap( -1 ); sbSizer61->Add( m_staticText37, 0, wxALL, 5 ); mFilePickButtonFont = new wxFilePickerCtrl( mButtonProperties, FILE_PICK_BUTTON_FONT, wxEmptyString, wxT("Select a file"), wxT("*.xml"), wxDefaultPosition, wxDefaultSize, wxFLP_DEFAULT_STYLE ); sbSizer61->Add( mFilePickButtonFont, 0, wxALL, 5 ); wxGridSizer* gSizer51; gSizer51 = new wxGridSizer( 2, 2, 0, 0 ); m_staticText342 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("Font Colour:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText342->Wrap( -1 ); gSizer51->Add( m_staticText342, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); mColorPickerButtonFont = new wxColourPickerCtrl( mButtonProperties, COLOR_PICKER_BUTTON_FONT, *wxBLACK, wxDefaultPosition, wxDefaultSize, wxCLRP_DEFAULT_STYLE ); gSizer51->Add( mColorPickerButtonFont, 0, wxALL|wxEXPAND, 5 ); m_staticText3521 = new wxStaticText( mButtonProperties, wxID_ANY, wxT("Font Size:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText3521->Wrap( -1 ); gSizer51->Add( m_staticText3521, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); mTextButtonFontSize = new wxTextCtrl( mButtonProperties, TEXT_BUTTON_FONT_SIZE, wxEmptyString, wxDefaultPosition, wxSize( 50,-1 ), wxTE_PROCESS_ENTER ); gSizer51->Add( mTextButtonFontSize, 0, wxALL, 5 ); sbSizer61->Add( gSizer51, 0, wxEXPAND, 5 ); wxGridSizer* gSizer81; gSizer81 = new wxGridSizer( 2, 2, 0, 0 ); wxString mChoiceButtonFontHorizontalChoices[] = { wxT("Left"), wxT("Right"), wxT("Centre") }; int mChoiceButtonFontHorizontalNChoices = sizeof( mChoiceButtonFontHorizontalChoices ) / sizeof( wxString ); mChoiceButtonFontHorizontal = new wxChoice( mButtonProperties, CHOICE_BUTTON_FONT_HORIZONTAL, wxDefaultPosition, wxDefaultSize, mChoiceButtonFontHorizontalNChoices, mChoiceButtonFontHorizontalChoices, 0 ); mChoiceButtonFontHorizontal->SetSelection( 0 ); gSizer81->Add( mChoiceButtonFontHorizontal, 0, wxALL, 5 ); wxString mChoiceButtonFontVerticalChoices[] = { wxT("Top"), wxT("Bottom"), wxT("Centre") }; int mChoiceButtonFontVerticalNChoices = sizeof( mChoiceButtonFontVerticalChoices ) / sizeof( wxString ); mChoiceButtonFontVertical = new wxChoice( mButtonProperties, CHOICE_BUTTON_FONT_VERTICAL, wxDefaultPosition, wxDefaultSize, mChoiceButtonFontVerticalNChoices, mChoiceButtonFontVerticalChoices, 0 ); mChoiceButtonFontVertical->SetSelection( 0 ); gSizer81->Add( mChoiceButtonFontVertical, 0, wxALL, 5 ); sbSizer61->Add( gSizer81, 0, 0, 5 ); fgSizer19->Add( sbSizer61, 0, wxEXPAND|wxALL, 5 ); mButtonProperties->SetSizer( fgSizer19 ); mButtonProperties->Layout(); fgSizer19->Fit( mButtonProperties ); bSizer7->Add( mButtonProperties, 1, wxALIGN_CENTER_HORIZONTAL|wxEXPAND, 5 ); mClearPanel = new wxScrolledWindow( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxHSCROLL|wxVSCROLL ); mClearPanel->SetScrollRate( 5, 5 ); mClearPanel->Hide(); mClearPanel->SetMinSize( wxSize( 250,800 ) ); bSizer7->Add( mClearPanel, 1, wxEXPAND, 5 ); mSliderProperties = new wxScrolledWindow( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxHSCROLL|wxVSCROLL ); mSliderProperties->SetScrollRate( 5, 5 ); mSliderProperties->Hide(); mSliderProperties->SetMinSize( wxSize( 250,800 ) ); wxFlexGridSizer* fgSizer192; fgSizer192 = new wxFlexGridSizer( 2, 1, 0, 0 ); fgSizer192->SetFlexibleDirection( wxBOTH ); fgSizer192->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); wxStaticBoxSizer* sbSizer72; sbSizer72 = new wxStaticBoxSizer( new wxStaticBox( mSliderProperties, wxID_ANY, wxEmptyString ), wxVERTICAL ); wxGridSizer* gSizer12; gSizer12 = new wxGridSizer( 8, 2, 0, 0 ); m_staticText381 = new wxStaticText( mSliderProperties, wxID_ANY, wxT("Name:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText381->Wrap( -1 ); gSizer12->Add( m_staticText381, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); mTextSliderName = new wxTextCtrl( mSliderProperties, TEXT_SLIDER_NAME, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer12->Add( mTextSliderName, 0, wxALL, 5 ); m_staticText3913 = new wxStaticText( mSliderProperties, wxID_ANY, wxT("Width:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText3913->Wrap( -1 ); gSizer12->Add( m_staticText3913, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); mTextSliderWidth = new wxTextCtrl( mSliderProperties, TEXT_SLIDER_WIDTH, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer12->Add( mTextSliderWidth, 0, wxALL, 5 ); m_staticText39112 = new wxStaticText( mSliderProperties, wxID_ANY, wxT("Height:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText39112->Wrap( -1 ); gSizer12->Add( m_staticText39112, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); mTextSliderHeight = new wxTextCtrl( mSliderProperties, TEXT_SLIDER_HEIGHT, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer12->Add( mTextSliderHeight, 0, wxALL, 5 ); m_staticText4113 = new wxStaticText( mSliderProperties, wxID_ANY, wxT("x:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText4113->Wrap( -1 ); gSizer12->Add( m_staticText4113, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); mTextSliderX = new wxTextCtrl( mSliderProperties, TEXT_SLIDER_X, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer12->Add( mTextSliderX, 0, wxALL, 5 ); m_staticText41112 = new wxStaticText( mSliderProperties, wxID_ANY, wxT("y:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText41112->Wrap( -1 ); gSizer12->Add( m_staticText41112, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); mTextSliderY = new wxTextCtrl( mSliderProperties, TEXT_SLIDER_Y, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer12->Add( mTextSliderY, 0, wxALL, 5 ); m_staticText81 = new wxStaticText( mSliderProperties, wxID_ANY, wxT("Min:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText81->Wrap( -1 ); gSizer12->Add( m_staticText81, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); mTextSliderMin = new wxTextCtrl( mSliderProperties, TEXT_SLIDER_MIN, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer12->Add( mTextSliderMin, 0, wxALL, 5 ); m_staticText82 = new wxStaticText( mSliderProperties, wxID_ANY, wxT("Max:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText82->Wrap( -1 ); gSizer12->Add( m_staticText82, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); mTextSliderMax = new wxTextCtrl( mSliderProperties, TEXT_SLIDER_MAX, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer12->Add( mTextSliderMax, 0, wxALL, 5 ); m_staticText83 = new wxStaticText( mSliderProperties, wxID_ANY, wxT("Default:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText83->Wrap( -1 ); gSizer12->Add( m_staticText83, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); mTextSliderDefault = new wxTextCtrl( mSliderProperties, TEXT_SLIDER_DEFAULT, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer12->Add( mTextSliderDefault, 0, wxALL, 5 ); sbSizer72->Add( gSizer12, 0, 0, 5 ); fgSizer192->Add( sbSizer72, 0, wxALL, 5 ); wxBoxSizer* bSizer181; bSizer181 = new wxBoxSizer( wxVERTICAL ); wxStaticBoxSizer* sbSizer612; sbSizer612 = new wxStaticBoxSizer( new wxStaticBox( mSliderProperties, wxID_ANY, wxEmptyString ), wxVERTICAL ); m_staticText362 = new wxStaticText( mSliderProperties, wxID_ANY, wxT("Texture Bar:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText362->Wrap( -1 ); sbSizer612->Add( m_staticText362, 0, wxALL, 5 ); mFilePickSliderTextureBar = new wxFilePickerCtrl( mSliderProperties, FILE_PICK_SLIDER_TEXTURE_BAR, wxEmptyString, wxT("Select a file"), wxT("*.png"), wxDefaultPosition, wxSize( -1,-1 ), wxFLP_DEFAULT_STYLE ); sbSizer612->Add( mFilePickSliderTextureBar, 0, wxALL, 5 ); wxFlexGridSizer* fgSizer12212; fgSizer12212 = new wxFlexGridSizer( 2, 2, 0, 0 ); fgSizer12212->SetFlexibleDirection( wxBOTH ); fgSizer12212->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); mButtonSliderClearTextureBar = new wxButton( mSliderProperties, BUTTON_SLIDER_CLEAR_TEXTURE_BAR, wxT("Clear"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer12212->Add( mButtonSliderClearTextureBar, 0, wxALL, 5 ); mButtonSliderCreateUVBar = new wxButton( mSliderProperties, BUTTON_SLIDER_CREATE_UV_BAR, wxT("Create UV"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer12212->Add( mButtonSliderCreateUVBar, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 ); sbSizer612->Add( fgSizer12212, 0, 0, 5 ); m_staticText3621 = new wxStaticText( mSliderProperties, wxID_ANY, wxT("Texture Button:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText3621->Wrap( -1 ); sbSizer612->Add( m_staticText3621, 0, wxALL, 5 ); mFilePickSliderTextureButton = new wxFilePickerCtrl( mSliderProperties, FILE_PICK_SLIDER_TEXTURE_BUTTON, wxEmptyString, wxT("Select a file"), wxT("*.png"), wxDefaultPosition, wxSize( -1,-1 ), wxFLP_DEFAULT_STYLE ); sbSizer612->Add( mFilePickSliderTextureButton, 0, wxALL, 5 ); wxFlexGridSizer* fgSizer122121; fgSizer122121 = new wxFlexGridSizer( 2, 2, 0, 0 ); fgSizer122121->SetFlexibleDirection( wxBOTH ); fgSizer122121->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); mButtonSliderClearTextureButton = new wxButton( mSliderProperties, BUTTON_SLIDER_CLEAR_TEXTURE_BUTTON, wxT("Clear"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer122121->Add( mButtonSliderClearTextureButton, 0, wxALL, 5 ); mButtonSliderCreateUVButton = new wxButton( mSliderProperties, BUTTON_SLIDER_CREATE_UV_BUTTON, wxT("Create UV"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer122121->Add( mButtonSliderCreateUVButton, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 ); sbSizer612->Add( fgSizer122121, 1, wxEXPAND, 5 ); bSizer181->Add( sbSizer612, 0, wxEXPAND|wxALL, 5 ); fgSizer192->Add( bSizer181, 0, 0, 5 ); mSliderProperties->SetSizer( fgSizer192 ); mSliderProperties->Layout(); fgSizer192->Fit( mSliderProperties ); bSizer7->Add( mSliderProperties, 1, wxEXPAND, 5 ); mSpriteProperties = new wxScrolledWindow( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxHSCROLL|wxVSCROLL ); mSpriteProperties->SetScrollRate( 5, 5 ); mSpriteProperties->Hide(); mSpriteProperties->SetMinSize( wxSize( 250,800 ) ); wxFlexGridSizer* fgSizer1911; fgSizer1911 = new wxFlexGridSizer( 2, 1, 0, 0 ); fgSizer1911->SetFlexibleDirection( wxBOTH ); fgSizer1911->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); wxStaticBoxSizer* sbSizer711; sbSizer711 = new wxStaticBoxSizer( new wxStaticBox( mSpriteProperties, wxID_ANY, wxEmptyString ), wxVERTICAL ); wxGridSizer* gSizer111; gSizer111 = new wxGridSizer( 8, 2, 0, 0 ); m_staticText3831 = new wxStaticText( mSpriteProperties, wxID_ANY, wxT("Name:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText3831->Wrap( -1 ); gSizer111->Add( m_staticText3831, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); mTextSpriteName = new wxTextCtrl( mSpriteProperties, TEXT_SPRITE_NAME, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer111->Add( mTextSpriteName, 0, wxALL, 5 ); m_staticText39121 = new wxStaticText( mSpriteProperties, wxID_ANY, wxT("Width:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText39121->Wrap( -1 ); gSizer111->Add( m_staticText39121, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); mTextSpriteWidth = new wxTextCtrl( mSpriteProperties, TEXT_SPRITE_WIDTH, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer111->Add( mTextSpriteWidth, 0, wxALL, 5 ); m_staticText391111 = new wxStaticText( mSpriteProperties, wxID_ANY, wxT("Height:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText391111->Wrap( -1 ); gSizer111->Add( m_staticText391111, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); mTextSpriteHeight = new wxTextCtrl( mSpriteProperties, TEXT_SPRITE_HEIGHT, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer111->Add( mTextSpriteHeight, 0, wxALL, 5 ); m_staticText41121 = new wxStaticText( mSpriteProperties, wxID_ANY, wxT("x:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText41121->Wrap( -1 ); gSizer111->Add( m_staticText41121, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); mTextSpriteX = new wxTextCtrl( mSpriteProperties, TEXT_SPRITE_X, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer111->Add( mTextSpriteX, 0, wxALL, 5 ); m_staticText411111 = new wxStaticText( mSpriteProperties, wxID_ANY, wxT("y:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText411111->Wrap( -1 ); gSizer111->Add( m_staticText411111, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); mTextSpriteY = new wxTextCtrl( mSpriteProperties, TEXT_SPRITE_Y, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer111->Add( mTextSpriteY, 0, wxALL, 5 ); m_staticText3511 = new wxStaticText( mSpriteProperties, wxID_ANY, wxT("Colour:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText3511->Wrap( -1 ); gSizer111->Add( m_staticText3511, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); mColorPickerSprite = new wxColourPickerCtrl( mSpriteProperties, COLOR_PICKER_SPRITE, *wxBLACK, wxDefaultPosition, wxDefaultSize, wxCLRP_DEFAULT_STYLE ); gSizer111->Add( mColorPickerSprite, 0, wxALL|wxEXPAND, 5 ); m_staticText5712 = new wxStaticText( mSpriteProperties, wxID_ANY, wxT("Transparency:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText5712->Wrap( -1 ); gSizer111->Add( m_staticText5712, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); mSliderSpriteAlpha = new wxSlider( mSpriteProperties, SLIDER_SPRITE_ALPHA, 255, 0, 255, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL ); gSizer111->Add( mSliderSpriteAlpha, 0, wxALL, 5 ); sbSizer711->Add( gSizer111, 0, 0, 5 ); fgSizer1911->Add( sbSizer711, 0, wxALL, 5 ); wxStaticBoxSizer* sbSizer6111; sbSizer6111 = new wxStaticBoxSizer( new wxStaticBox( mSpriteProperties, wxID_ANY, wxEmptyString ), wxVERTICAL ); m_staticText3611 = new wxStaticText( mSpriteProperties, wxID_ANY, wxT("Sprite Texture:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText3611->Wrap( -1 ); sbSizer6111->Add( m_staticText3611, 0, wxALL, 5 ); mFilePickSpriteTextureFile = new wxFilePickerCtrl( mSpriteProperties, FILE_PICK_SPRITE_TEXTURE_FILE, wxEmptyString, wxT("Select a file"), wxT("*.png"), wxDefaultPosition, wxSize( -1,-1 ), wxFLP_DEFAULT_STYLE ); sbSizer6111->Add( mFilePickSpriteTextureFile, 0, wxALL, 5 ); wxFlexGridSizer* fgSizer122111; fgSizer122111 = new wxFlexGridSizer( 2, 2, 0, 0 ); fgSizer122111->SetFlexibleDirection( wxBOTH ); fgSizer122111->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); mButtonSpriteClearTexture = new wxButton( mSpriteProperties, BUTTON_SPRITE_CLEAR_TEXTURE, wxT("Clear"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer122111->Add( mButtonSpriteClearTexture, 0, wxALL, 5 ); sbSizer6111->Add( fgSizer122111, 0, 0, 5 ); wxFlexGridSizer* fgSizer17; fgSizer17 = new wxFlexGridSizer( 1, 2, 0, 0 ); fgSizer17->SetFlexibleDirection( wxBOTH ); fgSizer17->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); m_staticText38311 = new wxStaticText( mSpriteProperties, wxID_ANY, wxT("Frames Per Second:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText38311->Wrap( -1 ); fgSizer17->Add( m_staticText38311, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); mTextSpriteFPS = new wxTextCtrl( mSpriteProperties, TEXT_SPRITE_FPS, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); fgSizer17->Add( mTextSpriteFPS, 0, wxALL, 5 ); sbSizer6111->Add( fgSizer17, 1, wxEXPAND, 5 ); fgSizer1911->Add( sbSizer6111, 0, wxALL, 5 ); mSpriteProperties->SetSizer( fgSizer1911 ); mSpriteProperties->Layout(); fgSizer1911->Fit( mSpriteProperties ); bSizer7->Add( mSpriteProperties, 1, wxEXPAND, 5 ); mStaticProperties = new wxScrolledWindow( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxHSCROLL|wxVSCROLL ); mStaticProperties->SetScrollRate( 5, 5 ); mStaticProperties->SetMinSize( wxSize( 250,800 ) ); wxFlexGridSizer* fgSizer191; fgSizer191 = new wxFlexGridSizer( 3, 1, 0, 0 ); fgSizer191->SetFlexibleDirection( wxBOTH ); fgSizer191->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); wxStaticBoxSizer* sbSizer71; sbSizer71 = new wxStaticBoxSizer( new wxStaticBox( mStaticProperties, wxID_ANY, wxEmptyString ), wxVERTICAL ); wxGridSizer* gSizer11; gSizer11 = new wxGridSizer( 7, 2, 0, 0 ); m_staticText383 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("Name:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText383->Wrap( -1 ); gSizer11->Add( m_staticText383, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); mTextStaticName = new wxTextCtrl( mStaticProperties, TEXT_STATIC_NAME, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer11->Add( mTextStaticName, 0, wxALL, 5 ); m_staticText3912 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("Width:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText3912->Wrap( -1 ); gSizer11->Add( m_staticText3912, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); mTextStaticWidth = new wxTextCtrl( mStaticProperties, TEXT_STATIC_WIDTH, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer11->Add( mTextStaticWidth, 0, wxALL, 5 ); m_staticText39111 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("Height:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText39111->Wrap( -1 ); gSizer11->Add( m_staticText39111, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); mTextStaticHeight = new wxTextCtrl( mStaticProperties, TEXT_STATIC_HEIGHT, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer11->Add( mTextStaticHeight, 0, wxALL, 5 ); m_staticText4112 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("x:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText4112->Wrap( -1 ); gSizer11->Add( m_staticText4112, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); mTextStaticX = new wxTextCtrl( mStaticProperties, TEXT_STATIC_X, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer11->Add( mTextStaticX, 0, wxALL, 5 ); m_staticText41111 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("y:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText41111->Wrap( -1 ); gSizer11->Add( m_staticText41111, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); mTextStaticY = new wxTextCtrl( mStaticProperties, TEXT_STATIC_Y, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER ); gSizer11->Add( mTextStaticY, 0, wxALL, 5 ); m_staticText351 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("Colour:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText351->Wrap( -1 ); gSizer11->Add( m_staticText351, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); mColorPickerStatic = new wxColourPickerCtrl( mStaticProperties, COLOR_PICKER_STATIC, *wxBLACK, wxDefaultPosition, wxDefaultSize, wxCLRP_DEFAULT_STYLE ); gSizer11->Add( mColorPickerStatic, 0, wxALL|wxEXPAND, 5 ); m_staticText571 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("Transparency:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText571->Wrap( -1 ); gSizer11->Add( m_staticText571, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); mSliderStaticAlpha = new wxSlider( mStaticProperties, SLIDER_STATIC_ALPHA, 255, 0, 255, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL ); gSizer11->Add( mSliderStaticAlpha, 0, wxALL, 5 ); sbSizer71->Add( gSizer11, 0, 0, 5 ); fgSizer191->Add( sbSizer71, 0, wxALL, 5 ); wxStaticBoxSizer* sbSizer9; sbSizer9 = new wxStaticBoxSizer( new wxStaticBox( mStaticProperties, wxID_ANY, wxEmptyString ), wxVERTICAL ); m_staticText3411 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("Text:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText3411->Wrap( -1 ); sbSizer9->Add( m_staticText3411, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 ); mTextStaticText = new wxTextCtrl( mStaticProperties, TEXT_STATIC_TEXT, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE|wxTE_PROCESS_ENTER ); mTextStaticText->SetMinSize( wxSize( -1,70 ) ); sbSizer9->Add( mTextStaticText, 1, wxALL|wxEXPAND, 5 ); fgSizer191->Add( sbSizer9, 1, wxEXPAND, 5 ); wxStaticBoxSizer* sbSizer611; sbSizer611 = new wxStaticBoxSizer( new wxStaticBox( mStaticProperties, wxID_ANY, wxEmptyString ), wxVERTICAL ); m_staticText361 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("Texture:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText361->Wrap( -1 ); sbSizer611->Add( m_staticText361, 0, wxALL, 5 ); mFilePickStaticTexture = new wxFilePickerCtrl( mStaticProperties, FILE_PICK_STATIC_TEXTURE, wxEmptyString, wxT("Select a file"), wxT("*.png"), wxDefaultPosition, wxSize( -1,-1 ), wxFLP_DEFAULT_STYLE ); sbSizer611->Add( mFilePickStaticTexture, 0, wxALL, 5 ); wxFlexGridSizer* fgSizer12211; fgSizer12211 = new wxFlexGridSizer( 2, 2, 0, 0 ); fgSizer12211->SetFlexibleDirection( wxBOTH ); fgSizer12211->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); mButtonStaticClearTexture = new wxButton( mStaticProperties, BUTTON_STATIC_CLEAR_TEXTURE, wxT("Clear"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer12211->Add( mButtonStaticClearTexture, 0, wxALL, 5 ); mButtonStaticCreateUV = new wxButton( mStaticProperties, BUTTON_STATIC_CREATE_UV, wxT("Create UV"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer12211->Add( mButtonStaticCreateUV, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 ); sbSizer611->Add( fgSizer12211, 0, 0, 5 ); m_staticText371 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("Font:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText371->Wrap( -1 ); sbSizer611->Add( m_staticText371, 0, wxALL, 5 ); mFilePickStaticFont = new wxFilePickerCtrl( mStaticProperties, FILE_PICK_STATIC_FONT, wxEmptyString, wxT("Select a file"), wxT("*.xml"), wxDefaultPosition, wxDefaultSize, wxFLP_DEFAULT_STYLE ); sbSizer611->Add( mFilePickStaticFont, 0, wxALL, 5 ); wxGridSizer* gSizer5; gSizer5 = new wxGridSizer( 3, 2, 0, 0 ); m_staticText34 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("Font Colour:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText34->Wrap( -1 ); gSizer5->Add( m_staticText34, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); mColorPickerStaticFont = new wxColourPickerCtrl( mStaticProperties, COLOR_PICKER_STATIC_FONT, *wxBLACK, wxDefaultPosition, wxDefaultSize, wxCLRP_DEFAULT_STYLE ); gSizer5->Add( mColorPickerStaticFont, 0, wxALL|wxEXPAND, 5 ); m_staticText5711 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("Transparency:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText5711->Wrap( -1 ); gSizer5->Add( m_staticText5711, 0, wxALL|wxALIGN_RIGHT, 5 ); mSliderStaticAlphaFont = new wxSlider( mStaticProperties, SLIDER_STATIC_ALPHA_FONT, 255, 0, 255, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL ); gSizer5->Add( mSliderStaticAlphaFont, 0, wxALL, 5 ); m_staticText352 = new wxStaticText( mStaticProperties, wxID_ANY, wxT("Font Size:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText352->Wrap( -1 ); gSizer5->Add( m_staticText352, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); mTextStaticFontSize = new wxTextCtrl( mStaticProperties, TEXT_STATIC_FONT_SIZE, wxEmptyString, wxDefaultPosition, wxSize( 50,-1 ), wxTE_PROCESS_ENTER ); gSizer5->Add( mTextStaticFontSize, 0, wxALL, 5 ); sbSizer611->Add( gSizer5, 1, wxEXPAND, 5 ); wxGridSizer* gSizer8; gSizer8 = new wxGridSizer( 2, 2, 0, 0 ); wxString mChoiceStaticFontHorizontalChoices[] = { wxT("Left"), wxT("Right"), wxT("Centre") }; int mChoiceStaticFontHorizontalNChoices = sizeof( mChoiceStaticFontHorizontalChoices ) / sizeof( wxString ); mChoiceStaticFontHorizontal = new wxChoice( mStaticProperties, CHOICE_STATIC_FONT_HORIZONTAL, wxDefaultPosition, wxDefaultSize, mChoiceStaticFontHorizontalNChoices, mChoiceStaticFontHorizontalChoices, 0 ); mChoiceStaticFontHorizontal->SetSelection( 0 ); gSizer8->Add( mChoiceStaticFontHorizontal, 0, wxALL, 5 ); wxString mChoiceStaticFontVerticalChoices[] = { wxT("Bottom"), wxT("Top"), wxT("Centre") }; int mChoiceStaticFontVerticalNChoices = sizeof( mChoiceStaticFontVerticalChoices ) / sizeof( wxString ); mChoiceStaticFontVertical = new wxChoice( mStaticProperties, CHOICE_STATIC_FONT_VERTICAL, wxDefaultPosition, wxDefaultSize, mChoiceStaticFontVerticalNChoices, mChoiceStaticFontVerticalChoices, 0 ); mChoiceStaticFontVertical->SetSelection( 1 ); gSizer8->Add( mChoiceStaticFontVertical, 0, wxALL, 5 ); sbSizer611->Add( gSizer8, 0, 0, 5 ); fgSizer191->Add( sbSizer611, 0, wxALL, 5 ); mStaticProperties->SetSizer( fgSizer191 ); mStaticProperties->Layout(); fgSizer191->Fit( mStaticProperties ); bSizer7->Add( mStaticProperties, 1, wxEXPAND, 5 ); fgSizer11->Add( bSizer7, 1, wxEXPAND, 5 ); wxBoxSizer* mRightSideBoxSizer; mRightSideBoxSizer = new wxBoxSizer( wxVERTICAL ); wxBoxSizer* bSizer10; bSizer10 = new wxBoxSizer( wxVERTICAL ); wxBoxSizer* mAnimationBoxSizer; mAnimationBoxSizer = new wxBoxSizer( wxVERTICAL ); mAnimationControlsPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxFlexGridSizer* fgSizer15; fgSizer15 = new wxFlexGridSizer( 1, 10, 0, 0 ); fgSizer15->SetFlexibleDirection( wxBOTH ); fgSizer15->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); m_staticText191 = new wxStaticText( mAnimationControlsPanel, wxID_ANY, wxT("Frame:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText191->Wrap( -1 ); fgSizer15->Add( m_staticText191, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); mTextAnimationFrame = new wxTextCtrl( mAnimationControlsPanel, wxID_ANY, wxT("0"), wxDefaultPosition, wxSize( 50,-1 ), wxTE_PROCESS_ENTER|wxTE_RIGHT ); fgSizer15->Add( mTextAnimationFrame, 0, wxALL, 5 ); m_button9 = new wxButton( mAnimationControlsPanel, BUTTON_ID_ANIMATION_BACK_KEYFRAME, wxT("<"), wxDefaultPosition, wxSize( 20,-1 ), 0 ); fgSizer15->Add( m_button9, 0, wxALL, 5 ); m_button101 = new wxButton( mAnimationControlsPanel, BUTTON_ID_ANIMATION_FORWARD_KEYFRAME, wxT(">"), wxDefaultPosition, wxSize( 20,-1 ), 0 ); fgSizer15->Add( m_button101, 0, wxALL, 5 ); m_button5 = new wxButton( mAnimationControlsPanel, BUTTON_ID_ANIMATION_ADD_KEYFRAME, wxT("+"), wxDefaultPosition, wxSize( 30,-1 ), 0 ); fgSizer15->Add( m_button5, 0, wxALL, 5 ); m_button6 = new wxButton( mAnimationControlsPanel, BUTTON_ID_ANIMATION_DELETE_KEYFRAME, wxT("-"), wxDefaultPosition, wxSize( 30,-1 ), 0 ); fgSizer15->Add( m_button6, 0, wxALL, 5 ); m_button7 = new wxButton( mAnimationControlsPanel, BUTTON_ID_ANIMATION_PLAY, wxT("Play"), wxDefaultPosition, wxSize( 50,-1 ), 0 ); fgSizer15->Add( m_button7, 0, wxALL, 5 ); m_button8 = new wxButton( mAnimationControlsPanel, BUTTON_ID_ANIMATION_STOP, wxT("Stop"), wxDefaultPosition, wxSize( 50,-1 ), 0 ); fgSizer15->Add( m_button8, 0, wxALL, 5 ); mZoomIn = new wxButton( mAnimationControlsPanel, BUTTON_ID_ZOOM_IN, wxT("Zoom (+)"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer15->Add( mZoomIn, 0, wxALL, 5 ); mZoomOut = new wxButton( mAnimationControlsPanel, BUTTON_ID_ZOOM_OUT, wxT("Zoom (-)"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer15->Add( mZoomOut, 0, wxALL, 5 ); mAnimationControlsPanel->SetSizer( fgSizer15 ); mAnimationControlsPanel->Layout(); fgSizer15->Fit( mAnimationControlsPanel ); mAnimationBoxSizer->Add( mAnimationControlsPanel, 0, wxEXPAND, 5 ); m_panel6 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxFlexGridSizer* fgSizer12; fgSizer12 = new wxFlexGridSizer( 1, 5, 0, 0 ); fgSizer12->SetFlexibleDirection( wxBOTH ); fgSizer12->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); mAddAnimationSequenceButton = new wxButton( m_panel6, BUTTON_ADD_ANIMATION_SEQUENCE, wxT("+"), wxDefaultPosition, wxSize( 20,-1 ), 0 ); fgSizer12->Add( mAddAnimationSequenceButton, 0, wxALL, 5 ); mDeleteAnimationSequenceButton = new wxButton( m_panel6, BUTTON_DELETE_ANIMATION_SEQUENCE, wxT("-"), wxDefaultPosition, wxSize( 20,-1 ), 0 ); fgSizer12->Add( mDeleteAnimationSequenceButton, 0, wxALL, 5 ); mTextAnimationSequenceName = new wxTextCtrl( m_panel6, TEXT_ANIMATION_SEQUENCE_NAME, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); fgSizer12->Add( mTextAnimationSequenceName, 0, wxALL, 5 ); mAnimationSelectionLabel = new wxStaticText( m_panel6, wxID_ANY, wxT("Animations:"), wxDefaultPosition, wxDefaultSize, 0 ); mAnimationSelectionLabel->Wrap( -1 ); fgSizer12->Add( mAnimationSelectionLabel, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); wxArrayString mAnimationsChoiceChoices; mAnimationsChoice = new wxChoice( m_panel6, CHOICE_ANIMATION_SELECTION, wxDefaultPosition, wxDefaultSize, mAnimationsChoiceChoices, 0 ); mAnimationsChoice->SetSelection( 0 ); fgSizer12->Add( mAnimationsChoice, 1, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5 ); m_panel6->SetSizer( fgSizer12 ); m_panel6->Layout(); fgSizer12->Fit( m_panel6 ); mAnimationBoxSizer->Add( m_panel6, 1, wxEXPAND, 5 ); mTimeLineControl = new TimeLineWidget( this, wxID_ANY, wxDefaultPosition, wxSize( -1,30 ), wxTAB_TRAVERSAL ); mAnimationBoxSizer->Add( mTimeLineControl, 0, wxALL|wxEXPAND, 1 ); bSizer10->Add( mAnimationBoxSizer, 0, wxEXPAND, 5 ); wxBoxSizer* bSizer9; bSizer9 = new wxBoxSizer( wxVERTICAL ); mGraphicsPanel = new OGLCanvas( this, wxID_ANY, wxDefaultPosition, wxSize( -1,-1 ), wxTAB_TRAVERSAL ); mGraphicsPanel->SetMinSize( wxSize( 10,-1 ) ); bSizer9->Add( mGraphicsPanel, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5 ); bSizer10->Add( bSizer9, 0, 0, 5 ); mRightSideBoxSizer->Add( bSizer10, 0, 0, 5 ); fgSizer11->Add( mRightSideBoxSizer, 0, 0, 5 ); bSizer18->Add( fgSizer11, 0, 0, 5 ); this->SetSizer( bSizer18 ); this->Layout(); // Connect Events this->Connect( mNewMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionNew ) ); this->Connect( mOpenMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionOpen ) ); this->Connect( mSaveAsMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionSaveAs ) ); this->Connect( mSaveMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionSave ) ); this->Connect( m_menuItem23->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) ); this->Connect( mMenuItemEditCopy->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) ); this->Connect( mMenuItemEditCut->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) ); this->Connect( mMenuItemEditPaste->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) ); this->Connect( mMenuitemEditCopySize->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) ); this->Connect( mMenuitemEditCopyPosition->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) ); this->Connect( mMenuitemEditPasteSize->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) ); this->Connect( mMenuitemEditPastePosition->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) ); this->Connect( mMenuItemEditDelete->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) ); this->Connect( mMenuItemEditShowHide->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) ); this->Connect( mMenuItemOpenGL->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionRenderer ) ); this->Connect( mMenuItemD3D->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionRenderer ) ); this->Connect( mMenuItemPortrait320x480->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) ); this->Connect( mMenuItemLandscape480x320->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) ); this->Connect( mMenuItemPortrait640x960->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) ); this->Connect( mMenuItemLandscape960x640->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) ); this->Connect( mMenuItemPortrait640x1136->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) ); this->Connect( mMenuItemLandscape1136x640->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) ); this->Connect( mMenuItemPortrait720x1280->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) ); this->Connect( mMenuItemLandscape1280x720->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) ); this->Connect( mMenuItemPortrait768x1024->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) ); this->Connect( mMenuItemLandscape1024x768->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) ); this->Connect( mMenuItemPortrait1536x2048->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) ); this->Connect( mMenuItemLandscape2048x1536->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) ); this->Connect( mMenuInsertStatic->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) ); this->Connect( mMenuInsertButton->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) ); this->Connect( mMenuInsertSlider->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) ); this->Connect( mMenuInsertSprite->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) ); this->Connect( mMenuMoveBack->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) ); this->Connect( mMenuMoveFront->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) ); this->Connect( mMenuAnimationPlay->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionAnimation ) ); this->Connect( mMenuAnimationStop->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionAnimation ) ); this->Connect( mMenuAnimationAddKeyFrame->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionAnimation ) ); this->Connect( mMenuAnimationDeleteKeyFrame->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionAnimation ) ); mRadioBoxTransform->Connect( wxEVT_COMMAND_RADIOBOX_SELECTED, wxCommandEventHandler( GuiEditorGui::OnRadioBoxTransform ), NULL, this ); m_button10->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickLayout ), NULL, this ); m_button111->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickLayout ), NULL, this ); mColorPickerBoundingBox->Connect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColourChangedBoundingBox ), NULL, this ); mColorPickerBoundingBoxSelect->Connect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColourChangedBoundingBox ), NULL, this ); mColorPickerBackground->Connect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColourChangedBackground ), NULL, this ); mSceneGraphTree->Connect( wxEVT_KEY_DOWN, wxKeyEventHandler( GuiEditorGui::OnKeyDownSceneGraph ), NULL, this ); mSceneGraphTree->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( GuiEditorGui::OnLeftDownTree ), NULL, this ); mSceneGraphTree->Connect( wxEVT_RIGHT_DOWN, wxMouseEventHandler( GuiEditorGui::OnRightDownTree ), NULL, this ); mSceneGraphTree->Connect( wxEVT_COMMAND_TREE_ITEM_MENU, wxTreeEventHandler( GuiEditorGui::OnTreeItemMenu ), NULL, this ); mTextButtonName->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextButtonName->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextButtonWidth->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextButtonWidth->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextButtonHeight->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextButtonX->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextButtonX->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextButtonY->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextButtonY->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextButtonText->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextButtonText->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mColorPickerButton->Connect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColorChanged ), NULL, this ); mSliderButtonAlpha->Connect( wxEVT_SCROLL_TOP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderButtonAlpha->Connect( wxEVT_SCROLL_BOTTOM, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderButtonAlpha->Connect( wxEVT_SCROLL_LINEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderButtonAlpha->Connect( wxEVT_SCROLL_LINEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderButtonAlpha->Connect( wxEVT_SCROLL_PAGEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderButtonAlpha->Connect( wxEVT_SCROLL_PAGEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderButtonAlpha->Connect( wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderButtonAlpha->Connect( wxEVT_SCROLL_THUMBRELEASE, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderButtonAlpha->Connect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderButtonAlpha->Connect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScrollChanged ), NULL, this ); mFilePickButtonTexture->Connect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this ); mButtonButtonClearTexture->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mButtonButtonCreateUV->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mFilePickButtonOnPressTexture->Connect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this ); mButtonButtonClearOnPressTexture->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mButtonButtonOnPressCreateUV->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mFilePickButtonFont->Connect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this ); mColorPickerButtonFont->Connect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColorChanged ), NULL, this ); mTextButtonFontSize->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mChoiceButtonFontHorizontal->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( GuiEditorGui::OnChoice ), NULL, this ); mChoiceButtonFontVertical->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( GuiEditorGui::OnChoice ), NULL, this ); mTextSliderName->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSliderName->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextSliderWidth->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSliderWidth->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextSliderHeight->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSliderHeight->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextSliderX->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSliderX->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextSliderY->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSliderY->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextSliderMin->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSliderMin->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextSliderMax->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSliderMax->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextSliderDefault->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSliderDefault->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mFilePickSliderTextureBar->Connect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this ); mButtonSliderClearTextureBar->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mButtonSliderCreateUVBar->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mFilePickSliderTextureButton->Connect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this ); mButtonSliderClearTextureButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mButtonSliderCreateUVButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mTextSpriteName->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSpriteName->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextSpriteWidth->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSpriteWidth->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextSpriteHeight->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSpriteHeight->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextSpriteX->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSpriteX->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextSpriteY->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSpriteY->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mColorPickerSprite->Connect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColorChanged ), NULL, this ); mSliderSpriteAlpha->Connect( wxEVT_SCROLL_TOP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderSpriteAlpha->Connect( wxEVT_SCROLL_BOTTOM, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderSpriteAlpha->Connect( wxEVT_SCROLL_LINEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderSpriteAlpha->Connect( wxEVT_SCROLL_LINEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderSpriteAlpha->Connect( wxEVT_SCROLL_PAGEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderSpriteAlpha->Connect( wxEVT_SCROLL_PAGEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderSpriteAlpha->Connect( wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderSpriteAlpha->Connect( wxEVT_SCROLL_THUMBRELEASE, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderSpriteAlpha->Connect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderSpriteAlpha->Connect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScrollChanged ), NULL, this ); mFilePickSpriteTextureFile->Connect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this ); mButtonSpriteClearTexture->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mTextSpriteFPS->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSpriteFPS->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextStaticName->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextStaticName->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextStaticWidth->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextStaticWidth->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextStaticHeight->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextStaticHeight->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextStaticX->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextStaticX->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextStaticY->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextStaticY->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mColorPickerStatic->Connect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColorChanged ), NULL, this ); mSliderStaticAlpha->Connect( wxEVT_SCROLL_TOP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlpha->Connect( wxEVT_SCROLL_BOTTOM, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlpha->Connect( wxEVT_SCROLL_LINEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlpha->Connect( wxEVT_SCROLL_LINEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlpha->Connect( wxEVT_SCROLL_PAGEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlpha->Connect( wxEVT_SCROLL_PAGEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlpha->Connect( wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlpha->Connect( wxEVT_SCROLL_THUMBRELEASE, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlpha->Connect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlpha->Connect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScrollChanged ), NULL, this ); mTextStaticText->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextStaticText->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mFilePickStaticTexture->Connect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this ); mButtonStaticClearTexture->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mButtonStaticCreateUV->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mFilePickStaticFont->Connect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this ); mColorPickerStaticFont->Connect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColorChanged ), NULL, this ); mSliderStaticAlphaFont->Connect( wxEVT_SCROLL_TOP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlphaFont->Connect( wxEVT_SCROLL_BOTTOM, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlphaFont->Connect( wxEVT_SCROLL_LINEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlphaFont->Connect( wxEVT_SCROLL_LINEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlphaFont->Connect( wxEVT_SCROLL_PAGEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlphaFont->Connect( wxEVT_SCROLL_PAGEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlphaFont->Connect( wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlphaFont->Connect( wxEVT_SCROLL_THUMBRELEASE, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlphaFont->Connect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlphaFont->Connect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScrollChanged ), NULL, this ); mTextStaticFontSize->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mChoiceStaticFontHorizontal->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( GuiEditorGui::OnChoice ), NULL, this ); mChoiceStaticFontVertical->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( GuiEditorGui::OnChoice ), NULL, this ); mTextAnimationFrame->Connect( wxEVT_CHAR, wxKeyEventHandler( GuiEditorGui::OnCharAnimationFrame ), NULL, this ); mTextAnimationFrame->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnterAnimationFrame ), NULL, this ); m_button9->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this ); m_button101->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this ); m_button5->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this ); m_button6->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this ); m_button7->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this ); m_button8->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this ); mZoomIn->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickZoom ), NULL, this ); mZoomOut->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickZoom ), NULL, this ); mAddAnimationSequenceButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mDeleteAnimationSequenceButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mTextAnimationSequenceName->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextAnimationSequenceName->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mAnimationsChoice->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( GuiEditorGui::OnChoice ), NULL, this ); mGraphicsPanel->Connect( wxEVT_KEY_DOWN, wxKeyEventHandler( GuiEditorGui::OnKeyDownGraphicsPanel ), NULL, this ); mGraphicsPanel->Connect( wxEVT_KEY_UP, wxKeyEventHandler( GuiEditorGui::OnKeyUpGraphicsPanel ), NULL, this ); mGraphicsPanel->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( GuiEditorGui::OnLeftDownGraphicsPanel ), NULL, this ); mGraphicsPanel->Connect( wxEVT_LEFT_UP, wxMouseEventHandler( GuiEditorGui::OnLeftUpGraphicsPanel ), NULL, this ); mGraphicsPanel->Connect( wxEVT_MOTION, wxMouseEventHandler( GuiEditorGui::OnMotionGraphicsPanel ), NULL, this ); mGraphicsPanel->Connect( wxEVT_RIGHT_DOWN, wxMouseEventHandler( GuiEditorGui::OnRightDownGraphicsPanel ), NULL, this ); mGraphicsPanel->Connect( wxEVT_RIGHT_UP, wxMouseEventHandler( GuiEditorGui::OnRightUpGraphicsPanel ), NULL, this ); mGraphicsPanel->Connect( wxEVT_SIZE, wxSizeEventHandler( GuiEditorGui::OnSizeGraphicsPanel ), NULL, this ); } GuiEditorGui::~GuiEditorGui() { // Disconnect Events this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionNew ) ); this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionOpen ) ); this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionSaveAs ) ); this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionSave ) ); this->Disconnect( EDIT_UNDO, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) ); this->Disconnect( EDIT_COPY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) ); this->Disconnect( EDIT_CUT, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) ); this->Disconnect( EDIT_PASTE, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) ); this->Disconnect( EDIT_COPY_SIZE_DATA, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) ); this->Disconnect( EDIT_COPY_POSITION_DATA, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) ); this->Disconnect( EDIT_PASTE_SIZE_DATA, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) ); this->Disconnect( EDIT_PASTE_POSITION_DATA, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) ); this->Disconnect( EDIT_DELETE, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) ); this->Disconnect( EDIT_SHOW_HIDE, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEdit ) ); this->Disconnect( MENU_RENDERER_OPENGL, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionRenderer ) ); this->Disconnect( MENU_RENDERER_D3D, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionRenderer ) ); this->Disconnect( SCREEN_SIZE_PORTRAIT_320_480, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) ); this->Disconnect( SCREEN_SIZE_LANDSCAPE_480_320, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) ); this->Disconnect( SCREEN_SIZE_PORTRAIT_640_960, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) ); this->Disconnect( SCREEN_SIZE_LANDSCAPE_960_640, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) ); this->Disconnect( SCREEN_SIZE_PORTRAIT_640_1136, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) ); this->Disconnect( SCREEN_SIZE_LANDSCAPE_1136_640, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) ); this->Disconnect( SCREEN_SIZE_PORTRAIT_720_1280, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) ); this->Disconnect( SCREEN_SIZE_LANDSCAPE_1280_720, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) ); this->Disconnect( SCREEN_SIZE_PORTRAIT_768_1024, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) ); this->Disconnect( SCREEN_SIZE_LANDSCAPE_1024_768, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) ); this->Disconnect( SCREEN_SIZE_PORTRAIT_1536_2048, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionPortrait ) ); this->Disconnect( SCREEN_SIZE_LANDSCAPE_2048_1536, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionLandscape ) ); this->Disconnect( EDITOR_MENU_INSERT_STATIC, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) ); this->Disconnect( EDITOR_MENU_INSERT_BUTTON, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) ); this->Disconnect( EDITOR_MENU_INSERT_SLIDER, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) ); this->Disconnect( EDITOR_MENU_INSERT_SPRITE, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) ); this->Disconnect( EDITOR_MENU_MOVE_BACK, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) ); this->Disconnect( EDITOR_MENU_MOVE_FRONT, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionEditor ) ); this->Disconnect( EDITOR_MENU_ANIMATION_PLAY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionAnimation ) ); this->Disconnect( EDITOR_MENU_ANIMATION_STOP, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionAnimation ) ); this->Disconnect( EDITOR_MENU_ANIMATION_ADD_KEYFRAME, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionAnimation ) ); this->Disconnect( EDITOR_MENU_ANIMATION_DELETE_KEYFRAME, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GuiEditorGui::OnMenuSelectionAnimation ) ); mRadioBoxTransform->Disconnect( wxEVT_COMMAND_RADIOBOX_SELECTED, wxCommandEventHandler( GuiEditorGui::OnRadioBoxTransform ), NULL, this ); m_button10->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickLayout ), NULL, this ); m_button111->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickLayout ), NULL, this ); mColorPickerBoundingBox->Disconnect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColourChangedBoundingBox ), NULL, this ); mColorPickerBoundingBoxSelect->Disconnect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColourChangedBoundingBox ), NULL, this ); mColorPickerBackground->Disconnect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColourChangedBackground ), NULL, this ); mSceneGraphTree->Disconnect( wxEVT_KEY_DOWN, wxKeyEventHandler( GuiEditorGui::OnKeyDownSceneGraph ), NULL, this ); mSceneGraphTree->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( GuiEditorGui::OnLeftDownTree ), NULL, this ); mSceneGraphTree->Disconnect( wxEVT_RIGHT_DOWN, wxMouseEventHandler( GuiEditorGui::OnRightDownTree ), NULL, this ); mSceneGraphTree->Disconnect( wxEVT_COMMAND_TREE_ITEM_MENU, wxTreeEventHandler( GuiEditorGui::OnTreeItemMenu ), NULL, this ); mTextButtonName->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextButtonName->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextButtonWidth->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextButtonWidth->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextButtonHeight->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextButtonX->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextButtonX->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextButtonY->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextButtonY->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextButtonText->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextButtonText->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mColorPickerButton->Disconnect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColorChanged ), NULL, this ); mSliderButtonAlpha->Disconnect( wxEVT_SCROLL_TOP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderButtonAlpha->Disconnect( wxEVT_SCROLL_BOTTOM, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderButtonAlpha->Disconnect( wxEVT_SCROLL_LINEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderButtonAlpha->Disconnect( wxEVT_SCROLL_LINEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderButtonAlpha->Disconnect( wxEVT_SCROLL_PAGEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderButtonAlpha->Disconnect( wxEVT_SCROLL_PAGEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderButtonAlpha->Disconnect( wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderButtonAlpha->Disconnect( wxEVT_SCROLL_THUMBRELEASE, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderButtonAlpha->Disconnect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderButtonAlpha->Disconnect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScrollChanged ), NULL, this ); mFilePickButtonTexture->Disconnect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this ); mButtonButtonClearTexture->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mButtonButtonCreateUV->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mFilePickButtonOnPressTexture->Disconnect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this ); mButtonButtonClearOnPressTexture->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mButtonButtonOnPressCreateUV->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mFilePickButtonFont->Disconnect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this ); mColorPickerButtonFont->Disconnect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColorChanged ), NULL, this ); mTextButtonFontSize->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mChoiceButtonFontHorizontal->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( GuiEditorGui::OnChoice ), NULL, this ); mChoiceButtonFontVertical->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( GuiEditorGui::OnChoice ), NULL, this ); mTextSliderName->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSliderName->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextSliderWidth->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSliderWidth->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextSliderHeight->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSliderHeight->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextSliderX->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSliderX->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextSliderY->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSliderY->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextSliderMin->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSliderMin->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextSliderMax->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSliderMax->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextSliderDefault->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSliderDefault->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mFilePickSliderTextureBar->Disconnect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this ); mButtonSliderClearTextureBar->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mButtonSliderCreateUVBar->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mFilePickSliderTextureButton->Disconnect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this ); mButtonSliderClearTextureButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mButtonSliderCreateUVButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mTextSpriteName->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSpriteName->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextSpriteWidth->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSpriteWidth->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextSpriteHeight->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSpriteHeight->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextSpriteX->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSpriteX->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextSpriteY->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSpriteY->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mColorPickerSprite->Disconnect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColorChanged ), NULL, this ); mSliderSpriteAlpha->Disconnect( wxEVT_SCROLL_TOP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderSpriteAlpha->Disconnect( wxEVT_SCROLL_BOTTOM, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderSpriteAlpha->Disconnect( wxEVT_SCROLL_LINEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderSpriteAlpha->Disconnect( wxEVT_SCROLL_LINEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderSpriteAlpha->Disconnect( wxEVT_SCROLL_PAGEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderSpriteAlpha->Disconnect( wxEVT_SCROLL_PAGEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderSpriteAlpha->Disconnect( wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderSpriteAlpha->Disconnect( wxEVT_SCROLL_THUMBRELEASE, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderSpriteAlpha->Disconnect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderSpriteAlpha->Disconnect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScrollChanged ), NULL, this ); mFilePickSpriteTextureFile->Disconnect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this ); mButtonSpriteClearTexture->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mTextSpriteFPS->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextSpriteFPS->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextStaticName->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextStaticName->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextStaticWidth->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextStaticWidth->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextStaticHeight->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextStaticHeight->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextStaticX->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextStaticX->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mTextStaticY->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextStaticY->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mColorPickerStatic->Disconnect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColorChanged ), NULL, this ); mSliderStaticAlpha->Disconnect( wxEVT_SCROLL_TOP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlpha->Disconnect( wxEVT_SCROLL_BOTTOM, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlpha->Disconnect( wxEVT_SCROLL_LINEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlpha->Disconnect( wxEVT_SCROLL_LINEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlpha->Disconnect( wxEVT_SCROLL_PAGEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlpha->Disconnect( wxEVT_SCROLL_PAGEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlpha->Disconnect( wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlpha->Disconnect( wxEVT_SCROLL_THUMBRELEASE, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlpha->Disconnect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlpha->Disconnect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScrollChanged ), NULL, this ); mTextStaticText->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextStaticText->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mFilePickStaticTexture->Disconnect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this ); mButtonStaticClearTexture->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mButtonStaticCreateUV->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mFilePickStaticFont->Disconnect( wxEVT_COMMAND_FILEPICKER_CHANGED, wxFileDirPickerEventHandler( GuiEditorGui::OnFileChanged ), NULL, this ); mColorPickerStaticFont->Disconnect( wxEVT_COMMAND_COLOURPICKER_CHANGED, wxColourPickerEventHandler( GuiEditorGui::OnColorChanged ), NULL, this ); mSliderStaticAlphaFont->Disconnect( wxEVT_SCROLL_TOP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlphaFont->Disconnect( wxEVT_SCROLL_BOTTOM, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlphaFont->Disconnect( wxEVT_SCROLL_LINEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlphaFont->Disconnect( wxEVT_SCROLL_LINEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlphaFont->Disconnect( wxEVT_SCROLL_PAGEUP, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlphaFont->Disconnect( wxEVT_SCROLL_PAGEDOWN, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlphaFont->Disconnect( wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlphaFont->Disconnect( wxEVT_SCROLL_THUMBRELEASE, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlphaFont->Disconnect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScroll ), NULL, this ); mSliderStaticAlphaFont->Disconnect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( GuiEditorGui::OnScrollChanged ), NULL, this ); mTextStaticFontSize->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mChoiceStaticFontHorizontal->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( GuiEditorGui::OnChoice ), NULL, this ); mChoiceStaticFontVertical->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( GuiEditorGui::OnChoice ), NULL, this ); mTextAnimationFrame->Disconnect( wxEVT_CHAR, wxKeyEventHandler( GuiEditorGui::OnCharAnimationFrame ), NULL, this ); mTextAnimationFrame->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnterAnimationFrame ), NULL, this ); m_button9->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this ); m_button101->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this ); m_button5->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this ); m_button6->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this ); m_button7->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this ); m_button8->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickAnimation ), NULL, this ); mZoomIn->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickZoom ), NULL, this ); mZoomOut->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClickZoom ), NULL, this ); mAddAnimationSequenceButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mDeleteAnimationSequenceButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GuiEditorGui::OnButtonClick ), NULL, this ); mTextAnimationSequenceName->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( GuiEditorGui::OnKillFocus ), NULL, this ); mTextAnimationSequenceName->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( GuiEditorGui::OnTextEnter ), NULL, this ); mAnimationsChoice->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( GuiEditorGui::OnChoice ), NULL, this ); mGraphicsPanel->Disconnect( wxEVT_KEY_DOWN, wxKeyEventHandler( GuiEditorGui::OnKeyDownGraphicsPanel ), NULL, this ); mGraphicsPanel->Disconnect( wxEVT_KEY_UP, wxKeyEventHandler( GuiEditorGui::OnKeyUpGraphicsPanel ), NULL, this ); mGraphicsPanel->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( GuiEditorGui::OnLeftDownGraphicsPanel ), NULL, this ); mGraphicsPanel->Disconnect( wxEVT_LEFT_UP, wxMouseEventHandler( GuiEditorGui::OnLeftUpGraphicsPanel ), NULL, this ); mGraphicsPanel->Disconnect( wxEVT_MOTION, wxMouseEventHandler( GuiEditorGui::OnMotionGraphicsPanel ), NULL, this ); mGraphicsPanel->Disconnect( wxEVT_RIGHT_DOWN, wxMouseEventHandler( GuiEditorGui::OnRightDownGraphicsPanel ), NULL, this ); mGraphicsPanel->Disconnect( wxEVT_RIGHT_UP, wxMouseEventHandler( GuiEditorGui::OnRightUpGraphicsPanel ), NULL, this ); mGraphicsPanel->Disconnect( wxEVT_SIZE, wxSizeEventHandler( GuiEditorGui::OnSizeGraphicsPanel ), NULL, this ); }
72.721098
215
0.801701
841a7e2524ae14ecae06428526799000767f2719
1,069
cpp
C++
emulator/src/emu/dinetwork.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
1
2022-01-15T21:38:38.000Z
2022-01-15T21:38:38.000Z
emulator/src/emu/dinetwork.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
emulator/src/emu/dinetwork.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
// license:BSD-3-Clause // copyright-holders:Carl, Miodrag Milanovic #include "emu.h" #include "osdnet.h" device_network_interface::device_network_interface(const machine_config &mconfig, device_t &device, float bandwidth) : device_interface(device, "network") { m_promisc = false; m_bandwidth = bandwidth; set_mac("\0\0\0\0\0\0"); m_intf = 0; } device_network_interface::~device_network_interface() { } int device_network_interface::send(u8 *buf, int len) const { if(!m_dev) return 0; return m_dev->send(buf, len); } void device_network_interface::recv_cb(u8 *buf, int len) { } void device_network_interface::set_promisc(bool promisc) { m_promisc = promisc; if(m_dev) m_dev->set_promisc(promisc); } void device_network_interface::set_mac(const char *mac) { memcpy(m_mac, mac, 6); if(m_dev) m_dev->set_mac(m_mac); } void device_network_interface::set_interface(int id) { m_dev.reset(open_netdev(id, this, (int)(m_bandwidth*1000000/8.0f/1500))); if(!m_dev) { device().logerror("Network interface %d not found\n", id); id = -1; } m_intf = id; }
21.38
116
0.731525
8421f307b6c36c4060ee159cf7ed771972cd5bbb
90
cpp
C++
src/Item.cpp
Erick9Thor/Zork
43ee99711bb991e0f8c3cf61f18c1d2e373ac2a7
[ "MIT" ]
null
null
null
src/Item.cpp
Erick9Thor/Zork
43ee99711bb991e0f8c3cf61f18c1d2e373ac2a7
[ "MIT" ]
null
null
null
src/Item.cpp
Erick9Thor/Zork
43ee99711bb991e0f8c3cf61f18c1d2e373ac2a7
[ "MIT" ]
null
null
null
#include "../include/Item.h" ItemType Item::GetItemType() const { return itemType; }
12.857143
34
0.677778
84265e8c1625a8e0a499b82c9b1ea02d707ffee2
1,259
cpp
C++
vegastrike/src/cmd/bolt_server.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/src/cmd/bolt_server.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/src/cmd/bolt_server.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
#include "bolt.h" #include "gfxlib.h" #include "gfx/mesh.h" #include "gfxlib_struct.h" #include <vector> #include <string> #include <algorithm> #include "unit_generic.h" #include "configxml.h" GFXVertexList*bolt_draw::boltmesh = NULL; bolt_draw::~bolt_draw() { unsigned int i; for (i = 0; i < balls.size(); i++) for (int j = balls[i].size()-1; j >= 0; j--) balls[i][j].Destroy( j ); for (i = 0; i < bolts.size(); i++) for (int j = balls[i].size()-1; j >= 0; j--) bolts[i][j].Destroy( j ); } bolt_draw::bolt_draw() { boltmesh = NULL; boltdecals = NULL; } int Bolt::AddTexture( bolt_draw *q, std::string file ) { int decal = 0; if ( decal >= (int) q->bolts.size() ) q->bolts.push_back( vector< Bolt > () ); return decal; } int Bolt::AddAnimation( bolt_draw *q, std::string file, QVector cur_position ) { int decal = 0; if ( decal >= (int) q->balls.size() ) q->balls.push_back( vector< Bolt > () ); return decal; } void Bolt::Draw() {} extern void BoltDestroyGeneric( Bolt *whichbolt, unsigned int index, int decal, bool isBall ); void Bolt::Destroy( unsigned int index ) { BoltDestroyGeneric( this, index, decal, type->type != weapon_info::BOLT ); }
24.686275
94
0.601271
842b1dd42b8e6cfb395af85944e7da162dc0a8bc
4,385
cpp
C++
cnf_dump/cnf_dump_clo.cpp
appu226/FactorGraph
26e4de8518874abf2696a167eaf3dbaede5930f8
[ "MIT" ]
null
null
null
cnf_dump/cnf_dump_clo.cpp
appu226/FactorGraph
26e4de8518874abf2696a167eaf3dbaede5930f8
[ "MIT" ]
null
null
null
cnf_dump/cnf_dump_clo.cpp
appu226/FactorGraph
26e4de8518874abf2696a167eaf3dbaede5930f8
[ "MIT" ]
null
null
null
/* Copyright 2019 Parakram Majumdar 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 corresponding header file #include "cnf_dump_clo.h" // std includes #include <stdexcept> namespace cnf_dump { //---------------------------------------------------------------- // definitions of members of class CnfDumpClo //---------------------------------------------------------------- // function CnfDumpClo::create std::shared_ptr<CnfDumpClo> CnfDumpClo::create(int argc, char const * const * const argv) { return std::make_shared<CnfDumpClo>(argc, argv); } // function CnfDumpClo::printHelpMessage // prints help info void CnfDumpClo::printHelpMessage() { std::cout << "cnf_dump:\n" << " Utility for converting a blif file into a cnf_dump\n" << "\n" << "Usage:\n" << " cnf_dump <options>\n" << "\n" << "Options:\n" << " --blif_file <input blif file> (MANDATORY)\n" << " --cnf_file <output blif file> (MANDATORY)\n" << " --num_lo_vars_to_quantify <number of latch output vars to quantify out>, defaults to 0\n" << " --verbosity <verbosity> : one of QUIET/ERROR/WARNING/INFO/DEBUG, defaults to ERROR\n" << " --help: prints this help message and exits\n" << std::endl; return; } // constructor CnfDumpClo::CnfDumpClo // stub implementation CnfDumpClo::CnfDumpClo(int argc, char const * const * const argv) : blif_file(), output_cnf_file(), verbosity(blif_solve::ERROR), num_lo_vars_to_quantify(0), help(false) { char const * const * current_argv = argv + 1; for (int argnum = 1; argnum < argc; ++argnum, ++current_argv) { std::string current_arg(*current_argv); if (current_arg == "--blif_file") { ++argnum; ++current_argv; if (argnum >= argc) throw std::invalid_argument("Missing <input blif file> after argument --blif_file"); blif_file = *current_argv; } else if (current_arg == "--cnf_file") { ++argnum; ++current_argv; if (argnum >= argc) throw std::invalid_argument("Missing <input cnf file> after argument --cnf_file"); output_cnf_file = *current_argv; } else if (current_arg == "--verbosity") { ++argnum; ++current_argv; if (argnum >= argc) throw std::invalid_argument("Missing <verbosity> after argument --verbosity"); verbosity = blif_solve::parseVerbosity(*current_argv); } else if (current_arg == "--help") help = true; else if (current_arg == "--num_lo_vars_to_quantify") { ++argnum; ++current_argv; if (argnum >= argc) throw std::invalid_argument("Missing <number> after argument --num_lo_vars_to_quantify"); num_lo_vars_to_quantify = atoi(*current_argv); } else throw std::invalid_argument(std::string("Unexpected argument '") + *current_argv + "'"); } if (help) return; if (blif_file == "") throw std::invalid_argument("Missing mandatory argument --blif_file"); if (output_cnf_file == "") throw std::invalid_argument("Missing mandatory argument --cnf_file"); return; } } // end namespace cnf_dump
32.242647
109
0.620753
842cc9c6722bc81483b9a34464a134e42c681b75
14,748
cpp
C++
src/RotationPricer.cpp
sergebisaillon/MerinioScheduler
8549ce7f3c1c14817a2eba9d565ca0b56f451e2a
[ "MIT" ]
1
2020-05-05T15:51:41.000Z
2020-05-05T15:51:41.000Z
src/RotationPricer.cpp
qiqi789/NurseScheduler
8549ce7f3c1c14817a2eba9d565ca0b56f451e2a
[ "MIT" ]
null
null
null
src/RotationPricer.cpp
qiqi789/NurseScheduler
8549ce7f3c1c14817a2eba9d565ca0b56f451e2a
[ "MIT" ]
1
2019-11-11T17:59:23.000Z
2019-11-11T17:59:23.000Z
/* * RotationPricer.cpp * * Created on: 2015-03-02 * Author: legraina */ #include "RotationPricer.h" #include "BcpModeler.h" /* namespace usage */ using namespace std; ////////////////////////////////////////////////////////////// // // R O T A T I O N P R I C E R // ////////////////////////////////////////////////////////////// static char const * baseName = "rotation"; /* Constructs the pricer object. */ RotationPricer::RotationPricer(MasterProblem* master, const char* name, SolverParam param): MyPricer(name), nbMaxRotationsToAdd_(20), nbSubProblemsToSolve_(15), nursesToSolve_(master->theNursesSorted_), pMaster_(master), pScenario_(master->pScenario_), nbDays_(master->pDemand_->nbDays_), pModel_(master->getModel()), nb_int_solutions_(0) { // Initialize the parameters initPricerParameters(param); /* sort the nurses */ // random_shuffle( nursesToSolve_.begin(), nursesToSolve_.end()); } /* Destructs the pricer object. */ RotationPricer::~RotationPricer() { for(pair<const Contract*, SubProblem*> p: subProblems_) delete p.second; } void RotationPricer::initPricerParameters(SolverParam param){ // Here: doing a little check to be sure that secondchance is activated only when the parameters are different... withSecondchance_ = param.sp_withsecondchance_ && (param.sp_default_strategy_ != param.sp_secondchance_strategy_); nbMaxRotationsToAdd_ = param.sp_nbrotationspernurse_; nbSubProblemsToSolve_ = param.sp_nbnursestoprice_; defaultSubprobemStrategy_ = param.sp_default_strategy_; secondchanceSubproblemStrategy_ = param.sp_secondchance_strategy_; currentSubproblemStrategy_ = defaultSubprobemStrategy_; } /****************************************************** * Perform pricing ******************************************************/ vector<MyVar*> RotationPricer::pricing(double bound, bool before_fathom){ // Reset all rotations, columns, counters, etc. resetSolutions(); // count and store the nurses whose subproblems produced rotations. // DBG: why minDualCost? Isn't it more a reduced cost? double minDualCost = 0; vector<LiveNurse*> nursesSolved; for(vector<LiveNurse*>::iterator it0 = nursesToSolve_.begin(); it0 != nursesToSolve_.end();){ // RETRIEVE THE NURSE AND CHECK THAT HE/SHE IS NOT FORBIDDEN LiveNurse* pNurse = *it0; bool nurseForbidden = isNurseForbidden(pNurse->id_); // IF THE NURSE IS NOT FORBIDDEN, SOLVE THE SUBPROBLEM if(!nurseForbidden){ // BUILD OR RE-USE THE SUBPROBLEM SubProblem* subProblem = retriveSubproblem(pNurse); // RETRIEVE DUAL VALUES vector< vector<double> > workDualCosts(getWorkDualValues(pNurse)); vector<double> startWorkDualCosts(getStartWorkDualValues(pNurse)); vector<double> endWorkDualCosts(getEndWorkDualValues(pNurse)); double workedWeekendDualCost = getWorkedWeekendDualValue(pNurse); DualCosts dualCosts (workDualCosts, startWorkDualCosts, endWorkDualCosts, workedWeekendDualCost, true); // UPDATE FORBIDDEN SHIFTS if (pModel_->getParameters().isColumnDisjoint_) { addForbiddenShifts(); } set<pair<int,int> > nurseForbiddenShifts(forbiddenShifts_); pModel_->addForbiddenShifts(pNurse, nurseForbiddenShifts); // SET SOLVING OPTIONS SubproblemParam sp_param (currentSubproblemStrategy_,pNurse); // DBG *** // generateRandomForbiddenStartingDays(); // SOLVE THE PROBLEM ++ nbSPTried_; subProblem->solve(pNurse, &dualCosts, sp_param, nurseForbiddenShifts, forbiddenStartingDays_, true , bound); // RETRIEVE THE GENERATED ROTATIONS newRotationsForNurse_ = subProblem->getRotations(); // DBG *** // checkForbiddenStartingDays(); // recordSPStats(subProblem); // for(Rotation& rot: newRotationsForNurse_){ // rot.checkDualCost(dualCosts); // } // ADD THE ROTATIONS TO THE MASTER PROBLEM addRotationsToMaster(); } // CHECK IF THE SUBPROBLEM GENERATED NEW ROTATIONS // If yes, store the nures if(newRotationsForNurse_.size() > 0 && !nurseForbidden){ ++nbSPSolvedWithSuccess_; if(newRotationsForNurse_[0].dualCost_ < minDualCost) minDualCost = newRotationsForNurse_[0].dualCost_; nursesToSolve_.erase(it0); nursesSolved.push_back(pNurse); } // Otherwise (no rotation generated or nurse is forbidden), try the next nurse else { ++it0; // If it was the last nurse to search AND no improving column was found AND we may want to solve SP with // different parameters -> change these parameters and go for another loop of solving if( it0 == nursesToSolve_.end() && allNewColumns_.empty() && withSecondchance_){ if(currentSubproblemStrategy_ == defaultSubprobemStrategy_){ nursesToSolve_.insert(nursesToSolve_.end(), nursesSolved.begin(), nursesSolved.end()); it0 = nursesToSolve_.begin(); currentSubproblemStrategy_ = secondchanceSubproblemStrategy_; } else if (currentSubproblemStrategy_ == secondchanceSubproblemStrategy_) { currentSubproblemStrategy_ = defaultSubprobemStrategy_; } } } //if the maximum number of subproblem solved is reached, break. if(nbSPSolvedWithSuccess_ == nbSubProblemsToSolve_) break; } //Add the nurse in nursesSolved at the end nursesToSolve_.insert(nursesToSolve_.end(), nursesSolved.begin(), nursesSolved.end()); //set statistics BcpModeler* model = dynamic_cast<BcpModeler*>(pModel_); if(model){ model->setLastNbSubProblemsSolved(nbSPTried_); model->setLastMinDualCost(minDualCost); } if(allNewColumns_.empty()) print_current_solution_(); // std::cout << "# ------- END ------- Subproblems!" << std::endl; // return optimal; return allNewColumns_; } /****************************************************** * Get the duals values per day for a nurse ******************************************************/ vector< vector<double> > RotationPricer::getWorkDualValues(LiveNurse* pNurse){ vector< vector<double> > dualValues(nbDays_); int i = pNurse->id_; int p = pNurse->pContract_->id_; /* Min/Max constraints */ double minWorkedDays = pModel_->getDual(pMaster_->minWorkedDaysCons_[i], true); double maxWorkedDays = pModel_->getDual(pMaster_->maxWorkedDaysCons_[i], true); double minWorkedDaysAvg = pMaster_->isMinWorkedDaysAvgCons_[i] ? pModel_->getDual(pMaster_->minWorkedDaysAvgCons_[i], true):0.0; double maxWorkedDaysAvg = pMaster_->isMaxWorkedDaysAvgCons_[i] ? pModel_->getDual(pMaster_->maxWorkedDaysAvgCons_[i], true):0.0; double minWorkedDaysContractAvg = pMaster_->isMinWorkedDaysContractAvgCons_[p] ? pModel_->getDual(pMaster_->minWorkedDaysContractAvgCons_[p], true):0.0; double maxWorkedDaysContractAvg = pMaster_->isMaxWorkedDaysContractAvgCons_[p] ? pModel_->getDual(pMaster_->maxWorkedDaysContractAvgCons_[p], true):0.0; for(int k=0; k<nbDays_; ++k){ //initialize vector vector<double> dualValues2(pScenario_->nbShifts_-1); for(int s=1; s<pScenario_->nbShifts_; ++s){ /* Min/Max constraints */ dualValues2[s-1] = minWorkedDays + minWorkedDaysAvg + minWorkedDaysContractAvg; dualValues2[s-1] += maxWorkedDays + maxWorkedDaysAvg + maxWorkedDaysContractAvg; /* Skills coverage */ dualValues2[s-1] += pModel_->getDual( pMaster_->numberOfNursesByPositionCons_[k][s-1][pNurse->pPosition_->id_], true); } //store vector dualValues[k] = dualValues2; } return dualValues; } vector<double> RotationPricer::getStartWorkDualValues(LiveNurse* pNurse){ int i = pNurse->id_; vector<double> dualValues(nbDays_); //get dual value associated to the source dualValues[0] = pModel_->getDual(pMaster_->restFlowCons_[i][0], true); //get dual values associated to the work flow constraints //don't take into account the last which is the sink for(int k=1; k<nbDays_; ++k) dualValues[k] = pModel_->getDual(pMaster_->workFlowCons_[i][k-1], true); return dualValues; } vector<double> RotationPricer::getEndWorkDualValues(LiveNurse* pNurse){ int i = pNurse->id_; vector<double> dualValues(nbDays_); //get dual values associated to the work flow constraints //don't take into account the first which is the source //take into account the cost, if the last day worked is k for(int k=0; k<nbDays_-1; ++k) dualValues[k] = -pModel_->getDual(pMaster_->restFlowCons_[i][k+1], true); //get dual value associated to the sink dualValues[nbDays_-1] = pModel_->getDual( pMaster_->workFlowCons_[i][nbDays_-1], true); return dualValues; } double RotationPricer::getWorkedWeekendDualValue(LiveNurse* pNurse){ int id = pNurse->id_; double dualVal = pModel_->getDual(pMaster_->maxWorkedWeekendCons_[id], true); if (pMaster_->isMaxWorkedWeekendAvgCons_[id]) { dualVal += pModel_->getDual(pMaster_->maxWorkedWeekendAvgCons_[id], true); } if (pMaster_->isMaxWorkedWeekendContractAvgCons_[pNurse->pContract_->id_]) { dualVal += pModel_->getDual(pMaster_->maxWorkedWeekendContractAvgCons_[pNurse->pContract_->id_], true); } return dualVal; } /****************************************************** * add some forbidden shifts ******************************************************/ void RotationPricer::addForbiddenShifts(){ //search best rotation vector<Rotation>::iterator bestRotation; double bestDualcost = DBL_MAX; for(vector<Rotation>::iterator it = newRotationsForNurse_.begin(); it != newRotationsForNurse_.end(); ++it) if(it->dualCost_ < bestDualcost){ bestDualcost = it->dualCost_; bestRotation = it; } //forbid shifts of the best rotation if(bestDualcost != DBL_MAX) for(pair<int,int> pair: bestRotation->shifts_) forbiddenShifts_.insert(pair); } // Returns a pointer to the right subproblem SubProblem* RotationPricer::retriveSubproblem(LiveNurse* pNurse){ SubProblem* subProblem; map<const Contract*, SubProblem*>::iterator it = subProblems_.find(pNurse->pContract_); // Each contract has one subproblem. If it has not already been created, create it. if( it == subProblems_.end() ){ subProblem = new SubProblem(pScenario_, nbDays_, pNurse->pContract_, pMaster_->pInitState_); subProblems_.insert(it, pair<const Contract*, SubProblem*>(pNurse->pContract_, subProblem)); } else { subProblem = it->second; } return subProblem; } // Add the rotations to the master problem void RotationPricer::addRotationsToMaster(){ // COMPUTE THE COST OF THE ROTATIONS for(Rotation& rot: newRotationsForNurse_){ rot.computeCost(pScenario_, pMaster_->pPreferences_, pMaster_->theLiveNurses_,nbDays_); rot.treeLevel_ = pModel_->getCurrentTreeLevel(); } // SORT THE ROTATIONS sortNewlyGeneratedRotations(); // SECOND, ADD THE ROTATIONS TO THE MASTER PROBLEM (in the previously computed order) int nbRotationsAdded = 0; for(Rotation& rot: newRotationsForNurse_){ allNewColumns_.push_back(pMaster_->addRotation(rot, baseName)); ++nbRotationsAdded; // DBG //cout << rot.toString(nbDays_) << endl; if(nbRotationsAdded >= nbMaxRotationsToAdd_) break; } } // Sort the rotations that just were generated for a nurse. Default option is sort by increasing reduced cost but we // could try something else (involving disjoint columns for ex.) void RotationPricer::sortNewlyGeneratedRotations(){ std::stable_sort(newRotationsForNurse_.begin(), newRotationsForNurse_.end(), Rotation::compareDualCost); } // Set the subproblem options depending on the parameters // //void RotationPricer::setSubproblemOptions(vector<SolveOption>& options, int& maxRotationLengthForSubproblem, // LiveNurse* pNurse){ // // // Default option that should be used // options.push_back(SOLVE_ONE_SINK_PER_LAST_DAY); // // // Options are added depending on the chosen parameters // // // if (currentPricerParam_.isExhaustiveSearch()) { // options.push_back(SOLVE_SHORT_ALL); // maxRotationLengthForSubproblem = LARGE_TIME; // } // else if (currentPricerParam_.nonPenalizedRotationsOnly()) { // options.push_back(SOLVE_SHORT_DAY_0_ONLY); // maxRotationLengthForSubproblem = pNurse->maxConsDaysWork(); // } // else { // if(currentPricerParam_.withShortRotations()) options.push_back(SOLVE_SHORT_ALL); // maxRotationLengthForSubproblem = currentPricerParam_.maxRotationLength(); // } // //} // ------------------------------------------ // // PRINT functions // // ------------------------------------------ void RotationPricer::print_current_solution_(){ //pMaster_->costsConstrainstsToString(); //pMaster_->allocationToString(); if(nb_int_solutions_ < pMaster_->getModel()->nbSolutions()){ nb_int_solutions_ = pMaster_->getModel()->nbSolutions(); //pMaster_->getModel()->printBestSol(); //pMaster_->costsConstrainstsToString(); } } void RotationPricer::printStatSPSolutions(){ double tMeanSubproblems = timeInExSubproblems_ / ((double)nbExSubproblems_); double tMeanS = timeForS_ / ((double)nbS_); double tMeanNL = timeForNL_ / ((double)nbNL_); double tMeanN = timeForN_ / ((double)nbN_); string sepLine = "+-----------------+------------------------+-----------+\n"; printf("\n"); printf("%s", sepLine.c_str()); printf("| %-15s |%10s %12s |%10s |\n", "type", "time", "number", "mean time"); printf("%s", sepLine.c_str()); printf("| %-15s |%10.2f %12d |%10.4f |\n", "Ex. Subproblems", timeInExSubproblems_, nbExSubproblems_, tMeanSubproblems); printf("| %-15s |%10.2f %12d |%10.4f |\n", "Short rotations", timeForS_, nbS_, tMeanS); printf("| %-15s |%10.2f %12d |%10.4f |\n", "NL rotations", timeForNL_, nbNL_, tMeanNL); printf("%s", sepLine.c_str()); printf("| %-15s |%10.2f %12d |%10.4f |\n", "N rotations", timeForN_, nbN_, tMeanN); printf("%s", sepLine.c_str()); printf("\n"); } // ------------------------------------------ // // DBG functions - may be useful // // ------------------------------------------ //void RotationPricer::recordSPStats(SubProblem* sp){ // if (currentPricerParam_.isExhaustiveSearch()) { // nbExSubproblems_++; nbSubproblems_++; nbS_++; nbNL_++; // timeForS_ += sp->timeInS_->dSinceStart(); // timeForNL_ += sp->timeInNL_->dSinceStart(); // timeInExSubproblems_ += sp->timeInS_->dSinceStart() + sp->timeInNL_->dSinceStart(); // } // else if (currentPricerParam_.nonPenalizedRotationsOnly()) { // nbSubproblems_++; nbN_++; // timeForN_ += sp->timeInNL_->dSinceStart(); // } // else { // } //} void RotationPricer::generateRandomForbiddenStartingDays(){ set<int> randomForbiddenStartingDays; for(int m=0; m<5; m++){ int k = Tools::randomInt(0, nbDays_-1); randomForbiddenStartingDays.insert(k); } forbiddenStartingDays_ = randomForbiddenStartingDays; } void RotationPricer::checkForbiddenStartingDays(){ for(Rotation& rot: newRotationsForNurse_){ int startingDay = rot.firstDay_; if(forbiddenStartingDays_.find(startingDay) != forbiddenStartingDays_.end()){ cout << "# On a généré une rotation qui commence un jour interdit !" << endl; getchar(); } } }
34.619718
137
0.702129
8438b89e25ce446d49d0eda0cc0bc78749c00c74
4,741
cc
C++
Samples/PostProcessing/PostProcessing.cc
rodrigobmg/YumeEngine
67c525c84616a5167b5bae45f36641e90227c281
[ "MIT" ]
129
2016-05-05T23:34:44.000Z
2022-03-07T20:17:18.000Z
Samples/PostProcessing/PostProcessing.cc
rodrigobmg/YumeEngine
67c525c84616a5167b5bae45f36641e90227c281
[ "MIT" ]
1
2017-05-07T16:09:41.000Z
2017-05-08T15:35:50.000Z
Samples/PostProcessing/PostProcessing.cc
rodrigobmg/YumeEngine
67c525c84616a5167b5bae45f36641e90227c281
[ "MIT" ]
20
2016-02-24T20:40:08.000Z
2022-02-04T23:48:18.000Z
//-------------------------------------------------------------------------------- //This is a file from Arkengine // // //Copyright (c) arkenthera.All rights reserved. // //BasicRenderWindow.cpp //-------------------------------------------------------------------------------- #include "Core/YumeHeaders.h" #include "PostProcessing.h" #include "Logging/logging.h" #include "Core/YumeMain.h" #include "Renderer/YumeLPVCamera.h" #include <boost/shared_ptr.hpp> #include "Input/YumeInput.h" #include "Renderer/YumeTexture2D.h" #include "Renderer/YumeResourceManager.h" #include "Engine/YumeEngine.h" #include "UI/YumeDebugOverlay.h" #include "Renderer/Light.h" #include "Renderer/StaticModel.h" #include "Renderer/Scene.h" #include "Renderer/RenderPass.h" #include "UI/YumeOptionsMenu.h" YUME_DEFINE_ENTRY_POINT(YumeEngine::GodRays); #define TURNOFF 1 //#define NO_MODEL //#define OBJECTS_CAST_SHADOW #define NO_SKYBOX #define NO_PLANE namespace YumeEngine { GodRays::GodRays() : angle1_(0), updown1_(0), leftRight1_(0) { REGISTER_ENGINE_LISTENER; } GodRays::~GodRays() { } void GodRays::Start() { YumeResourceManager* rm_ = gYume->pResourceManager; YumeMiscRenderer* renderer = gYume->pRenderer; Scene* scene = renderer->GetScene(); YumeCamera* camera = renderer->GetCamera(); gYume->pInput->AddListener(this); #ifndef DISABLE_CEF optionsMenu_ = new YumeOptionsMenu; gYume->pUI->AddUIElement(optionsMenu_); optionsMenu_->SetVisible(true); overlay_ = new YumeDebugOverlay; gYume->pUI->AddUIElement(overlay_); overlay_->SetVisible(true); overlay_->GetBinding("SampleName")->SetValue("Post Processing"); #endif //Define post processing effects RenderPass* dp = renderer->GetDefaultPass(); dp->Load("RenderCalls/Bloom.xml",true); dp->Load("RenderCalls/FXAA.xml",true); dp->Load("RenderCalls/LensDistortion.xml",true); dp->Load("RenderCalls/Godrays.xml",true); dp->Load("RenderCalls/ShowGBuffer.xml",true); dp->DisableRenderCalls("ShowGBuffer"); dp->DisableRenderCalls("Godrays"); dp->DisableRenderCalls("Bloom"); MaterialPtr emissiveBlue = YumeAPINew Material; emissiveBlue->SetShaderParameter("DiffuseColor",DirectX::XMFLOAT4(0,0,1,1)); emissiveBlue->SetShaderParameter("SpecularColor",DirectX::XMFLOAT4(1,1,1,1)); emissiveBlue->SetShaderParameter("Roughness",0.001f); emissiveBlue->SetShaderParameter("ShadingMode",0); emissiveBlue->SetShaderParameter("has_diffuse_tex",false); emissiveBlue->SetShaderParameter("has_alpha_tex",false); emissiveBlue->SetShaderParameter("has_specular_tex",false); emissiveBlue->SetShaderParameter("has_normal_tex",false); emissiveBlue->SetShaderParameter("has_roughness_tex",false); MaterialPtr emissiveRed = YumeAPINew Material; emissiveRed->SetShaderParameter("DiffuseColor",DirectX::XMFLOAT4(1,0,0,1)); emissiveRed->SetShaderParameter("SpecularColor",DirectX::XMFLOAT4(1,1,1,1)); emissiveRed->SetShaderParameter("Roughness",0.001f); emissiveRed->SetShaderParameter("ShadingMode",0); emissiveRed->SetShaderParameter("has_diffuse_tex",false); emissiveRed->SetShaderParameter("has_alpha_tex",false); emissiveRed->SetShaderParameter("has_specular_tex",false); emissiveRed->SetShaderParameter("has_normal_tex",false); emissiveRed->SetShaderParameter("has_roughness_tex",false); MaterialPtr emissivePink = YumeAPINew Material; emissivePink->SetShaderParameter("DiffuseColor",DirectX::XMFLOAT4(1,0.0784314f,0.576471f,1)); emissivePink->SetShaderParameter("SpecularColor",DirectX::XMFLOAT4(1,1,1,1)); emissivePink->SetShaderParameter("Roughness",0.001f); emissivePink->SetShaderParameter("ShadingMode",0); emissivePink->SetShaderParameter("has_diffuse_tex",false); emissivePink->SetShaderParameter("has_alpha_tex",false); emissivePink->SetShaderParameter("has_specular_tex",false); emissivePink->SetShaderParameter("has_normal_tex",false); emissivePink->SetShaderParameter("has_roughness_tex",false); StaticModel* jeyjeyModel = CreateModel("Models/sponza/sponza.yume"); Light* dirLight = new Light; dirLight->SetName("DirLight"); dirLight->SetType(LT_DIRECTIONAL); dirLight->SetPosition(DirectX::XMVectorSet(0,1500,0,0)); dirLight->SetDirection(DirectX::XMVectorSet(0,-1,0,0)); dirLight->SetRotation(DirectX::XMVectorSet(-1,0,0,0)); dirLight->SetColor(YumeColor(1,1,1,0)); scene->AddNode(dirLight); } void GodRays::MoveCamera(float timeStep) { } void GodRays::HandleUpdate(float timeStep) { } void GodRays::HandleRenderUpdate(float timeStep) { } void GodRays::Setup() { engineVariants_["GI"] = LPV; engineVariants_["WindowWidth"] = 1024; engineVariants_["WindowHeight"] = 768; BaseApplication::Setup(); } }
27.725146
95
0.730015
843a8013b35ade495a373147057fe382813aa470
8,810
cpp
C++
3d_conv/xilinx_prj/lib_gen/__merlinwrapper_conv_3d_kernel.cpp
FCS-holding/acc_lib
1b6c0bc5467400e2ac678d18426cbbc7d44e8fec
[ "Apache-2.0" ]
null
null
null
3d_conv/xilinx_prj/lib_gen/__merlinwrapper_conv_3d_kernel.cpp
FCS-holding/acc_lib
1b6c0bc5467400e2ac678d18426cbbc7d44e8fec
[ "Apache-2.0" ]
null
null
null
3d_conv/xilinx_prj/lib_gen/__merlinwrapper_conv_3d_kernel.cpp
FCS-holding/acc_lib
1b6c0bc5467400e2ac678d18426cbbc7d44e8fec
[ "Apache-2.0" ]
null
null
null
#include "cmost.h" #include <string.h> #include <stdio.h> #include <stdlib.h> #include <hls_stream.h> #include "merlin_type_define.h" #include "__merlinhead_kernel_top.h" #include <chrono> #include <iostream> void __merlinwrapper_conv_3d_kernel(float data_in[DATA_IN_LENGTH], float filter[FILTER_IN_LENGTH], float data_out[DATA_OUT_LENGTH]) { if (filter == 0) { printf("Error! Detected null pointer 'filter' for external memory.\n"); exit(1); } if (data_in == 0) { printf("Error! Detected null pointer 'data_in' for external memory.\n"); exit(1); } if (data_out == 0) { printf("Error! Detected null pointer 'data_out' for external memory.\n"); exit(1); } #ifdef DEBUG printf("IN_SIZE_TILE = %d, OUT_SIZE_TILE = %d, IN_DEPTH = %d\n", IN_SIZE_TILE, OUT_SIZE_TILE, IN_DEPTH); printf("IN_SIZE_ONE_CALL = %d, OUT_SIZE_ONE_CALL = %d\n", IN_SIZE_ONE_CALL, OUT_SIZE_ONE_CALL); printf("LAST_OUT_SIZE_ONE_CALL = %d\n", LAST_OUT_SIZE_ONE_CALL); #endif float * data_in_merlin[PE]; float * data_out_merlin[PE]; for (int j = 0; j < PE; j++) { data_in_merlin[j] = (float *)malloc(IN_SIZE_TILE*sizeof(float)); data_out_merlin[j] = (float *)malloc(OUT_SIZE_TILE*sizeof(float)); } #ifdef DEBUG auto start0 = std::chrono::high_resolution_clock::now(); #endif //for(int i=0; i<IMAGE_SIZE; i++) { for(int i=0; i<FILTER_SIZE-1; i++) { for(int j=0; j<IN_DEPTH; j++) { for(int k=0; k<IMAGE_SIZE; k++) { data_in_merlin[0][i*IMAGE_SIZE*IN_DEPTH + j*IMAGE_SIZE + k] = data_in[i*IMAGE_SIZE*IMAGE_SIZE + (j+STEP*0)*IMAGE_SIZE + k]; data_in_merlin[1][i*IMAGE_SIZE*IN_DEPTH + j*IMAGE_SIZE + k] = data_in[i*IMAGE_SIZE*IMAGE_SIZE + (j+STEP*1)*IMAGE_SIZE + k]; data_in_merlin[2][i*IMAGE_SIZE*IN_DEPTH + j*IMAGE_SIZE + k] = data_in[i*IMAGE_SIZE*IMAGE_SIZE + (j+STEP*2)*IMAGE_SIZE + k]; data_in_merlin[3][i*IMAGE_SIZE*IN_DEPTH + j*IMAGE_SIZE + k] = data_in[i*IMAGE_SIZE*IMAGE_SIZE + (j+STEP*3)*IMAGE_SIZE + k]; } } } #ifdef DEBUG auto diff0 = std::chrono::high_resolution_clock::now() - start0; auto t0 = std::chrono::duration_cast<std::chrono::nanoseconds>(diff0); std::cout << "Data prepare time: " << t0.count() << std::endl; #endif // filter only need to copy once #ifdef DEBUG printf("[Merlin Info] Start %s data for %s, data size = %d...\n", "copy in", "filter", FILTER_IN_LENGTH * sizeof(float )); fflush(stdout); #endif for (int j = 0; j < PE; j++) { m_q[j]->enqueueWriteBuffer(*buffer_filter[j], CL_TRUE, 0, FILTER_IN_LENGTH * sizeof(float), filter); // memcpy(filter_align[j].data(), filter, FILTER_IN_LENGTH*sizeof(float)); // m_q[j]->enqueueMigrateMemObjects({*(buffer_filter[j])}, 0); } int flag = 0; for (int i = 0; i < OUT_IMAGE_SIZE + OVERLAP; i++) { // for (int i = 0; i < 2 + OVERLAP; i++) { for (int j = 0; j < PE; j++) { int queue_index = flag % (OVERLAP*PE); int overlap_index = (flag/PE) % OVERLAP; int pe_index = j; //printf("queue_index = %d, overlap_index = %d, pe_index = %d\n", queue_index, overlap_index, pe_index); if (i > 1) { #ifdef DEBUG //printf("Wait finish for queue %d\n", queue_index); #endif m_q[queue_index]->finish(); //printf("memcpy out index = %d, offset = %d, size = %d\n", pe_index, (i-OVERLAP)*OUT_SIZE_TILE, OUT_SIZE_ONE_CALL); //memcpy(data_out_merlin[pe_index] + (i-OVERLAP)*OUT_SIZE_ONE_CALL, output_align[pe_index][overlap_index].data(), OUT_SIZE_ONE_CALL*sizeof(float)); if (j == PE - 1 ) { memcpy(data_out + (i-OVERLAP)*OUT_IMAGE_SIZE*OUT_IMAGE_SIZE+j*OUT_SIZE_ONE_CALL, output_align[pe_index][overlap_index].data(), LAST_OUT_SIZE_ONE_CALL*sizeof(float)); } else { memcpy(data_out + (i-OVERLAP)*OUT_IMAGE_SIZE*OUT_IMAGE_SIZE+j*OUT_SIZE_ONE_CALL, output_align[pe_index][overlap_index].data(), OUT_SIZE_ONE_CALL*sizeof(float)); } // memcpy(data_out + (i-OVERLAP)*OUT_IMAGE_SIZE*OUT_IMAGE_SIZE+j*OUT_SIZE_ONE_CALL, // output_align[pe_index][overlap_index].data(), // OUT_SIZE_ONE_CALL*sizeof(float)); #ifdef DEBUG //printf("index = %d, data_out_kernel host[%d] = %15.6f\n", i, 0, (output_align[pe_index][overlap_index].data())[0]); #endif } if (i < OUT_IMAGE_SIZE) { #ifdef DEBUG printf("Do compute for one plane %d, on queue %d\n", i, queue_index); #endif //printf("memcpy in index = %d, offset = %d, size = %d\n", pe_index, i*IN_DEPTH*IMAGE_SIZE, IN_SIZE_ONE_CALL); //if(i == 0 && j == 0) { // for(int k=0; k<IN_SIZE_ONE_CALL; k++) { // printf("org k = %d, data = %f\n", k, data_in_merlin[pe_index][k]); // } //} //if(i == 0 && j == 0) { // printf("offset1 = %d, offset2 = %d\n", // (i+FILTER_SIZE-1)*IN_DEPTH*IMAGE_SIZE, // (i+FILTER_SIZE-1)*IMAGE_SIZE*IMAGE_SIZE + STEP*j*IMAGE_SIZE); //} memcpy(data_in_merlin[pe_index] + (i+FILTER_SIZE-1)*IN_DEPTH*IMAGE_SIZE, data_in + (i+FILTER_SIZE-1)*IMAGE_SIZE*IMAGE_SIZE + STEP*j*IMAGE_SIZE, IN_DEPTH*IMAGE_SIZE*sizeof(float)); //if(i == 0 && j == 0) { // for(int k=0; k<IN_SIZE_ONE_CALL; k++) { // printf("new k = %d, data = %f\n", k, data_in_merlin[pe_index][k]); // } //} memcpy(input_align[pe_index][overlap_index].data(), data_in_merlin[pe_index] + i*IN_DEPTH*IMAGE_SIZE, IN_SIZE_ONE_CALL*sizeof(float)); //if(i == 0 && j == 0) { //for(int x = 0; x < IN_SIZE_ONE_CALL; x++) { // printf("input_align[%d] = %f\n", x, (input_align[pe_index][overlap_index].data())[x]); //} //} m_q[queue_index]->enqueueMigrateMemObjects({*(buffer_input[pe_index][overlap_index])}, 0); conv_kernel[pe_index]->setArg(0, *(buffer_input[pe_index][overlap_index])); conv_kernel[pe_index]->setArg(1, *(buffer_filter[pe_index])); conv_kernel[pe_index]->setArg(2, *(buffer_output[pe_index][overlap_index])); m_q[queue_index]->enqueueTask(*conv_kernel[pe_index]); m_q[queue_index]->enqueueMigrateMemObjects({*(buffer_output[pe_index][overlap_index])}, CL_MIGRATE_MEM_OBJECT_HOST); } flag++; } #ifdef DEBUG printf("\n"); #endif } for (int i = 0; i < PE * OVERLAP; i++) { m_q[i]->finish(); } /* printf("Start merge out data\n"); for(int i=0; i<OUT_IMAGE_SIZE; i++) { for(int j=0; j<OUT_IMAGE_SIZE; j++) { for(int k=0; k<OUT_IMAGE_SIZE; k++) { if(j < OUT_DEPTH) { data_out[i*OUT_IMAGE_SIZE*OUT_IMAGE_SIZE + j*OUT_IMAGE_SIZE + k] \ = data_out_merlin[0][i*OUT_IMAGE_SIZE*STEP + j*OUT_IMAGE_SIZE + k]; } else if(j < OUT_DEPTH * 2) { data_out[i*OUT_IMAGE_SIZE*OUT_IMAGE_SIZE + j*OUT_IMAGE_SIZE + k] \ = data_out_merlin[1][i*OUT_IMAGE_SIZE*STEP + (j-OUT_DEPTH)*OUT_IMAGE_SIZE + k]; } else if(j < OUT_DEPTH * 3) { data_out[i*OUT_IMAGE_SIZE*OUT_IMAGE_SIZE + j*OUT_IMAGE_SIZE + k] \ = data_out_merlin[2][i*OUT_IMAGE_SIZE*STEP + (j-OUT_DEPTH*2)*OUT_IMAGE_SIZE + k]; } else { data_out[i*OUT_IMAGE_SIZE*OUT_IMAGE_SIZE + j*OUT_IMAGE_SIZE + k] \ = data_out_merlin[3][i*OUT_IMAGE_SIZE*STEP + (j-OUT_DEPTH*3)*OUT_IMAGE_SIZE + k]; } } } } */ } void __merlin_conv_3d_kernel(float data_in[LENGTH_IN_TILE],float filter[FILTER_IN_LENGTH],float data_out[LENGTH_OUT_TILE]) { __merlinwrapper_conv_3d_kernel(data_in,filter,data_out); }
50.056818
163
0.539955
8442f55fa028083cadf0b9d9008b6ee0bc7e20dd
49,789
cc
C++
sim/models/actuators/ground_station_v2.cc
leozz37/makani
c94d5c2b600b98002f932e80a313a06b9285cc1b
[ "Apache-2.0" ]
1,178
2020-09-10T17:15:42.000Z
2022-03-31T14:59:35.000Z
sim/models/actuators/ground_station_v2.cc
leozz37/makani
c94d5c2b600b98002f932e80a313a06b9285cc1b
[ "Apache-2.0" ]
1
2020-05-22T05:22:35.000Z
2020-05-22T05:22:35.000Z
sim/models/actuators/ground_station_v2.cc
leozz37/makani
c94d5c2b600b98002f932e80a313a06b9285cc1b
[ "Apache-2.0" ]
107
2020-09-10T17:29:30.000Z
2022-03-18T09:00:14.000Z
// Copyright 2020 Makani Technologies LLC // // 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 "sim/models/actuators/ground_station_v2.h" #include <math.h> #include <algorithm> #include <limits> #include "common/c_math/geometry.h" #include "common/c_math/mat3.h" #include "common/c_math/util.h" #include "control/sensor_util.h" #include "control/system_params.h" #include "control/vessel_frame.h" #include "sim/sim_telemetry.h" namespace { // Attenuate a velocity command and apply a dead zone as the position target is // approached. This corresponds to the McLaren Simulink block "Attenuate // angular velocity demand as angular target is approached". static double AttenuateAndApplyDeadZone(double vel_cmd, double pos_error, double max_accel, double dead_zone_half_width) { // The attenuation strategy is based on the standard relationship for a system // under constant acceleration: // 2 * a * (x - x_0) = v^2 - v_0^2. // Our choice of a maximum velocity corresponds to choosing v_0 such that // pos_error = (x - x_0) will be zero when the velocity is zero if the system // is decelerated as quickly as allowed. double v_max = Sqrt(fabs(pos_error) * 2.0 * max_accel); double modified_cmd = Saturate(vel_cmd, -v_max, v_max); // This is equivalent to a standard Simulink dead zone: // https://www.mathworks.com/help/simulink/slref/deadzone.html. double dead_zone_upper = Sqrt(fabs(dead_zone_half_width) * 2.0 * max_accel); if (modified_cmd < -dead_zone_upper) { modified_cmd += dead_zone_upper; } else if (modified_cmd < dead_zone_upper) { modified_cmd = 0.0; } else { modified_cmd -= dead_zone_upper; } return modified_cmd; } } // namespace Gs02ModeController::Gs02ModeController(const std::string &name__, double ts) : Model(name__, ts), azi_pos_(new_discrete_state(), "azi_pos", ts_, 0.0), azi_vel_(new_discrete_state(), "azi_vel", ts_, 0.0), drum_pos_(new_discrete_state(), "drum_pos", ts_, 0.0), drum_vel_(new_discrete_state(), "drum_pos", ts_, 0.0), wing_azi_(new_discrete_state(), "wing_azi", ts_, 0.0), enabled_(new_discrete_state(), "enabled", ts_, false), azi_vel_cmd_(new_discrete_state(), "azi_vel_cmd", ts_, 0.0), drum_vel_cmd_(new_discrete_state(), "drum_vel_cmd", ts_, 0.0) {} void Gs02ModeController::SetCommonInputs(double t, double azi_pos, double azi_vel, double drum_pos, double drum_vel, double wing_azi) { azi_pos_.DiscreteUpdate(t, azi_pos); azi_vel_.DiscreteUpdate(t, azi_vel); drum_pos_.DiscreteUpdate(t, drum_pos); drum_pos_.DiscreteUpdate(t, drum_vel); wing_azi_.DiscreteUpdate(t, wing_azi); } ReelController::ReelController(const Gs02SimMcLarenControllerParams &params, double drum_radius) : Gs02ModeController("Reel controller", params.ts), params_(params), drum_radius_(drum_radius), drum_linear_vel_cmd_from_wing_(new_discrete_state(), "drum_linear_vel_cmd_from_wing", params.ts, 0.0), azi_cmd_z_(new_discrete_state(), "azi_cmd_z", params.ts, {{0.0, 0.0}}), azi_cmd_delay_state_(new_discrete_state(), "azi_cmd_delay_state", params.ts, 0.0), azi_cmd_dead_zone_(new_discrete_state(), "azi_cmd_dead_zone", params.ts, 0.0), azi_in_dead_zone_z1_(new_discrete_state(), "azi_in_dead_zone_z1", params.ts, false), azi_delay_state_(new_discrete_state(), "azi_delay_state", params.ts, 0.0), azi_rate_limit_state_(new_discrete_state(), "azi_rate_limit_state", params.ts, 0.0), drum_vel_rate_limit_state_(new_discrete_state(), "drum_vel_rate_limit_state", params.ts, 0.0), levelwind_engaged_(new_discrete_state(), "levelwind_engaged", params.ts, true) { SetupDone(); } void ReelController::DiscreteStepHelper(double t) { if (!enabled_.val()) { azi_cmd_z_.DiscreteUpdate(t, azi_cmd_z_.val()); azi_cmd_delay_state_.DiscreteUpdate(t, azi_cmd_delay_state_.val()); azi_delay_state_.DiscreteUpdate(t, azi_vel_.val()); azi_rate_limit_state_.DiscreteUpdate(t, azi_vel_.val()); drum_vel_rate_limit_state_.DiscreteUpdate(t, drum_vel_.val()); return; } { // Generate azimuth velocity command. const double target_pos = wing_azi_.val() + params_.reel.azi_offset_from_wing; // Unwrap the target position toward the state of the command filter. // This prevents the perch from taking the long way around the circle when // the target azimuth goes through a 2*pi discontinuity. double unwrapped_target_pos = azi_cmd_delay_state_.val(); double twopimoddiff = fmod(azi_cmd_delay_state_.val() - target_pos, 2.0 * PI); if (twopimoddiff > PI) { unwrapped_target_pos -= twopimoddiff - 2.0 * PI; } else { unwrapped_target_pos -= twopimoddiff; } // Apply the 2nd order command filter. std::array<double, 2> azi_cmd_z = azi_cmd_z_.val(); double azi_cmd = Lpf2(unwrapped_target_pos, params_.reel.azi_cmd_filter_omega / 2.0 / PI, params_.reel.azi_cmd_filter_zeta, params_.ts, azi_cmd_z.data()); azi_cmd_z_.DiscreteUpdate(t, azi_cmd_z); // Acquire the delayed value, and then update it. double output_cmd = azi_delay_state_.val(); double azi_vel_cmd = (azi_cmd - azi_cmd_delay_state_.val()) / params_.ts; azi_cmd_delay_state_.DiscreteUpdate(t, azi_cmd); double pos_error = Wrap(azi_cmd - azi_pos_.val(), -PI, PI); // Apply dead zone. The "effective dead zone" controls the azimuth to within // a tight envelope around the target (as a fraction of the commanded dead // zone), then expands the envelope to the full specified dead zone. Doing // this prevents jitter at the edges of the dead zone. double effective_dead_zone = azi_in_dead_zone_z1_.val() ? azi_cmd_dead_zone_.val() : azi_cmd_dead_zone_.val() * params_.reel.little_dead_zone; if (fabs(pos_error) <= effective_dead_zone) { azi_in_dead_zone_z1_.DiscreteUpdate(t, true); pos_error = 0.0; } else { azi_in_dead_zone_z1_.DiscreteUpdate(t, false); } double pos_error_saturated = Saturate( pos_error, -params_.reel.azi_error_max, params_.reel.azi_error_max); azi_delay_state_.DiscreteUpdate( t, params_.reel.azi_vel_cmd_kp * pos_error_saturated + params_.reel.azi_vel_cmd_ff_gain * azi_vel_cmd); // Apply the rate limit. double cmd_z1 = azi_rate_limit_state_.val(); output_cmd = RateLimit(output_cmd, -params_.reel.azi_vel_cmd_rate_limit, params_.reel.azi_vel_cmd_rate_limit, params_.ts, &cmd_z1); azi_rate_limit_state_.DiscreteUpdate(t, cmd_z1); azi_vel_cmd_.DiscreteUpdate(t, output_cmd); } { // Generate drum velocity command. double cmd = drum_linear_vel_cmd_from_wing_.val() / drum_radius_; if (!levelwind_engaged_.val()) { // Stop the winch if the levelwind disengages. cmd = 0.0; } double pos_error; if (cmd > 0.0) { pos_error = params_.reel.drum_angle_upper_limit - drum_pos_.val(); } else { pos_error = -std::numeric_limits<double>::infinity(); } // Clip the velocity command if it's in the wrong direction. if (cmd * pos_error < 0) cmd = 0.0; cmd = AttenuateAndApplyDeadZone( cmd, params_.reel.drum_angle_upper_limit - drum_pos_.val(), params_.reel.max_drum_accel, 0.0); // Apply the rate limit. double cmd_z1 = drum_vel_rate_limit_state_.val(); cmd = RateLimit(cmd, -params_.reel.max_drum_accel, params_.reel.max_drum_accel, params_.ts, &cmd_z1); drum_vel_rate_limit_state_.DiscreteUpdate(t, cmd_z1); drum_vel_cmd_.DiscreteUpdate(t, cmd); } } TransformController::TransformController( const Gs02SimMcLarenControllerParams &params) : Gs02ModeController("Transform controller", params.ts), params_(params.transform), azi_rate_limit_state_(new_discrete_state(), "azi_rate_limit_state", params.ts, 0.0), winch_rate_limit_state_(new_discrete_state(), "winch_rate_limit_state", params.ts, 0.0), detwist_pos_cmd_(new_discrete_state(), "detwist_pos_cmd", ts_, 0.0), unpause_transform_(new_discrete_state(), "unpause_transform", params.ts, false), transform_stage_(new_discrete_state(), "transform_stage", params.ts, 0), ht2reel_(new_discrete_state(), "ht2reel", params.ts, false), transform_complete_(new_discrete_state(), "transform_complete", params.ts, false) { SetupDone(); } void TransformController::Publish() const { sim_telem.gs02.transform_stage = transform_stage_.val(); } void TransformController::DiscreteStepHelper(double t) { if (!enabled_.val()) { azi_rate_limit_state_.DiscreteUpdate(t, azi_vel_.val()); winch_rate_limit_state_.DiscreteUpdate(t, drum_vel_.val()); transform_complete_.DiscreteUpdate(t, false); transform_stage_.DiscreteUpdate(t, 0); return; } const int32_t s = transform_stage_.val(); bool azi_target_satisfied; { // Azimuth double target = wing_azi_.val() + params_.azi_offset_from_wing; double tol; if (ht2reel_.val()) { target += params_.azi_targets_ht2reel[s]; tol = params_.azi_tols_ht2reel[s]; } else { target += params_.azi_targets_reel2ht[s]; tol = params_.azi_tols_reel2ht[s]; } double pos_error = Wrap(target - azi_pos_.val(), -PI, PI); double vel_cmd = Sign(pos_error) * params_.azi_nominal_vel; vel_cmd = AttenuateAndApplyDeadZone( vel_cmd, pos_error, params_.azi_decel_ratio * params_.azi_max_accel, params_.azi_dead_zone_half_width); double cmd_z1 = azi_rate_limit_state_.val(); vel_cmd = RateLimit(vel_cmd, -params_.azi_max_accel, params_.azi_max_accel, ts_, &cmd_z1); azi_rate_limit_state_.DiscreteUpdate(t, vel_cmd); azi_vel_cmd_.DiscreteUpdate(t, vel_cmd); azi_target_satisfied = -tol < pos_error && pos_error < tol; } bool winch_target_satisfied; { // Winch double target, tol; if (ht2reel_.val()) { target = params_.winch_targets_ht2reel[transform_stage_.val()]; tol = params_.winch_tols_ht2reel[transform_stage_.val()]; } else { target = params_.winch_targets_reel2ht[transform_stage_.val()]; tol = params_.winch_tols_reel2ht[transform_stage_.val()]; } double pos_error = target - drum_pos_.val(); double vel_cmd = Sign(pos_error) * params_.winch_nominal_vel; vel_cmd = AttenuateAndApplyDeadZone( vel_cmd, pos_error, params_.winch_decel_ratio * params_.winch_max_accel, params_.winch_dead_zone_half_width); double cmd_z1 = winch_rate_limit_state_.val(); vel_cmd = RateLimit(vel_cmd, -params_.winch_max_accel, params_.winch_max_accel, ts_, &cmd_z1); winch_rate_limit_state_.DiscreteUpdate(t, vel_cmd); drum_vel_cmd_.DiscreteUpdate(t, vel_cmd); winch_target_satisfied = target - tol < drum_pos_.val() && drum_pos_.val() < target + tol; } { // Generate detwist position command. double target; if (ht2reel_.val()) { target = params_.detwist_targets_ht2reel[transform_stage_.val()]; } else { target = params_.detwist_targets_reel2ht[transform_stage_.val()]; } detwist_pos_cmd_.DiscreteUpdate(t, target); } // Update the transform stage and determine if the transform is complete. bool stage_complete = azi_target_satisfied && winch_target_satisfied; int32_t next_stage, last_stage; if (ht2reel_.val()) { // HighTension to Reel: Stage progression is 0, 1, 2, 3, 4. last_stage = 4; next_stage = std::min(s + 1, last_stage); // Wait at the end of stages 1 and 2 unless unpaused. if (!unpause_transform() && (s == 1 || s == 2)) { stage_complete = false; } } else { // Reel to HighTension: Stage progression is 0, 4, 3, 2, 1. last_stage = 1; next_stage = s == 0 ? 4 : std::max(s - 1, last_stage); // Wait at the end of stage 3 unless unpaused. if (!unpause_transform() && s == 3) { stage_complete = false; } } transform_complete_.DiscreteUpdate(t, s == last_stage && stage_complete); transform_stage_.DiscreteUpdate(t, stage_complete ? next_stage : s); } void TransformController::StartTransform(double t, bool ht2reel) { transform_stage_.DiscreteUpdate(t, 0); ht2reel_.DiscreteUpdate(t, ht2reel); transform_complete_.DiscreteUpdate(t, false); } HighTensionController::HighTensionController( const Gs02SimMcLarenControllerParams &params) : Gs02ModeController("High tension controller", params.ts), params_(params.high_tension), active_braking_first_entry_(true), active_braking_t0_(0.0), angular_rate_tol_(1.7e-4), hpu_cmd_change_t0_(0.0), hpu_delay_(0.4), ht_ts_(params.ts), brake_torque_(new_discrete_state(), "brake_torque", params.ts, 0.0), tether_torque_(new_discrete_state(), "tether_torque", params.ts, 0.0), brake_torque_cmd_(new_discrete_state(), "brake_torque_cmd", params.ts, 0.0), n_hpu_mode_demand_(new_discrete_state(), "n_hpu_mode_demand", params.ts, kBrakesOn), azi_velocity_dir_(new_discrete_state(), "azi_velocity_dir", params.ts, 0.0), n_state_machine_(new_discrete_state(), "n_state_machine", params.ts, kBaseCase), total_torque_(new_discrete_state(), "total_torque", params.ts, 0.0), n_hpu_mode_(new_discrete_state(), "n_hpu_mode", params.ts, kBrakesOn), n_hpu_mode_last_(new_discrete_state(), "n_hpu_mode_last", params.ts, kBrakesOn), a_error_(new_discrete_state(), "azimuth_error", params.ts, 0.0), detwist_pos_cmd_(new_discrete_state(), "detwist_pos_cmd", ts_, 0.0), detwist_pos_cmd_from_wing_(new_discrete_state(), "detwist_pos_cmd_from_wing", params.ts, 0.0) { SetupDone(); } // The high-tension controller uses a brake plus the tether torque to // semi-actively control the ground station aziumth in the high-tension mode // i.e. when the kite is in crosswind flight. void HighTensionController::DiscreteStepHelper(double t) { // Run the controller state logic which emulates the GS02 Simulink code. RunControlSwitchingLogic(t); // Run the GS02 azimuth control laws and update the HPU and brake models. RunControlLaw(t); // Generate detwist position command. detwist_pos_cmd_.DiscreteUpdate(t, detwist_pos_cmd_from_wing_.val()); } // The high-tension controller switching logic as implemented in the GS02 // Simulink state-flow code. void HighTensionController::RunControlSwitchingLogic(double t) { // n_state_machine_val keeps track of the current state machine case. static SwitchingLogicState n_state_machine_val = kBaseCase; // a_error is the error between the flight circle center azimuth and the GS02 // azimuth less Pi i.e. the GS needs to be pointed -Pi from its reference // azimuth in crosswind. a_error_.DiscreteUpdate( t, Wrap(wing_azi_.val() - azi_pos_.val() - M_PI, -PI, PI)); switch (n_state_machine()) { case kBaseCase: azi_velocity_dir_.DiscreteUpdate(t, 0.0); n_hpu_mode_demand_.DiscreteUpdate(t, kBrakesOn); if ((tether_torque() > params_.m_max_azi_ht) && (a_error() > params_.a_control_threshold_azi_ht)) { n_state_machine_val = kWaitForPositiveTetherOverload; } if ((tether_torque() < -params_.m_max_azi_ht) && (a_error() < -params_.a_control_threshold_azi_ht)) { n_state_machine_val = kWaitForNegativeTetherOverload; } n_state_machine_.DiscreteUpdate(t, n_state_machine_val); break; case kWaitForPositiveTetherOverload: azi_velocity_dir_.DiscreteUpdate(t, 0.0); n_hpu_mode_demand_.DiscreteUpdate(t, kBrakesOn); if (tether_torque() > params_.m_control_threshold_azi_ht) { n_state_machine_val = kWaitForHpuPositive; } n_state_machine_.DiscreteUpdate(t, n_state_machine_val); break; case kWaitForHpuPositive: azi_velocity_dir_.DiscreteUpdate(t, 0.0); n_hpu_mode_demand_.DiscreteUpdate(t, kBrakesRegulated); if (n_hpu_mode() == kBrakesRegulated) { n_state_machine_val = kAzimuthPositiveRotation; } if (tether_torque() < params_.m_control_threshold_azi_ht) { n_state_machine_val = kWaitForPositiveTetherOverload; } n_state_machine_.DiscreteUpdate(t, n_state_machine_val); break; case kAzimuthPositiveRotation: azi_velocity_dir_.DiscreteUpdate(t, params_.n_demand_azi_ht); // Command zero azimuth rate when close to the commanded azimuth. if ((fabs(a_error()) < params_.a_control_tolerance_azi_ht) || a_error() < 0.0) { n_state_machine_val = kActiveBraking; active_braking_first_entry_ = true; } else if (a_error() < 0.0) { n_state_machine_val = kAzimuthNegativeRotation; } n_state_machine_.DiscreteUpdate(t, n_state_machine_val); break; case kActiveBraking: azi_velocity_dir_.DiscreteUpdate(t, 0.0); if (active_braking_first_entry_) { active_braking_first_entry_ = false; active_braking_t0_ = t; } // Command the brakes fully on if the azimuth rate is small enough. if (fabs(azi_vel_.val()) < params_.n_control_tolerance_azi_ht) { n_state_machine_val = kBaseCase; } // Command the brakes fully on if time in this mode is large enough. if (t > (active_braking_t0_ + params_.t_threshold_wait_azi_ht)) { n_state_machine_val = kBaseCase; } n_state_machine_.DiscreteUpdate(t, n_state_machine_val); break; case kWaitForNegativeTetherOverload: azi_velocity_dir_.DiscreteUpdate(t, 0.0); n_hpu_mode_demand_.DiscreteUpdate(t, kBrakesOn); if (tether_torque() < -params_.m_control_threshold_azi_ht) { n_state_machine_val = kWaitForHpuNegative; } n_state_machine_.DiscreteUpdate(t, n_state_machine_val); break; case kWaitForHpuNegative: azi_velocity_dir_.DiscreteUpdate(t, 0.0); n_hpu_mode_demand_.DiscreteUpdate(t, kBrakesRegulated); if (tether_torque() > -params_.m_control_threshold_azi_ht) { n_state_machine_val = kWaitForNegativeTetherOverload; } if (n_hpu_mode() == kBrakesRegulated) { n_state_machine_val = kAzimuthNegativeRotation; } n_state_machine_.DiscreteUpdate(t, n_state_machine_val); break; case kAzimuthNegativeRotation: azi_velocity_dir_.DiscreteUpdate(t, -params_.n_demand_azi_ht); // Command zero azimuth rate when close to the commanded azimuth. if ((fabs(a_error()) < params_.a_control_tolerance_azi_ht) || a_error() > 0.0) { n_state_machine_val = kActiveBraking; active_braking_first_entry_ = true; } else if (a_error() > 0.0) { n_state_machine_val = kAzimuthPositiveRotation; } n_state_machine_.DiscreteUpdate(t, n_state_machine_val); break; default: {}; } } void HighTensionController::RunBrakeModel(double t) { double brake_torque_val = brake_torque_cmd(); double total_torque_val = 0.0; // Check if the brake torque is the same sign as the tether torque // (this is not physical). If so, then set the brake torque to zero. The // controller sign will eventually change. // Additionally, check that the brake torque is not higher than the tether // torque. This would not be a phisically possible scenario. if (tether_torque() * brake_torque_val > 0.0) { brake_torque_val = 0.0; } else if (fabs(brake_torque_val) > fabs(tether_torque())) { brake_torque_val = -tether_torque(); } // Keep the brake torque on for a few hundred milliseconds after // n_state_machine goes to zero to kill the residual angular rate (we cannot // instantaneously set it to zero because we only have finite brake torque). if ((n_state_machine() == kBaseCase) && (n_hpu_mode() == kBrakesRegulated)) { // Still have some residual rate so hold the last total torque. if (fabs(azi_vel_.val()) > angular_rate_tol_) { brake_torque_val = total_torque() - tether_torque(); } else { // Residual rate is small but n_hpu_mode != 0 yet so lock the // brake. brake_torque_val = -tether_torque(); } } else { // Update last total torque value. total_torque_val = tether_torque() + brake_torque_val; } brake_torque_.DiscreteUpdate(t, brake_torque_val); total_torque_.DiscreteUpdate(t, total_torque_val); } // This function is a simple model of the ground station HPU controller. The // model is a time delay between the command and state. void HighTensionController::RunHpuModel(double t) { if (n_hpu_mode_last_.val() != n_hpu_mode_demand()) { // HPU demand changed. hpu_cmd_change_t0_ = t; } if (t > hpu_cmd_change_t0_ + hpu_delay_) { // Update HPU mode after delay. n_hpu_mode_.DiscreteUpdate(t, n_hpu_mode_demand()); } n_hpu_mode_last_.DiscreteUpdate(t, n_hpu_mode_demand()); } // Run the high-tension closed-loop controller. void HighTensionController::RunControlLaw(double t) { double brake_torque_cmd_val = 0.0; // Brake torque command [N-m]. double azi_omega_cmd = 0.0; // Azimuth angular rate command [rad/s]. double k_omega = 0.0; // Angular rate loop gain [Nm/(rad/s)]. double total_torque_cmd = 0.0; // Total torque command [N-m]. // Brakes reguated mode i.e. closed loop control on speed. if (n_hpu_mode_demand() == kBrakesRegulated) { if (fabs(azi_velocity_dir()) < params_.test_threshold) { azi_omega_cmd = 0.0; k_omega = params_.k_stop; } else if (fabs(azi_velocity_dir() - params_.n_demand_azi_ht) < params_.test_threshold) { azi_omega_cmd = params_.omega_nom; k_omega = params_.k_spin; } else if (fabs(azi_velocity_dir() + params_.n_demand_azi_ht) < params_.test_threshold) { azi_omega_cmd = -params_.omega_nom; k_omega = params_.k_spin; } else { azi_omega_cmd = 0.0; k_omega = params_.k_stop; } // Compute the brake torque command based on this control law. total_torque_cmd = k_omega * (azi_omega_cmd - azi_vel_.val()); brake_torque_cmd_val = total_torque_cmd - tether_torque(); } else { // Do not allow net torque on the azimuth as brakes are fully on. brake_torque_cmd_val = -tether_torque(); } // Update brake torque command. brake_torque_cmd_.DiscreteUpdate(t, brake_torque_cmd_val); // Run a model of the GS02 brake. RunBrakeModel(t); // Run a simple model of the GS02 HPU (Hydraulic Power Unit). RunHpuModel(t); // Update azimuth and drum velocity commands. azi_vel_cmd_.DiscreteUpdate( t, total_torque() / mclarenparams().Iz_gndstation * ht_ts_); drum_vel_cmd_.DiscreteUpdate(t, 0.0); } GroundStationV2Base::GroundStationV2Base(const ReferenceFrame &ned_frame, const ReferenceFrame &parent_frame, const Gs02Params &params, const Gs02SimParams &sim_params__) : Actuator("GS02"), params_(params), sim_params_(sim_params__), racetrack_integrator_(params, sim_params__), ned_frame_(ned_frame), parent_frame_(parent_frame), azi_cmd_target_(new_derived_value(), "azi_cmd_target"), azi_cmd_dead_zone_(new_derived_value(), "azi_cmd_dead_zone"), drum_linear_vel_cmd_from_wing_(new_derived_value(), "drum_linear_vel_cmd_from_wing"), detwist_pos_cmd_from_wing_(new_derived_value(), "detwist_pos_cmd_from_wing"), mode_cmd_(new_derived_value(), "mode_cmd"), tether_force_g_(new_derived_value(), "tether_force_g"), unpause_transform_(new_derived_value(), "unpause_transform"), levelwind_engaged_(new_derived_value(), "levelwind_engaged"), tether_force_p_(kVec3Zero), gsg_pos_p_(kVec3Zero), mode_(new_discrete_state(), "mode", 0.0, kGroundStationModeReel), transform_stage_(new_discrete_state(), "transform_stage", 0.0, 0), platform_frame_(new_derived_value(), "platform_frame"), dcm_v2p_(new_derived_value(), "dcm_v2p"), wd0_frame_(new_derived_value(), "wd_frame"), wd_frame_(new_derived_value(), "wd_frame"), gsg0_frame_(new_derived_value(), "gsg0_frame"), panel_frame_(new_derived_value(), "panel_frame"), panel_surface_(this->panel_frame_.val_unsafe(), nullptr) { panel_surface_.set_collision_func( [this](const Vec3 &contactor_pos_panel, Vec3 *collision_pos) -> bool { return ContactPerchPanel(contactor_pos_panel, platform_frame_.val(), panel_frame_.val(), sim_params().panel, collision_pos); }); } void GroundStationV2::Init(double azimuth, double drum_angle__) { platform_azi_.Clear(); platform_azi_.set_val(azimuth); drum_angle_.Clear(); drum_angle_.set_val(drum_angle__); ClearDerivedValues(); UpdateDerivedStates(); } void GroundStationV2Base::SetLevelwindEngaged(double tether_elevation) { bool is_engaged = false; bool levelwind_in_use = false; switch (mode()) { case kGroundStationModeReel: case kGroundStationModeManual: levelwind_in_use = true; break; case kGroundStationModeTransform: // TODO: It is also in use when transform stage == 0 during // transform up. levelwind_in_use = transform_stage() == 4; break; case kGroundStationModeHighTension: break; case kNumGroundStationModes: default: LOG(FATAL) << "Bad GS02 mode: " << static_cast<int32_t>(mode()); } if (levelwind_in_use && tether_elevation >= sim_params().min_levelwind_angle_for_tether_engagement) { is_engaged = true; } levelwind_engaged_.set_val(is_engaged); } void GroundStationV2Base::SetFromAvionicsPackets( const AvionicsPackets &avionics_packets) { const ControllerCommandMessage &cmd = avionics_packets.command_message; // The actual ground station reads from TetherDownMessage, so this isn't quite // proper. But the benefit of simulating the core switches assembling // TetherDownMessage is dubious. azi_cmd_target_.set_val(cmd.gs_azi_target); azi_cmd_dead_zone_.set_val(cmd.gs_azi_dead_zone); drum_linear_vel_cmd_from_wing_.set_val(cmd.winch_velocity); detwist_pos_cmd_from_wing_.set_val(cmd.detwist_position); mode_cmd_.set_val(static_cast<GroundStationMode>(cmd.gs_mode_request)); unpause_transform_.set_val(cmd.gs_unpause_transform); } void GroundStationV2Base::UpdateDerivedStates() { Mat3 dcm_vessel_to_platform; // The GSv2 platform azimuth is defined as a heading with respect to the // x-axis of the vessel frame. // The parameter azi_ref_offset is defined to be exactly zero. DCHECK_EQ(GetSystemParams()->ground_station.azi_ref_offset, 0.0); AngleToDcm(platform_azi(), 0.0, 0.0, kRotationOrderZyx, &dcm_vessel_to_platform); Vec3 platform_omega; Vec3Scale(&kVec3Z, platform_azi_vel(), &platform_omega); platform_frame_.set_val(ReferenceFrame(parent_frame_, kVec3Zero, kVec3Zero, dcm_vessel_to_platform, platform_omega)); dcm_v2p_.set_val(dcm_vessel_to_platform); // The winch drum frame's (wd) axes are aligned with the platform frame when // the drum angle is zero. wd0_frame_.set_val(ReferenceFrame(platform_frame_.val(), params_.drum_origin_p, kMat3Identity)); Mat3 dcm_wd0_to_wd; AngleToDcm(0.0, 0.0, drum_angle(), kRotationOrderZyx, &dcm_wd0_to_wd); Vec3 drum_omega_vector; Vec3Scale(&kVec3X, drum_omega(), &drum_omega_vector); wd_frame_.set_val(ReferenceFrame(wd0_frame_.val(), kVec3Zero, kVec3Zero, dcm_wd0_to_wd, drum_omega_vector)); Mat3 dcm_wd_to_gsg0; CalcDcmWdToGsg0(params_.detwist_elevation, detwist_angle(), &dcm_wd_to_gsg0); gsg0_frame_.set_val( ReferenceFrame(wd_frame_.val(), params_.gsg_pos_drum, dcm_wd_to_gsg0)); panel_frame_.set_val(ReferenceFrame(platform_frame_.val(), sim_params().panel.origin_pos_p, sim_params().panel.dcm_p2panel)); } void GroundStationV2::UpdateModeControllerCommands() { switch (mode()) { case kGroundStationModeReel: azi_vel_cmd_.set_val(reel_controller_.azi_vel_cmd()); drum_vel_cmd_.set_val(reel_controller_.drum_vel_cmd()); detwist_vel_.set_val(0.0); break; case kGroundStationModeTransform: azi_vel_cmd_.set_val(transform_controller_.azi_vel_cmd()); drum_vel_cmd_.set_val(transform_controller_.drum_vel_cmd()); detwist_vel_.set_val( Saturate(sim_params().detwist_angle_kp * (Wrap(Saturate(-drum_angle(), 0.0, sim_params().mclaren.detwist_setpoint) - detwist_angle(), -PI, PI)), -transform_controller_.detwist_max_vel(), transform_controller_.detwist_max_vel())); break; case kGroundStationModeHighTension: azi_vel_cmd_.set_val(high_tension_controller_.azi_vel_cmd()); drum_vel_cmd_.set_val(high_tension_controller_.drum_vel_cmd()); detwist_vel_.set_val(Saturate( sim_params().detwist_angle_kp * (Wrap( high_tension_controller_.detwist_pos_cmd() - detwist_angle(), -PI, PI)), -high_tension_controller_.detwist_max_vel(), high_tension_controller_.detwist_max_vel())); break; case kGroundStationModeManual: case kNumGroundStationModes: default: LOG(FATAL) << "Bad GS02 mode: " << static_cast<int32_t>(mode()); } } void GroundStationV2::AddInternalConnections(ConnectionStore *connections) { connections->Add(1, [this](double /*t*/) { UpdateModeControllerCommands(); UpdateDerivedStates(); }); } double GroundStationV2Base::CalcTetherFreeLength() const { return CalcTetherFreeLengthInternal(drum_angle()); } double GroundStationV2Base::CalcTetherFreeLengthInternal( double drum_angle__) const { double length = g_sys.tether->length; const Gs02DrumAngles &angles = GetSystemParams()->ground_station.gs02.drum_angles; // Racetrack. if (drum_angle__ < angles.racetrack_high) { length -= racetrack_integrator_.WrappedLength(drum_angle__); } // Wide wrap section. const double wide_wrap_high = angles.racetrack_low; if (drum_angle__ < wide_wrap_high) { length -= (wide_wrap_high - fmax(angles.wide_wrap_low, drum_angle__)) * Sqrt(Square(sim_params().dx_dtheta_wide_wrap) + Square(params_.drum_radius)); } // Main wrap section. const double main_wrap_high = angles.wide_wrap_low; if (drum_angle__ < main_wrap_high) { length -= (main_wrap_high - drum_angle__) * Sqrt(Square(sim_params().dx_dtheta_main_wrap) + Square(params_.drum_radius)); } DCHECK(length >= 0.0); return length; } double GroundStationV2Base::MinDrumAngle() const { const Gs02DrumAngles &drum_angles = GetSystemParams()->ground_station.gs02.drum_angles; double main_wrap_length = CalcTetherFreeLengthInternal(drum_angles.wide_wrap_low); double main_wrap_dtheta = main_wrap_length / Sqrt(Square(sim_params().dx_dtheta_main_wrap) + Square(params_.drum_radius)); return drum_angles.wide_wrap_low - main_wrap_dtheta; } void GroundStationV2Base::CalcTetherAnchorPosVelNed(Vec3 *pos_ned, Vec3 *vel_ned) const { const Gs02DrumAngles &angles = GetSystemParams()->ground_station.gs02.drum_angles; // If the drum angle is above racetrack_high, the anchor point is the GSG. if (drum_angle() > angles.racetrack_high) { wd_frame_.val().TransformTo(ned_frame_, ReferenceFrame::kPosition, params_.gsg_pos_drum, pos_ned); ReferenceFrame at_gsg(wd_frame_.val(), params_.gsg_pos_drum); at_gsg.TransformTo(ned_frame_, ReferenceFrame::kVelocity, kVec3Zero, vel_ned); return; } // We'll start at the GSG, and move along the wrapping. const double inner_radius = hypot(params_.gsg_pos_drum.y, params_.gsg_pos_drum.z); Vec3 pos_wd0 = {params_.gsg_pos_drum.x, 0.0, -inner_radius}; Vec3 vel_wd0 = kVec3Zero; // Racetrack. if (drum_angle() < angles.racetrack_high) { const double dx_dtheta = (params_.gsg_pos_drum.x - sim_params().wrap_start_posx_drum) / (angles.racetrack_high - angles.racetrack_low); const double dz_dtheta = (-inner_radius + params_.drum_radius) / (angles.racetrack_high - angles.racetrack_low); const double dtheta = fmax(drum_angle(), angles.racetrack_low) - angles.racetrack_high; pos_wd0.x += dx_dtheta * dtheta; pos_wd0.z += dz_dtheta * dtheta; vel_wd0.x = dx_dtheta * drum_omega(); vel_wd0.z = dz_dtheta * drum_omega(); } // Wide wrapping. const double wide_wrap_high = angles.racetrack_low; if (drum_angle() < wide_wrap_high) { const double dtheta = fmax(drum_angle(), angles.wide_wrap_low) - wide_wrap_high; pos_wd0.x += sim_params().dx_dtheta_wide_wrap * dtheta; vel_wd0.x = sim_params().dx_dtheta_wide_wrap * drum_omega(); vel_wd0.z = 0.0; } // Main wrapping. const double main_wrap_high = angles.wide_wrap_low; if (drum_angle() < main_wrap_high) { pos_wd0.x += sim_params().dx_dtheta_main_wrap * (drum_angle() - main_wrap_high); vel_wd0.x = sim_params().dx_dtheta_main_wrap; vel_wd0.z = 0.0; } wd0_frame_.val().TransformTo(ned_frame_, ReferenceFrame::kPosition, pos_wd0, pos_ned); ReferenceFrame anchor_frame(wd0_frame_.val(), pos_wd0); anchor_frame.TransformTo(ned_frame_, ReferenceFrame::kVelocity, vel_wd0, vel_ned); } void GroundStationV2Base::TetherDirToAngles(const Vec3 &tether_dir_v, double *tether_ele_v, double *tether_azi_v, double *gsg_yoke, double *gsg_termination) const { // TODO: Calibrate with real test data about where is the reference // angle (yoke=termination=0) pointing to. // Currently, the tether points away from the detwist plane along the -Z axis // of gsg0 frame when GSG yoke and termination are 0.0. +yoke rotates around // X axis and +termination rotates around Y axis. // The local frame (X'Y'Z') rotates the gsg0 frame (XYZ) by 90 deg // around Y-axis, so that the spherical azimuth (yoke) and elevation // (termination) are phi and -theta, where (phi, theta, 0) are euler angles // to rotate gsg0 frame to gsg2 frame in XYZ order. // X' Tether // X(Z') | / // \ | / // \ | / // \|/_____ Y(Y') // | // | // Z *tether_ele_v = VecVToElevation(&tether_dir_v); *tether_azi_v = VecVToAzimuth(&tether_dir_v); Mat3 dcm_gsg0_to_local; AngleToDcm(0.0, 0.5 * PI, 0.0, kRotationOrderZyx, &dcm_gsg0_to_local); ReferenceFrame local_frame(gsg0_frame(), kVec3Zero, dcm_gsg0_to_local); Vec3 tether_dir_local; parent_frame_.RotateTo(local_frame, tether_dir_v, &tether_dir_local); double r_unused; CartToSph(&tether_dir_local, gsg_yoke, gsg_termination, &r_unused); // The spherical elevation has the opposite sign of the rotational angle // around Y-axis. *gsg_termination = -*gsg_termination; } void GroundStationV2Base::Publish() const { sim_telem.gs02.azimuth = platform_azi(); sim_telem.gs02.azimuth_vel = platform_azi_vel(); sim_telem.gs02.dcm_v2p = dcm_v2p(); sim_telem.gs02.drum_angle = drum_angle(); sim_telem.gs02.drum_omega = drum_omega(); sim_telem.gs02.levelwind_engaged = levelwind_engaged(); } void GroundStationV2::Publish() const { GroundStationV2Base::Publish(); sim_telem.gs02.mclaren_azi_vel_cmd = azi_vel_cmd_.val(); sim_telem.gs02.mclaren_drum_vel_cmd = drum_vel_cmd_.val(); sim_telem.gs02.mode = static_cast<int32_t>(mode()); sim_telem.gs02.detwist_vel = detwist_vel_.val(); sim_telem.gs02.detwist_angle = Wrap(detwist_angle_.val(), 0, PI * 2.0 * static_cast<double>(TETHER_DETWIST_REVS)); sim_telem.gs02.n_state_machine = high_tension_controller_.n_state_machine(); sim_telem.gs02.n_hpu_mode = high_tension_controller_.n_hpu_mode(); sim_telem.gs02.brake_torque = high_tension_controller_.brake_torque(); sim_telem.gs02.brake_torque_cmd = high_tension_controller_.brake_torque_cmd(); sim_telem.gs02.tether_torque = high_tension_controller_.tether_torque(); sim_telem.gs02.total_torque = high_tension_controller_.total_torque(); sim_telem.gs02.azi_velocity_dir = high_tension_controller_.azi_velocity_dir(); sim_telem.gs02.a_error = high_tension_controller_.a_error(); sim_telem.gs02.wing_azi = high_tension_controller_.wing_azi_val(); sim_telem.gs02.gs_azi = high_tension_controller_.azi_pos_val(); for (const Model *m : sub_models_) { m->Publish(); } } GroundStationV2::GroundStationV2(const ReferenceFrame &ned_frame, const ReferenceFrame &parent_frame, const Gs02Params &params, const Gs02SimParams &sim_params__) : GroundStationV2Base(ned_frame, parent_frame, params, sim_params__), reel_controller_(sim_params__.mclaren, params.drum_radius), transform_controller_(sim_params__.mclaren), high_tension_controller_(sim_params__.mclaren), platform_azi_(new_continuous_state(), "platform_azi", 0.0), platform_azi_vel_(new_continuous_state(), "platform_azi_vel", 0.0), drum_angle_(new_continuous_state(), "drum_angle", 0.0), detwist_angle_(new_continuous_state(), "detwist_angle", sim_params__.mclaren.detwist_setpoint), drum_omega_(new_continuous_state(), "drum_omega", 0.0), ddrum_omega_dt_(new_continuous_state(), "ddrum_omega_dt", 0.0), azi_vel_cmd_(new_derived_value(), "azi_vel_cmd"), drum_vel_cmd_(new_derived_value(), "drum_vel_cmd"), detwist_vel_(new_derived_value(), "detwist_vel"), mode_z1_(new_discrete_state(), "mode_z1", 0.0, kGroundStationModeReel), ht2reel_(new_discrete_state(), "ht2reel", 0.0, false), prox_sensor_active_(new_discrete_state(), "prox_sensor_active", 0.0, false) { set_sub_models( {&reel_controller_, &transform_controller_, &high_tension_controller_}); UpdateDerivedStates(); SetupDone(); } void GroundStationV2::CalcDerivHelper(double /*t*/) { platform_azi_.set_deriv(platform_azi_vel()); platform_azi_vel_.set_deriv(sim_params().azi_accel_kp * (azi_vel_cmd_.val() - platform_azi_vel())); const double omega_n = sim_params().winch_drive_natural_freq; const double zeta = sim_params().winch_drive_damping_ratio; ddrum_omega_dt_.set_deriv(Square(omega_n) * (drum_vel_cmd_.val() - drum_omega()) - 2.0 * zeta * omega_n * ddrum_omega_dt_.val()); drum_omega_.set_deriv(ddrum_omega_dt_.val()); drum_angle_.set_deriv(drum_omega()); detwist_angle_.set_deriv(detwist_vel_.val()); } void GroundStationV2::DiscreteStepHelper(double t) { // Update mode. switch (mode()) { case kGroundStationModeReel: if (mode_cmd() == kGroundStationModeHighTension) { set_mode(t, kGroundStationModeTransform); ht2reel_.DiscreteUpdate(t, false); } break; case kGroundStationModeHighTension: if (mode_cmd() == kGroundStationModeReel) { set_mode(t, kGroundStationModeTransform); ht2reel_.DiscreteUpdate(t, true); } break; case kGroundStationModeTransform: if (transform_controller_.transform_complete()) { set_mode(t, ht2reel_.val() ? kGroundStationModeReel : kGroundStationModeHighTension); } break; case kGroundStationModeManual: case kNumGroundStationModes: default: LOG(FATAL) << "Bad GS02 mode: " << static_cast<int32_t>(mode()); } DCHECK(azi_cmd_target() >= 0.0 && azi_cmd_target() <= 2.0 * M_PI); reel_controller_.SetCommonInputs(t, platform_azi(), platform_azi_vel(), drum_angle(), drum_omega(), azi_cmd_target()); transform_controller_.SetCommonInputs(t, platform_azi(), platform_azi_vel(), drum_angle(), drum_omega(), azi_cmd_target()); high_tension_controller_.SetCommonInputs(t, platform_azi(), platform_azi_vel(), drum_angle(), drum_omega(), azi_cmd_target()); // Apply mode- and controller-specific inputs. switch (mode()) { case kGroundStationModeReel: reel_controller_.Enable(t); transform_controller_.Disable(t); high_tension_controller_.Disable(t); reel_controller_.set_azi_cmd_dead_zone(t, azi_cmd_dead_zone()); reel_controller_.set_drum_linear_vel_cmd_from_wing( t, drum_linear_vel_cmd_from_wing()); reel_controller_.set_levelwind_engaged(t, levelwind_engaged()); set_transform_stage(t, 0); break; case kGroundStationModeTransform: transform_controller_.Enable(t); reel_controller_.Disable(t); high_tension_controller_.Disable(t); set_transform_stage(t, transform_controller_.stage()); transform_controller_.set_unpause_transform(t, unpause_transform()); if (mode() != mode_z1_.val()) { transform_controller_.StartTransform(t, ht2reel_.val()); } break; case kGroundStationModeHighTension: high_tension_controller_.set_tether_torque(t, gsg_pos_p(), tether_force_p()); high_tension_controller_.Enable(t); transform_controller_.Disable(t); reel_controller_.Disable(t); high_tension_controller_.set_detwist_pos_cmd_from_wing( t, Wrap(detwist_pos_cmd_from_wing(), -PI, PI)); set_transform_stage(t, 0); break; case kGroundStationModeManual: case kNumGroundStationModes: default: LOG(FATAL) << "Bad GS02 mode: " << static_cast<int32_t>(mode()); } mode_z1_.DiscreteUpdate(t, mode()); // The proximity sensor activates when a sufficient portion of the tether has // been reeled in. prox_sensor_active_.DiscreteUpdate( t, CalcTetherFreeLength() < sim_params().prox_sensor_tether_free_length); } HitlGroundStationV2::HitlGroundStationV2(const ReferenceFrame &ned_frame, const ReferenceFrame &parent_frame, const Gs02Params &params, const Gs02SimParams &sim_params__) : GroundStationV2Base(ned_frame, parent_frame, params, sim_params__), platform_azi_(new_continuous_state(), "platform_azi", 0.0), platform_azi_vel_(new_continuous_state(), "platform_azi_vel", 0.0), dplatform_azi_(new_discrete_state(), "dplatform_azi", 0.0, 0.0), dplatform_azi_vel_(new_discrete_state(), "dplatform_azi_vel", 0.0, 0.0), int_err_platform_azi_(new_discrete_state(), "int_err_platform_azi", 0.0, 0.0), drum_angle_(new_continuous_state(), "drum_angle", 0.0), drum_angle_vel_(new_continuous_state(), "drum_angle_vel", 0.0), ddrum_angle_(new_discrete_state(), "ddrum_angle", 0.0, 0.0), ddrum_angle_vel_(new_discrete_state(), "ddrum_angle_vel", 0.0, 0.0), detwist_angle_vel_(new_continuous_state(), "detwist_angle_vel", 0.0), ddetwist_angle_(new_discrete_state(), "ddetwist_angle", 0.0, 0.0), ddetwist_angle_vel_(new_discrete_state(), "ddetwist_angle_vel", 0.0, 0.0), int_err_drum_angle_(new_discrete_state(), "int_err_drum_angle", 0.0, 0.0), detwist_angle_(new_continuous_state(), "detwist_angle", 0.0), prox_sensor_active_(new_discrete_state(), "prox_sensor_active", 0.0, false), actual_mode_(new_derived_value(), "actual_mode", kGroundStationModeReel), actual_transform_stage_(new_derived_value(), "actual_transform_stage", 0), actual_platform_azi_(new_derived_value(), "actual_platform_azi", 0.0), actual_drum_angle_(new_derived_value(), "actual_drum_angle", 0.0), actual_detwist_angle_(new_derived_value(), "actual_detwist_angle", 0.0), actual_prox_sensor_active_(new_derived_value(), "actual_prox_sensor_active", 0.0) { UpdateDerivedStates(); SetupDone(); } void HitlGroundStationV2::Init(double azimuth, double drum_angle__) { platform_azi_.Clear(); platform_azi_.set_val(azimuth); platform_azi_vel_.Clear(); platform_azi_vel_.set_val(0.0); drum_angle_.Clear(); drum_angle_.set_val(drum_angle__); drum_angle_vel_.Clear(); drum_angle_vel_.set_val(0.0); detwist_angle_.Clear(); detwist_angle_.set_val(0.0); detwist_angle_vel_.Clear(); detwist_angle_vel_.set_val(0.0); ClearDerivedValues(); UpdateDerivedStates(); } void HitlGroundStationV2::SetFromAvionicsPackets( const AvionicsPackets &avionics_packets) { GroundStationV2Base::SetFromAvionicsPackets(avionics_packets); if (avionics_packets.ground_station_status_valid) { const auto &gs = avionics_packets.ground_station_status.status; actual_mode_.set_val(static_cast<GroundStationMode>(gs.mode)); actual_transform_stage_.set_val(gs.transform_stage); actual_platform_azi_.set_val(gs.azimuth.position); actual_drum_angle_.set_val(gs.winch.position); actual_prox_sensor_active_.set_val(gs.bridle_proximity.proximity); actual_detwist_angle_.set_val(gs.detwist.position); } else { // The ground station status is not valid if we've never received it. In // that event, set the "actual" value to the current model values, so we // don't attempt to control a signal to a bogus data point. actual_mode_.set_val(mode()); actual_transform_stage_.set_val(transform_stage()); actual_platform_azi_.set_val(platform_azi_.val()); actual_drum_angle_.set_val(drum_angle_.val()); actual_prox_sensor_active_.set_val(prox_sensor_active()); actual_detwist_angle_.set_val(detwist_angle()); } } void HitlGroundStationV2::DiscreteStepHelper(double t) { set_mode(t, actual_mode_.val()); set_transform_stage(t, actual_transform_stage_.val()); // The model's platform azimuth and drum angle both track the actual signals // by way of a simple second-order transfer function. Doing so keeps // derivatives of these quantities reasonable as the simulator tracks reality. // // The transfer function is artifical, so we encode it here rather than // parameterizing it in a config file. double wn = 50.0; double zeta = 1.0; { // Platform azimuth. double err = actual_platform_azi_.val() - platform_azi_.val(); dplatform_azi_.DiscreteUpdate(t, platform_azi_vel_.val()); dplatform_azi_vel_.DiscreteUpdate( t, err * wn * wn - 2.0 * zeta * wn * platform_azi_vel_.val()); } { // Drum angle. double err = actual_drum_angle_.val() - drum_angle_.val(); ddrum_angle_.DiscreteUpdate(t, drum_angle_vel_.val()); ddrum_angle_vel_.DiscreteUpdate( t, err * wn * wn - 2.0 * zeta * wn * drum_angle_vel_.val()); } { // Detwist angle. double err = actual_detwist_angle_.val() - detwist_angle_.val(); ddetwist_angle_.DiscreteUpdate(t, detwist_angle_vel_.val()); ddetwist_angle_vel_.DiscreteUpdate( t, err * wn * wn - 2.0 * zeta * wn * detwist_angle_vel_.val()); } prox_sensor_active_.DiscreteUpdate(t, actual_prox_sensor_active_.val()); } void HitlGroundStationV2::CalcDerivHelper(double /*t*/) { platform_azi_.set_deriv(dplatform_azi_.val()); platform_azi_vel_.set_deriv(dplatform_azi_vel_.val()); drum_angle_.set_deriv(ddrum_angle_.val()); drum_angle_vel_.set_deriv(ddrum_angle_vel_.val()); detwist_angle_.set_deriv(ddetwist_angle_.val()); detwist_angle_vel_.set_deriv(ddetwist_angle_vel_.val()); } void HitlGroundStationV2::AddInternalConnections(ConnectionStore *connections) { connections->Add(1, [this](double /*t*/) { UpdateDerivedStates(); }); }
41.387365
80
0.685834
84459f68a60fdf2e0000ed96d3ea03669d0acbe6
4,547
cpp
C++
Sankore-3.1/src/domain/UBItem.cpp
eaglezzb/rsdc
cce881f6542ff206bf286cf798c8ec8da3b51d50
[ "MIT" ]
null
null
null
Sankore-3.1/src/domain/UBItem.cpp
eaglezzb/rsdc
cce881f6542ff206bf286cf798c8ec8da3b51d50
[ "MIT" ]
null
null
null
Sankore-3.1/src/domain/UBItem.cpp
eaglezzb/rsdc
cce881f6542ff206bf286cf798c8ec8da3b51d50
[ "MIT" ]
null
null
null
/* * Copyright (C) 2010-2013 Groupement d'Intérêt Public pour l'Education Numérique en Afrique (GIP ENA) * * This file is part of Open-Sankoré. * * Open-Sankoré 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, version 3 of the License, * with a specific linking exception for the OpenSSL project's * "OpenSSL" library (or with modified versions of it that use the * same license as the "OpenSSL" library). * * Open-Sankoré 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 Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. */ #include "UBItem.h" #include "core/memcheck.h" #include "domain/UBGraphicsPixmapItem.h" #include "domain/UBGraphicsTextItem.h" #include "domain/UBGraphicsSvgItem.h" #include "domain/UBGraphicsMediaItem.h" #include "domain/UBGraphicsStrokesGroup.h" #include "domain/UBGraphicsGroupContainerItem.h" #include "domain/UBGraphicsWidgetItem.h" #include "domain/UBEditableGraphicsPolygonItem.h" #include "domain/UBEditableGraphicsRegularShapeItem.h" #include "domain/UBGraphicsEllipseItem.h" #include "domain/UBGraphicsRectItem.h" #include "domain/UBGraphicsLineItem.h" #include "domain/UBGraphicsFreehandItem.h" #include "tools/UBGraphicsCurtainItem.h" UBItem::UBItem() : mUuid(QUuid()) , mRenderingQuality(UBItem::RenderingQualityNormal) { // NOOP } UBItem::~UBItem() { // NOOP } UBGraphicsItem::~UBGraphicsItem() { if (mDelegate!=NULL){ delete mDelegate; mDelegate = NULL; } } void UBGraphicsItem::setDelegate(UBGraphicsItemDelegate* delegate) { Q_ASSERT(mDelegate==NULL); mDelegate = delegate; } void UBGraphicsItem::assignZValue(QGraphicsItem *item, qreal value) { item->setZValue(value); item->setData(UBGraphicsItemData::ItemOwnZValue, value); } bool UBGraphicsItem::isFlippable(QGraphicsItem *item) { return item->data(UBGraphicsItemData::ItemFlippable).toBool(); } bool UBGraphicsItem::isRotatable(QGraphicsItem *item) { return item->data(UBGraphicsItemData::ItemRotatable).toBool(); } bool UBGraphicsItem::isLocked(QGraphicsItem *item) { return item->data(UBGraphicsItemData::ItemLocked).toBool(); } QUuid UBGraphicsItem::getOwnUuid(QGraphicsItem *item) { QString idCandidate = item->data(UBGraphicsItemData::ItemUuid).toString(); return idCandidate == QUuid().toString() ? QUuid() : QUuid(idCandidate); } qreal UBGraphicsItem::getOwnZValue(QGraphicsItem *item) { return item->data(UBGraphicsItemData::ItemOwnZValue).toReal(); } void UBGraphicsItem::remove(bool canUndo) { if (Delegate() && !Delegate()->isLocked()) Delegate()->remove(canUndo); } UBGraphicsItemDelegate *UBGraphicsItem::Delegate(QGraphicsItem *pItem) { UBGraphicsItemDelegate *result = 0; switch (static_cast<int>(pItem->type())) { case UBGraphicsPixmapItem::Type : result = (static_cast<UBGraphicsPixmapItem*>(pItem))->Delegate(); break; case UBGraphicsTextItem::Type : result = (static_cast<UBGraphicsTextItem*>(pItem))->Delegate(); break; case UBGraphicsSvgItem::Type : result = (static_cast<UBGraphicsSvgItem*>(pItem))->Delegate(); break; case UBGraphicsMediaItem::Type: result = (static_cast<UBGraphicsMediaItem*>(pItem))->Delegate(); break; case UBGraphicsStrokesGroup::Type : result = (static_cast<UBGraphicsStrokesGroup*>(pItem))->Delegate(); break; case UBGraphicsGroupContainerItem::Type : result = (static_cast<UBGraphicsGroupContainerItem*>(pItem))->Delegate(); break; case UBGraphicsWidgetItem::Type : result = (static_cast<UBGraphicsWidgetItem*>(pItem))->Delegate(); break; case UBGraphicsCurtainItem::Type : result = (static_cast<UBGraphicsCurtainItem*>(pItem))->Delegate(); break; case UBEditableGraphicsRegularShapeItem::Type : case UBEditableGraphicsPolygonItem::Type : case UBGraphicsFreehandItem::Type : case UBGraphicsItemType::GraphicsShapeItemType : UBAbstractGraphicsItem* item = dynamic_cast<UBAbstractGraphicsItem*>(pItem); if (item) result = item->Delegate(); break; } return result; }
30.516779
102
0.720475
844620b796aba499ce01fcbcbd13774f592a3af7
1,917
cpp
C++
src/renderer/components/RectComponent.cpp
artfulbytes/sumobot_simulator
f2784d2ff506759019d7d5e840bd7aed591a0add
[ "MIT" ]
null
null
null
src/renderer/components/RectComponent.cpp
artfulbytes/sumobot_simulator
f2784d2ff506759019d7d5e840bd7aed591a0add
[ "MIT" ]
null
null
null
src/renderer/components/RectComponent.cpp
artfulbytes/sumobot_simulator
f2784d2ff506759019d7d5e840bd7aed591a0add
[ "MIT" ]
null
null
null
#include "components/RectComponent.h" #include "Renderer.h" #include "components/Transforms.h" #include "TexCoords.h" #include "Texture.h" #include "SpriteAnimation.h" RectComponent::RectComponent(const RectTransform *transform, const glm::vec4& color) : m_quadTransform(transform), m_color(color) { } RectComponent::RectComponent(const RectTransform *transform, const std::string &textureName, SpriteAnimation *spriteAnimation) : m_quadTransform(transform), m_texture(std::make_unique<Texture>(textureName)), m_texCoords(std::make_unique<TexCoords>()), m_spriteAnimation(spriteAnimation) { } RectComponent::RectComponent(const CircleTransform *transform, const std::string &textureName, SpriteAnimation *spriteAnimation) : m_circleTransform(transform), m_texture(std::make_unique<Texture>(textureName)), m_texCoords(std::make_unique<TexCoords>()), m_spriteAnimation(spriteAnimation) { } RectComponent::~RectComponent() { } void RectComponent::onFixedUpdate() { if (m_enabled == false) { return; } if (m_spriteAnimation != nullptr) { m_spriteAnimation->onFixedUpdate(); m_spriteAnimation->computeTexCoords(*m_texCoords); } glm::vec2 size; glm::vec2 position; float rotation = 0.0f; if (m_quadTransform != nullptr) { size = m_quadTransform->size; position = m_quadTransform->position; rotation = m_quadTransform->rotation; } else if (m_circleTransform != nullptr) { size = glm::vec2{ 2 * m_circleTransform->radius, 2 * m_circleTransform->radius }; position = m_circleTransform->position; rotation = m_circleTransform->rotation; } else { assert(0); } if (m_texture) { Renderer::drawRect(position, size, rotation, *m_texture.get(), m_texCoords.get()); } else { Renderer::drawRect(position, size, rotation, m_color); } }
29.045455
130
0.695357
8446b534ea042ba69efdfb5ac4c427e47710ad33
5,067
cpp
C++
src/imports/cvkb/vkbquickmodel.cpp
CELLINKAB/qtcvkb
5b870f8ea4b42480eb678b065778de5dab36b199
[ "MIT" ]
null
null
null
src/imports/cvkb/vkbquickmodel.cpp
CELLINKAB/qtcvkb
5b870f8ea4b42480eb678b065778de5dab36b199
[ "MIT" ]
null
null
null
src/imports/cvkb/vkbquickmodel.cpp
CELLINKAB/qtcvkb
5b870f8ea4b42480eb678b065778de5dab36b199
[ "MIT" ]
null
null
null
/* * The MIT License (MIT) * * Copyright (C) 2020 CELLINK AB <info@cellink.com> * * 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 "vkbquickmodel.h" #include "vkbquickdelegate.h" #include "vkbquicklayout.h" #include "vkbquickpopup.h" #include <QtQml/qqmlcomponent.h> #include <QtQml/qqmlcontext.h> #include <QtQml/qqmlengine.h> #include <QtQuickTemplates2/private/qquickabstractbutton_p.h> VkbQuickModel::VkbQuickModel(QObject *parent) : QObject(parent) { } QQmlListProperty<VkbQuickDelegate> VkbQuickModel::delegates() { return QQmlListProperty<VkbQuickDelegate>(this, nullptr, delegates_append, delegates_count, delegates_at, delegates_clear); } VkbQuickDelegate *VkbQuickModel::findDelegate(Qt::Key key) const { auto it = std::find_if(m_delegates.cbegin(), m_delegates.cend(), [&key](VkbQuickDelegate *delegate) { return delegate->key() == key; }); if (it != m_delegates.cend()) return *it; if (key != Qt::Key_unknown) return findDelegate(Qt::Key_unknown); return nullptr; } template <typename T> static T *beginCreate(const VkbInputKey &key, QQmlComponent *component, QObject *parent) { if (!component) return nullptr; QQmlContext *creationContext = component->creationContext(); if (!creationContext) creationContext = qmlContext(parent); QQmlContext *context = new QQmlContext(creationContext, parent); QObject *instance = component->beginCreate(context); T *object = qobject_cast<T *>(instance); if (!object) { delete instance; return nullptr; } VkbQuickLayoutAttached *attached = VkbQuickLayout::qmlAttachedPropertiesObject(instance); if (attached) attached->setInputKey(key); return object; } QQuickAbstractButton *VkbQuickModel::createButton(const VkbInputKey &key, QQuickItem *parent) const { VkbQuickDelegate *delegate = findDelegate(key.key); if (!delegate) return nullptr; QQmlComponent *component = delegate->button(); QQuickAbstractButton *button = beginCreate<QQuickAbstractButton>(key, component, parent); if (!button) { qWarning() << "VkbQuickModel::createButton: button delegate for" << key.key << "is not a Button"; return nullptr; } button->setParentItem(parent); button->setFocusPolicy(Qt::NoFocus); button->setAutoRepeat(key.autoRepeat); button->setCheckable(key.checkable); if (key.checked) button->setChecked(true); component->completeCreate(); return button; } VkbQuickPopup *VkbQuickModel::createPopup(const VkbInputKey &key, QQuickAbstractButton *button) const { VkbQuickDelegate *delegate = findDelegate(key.key); if (!delegate) return nullptr; QQmlComponent *component = delegate->popup(); VkbQuickPopup *popup = beginCreate<VkbQuickPopup>(key, component, button); if (!popup) { qWarning() << "VkbQuickModel::createPopup: popup delegate for" << key.key << "is not an InputPopup"; return nullptr; } popup->setParentItem(button); popup->setAlt(key.alt); component->completeCreate(); return popup; } void VkbQuickModel::delegates_append(QQmlListProperty<VkbQuickDelegate> *property, VkbQuickDelegate *delegate) { VkbQuickModel *that = static_cast<VkbQuickModel *>(property->object); that->m_delegates.append(delegate); emit that->delegatesChanged(); } int VkbQuickModel::delegates_count(QQmlListProperty<VkbQuickDelegate> *property) { VkbQuickModel *that = static_cast<VkbQuickModel *>(property->object); return that->m_delegates.count(); } VkbQuickDelegate *VkbQuickModel::delegates_at(QQmlListProperty<VkbQuickDelegate> *property, int index) { VkbQuickModel *that = static_cast<VkbQuickModel *>(property->object); return that->m_delegates.value(index); } void VkbQuickModel::delegates_clear(QQmlListProperty<VkbQuickDelegate> *property) { VkbQuickModel *that = static_cast<VkbQuickModel *>(property->object); that->m_delegates.clear(); emit that->delegatesChanged(); }
34.705479
140
0.727452
84497ae9875b5463168efd697efe59406a255318
13,416
cc
C++
pigasus/software/src/file_api/file_identifier.cc
zhipengzhaocmu/fpga2022_artifact
0ac088a5b04c5c75ae6aef25202b66b0f674acd3
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
null
null
null
pigasus/software/src/file_api/file_identifier.cc
zhipengzhaocmu/fpga2022_artifact
0ac088a5b04c5c75ae6aef25202b66b0f674acd3
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
null
null
null
pigasus/software/src/file_api/file_identifier.cc
zhipengzhaocmu/fpga2022_artifact
0ac088a5b04c5c75ae6aef25202b66b0f674acd3
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
null
null
null
//-------------------------------------------------------------------------- // Copyright (C) 2014-2018 Cisco and/or its affiliates. All rights reserved. // Copyright (C) 2012-2013 Sourcefire, Inc. // // This program is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License Version 2 as published // by the Free Software Foundation. You may not use, modify or distribute // this program under any other version of the GNU General Public License. // // 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., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. //-------------------------------------------------------------------------- /* ** Author(s): Hui Cao <huica@cisco.com> ** ** NOTES ** 5.25.2012 - Initial Source Code. Hcao */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "file_identifier.h" #include <algorithm> #include <cassert> #include "log/messages.h" #include "utils/util.h" #ifdef UNIT_TEST #include "catch/snort_catch.h" #endif using namespace snort; struct MergeNode { IdentifierNode* shared_node; /*the node that is shared*/ IdentifierNode* append_node; /*the node that is added*/ } ; void FileMagicData::clear() { content_str.clear(); content.clear(); offset = 0; } void FileMagicRule::clear() { rev = 0; message.clear(); type.clear(); id = 0; category.clear(); version.clear(); groups.clear(); file_magics.clear(); } void FileIdentifier::init_merge_hash() { identifier_merge_hash = snort::ghash_new(1000, sizeof(MergeNode), 0, nullptr); assert(identifier_merge_hash); } FileIdentifier::~FileIdentifier() { /*Release memory used for identifiers*/ for (auto mem_block:id_memory_blocks) { snort_free(mem_block); } if (identifier_merge_hash != nullptr) { ghash_delete(identifier_merge_hash); } } void* FileIdentifier::calloc_mem(size_t size) { void* ret = snort_calloc(size); memory_used += size; /*For memory management*/ id_memory_blocks.emplace_back(ret); return ret; } void FileIdentifier::set_node_state_shared(IdentifierNode* start) { unsigned int i; if (!start) return; if (start->state == ID_NODE_SHARED) return; if (start->state == ID_NODE_USED) start->state = ID_NODE_SHARED; else start->state = ID_NODE_USED; for (i = 0; i < MAX_BRANCH; i++) set_node_state_shared(start->next[i]); } /*Clone a trie*/ IdentifierNode* FileIdentifier::clone_node(IdentifierNode* start) { unsigned int index; IdentifierNode* node; if (!start) return nullptr; node = (IdentifierNode*)calloc_mem(sizeof(*node)); node->offset = start->offset; node->type_id = start->type_id; for (index = 0; index < MAX_BRANCH; index++) { if (start->next[index]) { node->next[index] = start->next[index]; } } return node; } IdentifierNode* FileIdentifier::create_trie_from_magic(FileMagicRule& rule, uint32_t type_id) { IdentifierNode* current; IdentifierNode* root = nullptr; if (rule.file_magics.empty() || !type_id) return nullptr; /* Content magics are sorted based on offset, this * will help compile the file magic trio */ std::sort(rule.file_magics.begin(),rule.file_magics.end()); current = (IdentifierNode*)calloc_mem(sizeof(*current)); current->state = ID_NODE_NEW; root = current; for (auto magic:rule.file_magics) { unsigned int i; current->offset = magic.offset; for (i = 0; i < magic.content.size(); i++) { IdentifierNode* node = (IdentifierNode*)calloc_mem(sizeof(*node)); uint8_t index = magic.content[i]; node->offset = magic.offset + i + 1; node->state = ID_NODE_NEW; current->next[index] = node; current = node; } } /*Last node has type name*/ current->type_id = type_id; return root; } /*This function examines whether to update the trie based on shared state*/ bool FileIdentifier::update_next(IdentifierNode* start,IdentifierNode** next_ptr, IdentifierNode* append) { IdentifierNode* next = (*next_ptr); MergeNode merge_node; IdentifierNode* result; if (!append || (next == append)) return false; merge_node.append_node = append; merge_node.shared_node = next; if (!next) { /*reuse the append*/ *next_ptr = append; set_node_state_shared(append); return false; } else if ((result = (IdentifierNode*)ghash_find(identifier_merge_hash, &merge_node))) { /*the same pointer has been processed, reuse it*/ *next_ptr = result; set_node_state_shared(result); return false; } else { if ((start->offset < append->offset) && (next->offset > append->offset)) { /*offset could have gap when non 0 offset is allowed */ unsigned int index; IdentifierNode* node = (IdentifierNode*)calloc_mem(sizeof(*node)); merge_node.shared_node = next; merge_node.append_node = append; node->offset = append->offset; for (index = 0; index < MAX_BRANCH; index++) { node->next[index] = next; } set_node_state_shared(next); next = node; ghash_add(identifier_merge_hash, &merge_node, next); } else if (next->state == ID_NODE_SHARED) { /*shared, need to clone one*/ IdentifierNode* current_next = next; merge_node.shared_node = current_next; merge_node.append_node = append; next = clone_node(current_next); set_node_state_shared(next); ghash_add(identifier_merge_hash, &merge_node, next); } *next_ptr = next; } return true; } /* * Append magic to existing trie */ void FileIdentifier::update_trie(IdentifierNode* start, IdentifierNode* append) { unsigned int i; if ((!start )||(!append)||(start == append)) return; if (start->offset == append->offset ) { /* when we come here, make sure this tree is not shared * Update start trie using append information*/ assert(start->state != ID_NODE_SHARED); if (append->type_id) { if (start->type_id) ParseWarning(WARN_RULES, "Duplicated type definition '%u -> %u at offset %u", start->type_id, append->type_id, append->offset); start->type_id = append->type_id; } for (i = 0; i < MAX_BRANCH; i++) { if (update_next(start,&start->next[i], append->next[i])) { update_trie(start->next[i], append->next[i]); } } } else if (start->offset < append->offset ) { for (i = 0; i < MAX_BRANCH; i++) { if (update_next(start,&start->next[i], append)) update_trie(start->next[i], append); } } } void FileIdentifier::insert_file_rule(FileMagicRule& rule) { IdentifierNode* node; if (!identifier_root) { identifier_root = (IdentifierNode*)calloc_mem(sizeof(*identifier_root)); init_merge_hash(); } if (rule.id >= FILE_ID_MAX) { ParseError("file type: rule id %u exceeds max id of %d", rule.id, FILE_ID_MAX-1); return; } if (file_magic_rules[rule.id].id > 0) { ParseError("file type: duplicated rule id %u defined", rule.id); return; } file_magic_rules[rule.id] = rule; node = create_trie_from_magic(rule, rule.id); update_trie(identifier_root, node); } /* * This is the main function to find file type * Find file type is to traverse the tries. * Context is saved to continue file type identification as data becomes available */ uint32_t FileIdentifier::find_file_type_id(const uint8_t* buf, int len, uint64_t file_offset, void** context) { uint32_t file_type_id = SNORT_FILE_TYPE_CONTINUE; assert(context); if ( !buf || len <= 0 ) return SNORT_FILE_TYPE_CONTINUE; if (!(*context)) *context = (void*)(identifier_root); IdentifierNode* current = (IdentifierNode*)(*context); uint64_t end = file_offset + len; while (current && (current->offset >= file_offset)) { /*Found file id, save and continue*/ if (current->type_id) { file_type_id = current->type_id; } if ( current->offset >= end ) { /* Save current state */ *context = current; if (file_type_id) return file_type_id; else return SNORT_FILE_TYPE_CONTINUE; } /*Move to the next level*/ current = current->next[buf[current->offset - file_offset ]]; } /*Either end of magics or passed the current offset*/ *context = nullptr; if ( file_type_id == SNORT_FILE_TYPE_CONTINUE ) file_type_id = SNORT_FILE_TYPE_UNKNOWN; return file_type_id; } FileMagicRule* FileIdentifier::get_rule_from_id(uint32_t id) { if ((id < FILE_ID_MAX) && (file_magic_rules[id].id > 0)) { return (&(file_magic_rules[id])); } else return nullptr; } void FileIdentifier::get_magic_rule_ids_from_type(const std::string& type, const std::string& version, snort::FileTypeBitSet& ids_set) { ids_set.reset(); for (uint32_t i = 0; i < FILE_ID_MAX; i++) { if (type == file_magic_rules[i].type) { if (version.empty() or version == file_magic_rules[i].version) { ids_set.set(file_magic_rules[i].id); } } } } //-------------------------------------------------------------------------- // unit tests //-------------------------------------------------------------------------- #ifdef UNIT_TEST TEST_CASE ("FileIdMemory", "[FileMagic]") { FileIdentifier rc; CHECK(rc.memory_usage() == 0); } TEST_CASE ("FileIdRulePDF", "[FileMagic]") { FileMagicData magic; magic.content = "PDF"; magic.offset = 0; FileMagicRule rule; rule.type = "pdf"; rule.file_magics.emplace_back(magic); rule.id = 1; FileIdentifier rc; rc.insert_file_rule(rule); const char* data = "PDF"; void* context = nullptr; CHECK(rc.find_file_type_id((const uint8_t*)data, strlen(data), 0, &context) == 1); } TEST_CASE ("FileIdRuleUnknow", "[FileMagic]") { FileMagicData magic; magic.content = "PDF"; magic.offset = 0; FileMagicRule rule; rule.type = "pdf"; rule.file_magics.emplace_back(magic); rule.id = 1; FileIdentifier rc; rc.insert_file_rule(rule); const char* data = "DDF"; void* context = nullptr; CHECK((rc.find_file_type_id((const uint8_t*)data, strlen(data), 0, &context) == SNORT_FILE_TYPE_UNKNOWN)); } TEST_CASE ("FileIdRuleEXE", "[FileMagic]") { FileMagicData magic; magic.content = "PDF"; magic.offset = 0; FileMagicRule rule; rule.type = "exe"; rule.file_magics.emplace_back(magic); rule.id = 1; FileIdentifier rc; rc.insert_file_rule(rule); magic.clear(); magic.content = "EXE"; magic.offset = 0; rule.clear(); rule.type = "exe"; rule.file_magics.emplace_back(magic); rule.id = 3; rc.insert_file_rule(rule); const char* data = "PDFooo"; void* context = nullptr; CHECK(rc.find_file_type_id((const uint8_t*)data, strlen(data), 0, &context) == 1); } TEST_CASE ("FileIdRulePDFEXE", "[FileMagic]") { FileMagicData magic; magic.content = "PDF"; magic.offset = 0; FileMagicRule rule; rule.type = "exe"; rule.file_magics.emplace_back(magic); rule.id = 1; FileIdentifier rc; rc.insert_file_rule(rule); magic.clear(); magic.content = "EXE"; magic.offset = 3; rule.clear(); rule.type = "exe"; rule.file_magics.emplace_back(magic); rule.id = 3; rc.insert_file_rule(rule); const char* data = "PDFEXE"; void* context = nullptr; // Match the last one CHECK((rc.find_file_type_id((const uint8_t*)data, strlen(data), 0, &context) == 3)); } TEST_CASE ("FileIdRuleFirst", "[FileMagic]") { FileMagicData magic; magic.content = "PDF"; magic.offset = 0; FileMagicRule rule; rule.type = "exe"; rule.file_magics.emplace_back(magic); rule.id = 1; FileIdentifier rc; rc.insert_file_rule(rule); magic.clear(); magic.content = "EXE"; magic.offset = 3; rule.clear(); rule.type = "exe"; rule.file_magics.emplace_back(magic); rule.id = 3; rc.insert_file_rule(rule); const char* data = "PDF"; void* context = nullptr; CHECK(rc.find_file_type_id((const uint8_t*)data, strlen(data), 0, &context) == 1); } #endif
24.172973
93
0.60003
e0fe61b355cc89c9ca6d6501a2aaa5278a998e4f
539
cpp
C++
notes/code4/GTX.cpp
suryaavala/advancedcpp
84c1847bf42ff744f99b4c0f94b77cfa71ca00d8
[ "MIT" ]
null
null
null
notes/code4/GTX.cpp
suryaavala/advancedcpp
84c1847bf42ff744f99b4c0f94b77cfa71ca00d8
[ "MIT" ]
null
null
null
notes/code4/GTX.cpp
suryaavala/advancedcpp
84c1847bf42ff744f99b4c0f94b77cfa71ca00d8
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> class GTx { public: GTx(size_t val = 0): bound{val} {} bool operator()(const std::string &s) { return s.size() >= bound; } private: std::string::size_type bound; }; int main() { std::vector<std::string> words{"function","objects","are","fun"}; std::cout << std::count_if(words.begin(), words.end(), GTx{6}) << " words have 6 characters or longer; " << std::count_if(words.begin(), words.end(), GTx{3}) << " words have 3 characters or longer." << std::endl; }
25.666667
69
0.628942
460071945d8a1109cb33f18a22a10552fabac77c
1,052
cpp
C++
src/dynamic_load.cpp
cgilmour/dd-opentracing-cpp
c83c6a5dc72029d13ab0d64a7222fb139a1889f1
[ "Apache-2.0" ]
null
null
null
src/dynamic_load.cpp
cgilmour/dd-opentracing-cpp
c83c6a5dc72029d13ab0d64a7222fb139a1889f1
[ "Apache-2.0" ]
null
null
null
src/dynamic_load.cpp
cgilmour/dd-opentracing-cpp
c83c6a5dc72029d13ab0d64a7222fb139a1889f1
[ "Apache-2.0" ]
null
null
null
#include <opentracing/dynamic_load.h> #include <iostream> #include "tracer.h" #include "tracer_factory.h" #include "version_check.h" int OpenTracingMakeTracerFactory(const char* opentracing_version, const void** error_category, void** tracer_factory) try { if (!datadog::opentracing::equal_or_higher_version(std::string(opentracing_version), std::string(OPENTRACING_VERSION))) { std::cerr << "version mismatch: " << std::string(opentracing_version) << " != " << std::string(OPENTRACING_VERSION) << std::endl; *error_category = static_cast<const void*>(&opentracing::dynamic_load_error_category()); return opentracing::incompatible_library_versions_error.value(); } *tracer_factory = new datadog::opentracing::TracerFactory<datadog::opentracing::Tracer>{}; return 0; } catch (const std::bad_alloc&) { *error_category = static_cast<const void*>(&std::generic_category()); return static_cast<int>(std::errc::not_enough_memory); }
47.818182
94
0.681559
4604097af0b164349f1049831f710259fb25a9af
12,410
cc
C++
mysql-server/mysys/crypt_genhash_impl.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/mysys/crypt_genhash_impl.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/mysys/crypt_genhash_impl.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* Copyright (c) 2011, 2019, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. Without limiting anything contained in the foregoing, this file, which is part of C Driver for MySQL (Connector/C), is also subject to the Universal FOSS Exception, version 1.0, a copy of which can be found at http://oss.oracle.com/licenses/universal-foss-exception. 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, version 2.0, 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** @file mysys/crypt_genhash_impl.cc */ // First include (the generated) my_config.h, to get correct platform defines. #include "my_config.h" #include <sys/types.h> #include <openssl/evp.h> #include <openssl/rand.h> #include <openssl/sha.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "crypt_genhash_impl.h" #include "m_string.h" #ifdef HAVE_ALLOCA_H #include <alloca.h> #endif #include <errno.h> #ifdef _WIN32 #include <malloc.h> #endif #define DIGEST_CTX EVP_MD_CTX #define DIGEST_LEN SHA256_DIGEST_LENGTH static void DIGESTCreate(DIGEST_CTX **ctx) { if (ctx != nullptr) { *ctx = EVP_MD_CTX_create(); } } static void DIGESTInit(DIGEST_CTX *ctx) { EVP_DigestInit_ex(ctx, EVP_sha256(), nullptr); } static void DIGESTUpdate(DIGEST_CTX *ctx, const void *plaintext, int len) { EVP_DigestUpdate(ctx, plaintext, len); } static void DIGESTFinal(void *txt, DIGEST_CTX *ctx) { EVP_DigestFinal_ex(ctx, (unsigned char *)txt, nullptr); } static void DIGESTDestroy(DIGEST_CTX **ctx) { if (ctx != nullptr) { EVP_MD_CTX_destroy(*ctx); *ctx = nullptr; } } static const char crypt_alg_magic[] = "$5"; #ifndef MAX #define MAX(a, b) (((a) > (b)) ? (a) : (b)) #endif #ifndef MIN #define MIN(a, b) (((a) < (b)) ? (a) : (b)) #endif #ifndef HAVE_STRLCAT /** Size-bounded string copying and concatenation This is a replacement for STRLCPY(3) */ static size_t strlcat(char *dst, const char *src, size_t siz) { char *d = dst; const char *s = src; size_t n = siz; size_t dlen; /* Find the end of dst and adjust bytes left but don't go past end */ while (n-- != 0 && *d != '\0') d++; dlen = d - dst; n = siz - dlen; if (n == 0) return (dlen + siz); while (*s != '\0') { if (n != 1) { *d++ = *s; n--; } s++; } *d = '\0'; return (dlen + (s - src)); /* count does not include NUL */ } #endif static const int crypt_alg_magic_len = sizeof(crypt_alg_magic) - 1; static unsigned char b64t[] = /* 0 ... 63 => ascii - 64 */ "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; #define b64_from_24bit(B2, B1, B0, N) \ { \ uint32_t w = ((B2) << 16) | ((B1) << 8) | (B0); \ int n = (N); \ while (--n >= 0 && ctbufflen > 0) { \ *p++ = b64t[w & 0x3f]; \ w >>= 6; \ ctbufflen--; \ } \ } #define ROUNDS "rounds=" #define ROUNDSLEN (sizeof(ROUNDS) - 1) /** Get the integer value after rounds= where ever it occurs in the string. if the last char after the int is a , or $ that is fine anything else is an error. */ static uint getrounds(const char *s) { const char *r; const char *p; char *e; long val; if (s == nullptr) return (0); if ((r = strstr(s, ROUNDS)) == nullptr) { return (0); } if (strncmp(r, ROUNDS, ROUNDSLEN) != 0) { return (0); } p = r + ROUNDSLEN; errno = 0; val = strtol(p, &e, 10); /* An error occurred or there is non-numeric stuff at the end which isn't one of the crypt(3c) special chars ',' or '$' */ if (errno != 0 || val < 0 || !(*e == '\0' || *e == ',' || *e == '$')) { return (0); } return ((uint32_t)val); } /** Finds the interval which envelopes the user salt in a crypt password The crypt format is assumed to be $a$bbbb$cccccc\0 and the salt is found by counting the delimiters and marking begin and end. @param [in,out] salt_begin As input, pointer to start of crypt passwd, as output, pointer to first byte of the salt @param [in,out] salt_end As input, pointer to the last byte in passwd, as output, pointer to the byte immediatly following the salt ($) @return The size of the salt identified */ int extract_user_salt(const char **salt_begin, const char **salt_end) { const char *it = *salt_begin; int delimiter_count = 0; while (it != *salt_end) { if (*it == '$') { ++delimiter_count; if (delimiter_count == 2) { *salt_begin = it + 1; } if (delimiter_count == 3) break; } ++it; } *salt_end = it; return *salt_end - *salt_begin; } /* * Portions of the below code come from crypt_bsdmd5.so (bsdmd5.c) : * ---------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * <phk@login.dknet.dk> wrote this file. As long as you retain this notice you * can do whatever you want with this stuff. If we meet some day, and you think * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp * ---------------------------------------------------------------------------- * * $FreeBSD: crypt.c,v 1.5 1996/10/14 08:34:02 phk Exp $ * */ /* * The below code implements the specification from: * * From http://people.redhat.com/drepper/SHA-crypt.txt * * Portions of the code taken from inspired by or verified against the * source in the above document which is licensed as: * * "Released into the Public Domain by Ulrich Drepper <drepper@redhat.com>." */ /* Due to a Solaris namespace bug DS is a reserved word. To work around this DS is undefined. */ #undef DS /* ARGSUSED4 */ char *my_crypt_genhash(char *ctbuffer, size_t ctbufflen, const char *plaintext, size_t plaintext_len, const char *switchsalt, const char **, unsigned int *num_rounds) /* = NULL */ { int salt_len; size_t i; char *salt; unsigned char A[DIGEST_LEN]; unsigned char B[DIGEST_LEN]; unsigned char DP[DIGEST_LEN]; unsigned char DS[DIGEST_LEN]; DIGEST_CTX *ctxA, *ctxB, *ctxC, *ctxDP, *ctxDS = nullptr; unsigned int rounds = num_rounds && (*num_rounds <= ROUNDS_MAX && *num_rounds >= ROUNDS_MIN) ? *num_rounds : ROUNDS_DEFAULT; int srounds = 0; bool custom_rounds = false; char *p; char *P, *Pp; char *S, *Sp; /* Create Digest context. */ DIGESTCreate(&ctxA); DIGESTCreate(&ctxB); DIGESTCreate(&ctxC); DIGESTCreate(&ctxDP); DIGESTCreate(&ctxDS); if (num_rounds) *num_rounds = rounds; /* Refine the salt */ salt = const_cast<char *>(switchsalt); /* skip our magic string */ if (strncmp(salt, crypt_alg_magic, crypt_alg_magic_len) == 0) { salt += crypt_alg_magic_len + 1; } srounds = getrounds(salt); if (srounds != 0) { rounds = MAX(ROUNDS_MIN, MIN(srounds, ROUNDS_MAX)); custom_rounds = true; p = strchr(salt, '$'); if (p != nullptr) salt = p + 1; } salt_len = MIN(strcspn(salt, "$"), CRYPT_SALT_LENGTH); // plaintext_len = strlen(plaintext); /* 1. */ DIGESTInit(ctxA); /* 2. The password first, since that is what is most unknown */ DIGESTUpdate(ctxA, plaintext, plaintext_len); /* 3. Then the raw salt */ DIGESTUpdate(ctxA, salt, salt_len); /* 4. - 8. */ DIGESTInit(ctxB); DIGESTUpdate(ctxB, plaintext, plaintext_len); DIGESTUpdate(ctxB, salt, salt_len); DIGESTUpdate(ctxB, plaintext, plaintext_len); DIGESTFinal(B, ctxB); /* 9. - 10. */ for (i = plaintext_len; i > MIXCHARS; i -= MIXCHARS) DIGESTUpdate(ctxA, B, MIXCHARS); DIGESTUpdate(ctxA, B, i); /* 11. */ for (i = plaintext_len; i > 0; i >>= 1) { if ((i & 1) != 0) { DIGESTUpdate(ctxA, B, MIXCHARS); } else { DIGESTUpdate(ctxA, plaintext, plaintext_len); } } /* 12. */ DIGESTFinal(A, ctxA); /* 13. - 15. */ DIGESTInit(ctxDP); for (i = 0; i < plaintext_len; i++) DIGESTUpdate(ctxDP, plaintext, plaintext_len); DIGESTFinal(DP, ctxDP); /* 16. */ Pp = P = (char *)alloca(plaintext_len); for (i = plaintext_len; i >= MIXCHARS; i -= MIXCHARS) { Pp = (char *)(memcpy(Pp, DP, MIXCHARS)) + MIXCHARS; } (void)memcpy(Pp, DP, i); /* 17. - 19. */ DIGESTInit(ctxDS); for (i = 0; i < 16U + (uint8_t)A[0]; i++) DIGESTUpdate(ctxDS, salt, salt_len); DIGESTFinal(DS, ctxDS); /* 20. */ Sp = S = (char *)alloca(salt_len); for (i = salt_len; i >= MIXCHARS; i -= MIXCHARS) { Sp = (char *)(memcpy(Sp, DS, MIXCHARS)) + MIXCHARS; } (void)memcpy(Sp, DS, i); /* 21. */ for (i = 0; i < rounds; i++) { DIGESTInit(ctxC); if ((i & 1) != 0) { DIGESTUpdate(ctxC, P, plaintext_len); } else { if (i == 0) DIGESTUpdate(ctxC, A, MIXCHARS); else DIGESTUpdate(ctxC, DP, MIXCHARS); } if (i % 3 != 0) { DIGESTUpdate(ctxC, S, salt_len); } if (i % 7 != 0) { DIGESTUpdate(ctxC, P, plaintext_len); } if ((i & 1) != 0) { if (i == 0) DIGESTUpdate(ctxC, A, MIXCHARS); else DIGESTUpdate(ctxC, DP, MIXCHARS); } else { DIGESTUpdate(ctxC, P, plaintext_len); } DIGESTFinal(DP, ctxC); } /* 22. Now make the output string */ if (custom_rounds) { (void)snprintf(ctbuffer, ctbufflen, "%s$rounds=%zu$", crypt_alg_magic, (size_t)rounds); } else { (void)snprintf(ctbuffer, ctbufflen, "%s$", crypt_alg_magic); } (void)strncat(ctbuffer, (const char *)salt, salt_len); (void)strlcat(ctbuffer, "$", ctbufflen); p = ctbuffer + strlen(ctbuffer); ctbufflen -= strlen(ctbuffer); b64_from_24bit(DP[0], DP[10], DP[20], 4); b64_from_24bit(DP[21], DP[1], DP[11], 4); b64_from_24bit(DP[12], DP[22], DP[2], 4); b64_from_24bit(DP[3], DP[13], DP[23], 4); b64_from_24bit(DP[24], DP[4], DP[14], 4); b64_from_24bit(DP[15], DP[25], DP[5], 4); b64_from_24bit(DP[6], DP[16], DP[26], 4); b64_from_24bit(DP[27], DP[7], DP[17], 4); b64_from_24bit(DP[18], DP[28], DP[8], 4); b64_from_24bit(DP[9], DP[19], DP[29], 4); b64_from_24bit(0, DP[31], DP[30], 3); *p = '\0'; (void)memset(A, 0, sizeof(A)); (void)memset(B, 0, sizeof(B)); (void)memset(DP, 0, sizeof(DP)); (void)memset(DS, 0, sizeof(DS)); /* 23. Clearing the context */ DIGESTDestroy(&ctxA); DIGESTDestroy(&ctxB); DIGESTDestroy(&ctxC); DIGESTDestroy(&ctxDP); DIGESTDestroy(&ctxDS); return (ctbuffer); } /** Generate a random string using ASCII characters but avoid seperator character. Stdlib rand and srand are used to produce pseudo random numbers between with about 7 bit worth of entropty between 1-127. */ void generate_user_salt(char *buffer, int buffer_len) { char *end = buffer + buffer_len - 1; RAND_bytes((unsigned char *)buffer, buffer_len); /* Sequence must be a legal UTF8 string */ for (; buffer < end; buffer++) { *buffer &= 0x7f; if (*buffer == '\0' || *buffer == '$') *buffer = *buffer + 1; } /* Make sure the buffer is terminated properly */ *end = '\0'; } void xor_string(char *to, int to_len, char *pattern, int pattern_len) { int loop = 0; while (loop <= to_len) { *(to + loop) ^= *(pattern + loop % pattern_len); ++loop; } }
27.88764
80
0.609347
4604dc0789f87eabd6425248d8f7f211dcb9baed
6,663
cpp
C++
src/future/flexer.cpp
rasfmar/future
189a996f7e2c6401626d11ca6d8f11243dd0b737
[ "MIT" ]
null
null
null
src/future/flexer.cpp
rasfmar/future
189a996f7e2c6401626d11ca6d8f11243dd0b737
[ "MIT" ]
null
null
null
src/future/flexer.cpp
rasfmar/future
189a996f7e2c6401626d11ca6d8f11243dd0b737
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include "internal/_ftoken.hpp" #include "fstate.hpp" #include "flexer.hpp" void flexer::lex(fstate *state, fparser &parser) { lex(state, parser.tokens); } void flexer::lex(fstate *state, std::vector<_ftoken*> &tokens) { std::stack<_ftoken*> fstack; bool die = false; for (_ftoken *token : tokens) { // if it's an operator if (token->type >= _FPLUS) { switch(token->type) { case _FPLUS: { // todo error handling if (fstack.size() < 2) { die = true; break; } _ftoken* second_operand = fstack.top(); fstack.pop(); _ftoken* first_operand = fstack.top(); fstack.pop(); // todo assert that second operand is of same type as first _27: switch (first_operand->type) { case _FINT32: { int32_t first_operand_val = *(int32_t *)first_operand->val; if (second_operand->type == _FID) { // todo stop assuming dEFINED std::string second_operand_val = *(std::string *)second_operand->val; if (!state->definitions.count(second_operand_val)) { // error die = true; break; } _ftoken *definition = state->definitions[second_operand_val]; second_operand->type = definition->type; second_operand->val = definition->val; } if (second_operand->type != _FINT32) { // error! fstack.push(new _ftoken()); break; } int32_t second_operand_val = *(int32_t *)second_operand->val; int32_t *result = new int32_t(first_operand_val + second_operand_val); fstack.push(new _ftoken(result)); // delete first_operand; // delete second_operand; break; } case _FSTRING: { std::string first_operand_val = *(std::string *)first_operand->val; std::string second_operand_val = *(std::string *)second_operand->val; std::string *result = new std::string(first_operand_val + second_operand_val); fstack.push(new _ftoken(result)); // delete first_operand; // delete second_operand; break; } case _FID: { // todo stop assuming its defined std::string first_operand_val = *(std::string *)first_operand->val; if (!state->definitions.count(first_operand_val)) { // error die = true; break; } _ftoken *definition = state->definitions[first_operand_val]; first_operand->type = definition->type; first_operand->val = definition->val; goto _27; } default: fstack.push(new _ftoken()); break; } break; } case _FMINUS: { // todo error handling if (fstack.size() < 2) { die = true; break; } _ftoken* second_operand = fstack.top(); fstack.pop(); _ftoken* first_operand = fstack.top(); fstack.pop(); // todo assert that second operand is of same type as first _60: switch (first_operand->type) { case _FINT32: { int32_t first_operand_val = *(int32_t *)first_operand->val; if (second_operand->type == _FID) { // todo stop assuming dEFINED std::string second_operand_val = *(std::string *)second_operand->val; if (!state->definitions.count(second_operand_val)) { // error die = true; break; } _ftoken *definition = state->definitions[second_operand_val]; second_operand->type = definition->type; second_operand->val = definition->val; } if (second_operand->type != _FINT32) { // error! fstack.push(new _ftoken()); break; } int32_t second_operand_val = *(int32_t *)second_operand->val; int32_t *result = new int32_t(first_operand_val - second_operand_val); fstack.push(new _ftoken(result)); // delete first_operand; // delete second_operand; break; } case _FID: { // todo stop assuming its defined std::string first_operand_val = *(std::string *)first_operand->val; if (!state->definitions.count(first_operand_val)) { // error die = true; break; } _ftoken *definition = state->definitions[first_operand_val]; first_operand->type = definition->type; first_operand->val = definition->val; goto _60; } default: fstack.push(new _ftoken()); break; } break; } case _FEQUALS: { // todo error handling for empty stack if (fstack.size() < 2) { die = true; break; } _ftoken* second_operand = fstack.top(); fstack.pop(); _ftoken* first_operand = fstack.top(); fstack.pop(); // todo error if first operand is not an identifier std::string first_operand_val = *(std::string *)first_operand->val; // setting this directly to second_operand could be a problem state->definitions[first_operand_val] = second_operand->clone(); // delete first_operand; // delete second_operand; break; } case _FPRINT: { if (fstack.size() < 1) { die = true; break; } _ftoken* first_operand = fstack.top(); fstack.pop(); if (first_operand->type == _FID) { std::string first_operand_val = *(std::string *)first_operand->val; if (!state->definitions.count(first_operand_val)) { die = true; break; } _ftoken *definition = state->definitions[first_operand_val]; first_operand->type = definition->type; first_operand->val = definition->val; } std::cout << first_operand->valstr() << std::endl; break; } case _FINPUT: { std::string *in = new std::string(""); std::getline(std::cin, *in); _ftoken *token = new _ftoken(in); fstack.push(token); break; } default: break; } } else { fstack.push(token); } if (die) break; } tokens.clear(); while (!fstack.empty()) { std::cout << (fstack.top())->str() << std::endl; fstack.pop(); } }
31.880383
88
0.540147
46054b06a51fe0732a8681424f05cfcf5161c13e
1,212
cpp
C++
test/communicator_broadcast.cpp
correaa/b-mpi3
161e52a28ab9043be9ef33acd8f31dbeae483b61
[ "BSL-1.0" ]
null
null
null
test/communicator_broadcast.cpp
correaa/b-mpi3
161e52a28ab9043be9ef33acd8f31dbeae483b61
[ "BSL-1.0" ]
null
null
null
test/communicator_broadcast.cpp
correaa/b-mpi3
161e52a28ab9043be9ef33acd8f31dbeae483b61
[ "BSL-1.0" ]
null
null
null
#if COMPILATION_INSTRUCTIONS mpic++ -O3 -std=c++14 -Wall -Wfatal-errors $0 -o $0x.x && time mpirun -n 2 $0x.x $@ && rm -f $0x.x; exit #endif // © Copyright Alfredo A. Correa 2018-2020 #include "../../mpi3/main.hpp" #include "../../mpi3/communicator.hpp" namespace mpi3 = boost::mpi3; int mpi3::main(int, char*[], mpi3::communicator world){ std::vector<std::size_t> sizes = {100, 64*1024};//, 128*1024}; // TODO check larger number (fails with openmpi 4.0.5) int NUM_REPS = 5; using value_type = int; std::vector<value_type> buf(128*1024); for(std::size_t n=0; n != sizes.size(); ++n){ // if(world.root()) cout<<"bcasting "<< sizes[n] <<" ints "<< NUM_REPS <<" times.\n"; for(int reps = 0; reps != NUM_REPS; ++reps){ if(world.root()) for(std::size_t i = 0; i != sizes[n]; ++i){ buf[i] = 1000000.*(n * NUM_REPS + reps) + i; } else for(std::size_t i = 0; i != sizes[n]; ++i){ buf[i] = -(n * NUM_REPS + reps) - 1; } world.broadcast_n(buf.begin(), sizes[n]); // world.broadcast(buf.begin(), buf.begin() + sizes[n], 0); for(std::size_t i = 0; i != sizes[n]; ++i) assert( fabs(buf[i] - (1000000.*(n * NUM_REPS + reps) + i)) < 1e-4 ); } } return 0; }
27.545455
118
0.575908
460819731d1f58a91ad128467d955be784f981e0
764
hpp
C++
libs/resource_tree/include/sge/resource_tree/detail/strip_path_prefix.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/resource_tree/include/sge/resource_tree/detail/strip_path_prefix.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/resource_tree/include/sge/resource_tree/detail/strip_path_prefix.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under 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) #ifndef SGE_RESOURCE_TREE_DETAIL_STRIP_PATH_PREFIX_HPP_INCLUDED #define SGE_RESOURCE_TREE_DETAIL_STRIP_PATH_PREFIX_HPP_INCLUDED #include <sge/resource_tree/path_fwd.hpp> #include <sge/resource_tree/detail/base_path.hpp> #include <sge/resource_tree/detail/sub_path.hpp> #include <sge/resource_tree/detail/symbol.hpp> namespace sge::resource_tree::detail { SGE_RESOURCE_TREE_DETAIL_SYMBOL sge::resource_tree::path strip_path_prefix( sge::resource_tree::detail::base_path const &, sge::resource_tree::detail::sub_path const &); } #endif
31.833333
97
0.784031
4608b94ee463cd53b6600c1666ac954f0d0ee380
3,114
cpp
C++
Drivers/SelfTests/Boundaries/InsertionBoundarySelfTest.cpp
gustavo-castillo-bautista/Mercury
eeb402ccec8e487652229d4595c46ec84f6aefbb
[ "BSD-3-Clause" ]
null
null
null
Drivers/SelfTests/Boundaries/InsertionBoundarySelfTest.cpp
gustavo-castillo-bautista/Mercury
eeb402ccec8e487652229d4595c46ec84f6aefbb
[ "BSD-3-Clause" ]
null
null
null
Drivers/SelfTests/Boundaries/InsertionBoundarySelfTest.cpp
gustavo-castillo-bautista/Mercury
eeb402ccec8e487652229d4595c46ec84f6aefbb
[ "BSD-3-Clause" ]
null
null
null
//Copyright (c) 2013-2020, The MercuryDPM Developers Team. All rights reserved. //For the list of developers, see <http://www.MercuryDPM.org/Team>. // //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 MercuryDPM 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 MERCURYDPM DEVELOPERS TEAM 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 <iostream> #include "Mercury3D.h" #include "Boundaries/CubeInsertionBoundary.h" #include "Boundaries/PeriodicBoundary.h" #include "Species/LinearViscoelasticSpecies.h" #include "Walls/InfiniteWall.h" class InsertionBoundarySelfTest : public Mercury3D { public: void setupInitialConditions() override { setName("InsertionBoundarySelfTest"); setSystemDimensions(3); setGravity(Vec3D(0, 0, 0)); setTimeStep(1e-4); dataFile.setSaveCount(10); setTimeMax(2e-2); setHGridMaxLevels(2); setMin(Vec3D(0, 0, 0)); setMax(Vec3D(1, 1, 1)); LinearViscoelasticSpecies species; species.setDensity(2000); species.setStiffness(10000); speciesHandler.copyAndAddObject(species); SphericalParticle insertionBoundaryParticle; insertionBoundaryParticle.setSpecies(speciesHandler.getObject(0)); CubeInsertionBoundary insertionBoundary; insertionBoundary.set(&insertionBoundaryParticle,1,getMin(),getMax(),Vec3D(1,0,0),Vec3D(1,0,0),0.025,0.05); boundaryHandler.copyAndAddObject(insertionBoundary); } void printTime() const override { logger(INFO,"t=%, tMax=%, N=%", getTime(),getTimeMax(), particleHandler.getSize()); } }; int main(int argc UNUSED, char *argv[] UNUSED) { logger(INFO,"Simple box for creating particles"); InsertionBoundarySelfTest insertionBoundary_problem; insertionBoundary_problem.solve(); }
39.923077
115
0.738279
460ad4d2f8b2dec3cb9b937daa8937e88710138c
1,572
cc
C++
solutions/mrJudge/base/main.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
4
2020-11-07T14:38:02.000Z
2022-01-03T19:02:36.000Z
solutions/mrJudge/base/main.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
1
2019-04-17T06:55:14.000Z
2019-04-17T06:55:14.000Z
solutions/mrJudge/base/main.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
null
null
null
// #include <bits/stdc++.h> #include <algorithm> #include <cmath> #include <deque> #include <iostream> #include <map> #include <queue> #include <set> #include <string> #include <unordered_map> #include <vector> using namespace std; #define FOR(i, j, k, l) for (s32 i = j; i < k; i += l) #define RFOR(i, j, k, l) for (s32 i = j; i >= k; i -= l) #define REP(i, j) FOR(i, 0, j, 1) #define RREP(i, j) RFOR(i, j, 0, 1) #define ALL(x) x.begin(), x.end() #define MEAN(a, b) min(a, b) + (abs(b - a) / 2) #define FASTIO() \ cin.tie(nullptr); \ ios::sync_with_stdio(false); typedef int64_t s64; typedef uint64_t u64; typedef int32_t s32; typedef uint32_t u32; typedef float f32; typedef double f64; inline long long pw(long long i, long long p) { return !p ? 1 : p >> 1 ? pw(i * i, p >> 1) * (p % 2 ? i : 1) : i; } int main() { // Don't collapse the block FASTIO(); string x; s64 a, b; cin >> x >> a >> b; if (a == b || x == "0") { cout << x; return 0; } s64 b10 = 0; if (a == 10) { b10 = stoi(x); } else { REP(i, x.size()) { s64 c; if (isdigit(x[i])) { c = x[i] - '0'; } else { c = x[i] - 'A' + 10; } b10 += c * pw(a, x.size() - 1 - i); } if (b == 10) { cout << b10; return 0; } } string r; while (b10) { s64 c; c = b10 % b; if (c >= 10) { c += 'A' - 10; } else { c += '0'; } // cout << b10 << ' ' << b10 / b << ' ' << c << '\n'; r.push_back(c); b10 /= b; } reverse(r.begin(), r.end()); cout << r; }
18.494118
67
0.48028
460e73849e3611b85524258bf2aaa70644de2b5f
22,430
cpp
C++
scatterplot.cpp
fadel/msc-pm
bedf6936885694688ddb8bd3452f6bd68ef8d29c
[ "MIT" ]
null
null
null
scatterplot.cpp
fadel/msc-pm
bedf6936885694688ddb8bd3452f6bd68ef8d29c
[ "MIT" ]
null
null
null
scatterplot.cpp
fadel/msc-pm
bedf6936885694688ddb8bd3452f6bd68ef8d29c
[ "MIT" ]
null
null
null
#include "scatterplot.h" #include <algorithm> #include <cmath> #include <limits> #include <QSGGeometryNode> #include <QSGSimpleRectNode> #include "continuouscolorscale.h" #include "geometry.h" // Glyphs settings static const QColor DEFAULT_GLYPH_COLOR(255, 255, 255); static const float DEFAULT_GLYPH_SIZE = 8.0f; static const qreal GLYPH_OPACITY = 1.0; static const qreal GLYPH_OPACITY_SELECTED = 1.0; static const float GLYPH_OUTLINE_WIDTH = 2.0f; static const QColor GLYPH_OUTLINE_COLOR(0, 0, 0); static const QColor GLYPH_OUTLINE_COLOR_SELECTED(20, 255, 225); // Brush settings static const float BRUSHING_MAX_DIST = 20.0f; static const float CROSSHAIR_LENGTH = 8.0f; static const float CROSSHAIR_THICKNESS1 = 1.0f; static const float CROSSHAIR_THICKNESS2 = 0.5f; static const QColor CROSSHAIR_COLOR1(255, 255, 255); static const QColor CROSSHAIR_COLOR2(0, 0, 0); // Selection settings static const QColor SELECTION_COLOR(128, 128, 128, 96); // Mouse buttons static const Qt::MouseButton NORMAL_BUTTON = Qt::LeftButton; static const Qt::MouseButton SPECIAL_BUTTON = Qt::RightButton; class QuadTree { public: QuadTree(const QRectF &bounds); ~QuadTree(); bool insert(float x, float y, int value); int query(float x, float y) const; void query(const QRectF &rect, std::vector<int> &result) const; int nearestTo(float x, float y) const; private: bool subdivide(); void nearestTo(float x, float y, int &nearest, float &dist) const; QRectF m_bounds; float m_x, m_y; int m_value; QuadTree *m_nw, *m_ne, *m_sw, *m_se; }; Scatterplot::Scatterplot(QQuickItem *parent) : QQuickItem(parent) , m_glyphSize(DEFAULT_GLYPH_SIZE) , m_colorScale(0) , m_autoScale(true) , m_sx(0, 1, 0, 1) , m_sy(0, 1, 0, 1) , m_anySelected(false) , m_brushedItem(-1) , m_interactionState(StateNone) , m_dragEnabled(false) , m_shouldUpdateGeometry(false) , m_shouldUpdateMaterials(false) , m_quadtree(0) { setClip(true); setFlag(QQuickItem::ItemHasContents); } Scatterplot::~Scatterplot() { if (m_quadtree) { delete m_quadtree; } } void Scatterplot::setColorScale(const ColorScale *colorScale) { m_colorScale = colorScale; if (m_colorData.n_elem > 0) { m_shouldUpdateMaterials = true; update(); } } arma::mat Scatterplot::XY() const { return m_xy; } void Scatterplot::setXY(const arma::mat &xy) { if (xy.n_cols != 2) { return; } m_xy = xy; emit xyChanged(m_xy); if (m_autoScale) { autoScale(); } updateQuadTree(); if (m_selection.size() != m_xy.n_rows) { m_selection.assign(m_xy.n_rows, false); } if (m_opacityData.n_elem != m_xy.n_rows) { // Reset opacity data m_opacityData.resize(xy.n_rows); m_opacityData.fill(GLYPH_OPACITY); emit opacityDataChanged(m_opacityData); } m_shouldUpdateGeometry = true; update(); } void Scatterplot::setColorData(const arma::vec &colorData) { if (m_xy.n_rows > 0 && (colorData.n_elem > 0 && colorData.n_elem != m_xy.n_rows)) { return; } m_colorData = colorData; emit colorDataChanged(m_colorData); m_shouldUpdateMaterials = true; update(); } void Scatterplot::setOpacityData(const arma::vec &opacityData) { if (m_xy.n_rows > 0 && opacityData.n_elem != m_xy.n_rows) { return; } m_opacityData = opacityData; emit opacityDataChanged(m_opacityData); update(); } void Scatterplot::setScale(const LinearScale<float> &sx, const LinearScale<float> &sy) { m_sx = sx; m_sy = sy; emit scaleChanged(m_sx, m_sy); updateQuadTree(); m_shouldUpdateGeometry = true; update(); } void Scatterplot::setAutoScale(bool autoScale) { m_autoScale = autoScale; if (autoScale) { this->autoScale(); } } void Scatterplot::autoScale() { m_sx.setDomain(m_xy.col(0).min(), m_xy.col(0).max()); m_sy.setDomain(m_xy.col(1).min(), m_xy.col(1).max()); emit scaleChanged(m_sx, m_sy); } void Scatterplot::setGlyphSize(float glyphSize) { if (m_glyphSize == glyphSize || glyphSize < 2.0f) { return; } m_glyphSize = glyphSize; emit glyphSizeChanged(m_glyphSize); m_shouldUpdateGeometry = true; update(); } QSGNode *Scatterplot::newSceneGraph() { // NOTE: // The hierarchy in the scene graph is as follows: // root [[splatNode] [glyphsRoot [glyph [...]]] [selectionNode]] QSGNode *root = new QSGNode; QSGNode *glyphTreeRoot = newGlyphTree(); if (glyphTreeRoot) { root->appendChildNode(glyphTreeRoot); } QSGSimpleRectNode *selectionRectNode = new QSGSimpleRectNode; selectionRectNode->setColor(SELECTION_COLOR); root->appendChildNode(selectionRectNode); QSGTransformNode *brushNode = new QSGTransformNode; QSGGeometryNode *whiteCrossHairNode = new QSGGeometryNode; QSGGeometry *whiteCrossHairGeom = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), 12); whiteCrossHairGeom->setDrawingMode(GL_POLYGON); whiteCrossHairGeom->setVertexDataPattern(QSGGeometry::DynamicPattern); updateCrossHairGeometry(whiteCrossHairGeom, 0, 0, CROSSHAIR_THICKNESS1, CROSSHAIR_LENGTH); QSGFlatColorMaterial *whiteCrossHairMaterial = new QSGFlatColorMaterial; whiteCrossHairMaterial->setColor(CROSSHAIR_COLOR1); whiteCrossHairNode->setGeometry(whiteCrossHairGeom); whiteCrossHairNode->setMaterial(whiteCrossHairMaterial); whiteCrossHairNode->setFlags(QSGNode::OwnsGeometry | QSGNode::OwnsMaterial); brushNode->appendChildNode(whiteCrossHairNode); QSGGeometryNode *blackCrossHairNode = new QSGGeometryNode; QSGGeometry *blackCrossHairGeom = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), 12); blackCrossHairGeom->setDrawingMode(GL_POLYGON); blackCrossHairGeom->setVertexDataPattern(QSGGeometry::DynamicPattern); updateCrossHairGeometry(blackCrossHairGeom, 0, 0, CROSSHAIR_THICKNESS2, CROSSHAIR_LENGTH); QSGFlatColorMaterial *blackCrossHairMaterial = new QSGFlatColorMaterial; blackCrossHairMaterial->setColor(CROSSHAIR_COLOR2); blackCrossHairNode->setGeometry(blackCrossHairGeom); blackCrossHairNode->setMaterial(blackCrossHairMaterial); blackCrossHairNode->setFlags(QSGNode::OwnsGeometry | QSGNode::OwnsMaterial); brushNode->appendChildNode(blackCrossHairNode); root->appendChildNode(brushNode); return root; } QSGNode *Scatterplot::newGlyphTree() { // NOTE: // The glyph graph is structured as: // root [opacityNode [outlineNode fillNode] ...] if (m_xy.n_rows < 1) { return 0; } QSGNode *node = new QSGNode; int vertexCount = calculateCircleVertexCount(m_glyphSize); for (arma::uword i = 0; i < m_xy.n_rows; i++) { QSGGeometry *glyphOutlineGeometry = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), vertexCount); glyphOutlineGeometry->setDrawingMode(GL_POLYGON); glyphOutlineGeometry->setVertexDataPattern(QSGGeometry::DynamicPattern); QSGGeometryNode *glyphOutlineNode = new QSGGeometryNode; glyphOutlineNode->setGeometry(glyphOutlineGeometry); glyphOutlineNode->setFlag(QSGNode::OwnsGeometry); QSGFlatColorMaterial *material = new QSGFlatColorMaterial; material->setColor(GLYPH_OUTLINE_COLOR); glyphOutlineNode->setMaterial(material); glyphOutlineNode->setFlag(QSGNode::OwnsMaterial); QSGGeometry *glyphGeometry = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), vertexCount); glyphGeometry->setDrawingMode(GL_POLYGON); glyphGeometry->setVertexDataPattern(QSGGeometry::DynamicPattern); QSGGeometryNode *glyphNode = new QSGGeometryNode; glyphNode->setGeometry(glyphGeometry); glyphNode->setFlag(QSGNode::OwnsGeometry); material = new QSGFlatColorMaterial; material->setColor(DEFAULT_GLYPH_COLOR); glyphNode->setMaterial(material); glyphNode->setFlag(QSGNode::OwnsMaterial); // Place the glyph geometry node under an opacity node QSGOpacityNode *glyphOpacityNode = new QSGOpacityNode; glyphOpacityNode->appendChildNode(glyphOutlineNode); glyphOpacityNode->appendChildNode(glyphNode); node->appendChildNode(glyphOpacityNode); } return node; } QSGNode *Scatterplot::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *) { QSGNode *root = oldNode ? oldNode : newSceneGraph(); if (m_xy.n_rows < 1) { return root; } // This keeps track of where we are in the scene when updating QSGNode *node = root->firstChild(); updateGlyphs(node); node = node->nextSibling(); if (m_shouldUpdateGeometry) { m_shouldUpdateGeometry = false; } if (m_shouldUpdateMaterials) { m_shouldUpdateMaterials = false; } // Selection QSGSimpleRectNode *selectionNode = static_cast<QSGSimpleRectNode *>(node); if (m_interactionState == StateSelecting) { selectionNode->setRect(QRectF(m_dragOriginPos, m_dragCurrentPos)); selectionNode->markDirty(QSGNode::DirtyGeometry); } else { // Hide selection rect selectionNode->setRect(QRectF(-1, -1, 0, 0)); } node = node->nextSibling(); // Brushing updateBrush(node); node = node->nextSibling(); return root; } void Scatterplot::updateGlyphs(QSGNode *glyphsNode) { qreal x, y, tx, ty, moveTranslationF; if (!m_shouldUpdateGeometry && !m_shouldUpdateMaterials) { return; } if (m_interactionState == StateMoving) { tx = m_dragCurrentPos.x() - m_dragOriginPos.x(); ty = m_dragCurrentPos.y() - m_dragOriginPos.y(); } else { tx = ty = 0; } m_sx.setRange(PADDING, width() - PADDING); m_sy.setRange(height() - PADDING, PADDING); QSGNode *node = glyphsNode->firstChild(); for (arma::uword i = 0; i < m_xy.n_rows; i++) { const arma::rowvec &row = m_xy.row(i); bool isSelected = m_selection[i]; QSGOpacityNode *glyphOpacityNode = static_cast<QSGOpacityNode *>(node); glyphOpacityNode->setOpacity(m_opacityData[i]); QSGGeometryNode *glyphOutlineNode = static_cast<QSGGeometryNode *>(node->firstChild()); QSGGeometryNode *glyphNode = static_cast<QSGGeometryNode *>(node->firstChild()->nextSibling()); if (m_shouldUpdateGeometry) { moveTranslationF = isSelected ? 1.0 : 0.0; x = m_sx(row[0]) + tx * moveTranslationF; y = m_sy(row[1]) + ty * moveTranslationF; QSGGeometry *geometry = glyphOutlineNode->geometry(); updateCircleGeometry(geometry, m_glyphSize, x, y); glyphOutlineNode->markDirty(QSGNode::DirtyGeometry); geometry = glyphNode->geometry(); updateCircleGeometry(geometry, m_glyphSize - 2*GLYPH_OUTLINE_WIDTH, x, y); glyphNode->markDirty(QSGNode::DirtyGeometry); } if (m_shouldUpdateMaterials) { QSGFlatColorMaterial *material = static_cast<QSGFlatColorMaterial *>(glyphOutlineNode->material()); material->setColor(isSelected ? GLYPH_OUTLINE_COLOR_SELECTED : GLYPH_OUTLINE_COLOR); glyphOutlineNode->markDirty(QSGNode::DirtyMaterial); material = static_cast<QSGFlatColorMaterial *>(glyphNode->material()); if (m_colorData.n_elem > 0) { material->setColor(m_colorScale->color(m_colorData[i])); } else { material->setColor(DEFAULT_GLYPH_COLOR); } glyphNode->markDirty(QSGNode::DirtyMaterial); } node = node->nextSibling(); } // XXX: Beware: QSGNode::DirtyForceUpdate is undocumented // // This causes the scene graph to correctly update the materials of glyphs, // even though we individually mark dirty materials. Used to work in Qt 5.5, // though. glyphsNode->markDirty(QSGNode::DirtyForceUpdate); } void Scatterplot::updateBrush(QSGNode *node) { QMatrix4x4 transform; if (m_brushedItem < 0 || (m_interactionState != StateNone && m_interactionState != StateSelected)) { transform.translate(-width(), -height()); } else { const arma::rowvec &row = m_xy.row(m_brushedItem); transform.translate(m_sx(row[0]), m_sy(row[1])); } QSGTransformNode *brushNode = static_cast<QSGTransformNode *>(node); brushNode->setMatrix(transform); } void Scatterplot::mousePressEvent(QMouseEvent *event) { switch (m_interactionState) { case StateNone: case StateSelected: switch (event->button()) { case NORMAL_BUTTON: if (event->modifiers() == Qt::ShiftModifier && m_dragEnabled) { m_interactionState = StateMoving; m_dragOriginPos = event->localPos(); m_dragCurrentPos = m_dragOriginPos; } else { // We say 'brushing', but we mean 'selecting the current brushed // item' m_interactionState = StateBrushing; } break; case SPECIAL_BUTTON: m_interactionState = StateNone; m_selection.assign(m_selection.size(), false); emit selectionInteractivelyChanged(m_selection); m_shouldUpdateMaterials = true; update(); break; } break; case StateBrushing: case StateSelecting: case StateMoving: // Probably shouldn't reach these break; } } void Scatterplot::mouseMoveEvent(QMouseEvent *event) { switch (m_interactionState) { case StateBrushing: // Move while brushing becomes selecting, hence the 'fall through' m_interactionState = StateSelecting; m_dragOriginPos = event->localPos(); // fall through case StateSelecting: m_dragCurrentPos = event->localPos(); update(); break; case StateMoving: m_dragCurrentPos = event->localPos(); m_shouldUpdateGeometry = true; update(); break; case StateNone: case StateSelected: break; } } void Scatterplot::mouseReleaseEvent(QMouseEvent *event) { bool mergeSelection = (event->modifiers() == Qt::ControlModifier); switch (m_interactionState) { case StateBrushing: // Mouse clicked with brush target; set new selection or append to // current if (!mergeSelection) { m_selection.assign(m_selection.size(), false); } if (m_brushedItem == -1) { m_interactionState = StateNone; if (m_anySelected && !mergeSelection) { m_anySelected = false; emit selectionInteractivelyChanged(m_selection); m_shouldUpdateMaterials = true; update(); } } else { m_interactionState = StateSelected; m_selection[m_brushedItem] = !m_selection[m_brushedItem]; if (m_selection[m_brushedItem]) { m_anySelected = true; } emit selectionInteractivelyChanged(m_selection); m_shouldUpdateMaterials = true; update(); } break; case StateSelecting: { // Selecting points and mouse is now released; update selection and // brush interactiveSelection(mergeSelection); m_interactionState = m_anySelected ? StateSelected : StateNone; QPoint pos = event->pos(); m_brushedItem = m_quadtree->nearestTo(pos.x(), pos.y()); emit itemInteractivelyBrushed(m_brushedItem); m_shouldUpdateMaterials = true; update(); } break; case StateMoving: // Moving points and now stopped; apply manipulation m_interactionState = StateSelected; applyManipulation(); m_shouldUpdateGeometry = true; update(); m_dragOriginPos = m_dragCurrentPos; break; case StateNone: case StateSelected: break; } } void Scatterplot::hoverEnterEvent(QHoverEvent *event) { QPointF pos = event->posF(); m_brushedItem = m_quadtree->nearestTo(pos.x(), pos.y()); emit itemInteractivelyBrushed(m_brushedItem); update(); } void Scatterplot::hoverMoveEvent(QHoverEvent *event) { QPointF pos = event->posF(); m_brushedItem = m_quadtree->nearestTo(pos.x(), pos.y()); emit itemInteractivelyBrushed(m_brushedItem); update(); } void Scatterplot::hoverLeaveEvent(QHoverEvent *event) { m_brushedItem = -1; emit itemInteractivelyBrushed(m_brushedItem); update(); } void Scatterplot::interactiveSelection(bool mergeSelection) { if (!mergeSelection) { m_selection.assign(m_selection.size(), false); } std::vector<int> selected; m_quadtree->query(QRectF(m_dragOriginPos, m_dragCurrentPos), selected); for (auto i: selected) { m_selection[i] = true; } for (auto isSelected: m_selection) { if (isSelected) { m_anySelected = true; break; } } emit selectionInteractivelyChanged(m_selection); } void Scatterplot::setSelection(const std::vector<bool> &selection) { if (m_selection.size() != selection.size()) { return; } m_selection = selection; emit selectionChanged(m_selection); m_shouldUpdateMaterials = true; update(); } void Scatterplot::brushItem(int item) { m_brushedItem = item; update(); } void Scatterplot::applyManipulation() { m_sx.inverse(); m_sy.inverse(); LinearScale<float> rx = m_sx; LinearScale<float> ry = m_sy; m_sy.inverse(); m_sx.inverse(); float tx = m_dragCurrentPos.x() - m_dragOriginPos.x(); float ty = m_dragCurrentPos.y() - m_dragOriginPos.y(); for (std::vector<bool>::size_type i = 0; i < m_selection.size(); i++) { if (m_selection[i]) { arma::rowvec row = m_xy.row(i); row[0] = rx(m_sx(row[0]) + tx); row[1] = ry(m_sy(row[1]) + ty); m_xy.row(i) = row; } } updateQuadTree(); emit xyInteractivelyChanged(m_xy); } void Scatterplot::updateQuadTree() { m_sx.setRange(PADDING, width() - PADDING); m_sy.setRange(height() - PADDING, PADDING); if (m_quadtree) { delete m_quadtree; } m_quadtree = new QuadTree(QRectF(x(), y(), width(), height())); for (arma::uword i = 0; i < m_xy.n_rows; i++) { const arma::rowvec &row = m_xy.row(i); m_quadtree->insert(m_sx(row[0]), m_sy(row[1]), (int) i); } } QuadTree::QuadTree(const QRectF &bounds) : m_bounds(bounds) , m_value(-1) , m_nw(0), m_ne(0), m_sw(0), m_se(0) { } QuadTree::~QuadTree() { if (m_nw) { delete m_nw; delete m_ne; delete m_sw; delete m_se; } } bool QuadTree::subdivide() { float halfWidth = m_bounds.width() / 2; float halfHeight = m_bounds.height() / 2; m_nw = new QuadTree(QRectF(m_bounds.x(), m_bounds.y(), halfWidth, halfHeight)); m_ne = new QuadTree(QRectF(m_bounds.x() + halfWidth, m_bounds.y(), halfWidth, halfHeight)); m_sw = new QuadTree(QRectF(m_bounds.x(), m_bounds.y() + halfHeight, halfWidth, halfHeight)); m_se = new QuadTree(QRectF(m_bounds.x() + halfWidth, m_bounds.y() + halfHeight, halfWidth, halfHeight)); int value = m_value; m_value = -1; return m_nw->insert(m_x, m_y, value) || m_ne->insert(m_x, m_y, value) || m_sw->insert(m_x, m_y, value) || m_se->insert(m_x, m_y, value); } bool QuadTree::insert(float x, float y, int value) { if (!m_bounds.contains(x, y)) { return false; } if (m_nw) { return m_nw->insert(x, y, value) || m_ne->insert(x, y, value) || m_sw->insert(x, y, value) || m_se->insert(x, y, value); } if (m_value >= 0) { subdivide(); return insert(x, y, value); } m_x = x; m_y = y; m_value = value; return true; } int QuadTree::nearestTo(float x, float y) const { if (!m_bounds.contains(x, y)) { return -1; } int q; if (m_nw) { q = m_nw->nearestTo(x, y); if (q >= 0) return q; q = m_ne->nearestTo(x, y); if (q >= 0) return q; q = m_sw->nearestTo(x, y); if (q >= 0) return q; q = m_se->nearestTo(x, y); if (q >= 0) return q; } float dist = std::numeric_limits<float>::infinity(); nearestTo(x, y, q, dist); if (dist < BRUSHING_MAX_DIST * BRUSHING_MAX_DIST) return q; return -1; } void QuadTree::nearestTo(float x, float y, int &nearest, float &dist) const { if (m_nw) { m_nw->nearestTo(x, y, nearest, dist); m_ne->nearestTo(x, y, nearest, dist); m_sw->nearestTo(x, y, nearest, dist); m_se->nearestTo(x, y, nearest, dist); } else if (m_value >= 0) { float d = (m_x - x)*(m_x - x) + (m_y - y)*(m_y - y); if (d < dist) { nearest = m_value; dist = d; } } } int QuadTree::query(float x, float y) const { if (!m_bounds.contains(x, y)) { // There is no way we could find the point return -1; } if (m_nw) { int q = -1; q = m_nw->query(x, y); if (q >= 0) return q; q = m_ne->query(x, y); if (q >= 0) return q; q = m_sw->query(x, y); if (q >= 0) return q; q = m_se->query(x, y); return q; } return m_value; } void QuadTree::query(const QRectF &rect, std::vector<int> &result) const { if (!m_bounds.intersects(rect)) { return; } if (m_nw) { m_nw->query(rect, result); m_ne->query(rect, result); m_sw->query(rect, result); m_se->query(rect, result); } else if (rect.contains(m_x, m_y) && m_value != -1) { result.push_back(m_value); } }
28.609694
115
0.626973
4612f6436bee91d7c6b0cfc94f22418164a6900d
2,187
cpp
C++
排序/交换排序/P324.6.cpp
Ruvikm/Wangdao-Data-Structures
e00494f40c0be9d81229062bf69fe1e12e340773
[ "MIT" ]
103
2021-01-07T13:03:57.000Z
2022-03-31T03:10:35.000Z
排序/交换排序/P324.6.cpp
fu123567/Wangdao-Data-Structures
e00494f40c0be9d81229062bf69fe1e12e340773
[ "MIT" ]
null
null
null
排序/交换排序/P324.6.cpp
fu123567/Wangdao-Data-Structures
e00494f40c0be9d81229062bf69fe1e12e340773
[ "MIT" ]
23
2021-04-10T07:53:03.000Z
2022-03-31T00:33:05.000Z
#include <cstdio> #include <iostream> #include <algorithm> #include <time.h> #include <stdlib.h> using namespace std; #pragma region 建立顺序存储的线性表 #define MAX 30 #define _for(i,a,b) for( int i=(a); i<(b); ++i) #define _rep(i,a,b) for( int i=(a); i<=(b); ++i) typedef struct { int data[MAX]; int length; }List; void swap(int& a, int& b) { int t; t = a; a = b; b = t; } //给定一个List,传入List的大小,要逆转的起始位置 void Reserve(List& list, int start, int end, int size) { if (end <= start || end >= size) { return; } int mid = (start + end) / 2; _rep(i, 0, mid - start) { swap(list.data[start + i], list.data[end - i]); } } void PrintList(List list) { _for(i, 0, list.length) { cout << list.data[i] << " "; } cout << endl; } void BuildList(List& list, int Len, int Data[]) { list.length = Len; _for(i, 0, list.length) list.data[i] = Data[i]; } #pragma endregion //P323.6 //〖2016统考真题】已知由n(n≥2)个正整数构成的集合A = { ak|0 ≤ k ≤ n }, 将其划分为两 //个不相交的子集A1和A2, 元素个数分别是n1和n2, A1和A2中的元素之和分别为S1和S2 //设计一个尽可能高效的划分算法, 满足|n1 - n2|最小且| S1 - S1|最大。要求 //1)给出算法的基本设计思想 //2)根据设计思想, 采用C或C++语言描述算法, 关键之处给出注释 //3)说明你所设计算法的平均时间复杂度和空间复杂度 int Partiton(List& list) { int low = 0, low0 = 0, high = list.length - 1, high0 = list.length - 1, k = list.length / 2; bool NoFind = true; while (NoFind) { int pivot = list.data[low]; while (low < high) { while (low < high && list.data[high] >= pivot) high--; if (low != high) list.data[low] = list.data[high]; while (low < high && list.data[low] <= pivot) low++; if (low != high) list.data[high] = list.data[low]; } list.data[low] = pivot; if (low == k - 1) NoFind = false; else { if (low < k - 1) { low0 = ++low; high = high0; } else { high0 = --high; low = low0; } } } int s1 = 0, s2 = 0; _for(i, 0, k) s1 += list.data[i]; _for(i, k, list.length) s2 += list.data[i]; return s2 - s1; } int main() { List list; int Data[] = { 1,43,22,12,14,24,18,54,32,81 }; BuildList(list, 10, Data); cout << "list为:" << endl; PrintList(list); cout << "排序后:" << endl; sort(list.data, list.data + 10); PrintList(list); cout << "S2-S1最大值为:" << Partiton(list) << endl; return 0; }
19.184211
93
0.581619
4615023df5a596ca4b465687e621a84d88042a86
359
cpp
C++
module02/ex02/main.cpp
JLL32/piscine-cpp
d1d3296d8e25a1c33f7c92df4f61e6f76b8dab8c
[ "MIT" ]
null
null
null
module02/ex02/main.cpp
JLL32/piscine-cpp
d1d3296d8e25a1c33f7c92df4f61e6f76b8dab8c
[ "MIT" ]
null
null
null
module02/ex02/main.cpp
JLL32/piscine-cpp
d1d3296d8e25a1c33f7c92df4f61e6f76b8dab8c
[ "MIT" ]
null
null
null
#include "Fixed.hpp" int main() { Fixed a; Fixed const b(Fixed(5.05f) * Fixed(2)); std::cout << a << std::endl; std::cout << ++a << std::endl; std::cout << a << std::endl; std::cout << a++ << std::endl; std::cout << a << std::endl; std::cout << b << std::endl; std::cout << Fixed::max(a, b) << std::endl; return 0; }
22.4375
47
0.487465
4617cf0f44153d1785df9b344a815585abe10e79
1,569
cpp
C++
Codeforces/MailRu/2018/Round1/C.cpp
Mindjolt2406/Competitive-Programming
d000d98bf7005ee4fb809bcea2f110e4c4793b80
[ "MIT" ]
2
2018-12-11T14:37:24.000Z
2022-01-23T18:11:54.000Z
Codeforces/MailRu/2018/Round1/C.cpp
Mindjolt2406/Competitive-Programming
d000d98bf7005ee4fb809bcea2f110e4c4793b80
[ "MIT" ]
null
null
null
Codeforces/MailRu/2018/Round1/C.cpp
Mindjolt2406/Competitive-Programming
d000d98bf7005ee4fb809bcea2f110e4c4793b80
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define mt make_tuple #define mp make_pair #define pu push_back #define INF 1000000001 #define MOD 1000000007 #define ll long long int #define ld long double #define vi vector<int> #define vll vector<long long int> #define sc(n) scanf("%d",&n); #define scll(n) scanf("%lld",&n); #define scld(n) scanf("%Lf",&n); #define scr(s) {char temp[1000000];scanf("%s",temp);s = temp;} using namespace std; int main() { int n; sc(n); int*l = new int[n]; int*r = new int[n]; for(int i=0;i<n;i++) sc(l[i]); for(int i=0;i<n;i++) sc(r[i]); vector<int> v; set<int> s; int max1 = -1; for(int i=0;i<n;i++) { if(l[i]>i || r[i]>n-1-i) {cout<<"NO"<<endl;return 0;} else {v.pu(n-l[i]-r[i]);s.insert(n-l[i]-r[i]);max1 = max(max1,l[i]+r[i]);} } // cout<<s.size()<<en dl; // for(int i=0;i<n;i++) // { // for(int j=i+1;j<n;j++) // { // if(l[i]+r[i]<l[j]+r[j] && r[i]<r[j]) {cout<<"NO"<<endl;return 0;} // if(l[i]+r[i]<l[j]+r[j] && l[i]>l[j]) {cout<<"NO"<<endl;return 0;} // } // } // map<int,int> dl,dr; // int maxl,maxr for(int i=0;i<n;i++) { // cout<<"i: "<<i<<endl; int count = 0; for(int j=i+1;j<n;j++) { if(l[j]+r[j]<l[i]+r[i]) count++; } if(count>r[i]) {cout<<"NO"<<endl;return 0;} } for(int i=n-1;i>=0;i--) { int count = 0; for(int j=i-1;j>=0;j--) { if(l[j]+r[j]<l[i]+r[i]) count++; } if(count>l[i]) {cout<<"NO"<<endl;return 0;} } cout<<"YES"<<endl; for(int i=0;i<v.size();i++) cout<<v[i]<<" ";cout<<endl; return 0; }
22.73913
78
0.50478
46192fd5c256d3617f496bcb3fad21959dbb54f8
1,769
cpp
C++
vlc_linux/vlc-3.0.16/modules/gui/skins2/commands/cmd_playtree.cpp
Brook1711/biubiu_Qt6
5c4d22a1d1beef63bc6c7738dce6c477c4642803
[ "MIT" ]
null
null
null
vlc_linux/vlc-3.0.16/modules/gui/skins2/commands/cmd_playtree.cpp
Brook1711/biubiu_Qt6
5c4d22a1d1beef63bc6c7738dce6c477c4642803
[ "MIT" ]
null
null
null
vlc_linux/vlc-3.0.16/modules/gui/skins2/commands/cmd_playtree.cpp
Brook1711/biubiu_Qt6
5c4d22a1d1beef63bc6c7738dce6c477c4642803
[ "MIT" ]
null
null
null
/***************************************************************************** * cmd_playtree.cpp ***************************************************************************** * Copyright (C) 2005 the VideoLAN team * $Id: 626ba09b03156290eba9bc3bb654ec031a8f75de $ * * Authors: Antoine Cellerier <dionoea@videolan.org> * Clément Stenac <zorglub@videolan.org> * * 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., * 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "cmd_playtree.hpp" #include <vlc_playlist.h> #include "../src/vlcproc.hpp" #include "../utils/var_bool.hpp" void CmdPlaytreeDel::execute() { m_rTree.delSelected(); } void CmdPlaytreeSort::execute() { /// \todo Choose sort method/order - Need more commands /// \todo Choose the correct view playlist_t *p_playlist = getPL(); PL_LOCK; playlist_RecursiveNodeSort( p_playlist, &p_playlist->root, SORT_TITLE, ORDER_NORMAL ); PL_UNLOCK; // Ask for rebuild VlcProc::instance( getIntf() )->getPlaytreeVar().onChange(); }
36.854167
79
0.616167
461a10273aba9fcf0e0d3aa55bec17e788550bae
271
cpp
C++
Test/run-test.cpp
As-12/Header-only-skeleton
17603f3ef8c1808000213d8f12a7f6271c15de25
[ "MIT" ]
null
null
null
Test/run-test.cpp
As-12/Header-only-skeleton
17603f3ef8c1808000213d8f12a7f6271c15de25
[ "MIT" ]
null
null
null
Test/run-test.cpp
As-12/Header-only-skeleton
17603f3ef8c1808000213d8f12a7f6271c15de25
[ "MIT" ]
null
null
null
// AllTests.cpp #include <gtest/gtest.h> #include <Library/Framework.hpp> TEST(SubtractTest1, SubtractTwoNumbers) { Library::print(); EXPECT_EQ(5, 5); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
15.055556
41
0.675277
461aa61039c0c41d53644a5192d06be4b61e2968
210
cpp
C++
266. Palindrome Permutation.cpp
rajeev-ranjan-au6/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
3
2020-12-30T00:29:59.000Z
2021-01-24T22:43:04.000Z
266. Palindrome Permutation.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
266. Palindrome Permutation.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
class Solution { public: bool canPermutePalindrome(string s) { unordered_map<char, int>m; int odd = 0; for(auto c: s) (m[c]++ % 2) ? odd-- : odd++; return odd <= 1; } };
21
52
0.504762
462041eb825084ccf615b4abf767bd7c7a37acd1
520
cpp
C++
Engine/Source/Core/Types/Time.cpp
SparkyPotato/Ignis
40cf87c03db7c07d3a05ab2c30bbe4fe3b16156c
[ "MIT" ]
1
2021-02-27T15:42:47.000Z
2021-02-27T15:42:47.000Z
Engine/Source/Core/Types/Time.cpp
SparkyPotato/Ignis
40cf87c03db7c07d3a05ab2c30bbe4fe3b16156c
[ "MIT" ]
null
null
null
Engine/Source/Core/Types/Time.cpp
SparkyPotato/Ignis
40cf87c03db7c07d3a05ab2c30bbe4fe3b16156c
[ "MIT" ]
null
null
null
/// Copyright (c) 2021 Shaye Garg. #include "Core/Types/Time.h" #include "Core/Platform/Platform.h" #ifdef PLATFORM_WINDOWS # include <Windows.h> #endif namespace Ignis { #ifdef PLATFORM_WINDOWS Time Time::Now() { SYSTEMTIME time; GetLocalTime(&time); return Time{ .Year = time.wYear, .Month = u8(time.wMonth), .Day = u8(time.wDay), .WeekDay = u8(time.wDayOfWeek), .Hour = u8(time.wHour), .Minute = u8(time.wMinute), .Millisecond = time.wMilliseconds }; } #else Time Time::Now() { } #endif }
13.684211
38
0.667308
46222bf791ebd8f20bf205a35de1fc7d309e10da
1,485
cpp
C++
src/VKHelpers/Command/bindings.cpp
hiradyazdan/sdf-ray4d-engine
d71385e23cb630c54ff620ba1dff287ad90861b8
[ "MIT" ]
2
2021-09-28T22:15:44.000Z
2022-02-03T22:25:46.000Z
src/VKHelpers/Command/bindings.cpp
hiradyazdan/sdf-ray4d-engine
d71385e23cb630c54ff620ba1dff287ad90861b8
[ "MIT" ]
null
null
null
src/VKHelpers/Command/bindings.cpp
hiradyazdan/sdf-ray4d-engine
d71385e23cb630c54ff620ba1dff287ad90861b8
[ "MIT" ]
null
null
null
/***************************************************** * Partial Class: CommandHelper * Members: Command Buffer Bindings/Overloads (Private) *****************************************************/ #include "VKHelpers/Command.hpp" using namespace sdfRay4d::vkHelpers; /** * * @param[in] _material */ void CommandHelper::executeCmdBind( const MaterialPtr &_material ) noexcept { m_deviceFuncs->vkCmdBindPipeline( m_cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, _material->pipeline ); device::Size vbOffset = 0; m_deviceFuncs->vkCmdBindVertexBuffers( m_cmdBuffer, 0, 1, &_material->buffer, &vbOffset ); const auto &descSets = _material->descSets; const auto &descSetCount = descSets.size(); // the dynamic buffer points to the beginning of the vertex uniform data for the current frame. const uint32_t frameDynamicOffset = m_frameId * vbOffset; std::vector<uint32_t> frameDynamicOffsets = {}; // memset for(auto i = 0; i < descSetCount; i++) { for (auto j = 0; j < _material->dynamicDescCount; j++) { frameDynamicOffsets.push_back(frameDynamicOffset); } const auto &dynamicOffsetCount = frameDynamicOffsets.size(); m_deviceFuncs->vkCmdBindDescriptorSets( m_cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, _material->pipelineLayout, i, descSetCount, &descSets[i], dynamicOffsetCount, dynamicOffsetCount > 0 ? frameDynamicOffsets.data() : nullptr ); } }
25.169492
97
0.648485
4624a63178202e6ae40f52aa49966a55347aa1d5
389
cpp
C++
src/lib/output/buzzer.cpp
aescariom/In3
0e6adcca3492bc69912170bf9a39719a407873c4
[ "MIT" ]
3
2016-09-23T18:11:32.000Z
2021-05-31T20:50:47.000Z
src/lib/output/buzzer.cpp
aescariom/In3
0e6adcca3492bc69912170bf9a39719a407873c4
[ "MIT" ]
1
2016-09-23T18:14:32.000Z
2016-10-08T21:11:14.000Z
src/lib/output/buzzer.cpp
aescariom/In3
0e6adcca3492bc69912170bf9a39719a407873c4
[ "MIT" ]
1
2017-03-24T19:30:43.000Z
2017-03-24T19:30:43.000Z
#include "buzzer.h" Buzzer::Buzzer(volatile uint8_t *port, volatile uint8_t *dir, uint8_t mask){ this->port = port; this->dir = dir; this->mask = mask; } void Buzzer::init(){ *(this->dir) |= 1 << this->mask; // output pin } void Buzzer::beep(){ this->toggle(); _delay_ms(_O_BUZZER_DELAY_MS); this->toggle(); } void Buzzer::toggle(){ *(this->port) ^= (1 << this->mask); }
17.681818
76
0.619537
4624bd768a1ee740003c4667e258e09558e94c5b
4,891
cpp
C++
Math/Generating Function of a Linear Recurrence.cpp
bazzyadb/all-code
cf3039641b5aa84b1c5b184a95d69bd4091974c9
[ "MIT" ]
1,639
2021-09-15T09:12:06.000Z
2022-03-31T22:58:57.000Z
Math/Generating Function of a Linear Recurrence.cpp
bazzyadb/all-code
cf3039641b5aa84b1c5b184a95d69bd4091974c9
[ "MIT" ]
16
2022-01-15T17:50:08.000Z
2022-01-28T12:55:21.000Z
Math/Generating Function of a Linear Recurrence.cpp
bazzyadb/all-code
cf3039641b5aa84b1c5b184a95d69bd4091974c9
[ "MIT" ]
444
2021-09-15T09:17:41.000Z
2022-03-29T18:21:46.000Z
#include<bits/stdc++.h> using namespace std; const int N = 3e3 + 9, mod = 998244353; template <int32_t MOD> struct modint { int32_t value; modint() = default; modint(int32_t value_) : value(value_) {} inline modint<MOD> operator + (modint<MOD> other) const { int32_t c = this->value + other.value; return modint<MOD>(c >= MOD ? c - MOD : c); } inline modint<MOD> operator - (modint<MOD> other) const { int32_t c = this->value - other.value; return modint<MOD>(c < 0 ? c + MOD : c); } inline modint<MOD> operator * (modint<MOD> other) const { int32_t c = (int64_t)this->value * other.value % MOD; return modint<MOD>(c < 0 ? c + MOD : c); } inline modint<MOD> & operator += (modint<MOD> other) { this->value += other.value; if (this->value >= MOD) this->value -= MOD; return *this; } inline modint<MOD> & operator -= (modint<MOD> other) { this->value -= other.value; if (this->value < 0) this->value += MOD; return *this; } inline modint<MOD> & operator *= (modint<MOD> other) { this->value = (int64_t)this->value * other.value % MOD; if (this->value < 0) this->value += MOD; return *this; } inline modint<MOD> operator - () const { return modint<MOD>(this->value ? MOD - this->value : 0); } modint<MOD> pow(uint64_t k) const { modint<MOD> x = *this, y = 1; for (; k; k >>= 1) { if (k & 1) y *= x; x *= x; } return y; } modint<MOD> inv() const { return pow(MOD - 2); } // MOD must be a prime inline modint<MOD> operator / (modint<MOD> other) const { return *this * other.inv(); } inline modint<MOD> operator /= (modint<MOD> other) { return *this *= other.inv(); } inline bool operator == (modint<MOD> other) const { return value == other.value; } inline bool operator != (modint<MOD> other) const { return value != other.value; } inline bool operator < (modint<MOD> other) const { return value < other.value; } inline bool operator > (modint<MOD> other) const { return value > other.value; } }; template <int32_t MOD> modint<MOD> operator * (int64_t value, modint<MOD> n) { return modint<MOD>(value) * n; } template <int32_t MOD> modint<MOD> operator * (int32_t value, modint<MOD> n) { return modint<MOD>(value % MOD) * n; } template <int32_t MOD> istream & operator >> (istream & in, modint<MOD> &n) { return in >> n.value; } template <int32_t MOD> ostream & operator << (ostream & out, modint<MOD> n) { return out << n.value; } using mint = modint<mod>; vector<mint> BerlekampMassey(vector<mint> S) { int n = (int)S.size(), L = 0, m = 0; vector<mint> C(n), B(n), T; C[0] = B[0] = 1; mint b = 1; for(int i = 0; i < n; i++) { ++m; mint d = S[i]; for(int j = 1; j <= L; j++) d += C[j] * S[i - j]; if (d == 0) continue; T = C; mint coef = d * b.inv(); for(int j = m; j < n; j++) C[j] -= coef * B[j - m]; if (2 * L > i) continue; L = i + 1 - L; B = T; b = d; m = 0; } C.resize(L + 1); C.erase(C.begin()); for(auto &x: C) x *= -1; return C; } // a[k] = c[0] * a[k - 1] + c[1] * a[k - 2] + ... for k >= n mint yo(vector<mint> a, vector<mint> c) { int n = a.size(); if (!n) return 0; vector<mint> p(n + 1, 0); p[0] = 1; for (int i = 0; i < n; i++) { p[i + 1] = -c[i]; } vector<mint> up(n + n, 0); for (int i = 0; i < n; i++) { for (int j = 0; j <= n; j++) { up[i + j] += a[i] * p[j]; } } up.resize(n); // generating function of the recurrence is up / p // now find its derivative and find the value at x = 1 mint v = 0; for (int i = 0; i < p.size(); i++) { v += p[i]; } mint u = 0; for (int i = 0; i < up.size(); i++) { u += up[i]; } mint du = 0; for (int i = 0; i < up.size(); i++) { du += up[i] * i; } mint dv = 0; for (int i = 0; i < p.size(); i++) { dv += p[i] * i; } return (v * du - u * dv) / (v * v); } mint dp[N * 2][N]; vector<int> g[N]; int deg[N]; mint ideg[N]; int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); int n; cin >> n; for (int i = 1; i <= n; i++) { int x, y; cin >> x >> y; } int m; cin >> m; while (m--) { int u, v; cin >> u >> v; g[u].push_back(v); g[v].push_back(u); ++deg[u]; ++deg[v]; } for (int i = 1; i <= n; i++) { ideg[i] = mint(deg[i]).inv(); } dp[0][1] = 1; for (int k = 1; k <= n * 2; k++) { for (int u = 1; u <= n; u++) { if (u == n) continue; for (auto v: g[u]) { dp[k][v] += dp[k - 1][u] * ideg[u]; } } } vector<mint> cur; for (int i = 0; i <= 2 * n; i++) { cur.push_back(dp[i][n]); } auto tr = BerlekampMassey(cur); cur.resize(tr.size()); cout << yo(cur, tr) << '\n'; return 0; } // https://codeforces.com/gym/102268/problem/E
35.963235
172
0.512983
4627c6de952526133cd87b47474dcad43cf53d93
1,025
cpp
C++
Homework01/Decryption/decryption.cpp
xmelkov/pb173-test
065b43cb05a1435c86eb5f582659eb03693a4302
[ "MIT" ]
null
null
null
Homework01/Decryption/decryption.cpp
xmelkov/pb173-test
065b43cb05a1435c86eb5f582659eb03693a4302
[ "MIT" ]
8
2017-02-24T05:05:35.000Z
2017-02-26T11:48:45.000Z
Homework01/Decryption/decryption.cpp
xmelkov/pb173-test
065b43cb05a1435c86eb5f582659eb03693a4302
[ "MIT" ]
null
null
null
#include ".\decryption.h" // Required for file input #include "..\commonFiles\aesFileIO.h" // Required for the hash function #include "..\libExcerpt\mbedtls\sha512.h" // Required for std::equal #include <algorithm> // Required for file input #include <fstream> // Required for error handling #include <stdexcept> bool verifyFile(const AESData & contents, const std::string & signatureFilePath) { SHA512output hash1 = {}; mbedtls_sha512(contents.data(), static_cast<size_t>(contents.size()), hash1.data(), 0); SHA512output hash2 = {}; std::ifstream hashInputFile; hashInputFile.open(signatureFilePath, std::ios::in); if (!hashInputFile.is_open()) { throw std::domain_error("Unable to read file signature and therefore verify file"); } std::string hashString(""); hashString.resize(SHA512_OUTPUT_SIZE); hashInputFile.getline(&hashString[0], constexpr(2*SHA512_OUTPUT_SIZE)); hashInputFile.close(); hash2 = hashFromString(hashString); return std::equal(hash1.begin(), hash1.end(), hash2.begin()); }
25
88
0.733659
462964858587a0c330f6bd85d4f57773591d9a22
465
cc
C++
modules/print_binary_tree.cc
xsthunder/a
3c30f31c59030d70462b71ef28c5eee19c6eddd6
[ "MIT" ]
1
2018-07-22T04:52:10.000Z
2018-07-22T04:52:10.000Z
modules/print_binary_tree.cc
xsthunder/a
3c30f31c59030d70462b71ef28c5eee19c6eddd6
[ "MIT" ]
1
2018-08-11T13:29:59.000Z
2018-08-11T13:31:28.000Z
modules/print_binary_tree.cc
xsthunder/a
3c30f31c59030d70462b71ef28c5eee19c6eddd6
[ "MIT" ]
null
null
null
#include<cstdio> #include<iostream> using namespace std; template <typename T> void pT(T *A, int d){//d for depth int sum=0; cout<<"------tree starts\n"; for(int i=0;i<d;i++){ cout<<i+1<<':'; for(int j=0;j<1<<i;j++){ cout<<*(A+sum++)<<' '; } cout<<endl; } cout<<"------tree ends\n"; } template <typename T> void pA(T *begin,int n){ for(int i=0;i<n;i++){ cout<<*(begin+i)<<' '; } printf("\n"); } int main(){ int A[10]={1,2,3,4,5,6,7,8}; pT(A,3); }
20.217391
87
0.535484
462cd92916a78d6d435ad71220631e0b3c63cc15
2,623
cpp
C++
plugins/goose/src/sub/QualityTemplatesConfigReader.cpp
openenergysolutions/openfmb.adapters
3c95b1c460a8967190bdd9ae16677a4e2a5d9861
[ "Apache-2.0" ]
1
2021-08-20T12:14:11.000Z
2021-08-20T12:14:11.000Z
plugins/goose/src/sub/QualityTemplatesConfigReader.cpp
openenergysolutions/openfmb.adapters
3c95b1c460a8967190bdd9ae16677a4e2a5d9861
[ "Apache-2.0" ]
3
2021-06-16T19:25:23.000Z
2021-09-02T14:39:10.000Z
plugins/goose/src/sub/QualityTemplatesConfigReader.cpp
openenergysolutions/openfmb.adapters
3c95b1c460a8967190bdd9ae16677a4e2a5d9861
[ "Apache-2.0" ]
null
null
null
// SPDX-FileCopyrightText: 2021 Open Energy Solutions Inc // // SPDX-License-Identifier: Apache-2.0 #include "sub/QualityTemplatesConfigReader.h" #include "ConfigStrings.h" #include <adapter-util/util/YAMLUtil.h> #include <adapter-util/config/YAMLGetters.h> namespace adapter { namespace goose { QualityTemplatesConfigReader::QualityTemplatesConfigReader(const YAML::Node& node) { util::yaml::foreach(node, [this](const YAML::Node& quality_node) { auto id = util::yaml::require_string(quality_node, keys::quality_id); auto quality = std::make_shared<commonmodule::Quality>(); quality->set_validity(static_cast<commonmodule::ValidityKind>(util::yaml::get::enum_value(quality_node, keys::quality_validity, *commonmodule::ValidityKind_descriptor()))); auto details = quality->mutable_detailqual(); details->set_overflow(util::yaml::require(quality_node, keys::quality_overflow).as<bool>()); details->set_outofrange(util::yaml::require(quality_node, keys::quality_outofrange).as<bool>()); details->set_badreference(util::yaml::require(quality_node, keys::quality_badreference).as<bool>()); details->set_oscillatory(util::yaml::require(quality_node, keys::quality_oscillatory).as<bool>()); details->set_failure(util::yaml::require(quality_node, keys::quality_failure).as<bool>()); details->set_olddata(util::yaml::require(quality_node, keys::quality_olddata).as<bool>()); details->set_inconsistent(util::yaml::require(quality_node, keys::quality_inconsistent).as<bool>()); details->set_inaccurate(util::yaml::require(quality_node, keys::quality_inaccurate).as<bool>()); quality->set_source(static_cast<commonmodule::SourceKind>(util::yaml::get::enum_value(quality_node, keys::quality_source, *commonmodule::SourceKind_descriptor()))); quality->set_test(util::yaml::require(quality_node, keys::quality_test).as<bool>()); quality->set_operatorblocked(util::yaml::require(quality_node, keys::quality_operatorblocked).as<bool>()); auto result = m_templates.insert({ id, quality }); if(!result.second) { throw api::Exception{"Quality template id \"" + id + "\" already used."}; } }); } const std::shared_ptr<commonmodule::Quality> QualityTemplatesConfigReader::get(const std::string& id) const { auto result = m_templates.find(id); if(result == m_templates.end()) { throw api::Exception{"Cannot find quality template with id \"" + id + "\"."}; } return result->second; } } // namespace goose } // namespace adapter
46.839286
180
0.704918
462ddf2182fe6a992adb577c17852966085f2cb9
12,751
cpp
C++
source/dynv/Xml.cpp
ericonr/gpick
ff0a3c0c797d3d06d1b8ab257cb2e9dcca389908
[ "BSD-3-Clause" ]
311
2015-03-26T18:38:51.000Z
2022-03-23T07:39:30.000Z
source/dynv/Xml.cpp
ericonr/gpick
ff0a3c0c797d3d06d1b8ab257cb2e9dcca389908
[ "BSD-3-Clause" ]
86
2015-03-27T06:05:57.000Z
2022-01-07T23:04:30.000Z
source/dynv/Xml.cpp
ericonr/gpick
ff0a3c0c797d3d06d1b8ab257cb2e9dcca389908
[ "BSD-3-Clause" ]
42
2015-03-25T16:40:26.000Z
2022-02-23T22:36:47.000Z
/* * Copyright (c) 2009-2020, Albertas Vyšniauskas * 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 software author 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 "Xml.h" #include "Map.h" #include "Variable.h" #include "Types.h" #include "common/Scoped.h" #include <expat.h> #include <sstream> using namespace std::string_literals; namespace dynv { namespace xml { using ValueType = types::ValueType; bool writeStart(std::ostream &stream, const std::string &name) { stream << "<" << name << ">"; return stream.good(); } bool writeStart(std::ostream &stream, const std::string &name, const std::string &type) { stream << "<" << name << " type=\"" << type << "\">"; return stream.good(); } bool writeEnd(std::ostream &stream, const std::string &name) { stream << "</" << name << ">"; return stream.good(); } bool writeListStart(std::ostream &stream, const std::string &name, const std::string &type) { stream << "<" << name << " type=\"" << type << "\" list=\"true\">"; return stream.good(); } struct SerializeVisitor: public boost::static_visitor<bool> { SerializeVisitor(std::ostream &stream, const std::string &name): stream(stream), name(name) { } template<typename T> bool operator()(const T &value) const { if (!writeStart(stream, name, dynv::types::typeHandler<T>().name)) return false; if (!types::xml::write(stream, value)) return false; if (!writeEnd(stream, name)) return false; return true; } bool operator()(const common::Ref<Map> &value) const { if (!writeStart(stream, name, dynv::types::typeHandler<common::Ref<Map>>().name)) return false; if (!types::xml::write(stream, value)) return false; if (!writeEnd(stream, name)) return false; return true; } template<typename T> bool operator()(const std::vector<T> &values) const { using namespace std::string_literals; if (!writeListStart(stream, name, dynv::types::typeHandler<T>().name)) return false; for (const auto &i: values) { if (!writeStart(stream, "li"s)) return false; if (!types::xml::write(stream, i)) return false; if (!writeEnd(stream, "li"s)) return false; } return writeEnd(stream, name); } std::ostream &stream; const std::string &name; }; static bool isTrue(const char *value) { using namespace std::string_literals; if (value == nullptr) return false; return value == "true"s; } enum class EntityType { root, map, list, listItem, value, unknown, }; struct Entity { Entity(Entity &entity) = delete; Entity(Entity &&entity): m_system(entity.m_system), m_entityType(entity.m_entityType), m_valueType(entity.m_valueType), m_value(std::move(entity.m_value)) { } Entity(Map &map, EntityType entityType, ValueType valueType): m_system(map), m_entityType(entityType), m_valueType(valueType) { } Entity(Map &map, EntityType entityType, ValueType valueType, std::unique_ptr<Variable> &&value): m_system(map), m_entityType(entityType), m_valueType(valueType), m_value(std::move(value)) { } void write(const XML_Char *data, int length) { m_data.write(reinterpret_cast<const char *>(data), length); } std::string data() { return m_data.str(); } bool isList() const { return m_entityType == EntityType::list; } bool ignoreData() const { return m_entityType != EntityType::listItem && m_entityType != EntityType::value; } bool isIgnored() const { return m_entityType == EntityType::unknown; } bool hasValue() const { return static_cast<bool>(m_value); } std::unique_ptr<Variable> &value() { return m_value; } Map &map() { return m_system; } ValueType valueType() const { return m_valueType; } EntityType entityType() const { return m_entityType; } private: Map &m_system; std::stringstream m_data; EntityType m_entityType; ValueType m_valueType; std::unique_ptr<Variable> m_value; }; struct Context { Context(Map &map): m_rootFound(false), m_errors(0) { push(map, EntityType::root); } ~Context() { m_entities.clear(); } Entity &entity() { return m_entities.back(); } Entity &parentEntity() { return m_entities.at(m_entities.size() - 2); } bool rootFound() const { return m_rootFound; } void setRootFound() { m_rootFound = true; } void push(Map &map, EntityType entityType, ValueType valueType = ValueType::unknown) { m_entities.emplace_back(map, entityType, valueType); } void push(Map &map, EntityType entityType, ValueType valueType, std::unique_ptr<Variable> &&value) { m_entities.emplace_back(map, entityType, valueType, std::move(value)); } void pop() { m_entities.pop_back(); } void error() { m_errors++; } operator bool() const { return m_errors == 0; } private: bool m_rootFound; std::vector<Entity> m_entities; uint32_t m_errors; }; static const char *getAttribute(const XML_Char **attributes, const std::string &name) { for (auto i = attributes; *i; i += 2) { if (*i == name) return i[1]; } return nullptr; } static void onCharacterData(Context *context, const XML_Char *data, int length) { auto &entity = context->entity(); if (entity.ignoreData() || entity.isIgnored()) return; entity.write(data, length); } struct IsVector: public boost::static_visitor<bool> { IsVector(Entity &entity): entity(entity) { } template<typename T> bool operator()(const T &) const { return false; } template<typename T> bool operator()(const std::vector<T> &) const { return true; } Entity &entity; }; static void onStartElement(Context *context, const XML_Char *name, const XML_Char **attributes) { using namespace std::string_literals; if (!context->rootFound()) { if (name == "root"s) context->setRootFound(); return; } auto &entity = context->entity(); if (entity.isIgnored()) { context->push(entity.map(), EntityType::unknown); return; } if (entity.isList()) { if (!(name && name == "li"s)) { context->push(entity.map(), EntityType::unknown); return; } if (!boost::apply_visitor(IsVector(entity), entity.value()->data())) { context->error(); context->push(entity.map(), EntityType::unknown); return; } if (entity.valueType() == ValueType::map) { auto map = common::Ref<Map>(new Map()); auto &data = entity.value()->data(); context->push(*map, EntityType::listItem); boost::get<std::vector<common::Ref<Map>> &>(data).push_back(std::move(map)); } else { context->push(entity.map(), EntityType::listItem); } return; } auto type = types::stringToType(getAttribute(attributes, "type"s)); auto isList = isTrue(getAttribute(attributes, "list"s)); switch (type) { case ValueType::basicBool: case ValueType::basicFloat: case ValueType::basicInt32: case ValueType::color: case ValueType::string: if (isList) { std::unique_ptr<Variable> variable; switch (type) { case ValueType::basicBool: variable = std::make_unique<Variable>(name, std::vector<bool>()); break; case ValueType::basicFloat: variable = std::make_unique<Variable>(name, std::vector<float>()); break; case ValueType::basicInt32: variable = std::make_unique<Variable>(name, std::vector<int32_t>()); break; case ValueType::color: variable = std::make_unique<Variable>(name, std::vector<Color>()); break; case ValueType::string: variable = std::make_unique<Variable>(name, std::vector<std::string>()); break; case ValueType::map: case ValueType::unknown: break; } context->push(entity.map(), EntityType::list, type, std::move(variable)); } else { context->push(entity.map(), EntityType::value, type); } break; case ValueType::map: if (isList) { auto systems = std::vector<common::Ref<Map>>(); auto variable = std::make_unique<Variable>(name, systems); context->push(entity.map(), EntityType::list, type, std::move(variable)); } else { auto map = common::Ref<Map>(new Map()); entity.map().set(name, map); context->push(*map, EntityType::map, type); } break; case ValueType::unknown: context->push(entity.map(), EntityType::unknown); break; } } static void onEndElement(Context *context, const XML_Char *name) { if (!context->rootFound()) return; auto &entity = context->entity(); if (entity.isIgnored()) { context->pop(); return; } if (entity.isList()) { entity.map().set(std::move(entity.value())); context->pop(); return; } if (entity.entityType() == EntityType::listItem) { auto &listEntity = context->parentEntity(); auto &data = listEntity.value()->data(); switch (listEntity.valueType()) { case ValueType::string: boost::get<std::vector<std::string> &>(data).push_back(entity.data()); break; case ValueType::basicBool: boost::get<std::vector<bool> &>(data).push_back(entity.data() == "true"); break; case ValueType::basicInt32: boost::get<std::vector<int32_t> &>(data).push_back(std::stoi(entity.data())); break; case ValueType::basicFloat: boost::get<std::vector<float> &>(data).push_back(std::stof(entity.data())); break; case ValueType::color: { std::stringstream in(entity.data()); Color color; in >> color[0] >> color[1] >> color[2] >> color[3]; boost::get<std::vector<Color> &>(data).push_back(color); } break; case ValueType::map: break; case ValueType::unknown: break; } context->pop(); return; } if (entity.entityType() == EntityType::value) { auto &map = entity.map(); switch (entity.valueType()) { case ValueType::string: map.set(name, entity.data()); break; case ValueType::basicBool: map.set(name, entity.data() == "true"); break; case ValueType::basicInt32: map.set(name, std::stoi(entity.data())); break; case ValueType::basicFloat: map.set(name, std::stof(entity.data())); break; case ValueType::color: { std::stringstream in(entity.data()); Color color; in >> color[0] >> color[1] >> color[2] >> color[3]; map.set(name, color); } break; case ValueType::map: break; case ValueType::unknown: break; } context->pop(); return; } if (entity.entityType() == EntityType::map) { context->pop(); return; } } bool serialize(std::ostream &stream, const Map &map, bool addRootElement) { if (addRootElement) { stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root>"; if (!stream.good()) return false; } auto visitor = [&stream](const Variable &value) -> bool { if (!boost::apply_visitor(SerializeVisitor(stream, value.name()), value.data())) return false; return true; }; if (!map.visit(visitor)) return false; if (addRootElement) { stream << "</root>"; if (!stream.good()) return false; } return true; } bool deserialize(std::istream &stream, Map &map) { auto parser = XML_ParserCreate("UTF-8"); auto freeParser = common::makeScoped(XML_ParserFree, parser); XML_SetElementHandler(parser, reinterpret_cast<XML_StartElementHandler>(onStartElement), reinterpret_cast<XML_EndElementHandler>(onEndElement)); XML_SetCharacterDataHandler(parser, reinterpret_cast<XML_CharacterDataHandler>(onCharacterData)); xml::Context context(map); XML_SetUserData(parser, &context); for (;;) { auto buffer = XML_GetBuffer(parser, 4096); stream.read(reinterpret_cast<char *>(buffer), 4096); size_t length = stream.gcount(); if (!XML_ParseBuffer(parser, length, length == 0)) { std::cerr << "XML parse error\n"; return false; } if (length == 0) break; } return context; } } }
29.861827
211
0.68426
462e31050795f341ff50315b2347c58bfbb784e9
83
cpp
C++
TP3_Prog_SpaceSim/Main.cpp
Arganancer/S3_TP3_Prog_SpaceSim
43364f6613ad690f81c94f8a027ee3708fa58d3d
[ "MIT" ]
null
null
null
TP3_Prog_SpaceSim/Main.cpp
Arganancer/S3_TP3_Prog_SpaceSim
43364f6613ad690f81c94f8a027ee3708fa58d3d
[ "MIT" ]
null
null
null
TP3_Prog_SpaceSim/Main.cpp
Arganancer/S3_TP3_Prog_SpaceSim
43364f6613ad690f81c94f8a027ee3708fa58d3d
[ "MIT" ]
null
null
null
#include "vld.h" #include "game.h" int main() { game game; return game.run(); }
9.222222
19
0.614458
463015586ebed441a243c541d8c89e57e01a6cc8
13,660
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/app/ProfileManager.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/app/ProfileManager.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/app/ProfileManager.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "elastos/droid/app/ProfileManager.h" #include "elastos/droid/app/CProfile.h" #include "elastos/droid/os/ServiceManager.h" #include "elastos/droid/os/CParcelUuid.h" #include "elastos/droid/provider/CSettingsSystem.h" #include <elastos/utility/logging/Logger.h> #include <Elastos.Droid.Utility.h> using Elastos::Droid::Content::IContentResolver; using Elastos::Droid::Os::IParcelUuid; using Elastos::Droid::Os::CParcelUuid; using Elastos::Droid::Os::IServiceManager; using Elastos::Droid::Os::ServiceManager; using Elastos::Droid::Provider::ISettingsSystem; using Elastos::Droid::Provider::CSettingsSystem; using Elastos::Utility::IUUIDHelper; using Elastos::Utility::CUUIDHelper; namespace Elastos { namespace Droid { namespace App { AutoPtr<IUUID> InitNoProfile() { AutoPtr<IUUIDHelper> helper; CUUIDHelper::AcquireSingleton((IUUIDHelper**)&helper); AutoPtr<IUUID> uuid; helper->FromString(String("00000000-0000-0000-0000-000000000000"), (IUUID**)&uuid); return uuid; } AutoPtr<IUUID> ProfileManager::NO_PROFILE = InitNoProfile(); AutoPtr<IIProfileManager> ProfileManager::sService; const String ProfileManager::TAG("ProfileManager"); const String ProfileManager::SYSTEM_PROFILES_ENABLED("system_profiles_enabled"); static AutoPtr<IProfile> InitEmptyProfile() { AutoPtr<IProfile> tmp; CProfile::New(String("EmptyProfile"), (IProfile**)&tmp); return tmp; } AutoPtr<IProfile> ProfileManager::sEmptyProfile = InitEmptyProfile(); CAR_INTERFACE_IMPL(ProfileManager, Object, IProfileManager) AutoPtr<IIProfileManager> ProfileManager::GetService() { if (sService != NULL) { return sService; } AutoPtr<IInterface> b = ServiceManager::GetService(IContext::PROFILE_SERVICE); sService = IIProfileManager::Probe(b); return sService; } ECode ProfileManager::ToString( /* [out] */ String* str) { VALIDATE_NOT_NULL(str) *str = String("ProfileManager"); return NOERROR; } ECode ProfileManager::constructor( /* [in] */ IContext* context, /* [in] */ IHandler* handler) { mContext = context; return NOERROR; } ECode ProfileManager::SetActiveProfile( /* [in] */ const String& profileName) { AutoPtr<ISettingsSystem> settingsSys; CSettingsSystem::AcquireSingleton((ISettingsSystem**)&settingsSys); AutoPtr<IContentResolver> resolver; mContext->GetContentResolver((IContentResolver**)&resolver); Int32 value; settingsSys->GetInt32(resolver, SYSTEM_PROFILES_ENABLED, 1, &value); if (value == 1) { // Profiles are enabled, return active profile // try { Boolean result; ECode ec = GetService()->SetActiveProfileByName(profileName, &result); if (ec == (ECode)E_REMOTE_EXCEPTION) { return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } } return NOERROR; } ECode ProfileManager::SetActiveProfile( /* [in] */ IUUID* profileUuid) { AutoPtr<ISettingsSystem> settingsSys; CSettingsSystem::AcquireSingleton((ISettingsSystem**)&settingsSys); AutoPtr<IContentResolver> resolver; mContext->GetContentResolver((IContentResolver**)&resolver); Int32 value; settingsSys->GetInt32(resolver, SYSTEM_PROFILES_ENABLED, 1, &value); if (value == 1) { // Profiles are enabled, return active profile // try { Boolean result; AutoPtr<IParcelUuid> uuid; CParcelUuid::New(profileUuid, (IParcelUuid**)&uuid); ECode ec = GetService()->SetActiveProfile(uuid, &result); if (ec == (ECode)E_REMOTE_EXCEPTION) { return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } } return NOERROR; } ECode ProfileManager::GetActiveProfile( /* [out] */ IProfile** profile) { VALIDATE_NOT_NULL(profile) AutoPtr<ISettingsSystem> settingsSys; CSettingsSystem::AcquireSingleton((ISettingsSystem**)&settingsSys); AutoPtr<IContentResolver> resolver; mContext->GetContentResolver((IContentResolver**)&resolver); Int32 value; settingsSys->GetInt32(resolver, SYSTEM_PROFILES_ENABLED, 1, &value); if (value == 1) { // Profiles are enabled, return active profile // try { ECode ec = GetService()->GetActiveProfile(profile); if (ec == (ECode)E_REMOTE_EXCEPTION) { *profile = NULL; return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } } else { // Profiles are not enabled, return the empty profile *profile = sEmptyProfile; REFCOUNT_ADD(*profile) } return NOERROR; } ECode ProfileManager::AddProfile( /* [in] */ IProfile* profile) { // try { Boolean result; return GetService()->AddProfile(profile, &result); // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } } ECode ProfileManager::RemoveProfile( /* [in] */ IProfile* profile) { // try { Boolean result; return GetService()->RemoveProfile(profile, &result); // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } } ECode ProfileManager::UpdateProfile( /* [in] */ IProfile* profile) { // try { return GetService()->UpdateProfile(profile); // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } } ECode ProfileManager::GetProfile( /* [in] */ const String& profileName, /* [out] */ IProfile** profile) { VALIDATE_NOT_NULL(profile) // try { ECode ec = GetService()->GetProfileByName(profileName, profile); if (ec == (ECode)E_REMOTE_EXCEPTION) { *profile = NULL; return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } return NOERROR; } ECode ProfileManager::GetProfile( /* [in] */ IUUID* profileUuid, /* [out] */ IProfile** profile) { VALIDATE_NOT_NULL(profile) // try { AutoPtr<IParcelUuid> uuid; CParcelUuid::New(profileUuid, (IParcelUuid**)&uuid); ECode ec = GetService()->GetProfile(uuid, profile); if (ec == (ECode)E_REMOTE_EXCEPTION) { *profile = NULL; return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } return NOERROR; } ECode ProfileManager::GetProfileNames( /* [out, callee] */ ArrayOf<String>** names) { VALIDATE_NOT_NULL(names) // try { AutoPtr<ArrayOf<IProfile*> > profiles; ECode ec = GetService()->GetProfiles((ArrayOf<IProfile*>**)&profiles); if (ec == (ECode)E_REMOTE_EXCEPTION) { *names = NULL; return ec; } ArrayOf<String>* profileNames = ArrayOf<String>::Alloc(profiles->GetLength()); for (Int32 i = 0; i < profiles->GetLength(); i++) { (*profiles)[i]->GetName(&(*profileNames)[i]); } *names = profileNames; // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } return NOERROR; } ECode ProfileManager::GetProfiles( /* [out, callee] */ ArrayOf<IProfile*>** profiles) { VALIDATE_NOT_NULL(profiles) // try { ECode ec = GetService()->GetProfiles(profiles); if (ec == (ECode)E_REMOTE_EXCEPTION) { *profiles = NULL; return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } return NOERROR; } ECode ProfileManager::ProfileExists( /* [in] */ const String& profileName, /* [out] */ Boolean* isExisted) { VALIDATE_NOT_NULL(isExisted) // try { ECode ec = GetService()->ProfileExistsByName(profileName, isExisted); if (ec == (ECode)E_REMOTE_EXCEPTION) { *isExisted = TRUE; return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // // To be on the safe side, we'll return "true", to prevent duplicate profiles // // from being created. // return true; // } return NOERROR; } ECode ProfileManager::ProfileExists( /* [in] */ IUUID* profileUuid, /* [out] */ Boolean* isExisted) { VALIDATE_NOT_NULL(isExisted) // try { AutoPtr<IParcelUuid> uuid; CParcelUuid::New(profileUuid, (IParcelUuid**)&uuid); ECode ec = GetService()->ProfileExists(uuid, isExisted); if (ec == (ECode)E_REMOTE_EXCEPTION) { *isExisted = TRUE; return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // // To be on the safe side, we'll return "true", to prevent duplicate profiles // // from being created. // return true; // } return NOERROR; } ECode ProfileManager::NotificationGroupExists( /* [in] */ const String& notificationGroupName, /* [out] */ Boolean* isExisted) { VALIDATE_NOT_NULL(isExisted) // try { ECode ec = GetService()->NotificationGroupExistsByName(notificationGroupName, isExisted); if (ec == (ECode)E_REMOTE_EXCEPTION) { *isExisted = TRUE; return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // // To be on the safe side, we'll return "true", to prevent duplicate notification // // groups from being created. // return true; // } return NOERROR; } ECode ProfileManager::GetNotificationGroups( /* [out, callee] */ ArrayOf<INotificationGroup*>** groups) { VALIDATE_NOT_NULL(groups) // try { ECode ec = GetService()->GetNotificationGroups(groups); if (ec == (ECode)E_REMOTE_EXCEPTION) { *groups = NULL; return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } return NOERROR; } ECode ProfileManager::AddNotificationGroup( /* [in] */ INotificationGroup* group) { // try { return GetService()->AddNotificationGroup(group); // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } } ECode ProfileManager::RemoveNotificationGroup( /* [in] */ INotificationGroup* group) { // try { return GetService()->RemoveNotificationGroup(group); // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } } ECode ProfileManager::UpdateNotificationGroup( /* [in] */ INotificationGroup* group) { // try { return GetService()->UpdateNotificationGroup(group); // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } } ECode ProfileManager::GetNotificationGroupForPackage( /* [in] */ const String& pkg, /* [out] */ INotificationGroup** group) { VALIDATE_NOT_NULL(group) // try { ECode ec = GetService()->GetNotificationGroupForPackage(pkg, group); if (ec == (ECode)E_REMOTE_EXCEPTION) { *group = NULL; return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } return NOERROR; } ECode ProfileManager::GetNotificationGroup( /* [in] */ IUUID* groupParcelUuid, /* [out] */ INotificationGroup** group) { VALIDATE_NOT_NULL(group) // try { AutoPtr<IParcelUuid> uuid; CParcelUuid::New(groupParcelUuid, (IParcelUuid**)&uuid); ECode ec = GetService()->GetNotificationGroup(uuid, group); if (ec == (ECode)E_REMOTE_EXCEPTION) { *group = NULL; return ec; } // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } return NOERROR; } ECode ProfileManager::GetActiveProfileGroup( /* [in] */ const String& packageName, /* [out] */ IProfileGroup** group) { VALIDATE_NOT_NULL(group) AutoPtr<INotificationGroup> notificationGroup; GetNotificationGroupForPackage(packageName, (INotificationGroup**)&notificationGroup); AutoPtr<IProfile> profile; GetActiveProfile((IProfile**)&profile); if (notificationGroup == NULL) { AutoPtr<IProfileGroup> defaultGroup; profile->GetDefaultGroup((IProfileGroup**)&defaultGroup); *group = defaultGroup; REFCOUNT_ADD(*group); return NOERROR; } AutoPtr<IUUID> uuid; notificationGroup->GetUuid((IUUID**)&uuid); return profile->GetProfileGroup(uuid, group); } ECode ProfileManager::ResetAll() { // try { ECode ec = GetService()->ResetAll(); if (ec == (ECode)E_REMOTE_EXCEPTION || ec == (ECode)E_SECURITY_EXCEPTION) { return ec; } return NOERROR; // } catch (RemoteException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } catch (SecurityException e) { // Log.e(TAG, e.getLocalizedMessage(), e); // } } } // namespace App } // namespace Droid } // namespace Elastos
29.06383
93
0.630161
4632501d59bf7b852fa5c135d97358d93bcdaa52
464
cpp
C++
storage/src/vespa/storage/distributor/operations/external/newest_replica.cpp
Anlon-Burke/vespa
5ecd989b36cc61716bf68f032a3482bf01fab726
[ "Apache-2.0" ]
4,054
2017-08-11T07:58:38.000Z
2022-03-31T22:32:15.000Z
storage/src/vespa/storage/distributor/operations/external/newest_replica.cpp
Anlon-Burke/vespa
5ecd989b36cc61716bf68f032a3482bf01fab726
[ "Apache-2.0" ]
4,854
2017-08-10T20:19:25.000Z
2022-03-31T19:04:23.000Z
storage/src/vespa/storage/distributor/operations/external/newest_replica.cpp
Anlon-Burke/vespa
5ecd989b36cc61716bf68f032a3482bf01fab726
[ "Apache-2.0" ]
541
2017-08-10T18:51:18.000Z
2022-03-11T03:18:56.000Z
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "newest_replica.h" #include <ostream> namespace storage::distributor { std::ostream& operator<<(std::ostream& os, const NewestReplica& nr) { os << "NewestReplica(timestamp " << nr.timestamp << ", bucket_id " << nr.bucket_id << ", node " << nr.node << ", is_tombstone " << nr.is_tombstone << ')'; return os; } }
27.294118
104
0.631466
4632a0c517ab096ba9b640cea6e21e3aa7a31f0b
507
cpp
C++
graphblockstest/src/main.cpp
dabulla/graphblocks
6006375747117636d8662076e64a677cf709a274
[ "MIT" ]
1
2017-05-01T20:39:35.000Z
2017-05-01T20:39:35.000Z
graphblockstest/src/main.cpp
dabulla/graphblocks
6006375747117636d8662076e64a677cf709a274
[ "MIT" ]
null
null
null
graphblockstest/src/main.cpp
dabulla/graphblocks
6006375747117636d8662076e64a677cf709a274
[ "MIT" ]
null
null
null
#include <QApplication> #include <QQmlApplicationEngine> #include <qqml.h> #include <QResource> #include <QDebug> #include <graphblocks.h> int main(int argc, char *argv[]) { QApplication app(argc, argv); GraphblocksContext* gbctx = initializeGraphBlocks(); QQmlApplicationEngine engine; addGraphBlocksLibrary( &engine, "userlibs", "gblibs" ); engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml"))); int result = app.exec(); shutdownGraphBlocks( gbctx ); return result; }
23.045455
59
0.704142
4634737aca597d284dca13cf9574464bab7dc1ff
20
cpp
C++
src/Game/zScript.cpp
DarkRTA/bfbbdecomp
e2105e94b8da26f6e6e2dfcf1f004aaaeed9799e
[ "OLDAP-2.7" ]
null
null
null
src/Game/zScript.cpp
DarkRTA/bfbbdecomp
e2105e94b8da26f6e6e2dfcf1f004aaaeed9799e
[ "OLDAP-2.7" ]
6
2022-01-16T05:29:01.000Z
2022-01-18T01:10:29.000Z
src/Game/zScript.cpp
DarkRTA/bfbbdecomp
e2105e94b8da26f6e6e2dfcf1f004aaaeed9799e
[ "OLDAP-2.7" ]
1
2022-01-16T00:04:23.000Z
2022-01-16T00:04:23.000Z
#include "zScript.h"
20
20
0.75
463b70decfcf756e76dc1f4d982ab90ff08f6feb
9,097
cpp
C++
src/daemon/process/AppProcess.cpp
FrederickHou/app-mesh
8f23a1555d3a8da1481d91e1e60464fc197bd6e5
[ "MIT" ]
null
null
null
src/daemon/process/AppProcess.cpp
FrederickHou/app-mesh
8f23a1555d3a8da1481d91e1e60464fc197bd6e5
[ "MIT" ]
null
null
null
src/daemon/process/AppProcess.cpp
FrederickHou/app-mesh
8f23a1555d3a8da1481d91e1e60464fc197bd6e5
[ "MIT" ]
1
2020-11-01T09:11:49.000Z
2020-11-01T09:11:49.000Z
#include <thread> #include <fstream> #include "AppProcess.h" #include "LinuxCgroup.h" #include "../Configuration.h" #include "../ResourceLimitation.h" #include "../../common/Utility.h" #include "../../common/DateTime.h" #include "../../common/os/pstree.hpp" #define CLOSE_ACE_HANDLER(handler) \ do \ { \ if (handler != ACE_INVALID_HANDLE) \ { \ ACE_OS::close(handler); \ handler = ACE_INVALID_HANDLE; \ } \ } while (false) AppProcess::AppProcess() : m_killTimerId(0), m_stdinHandler(ACE_INVALID_HANDLE), m_stdoutHandler(ACE_INVALID_HANDLE), m_uuid(Utility::createUUID()) { } AppProcess::~AppProcess() { if (this->running()) { killgroup(); } CLOSE_ACE_HANDLER(m_stdoutHandler); CLOSE_ACE_HANDLER(m_stdinHandler); if (m_stdinFileName.length() && Utility::isFileExist(m_stdinFileName)) { Utility::removeFile(m_stdinFileName); } if (m_stdoutReadStream && m_stdoutReadStream->is_open()) { m_stdoutReadStream->close(); } this->close_dup_handles(); this->close_passed_handles(); } void AppProcess::attach(int pid) { this->child_id_ = pid; } void AppProcess::detach() { attach(ACE_INVALID_PID); } pid_t AppProcess::getpid(void) const { return ACE_Process::getpid(); } void AppProcess::killgroup(int timerId) { const static char fname[] = "AppProcess::killgroup() "; LOG_INF << fname << "kill process <" << getpid() << ">."; if (timerId == 0) { // killed before timer event, cancel timer event this->cancelTimer(m_killTimerId); } if (m_killTimerId > 0 && m_killTimerId == timerId) { // clean timer id, trigger-ing this time. m_killTimerId = 0; } if (this->running() && this->getpid() > 1) { ACE_OS::kill(-(this->getpid()), 9); this->terminate(); if (this->wait() < 0 && errno != 10) // 10 is ECHILD:No child processes { //avoid zombie process (Interrupted system call) LOG_WAR << fname << "Wait process <" << getpid() << "> to exit failed with error : " << std::strerror(errno); std::this_thread::sleep_for(std::chrono::milliseconds(100)); if (this->wait() < 0) { LOG_ERR << fname << "Retry wait process <" << getpid() << "> failed with error : " << std::strerror(errno); } else { LOG_INF << fname << "Retry wait process <" << getpid() << "> success"; } } } } void AppProcess::setCgroup(std::shared_ptr<ResourceLimitation> &limit) { // https://blog.csdn.net/u011547375/article/details/9851455 if (limit != nullptr) { m_cgroup = std::make_unique<LinuxCgroup>(limit->m_memoryMb, limit->m_memoryVirtMb - limit->m_memoryMb, limit->m_cpuShares); m_cgroup->setCgroup(limit->m_name, getpid(), ++(limit->m_index)); } } const std::string AppProcess::getuuid() const { return m_uuid; } void AppProcess::regKillTimer(std::size_t timeout, const std::string from) { m_killTimerId = this->registerTimer(1000L * timeout, 0, std::bind(&AppProcess::killgroup, this, std::placeholders::_1), from); } // tuple: 1 cmdRoot, 2 parameters std::tuple<std::string, std::string> AppProcess::extractCommand(const std::string &cmd) { std::unique_ptr<char[]> buff(new char[cmd.length() + 1]); // find the string at the first blank not in a quote, quotes are removed std::size_t idxSrc = 0, idxDst = 0; bool isInQuote = false; while (cmd[idxSrc] != '\0') { if (cmd[idxSrc] == ' ' && !isInQuote) { break; } else if (cmd[idxSrc] == '\"') { isInQuote = isInQuote ^ true; } else { buff[idxDst++] = cmd[idxSrc]; } idxSrc++; } buff[idxDst] = '\0'; // remaining string are the parameters std::string params = cmd.substr(idxSrc); std::string cmdroot = buff.get(); return std::tuple<std::string, std::string>(params, cmdroot); } int AppProcess::spawnProcess(std::string cmd, std::string user, std::string workDir, std::map<std::string, std::string> envMap, std::shared_ptr<ResourceLimitation> limit, const std::string &stdoutFile, const std::string &stdinFileContent) { const static char fname[] = "AppProcess::spawnProcess() "; int pid = -1; // check command file existence & permission auto cmdRoot = std::get<1>(extractCommand(cmd)); bool checkCmd = true; if (cmdRoot.rfind('/') == std::string::npos && cmdRoot.rfind('\\') == std::string::npos) { checkCmd = false; } if (checkCmd && !Utility::isFileExist(cmdRoot)) { LOG_WAR << fname << "command file <" << cmdRoot << "> does not exist"; startError(Utility::stringFormat("command file <%s> does not exist", cmdRoot.c_str())); return ACE_INVALID_PID; } if (checkCmd && ACE_OS::access(cmdRoot.c_str(), X_OK) != 0) { LOG_WAR << fname << "command file <" << cmdRoot << "> does not have execution permission"; startError(Utility::stringFormat("command file <%s> does not have execution permission", cmdRoot.c_str())); return ACE_INVALID_PID; } envMap[ENV_APP_MANAGER_LAUNCH_TIME] = DateTime::formatLocalTime(std::chrono::system_clock::now(), DATE_TIME_FORMAT); std::size_t cmdLength = cmd.length() + ACE_Process_Options::DEFAULT_COMMAND_LINE_BUF_LEN; int totalEnvSize = 0; int totalEnvArgs = 0; Utility::getEnvironmentSize(envMap, totalEnvSize, totalEnvArgs); ACE_Process_Options option(1, cmdLength, totalEnvSize, totalEnvArgs); option.command_line("%s", cmd.c_str()); //option.avoid_zombies(1); if (user.empty()) user = Configuration::instance()->getDefaultExecUser(); if (user != "root") { unsigned int gid, uid; if (Utility::getUid(user, uid, gid)) { option.seteuid(uid); option.setruid(uid); option.setegid(gid); option.setrgid(gid); } else { startError(Utility::stringFormat("user <%s> does not exist", user.c_str())); return ACE_INVALID_PID; } } option.setgroup(0); // set group id with the process id, used to kill process group option.inherit_environment(true); option.handle_inheritance(0); if (workDir.length()) { option.working_directory(workDir.c_str()); } else { option.working_directory(Configuration::instance()->getDefaultWorkDir().c_str()); // set default working dir } std::for_each(envMap.begin(), envMap.end(), [&option](const std::pair<std::string, std::string> &pair) { option.setenv(pair.first.c_str(), "%s", pair.second.c_str()); LOG_DBG << "spawnProcess env: " << pair.first.c_str() << "=" << pair.second.c_str(); }); option.release_handles(); // clean if necessary CLOSE_ACE_HANDLER(m_stdoutHandler); CLOSE_ACE_HANDLER(m_stdinHandler); ACE_HANDLE dummy = ACE_INVALID_HANDLE; m_stdoutFileName = stdoutFile; if (stdoutFile.length() || stdinFileContent.length()) { dummy = ACE_OS::open("/dev/null", O_RDWR); m_stdoutHandler = m_stdinHandler = dummy; if (stdoutFile.length()) { m_stdoutHandler = ACE_OS::open(stdoutFile.c_str(), O_CREAT | O_WRONLY | O_APPEND | O_TRUNC); LOG_DBG << "std_out: " << stdoutFile; } if (stdinFileContent.length() && stdinFileContent != JSON_KEY_APP_CLOUD_APP) { m_stdinFileName = Utility::stringFormat("appmesh.%s.stdin", m_uuid.c_str()); std::ofstream inputFile(m_stdinFileName, std::ios::trunc); inputFile << stdinFileContent; inputFile.close(); assert(Utility::isFileExist(m_stdinFileName)); m_stdinHandler = ACE_OS::open(m_stdinFileName.c_str(), O_RDONLY); LOG_DBG << "std_in: " << m_stdinFileName << " : " << stdinFileContent; } option.set_handles(m_stdinHandler, m_stdoutHandler, m_stdoutHandler); } // do not inherit LD_LIBRARY_PATH to child static const std::string ldEnv = ACE_OS::getenv("LD_LIBRARY_PATH") ? ACE_OS::getenv("LD_LIBRARY_PATH") : ""; if (!ldEnv.empty()) { std::string env = ldEnv; env = Utility::stringReplace(env, "/opt/appmesh/lib64:", ""); env = Utility::stringReplace(env, ":/opt/appmesh/lib64", ""); option.setenv("LD_LIBRARY_PATH", "%s", env.c_str()); } if (this->spawn(option) >= 0) { pid = this->getpid(); LOG_INF << fname << "Process <" << cmd << "> started with pid <" << pid << ">."; this->setCgroup(limit); } else { pid = -1; LOG_ERR << fname << "Process:<" << cmd << "> start failed with error : " << std::strerror(errno); startError(Utility::stringFormat("start failed with error <%s>", std::strerror(errno))); } if (dummy != ACE_INVALID_HANDLE) ACE_OS::close(dummy); return pid; } std::string AppProcess::fetchOutputMsg() { std::lock_guard<std::recursive_mutex> guard(m_outFileMutex); if (m_stdoutReadStream == nullptr) m_stdoutReadStream = std::make_shared<std::ifstream>(m_stdoutFileName, ios::in); if (m_stdoutReadStream->is_open() && m_stdoutReadStream->good()) { std::stringstream buffer; buffer << m_stdoutReadStream->rdbuf(); return std::move(buffer.str()); } return std::string(); } std::string AppProcess::fetchLine() { char buffer[512] = {0}; std::lock_guard<std::recursive_mutex> guard(m_outFileMutex); if (m_stdoutReadStream == nullptr) m_stdoutReadStream = std::make_shared<std::ifstream>(m_stdoutFileName, ios::in); if (m_stdoutReadStream->is_open() && m_stdoutReadStream->good()) { m_stdoutReadStream->getline(buffer, sizeof(buffer)); } return buffer; }
30.62963
238
0.67165
463dea99028bceb273e29e22982b837fae318681
4,507
cpp
C++
src/controller/src/SMACS.cpp
BCLab-UNM/M2M-MC
4bde093b2c43c2217fda2f4a0efd55bbfc45b9a1
[ "MIT" ]
6
2020-07-02T13:01:30.000Z
2021-05-01T06:35:10.000Z
src/controller/src/SMACS.cpp
BCLab-UNM/M2M-MC
4bde093b2c43c2217fda2f4a0efd55bbfc45b9a1
[ "MIT" ]
null
null
null
src/controller/src/SMACS.cpp
BCLab-UNM/M2M-MC
4bde093b2c43c2217fda2f4a0efd55bbfc45b9a1
[ "MIT" ]
2
2020-05-17T18:51:12.000Z
2020-11-16T16:32:44.000Z
#include "SMACS.h" // Initialize the instance SMACS* SMACS::s_instance = 0; SMACS::SMACS(){} SMACS* SMACS::instance(){ if(!s_instance) s_instance = new SMACS; return s_instance; } void SMACS::pushWithMutex(Behavior* b){ // Check if behavior is null. If it is then do not put anything on stack if(b == NULL){ cout << "STACK: " << "NULL pointer passed to stack" << endl; return; } //lock the stack from being used while we are doing something with it std::lock_guard<std::mutex> guard(stackMutex); //cout << "STACK: " << "Stack locked"<< endl; //if stack is not empty, check if behavior is stackable if(!behaviorStack.empty()){ Behavior *top = behaviorStack.top(); cout << "STACK: " << "Got top"<< endl; if(b->getType() == top->getType()){ if(!b->isStackable()){ cout << "STACK: " << "Behavior is not stackable. Was not pushed to stack"<< endl; return; } } } //stop the robot DriveController::instance()->stop(); //push new behavior behaviorStack.push(b); cout << "STACK: " << "Pushed to stack"<< endl; //cout << "STACK: " << "Stack unlocked"<< endl; } void SMACS::push(Behavior* b){ // Check if behavior is null. If it is then do not put anything on stack if(b == NULL){ cout << "STACK: " << "NULL pointer passed to stack" << endl; return; } //lock the stack from being used while we are doing something with it cout << "STACK: " << "Pushing with no mutex"<< endl; //if stack is not empty, check if behavior is stackable if(!behaviorStack.empty()){ Behavior *top = behaviorStack.top(); //cout << "STACK: " << "Got top"<< endl; if(b->getType() == top->getType()){ if(!b->isStackable()){ //cout << "STACK: " << "Behavior is not stackable. Was not pushed to stack"<< endl; return; } } } //stop the robot DriveController::instance()->stop(); //push new behavior behaviorStack.push(b); cout << "STACK: " << "Pushed to stack"<< endl; //cout << "STACK: " << "Stack unlocked"<< endl; } void SMACS::pop(){ if(behaviorStack.empty()){ cout << "STACK: " << "Behavior stack is already empty."<< endl; return; } //lock stack std::lock_guard<std::mutex> guard(stackMutex); //cout << "STACK: " << "Stack locked"<< endl; DriveController::instance()->stop(); cout << "STACK: " << "Popped from stack"<< endl; //pop element behaviorStack.pop(); //cout << "STACK: " << "Stack unlocked"<< endl; } void SMACS::pushNext(Behavior *b){ if(b == NULL){ cout << "STACK: " << "NULL pointer passed to stack"<< endl; return; } // cout << "STACK: " << "Stack not locked for push next"<< endl; // if stack is not empty, then save top element and pop it to get to the next element if(!behaviorStack.empty()){ Behavior *hold = behaviorStack.top(); behaviorStack.pop(); //if stack is not empty, check if second elements is stackable if(!behaviorStack.empty()){ Behavior *top = behaviorStack.top(); if(b->getType() == top->getType()){ if(!b->isStackable()){ cout << "STACK: " << "Behavior is not stackable. Was not pushed to stack"<< endl; behaviorStack.push(hold); return; } } } behaviorStack.push(b); behaviorStack.push(hold); } else { behaviorStack.push(b); } cout << "STACK: " << "Pushed next behavior to stack."<<endl; } bool SMACS::isEmpty(){return behaviorStack.empty();} // This is a tick method bool SMACS::tick(){ // Lock stack std::lock_guard<std::mutex> guard(stackMutex); // If stack is not empty if(!behaviorStack.empty()){ cout << "STACK: " << "Ticking behvior: "<< behaviorStack.top()->getCurrentBehavior()<< endl; if(behaviorStack.top()->tick()){ DriveController::instance()->stop(); cout << "STACK: " << "Popped from stack"<< endl; //pop element behaviorStack.pop(); //cout << "STACK: " << "Stack popped from tick"<< endl; return true; } //cout << "STACK: " << "Stack unlocked for tick"<< endl; } return false; }
25.463277
101
0.544264
463ed1f546940c56ba4ee677e916d5a1b61dab89
7,947
cpp
C++
tests/src/percent_input_tests.cpp
DmitryDzz/calculator-comrade-lib
107930ef7df88b330b800993028b35d08d5d78f6
[ "MIT" ]
4
2021-01-18T03:11:14.000Z
2022-01-29T09:17:06.000Z
tests/src/percent_input_tests.cpp
DmitryDzz/calculator-comrade-lib
107930ef7df88b330b800993028b35d08d5d78f6
[ "MIT" ]
32
2018-10-11T22:05:14.000Z
2019-05-26T16:25:38.000Z
tests/src/percent_input_tests.cpp
DmitryDzz/calculator-comrade-lib
107930ef7df88b330b800993028b35d08d5d78f6
[ "MIT" ]
null
null
null
/** * Calculator Comrade Library * License: https://github.com/DmitryDzz/calculator-comrade-lib/blob/master/LICENSE * Author: Dmitry Dzakhov * Email: info@robot-mitya.ru */ #include <gmock/gmock.h> #include "calculator/calculator.h" #include "calculator/button.h" #include "calculator/operation.h" #include "calc_helper.h" using namespace calculatorcomrade; #define TEST_PERCENT(test_name) TEST(PercentOperations, test_name) TEST_PERCENT(NoOperation) { Calculator c(8); Register &x = c.getX(); c.input(Button::d5); c.input(Button::percent); ASSERT_EQ(5, getIntValue(x)); } TEST_PERCENT(AddPercent) { Calculator c(8); Register &x = c.getX(); c.input(Button::ca); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::plus); c.input(Button::d5); c.input(Button::percent); ASSERT_EQ(210, getIntValue(x)); c.input(Button::percent); ASSERT_EQ(210, getIntValue(x)); c.input(Button::equals); ASSERT_EQ(410, getIntValue(x)); c.input(Button::ca); c.input(Button::minus); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::plus); c.input(Button::d5); c.input(Button::percent); ASSERT_EQ(-210, getIntValue(x)); c.input(Button::percent); ASSERT_EQ(-210, getIntValue(x)); c.input(Button::equals); ASSERT_EQ(-410, getIntValue(x)); c.input(Button::ca); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::plus); c.input(Button::d5); c.input(Button::changeSign); c.input(Button::percent); ASSERT_EQ(190, getIntValue(x)); c.input(Button::percent); ASSERT_EQ(190, getIntValue(x)); c.input(Button::equals); ASSERT_EQ(-10, getIntValue(x)); c.input(Button::ca); c.input(Button::minus); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::plus); c.input(Button::d5); c.input(Button::changeSign); c.input(Button::percent); ASSERT_EQ(-190, getIntValue(x)); c.input(Button::percent); ASSERT_EQ(-190, getIntValue(x)); c.input(Button::equals); ASSERT_EQ(10, getIntValue(x)); } TEST_PERCENT(SubPercent) { Calculator c(8); Register &x = c.getX(); c.input(Button::ca); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::minus); c.input(Button::d5); c.input(Button::percent); ASSERT_EQ(190, getIntValue(x)); c.input(Button::percent); ASSERT_EQ(190, getIntValue(x)); c.input(Button::equals); ASSERT_EQ(-10, getIntValue(x)); c.input(Button::ca); c.input(Button::minus); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::minus); c.input(Button::d5); c.input(Button::percent); ASSERT_EQ(-190, getIntValue(x)); c.input(Button::percent); ASSERT_EQ(-190, getIntValue(x)); c.input(Button::equals); ASSERT_EQ(10, getIntValue(x)); c.input(Button::ca); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::minus); c.input(Button::d5); c.input(Button::changeSign); c.input(Button::percent); ASSERT_EQ(210, getIntValue(x)); c.input(Button::percent); ASSERT_EQ(210, getIntValue(x)); c.input(Button::equals); ASSERT_EQ(410, getIntValue(x)); c.input(Button::ca); c.input(Button::minus); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::minus); c.input(Button::d5); c.input(Button::changeSign); c.input(Button::percent); ASSERT_EQ(-210, getIntValue(x)); c.input(Button::percent); ASSERT_EQ(-210, getIntValue(x)); c.input(Button::equals); ASSERT_EQ(-410, getIntValue(x)); } TEST_PERCENT(MulPercent) { Calculator c(8); Register &x = c.getX(); Register &y = c.getY(); c.input(Button::ca); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::mul); c.input(Button::d5); c.input(Button::percent); ASSERT_EQ(10, getIntValue(x)); ASSERT_EQ(200, getIntValue(y)); c.input(Button::percent); ASSERT_EQ(20, getIntValue(x)); ASSERT_EQ(200, getIntValue(y)); c.input(Button::equals); ASSERT_EQ(4000, getIntValue(x)); ASSERT_EQ(200, getIntValue(y)); c.input(Button::ca); c.input(Button::minus); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::mul); c.input(Button::d5); c.input(Button::percent); ASSERT_EQ(-10, getIntValue(x)); ASSERT_EQ(-200, getIntValue(y)); c.input(Button::percent); ASSERT_EQ(20, getIntValue(x)); ASSERT_EQ(-200, getIntValue(y)); c.input(Button::equals); ASSERT_EQ(-4000, getIntValue(x)); ASSERT_EQ(-200, getIntValue(y)); c.input(Button::ca); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::mul); c.input(Button::d5); c.input(Button::changeSign); c.input(Button::percent); ASSERT_EQ(-10, getIntValue(x)); ASSERT_EQ(200, getIntValue(y)); c.input(Button::percent); ASSERT_EQ(-20, getIntValue(x)); ASSERT_EQ(200, getIntValue(y)); c.input(Button::equals); ASSERT_EQ(-4000, getIntValue(x)); ASSERT_EQ(200, getIntValue(y)); c.input(Button::ca); c.input(Button::minus); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::mul); c.input(Button::d5); c.input(Button::changeSign); c.input(Button::percent); ASSERT_EQ(10, getIntValue(x)); ASSERT_EQ(-200, getIntValue(y)); c.input(Button::percent); ASSERT_EQ(-20, getIntValue(x)); ASSERT_EQ(-200, getIntValue(y)); c.input(Button::equals); ASSERT_EQ(4000, getIntValue(x)); ASSERT_EQ(-200, getIntValue(y)); } TEST_PERCENT(DivPercent1) { Calculator c(8); Register &x = c.getX(); Register &y = c.getY(); c.input(Button::ca); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::div); c.input(Button::d5); c.input(Button::percent); ASSERT_EQ(4000, getIntValue(x)); ASSERT_EQ(5, getIntValue(y)); c.input(Button::percent); ASSERT_EQ(80000, getIntValue(x)); ASSERT_EQ(5, getIntValue(y)); c.input(Button::equals); ASSERT_EQ(16000, getIntValue(x)); ASSERT_EQ(5, getIntValue(y)); c.input(Button::ca); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::div); c.input(Button::d5); c.input(Button::changeSign); c.input(Button::percent); ASSERT_EQ(-4000, getIntValue(x)); ASSERT_EQ(-5, getIntValue(y)); c.input(Button::percent); ASSERT_EQ(80000, getIntValue(x)); ASSERT_EQ(-5, getIntValue(y)); c.input(Button::equals); ASSERT_EQ(-16000, getIntValue(x)); ASSERT_EQ(-5, getIntValue(y)); c.input(Button::ca); c.input(Button::minus); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::div); c.input(Button::d5); c.input(Button::percent); ASSERT_EQ(-4000, getIntValue(x)); ASSERT_EQ(5, getIntValue(y)); c.input(Button::percent); ASSERT_EQ(-80000, getIntValue(x)); ASSERT_EQ(5, getIntValue(y)); c.input(Button::equals); ASSERT_EQ(-16000, getIntValue(x)); ASSERT_EQ(5, getIntValue(y)); c.input(Button::ca); c.input(Button::minus); c.input(Button::d2); c.input(Button::d0); c.input(Button::d0); c.input(Button::div); c.input(Button::d5); c.input(Button::changeSign); c.input(Button::percent); ASSERT_EQ(4000, getIntValue(x)); ASSERT_EQ(-5, getIntValue(y)); c.input(Button::percent); ASSERT_EQ(-80000, getIntValue(x)); ASSERT_EQ(-5, getIntValue(y)); c.input(Button::equals); ASSERT_EQ(16000, getIntValue(x)); ASSERT_EQ(-5, getIntValue(y)); }
26.938983
83
0.623632
463fb36ee7f82268919c4c195906ebf824f4fd3f
3,539
cpp
C++
projects/biogears/libBiogears/src/cdm/properties/SEScalarAmountPerVolume.cpp
Aaryan-kapur/core
5ebf096d18a3ddbe0259f83ca82a39607ba1f892
[ "Apache-2.0" ]
1
2020-03-13T17:43:34.000Z
2020-03-13T17:43:34.000Z
projects/biogears/libBiogears/src/cdm/properties/SEScalarAmountPerVolume.cpp
BhumikaSaini/core
baecdd736961d301fe2723858de94cef285296b0
[ "Apache-2.0" ]
5
2020-12-23T00:19:32.000Z
2020-12-29T20:53:58.000Z
projects/biogears/libBiogears/src/cdm/properties/SEScalarAmountPerVolume.cpp
BhumikaSaini/core
baecdd736961d301fe2723858de94cef285296b0
[ "Apache-2.0" ]
3
2020-02-23T06:20:08.000Z
2021-12-02T04:18:29.000Z
/************************************************************************************** Copyright 2015 Applied Research Associates, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **************************************************************************************/ #include <biogears/cdm/properties/SEScalarAmountPerVolume.h> namespace biogears { AmountPerVolumeUnit AmountPerVolumeUnit::mol_Per_L("mol/L"); AmountPerVolumeUnit AmountPerVolumeUnit::mol_Per_mL("mol/mL"); AmountPerVolumeUnit AmountPerVolumeUnit::mmol_Per_L("mmol/L"); AmountPerVolumeUnit AmountPerVolumeUnit::mmol_Per_mL("mmol/mL"); AmountPerVolumeUnit AmountPerVolumeUnit::ct_Per_L("ct/L"); AmountPerVolumeUnit AmountPerVolumeUnit::ct_Per_uL("ct/uL"); AmountPerVolumeUnit::AmountPerVolumeUnit(const char* u) : AmountPerVolumeUnit(std::string{ u }) { } //------------------------------------------------------------------------------- AmountPerVolumeUnit::AmountPerVolumeUnit(const std::string& u) : CCompoundUnit(u) { } //------------------------------------------------------------------------------- CDM::ScalarAmountPerVolumeData* SEScalarAmountPerVolume::Unload() const { if (!IsValid()) return nullptr; CDM::ScalarAmountPerVolumeData* data(new CDM::ScalarAmountPerVolumeData()); SEScalarQuantity::Unload(*data); return data; } //------------------------------------------------------------------------------- bool AmountPerVolumeUnit::IsValidUnit(const char* unit) { if (strcmp(mol_Per_L.GetString(),unit) == 0) return true; if (strcmp(mol_Per_mL.GetString(),unit) == 0) return true; if (strcmp(mmol_Per_L.GetString(),unit) == 0) return true; if (strcmp(mmol_Per_mL.GetString(),unit) == 0) return true; if (strcmp(ct_Per_L.GetString(),unit) == 0) return true; if (strcmp(ct_Per_uL.GetString(),unit) == 0) return true; return false; } //------------------------------------------------------------------------------- bool AmountPerVolumeUnit::IsValidUnit(const std::string& unit) { return IsValidUnit(unit.c_str()); } //------------------------------------------------------------------------------- const AmountPerVolumeUnit& AmountPerVolumeUnit::GetCompoundUnit(const char* unit) { if (strcmp(mol_Per_L.GetString(),unit) == 0) return mol_Per_L; if (strcmp(mol_Per_mL.GetString(),unit) == 0) return mol_Per_mL; if (strcmp(mmol_Per_L.GetString(),unit) == 0) return mmol_Per_L; if (strcmp(mmol_Per_mL.GetString(),unit) == 0) return mmol_Per_mL; if (strcmp(ct_Per_L.GetString(),unit) == 0) return ct_Per_L; if (strcmp(ct_Per_uL.GetString(),unit) == 0) return ct_Per_uL; std::stringstream err; err << unit << " is not a valid AmountPerVolume unit"; throw CommonDataModelException(err.str()); } //------------------------------------------------------------------------------- const AmountPerVolumeUnit& AmountPerVolumeUnit::GetCompoundUnit(const std::string& unit) { return GetCompoundUnit(unit.c_str()); } //------------------------------------------------------------------------------- }
40.678161
88
0.593105
46439014fe67edc86b801095f99e4c66d75c337f
1,571
cpp
C++
test/utils/test_utils.cpp
patwoodburn/fort_assesment
e5dd21a4e179ffca647e0a3c6963bba437d614e6
[ "MIT" ]
1
2021-03-01T17:57:49.000Z
2021-03-01T17:57:49.000Z
test/utils/test_utils.cpp
patwoodburn/cpp_base_project
b1481c4ee28fd267d63658b0bb2fa27bd2d948b7
[ "MIT" ]
null
null
null
test/utils/test_utils.cpp
patwoodburn/cpp_base_project
b1481c4ee28fd267d63658b0bb2fa27bd2d948b7
[ "MIT" ]
null
null
null
#include "catch2/catch.hpp" #include "utils.h" #include <algorithm> #include <array> SCENARIO("An array of values needs to be sorted", "") { GIVEN("An an unsorted arry a1") { std::array<int, 10> a1 = {5, 10, 1, 2, 8, 3, 7, 9, 4, 6}; WHEN("Array a1 is passed to bubble sort.") { BubbleSort(a1.begin(), a1.end()); THEN("Array a1 should be sorted.") { REQUIRE(std::is_sorted(a1.begin(), a1.end())); REQUIRE(a1.size() == 10); REQUIRE(a1[0] == 1); REQUIRE(a1[1] == 2); REQUIRE(a1[2] == 3); REQUIRE(a1[3] == 4); REQUIRE(a1[4] == 5); REQUIRE(a1[5] == 6); REQUIRE(a1[6] == 7); REQUIRE(a1[7] == 8); REQUIRE(a1[8] == 9); REQUIRE(a1[9] == 10); } } } } SCENARIO("An array of values need to be sorted with out changing the order of " "the orriganal array", "") { GIVEN("An unsorted array a1 and an empty target array a2") { std::array<int, 10> a1 = {10, 1, 5, 6, 8, 7, 0, 2, 3, 9}; std::array<int, 10> a2; WHEN("Array a1 and a2 and a sort function are passed to copy sort") { CopySort(a1.begin(), a1.end(), a2.begin(), BubbleSort); THEN("a2 should be sorted copy of a1 and a1 should be unchanged") { REQUIRE(!std::is_sorted(a1.begin(), a1.end())); REQUIRE(std::is_sorted(a2.begin(), a2.end())); REQUIRE(a1.size() == 10); REQUIRE(a2.size() == 10); for (int i : a1) { REQUIRE(a2.end() != std::find(a2.begin(), a2.end(), i)); } } } } }
29.092593
79
0.521961
4643ab8154366f53cffbe193c750fd0a35c954a3
578
cpp
C++
barelymusician/dsp/one_pole_filter.cpp
anokta/barelymusician
5e3485c80cc74c4bcbc0653c0eb8750ad44981d6
[ "MIT" ]
6
2021-11-25T17:40:21.000Z
2022-03-24T03:38:11.000Z
barelymusician/dsp/one_pole_filter.cpp
anokta/barelymusician
5e3485c80cc74c4bcbc0653c0eb8750ad44981d6
[ "MIT" ]
17
2021-11-27T00:10:39.000Z
2022-03-30T00:33:51.000Z
barelymusician/dsp/one_pole_filter.cpp
anokta/barelymusician
5e3485c80cc74c4bcbc0653c0eb8750ad44981d6
[ "MIT" ]
null
null
null
#include "barelymusician/dsp/one_pole_filter.h" #include <algorithm> namespace barelyapi { double OnePoleFilter::Next(double input) noexcept { output_ = coefficient_ * (output_ - input) + input; if (type_ == FilterType::kHighPass) { return input - output_; } return output_; } void OnePoleFilter::Reset() noexcept { output_ = 0.0; } void OnePoleFilter::SetCoefficient(double coefficient) noexcept { coefficient_ = std::min(std::max(coefficient, 0.0), 1.0); } void OnePoleFilter::SetType(FilterType type) noexcept { type_ = type; } } // namespace barelyapi
24.083333
71
0.719723
4647b087057511edb5817108d19eb772335602fb
10,906
cpp
C++
src/dev/steve/ScarrArm/ScarrArmModel.cpp
wvat/NTRTsim
0443cbd542e12e23c04adf79ea0d8d003c428baa
[ "Apache-2.0" ]
148
2015-01-08T22:44:00.000Z
2022-03-19T18:42:48.000Z
src/dev/steve/ScarrArm/ScarrArmModel.cpp
wvat/NTRTsim
0443cbd542e12e23c04adf79ea0d8d003c428baa
[ "Apache-2.0" ]
107
2015-01-02T16:41:42.000Z
2021-06-14T22:09:19.000Z
src/dev/steve/ScarrArm/ScarrArmModel.cpp
wvat/NTRTsim
0443cbd542e12e23c04adf79ea0d8d003c428baa
[ "Apache-2.0" ]
86
2015-01-06T07:02:36.000Z
2022-02-28T17:36:14.000Z
/* * Copyright © 2015, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is 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. */ /** * @file ScarrArmModel.cpp * @brief Contains the implementation of class ScarrArmModel. See README * $Id$ */ // This module #include "ScarrArmModel.h" // This library #include "core/tgBasicActuator.h" #include "core/tgRod.h" #include "core/abstractMarker.h" #include "tgcreator/tgBuildSpec.h" #include "tgcreator/tgBasicActuatorInfo.h" #include "tgcreator/tgKinematicContactCableInfo.h" #include "tgcreator/tgRodInfo.h" #include "tgcreator/tgStructure.h" #include "tgcreator/tgStructureInfo.h" // The Bullet Physics library #include "LinearMath/btVector3.h" // The C++ Standard Library #include <stdexcept> namespace { // see tgBaseString.h for a descripton of some of these rod parameters // (specifically, those related to the motor moving the strings.) // NOTE that any parameter that depends on units of length will scale // with the current gravity scaling. E.g., with gravity as 98.1, // the length units below are in decimeters. const struct ConfigRod { double density; double radius; double rod_length; double rod_space; double friction; double rollFriction; double restitution; } cRod = { 0.05, // density (kg / length^3) 0.8, // radius (length) 15.0, // rod_length (length) 7.5, // rod_space (length) 1.0, // friction (unitless) 0.01, // rollFriction (unitless) 0.2 // restitution (?) }; const struct ConfigCable { double elasticity; double damping; double stiffness; double pretension_olecranon; double pretension_anconeus; double pretension_brachioradialis; double pretension_support; bool history; double maxTens; double targetVelocity; double mRad; double motorFriction; double motorInertia; bool backDrivable; } cCable = { 1000.0, // elasticity 200.0, // damping (kg/s) 3000.0, // stiffness (kg / sec^2) 3000.0/1, // pretension_olecranon (force), stiffness/initial length 3000.0/15.55, // pretension_anconeus (force), stiffness/initial length 3000.0/262, // pretension_brachioradialis (force), stiffness/initial length 30000.0/1, // pretension_support (force), stiffness/initial length false, // history (boolean) 100000, // maxTens 10000, // targetVelocity 1.0, // mRad 10.0, // motorFriction 1.0, // motorInertia false // backDrivable (boolean) }; } // namespace ScarrArmModel::ScarrArmModel() : tgModel() {} ScarrArmModel::~ScarrArmModel() {} void ScarrArmModel::addNodes(tgStructure& s) { const double scale = 0.5; const double bone_scale = 0.3; const size_t nNodes = 15 + 2; //2 for massless rod // Average Adult Male Measurements with scale // Lengths are in mm const double a = 22 * scale; //ulnta distal width const double b = 334 * scale * bone_scale; //ulna length const double c = 265 * scale * bone_scale; //humerus length //NB: in model, c==b //const double d = 66 * scale; // humerus epicondylar width //const double e = 246 * scale * bone_scale; //radius length const double f = 25 * scale; // humerus head radius const double g = 17 * scale; //ulna proximal width const double x = a/2; const double z = c/2; //Format: (x, z, y) nodePositions.push_back(btVector3(g, 0, 0)); nodePositions.push_back(btVector3(0, -g, 0)); nodePositions.push_back(btVector3(-a/2, 0, 0)); nodePositions.push_back(btVector3(0, 0, g)); nodePositions.push_back(btVector3(0, 0, -g)); nodePositions.push_back(btVector3(0, g, 0)); nodePositions.push_back(btVector3(0, c, 0)); nodePositions.push_back(btVector3(x, z, 0)); nodePositions.push_back(btVector3(b+a/2, -g, 0)); nodePositions.push_back(btVector3(0, c+2, f)); nodePositions.push_back(btVector3(0, c+2, -f)); //Added 6/17/15 nodePositions.push_back(btVector3(a/2, -2*g, 0)); //ulna and radius nodePositions.push_back(btVector3(3*a/2, -g, 0)); nodePositions.push_back(btVector3(3*a/4, -g, g)); nodePositions.push_back(btVector3(3*a/4, -g, -g)); nodePositions.push_back(btVector3(f, c+2, 0)); nodePositions.push_back(btVector3(-f, c+2, 0)); for(size_t i=0;i<nNodes;i++) { s.addNode(nodePositions[i][0],nodePositions[i][1],nodePositions[i][2]); } } void ScarrArmModel::addRods(tgStructure& s) { // ulna and radius s.addPair(8, 12, "rod"); s.addPair(12, 14, "rod"); s.addPair(12, 13, "rod"); //olecranon s.addPair(0, 1, "rod"); s.addPair(1, 2, "rod"); s.addPair(1, 11, "rod"); // humerus s.addPair(3, 5, "humerus massless"); s.addPair(4, 5, "humerus massless"); s.addPair(5, 6, "humerus massless"); } void ScarrArmModel::addMuscles(tgStructure& s) { const std::vector<tgStructure*> children = s.getChildren(); s.addPair(0, 3, "olecranon muscle"); //NB actually fascial tissue s.addPair(0, 4, "olecranon muscle"); //NB actually fascial tissue s.addPair(1, 3, "olecranon muscle"); //NB actually fascial tissue s.addPair(1, 4, "olecranon muscle"); //NB actually fascial tissue s.addPair(2, 3, "olecranon muscle"); //NB actually fascial tissue s.addPair(2, 4, "olecranon muscle"); //NB actually fascial tissue s.addPair(0, 13, "olecranon muscle"); //NB actually fascial tissue s.addPair(1, 13, "olecranon muscle"); //NB actually fascial tissue s.addPair(11, 13, "olecranon muscle"); //NB actually fascial tissue s.addPair(0, 14, "olecranon muscle"); //NB actually fascial tissue s.addPair(1, 14, "olecranon muscle"); //NB actually fascial tissue s.addPair(11, 14, "olecranon muscle"); //NB actually fascial tissue s.addPair(0, 12, "olecranon muscle"); //NB actually fascial tissue s.addPair(11, 12, "olecranon muscle"); //NB actually fascial tissue s.addPair(0, 5, "brachioradialis muscle"); s.addPair(2, 5, "olecranon muscle"); //NB actually fascial tissue s.addPair(3, 13, "right anconeus muscle"); s.addPair(4, 14, "left anconeus muscle"); } /* void ScarrArmModel::addMarkers(tgStructure &s) { std::vector<tgRod *> rods=find<tgRod>("rod"); for(int i=0;i<10;i++) { const btRigidBody* bt = rods[rodNumbersPerNode[i]]->getPRigidBody(); btTransform inverseTransform = bt->getWorldTransform().inverse(); btVector3 pos = inverseTransform * (nodePositions[i]); abstractMarker tmp=abstractMarker(bt,pos,btVector3(0.08*i,1.0 - 0.08*i,.0),i); this->addMarker(tmp); } } */ void ScarrArmModel::setup(tgWorld& world) { const tgRod::Config rodConfig(cRod.radius, cRod.density, cRod.friction, cRod.rollFriction, cRod.restitution); const tgRod::Config rodConfigMassless(cRod.radius, 0.00/*c.density*/, cRod.friction, cRod.rollFriction, cRod.restitution); /// @todo acceleration constraint was removed on 12/10/14 Replace with tgKinematicActuator as appropreate tgBasicActuator::Config olecranonMuscleConfig(cCable.stiffness, cCable.damping, cCable.pretension_olecranon, cCable.history, cCable.maxTens, cCable.targetVelocity); tgBasicActuator::Config anconeusMuscleConfig(cCable.stiffness, cCable.damping, cCable.pretension_anconeus, cCable.history, cCable.maxTens, cCable.targetVelocity); tgBasicActuator::Config brachioradialisMuscleConfig(cCable.stiffness, cCable.damping, cCable.pretension_brachioradialis, cCable.history, cCable.maxTens, cCable.targetVelocity); tgBasicActuator::Config supportstringMuscleConfig(cCable.stiffness, cCable.damping, cCable.pretension_support, cCable.history, cCable.maxTens, cCable.targetVelocity); // Start creating the structure tgStructure s; addNodes(s); addRods(s); addMuscles(s); // Move the arm out of the ground btVector3 offset(0.0, 50.0, 0.0); s.move(offset); // Create the build spec that uses tags to turn the structure into a real model tgBuildSpec spec; spec.addBuilder("massless", new tgRodInfo(rodConfigMassless)); spec.addBuilder("rod", new tgRodInfo(rodConfig)); spec.addBuilder("olecranon muscle", new tgBasicActuatorInfo(olecranonMuscleConfig)); spec.addBuilder("anconeus muscle", new tgBasicActuatorInfo(anconeusMuscleConfig)); spec.addBuilder("brachioradialis muscle", new tgBasicActuatorInfo(brachioradialisMuscleConfig)); spec.addBuilder("support muscle", new tgBasicActuatorInfo(supportstringMuscleConfig)); // Create your structureInfo tgStructureInfo structureInfo(s, spec); // Use the structureInfo to build ourselves structureInfo.buildInto(*this, world); // We could now use tgCast::filter or similar to pull out the // models (e.g. muscles) that we want to control. allMuscles = tgCast::filter<tgModel, tgBasicActuator> (getDescendants()); // call the onSetup methods of all observed things e.g. controllers notifySetup(); // Actually setup the children tgModel::setup(world); //map the rods and add the markers to them //addMarkers(s); } void ScarrArmModel::step(double dt) { // Precondition if (dt <= 0.0) { throw std::invalid_argument("dt is not positive"); } else { // Notify observers (controllers) of the step so that they can take action notifyStep(dt); tgModel::step(dt); // Step any children } } void ScarrArmModel::onVisit(tgModelVisitor& r) { tgModel::onVisit(r); } const std::vector<tgBasicActuator*>& ScarrArmModel::getAllMuscles() const { return allMuscles; } void ScarrArmModel::teardown() { notifyTeardown(); tgModel::teardown(); }
37.737024
126
0.656703
46498961a608ee3f3a53e462acc2ee7f0d39f35f
415
cpp
C++
sursa.cpp
seerj30/backtracking-recursiv_permutari
8ec7d75ed50305e68527d6dd74133910d9c35256
[ "MIT" ]
null
null
null
sursa.cpp
seerj30/backtracking-recursiv_permutari
8ec7d75ed50305e68527d6dd74133910d9c35256
[ "MIT" ]
null
null
null
sursa.cpp
seerj30/backtracking-recursiv_permutari
8ec7d75ed50305e68527d6dd74133910d9c35256
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int n; void back(int st[], int k) { int i,ev,j; if(k==n+1) { for(int i = 1; i < k; i++) cout << st[i] << " "; cout << endl; } else for(int i = 1; i <= n; i++) { st[k] = i; ev=1; for(j = 1; j < k; j++) if(st[j] == st[k]) ev=0; if(ev) back(st, k+1); } } int main() { int st[50]; cout << "n="; cin >> n; back(st, 1); return 0; }
12.205882
29
0.436145
464a3aeedf7fb4a9e26ce09eb1d2a829735d1f65
1,829
hh
C++
test/CLI/AppTest.hh
decouple/decouple.io
c841e905fbc8bd9507759a0ef6e56e1985c56c5a
[ "MIT" ]
null
null
null
test/CLI/AppTest.hh
decouple/decouple.io
c841e905fbc8bd9507759a0ef6e56e1985c56c5a
[ "MIT" ]
null
null
null
test/CLI/AppTest.hh
decouple/decouple.io
c841e905fbc8bd9507759a0ef6e56e1985c56c5a
[ "MIT" ]
null
null
null
<?hh // partial namespace Test\CLI; use Decouple\CLI\App; use Decouple\CLI\Request\Request; use Decouple\Decoupler\Decoupler; use Decouple\Registry\Paths; use Decouple\CLI\Console; class AppTest extends \Decouple\Test\TestCase { public function execute() : void { Console::output('Testing CLI bootstrap (version)'); $this->testBootstrapA(); Console::output('Testing CLI bootstrap (FooCommand)'); $this->testBootstrapB(); Console::output('Testing CLI bootstrap (BarCommand)'); $this->testBootstrapC(); } public function testBootstrapA() : void { $app = $this->__bootstrap("decouple:version"); $result = $this->capture($app); $this->assertEquals($result, "Decouple v0.1a\n"); Console::output('Passed'); } public function testBootstrapB() : void { $app = $this->__bootstrap("foo:bar"); $result = $this->capture($app); $this->assertEquals($result, "FooBar!\n"); Console::output('Passed'); } public function testBootstrapC() : void { $app = $this->__bootstrap("bar:baz --bar=wtf!"); $result = $this->capture($app); $this->assertEquals($result, "bar:wtf!\n"); Console::output('Passed'); } public function __bootstrap(string $args) : App { $args = stristr($args, ' ') ? new Vector(explode(' ', $args)) : Vector { $args }; $request = new Request($args); $services = Map {"Decouple\\CLI\\Request\Request" => $request}; $decoupler = new Decoupler($services); $app = new App($request, $decoupler, new Paths(Map { }), Vector { "Test\CLI\Fixture\FooCommand", "Test\CLI\Fixture\BarCommand" }); return $app; } public function capture(App $app) : string { ob_start(); try { $app->execute(); } catch(Exception $e) { echo $e->getMessage(); } return ob_get_clean(); } }
29.031746
85
0.631493
464b0c44e0f870c5e760b5c4e5248cfc41c05ea1
14,229
cpp
C++
modules/Math/test/Vector4Test.cpp
akb825/DeepSea
fff790d0a472cf2f9f89de653e0b4470ce605d24
[ "Apache-2.0" ]
5
2018-11-17T23:13:22.000Z
2021-09-30T13:37:04.000Z
modules/Math/test/Vector4Test.cpp
akb825/DeepSea
fff790d0a472cf2f9f89de653e0b4470ce605d24
[ "Apache-2.0" ]
null
null
null
modules/Math/test/Vector4Test.cpp
akb825/DeepSea
fff790d0a472cf2f9f89de653e0b4470ce605d24
[ "Apache-2.0" ]
2
2019-09-23T12:23:35.000Z
2020-04-07T05:31:06.000Z
/* * Copyright 2016 Aaron Barany * * 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 <DeepSea/Math/Vector4.h> #include <gtest/gtest.h> #include <cmath> // Handle older versions of gtest. #ifndef TYPED_TEST_SUITE #define TYPED_TEST_SUITE TYPED_TEST_CASE #endif template <typename T> struct Vector4TypeSelector; template <> struct Vector4TypeSelector<float> {typedef dsVector4f Type;}; template <> struct Vector4TypeSelector<double> {typedef dsVector4d Type;}; template <> struct Vector4TypeSelector<int> {typedef dsVector4i Type;}; template <typename T> class Vector4Test : public testing::Test { }; using Vector4Types = testing::Types<float, double, int>; TYPED_TEST_SUITE(Vector4Test, Vector4Types); template <typename T> class Vector4FloatTest : public Vector4Test<T> { }; using Vector4FloatTypes = testing::Types<float, double>; TYPED_TEST_SUITE(Vector4FloatTest, Vector4FloatTypes); inline float dsVector4_len(dsVector4f* a) { return dsVector4f_len(a); } inline double dsVector4_len(dsVector4d* a) { return dsVector4d_len(a); } inline double dsVector4_len(dsVector4i* a) { return dsVector4i_len(a); } inline float dsVector4_dist(dsVector4f* a, dsVector4f* b) { return dsVector4f_dist(a, b); } inline double dsVector4_dist(dsVector4d* a, dsVector4d* b) { return dsVector4d_dist(a, b); } inline double dsVector4_dist(dsVector4i* a, dsVector4i* b) { return dsVector4i_dist(a, b); } inline void dsVector4_normalize(dsVector4f* result, dsVector4f* a) { dsVector4f_normalize(result, a); } inline void dsVector4_normalize(dsVector4d* result, dsVector4d* a) { dsVector4d_normalize(result, a); } inline bool dsVector4_epsilonEqual(const dsVector4f* a, const dsVector4f* b, float epsilon) { return dsVector4f_epsilonEqual(a, b, epsilon); } inline bool dsVector4_epsilonEqual(const dsVector4d* a, const dsVector4d* b, double epsilon) { return dsVector4d_epsilonEqual(a, b, epsilon); } inline bool dsVector4_relativeEpsilonEqual(const dsVector4f* a, const dsVector4f* b, float epsilon) { return dsVector4f_relativeEpsilonEqual(a, b, epsilon); } inline bool dsVector4_relativeEpsilonEqual(const dsVector4d* a, const dsVector4d* b, double epsilon) { return dsVector4d_relativeEpsilonEqual(a, b, epsilon); } TYPED_TEST(Vector4Test, Initialize) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; EXPECT_EQ((TypeParam)-2.3, a.x); EXPECT_EQ((TypeParam)4.5, a.y); EXPECT_EQ((TypeParam)-6.7, a.z); EXPECT_EQ((TypeParam)8.9, a.w); EXPECT_EQ((TypeParam)-2.3, a.s); EXPECT_EQ((TypeParam)4.5, a.t); EXPECT_EQ((TypeParam)-6.7, a.p); EXPECT_EQ((TypeParam)8.9, a.q); EXPECT_EQ((TypeParam)-2.3, a.r); EXPECT_EQ((TypeParam)4.5, a.g); EXPECT_EQ((TypeParam)-6.7, a.b); EXPECT_EQ((TypeParam)8.9, a.w); EXPECT_EQ((TypeParam)-2.3, a.values[0]); EXPECT_EQ((TypeParam)4.5, a.values[1]); EXPECT_EQ((TypeParam)-6.7, a.values[2]); EXPECT_EQ((TypeParam)8.9, a.values[3]); } TYPED_TEST(Vector4Test, Add) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type b = {{(TypeParam)3.2, (TypeParam)-5.4, (TypeParam)7.6, (TypeParam)-9.8}}; Vector4Type result; dsVector4_add(result, a, b); EXPECT_EQ((TypeParam)-2.3 + (TypeParam)3.2, result.x); EXPECT_EQ((TypeParam)4.5 + (TypeParam)-5.4, result.y); EXPECT_EQ((TypeParam)-6.7 + (TypeParam)7.6, result.z); EXPECT_EQ((TypeParam)8.9 + (TypeParam)-9.8, result.w); } TYPED_TEST(Vector4Test, Subtract) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type b = {{(TypeParam)3.2, (TypeParam)-5.4, (TypeParam)7.6, (TypeParam)-9.8}}; Vector4Type result; dsVector4_sub(result, a, b); EXPECT_EQ((TypeParam)-2.3 - (TypeParam)3.2, result.x); EXPECT_EQ((TypeParam)4.5 - (TypeParam)-5.4, result.y); EXPECT_EQ((TypeParam)-6.7 - (TypeParam)7.6, result.z); EXPECT_EQ((TypeParam)8.9 - (TypeParam)-9.8, result.w); } TYPED_TEST(Vector4Test, Multiply) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type b = {{(TypeParam)3.2, (TypeParam)-5.4, (TypeParam)7.6, (TypeParam)-9.8}}; Vector4Type result; dsVector4_mul(result, a, b); EXPECT_EQ((TypeParam)-2.3 * (TypeParam)3.2, result.x); EXPECT_EQ((TypeParam)4.5 * (TypeParam)-5.4, result.y); EXPECT_EQ((TypeParam)-6.7 * (TypeParam)7.6, result.z); EXPECT_EQ((TypeParam)8.9 * (TypeParam)-9.8, result.w); } TYPED_TEST(Vector4Test, Divide) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type b = {{(TypeParam)3.2, (TypeParam)-5.4, (TypeParam)7.6, (TypeParam)-9.8}}; Vector4Type result; dsVector4_div(result, a, b); EXPECT_EQ((TypeParam)-2.3 / (TypeParam)3.2, result.x); EXPECT_EQ((TypeParam)4.5 / (TypeParam)-5.4, result.y); EXPECT_EQ((TypeParam)-6.7 / (TypeParam)7.6, result.z); EXPECT_EQ((TypeParam)8.9 / (TypeParam)-9.8, result.w); } TYPED_TEST(Vector4Test, Scale) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type result; dsVector4_scale(result, a, (TypeParam)3.2); EXPECT_EQ((TypeParam)-2.3 * (TypeParam)3.2, result.x); EXPECT_EQ((TypeParam)4.5 * (TypeParam)3.2, result.y); EXPECT_EQ((TypeParam)-6.7 * (TypeParam)3.2, result.z); EXPECT_EQ((TypeParam)8.9 * (TypeParam)3.2, result.w); } TYPED_TEST(Vector4Test, Neg) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type result; dsVector4_neg(result, a); EXPECT_EQ(-a.x, result.x); EXPECT_EQ(-a.y, result.y); EXPECT_EQ(-a.z, result.z); EXPECT_EQ(-a.w, result.w); } TYPED_TEST(Vector4Test, Dot) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type b = {{(TypeParam)3.2, (TypeParam)-5.4, (TypeParam)7.6, (TypeParam)-9.8}}; EXPECT_EQ((TypeParam)-2.3*(TypeParam)3.2 + (TypeParam)4.5*(TypeParam)-5.4 + (TypeParam)-6.7*(TypeParam)7.6 + (TypeParam)8.9*(TypeParam)-9.8, dsVector4_dot(a, b)); } TYPED_TEST(Vector4Test, Length) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; EXPECT_EQ(dsPow2((TypeParam)-2.3) + dsPow2((TypeParam)4.5) + dsPow2((TypeParam)-6.7) + dsPow2((TypeParam)8.9), dsVector4_len2(a)); EXPECT_EQ(std::sqrt(dsPow2((TypeParam)-2.3) + dsPow2((TypeParam)4.5) + dsPow2((TypeParam)-6.7) + dsPow2((TypeParam)8.9)), dsVector4_len(&a)); } TYPED_TEST(Vector4Test, Distance) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type b = {{(TypeParam)3.2, (TypeParam)-5.4, (TypeParam)7.6, (TypeParam)-9.8}}; EXPECT_EQ(dsPow2((TypeParam)-2.3 - (TypeParam)3.2) + dsPow2((TypeParam)4.5 - (TypeParam)-5.4) + dsPow2((TypeParam)-6.7 - (TypeParam)7.6) + dsPow2((TypeParam)8.9 - (TypeParam)-9.8), dsVector4_dist2(a, b)); EXPECT_EQ(std::sqrt(dsPow2((TypeParam)-2.3 - (TypeParam)3.2) + dsPow2((TypeParam)4.5 - (TypeParam)-5.4) + dsPow2((TypeParam)-6.7 - (TypeParam)7.6) + dsPow2((TypeParam)8.9 - (TypeParam)-9.8)), dsVector4_dist(&a, &b)); } TYPED_TEST(Vector4Test, Equal) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type b = {{(TypeParam)2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type c = {{(TypeParam)-2.3, (TypeParam)-4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type d = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)6.7, (TypeParam)8.9}}; Vector4Type e = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)-8.9}}; EXPECT_TRUE(dsVector4_equal(a, a)); EXPECT_FALSE(dsVector4_equal(a, b)); EXPECT_FALSE(dsVector4_equal(a, c)); EXPECT_FALSE(dsVector4_equal(a, d)); EXPECT_FALSE(dsVector4_equal(a, e)); } TEST(Vector4IntTest, Lerp) { dsVector4i a = {{-2, 4, -6, 8}}; dsVector4i b = {{3, -5, 7, -9}}; dsVector4i result; dsVector4i_lerp(&result, &a, &b, 0.3f); EXPECT_EQ(0, result.x); EXPECT_EQ(1, result.y); EXPECT_EQ(-2, result.z); EXPECT_EQ(2, result.w); } TYPED_TEST(Vector4FloatTest, Lerp) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type b = {{(TypeParam)3.2, (TypeParam)-5.4, (TypeParam)7.6, (TypeParam)-9.8}}; Vector4Type result; dsVector4_lerp(result, a, b, (TypeParam)0.3); EXPECT_EQ(dsLerp(a.x, b.x, (TypeParam)0.3), result.x); EXPECT_EQ(dsLerp(a.y, b.y, (TypeParam)0.3), result.y); EXPECT_EQ(dsLerp(a.z, b.z, (TypeParam)0.3), result.z); EXPECT_EQ(dsLerp(a.w, b.w, (TypeParam)0.3), result.w); } TYPED_TEST(Vector4FloatTest, Normalize) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type result; TypeParam length = dsVector4_len(&a); dsVector4_normalize(&result, &a); EXPECT_EQ((TypeParam)-2.3*(1/length), result.x); EXPECT_EQ((TypeParam)4.5*(1/length), result.y); EXPECT_EQ((TypeParam)-6.7*(1/length), result.z); EXPECT_EQ((TypeParam)8.9*(1/length), result.w); } TYPED_TEST(Vector4FloatTest, EpsilonEqual) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; TypeParam epsilon = (TypeParam)1e-3; Vector4Type a = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type b = {{(TypeParam)-2.3001, (TypeParam)4.5001, (TypeParam)-6.7001, (TypeParam)8.9001}}; Vector4Type c = {{(TypeParam)-2.31, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type d = {{(TypeParam)-2.3, (TypeParam)4.51, (TypeParam)-6.7, (TypeParam)8.9}}; Vector4Type e = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.71, (TypeParam)8.9}}; Vector4Type f = {{(TypeParam)-2.3, (TypeParam)4.5, (TypeParam)-6.7, (TypeParam)8.91}}; EXPECT_TRUE(dsVector4_epsilonEqual(&a, &b, epsilon)); EXPECT_FALSE(dsVector4_epsilonEqual(&a, &c, epsilon)); EXPECT_FALSE(dsVector4_epsilonEqual(&a, &d, epsilon)); EXPECT_FALSE(dsVector4_epsilonEqual(&a, &e, epsilon)); EXPECT_FALSE(dsVector4_epsilonEqual(&a, &f, epsilon)); } TYPED_TEST(Vector4FloatTest, RelativeEpsilonEqual) { typedef typename Vector4TypeSelector<TypeParam>::Type Vector4Type; TypeParam epsilon = (TypeParam)1e-3; Vector4Type a = {{(TypeParam)-23.0, (TypeParam)45.0, (TypeParam)-67.0, (TypeParam)89.0}}; Vector4Type b = {{(TypeParam)-23.001, (TypeParam)45.001, (TypeParam)-67.001, (TypeParam)89.001}}; Vector4Type c = {{(TypeParam)-23.1, (TypeParam)45.0, (TypeParam)-67.0, (TypeParam)89.0}}; Vector4Type d = {{(TypeParam)-23.0, (TypeParam)45.1, (TypeParam)-67.0, (TypeParam)89.0}}; Vector4Type e = {{(TypeParam)-23.0, (TypeParam)45.0, (TypeParam)-67.1, (TypeParam)89.0}}; Vector4Type f = {{(TypeParam)-23.0, (TypeParam)45.0, (TypeParam)-67.0, (TypeParam)89.1}}; EXPECT_TRUE(dsVector4_relativeEpsilonEqual(&a, &b, epsilon)); EXPECT_FALSE(dsVector4_relativeEpsilonEqual(&a, &c, epsilon)); EXPECT_FALSE(dsVector4_relativeEpsilonEqual(&a, &d, epsilon)); EXPECT_FALSE(dsVector4_relativeEpsilonEqual(&a, &e, epsilon)); EXPECT_FALSE(dsVector4_relativeEpsilonEqual(&a, &f, epsilon)); } TEST(Vector4, ConvertFloatToDouble) { dsVector4f vectorf = {{-2.3f, 4.5f, -6.7f, 8.9f}}; dsVector4d vectord; dsConvertFloatToDouble(vectord, vectorf); EXPECT_FLOAT_EQ(vectorf.x, (float)vectord.x); EXPECT_FLOAT_EQ(vectorf.y, (float)vectord.y); EXPECT_FLOAT_EQ(vectorf.z, (float)vectord.z); EXPECT_FLOAT_EQ(vectorf.w, (float)vectord.w); } TEST(Vector4, ConvertDoubleToFloat) { dsVector4d vectord = {{-2.3, 4.5, -6.7, 8.9}}; dsVector4f vectorf; dsConvertDoubleToFloat(vectorf, vectord); EXPECT_FLOAT_EQ((float)vectord.x, vectorf.x); EXPECT_FLOAT_EQ((float)vectord.y, vectorf.y); EXPECT_FLOAT_EQ((float)vectord.z, vectorf.z); EXPECT_FLOAT_EQ((float)vectord.w, vectorf.w); } TEST(Vector4, ConvertFloatToInt) { dsVector4f vectorf = {{-2, 3, -4, 5}}; dsVector4i vectori; dsConvertFloatToInt(vectori, vectorf); EXPECT_EQ(vectorf.x, (float)vectori.x); EXPECT_EQ(vectorf.y, (float)vectori.y); EXPECT_EQ(vectorf.z, (float)vectori.z); EXPECT_EQ(vectorf.w, (float)vectori.w); } TEST(Vector4, ConvertIntToFloat) { dsVector4i vectori = {{-2, 3, -4, 5}}; dsVector4f vectorf; dsConvertIntToFloat(vectorf, vectori); EXPECT_EQ(vectori.x, (int)vectorf.x); EXPECT_EQ(vectori.y, (int)vectorf.y); EXPECT_EQ(vectori.z, (int)vectorf.z); EXPECT_EQ(vectori.w, (int)vectorf.w); } TEST(Vector4, ConvertDoubleToInt) { dsVector4d vectord = {{-2, 3, -4, 5}}; dsVector4i vectori; dsConvertDoubleToInt(vectori, vectord); EXPECT_EQ(vectord.x, vectori.x); EXPECT_EQ(vectord.y, vectori.y); EXPECT_EQ(vectord.z, vectori.z); EXPECT_EQ(vectord.w, vectori.w); } TEST(Vector4, ConvertIntToDouble) { dsVector4i vectori = {{-2, 3, -4, 5}}; dsVector4d vectord; dsConvertIntToDouble(vectord, vectori); EXPECT_EQ(vectori.x, vectord.x); EXPECT_EQ(vectori.y, vectord.y); EXPECT_EQ(vectori.z, vectord.z); EXPECT_EQ(vectori.w, vectord.w); }
31.135667
100
0.710661
464b77d844ad0b1b829a3053a1afbc119a63c6ad
4,139
cpp
C++
cha1/max_subarray.cpp
byzhou/CLRS
1af11fc971b9b91a050cdb1f2b3cf9a9471c8a22
[ "MIT" ]
null
null
null
cha1/max_subarray.cpp
byzhou/CLRS
1af11fc971b9b91a050cdb1f2b3cf9a9471c8a22
[ "MIT" ]
null
null
null
cha1/max_subarray.cpp
byzhou/CLRS
1af11fc971b9b91a050cdb1f2b3cf9a9471c8a22
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdlib> #include <ctime> #include <time.h> #include <stdio.h> using namespace std; const int neg_infinity = 0xFFFFFFFF ; const int pos_infinity = 0x7FFFFFFF ; void print_array ( int* array , int num ) ; void diff_array ( int* array, int* diff_array ) ; void max_cross_subarray ( int* array , int& left , int mid , int& right ) ; struct left_right { int left ; int right ; int sum ; }; /* For a given array, this function print out the array's * elements. */ void print_array ( int* array , int num ) { printf ( "Below is the the array: \n " ) ; for ( int i = 0 ; i < num ; i ++ ) { printf ( "%d \t", array[i] ) ; } printf ( "\n " ) ; } /* This function will take the diff between two elements of an * array. */ void diff_array ( int* array , int* diff_array ) { if ( (array + 1) == NULL ) printf ( " This array has too less elements. \n " ) ; for ( int i = 0 ; (array + i + 1) != NULL ; i ++ ) diff_array[i] = array[i+1] - array[i]; } struct left_right max_cross_subarray ( int* array , int left , int mid , int right ) { int left_sum = neg_infinity ; int right_sum = neg_infinity ; int sum = 0 ; int i = 0 ; int return_left = 0 ; int return_right= 0 ; struct left_right tmp; if (left == mid || mid == right || left == right) return 0; for ( i = mid ; i > left ; i -- ) { sum += array[i] ; if ( sum > left_sum ) left_sum = sum ; return_left = i ; } tmp.left = return_left ; for ( i = mid ; i < right ; i ++ ) { sum += array[i] ; if ( sum > right_sum ) right_sum = sum ; return_right = i ; } tmp.right = return_right ; tmp.sum = left_sum + right_sum ; return tmp; } struct left_right max_subarray ( int* array , int left , int right ) { int left_sum = neg_infinity ; int right_sum = neg_infinity ; int mid_sum = neg_infinity ; int mid = (left + right) / 2 ; struct left_rigth tmp ; tmp.left = left ; tmp.right = right ; tmp.sum = array[left] ; if (left == right) return tmp ; else { left_sum = max_subarray ( array , left , mid ) . sum ; right_sum = max_subarray ( array , mid , right ) . sum ; mid_sum = max_cross_subarray ( array , left , mid , right ) . sum ; if ( ( left_sum >= right_sum ) && ( left_sum >= mid_sum ) ) return max_subarray ( array , left , mid ) ; if ( ( right_sum >= left_sum ) && ( right_sum >= mid_sum ) ) return max_subarray ( array , mid , right ) ; if ( ( mid_sum >= left_sum ) && ( mid_sum >= right_sum ) ) return max_cross_subarray ( array , left , mid , right ) ; } } int main(){ struct left_right = tmp ; //length of the array const int num = 3; //random generator seed srand(time(0)); //time generation clock_t t; int array[num*num]; int i,j; //record start time t = clock(); for ( i = 0; i < num; i++ ) { for ( j = 0; j < num; j ++ ) { array[i * num + j] = rand() / 1000000 ; printf( "array %d value is %d \n", i*num + j, array[i * num + j] ) ; } } printf( "The time spent on the array generation is: %4.2f \n", (float)( clock() - t) / CLOCKS_PER_SEC ) ; long double key; //record start time tmp = max_subarray(array , 0 , num * num - 1 ) ; print_array ( array + tmp.left, , tmp.right - tmp.left + 1 ) ; //record end time printf( "The time spent on the array sorting is: %4.2f \n", (float)( clock() - t) / CLOCKS_PER_SEC ); cout<<"The array has been sorted."<<endl; //print the sorted array /* for ( i = 0; i < num; i++ ) { for ( j = 0 ; j < num ; j++ ) { printf( "array %d value is %d \n", i * num + j , array[i * num + j] ) ; } } */ return 0; }
28.349315
113
0.512926
464ca6a431f7f3789925b04e79a4043171b28317
785
cpp
C++
samples/test/src/main.cpp
hiroog/CCTFLibrary
9eb1d7f740ba7f6174c40dba255c12212b85d9e4
[ "MIT" ]
null
null
null
samples/test/src/main.cpp
hiroog/CCTFLibrary
9eb1d7f740ba7f6174c40dba255c12212b85d9e4
[ "MIT" ]
null
null
null
samples/test/src/main.cpp
hiroog/CCTFLibrary
9eb1d7f740ba7f6174c40dba255c12212b85d9e4
[ "MIT" ]
null
null
null
// 2019/09/01 Hiroyuki Ogasawara // vim:ts=4 sw=4 noet: #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <cctf/CCTFSystem.h> using namespace cctf; //----------------------------------------------------------------------------- class MySystemAPI : public CCSystemAPI { public: size_t AllocCount= 0; public: void* Alloc( size_t byte_size ) override { AllocCount++; return malloc( byte_size ); } void Free( void* ptr, size_t byte_size ) override { AllocCount--; free( ptr ); } }; //----------------------------------------------------------------------------- extern void cctest(); extern void ccmnist(); int main() { static MySystemAPI api; CCSystem::RegisterAPI( &api ); cctest(); ccmnist(); assert( api.AllocCount == 0 ); return 0; }
16.702128
79
0.536306
464de57caa7356693d06b6ce102678f354019d98
4,959
cpp
C++
Lab_03.cpp
Mila04/Lab_3
ff874c0c77f661e39abada417194bc2a5e3d292b
[ "MIT" ]
null
null
null
Lab_03.cpp
Mila04/Lab_3
ff874c0c77f661e39abada417194bc2a5e3d292b
[ "MIT" ]
null
null
null
Lab_03.cpp
Mila04/Lab_3
ff874c0c77f661e39abada417194bc2a5e3d292b
[ "MIT" ]
null
null
null
#include <cstdlib> #include <cstdio> #include <cctype> #include <vector> #include <stack> #include <utility> #include <iostream> #include <sstream> #include <string> #include <ctype.h> #include <locale> #include <list> using namespace std; //split the string in vector of type string vector<string> split(const string &s, char delim) { stringstream ss(s); string item; vector<string> tokens; while (getline(ss, item, delim)) { tokens.push_back(item); } return tokens; } vector< vector<char> > string_to_vector_of_char(string input_current_state){ vector<string> states = split(input_current_state,';'); vector<char> aux; vector< vector<char> > state; vector<string>::iterator it; //cycle to get the vector for (it=states.begin(); it<states.end(); it++) { string aux_string = *it; if (aux_string.compare(" ()") != 0 && aux_string.compare("()") != 0 ) { for(int i = 0; i< aux_string.length(); i++) { if(isalpha(aux_string[i])) { aux.push_back(aux_string[i]); } } //create the vector of vectors state.push_back(aux); //earse the content of the vector aux to get the next states right aux.erase(aux.begin(), aux.end()); } else { aux.push_back(' '); //create the vector of vectors state.push_back(aux); //earse the content of the vector aux to get the next states right aux.erase(aux.begin(), aux.end()); } } return state; } // State class to repepresent the conection of each state class State{ vector< vector<char> > state; int path_cost; pair<int, int> movement; int visited = 1; int h = 0; int g = 0; public: State(vector<vector <char> > state); State(vector<vector <char> > state,int path_cost,pair<int,int> movement); vector<vector<char> > getState(); int getVisit(); int getPathCost(); void setMovement(pair<int,int> movement); void setPathCost(int v); void setVisited(int v); void setState(vector< vector<char> > state); void DFS(State state); }; vector<vector<char> > State::getState(){ return this->state; } void State::setPathCost(int v){ this->path_cost = v; } int State::getPathCost(){ return this->path_cost; } void State::setVisited(int v){ this->visited = v; } void State::setMovement(pair<int,int> movement){ this->movement = movement; } void State::setState(vector< vector<char> > state){ this->state = state; } int State::getVisit(){ return this->visited; } State::State(vector<vector <char> > state){ this->state = state; this->path_cost = 0; this->movement = {0,0}; } State::State(vector<vector <char> > state,int path_cost,pair<int,int> movement){ this->state = state; this->path_cost = path_cost; this->movement = movement; this->visited = 1; } stack< State > GenerateEstates(State state){ //variables stack< State > DFS_Stack; int i = 0; int j = 0; char aux; int size = state.getState().size() -1; vector<vector<char> > v = state.getState(); for (i = 0;i < v.size(); i++) { if (v.at(i).back() != ' '){ aux = v.at(i).back(); v.at(i).pop_back(); for (j = 0; j < v.size(); j++) { if (i != size-j){ vector<char> aux_vector; if(state.getState().at(size-j).back() == ' '){ aux_vector.push_back(aux); State state_aux(v,(state.getPathCost() + 1 + abs(size-j)),{i,j}); v.at(size-j).swap(aux_vector); } else{ v.at(size-j).push_back(aux); State state_aux(v,(state.getPathCost() + 1 + abs(size-j)),{i,j}); DFS_Stack.push(state_aux); v.at(size-j).pop_back(); } } } v.at(i).push_back(aux); } } return DFS_Stack; } void DFSUtil(State state){ } void DFS(State state){ stack< State > states = GenerateEstates(state); for (stack< State > dump = states; !dump.empty(); dump.pop()){ cout<< "estado: \n"; for (int i = 0; i < dump.top().getState().size();i++){ for (int j = 0; j < dump.top().getState().at(i).size(); ++j) { cout<< dump.top().getState().at(i)[j]; } cout << "\n"; } } for (; !states.empty(); states.pop()){ if(states.top().getVisit() != 0){ // DFS(states.top()); }else{ } } } int main(){ // variables int number_height; string input_current_state; string input_goal_state; vector< vector<char> > current_state; vector< vector<char> > goal_state; //read the height scanf("%d \n", &number_height); printf("number of the height is: %d \n", number_height); //read current state getline(cin, input_current_state); //convert the string to vecor of vector of type char current_state = string_to_vector_of_char(input_current_state); // it works // cout << "succes: " << current_state.at(0)[0] << "_\n"; //initialize state State state(current_state); DFS(state); // read el goal state getline(cin, input_goal_state); //convert the string to vecor of vector of type char goal_state = string_to_vector_of_char(input_goal_state); return 0; }
23.391509
80
0.631377
4651aaa16edb80934cf929c9247afe00b844b711
1,579
cpp
C++
src/asseteditdelegate.cpp
valzav/cryptoportfolio-qt
bea3eb4ad06b9262300212a90d898fd0a695fc87
[ "MIT" ]
3
2020-02-13T17:42:45.000Z
2022-01-09T22:10:41.000Z
src/asseteditdelegate.cpp
valzav/cryptoportfolio-qt
bea3eb4ad06b9262300212a90d898fd0a695fc87
[ "MIT" ]
null
null
null
src/asseteditdelegate.cpp
valzav/cryptoportfolio-qt
bea3eb4ad06b9262300212a90d898fd0a695fc87
[ "MIT" ]
2
2015-08-30T12:45:39.000Z
2022-03-24T17:54:08.000Z
#include <QtCore> #include <QtSql> #include "asseteditdelegate.h" AssetEditDelegate::AssetEditDelegate(QObject *parent) : QItemDelegate(parent) { } void AssetEditDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QComboBox *combo = qobject_cast<QComboBox *>(editor); if (!combo) QItemDelegate::setEditorData(editor, index); else combo->setCurrentIndex(combo->findText(index.data().toString())); } void AssetEditDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { if (!index.isValid()) return; QSqlRelationalTableModel *sqlModel = qobject_cast<QSqlRelationalTableModel *>(model); QSqlTableModel *childModel = sqlModel ? sqlModel->relationModel(index.column()) : 0; QComboBox *combo = qobject_cast<QComboBox *>(editor); if (!sqlModel || !childModel || !combo) { QItemDelegate::setModelData(editor, model, index); } else { int currentItem = combo->currentIndex(); int childColIndex = childModel->fieldIndex(sqlModel->relation(index.column()).displayColumn()); int childEditIndex = childModel->fieldIndex(sqlModel->relation(index.column()).indexColumn()); QVariant data1 = childModel->data(childModel->index(currentItem, childColIndex), Qt::DisplayRole); QVariant data2 = childModel->data(childModel->index(currentItem, childEditIndex), Qt::EditRole); sqlModel->setData(index, data1, Qt::DisplayRole); sqlModel->setData(index, data2, Qt::EditRole); } emit dataChanged(index); }
42.675676
114
0.71121
465470dd4d63504759a42fd83d03389631e1900b
10,971
cpp
C++
solver/modules/slide/src/StraightSolver.cpp
taiheioki/procon2014_ut
8199ff0a54220f1a0c51acece377f65b64db4863
[ "MIT" ]
2
2021-04-14T06:41:18.000Z
2021-04-29T01:56:08.000Z
solver/modules/slide/src/StraightSolver.cpp
taiheioki/procon2014_ut
8199ff0a54220f1a0c51acece377f65b64db4863
[ "MIT" ]
null
null
null
solver/modules/slide/src/StraightSolver.cpp
taiheioki/procon2014_ut
8199ff0a54220f1a0c51acece377f65b64db4863
[ "MIT" ]
null
null
null
#include <algorithm> #include <functional> #include <limits> #include <boost/format.hpp> #include "StraightSolver.hpp" namespace slide { void StraightSolver::alignRow(AnswerBoard<Flexible>& board) { BOOST_ASSERT(board.height() >= 3 && board.width() >= 2); // 右端2個以外 rep(dstX, board.width()-2){ const Point dst(board.height()-1, dstX); const Point src = board.find(board.correctId(dst)); // 既に大丈夫だった if(src == dst){ continue; } if(dst.x == src.x){ if(dst.x <= board.selected.x){ moveTargetPiece(board, src, dst, 0, dst.x, board.height(), board.width()-dst.x); } else{ moveTargetPiece(board, src, dst + Point(-1, 0), 0, 0, board.height()-1, board.width()); board.moveVertically(dst.y - 2); board.moveHorizontally(dst.x); board.moveRight(); board.moveDown(); board.moveDown(); board.moveLeft(); board.moveUp(); } } else if(dst.x < src.x){ if(board.selected.x < dst.x){ board.moveHorizontally(dst.x); } moveTargetPiece(board, src, dst, 0, dst.x, board.height(), board.width()-dst.x); } else{ if(dst.x < board.selected.x){ board.moveHorizontally(dst.x); } if(board.selected.y == dst.y){ board.moveUp(); } moveTargetPiece(board, src, dst + Point(-1, 0), 0, 0, board.height(), dst.x+1); // src と dst は絶対に同じにならない if(board.selected.x == dst.x - 1){ board.moveUp(); board.moveRight(); } board.moveRight(); board.moveDown(); board.moveDown(); board.moveLeft(); board.moveUp(); } } if(board.isAligned(board.height()-1, board.width()-1)){ const uchar pieceId = board.correctId(board.height()-1, board.width()-2); if(board(board.height()-1, board.width()-2) == pieceId){ return; } else if(board(board.height()-2, board.width()-2) == pieceId && board.selected == Point(board.height()-1, board.width()-2)){ board.moveUp(); return; } } // 最後の二つ目 { const uchar pieceId = board.correctId(board.height()-1, board.width()-2); const Point src = board.find(pieceId); const Point dst(board.height()-1, board.width()-1); if(src == dst); else if(src.y == dst.y){ board.moveHorizontally(board.width() - 1); board.moveVertically(board.height() - 1); board.moveLeft(); } else if(board.selected.y == dst.y && board.width()-2 <= src.x){ moveTargetPiece(board, src, dst, 0, board.width()-2, board.height(), 2); } else{ if(board.selected.y == dst.y){ board.moveUp(); } moveTargetPiece(board, src, Point(dst.y-1, dst.x), 0, 0, board.height()-1, board.width()); board.moveHorizontally(board.width() - 2); board.moveVertically(board.height() - 1); board.moveRight(); board.moveUp(); } } // ラス1 { const uchar pieceId = board.correctId(board.height()-1, board.width()-1); if(board.selected.y == board.height()-1 && board(board.height()-2, board.width()-2) != pieceId){ board.moveUp(); } if(board.selected.y != board.height()-1 && board(board.height()-1, board.width()-2) != pieceId){ const Point src = board.find(pieceId); const Point dst(board.height()-2, board.width()-1); moveTargetPiece(board, src, dst, 0, 0, board.height()-1, board.width()); board.moveHorizontally(board.width() - 2); board.moveVertically(board.height() - 1); board.moveRight(); board.moveUp(); } else if(board.width() >= 3){ board.moveHorizontally(board.width() - 2); board.moveVertically(board.height() - 1); board.moveRight(); board.moveUp(); board.moveLeft(); board.moveLeft(); board.moveDown(); board.moveRight(); board.moveRight(); board.moveUp(); board.moveLeft(); board.moveDown(); board.moveLeft(); board.moveUp(); } else{ board.moveHorizontally(0); board.moveVertically(board.height() - 1); board.moveRight(); board.moveUp(); board.moveLeft(); board.moveUp(); board.moveRight(); board.moveDown(); board.moveDown(); board.moveLeft(); board.moveUp(); board.moveRight(); board.moveUp(); board.moveLeft(); board.moveDown(); board.moveDown(); board.moveRight(); board.moveUp(); } } } void StraightSolver::moveTargetPiece(AnswerBoard<Flexible>& board, Point src, Point dst, int y, int x, int height, int width) { BOOST_ASSERT(src.isIn(y, x, height, width)); BOOST_ASSERT(dst.isIn(y, x, height, width)); BOOST_ASSERT(board.selected.isIn(y, x, height, width)); BOOST_ASSERT(0 <= y && y+height <= board.height() && 0 <= x && x+width <= board.width()); BOOST_ASSERT(height >= 2 && width >= 2); BOOST_ASSERT(src != board.selected); // 既に大丈夫だった if(src == dst){ return; } const uchar pieceId = board(src); const Point sel = board.selected; // src に隣接する有効なセルを列挙 Direction dir = Direction::Up; Point adj = Point(-1, -1); int minDist = std::numeric_limits<int>::max(); // for each directions rep(k, 4){ const Direction nowdir = Direction(k); if(dst.y >= src.y && nowdir == Direction::Up) continue; if(dst.y <= src.y && nowdir == Direction::Down) continue; if(dst.x >= src.x && nowdir == Direction::Left) continue; if(dst.x <= src.x && nowdir == Direction::Right) continue; const Point nowadj = src + Point::delta(nowdir); if(!nowadj.isIn(y, x, height, width)){ continue; } const int dist = (nowadj - sel).l1norm(); if(dist < minDist){ dir = nowdir; adj = nowadj; minDist = dist; } } BOOST_ASSERT(adj.y >= 0); // 月蝕判定 const bool eclipseY = (sel.y <= src.y && src.y < adj.y) || (adj.y < src.y && src.y <= sel.y); const bool eclipseX = (sel.x <= src.x && src.x < adj.x) || (adj.x < src.x && src.x <= sel.x); // 月蝕の位置で一直線に並んでいるケース // the special case if(sel.x == src.x && src.x == adj.x && eclipseY){ sel.x == x ? board.moveRight() : board.moveLeft(); } else if(sel.y == src.y && src.y == adj.y && eclipseX){ sel.y == y ? board.moveDown() : board.moveUp(); } // 月蝕の位置の方向から移動 if(eclipseY){ board.moveVertically(adj.y); board.moveHorizontally(adj.x); } else{ board.moveHorizontally(adj.x); board.moveVertically(adj.y); } // move target for(;;){ board.move(dir.opposite()); if(board(dst) == pieceId){ break; } switch(dir){ case Direction::Up: if(board.selected.x == dst.x){ dst.x == x ? board.moveRight() : board.moveLeft(); board.moveUp(); board.moveUp(); dst.x == x ? board.moveLeft() : board.moveRight(); } else if(board.selected.x < dst.x){ board.moveRight(); board.moveUp(); dir = Direction::Right; } else{ board.moveLeft(); board.moveUp(); dir = Direction::Left; } break; case Direction::Right: if(board.selected.y == dst.y){ dst.y == y ? board.moveDown() : board.moveUp(); board.moveRight(); board.moveRight(); dst.y == y ? board.moveUp() : board.moveDown(); } else if(board.selected.y < dst.y){ board.moveDown(); board.moveRight(); dir = Direction::Down; } else{ board.moveUp(); board.moveRight(); dir = Direction::Up; } break; case Direction::Down: if(board.selected.x == dst.x){ dst.x == x ? board.moveRight() : board.moveLeft(); board.moveDown(); board.moveDown(); dst.x == x ? board.moveLeft() : board.moveRight(); } else if(board.selected.x > dst.x){ board.moveLeft(); board.moveDown(); dir = Direction::Left; } else{ board.moveRight(); board.moveDown(); dir = Direction::Right; } break; case Direction::Left: if(board.selected.y == dst.y){ dst.y == y ? board.moveDown() : board.moveUp(); board.moveLeft(); board.moveLeft(); dst.y == y ? board.moveUp() : board.moveDown(); } else if(board.selected.y < dst.y){ board.moveDown(); board.moveLeft(); dir = Direction::Down; } else{ board.moveUp(); board.moveLeft(); dir = Direction::Up; } break; } } } void StraightSolver::align2x2(AnswerBoard<Flexible>& board) { BOOST_ASSERT(board.selected.isIn(2, 2)); board.moveVertically(0); board.moveHorizontally(0); const uchar id = board.correctId(0, 1); if(board(1, 0) == id){ board.moveDown(); board.moveRight(); board.moveUp(); board.moveLeft(); } else if(board(1, 1) == id){ board.moveRight(); board.moveDown(); board.moveLeft(); board.moveUp(); } if(!board.isAligned(1, 0)){ board.select(1, 0); board.moveRight(); } } AnswerBoard<Flexible> StraightSolver::cropTo( const AnswerBoard<Flexible>& src, int y, int x, int height, int width, Direction topSide, bool yflip, bool xflip) { Board<Flexible> dst(topSide.isUpOrDown() ? height : width, topSide.isUpOrDown() ? width : height); rep(i, height) rep(j, width){ uchar id = src(i+y, j+x); id = Point(id).rotateFlip(topSide, yflip, xflip, height, width).toInt(); dst(Point(i, j).rotateFlip(topSide, yflip, xflip, height, width)) = id; } AnswerBoard<Flexible> answerBoard(dst); answerBoard.selected = (src.selected - Point(y, x)).rotateFlip(topSide, yflip, xflip, height, width); return answerBoard; } void StraightSolver::restore( const AnswerBoard<Flexible>& src, AnswerBoard<Flexible>& dst, int y, int x, Direction topSide, bool yflip, bool xflip) { const Direction preTopSide = topSide; topSide = topSide.isRightOrLeft() ? topSide.opposite() : topSide; rep(i, src.height()) rep(j, src.width()){ uchar id = src(i, j); id = (Point(id).rotateFlip(topSide, yflip, xflip, src.height(), src.width()) + Point(y, x)).toInt(); dst.at(Point(i, j).rotateFlip(topSide, yflip, xflip, src.height(), src.width()) + Point(y, x)) = id; } dst.selected = src.selected.rotateFlip(topSide, yflip, xflip, src.height(), src.width()) + Point(y, x); // answer の restore for(const Move& move : src.answer){ if(move.isSelection){ dst.answer.emplace_back(move.getSelected().rotateFlip(topSide, yflip, xflip, src.height(), src.width()) + Point(y, x)); } else{ Direction dir = move.getDirection(); if(yflip && dir.isUpOrDown()) dir = dir.opposite(); if(xflip && dir.isRightOrLeft()) dir = dir.opposite(); dst.answer.emplace_back(dir + preTopSide); } } } void StraightSolver::solve() { // initialize AnswerBoard AnswerBoard<Flexible> board(problem.board); board.select(board.find(board.correctId(0, 0))); // continue rearrangement until the remaining region is larger than 2x2 int remH = board.height(); int remW = board.width(); while(remH > 2 || remW > 2){ const bool isRow = remH >= remW; if(isRow){ AnswerBoard<Flexible> tmp = cropTo(board, 0, 0, remH, remW, Direction::Up, false, false); alignRow(tmp); restore(tmp, board, 0, 0, Direction::Up, false, false); --remH; } else{ AnswerBoard<Flexible> tmp = cropTo(board, 0, 0, remH, remW, Direction::Left, false, false); alignRow(tmp); restore(tmp, board, 0, 0, Direction::Left, false, false); --remW; } } align2x2(board); board.answer.optimize(); onCreatedAnswer(board.answer); std::cout << "move_count = " << board.answer.size() << std::endl; } } // end of namespace slide
25.753521
125
0.627199
4654c53aeb35a7c4dbdd747d4f61e5dd3ced6dd0
3,332
hpp
C++
alpaka/include/alpaka/block/shared/dyn/BlockSharedMemDynUniformCudaHipBuiltIn.hpp
alpaka-group/mallocMC
ddba224b764885f816c42a7719551b14e6f5752b
[ "MIT" ]
6
2021-02-01T09:01:39.000Z
2021-11-14T17:09:03.000Z
alpaka/include/alpaka/block/shared/dyn/BlockSharedMemDynUniformCudaHipBuiltIn.hpp
alpaka-group/mallocMC
ddba224b764885f816c42a7719551b14e6f5752b
[ "MIT" ]
17
2020-11-09T14:13:50.000Z
2021-11-03T11:54:54.000Z
alpaka/include/alpaka/block/shared/dyn/BlockSharedMemDynUniformCudaHipBuiltIn.hpp
alpaka-group/mallocMC
ddba224b764885f816c42a7719551b14e6f5752b
[ "MIT" ]
null
null
null
/* Copyright 2019 Benjamin Worpitz, René Widera * * This file is part of alpaka. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #if defined(ALPAKA_ACC_GPU_CUDA_ENABLED) || defined(ALPAKA_ACC_GPU_HIP_ENABLED) # include <alpaka/core/BoostPredef.hpp> # if defined(ALPAKA_ACC_GPU_CUDA_ENABLED) && !BOOST_LANG_CUDA # error If ALPAKA_ACC_GPU_CUDA_ENABLED is set, the compiler has to support CUDA! # endif # if defined(ALPAKA_ACC_GPU_HIP_ENABLED) && !BOOST_LANG_HIP # error If ALPAKA_ACC_GPU_HIP_ENABLED is set, the compiler has to support HIP! # endif # include <alpaka/block/shared/dyn/Traits.hpp> # include <type_traits> namespace alpaka { //############################################################################# //! The GPU CUDA/HIP block shared memory allocator. class BlockSharedMemDynUniformCudaHipBuiltIn : public concepts::Implements<ConceptBlockSharedDyn, BlockSharedMemDynUniformCudaHipBuiltIn> { public: //----------------------------------------------------------------------------- BlockSharedMemDynUniformCudaHipBuiltIn() = default; //----------------------------------------------------------------------------- __device__ BlockSharedMemDynUniformCudaHipBuiltIn(BlockSharedMemDynUniformCudaHipBuiltIn const&) = delete; //----------------------------------------------------------------------------- __device__ BlockSharedMemDynUniformCudaHipBuiltIn(BlockSharedMemDynUniformCudaHipBuiltIn&&) = delete; //----------------------------------------------------------------------------- __device__ auto operator=(BlockSharedMemDynUniformCudaHipBuiltIn const&) -> BlockSharedMemDynUniformCudaHipBuiltIn& = delete; //----------------------------------------------------------------------------- __device__ auto operator=(BlockSharedMemDynUniformCudaHipBuiltIn&&) -> BlockSharedMemDynUniformCudaHipBuiltIn& = delete; //----------------------------------------------------------------------------- /*virtual*/ ~BlockSharedMemDynUniformCudaHipBuiltIn() = default; }; namespace traits { //############################################################################# template<typename T> struct GetDynSharedMem<T, BlockSharedMemDynUniformCudaHipBuiltIn> { //----------------------------------------------------------------------------- __device__ static auto getMem(BlockSharedMemDynUniformCudaHipBuiltIn const&) -> T* { // Because unaligned access to variables is not allowed in device code, // we have to use the widest possible type to have all types aligned correctly. // See: http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#shared // http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#vector-types extern __shared__ float4 shMem[]; return reinterpret_cast<T*>(shMem); } }; } // namespace traits } // namespace alpaka #endif
45.643836
114
0.536315
465af3690db8e7e38b86005371afe4aa42b6cc8b
556
cpp
C++
test/filter.cpp
ericjavier/yaml
92d9097fc58602fbc88000fd22e2debc2f90996c
[ "Apache-2.0" ]
1
2015-04-12T19:46:13.000Z
2015-04-12T19:46:13.000Z
test/filter.cpp
ericjavier/yaml
92d9097fc58602fbc88000fd22e2debc2f90996c
[ "Apache-2.0" ]
null
null
null
test/filter.cpp
ericjavier/yaml
92d9097fc58602fbc88000fd22e2debc2f90996c
[ "Apache-2.0" ]
null
null
null
#include <gtest/gtest.h> #include <yaml/config.hpp> #include <yaml/detail/placeholders.hpp> #include <yaml/arithmetic.hpp> #include <yaml/sequence/filter.hpp> #include "test_utils.hpp" using namespace YAML_NSP; using func = less::ret<_0, std::integral_constant<int, 3>>; using expected = list<std::integral_constant<int, 0>, std::integral_constant<int, 1>, std::integral_constant<int, 2 >>; TEST(filter, seq) { expect_same_seq<expected, filter::ret<func, seq3>>(); } TEST(filter, list) { expect_same_seq<expected, filter::ret<func, lst3>>(); }
25.272727
59
0.723022
465bb25a1f734987150e98294c974113721a02e6
991
cc
C++
src/abc011/c.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc011/c.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc011/c.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
#define _GLIBCXX_DEBUG #include <bits/stdc++.h> using namespace std; typedef long long ll; const int INF = 400; int dfs(int start, vector<int> &dp, set<int> &ng) { if(dp[start] >= 0) { return dp[start]; } if(ng.find(start) != ng.end()) { return dp[start] = INF; } int one = INF, two = INF, three = INF; if(start - 1 >= 0) { one = dfs(start - 1, dp, ng); } if(start - 2 >= 0) { two = dfs(start - 2, dp, ng); } if(start - 3 >= 0) { three = dfs(start - 3, dp, ng); } return dp[start] = min(one, min(two, three)) + 1; } string solve(int n, vector<int> ng) { vector<int> dp(301, -1); dp[0] = 0; set<int> ng_set; ng_set.insert(ng[0]); ng_set.insert(ng[1]); ng_set.insert(ng[2]); int res = dfs(n, dp, ng_set); return res <= 100 ? "YES" : "NO"; } /* int main() { int n; vector<int> ng(3); cin >> n >> ng[0] >> ng[1] >> ng[2]; cout << solve(n, ng) << endl; } */
22.022222
53
0.498486
465eb68fb7072790e82f6c3db5f23dbfb93e7340
4,148
cpp
C++
Linked list/LinkedListStruct.cpp
lovinh/Data-Structure
f5dab728b809507b8b15eb8f8450a6a85f95467e
[ "MIT" ]
null
null
null
Linked list/LinkedListStruct.cpp
lovinh/Data-Structure
f5dab728b809507b8b15eb8f8450a6a85f95467e
[ "MIT" ]
null
null
null
Linked list/LinkedListStruct.cpp
lovinh/Data-Structure
f5dab728b809507b8b15eb8f8450a6a85f95467e
[ "MIT" ]
null
null
null
#ifndef __LinkedListStruct_cpp #define __LinkedListStruct_cpp #include <iostream> template <class T> struct sNode // struct node { T data; sNode<T> *next; }; // Insert template <class T> void push_front(sNode<T> **head, const T &data) { sNode<T> *node = new sNode<T>; node->data = data; node->next = *head; *head = node; } template <class T> void push_back(sNode<T> **head, const T &data) { sNode<T> *nNode = new sNode<T>(); nNode->data = data; nNode->next = NULL; if (*head == NULL) { *head = nNode; } else { sNode<T> *it; // iterator it = *head; while (it->next != NULL) { it = it->next; } it->next = nNode; } } template <class T> void insert(sNode<T> **head, const T &data, size_t index) { if (index == 0) { push_front(head, data); return; } size_t size_list = size(*head); if (index > size_list) { push_back(head, data); return; } sNode<T> *nNode = new sNode<T>(); nNode->data = data; sNode<T> *it = *head; for (size_t i = 0; i < index - 1; i++) { it = it->next; } nNode->next = it->next; it->next = nNode; } // delete node template <class T> void pop_front(sNode<T> **head) { if (empty(*head)) { return; } size_t lSize = size(*head); if (lSize == 1) { sNode<T> *dNode = *head; (*head) = NULL; delete dNode; } else { sNode<T> *dNode = *head; (*head) = dNode->next; delete dNode; } } template <class T> void pop_back(sNode<T> **head) { if (empty(*head)) { return; } size_t lSize = size(*head); if (lSize == 1) { sNode<T> *dNode = *head; (*head) = NULL; delete dNode; } else { sNode<T> *dNode = *head; for (int i = 0; i < lSize - 2; i++) { dNode = dNode->next; } sNode<T> *dNode2 = dNode->next; dNode->next = NULL; delete dNode2; } } template <class T> void erase(sNode<T> **head, size_t index) { if (empty(*head)) { return; } size_t len = size(*head); if (index >= len) { return; } else { if (index == 0) pop_front(head); else if (index == len - 1) pop_back(head); else { sNode<T> *dNode = *head; for (int i = 0; i < index - 1; i++) { dNode = dNode->next; } sNode<T> *dNode2 = dNode->next; dNode->next = dNode2->next; delete dNode2; } } } // capacity template <class T> size_t size(sNode<T> *head) { size_t count = 0; while (head->next != NULL) { count++; head = head->next; } return count + 1; } template <class T> bool empty(sNode<T> *head) { return (head == NULL); } // Access template <class T> T &front(sNode<T> *head) { return head->data; } template <class T> T &back(sNode<T> *head) { sNode<T> *it = head; while (it->next != NULL) { it = it->next; } return it->data; } // Reverse a linked list template <class T> void Reverse(sNode<T> **head) { sNode<T> *previous, *current, *next; previous = NULL; current = *head; while (current != NULL) { next = current->next; current->next = previous; previous = current; current = next; } *head = previous; } // In list template <class T> void printList(sNode<T> *head) { if (empty(head)) { std::cout << "list is empty"; } else { sNode<T> *it = head; // iterator std::cout << "List is "; while (it != NULL) { std::cout << it->data << " "; it = it->next; } std::cout << "\t" << size(head); } std::cout << std::endl; } template <class T> void Print(sNode<T> *head) { if (head == NULL) return; std ::cout << head->data << " "; Print(head->next); } #endif
18.435556
57
0.478303
465ed2ea6fea6919b888be71acce359be427cbd8
1,684
cxx
C++
main/setup_native/source/win32/customactions/quickstarter/remove_quickstart_link.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/setup_native/source/win32/customactions/quickstarter/remove_quickstart_link.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/setup_native/source/win32/customactions/quickstarter/remove_quickstart_link.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * *************************************************************/ #ifdef _MSC_VER #pragma warning(push, 1) /* disable warnings within system headers */ #pragma warning(disable: 4917) #endif #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <shlobj.h> #include <msiquery.h> #ifdef _MSC_VER #pragma warning(pop) #endif #include <string> #include "quickstarter.hxx" extern "C" UINT __stdcall RemoveQuickstarterLink( MSIHANDLE hMSI ) { CHAR szStartupPath[MAX_PATH]; if ( SHGetSpecialFolderPathA( NULL, szStartupPath, CSIDL_STARTUP, FALSE ) ) { std::string sQuickstartLinkPath = szStartupPath; sQuickstartLinkPath += "\\"; sQuickstartLinkPath += GetQuickstarterLinkName( hMSI ); sQuickstartLinkPath += ".lnk"; DeleteFileA( sQuickstartLinkPath.c_str() ); } return ERROR_SUCCESS; }
29.54386
76
0.690024
46638a06ef05cd551a0d25bc744069d85864c7f2
2,585
cpp
C++
allocore/src/protocol/opencl/al_OpenCLProgram.cpp
donghaoren/AlloSystem
7674cc8597e470a355a5dab1dac9191c2c2e8086
[ "BSD-3-Clause" ]
null
null
null
allocore/src/protocol/opencl/al_OpenCLProgram.cpp
donghaoren/AlloSystem
7674cc8597e470a355a5dab1dac9191c2c2e8086
[ "BSD-3-Clause" ]
null
null
null
allocore/src/protocol/opencl/al_OpenCLProgram.cpp
donghaoren/AlloSystem
7674cc8597e470a355a5dab1dac9191c2c2e8086
[ "BSD-3-Clause" ]
null
null
null
#include "allocore/protocol/opencl/al_OpenCLProgram.hpp" #ifndef MIN #define MIN(a, b) (((a) < (b)) ? (a) : (b)) #endif namespace al { namespace cl { void OpenCLProgram :: create(OpenCLContext &ctx, const char *source) { destroy(); detach(); cl_int res = CL_SUCCESS; cl_program program = clCreateProgramWithSource( ctx.get_context(), 1, &source, NULL, &res ); if(opencl_error(res, "clCreateProgramWithSource error creating program")) { return; } mProgram = program; ctx.attach_resource(this); } void OpenCLProgram :: build(const OpenCLDevice &dev) { build(vector<OpenCLDevice>(1, dev)); } void OpenCLProgram :: build(const vector<OpenCLDevice> &devs) { int ndevices = devs.size(); cl_device_id devices[MAX_DEVICES]; for(int i=0; i < MIN(MAX_DEVICES, ndevices); i++) { devices[i] = devs[i].get_device(); if(!devs[i].get_available()) { char msg[256]; sprintf(msg, "OpenCL Device %s is not available", devs[i].get_name().c_str()); opencl_error(USER_OPENCL_ERROR, msg); return; } } cl_int res = clBuildProgram( mProgram, ndevices, devices, "", NULL, NULL ); if(opencl_error(res, "clBuildProgram error building program")) { /* INSTEAD OF CALLBACKS: clGetProgramBuildInfo( program, // the program object being queried device_id, // the device for which the OpenCL code was built CL_PROGRAM_BUILD_LOG, // specifies that we want the build log sizeof(buffer), // the size of the buffer buffer, // on return, holds the build log &len); // on return, the actual size in bytes of the // data returned */ return; } return; } void OpenCLProgram :: destroy() { if(mProgram) { list<OpenCLResource<OpenCLProgram> *>::iterator it = mResources.begin(); while(it != mResources.end()) { (*it)->destroy(); (*it)->detach(); it = mResources.begin(); } cl_int res = clReleaseProgram(mProgram); mProgram = 0; opencl_error(res, "clReleaseProgram error releasing program"); } } void OpenCLProgram :: attach_resource(OpenCLResource<OpenCLProgram> *resource) { resource->attach(this); mResources.push_back(resource); } void OpenCLProgram :: detach_resource(OpenCLResource<OpenCLProgram> *resource) { list<OpenCLResource<OpenCLProgram> *>::iterator it = mResources.begin(); list<OpenCLResource<OpenCLProgram> *>::iterator ite = mResources.end(); for(; it != ite; ++it) { if((*it) == resource) { mResources.erase(it); break; } } } } // cl:: } // al::
23.288288
81
0.648743
4663c2afa22114665144549d50fe2d00da904b5c
1,287
cpp
C++
app/src/main/cpp/Threads/FileStreamThread.cpp
PetrFlajsingr/SpeechRecognition
23c675c7389b9ad97b18a8ba3739dceb04f42856
[ "Apache-2.0" ]
1
2019-04-18T06:33:09.000Z
2019-04-18T06:33:09.000Z
app/src/main/cpp/Threads/FileStreamThread.cpp
PetrFlajsingr/SpeechRecognition
23c675c7389b9ad97b18a8ba3739dceb04f42856
[ "Apache-2.0" ]
null
null
null
app/src/main/cpp/Threads/FileStreamThread.cpp
PetrFlajsingr/SpeechRecognition
23c675c7389b9ad97b18a8ba3739dceb04f42856
[ "Apache-2.0" ]
null
null
null
// // Created by Petr Flajsingr on 18/04/2018. // #include "FileStreamThread.h" #include <constants.h> #include <android/log.h> SpeechRecognition::Threads::FileStreamThread::FileStreamThread(std::ifstream& fileStream) : thread(&FileStreamThread::threadFileStream, this) { this->fileStream = &fileStream; } void SpeechRecognition::Threads::FileStreamThread::threadFileStream() { std::unique_lock<std::mutex> lock(startMutex); conditionVariable.wait(lock); short* data = wavReader.wavToPcm(*fileStream); Q_AudioData* audioData; if(data == NULL) { audioData = new Q_AudioData{TERMINATE, NULL}; melQueue->enqueue(audioData); return; } int framesSent = 0; for(int i = 0; i < wavReader.getDataSize(); i += SUBSAMPLED_OVERLAP_LENGTH){ short* dataToSend = new short[SUBSAMPLED_OVERLAP_LENGTH]; std::copy(data + i, data + i + SUBSAMPLED_OVERLAP_LENGTH, dataToSend); audioData = new Q_AudioData{SEQUENCE_DATA, dataToSend}; melQueue->enqueue(audioData); framesSent++; } audioData = new Q_AudioData{TERMINATE, NULL}; melQueue->enqueue(audioData); } void SpeechRecognition::Threads::FileStreamThread::start() { conditionVariable.notify_all(); }
26.8125
89
0.677545
46642a3737950cf666a252806f317be9196ca388
1,864
cpp
C++
c++/Data Structures/RMQ.cpp
WearyJunger/notebook
8fc7bfdcacffd63b131b5ed0c92365f682ba313f
[ "MIT" ]
null
null
null
c++/Data Structures/RMQ.cpp
WearyJunger/notebook
8fc7bfdcacffd63b131b5ed0c92365f682ba313f
[ "MIT" ]
null
null
null
c++/Data Structures/RMQ.cpp
WearyJunger/notebook
8fc7bfdcacffd63b131b5ed0c92365f682ba313f
[ "MIT" ]
1
2018-10-08T21:01:59.000Z
2018-10-08T21:01:59.000Z
Range minimum query. Recibe como parametro en el constructor un array de valores. Las consultas se realizan con el método rmq(indice_inicio, indice_final) y pueden actualizarse los valores con update_point(indice, nuevo_valor) class SegmentTree { private: vector<int> st, A; int n; int left (int p) { return p << 1; } int right(int p) { return (p << 1) + 1; } void build(int p, int L, int R) { if (L == R) st[p] = L; else { build(left(p) , L, (L + R) / 2); build(right(p), (L + R) / 2 + 1, R); int p1 = st[left(p)], p2 = st[right(p)]; st[p] = (A[p1] <= A[p2]) ? p1 : p2; } } int rmq(int p, int L, int R, int i, int j) { if (i > R || j < L) return -1; if (L >= i && R <= j) return st[p]; int p1 = rmq(left(p) , L, (L+R) / 2, i, j); int p2 = rmq(right(p), (L+R) / 2 + 1, R, i, j); if (p1 == -1) return p2; if (p2 == -1) return p1; return (A[p1] <= A[p2]) ? p1 : p2; } int update_point(int p, int L, int R, int idx, int new_value) { int i = idx, j = idx; if (i > R || j < L) return st[p]; if (L == i && R == j) { A[i] = new_value; return st[p] = L; } int p1, p2; p1 = update_point(left(p) , L, (L + R) / 2, idx, new_value); p2 = update_point(right(p), (L + R) / 2 + 1, R, idx, new_value); return st[p] = (A[p1] <= A[p2]) ? p1 : p2; } public: SegmentTree(const vector<int> &_A) { A = _A; n = (int)A.size(); st.assign(4 * n, 0); build(1, 0, n - 1); } int rmq(int i, int j) { return rmq(1, 0, n - 1, i, j); } int update_point(int idx, int new_value) { return update_point(1, 0, n - 1, idx, new_value); } }; int main() { int arr[] = { 18, 17, 13, 19, 15, 11, 20 }; vector<int> A(arr, arr + 7); SegmentTree st(A); return 0; }
28.242424
226
0.495708
466cc79151dff2e1c1bf8abf8acbd3a5d6c861c0
630
cpp
C++
225-Days Coding Problem/Day-002.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
225-Days Coding Problem/Day-002.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
225-Days Coding Problem/Day-002.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { const size_t n= nums.size(); vector<int>ans(n,1); int answer =1; for(size_t i=0;i<n; ++i){ if(i==0){ ans[i] = nums[i]; }else{ ans[i] = nums[i]*ans[i-1]; } } int temp; for(int i=n-1;i>=0;--i){ if(i!=0){ temp = nums[i]; nums[i] = ans[i-1]*answer; answer*=temp; }else{ nums[i] = answer; } } return nums; } };
23.333333
54
0.365079
466e60dd8dd600cfbe3235959f31c170b9a87f0d
3,347
cpp
C++
SelPh/metriclearning.cpp
yuki-koyama/selph
9f3d1a868333843c6884adac41e344684efa2366
[ "MIT" ]
3
2019-09-13T07:47:39.000Z
2021-03-10T20:31:32.000Z
SelPh/metriclearning.cpp
yuki-koyama/selph
9f3d1a868333843c6884adac41e344684efa2366
[ "MIT" ]
7
2018-04-06T10:06:56.000Z
2019-08-04T05:38:12.000Z
SelPh/metriclearning.cpp
yuki-koyama/selph
9f3d1a868333843c6884adac41e344684efa2366
[ "MIT" ]
null
null
null
// #define TIME #include "metriclearning.h" #ifdef TIME #include <chrono> #endif #include <nlopt.hpp> #include "core.h" #include "eigenutility.h" using namespace Eigen; using namespace std; namespace { Core& core = Core::getInstance(); } namespace MetricLearning { struct Arg { Arg(const Core::Distance* D_images, const MatrixXd* D_params, unsigned nData) : D_images(D_images), D_params(D_params), nData(nData) {} const Core::Distance* D_images; const MatrixXd* D_params; const unsigned nData; }; /////////////////////////////////////////////////////////////////////////////////////////////// // \grad(C) = \sum_{i, j} \grad { \| D_images_{i, j}^T \alpha - D_params_{i, j} \|^2 } // = - 2 \sum_{i, j} D_images_{i, j} ( D_params_{i, j} - D_images_{i, j}^T \alpha ) /////////////////////////////////////////////////////////////////////////////////////////////// Eigen::VectorXd computeGradient(const VectorXd& alpha, const Arg* data, const double weight) { VectorXd grad = VectorXd::Zero(alpha.rows()); for (unsigned i = 0; i < data->nData; ++ i) for (unsigned j = i + 1; j < data->nData; ++ j) { const VectorXd D_ij = EigenUtility::std2eigen((*data->D_images)[i][j]); grad += D_ij * (weight * data->D_params->coeff(i, j) - D_ij.transpose() * alpha); } grad = - 2.0 * grad; return grad; } /////////////////////////////////////////////////////////////////////////////////////////////// // C = \sum_{i, j} { \| D_images_{i, j}^T \alpha - D_params_{i, j} \|^2 } /////////////////////////////////////////////////////////////////////////////////////////////// double objectiveFunction(const vector<double> &x, vector<double>& grad, void* argData) { const Arg* data = static_cast<const Arg*>(argData); const VectorXd alpha = EigenUtility::std2eigen(x); const double weight = 5.0; // Compute the function value double cost = 0.0; for (unsigned i = 0; i < data->nData; ++ i) for (unsigned j = i + 1; j < data->nData; ++ j) { const double d = Core::computeDistance(alpha, *(data->D_images), i, j) - weight * data->D_params->coeff(i, j); cost += d * d; } // Compute the gradient grad = EigenUtility::eigen2std(computeGradient(alpha, data, weight)); return cost; } VectorXd computeMetricLearning(const vector<vector<vector<double>>> &D_images, const MatrixXd &D_params, const VectorXd &seed, unsigned nData) { const unsigned dim = seed.rows(); vector<double> x = EigenUtility::eigen2std(seed); double value; const Arg argData(&D_images, &D_params, nData); // Compute local optimization nlopt::opt localOpt(nlopt::LD_LBFGS, dim); localOpt.set_min_objective(objectiveFunction, (void*) &argData); localOpt.set_lower_bounds(0.0); try { #ifdef TIME const auto t1 = chrono::system_clock::now(); #endif localOpt.optimize(x, value); #ifdef TIME const auto t2 = chrono::system_clock::now(); cout << "Metric learning: " << chrono::duration_cast<chrono::milliseconds>(t2 - t1).count() << " [ms]" << endl; #endif } catch (const nlopt::roundoff_limited e) { cerr << e.what() << endl; } catch (const std::runtime_error e) { cerr << e.what() << endl; } return EigenUtility::std2eigen(x); } }
31.575472
142
0.553929
466f649cd8398e7deb5c21a4cf7fc57bbcff1ba5
1,025
cpp
C++
Lab 4/Lab 4/Lab 4.cpp
shonwr/c-assignments-projects
fab40807ba2720cec577aa9689361746e33ef678
[ "Apache-2.0" ]
null
null
null
Lab 4/Lab 4/Lab 4.cpp
shonwr/c-assignments-projects
fab40807ba2720cec577aa9689361746e33ef678
[ "Apache-2.0" ]
null
null
null
Lab 4/Lab 4/Lab 4.cpp
shonwr/c-assignments-projects
fab40807ba2720cec577aa9689361746e33ef678
[ "Apache-2.0" ]
null
null
null
// Lab 4.cpp : main project file. #include "stdafx.h" #include <iostream> using namespace System; using namespace std; char fName[50]; char lName[50]; char space[10] = " "; int main() { system("color f0"); printf("This program: \n\t(1)Prints an entered first and last name \n\t(2)Prints the number of letters in each name on the following line.\n\n"); printf("Press enter to begin: "); scanf("%c"); printf("\n\nEnter first name: "); scanf("%s",fName); printf("\nEnter last name: "); scanf("%s",lName); //Aligned @ end printf("\n\nYou enterered: %s %s \n",fName,lName); int fLength = (strlen(fName)); int lLength = (strlen(lName)); int fSpaceEnd = (strlen(fName)-2); int lSpaceEnd = (strlen(lName)-1); printf(" %*s %d", "%*s\n\n",fSpaceEnd,space,fLength,lSpaceEnd,space,lLength); //Aligned @ beginning printf("\n\nYou enterered: %s %s \n",fName,lName); int fSpace = (strlen(fName)-2); printf(" %d %-*s %d\n\n",fLength,fSpace,space,lLength); system("pause"); return 0; }
26.973684
146
0.636098
4671ec7a3b1a40d24223e8bfc1ef09540e1dc440
1,784
cpp
C++
DivisionEngine/DivisionTest/ClockTest.cpp
martheveldhuis/DivisionEngine
8f7ba1c355ee010c005df207e08d51673f3cdf8d
[ "MIT" ]
1
2017-11-29T19:19:43.000Z
2017-11-29T19:19:43.000Z
DivisionEngine/DivisionTest/ClockTest.cpp
martheveldhuis/DivisionEngine
8f7ba1c355ee010c005df207e08d51673f3cdf8d
[ "MIT" ]
2
2018-01-16T12:11:24.000Z
2018-01-16T15:21:46.000Z
DivisionEngine/DivisionTest/ClockTest.cpp
martheveldhuis/DivisionEngine
8f7ba1c355ee010c005df207e08d51673f3cdf8d
[ "MIT" ]
1
2018-01-28T13:10:49.000Z
2018-01-28T13:10:49.000Z
#include "CppUnitTest.h" #include "Clock.h" #include <chrono> #include <thread> #include <iostream> using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace Division; namespace DivisionTest { TEST_CLASS(ClockTest) { public: TEST_METHOD(testClockStart) { Clock clock; clock.start(); Assert::IsTrue(clock.isRunning()); } TEST_METHOD(testClockPoll) { Clock clock; clock.start(); // Sleep for 1000 ms. std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // Retrieve the time that has past. int timePast = clock.poll(); // Check if the time is between a certain timespan. // Usually the past time will be 1001 ms. For cpu-threading // priority delay occasions we will allow for a 5ms delay. int isBetween = 1000 <= timePast && timePast < 1050; Assert::IsTrue(isBetween); } TEST_METHOD(testClockStop) { Clock clock; clock.start(); clock.stop(); Assert::IsFalse(clock.isRunning()); } TEST_METHOD(testClockRuntime) { Clock clock; clock.start(); // Sleep for 500 ms. std::this_thread::sleep_for(std::chrono::milliseconds(500)); clock.stop(); std::this_thread::sleep_for(std::chrono::milliseconds(500)); clock.start(); // Sleep for 500 ms. std::this_thread::sleep_for(std::chrono::milliseconds(500)); clock.stop(); int timePast = clock.getRuntime(); int isBetween = 1000 <= timePast && timePast < 1050; Assert::IsTrue(isBetween); } TEST_METHOD(testClockReset) { Clock clock; clock.start(); // Sleep for 500 ms. std::this_thread::sleep_for(std::chrono::milliseconds(500)); clock.stop(); clock.reset(); int timePast = clock.getRuntime(); Assert::AreEqual(0, timePast); } }; }
16.830189
64
0.663117
4672121dbfdbb543cd8767a085f1823f8735a986
7,810
cpp
C++
src/mame/video/namco_c169roz.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/mame/video/namco_c169roz.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/mame/video/namco_c169roz.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:David Haywood, Phil Stroffolino /****************************************************************************** Namco C169 (ROZ - Rotate and Zoom) Advanced rotate-zoom chip manages two layers. Each layer uses a designated subset of a master 256x256 tile tilemap (4096x4096 pixels). Each layer has configurable color and tile banking. ROZ attributes may be specified independently for each scanline. Used by: Namco NB2 - The Outfoxies, Mach Breakers Namco System 2 - Metal Hawk, Lucky and Wild Namco System FL - Final Lap R, Speed Racer ******************************************************************************/ #include "emu.h" #include "namco_c169roz.h" static const gfx_layout layout = { 16,16, RGN_FRAC(1,1), 8, { STEP8(0,1) }, { STEP16(0,8) }, { STEP16(0,8*16) }, 16*128 }; GFXDECODE_START( namco_c169roz_device::gfxinfo ) GFXDECODE_DEVICE( DEVICE_SELF, 0, layout, 0, 32 ) GFXDECODE_END DEFINE_DEVICE_TYPE(NAMCO_C169ROZ, namco_c169roz_device, "namco_c169roz", "Namco C169 (ROZ)") namco_c169roz_device::namco_c169roz_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock) : device_t(mconfig, NAMCO_C169ROZ, tag, owner, clock), device_gfx_interface(mconfig, *this, gfxinfo), m_color_base(0), m_is_namcofl(false), m_mask(*this, "mask") { } void namco_c169roz_device::device_start() { m_videoram.resize(m_ramsize); std::fill(std::begin(m_videoram), std::end(m_videoram), 0x0000); m_tilemap[0] = &machine().tilemap().create(*this, tilemap_get_info_delegate(*this, FUNC(namco_c169roz_device::get_info<0>)), tilemap_mapper_delegate(*this, FUNC(namco_c169roz_device::mapper)), 16, 16, 256, 256); m_tilemap[1] = &machine().tilemap().create(*this, tilemap_get_info_delegate(*this, FUNC(namco_c169roz_device::get_info<1>)), tilemap_mapper_delegate(*this, FUNC(namco_c169roz_device::mapper)), 16, 16, 256, 256); save_item(NAME(m_control)); save_item(NAME(m_videoram)); } // for bank changes void namco_c169roz_device::mark_all_dirty() { for (auto & elem : m_tilemap) elem->mark_all_dirty(); } /** * Graphics ROM addressing varies across games. * (mostly scrambling, which could be handled in the game inits, but NB1 also has banking) */ template<int Which> TILE_GET_INFO_MEMBER(namco_c169roz_device::get_info) { int tile = 0, mask = 0; m_c169_cb(m_videoram[tile_index&(m_ramsize-1)] & 0x3fff, &tile, &mask, Which); // need to mask with ramsize because the nb1/fl games have twice as much RAM, presumably the tilemaps mirror in ns2? tileinfo.mask_data = m_mask + 32 * mask; tileinfo.set(0, tile, 0/*color*/, 0/*flag*/); } TILEMAP_MAPPER_MEMBER( namco_c169roz_device::mapper ) { return ((col & 0x80) << 8) | ((row & 0xff) << 7) | (col & 0x7f); } void namco_c169roz_device::unpack_params(const uint16_t *source, roz_parameters &params) { const int xoffset = 36, yoffset = 3; /** * x-------.-------- disable layer * ----x---.-------- wrap? * ------xx.-------- size * --------.xxxx---- priority * --------.----xxxx color */ uint16_t temp = source[1]; params.wrap = BIT(~temp, 11); params.size = 512 << ((temp & 0x0300) >> 8); if (m_is_namcofl) params.color = (temp & 0x0007) * 256; else params.color = (temp & 0x000f) * 256; params.priority = (temp & 0x00f0) >> 4; temp = source[2]; params.left = (temp & 0x7000) >> 3; if (temp & 0x8000) temp |= 0xf000; else temp &= 0x0fff; // sign extend params.incxx = int16_t(temp); temp = source[3]; params.top = (temp&0x7000)>>3; if (temp & 0x8000) temp |= 0xf000; else temp &= 0x0fff; // sign extend params.incxy = int16_t(temp); temp = source[4]; if (temp & 0x8000) temp |= 0xf000; else temp &= 0x0fff; // sign extend params.incyx = int16_t(temp); temp = source[5]; if (temp & 0x8000) temp |= 0xf000; else temp &= 0x0fff; // sign extend params.incyy = int16_t(temp); params.startx = int16_t(source[6]); params.starty = int16_t(source[7]); params.startx <<= 4; params.starty <<= 4; params.startx += xoffset * params.incxx + yoffset * params.incyx; params.starty += xoffset * params.incxy + yoffset * params.incyy; // normalize params.startx <<= 8; params.starty <<= 8; params.incxx <<= 8; params.incxy <<= 8; params.incyx <<= 8; params.incyy <<= 8; } void namco_c169roz_device::draw_helper(screen_device &screen, bitmap_ind16 &bitmap, tilemap_t &tmap, const rectangle &clip, const roz_parameters &params) { if (!m_is_namcofl) // if (m_gametype != NAMCOFL_FINAL_LAP_R) // Fix speedrcr some title animations, but broke at road scene { uint32_t size_mask = params.size - 1; bitmap_ind16 &srcbitmap = tmap.pixmap(); bitmap_ind8 &flagsbitmap = tmap.flagsmap(); uint32_t startx = params.startx + clip.min_x * params.incxx + clip.min_y * params.incyx; uint32_t starty = params.starty + clip.min_x * params.incxy + clip.min_y * params.incyy; int sx = clip.min_x; int sy = clip.min_y; while (sy <= clip.max_y) { int x = sx; uint32_t cx = startx; uint32_t cy = starty; uint16_t *dest = &bitmap.pix(sy, sx); while (x <= clip.max_x) { // TODO : Wraparound disable isn't implemented uint32_t xpos = (((cx >> 16) & size_mask) + params.left) & 0xfff; uint32_t ypos = (((cy >> 16) & size_mask) + params.top) & 0xfff; if (flagsbitmap.pix(ypos, xpos) & TILEMAP_PIXEL_LAYER0) *dest = srcbitmap.pix(ypos, xpos) + params.color + m_color_base; cx += params.incxx; cy += params.incxy; x++; dest++; } startx += params.incyx; starty += params.incyy; sy++; } } else { tmap.set_palette_offset(m_color_base + params.color); tmap.draw_roz( screen, bitmap, clip, params.startx, params.starty, params.incxx, params.incxy, params.incyx, params.incyy, params.wrap,0,0); // wrap, flags, pri } } void namco_c169roz_device::draw_scanline(screen_device &screen, bitmap_ind16 &bitmap, int line, int which, int pri, const rectangle &cliprect) { if (line >= cliprect.min_y && line <= cliprect.max_y) { int row = line / 8; int offs = row * 0x100 + (line & 7) * 0x10 + 0xe080; uint16_t *source = &m_videoram[offs / 2]; // if enabled if ((source[1] & 0x8000) == 0) { roz_parameters params; unpack_params(source, params); // check priority if (pri == params.priority) { rectangle clip(0, bitmap.width() - 1, line, line); clip &= cliprect; draw_helper(screen, bitmap, *m_tilemap[which], clip, params); } } } } void namco_c169roz_device::draw(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect, int pri) { int special = (m_is_namcofl) ? 0 : 1; int mode = m_control[0]; // 0x8000 or 0x1000 for (int which = 1; which >= 0; which--) { const uint16_t *source = &m_control[which * 8]; uint16_t attrs = source[1]; // if enabled if ((attrs & 0x8000) == 0) { // second ROZ layer is configured to use per-scanline registers if (which == special && mode == 0x8000) { for (int line = cliprect.min_y; line <= cliprect.max_y; line++) draw_scanline(screen, bitmap, line, which, pri, cliprect); } else { roz_parameters params; unpack_params(source, params); if (params.priority == pri) draw_helper(screen, bitmap, *m_tilemap[which], cliprect, params); } } } } uint16_t namco_c169roz_device::control_r(offs_t offset) { return m_control[offset]; } void namco_c169roz_device::control_w(offs_t offset, uint16_t data, uint16_t mem_mask) { COMBINE_DATA(&m_control[offset]); } uint16_t namco_c169roz_device::videoram_r(offs_t offset) { return m_videoram[offset]; } void namco_c169roz_device::videoram_w(offs_t offset, uint16_t data, uint16_t mem_mask) { COMBINE_DATA(&m_videoram[offset]); for (auto & elem : m_tilemap) elem->mark_tile_dirty(offset); }
28.194946
196
0.66402
4674ea079e6d2cdc296410871e1316c79c9577e3
5,471
cpp
C++
triangles.cpp
bradgrantham/raycast
a103801f473d55e99fc25db28c4b0587a1271093
[ "BSD-2-Clause" ]
null
null
null
triangles.cpp
bradgrantham/raycast
a103801f473d55e99fc25db28c4b0587a1271093
[ "BSD-2-Clause" ]
null
null
null
triangles.cpp
bradgrantham/raycast
a103801f473d55e99fc25db28c4b0587a1271093
[ "BSD-2-Clause" ]
null
null
null
#include <algorithm> #include <cmath> // Okay, it's ugly, I get it. // // I didn't use classes or a vector library. I use loops to // 3 everywhere for vector operations, and I even write out dot // products. My intent was to try to build a minimal triangle // raycaster that I could convert simply to BASIC or FORTH or other // simple languages without having to downconvert C++ concepts. // // I'm already thinking function calls are problematic, as well as // the arrays with 3 dimensions. I might have to inline the functions // and use goto instead of early returns. // // So it's probably still not ugly enough. const float F = 1000000; const int W = 256; const int H = 256; const int M = 400000; float tv[M][3][3]; // vertices float tp[M][4]; // planes float te[M][3][4]; // edge half-space planes float tb[M][4]; // xmin, xmax, ymin, ymax int tc = 0; float L[3] = {.577, .577, .577}; void prepare(int k) { // Get edge vectors float e[3][3]; for(int i = 0; i < 3; i++) e[0][i] = tv[k][1][i] - tv[k][0][i]; for(int i = 0; i < 3; i++) e[1][i] = tv[k][2][i] - tv[k][1][i]; for(int i = 0; i < 3; i++) e[2][i] = tv[k][0][i] - tv[k][2][i]; // Cross product e0 and e1 to get normal tp[k][0] = e[0][1] * e[1][2] - e[0][2] * e[1][1]; tp[k][1] = e[0][2] * e[1][0] - e[0][0] * e[1][2]; tp[k][2] = e[0][0] * e[1][1] - e[0][1] * e[1][0]; // Normalize normal float d = sqrt(tp[k][0] * tp[k][0] + tp[k][1] * tp[k][1] + tp[k][2] * tp[k][2]); for(int i = 0; i < 3; i++) tp[k][i] /= d; // Use dot product of normal and v0 to get fourth plane equation element tp[k][3] = tp[k][0] * tv[k][0][0] + tp[k][1] * tv[k][0][1] + tp[k][2] * tv[k][0][2]; // Get half-spaces representing each edge by making vector // perpendicular to edge and dot that with opposite vertex to get // plane equation for(int j = 0; j < 3; j++) { te[k][j][0] = tp[k][1] * e[j][2] - tp[k][2] * e[j][1]; te[k][j][1] = tp[k][2] * e[j][0] - tp[k][0] * e[j][2]; te[k][j][2] = tp[k][0] * e[j][1] - tp[k][1] * e[j][0]; te[k][j][3] = te[k][j][0] * tv[k][j][0] + te[k][j][1] * tv[k][j][1] + te[k][j][2] * tv[k][j][2]; } tb[k][0] = 2; tb[k][1] = -2; tb[k][2] = 2; tb[k][3] = -2; for(int j = 0; j < 3; j++) { tb[k][0] = std::min(tb[k][0], tv[k][j][0] / -tv[k][j][2]); tb[k][1] = std::max(tb[k][1], tv[k][j][0] / -tv[k][j][2]); tb[k][2] = std::min(tb[k][2], tv[k][j][1] / -tv[k][j][2]); tb[k][3] = std::max(tb[k][3], tv[k][j][1] / -tv[k][j][2]); } } float intersect(int k, float r[3]) { int i; // find distance from r origin (0,0,0) to plane in units of plane normal float factor = r[0] * tp[k][0] + r[1] * tp[k][1] + r[2] * tp[k][2]; // if coincident, fail if(factor == 0.0) return F; // find distance to plane in world units float t = tp[k][3] / factor; // if intersection is behind the ray, fail if(t < 0) return F; // calculate the point in the plane float p[3]; for(int i = 0; i < 3; i++) p[i] = r[i] * t; for(i = 0; i < 3; i++) { // calculate the distance from each edge i to the point float edge = te[k][i][0] * p[0] + te[k][i][1] * p[1] + te[k][i][2] * p[2]; // if the distance is greater than the distance to the opposite vertex, fail if(edge < te[k][i][3]) return F; } // succeed by returning the distance return t; } int main() { float v[3][3]; // Read triangles. while(scanf("%f %f %f %f %f %f %f %f %f", &v[0][0], &v[0][1], &v[0][2], &v[1][0], &v[1][1], &v[1][2], &v[2][0], &v[2][1], &v[2][2]) == 9) { for(int j = 0; j < 3; j++) for(int i = 0; i < 3; i++) { tv[tc][j][i] = v[j][i]; } prepare(tc); tc++; } printf("P2 %d %d 255\n", W, H); float pdx = .5 / (W / 2.0); float pdy = .5 / (H / 2.0); for(int py = 0; py < H; py++) for(int px = 0; px < W; px++) { // Make the ray float r[3]; r[0] = -.5 + (px + .5) * pdx; r[1] = - (-.5 + (py + .5) * pdy); r[2] = -1; // find the closest triangle int tri = -1; float t = F; for(int k = 0; k < tc; k++) { if(r[0] < tb[k][0]) continue; if(r[0] > tb[k][1]) continue; if(r[1] < tb[k][2]) continue; if(r[1] > tb[k][3]) continue; float t2 = intersect(k, r); if(t2 < t) { t = t2; tri = k; } } // shade the intersection float shade; if(tri == -1) { shade = .2; } else { float facing = r[0] * tp[tri][0] + r[1] * tp[tri][1] + r[2] * tp[tri][2]; float lighting = L[0] * tp[tri][0] + L[1] * tp[tri][1] + L[2] * tp[tri][2]; if(facing > 0) lighting = -lighting; shade = std::max(0.1f, lighting); } printf("%d ", (int)(shade * 255)); } }
26.687805
91
0.425882
4679a7b3404ed6d2823d710f72a2e305de31da3b
755
cpp
C++
insts/std/PVOC/PVFilterTest.cpp
jwmatthys/RTcmix
c9ba0c5bee2cd5e091c81333cf819d267008635b
[ "Apache-2.0" ]
40
2015-01-14T20:52:42.000Z
2022-03-09T00:50:45.000Z
insts/std/PVOC/PVFilterTest.cpp
jwmatthys/RTcmix
c9ba0c5bee2cd5e091c81333cf819d267008635b
[ "Apache-2.0" ]
20
2015-01-26T19:02:59.000Z
2022-01-30T18:00:39.000Z
insts/std/PVOC/PVFilterTest.cpp
jwmatthys/RTcmix
c9ba0c5bee2cd5e091c81333cf819d267008635b
[ "Apache-2.0" ]
14
2015-01-14T20:52:43.000Z
2021-09-24T02:24:32.000Z
// PVFilterTest.cpp -- test class for pvoc data filters #include "PVFilterTest.h" #include <stdio.h> #include <ugens.h> PVFilter * PVFilterTest::create() { return new PVFilterTest; } PVFilterTest::PVFilterTest() { } PVFilterTest::~PVFilterTest() { } int PVFilterTest::run(float *pvdata, int nvals) { for (int n = 0; n < nvals; ++n) { const int ampIdx = n * 2; const int frqIdx = ampIdx + 1; pvdata[frqIdx] *= val2; pvdata[frqIdx] += val1; } return 0; } int PVFilterTest::init(double *pp, int nargs) { val1 = pp[0]; val2 = pp[1]; return 1; } // This function is called by the PVOC setup() routine for each DSO extern "C" { int registerLib(int (*register_fun)(FilterCreateFunction)) { return register_fun(&PVFilterTest::create); } }
15.729167
67
0.675497
467a5110cc99dab334a99239e0b6d2733962ca4c
21
cc
C++
src/main/c++/novemberizing/io/buffer.cc
iticworld/reactive-lib
9ab761376776e759390fa417d50921ec6e8a898a
[ "Apache-2.0" ]
1
2020-10-10T11:57:15.000Z
2020-10-10T11:57:15.000Z
src/main/c++/novemberizing/io/buffer.cc
iticworld/reactive-lib
9ab761376776e759390fa417d50921ec6e8a898a
[ "Apache-2.0" ]
null
null
null
src/main/c++/novemberizing/io/buffer.cc
iticworld/reactive-lib
9ab761376776e759390fa417d50921ec6e8a898a
[ "Apache-2.0" ]
null
null
null
#include "buffer.hh"
10.5
20
0.714286
467adea4e2f3af676246adae4073c1f4877d720e
75
hxx
C++
src/drawable.hxx
luutifa/openglpractice
1158453f0b124910ad8c4101f226dd55b5ce4262
[ "MIT" ]
null
null
null
src/drawable.hxx
luutifa/openglpractice
1158453f0b124910ad8c4101f226dd55b5ce4262
[ "MIT" ]
null
null
null
src/drawable.hxx
luutifa/openglpractice
1158453f0b124910ad8c4101f226dd55b5ce4262
[ "MIT" ]
null
null
null
#pragma once class Drawable { public: virtual void draw() const; };
10.714286
30
0.653333
46811eb70d97fa59ee2378376fe31f71a8204a9b
1,327
cc
C++
mindspore/lite/tools/converter/adapter/acl/mapper/fused_batchnorm_mapper.cc
PowerOlive/mindspore
bda20724a94113cedd12c3ed9083141012da1f15
[ "Apache-2.0" ]
3,200
2020-02-17T12:45:41.000Z
2022-03-31T20:21:16.000Z
mindspore/lite/tools/converter/adapter/acl/mapper/fused_batchnorm_mapper.cc
zimo-geek/mindspore
665ec683d4af85c71b2a1f0d6829356f2bc0e1ff
[ "Apache-2.0" ]
176
2020-02-12T02:52:11.000Z
2022-03-28T22:15:55.000Z
mindspore/lite/tools/converter/adapter/acl/mapper/fused_batchnorm_mapper.cc
zimo-geek/mindspore
665ec683d4af85c71b2a1f0d6829356f2bc0e1ff
[ "Apache-2.0" ]
621
2020-03-09T01:31:41.000Z
2022-03-30T03:43:19.000Z
/** * Copyright 2021 Huawei Technologies Co., Ltd * * 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 "tools/converter/adapter/acl/mapper/fused_batchnorm_mapper.h" #include "tools/converter/adapter/acl/mapper/primitive_mapper_register.h" #include "ops/op_utils.h" namespace mindspore { namespace lite { STATUS FusedBatchNormMapper::Mapper(const CNodePtr &cnode) { ValueNodePtr value_node = nullptr; PrimitivePtr src_prim = nullptr; if (GetValueNodeAndPrimFromCnode(cnode, &value_node, &src_prim) != lite::RET_OK) { MS_LOG(ERROR) << "Get primitive from cnode failed."; return lite::RET_ERROR; } src_prim->AddAttr(ops::kIsTraining, MakeValue(false)); return lite::RET_OK; } REGISTER_PRIMITIVE_MAPPER(kNameFusedBatchNorm, FusedBatchNormMapper) } // namespace lite } // namespace mindspore
35.864865
84
0.757347
46816ff6a443ba8ba63c8eefac6401da4f99b69f
2,338
cxx
C++
include/rrwindows/console/console_virtual_terminal_sequences.cxx
afoolsbag/rrCnCxx
1e673bd4edac43d8406a0c726138cba194d17f48
[ "Unlicense" ]
2
2019-03-20T01:14:10.000Z
2021-12-08T15:39:32.000Z
include/rrwindows/console/console_virtual_terminal_sequences.cxx
afoolsbag/rrCnCxx
1e673bd4edac43d8406a0c726138cba194d17f48
[ "Unlicense" ]
null
null
null
include/rrwindows/console/console_virtual_terminal_sequences.cxx
afoolsbag/rrCnCxx
1e673bd4edac43d8406a0c726138cba194d17f48
[ "Unlicense" ]
null
null
null
/// \copyright Unlicense #include "rrwindows/console/console_virtual_terminal_sequences.hxx" #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include "rrwindows/debug/error_handling.hxx" using namespace std; namespace rrwindows { RRWINDOWS_API void RRWINDOWS_CALL enable_virtual_terminal_mode() { DWORD dwMode; CONST HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); if (hStdOut == INVALID_HANDLE_VALUE) throw system_error_exception("GetStdHandle failed", GetLastError()); if (!GetConsoleMode(hStdOut, &dwMode)) throw system_error_exception("GetConsoleMode failed", GetLastError()); dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; if (!SetConsoleMode(hStdOut, dwMode)) throw system_error_exception("SetConsoleMode failed", GetLastError()); const auto hStdErr = GetStdHandle(STD_ERROR_HANDLE); if (hStdErr == INVALID_HANDLE_VALUE) throw system_error_exception("GetStdHandle failed", GetLastError()); if (!GetConsoleMode(hStdErr, &dwMode)) throw system_error_exception("GetConsoleMode failed", GetLastError()); dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; if (!SetConsoleMode(hStdErr, dwMode)) throw system_error_exception("SetConsoleMode failed", GetLastError()); } RRWINDOWS_API void RRWINDOWS_CALL disable_virtual_terminal_mode() { DWORD dwMode; const auto hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); if (hStdOut == INVALID_HANDLE_VALUE) throw system_error_exception("GetStdHandle failed", GetLastError()); if (!GetConsoleMode(hStdOut, &dwMode)) throw system_error_exception("GetConsoleMode failed", GetLastError()); dwMode &= ~static_cast<DWORD>(ENABLE_VIRTUAL_TERMINAL_PROCESSING); if (!SetConsoleMode(hStdOut, dwMode)) throw system_error_exception("SetConsoleMode failed", GetLastError()); const auto hStdErr = GetStdHandle(STD_ERROR_HANDLE); if (hStdErr == INVALID_HANDLE_VALUE) throw system_error_exception("GetStdHandle failed", GetLastError()); if (!GetConsoleMode(hStdErr, &dwMode)) throw system_error_exception("GetConsoleMode failed", GetLastError()); dwMode &= ~static_cast<DWORD>(ENABLE_VIRTUAL_TERMINAL_PROCESSING); if (!SetConsoleMode(hStdErr, dwMode)) throw system_error_exception("SetConsoleMode failed", GetLastError()); } }
38.327869
78
0.749358
46823dbdade1cbfdbfe418a0c45b44216ff606cf
14,456
cpp
C++
push1st-server/core/lua/clua.cpp
navek-soft/push1st
6d0638e31031dcf55442382df0e92ac67d95801b
[ "Apache-2.0" ]
16
2021-11-02T07:29:18.000Z
2021-12-23T13:28:05.000Z
push1st-server/core/lua/clua.cpp
navek-soft/push1st
6d0638e31031dcf55442382df0e92ac67d95801b
[ "Apache-2.0" ]
null
null
null
push1st-server/core/lua/clua.cpp
navek-soft/push1st
6d0638e31031dcf55442382df0e92ac67d95801b
[ "Apache-2.0" ]
null
null
null
#include "clua.h" #include <unordered_map> #include <set> #include <deque> #include <functional> #include <ctime> #define l L.get() void* clua::engine::getModule(clua::lua_t L, const std::string_view& modName, const std::string_view& modNamespace) { if (lua_getglobal(L, modNamespace.data()); lua_istable(L, -1)) { if (lua_getfield(L, -1, modName.data()); lua_istable(L, -1)) { lua_getfield(L, -1, "__self"); if (lua_islightuserdata(L, -1)) { return (void*)lua_touserdata(L, -1); } } } return nullptr; } ssize_t clua::engine::luaRegisterModule(lua_t L, std::initializer_list<std::pair<std::string_view, lua_CFunction>>& methods, void* modClassSelf, const std::string_view& modName, const std::string_view& modNamespace) { if (!modNamespace.empty()) { lua_getglobal(L, modNamespace.data()); if (/*auto nfn = lua_gettop(L); */lua_isnil(L, -1)) { lua_newtable(L); //lua_pushstring(L, modNamespace.c_str()); //lua_setfield(L, -2, "__namespace"); lua_setglobal(L, modNamespace.data()); } if (lua_getglobal(L, modNamespace.data()); lua_istable(L, -1)) { lua_pushstring(L, modName.data()); { lua_newtable(L); lua_pushlightuserdata(L, modClassSelf); lua_setfield(L, -2, "__self"); for (auto&& [mn, mfn] : methods) { lua_pushcfunction(L, mfn); lua_setfield(L, -2, mn.data()); } lua_settable(L, -3); } } } else { lua_newtable(L); lua_pushlightuserdata(L, modClassSelf); lua_setfield(L, -2, "__self"); for (auto&& [mn, mfn] : methods) { lua_pushcfunction(L, mfn); lua_setfield(L, -2, mn.data()); } lua_setglobal(L, modName.data()); } return 0; } std::vector<std::any> clua::engine::luaExecute(const std::string& luaScript, const std::string& luaFunction, const std::vector<std::any>& luaArgs) { std::vector<std::any> multiReturn; if (auto&& L{ S() }; L) { if (!luaScript.empty()) { if (luaL_dofile(l, luaScript.c_str()) != 0) { fprintf(stderr, "clua::execute(`%s`): %s\n", luaScript.c_str(), lua_tostring(l, -1)); lua_pop(l, 1); return {}; } } if (!luaFunction.empty()) { auto multi_return_top = lua_gettop(l); try { if (lua_getglobal(l, luaFunction.c_str()); lua_isfunction(l, -1)) { for (auto&& v : luaArgs) { pushValue(l, v); } if (lua_pcall(l, (int)luaArgs.size(), LUA_MULTRET, 0) == 0) { if (int multi_return_count = lua_gettop(l) - multi_return_top; multi_return_count) { multiReturn.reserve(multi_return_count); for (; multi_return_count; --multi_return_count) { if (lua_isinteger(l, -multi_return_count)) { multiReturn.emplace_back(std::any{ ssize_t(lua_tointeger(l, -multi_return_count)) }); } else if (lua_isboolean(l, -multi_return_count)) { multiReturn.emplace_back(std::any{ bool(lua_toboolean(l, -multi_return_count)) }); } else if (lua_isnil(l, -multi_return_count)) { multiReturn.emplace_back(std::any{ nullptr }); } else if (lua_isstring(l, -multi_return_count)) { size_t ptr_len{ 0 }; if (auto ptr_str = lua_tolstring(l, -multi_return_count, &ptr_len); ptr_str && ptr_len) { multiReturn.emplace_back(std::string{ ptr_str,ptr_str + ptr_len }); } else { multiReturn.emplace_back(std::string{ }); } } else if (lua_istable(l, -multi_return_count)) { std::unordered_map<std::string, std::string> map; auto ntop = lua_gettop(l); lua_pushnil(l); while (lua_next(l, -multi_return_count - 1)) { if (lua_isnumber(l, -2)) { map.emplace(std::to_string(lua_tointeger(l, -2)), lua_tostring(l, -1)); } else if (lua_isstring(l, -2)) { map.emplace(lua_tostring(l, -2), lua_tostring(l, -1)); } lua_pop(l, 1); } multiReturn.emplace_back(map); lua_settop(l, ntop); } } } } else { fprintf(stderr, "clua::execute(error running function `%s`): %s\n", luaFunction.c_str(), lua_tostring(l, -1)); return {}; } } else { fprintf(stderr, "clua::execute(error running function `%s`): %s\n", luaFunction.c_str(), lua_tostring(l, -1)); return {}; } lua_settop(l, multi_return_top); } catch (std::exception& ex) { fprintf(stderr, "clua::exception(error running function `%s`): %s\n", luaFunction.c_str(), lua_tostring(l, -1)); } } } else { fprintf(stderr, "clua::execute(error script): %s\n", "invalid lua context (script is empty)"); } return multiReturn; } void clua::engine::luaAddRelativePackagePath(lua_t L, const std::string& path) { if (!path.empty()) { std::string pPath; if (path.front() != '/') { pPath = packageBasePath + path; } else { pPath = path; } packagePaths.emplace(pPath); if (L) { lua_getglobal(L, "package"); lua_getfield(L, -1, "path"); std::string cur_path{ lua_tostring(L, -1) }; cur_path.append(";" + pPath); lua_pop(L, 1); lua_pushstring(L, cur_path.c_str()); lua_setfield(L, -2, "path"); lua_pop(L, 1); } } } void clua::engine::luaAddPackagePath(const std::string& path) { if (!path.empty()) { if (path.back() == '/') packagePaths.emplace(path + "?.lua"); else packagePaths.emplace(path + "/?.lua"); } } void clua::engine::luaPackagePath(std::string& pathPackages) { for (auto&& path : packagePaths) { pathPackages.append(";" + path); } } clua::engine::engine() { } clua::engine::~engine() { } clua::lua_ptr_t clua::engine::S() { lua_ptr_t jitLua{ luaL_newstate(), [](lua_t L) { lua_close(L); } }; luaL_openlibs(jitLua.get()); /* adjust lua package.path */ { lua_getglobal(jitLua.get(), "package"); lua_getfield(jitLua.get(), -1, "path"); std::string cur_path{ lua_tostring(jitLua.get(), -1) }; luaPackagePath(cur_path); lua_pop(jitLua.get(), 1); lua_pushstring(jitLua.get(), cur_path.c_str()); lua_setfield(jitLua.get(), -2, "path"); lua_pop(jitLua.get(), 1); } luaLoadModules(jitLua.get()); return jitLua; } namespace typecast { static void push_value(clua::lua_t L, const std::any& val); template<typename T> void push_integer(clua::lua_t L, const std::any& val) { lua_pushinteger(L, std::any_cast<T>(val)); } template<typename T> void push_number(clua::lua_t L, const std::any& val) { lua_pushnumber(L, std::any_cast<T>(val)); } void push_bool(clua::lua_t L, const std::any& val) { lua_pushboolean(L, std::any_cast<bool>(val)); } void push_string(clua::lua_t L, const std::any& val) { lua_pushstring(L, std::any_cast<const char*>(val)); } void push_cstring(clua::lua_t L, const std::any& val) { auto&& _v = std::any_cast<std::string>(val); lua_pushlstring(L, _v.data(), _v.length()); } void push_vstring(clua::lua_t L, const std::any& val) { auto&& _v = std::any_cast<std::string_view>(val); lua_pushlstring(L, _v.data(), _v.length()); } void push_rawdata(clua::lua_t L, const std::any& val) { auto&& _v = std::any_cast<std::vector<uint8_t>>(val); lua_pushlstring(L, (const char*)_v.data(), _v.size()); } void push_nil(clua::lua_t L, const std::any& val) { lua_pushnil(L); } void push_mapsa(clua::lua_t L, const std::any& val) { lua_newtable(L); if (!std::any_cast<std::unordered_map<std::string, std::any>>(val).empty()) { for (auto&& [k, v] : std::any_cast<std::unordered_map<std::string, std::any>>(val)) { lua_pushlstring(L, k.c_str(), k.length()); push_value(L, v); lua_settable(L, -3); } } } void push_mapsva(clua::lua_t L, const std::any& val) { lua_newtable(L); if (!std::any_cast<std::unordered_map<std::string_view, std::any>>(val).empty()) { for (auto&& [k, v] : std::any_cast<std::unordered_map<std::string_view, std::any>>(val)) { lua_pushlstring(L, k.data(), k.size()); push_value(L, v); lua_settable(L, -3); } } } void push_seta(clua::lua_t L, const std::any& val) { lua_newtable(L); if (!std::any_cast<std::set<std::any>>(val).empty()) { int n = 1; for (auto&& v : std::any_cast<std::set<std::any>>(val)) { lua_pushinteger(L, n++); push_value(L, (std::any&)v); lua_settable(L, -3); } } } void push_deqa(clua::lua_t L, const std::any& val) { lua_newtable(L); if (!std::any_cast<std::deque<std::any>>(val).empty()) { int n = 1; for (auto&& v : std::any_cast<std::deque<std::any>>(val)) { lua_pushinteger(L, n++); push_value(L, (std::any&)v); lua_settable(L, -3); } } } void push_deqsw(clua::lua_t L, const std::any& val) { lua_newtable(L); if (!std::any_cast<std::deque<std::string_view>>(val).empty()) { int n = 1; for (auto&& v : std::any_cast<std::deque<std::string_view>>(val)) { lua_pushinteger(L, n++); lua_pushlstring(L, v.data(), v.length()); lua_settable(L, -3); } } } void push_class_t(clua::lua_t L, const std::any& val) { auto&& v{ std::any_cast<clua::class_t::self_t>(val) }; void** place = (void**)lua_newuserdata(L, sizeof(void*)); *place = v.selfObject; lua_newtable(L); lua_pushcfunction(L, clua::class_t::__index); lua_setfield(L, -2, "__index"); lua_pushcfunction(L, clua::class_t::__tostring); lua_setfield(L, -2, "__tostring"); lua_pushcfunction(L, clua::class_t::__gc); lua_setfield(L, -2, "__gc"); lua_setmetatable(L, -2); v.selfObject = nullptr; // now __gc can free resource } void push_veca(clua::lua_t L, const std::any& val) { lua_newtable(L); if (!std::any_cast<std::vector<std::any>>(val).empty()) { int n = 1; for (auto&& v : std::any_cast<std::vector<std::any>>(val)) { lua_pushinteger(L, n++); push_value(L, (std::any&)v); lua_settable(L, -3); } } } static const std::unordered_map<size_t, std::function<void(clua::lua_t L, const std::any& val)>> PushTypecast{ {typeid(float).hash_code(),push_number<float>}, {typeid(double).hash_code(),push_number<double>}, {typeid(int).hash_code(),push_integer<int>}, {typeid(int16_t).hash_code(),push_integer<int16_t>}, {typeid(uint16_t).hash_code(),push_integer<uint16_t>}, {typeid(int32_t).hash_code(),push_integer<int32_t>}, {typeid(uint32_t).hash_code(),push_integer<uint32_t>}, {typeid(ssize_t).hash_code(),push_integer<ssize_t>}, {typeid(std::time_t).hash_code(),push_integer<std::time_t>}, {typeid(size_t).hash_code(),push_integer<size_t>}, {typeid(int64_t).hash_code(),push_integer<int64_t>}, {typeid(uint64_t).hash_code(),push_integer<uint64_t>}, {typeid(bool).hash_code(),push_bool}, {typeid(const char*).hash_code(),push_string}, {typeid(std::string).hash_code(),push_cstring}, {typeid(std::string_view).hash_code(),push_vstring}, {typeid(std::deque<std::any>).hash_code(),push_deqa}, {typeid(std::deque<std::string_view>).hash_code(),push_deqsw}, {typeid(std::vector<std::any>).hash_code(),push_veca}, {typeid(std::set<std::any>).hash_code(),push_seta}, {typeid(std::unordered_map<std::string,std::any>).hash_code(),push_mapsa}, {typeid(std::unordered_map<std::string_view,std::any>).hash_code(), push_mapsva}, {typeid(clua::class_t::self_t).hash_code(),push_class_t}, {typeid(nullptr).hash_code(),push_nil}, }; void push_value(clua::lua_t L, const std::any& val) { if (val.has_value()) { if (auto&& it = typecast::PushTypecast.find(val.type().hash_code()); it != typecast::PushTypecast.end()) { it->second(L, val); } else { fprintf(stderr, "clua::typecast(%s) no found\n", val.type().name()); } } else { push_nil(L, { nullptr }); } } } void clua::engine::pushValue(clua::lua_t L, const std::any& val) { typecast::push_value(L, val); }
41.185185
217
0.509408
46835ffc0fa55038a82c3e8f90cfff09dc4cb13e
19,985
cpp
C++
src/game/server/hl1/hl1_npc_leech.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/game/server/hl1/hl1_npc_leech.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/game/server/hl1/hl1_npc_leech.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //=============================================================================// #include "cbase.h" #include "ai_default.h" #include "ai_task.h" #include "ai_schedule.h" #include "ai_node.h" #include "ai_hull.h" #include "ai_hint.h" #include "ai_memory.h" #include "ai_route.h" #include "ai_motor.h" #include "soundent.h" #include "game.h" #include "npcevent.h" #include "entitylist.h" #include "activitylist.h" #include "animation.h" #include "basecombatweapon.h" #include "IEffects.h" #include "vstdlib/random.h" #include "engine/IEngineSound.h" #include "ammodef.h" #include "hl1_ai_basenpc.h" #include "ai_senses.h" // Animation events #define LEECH_AE_ATTACK 1 #define LEECH_AE_FLOP 2 //#define DEBUG_BEAMS 0 ConVar sk_leech_health("sk_leech_health", "2"); ConVar sk_leech_dmg_bite("sk_leech_dmg_bite", "2"); // Movement constants #define LEECH_ACCELERATE 10 #define LEECH_CHECK_DIST 45 #define LEECH_SWIM_SPEED 50 #define LEECH_SWIM_ACCEL 80 #define LEECH_SWIM_DECEL 10 #define LEECH_TURN_RATE 70 #define LEECH_SIZEX 10 #define LEECH_FRAMETIME 0.1 class CNPC_Leech : public CHL1BaseNPC { DECLARE_CLASS( CNPC_Leech, CHL1BaseNPC ); public: DECLARE_DATADESC(); void Spawn(void); void Precache(void); static const char *pAlertSounds[]; void SwimThink(void); void DeadThink(void); void SwitchLeechState(void); float ObstacleDistance(CBaseEntity *pTarget); void UpdateMotion(void); void RecalculateWaterlevel(void); void Touch(CBaseEntity *pOther); Disposition_t IRelationType(CBaseEntity *pTarget); void HandleAnimEvent(animevent_t *pEvent); void AttackSound(void); void AlertSound(void); void Activate(void); Class_T Classify(void) { return CLASS_INSECT; }; void Event_Killed(const CTakeDamageInfo &info); bool ShouldGib(const CTakeDamageInfo &info); /* // Base entity functions void Killed( entvars_t *pevAttacker, int iGib ); int TakeDamage( entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType ); */ private: // UNDONE: Remove unused boid vars, do group behavior float m_flTurning;// is this boid turning? bool m_fPathBlocked;// TRUE if there is an obstacle ahead float m_flAccelerate; float m_obstacle; float m_top; float m_bottom; float m_height; float m_waterTime; float m_sideTime; // Timer to randomly check clearance on sides float m_zTime; float m_stateTime; float m_attackSoundTime; Vector m_oldOrigin; }; LINK_ENTITY_TO_CLASS( monster_leech, CNPC_Leech ); BEGIN_DATADESC( CNPC_Leech ) DEFINE_FIELD( m_flTurning, FIELD_FLOAT ), DEFINE_FIELD( m_fPathBlocked, FIELD_BOOLEAN ), DEFINE_FIELD( m_flAccelerate, FIELD_FLOAT ), DEFINE_FIELD( m_obstacle, FIELD_FLOAT ), DEFINE_FIELD( m_top, FIELD_FLOAT ), DEFINE_FIELD( m_bottom, FIELD_FLOAT ), DEFINE_FIELD( m_height, FIELD_FLOAT ), DEFINE_FIELD( m_waterTime, FIELD_TIME ), DEFINE_FIELD( m_sideTime, FIELD_TIME ), DEFINE_FIELD( m_zTime, FIELD_TIME ), DEFINE_FIELD( m_stateTime, FIELD_TIME ), DEFINE_FIELD( m_attackSoundTime, FIELD_TIME ), DEFINE_FIELD( m_oldOrigin, FIELD_VECTOR ), DEFINE_THINKFUNC( SwimThink ), DEFINE_THINKFUNC(DeadThink), END_DATADESC() bool CNPC_Leech::ShouldGib(const CTakeDamageInfo &info) { return false; } void CNPC_Leech::Spawn(void) { Precache(); SetModel("models/leech.mdl"); SetHullType(HULL_TINY_CENTERED); SetHullSizeNormal(); UTIL_SetSize(this, Vector(-1, -1, 0), Vector(1, 1, 2)); Vector vecSurroundingMins(-8, -8, 0); Vector vecSurroundingMaxs(8, 8, 2); CollisionProp()->SetSurroundingBoundsType(USE_SPECIFIED_BOUNDS, &vecSurroundingMins, &vecSurroundingMaxs); // Don't push the minz down too much or the water check will fail because this entity is really point-sized SetSolid(SOLID_BBOX); AddSolidFlags(FSOLID_NOT_STANDABLE); SetMoveType(MOVETYPE_FLY); AddFlag(FL_SWIM); m_iHealth = sk_leech_health.GetInt(); m_flFieldOfView = -0.5; // 180 degree FOV SetDistLook(750); NPCInit(); SetThink(&CNPC_Leech::SwimThink); SetUse(NULL); SetTouch(NULL); SetViewOffset(vec3_origin); m_flTurning = 0; m_fPathBlocked = FALSE; SetActivity(ACT_SWIM); SetState(NPC_STATE_IDLE); m_stateTime = gpGlobals->curtime + random->RandomFloat(1, 5); SetRenderColor(255, 255, 255, 255); m_bloodColor = DONT_BLEED; SetCollisionGroup(COLLISION_GROUP_DEBRIS); } void CNPC_Leech::Activate(void) { RecalculateWaterlevel(); BaseClass::Activate(); } void CNPC_Leech::DeadThink(void) { if (IsSequenceFinished()) { if (GetActivity() == ACT_DIEFORWARD) { SetThink(NULL); StopAnimation(); return; } else if (GetFlags() & FL_ONGROUND) { AddSolidFlags(FSOLID_NOT_SOLID); SetActivity(ACT_DIEFORWARD); } } StudioFrameAdvance(); SetNextThink(gpGlobals->curtime + 0.1); // Apply damage velocity, but keep out of the walls if (GetAbsVelocity().x != 0 || GetAbsVelocity().y != 0) { trace_t tr; // Look 0.5 seconds ahead UTIL_TraceLine(GetLocalOrigin(), GetLocalOrigin() + GetAbsVelocity() * 0.5, MASK_SOLID, this, COLLISION_GROUP_NONE, &tr); if (tr.fraction != 1.0) { Vector vVelocity = GetAbsVelocity(); vVelocity.x = 0; vVelocity.y = 0; SetAbsVelocity(vVelocity); } } } Disposition_t CNPC_Leech::IRelationType(CBaseEntity *pTarget) { if (pTarget->IsPlayer()) return D_HT; return BaseClass::IRelationType(pTarget); } void CNPC_Leech::Touch(CBaseEntity *pOther) { if (!pOther->IsPlayer()) return; if (pOther == GetTouchTrace().m_pEnt) { if (pOther->GetAbsVelocity() == vec3_origin) return; SetBaseVelocity(pOther->GetAbsVelocity()); AddFlag(FL_BASEVELOCITY); } } void CNPC_Leech::HandleAnimEvent(animevent_t *pEvent) { CBaseEntity *pEnemy = GetEnemy(); switch (pEvent->event) { case LEECH_AE_FLOP: // Play flop sound break; case LEECH_AE_ATTACK: AttackSound(); if (pEnemy != NULL) { Vector dir, face; AngleVectors(GetAbsAngles(), &face); face.z = 0; dir = (pEnemy->GetLocalOrigin() - GetLocalOrigin()); dir.z = 0; VectorNormalize(dir); VectorNormalize(face); if (DotProduct(dir, face) > 0.9) // Only take damage if the leech is facing the prey { CTakeDamageInfo info(this, this, sk_leech_dmg_bite.GetInt(), DMG_SLASH); CalculateMeleeDamageForce(&info, dir, pEnemy->GetAbsOrigin()); pEnemy->TakeDamage(info); } } m_stateTime -= 2; break; default: BaseClass::HandleAnimEvent(pEvent); break; } } void CNPC_Leech::Precache(void) { PrecacheModel("models/leech.mdl"); PrecacheScriptSound("Leech.Attack"); PrecacheScriptSound("Leech.Alert"); } void CNPC_Leech::AttackSound(void) { if (gpGlobals->curtime > m_attackSoundTime) { CPASAttenuationFilter filter(this); EmitSound(filter, entindex(), "Leech.Attack"); m_attackSoundTime = gpGlobals->curtime + 0.5; } } void CNPC_Leech::AlertSound(void) { CPASAttenuationFilter filter(this); EmitSound(filter, entindex(), "Leech.Alert"); } void CNPC_Leech::SwitchLeechState(void) { m_stateTime = gpGlobals->curtime + random->RandomFloat(3, 6); if (m_NPCState == NPC_STATE_COMBAT) { SetEnemy(NULL); SetState(NPC_STATE_IDLE); // We may be up against the player, so redo the side checks m_sideTime = 0; } else { GetSenses()->Look(GetSenses()->GetDistLook()); CBaseEntity *pEnemy = BestEnemy(); if (pEnemy && pEnemy->GetWaterLevel() != 0) { SetEnemy(pEnemy); SetState(NPC_STATE_COMBAT); m_stateTime = gpGlobals->curtime + random->RandomFloat(18, 25); AlertSound(); } } } void CNPC_Leech::RecalculateWaterlevel(void) { // Calculate boundaries Vector vecTest = GetLocalOrigin() - Vector(0, 0, 400); trace_t tr; UTIL_TraceLine(GetLocalOrigin(), vecTest, MASK_SOLID, this, COLLISION_GROUP_NONE, &tr); if (tr.fraction != 1.0) m_bottom = tr.endpos.z + 1; else m_bottom = vecTest.z; m_top = UTIL_WaterLevel(GetLocalOrigin(), GetLocalOrigin().z, GetLocalOrigin().z + 400) - 1; #if DEBUG_BEAMS NDebugOverlay::Line( GetLocalOrigin(), GetLocalOrigin() + Vector( 0, 0, m_bottom ), 0, 255, 0, false, 0.1f ); NDebugOverlay::Line( GetLocalOrigin(), GetLocalOrigin() + Vector( 0, 0, m_top ), 0, 255, 255, false, 0.1f ); #endif // Chop off 20% of the outside range float newBottom = m_bottom * 0.8 + m_top * 0.2; m_top = m_bottom * 0.2 + m_top * 0.8; m_bottom = newBottom; m_height = random->RandomFloat(m_bottom, m_top); m_waterTime = gpGlobals->curtime + random->RandomFloat(5, 7); } void CNPC_Leech::SwimThink(void) { trace_t tr; float flLeftSide; float flRightSide; float targetSpeed; float targetYaw = 0; CBaseEntity *pTarget; /*if ( !UTIL_FindClientInPVS( edict() ) ) { m_flNextThink = gpGlobals->curtime + random->RandomFloat( 1.0f, 1.5f ); SetAbsVelocity( vec3_origin ); return; } else*/ SetNextThink(gpGlobals->curtime + 0.1); targetSpeed = LEECH_SWIM_SPEED; if (m_waterTime < gpGlobals->curtime) RecalculateWaterlevel(); if (m_stateTime < gpGlobals->curtime) SwitchLeechState(); ClearCondition(COND_CAN_MELEE_ATTACK1); switch (m_NPCState) { case NPC_STATE_COMBAT: pTarget = GetEnemy(); if (!pTarget) SwitchLeechState(); else { // Chase the enemy's eyes m_height = pTarget->GetLocalOrigin().z + pTarget->GetViewOffset().z - 5; // Clip to viable water area if (m_height < m_bottom) m_height = m_bottom; else if (m_height > m_top) m_height = m_top; Vector location = pTarget->GetLocalOrigin() - GetLocalOrigin(); location.z += (pTarget->GetViewOffset().z); if (location.Length() < 80) SetCondition(COND_CAN_MELEE_ATTACK1); // Turn towards target ent targetYaw = UTIL_VecToYaw(location); QAngle vTestAngle = GetAbsAngles(); targetYaw = UTIL_AngleDiff(targetYaw, UTIL_AngleMod(GetAbsAngles().y)); if (targetYaw < (-LEECH_TURN_RATE)) targetYaw = (-LEECH_TURN_RATE); else if (targetYaw > (LEECH_TURN_RATE)) targetYaw = (LEECH_TURN_RATE); else targetSpeed *= 2; } break; default: if (m_zTime < gpGlobals->curtime) { float newHeight = random->RandomFloat(m_bottom, m_top); m_height = 0.5 * m_height + 0.5 * newHeight; m_zTime = gpGlobals->curtime + random->RandomFloat(1, 4); } if (random->RandomInt(0, 100) < 10) targetYaw = random->RandomInt(-30, 30); pTarget = NULL; // oldorigin test if ((GetLocalOrigin() - m_oldOrigin).Length() < 1) { // If leech didn't move, there must be something blocking it, so try to turn m_sideTime = 0; } break; } m_obstacle = ObstacleDistance(pTarget); m_oldOrigin = GetLocalOrigin(); if (m_obstacle < 0.1) m_obstacle = 0.1; Vector vForward, vRight; AngleVectors(GetAbsAngles(), &vForward, &vRight, NULL); // is the way ahead clear? if (m_obstacle == 1.0) { // if the leech is turning, stop the trend. if (m_flTurning != 0) { m_flTurning = 0; } m_fPathBlocked = FALSE; m_flSpeed = UTIL_Approach(targetSpeed, m_flSpeed, LEECH_SWIM_ACCEL * LEECH_FRAMETIME); SetAbsVelocity(vForward * m_flSpeed); } else { m_obstacle = 1.0 / m_obstacle; // IF we get this far in the function, the leader's path is blocked! m_fPathBlocked = TRUE; if (m_flTurning == 0)// something in the way and leech is not already turning to avoid { Vector vecTest; // measure clearance on left and right to pick the best dir to turn vecTest = GetLocalOrigin() + (vRight * LEECH_SIZEX) + (vForward * LEECH_CHECK_DIST); UTIL_TraceLine(GetLocalOrigin(), vecTest, MASK_SOLID, this, COLLISION_GROUP_NONE, &tr); flRightSide = tr.fraction; vecTest = GetLocalOrigin() + (vRight * -LEECH_SIZEX) + (vForward * LEECH_CHECK_DIST); UTIL_TraceLine(GetLocalOrigin(), vecTest, MASK_SOLID, this, COLLISION_GROUP_NONE, &tr); flLeftSide = tr.fraction; // turn left, right or random depending on clearance ratio float delta = (flRightSide - flLeftSide); if (delta > 0.1 || (delta > -0.1 && random->RandomInt(0, 100) < 50)) m_flTurning = -LEECH_TURN_RATE; else m_flTurning = LEECH_TURN_RATE; } m_flSpeed = UTIL_Approach(-(LEECH_SWIM_SPEED * 0.5), m_flSpeed, LEECH_SWIM_DECEL * LEECH_FRAMETIME * m_obstacle); SetAbsVelocity(vForward * m_flSpeed); } GetMotor()->SetIdealYaw(m_flTurning + targetYaw); UpdateMotion(); } // // ObstacleDistance - returns normalized distance to obstacle // float CNPC_Leech::ObstacleDistance(CBaseEntity *pTarget) { trace_t tr; Vector vecTest; Vector vForward, vRight; // use VELOCITY, not angles, not all boids point the direction they are flying //Vector vecDir = UTIL_VecToAngles( pev->velocity ); QAngle tmp = GetAbsAngles(); tmp.x = -tmp.x; AngleVectors(tmp, &vForward, &vRight, NULL); // check for obstacle ahead vecTest = GetLocalOrigin() + vForward * LEECH_CHECK_DIST; UTIL_TraceLine(GetLocalOrigin(), vecTest, MASK_SOLID, this, COLLISION_GROUP_NONE, &tr); if (tr.startsolid) { m_flSpeed = -LEECH_SWIM_SPEED * 0.5; } if (tr.fraction != 1.0) { if ((pTarget == NULL || tr.m_pEnt != pTarget)) { return tr.fraction; } else { if (fabs(m_height - GetLocalOrigin().z) > 10) return tr.fraction; } } if (m_sideTime < gpGlobals->curtime) { // extra wide checks vecTest = GetLocalOrigin() + vRight * LEECH_SIZEX * 2 + vForward * LEECH_CHECK_DIST; UTIL_TraceLine(GetLocalOrigin(), vecTest, MASK_SOLID, this, COLLISION_GROUP_NONE, &tr); if (tr.fraction != 1.0) return tr.fraction; vecTest = GetLocalOrigin() - vRight * LEECH_SIZEX * 2 + vForward * LEECH_CHECK_DIST; UTIL_TraceLine(GetLocalOrigin(), vecTest, MASK_SOLID, this, COLLISION_GROUP_NONE, &tr); if (tr.fraction != 1.0) return tr.fraction; // Didn't hit either side, so stop testing for another 0.5 - 1 seconds m_sideTime = gpGlobals->curtime + random->RandomFloat(0.5, 1); } return 1.0; } void CNPC_Leech::UpdateMotion(void) { float flapspeed = (m_flSpeed - m_flAccelerate) / LEECH_ACCELERATE; m_flAccelerate = m_flAccelerate * 0.8 + m_flSpeed * 0.2; if (flapspeed < 0) flapspeed = -flapspeed; flapspeed += 1.0; if (flapspeed < 0.5) flapspeed = 0.5; if (flapspeed > 1.9) flapspeed = 1.9; m_flPlaybackRate = flapspeed; QAngle vAngularVelocity = GetLocalAngularVelocity(); QAngle vAngles = GetLocalAngles(); if (!m_fPathBlocked) vAngularVelocity.y = GetMotor()->GetIdealYaw(); else vAngularVelocity.y = GetMotor()->GetIdealYaw() * m_obstacle; if (vAngularVelocity.y > 150) SetIdealActivity(ACT_TURN_LEFT); else if (vAngularVelocity.y < -150) SetIdealActivity(ACT_TURN_RIGHT); else SetIdealActivity(ACT_SWIM); // lean float targetPitch, delta; delta = m_height - GetLocalOrigin().z; /* if ( delta < -10 ) targetPitch = -30; else if ( delta > 10 ) targetPitch = 30; else*/ targetPitch = 0; vAngles.x = UTIL_Approach(targetPitch, vAngles.x, 60 * LEECH_FRAMETIME); // bank vAngularVelocity.z = -(vAngles.z + (vAngularVelocity.y * 0.25)); if (m_NPCState == NPC_STATE_COMBAT && HasCondition(COND_CAN_MELEE_ATTACK1)) SetIdealActivity(ACT_MELEE_ATTACK1); // Out of water check if (!GetWaterLevel()) { SetMoveType(MOVETYPE_FLYGRAVITY); SetIdealActivity(ACT_HOP); SetAbsVelocity(vec3_origin); // Animation will intersect the floor if either of these is non-zero vAngles.z = 0; vAngles.x = 0; m_flPlaybackRate = random->RandomFloat(0.8, 1.2); } else if (GetMoveType() == MOVETYPE_FLYGRAVITY) { SetMoveType(MOVETYPE_FLY); SetGroundEntity(NULL); // TODO RecalculateWaterlevel(); m_waterTime = gpGlobals->curtime + 2; // Recalc again soon, water may be rising } if (GetActivity() != GetIdealActivity()) { SetActivity(GetIdealActivity()); } StudioFrameAdvance(); DispatchAnimEvents(this); SetLocalAngles(vAngles); SetLocalAngularVelocity(vAngularVelocity); Vector vForward, vRight; AngleVectors(vAngles, &vForward, &vRight, NULL); #if DEBUG_BEAMS if ( m_fPathBlocked ) { float color = m_obstacle * 30; if ( m_obstacle == 1.0 ) color = 0; if ( color > 255 ) color = 255; NDebugOverlay::Line( GetLocalOrigin(), GetLocalOrigin() + vForward * LEECH_CHECK_DIST, 255, color, color, false, 0.1f ); } else NDebugOverlay::Line( GetLocalOrigin(), GetLocalOrigin() + vForward * LEECH_CHECK_DIST, 255, 255, 0, false, 0.1f ); NDebugOverlay::Line( GetLocalOrigin(), GetLocalOrigin() + vRight * (vAngularVelocity.y*0.25), 0, 0, 255, false, 0.1f ); #endif } void CNPC_Leech::Event_Killed(const CTakeDamageInfo &info) { Vector vecSplatDir; trace_t tr; //ALERT(at_aiconsole, "Leech: killed\n"); // tell owner ( if any ) that we're dead.This is mostly for MonsterMaker functionality. CBaseEntity *pOwner = GetOwnerEntity(); if (pOwner) pOwner->DeathNotice(this); // When we hit the ground, play the "death_end" activity if (GetWaterLevel()) { QAngle qAngles = GetAbsAngles(); QAngle qAngularVel = GetLocalAngularVelocity(); Vector vOrigin = GetLocalOrigin(); qAngles.z = 0; qAngles.x = 0; vOrigin.z += 1; SetAbsVelocity(vec3_origin); if (random->RandomInt(0, 99) < 70) qAngularVel.y = random->RandomInt(-720, 720); SetAbsAngles(qAngles); SetLocalAngularVelocity(qAngularVel); SetAbsOrigin(vOrigin); SetGravity(0.02); SetGroundEntity(NULL); SetActivity(ACT_DIESIMPLE); } else SetActivity(ACT_DIEFORWARD); SetMoveType(MOVETYPE_FLYGRAVITY); m_takedamage = DAMAGE_NO; SetThink(&CNPC_Leech::DeadThink); }
28.71408
129
0.615161
468943227aa1aababc7ce2303fe243effbaadc5e
11,202
inl
C++
Extras/RigidBodyGpuPipeline/opencl/primitives/AdlPrimitives/Sort/RadixSort32.inl
tizenorg/platform.upstream.libbullet
eb6918d59f661c0e5b469d6e007f91a82d46a302
[ "Zlib" ]
2
2015-02-28T15:50:06.000Z
2016-04-12T18:03:10.000Z
Extras/RigidBodyGpuPipeline/opencl/primitives/AdlPrimitives/Sort/RadixSort32.inl
tizenorg/platform.upstream.libbullet
eb6918d59f661c0e5b469d6e007f91a82d46a302
[ "Zlib" ]
null
null
null
Extras/RigidBodyGpuPipeline/opencl/primitives/AdlPrimitives/Sort/RadixSort32.inl
tizenorg/platform.upstream.libbullet
eb6918d59f661c0e5b469d6e007f91a82d46a302
[ "Zlib" ]
null
null
null
/* 2011 Takahiro Harada */ #define PATH "..\\..\\opencl\\primitives\\AdlPrimitives\\Sort\\RadixSort32Kernels" #define RADIXSORT32_KERNEL0 "StreamCountKernel" #define RADIXSORT32_KERNEL1 "PrefixScanKernel" #define RADIXSORT32_KERNEL2 "SortAndScatterKernel" #define RADIXSORT32_KERNEL3 "SortAndScatterKeyValueKernel" #define RADIXSORT32_KERNEL4 "SortAndScatterSortDataKernel" #define RADIXSORT32_KERNEL5 "StreamCountSortDataKernel" #include "RadixSort32KernelsCL.h" #include "RadixSort32KernelsDX11.h" // todo. Shader compiler (2010JuneSDK) doesn't allow me to place Barriers in SortAndScatterKernel... // So it only works on a GPU with 64 wide SIMD. template<DeviceType TYPE> typename RadixSort32<TYPE>::Data* RadixSort32<TYPE>::allocate( const Device* device, int maxSize ) { ADLASSERT( TYPE == device->m_type ); const char* src[] = #if defined(ADL_LOAD_KERNEL_FROM_STRING) {radixSort32KernelsCL, radixSort32KernelsDX11}; #else {0,0}; #endif Data* data = new Data; data->m_device = device; data->m_maxSize = maxSize; data->m_streamCountKernel = device->getKernel( PATH, RADIXSORT32_KERNEL0, 0, src[TYPE] ); data->m_streamCountSortDataKernel = device->getKernel( PATH, RADIXSORT32_KERNEL5, 0, src[TYPE] ); data->m_prefixScanKernel = device->getKernel( PATH, RADIXSORT32_KERNEL1, 0, src[TYPE] ); data->m_sortAndScatterKernel = device->getKernel( PATH, RADIXSORT32_KERNEL2, 0, src[TYPE] ); data->m_sortAndScatterKeyValueKernel = device->getKernel( PATH, RADIXSORT32_KERNEL3, 0, src[TYPE] ); data->m_sortAndScatterSortDataKernel = device->getKernel( PATH, RADIXSORT32_KERNEL4, 0, src[TYPE] ); int wtf = NUM_WGS*(1<<BITS_PER_PASS); data->m_workBuffer0 = new Buffer<u32>( device, maxSize ); data->m_workBuffer1 = new Buffer<u32>( device , wtf ); data->m_workBuffer2 = new Buffer<u32>( device, maxSize ); data->m_workBuffer3 = new Buffer<SortData>(device,maxSize); for(int i=0; i<32/BITS_PER_PASS; i++) data->m_constBuffer[i] = new Buffer<ConstData>( device, 1, BufferBase::BUFFER_CONST ); data->m_copyData = Copy<TYPE>::allocate( device ); return data; } template<DeviceType TYPE> void RadixSort32<TYPE>::deallocate( Data* data ) { delete data->m_workBuffer0; delete data->m_workBuffer1; delete data->m_workBuffer2; delete data->m_workBuffer3; for(int i=0; i<32/BITS_PER_PASS; i++) delete data->m_constBuffer[i]; Copy<TYPE>::deallocate( data->m_copyData ); delete data; } template<DeviceType TYPE> void RadixSort32<TYPE>::execute(Data* data, Buffer<u32>& inout, int n, int sortBits /* = 32 */ ) { ADLASSERT( n%DATA_ALIGNMENT == 0 ); ADLASSERT( n <= data->m_maxSize ); // ADLASSERT( ELEMENTS_PER_WORK_ITEM == 4 ); ADLASSERT( BITS_PER_PASS == 4 ); ADLASSERT( WG_SIZE == 64 ); ADLASSERT( (sortBits&0x3) == 0 ); Buffer<u32>* src = &inout; Buffer<u32>* dst = data->m_workBuffer0; Buffer<u32>* histogramBuffer = data->m_workBuffer1; int nWGs = NUM_WGS; ConstData cdata; { int nBlocks = (n+ELEMENTS_PER_WORK_ITEM*WG_SIZE-1)/(ELEMENTS_PER_WORK_ITEM*WG_SIZE); cdata.m_n = n; cdata.m_nWGs = NUM_WGS; cdata.m_startBit = 0; cdata.m_nBlocksPerWG = (nBlocks + cdata.m_nWGs - 1)/cdata.m_nWGs; if( nBlocks < NUM_WGS ) { cdata.m_nBlocksPerWG = 1; nWGs = nBlocks; } } for(int ib=0; ib<sortBits; ib+=4) { cdata.m_startBit = ib; { BufferInfo bInfo[] = { BufferInfo( src, true ), BufferInfo( histogramBuffer ) }; Launcher launcher( data->m_device, data->m_streamCountKernel ); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( NUM_WGS*WG_SIZE, WG_SIZE ); } {// prefix scan group histogram BufferInfo bInfo[] = { BufferInfo( histogramBuffer ) }; Launcher launcher( data->m_device, data->m_prefixScanKernel ); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( 128, 128 ); } {// local sort and distribute BufferInfo bInfo[] = { BufferInfo( src, true ), BufferInfo( histogramBuffer, true ), BufferInfo( dst ) }; Launcher launcher( data->m_device, data->m_sortAndScatterKernel ); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( nWGs*WG_SIZE, WG_SIZE ); } swap2( src, dst ); } if( src != &inout ) { Copy<TYPE>::execute( data->m_copyData, (Buffer<float>&)inout, (Buffer<float>&)*src, n ); } } template<DeviceType TYPE> void RadixSort32<TYPE>::execute(Data* data, Buffer<u32>& in, Buffer<u32>& out, int n, int sortBits /* = 32 */ ) { ADLASSERT( n%DATA_ALIGNMENT == 0 ); ADLASSERT( n <= data->m_maxSize ); // ADLASSERT( ELEMENTS_PER_WORK_ITEM == 4 ); ADLASSERT( BITS_PER_PASS == 4 ); ADLASSERT( WG_SIZE == 64 ); ADLASSERT( (sortBits&0x3) == 0 ); Buffer<u32>* src = &in; Buffer<u32>* dst = data->m_workBuffer0; Buffer<u32>* histogramBuffer = data->m_workBuffer1; int nWGs = NUM_WGS; ConstData cdata; { int nBlocks = (n+ELEMENTS_PER_WORK_ITEM*WG_SIZE-1)/(ELEMENTS_PER_WORK_ITEM*WG_SIZE); cdata.m_n = n; cdata.m_nWGs = NUM_WGS; cdata.m_startBit = 0; cdata.m_nBlocksPerWG = (nBlocks + cdata.m_nWGs - 1)/cdata.m_nWGs; if( nBlocks < NUM_WGS ) { cdata.m_nBlocksPerWG = 1; nWGs = nBlocks; } } if( sortBits == 4 ) dst = &out; for(int ib=0; ib<sortBits; ib+=4) { if( ib==4 ) { dst = &out; } cdata.m_startBit = ib; { BufferInfo bInfo[] = { BufferInfo( src, true ), BufferInfo( histogramBuffer ) }; Launcher launcher( data->m_device, data->m_streamCountKernel ); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( NUM_WGS*WG_SIZE, WG_SIZE ); } {// prefix scan group histogram BufferInfo bInfo[] = { BufferInfo( histogramBuffer ) }; Launcher launcher( data->m_device, data->m_prefixScanKernel ); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( 128, 128 ); } {// local sort and distribute BufferInfo bInfo[] = { BufferInfo( src, true ), BufferInfo( histogramBuffer, true ), BufferInfo( dst ) }; Launcher launcher( data->m_device, data->m_sortAndScatterKernel ); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( nWGs*WG_SIZE, WG_SIZE ); } swap2( src, dst ); } } template<DeviceType TYPE> void RadixSort32<TYPE>::execute(Data* data, Buffer<u32>& keysIn, Buffer<u32>& keysOut, Buffer<u32>& valuesIn, Buffer<u32>& valuesOut, int n, int sortBits /* = 32 */) { ADLASSERT( n%DATA_ALIGNMENT == 0 ); ADLASSERT( n <= data->m_maxSize ); // ADLASSERT( ELEMENTS_PER_WORK_ITEM == 4 ); ADLASSERT( BITS_PER_PASS == 4 ); ADLASSERT( WG_SIZE == 64 ); ADLASSERT( (sortBits&0x3) == 0 ); Buffer<u32>* src = &keysIn; Buffer<u32>* srcVal = &valuesIn; Buffer<u32>* dst = data->m_workBuffer0; Buffer<u32>* dstVal = data->m_workBuffer2; Buffer<u32>* histogramBuffer = data->m_workBuffer1; int nWGs = NUM_WGS; ConstData cdata; { int nBlocks = (n+ELEMENTS_PER_WORK_ITEM*WG_SIZE-1)/(ELEMENTS_PER_WORK_ITEM*WG_SIZE); cdata.m_n = n; cdata.m_nWGs = NUM_WGS; cdata.m_startBit = 0; cdata.m_nBlocksPerWG = (nBlocks + cdata.m_nWGs - 1)/cdata.m_nWGs; if( nBlocks < NUM_WGS ) { cdata.m_nBlocksPerWG = 1; nWGs = nBlocks; } } if( sortBits == 4 ) { dst = &keysOut; dstVal = &valuesOut; } for(int ib=0; ib<sortBits; ib+=4) { if( ib==4 ) { dst = &keysOut; dstVal = &valuesOut; } cdata.m_startBit = ib; { BufferInfo bInfo[] = { BufferInfo( src, true ), BufferInfo( histogramBuffer ) }; Launcher launcher( data->m_device, data->m_streamCountKernel ); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( NUM_WGS*WG_SIZE, WG_SIZE ); } {// prefix scan group histogram BufferInfo bInfo[] = { BufferInfo( histogramBuffer ) }; Launcher launcher( data->m_device, data->m_prefixScanKernel ); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( 128, 128 ); } {// local sort and distribute BufferInfo bInfo[] = { BufferInfo( src, true ), BufferInfo( srcVal, true ), BufferInfo( histogramBuffer, true ), BufferInfo( dst ), BufferInfo( dstVal ) }; Launcher launcher( data->m_device, data->m_sortAndScatterKeyValueKernel ); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( nWGs*WG_SIZE, WG_SIZE ); } swap2( src, dst ); swap2( srcVal, dstVal ); } } template<DeviceType TYPE> void RadixSort32<TYPE>::execute(Data* data, Buffer<SortData>& keyValuesInOut, int n, int sortBits /* = 32 */) { ADLASSERT( n%DATA_ALIGNMENT == 0 ); ADLASSERT( n <= data->m_maxSize ); // ADLASSERT( ELEMENTS_PER_WORK_ITEM == 4 ); ADLASSERT( BITS_PER_PASS == 4 ); ADLASSERT( WG_SIZE == 64 ); ADLASSERT( (sortBits&0x3) == 0 ); Buffer<SortData>* src = &keyValuesInOut; Buffer<SortData>* dst = data->m_workBuffer3; Buffer<u32>* histogramBuffer = data->m_workBuffer1; int nWGs = NUM_WGS; ConstData cdata; { int nBlocks = (n+ELEMENTS_PER_WORK_ITEM*WG_SIZE-1)/(ELEMENTS_PER_WORK_ITEM*WG_SIZE); cdata.m_n = n; cdata.m_nWGs = NUM_WGS; cdata.m_startBit = 0; cdata.m_nBlocksPerWG = (nBlocks + cdata.m_nWGs - 1)/cdata.m_nWGs; if( nBlocks < NUM_WGS ) { cdata.m_nBlocksPerWG = 1; nWGs = nBlocks; } } int count=0; for(int ib=0; ib<sortBits; ib+=4) { cdata.m_startBit = ib; { BufferInfo bInfo[] = { BufferInfo( src, true ), BufferInfo( histogramBuffer ) }; Launcher launcher( data->m_device, data->m_streamCountSortDataKernel); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( NUM_WGS*WG_SIZE, WG_SIZE ); } {// prefix scan group histogram BufferInfo bInfo[] = { BufferInfo( histogramBuffer ) }; Launcher launcher( data->m_device, data->m_prefixScanKernel ); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( 128, 128 ); } {// local sort and distribute BufferInfo bInfo[] = { BufferInfo( src, true ), BufferInfo( histogramBuffer, true ), BufferInfo( dst )}; Launcher launcher( data->m_device, data->m_sortAndScatterSortDataKernel ); launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) ); launcher.setConst( *data->m_constBuffer[ib/4], cdata ); launcher.launch1D( nWGs*WG_SIZE, WG_SIZE ); } swap2( src, dst ); count++; } if (count&1) { ADLASSERT(0);//need to copy from workbuffer to keyValuesInOut } } #undef PATH #undef RADIXSORT32_KERNEL0 #undef RADIXSORT32_KERNEL1 #undef RADIXSORT32_KERNEL2 #undef RADIXSORT32_KERNEL3
32.282421
165
0.701303
468fcc6d2ed9c2da8a6a448e880c86f2aa80fc2a
310
hpp
C++
src/FileSystemUtils.hpp
antmicro/ros-tracking-nodes-tester-node
878336dca10288e017665d2b2b9d075acecbf26b
[ "Apache-2.0" ]
null
null
null
src/FileSystemUtils.hpp
antmicro/ros-tracking-nodes-tester-node
878336dca10288e017665d2b2b9d075acecbf26b
[ "Apache-2.0" ]
null
null
null
src/FileSystemUtils.hpp
antmicro/ros-tracking-nodes-tester-node
878336dca10288e017665d2b2b9d075acecbf26b
[ "Apache-2.0" ]
null
null
null
#ifndef FILE_SYSTEM_UTILS #define FILE_SYSTEM_UTILS #include <string> #include <vector> namespace FileSystemUtils { inline bool endsWith(std::string const & value, std::string const & ending); void listFiles(std::string dir_path, std::vector<std::string> &files, std::string extension=""); } #endif
22.142857
100
0.73871
46919e1867b7bb36b75acf947a58b6309383024e
1,566
cc
C++
src/abc059/c.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc059/c.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc059/c.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; ll solve(int n, vector<ll> a) { ll sum = 0, count = 0; for(int i = 0; i < n; i++) { ll temp = sum + a[i]; if(i % 2 == 0) { if(temp > 0) { sum = temp; continue; } else { ll delta = abs(temp) + 1; count += delta; sum = temp + delta; } } else { // odd if(temp < 0) { sum = temp; continue; } else { // temp > 0 ll delta = -temp - 1; count += abs(delta); sum = temp + delta; } } } ll res = count; sum = count = 0; for(int i = 0; i < n; i++) { ll temp = sum + a[i]; if(i % 2 == 1) { // odd if(temp > 0) { sum = temp; continue; } else { ll delta = abs(temp) + 1; count += delta; sum = temp + delta; } } else { // odd if(temp < 0) { sum = temp; continue; } else { // temp > 0 ll delta = -temp - 1; count += abs(delta); sum = temp + delta; } } } res = min(res, count); return res; } /* int main() { int n; cin >> n; vector<ll> a(n); for(int i = 0; i < n; i++) { cin >> a[i]; } cout << solve(n, a) << endl; } */
23.727273
41
0.327586
46949531f8ddf132fb5010d55fba16a29d7c004e
7,478
cpp
C++
Simbody/tests/TestSmoothSphereHalfSpaceForce.cpp
e-schumann/simbody
4d8842270d5c400ef64cfd5723e0e0399161e51f
[ "Apache-2.0" ]
1,916
2015-01-01T09:35:21.000Z
2022-03-30T11:38:43.000Z
Simbody/tests/TestSmoothSphereHalfSpaceForce.cpp
e-schumann/simbody
4d8842270d5c400ef64cfd5723e0e0399161e51f
[ "Apache-2.0" ]
389
2015-01-01T01:13:51.000Z
2022-03-16T15:30:58.000Z
Simbody/tests/TestSmoothSphereHalfSpaceForce.cpp
e-schumann/simbody
4d8842270d5c400ef64cfd5723e0e0399161e51f
[ "Apache-2.0" ]
486
2015-01-02T10:25:49.000Z
2022-03-16T15:31:40.000Z
/* -------------------------------------------------------------------------- * * Simbody(tm) * * -------------------------------------------------------------------------- * * This is part of the SimTK biosimulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. * * * * Portions copyright (c) 2008-19 Stanford University and the Authors. * * Authors: Antoine Falisse, Gil Serrancoli * * Contributors: Peter Eastman * * * * 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 "SimTKsimbody.h" using namespace SimTK; using namespace std; const Real TOL = 1e-10; #define ASSERT(cond) {SimTK_ASSERT_ALWAYS(cond, "Assertion failed");} template <class T> void assertEqual(T val1, T val2) { ASSERT(abs(val1-val2) < TOL); } template <int N> void assertEqual(Vec<N> val1, Vec<N> val2) { for (int i = 0; i < N; ++i) ASSERT(abs(val1[i]-val2[i]) < TOL); } void testForces() { MultibodySystem system; SimbodyMatterSubsystem matter(system); GeneralForceSubsystem forces(system); const Vec3 gravity = Vec3(0, -9.8, 0); Force::UniformGravity(forces, matter, gravity, 0); const Real radius = 0.8; const Real k = 1500.0; const Real stiffness = 0.5*std::pow(k, 2.0/3.0); const Real dissipation = 0.5; const Real us = 1.0; const Real ud = 0.5; const Real uv = 0.1; const Real vt = 0.001; const Real cf = 1e-5; const Real bd = 300; const Real bv = 50; Body::Rigid body1(MassProperties(1.0, Vec3(0), Inertia(1))); MobilizedBody::Translation sphere(matter.updGround(), Transform(), body1, Transform()); Body::Rigid body2(MassProperties(1.0, Vec3(0), Inertia(1))); MobilizedBody::Free halfSpace(matter.updGround(), Transform(), body2, Transform()); SmoothSphereHalfSpaceForce hc_smooth(forces); hc_smooth.setParameters(k,dissipation,us,ud,uv,vt,cf,bd,bv); hc_smooth.setContactSphereBody(sphere); hc_smooth.setContactSphereLocationInBody(Vec3(0)); hc_smooth.setContactSphereRadius(radius); Transform testFrame(Rotation(-0.5*Pi, ZAxis), Vec3(0)); hc_smooth.setContactHalfSpaceFrame(testFrame); hc_smooth.setContactHalfSpaceBody(halfSpace); State state = system.realizeTopology(); // Position the sphere at a variety of positions and see if the normal // force and potential energy are correct. for (Real height = radius+0.2; height > 0; height -= 0.1) { sphere.setQToFitTranslation(state, Vec3(0, height, 0)); system.realize(state, Stage::Dynamics); const Real depth = radius-height; Real f = (4./3.)*stiffness*std::pow(std::sqrt(depth*depth+cf),3./2.) *std::sqrt(radius*stiffness); Real f_smooth = f*(1./2.+(1./2.)*std::tanh(bd*depth)); assertEqual(system.getRigidBodyForces(state, Stage::Dynamics) [sphere.getMobilizedBodyIndex()][1], gravity+Vec3(0, f_smooth, 0)); assertEqual(hc_smooth.calcPotentialEnergyContribution(state), (2./5.)*f_smooth*depth); } // Now do it with a vertical velocity and see if the dissipation force is // correct. for (Real height = radius+0.2; height > 0; height -= 0.1) { sphere.setQToFitTranslation(state, Vec3(0, height, 0)); const Real depth = radius-height; Real fh = (4./3.)*stiffness*std::pow(std::sqrt(depth*depth+cf),3./2.) *std::sqrt(radius*stiffness); Real fh_smooth = fh*(1./2.+(1./2.)*std::tanh(bd*depth)); for (Real v = -1.0; v <= 1.0; v += 0.1) { sphere.setUToFitLinearVelocity(state, Vec3(0, -v, 0)); system.realize(state, Stage::Dynamics); Real f = fh_smooth*(1.+(3./2.)*dissipation*v); Real f_smooth = f*(1./2.+(1./2.) *std::tanh(bv*(v+(2./(3.*dissipation))))); assertEqual(system.getRigidBodyForces(state, Stage::Dynamics) [sphere.getMobilizedBodyIndex()][1], gravity+Vec3(0, f_smooth, 0)); } } // Now do it with a horizontal velocity and see if the friction force is // correct. Vector_<SpatialVec> expectedForce(matter.getNumBodies()); for (Real height = radius+0.2; height > 0; height -= 0.1) { sphere.setQToFitTranslation(state, Vec3(0, height, 0)); const Real depth = radius-height; Real fh = (4./3.)*stiffness*std::pow(std::sqrt(depth*depth+cf),3./2.) *std::sqrt(radius*stiffness); Real fh_smooth = fh*(1./2.+(1./2.)*std::tanh(bd*depth)); for (Real v = -1.0; v <= 1.0; v += 0.1) { sphere.setUToFitLinearVelocity(state, Vec3(v, 0, 0)); system.realize(state, Stage::Dynamics); Vec3 vec3v(v,0,0); UnitVec3 normal = (halfSpace.getBodyRotation(state)*testFrame.x()); Real vnormal = dot(vec3v, normal); Vec3 vtangent = vec3v - vnormal*normal; Real aux = vtangent.normSqr() + cf; Real vslip = pow(aux,1./2.); Real vrel = vslip / vt; Real ff_smooth_scalar = fh_smooth*(std::min(vrel,Real(1))* (ud+2*(us-ud)/(1+vrel*vrel))+uv*vslip); Vec3 ff_smooth = ff_smooth_scalar*(vtangent) / vslip; const Vec3 totalForceOnSphere = gravity - ff_smooth - fh_smooth*normal; expectedForce = SpatialVec(Vec3(0), Vec3(0)); Vec3 contactPointInSphere = sphere.findStationAtGroundPoint(state, Vec3(0, -stiffness*depth/(stiffness+stiffness), 0)); sphere.applyForceToBodyPoint(state, contactPointInSphere, totalForceOnSphere, expectedForce); SpatialVec actualForce = system.getRigidBodyForces(state, Stage::Dynamics)[sphere.getMobilizedBodyIndex()]; assertEqual(actualForce[0], expectedForce[sphere.getMobilizedBodyIndex()][0]); assertEqual(actualForce[1], expectedForce[sphere.getMobilizedBodyIndex()][1]); } } } int main() { try { testForces(); } catch(const std::exception& e) { cout << "exception: " << e.what() << endl; return 1; } cout << "Done" << endl; return 0; }
44.778443
80
0.56606
4696fe7ded22d7a620a092d9bfb77c12dec81854
718
cpp
C++
L04-Railroad/Student_Code/Factory.cpp
tlyon3/CS235
2bdb8eaf66c9adbfe7ec59c0535852fd1cc30eda
[ "MIT" ]
1
2018-03-04T02:58:55.000Z
2018-03-04T02:58:55.000Z
L04-Railroad/Student_Code/Factory.cpp
tlyon3/CS235
2bdb8eaf66c9adbfe7ec59c0535852fd1cc30eda
[ "MIT" ]
1
2015-02-09T21:29:12.000Z
2015-02-09T21:32:06.000Z
L04-Railroad/Student_Code/Factory.cpp
tlyon3/CS235
2bdb8eaf66c9adbfe7ec59c0535852fd1cc30eda
[ "MIT" ]
4
2019-05-20T02:57:47.000Z
2021-02-11T15:41:15.000Z
#include "Factory.h" #include "station.h" //You may add #include statments here using namespace std; /* Unlike all other documents provided, you may modify this document slightly (but do not change its name) */ //======================================================================================= /* createStation() Creates and returns an object whose class extends StationInterface. This should be an object of a class you have created. Example: If you made a class called "Station", you might say, "return new Station();". */ StationInterface* Factory::createStation() { return new Station();//Modify this line } //=======================================================================================
31.217391
104
0.558496
469ae2939322e272ff45c6fe1f633df93b3137a6
373
hh
C++
LAMPS-HighEnergy/detector/LHNeutronScintArray.hh
ggfdsa10/KEBI_AT-TPC
40e00fcd10d3306b93fff93be5fb0988f87715a7
[ "MIT" ]
3
2021-05-24T19:43:30.000Z
2022-01-06T21:03:23.000Z
LAMPS-HighEnergy/detector/LHNeutronScintArray.hh
ggfdsa10/KEBI_AT-TPC
40e00fcd10d3306b93fff93be5fb0988f87715a7
[ "MIT" ]
4
2020-05-04T15:52:26.000Z
2021-09-13T10:51:03.000Z
LAMPS-HighEnergy/detector/LHNeutronScintArray.hh
ggfdsa10/KEBI_AT-TPC
40e00fcd10d3306b93fff93be5fb0988f87715a7
[ "MIT" ]
3
2020-06-14T10:53:58.000Z
2022-01-06T21:03:30.000Z
#ifndef LHNEUTRONSCINTARRAY_HH #define LHNEUTRONSCINTARRAY_HH #include "KBDetector.hh" class LHNeutronScintArray : public KBDetector { public: LHNeutronScintArray(); virtual ~LHNeutronScintArray() {}; virtual bool Init(); protected: virtual bool BuildGeometry(); virtual bool BuildDetectorPlane(); ClassDef(LHNeutronScintArray, 1) }; #endif
16.954545
45
0.739946
46a09092cd0564f2523082aafc7e85aa138113b0
3,015
cpp
C++
src/drivers/Input/PS2MouseDriver.cpp
Unified-Projects/Unified-OS
89912adc1ed9ec35753fe0f4fa35f03d30ec66a2
[ "BSD-2-Clause" ]
null
null
null
src/drivers/Input/PS2MouseDriver.cpp
Unified-Projects/Unified-OS
89912adc1ed9ec35753fe0f4fa35f03d30ec66a2
[ "BSD-2-Clause" ]
null
null
null
src/drivers/Input/PS2MouseDriver.cpp
Unified-Projects/Unified-OS
89912adc1ed9ec35753fe0f4fa35f03d30ec66a2
[ "BSD-2-Clause" ]
null
null
null
#include <drivers/Input/PS2MouseDriver.h> using namespace UnifiedOS; using namespace UnifiedOS::Drivers; PS2MouseEventHandler::PS2MouseEventHandler(){ } PS2MouseEventHandler::~PS2MouseEventHandler(){ } void PS2MouseEventHandler::OnMouseDown(uint8_t button){ } void PS2MouseEventHandler::OnMouseUp(uint8_t button){ } void PS2MouseEventHandler::OnMouseMove(int x, int y){ } PS2MouseDriver::PS2MouseDriver(Interrupts::InterruptManager* manager, PS2MouseEventHandler* handler) : InterruptHandler(0x2C, manager), dataPort(0x60), commandPort(0x64) { Handler = handler; } PS2MouseDriver::~PS2MouseDriver(){ } void PS2MouseDriver::Wait(){ uint64_t timeout = 100000; while(timeout--){ if((commandPort.Read() & 0b10) == 0){ return; } } } void PS2MouseDriver::Wait_Input(){ uint64_t timeout = 100000; while(timeout--){ if(commandPort.Read() & 0b1){ return; } } } void PS2MouseDriver::Activate(){ // offset = 0; //Default Buffers // buttons = 0; // commandPort.Write(0xA8); //PIC start sending interrupts // Wait(); // commandPort.Write(0x20); //Get state // Wait_Input(); // uint8_t status = dataPort.Read() | 2; // Wait(); // commandPort.Write(0x60); //Set State // Wait(); // dataPort.Write(status); // Wait(); // commandPort.Write(0xD4); // Wait(); // dataPort.Write(0xF6); //Activate // Wait_Input(); // dataPort.Read(); // Wait(); // commandPort.Write(0xD4); // Wait(); // dataPort.Write(0xF4); //Activate // Wait_Input(); // dataPort.Read(); } bool Skip = true; void PS2MouseDriver::HandleInterrupt(uint64_t rsp){ if(Skip) {Skip = false; return;} //Skip first packet //Read status uint8_t status = commandPort.Read(); if (!(status & 0x20)) return; //If not ready return //Read Buffer at current offset buffer[offset] = dataPort.Read(); //We dont want to skip this if there is no handler if(Handler == 0) //If handler does not exist leave return; offset = (offset + 1) % 3; //Increase offset while keeping it less than three if(offset == 0) //If offset 0 (Means full buffer overwrite) { if(buffer[1] != 0 || buffer[2] != 0) //Buffer positions for cursor movement { Handler->OnMouseMove((int8_t)buffer[1], -((int8_t)buffer[2])); //We send to handler but inverse y because it is negative version } for(uint8_t i = 0; i < 3; i++) //We loop over buttons { if((buffer[0] & (0x1<<i)) != (buttons & (0x1<<i))) //Check if it is different { if(buttons & (0x1<<i)) //Shows if it is up or down Handler->OnMouseUp(i+1); //Send to handler else Handler->OnMouseDown(i+1); //Send to handler } } buttons = buffer[0]; //Load the buttons from buffer for next comparison } }
24.314516
140
0.596352
46a259730f0a41dd17d84687e7e34ffb35ebbc7c
1,677
cpp
C++
MidiChannel.cpp
Madsy/libmidi
c271e991e9d6f762e81a8d2dbf7a5cd63973629d
[ "MIT" ]
5
2018-08-14T01:04:33.000Z
2021-07-15T22:13:45.000Z
MidiChannel.cpp
Madsy/libmidi
c271e991e9d6f762e81a8d2dbf7a5cd63973629d
[ "MIT" ]
4
2017-03-21T23:10:46.000Z
2017-03-21T23:19:55.000Z
MidiChannel.cpp
Madsy/libmidi
c271e991e9d6f762e81a8d2dbf7a5cd63973629d
[ "MIT" ]
null
null
null
// // Created by madsy on 22.03.17. // #include <algorithm> #include "MidiChannel.h" MidiChannel::MidiChannel() : pChannelIndex(0), pStartTick(0), pEndTick(0) { } MidiChannel::~MidiChannel() { } std::vector<std::shared_ptr<MidiEvent>> MidiChannel::getEventsWithinInterval(unsigned int startTick, unsigned int endTick) const { std::vector<std::shared_ptr<MidiEvent>> result; for(size_t i = 0; i < pEvents.size(); i++){ unsigned int t = pEvents[i]->getTimestamp(); if(t >= startTick && t < endTick){ result.push_back(pEvents[i]); } } return pEvents; } const std::vector<std::shared_ptr<MidiEvent>> &MidiChannel::getEvents() const { return pEvents; } void MidiChannel::addEvent(const std::shared_ptr<MidiEvent> &evt) { pEvents.push_back(evt); } void MidiChannel::sort() { std::stable_sort(pEvents.begin(), pEvents.end(), [](const std::shared_ptr<MidiEvent>& a, const std::shared_ptr<MidiEvent>& b) -> bool { return a->getTimestamp() < b->getTimestamp(); } ); } unsigned int MidiChannel::getStartTick() const { return pStartTick; } unsigned int MidiChannel::getEndTick() const { return pEndTick; } void MidiChannel::update() { //refresh start and end tick after adding all events pStartTick = 0xFFFFFFFF; pEndTick = 0; for(size_t i = 0; i < pEvents.size(); i++){ if(pEvents[i] && pEvents[i]->getTimestamp() < pStartTick){ pStartTick = pEvents[i]->getTimestamp(); } if(pEvents[i] && pEvents[i]->getTimestamp() > pEndTick){ pEndTick = pEvents[i]->getTimestamp(); } } }
26.619048
130
0.621944
46a38100725550a521f3db415b1ccaf992cbaa83
1,588
cpp
C++
Cpp/odin/odin.cpp
Deuanz/odin
da31a6bc8b9b4a0270f0807b588483840a24cf46
[ "BSL-1.0" ]
null
null
null
Cpp/odin/odin.cpp
Deuanz/odin
da31a6bc8b9b4a0270f0807b588483840a24cf46
[ "BSL-1.0" ]
null
null
null
Cpp/odin/odin.cpp
Deuanz/odin
da31a6bc8b9b4a0270f0807b588483840a24cf46
[ "BSL-1.0" ]
null
null
null
/* Copyright 2016-2017 Felspar Co Ltd. http://odin.felspar.com/ Distributed under 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 */ #include <odin/odin.hpp> #include <odin/nonce.hpp> #include <fostgres/callback.hpp> const fostlib::module odin::c_odin("odin"); const fostlib::setting<fostlib::string> odin::c_jwt_secret( "odin/odin.cpp", "odin", "JWT secret", odin::nonce(), true); const fostlib::setting<bool> odin::c_jwt_trust( "odin/odin.cpp", "odin", "Trust JWT", false, true); const fostlib::setting<fostlib::string> odin::c_jwt_logout_claim( "odin/odin.cpp", "odin", "JWT logout claim", "http://odin.felspar.com/lo", true); const fostlib::setting<bool> odin::c_jwt_logout_check( "odin/odin.cpp", "odin", "Perform JWT logout check", true, true); const fostlib::setting<fostlib::string> odin::c_jwt_permissions_claim( "odin/odin.cpp", "odin", "JWT permissions claim", "http://odin.felspar.com/p", true); namespace { const fostgres::register_cnx_callback c_cb( [](fostlib::pg::connection &cnx, const fostlib::http::server::request &req) { if ( req.headers().exists("__user") ) { const auto &user = req.headers()["__user"]; cnx.set_session("odin.jwt.sub", user.value()); } if ( req.headers().exists("__jwt") ) { for ( const auto &sv : req.headers()["__jwt"] ) cnx.set_session("odin.jwt." + sv.first, sv.second); } }); }
35.288889
89
0.630982
46a467cd6e2de7a95f4fef7ee57741d079069e60
9,543
cpp
C++
dali/tensor/op/cost.cpp
bzcheeseman/Dali
a77c7ce60b20ce150a5927747e128688657907eb
[ "MIT" ]
null
null
null
dali/tensor/op/cost.cpp
bzcheeseman/Dali
a77c7ce60b20ce150a5927747e128688657907eb
[ "MIT" ]
null
null
null
dali/tensor/op/cost.cpp
bzcheeseman/Dali
a77c7ce60b20ce150a5927747e128688657907eb
[ "MIT" ]
null
null
null
#include "cost.h" #include "dali/array/op/binary.h" #include "dali/array/op/unary.h" #include "dali/array/op/gather_from_rows.h" #include "dali/array/op/reducers.h" #include "dali/array/op/softmax.h" #include "dali/tensor/tape.h" #include "dali/utils/make_message.h" #include "dali/tensor/tensor_macros.h" namespace tensor_ops { Tensor binary_cross_entropy(const Tensor& t, const double& target) { ASSERT2(0 <= target && target <= 1, utils::MS() << "Target value for binary_cross_entropy must be a " << "real number between 0 and 1 (got " << target << ")."); Tensor out(op::binary_cross_entropy(t.w, target)); if (graph::backprop_enabled()) { graph::emplace_back([t, target, out]() mutable { MAYBE_GRAD(t) <<= op::binary_cross_entropy_grad(t.w, target) * out.dw; }); } return out; } Tensor binary_cross_entropy(const Tensor& t, const Tensor& target) { Tensor out(op::binary_cross_entropy(t.w, target.w)); if (graph::backprop_enabled()) { graph::emplace_back([t, target, out]() mutable { MAYBE_GRAD(t) <<= op::binary_cross_entropy_grad(t.w, target.w) * out.dw; MAYBE_GRAD(target) <<= 2.0 * op::inverse_tanh(1.0 - 2.0 * t.w) * out.dw; }); } return out; } Tensor sigmoid_binary_cross_entropy(const Tensor& t, const double& target) { ASSERT2(0 <= target && target <= 1, utils::MS() << "Target value for binary_cross_entropy must be a " << "real number between 0 and 1 (got " << target << ")."); Tensor out(op::binary_cross_entropy(op::sigmoid(t.w), target)); if (graph::backprop_enabled()) { graph::emplace_back([t, target, out]() mutable { MAYBE_GRAD(t) <<= (op::sigmoid(t.w) - target) * out.dw; }); } return out; } Tensor sigmoid_binary_cross_entropy(const Tensor& t, const Tensor& target) { Tensor out(op::binary_cross_entropy(op::sigmoid(t.w), target.w)); if (graph::backprop_enabled()) { graph::emplace_back([t, target, out]() mutable { MAYBE_GRAD(t) <<= (op::sigmoid(t.w) - target.w) * out.dw; MAYBE_GRAD(target) <<= 2.0 * op::inverse_tanh(1.0 - 2.0 * op::sigmoid(t.w)) * out.dw; }); } return out; } Tensor margin_loss(const Tensor& t, const int& target, const double& margin, const int& axis) { // relevant slice: auto t_plucked = t.pluck_axis(axis, target); t_plucked = t_plucked.insert_broadcast_axis(axis); // now compare slice to rest of elements: Tensor out(op::eltmax(t_plucked.w - t.w + margin, 0.0)); out.pluck_axis(axis, target).w = 0; // gradient is wherever the if (graph::backprop_enabled()) { graph::emplace_back([t, t_plucked, margin, out, axis, target]() mutable { // TODO(szymon, jonathan): implement gradient -- previous gradient was not done explicitly // MAYBE_GRAD(t) <<= -op::F<functor::greaterthanequal>(out.w, 0.0) * out.dw; // auto t_at_target = t.pluck_axis(axis, target); // MAYBE_GRAD(t_at_target) <<= ( // op::F<functor::greaterthanequal>(out.pluck_axis(axis, target).w, 0.0) * // out.pluck_axis(axis, target).dw // ); // auto out_subslice = out.pluck_axis(axis, target); // out_subslice = out_subslice.insert_broadcast_axis(axis); // MAYBE_GRAD(t_plucked) <<= out_subslice.dw; }); } return out; } Tensor margin_loss(const Tensor&, const Tensor& target, const double& margin, const int& axis) { ASSERT2(false, "Margin loss is not yet implemented."); return Tensor(); } Tensor softmax(const Tensor& t, int axis, const double& temperature) { if (axis < 0) axis = t.ndim() + axis; Tensor out(op::softmax(t.w, axis, temperature)); if (graph::backprop_enabled() && !t.constant) graph::emplace_back([t, out, axis, temperature]() { Array softmax_times_grad_summed(op::sum(out.w * out.dw, {axis})); auto expr = (out.w * out.dw) - (out.w * softmax_times_grad_summed.insert_broadcast_axis(axis)); if (std::abs(temperature - 1.0) < 1e-6) { MAYBE_GRAD(t) <<= expr; } else { MAYBE_GRAD(t) <<= expr / temperature; } }); return out; } Tensor softmax_cross_entropy_with_idxes(const Tensor& unnormalized_probs, const Tensor& targets, const double& temperature, const int& axis) { ASSERT2(axis == unnormalized_probs.ndim() -1, utils::make_message( "softmax_cross_entropy is not yet implemented for axes other than " "-1 (got axis=", axis, ")")); Array softmax_result = op::softmax(unnormalized_probs.w, axis, temperature); Tensor out(-1.0 * op::log(op::gather_from_rows(softmax_result, targets.w))); if (graph::backprop_enabled() && !unnormalized_probs.constant) graph::emplace_back([unnormalized_probs, softmax_result, targets, temperature, axis, out]() { unnormalized_probs.dw <<= softmax_result * out.dw.insert_broadcast_axis(axis) / temperature; unnormalized_probs.dw.gather_from_rows(targets.w) -= out.dw / temperature; }); return out; } Tensor softmax_cross_entropy_with_probs(const Tensor& unnormalized_probs, const Tensor& targets, const double& temperature, const int& axis) { Array softmax_result = op::softmax(unnormalized_probs.w, axis, temperature); Tensor out(-1.0 * targets.w * op::log(softmax_result)); if (graph::backprop_enabled()) graph::emplace_back([unnormalized_probs, softmax_result, targets, temperature, axis, out]() { if (!unnormalized_probs.constant) { Array grad_times_target = op::sum(targets.w * out.dw, {axis}); grad_times_target = grad_times_target.insert_broadcast_axis(axis); unnormalized_probs.dw <<= softmax_result * grad_times_target / temperature - targets.w * out.dw / temperature; } MAYBE_GRAD(targets) <<= -op::log(softmax_result) * out.dw; }); return out; } Tensor softmax_cross_entropy(const Tensor& unnormalized_probs, const Tensor& targets, const double& temperature, int axis) { if (axis < 0) axis = unnormalized_probs.ndim() + axis; if (targets.dtype() == DTYPE_INT32) { return softmax_cross_entropy_with_idxes(unnormalized_probs, targets, temperature, axis); } else { return softmax_cross_entropy_with_probs(unnormalized_probs, targets, temperature, axis); } } Tensor cross_entropy_with_idxes(const Tensor& probs, const Tensor& target, int axis) { // 1) we ensure that cross entropy is happening in a 1D setting or // else the behavior of gather_from_rows would not broadcast in the // desired way (e.g. we assume that a single dimension contains a // multinomial distribution for which KL divergence must be computed). if (target.ndim() > 1) { return cross_entropy_with_idxes( probs.swapaxes(-1, axis).right_fit_ndim(2), target.ravel(), -1 ).reshape(target.shape()).swapaxes(-1, axis); } // 2) We now know that input probs are of the right dimensionality for // our problem (e.g. they should be 2D) and that our targets are 1D: auto permuted_probs = probs.swapaxes(-1, axis); Tensor out(-1.0 * op::log(op::gather_from_rows(permuted_probs.w, target.w))); if (graph::backprop_enabled()) graph::emplace_back([permuted_probs, target, out]() { if (!permuted_probs.constant) { permuted_probs.dw.gather_from_rows(target.w) += -out.dw / op::gather_from_rows(permuted_probs.w, target.w); } }); return out.swapaxes(axis, -1); } Tensor cross_entropy_with_probs(const Tensor& probs, const Tensor& target) { Tensor out(-1.0 * target.w * op::log(probs.w)); if (graph::backprop_enabled()) graph::emplace_back([probs, target, out]() { MAYBE_GRAD(probs) <<= -op::eltinv(probs.w) * target.w * out.dw; MAYBE_GRAD(target) <<= -op::log(probs.w) * out.dw; }); return out; } Tensor cross_entropy(const Tensor& probs, const Tensor& target, int axis) { if (target.dtype() == DTYPE_INT32) { return cross_entropy_with_idxes(probs, target, axis); } else { return cross_entropy_with_probs(probs, target); } } } // namespace tensor_ops
43.180995
111
0.562192
46a6e16f9495c024a23c36ec0d97d124ebfb46f3
593
cpp
C++
vendor/mapbox-gl-native/vendor/mapbox-base/test/io_delete.cpp
aic-develop/vietmaps-gl-native-ios-source
c73c28c4f1ea60ecd4c83c8b49f6947ee06f24f2
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
vendor/mapbox-gl-native/vendor/mapbox-base/test/io_delete.cpp
aic-develop/vietmaps-gl-native-ios-source
c73c28c4f1ea60ecd4c83c8b49f6947ee06f24f2
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
vendor/mapbox-gl-native/vendor/mapbox-base/test/io_delete.cpp
aic-develop/vietmaps-gl-native-ios-source
c73c28c4f1ea60ecd4c83c8b49f6947ee06f24f2
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
#include <mapbox/io.hpp> #include "io_delete.hpp" #include <cassert> #include <string> void deleteTests(const std::string& path, const std::string& copyPath, const std::string& invalidPath) { nonstd::expected<void, std::string> voidExpected; voidExpected = mapbox::base::io::deleteFile(path); assert(voidExpected); voidExpected = mapbox::base::io::deleteFile(copyPath); assert(voidExpected); voidExpected = mapbox::base::io::deleteFile(invalidPath); assert(!voidExpected); assert(voidExpected.error() == std::string("Failed to delete file 'invalid'")); }
28.238095
104
0.706577
46a7bca86ec9b994cc5976c29460d58adfaee694
550
hpp
C++
ex03/include/RobotomyRequestForm.hpp
42cursus-youkim/-Rank04-CPP-Module05
71244b25b1c9556dd4ec186e543c2a3e308d0036
[ "MIT" ]
null
null
null
ex03/include/RobotomyRequestForm.hpp
42cursus-youkim/-Rank04-CPP-Module05
71244b25b1c9556dd4ec186e543c2a3e308d0036
[ "MIT" ]
null
null
null
ex03/include/RobotomyRequestForm.hpp
42cursus-youkim/-Rank04-CPP-Module05
71244b25b1c9556dd4ec186e543c2a3e308d0036
[ "MIT" ]
null
null
null
#ifndef __ROBOTOMYREQUESTFORM_H__ #define __ROBOTOMYREQUESTFORM_H__ #include "Form.hpp" class RobotomyRequestForm : public Form { private: // Disabled Operators RobotomyRequestForm& operator=(const RobotomyRequestForm& assign); public: enum Requirement { SIGN = 72, EXEC = 45 }; // Constructors & Destructor RobotomyRequestForm(const string& target); RobotomyRequestForm(const RobotomyRequestForm& other); ~RobotomyRequestForm(); // Overrided Abstract Methods void formAction() const; }; #endif // __ROBOTOMYREQUESTFORM_H__
23.913043
68
0.767273
9e51862fa22a4663a14bf23659084d2a25b8fc92
1,074
cpp
C++
solutions/LeetCode/C++/205.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
854
2018-11-09T08:06:16.000Z
2022-03-31T06:05:53.000Z
solutions/LeetCode/C++/205.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
29
2019-06-02T05:02:25.000Z
2021-11-15T04:09:37.000Z
solutions/LeetCode/C++/205.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
347
2018-12-23T01:57:37.000Z
2022-03-12T14:51:21.000Z
__________________________________________________________________________________________________ sample 4 ms submission static int lambda_0 = []() { std::ios::sync_with_stdio(false); cin.tie(NULL); return 0; }(); class Solution { public: bool isIsomorphic(string s, string t) { int m1[256] ={0}, m2[256] = {0}; for(int i = 0; i < s.size(); i ++) { if (m1[s[i]] != m2[t[i]]) return false; m1[s[i]] = i + 1; m2[t[i]] = i + 1; } return true; } }; __________________________________________________________________________________________________ sample 8612 kb submission class Solution { public: bool isIsomorphic(string s, string t) { int m1[256]={0}; int m2[256]={0}; for(int i=0;i<s.size();++i){ if(m1[s[i]]!=m2[t[i]])return false; m1[s[i]]=i+1; m2[t[i]]=i+1; } return true; } }; __________________________________________________________________________________________________
30.685714
98
0.597765
9e56615e2ffd44d3ff32857a39c631984255f628
8,484
cp
C++
Linux/Sources/Application/Calendar/Calendar_View/Free_Busy_View/CFreeBusyTable.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
12
2015-04-21T16:10:43.000Z
2021-11-05T13:41:46.000Z
Linux/Sources/Application/Calendar/Calendar_View/Free_Busy_View/CFreeBusyTable.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
2
2015-11-02T13:32:11.000Z
2019-07-10T21:11:21.000Z
Linux/Sources/Application/Calendar/Calendar_View/Free_Busy_View/CFreeBusyTable.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
6
2015-01-12T08:49:12.000Z
2021-03-27T09:11:10.000Z
/* Copyright (c) 2007-2009 Cyrus Daboo. 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 "CFreeBusyTable.h" #include "CCalendarUtils.h" #include "CCommands.h" #include "CFreeBusyTitleTable.h" #include "CMulberryCommon.h" #include "CPreferences.h" #include "CXStringResources.h" #include "CICalendarLocale.h" #include "StPenState.h" #include <UNX_LTableMultiGeometry.h> #include <JPainter.h> #include <JXColormap.h> #include <JXTextMenu.h> #include <JXScrollbar.h> #include <JXScrollbarSet.h> #include <algorithm> const uint32_t cRowHeight = 24; const uint32_t cNameColumnWidth = 128; const uint32_t cHourColumnWidth = 96; const uint32_t cNameColumn = 1; const uint32_t cFirstTimedColumn = 2; // --------------------------------------------------------------------------- // CFreeBusyTable [public] /** Default constructor */ CFreeBusyTable::CFreeBusyTable(JXScrollbarSet* scrollbarSet, JXContainer* enclosure, const HSizingOption hSizing, const VSizingOption vSizing, const JCoordinate x, const JCoordinate y, const JCoordinate w, const JCoordinate h) : CCalendarEventTableBase(scrollbarSet, enclosure, hSizing, vSizing, x, y, w, h) { mTitles = NULL; mScaleColumns = 0; mStartHour = 0; mEndHour = 24; mTableGeometry = new LTableMultiGeometry(this, 128, 24); } // --------------------------------------------------------------------------- // ~CFreeBusyTable [public] /** Destructor */ CFreeBusyTable::~CFreeBusyTable() { } #pragma mark - void CFreeBusyTable::OnCreate() { // Call inherited CCalendarEventTableBase::OnCreate(); InsertCols(1, 1, NULL); InsertRows(1, 1, NULL); SetRowHeight(cRowHeight, 1, 1); SetColWidth(cNameColumnWidth, 1, 1); itsScrollbarSet->GetHScrollbar()->SetStepSize(cHourColumnWidth); itsScrollbarSet->GetVScrollbar()->SetStepSize(cRowHeight); CreateContextMenu(CMainMenu::eContextCalendarEventTable); ApertureResized(0, 0); } void CFreeBusyTable::DrawCellRange(JPainter* pDC, const STableCell& inTopLeftCell, const STableCell& inBottomRightCell) { STableCell cell; for ( cell.row = inTopLeftCell.row; cell.row <= inBottomRightCell.row; cell.row++ ) { // Draw entire row JRect rowRect; GetLocalCellRect(STableCell(cell.row, 2), rowRect); JRect cellRect; GetLocalCellRect(STableCell(cell.row, mCols), cellRect); rowRect.right = cellRect.right; DrawRow(pDC, cell.row, rowRect); for ( cell.col = inTopLeftCell.col; cell.col <= inBottomRightCell.col; cell.col++ ) { JRect cellRect; GetLocalCellRect(cell, cellRect); DrawCell(pDC, cell, cellRect); } } } void CFreeBusyTable::DrawRow(JPainter* pDC, TableIndexT row, const JRect& inLocalRect) { StPenState save(pDC); JRect adjustedRect = inLocalRect; adjustedRect.Shrink(0, 3); float total_width = adjustedRect.width(); const SFreeBusyInfo& info = mItems.at(row - 1); JRect itemRect = adjustedRect; for(std::vector<SFreeBusyInfo::SFreeBusyPeriod>::const_iterator iter = info.mPeriods.begin(); iter != info.mPeriods.end(); iter++) { // Adjust for current width itemRect.right = itemRect.left + total_width * ((float) (*iter).second / (float)mColumnSeconds); itemRect.Shrink(1, 0); // Red for busy, green for free, blue for tentative, grey for unavailable float red = 0.0; float green = 0.0; float blue = 0.0; switch((*iter).first) { case iCal::CICalendarFreeBusy::eFree: green = 1.0; break; case iCal::CICalendarFreeBusy::eBusyTentative: blue = 1.0; break; case iCal::CICalendarFreeBusy::eBusyUnavailable: red = 0.25; green = 0.25; blue = 0.25; break; case iCal::CICalendarFreeBusy::eBusy: red = 1.0; break; } CCalendarUtils::LightenColours(red, green, blue); // Draw it JColorIndex cindex; GetColormap()->JColormap::AllocateStaticColor(CCalendarUtils::GetRGBColor(red, green, blue), &cindex); pDC->SetPenColor(cindex); pDC->SetFilling(kTrue); pDC->Rect(itemRect); pDC->SetFilling(kFalse); GetColormap()->JColormap::AllocateStaticColor(CCalendarUtils::GetRGBColor(red * 0.6, green * 0.6, blue * 0.6), &cindex); pDC->SetPenColor(cindex); pDC->Rect(itemRect); // Now adjust for next one itemRect.left += itemRect.width() + 1; itemRect.right = itemRect.left + adjustedRect.right - itemRect.left; } } void CFreeBusyTable::DrawCell(JPainter* pDC, const STableCell& inCell, const JRect& inLocalRect) { StPenState save(pDC); JRect adjustedRect = inLocalRect; JColorIndex cindex; // Left-side always { JColorIndex old_cindex = pDC->GetPenColor(); GetColormap()->JColormap::AllocateStaticColor( CCalendarUtils::GetGreyColor((inCell.col > 2) ? 0.75 : 0.5), &cindex); pDC->SetPenColor(cindex); pDC->Line(adjustedRect.left, adjustedRect.top, adjustedRect.left, adjustedRect.bottom); pDC->SetPenColor(old_cindex); } // Right-side only for last column if (inCell.col == mCols) { JColorIndex old_cindex = pDC->GetPenColor(); GetColormap()->JColormap::AllocateStaticColor(CCalendarUtils::GetGreyColor(0.5), &cindex); pDC->SetPenColor(cindex); pDC->Line(adjustedRect.right, adjustedRect.top, adjustedRect.right, adjustedRect.bottom); pDC->SetPenColor(old_cindex); } // Top-side always (lighter line above half-hour row) { JColorIndex old_cindex = pDC->GetPenColor(); GetColormap()->JColormap::AllocateStaticColor(CCalendarUtils::GetGreyColor(0.5), &cindex); pDC->SetPenColor(cindex); pDC->Line(adjustedRect.left, adjustedRect.top, adjustedRect.right, adjustedRect.top); pDC->SetPenColor(old_cindex); } // Bottom-side for last row if (inCell.row == mRows) { JColorIndex old_cindex = pDC->GetPenColor(); GetColormap()->JColormap::AllocateStaticColor(CCalendarUtils::GetGreyColor(0.5), &cindex); pDC->SetPenColor(cindex); pDC->Line(adjustedRect.left, adjustedRect.bottom, adjustedRect.right, adjustedRect.bottom); pDC->SetPenColor(old_cindex); } adjustedRect.Shrink(2, 0); if (inCell.col == 1) { cdstring name = mItems.at(inCell.row - 1).mName; pDC->SetPenColor(GetColormap()->GetBlackColor()); JRect clipRect(adjustedRect); clipRect.Shrink(0, 1); clipRect.right += 2; ::DrawClippedStringUTF8(pDC, name, JPoint(adjustedRect.left, adjustedRect.top), clipRect, eDrawString_Right); } } void CFreeBusyTable::RefreshNow() { // Redraw - double-buffering removes any flashing FRAMEWORK_REFRESH_WINDOW(this) } void CFreeBusyTable::ApertureResized(const JCoordinate dw, const JCoordinate dh) { // Allow frame adapter to adjust size CCalendarEventTableBase::ApertureResized(dw, dh); // Look for change in image size UInt32 old_width, old_height; mTableGeometry->GetTableDimensions(old_width, old_height); // If auto-fit rows, change row height RescaleWidth(); itsScrollbarSet->GetHScrollbar()->SetStepSize(GetColWidth(cFirstTimedColumn)); itsScrollbarSet->GetVScrollbar()->SetStepSize(cRowHeight); UInt32 new_width, new_height; mTableGeometry->GetTableDimensions(new_width, new_height); if (mTitles) mTitles->TableChanged(); } void CFreeBusyTable::RescaleWidth() { // If auto-fit rows, change row height if (mScaleColumns == 0) { JRect my_frame = GetFrameGlobal(); if (mCols > 1) { SInt32 col_size = std::max((SInt32) ((my_frame.width() - GetColWidth(cNameColumn)) / (mCols - 1)), 8L); SetColWidth(col_size, cFirstTimedColumn, mCols); } } } // Keep titles in sync void CFreeBusyTable::ScrollImageBy(SInt32 inLeftDelta, SInt32 inTopDelta, bool inRefresh) { // Find titles in owner chain if (mTitles) mTitles->ScrollImageBy(inLeftDelta, 0, inRefresh); CTableDrag::ScrollImageBy(inLeftDelta, inTopDelta, inRefresh); } void CFreeBusyTable::ScaleColumns(uint32_t scale) { if (scale != mScaleColumns) { mScaleColumns = scale; if (mScaleColumns > 0) SetColWidth(cHourColumnWidth / mScaleColumns, cFirstTimedColumn, mCols); else { RescaleWidth(); } } }
26.933333
131
0.709335
9e598ab89a764c1ec62524703ed3067e2692fd1f
1,497
hh
C++
src/physics/JointFeedback.hh
nherment/gazebo
fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a
[ "ECL-2.0", "Apache-2.0" ]
5
2016-01-17T20:41:39.000Z
2018-05-01T12:02:58.000Z
src/physics/JointFeedback.hh
nherment/gazebo
fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/physics/JointFeedback.hh
nherment/gazebo
fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a
[ "ECL-2.0", "Apache-2.0" ]
5
2015-09-29T02:30:16.000Z
2022-03-30T12:11:22.000Z
/* * Copyright 2011 Nate Koenig & Andrew Howard * * 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. * */ /* Desc: Specification of a contact * Author: Nate Koenig * Date: 10 Nov 2009 */ #ifndef JOINTFEEDBACK_HH #define JOINTFEEDBACK_HH #include "math/Vector3.hh" namespace gazebo { namespace physics { /// \addtogroup gazebo_physics /// \{ /// \brief Feedback information from a joint class JointFeedback { /// \brief Operator = public: JointFeedback &operator =(const JointFeedback &f) { this->body1Force = f.body1Force; this->body2Force = f.body2Force; this->body1Torque = f.body1Torque; this->body2Torque = f.body2Torque; return *this; } public: math::Vector3 body1Force; public: math::Vector3 body2Force; public: math::Vector3 body1Torque; public: math::Vector3 body2Torque; }; /// \} } } #endif
25.372881
75
0.645291
9e5a23f8dff7b1550221b4624d554fa2a046fab9
400
cpp
C++
test/unit/math/prim/prob/bernoulli_ccdf_log_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
1
2020-06-14T14:33:37.000Z
2020-06-14T14:33:37.000Z
test/unit/math/prim/prob/bernoulli_ccdf_log_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
2
2019-07-23T12:45:30.000Z
2020-05-01T20:43:03.000Z
test/unit/math/prim/prob/bernoulli_ccdf_log_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
1
2020-05-10T12:55:07.000Z
2020-05-10T12:55:07.000Z
#include <stan/math/prim.hpp> #include <gtest/gtest.h> TEST(ProbBernoulli, ccdf_log_matches_lccdf) { int n = 1; double theta = 0.3; EXPECT_FLOAT_EQ((stan::math::bernoulli_lccdf(n, theta)), (stan::math::bernoulli_ccdf_log(n, theta))); EXPECT_FLOAT_EQ((stan::math::bernoulli_lccdf<double>(n, theta)), (stan::math::bernoulli_ccdf_log<double>(n, theta))); }
30.769231
70
0.6525
9e5a44e311b394c612d80c73766e978ebcbf9759
5,009
hpp
C++
Linux/Ubuntu/64bit/AVAPI/Avapi/TECHNICAL_INDICATOR/AROONOSC.hpp
AvapiDotNet/AvapiCpp
2157ccbe750cac077098a6f1aa401d80fc943ff5
[ "MIT" ]
15
2018-01-31T16:58:36.000Z
2021-08-19T21:37:08.000Z
Linux/Ubuntu/64bit/AVAPI/Avapi/TECHNICAL_INDICATOR/AROONOSC.hpp
AvapiDotNet/AvapiCpp
2157ccbe750cac077098a6f1aa401d80fc943ff5
[ "MIT" ]
null
null
null
Linux/Ubuntu/64bit/AVAPI/Avapi/TECHNICAL_INDICATOR/AROONOSC.hpp
AvapiDotNet/AvapiCpp
2157ccbe750cac077098a6f1aa401d80fc943ff5
[ "MIT" ]
4
2018-01-31T17:06:26.000Z
2020-05-03T20:59:27.000Z
#ifndef AROONOSC_HPP_INCLUDED #define AROONOSC_HPP_INCLUDED #include <string> #include <map> #include <list> #include "../jsmn/jsmn.h" using namespace std; namespace Avapi { class RestClient; //forward declaration enum class Const_AROONOSC_interval{ none, n_1min, n_5min, n_15min, n_30min, n_60min, daily, weekly, monthly, }; class MAP_AROONOSC { public: static const map<Const_AROONOSC_interval, string> s_interval_translation; }; class MetaData_Type_AROONOSC { private: string Symbol; string Indicator; string LastRefreshed; string Interval; string TimePeriod; string TimeZone; public: MetaData_Type_AROONOSC(); MetaData_Type_AROONOSC(const MetaData_Type_AROONOSC& other); // copy constructor string get_Symbol() const {return Symbol;}; string get_Indicator() const {return Indicator;}; string get_LastRefreshed() const {return LastRefreshed;}; string get_Interval() const {return Interval;}; string get_TimePeriod() const {return TimePeriod;}; string get_TimeZone() const {return TimeZone;}; void set_Symbol(string Symbol){this->Symbol = Symbol;}; void set_Indicator(string Indicator){this->Indicator = Indicator;}; void set_LastRefreshed(string LastRefreshed){this->LastRefreshed = LastRefreshed;}; void set_Interval(string Interval){this->Interval = Interval;}; void set_TimePeriod(string TimePeriod){this->TimePeriod = TimePeriod;}; void set_TimeZone(string TimeZone){this->TimeZone = TimeZone;}; int ParseInternal(string& str_data, jsmntok_t* array_token ,int index, int token_size); }; class TechnicalIndicator_Type_AROONOSC { private: string AROONOSC; string DateTime; public: TechnicalIndicator_Type_AROONOSC(); TechnicalIndicator_Type_AROONOSC(const TechnicalIndicator_Type_AROONOSC& other); // copy constructor string get_AROONOSC() const {return AROONOSC;}; string get_DateTime() const {return DateTime;}; void set_AROONOSC(string AROONOSC){this->AROONOSC = AROONOSC;}; void set_DateTime(string DateTime){this->DateTime = DateTime;}; int ParseInternal(string& str_data, jsmntok_t* array_token, int index, int token_size); }; class AvapiResponse_AROONOSC_Content { private: MetaData_Type_AROONOSC MetaData; list<TechnicalIndicator_Type_AROONOSC> TechnicalIndicator; string str_prefix; bool error_status; string ErrorMessage; public: AvapiResponse_AROONOSC_Content(); ~AvapiResponse_AROONOSC_Content() {}; AvapiResponse_AROONOSC_Content(const AvapiResponse_AROONOSC_Content& other); // copy constructor MetaData_Type_AROONOSC& get_MetaData() {return MetaData;}; list<TechnicalIndicator_Type_AROONOSC>& get_TechnicalIndicator() {return TechnicalIndicator;}; void set_Error(bool error_status) {this->error_status = error_status;}; bool isError() {return error_status;}; string get_ErrorMessage() {return ErrorMessage;}; void set_ErrorMessage(string ErrorMessage) {this->ErrorMessage = str_prefix + ErrorMessage;}; }; class AvapiResponse_AROONOSC { private: string LastHttpRequest; string RawData; AvapiResponse_AROONOSC_Content* Data; public: AvapiResponse_AROONOSC(); AvapiResponse_AROONOSC(const AvapiResponse_AROONOSC& other); // copy constructor AvapiResponse_AROONOSC(AvapiResponse_AROONOSC&& other); // move constructor AvapiResponse_AROONOSC& operator=(const AvapiResponse_AROONOSC& other); //copy assignment AvapiResponse_AROONOSC& operator=(AvapiResponse_AROONOSC&& other); //move assignment ~AvapiResponse_AROONOSC(); AvapiResponse_AROONOSC_Content& get_Data() const {return *Data;}; string get_LastHttpRequest() const {return LastHttpRequest;}; string get_RawData() const {return RawData;}; void set_LastHttpRequest(string LastHttpRequest){this->LastHttpRequest = LastHttpRequest;}; void set_RawData(string RawData){this->RawData = RawData;}; }; class Impl_AROONOSC { private: string AvapiUrl; string ApiKey; RestClient *Client; static string s_function; static Impl_AROONOSC *s_instance; Impl_AROONOSC() {}; static const unsigned int START_TOKEN_SIZE = 3000; static void ParseInternal(AvapiResponse_AROONOSC& Response); public: static Impl_AROONOSC& getInstance(); static void destroyInstance(); string get_AvapiUrl() const {return AvapiUrl;}; RestClient* get_Client() const {return Client;}; string get_ApiKey() const {return ApiKey;}; void set_AvapiUrl(string AvapiUrl){this->AvapiUrl = AvapiUrl;}; void set_Client(RestClient *Client){this->Client = Client;}; void set_ApiKey(string ApiKey){this->ApiKey = ApiKey;}; AvapiResponse_AROONOSC Query(string symbol ,Const_AROONOSC_interval interval ,string time_period ); AvapiResponse_AROONOSC Query(string symbol ,string interval ,string time_period ); }; }//end namespace Avapi #endif // AROONOSC_HPP_INCLUDED
31.111801
104
0.743262
9e5d618715c325995cc920febbce9c21e04c9062
2,489
cpp
C++
code/tests/glx/src/main.cpp
BrightComposite/RaptureStateToolkit
6eb3c831540ba6a9d29e903dd3c537aac2e7f91f
[ "MIT" ]
null
null
null
code/tests/glx/src/main.cpp
BrightComposite/RaptureStateToolkit
6eb3c831540ba6a9d29e903dd3c537aac2e7f91f
[ "MIT" ]
null
null
null
code/tests/glx/src/main.cpp
BrightComposite/RaptureStateToolkit
6eb3c831540ba6a9d29e903dd3c537aac2e7f91f
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- #include <application/starter.h> //--------------------------------------------------------------------------- #include <X11/X.h> #include <X11/Xlib.h> #include <GL/gl.h> #include <GL/glx.h> #include <GL/glu.h> #include <iostream> //--------------------------------------------------------------------------- namespace asd { void DrawAQuad() { glClearColor(1.0, 1.0, 1.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-1., 1., -1., 1., 1., 20.); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0., 0., 10., 0., 0., 0., 0., 1., 0.); glBegin(GL_QUADS); glColor3f(1.f, 0.f, 0.f); glVertex3f(-.75f, -.75f, 0.f); glColor3f(0.f, 1.f, 0.f); glVertex3f(.75f, -.75f, 0.f); glColor3f(0.f, 0.f, 1.f); glVertex3f(.75f, .75f, 0.f); glColor3f(1.f, 1.f, 0.f); glVertex3f(-.75f, .75f, 0.f); glEnd(); } static entrance open([]() { using namespace std; auto d = XOpenDisplay(NULL); if(d == nullptr) { cout << "Cannot connect to X server" << endl; return 1; } GLint att[] = {GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None}; auto vi = glXChooseVisual(d, 0, att); if(vi == NULL) { cout << "No appropriate visual found" << endl; return 1; } auto root = DefaultRootWindow(d); XSetWindowAttributes swa; swa.colormap = XCreateColormap(d, root, vi->visual, AllocNone); swa.event_mask = ExposureMask | KeyPressMask; auto w = XCreateWindow(d, root, 0, 0, 600, 600, 0, vi->depth, InputOutput, vi->visual, CWColormap | CWEventMask, &swa); XMapWindow(d, w); XStoreName(d, w, "ASD: glxtest"); auto glc = glXCreateContext(d, vi, NULL, GL_TRUE); glXMakeCurrent(d, w, glc); glEnable(GL_DEPTH_TEST); XWindowAttributes gwa; XEvent xev; cout << "Press ESC to exit" << endl; while(1) { XNextEvent(d, &xev); if(xev.type == Expose) { XGetWindowAttributes(d, w, &gwa); glViewport(0, 0, gwa.width, gwa.height); DrawAQuad(); glXSwapBuffers(d, w); } else if(xev.type == KeyPress) { if(xev.xkey.keycode == 9) { cout << "Exit..." << endl; glXMakeCurrent(d, None, NULL); glXDestroyContext(d, glc); XDestroyWindow(d, w); XCloseDisplay(d); break; } } } return 0; }); } //---------------------------------------------------------------------------
23.261682
121
0.527923
9e5fed5b8db9931f8f0dca8131debee4179261a1
5,253
cpp
C++
tests/chain_tests/plugins/tags/get_posts_and_comments_tests.cpp
scorum/scorum
1da00651f2fa14bcf8292da34e1cbee06250ae78
[ "MIT" ]
53
2017-10-28T22:10:35.000Z
2022-02-18T02:20:48.000Z
tests/chain_tests/plugins/tags/get_posts_and_comments_tests.cpp
Scorum/Scorum
fb4aa0b0960119b97828865d7a5b4d0409af7876
[ "MIT" ]
38
2017-11-25T09:06:51.000Z
2018-10-31T09:17:22.000Z
tests/chain_tests/plugins/tags/get_posts_and_comments_tests.cpp
Scorum/Scorum
fb4aa0b0960119b97828865d7a5b4d0409af7876
[ "MIT" ]
27
2018-01-08T19:43:35.000Z
2022-01-14T10:50:42.000Z
#include <scorum/tags/tags_api_objects.hpp> #include <boost/test/unit_test.hpp> #include "tags_common.hpp" using namespace scorum; using namespace scorum::tags::api; using namespace scorum::app; using namespace scorum::tags; BOOST_FIXTURE_TEST_SUITE(get_posts_and_comments_tests, database_fixture::tags_fixture) SCORUM_TEST_CASE(check_get_posts_and_comments_contract_negative) { discussion_query q; q.limit = 101; BOOST_REQUIRE_THROW(_api.get_posts_and_comments(q), fc::assert_exception); q.limit = 100; q.start_author = "x"; BOOST_REQUIRE_THROW(_api.get_posts_and_comments(q), fc::assert_exception); q.start_author.reset(); q.start_permlink = "x"; BOOST_REQUIRE_THROW(_api.get_posts_and_comments(q), fc::assert_exception); } SCORUM_TEST_CASE(check_get_posts_and_comments_contract_positive) { discussion_query q; q.limit = 100; BOOST_REQUIRE_NO_THROW(_api.get_posts_and_comments(q)); q.start_author = "alice"; q.start_permlink = "p"; BOOST_REQUIRE_NO_THROW(_api.get_posts_and_comments(q)); } SCORUM_TEST_CASE(check_both_posts_and_comments_returned) { discussion_query q; q.limit = 100; BOOST_REQUIRE_EQUAL(_api.get_posts_and_comments(q).size(), 0u); auto p = create_post(alice).in_block(); p.create_comment(bob).in_block(); BOOST_REQUIRE_EQUAL(_api.get_posts_and_comments(q).size(), 2u); } SCORUM_TEST_CASE(check_truncate_body) { auto p = create_post(alice).set_body("1234567").in_block(); auto c = p.create_comment(bob).set_body("abcdefgh").in_block(); discussion_query q; q.limit = 100; q.truncate_body = 5; auto discussions = _api.get_posts_and_comments(q); BOOST_REQUIRE_EQUAL(discussions.size(), 2u); #ifdef IS_LOW_MEM BOOST_CHECK_EQUAL(discussions[0].body, ""); BOOST_CHECK_EQUAL(discussions[1].body, ""); BOOST_CHECK_EQUAL(discussions[0].body_length, 0u); BOOST_CHECK_EQUAL(discussions[1].body_length, 0u); #else BOOST_CHECK_EQUAL(discussions[0].body, "12345"); BOOST_CHECK_EQUAL(discussions[1].body, "abcde"); BOOST_CHECK_EQUAL(discussions[0].body_length, 7u); BOOST_CHECK_EQUAL(discussions[1].body_length, 8u); #endif } SCORUM_TEST_CASE(check_limit) { auto p = create_post(alice).in_block(); auto c1 = p.create_comment(bob).in_block(); auto c2 = c1.create_comment(sam).in_block(); discussion_query q; q.limit = 2; auto discussions = _api.get_posts_and_comments(q); BOOST_REQUIRE_EQUAL(discussions.size(), 2u); BOOST_CHECK_EQUAL(discussions[0].permlink, p.permlink()); BOOST_CHECK_EQUAL(discussions[1].permlink, c1.permlink()); } SCORUM_TEST_CASE(check_same_author_comments) { auto p = create_post(alice).in_block_with_delay(); auto c1 = p.create_comment(alice).in_block_with_delay(); c1.create_comment(alice).in_block_with_delay(); discussion_query q; q.limit = 100; auto discussions = _api.get_posts_and_comments(q); BOOST_REQUIRE_EQUAL(discussions.size(), 3u); } SCORUM_TEST_CASE(check_pagination) { /* * Heirarchy: * * alice/p1 * --bob/c1 * ----sam/c2 * ----alice/c3 * sam/p2 * --alice/c4 * --bob/c5 * * 'by_permlink' index will be sorted as follows: * 0. alice/c3 * 1. alice/c4 * 2. alice/p1 * 3. bob/c1 * 4. bob/c5 * 5. sam/c2 * 6. sam/p2 */ auto p1 = create_post(alice).set_permlink("p1").in_block_with_delay(); auto c1 = p1.create_comment(bob).set_permlink("c1").in_block_with_delay(); auto c2 = c1.create_comment(sam).set_permlink("c2").in_block_with_delay(); auto c3 = c1.create_comment(alice).set_permlink("c3").in_block_with_delay(); auto p2 = create_post(sam).set_permlink("p2").in_block_with_delay(); auto c4 = p2.create_comment(alice).set_permlink("c4").in_block_with_delay(); auto c5 = p2.create_comment(bob).set_permlink("c5").in_block_with_delay(); discussion_query q; q.limit = 4; { auto discussions = _api.get_posts_and_comments(q); BOOST_REQUIRE_EQUAL(discussions.size(), 4u); BOOST_CHECK_EQUAL(discussions[0].permlink, c3.permlink()); BOOST_CHECK_EQUAL(discussions[1].permlink, c4.permlink()); BOOST_CHECK_EQUAL(discussions[2].permlink, p1.permlink()); BOOST_CHECK_EQUAL(discussions[3].permlink, c1.permlink()); } { q.start_author = p1.author(); q.start_permlink = p1.permlink(); q.limit = 3u; auto discussions = _api.get_posts_and_comments(q); BOOST_REQUIRE_EQUAL(discussions.size(), 3u); BOOST_CHECK_EQUAL(discussions[0].permlink, p1.permlink()); BOOST_CHECK_EQUAL(discussions[1].permlink, c1.permlink()); BOOST_CHECK_EQUAL(discussions[2].permlink, c5.permlink()); } { q.start_author = c5.author(); q.start_permlink = c5.permlink(); q.limit = 4u; auto discussions = _api.get_posts_and_comments(q); BOOST_REQUIRE_EQUAL(discussions.size(), 3u); BOOST_CHECK_EQUAL(discussions[0].permlink, c5.permlink()); BOOST_CHECK_EQUAL(discussions[1].permlink, c2.permlink()); BOOST_CHECK_EQUAL(discussions[2].permlink, p2.permlink()); } } BOOST_AUTO_TEST_SUITE_END()
31.08284
86
0.695031
9e618b77758ee753e3d33f0beaf5ff8aa3b9b031
614
cpp
C++
esp32/examples/ttgo_demo/main/system.cpp
joachimBurket/esp32-opencv
f485b59d7b43b0a2f77a5ab547e2597929f7094a
[ "BSD-3-Clause" ]
56
2020-03-24T15:17:56.000Z
2022-03-21T13:44:08.000Z
esp32/examples/ttgo_demo/main/system.cpp
0015/esp32-opencv
f485b59d7b43b0a2f77a5ab547e2597929f7094a
[ "BSD-3-Clause" ]
6
2021-03-08T13:41:24.000Z
2022-02-19T08:10:24.000Z
esp32/examples/ttgo_demo/main/system.cpp
0015/esp32-opencv
f485b59d7b43b0a2f77a5ab547e2597929f7094a
[ "BSD-3-Clause" ]
15
2020-05-06T13:41:20.000Z
2022-03-31T19:15:47.000Z
#include <esp_log.h> #include <esp_system.h> #include <sdkconfig.h> #include <freertos/FreeRTOS.h> #include <freertos/task.h> #include <sys/param.h> #include <esp32/clk.h> #include "system.h" #define TAG "SYSTEM" void wait_msec(uint16_t v) { vTaskDelay(v / portTICK_PERIOD_MS); } void wait_sec(uint16_t v) { vTaskDelay(v * 1000 / portTICK_PERIOD_MS); } void disp_infos() { /* Print memory information */ ESP_LOGI(TAG, "task %s stack high watermark: %d Bytes", pcTaskGetTaskName(NULL), uxTaskGetStackHighWaterMark(NULL)); ESP_LOGI(TAG, "heap left: %d Bytes", esp_get_free_heap_size()); }
21.928571
120
0.708469
9e622fd05f2006fc419715ae76d2647f62cbab3c
1,907
hpp
C++
include/vheis/geodesic-growth.hpp
alexbishop/Virtually-Abelian
4f19bf39e664a6ae51ef0c7f011e2fede7762d0c
[ "MIT" ]
null
null
null
include/vheis/geodesic-growth.hpp
alexbishop/Virtually-Abelian
4f19bf39e664a6ae51ef0c7f011e2fede7762d0c
[ "MIT" ]
null
null
null
include/vheis/geodesic-growth.hpp
alexbishop/Virtually-Abelian
4f19bf39e664a6ae51ef0c7f011e2fede7762d0c
[ "MIT" ]
null
null
null
#pragma once #include <map> #include <utility> #include <vector> #include "SafeInt.hpp" namespace vheis { template <class Group> class geodesic_growth { public: template <class Vector> explicit geodesic_growth(Vector g_set); template <class Iterator> explicit geodesic_growth(Iterator begin, Iterator end); std::pair<SafeInt<int>, SafeInt<unsigned long long>> next(); private: SafeInt<int> current_size; SafeInt<unsigned long long> running_total; std::vector<Group> g_set; std::map<Group, SafeInt<unsigned long long>> sphere_0; std::map<Group, SafeInt<unsigned long long>> sphere_1; std::map<Group, SafeInt<unsigned long long>> sphere_2; }; }; // namespace vheis // Implementation namespace vheis { template <class Group> template <class Vector> geodesic_growth<Group>::geodesic_growth(Vector g_set) : geodesic_growth(g_set.begin(), g_set.end()) {} template <class Group> template <class Iterator> geodesic_growth<Group>::geodesic_growth(Iterator begin, Iterator end) : g_set(begin, end), running_total(0), current_size(-1) {} template <class Group> std::pair<SafeInt<int>, SafeInt<unsigned long long>> geodesic_growth<Group>::next() { if (current_size < 0) { Group identity; sphere_0[identity] = 1ull; current_size = 0; running_total = 1ull; return std::make_pair(current_size, running_total); } sphere_2 = std::move(sphere_1); sphere_1 = std::move(sphere_0); sphere_0 = std::map<Group, SafeInt<unsigned long long>>(); for (const auto& [element, count] : sphere_1) { for (auto& g : g_set) { const auto next_element = element * g; if (sphere_1.count(next_element) == 0 && sphere_2.count(next_element) == 0) { sphere_0[next_element] += count; running_total += count; } } } ++current_size; return std::make_pair(current_size, running_total); } } // namespace vheis
23.54321
69
0.694284