blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
6
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
26
license_type
stringclasses
2 values
repo_name
stringlengths
7
95
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
57 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
197k
639M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
11 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
34 values
src_encoding
stringclasses
18 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
11
9.86M
extension
stringclasses
27 values
content
stringlengths
11
9.86M
authors
listlengths
1
1
author
stringlengths
0
70
28ccee844626dc8f532b974e14b830d2f77d8276
fce00ed7da745340691c8c6cf47905ba4fe5a08e
/UchClient/FrmMain.cpp
632d7a2b262d04091ced8c1a66af203405b47a34
[ "Unlicense" ]
permissive
EAirPeter/Uch
bc9bae801721a9241afbfe8add293cf5dcf7a322
193ee52fb98d2d224cd22483b2523caf02805cfe
refs/heads/master
2021-07-24T15:06:17.555444
2017-11-05T14:25:50
2017-11-05T14:25:50
109,581,211
0
0
null
null
null
null
UTF-8
C++
false
false
6,153
cpp
#include "Common.hpp" #include "FrmFileRecv.hpp" #include "FrmFileSend.hpp" #include "FrmMain.hpp" #include "Ucl.hpp" #include <nana/gui/filebox.hpp> using namespace nana; FrmMain::FrmMain() : form(nullptr, {768, 480}, appear::decorate< appear::taskbar, appear::minimize, appear::maximize, appear::sizable >()) { caption(Title(L"Client")); events().destroy(std::bind(&FrmMain::X_OnDestroy, this, std::placeholders::_1)); events().user(std::bind(&FrmMain::X_OnUser, this, std::placeholders::_1)); events().unload([this] (const arg_unload &e) { msgbox mbx {nullptr, TitleU8(L"Exit"), msgbox::yes_no}; mbx.icon(msgbox::icon_question); mbx << L"Are you sure to exit Uch?"; if (mbx() != mbx.pick_yes) e.cancel = true; }); x_btnSend.caption(L"Send"); x_btnSend.events().click(std::bind(&FrmMain::X_OnSend, this)); x_btnSend.events().key_press([this] (const arg_keyboard &e) { if (e.key == keyboard::enter) X_OnSend(); }); x_btnFile.caption(L"Send File"); x_btnFile.events().click(std::bind(&FrmMain::X_OnFile, this)); x_btnFile.events().key_press([this] (const arg_keyboard &e) { if (e.key == keyboard::enter) X_OnFile(); }); x_btnExit.caption(L"Exit"); x_btnExit.events().click(std::bind(&FrmMain::close, this)); x_btnExit.events().key_press([this] (const arg_keyboard &e) { if (e.key == keyboard::enter) close(); }); x_txtMessage.multi_lines(false).tip_string(u8"Message:"); x_txtMessage.events().focus([this] (const arg_focus &e) { x_txtMessage.select(e.getting); }); x_txtMessage.events().key_press([this] (const arg_keyboard &e) { if (e.key == keyboard::enter) X_OnSend(); }); x_lbxUsers.enable_single(true, false); x_lbxUsers.append_header(L"Who", 110); x_lbxUsers.append({L"Online", L"Offline"}); x_lbxMessages.sortable(false); x_lbxMessages.append_header(L"When", 80); x_lbxMessages.append_header(L"How", 180); x_lbxMessages.append_header(L"What", 310); x_pl.div( "margin=[14,16]" " <weight=120 List> <weight=8>" " <vert" " <Msgs> <weight=7>" " <weight=25 Imsg> <weight=7>" " <weight=25 <> <weight=259 gap=8 Btns>>" " >" ); x_pl["List"] << x_lbxUsers; x_pl["Msgs"] << x_lbxMessages; x_pl["Imsg"] << x_txtMessage; x_pl["Btns"] << x_btnExit << x_btnFile << x_btnSend; x_pl.collocate(); Ucl::Bus().Register(*this); } void FrmMain::OnEvent(event::EvMessage &e) noexcept { constexpr static auto kszFmt = L"(%s) %s => %s"; x_lbxMessages.at(0).append({ FormattedTime(), FormatString(L"(%s) %s => %s", e.sCat.c_str(), e.sFrom.c_str(), e.sTo.c_str()), e.sWhat }); x_lbxMessages.scroll(true); } void FrmMain::OnEvent(event::EvListUon &e) noexcept { x_lbxUsers.at(1).model<std::recursive_mutex>( e.vecUon, [] (auto &c) { return AsWideString(c.front().text); }, [] (auto &s) { return std::vector<listbox::cell> {AsUtf8String(s)}; } ); } void FrmMain::OnEvent(event::EvListUff &e) noexcept { x_lbxUsers.at(2).model<std::recursive_mutex>( e.vecUff, [] (auto &c) { return AsWideString(c.front().text); }, [] (auto &s) { return std::vector<listbox::cell> {AsUtf8String(s)}; } ); } void FrmMain::OnEvent(event::EvFileReq &e) noexcept { user(std::make_unique<event::EvFileReq>(e).release()); } void FrmMain::X_OnSend() { auto vec = x_lbxUsers.selected(); if (vec.empty()) { msgbox mbx {nullptr, TitleU8(L"Send message"), msgbox::ok}; mbx.icon(msgbox::icon_error); mbx << L"Please select a recipient"; mbx(); return; } auto &idx = vec.front(); auto sUser = AsWideString(x_lbxUsers.at(idx.cat).at(idx.item).text(0)); switch (idx.cat) { case 1: // Online X_AddMessage({kszCatChat, kszSelf, sUser, x_txtMessage.caption_wstring()}); (*Ucl::Pmg())[sUser].PostPacket(protocol::EvpMessage { x_txtMessage.caption_wstring() }); break; case 2: // Offline X_AddMessage({kszCatFmsg, kszSelf, sUser, x_txtMessage.caption_wstring()}); Ucl::Con()->PostPacket(protocol::EvcMessageTo { sUser, x_txtMessage.caption_wstring() }); break; default: throw ExnIllegalState {}; } x_txtMessage.caption(String {}); } void FrmMain::X_OnFile() { auto vec = x_lbxUsers.selected(); if (vec.empty()) { msgbox mbx {TitleU8(L"Send file")}; mbx.icon(msgbox::icon_error); mbx << L"Please select a recipient"; mbx(); return; } auto &idx = vec.front(); if (idx.cat != 1) { msgbox mbx {TitleU8(L"Send file")}; mbx.icon(msgbox::icon_error); mbx << L"Please select an online user"; mbx(); return; } auto sUser = AsWideString(x_lbxUsers.at(idx.cat).at(idx.item).text(0)); filebox fbx {nullptr, true}; if (!fbx()) return; auto sPath = AsWideString(fbx.file()); UccPipl *pPipl; try { pPipl = &(*Ucl::Pmg())[sUser]; } catch (std::out_of_range) { msgbox mbx {TitleU8(L"Send file")}; mbx << L"The user if offline"; mbx(); return; } form_loader<FrmFileSend>() (*this, pPipl, sPath).show(); } void FrmMain::X_OnDestroy(const nana::arg_destroy &e) { Ucl::Con()->PostPacket(protocol::EvcExit {Ucl::Usr()}); Ucl::Con()->Shutdown(); Ucl::Pmg()->Shutdown(); Ucl::Bus().Unregister(*this); } void FrmMain::X_OnUser(const nana::arg_user &e) { std::unique_ptr<event::EvFileReq> up { reinterpret_cast<event::EvFileReq *>(e.param) }; try { form_loader<FrmFileRecv>() (*this, up->pPipl, up->eReq).show(); } catch (ExnIllegalState) {} } void FrmMain::X_AddMessage(event::EvMessage &&e) noexcept { OnEvent(e); }
[ "VioletCrestfall@hotmail.com" ]
VioletCrestfall@hotmail.com
41411ede81a3f14d5f5efda3aad396093d6910f8
16337b0d88df96767281cbc0024ed4e5e0dc2309
/Tic-Tac-bigToe.cpp
ccd6f979a725f324386a94cc966771516cbbf2ac
[]
no_license
Xephoney/Tic-Tac-bigToe
8c3c5d93a5f49799d90034a428a61d509b672883
3ea53e4f72486c476eb673a8f1736b24f3f5442c
refs/heads/master
2022-12-24T15:47:03.404365
2020-09-27T19:22:51
2020-09-27T19:22:51
298,370,665
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
12,368
cpp
#include <iostream> #include <string> #include <vector> //This is included for the use of vectors #include <time.h> //This is for random number generation //Here we declare the functions that i will define further down. //these functions are tied to the gameplay loop void DisplayGrid(); void InputAndExec(); void PlayerSwitch(); int WinConditionCheck(); void CalculateComputerMove(char); //These are the main functions between games. void GamePvP(); void GamePvE(); void MainMenu(); //The reason i went with global variables was to limit the amount of calls, and passing variables to functions and getting... //the right return variables. Only the important variables are global. std::vector<char> grid { '1','2','3','4','5','6','7','8','9' }; char players[2] { 'X', 'O' }; int playerIndex = 1; int main() { srand(time(NULL)); //Greeting when first running the application std::cout << "Welcome to Tic-Tac-(Big)Toe \n"; MainMenu(); return 0; } void MainMenu() { int answer = NULL; std::cout << "What would you like to play? \n"; std::cout << " 1 : Player VS Player \n" << " 2 : Player VS CPU \n \n" << " 8 : Exit Game \n"; std::cout << "Select a gamemode : "; std::cin >> answer; //here we do the corresponding code execution based on what the user typed in. // I wanted to avoid using a while loop here, because of the thought that it would be a loop, in a loop, in a loop... for ever. // So instead i just kept to Functions executions. // I don't know for sure whether this is the best solution or not, but it works! :D //Here i get then input from the player and execute the right code that was selected from the player. switch (answer) { case 0: //I have to include cin.clear and cin.ignore before calling MainMenu() again, to stop it from looping forever. system("CLS"); std::cin.clear(); std::cin.ignore(10000, '\n'); MainMenu(); break; case 1: system("CLS"); GamePvP(); break; case 2: system("CLS"); GamePvE(); break; case 8: std::cout << "Closing Game"; return; default: //I have to include cin.clear and cin.ignore before calling MainMenu() again, to stop it from looping forever. system("CLS"); std::cin.clear(); std::cin.ignore(10000, '\n'); MainMenu(); break; } } int moves = 0; void GamePvP() { playerIndex = 0; bool GameOver = false; moves = 0; //The reason why i fill out the grid here, is because everytime the game restarts... //I need to make sure its a new grid. so it clears the board from the last game. grid = { '1', '2', '3', '4', '5', '6', '7', '8', '9' }; do { //as the functions says it displays the grid. DisplayGrid(); //This is for getting input, aswell as InputAndExec(); //Here i run the Win Condition function and store the result of that test in my X variable. //Then we proceed to check weather that the winner was either X or O. int x = WinConditionCheck(); if (x == 0 || x == 1) { //The reason for Display Grid is just to update the display so you could see where the //Where the winning connections were! DisplayGrid(); std::cout << "\nPlayer " << players[x] << " wins! Congrats! \n"; GameOver = true; system("pause"); } //I keep a count of the total amount of moves. and if the total number of moves is 9, and wincheck returns false. then it has to be a tie. else if (moves == 9) { //Tie DisplayGrid(); std::cout << "\n [- TIE -] \n"; GameOver = true; system("pause"); } } while (!GameOver); //Clears screen and returns to Main Menu system("CLS"); MainMenu(); } void GamePvE() { playerIndex = 0; bool GameOver = false; moves = 0; grid = { '1', '2', '3', '4', '5', '6', '7', '8', '9' }; char answer = 'æ'; int computer = -1; int player = -1; std::cout << "Do you want to be X or O? \n "; std::cout << "X / O : "; std::cin >> answer; answer = toupper(answer); //This is just to make sure that the input is a Char value. //Initial game setup. The player selects their desigered and the cpu gets if (answer == players[0]) { computer = 1; player = 0; std::cout << "Okay, You = X CPU = O \n When you are ready "; } else if (answer == players[1]) { computer = 0; player = 1; std::cout << "Okay, CPU = X You = O \n When you are ready "; } else //This is just to remove the possibility of a rogue exec without the right variables. { std::cin.clear(); std::cin.ignore(10000, '\n'); GamePvE(); return; } system("pause"); //This do-while loop goes aslong as GameOver is false. do { DisplayGrid(); if (playerIndex == computer) { //this just ends up passing through what character the computer has. //So it can do the right placement in the grid. CalculateComputerMove(players[computer]); } else { InputAndExec(); } //This is the section of the gameloop that checks for wins or if the game is a tie. int x = WinConditionCheck(); if (x == computer) { //The reason for Display Grid is just to update the display so you could see where the //Where the winning connections were! DisplayGrid(); std::cout << "\n [- CPU WON -] "; GameOver = true; system("pause"); } else if (x == player) { DisplayGrid(); std::cout << "\n [- YOU WON -] "; GameOver = true; system("pause"); } else if (moves == 9) { DisplayGrid(); std::cout << "\n [- TIE -] \n"; GameOver = true; system("pause"); } } while (!GameOver); system("CLS"); MainMenu(); } //Game Loop functions void DisplayGrid() { system("CLS"); for (auto x = 0; x < grid.size(); x++) { std::cout << "| " << grid.at(x) << " "; if (x == 2 || x == 5 || x == 8) { std::cout << "|" << std::endl; } } } void InputAndExec() { //The reason for this being a long long int, is because i kept getting build errors because i was doing a arithmetic overflow warning //So i then "upgraded" to this to remove that error. long long int playerInput = 0; std::cout << "[" << players[playerIndex] << "] turn : "; //Gets input from console and store the answer in the playerInput variable std::cin >> playerInput; if (playerInput-1 <= 8 && playerInput-1 >= 0) { if (grid.at(playerInput-1) == 'X' || grid.at(playerInput-1) == 'O') { std::cout << "Invalid selection, you cannot select a place that has already been taken! \n"; InputAndExec(); return; } else { grid[playerInput-1] = players[playerIndex]; moves++; PlayerSwitch(); return; } } else // This else is to catch any input that isn't an integer. then repeat. { std::cin.clear(); std::cin.ignore(10000, '\n'); std::cout << "Invalid input! Choose a number from the grid above! \n"; } } int WinConditionCheck() { //Here im just creating a variable that checks for winner, and then returns the player index number... //which corresponds with a char in players[]. char winner = 'Ø'; char a, b, c; //Horizontal for (long int i = 1; i <= 7; i+=3) { // These variables are temp just for storing values so the if statement further down stays relativly clean and easy to debug. a = grid.at(i); b = grid.at(i-1); c = grid.at(i+1); //What these variables check store is what is in the grid at the spesific point. They only hold that info based on the current iteration. //This if statement then checks weather or not they are all the same, it doesn't matter if its X or O. Aslong as all of them are the same... //it then continues to the next check if (a == b && b == c) { //Here we grab the character value of the winning row, then we do a check as to who won. then return a int value. //This int value that is returned, corresponds with the index of the players[], where X = 0, and O = 1. winner = grid.at(i); if (winner == 'X') { return 0; } else { return 1; } } } //Vertical win check for (long int i = 0; i < 3; i++) { //Here i grab a the current iterator and add the required grid locations to make a check. //im just using a, b and c because it really doesn't require to be that spesific. These are temp variables that... //have a single purpose, which is to check weather or not they are the same. a = grid.at(i); b = grid.at(i + 3); c = grid.at(i + 6); //This if statement just checks that all the temp variables are the same, and by that we can determine that we have a winner. //Since the temp varibles are set to check the one beneath another, this then checks the colum for a win condition. if (a == b && b == c) { //Here we grab the character value of the winning row, then we do a check as to who won. then return a int value. //This int value that is returned, corresponds with the index of the players[], where X = 0, and O = 1. winner = grid.at(i); if (winner == 'X') { return 0; } else { return 1; } } } //For the diagonal checks, all i have to do, since there are only two options. i will hardcode those checks. //The reason for that is because of time, i could most likly come up with a clever solution, however it would end up taking way longer.. //Than simply writing it out. This is only Tic-Tac-Toe. #pragma region DiagonalChecks //Diagonal Check 1 a = grid.at(2); b = grid.at(4); c = grid.at(6); std::cout << a << b << c; if (a == b && b == c) { //Same as before, we grab the variable at a this time, and return the correct index in players[]. winner = b; if (winner == 'X') { return 0; } else { return 1; } } //Diagonal Check 2 a = grid.at(0); b = grid.at(4); c = grid.at(8); if (a == b && b == c) { //Same as before, we grab the variable at a this time, and return the correct index in players[]. winner = b; if (winner == 'X') { return 0; } else { return 1; } } #pragma endregion return 2; } void PlayerSwitch() { //This function just inverts the player index. I think there is a better and prettier way to do this, however this will do for now. //Its not pretty, but i added an easter-egg incase something went horribly wrong! switch (playerIndex) { case 0 : playerIndex = 1; break; case 1 : playerIndex = 0; break; default: std::cout << "WTF just happened, im just gonna try something\n"; playerIndex = 0; break; } } void CalculateComputerMove(char CPUchar) { //Just initializing a seed(time) for my random number generator. int selected = (rand() % 8 + 1)-1; if (grid.at(selected) == 'X' || grid.at(selected) == 'O') { CalculateComputerMove(CPUchar); return; } else { grid.at(selected) = CPUchar; moves++; PlayerSwitch(); return; } }
[ "hans_olahoftun@hotmail.com" ]
hans_olahoftun@hotmail.com
39cc31371670480b292396298ed339ab29cd2e67
3dc0034f54360349734e5b133f169e39cdff3ce5
/BUGLIFE-12867964-src.cpp
412ba3f82f97ff515730e433b6f57995f2dd67c2
[]
no_license
anshul1927/SPOJ-Solutions
6c8022d11b3097b8ef3af2c17983375e01b8eb56
07c1d4dcc5b29c4b3a0c61cc8bc7d7e10307822a
refs/heads/master
2021-03-30T21:20:19.514777
2015-08-19T15:49:04
2015-08-19T15:49:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,558
cpp
#include <iostream> #include<queue> #include<cstring> #include<cstdio> #define comp(c) (c==1)?2:1 #define gc getchar_unlocked using namespace std; bool sus; int idx[2000]; bool done[2000]; int bugs[2000]; int inter[2000][2000]; int n,in; void scanint(int &x) { register int c = gc(); x = 0; for(;(c<48 || c>57);c = gc()); for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;} } void bfs(){ for(int p=0;p<n;p++){ if(!done[p]){ queue<int> Q; bugs[p]=1; done[p]=true; Q.push(p); while(!Q.empty()){ int curr=Q.front(); Q.pop(); for(int i=0;i<idx[curr];i++){ if(!done[inter[curr][i]]){ bugs[inter[curr][i]]=comp(bugs[curr]); Q.push(inter[curr][i]); done[inter[curr][i]]=true; } else{ if(bugs[inter[curr][i]]==bugs[curr]){ sus=true; return; } } } } } } } int main() { long long t; cin>>t; for(long long j=1;j<=t;j++){ scanint(n); scanint(in); memset(idx,0,sizeof idx); for(int i=0;i<in;i++){ int x,y; scanint(x); scanint(y); x=x-1; y=y-1; inter[x][idx[x]]=y;idx[x]++; inter[y][idx[y]]=x;idx[y]++; } sus=false; memset(bugs,0,sizeof bugs); memset(done,false,sizeof bugs); bfs(); cout<<"Scenario #"<<j<<":"<<endl; if(sus)printf("Suspicious bugs found!\n"); else printf("No suspicious bugs found!\n"); } return 0; }
[ "jayati.009@gmail.com" ]
jayati.009@gmail.com
bab79ca9935598c0d5582f4c76d7f8c63fa390e7
0084166695a3bea4f4285eadd57d03607314c149
/TouchGFX/target/generated/TouchGFXGeneratedHAL.cpp
ae76144669a0671e69c7eb5f250a13bce5357755
[]
no_license
Zhangzhicheng001/Magnetic_shielding_system
142556f79ada0e9f1b4addcbeaf69441a0f515b6
7714e14758de2a30c920ab9ad74ec9dc1e094820
refs/heads/main
2023-07-08T11:18:05.720893
2021-08-09T10:25:02
2021-08-09T10:25:02
391,795,760
0
0
null
null
null
null
UTF-8
C++
false
false
4,986
cpp
/** ****************************************************************************** * File Name : TouchGFXGeneratedHAL.cpp ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ #include <TouchGFXGeneratedHAL.hpp> #include <touchgfx/hal/OSWrappers.hpp> #include <gui/common/FrontendHeap.hpp> #include <touchgfx/hal/GPIO.hpp> #include "stm32h7xx.h" #include "stm32h7xx_hal_ltdc.h" using namespace touchgfx; namespace { static uint16_t lcd_int_active_line; static uint16_t lcd_int_porch_line; } void TouchGFXGeneratedHAL::initialize() { HAL::initialize(); registerEventListener(*(Application::getInstance())); setFrameBufferStartAddresses((void*)0xC0000000, (void*)0xC0119400, (void*)0); } void TouchGFXGeneratedHAL::configureInterrupts() { NVIC_SetPriority(DMA2D_IRQn, 9); NVIC_SetPriority(LTDC_IRQn, 9); } void TouchGFXGeneratedHAL::enableInterrupts() { NVIC_EnableIRQ(DMA2D_IRQn); NVIC_EnableIRQ(LTDC_IRQn); } void TouchGFXGeneratedHAL::disableInterrupts() { NVIC_DisableIRQ(DMA2D_IRQn); NVIC_DisableIRQ(LTDC_IRQn); } void TouchGFXGeneratedHAL::enableLCDControllerInterrupt() { lcd_int_active_line = (LTDC->BPCR & 0x7FF) - 1; lcd_int_porch_line = (LTDC->AWCR & 0x7FF) - 1; /* Sets the Line Interrupt position */ LTDC->LIPCR = lcd_int_active_line; /* Line Interrupt Enable */ LTDC->IER |= LTDC_IER_LIE; } bool TouchGFXGeneratedHAL::beginFrame() { return HAL::beginFrame(); } void TouchGFXGeneratedHAL::endFrame() { HAL::endFrame(); } uint16_t* TouchGFXGeneratedHAL::getTFTFrameBuffer() const { return (uint16_t*)LTDC_Layer1->CFBAR; } void TouchGFXGeneratedHAL::setTFTFrameBuffer(uint16_t* adr) { LTDC_Layer1->CFBAR = (uint32_t)adr; /* Reload immediate */ LTDC->SRCR = (uint32_t)LTDC_SRCR_IMR; } void TouchGFXGeneratedHAL::flushFrameBuffer(const touchgfx::Rect& rect) { HAL::flushFrameBuffer(rect); // If the framebuffer is placed in Write Through cached memory (e.g. SRAM) then // the DCache must be flushed prior to DMA2D accessing it. That's done // using the function SCB_CleanInvalidateDCache(). Remember to enable "CPU Cache" in the // "System Core" settings for "Cortex M7" in CubeMX in order for this function call to work. if (SCB->CCR & SCB_CCR_DC_Msk) { SCB_CleanInvalidateDCache(); } } bool TouchGFXGeneratedHAL::blockCopy(void* RESTRICT dest, const void* RESTRICT src, uint32_t numBytes) { return HAL::blockCopy(dest, src, numBytes); } void TouchGFXGeneratedHAL::InvalidateCache() { // If the framebuffer is placed in Write Through cached memory (e.g. SRAM) then // the DCache must be flushed prior to DMA2D accessing it. That's done // using the function SCB_CleanInvalidateDCache(). Remember to enable "CPU Cache" in the // "System Core" settings for "Cortex M7" in CubeMX in order for this function call to work. if (SCB->CCR & SCB_CCR_DC_Msk) { SCB_CleanInvalidateDCache(); } } void TouchGFXGeneratedHAL::FlushCache() { // If the framebuffer is placed in Write Through cached memory (e.g. SRAM) then // the DCache must be flushed prior to DMA2D accessing it. That's done // using the function SCB_CleanInvalidateDCache(). Remember to enable "CPU Cache" in the // "System Core" settings for "Cortex M7" in CubeMX in order for this function call to work. if (SCB->CCR & SCB_CCR_DC_Msk) { SCB_CleanInvalidateDCache(); } } extern "C" { void HAL_LTDC_LineEventCallback(LTDC_HandleTypeDef* hltdc) { if (LTDC->LIPCR == lcd_int_active_line) { //entering active area HAL_LTDC_ProgramLineEvent(hltdc, lcd_int_porch_line); HAL::getInstance()->vSync(); OSWrappers::signalVSync(); // Swap frame buffers immediately instead of waiting for the task to be scheduled in. // Note: task will also swap when it wakes up, but that operation is guarded and will not have // any effect if already swapped. HAL::getInstance()->swapFrameBuffers(); GPIO::set(GPIO::VSYNC_FREQ); } else { //exiting active area HAL_LTDC_ProgramLineEvent(hltdc, lcd_int_active_line); GPIO::clear(GPIO::VSYNC_FREQ); HAL::getInstance()->frontPorchEntered(); } } } /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
[ "601596643@qq.com" ]
601596643@qq.com
18296b24c1a4c774d930261e017e37a0cf8d04fa
d0601b28a3060105e82c2a839d435c4329fe82a9
/OpenGL_Material/build-OpenGL_Material-Desktop_Qt_5_8_0_MSVC2015_64bit-Debug/debug/moc_mainwindow.cpp
51b68186ab06892d4bfefdfe122cf57267d5fcdf
[]
no_license
guoerba/opengl
9458b1b3827e24884bcd0a1b91d122ab6a252f8e
103da63ada1703a3f450cfde19f41b04e922187e
refs/heads/master
2020-07-10T15:40:49.828059
2019-08-25T13:52:58
2019-08-25T13:52:58
204,300,456
0
0
null
null
null
null
UTF-8
C++
false
false
2,706
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'mainwindow.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.8.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../OpenGL_Material/mainwindow.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'mainwindow.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.8.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_MainWindow_t { QByteArrayData data[1]; char stringdata0[11]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = { { QT_MOC_LITERAL(0, 0, 10) // "MainWindow" }, "MainWindow" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_MainWindow[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { Q_UNUSED(_o); Q_UNUSED(_id); Q_UNUSED(_c); Q_UNUSED(_a); } const QMetaObject MainWindow::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_MainWindow.data, qt_meta_data_MainWindow, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *MainWindow::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *MainWindow::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0)) return static_cast<void*>(const_cast< MainWindow*>(this)); return QMainWindow::qt_metacast(_clname); } int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
[ "guoerbamicro@outlook.com" ]
guoerbamicro@outlook.com
4b1a2ff69ea1c73dca9f8d22448ade38d373b8e1
84df2566bbce86ad087ec0465eaed091737b8e69
/66. Trojki liczb/66.3/main.cpp
925fdf6fbfb5a04c38f48df0aa157c12d0745e0b
[]
no_license
matura-inf/cpp
5d6ea1bd12395042551f9e55fc3a88375a0aa911
f1a9cb6930b536acb5fb1632773abd411daa0c3d
refs/heads/main
2023-03-01T04:03:05.107390
2021-02-10T21:40:32
2021-02-10T21:40:32
309,538,910
3
0
null
null
null
null
UTF-8
C++
false
false
1,325
cpp
#include <iostream> #include <fstream> #include <cmath> using namespace std; int main() { ifstream in("../trojki.txt"); ofstream out("../wyniki_trojki.txt", ofstream::app); long long pierwsza, druga, trzecia, nr_linii = 0; long long pierwsza_p = 1, druga_p = 2, trzecia_p = 3; long long pierwsza_n = 1, druga_n = 2, trzecia_n = 3; out << endl << "Zad3" << endl << endl; while (in >> pierwsza >> druga >> trzecia) { if (nr_linii % 2 == 0) { pierwsza_p = pierwsza; druga_p = druga; trzecia_p = trzecia; } if (nr_linii % 2 == 1) { pierwsza_n = pierwsza; druga_n = druga; trzecia_n = trzecia; } if (((pow(pierwsza_p, 2) + pow(druga_p, 2) == pow(trzecia_p, 2)) || (pow(pierwsza_p, 2) + pow(trzecia_p, 2) == pow(druga_p, 2)) || (pow(trzecia_p, 2) + pow(druga_p, 2) == pow(pierwsza_p, 2))) && ((pow(pierwsza_n, 2) + pow(druga_n, 2) == pow(trzecia_n, 2)) || (pow(pierwsza_n, 2) + pow(trzecia_n, 2) == pow(druga_n, 2)) || (pow(trzecia_n, 2) + pow(druga_n, 2) == pow(pierwsza_n, 2)))) { out << pierwsza_n << " " << druga_n << " " << trzecia_n << endl; out << pierwsza_p << " " << druga_p << " " << trzecia_p << endl << endl; } nr_linii++; } in.close(); out.close(); system("pause"); return 0; }
[ "piotrmiernik255@gmail.com" ]
piotrmiernik255@gmail.com
a35449fec2af60cbb23f7da0b8bae35a4ce64aef
1dc05c3cb3a57aea5f64052f329eaf458f73c832
/topic/LeetCode/0807maxIncreaseKeepingSkyline.cpp
603cf6950b266ec0a72ef42137f69d3f137e23ee
[]
no_license
ITShadow/practiceCode
0b1fcbb6b150a1ee91283e8ac7a8d928b4751eda
4b407ad98e3abc0be5eadc97ff32165f9f367104
refs/heads/master
2023-04-08T05:53:21.734166
2021-04-26T03:45:46
2021-04-26T03:45:46
295,429,631
0
0
null
null
null
null
UTF-8
C++
false
false
2,203
cpp
/* 在二维数组grid中,grid[i][j]代表位于某处的建筑物的高度。 我们被允许增加任何数量(不同建筑物的数量可能不同)的建筑物的高度。 高度 0 也被认为是建筑物。 最后,从新数组的所有四个方向(即顶部,底部,左侧和右侧)观看的“天际线”必须与原始数组的天际线相同。 城市的天际线是从远处观看时,由所有建筑物形成的矩形的外部轮廓。 请看下面的例子。 建筑物高度可以增加的最大总和是多少? 例子: 输入: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]] 输出: 35 解释: The grid is: [ [3, 0, 8, 4], [2, 4, 5, 7], [9, 2, 6, 3], [0, 3, 1, 0] ] 从数组竖直方向(即顶部,底部)看“天际线”是:[9, 4, 8, 7] 从水平水平方向(即左侧,右侧)看“天际线”是:[8, 7, 9, 3] 在不影响天际线的情况下对建筑物进行增高后,新数组如下: gridNew = [ [8, 4, 8, 7], [7, 4, 7, 7], [9, 4, 8, 7], [3, 3, 3, 3] ] 说明: 1 < grid.length = grid[0].length <= 50。  grid[i][j] 的高度范围是: [0, 100]。 一座建筑物占据一个grid[i][j]:换言之,它们是 1 x 1 x grid[i][j] 的长方体。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/max-increase-to-keep-city-skyline 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 class Solution { public: int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) { if (grid.empty()) return 0; int R = grid.size(); int C = grid[0].size(); vector<int> row_max(R, 0); vector<int> col_max(C, 0); for (int i = 0; i < R; ++i) { for (int j = 0; j < C; ++j) { row_max[i] = max(row_max[i], grid[i][j]); col_max[j] = max(col_max[j], grid[i][j]); } } int res = 0; for (int i = 0; i < R; ++i) { for (int j = 0; j < C; ++j) { res += min(row_max[i], col_max[j]) - grid[i][j]; } } return res; } }; */ /* 就是找行列最大 */
[ "13710255965@163.com" ]
13710255965@163.com
8ab716daca33856e610a208732527f0dd9de4e8e
70d18762f2443bb5df8df38967bcd38277573cdb
/arch/generic/kernel/gen_ke_arch64.cpp
1f2b16ecf52f14ac9a8389e3bec0a1176360b3fd
[]
no_license
15831944/evita-common-lisp
f829defc5386cd1988754c59f2056f0367c77ed7
cb2cbd3cc541878d25dcedb4abd88cf8e2c881d9
refs/heads/master
2021-05-27T16:35:25.208083
2013-12-01T06:21:32
2013-12-01T06:21:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,776
cpp
////////////////////////////////////////////////////////////////////////////// // // evcl - kernel - arch 64 // kernel/ke_arch64.cpp // // This file is part of Evita Common Lisp. // // Copyright (C) 1996-2006 by Project Vogue. // Written by Yoshifumi "VOGUE" INOUE. (yosi@msn.com) // // @(#)$Id: //proj/evcl3/mainline/arch/generic/kernel/gen_ke_arch64.cpp#3 $ // #if SIZEOF_VAL == 8 #include "../../../kernel/ke_arch.h" namespace Kernel { const uint64 Kernel::Arch64::k_rgfBit[64] = { 1ull << 0, 1ull << 1, 1ull << 2, 1ull << 3, 1ull << 4, 1ull << 5, 1ull << 6, 1ull << 7, 1ull << 8, 1ull << 9, 1ull << 10, 1ull << 11, 1ull << 12, 1ull << 13, 1ull << 14, 1ull << 15, 1ull << 16, 1ull << 17, 1ull << 18, 1ull << 19, 1ull << 20, 1ull << 21, 1ull << 22, 1ull << 23, 1ull << 24, 1ull << 25, 1ull << 26, 1ull << 27, 1ull << 28, 1ull << 29, 1ull << 30, 1ull << 31, 1ull << 32, 1ull << 33, 1ull << 34, 1ull << 35, 1ull << 36, 1ull << 37, 1ull << 38, 1ull << 39, 1ull << 40, 1ull << 41, 1ull << 42, 1ull << 43, 1ull << 44, 1ull << 45, 1ull << 46, 1ull << 47, 1ull << 48, 1ull << 49, 1ull << 50, 1ull << 51, 1ull << 52, 1ull << 53, 1ull << 54, 1ull << 55, 1ull << 56, 1ull << 57, 1ull << 58, 1ull << 59, 1ull << 60, 1ull << 61, 1ull << 62, 1ull << 63 }; // Kernel::Arch64::k_rgfBit ////////////////////////////////////////////////////////////////////// // // Mask For Bit Stream Leader and Trailer // // Bit Stream: // LLLL LLLL xxxx xxxx ... xxxx xxxx TTTT TTTT // // x = bits for processing // L = leader bits (not affect) // T = trailer bits (not affect) // // Note: Bit stream is stored in each 32bit word from LSB to MSB. // // // (loop for i below 64 do (format t "0x~16,'0Xull, // ~D~%" (1- (ash 1 i)) i)) const Arch64::BitEltT Arch64::k_rgnLeaderMask[64] = { 0x0000000000000000ull, // 0 0x0000000000000001ull, // 1 0x0000000000000003ull, // 2 0x0000000000000007ull, // 3 0x000000000000000Full, // 4 0x000000000000001Full, // 5 0x000000000000003Full, // 6 0x000000000000007Full, // 7 0x00000000000000FFull, // 8 0x00000000000001FFull, // 9 0x00000000000003FFull, // 10 0x00000000000007FFull, // 11 0x0000000000000FFFull, // 12 0x0000000000001FFFull, // 13 0x0000000000003FFFull, // 14 0x0000000000007FFFull, // 15 0x000000000000FFFFull, // 16 0x000000000001FFFFull, // 17 0x000000000003FFFFull, // 18 0x000000000007FFFFull, // 19 0x00000000000FFFFFull, // 20 0x00000000001FFFFFull, // 21 0x00000000003FFFFFull, // 22 0x00000000007FFFFFull, // 23 0x0000000000FFFFFFull, // 24 0x0000000001FFFFFFull, // 25 0x0000000003FFFFFFull, // 26 0x0000000007FFFFFFull, // 27 0x000000000FFFFFFFull, // 28 0x000000001FFFFFFFull, // 29 0x000000003FFFFFFFull, // 30 0x000000007FFFFFFFull, // 31 0x00000000FFFFFFFFull, // 32 0x00000001FFFFFFFFull, // 33 0x00000003FFFFFFFFull, // 34 0x00000007FFFFFFFFull, // 35 0x0000000FFFFFFFFFull, // 36 0x0000001FFFFFFFFFull, // 37 0x0000003FFFFFFFFFull, // 38 0x0000007FFFFFFFFFull, // 39 0x000000FFFFFFFFFFull, // 40 0x000001FFFFFFFFFFull, // 41 0x000003FFFFFFFFFFull, // 42 0x000007FFFFFFFFFFull, // 43 0x00000FFFFFFFFFFFull, // 44 0x00001FFFFFFFFFFFull, // 45 0x00003FFFFFFFFFFFull, // 46 0x00007FFFFFFFFFFFull, // 47 0x0000FFFFFFFFFFFFull, // 48 0x0001FFFFFFFFFFFFull, // 49 0x0003FFFFFFFFFFFFull, // 50 0x0007FFFFFFFFFFFFull, // 51 0x000FFFFFFFFFFFFFull, // 52 0x001FFFFFFFFFFFFFull, // 53 0x003FFFFFFFFFFFFFull, // 54 0x007FFFFFFFFFFFFFull, // 55 0x00FFFFFFFFFFFFFFull, // 56 0x01FFFFFFFFFFFFFFull, // 57 0x03FFFFFFFFFFFFFFull, // 58 0x07FFFFFFFFFFFFFFull, // 59 0x0FFFFFFFFFFFFFFFull, // 60 0x1FFFFFFFFFFFFFFFull, // 61 0x3FFFFFFFFFFFFFFFull, // 62 0x7FFFFFFFFFFFFFFFull, // 63 }; // k_rgnLeaderMask // (loop with x = (1- (ash 1 64)) for i below 64 for m = (1- (ash 1 i)) // do (format t " 0x~16,'0Xull, // ~D~%" (- x m) i) ) const Arch64::BitEltT Arch64::k_rgnTrailerMask[64] = { 0xFFFFFFFFFFFFFFFFull, // 0 0xFFFFFFFFFFFFFFFEull, // 1 0xFFFFFFFFFFFFFFFCull, // 2 0xFFFFFFFFFFFFFFF8ull, // 3 0xFFFFFFFFFFFFFFF0ull, // 4 0xFFFFFFFFFFFFFFE0ull, // 5 0xFFFFFFFFFFFFFFC0ull, // 6 0xFFFFFFFFFFFFFF80ull, // 7 0xFFFFFFFFFFFFFF00ull, // 8 0xFFFFFFFFFFFFFE00ull, // 9 0xFFFFFFFFFFFFFC00ull, // 10 0xFFFFFFFFFFFFF800ull, // 11 0xFFFFFFFFFFFFF000ull, // 12 0xFFFFFFFFFFFFE000ull, // 13 0xFFFFFFFFFFFFC000ull, // 14 0xFFFFFFFFFFFF8000ull, // 15 0xFFFFFFFFFFFF0000ull, // 16 0xFFFFFFFFFFFE0000ull, // 17 0xFFFFFFFFFFFC0000ull, // 18 0xFFFFFFFFFFF80000ull, // 19 0xFFFFFFFFFFF00000ull, // 20 0xFFFFFFFFFFE00000ull, // 21 0xFFFFFFFFFFC00000ull, // 22 0xFFFFFFFFFF800000ull, // 23 0xFFFFFFFFFF000000ull, // 24 0xFFFFFFFFFE000000ull, // 25 0xFFFFFFFFFC000000ull, // 26 0xFFFFFFFFF8000000ull, // 27 0xFFFFFFFFF0000000ull, // 28 0xFFFFFFFFE0000000ull, // 29 0xFFFFFFFFC0000000ull, // 30 0xFFFFFFFF80000000ull, // 31 0xFFFFFFFF00000000ull, // 32 0xFFFFFFFE00000000ull, // 33 0xFFFFFFFC00000000ull, // 34 0xFFFFFFF800000000ull, // 35 0xFFFFFFF000000000ull, // 36 0xFFFFFFE000000000ull, // 37 0xFFFFFFC000000000ull, // 38 0xFFFFFF8000000000ull, // 39 0xFFFFFF0000000000ull, // 40 0xFFFFFE0000000000ull, // 41 0xFFFFFC0000000000ull, // 42 0xFFFFF80000000000ull, // 43 0xFFFFF00000000000ull, // 44 0xFFFFE00000000000ull, // 45 0xFFFFC00000000000ull, // 46 0xFFFF800000000000ull, // 47 0xFFFF000000000000ull, // 48 0xFFFE000000000000ull, // 49 0xFFFC000000000000ull, // 50 0xFFF8000000000000ull, // 51 0xFFF0000000000000ull, // 52 0xFFE0000000000000ull, // 53 0xFFC0000000000000ull, // 54 0xFF80000000000000ull, // 55 0xFF00000000000000ull, // 56 0xFE00000000000000ull, // 57 0xFC00000000000000ull, // 58 0xF800000000000000ull, // 59 0xF000000000000000ull, // 60 0xE000000000000000ull, // 61 0xC000000000000000ull, // 62 0x8000000000000000ull, // 63 }; // k_rgnTrailerMask CASSERT(sizeof(Arch64::k_rgnLeaderMask) == sizeof(Arch64::k_rgnTrailerMask)); } // Kernel #endif // SIZEOF_VAL == 8
[ "eval1749@gmail.com" ]
eval1749@gmail.com
6f9e2a1251e0d80527ebef9b1764f62a60cc7984
c26e9d3f92d95f7ce9d0fd5ef2c18dd95ec209a5
/hackerrank/graph/murderer.cpp
1fb9dd65652537e7209bab94ed2d7f66c6acb818
[]
no_license
crystal95/Competetive-Programming-at-different-platforms
c9ad1684f6258539309d07960ed6abfa7d1a16d0
92d283171b0ae0307e9ded473c6eea16f62cb60e
refs/heads/master
2021-01-09T21:44:28.175506
2016-03-27T21:26:26
2016-03-27T21:26:26
54,848,617
0
0
null
null
null
null
UTF-8
C++
false
false
1,083
cpp
using namespace std; #include <stdio.h> #include <stdlib.h> #include <string.h> #include <vector> #include <iostream> #include <queue> #include <algorithm> #include <unordered_set> typedef long long int ll; typedef pair<int,int> ii; void bfs(vector<vector<int> > &adj,int s,vector<int> &dis,int n) { int i ; unordered_set<int> unvisited; for(i=1;i<=n;i++) unvisited.insert(i); queue<int> q; q.push(s); unvisited.erase(s); while(!q.empty()) { int tmp=q.front(); q.pop(); for(auto it=unvisited.begin();it!=unvisited.end();++it) { if(find(adj[tmp].begin(),adj[tmp].end(),*it)==adj[tmp].end()) { q.push(*it); dis[*it]=dis[tmp]+1; unvisited.erase(*it); } } } } int main() { int T; cin>>T; while(T--) { int i,n,m,u,v,s,w,start; cin>>n>>m; vector<vector<int > > adj(n+1); vector<int> dis(n+1,0); for(i=0;i<m;i++) { cin>>u>>v; adj[u].push_back(v); adj[v].push_back(u); } cin>>start; bfs(adj,start,dis,n); for(i=1;i<=n;i++) { if(start!=i) cout<<dis[i]<<" "; } cout<<endl; } return 0; }
[ "dsodhi95@gmail.com" ]
dsodhi95@gmail.com
48c0f65f815f5a8f95648c04f8d7974b965a502f
a88750ab34c33c8a00a7d653205c15fd429aac94
/src/bip32/hdwalletutil.cpp
15c54a63cda010516a0f02bb86512a3b6f4d10dd
[ "MIT" ]
permissive
FromHDDtoSSD/SorachanCoin-qt
8ccb4b1341b0e8228f93e101b75f741b99d49de0
9dff8dccd71518eea9a1ff80671cccf31915ca09
refs/heads/master
2022-09-08T01:14:20.838440
2022-08-27T16:39:36
2022-08-27T16:39:36
144,701,661
9
3
null
null
null
null
UTF-8
C++
false
false
3,845
cpp
// Copyright (c) 2017-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <bip32/hdwalletutil.h> #include <util/logging.h> #include <util/system.h> #include <util/args.h> fs::path hdwalletutil::GetWalletDir() { fs::path path; if (ARGS.IsArgSet("-walletdir")) { path = ARGS.GetArg("-walletdir", ""); if (! fs::is_directory(path)) { // If the path specified doesn't exist, we return the deliberately // invalid empty string. path = ""; } } else { path = lutil::GetDataDir(); // If a wallets directory exists, use that, otherwise default to GetDataDir if (fs::is_directory(path / "wallets")) { path /= "wallets"; } } return path; } static bool IsBerkeleyBtree(const fs::path &path) { // A Berkeley DB Btree file has at least 4K. // This check also prevents opening lock files. boost::system::error_code ec; auto size = fs::file_size(path, ec); if (ec) logging::LogPrintf("%s: %s %s\n", __func__, ec.message(), path.string()); if (size < 4096) return false; fsbridge::ifstream file(path, std::ios::binary); if (! file.is_open()) return false; file.seekg(12, std::ios::beg); // Magic bytes start at offset 12 uint32_t data = 0; file.read((char*) &data, sizeof(data)); // Read 4 bytes of file to compare against magic // Berkeley DB Btree magic bytes, from: // https://github.com/file/file/blob/5824af38469ec1ca9ac3ffd251e7afe9dc11e227/magic/Magdir/database#L74-L75 // - big endian systems - 00 05 31 62 // - little endian systems - 62 31 05 00 return data == 0x00053162 || data == 0x62310500; } std::vector<fs::path> hdwalletutil::ListWalletDir() { const fs::path wallet_dir = GetWalletDir(); const size_t offset = wallet_dir.string().size() + 1; std::vector<fs::path> paths; boost::system::error_code ec; for (auto it = fs::recursive_directory_iterator(wallet_dir, ec); it != fs::recursive_directory_iterator(); it.increment(ec)) { if (ec) { logging::LogPrintf("%s: %s %s\n", __func__, ec.message(), it->path().string()); continue; } // Get wallet path relative to walletdir by removing walletdir from the wallet path. // This can be replaced by boost::filesystem::lexically_relative once boost is bumped to 1.60. const fs::path path = it->path().string().substr(offset); if (it->status().type() == fs::directory_file && IsBerkeleyBtree(it->path() / "wallet.dat")) { // Found a directory which contains wallet.dat btree file, add it as a wallet. paths.emplace_back(path); } else if (it.level() == 0 && it->symlink_status().type() == fs::regular_file && IsBerkeleyBtree(it->path())) { if (it->path().filename() == "wallet.dat") { // Found top-level wallet.dat btree file, add top level directory "" // as a wallet. paths.emplace_back(); } else { // Found top-level btree file not called wallet.dat. Current bitcoin // software will never create these files but will allow them to be // opened in a shared database environment for backwards compatibility. // Add it to the list of available wallets. paths.emplace_back(path); } } } return paths; } hdwalletutil::WalletLocation::WalletLocation(const std::string &name) : m_name(name) , m_path(fs::absolute(name, GetWalletDir())) { } bool hdwalletutil::WalletLocation::Exists() const { return fs::symlink_status(m_path).type() != fs::file_not_found; }
[ "42310034+FromHDDtoSSD@users.noreply.github.com" ]
42310034+FromHDDtoSSD@users.noreply.github.com
4bf7445e62392551dbda48960e850b648fa4164c
0863a85756b0385a36605f6da18550d74df417ea
/insertDeletBinarySearchTree/main.cpp
06dc38bff06ee3a609f252482761aa820f13f3d0
[]
no_license
tianjingyu1/cProject
f759fb538538d689b14e38995c00afd5b70d1283
b5c01517b8f9f654f175161de1c0967cbe43f557
refs/heads/master
2021-02-27T15:39:22.998819
2020-05-29T00:13:41
2020-05-29T00:13:41
245,616,533
0
0
null
null
null
null
GB18030
C++
false
false
1,967
cpp
#include <iostream> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ BinTree Insert( BinTree BST, ElementType X ) { if( !BST ){ /* 若原树为空,生成并返回一个结点的二叉搜索树 */ BST = (BinTree)malloc(sizeof(struct TNode)); BST->Data = X; BST->Left = BST->Right = NULL; } else { /* 开始找要插入元素的位置 */ if( X < BST->Data ) BST->Left = Insert( BST->Left, X ); /*递归插入左子树*/ else if( X > BST->Data ) BST->Right = Insert( BST->Right, X ); /*递归插入右子树*/ /* else X已经存在,什么都不做 */ } return BST; } BinTree Delete( BinTree BST, ElementType X ) { Position Tmp; if( !BST ) printf("要删除的元素未找到"); else { if( X < BST->Data ) BST->Left = Delete( BST->Left, X ); /* 从左子树递归删除 */ else if( X > BST->Data ) BST->Right = Delete( BST->Right, X ); /* 从右子树递归删除 */ else { /* BST就是要删除的结点 */ /* 如果被删除结点有左右两个子结点 */ if( BST->Left && BST->Right ) { /* 从右子树中找最小的元素填充删除结点 */ Tmp = FindMin( BST->Right ); BST->Data = Tmp->Data; /* 从右子树中删除最小元素 */ BST->Right = Delete( BST->Right, BST->Data ); } else { /* 被删除结点有一个或无子结点 */ Tmp = BST; if( !BST->Left ) /* 只有右孩子或无子结点 */ BST = BST->Right; else /* 只有左孩子 */ BST = BST->Left; free( Tmp ); } } } return BST; } int main(int argc, char** argv) { return 0; }
[ "820410740@qq.com" ]
820410740@qq.com
ca132ef2e0abab744552b5d3569fea6189f708df
9407b552787d3e872d8cdcfae5f86cd056042dfa
/dfs2.cpp
802f9dd49b7db9f78140d4c167793fdfe7ce8a5a
[]
no_license
themechanicalcoder/Data-Structure-And-Algorithms
7077c30cecdd42c8291c07b39089252d6cd672e3
3dc49f9926de10b2645e0b1c022ddbce932e208c
refs/heads/master
2021-06-19T21:12:35.973712
2020-12-18T10:58:03
2020-12-18T10:58:03
134,423,943
0
1
null
2020-03-22T11:18:56
2018-05-22T14:02:38
C++
UTF-8
C++
false
false
574
cpp
#include<bits/stdc++.h> using namespace std; vector<list<int> >g; vector<int>v; vector<int>d; void dfs(int u){ if(!v[u]){ v[u]=1; cout<<u<<" "; for(auto it=g[u].begin();it!=g[u].end();it++){ if(!v[*it]){ d[*it]=d[u]+1; dfs(*it); } } }} int main(){ int n,m,a,b; cin>>n>>m; d.assign(n+1,0); v.assign(n+1,0); g.assign(n+1,list<int>()); for(int i=0;i<m;i++){ cin>>a>>b; g[a].push_back(b); g[b].push_back(a); } for(int i=1;i<=n;i++){ if(!v[i]){ dfs(i); } } for(int i=1;i<=n;i++){ cout<<d[i]; } return 0; }
[ "gouravroy261999@gmail.com" ]
gouravroy261999@gmail.com
510031590fb18ee868c9ac88fb8da30c2ec3e09a
b056684eb040d7f14f3d1bd5a5ae26d33bd18481
/src/file_trans/include/file_trans.grpc.pb.h
87036594527e453e37245aeeeaa4e6ddcda5ffe1
[]
no_license
amyxu1/webpack-mdns
5f1fbba65452d7475e5cc7a2548805ddf1c74859
516a44825d200ca495afe18f59411ae2cecec28e
refs/heads/master
2023-06-02T21:17:44.070368
2021-06-15T16:52:22
2021-06-15T16:52:22
294,596,101
1
1
null
2020-11-06T07:05:55
2020-09-11T04:43:30
Makefile
UTF-8
C++
false
true
14,845
h
// Generated by the gRPC C++ plugin. // If you make any local change, they will be lost. // source: file_trans.proto #ifndef GRPC_file_5ftrans_2eproto__INCLUDED #define GRPC_file_5ftrans_2eproto__INCLUDED #include "file_trans.pb.h" #include <functional> #include <grpc/impl/codegen/port_platform.h> #include <grpcpp/impl/codegen/async_generic_service.h> #include <grpcpp/impl/codegen/async_stream.h> #include <grpcpp/impl/codegen/async_unary_call.h> #include <grpcpp/impl/codegen/client_callback.h> #include <grpcpp/impl/codegen/client_context.h> #include <grpcpp/impl/codegen/completion_queue.h> #include <grpcpp/impl/codegen/message_allocator.h> #include <grpcpp/impl/codegen/method_handler.h> #include <grpcpp/impl/codegen/proto_utils.h> #include <grpcpp/impl/codegen/rpc_method.h> #include <grpcpp/impl/codegen/server_callback.h> #include <grpcpp/impl/codegen/server_callback_handlers.h> #include <grpcpp/impl/codegen/server_context.h> #include <grpcpp/impl/codegen/service_type.h> #include <grpcpp/impl/codegen/status.h> #include <grpcpp/impl/codegen/stub_options.h> #include <grpcpp/impl/codegen/sync_stream.h> namespace file_trans { class WebpackServer final { public: static constexpr char const* service_full_name() { return "file_trans.WebpackServer"; } class StubInterface { public: virtual ~StubInterface() {} std::unique_ptr< ::grpc::ClientReaderInterface< ::file_trans::FileChunk>> SendFile(::grpc::ClientContext* context, const ::file_trans::Request& request) { return std::unique_ptr< ::grpc::ClientReaderInterface< ::file_trans::FileChunk>>(SendFileRaw(context, request)); } std::unique_ptr< ::grpc::ClientAsyncReaderInterface< ::file_trans::FileChunk>> AsyncSendFile(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq, void* tag) { return std::unique_ptr< ::grpc::ClientAsyncReaderInterface< ::file_trans::FileChunk>>(AsyncSendFileRaw(context, request, cq, tag)); } std::unique_ptr< ::grpc::ClientAsyncReaderInterface< ::file_trans::FileChunk>> PrepareAsyncSendFile(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncReaderInterface< ::file_trans::FileChunk>>(PrepareAsyncSendFileRaw(context, request, cq)); } class experimental_async_interface { public: virtual ~experimental_async_interface() {} #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL virtual void SendFile(::grpc::ClientContext* context, ::file_trans::Request* request, ::grpc::ClientReadReactor< ::file_trans::FileChunk>* reactor) = 0; #else virtual void SendFile(::grpc::ClientContext* context, ::file_trans::Request* request, ::grpc::experimental::ClientReadReactor< ::file_trans::FileChunk>* reactor) = 0; #endif }; #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL typedef class experimental_async_interface async_interface; #endif #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL async_interface* async() { return experimental_async(); } #endif virtual class experimental_async_interface* experimental_async() { return nullptr; } private: virtual ::grpc::ClientReaderInterface< ::file_trans::FileChunk>* SendFileRaw(::grpc::ClientContext* context, const ::file_trans::Request& request) = 0; virtual ::grpc::ClientAsyncReaderInterface< ::file_trans::FileChunk>* AsyncSendFileRaw(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq, void* tag) = 0; virtual ::grpc::ClientAsyncReaderInterface< ::file_trans::FileChunk>* PrepareAsyncSendFileRaw(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq) = 0; }; class Stub final : public StubInterface { public: Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel); std::unique_ptr< ::grpc::ClientReader< ::file_trans::FileChunk>> SendFile(::grpc::ClientContext* context, const ::file_trans::Request& request) { return std::unique_ptr< ::grpc::ClientReader< ::file_trans::FileChunk>>(SendFileRaw(context, request)); } std::unique_ptr< ::grpc::ClientAsyncReader< ::file_trans::FileChunk>> AsyncSendFile(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq, void* tag) { return std::unique_ptr< ::grpc::ClientAsyncReader< ::file_trans::FileChunk>>(AsyncSendFileRaw(context, request, cq, tag)); } std::unique_ptr< ::grpc::ClientAsyncReader< ::file_trans::FileChunk>> PrepareAsyncSendFile(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncReader< ::file_trans::FileChunk>>(PrepareAsyncSendFileRaw(context, request, cq)); } class experimental_async final : public StubInterface::experimental_async_interface { public: #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL void SendFile(::grpc::ClientContext* context, ::file_trans::Request* request, ::grpc::ClientReadReactor< ::file_trans::FileChunk>* reactor) override; #else void SendFile(::grpc::ClientContext* context, ::file_trans::Request* request, ::grpc::experimental::ClientReadReactor< ::file_trans::FileChunk>* reactor) override; #endif private: friend class Stub; explicit experimental_async(Stub* stub): stub_(stub) { } Stub* stub() { return stub_; } Stub* stub_; }; class experimental_async_interface* experimental_async() override { return &async_stub_; } private: std::shared_ptr< ::grpc::ChannelInterface> channel_; class experimental_async async_stub_{this}; ::grpc::ClientReader< ::file_trans::FileChunk>* SendFileRaw(::grpc::ClientContext* context, const ::file_trans::Request& request) override; ::grpc::ClientAsyncReader< ::file_trans::FileChunk>* AsyncSendFileRaw(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq, void* tag) override; ::grpc::ClientAsyncReader< ::file_trans::FileChunk>* PrepareAsyncSendFileRaw(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq) override; const ::grpc::internal::RpcMethod rpcmethod_SendFile_; }; static std::unique_ptr<Stub> NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options = ::grpc::StubOptions()); class Service : public ::grpc::Service { public: Service(); virtual ~Service(); virtual ::grpc::Status SendFile(::grpc::ServerContext* context, const ::file_trans::Request* request, ::grpc::ServerWriter< ::file_trans::FileChunk>* writer); }; template <class BaseClass> class WithAsyncMethod_SendFile : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} public: WithAsyncMethod_SendFile() { ::grpc::Service::MarkMethodAsync(0); } ~WithAsyncMethod_SendFile() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status SendFile(::grpc::ServerContext* /*context*/, const ::file_trans::Request* /*request*/, ::grpc::ServerWriter< ::file_trans::FileChunk>* /*writer*/) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestSendFile(::grpc::ServerContext* context, ::file_trans::Request* request, ::grpc::ServerAsyncWriter< ::file_trans::FileChunk>* writer, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncServerStreaming(0, context, request, writer, new_call_cq, notification_cq, tag); } }; typedef WithAsyncMethod_SendFile<Service > AsyncService; template <class BaseClass> class ExperimentalWithCallbackMethod_SendFile : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} public: ExperimentalWithCallbackMethod_SendFile() { #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL ::grpc::Service:: #else ::grpc::Service::experimental(). #endif MarkMethodCallback(0, new ::grpc_impl::internal::CallbackServerStreamingHandler< ::file_trans::Request, ::file_trans::FileChunk>( [this]( #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL ::grpc::CallbackServerContext* #else ::grpc::experimental::CallbackServerContext* #endif context, const ::file_trans::Request* request) { return this->SendFile(context, request); })); } ~ExperimentalWithCallbackMethod_SendFile() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status SendFile(::grpc::ServerContext* /*context*/, const ::file_trans::Request* /*request*/, ::grpc::ServerWriter< ::file_trans::FileChunk>* /*writer*/) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL virtual ::grpc::ServerWriteReactor< ::file_trans::FileChunk>* SendFile( ::grpc::CallbackServerContext* /*context*/, const ::file_trans::Request* /*request*/) #else virtual ::grpc::experimental::ServerWriteReactor< ::file_trans::FileChunk>* SendFile( ::grpc::experimental::CallbackServerContext* /*context*/, const ::file_trans::Request* /*request*/) #endif { return nullptr; } }; #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL typedef ExperimentalWithCallbackMethod_SendFile<Service > CallbackService; #endif typedef ExperimentalWithCallbackMethod_SendFile<Service > ExperimentalCallbackService; template <class BaseClass> class WithGenericMethod_SendFile : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} public: WithGenericMethod_SendFile() { ::grpc::Service::MarkMethodGeneric(0); } ~WithGenericMethod_SendFile() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status SendFile(::grpc::ServerContext* /*context*/, const ::file_trans::Request* /*request*/, ::grpc::ServerWriter< ::file_trans::FileChunk>* /*writer*/) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithRawMethod_SendFile : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} public: WithRawMethod_SendFile() { ::grpc::Service::MarkMethodRaw(0); } ~WithRawMethod_SendFile() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status SendFile(::grpc::ServerContext* /*context*/, const ::file_trans::Request* /*request*/, ::grpc::ServerWriter< ::file_trans::FileChunk>* /*writer*/) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestSendFile(::grpc::ServerContext* context, ::grpc::ByteBuffer* request, ::grpc::ServerAsyncWriter< ::grpc::ByteBuffer>* writer, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncServerStreaming(0, context, request, writer, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class ExperimentalWithRawCallbackMethod_SendFile : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} public: ExperimentalWithRawCallbackMethod_SendFile() { #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL ::grpc::Service:: #else ::grpc::Service::experimental(). #endif MarkMethodRawCallback(0, new ::grpc_impl::internal::CallbackServerStreamingHandler< ::grpc::ByteBuffer, ::grpc::ByteBuffer>( [this]( #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL ::grpc::CallbackServerContext* #else ::grpc::experimental::CallbackServerContext* #endif context, const::grpc::ByteBuffer* request) { return this->SendFile(context, request); })); } ~ExperimentalWithRawCallbackMethod_SendFile() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status SendFile(::grpc::ServerContext* /*context*/, const ::file_trans::Request* /*request*/, ::grpc::ServerWriter< ::file_trans::FileChunk>* /*writer*/) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL virtual ::grpc::ServerWriteReactor< ::grpc::ByteBuffer>* SendFile( ::grpc::CallbackServerContext* /*context*/, const ::grpc::ByteBuffer* /*request*/) #else virtual ::grpc::experimental::ServerWriteReactor< ::grpc::ByteBuffer>* SendFile( ::grpc::experimental::CallbackServerContext* /*context*/, const ::grpc::ByteBuffer* /*request*/) #endif { return nullptr; } }; typedef Service StreamedUnaryService; template <class BaseClass> class WithSplitStreamingMethod_SendFile : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} public: WithSplitStreamingMethod_SendFile() { ::grpc::Service::MarkMethodStreamed(0, new ::grpc::internal::SplitServerStreamingHandler< ::file_trans::Request, ::file_trans::FileChunk>( [this](::grpc_impl::ServerContext* context, ::grpc_impl::ServerSplitStreamer< ::file_trans::Request, ::file_trans::FileChunk>* streamer) { return this->StreamedSendFile(context, streamer); })); } ~WithSplitStreamingMethod_SendFile() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status SendFile(::grpc::ServerContext* /*context*/, const ::file_trans::Request* /*request*/, ::grpc::ServerWriter< ::file_trans::FileChunk>* /*writer*/) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with split streamed virtual ::grpc::Status StreamedSendFile(::grpc::ServerContext* context, ::grpc::ServerSplitStreamer< ::file_trans::Request,::file_trans::FileChunk>* server_split_streamer) = 0; }; typedef WithSplitStreamingMethod_SendFile<Service > SplitStreamedService; typedef WithSplitStreamingMethod_SendFile<Service > StreamedService; }; } // namespace file_trans #endif // GRPC_file_5ftrans_2eproto__INCLUDED
[ "amyxu@cs.washington.edu" ]
amyxu@cs.washington.edu
f46de1bd281fa3736931ddc5c85eb5849f2b7ee0
723b67f6a8b202dc5bb009427f60ffd9f185dba8
/devel/include/ros_arduino_msgs/ServoWriteResponse.h
ef1a29d38d970bae98cdea4932c90d41f162ce62
[]
no_license
Dhawgupta/catkin_ws
15edced50d3d69bf78851315658646cd671eb911
edab645f1a94c83925836b36d38ecf2ad8f42abc
refs/heads/master
2021-01-19T10:56:09.954495
2017-04-11T09:52:20
2017-04-11T09:52:20
87,917,514
0
0
null
null
null
null
UTF-8
C++
false
false
5,028
h
// Generated by gencpp from file ros_arduino_msgs/ServoWriteResponse.msg // DO NOT EDIT! #ifndef ROS_ARDUINO_MSGS_MESSAGE_SERVOWRITERESPONSE_H #define ROS_ARDUINO_MSGS_MESSAGE_SERVOWRITERESPONSE_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace ros_arduino_msgs { template <class ContainerAllocator> struct ServoWriteResponse_ { typedef ServoWriteResponse_<ContainerAllocator> Type; ServoWriteResponse_() { } ServoWriteResponse_(const ContainerAllocator& _alloc) { (void)_alloc; } typedef boost::shared_ptr< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> const> ConstPtr; }; // struct ServoWriteResponse_ typedef ::ros_arduino_msgs::ServoWriteResponse_<std::allocator<void> > ServoWriteResponse; typedef boost::shared_ptr< ::ros_arduino_msgs::ServoWriteResponse > ServoWriteResponsePtr; typedef boost::shared_ptr< ::ros_arduino_msgs::ServoWriteResponse const> ServoWriteResponseConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> & v) { ros::message_operations::Printer< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace ros_arduino_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False} // {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'ros_arduino_msgs': ['/home/dawg/catkin_ws/src/ros_arduino_bridge/ros_arduino_msgs/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> > { static const char* value() { return "d41d8cd98f00b204e9800998ecf8427e"; } static const char* value(const ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xd41d8cd98f00b204ULL; static const uint64_t static_value2 = 0xe9800998ecf8427eULL; }; template<class ContainerAllocator> struct DataType< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> > { static const char* value() { return "ros_arduino_msgs/ServoWriteResponse"; } static const char* value(const ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> > { static const char* value() { return "\n\ "; } static const char* value(const ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream&, T) {} ROS_DECLARE_ALLINONE_SERIALIZER }; // struct ServoWriteResponse_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> > { template<typename Stream> static void stream(Stream&, const std::string&, const ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator>&) {} }; } // namespace message_operations } // namespace ros #endif // ROS_ARDUINO_MSGS_MESSAGE_SERVOWRITERESPONSE_H
[ "dhawal.cs15@iitp.ac.in" ]
dhawal.cs15@iitp.ac.in
38f7c8a3cad67c635c35e49aa86561033dd5059e
b2b9e4d616a6d1909f845e15b6eaa878faa9605a
/Genemardon/20150726浙大月赛/H.cpp
a21dd35a335cc1f9d08f48963c32541c661122f1
[]
no_license
JinbaoWeb/ACM
db2a852816d2f4e395086b2b7f2fdebbb4b56837
021b0c8d9c96c1bc6e10374ea98d0706d7b509e1
refs/heads/master
2021-01-18T22:32:50.894840
2016-06-14T07:07:51
2016-06-14T07:07:51
55,882,694
0
0
null
null
null
null
UTF-8
C++
false
false
737
cpp
#include <stdio.h> #include <string.h> #include <algorithm> #include <vector> using namespace std; vector<int>tab[50010]; int n,m,q; int ans[50010]; int main(int argc, char const *argv[]) { while (scanf("%d%d%d",&n,&m,&q) != EOF) { memset(ans,0,sizeof(ans)); for (int i=1;i<=n;i++) tab[i].clear(); for (int i=0;i<m;i++) { int u,v; scanf("%d%d",&u,&v); if (v<u) tab[u].push_back(v); } int m1=n,m2=n; for (int i=n;i>1;i--) { for (int j=0;j<tab[i].size();j++) if (tab[i][j]<m1) { m2=m1; m1=tab[i][j]; } else if (tab[i][j]<m2) { m2=tab[i][j]; } ans[i]=max(i-m2,0); } int ask; for (int i=0;i<q;i++) { scanf("%d",&ask); printf("%d\n", ans[ask]); } } return 0; }
[ "jinbaosite@yeah.net" ]
jinbaosite@yeah.net
85ea4dd8d55151bc08e835ee9c71d1a426ef6ce3
13c402c37ff65709039cb190f9079667429fd31d
/dll/StatisticsClass.cpp
2b0c76776a165c45531775a642a1473fe7a1e2c5
[]
no_license
DarkGL/TrackerUI
7146689298e1b44386b4575d06c96c4c5b461463
3de5fb05c662ba1bb06673d815062de2448ff22b
refs/heads/master
2023-03-17T04:39:45.409222
2023-03-15T06:48:49
2023-03-15T06:48:49
41,966,780
1
1
null
null
null
null
UTF-8
C++
false
false
2,308
cpp
#include "StatisticsClass.h" const char * StatisticsClass::urlNewClient = "http://csiks.pl/pliki/stats/newClient.php"; const char * StatisticsClass::urlPingClient = "http://csiks.pl/pliki/stats/pingClient.php"; char StatisticsClass::token[] = ""; bool StatisticsClass::clientConnected = false; void StatisticsClass::newClient(){ if( this -> getClientConnected() ){ return ; } HINTERNET connectHandle = InternetOpen( "HL" ,0,NULL, NULL, 0); if( !connectHandle ){ return; } char connectUrl[ 512 ]; snprintf( connectUrl , sizeof( connectUrl ) , "%s?version=%s" , StatisticsClass::urlNewClient , currentVersion ); HINTERNET openAddress = InternetOpenUrl( connectHandle , connectUrl , NULL , 0, INTERNET_FLAG_PRAGMA_NOCACHE , 0); if ( !openAddress ){ InternetCloseHandle( connectHandle ); return; } char bufferRead[ 64 ]; DWORD NumberOfBytesRead = 0; InternetReadFile( openAddress , bufferRead , sizeof bufferRead , &NumberOfBytesRead ); if( NumberOfBytesRead <= 0 ){ InternetCloseHandle( openAddress ); InternetCloseHandle( connectHandle ); return; } InternetCloseHandle( openAddress ); InternetCloseHandle( connectHandle ); this -> setToken( bufferRead ); this -> setClientConnected( true ); } void StatisticsClass::pingClient(){ if( !this -> getClientConnected() ){ return ; } char bufferUrl[ 2048 ]; snprintf( bufferUrl , sizeof( bufferUrl ) / sizeof( char ) , "%s?token=%s&version=%s" , StatisticsClass::urlPingClient , this -> getToken() , currentVersion ); HINTERNET connectHandle = InternetOpen( "HL" ,0,NULL, NULL, 0); if( !connectHandle ){ return; } HINTERNET openAddress = InternetOpenUrl( connectHandle , bufferUrl , NULL , 0, INTERNET_FLAG_PRAGMA_NOCACHE , 0); if ( !openAddress ){ InternetCloseHandle( connectHandle ); return; } InternetCloseHandle( openAddress ); InternetCloseHandle( connectHandle ); } bool StatisticsClass::getClientConnected(){ return StatisticsClass::clientConnected; } void StatisticsClass::setClientConnected( bool value ){ StatisticsClass::clientConnected = value; } const char * StatisticsClass::getToken(){ return StatisticsClass::token; } void StatisticsClass::setToken( char * tokenSet ){ strcpy( StatisticsClass::token , tokenSet ); }
[ "gitzzz14@gmail.com" ]
gitzzz14@gmail.com
2b17e47589ce2b7bb6579f599aad8e4a664896b5
b8487f927d9fb3fa5529ad3686535714c687dd50
/include/hermes/VM/JIT/DenseUInt64.h
7cb45f61cba99d132ac4e42fc17f6b4a3b55cbc0
[ "MIT" ]
permissive
hoangtuanhedspi/hermes
4a1399f05924f0592c36a9d4b3fd1f804f383c14
02dbf3c796da4d09ec096ae1d5808dcb1b6062bf
refs/heads/master
2020-07-12T21:21:53.781167
2019-08-27T22:58:17
2019-08-27T22:59:55
204,908,743
1
0
MIT
2019-08-28T17:44:49
2019-08-28T10:44:49
null
UTF-8
C++
false
false
2,568
h
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the LICENSE * file in the root directory of this source tree. */ #ifndef HERMES_VM_JIT_DENSEUINT64_H #define HERMES_VM_JIT_DENSEUINT64_H #include "hermes/VM/HermesValue.h" #include "llvm/ADT/DenseMapInfo.h" namespace hermes { namespace vm { /// A wrapper for using uint64_t with llvm::DenseMap/Set. class DenseUInt64 { public: /// Enum to differentiate between LLVM's empty/tombstone and normal values. enum class MapKeyType { empty, tombstone, valid, }; DenseUInt64(uint64_t cval) : keyType_(MapKeyType::valid), rawValue_(cval) {} DenseUInt64(void *addr) : keyType_(MapKeyType::valid), rawValue_((uint64_t)addr) {} DenseUInt64(HermesValue hv) : keyType_(MapKeyType::valid), rawValue_(hv.getRaw()) {} DenseUInt64(double v) : DenseUInt64(HermesValue::encodeDoubleValue(v)) {} DenseUInt64(MapKeyType keyType) : keyType_(keyType), rawValue_(0) { assert(keyType_ != MapKeyType::valid && "valid entries must have a value"); } bool operator==(const DenseUInt64 &other) const { return keyType_ == other.keyType_ && rawValue_ == other.rawValue_; } HermesValue valueAsHV() const { assert( keyType_ == MapKeyType::valid && "attempting to get the value of tombstone/empty entry"); return HermesValue(rawValue_); } void *valueAsAddr() const { assert( keyType_ == MapKeyType::valid && "attempting to get the value of tombstone/empty entry"); return (void *)rawValue_; } uint64_t rawValue() const { return rawValue_; } private: /// The type of value we have: empty/tombstone/normal. MapKeyType keyType_; /// A raw uint64_t: it could be a HermesValue or an address uint64_t rawValue_; }; } // namespace vm } // namespace hermes namespace llvm { /// Traits to enable using UInt64Constant with llvm::DenseSet/Map. template <> struct DenseMapInfo<hermes::vm::DenseUInt64> { using UInt64Constant = hermes::vm::DenseUInt64; using MapKeyType = UInt64Constant::MapKeyType; static inline UInt64Constant getEmptyKey() { return MapKeyType::empty; } static inline UInt64Constant getTombstoneKey() { return MapKeyType::tombstone; } static inline unsigned getHashValue(UInt64Constant x) { return DenseMapInfo<uint64_t>::getHashValue(x.rawValue()); } static inline bool isEqual(UInt64Constant a, UInt64Constant b) { return a == b; } }; } // namespace llvm #endif // HERMES_VM_JIT_DENSEUINT64_H
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
b54f8af3b8d91ec3312f1936cc121941612c52f9
33c05858242f026297d97a902656ee8f066683a8
/satellite_sniffer_BoTFSM/src/Canvas.cpp
ad8ababfa55c65250d872cc2f5187e0f6e6b207d
[]
no_license
CodecoolBP20171/cpp-satellite-sniffer-botfsm
d8bcb902da2c4f3e2d7b827da0558343022687c3
b29818ae7dc1d2f7f3967c278a3d01c447786df8
refs/heads/master
2021-06-01T16:43:46.978984
2018-09-30T13:10:56
2018-09-30T13:10:56
113,032,533
4
2
null
2018-09-30T13:10:57
2017-12-04T11:09:09
C
UTF-8
C++
false
false
883
cpp
#include "stdafx.h" #include "Canvas.h" #include "Resources.h" #include <SDL.h> Canvas::Canvas(const int width, const int height) { this->height = height; this->width = width; texture = SDL_CreateTexture(Resources::getInstance()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height); SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND); } void Canvas::resize(const int width, const int height) { if (texture) SDL_DestroyTexture(texture); this->height = height; this->width = width; texture = SDL_CreateTexture(Resources::getInstance()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height); SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND); } void Canvas::setAsRenderTarget() { SDL_SetRenderTarget(Resources::getInstance()->getRenderer(), texture); } Canvas::~Canvas() { }
[ "afga93+cc@gmail.com" ]
afga93+cc@gmail.com
583d34be535e307cea59286df8c350b922d68244
4dabe3dca7a679a5ba7c79cd4e0384657657dec2
/views/console/proposedCombinationView.cpp
71f0f78cfcc080d0bf61444707db3121b212baf5
[]
no_license
carlosv5/MasterMind
47285e4a3b191294bc07650873fb13e46459e42d
b45c61a264c936191e8db23f27234b91943e7638
refs/heads/master
2020-04-20T12:26:51.642639
2019-05-11T19:05:23
2019-05-11T19:05:23
150,888,071
0
0
null
null
null
null
UTF-8
C++
false
false
2,741
cpp
#include <assert.h> #include <iostream> #include "proposedCombinationView.hpp" #include "../../controllers/colocateController.hpp" #include "../../models/proposedCombination.hpp" using namespace std; ProposedCombinationView::ProposedCombinationView(){}; ProposedCombination ProposedCombinationView::readProposedCombination(ProposedCombination proposedCombination, int SIZE_COMBINATION){ showColorOptions(); std::cout << "--Insert your colors (XXXX)--" << std::endl; std::string combinationString; getline(std::cin, combinationString); char * combination = proposedCombination.getCombination(); for (int i = 0; i < SIZE_COMBINATION; i++) { char *colorArray = new char[Color::numberOfColors]; Color::values(colorArray); bool isAColor = false; for (int j = 0; j < Color::numberOfColors; j++) { if (combinationString[i] == colorArray[j]) { isAColor = true; } } assert(isAColor); char colorToInsert = combinationString[i]; combination[i] = colorToInsert; } return proposedCombination; } void ProposedCombinationView::showColorOptions() { std::cout << "You can use these colors:" << std::endl; char *colorArray = new char[Color::numberOfColors]; Color::values(colorArray); for (int i = 0; i < Color::numberOfColors; i++) { std::cout << colorArray[i] << " "; } std::cout << std::endl; delete (colorArray); } void ProposedCombinationView::printResults(ProposedCombination * proposedCombinations, int turn) { std::cout << "Results:" << std::endl; for (int i = 0; i < turn + 1; i++){ for (int j = 0; j < proposedCombinations[0].getSize(); j++) { std::cout << "|" << proposedCombinations[i].getCombination()[j] << "|" << " "; } std::cout << "Results:|" << proposedCombinations[i].getResults()[INDEX_BLACK_RESULT] << " Blacks|" << proposedCombinations[i].getResults()[INDEX_WHITE_RESULT] << "Whites|" << " " << std::endl; } } void ProposedCombinationView::printPreviewCombinations(ProposedCombination * proposedCombinations, int turn) { std::cout << "The board is:" << std::endl; for (int i = 0; i < turn; i++){ for (int j = 0; j < proposedCombinations[0].getSize(); j++) { std::cout << "|" << proposedCombinations[i].getCombination()[j] << "|" << " "; } std::cout << "Results:|" << proposedCombinations[i].getResults()[INDEX_BLACK_RESULT] << " Blacks|" << proposedCombinations[i].getResults()[INDEX_WHITE_RESULT] << "Whites|" << " " << std::endl; } }
[ "c.vegag5@gmail.com" ]
c.vegag5@gmail.com
0097d92533baaeb7b0f9a69817088336a809c56e
e9c9efaa1f19a28a5154c19312b2871cc4449f92
/src/fsw/FCCode/ADCSBoxController.hpp
d57a42f104cc371266e2b4a71bca2c39e6067346
[ "MIT" ]
permissive
Vsj986/FlightSoftware
52bc663d00786e6866a4cbaf2c04282cacf4ad97
c8ae3504a1685d05556a0c9253b147f9d24c03b6
refs/heads/master
2022-04-24T23:48:34.531495
2020-04-28T08:07:32
2020-04-28T08:07:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,690
hpp
#ifndef ADCS_BOX_CONTROLLER_HPP_ #define ADCS_BOX_CONTROLLER_HPP_ #include "Drivers/ADCS.hpp" #include "TimedControlTask.hpp" /** * @brief Takes input command statefields and commands the ADCS Box. * * Note this CT doesn't do any computing, just actuation * This CT is inteded to only do hardware calls */ class ADCSBoxController : public TimedControlTask<void> { public: /** * @brief Construct a new ADCSBoxController control task * * @param registry input StateField registry * @param offset control task offset * @param _adcs the input adcs system */ ADCSBoxController(StateFieldRegistry &registry, unsigned int offset, Devices::ADCS &_adcs); /** ADCS Driver. **/ Devices::ADCS& adcs_system; /** * @brief Given the command statefields, use the ADCS driver to execute */ void execute() override; protected: /** * @brief Command to get from mission_manager * */ const WritableStateField<unsigned char>* adcs_state_fp; /** * @brief RWA command fields * */ const WritableStateField<unsigned char>* rwa_mode_fp; const WritableStateField<f_vector_t>* rwa_speed_cmd_fp; const WritableStateField<f_vector_t>* rwa_torque_cmd_fp; const WritableStateField<float>* rwa_speed_filter_fp; const WritableStateField<float>* rwa_ramp_filter_fp; /** * @brief MTR command fields * */ const WritableStateField<unsigned char>* mtr_mode_fp; const WritableStateField<f_vector_t>* mtr_cmd_fp; const WritableStateField<float>* mtr_limit_fp; /** * @brief SSA command fields * */ const ReadableStateField<unsigned char>* ssa_mode_fp; const WritableStateField<float>* ssa_voltage_filter_fp; /** * @brief IMU command fields * */ const WritableStateField<unsigned char>* mag1_mode_fp; const WritableStateField<unsigned char>* mag2_mode_fp; const WritableStateField<float>* imu_mag_filter_fp; const WritableStateField<float>* imu_gyr_filter_fp; const WritableStateField<float>* imu_gyr_temp_filter_fp; const WritableStateField<float>* imu_gyr_temp_kp_fp; const WritableStateField<float>* imu_gyr_temp_ki_fp; const WritableStateField<float>* imu_gyr_temp_kd_fp; const WritableStateField<float>* imu_gyr_temp_desired_fp; /** * @brief HAVT command tables, a vector of pointers to bool state fields * */ std::vector<WritableStateField<bool>*> havt_cmd_reset_vector_fp; std::vector<WritableStateField<bool>*> havt_cmd_disable_vector_fp; }; #endif
[ "noreply@github.com" ]
noreply@github.com
22b4b85995b27b9bf5a3b2c844bcb56c4ab65e55
090243cf699213f32f870baf2902eb4211f825d6
/cf/621/D.cpp
27cba968aae8be25270c8a561e72debc59131184
[]
no_license
zhu-he/ACM-Source
0d4d0ac0668b569846b12297e7ed4abbb1c16571
02e3322e50336063d0d2dad37b2761ecb3d4e380
refs/heads/master
2021-06-07T18:27:19.702607
2016-07-10T09:20:48
2016-07-10T09:20:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
625
cpp
#include <cstdio> #include <cmath> const char s[12][10] = {"x^y^z", "x^z^y", "(x^y)^z", "(x^z)^y", "y^x^z", "y^z^x", "(y^x)^z", "(y^z)^x", "z^x^y", "z^y^x", "(z^x)^y", "(z^y)^x"}; double d[12]; int main() { double x, y, z; scanf("%lf %lf %lf", &x, &y, &z); d[0] = pow(y, z) * log(x); d[1] = pow(z, y) * log(x); d[2] = d[3] = y * z * log(x); d[4] = pow(x, z) * log(y); d[5] = pow(z, x) * log(y); d[6] = d[7] = x * z * log(y); d[8] = pow(x, y) * log(z); d[9] = pow(y, x) * log(z); d[10] = d[11] = x * y * log(z); int mx = 0; for (int i = 1; i < 12; ++i) if (d[i] > d[mx]) mx = i; puts(s[mx]); return 0; }
[ "841815229@qq.com" ]
841815229@qq.com
6dab7827ababfb8c432c08e1e9a9dc6eff7e91be
866948421e7f22480da2bdf699c54220734e3a4b
/C/permutation.cpp
1de35f518bc8136f4d30d264ac7ce768cd0b7ed8
[]
no_license
QinShelly/workspace
f0f5aba1280a1a112cf7df316b7857454338fb2d
4734ec9e561c64bcbdb11e321163048c1c140f58
refs/heads/master
2020-07-06T21:49:25.249134
2020-02-08T07:34:34
2020-02-08T07:34:34
67,876,658
1
1
null
null
null
null
UTF-8
C++
false
false
530
cpp
#include <iostream> int a[10],book[10],n; void dfs(int step){ int i; if (step == n + 1) { for (i=1; i<=n; i++) { printf(" %d",a[i]); } printf("\n"); } for (i = 1; i <= n; i++) { if (book[i] == 0 ) { a[step] = i; book[i] = 1; dfs(step + 1); book[i] = 0; } } return; } int main(int argc, const char * argv[]) { scanf("%d",&n); dfs(1); getchar(); return 0; }
[ "Shelly.Qin@outlook.com" ]
Shelly.Qin@outlook.com
6af9d762a27675c814e1f06738962bbda04fa16b
311525f7de84975434f55c00b545ccf7fe3dcce6
/oi/japan/joisc/2017/day2/arranging_tickets.cpp
d2f48dc83125e17fcf6fcfd2ff8db33c7cff6918
[]
no_license
fishy15/competitive_programming
60f485bc4022e41efb0b7d2e12d094213d074f07
d9bca2e6bea704f2bfe5a30e08aa0788be6a8022
refs/heads/master
2023-08-16T02:05:08.270992
2023-08-06T01:00:21
2023-08-06T01:00:21
171,861,737
29
5
null
null
null
null
UTF-8
C++
false
false
7,612
cpp
/* * We can first split the circle at 0, initially marking each range from the lower number to the higher * number. First, we note that we never want to flip both [a, b) and [c, d) where a < b <= c < d. This * increases the count at each location not within the ranges by 2, and the values within the ranges don't * change. Therefore, this only makes the situation worse. * * We can then binary search for the answer. Let the answer we are checking for be m. We can also define * two other parameters: n will be the total number of ranges flipped, and t will be a point that all the * ranges flipped will have in common (which must exist as we have shown earlier). For a given point, if * there are currently a people that go over the point and there are n' tickets left to assign, then the * amount of ranges we have to flip is max(ceil((a + n' - m) / 2), 0). We maintain a set of ranges to flip * and then greedily flip the rightmost edges in the set, flipping as many as we need. Afterwards, we can * do a final check to see if it works. Overall, this is O(n^2 m log(n) log(sum of c)). * * We can do two optimizations to this. First, we will try to limit the values of n that we will check. * Let a_i denote the initial values, and b_i be the values after doing all necessary flips. We will prove * that we can always pick a value of t such that b_t = or b_t = max(b_i) - 1. First of all, t can * be any value in the intersection of all the ranges picked, so we can choose t to have the maximum value * in the range. Now, suppose that there is some value outside of the intersection i such that b_i > b_t. * We can then unflip both the flipped intervals with the leftmost right bound and the rightmost left bound * If both ranges are distinct, then the b_i value of everything within the intersection will increase by * +2 (increase by +1 if the ranges are not distinct). By repeating this process, we will either end up * with b_t = m or b_t = m - 1, so our proof is done. Since n ranges will cover t, the b_t = a_t - n, * so n = a_t - m or n = a_t - m + 1. * * Now, we want to limit the values of t that we have to check. We can first limit the candidates to t to * be the values of i where a_i is the maximum of the array. If we let x_i denote the number of ranges * flipped that include location i, then we know that x_j < x_t if j is not in the intersection. Taking the * maximum possible value of b_j, we have b_j <= b_t + 1 and x_j + 1 <= x_t. Since a_i = x_i + b_i, we get * that a_j <= a_t if j is not in the interesction, so a_t must be the maxmimum of a. * * Next, we will show that we only need to check the leftmost and rightmost indices where a_i is at its * maximum. Denote these left and right indices by l and r. First, we will show that there is no need to * flip a range [c, d) where l < c < d <= r. Suppose that there is some such range that we flip. If we * unflip it, then everything outside the range decrements by 1, so it is still valid. Everything inside * of the range increments by 1 as well. However, since x_l > x_t since l is not within the intersection * of all flipped intervals, b_l > b_t originally, so incrementing b_t by 1 does not make the configuration * invalid. Therefore, every interval that we flip must either include l or r. If there exists two intervals * where one does not include l and the other does not include r, then we can unflip both of them. Let b' * represent the new values at each location. For similar reasons as before, b'_l >= b'_i for l <= i <= r * because a_l and a_r are the max values of a over the entire array, but x'_l and x'_r are still the * lowest values between l and r (since they are the farthest from t). Everything outside of l and r will * either not change in value or decrease by 2, so overall, the combination is still valid. We can keep * repeating this process until all remaining ranges contain either l or r, so we could have chosen t = l * or t = r. Therefore, we only need to check these two location. * * Overall, this cuts a factor of O(nm) from the solution, so the new time complexity is * O(n log(n) log(sum of c)), which passes. */ #include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <array> #include <algorithm> #include <utility> #include <map> #include <queue> #include <set> #include <cmath> #include <cstdio> #include <cstring> #define ll long long #define ld long double #define eps 1e-8 #define MOD 1000000007 #define INF 0x3f3f3f3f #define INFLL 0x3f3f3f3f3f3f3f3f // change if necessary #define MAXN 200010 using namespace std; int n, m; vector<array<int, 3>> range[MAXN]; ll init[MAXN]; int min_check, max_check; struct cmp { bool operator()(const array<int, 3> &a, const array<int, 3> &b) const { if (a[1] == b[1]) { if (a[0] == b[0]) { return a[2] < b[2]; } return a[0] > b[0]; } return a[1] < b[1]; } }; struct bit { ll vals[MAXN]; void reset() { for (int i = 0; i < n + 10; i++) { vals[i] = 0; } for (int i = 0; i < n; i++) { ll x = init[i]; if (i) x -= init[i - 1]; upd(i, x); } } void upd(int x, ll v) { x++; while (x < n + 10) { vals[x] += v; x += x & -x; } } void upd(int l, int r, ll v) { upd(l, v); upd(r, -v); } ll qry(int x) { x++; ll res = 0; while (x) { res += vals[x]; x -= x & -x; } return res; } } b; ll check(ll m, ll n, ll t) { b.reset(); priority_queue<array<int, 3>, vector<array<int, 3>>, cmp> pq; for (int i = 0; i <= t; i++) { ll need_rem = max((b.qry(i) + n - m + 1) / 2, 0LL); n -= need_rem; for (auto &arr : range[i]) { if (arr[1] > t) { pq.push(arr); } } while (need_rem) { if (pq.empty()) { return false; } auto t = pq.top(); pq.pop(); ll to_rem = min<ll>(t[2], need_rem); b.upd(0, t[0], to_rem); b.upd(t[0], t[1], -to_rem); b.upd(t[1], ::n, to_rem); t[2] -= to_rem; need_rem -= to_rem; if (t[2]) pq.push(t); } } for (int i = 0; i < ::n; i++) { if (b.qry(i) > m) { return false; } } return true; } ll check(ll m) { ll a = init[min_check]; return check(m, a - m, min_check) || check(m, a - m + 1, min_check) || check(m, a - m, max_check) || check(m, a - m + 1, max_check); } int main() { cin.tie(0)->sync_with_stdio(0); cin >> n >> m; for (int i = 0; i < m; i++) { int a, b, c; cin >> a >> b >> c; a--; b--; if (a > b) swap(a, b); init[a] += c; init[b] -= c; range[a].push_back({a, b, c}); } for (int i = 1; i < n; i++) { init[i] += init[i - 1]; } for (int i = 0; i < n; i++) { if (init[i] > init[min_check]) { min_check = i; max_check = i; } else if (init[i] == init[min_check]) { max_check = i; } } ll l = 0; ll r = init[min_check]; ll ans = init[min_check]; while (l <= r) { ll m = (l + r) / 2; if (check(m)) { ans = m; r = m - 1; } else { l = m + 1; } } cout << ans << '\n'; return 0; }
[ "aaryan.prakash3.14@gmail.com" ]
aaryan.prakash3.14@gmail.com
579829351084c1173b9154fd34d518856cd45da2
829869a01da6da0f17dcc173bb5ddd640fd8ba2c
/src/server/test/pegasus_write_service_impl_test.cpp
f3ee0a89b6f99cdf004fb08a169bca7d8300c1f6
[ "Apache-2.0" ]
permissive
SunnyShow/incubator-pegasus
fff92fa95354c7e44de6c82eb6bb4e6181b8f86d
c02e055e803dab479a31d3cac31739b75542f804
refs/heads/master
2022-12-21T00:30:26.747514
2020-09-28T16:03:42
2020-09-28T16:03:42
299,217,109
0
0
Apache-2.0
2020-09-28T06:57:47
2020-09-28T06:57:47
null
UTF-8
C++
false
false
8,058
cpp
// Copyright (c) 2017, Xiaomi, Inc. All rights reserved. // This source code is licensed under the Apache License Version 2.0, which // can be found in the LICENSE file in the root directory of this source tree. #include "pegasus_server_test_base.h" #include "server/pegasus_server_write.h" #include "server/pegasus_write_service_impl.h" #include "message_utils.h" #include <dsn/utility/defer.h> namespace pegasus { namespace server { class pegasus_write_service_impl_test : public pegasus_server_test_base { protected: std::unique_ptr<pegasus_server_write> _server_write; pegasus_write_service::impl *_write_impl{nullptr}; public: void SetUp() override { start(); _server_write = dsn::make_unique<pegasus_server_write>(_server.get(), true); _write_impl = _server_write->_write_svc->_impl.get(); } uint64_t read_timestamp_from(dsn::string_view raw_key) { std::string raw_value; rocksdb::Status s = _write_impl->_db->Get( _write_impl->_rd_opts, utils::to_rocksdb_slice(raw_key), &raw_value); uint64_t local_timetag = pegasus_extract_timetag(_write_impl->_pegasus_data_version, raw_value); return extract_timestamp_from_timetag(local_timetag); } // start with duplicating. void set_app_duplicating() { _server->stop(false); dsn::replication::destroy_replica(_replica); dsn::app_info app_info; app_info.app_type = "pegasus"; app_info.duplicating = true; _replica = dsn::replication::create_test_replica(_replica_stub, _gpid, app_info, "./", false); _server = dsn::make_unique<pegasus_server_impl>(_replica); SetUp(); } int db_get(dsn::string_view raw_key, db_get_context *get_ctx) { return _write_impl->db_get(raw_key, get_ctx); } void single_set(dsn::blob raw_key, dsn::blob user_value) { dsn::apps::update_request put; put.key = raw_key; put.value = user_value; db_write_context write_ctx; dsn::apps::update_response put_resp; _write_impl->batch_put(write_ctx, put, put_resp); ASSERT_EQ(_write_impl->batch_commit(0), 0); } }; TEST_F(pegasus_write_service_impl_test, put_verify_timetag) { set_app_duplicating(); dsn::blob raw_key; pegasus::pegasus_generate_key( raw_key, dsn::string_view("hash_key"), dsn::string_view("sort_key")); std::string value = "value"; int64_t decree = 10; /// insert timestamp 10 uint64_t timestamp = 10; auto ctx = db_write_context::create(decree, timestamp); ASSERT_EQ(0, _write_impl->db_write_batch_put_ctx(ctx, raw_key, value, 0)); ASSERT_EQ(0, _write_impl->db_write(ctx.decree)); _write_impl->clear_up_batch_states(decree, 0); ASSERT_EQ(read_timestamp_from(raw_key), timestamp); /// insert timestamp 15, which overwrites the previous record timestamp = 15; ctx = db_write_context::create(decree, timestamp); ASSERT_EQ(0, _write_impl->db_write_batch_put_ctx(ctx, raw_key, value, 0)); ASSERT_EQ(0, _write_impl->db_write(ctx.decree)); _write_impl->clear_up_batch_states(decree, 0); ASSERT_EQ(read_timestamp_from(raw_key), timestamp); /// insert timestamp 15 from remote, which will overwrite the previous record, /// since its cluster id is larger (current cluster_id=1) timestamp = 15; ctx.remote_timetag = pegasus::generate_timetag(timestamp, 2, false); ctx.verify_timetag = true; ASSERT_EQ(0, _write_impl->db_write_batch_put_ctx(ctx, raw_key, value + "_new", 0)); ASSERT_EQ(0, _write_impl->db_write(ctx.decree)); _write_impl->clear_up_batch_states(decree, 0); ASSERT_EQ(read_timestamp_from(raw_key), timestamp); std::string raw_value; dsn::blob user_value; rocksdb::Status s = _write_impl->_db->Get(_write_impl->_rd_opts, utils::to_rocksdb_slice(raw_key), &raw_value); pegasus_extract_user_data(_write_impl->_pegasus_data_version, std::move(raw_value), user_value); ASSERT_EQ(user_value.to_string(), "value_new"); // write retry ASSERT_EQ(0, _write_impl->db_write_batch_put_ctx(ctx, raw_key, value + "_new", 0)); ASSERT_EQ(0, _write_impl->db_write(ctx.decree)); _write_impl->clear_up_batch_states(decree, 0); /// insert timestamp 16 from local, which will overwrite the remote record, /// since its timestamp is larger timestamp = 16; ctx = db_write_context::create(decree, timestamp); ASSERT_EQ(0, _write_impl->db_write_batch_put_ctx(ctx, raw_key, value, 0)); ASSERT_EQ(0, _write_impl->db_write(ctx.decree)); _write_impl->clear_up_batch_states(decree, 0); ASSERT_EQ(read_timestamp_from(raw_key), timestamp); // write retry ASSERT_EQ(0, _write_impl->db_write_batch_put_ctx(ctx, raw_key, value, 0)); ASSERT_EQ(0, _write_impl->db_write(ctx.decree)); _write_impl->clear_up_batch_states(decree, 0); } // verify timetag on data version v0 TEST_F(pegasus_write_service_impl_test, verify_timetag_compatible_with_version_0) { dsn::fail::setup(); dsn::fail::cfg("db_get", "100%1*return()"); // if db_write_batch_put_ctx invokes db_get, this test must fail. const_cast<uint32_t &>(_write_impl->_pegasus_data_version) = 0; // old version dsn::blob raw_key; pegasus::pegasus_generate_key( raw_key, dsn::string_view("hash_key"), dsn::string_view("sort_key")); std::string value = "value"; int64_t decree = 10; uint64_t timestamp = 10; auto ctx = db_write_context::create_duplicate(decree, timestamp, true); ASSERT_EQ(0, _write_impl->db_write_batch_put_ctx(ctx, raw_key, value, 0)); ASSERT_EQ(0, _write_impl->db_write(ctx.decree)); _write_impl->clear_up_batch_states(decree, 0); dsn::fail::teardown(); } class incr_test : public pegasus_write_service_impl_test { public: void SetUp() override { pegasus_write_service_impl_test::SetUp(); pegasus::pegasus_generate_key( req.key, dsn::string_view("hash_key"), dsn::string_view("sort_key")); } dsn::apps::incr_request req; dsn::apps::incr_response resp; }; TEST_F(incr_test, incr_on_absent_record) { // ensure key is absent db_get_context get_ctx; db_get(req.key, &get_ctx); ASSERT_FALSE(get_ctx.found); req.increment = 100; _write_impl->incr(0, req, resp); ASSERT_EQ(resp.new_value, 100); db_get(req.key, &get_ctx); ASSERT_TRUE(get_ctx.found); } TEST_F(incr_test, negative_incr_and_zero_incr) { req.increment = -100; ASSERT_EQ(0, _write_impl->incr(0, req, resp)); ASSERT_EQ(resp.new_value, -100); req.increment = -1; ASSERT_EQ(0, _write_impl->incr(0, req, resp)); ASSERT_EQ(resp.new_value, -101); req.increment = 0; ASSERT_EQ(0, _write_impl->incr(0, req, resp)); ASSERT_EQ(resp.new_value, -101); } TEST_F(incr_test, invalid_incr) { single_set(req.key, dsn::blob::create_from_bytes("abc")); req.increment = 10; _write_impl->incr(1, req, resp); ASSERT_EQ(resp.error, rocksdb::Status::kInvalidArgument); ASSERT_EQ(resp.new_value, 0); single_set(req.key, dsn::blob::create_from_bytes("100")); req.increment = std::numeric_limits<int64_t>::max(); _write_impl->incr(1, req, resp); ASSERT_EQ(resp.error, rocksdb::Status::kInvalidArgument); ASSERT_EQ(resp.new_value, 100); } TEST_F(incr_test, fail_on_get) { dsn::fail::setup(); dsn::fail::cfg("db_get", "100%1*return()"); // when db_get failed, incr should return an error. req.increment = 10; _write_impl->incr(1, req, resp); ASSERT_EQ(resp.error, FAIL_DB_GET); dsn::fail::teardown(); } TEST_F(incr_test, fail_on_put) { dsn::fail::setup(); dsn::fail::cfg("db_write_batch_put", "100%1*return()"); // when rocksdb put failed, incr should return an error. req.increment = 10; _write_impl->incr(1, req, resp); ASSERT_EQ(resp.error, FAIL_DB_WRITE_BATCH_PUT); dsn::fail::teardown(); } } // namespace server } // namespace pegasus
[ "noreply@github.com" ]
noreply@github.com
6ac48384b37ee2583609e4478de1a2f61b0ef09a
a7ec77cc491d24998e00a68a203c54b9e121ef79
/SDK/include/SoT_Interaction_enums.hpp
b48b3df2a125a4b79427c6855e7e76f7316ab0bd
[]
no_license
EO-Zanzo/zSoT-DLL
a213547ca63a884a009991b9a5c49f7c08ecffcb
3b241befbb47062cda3cebc3ac0cf12e740ddfd7
refs/heads/master
2020-12-26T21:21:14.909021
2020-02-01T17:39:43
2020-02-01T17:39:43
237,647,839
4
1
null
2020-02-01T17:05:08
2020-02-01T17:05:08
null
UTF-8
C++
false
false
866
hpp
#pragma once // Sea of Thieves (2.0) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- //Enums //--------------------------------------------------------------------------- // Enum Interaction.EInteractionBlockReason enum class EInteractionBlockReason : uint8_t { EInteractionBlockReason__None = 0, EInteractionBlockReason__Radial = 1, EInteractionBlockReason__Other = 2, EInteractionBlockReason__EInteractionBlockReason_MAX = 3 }; // Enum Interaction.EInteractionObject enum class EInteractionObject : uint8_t { EInteractionObject__None = 0, EInteractionObject__Shop = 1, EInteractionObject__Chest = 2, EInteractionObject__Barrel = 3, EInteractionObject__EInteractionObject_MAX = 4 }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
759a015ca9170f3456ab0ac5f3a1626efca68ad7
483428f23277dc3fd2fad6588de334fc9b8355d2
/hpp/iOSDevice32/Release/uTPLb_MemoryStreamPool.hpp
bee8378fa9718a035cca20b9ad1bd10f11e6c5d4
[]
no_license
gzwplato/LockBox3-1
7084932d329beaaa8169b94729c4b05c420ebe44
89e300b47f8c1393aefbec01ffb89ddf96306c55
refs/heads/master
2021-05-10T18:41:18.748523
2015-07-04T09:48:06
2015-07-04T09:48:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,375
hpp
// CodeGear C++Builder // Copyright (c) 1995, 2015 by Embarcadero Technologies, Inc. // All rights reserved // (DO NOT EDIT: machine generated header) 'uTPLb_MemoryStreamPool.pas' rev: 29.00 (iOS) #ifndef Utplb_memorystreampoolHPP #define Utplb_memorystreampoolHPP #pragma delphiheader begin #pragma option push #pragma option -w- // All warnings off #pragma option -Vx // Zero-length empty class member #pragma pack(push,8) #include <System.hpp> #include <SysInit.hpp> #include <System.Classes.hpp> //-- user supplied ----------------------------------------------------------- namespace Utplb_memorystreampool { //-- forward type declarations ----------------------------------------------- __interface IMemoryStreamPool; typedef System::DelphiInterface<IMemoryStreamPool> _di_IMemoryStreamPool; class DELPHICLASS TPooledMemoryStream; //-- type declarations ------------------------------------------------------- __interface INTERFACE_UUID("{ADB2D4BA-40F6-4249-923E-201D4719609B}") IMemoryStreamPool : public System::IInterface { virtual int __fastcall BayCount(void) = 0 ; virtual void __fastcall GetUsage(int Size, int &Current, int &Peak) = 0 ; virtual int __fastcall GetSize(int Idx) = 0 ; virtual System::Classes::TMemoryStream* __fastcall NewMemoryStream(int InitSize) = 0 ; }; #pragma pack(push,4) class PASCALIMPLEMENTATION TPooledMemoryStream : public System::Classes::TMemoryStream { typedef System::Classes::TMemoryStream inherited; protected: _di_IMemoryStreamPool FPool; int FCoVector; virtual void * __fastcall Realloc(int &NewCapacity); public: __fastcall TPooledMemoryStream(const _di_IMemoryStreamPool Pool1); public: /* TMemoryStream.Destroy */ inline __fastcall virtual ~TPooledMemoryStream(void) { } }; #pragma pack(pop) //-- var, const, procedure --------------------------------------------------- extern DELPHI_PACKAGE _di_IMemoryStreamPool __fastcall NewPool(void); } /* namespace Utplb_memorystreampool */ #if !defined(DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE) && !defined(NO_USING_NAMESPACE_UTPLB_MEMORYSTREAMPOOL) using namespace Utplb_memorystreampool; #endif #pragma pack(pop) #pragma option pop #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // Utplb_memorystreampoolHPP
[ "roman.kassebaum@kdv-dt.de" ]
roman.kassebaum@kdv-dt.de
31c05ddd07b9d79686913c8c08a00eaf1395abbb
6fdd703d48a01bb73bf658c8d3aac0d98f965967
/src_cpp/elfgames/go/train/data_loader.h
472fb3d536934f874a4ab6fd4147fce6d3ed1d0d
[ "BSD-3-Clause" ]
permissive
roughsoft/ELF
27f762aad66f4946411f2fdae71a45fabd028730
751eb1cf85aac15e3c3c792a47afa1ac64ea810c
refs/heads/master
2020-03-25T19:54:55.579846
2018-08-08T21:34:11
2018-08-08T21:34:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,596
h
/** * Copyright (c) 2018-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include "../common/record.h" #include "elf/distributed/shared_reader.h" #include "elf/distributed/shared_rw_buffer2.h" struct Stats { std::atomic<int> client_size; std::atomic<int> buffer_size; std::atomic<int> failed_count; std::atomic<int> msg_count; std::atomic<uint64_t> total_msg_size; Stats() : client_size(0), buffer_size(0), failed_count(0), msg_count(0), total_msg_size(0) {} std::string info() const { std::stringstream ss; ss << "#msg: " << buffer_size << " #client: " << client_size << ", "; ss << "Msg count: " << msg_count << ", avg msg size: " << (float)(total_msg_size) / msg_count << ", failed count: " << failed_count; return ss.str(); } void feed(const elf::shared::InsertInfo& insert_info) { if (!insert_info.success) { failed_count++; } else { buffer_size += insert_info.delta; msg_count++; total_msg_size += insert_info.msg_size; } } }; class DataInterface { public: virtual void OnStart() {} virtual elf::shared::InsertInfo OnReceive( const std::string& identity, const std::string& msg) = 0; virtual bool OnReply(const std::string& identity, std::string* msg) = 0; }; class DataOnlineLoader { public: DataOnlineLoader(const elf::shared::Options& net_options) : logger_(elf::logging::getLogger("DataOnlineLoader-", "")) { auto curr_timestamp = time(NULL); const std::string database_name = "data-" + std::to_string(curr_timestamp) + ".db"; reader_.reset(new elf::shared::Reader(database_name, net_options)); std::cout << reader_->info() << std::endl; } void start(DataInterface* interface) { auto proc_func = [&, interface]( elf::shared::Reader* reader, const std::string& identity, const std::string& msg) -> bool { (void)reader; try { auto info = interface->OnReceive(identity, msg); stats_.feed(info); /* if (options_.verbose) { std::cout << "Content from " << identity << ", msg_size: " << msg.size() << ", " << stats_.info() << std::endl; } */ if (stats_.msg_count % 1000 == 0) { std::cout << elf_utils::now() << ", last_identity: " << identity << ", " << stats_.info() << std::endl; } return info.success; } catch (...) { logger_->error("Data malformed! String is {}", msg); return false; } }; auto replier_func = [&, interface]( elf::shared::Reader* reader, const std::string& identity, std::string* msg) -> bool { (void)reader; interface->OnReply(identity, msg); if (logger_->should_log(spdlog::level::level_enum::debug)) { logger_->debug( "Replier: about to send: recipient {}; msg {}; reader {}", identity, *msg, reader_->info()); } return true; }; reader_->startReceiving( proc_func, replier_func, [interface]() { interface->OnStart(); }); } ~DataOnlineLoader() {} private: std::unique_ptr<elf::shared::Reader> reader_; Stats stats_; std::shared_ptr<spdlog::logger> logger_; };
[ "noreplyspamblackhole@gmail.com" ]
noreplyspamblackhole@gmail.com
ec71eee9144a294508e930330ca1e438fb3fc919
32b88f828b33279cfe33420c2ed969131a7df987
/Code/Core/Mem/MemTracker.cpp
777a97039b84548fb8dbfdacb216b93ff26a076f
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
punitchandra/fastbuild
53b51f001350104629e71434bb5e521a1bb63cae
8a445d77343bc4881b33a5ebcf31a2ec8777ae2d
refs/heads/master
2021-01-15T13:23:26.995800
2017-08-21T15:05:32
2017-08-21T15:05:32
38,138,811
0
0
null
2015-06-26T23:30:24
2015-06-26T23:30:23
null
UTF-8
C++
false
false
7,281
cpp
// MemTracker.cpp //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include "Core/PrecompiledHeader.h" #include "MemTracker.h" //------------------------------------------------------------------------------ #if defined( MEMTRACKER_ENABLED ) // Includes //------------------------------------------------------------------------------ #include "Core/Mem/MemPoolBlock.h" #include "Core/Process/Atomic.h" #include "Core/Process/Thread.h" #include "Core/Tracing/Tracing.h" // system #include <memory.h> // for memset // Static Data //------------------------------------------------------------------------------ /*static*/ uint32_t MemTracker::s_Id( 0 ); /*static*/ bool MemTracker::s_Enabled( true ); /*static*/ bool MemTracker::s_Initialized( false ); /*static*/ uint32_t MemTracker::s_AllocationCount( 0 ); /*static*/ uint64_t MemTracker::s_Mutex[]; /*static*/ MemTracker::Allocation ** MemTracker::s_AllocationHashTable = nullptr; /*static*/ MemPoolBlock * MemTracker::s_Allocations( nullptr ); // Thread-Local Data //------------------------------------------------------------------------------ THREAD_LOCAL uint32_t g_MemTrackerDisabledOnThisThread( 0 ); // Defines #define ALLOCATION_MINIMUM_ALIGN ( 0x4 ) // assume at least 4 byte alignment #define ALLOCATION_HASH_SHIFT ( 0x2 ) // shift off lower bits #define ALLOCATION_HASH_SIZE ( 0x100000 ) // one megabyte #define ALLOCATION_HASH_MASK ( 0x0FFFFF ) // mask off upper bits // Alloc //------------------------------------------------------------------------------ /*static*/ void MemTracker::Alloc( void * ptr, size_t size, const char * file, int line ) { if ( !s_Enabled ) { return; } // handle allocations during initialization if ( g_MemTrackerDisabledOnThisThread ) { return; } ++g_MemTrackerDisabledOnThisThread; if ( !s_Initialized ) { Init(); } const size_t hashIndex = ( ( (size_t)ptr >> ALLOCATION_HASH_SHIFT ) & ALLOCATION_HASH_MASK ); { MutexHolder mh( GetMutex() ); Allocation * a = (Allocation *)s_Allocations->Alloc( sizeof( Allocation ) ); ++s_AllocationCount; a->m_Id = ++s_Id; a->m_Ptr = ptr; a->m_Size = size; a->m_Next = s_AllocationHashTable[ hashIndex ]; a->m_File = file; a->m_Line = line; static size_t breakOnSize = (size_t)-1; static uint32_t breakOnId = 0; if ( ( size == breakOnSize ) || ( a->m_Id == breakOnId ) ) { BREAK_IN_DEBUGGER; } s_AllocationHashTable[ hashIndex ] = a; } --g_MemTrackerDisabledOnThisThread; } // Free //------------------------------------------------------------------------------ /*static*/ void MemTracker::Free( void * ptr ) { if ( !s_Enabled ) { return; } if ( !s_Initialized ) { return; } if ( g_MemTrackerDisabledOnThisThread ) { return; } const size_t hashIndex = ( ( (size_t)ptr >> ALLOCATION_HASH_SHIFT ) & ALLOCATION_HASH_MASK ); MutexHolder mh( GetMutex() ); Allocation * a = s_AllocationHashTable[ hashIndex ]; Allocation * prev = nullptr; while ( a ) { if ( a->m_Ptr == ptr ) { if ( prev == nullptr ) { s_AllocationHashTable[ hashIndex ] = a->m_Next; } else { prev->m_Next = a->m_Next; } ++g_MemTrackerDisabledOnThisThread; s_Allocations->Free( a ); --s_AllocationCount; --g_MemTrackerDisabledOnThisThread; break; } prev = a; a = a->m_Next; } } // DumpAllocations //------------------------------------------------------------------------------ /*static*/ void MemTracker::DumpAllocations() { if ( s_Enabled == false ) { OUTPUT( "DumpAllocations failed - MemTracker not enabled\n" ); return; } if ( s_Initialized == false ) { OUTPUT( "DumpAllocations : No allocations\n" ); return; } MutexHolder mh( GetMutex() ); if ( s_AllocationCount == 0 ) { OUTPUT( "DumpAllocations : No allocations\n" ); return; } uint64_t total = 0; uint64_t numAllocs = 0; // for each leak, we'll print a view of the memory unsigned char displayChar[256]; memset( displayChar, '.', sizeof( displayChar ) ); const unsigned char * okChars = (const unsigned char *)"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`1234567890-=!@#$^&*()_+[]{};:'\",<>/?|\\"; const unsigned char * ok = okChars; for ( ;; ) { unsigned char c = *ok; if ( c == 0 ) break; displayChar[ c ] = c; ++ok; } char memView[ 32 ] = { 0 }; OUTPUT( "--- DumpAllocations ------------------------------------------------\n" ); for ( size_t i=0; i<ALLOCATION_HASH_SIZE; ++i ) { Allocation * a = s_AllocationHashTable[ i ]; while ( a ) { uint32_t id = a->m_Id; uint64_t addr = (size_t)a->m_Ptr; uint64_t size = a->m_Size; // format a view of the memory contents const char * src = (const char *)addr; char * dst = memView; const size_t num = Math::Min< size_t >( (size_t)size, 31 ); for ( uint32_t j=0; j<num; ++j ) { unsigned char c = *src; *dst = displayChar[ c ]; ++src; ++dst; } *dst = 0; OUTPUT( "%s(%u): Id %u : %u bytes @ 0x%016llx (Mem: %s)\n", a->m_File, a->m_Line, id, size, addr, memView ); ++numAllocs; total += size; a = a->m_Next; } } OUTPUT( "--------------------------------------------------------------------\n" ); OUTPUT( "Total: %llu bytes in %llu allocs\n", total, numAllocs ); OUTPUT( "--------------------------------------------------------------------\n" ); } // Reset //------------------------------------------------------------------------------ /*static*/ void MemTracker::Reset() { MutexHolder mh( GetMutex() ); ++g_MemTrackerDisabledOnThisThread; // free all allocation tracking for ( size_t i=0; i<ALLOCATION_HASH_SIZE; ++i ) { Allocation * a = s_AllocationHashTable[ i ]; while ( a ) { s_Allocations->Free( a ); --s_AllocationCount; a = a->m_Next; } s_AllocationHashTable[ i ] = nullptr; } ASSERT( s_AllocationCount == 0 ); s_Id = 0; --g_MemTrackerDisabledOnThisThread; } // Init //------------------------------------------------------------------------------ /*static*/ void MemTracker::Init() { CTASSERT( sizeof( MemTracker::s_Mutex ) == sizeof( Mutex ) ); ASSERT( g_MemTrackerDisabledOnThisThread ); // first caller does init static uint32_t threadSafeGuard( 0 ); if ( AtomicIncU32( &threadSafeGuard ) != 1 ) { // subsequent callers wait for init while ( !s_Initialized ) {} return; } // construct primary mutex in-place INPLACE_NEW ( &GetMutex() ) Mutex; // init hash table s_AllocationHashTable = new Allocation*[ ALLOCATION_HASH_SIZE ]; memset( s_AllocationHashTable, 0, ALLOCATION_HASH_SIZE * sizeof( Allocation * ) ); // init pool for allocation structures s_Allocations = new MemPoolBlock( sizeof( Allocation ), __alignof( Allocation ) ); MemoryBarrier(); s_Initialized = true; } //------------------------------------------------------------------------------ #endif // MEMTRACKER_ENABLED //------------------------------------------------------------------------------
[ "franta.fulin@gmail.com" ]
franta.fulin@gmail.com
aaa8f706eca185ad9f7dd72dda3930415ee4cc22
e4f29494a0ecb0a19b231a17e51127a7ddbfe387
/TcpDebug.ino
4c4d7c9df0d7cf9d84c51667ee552e72d3a97973
[]
no_license
EvertDekker/Nixieclock3V1
de9fb41a14decd21a2a86ba4914bc6c5b1839414
67a97d38f1895dbb285c541efe6988dcb04496fc
refs/heads/master
2020-05-29T15:43:43.041005
2019-05-29T13:26:52
2019-05-29T13:26:52
189,228,943
0
0
null
null
null
null
UTF-8
C++
false
false
436
ino
void init_telnet_debug(){ #ifdef TELNET if (MDNS.begin(hostn)) { Serial.println("* MDNS responder started. Hostname -> "); Serial.println(hostn); } MDNS.addService("telnet", "tcp", 23); // Initialize the telnet server of RemoteDebug Debug.begin(hostn); // Initiaze the telnet server Debug.setResetCmdEnabled(true); // Enable the reset command //Debug.showTime(true); // To show time #endif }
[ "Github@evertdekker.com" ]
Github@evertdekker.com
e5da24000808179faf59b1240f2745fd73190189
129136fed2665b6554223cb95407b1bbb7c421e2
/Programming/1-2_sem/Qsort_opt/Qsort_opt.cpp
61fe73c950928a8237e6ccb996816d7ad125f5f5
[]
no_license
PotapovaSofia/DIHT-MIPT
e28f62c3ef91137d86ee8585ad4daefb1930a890
aef75ac5154d22ce0e424b3874bf15bae779fbf0
refs/heads/master
2016-09-05T16:44:46.501488
2016-02-20T21:46:23
2016-02-20T21:46:23
32,089,336
2
1
null
null
null
null
UTF-8
C++
false
false
2,077
cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> void generation(int* Arr, int n) { int i; srand(time(NULL)); for ( i=0;i<n;++i) { Arr[i] = rand()%100 - 50; printf("%d ", Arr[i]); } printf("\n"); } int cmp_(void* a, void* b){ return (*(int*)a - *(int*)b); } void swap(void* a, void* b, size_t size) { char* x = (char*)(malloc(size)); memcpy(x, a, size); memcpy(a, b, size); memcpy(b, x, size); free(x); } void QuickSort ( void* Arr, int first, int last, size_t size, int(*cmp)(void*, void*)) { if ((last - first) > 10) { int i, j; i = first; j = last; int key = (rand() % last + first) % last; char *buf = (char*)malloc(size); memcpy(buf, (char*)Arr + key*size, size); do { while (cmp((char*)Arr + i*size, buf) < 0) i++; while (cmp((char*)Arr + j*size, buf) > 0) j--; if(i <= j) { if (i < j) swap((char*)Arr + i*size, (char*)Arr + j*size, size); i++; j--; } } while (i <= j); if (i < last) QuickSort(Arr, i, last, size, cmp); if (first < j) QuickSort(Arr, first,j, size, cmp); } } void InsertSort(void* a, int n, size_t size, int(*cmp)(void*, void*)) { int i; for (i = 1; i < n; ++i) { char* key = (char*)(malloc(size)); memcpy(key, (char*)a + i* size, size); int j = i - 1; while ((j >= 0) && (cmp((char*)a + j * size, key) > 0)) { swap((char*)a + j*size, (char*)a + (j + 1) * size, size); j--; } memcpy((char*)a + (j + 1) * size, key, size); } } int main() { int i, n; printf("Number: "); scanf("%d", &n); printf ("\n"); int* Arr = (int*)(malloc(sizeof(int)*n)); generation(Arr, n); int(*p)(void*, void*); p = cmp_; QuickSort(Arr, 0, n - 1, sizeof(int), p); InsertSort(Arr, n, sizeof(int), p); for (i = 0; i < n; ++i) { printf("%d ", Arr[i]); } free(Arr); return 0; }
[ "sofiapotapova95@mail.ru" ]
sofiapotapova95@mail.ru
f2fd573fb8ac9dde4919620147f9c6d1cc0536a0
d47ad8721876e05cc92a48ea772981dd2541d27c
/FPMLib/lib/bfc/autores.h
78620a35bff0d40b0b1f790be9dc42de2b418042
[]
no_license
cjld/ANNO-video
5ac5f604d43e00a3ee8b2a40050413ffd8334c3e
e8ad4f1d617f8b2393db5241a40f98c156127e52
refs/heads/master
2021-01-25T06:45:24.164963
2017-06-12T15:54:19
2017-06-12T15:54:19
93,606,386
2
0
null
null
null
null
UTF-8
C++
false
false
5,150
h
#ifndef _FF_BFC_AUTORES_H #define _FF_BFC_AUTORES_H #include <utility> #include <iterator> #include"ffdef.h" _FF_BEG //To help implement reference-counter in @AutoRes. template<typename ValT> class ReferenceCounter { typedef std::pair<int,ValT> _CounterT; private: _CounterT *_pdata; void _inc() const { ++_pdata->first; } void _dec() const { --_pdata->first; } public: ReferenceCounter() :_pdata(new _CounterT(1,ValT())) { } ReferenceCounter(const ValT& val) :_pdata(new _CounterT(1,val)) { } ReferenceCounter(const ReferenceCounter& right) :_pdata(right._pdata) { this->_inc(); } ReferenceCounter& operator=(const ReferenceCounter& right) { if(_pdata!=right._pdata) { if(this->IsLast()) delete _pdata; else this->_dec(); _pdata=right._pdata; right._inc(); } return *this; } //whether current reference is the last one. bool IsLast() const { return _pdata->first==1; } //get the value stored with the counter. const ValT& Value() const { return _pdata->second; } ValT& Value() { return _pdata->second; } //swap two counters. void Swap(ReferenceCounter& right) { std::swap(this->_pdata,right._pdata); } ~ReferenceCounter() { if(this->IsLast()) delete _pdata; else this->_dec(); } }; //auto-resource, which is the base to implement AutoPtr,AutoArrayPtr and AutoComPtr. template<typename PtrT,typename RetPtrT,typename ReleaseOpT> class AutoRes { enum{_F_DETACHED=0x01}; struct _ValT { PtrT ptr; ReleaseOpT rel_op; int flag; public: _ValT() :ptr(PtrT()),flag(0) { } _ValT(const PtrT & _ptr,const ReleaseOpT & _rel_op, int _flag=0) :ptr(_ptr),rel_op(_rel_op),flag(_flag) { } void release() { if((flag&_F_DETACHED)==0) rel_op(ptr); } }; typedef ReferenceCounter<_ValT> _CounterT; protected: _CounterT _counter; void _release() { //release the referenced object with the stored operator. _counter.Value().release(); } public: AutoRes() { } explicit AutoRes(PtrT ptr,const ReleaseOpT& op=ReleaseOpT()) :_counter(_ValT(ptr,op)) { } AutoRes& operator=(const AutoRes& right) { if(this!=&right) { if(_counter.IsLast()) this->_release(); _counter=right._counter; } return *this; } RetPtrT operator->() const { return &*_counter.Value().ptr; } typename std::iterator_traits<RetPtrT>::reference operator*() const { return *_counter.Value().ptr; } void Swap(AutoRes& right) { _counter.Swap(right._counter); } //detach the referenced object from @*this. RetPtrT Detach() { _counter.Value().flag|=_F_DETACHED; return &*_counter.Value().ptr; } operator PtrT() { return _counter.Value().ptr; } ~AutoRes() throw() { if(_counter.IsLast()) this->_release(); } }; //operator to delete a single object. class DeleteObj { public: template<typename _PtrT> void operator()(_PtrT ptr) { delete ptr; } }; template<typename _ObjT> class AutoPtr :public AutoRes<_ObjT*,_ObjT*,DeleteObj> { public: explicit AutoPtr(_ObjT* ptr=NULL) :AutoRes<_ObjT*,_ObjT*,DeleteObj>(ptr) { } }; //operator to delete array of objects. class DeleteArray { public: template<typename _PtrT> void operator()(_PtrT ptr) { delete[]ptr; } }; template<typename _ObjT> class AutoArrayPtr :public AutoRes<_ObjT*,_ObjT*,DeleteArray> { public: explicit AutoArrayPtr(_ObjT* ptr=NULL) :AutoRes<_ObjT*,_ObjT*,DeleteArray>(ptr) { } //_ObjT& operator[](int i) const //{ // return this->_counter.Value().ptr[i]; //} }; class OpCloseFile { public: void operator()(const FILE *fp) { if(fp) fclose((FILE*)fp); } }; class AutoFilePtr :public AutoRes<FILE*,FILE*,OpCloseFile> { public: explicit AutoFilePtr(FILE *fp=NULL) :AutoRes<FILE*,FILE*,OpCloseFile>(fp) { } }; //operator to release COM object. class ReleaseObj { public: template<typename _PtrT> void operator()(_PtrT ptr) { if(ptr) ptr->Release(); } }; template<typename _ObjT> class AutoComPtr :public AutoRes<_ObjT*,_ObjT*,ReleaseObj> { public: explicit AutoComPtr(_ObjT* ptr=NULL) :AutoRes<_ObjT*,_ObjT*,ReleaseObj>(ptr) { } }; class DestroyObj { public: template<typename _PtrT> void operator()(_PtrT ptr) { if(ptr) ptr->Destroy(); } }; template<typename _ObjT> class AutoDestroyPtr :public AutoRes<_ObjT*,_ObjT*,DestroyObj> { public: explicit AutoDestroyPtr(_ObjT* ptr=NULL) :AutoRes<_ObjT*,_ObjT*,DestroyObj>(ptr) { } }; template<typename _ServerPtrT> class ReleaseClientOp { private: _ServerPtrT m_pServer; public: ReleaseClientOp(_ServerPtrT pServer=_ServerPtrT()) :m_pServer(pServer) { } template<typename _ClientPtrT> void operator()(_ClientPtrT ptr) { if(m_pServer) m_pServer->ReleaseClient(ptr); } }; template<typename _ServerPtrT,typename _ClientPtrT> class AutoClientPtr :public AutoRes<_ClientPtrT,_ClientPtrT,ReleaseClientOp<_ServerPtrT> > { typedef AutoRes<_ClientPtrT,_ClientPtrT,ReleaseClientOp<_ServerPtrT> > _MyBaseT; public: explicit AutoClientPtr(_ServerPtrT pServer=_ServerPtrT(),_ClientPtrT pClient=_ClientPtrT()) :_MyBaseT(pClient,ReleaseClientOp<_ServerPtrT>(pServer)) { } }; _FF_END #endif
[ "randonlang@gmail.com" ]
randonlang@gmail.com
fc66a1678930bf9093bd076f90dd380635b60366
ceeddddcf3e99e909c4af5ff2b9fad4a8ecaeb2a
/branches/releases/1.3.NET/source/Irrlicht/CGUIColorSelectDialog.h
fed63371d4d75b6f6d20e164aab8c2e8f2527655
[ "Zlib", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-other-permissive" ]
permissive
jivibounty/irrlicht
d9d6993bd0aee00dce2397a887b7f547ade74fbb
c5c80cde40b6d14fe5661440638d36a16b41d7ab
refs/heads/master
2021-01-18T02:56:08.844268
2015-07-21T08:02:25
2015-07-21T08:02:25
39,405,895
0
0
null
2015-07-20T20:07:06
2015-07-20T20:07:06
null
UTF-8
C++
false
false
1,684
h
// Copyright (C) 2002-2007 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #ifndef __C_GUI_COLOR_SELECT_DIALOG_H_INCLUDED__ #define __C_GUI_COLOR_SELECT_DIALOG_H_INCLUDED__ #include "IGUIColorSelectDialog.h" #include "IGUIButton.h" #include "IGUIEditBox.h" #include "IGUIScrollBar.h" #include "IGUIImage.h" #include "irrArray.h" namespace irr { namespace gui { class CGUIColorSelectDialog : public IGUIColorSelectDialog { public: //! constructor CGUIColorSelectDialog(const wchar_t* title, IGUIEnvironment* environment, IGUIElement* parent, s32 id); //! destructor virtual ~CGUIColorSelectDialog(); //! called if an event happened. virtual bool OnEvent(SEvent event); //! draws the element and its children virtual void draw(); private: //! sends the event that the file has been selected. void sendSelectedEvent(); //! sends the event that the file choose process has been canceld void sendCancelEvent(); core::position2d<s32> DragStart; bool Dragging; IGUIButton* CloseButton; IGUIButton* OKButton; IGUIButton* CancelButton; struct SBatteryItem { f32 Incoming; f32 Outgoing; IGUIEditBox * Edit; IGUIScrollBar *Scrollbar; }; core::array< SBatteryItem > Battery; struct SColorCircle { IGUIImage * Control; video::ITexture * Texture; }; SColorCircle ColorRing; void buildColorRing( const core::dimension2d<s32> & dim, s32 supersample, const u32 borderColor ); }; } // end namespace gui } // end namespace irr #endif
[ "hybrid@dfc29bdd-3216-0410-991c-e03cc46cb475" ]
hybrid@dfc29bdd-3216-0410-991c-e03cc46cb475
d59c5f726c85c0426fe1f464a529f7fc97a16b65
a6f1cd042e91b17f72bcc7872a47cc022f2cf21e
/DFS/140. Word Break II.cpp
f0c3e25853d36e6953d7c4095b60ae93953c6b90
[]
no_license
sammiiT/leetcode
bc1b8fa107c15bbdd803e6f5e4f86a179904a988
8e882f4a6fb05ba645bd1ff8355d3b8f14654fb0
refs/heads/master
2023-09-06T04:43:54.582944
2023-09-04T15:19:00
2023-09-04T15:19:00
219,103,778
0
0
null
null
null
null
UTF-8
C++
false
false
2,104
cpp
//===類似題=== 139. Word Break 472. Concatenated Words //=== 思路==== (*) DFS算法 - 陣列中的每一個節點都可以當作root節點, 每一個節點都是上一層的child節點 - 此題的陣列是vector<string> wordDict - 因為陣列元素可以reused,所以每進入下一層, loop迴圈都從i=0開始 0. segment 是要連續,不能中間斷掉, 左半部和右半部連接 1.宣告 string& out, 紀錄每一個滿足條件的string 2.宣告 vector<string>& res, 紀錄滿足最後條件的string 3.每一次substring都要從string[0]開始, - 取從0開始的substr, 判斷此substr是否等於wordDict[i] --不等於就continue 4.每一次都要記錄(append)新的string; out.append(wordDict[i]+" ") 跳回上一層要把append刪除; out = out.substr(0,size);//size維之前out的長度 5.最回傳res (*) cout<<str.substr(pos, str.size()-pos)<<endl; //str.size()是1-index, pos是0-index 相減?????? (*)思路重構 1.以wordDict為依據, 遍歷wordDict並與string做比較 2.wordDict[i]不同的排列方式, 可以滿足string的segmentation => 所以用DFS for(int i=0; i<wordDict.size(); ++i){...} 3.每一次判斷string segement, 都把此segment從string中刪除, 並將剩下的string放到下一層DFS中做運算 //===== void helper(string s ,vector<string>& wordDict, string& out, vector<string>& res){ if(s.size()==0){ out.pop_back();//將space 字元移除 res.push_back(out); return; } for(int i=0; i<wordDict.size(); ++i){ int len = wordDict[i].size(); if(s.substr(0,len)!=wordDict[i]) continue;//不同排列順序 string tmp = s.substr(len,s.size()-len);//剩下的String int size = out.size(); out.append(wordDict[i]+" "); helper(tmp,wordDict,out,res); out = out.substr(0,size);//沒有辦法pop_back() string,所以用之前紀錄的substriing size } } vector<string> wordBreak(string s, vector<string>& wordDict) { vector<string> res; string out; helper(s,wordDict,out,res); return res; }
[ "noreply@github.com" ]
noreply@github.com
c35c2d62a156829d22448cc6b0d87e80e60d5a76
c27a1b7e258b9fa30653a9aa6dd36dcd1df15810
/arduino_code_outer.ino
a27b32227a2881ae73337661e4ccde0c8c8668c9
[]
no_license
Emmanuel-Edidiong/Automatic-Wireless-Weather-Station-with-Arduino
1b0b97d20a742c1dfb98d8b97966ee2560e86c00
8268b1b4dbe8bbb79386ecaf867eea141e34610b
refs/heads/master
2020-09-13T13:51:21.347427
2019-11-19T23:08:11
2019-11-19T23:08:11
222,806,119
2
0
null
null
null
null
UTF-8
C++
false
false
1,116
ino
/* Outdoor unit - Transmitter */ #include <SPI.h> #include <nRF24L01.h> #include <RF24.h> #include <dht.h> #include <LowPower.h> #define dataPin 8 // DHT22 data pina dht DHT; // Creates a DHT object RF24 radio(10, 9); // CE, CSN const byte address[6] = "00001"; char thChar[32] = ""; String thString = ""; void setup() { Serial.begin(115200); radio.begin(); radio.openWritingPipe(address); radio.setPALevel(RF24_PA_MIN); radio.stopListening(); } void loop() { int readData = DHT.read22(dataPin); // Reads the data from the sensor int t = DHT.temperature; // Gets the values of the temperature int h = DHT.humidity; // Gets the values of the humidity thString = String(t) + String(h); thString.toCharArray(thChar, 12); Serial.println(thChar); // Sent the data wirelessly to the indoor unit for (int i = 0; i <= 3; i++) { // Send the data 3 times radio.write(&thChar, sizeof(thChar)); delay(50); } // Sleep for 2 minutes, 15*8 = 120s for (int sleepCounter = 15; sleepCounter > 0; sleepCounter--) { LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF); } }
[ "noreply@github.com" ]
noreply@github.com
24db047e3e13fafc5ddd4547fc9e46520a696d7f
b301ab714ad4d4625d4a79005a1bda6456a283ec
/UVa/334.cpp
f025069dbdd616fd733ba2408d048555a145a5a6
[]
no_license
askeySnip/OJ_records
220fd83d406709328e8450df0f6da98ae57eb2d9
4b77e3bb5cf19b98572fa6583dff390e03ff1a7c
refs/heads/master
2022-06-26T02:14:34.957580
2022-06-11T13:56:33
2022-06-11T13:56:33
117,955,514
1
0
null
null
null
null
UTF-8
C++
false
false
2,302
cpp
/* ID: leezhen TASK: practice LANG: C++11 */ #include <iostream> #include <fstream> #include <string> #include <vector> #include <algorithm> #include <cstdio> #include <cstring> #include <set> #include <map> #include <stack> #include <queue> #include <cmath> #include <bitset> using namespace std; typedef vector<int> vi; typedef pair<int, int> ii; typedef vector<pair<int, int> > vii; // struct #define inf 1e6 // data int nc, ne, nm; int dist[404][404]; char e[2][10]; vector<string> vstr; map<string, int> mpsi; int main() { int kase = 0; while(scanf("%d", &nc), nc) { mpsi.clear(); vstr.clear(); for(int i=0; i<404; i++) { for(int j=0; j<404; j++) { if(i == j) dist[i][j] = 0; else dist[i][j] = inf; } } for(int i=0; i<nc; i++) { scanf("%d", &ne); scanf("%s", e[0]); if(mpsi.find(e[0]) == mpsi.end()) { vstr.push_back(e[0]); mpsi[e[0]] = vstr.size()-1; } int last = 0; for(int j=1; j<ne; j++) { scanf("%s", e[1-last]); if(mpsi.find(e[1-last]) == mpsi.end()) { mpsi[e[1-last]] = vstr.size(); vstr.push_back(e[1-last]); } dist[mpsi[e[last]]][mpsi[e[1-last]]] = 1; last = 1-last; } } scanf("%d", &nm); for(int i=0; i<nm; i++) { scanf("%s %s", e[0], e[1]); dist[mpsi[e[0]]][mpsi[e[1]]] = 1; } int n = vstr.size(); for(int k=0; k<n; k++) { for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { if(dist[i][j] > dist[i][k] + dist[k][j]) { dist[i][j] = dist[i][k] + dist[k][j]; } } } } vii ans; for(int i=0; i<n; i++) { for(int j=i+1; j<n; j++) { if(dist[i][j] == inf && dist[j][i] == inf) ans.push_back(ii(i, j)); } } if(ans.empty())printf("Case %d, no concurrent events.\n", ++kase); else { printf("Case %d, %d concurrent events:\n", ++kase, (int)ans.size()); if((int)ans.size() == 1) { printf("(%s,%s) \n", vstr[ans[0].first].c_str(), vstr[ans[0].second].c_str()); } else { printf("(%s,%s) (%s,%s) \n", vstr[ans[0].first].c_str(), vstr[ans[0].second].c_str(), vstr[ans[1].first].c_str(), vstr[ans[1].second].c_str()); } } } return 0; }
[ "296181278@qq.com" ]
296181278@qq.com
fb140c6343d8cb845bec30e15d68b2741357c692
5668d876245e982c842409466b39e6660e5fc740
/servo_brazo_potenciometros_guardaposicion.ino
3ef4e592616b58aabc9c2a86ef50a4ec55730403
[]
no_license
RiquiMora/Brazo-Robotico-4DOF
5dea34ff7115e9e5e126d5e292b84d92cfcb2d4b
a472bd7ea25e75f91f6079aa184c3a1e47ec18b2
refs/heads/master
2020-03-19T02:04:27.984336
2018-05-31T15:05:30
2018-05-31T15:05:30
135,596,748
0
0
null
null
null
null
UTF-8
C++
false
false
7,326
ino
#include <Servo.h> Servo hombro, brazo, base, garra; int potpi = 0; int pot = 1; int potp = 2; int po = 3; int val; // variable to read the value from the analog pin int val1; int val2; int val3; const int max_root = 180; char valores; String codigo = ""; boolean mode = true; void setup() { Serial.begin(9600); base.attach(11); brazo.attach(10); hombro.attach(9); garra.attach(8); } void loop() { val = analogRead(potpi); // reads the value of the potentiometer (value between 0 and 1023) val = map(val, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180) hombro.write(val); // sets the servo position according to the scaled value delay(15); // waits for the servo to get there val1 = analogRead(pot); // reads the value of the potentiometer (value between 0 and 1023) val1 = map(val1, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180) brazo.write(val1); // sets the servo position according to the scaled value delay(15); // waits for the servo to get there val2 = analogRead(potp); // reads the value of the potentiometer (value between 0 and 1023) val2 = map(val2, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180) base.write(val2); // sets the servo position according to the scaled value delay(15); // waits for the servo to get there val3 = analogRead(po); // reads the value of the potentiometer (value between 0 and 1023) val3 = map(val3, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180) garra.write(val3); // sets the servo position according to the scaled value delay(15); // waits for the servo to get there String metodo="",init = ""; boolean tipo = false; int posicion = 0; base.write(60); brazo.write(60); hombro.write(60); garra.write(60); if(Serial.available() > 0) { codigo = ""; while(Serial.available() > 0) { valores = Decimal_to_ASCII(Serial.read()); Serial.print(valores); codigo = codigo + valores; } delay(2000); } Serial.println(codigo); delay(2000); for( int i=0; i < codigo.length(); i++) { if(tipo == false) { if(codigo.charAt(i) == '(') { tipo = true; continue; } metodo = metodo + codigo.charAt(i); } else { init = init + codigo.charAt(i); if(codigo.charAt(i) == ')') { continue; }else if(codigo.charAt(i) == ';'){ delay(2000); posicion = init.toInt(); if(metodo == "brazo") { posicion < 180 ? brazo.write(posicion) : brazo.write(180); Serial.println("brazo"); delay(2000); }else if(metodo == "base") { posicion < max_root ? base.write(posicion) : base.write(180); Serial.println("base"); delay(2000); }else if(metodo == "hombro") { posicion < max_root ? hombro.write(posicion) : hombro.write(180); Serial.println("hombro"); delay(2000); }else if(metodo == "garra") { posicion < max_root ? garra.write(posicion) : garra.write(180); Serial.println("garra"); delay(2000); } metodo = ""; tipo = false; init = ""; } } } } char Decimal_to_ASCII(int entrada){ char salida=' '; switch(entrada){ case 32: salida=' '; break; case 33: salida='!'; break; case 34: salida='"'; break; case 35: salida='#'; break; case 36: salida='$'; break; case 37: salida='%'; break; case 38: salida='&'; break; case 39: salida=' '; break; case 40: salida='('; break; case 41: salida=')'; break; case 42: salida='*'; break; case 43: salida='+'; break; case 44: salida=','; break; case 45: salida='-'; break; case 46: salida='.'; break; case 47: salida='/'; break; case 48: salida='0'; break; case 49: salida='1'; break; case 50: salida='2'; break; case 51: salida='3'; break; case 52: salida='4'; break; case 53: salida='5'; break; case 54: salida='6'; break; case 55: salida='7'; break; case 56: salida='8'; break; case 57: salida='9'; break; case 58: salida=':'; break; case 59: salida=';'; break; case 60: salida='<'; break; case 61: salida='='; break; case 62: salida='>'; break; case 63: salida='?'; break; case 64: salida='@'; break; case 65: salida='A'; break; case 66: salida='B'; break; case 67: salida='C'; break; case 68: salida='D'; break; case 69: salida='E'; break; case 70: salida='F'; break; case 71: salida='G'; break; case 72: salida='H'; break; case 73: salida='I'; break; case 74: salida='J'; break; case 75: salida='K'; break; case 76: salida='L'; break; case 77: salida='M'; break; case 78: salida='N'; break; case 79: salida='O'; break; case 80: salida='P'; break; case 81: salida='Q'; break; case 82: salida='R'; break; case 83: salida='S'; break; case 84: salida='T'; break; case 85: salida='U'; break; case 86: salida='V'; break; case 87: salida='W'; break; case 88: salida='X'; break; case 89: salida='Y'; break; case 90: salida='Z'; break; case 91: salida='['; break; case 92: salida=' '; break; case 93: salida=']'; break; case 94: salida='^'; break; case 95: salida='_'; break; case 96: salida='`'; break; case 97: salida='a'; break; case 98: salida='b'; break; case 99: salida='c'; break; case 100: salida='d'; break; case 101: salida='e'; break; case 102: salida='f'; break; case 103: salida='g'; break; case 104: salida='h'; break; case 105: salida='i'; break; case 106: salida='j'; break; case 107: salida='k'; break; case 108: salida='l'; break; case 109: salida='m'; break; case 110: salida='n'; break; case 111: salida='o'; break; case 112: salida='p'; break; case 113: salida='q'; break; case 114: salida='r'; break; case 115: salida='s'; break; case 116: salida='t'; break; case 117: salida='u'; break; case 118: salida='v'; break; case 119: salida='w'; break; case 120: salida='x'; break; case 121: salida='y'; break; case 122: salida='z'; break; case 123: salida='{'; break; case 124: salida='|'; break; case 125: salida='}'; break; case 126: salida='~'; break; } return salida; }
[ "noreply@github.com" ]
noreply@github.com
3c562a4243e222e2a5d2afd6f33ac1002b5d77d5
e49020bee62e9a7006b7a603588aff026ac19402
/clang/lib/Basic/IdentifierTable.cpp
621bcc265020d77a202936efaba490ba1a2832a7
[ "NCSA" ]
permissive
angopher/llvm
10d540f4d38fd184506d9096fb02a288af8a1aa1
163def217817c90fb982a6daf384744d8472b92b
refs/heads/master
2020-06-10T09:59:52.274700
2018-05-10T23:14:40
2018-05-10T23:14:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
23,406
cpp
//===- IdentifierTable.cpp - Hash table for identifier lookup -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the IdentifierInfo, IdentifierVisitor, and // IdentifierTable interfaces. // //===----------------------------------------------------------------------===// #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/OperatorKinds.h" #include "clang/Basic/Specifiers.h" #include "clang/Basic/TokenKinds.h" #include "llvm/ADT/DenseMapInfo.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include <cassert> #include <cstdio> #include <cstring> #include <string> using namespace clang; //===----------------------------------------------------------------------===// // IdentifierInfo Implementation //===----------------------------------------------------------------------===// IdentifierInfo::IdentifierInfo() { TokenID = tok::identifier; ObjCOrBuiltinID = 0; HasMacro = false; HadMacro = false; IsExtension = false; IsFutureCompatKeyword = false; IsPoisoned = false; IsCPPOperatorKeyword = false; NeedsHandleIdentifier = false; IsFromAST = false; ChangedAfterLoad = false; FEChangedAfterLoad = false; RevertedTokenID = false; OutOfDate = false; IsModulesImport = false; } //===----------------------------------------------------------------------===// // IdentifierTable Implementation //===----------------------------------------------------------------------===// IdentifierIterator::~IdentifierIterator() = default; IdentifierInfoLookup::~IdentifierInfoLookup() = default; namespace { /// A simple identifier lookup iterator that represents an /// empty sequence of identifiers. class EmptyLookupIterator : public IdentifierIterator { public: StringRef Next() override { return StringRef(); } }; } // namespace IdentifierIterator *IdentifierInfoLookup::getIdentifiers() { return new EmptyLookupIterator(); } IdentifierTable::IdentifierTable(IdentifierInfoLookup *ExternalLookup) : HashTable(8192), // Start with space for 8K identifiers. ExternalLookup(ExternalLookup) {} IdentifierTable::IdentifierTable(const LangOptions &LangOpts, IdentifierInfoLookup *ExternalLookup) : IdentifierTable(ExternalLookup) { // Populate the identifier table with info about keywords for the current // language. AddKeywords(LangOpts); } //===----------------------------------------------------------------------===// // Language Keyword Implementation //===----------------------------------------------------------------------===// // Constants for TokenKinds.def namespace { enum { KEYC99 = 0x1, KEYCXX = 0x2, KEYCXX11 = 0x4, KEYGNU = 0x8, KEYMS = 0x10, BOOLSUPPORT = 0x20, KEYALTIVEC = 0x40, KEYNOCXX = 0x80, KEYBORLAND = 0x100, KEYOPENCL = 0x200, KEYC11 = 0x400, KEYARC = 0x800, KEYNOMS18 = 0x01000, KEYNOOPENCL = 0x02000, WCHARSUPPORT = 0x04000, HALFSUPPORT = 0x08000, CHAR8SUPPORT = 0x10000, KEYCONCEPTS = 0x20000, KEYOBJC2 = 0x40000, KEYZVECTOR = 0x80000, KEYCOROUTINES = 0x100000, KEYMODULES = 0x200000, KEYCXX2A = 0x400000, KEYALLCXX = KEYCXX | KEYCXX11 | KEYCXX2A, KEYALL = (0x7fffff & ~KEYNOMS18 & ~KEYNOOPENCL) // KEYNOMS18 and KEYNOOPENCL are used to exclude. }; /// How a keyword is treated in the selected standard. enum KeywordStatus { KS_Disabled, // Disabled KS_Extension, // Is an extension KS_Enabled, // Enabled KS_Future // Is a keyword in future standard }; } // namespace /// Translates flags as specified in TokenKinds.def into keyword status /// in the given language standard. static KeywordStatus getKeywordStatus(const LangOptions &LangOpts, unsigned Flags) { if (Flags == KEYALL) return KS_Enabled; if (LangOpts.CPlusPlus && (Flags & KEYCXX)) return KS_Enabled; if (LangOpts.CPlusPlus11 && (Flags & KEYCXX11)) return KS_Enabled; if (LangOpts.CPlusPlus2a && (Flags & KEYCXX2A)) return KS_Enabled; if (LangOpts.C99 && (Flags & KEYC99)) return KS_Enabled; if (LangOpts.GNUKeywords && (Flags & KEYGNU)) return KS_Extension; if (LangOpts.MicrosoftExt && (Flags & KEYMS)) return KS_Extension; if (LangOpts.Borland && (Flags & KEYBORLAND)) return KS_Extension; if (LangOpts.Bool && (Flags & BOOLSUPPORT)) return KS_Enabled; if (LangOpts.Half && (Flags & HALFSUPPORT)) return KS_Enabled; if (LangOpts.WChar && (Flags & WCHARSUPPORT)) return KS_Enabled; if (LangOpts.Char8 && (Flags & CHAR8SUPPORT)) return KS_Enabled; if (LangOpts.AltiVec && (Flags & KEYALTIVEC)) return KS_Enabled; if (LangOpts.OpenCL && (Flags & KEYOPENCL)) return KS_Enabled; if (!LangOpts.CPlusPlus && (Flags & KEYNOCXX)) return KS_Enabled; if (LangOpts.C11 && (Flags & KEYC11)) return KS_Enabled; // We treat bridge casts as objective-C keywords so we can warn on them // in non-arc mode. if (LangOpts.ObjC2 && (Flags & KEYARC)) return KS_Enabled; if (LangOpts.ObjC2 && (Flags & KEYOBJC2)) return KS_Enabled; if (LangOpts.ConceptsTS && (Flags & KEYCONCEPTS)) return KS_Enabled; if (LangOpts.CoroutinesTS && (Flags & KEYCOROUTINES)) return KS_Enabled; if (LangOpts.ModulesTS && (Flags & KEYMODULES)) return KS_Enabled; if (LangOpts.CPlusPlus && (Flags & KEYALLCXX)) return KS_Future; return KS_Disabled; } /// AddKeyword - This method is used to associate a token ID with specific /// identifiers because they are language keywords. This causes the lexer to /// automatically map matching identifiers to specialized token codes. static void AddKeyword(StringRef Keyword, tok::TokenKind TokenCode, unsigned Flags, const LangOptions &LangOpts, IdentifierTable &Table) { KeywordStatus AddResult = getKeywordStatus(LangOpts, Flags); // Don't add this keyword under MSVCCompat. if (LangOpts.MSVCCompat && (Flags & KEYNOMS18) && !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2015)) return; // Don't add this keyword under OpenCL. if (LangOpts.OpenCL && (Flags & KEYNOOPENCL)) return; // Don't add this keyword if disabled in this language. if (AddResult == KS_Disabled) return; IdentifierInfo &Info = Table.get(Keyword, AddResult == KS_Future ? tok::identifier : TokenCode); Info.setIsExtensionToken(AddResult == KS_Extension); Info.setIsFutureCompatKeyword(AddResult == KS_Future); } /// AddCXXOperatorKeyword - Register a C++ operator keyword alternative /// representations. static void AddCXXOperatorKeyword(StringRef Keyword, tok::TokenKind TokenCode, IdentifierTable &Table) { IdentifierInfo &Info = Table.get(Keyword, TokenCode); Info.setIsCPlusPlusOperatorKeyword(); } /// AddObjCKeyword - Register an Objective-C \@keyword like "class" "selector" /// or "property". static void AddObjCKeyword(StringRef Name, tok::ObjCKeywordKind ObjCID, IdentifierTable &Table) { Table.get(Name).setObjCKeywordID(ObjCID); } /// AddKeywords - Add all keywords to the symbol table. /// void IdentifierTable::AddKeywords(const LangOptions &LangOpts) { // Add keywords and tokens for the current language. #define KEYWORD(NAME, FLAGS) \ AddKeyword(StringRef(#NAME), tok::kw_ ## NAME, \ FLAGS, LangOpts, *this); #define ALIAS(NAME, TOK, FLAGS) \ AddKeyword(StringRef(NAME), tok::kw_ ## TOK, \ FLAGS, LangOpts, *this); #define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \ if (LangOpts.CXXOperatorNames) \ AddCXXOperatorKeyword(StringRef(#NAME), tok::ALIAS, *this); #define OBJC1_AT_KEYWORD(NAME) \ if (LangOpts.ObjC1) \ AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this); #define OBJC2_AT_KEYWORD(NAME) \ if (LangOpts.ObjC2) \ AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this); #define TESTING_KEYWORD(NAME, FLAGS) #include "clang/Basic/TokenKinds.def" if (LangOpts.ParseUnknownAnytype) AddKeyword("__unknown_anytype", tok::kw___unknown_anytype, KEYALL, LangOpts, *this); if (LangOpts.DeclSpecKeyword) AddKeyword("__declspec", tok::kw___declspec, KEYALL, LangOpts, *this); // Add the '_experimental_modules_import' contextual keyword. get("import").setModulesImport(true); } /// Checks if the specified token kind represents a keyword in the /// specified language. /// \returns Status of the keyword in the language. static KeywordStatus getTokenKwStatus(const LangOptions &LangOpts, tok::TokenKind K) { switch (K) { #define KEYWORD(NAME, FLAGS) \ case tok::kw_##NAME: return getKeywordStatus(LangOpts, FLAGS); #include "clang/Basic/TokenKinds.def" default: return KS_Disabled; } } /// Returns true if the identifier represents a keyword in the /// specified language. bool IdentifierInfo::isKeyword(const LangOptions &LangOpts) const { switch (getTokenKwStatus(LangOpts, getTokenID())) { case KS_Enabled: case KS_Extension: return true; default: return false; } } /// Returns true if the identifier represents a C++ keyword in the /// specified language. bool IdentifierInfo::isCPlusPlusKeyword(const LangOptions &LangOpts) const { if (!LangOpts.CPlusPlus || !isKeyword(LangOpts)) return false; // This is a C++ keyword if this identifier is not a keyword when checked // using LangOptions without C++ support. LangOptions LangOptsNoCPP = LangOpts; LangOptsNoCPP.CPlusPlus = false; LangOptsNoCPP.CPlusPlus11 = false; LangOptsNoCPP.CPlusPlus2a = false; return !isKeyword(LangOptsNoCPP); } tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const { // We use a perfect hash function here involving the length of the keyword, // the first and third character. For preprocessor ID's there are no // collisions (if there were, the switch below would complain about duplicate // case values). Note that this depends on 'if' being null terminated. #define HASH(LEN, FIRST, THIRD) \ (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31) #define CASE(LEN, FIRST, THIRD, NAME) \ case HASH(LEN, FIRST, THIRD): \ return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME unsigned Len = getLength(); if (Len < 2) return tok::pp_not_keyword; const char *Name = getNameStart(); switch (HASH(Len, Name[0], Name[2])) { default: return tok::pp_not_keyword; CASE( 2, 'i', '\0', if); CASE( 4, 'e', 'i', elif); CASE( 4, 'e', 's', else); CASE( 4, 'l', 'n', line); CASE( 4, 's', 'c', sccs); CASE( 5, 'e', 'd', endif); CASE( 5, 'e', 'r', error); CASE( 5, 'i', 'e', ident); CASE( 5, 'i', 'd', ifdef); CASE( 5, 'u', 'd', undef); CASE( 6, 'a', 's', assert); CASE( 6, 'd', 'f', define); CASE( 6, 'i', 'n', ifndef); CASE( 6, 'i', 'p', import); CASE( 6, 'p', 'a', pragma); CASE( 7, 'd', 'f', defined); CASE( 7, 'i', 'c', include); CASE( 7, 'w', 'r', warning); CASE( 8, 'u', 'a', unassert); CASE(12, 'i', 'c', include_next); CASE(14, '_', 'p', __public_macro); CASE(15, '_', 'p', __private_macro); CASE(16, '_', 'i', __include_macros); #undef CASE #undef HASH } } //===----------------------------------------------------------------------===// // Stats Implementation //===----------------------------------------------------------------------===// /// PrintStats - Print statistics about how well the identifier table is doing /// at hashing identifiers. void IdentifierTable::PrintStats() const { unsigned NumBuckets = HashTable.getNumBuckets(); unsigned NumIdentifiers = HashTable.getNumItems(); unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers; unsigned AverageIdentifierSize = 0; unsigned MaxIdentifierLength = 0; // TODO: Figure out maximum times an identifier had to probe for -stats. for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator I = HashTable.begin(), E = HashTable.end(); I != E; ++I) { unsigned IdLen = I->getKeyLength(); AverageIdentifierSize += IdLen; if (MaxIdentifierLength < IdLen) MaxIdentifierLength = IdLen; } fprintf(stderr, "\n*** Identifier Table Stats:\n"); fprintf(stderr, "# Identifiers: %d\n", NumIdentifiers); fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets); fprintf(stderr, "Hash density (#identifiers per bucket): %f\n", NumIdentifiers/(double)NumBuckets); fprintf(stderr, "Ave identifier length: %f\n", (AverageIdentifierSize/(double)NumIdentifiers)); fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength); // Compute statistics about the memory allocated for identifiers. HashTable.getAllocator().PrintStats(); } //===----------------------------------------------------------------------===// // SelectorTable Implementation //===----------------------------------------------------------------------===// unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) { return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr()); } namespace clang { /// MultiKeywordSelector - One of these variable length records is kept for each /// selector containing more than one keyword. We use a folding set /// to unique aggregate names (keyword selectors in ObjC parlance). Access to /// this class is provided strictly through Selector. class MultiKeywordSelector : public DeclarationNameExtra, public llvm::FoldingSetNode { MultiKeywordSelector(unsigned nKeys) { ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys; } public: // Constructor for keyword selectors. MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV) { assert((nKeys > 1) && "not a multi-keyword selector"); ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys; // Fill in the trailing keyword array. IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this+1); for (unsigned i = 0; i != nKeys; ++i) KeyInfo[i] = IIV[i]; } // getName - Derive the full selector name and return it. std::string getName() const; unsigned getNumArgs() const { return ExtraKindOrNumArgs - NUM_EXTRA_KINDS; } using keyword_iterator = IdentifierInfo *const *; keyword_iterator keyword_begin() const { return reinterpret_cast<keyword_iterator>(this+1); } keyword_iterator keyword_end() const { return keyword_begin()+getNumArgs(); } IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const { assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index"); return keyword_begin()[i]; } static void Profile(llvm::FoldingSetNodeID &ID, keyword_iterator ArgTys, unsigned NumArgs) { ID.AddInteger(NumArgs); for (unsigned i = 0; i != NumArgs; ++i) ID.AddPointer(ArgTys[i]); } void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, keyword_begin(), getNumArgs()); } }; } // namespace clang. unsigned Selector::getNumArgs() const { unsigned IIF = getIdentifierInfoFlag(); if (IIF <= ZeroArg) return 0; if (IIF == OneArg) return 1; // We point to a MultiKeywordSelector. MultiKeywordSelector *SI = getMultiKeywordSelector(); return SI->getNumArgs(); } IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const { if (getIdentifierInfoFlag() < MultiArg) { assert(argIndex == 0 && "illegal keyword index"); return getAsIdentifierInfo(); } // We point to a MultiKeywordSelector. MultiKeywordSelector *SI = getMultiKeywordSelector(); return SI->getIdentifierInfoForSlot(argIndex); } StringRef Selector::getNameForSlot(unsigned int argIndex) const { IdentifierInfo *II = getIdentifierInfoForSlot(argIndex); return II? II->getName() : StringRef(); } std::string MultiKeywordSelector::getName() const { SmallString<256> Str; llvm::raw_svector_ostream OS(Str); for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) { if (*I) OS << (*I)->getName(); OS << ':'; } return OS.str(); } std::string Selector::getAsString() const { if (InfoPtr == 0) return "<null selector>"; if (getIdentifierInfoFlag() < MultiArg) { IdentifierInfo *II = getAsIdentifierInfo(); if (getNumArgs() == 0) { assert(II && "If the number of arguments is 0 then II is guaranteed to " "not be null."); return II->getName(); } if (!II) return ":"; return II->getName().str() + ":"; } // We have a multiple keyword selector. return getMultiKeywordSelector()->getName(); } void Selector::print(llvm::raw_ostream &OS) const { OS << getAsString(); } /// Interpreting the given string using the normal CamelCase /// conventions, determine whether the given string starts with the /// given "word", which is assumed to end in a lowercase letter. static bool startsWithWord(StringRef name, StringRef word) { if (name.size() < word.size()) return false; return ((name.size() == word.size() || !isLowercase(name[word.size()])) && name.startswith(word)); } ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) { IdentifierInfo *first = sel.getIdentifierInfoForSlot(0); if (!first) return OMF_None; StringRef name = first->getName(); if (sel.isUnarySelector()) { if (name == "autorelease") return OMF_autorelease; if (name == "dealloc") return OMF_dealloc; if (name == "finalize") return OMF_finalize; if (name == "release") return OMF_release; if (name == "retain") return OMF_retain; if (name == "retainCount") return OMF_retainCount; if (name == "self") return OMF_self; if (name == "initialize") return OMF_initialize; } if (name == "performSelector" || name == "performSelectorInBackground" || name == "performSelectorOnMainThread") return OMF_performSelector; // The other method families may begin with a prefix of underscores. while (!name.empty() && name.front() == '_') name = name.substr(1); if (name.empty()) return OMF_None; switch (name.front()) { case 'a': if (startsWithWord(name, "alloc")) return OMF_alloc; break; case 'c': if (startsWithWord(name, "copy")) return OMF_copy; break; case 'i': if (startsWithWord(name, "init")) return OMF_init; break; case 'm': if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy; break; case 'n': if (startsWithWord(name, "new")) return OMF_new; break; default: break; } return OMF_None; } ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) { IdentifierInfo *first = sel.getIdentifierInfoForSlot(0); if (!first) return OIT_None; StringRef name = first->getName(); if (name.empty()) return OIT_None; switch (name.front()) { case 'a': if (startsWithWord(name, "array")) return OIT_Array; break; case 'd': if (startsWithWord(name, "default")) return OIT_ReturnsSelf; if (startsWithWord(name, "dictionary")) return OIT_Dictionary; break; case 's': if (startsWithWord(name, "shared")) return OIT_ReturnsSelf; if (startsWithWord(name, "standard")) return OIT_Singleton; break; case 'i': if (startsWithWord(name, "init")) return OIT_Init; default: break; } return OIT_None; } ObjCStringFormatFamily Selector::getStringFormatFamilyImpl(Selector sel) { IdentifierInfo *first = sel.getIdentifierInfoForSlot(0); if (!first) return SFF_None; StringRef name = first->getName(); switch (name.front()) { case 'a': if (name == "appendFormat") return SFF_NSString; break; case 'i': if (name == "initWithFormat") return SFF_NSString; break; case 'l': if (name == "localizedStringWithFormat") return SFF_NSString; break; case 's': if (name == "stringByAppendingFormat" || name == "stringWithFormat") return SFF_NSString; break; } return SFF_None; } namespace { struct SelectorTableImpl { llvm::FoldingSet<MultiKeywordSelector> Table; llvm::BumpPtrAllocator Allocator; }; } // namespace static SelectorTableImpl &getSelectorTableImpl(void *P) { return *static_cast<SelectorTableImpl*>(P); } SmallString<64> SelectorTable::constructSetterName(StringRef Name) { SmallString<64> SetterName("set"); SetterName += Name; SetterName[3] = toUppercase(SetterName[3]); return SetterName; } Selector SelectorTable::constructSetterSelector(IdentifierTable &Idents, SelectorTable &SelTable, const IdentifierInfo *Name) { IdentifierInfo *SetterName = &Idents.get(constructSetterName(Name->getName())); return SelTable.getUnarySelector(SetterName); } size_t SelectorTable::getTotalMemory() const { SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl); return SelTabImpl.Allocator.getTotalMemory(); } Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) { if (nKeys < 2) return Selector(IIV[0], nKeys); SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl); // Unique selector, to guarantee there is one per name. llvm::FoldingSetNodeID ID; MultiKeywordSelector::Profile(ID, IIV, nKeys); void *InsertPos = nullptr; if (MultiKeywordSelector *SI = SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos)) return Selector(SI); // MultiKeywordSelector objects are not allocated with new because they have a // variable size array (for parameter types) at the end of them. unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *); MultiKeywordSelector *SI = (MultiKeywordSelector *)SelTabImpl.Allocator.Allocate( Size, alignof(MultiKeywordSelector)); new (SI) MultiKeywordSelector(nKeys, IIV); SelTabImpl.Table.InsertNode(SI, InsertPos); return Selector(SI); } SelectorTable::SelectorTable() { Impl = new SelectorTableImpl(); } SelectorTable::~SelectorTable() { delete &getSelectorTableImpl(Impl); } const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) { switch (Operator) { case OO_None: case NUM_OVERLOADED_OPERATORS: return nullptr; #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ case OO_##Name: return Spelling; #include "clang/Basic/OperatorKinds.def" } llvm_unreachable("Invalid OverloadedOperatorKind!"); } StringRef clang::getNullabilitySpelling(NullabilityKind kind, bool isContextSensitive) { switch (kind) { case NullabilityKind::NonNull: return isContextSensitive ? "nonnull" : "_Nonnull"; case NullabilityKind::Nullable: return isContextSensitive ? "nullable" : "_Nullable"; case NullabilityKind::Unspecified: return isContextSensitive ? "null_unspecified" : "_Null_unspecified"; } llvm_unreachable("Unknown nullability kind."); }
[ "milovidov@yandex-team.ru" ]
milovidov@yandex-team.ru
4a9133ddb6d9eb9f7a3eb47d157200415e748cd3
4b6db2bfec027acdd71e1d030829983bade67980
/src/Draw/Text.h
ff67611214c68cec2ac1055830858cf152892386
[]
no_license
AkiraSekine/CreaDXTKLib
78b0980777814d6d2a4336cfdb779d1ab0007f7b
9259ecd31a003c620dddc770e383173f5d3bcda7
refs/heads/develop
2020-03-30T23:07:33.919981
2019-02-15T06:02:02
2019-02-15T06:02:02
151,691,370
0
0
null
2019-02-15T06:02:03
2018-10-05T08:23:28
HTML
SHIFT_JIS
C++
false
false
2,502
h
#pragma once #include "../Default/pch.h" #include "../Utility/Singleton.h" #include "../Math/Vector2.h" #include <string> #include <map> namespace CreaDXTKLib { namespace Draw { /// <summary> /// テキスト描画クラス /// </summary> class Text final : public Utility::Singleton<Text> { SINGLETON(Text) public: /// <summary> /// フォントファイルの読み込み /// </summary> /// <param name="_key">ハンドル名</param> /// <param name="_fileName">ファイル名</param> void Load(const std::wstring& _key, const std::wstring& _fileName); /// <summary> /// テキストの描画 /// </summary> /// <param name="_key">ハンドル名</param> /// <param name="_position">描画座標</param> /// <param name="_text">描画文字列(フォーマット)</param> void Draw(const std::wstring& _key, const Math::Vector2& _position, const std::wstring _text, ...); /// <summary> /// テキストの描画 /// </summary> /// <param name="_key">ハンドル名</param> /// <param name="_position">描画座標</param> /// <param name="_color">色</param> /// <param name="_text">描画文字列(フォーマット)</param> void Draw(const std::wstring& _key, const Math::Vector2& _position, const DirectX::XMVECTORF32& _color , const std::wstring _text, ...); /// <summary> /// テキストの描画 /// </summary> /// <param name="_key">ハンドル名</param> /// <param name="_position">描画座標</param> /// <param name="_color">色</param> /// <param name="_text">描画文字列(フォーマット)</param> void Draw(const std::wstring& _key, const Math::Vector2& _position, const DirectX::FXMVECTOR& _color , const std::wstring _text, ...); /// <summary> /// 初期化処理 /// </summary> void Initialize(Microsoft::WRL::ComPtr<ID3D11Device1> _device, Microsoft::WRL::ComPtr<ID3D11DeviceContext1> _context); /// <summary> /// 終了処理 /// </summary> void OnEnd(); private: Microsoft::WRL::ComPtr<ID3D11Device1> m_device; std::unique_ptr<DirectX::SpriteBatch> m_spriteBatch; std::map<std::wstring, DirectX::SpriteFont*> m_fonts = std::map<std::wstring, DirectX::SpriteFont*>(); }; } // Draw } // CreaDXTKLib
[ "ekusika834@gmail.com" ]
ekusika834@gmail.com
288230e9c8d07e65f331be84dae3541bd8429c30
c26b2d68eab6ce8a7bcabaa61a0edcf067362aea
/vz03/src/herbivora.h
bb867b5ce4aa6e64988ea2e29cc49c33f213e8af
[]
no_license
reiva5/oop
b810f4c75f209eef631c2cf2cd26dfad284cd236
465c6075f2d2f16221c482bae9dbb4117c4a6398
refs/heads/master
2020-12-10T04:28:46.077254
2017-03-15T06:36:02
2017-03-15T06:36:02
83,626,249
0
0
null
null
null
null
UTF-8
C++
false
false
419
h
#ifndef HERBIVORA_H #define HREBIVORA_H #include "pemakan.h" /** @class Herbivora * Kelas Herbivora menyimpan informasi makanan berupa tumbuhan */ class Herbivora: public Pemakan { public: /** @brief Setter tumbuhan * @param n Jumlah tumbuhan yang diinginkan */ void SetAmount(int n); /** @brief Getter tumbuhan * @return tumbuhan */ int GetAmount(); protected: int tumbuhan; }; #endif
[ "apratamamia@gmail.com" ]
apratamamia@gmail.com
1cd2b7ce9a506eb8b775389be6d61a36481bfe5c
3c1dbc0532ec129a34dfc5eb6b663d7eaf31a1f8
/limak_house.cpp
ac80f9d7ee246671c9cd11ac2355035eae409fcd
[]
no_license
fredybotas/Spoj
c79702b163627f3f83461fb2ccb923c544ae7a16
5a99e0d15b8fcbbb093dc1c694cdd56c2f83f0c4
refs/heads/master
2021-01-19T20:34:56.636668
2017-02-27T00:03:39
2017-02-27T00:03:39
81,080,973
0
0
null
null
null
null
UTF-8
C++
false
false
1,865
cpp
#include <stdio.h> #include <string.h> int main(){ //najdi spodok char buffer[20]; int curr, i, low = 0, high = 1000; while(low < high){ curr = (low + high) / 2; printf("? %d %d\n", curr, 0); fflush(stdout); scanf("%s", buffer); if(!strcmp(buffer, "YES")) low = curr + 1; else high = curr; } for(i = curr - 3; i < curr + 4; i++){ if(i == 1000){ curr = 1000; break; } printf("? %d %d\n", i, 0); fflush(stdout); scanf("%s", buffer); if(!strcmp(buffer, "YES")) continue; else{ curr = i - 1; break; } } int x_square = curr*2; //trojuholnik low = x_square/2; high = 1000; while(low < high){ curr = (low + high) / 2; printf("? %d %d\n", curr, x_square); fflush(stdout); scanf("%s", buffer); if(!strcmp(buffer, "YES")) low = curr + 1; else high = curr; } for(i = curr - 3; i < curr + 4; i++){ if(i == 1000){ curr = 1000; break; } printf("? %d %d\n", i, x_square); fflush(stdout); scanf("%s", buffer); if(!strcmp(buffer, "YES")) continue; else{ curr = i - 1; break; } } int x_triangle = curr*2; low = x_square; high = 1000; while(low < high){ curr = (low + high) / 2; printf("? %d %d\n", 0, curr); fflush(stdout); scanf("%s", buffer); if(!strcmp(buffer, "YES")) low = curr + 1; else high = curr; } for(i = curr - 3; i < curr + 4; i++){ if(i == 1000){ curr = 1000; break; } printf("? %d %d\n", 0, i); fflush(stdout); scanf("%s", buffer); if(!strcmp(buffer, "YES")) continue; else{ curr = i - 1; break; } } int height = curr; printf("! %d\n", x_square*x_square + x_triangle*(height - x_square)/2); fflush(stdout); return 0; }
[ "fredybotas@gmail.com" ]
fredybotas@gmail.com
508d55d75ab154fe547faf8438d150f7652f0e14
52a3c93c38bef127eaee4420f36a89d929a321c5
/SDK/SoT_BP_FishingFish_Wrecker_05_Colour_05_Moon_classes.hpp
8be34a73802fcedf704075651af56099a98ab051
[]
no_license
RDTCREW/SoT-SDK_2_0_7_reserv
8e921275508d09e5f81b10f9a43e47597223cb35
db6a5fc4cdb9348ddfda88121ebe809047aa404a
refs/heads/master
2020-07-24T17:18:40.537329
2019-09-11T18:53:58
2019-09-11T18:53:58
207,991,316
0
0
null
null
null
null
UTF-8
C++
false
false
883
hpp
#pragma once // Sea of Thieves (2.0) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_BP_FishingFish_Wrecker_05_Colour_05_Moon_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_FishingFish_Wrecker_05_Colour_05_Moon.BP_FishingFish_Wrecker_05_Colour_05_Moon_C // 0x0000 (0x0990 - 0x0990) class ABP_FishingFish_Wrecker_05_Colour_05_Moon_C : public ABP_FishingFish_Wrecker_05_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass BP_FishingFish_Wrecker_05_Colour_05_Moon.BP_FishingFish_Wrecker_05_Colour_05_Moon_C")); return ptr; } void UserConstructionScript(); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "igromanru@yahoo.de" ]
igromanru@yahoo.de
3046cc516b94d3d61b5944e8e72cb324eb8e83b2
2f10f807d3307b83293a521da600c02623cdda82
/deps/boost/win/debug/include/boost/hana/fwd/concept/sequence.hpp
422e52578079c9edc98e149f855e4d4868c1d9cf
[]
no_license
xpierrohk/dpt-rp1-cpp
2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e
643d053983fce3e6b099e2d3c9ab8387d0ea5a75
refs/heads/master
2021-05-23T08:19:48.823198
2019-07-26T17:35:28
2019-07-26T17:35:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
129
hpp
version https://git-lfs.github.com/spec/v1 oid sha256:2995f98908d109d3d0c6f3843c95855164d1b5d8229cdc1d99bcf3b7094d3655 size 7412
[ "YLiLarry@gmail.com" ]
YLiLarry@gmail.com
95f7befcf665c6bd7d6cf9cdcc561666e56f2e88
cf88c1e3d9587f2bdc8cf40397bca3f0b5f11e7c
/Arrays/Array_Rearrangement/MaxLengthBitonicSubsequence.cpp
fb2e5de210006b85afeb4f3b2d78fe1f36e1b413
[]
no_license
shaival141/Practice_Old
f6193b4ae2365548d70c047180de429f9a9fdc1d
f02d55faf1c0a861093bf0e094747c64bdd81b34
refs/heads/master
2022-01-05T12:54:54.863035
2018-05-18T18:05:06
2018-05-18T18:05:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,321
cpp
/* Dynamic Programming implementation of longest bitonic subsequence problem */ #include<stdio.h> #include<stdlib.h> /* lbs() returns the length of the Longest Bitonic Subsequence in arr[] of size n. The function mainly creates two temporary arrays lis[] and lds[] and returns the maximum lis[i] + lds[i] - 1. lis[i] ==> Longest Increasing subsequence ending with arr[i] lds[i] ==> Longest decreasing subsequence starting with arr[i] */ int lbs( int arr[], int n ) { int i,j; int lis[n]; int lds[n]; for(i=0;i<n;i++) lis[i]=1; for(i=0;i<n;i++) lds[i]=1; for(i=1;i<n;i++) { for(j=0;j<i;j++) { if(arr[j]<arr[i] && lis[i]<lis[j]+1) lis[i]=lis[j]+1; } } for(i=n-1;i>=0;i--) { for(j=n-1;j>i;j--) { if(arr[j]<arr[i] && lds[i]<lds[j]+1) lds[i]=lds[j]+1; } } int max=0; for(i=0;i<n;i++) { if(lis[i]+lds[i]-1>max) { max =lis[i] + lds[i] - 1; } } return max; } /* Driver program to test above function */ int main() { int arr[] = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}; int n = sizeof(arr)/sizeof(arr[0]); printf("Length of LBS is %d\n", lbs( arr, n ) ); return 0; }
[ "ambiciomonk@gmail.com" ]
ambiciomonk@gmail.com
a8d17ef93bf42f1113f7e8f7b8af41d62d7166d6
2b1a79a1fd6ebe6ebeb3b58d6b8144bf8ccd8c0d
/Games/Rong/Export/cpp/windows/obj/src/StringTools.cpp
7cd4329bc5960408e432ca980ec5fefd8315e61a
[]
no_license
spoozbe/Portfolio
18ba48bad5981e21901d2ef2b5595584b2451c19
4818a58eb50cbec949854456af6bbd49d6f37716
refs/heads/master
2021-01-02T08:45:38.660402
2014-11-02T04:49:25
2014-11-02T04:49:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,029
cpp
#include <hxcpp.h> #ifndef INCLUDED_StringTools #include <StringTools.h> #endif Void StringTools_obj::__construct() { return null(); } StringTools_obj::~StringTools_obj() { } Dynamic StringTools_obj::__CreateEmpty() { return new StringTools_obj; } hx::ObjectPtr< StringTools_obj > StringTools_obj::__new() { hx::ObjectPtr< StringTools_obj > result = new StringTools_obj(); result->__construct(); return result;} Dynamic StringTools_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< StringTools_obj > result = new StringTools_obj(); result->__construct(); return result;} ::String StringTools_obj::urlEncode( ::String s){ HX_STACK_PUSH("StringTools::urlEncode","C:\\Motion-Twin\\haxe/std/StringTools.hx",41); HX_STACK_ARG(s,"s"); HX_STACK_LINE(41) return s.__URLEncode(); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,urlEncode,return ) ::String StringTools_obj::urlDecode( ::String s){ HX_STACK_PUSH("StringTools::urlDecode","C:\\Motion-Twin\\haxe/std/StringTools.hx",68); HX_STACK_ARG(s,"s"); HX_STACK_LINE(68) return s.__URLDecode(); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,urlDecode,return ) ::String StringTools_obj::htmlEscape( ::String s){ HX_STACK_PUSH("StringTools::htmlEscape","C:\\Motion-Twin\\haxe/std/StringTools.hx",95); HX_STACK_ARG(s,"s"); HX_STACK_LINE(95) return s.split(HX_CSTRING("&"))->join(HX_CSTRING("&amp;")).split(HX_CSTRING("<"))->join(HX_CSTRING("&lt;")).split(HX_CSTRING(">"))->join(HX_CSTRING("&gt;")); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,htmlEscape,return ) ::String StringTools_obj::htmlUnescape( ::String s){ HX_STACK_PUSH("StringTools::htmlUnescape","C:\\Motion-Twin\\haxe/std/StringTools.hx",102); HX_STACK_ARG(s,"s"); HX_STACK_LINE(102) return s.split(HX_CSTRING("&gt;"))->join(HX_CSTRING(">")).split(HX_CSTRING("&lt;"))->join(HX_CSTRING("<")).split(HX_CSTRING("&amp;"))->join(HX_CSTRING("&")); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,htmlUnescape,return ) bool StringTools_obj::startsWith( ::String s,::String start){ HX_STACK_PUSH("StringTools::startsWith","C:\\Motion-Twin\\haxe/std/StringTools.hx",113); HX_STACK_ARG(s,"s"); HX_STACK_ARG(start,"start"); HX_STACK_LINE(113) return (bool((s.length >= start.length)) && bool((s.substr((int)0,start.length) == start))); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(StringTools_obj,startsWith,return ) bool StringTools_obj::endsWith( ::String s,::String end){ HX_STACK_PUSH("StringTools::endsWith","C:\\Motion-Twin\\haxe/std/StringTools.hx",126); HX_STACK_ARG(s,"s"); HX_STACK_ARG(end,"end"); HX_STACK_LINE(132) int elen = end.length; HX_STACK_VAR(elen,"elen"); HX_STACK_LINE(133) int slen = s.length; HX_STACK_VAR(slen,"slen"); HX_STACK_LINE(134) return (bool((slen >= elen)) && bool((s.substr((slen - elen),elen) == end))); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(StringTools_obj,endsWith,return ) bool StringTools_obj::isSpace( ::String s,int pos){ HX_STACK_PUSH("StringTools::isSpace","C:\\Motion-Twin\\haxe/std/StringTools.hx",141); HX_STACK_ARG(s,"s"); HX_STACK_ARG(pos,"pos"); HX_STACK_LINE(142) Dynamic c = s.charCodeAt(pos); HX_STACK_VAR(c,"c"); HX_STACK_LINE(143) return (bool((bool((c >= (int)9)) && bool((c <= (int)13)))) || bool((c == (int)32))); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(StringTools_obj,isSpace,return ) ::String StringTools_obj::ltrim( ::String s){ HX_STACK_PUSH("StringTools::ltrim","C:\\Motion-Twin\\haxe/std/StringTools.hx",149); HX_STACK_ARG(s,"s"); HX_STACK_LINE(155) int l = s.length; HX_STACK_VAR(l,"l"); HX_STACK_LINE(156) int r = (int)0; HX_STACK_VAR(r,"r"); HX_STACK_LINE(157) while(((bool((r < l)) && bool(::StringTools_obj::isSpace(s,r))))){ HX_STACK_LINE(157) (r)++; } HX_STACK_LINE(160) if (((r > (int)0))){ HX_STACK_LINE(161) return s.substr(r,(l - r)); } else{ HX_STACK_LINE(163) return s; } HX_STACK_LINE(160) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,ltrim,return ) ::String StringTools_obj::rtrim( ::String s){ HX_STACK_PUSH("StringTools::rtrim","C:\\Motion-Twin\\haxe/std/StringTools.hx",170); HX_STACK_ARG(s,"s"); HX_STACK_LINE(176) int l = s.length; HX_STACK_VAR(l,"l"); HX_STACK_LINE(177) int r = (int)0; HX_STACK_VAR(r,"r"); HX_STACK_LINE(178) while(((bool((r < l)) && bool(::StringTools_obj::isSpace(s,((l - r) - (int)1)))))){ HX_STACK_LINE(178) (r)++; } HX_STACK_LINE(181) if (((r > (int)0))){ HX_STACK_LINE(181) return s.substr((int)0,(l - r)); } else{ HX_STACK_LINE(183) return s; } HX_STACK_LINE(181) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,rtrim,return ) ::String StringTools_obj::trim( ::String s){ HX_STACK_PUSH("StringTools::trim","C:\\Motion-Twin\\haxe/std/StringTools.hx",192); HX_STACK_ARG(s,"s"); HX_STACK_LINE(192) return ::StringTools_obj::ltrim(::StringTools_obj::rtrim(s)); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,trim,return ) ::String StringTools_obj::rpad( ::String s,::String c,int l){ HX_STACK_PUSH("StringTools::rpad","C:\\Motion-Twin\\haxe/std/StringTools.hx",207); HX_STACK_ARG(s,"s"); HX_STACK_ARG(c,"c"); HX_STACK_ARG(l,"l"); HX_STACK_LINE(211) int sl = s.length; HX_STACK_VAR(sl,"sl"); HX_STACK_LINE(212) int cl = c.length; HX_STACK_VAR(cl,"cl"); HX_STACK_LINE(213) while(((sl < l))){ HX_STACK_LINE(213) if ((((l - sl) < cl))){ HX_STACK_LINE(215) hx::AddEq(s,c.substr((int)0,(l - sl))); HX_STACK_LINE(216) sl = l; } else{ HX_STACK_LINE(218) hx::AddEq(s,c); HX_STACK_LINE(219) hx::AddEq(sl,cl); } } HX_STACK_LINE(222) return s; } STATIC_HX_DEFINE_DYNAMIC_FUNC3(StringTools_obj,rpad,return ) ::String StringTools_obj::lpad( ::String s,::String c,int l){ HX_STACK_PUSH("StringTools::lpad","C:\\Motion-Twin\\haxe/std/StringTools.hx",229); HX_STACK_ARG(s,"s"); HX_STACK_ARG(c,"c"); HX_STACK_ARG(l,"l"); HX_STACK_LINE(233) ::String ns = HX_CSTRING(""); HX_STACK_VAR(ns,"ns"); HX_STACK_LINE(234) int sl = s.length; HX_STACK_VAR(sl,"sl"); HX_STACK_LINE(235) if (((sl >= l))){ HX_STACK_LINE(235) return s; } HX_STACK_LINE(237) int cl = c.length; HX_STACK_VAR(cl,"cl"); HX_STACK_LINE(238) while(((sl < l))){ HX_STACK_LINE(238) if ((((l - sl) < cl))){ HX_STACK_LINE(240) hx::AddEq(ns,c.substr((int)0,(l - sl))); HX_STACK_LINE(241) sl = l; } else{ HX_STACK_LINE(243) hx::AddEq(ns,c); HX_STACK_LINE(244) hx::AddEq(sl,cl); } } HX_STACK_LINE(247) return (ns + s); } STATIC_HX_DEFINE_DYNAMIC_FUNC3(StringTools_obj,lpad,return ) ::String StringTools_obj::replace( ::String s,::String sub,::String by){ HX_STACK_PUSH("StringTools::replace","C:\\Motion-Twin\\haxe/std/StringTools.hx",254); HX_STACK_ARG(s,"s"); HX_STACK_ARG(sub,"sub"); HX_STACK_ARG(by,"by"); HX_STACK_LINE(254) return s.split(sub)->join(by); } STATIC_HX_DEFINE_DYNAMIC_FUNC3(StringTools_obj,replace,return ) ::String StringTools_obj::hex( int n,Dynamic digits){ HX_STACK_PUSH("StringTools::hex","C:\\Motion-Twin\\haxe/std/StringTools.hx",269); HX_STACK_ARG(n,"n"); HX_STACK_ARG(digits,"digits"); HX_STACK_LINE(275) ::String s = HX_CSTRING(""); HX_STACK_VAR(s,"s"); HX_STACK_LINE(276) ::String hexChars = HX_CSTRING("0123456789ABCDEF"); HX_STACK_VAR(hexChars,"hexChars"); HX_STACK_LINE(277) do{ HX_STACK_LINE(278) s = (hexChars.charAt((int(n) & int((int)15))) + s); HX_STACK_LINE(279) hx::UShrEq(n,(int)4); } while(((n > (int)0))); HX_STACK_LINE(282) if (((digits != null()))){ HX_STACK_LINE(283) while(((s.length < digits))){ HX_STACK_LINE(284) s = (HX_CSTRING("0") + s); } } HX_STACK_LINE(285) return s; } STATIC_HX_DEFINE_DYNAMIC_FUNC2(StringTools_obj,hex,return ) int StringTools_obj::fastCodeAt( ::String s,int index){ HX_STACK_PUSH("StringTools::fastCodeAt","C:\\Motion-Twin\\haxe/std/StringTools.hx",292); HX_STACK_ARG(s,"s"); HX_STACK_ARG(index,"index"); HX_STACK_LINE(292) return s.cca(index); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(StringTools_obj,fastCodeAt,return ) bool StringTools_obj::isEOF( int c){ HX_STACK_PUSH("StringTools::isEOF","C:\\Motion-Twin\\haxe/std/StringTools.hx",322); HX_STACK_ARG(c,"c"); HX_STACK_LINE(322) return (c == (int)0); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,isEOF,return ) StringTools_obj::StringTools_obj() { } void StringTools_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(StringTools); HX_MARK_END_CLASS(); } void StringTools_obj::__Visit(HX_VISIT_PARAMS) { } Dynamic StringTools_obj::__Field(const ::String &inName,bool inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"hex") ) { return hex_dyn(); } break; case 4: if (HX_FIELD_EQ(inName,"trim") ) { return trim_dyn(); } if (HX_FIELD_EQ(inName,"rpad") ) { return rpad_dyn(); } if (HX_FIELD_EQ(inName,"lpad") ) { return lpad_dyn(); } break; case 5: if (HX_FIELD_EQ(inName,"ltrim") ) { return ltrim_dyn(); } if (HX_FIELD_EQ(inName,"rtrim") ) { return rtrim_dyn(); } if (HX_FIELD_EQ(inName,"isEOF") ) { return isEOF_dyn(); } break; case 7: if (HX_FIELD_EQ(inName,"isSpace") ) { return isSpace_dyn(); } if (HX_FIELD_EQ(inName,"replace") ) { return replace_dyn(); } break; case 8: if (HX_FIELD_EQ(inName,"endsWith") ) { return endsWith_dyn(); } break; case 9: if (HX_FIELD_EQ(inName,"urlEncode") ) { return urlEncode_dyn(); } if (HX_FIELD_EQ(inName,"urlDecode") ) { return urlDecode_dyn(); } break; case 10: if (HX_FIELD_EQ(inName,"htmlEscape") ) { return htmlEscape_dyn(); } if (HX_FIELD_EQ(inName,"startsWith") ) { return startsWith_dyn(); } if (HX_FIELD_EQ(inName,"fastCodeAt") ) { return fastCodeAt_dyn(); } break; case 12: if (HX_FIELD_EQ(inName,"htmlUnescape") ) { return htmlUnescape_dyn(); } } return super::__Field(inName,inCallProp); } Dynamic StringTools_obj::__SetField(const ::String &inName,const Dynamic &inValue,bool inCallProp) { return super::__SetField(inName,inValue,inCallProp); } void StringTools_obj::__GetFields(Array< ::String> &outFields) { super::__GetFields(outFields); }; static ::String sStaticFields[] = { HX_CSTRING("urlEncode"), HX_CSTRING("urlDecode"), HX_CSTRING("htmlEscape"), HX_CSTRING("htmlUnescape"), HX_CSTRING("startsWith"), HX_CSTRING("endsWith"), HX_CSTRING("isSpace"), HX_CSTRING("ltrim"), HX_CSTRING("rtrim"), HX_CSTRING("trim"), HX_CSTRING("rpad"), HX_CSTRING("lpad"), HX_CSTRING("replace"), HX_CSTRING("hex"), HX_CSTRING("fastCodeAt"), HX_CSTRING("isEOF"), String(null()) }; static ::String sMemberFields[] = { String(null()) }; static void sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(StringTools_obj::__mClass,"__mClass"); }; static void sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(StringTools_obj::__mClass,"__mClass"); }; Class StringTools_obj::__mClass; void StringTools_obj::__register() { Static(__mClass) = hx::RegisterClass(HX_CSTRING("StringTools"), hx::TCanCast< StringTools_obj> ,sStaticFields,sMemberFields, &__CreateEmpty, &__Create, &super::__SGetClass(), 0, sMarkStatics, sVisitStatics); } void StringTools_obj::__boot() { }
[ "venablesk@gmail.com" ]
venablesk@gmail.com
37a17f5aada19a69bd57c79199f40ec689d1616f
4ddb183621a8587f45c12216d0227d36dfb430ff
/MBDGeneralFW/MBDTechInfo.m/src/MBDNoteModifyDlg.cpp
a936ad957930efba2ddfc947cf25662e1c5142a8
[]
no_license
0000duck/good-idea
7cdd05c55483faefb96ef9b2efaa7b7eb2f22512
876b9c8bb67fa4a7dc62d89683d4fd9d28a94cae
refs/heads/master
2021-05-29T02:46:02.336920
2013-07-22T17:53:06
2013-07-22T17:53:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,085
cpp
// COPYRIGHT Dassault Systemes 2010 //=================================================================== // // MBDNoteModifyDlg.cpp // The dialog : MBDNoteModifyDlg // //=================================================================== // // Usage notes: // //=================================================================== // // Mar 2010 Creation: Code generated by the CAA wizard ev5adm //=================================================================== #include "MBDNoteModifyDlg.h" #include "CATApplicationFrame.h" #include "CATDlgGridConstraints.h" #include "CATMsgCatalog.h" #ifdef MBDNoteModifyDlg_ParameterEditorInclude #include "CATIParameterEditorFactory.h" #include "CATIParameterEditor.h" #include "CATICkeParm.h" #endif //------------------------------------------------------------------------- // Constructor //------------------------------------------------------------------------- MBDNoteModifyDlg::MBDNoteModifyDlg() : CATDlgDialog ((CATApplicationFrame::GetApplicationFrame())->GetMainWindow(), //CAA2 WIZARD CONSTRUCTOR DECLARATION SECTION "MBDNoteModifyDlg",CATDlgWndModal|CATDlgWndPointerLocation|CATDlgWndBtnOKCancel|CATDlgGridLayout //END CAA2 WIZARD CONSTRUCTOR DECLARATION SECTION ) { //CAA2 WIZARD CONSTRUCTOR INITIALIZATION SECTION _MBDModifyNameEditor = NULL; _MBDModifyValueEditor = NULL; //END CAA2 WIZARD CONSTRUCTOR INITIALIZATION SECTION } //------------------------------------------------------------------------- // Destructor //------------------------------------------------------------------------- MBDNoteModifyDlg::~MBDNoteModifyDlg() { // Do not delete the control elements of your dialog: // this is done automatically // -------------------------------------------------- //CAA2 WIZARD DESTRUCTOR DECLARATION SECTION _MBDModifyNameEditor = NULL; _MBDModifyValueEditor = NULL; //END CAA2 WIZARD DESTRUCTOR DECLARATION SECTION } void MBDNoteModifyDlg::Build() { // TODO: This call builds your dialog from the layout declaration file // ------------------------------------------------------------------- //CAA2 WIZARD WIDGET CONSTRUCTION SECTION _MBDModifyNameEditor = new CATDlgEditor(this, "MBDModifyNameEditor", CATDlgEdtReadOnly); _MBDModifyNameEditor -> SetVisibleTextWidth(5); _MBDModifyNameEditor -> SetGridConstraints(0, 0, 1, 1, CATGRID_4SIDES); _MBDModifyValueEditor = new CATDlgEditor(this, "MBDModifyValueEditor"); _MBDModifyValueEditor -> SetGridConstraints(0, 1, 1, 1, CATGRID_4SIDES); //END CAA2 WIZARD WIDGET CONSTRUCTION SECTION int oHeight = 0,oWidth = 0; PrtService::GetWindowMaxSize(&oHeight,&oWidth ); _MBDModifyValueEditor -> SetVisibleTextWidth(int (0.065*oWidth)); //CAA2 WIZARD CALLBACK DECLARATION SECTION //END CAA2 WIZARD CALLBACK DECLARATION SECTION } CATDlgEditor* MBDNoteModifyDlg::GetMBDNoteModifyNameEditor() { return _MBDModifyNameEditor; } CATDlgEditor* MBDNoteModifyDlg::GetMBDNoteModifyValueEditor() { return _MBDModifyValueEditor; }
[ "zhangwy0916@e6631ee2-bc36-6fc4-7263-08c298121e4e" ]
zhangwy0916@e6631ee2-bc36-6fc4-7263-08c298121e4e
088e07cf5b8e57147205361a7bb8da08825fbeeb
8dc84558f0058d90dfc4955e905dab1b22d12c08
/third_party/blink/renderer/core/html/link_element_loading_test.cc
c82c7593f5fe8ef11d8e34e702f07dfa1a2f5fb7
[ "LGPL-2.0-only", "BSD-2-Clause", "LGPL-2.1-only", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
1,395
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/html/html_link_element.h" #include "third_party/blink/renderer/core/testing/sim/sim_request.h" #include "third_party/blink/renderer/core/testing/sim/sim_test.h" namespace blink { class LinkElementLoadingTest : public SimTest {}; TEST_F(LinkElementLoadingTest, ShouldCancelLoadingStyleSheetIfLinkElementIsDisconnected) { SimRequest main_resource("https://example.com/test.html", "text/html"); SimRequest css_resource("https://example.com/test.css", "text/css"); LoadURL("https://example.com/test.html"); main_resource.Start(); main_resource.Write( "<!DOCTYPE html><link id=link rel=stylesheet href=test.css>"); // Sheet is streaming in, but not ready yet. css_resource.Start(); // Remove a link element from a document HTMLLinkElement* link = ToHTMLLinkElement(GetDocument().getElementById("link")); EXPECT_NE(nullptr, link); link->remove(); // Finish the load. css_resource.Complete(); main_resource.Finish(); // Link element's sheet loading should be canceled. EXPECT_EQ(nullptr, link->sheet()); } } // namespace blink
[ "arnaud@geometry.ee" ]
arnaud@geometry.ee
e96e3af0be76106444fb057262c722e6095061a3
d4baaa6748dda226b88a1afb2fba2b6c6f54a3cc
/QuestionAnswer_1/source/user.h
a61b280ceaa5b68c731d18c6ba2624a705a5fe11
[]
no_license
zhangjiuchao/ProgramDesign
8343363e9ebd4ad8bc2beb051c36f450cda653fe
175c286b2ed2eca3c386f7aaf7ec13404989a95f
refs/heads/master
2020-06-30T18:34:16.947478
2016-08-26T15:20:53
2016-08-26T15:20:53
66,571,078
0
0
null
null
null
null
UTF-8
C++
false
false
1,026
h
#ifndef USER_H #define USER_H //#include <iostream> #include <QString> #include <QList> #include "questinfor.h" #include <QTextStream> class user { public: user(QString str1="",QString str2="",QString str3=""); bool AddFocus(QString focusID); void AddQuest(QString title,QString content); void AddAnswer(QString); void eraseQuest(QString question_id); void eraseFocus(QString eraseID); bool changePassword(QString str1,QString str2,QString str3); bool isFocus(QString id); friend QTextStream& operator<<(QTextStream& os,const user* host); friend QTextStream& operator>>(QTextStream& is,user* host); QList<QString> getFocusList(); QList<QString> getMyQuestion(); QList<QString> get_question_my_anwser(); QString getID(); QString getName(); QString getPassword(); private: QString ID; QString userName; QString Password; QList<QString> focusList; QList<QString> myQuestion; QList<QString> question_my_answer; }; #endif // USER_H
[ "1665327050@qq.com" ]
1665327050@qq.com
df4686b64f23df1bd180ab71749f892557da3e90
c50c4796cc416e78ef2c8883899d12f1d4e0a9e8
/RPG/QuotesSettings.h
fcf5f16592a9e42f06884c6e6b893fd4d83f061d
[ "MIT" ]
permissive
kriskirov/RPG-Remote
052b5c9eb24a1f61415def3cb3d72e0d30489a49
f446f5461ad38267ed3a34dc80e8bd807ae29ef9
refs/heads/master
2021-01-20T01:19:10.416123
2017-05-09T11:37:42
2017-05-09T11:37:42
89,253,403
0
0
null
null
null
null
UTF-8
C++
false
false
465
h
#ifndef QUOTES_SETTINGS_H #define QUOTES_SETTINGS_H #include <string> struct QuotesSettings{ QuotesSettings() = default; QuotesSettings( std::string attack, std::string getAttacked, std::string getAttackedWhileDead, std::string dead ); ~QuotesSettings() = default; QuotesSettings& operator=(const QuotesSettings& rhs) = default; std::string mAttack; std::string mGetAttacked; std::string mGetAttackedWhileDead; std::string mDead; }; #endif
[ "kriskirov92@gmail.com" ]
kriskirov92@gmail.com
4369c661485646300e4388170f7303ad261fce8b
70dc2b3a7418bb0b5b8092b037bb3eeeea1ed4a0
/gui-kde/unitselector.h
638588de4f3f8c94b3295bf57eabc8f9ffb756fe
[]
no_license
jusirkka/freeciv-kde
829bc62643876b1491bbf8e3b3f8274383aedf3a
417c80d46b53f0a7fe75f3ffd5200041f1a58d57
refs/heads/master
2020-04-20T01:55:45.980679
2019-04-28T03:28:24
2019-04-28T03:28:24
168,558,596
0
0
null
null
null
null
UTF-8
C++
false
false
999
h
#ifndef UNITSELECTOR_H #define UNITSELECTOR_H #include <QWidget> #include <QTimer> struct tile; struct unit; namespace KV { class UnitSelector: public QWidget { Q_OBJECT public: explicit UnitSelector(tile* t, QWidget *parent = nullptr); protected: void paintEvent(QPaintEvent *event) override; void mousePressEvent(QMouseEvent *event) override; void keyPressEvent(QKeyEvent *event) override; void mouseMoveEvent(QMouseEvent *event) override; void wheelEvent(QWheelEvent *event) override; void closeEvent(QCloseEvent *event) override; void enterEvent(QEvent *event) override; void leaveEvent(QEvent *event) override; private slots: void updateUnits(); private: void updateUnitList(); void createPixmap(); private: QPixmap m_pix; QPixmap m_pixHigh; QSize m_itemSize; QList<unit*> m_unitList; QFont m_font; QFont m_infoFont; int m_indexHigh; int m_unitOffset; tile *m_tile; QTimer m_delay; bool m_first; }; } #endif // UNITSELECTOR_H
[ "jukka.sirkka@iki.fi" ]
jukka.sirkka@iki.fi
da31735876bffe91848fabb58d01bca37453a174
fcb11ed067ca203932f930facb608e4a07824112
/series5.cpp
cb814ccf6b5cbbefc393b33f4d1027f8ca52fbf2
[]
no_license
debjyotigorai/Cpp
8891a7cdb813ae52a67667a04c80658f1374281f
19f35c3e64b480471cac0658713cb32d9213aa04
refs/heads/master
2021-06-28T01:31:01.889120
2019-02-06T16:08:53
2019-02-06T16:08:53
100,121,539
0
0
null
null
null
null
UTF-8
C++
false
false
455
cpp
//1 - x^2 + x^3 - x^4 + ... #include <iostream> #include <math.h> using namespace std; int main() { long long int i, x, sum=1, n; cout << "Enter the value of x : "; cin >> x; cout << "Enter the range : "; cin >> n; cout << "1"; for (i=2; i<=n; i++) { int z=pow(-1,i+1); if (z<0) cout << " - "; else cout << " + "; if (i==n) cout << x << "^5 "; else cout << x << "^" << i; sum+=(z)*(pow(x,i)); } cout << " = " << sum; }
[ "debjyotigorai@outlook.com" ]
debjyotigorai@outlook.com
9b83294b2fb573490cadd874fd3157c93a47fcac
c689037be8a029aa95bf5fe1c4aef2912f194f31
/LaboratoryDevices/SelectDevicesWidget.h
1278c022880d40441eb5570eadcee42586655303
[]
no_license
oscilo/LabDev
b6933d65562af9d210f809e00a0cfcc09c37833b
8ae22a5658f85f2854b30b47e6aebc75d1cb02e4
refs/heads/master
2020-05-31T03:27:28.118419
2017-03-15T22:44:28
2017-03-15T22:44:28
30,373,361
0
0
null
null
null
null
UTF-8
C++
false
false
2,663
h
#ifndef SELECTDEVICESWIDGET_H #define SELECTDEVICESWIDGET_H #include "globals.h" #include "structures.h" class CheckDeviceLayout : public QHBoxLayout { Q_OBJECT public: CheckDeviceLayout(const DeviceInfo &di, QWidget *parent = 0) : QHBoxLayout(parent), curDI(di) { check = new QCheckBox(di.name, parent); spin = new QSpinBox(parent); spin->setRange(1, 5); spin->hide(); connect(check, SIGNAL(clicked(bool)), spin, SLOT(setVisible(bool))); connect(check, SIGNAL(clicked(bool)), this, SLOT(OnOffSlot(bool))); connect(spin, SIGNAL(valueChanged(int)), this, SLOT(CountChanged(int))); this->addWidget(check, 1); this->addWidget(spin); } ~CheckDeviceLayout() { } QList<DeviceInfo>& GetDeviceList() { return devices; } signals: void UpdateDevices(); public slots: void Clear() { spin->setValue(1); spin->hide(); check->setChecked(false); } void CheckSelectionList(const QList<DeviceInfo> &existingSelection) { QList<DeviceInfo> newDevices; foreach(DeviceInfo di, existingSelection) { if(di.id == curDI.id) { di.order = newDevices.size(); newDevices << di; } } if(0 == newDevices.size()) Clear(); else { check->setChecked(true); spin->show(); spin->setValue(newDevices.size()); devices = newDevices; } } private slots: void OnOffSlot(bool action) { if(action) emit CountChanged(spin->value()); else emit CountChanged(0); } void CountChanged(int count) { int oldSize = devices.size(); if(oldSize == count) return; if(oldSize < count) { int flag = count - oldSize; while(flag) { DeviceInfo di = curDI; di.order = devices.size(); di.uuid = QUuid::createUuid(); devices << di; flag--; } } else { int flag = oldSize - count; while(flag) { devices.removeLast(); flag--; } } emit UpdateDevices(); } private: DeviceInfo curDI; QList<DeviceInfo> devices; QCheckBox *check; QSpinBox *spin; }; class SelectDevicesWidget : public QGroupBox { Q_OBJECT public: SelectDevicesWidget(QWidget *parent = 0); ~SelectDevicesWidget(); void SetDevicesList(const QList<DeviceInfo>&); DBRecordList GetSelectedDevices(); signals: void SelectionUpdated(const QList<DeviceInfo>&); void CheckSelectionList(const QList<DeviceInfo>&); public slots: void Clear(); void SetExistingSelection(const QList<DeviceInfo>&); private slots: void UpdateSelectedDevices(); private: void FillWidget(); void AddCheckLayoutAtPosition(const DeviceInfo &, int row, int column); QList<DeviceInfo> totalDevices; QList<DeviceInfo> selectedDevices; QList<CheckDeviceLayout*> checkLayouts; QGridLayout *layout; }; #endif
[ "deep@aaanet.ru" ]
deep@aaanet.ru
72a8c8e1d5a24677d25f802676368885cde7f460
c712c82341b30aad4678f6fbc758d6d20bd84c37
/CAC_Source_1.7884/RecusalBookDialog.h
43ecb8655aa472f0ac07fe40bdad7923e117ad1a
[]
no_license
governmentbg/EPEP_2019_d2
ab547c729021e1d625181e264bdf287703dcb46c
5e68240f15805c485505438b27de12bab56df91e
refs/heads/master
2022-12-26T10:00:41.766991
2020-09-28T13:55:30
2020-09-28T13:55:30
292,803,726
0
0
null
null
null
null
UTF-8
C++
false
false
358
h
class TRecusalBookDialog : public TFloatDialog { public: TRecusalBookDialog(TWindow* parent, TRecusalBookGroup *group, int resId = IDD_RECUSAL_BOOK); protected: TCharListFace *types; TCharAutoListFace *compositions; TDateFace *minDate; TDateFace *maxDate; TLongFace *autogen; TCheckFace *filtered; TCheckFace *recujed; virtual bool IsValid(); };
[ "git@vakata.com" ]
git@vakata.com
29ada50980d562e467d8267b9d3af643f6559c76
3ff49c066ddaf7e97ed2631760d438c6a1a452c5
/src/ast/ASTAbstractVisitor.h
479f96b3bd7bc0b42631a05748bb30fce6d49deb
[]
no_license
rudo-rov/CppSOM
26321838d058ec188ab72bfd70dca5c12184df1d
0fff035f9a5989014fb6ed214b41e7bdf088b904
refs/heads/main
2023-05-05T14:15:42.562364
2021-05-24T12:24:19
2021-05-24T12:24:19
342,613,612
0
0
null
null
null
null
UTF-8
C++
false
false
2,222
h
#pragma once #include <any> namespace som { // Forward declaration of AST nodes to resolve circular reference struct Class; struct Method; struct Block; struct NestedBlock; struct UnaryPattern; struct BinaryPattern; struct KeywordPattern; struct Keyword; struct KeywordWithArgs; struct UnarySelector; struct BinarySelector; struct BinaryOperand; struct KeywordSelector; struct UnaryMessage; struct BinaryMessage; struct KeywordMessage; struct Formula; struct LiteralInteger; struct LiteralDouble; struct LiteralArray; struct LiteralString; struct Assignation; struct Evaluation; struct Variable; struct NestedTerm; struct Result; class CAstAbstractVisitor { public: virtual std::any visit(Method* method) = 0; virtual std::any visit(Class* classNode) = 0; virtual std::any visit(Block* block) = 0; virtual std::any visit(NestedBlock* nestedBlock) = 0; virtual std::any visit(UnaryPattern* unaryPattern) = 0; virtual std::any visit(BinaryPattern* binaryPattern) = 0; virtual std::any visit(KeywordPattern* keywordPattern) = 0; virtual std::any visit(Keyword* keyword) = 0; virtual std::any visit(KeywordWithArgs* keyword) = 0; virtual std::any visit(UnarySelector* unarySelector) = 0; virtual std::any visit(BinarySelector* binarySelector) = 0; virtual std::any visit(KeywordSelector* keywordSelector) = 0; virtual std::any visit(UnaryMessage* unaryMessage) = 0; virtual std::any visit(BinaryMessage* binaryMessage) = 0; virtual std::any visit(BinaryOperand* binaryOperand) = 0; virtual std::any visit(KeywordMessage* keywordMessage) = 0; virtual std::any visit(Formula* formula) = 0; virtual std::any visit(LiteralInteger* litInteger) = 0; virtual std::any visit(LiteralString* litString) = 0; virtual std::any visit(LiteralArray* litArray) = 0; virtual std::any visit(LiteralDouble* litDouble) = 0; virtual std::any visit(Assignation* assignation) = 0; virtual std::any visit(Evaluation* evaluation) = 0; virtual std::any visit(Result* result) = 0; virtual std::any visit(Variable* variable) = 0; virtual std::any visit(NestedTerm* nestedTerm) = 0; }; }
[ "r.rovnak@gmail.com" ]
r.rovnak@gmail.com
76e76978aa547bdd62a466f226aa7723fe14facb
9484781e2faf0889182bc9fc9071d2a81e15e341
/Ground.cpp
3eaa89f1d1492713517daa9c1a3a76cd8cc0b333
[]
no_license
Tubbz-alt/trip-to-mars
0e34a7a608d8868a16f1748e327ada85b6310300
2122bb58f63abad0a2e6d0e814f7d0f2c323c98f
refs/heads/master
2021-05-28T23:14:41.708327
2015-03-27T19:11:12
2015-03-27T19:11:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,582
cpp
#include "Ground.h" /*---------------------------------------------------------------------------*/ Ground::Ground(int Xground, int Zground, float MaxHigh, float SoftCoef) { int i,j; xground = Xground; zground = Zground; maxhigh = MaxHigh; softcoef = SoftCoef; map = new float* [xground]; for(i=0; i<xground; i++) map[i] = new float [zground]; if( !USEFROMFILE ) { for(i=0; i<xground; i++) for(j=0; j<zground; j++) map[i][j]=-1.0; map[0][0]=xrand(0.0, maxhigh); // 1er rnd bug map[0][0]=xrand(0.0, maxhigh); map[xground-1][0]=xrand(0.0, maxhigh); map[0][zground-1]=xrand(0.0, maxhigh); map[xground-1][zground-1]=xrand(0.0, maxhigh); map[0][0]=0.; map[xground-1][0]=0.; map[0][zground-1]=0.; map[xground-1][zground-1]=0.; buildground(); lissage(LISSAGEDEGRE); HighCut(HIGHCUT); } else { loadheightmap(); lissage(LISSAGEDEGRE); } } /*---------------------------------------------------------------------------*/ Ground::~Ground() { for(int i=0; i<xground; i++) delete [] map[i]; delete [] map; } /*---------------------------------------------------------------------------*/ void Ground::loadheightmap() { int i, j; set_color_depth(8); //heightmap = load_bitmap("mountainheight513.bmp", NULL); heightmap = load_bitmap("canyonheight2.bmp", NULL); if ( !heightmap ) { allegro_message("No Highmap Found \n"); exit(1); } for(j=0; j<zground; j++) for(i=0; i<xground; i++) map[i][j] = float( (unsigned char)getpixel(heightmap, i, j) ); destroy_bitmap(heightmap); } /*---------------------------------------------------------------------------*/ void Ground::buildground() { buildsubground(0, 0, xground-1, zground-1); } /*---------------------------------------------------------------------------*/ void Ground::buildsubground(int x1, int z1, int x2, int z2) { int xm = (x1+x2)/2; int zm = (z1+z2)/2; int dl = MIN(x2-x1,z2-z1); int variance; float scaledrnd; variance = random(dl); variance = 2*variance - dl; scaledrnd = float(variance) * softcoef; if((xm!=x1)||(zm!=z1)) { // altitude new points map[x1][zm] = (map[x1][zm]==-1.0) ? ((map[x1][z1]+map[x1][z2])/float(2))+scaledrnd : map[x1][zm]; map[xm][z1] = (map[xm][z1]==-1.0) ? ((map[x1][z1]+map[x2][z1])/float(2))+scaledrnd : map[xm][z1]; map[xm][z2] = (map[xm][z2]==-1.0) ? ((map[x1][z2]+map[x2][z2])/float(2))+scaledrnd : map[xm][z2]; map[x2][zm] = (map[x2][zm]==-1.0) ? ((map[x2][z1]+map[x2][z2])/float(2))+scaledrnd : map[x2][zm]; map[xm][zm] = (map[xm][zm]==-1.0) ?((map[x1][z1]+map[x2][z1]+map[x1][z2]+map[x2][z2])/float(4))+scaledrnd : map[xm][zm]; // hauteur clipping map[x1][zm] = (map[x1][zm]<0.0) ? 0.0 : map[x1][zm]; map[xm][z1] = (map[xm][z1]<0.0) ? 0.0 : map[xm][z1]; map[xm][z2] = (map[xm][z2]<0.0) ? 0.0 : map[xm][z2]; map[x2][zm] = (map[x2][zm]<0.0) ? 0.0 : map[x2][zm]; map[xm][zm] = (map[xm][zm]<0.0) ? 0.0 : map[xm][zm]; map[x1][zm] = (map[x1][zm]>maxhigh) ? maxhigh : map[x1][zm]; map[xm][z1] = (map[xm][z1]>maxhigh) ? maxhigh : map[xm][z1]; map[xm][z2] = (map[xm][z2]>maxhigh) ? maxhigh : map[xm][z2]; map[x2][zm] = (map[x2][zm]>maxhigh) ? maxhigh : map[x2][zm]; map[xm][zm] = (map[xm][zm]>maxhigh) ? maxhigh : map[xm][zm]; // rec (!ordre>) buildsubground(x1,z1,xm,zm); buildsubground(xm,z1,x2,zm); buildsubground(x1,zm,xm,z2); buildsubground(xm,zm,x2,z2); } } /*---------------------------------------------------------------------------*/ void Ground::lissage(int degre) { int i, j, k; for(k=0; k<degre; k++) for(i=1; i<xground-1; i++) for(j=1; j<zground-1; j++) { if(map[i][j]!=0) { map[i][j]=(map[i-1][j-1]+map[i-1][j]+map[i-1][j+1]+map[i][j-1]+ map[i][j+1]+map[i+1][j-1]+map[i+1][j]+map[i+1][j+1])/8.; } } } /*---------------------------------------------------------------------------*/ void Ground::HighCut(int highcut) { int i, j; for(i=0; i<xground; i++) for(j=0; j<zground; j++) map[i][j] = (map[i][j]<(float)highcut) ? 0.0 : map[i][j]; } /*---------------------------------------------------------------------------*/ float Ground::xrand(float xl, float xh) { #if defined(LINUX) return (xl + (xh - xl) * drand48() ); #else return (xl + (xh - xl) * rand() / 32767.0 ); #endif } int Ground::random(int rndmax) { return ( rand() % (rndmax+1) ); }
[ "anthony.prieur@4cb61479-95d8-4551-e4b5-d013f55dcc39" ]
anthony.prieur@4cb61479-95d8-4551-e4b5-d013f55dcc39
d0037625ad2d3affbd5873f079c58a7a0a50304d
2db92f5aed1f3a18de6bfad1818ae662137692b2
/Default.h
c4b0f2e11e1a84c2feeb019b64a2b3af6fc57ca5
[]
no_license
Gelya-Cyber/Restoraunt
ec0bea4e6cf43543f78e266df8dae2700da192b9
3d0fb719568f84467b0966cd24b3e1e6af08e085
refs/heads/master
2022-11-13T00:05:21.289599
2020-06-18T12:21:22
2020-06-18T12:21:22
273,228,806
0
0
null
null
null
null
UTF-8
C++
false
false
1,936
h
/********************************************************************* Rhapsody : 9.0 Login : raxma Component : DefaultComponent Configuration : DefaultConfig Model Element : Default //! Generated Date : Thu, 18, Jun 2020 File Path : DefaultComponent\DefaultConfig\Default.h *********************************************************************/ #ifndef Default_H #define Default_H //## auto_generated #include <oxf\oxf.h> //## auto_generated #include <oxf\event.h> //## auto_generated class Authorization_Form; //## auto_generated class CancelReservation_Form; //## auto_generated class Database; //## auto_generated class Main_Form; //## auto_generated class MenuAdd_Form; //## auto_generated class MenuDelete_Form; //## auto_generated class MenuEdit_Form; //## auto_generated class Menu_Form; //## auto_generated class OrderAdd_Form; //## auto_generated class OrderDelete_Form; //## auto_generated class OrderEdit_Form; //## auto_generated class Order_Form; //## auto_generated class Reservation_Form; //## auto_generated class Table_Form; //## auto_generated class WaiterAdd_Form; //## auto_generated class WaiterDelete_Form; //## auto_generated class WaiterEdit_Form; //## auto_generated class Waiter_Form; //#[ ignore #define Enter_Password_Default_id 18601 //#] //## package Default //## event Enter_Password() class Enter_Password : public OMEvent { //// Constructors and destructors //// public : //## auto_generated Enter_Password(); //// Framework operations //// //## statechart_method virtual bool isTypeOf(const short id) const; }; #endif /********************************************************************* File Path : DefaultComponent\DefaultConfig\Default.h *********************************************************************/
[ "noreply@github.com" ]
noreply@github.com
a4b0f42c09efa2ae00be3b45fa8c4aee80eac3e7
575731c1155e321e7b22d8373ad5876b292b0b2f
/examples/native/ios/Pods/boost-for-react-native/boost/metaparse/v1/impl/push_back_c.hpp
c6868c0dc16cb49fd78c00b976ceed9edb14fad6
[ "BSL-1.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Nozbe/zacs
802a84ffd47413a1687a573edda519156ca317c7
c3d455426bc7dfb83e09fdf20781c2632a205c04
refs/heads/master
2023-06-12T20:53:31.482746
2023-06-07T07:06:49
2023-06-07T07:06:49
201,777,469
432
10
MIT
2023-01-24T13:29:34
2019-08-11T14:47:50
JavaScript
UTF-8
C++
false
false
1,027
hpp
#ifndef BOOST_METAPARSE_V1_PUSH_BACK_C_HPP #define BOOST_METAPARSE_V1_PUSH_BACK_C_HPP // Copyright Abel Sinkovics (abel@sinkovics.hu) 2013. // 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 <boost/metaparse/config.hpp> #include <boost/metaparse/v1/fwd/string.hpp> #include <boost/metaparse/v1/impl/update_c.hpp> #include <boost/metaparse/v1/impl/size.hpp> namespace boost { namespace metaparse { namespace v1 { namespace impl { template <class S, char C> struct push_back_c; #ifdef BOOST_METAPARSE_VARIADIC_STRING template <char... Cs, char C> struct push_back_c<string<Cs...>, C> : string<Cs..., C> {}; #else template <class S, char C> struct push_back_c : update_c<typename S::type, size<typename S::type>::type::value, C> {}; #endif } } } } #endif
[ "radexpl@gmail.com" ]
radexpl@gmail.com
753d6db593d2dbb3cbc3552a2e76c038af4365c9
f5f750efbde0ccd95856820c975ec88ee6ace0f8
/aws-cpp-sdk-apigateway/include/aws/apigateway/model/PutMethodRequest.h
b09c86623a5a17eb3cc9a9ae9099ed949c7e68f2
[ "JSON", "MIT", "Apache-2.0" ]
permissive
csimmons0/aws-sdk-cpp
578a4ae6e7899944f8850dc37accba5568b919eb
1d0e1ddb51022a02700a9d1d3658abf628bb41c8
refs/heads/develop
2020-06-17T14:58:41.406919
2017-04-12T03:45:33
2017-04-12T03:45:33
74,995,798
0
0
null
2017-03-02T05:35:49
2016-11-28T17:12:34
C++
UTF-8
C++
false
false
25,054
h
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/apigateway/APIGateway_EXPORTS.h> #include <aws/apigateway/APIGatewayRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSMap.h> namespace Aws { namespace APIGateway { namespace Model { /** * <p>Request to add a method to an existing <a>Resource</a> * resource.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/apigateway-2015-07-09/PutMethodRequest">AWS * API Reference</a></p> */ class AWS_APIGATEWAY_API PutMethodRequest : public APIGatewayRequest { public: PutMethodRequest(); Aws::String SerializePayload() const override; /** * <p>The <a>RestApi</a> identifier for the new <a>Method</a> resource.</p> */ inline const Aws::String& GetRestApiId() const{ return m_restApiId; } /** * <p>The <a>RestApi</a> identifier for the new <a>Method</a> resource.</p> */ inline void SetRestApiId(const Aws::String& value) { m_restApiIdHasBeenSet = true; m_restApiId = value; } /** * <p>The <a>RestApi</a> identifier for the new <a>Method</a> resource.</p> */ inline void SetRestApiId(Aws::String&& value) { m_restApiIdHasBeenSet = true; m_restApiId = value; } /** * <p>The <a>RestApi</a> identifier for the new <a>Method</a> resource.</p> */ inline void SetRestApiId(const char* value) { m_restApiIdHasBeenSet = true; m_restApiId.assign(value); } /** * <p>The <a>RestApi</a> identifier for the new <a>Method</a> resource.</p> */ inline PutMethodRequest& WithRestApiId(const Aws::String& value) { SetRestApiId(value); return *this;} /** * <p>The <a>RestApi</a> identifier for the new <a>Method</a> resource.</p> */ inline PutMethodRequest& WithRestApiId(Aws::String&& value) { SetRestApiId(value); return *this;} /** * <p>The <a>RestApi</a> identifier for the new <a>Method</a> resource.</p> */ inline PutMethodRequest& WithRestApiId(const char* value) { SetRestApiId(value); return *this;} /** * <p>The <a>Resource</a> identifier for the new <a>Method</a> resource.</p> */ inline const Aws::String& GetResourceId() const{ return m_resourceId; } /** * <p>The <a>Resource</a> identifier for the new <a>Method</a> resource.</p> */ inline void SetResourceId(const Aws::String& value) { m_resourceIdHasBeenSet = true; m_resourceId = value; } /** * <p>The <a>Resource</a> identifier for the new <a>Method</a> resource.</p> */ inline void SetResourceId(Aws::String&& value) { m_resourceIdHasBeenSet = true; m_resourceId = value; } /** * <p>The <a>Resource</a> identifier for the new <a>Method</a> resource.</p> */ inline void SetResourceId(const char* value) { m_resourceIdHasBeenSet = true; m_resourceId.assign(value); } /** * <p>The <a>Resource</a> identifier for the new <a>Method</a> resource.</p> */ inline PutMethodRequest& WithResourceId(const Aws::String& value) { SetResourceId(value); return *this;} /** * <p>The <a>Resource</a> identifier for the new <a>Method</a> resource.</p> */ inline PutMethodRequest& WithResourceId(Aws::String&& value) { SetResourceId(value); return *this;} /** * <p>The <a>Resource</a> identifier for the new <a>Method</a> resource.</p> */ inline PutMethodRequest& WithResourceId(const char* value) { SetResourceId(value); return *this;} /** * <p>Specifies the method request's HTTP method type.</p> */ inline const Aws::String& GetHttpMethod() const{ return m_httpMethod; } /** * <p>Specifies the method request's HTTP method type.</p> */ inline void SetHttpMethod(const Aws::String& value) { m_httpMethodHasBeenSet = true; m_httpMethod = value; } /** * <p>Specifies the method request's HTTP method type.</p> */ inline void SetHttpMethod(Aws::String&& value) { m_httpMethodHasBeenSet = true; m_httpMethod = value; } /** * <p>Specifies the method request's HTTP method type.</p> */ inline void SetHttpMethod(const char* value) { m_httpMethodHasBeenSet = true; m_httpMethod.assign(value); } /** * <p>Specifies the method request's HTTP method type.</p> */ inline PutMethodRequest& WithHttpMethod(const Aws::String& value) { SetHttpMethod(value); return *this;} /** * <p>Specifies the method request's HTTP method type.</p> */ inline PutMethodRequest& WithHttpMethod(Aws::String&& value) { SetHttpMethod(value); return *this;} /** * <p>Specifies the method request's HTTP method type.</p> */ inline PutMethodRequest& WithHttpMethod(const char* value) { SetHttpMethod(value); return *this;} /** * <p>Specifies the type of authorization used for the method.</p> */ inline const Aws::String& GetAuthorizationType() const{ return m_authorizationType; } /** * <p>Specifies the type of authorization used for the method.</p> */ inline void SetAuthorizationType(const Aws::String& value) { m_authorizationTypeHasBeenSet = true; m_authorizationType = value; } /** * <p>Specifies the type of authorization used for the method.</p> */ inline void SetAuthorizationType(Aws::String&& value) { m_authorizationTypeHasBeenSet = true; m_authorizationType = value; } /** * <p>Specifies the type of authorization used for the method.</p> */ inline void SetAuthorizationType(const char* value) { m_authorizationTypeHasBeenSet = true; m_authorizationType.assign(value); } /** * <p>Specifies the type of authorization used for the method.</p> */ inline PutMethodRequest& WithAuthorizationType(const Aws::String& value) { SetAuthorizationType(value); return *this;} /** * <p>Specifies the type of authorization used for the method.</p> */ inline PutMethodRequest& WithAuthorizationType(Aws::String&& value) { SetAuthorizationType(value); return *this;} /** * <p>Specifies the type of authorization used for the method.</p> */ inline PutMethodRequest& WithAuthorizationType(const char* value) { SetAuthorizationType(value); return *this;} /** * <p>Specifies the identifier of an <a>Authorizer</a> to use on this Method, if * the type is CUSTOM.</p> */ inline const Aws::String& GetAuthorizerId() const{ return m_authorizerId; } /** * <p>Specifies the identifier of an <a>Authorizer</a> to use on this Method, if * the type is CUSTOM.</p> */ inline void SetAuthorizerId(const Aws::String& value) { m_authorizerIdHasBeenSet = true; m_authorizerId = value; } /** * <p>Specifies the identifier of an <a>Authorizer</a> to use on this Method, if * the type is CUSTOM.</p> */ inline void SetAuthorizerId(Aws::String&& value) { m_authorizerIdHasBeenSet = true; m_authorizerId = value; } /** * <p>Specifies the identifier of an <a>Authorizer</a> to use on this Method, if * the type is CUSTOM.</p> */ inline void SetAuthorizerId(const char* value) { m_authorizerIdHasBeenSet = true; m_authorizerId.assign(value); } /** * <p>Specifies the identifier of an <a>Authorizer</a> to use on this Method, if * the type is CUSTOM.</p> */ inline PutMethodRequest& WithAuthorizerId(const Aws::String& value) { SetAuthorizerId(value); return *this;} /** * <p>Specifies the identifier of an <a>Authorizer</a> to use on this Method, if * the type is CUSTOM.</p> */ inline PutMethodRequest& WithAuthorizerId(Aws::String&& value) { SetAuthorizerId(value); return *this;} /** * <p>Specifies the identifier of an <a>Authorizer</a> to use on this Method, if * the type is CUSTOM.</p> */ inline PutMethodRequest& WithAuthorizerId(const char* value) { SetAuthorizerId(value); return *this;} /** * <p>Specifies whether the method required a valid <a>ApiKey</a>.</p> */ inline bool GetApiKeyRequired() const{ return m_apiKeyRequired; } /** * <p>Specifies whether the method required a valid <a>ApiKey</a>.</p> */ inline void SetApiKeyRequired(bool value) { m_apiKeyRequiredHasBeenSet = true; m_apiKeyRequired = value; } /** * <p>Specifies whether the method required a valid <a>ApiKey</a>.</p> */ inline PutMethodRequest& WithApiKeyRequired(bool value) { SetApiKeyRequired(value); return *this;} /** * <p>A human-friendly operation identifier for the method. For example, you can * assign the <code>operationName</code> of <code>ListPets</code> for the <code>GET * /pets</code> method in <a * href="http://petstore-demo-endpoint.execute-api.com/petstore/pets">PetStore</a> * example.</p> */ inline const Aws::String& GetOperationName() const{ return m_operationName; } /** * <p>A human-friendly operation identifier for the method. For example, you can * assign the <code>operationName</code> of <code>ListPets</code> for the <code>GET * /pets</code> method in <a * href="http://petstore-demo-endpoint.execute-api.com/petstore/pets">PetStore</a> * example.</p> */ inline void SetOperationName(const Aws::String& value) { m_operationNameHasBeenSet = true; m_operationName = value; } /** * <p>A human-friendly operation identifier for the method. For example, you can * assign the <code>operationName</code> of <code>ListPets</code> for the <code>GET * /pets</code> method in <a * href="http://petstore-demo-endpoint.execute-api.com/petstore/pets">PetStore</a> * example.</p> */ inline void SetOperationName(Aws::String&& value) { m_operationNameHasBeenSet = true; m_operationName = value; } /** * <p>A human-friendly operation identifier for the method. For example, you can * assign the <code>operationName</code> of <code>ListPets</code> for the <code>GET * /pets</code> method in <a * href="http://petstore-demo-endpoint.execute-api.com/petstore/pets">PetStore</a> * example.</p> */ inline void SetOperationName(const char* value) { m_operationNameHasBeenSet = true; m_operationName.assign(value); } /** * <p>A human-friendly operation identifier for the method. For example, you can * assign the <code>operationName</code> of <code>ListPets</code> for the <code>GET * /pets</code> method in <a * href="http://petstore-demo-endpoint.execute-api.com/petstore/pets">PetStore</a> * example.</p> */ inline PutMethodRequest& WithOperationName(const Aws::String& value) { SetOperationName(value); return *this;} /** * <p>A human-friendly operation identifier for the method. For example, you can * assign the <code>operationName</code> of <code>ListPets</code> for the <code>GET * /pets</code> method in <a * href="http://petstore-demo-endpoint.execute-api.com/petstore/pets">PetStore</a> * example.</p> */ inline PutMethodRequest& WithOperationName(Aws::String&& value) { SetOperationName(value); return *this;} /** * <p>A human-friendly operation identifier for the method. For example, you can * assign the <code>operationName</code> of <code>ListPets</code> for the <code>GET * /pets</code> method in <a * href="http://petstore-demo-endpoint.execute-api.com/petstore/pets">PetStore</a> * example.</p> */ inline PutMethodRequest& WithOperationName(const char* value) { SetOperationName(value); return *this;} /** * <p>A key-value map defining required or optional method request parameters that * can be accepted by Amazon API Gateway. A key defines a method request parameter * name matching the pattern of <code>method.request.{location}.{name}</code>, * where <code>location</code> is <code>querystring</code>, <code>path</code>, or * <code>header</code> and <code>name</code> is a valid and unique parameter name. * The value associated with the key is a Boolean flag indicating whether the * parameter is required (<code>true</code>) or optional (<code>false</code>). The * method request parameter names defined here are available in <a>Integration</a> * to be mapped to integration request parameters or body-mapping templates.</p> */ inline const Aws::Map<Aws::String, bool>& GetRequestParameters() const{ return m_requestParameters; } /** * <p>A key-value map defining required or optional method request parameters that * can be accepted by Amazon API Gateway. A key defines a method request parameter * name matching the pattern of <code>method.request.{location}.{name}</code>, * where <code>location</code> is <code>querystring</code>, <code>path</code>, or * <code>header</code> and <code>name</code> is a valid and unique parameter name. * The value associated with the key is a Boolean flag indicating whether the * parameter is required (<code>true</code>) or optional (<code>false</code>). The * method request parameter names defined here are available in <a>Integration</a> * to be mapped to integration request parameters or body-mapping templates.</p> */ inline void SetRequestParameters(const Aws::Map<Aws::String, bool>& value) { m_requestParametersHasBeenSet = true; m_requestParameters = value; } /** * <p>A key-value map defining required or optional method request parameters that * can be accepted by Amazon API Gateway. A key defines a method request parameter * name matching the pattern of <code>method.request.{location}.{name}</code>, * where <code>location</code> is <code>querystring</code>, <code>path</code>, or * <code>header</code> and <code>name</code> is a valid and unique parameter name. * The value associated with the key is a Boolean flag indicating whether the * parameter is required (<code>true</code>) or optional (<code>false</code>). The * method request parameter names defined here are available in <a>Integration</a> * to be mapped to integration request parameters or body-mapping templates.</p> */ inline void SetRequestParameters(Aws::Map<Aws::String, bool>&& value) { m_requestParametersHasBeenSet = true; m_requestParameters = value; } /** * <p>A key-value map defining required or optional method request parameters that * can be accepted by Amazon API Gateway. A key defines a method request parameter * name matching the pattern of <code>method.request.{location}.{name}</code>, * where <code>location</code> is <code>querystring</code>, <code>path</code>, or * <code>header</code> and <code>name</code> is a valid and unique parameter name. * The value associated with the key is a Boolean flag indicating whether the * parameter is required (<code>true</code>) or optional (<code>false</code>). The * method request parameter names defined here are available in <a>Integration</a> * to be mapped to integration request parameters or body-mapping templates.</p> */ inline PutMethodRequest& WithRequestParameters(const Aws::Map<Aws::String, bool>& value) { SetRequestParameters(value); return *this;} /** * <p>A key-value map defining required or optional method request parameters that * can be accepted by Amazon API Gateway. A key defines a method request parameter * name matching the pattern of <code>method.request.{location}.{name}</code>, * where <code>location</code> is <code>querystring</code>, <code>path</code>, or * <code>header</code> and <code>name</code> is a valid and unique parameter name. * The value associated with the key is a Boolean flag indicating whether the * parameter is required (<code>true</code>) or optional (<code>false</code>). The * method request parameter names defined here are available in <a>Integration</a> * to be mapped to integration request parameters or body-mapping templates.</p> */ inline PutMethodRequest& WithRequestParameters(Aws::Map<Aws::String, bool>&& value) { SetRequestParameters(value); return *this;} /** * <p>A key-value map defining required or optional method request parameters that * can be accepted by Amazon API Gateway. A key defines a method request parameter * name matching the pattern of <code>method.request.{location}.{name}</code>, * where <code>location</code> is <code>querystring</code>, <code>path</code>, or * <code>header</code> and <code>name</code> is a valid and unique parameter name. * The value associated with the key is a Boolean flag indicating whether the * parameter is required (<code>true</code>) or optional (<code>false</code>). The * method request parameter names defined here are available in <a>Integration</a> * to be mapped to integration request parameters or body-mapping templates.</p> */ inline PutMethodRequest& AddRequestParameters(const Aws::String& key, bool value) { m_requestParametersHasBeenSet = true; m_requestParameters[key] = value; return *this; } /** * <p>A key-value map defining required or optional method request parameters that * can be accepted by Amazon API Gateway. A key defines a method request parameter * name matching the pattern of <code>method.request.{location}.{name}</code>, * where <code>location</code> is <code>querystring</code>, <code>path</code>, or * <code>header</code> and <code>name</code> is a valid and unique parameter name. * The value associated with the key is a Boolean flag indicating whether the * parameter is required (<code>true</code>) or optional (<code>false</code>). The * method request parameter names defined here are available in <a>Integration</a> * to be mapped to integration request parameters or body-mapping templates.</p> */ inline PutMethodRequest& AddRequestParameters(Aws::String&& key, bool value) { m_requestParametersHasBeenSet = true; m_requestParameters[key] = value; return *this; } /** * <p>A key-value map defining required or optional method request parameters that * can be accepted by Amazon API Gateway. A key defines a method request parameter * name matching the pattern of <code>method.request.{location}.{name}</code>, * where <code>location</code> is <code>querystring</code>, <code>path</code>, or * <code>header</code> and <code>name</code> is a valid and unique parameter name. * The value associated with the key is a Boolean flag indicating whether the * parameter is required (<code>true</code>) or optional (<code>false</code>). The * method request parameter names defined here are available in <a>Integration</a> * to be mapped to integration request parameters or body-mapping templates.</p> */ inline PutMethodRequest& AddRequestParameters(const char* key, bool value) { m_requestParametersHasBeenSet = true; m_requestParameters[key] = value; return *this; } /** * <p>Specifies the <a>Model</a> resources used for the request's content type. * Request models are represented as a key/value map, with a content type as the * key and a <a>Model</a> name as the value.</p> */ inline const Aws::Map<Aws::String, Aws::String>& GetRequestModels() const{ return m_requestModels; } /** * <p>Specifies the <a>Model</a> resources used for the request's content type. * Request models are represented as a key/value map, with a content type as the * key and a <a>Model</a> name as the value.</p> */ inline void SetRequestModels(const Aws::Map<Aws::String, Aws::String>& value) { m_requestModelsHasBeenSet = true; m_requestModels = value; } /** * <p>Specifies the <a>Model</a> resources used for the request's content type. * Request models are represented as a key/value map, with a content type as the * key and a <a>Model</a> name as the value.</p> */ inline void SetRequestModels(Aws::Map<Aws::String, Aws::String>&& value) { m_requestModelsHasBeenSet = true; m_requestModels = value; } /** * <p>Specifies the <a>Model</a> resources used for the request's content type. * Request models are represented as a key/value map, with a content type as the * key and a <a>Model</a> name as the value.</p> */ inline PutMethodRequest& WithRequestModels(const Aws::Map<Aws::String, Aws::String>& value) { SetRequestModels(value); return *this;} /** * <p>Specifies the <a>Model</a> resources used for the request's content type. * Request models are represented as a key/value map, with a content type as the * key and a <a>Model</a> name as the value.</p> */ inline PutMethodRequest& WithRequestModels(Aws::Map<Aws::String, Aws::String>&& value) { SetRequestModels(value); return *this;} /** * <p>Specifies the <a>Model</a> resources used for the request's content type. * Request models are represented as a key/value map, with a content type as the * key and a <a>Model</a> name as the value.</p> */ inline PutMethodRequest& AddRequestModels(const Aws::String& key, const Aws::String& value) { m_requestModelsHasBeenSet = true; m_requestModels[key] = value; return *this; } /** * <p>Specifies the <a>Model</a> resources used for the request's content type. * Request models are represented as a key/value map, with a content type as the * key and a <a>Model</a> name as the value.</p> */ inline PutMethodRequest& AddRequestModels(Aws::String&& key, const Aws::String& value) { m_requestModelsHasBeenSet = true; m_requestModels[key] = value; return *this; } /** * <p>Specifies the <a>Model</a> resources used for the request's content type. * Request models are represented as a key/value map, with a content type as the * key and a <a>Model</a> name as the value.</p> */ inline PutMethodRequest& AddRequestModels(const Aws::String& key, Aws::String&& value) { m_requestModelsHasBeenSet = true; m_requestModels[key] = value; return *this; } /** * <p>Specifies the <a>Model</a> resources used for the request's content type. * Request models are represented as a key/value map, with a content type as the * key and a <a>Model</a> name as the value.</p> */ inline PutMethodRequest& AddRequestModels(Aws::String&& key, Aws::String&& value) { m_requestModelsHasBeenSet = true; m_requestModels[key] = value; return *this; } /** * <p>Specifies the <a>Model</a> resources used for the request's content type. * Request models are represented as a key/value map, with a content type as the * key and a <a>Model</a> name as the value.</p> */ inline PutMethodRequest& AddRequestModels(const char* key, Aws::String&& value) { m_requestModelsHasBeenSet = true; m_requestModels[key] = value; return *this; } /** * <p>Specifies the <a>Model</a> resources used for the request's content type. * Request models are represented as a key/value map, with a content type as the * key and a <a>Model</a> name as the value.</p> */ inline PutMethodRequest& AddRequestModels(Aws::String&& key, const char* value) { m_requestModelsHasBeenSet = true; m_requestModels[key] = value; return *this; } /** * <p>Specifies the <a>Model</a> resources used for the request's content type. * Request models are represented as a key/value map, with a content type as the * key and a <a>Model</a> name as the value.</p> */ inline PutMethodRequest& AddRequestModels(const char* key, const char* value) { m_requestModelsHasBeenSet = true; m_requestModels[key] = value; return *this; } private: Aws::String m_restApiId; bool m_restApiIdHasBeenSet; Aws::String m_resourceId; bool m_resourceIdHasBeenSet; Aws::String m_httpMethod; bool m_httpMethodHasBeenSet; Aws::String m_authorizationType; bool m_authorizationTypeHasBeenSet; Aws::String m_authorizerId; bool m_authorizerIdHasBeenSet; bool m_apiKeyRequired; bool m_apiKeyRequiredHasBeenSet; Aws::String m_operationName; bool m_operationNameHasBeenSet; Aws::Map<Aws::String, bool> m_requestParameters; bool m_requestParametersHasBeenSet; Aws::Map<Aws::String, Aws::String> m_requestModels; bool m_requestModelsHasBeenSet; }; } // namespace Model } // namespace APIGateway } // namespace Aws
[ "henso@amazon.com" ]
henso@amazon.com
9db88d488c6ffd2b10d44ee4753ddf7f6822594e
81bb77804b2481a92c0d48ad2f76e5b79d29e9ec
/src/base58.h
458f045ad5289379066b5ccc631231dae4dcac16
[ "MIT" ]
permissive
AndrewJEON/qtum
a5216a67c25e818b11266366f37d0b7bcf5a573f
5373115c4550a9dbd99f360dd50cc4f67722dc91
refs/heads/master
2021-06-11T16:50:00.126511
2017-03-14T17:12:40
2017-03-14T17:12:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,741
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. /** * Why base-58 instead of standard base-64 encoding? * - Don't want 0OIl characters that look the same in some fonts and * could be used to create visually identical looking data. * - A string with non-alphanumeric characters is not as easily accepted as input. * - E-mail usually won't line-break if there's no punctuation to break at. * - Double-clicking selects the whole string as one word if it's all alphanumeric. */ #ifndef QUANTUM_BASE58_H #define QUANTUM_BASE58_H #include "chainparams.h" #include "key.h" #include "pubkey.h" #include "script/script.h" #include "script/standard.h" #include "support/allocators/zeroafterfree.h" #include <string> #include <vector> /** * Encode a byte sequence as a base58-encoded string. * pbegin and pend cannot be NULL, unless both are. */ std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend); /** * Encode a byte vector as a base58-encoded string */ std::string EncodeBase58(const std::vector<unsigned char>& vch); /** * Decode a base58-encoded string (psz) into a byte vector (vchRet). * return true if decoding is successful. * psz cannot be NULL. */ bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet); /** * Decode a base58-encoded string (str) into a byte vector (vchRet). * return true if decoding is successful. */ bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet); /** * Encode a byte vector into a base58-encoded string, including checksum */ std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn); /** * Decode a base58-encoded string (psz) that includes a checksum into a byte * vector (vchRet), return true if decoding is successful */ inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet); /** * Decode a base58-encoded string (str) that includes a checksum into a byte * vector (vchRet), return true if decoding is successful */ inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet); /** * Base class for all base58-encoded data */ class CBase58Data { protected: //! the version byte(s) std::vector<unsigned char> vchVersion; //! the actually encoded data typedef std::vector<unsigned char, zero_after_free_allocator<unsigned char> > vector_uchar; vector_uchar vchData; CBase58Data(); void SetData(const std::vector<unsigned char> &vchVersionIn, const void* pdata, size_t nSize); void SetData(const std::vector<unsigned char> &vchVersionIn, const unsigned char *pbegin, const unsigned char *pend); public: bool SetString(const char* psz, unsigned int nVersionBytes = 1); bool SetString(const std::string& str); std::string ToString() const; int CompareTo(const CBase58Data& b58) const; bool operator==(const CBase58Data& b58) const { return CompareTo(b58) == 0; } bool operator<=(const CBase58Data& b58) const { return CompareTo(b58) <= 0; } bool operator>=(const CBase58Data& b58) const { return CompareTo(b58) >= 0; } bool operator< (const CBase58Data& b58) const { return CompareTo(b58) < 0; } bool operator> (const CBase58Data& b58) const { return CompareTo(b58) > 0; } }; /** base58-encoded Quantum addresses. * Public-key-hash-addresses have version 0 (or 111 testnet). * The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key. * Script-hash-addresses have version 5 (or 196 testnet). * The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script. */ class CQuantumAddress : public CBase58Data { public: bool Set(const CKeyID &id); bool Set(const CScriptID &id); bool Set(const CTxDestination &dest); bool IsValid() const; bool IsValid(const CChainParams &params) const; CQuantumAddress() {} CQuantumAddress(const CTxDestination &dest) { Set(dest); } CQuantumAddress(const std::string& strAddress) { SetString(strAddress); } CQuantumAddress(const char* pszAddress) { SetString(pszAddress); } CTxDestination Get() const; bool GetKeyID(CKeyID &keyID) const; bool IsScript() const; }; /** * A base58-encoded secret key */ class CQuantumSecret : public CBase58Data { public: void SetKey(const CKey& vchSecret); CKey GetKey(); bool IsValid() const; bool SetString(const char* pszSecret); bool SetString(const std::string& strSecret); CQuantumSecret(const CKey& vchSecret) { SetKey(vchSecret); } CQuantumSecret() {} }; template<typename K, int Size, CChainParams::Base58Type Type> class CQuantumExtKeyBase : public CBase58Data { public: void SetKey(const K &key) { unsigned char vch[Size]; key.Encode(vch); SetData(Params().Base58Prefix(Type), vch, vch+Size); } K GetKey() { K ret; if (vchData.size() == Size) { //if base58 encouded data not holds a ext key, return a !IsValid() key ret.Decode(&vchData[0]); } return ret; } CQuantumExtKeyBase(const K &key) { SetKey(key); } CQuantumExtKeyBase(const std::string& strBase58c) { SetString(strBase58c.c_str(), Params().Base58Prefix(Type).size()); } CQuantumExtKeyBase() {} }; typedef CQuantumExtKeyBase<CExtKey, BIP32_EXTKEY_SIZE, CChainParams::EXT_SECRET_KEY> CQuantumExtKey; typedef CQuantumExtKeyBase<CExtPubKey, BIP32_EXTKEY_SIZE, CChainParams::EXT_PUBLIC_KEY> CQuantumExtPubKey; #endif // QUANTUM_BASE58_H
[ "development@solarius.fi" ]
development@solarius.fi
a98e9f476dd86e348da9401f20f3a06c021ea80e
8e4a2a7152e4b25641d72e930de8842732bcf53a
/OpenSeesCpp/eigen3/linearFunctionai.cpp
48b55e4dcfecc4b8ffb1ebbb720b2ff0b2316df4
[]
no_license
Mengsen-W/OpenSeesFiles
9b9e8865a2b802047e419c5155aff5c20ac05937
cda268d37cd17280dc18ada8c7f1b30af0b2bd6b
refs/heads/master
2021-12-23T23:21:28.369076
2021-12-22T13:14:53
2021-12-22T13:14:53
239,237,550
3
0
null
null
null
null
UTF-8
C++
false
false
2,450
cpp
/* * @Author: Mengsen.Wang * @Date: 2020-07-17 09:49:15 * @Last Modified by: Mengsen.Wang * @Last Modified time: 2020-07-17 10:47:16 */ #include <ctime> #include <eigen3/Eigen/Core> #include <eigen3/Eigen/Dense> #include <iostream> #define MATRIX_SIZE 1000 int main() { Eigen::MatrixXd A; Eigen::MatrixXd B; Eigen::MatrixXd X; A = Eigen::MatrixXd::Random(MATRIX_SIZE, MATRIX_SIZE); B = Eigen::MatrixXd::Random(MATRIX_SIZE, 1); X = Eigen::MatrixXd::Random(MATRIX_SIZE, MATRIX_SIZE); clock_t time_stt = clock(); std::cout << "----- QR decomposition colPivHouseholder -----" << std::endl; X = A.colPivHouseholderQr().solve(B); std::cout << "time use in QR colPivHouseholderQr decomposition is " << (1000) * (clock() - time_stt) / static_cast<double>(CLOCKS_PER_SEC) << "ms" << std::endl; time_stt = clock(); std::cout << "----- QR decomposition fullPivHouseholder -----" << std::endl; X = A.fullPivHouseholderQr().solve(B); std::cout << "time use in QR fullPivHouseholder decomposition is " << (1000) * (clock() - time_stt) / static_cast<double>(CLOCKS_PER_SEC) << "ms" << std::endl; time_stt = clock(); std::cout << "----- llt decomposition -----" << std::endl; X = A.llt().solve(B); std::cout << "time use in llt decomposition is " << (1000) * (clock() - time_stt) / static_cast<double>(CLOCKS_PER_SEC) << "ms" << std::endl; time_stt = clock(); std::cout << "----- ldlt decomposition -----" << std::endl; X = A.ldlt().solve(B); std::cout << "time use in ldlt decomposition is " << (1000) * (clock() - time_stt) / static_cast<double>(CLOCKS_PER_SEC) << "ms" << std::endl; time_stt = clock(); std::cout << "----- partialPivLu decomposition -----" << std::endl; X = A.partialPivLu().solve(B); std::cout << "time use in partialPivLu decomposition is " << (1000) * (clock() - time_stt) / static_cast<double>(CLOCKS_PER_SEC) << "ms" << std::endl; time_stt = clock(); std::cout << "----- fullPivLu decomposition -----" << std::endl; X = A.fullPivLu().solve(B); std::cout << "time use in fullPivLu decomposition is " << (1000) * (clock() - time_stt) / static_cast<double>(CLOCKS_PER_SEC) << "ms" << std::endl; return 0; }
[ "mengsen_wang@163.com" ]
mengsen_wang@163.com
0ebecc26962b4a030a103e91a8befd0cfbb7a7ea
95273e09057dea3ee4d8b2c7405c62c511d76e6c
/src/ESPectroBase_GpioEx.cpp
cf2412036d67e8a1d928b4cc1a1afd5715308196
[]
no_license
alwint3r/EspX
a3af26c86f7bdace1adfe8f3ab5b50a8344bcc05
eed8cb93a18a11a6b72be85326e2fef900427dd7
refs/heads/master
2020-05-29T08:40:33.140368
2017-01-07T19:04:28
2017-01-07T19:04:28
69,655,952
0
0
null
2016-09-30T10:02:22
2016-09-30T10:02:22
null
UTF-8
C++
false
false
979
cpp
// // Created by Andri Yadi on 8/1/16. // #include "ESPectroBase_GpioEx.h" ESPectroBase_GpioEx::ESPectroBase_GpioEx(uint8_t address): SX1508(address), i2cDeviceAddress_(address) { } ESPectroBase_GpioEx::~ESPectroBase_GpioEx() { } byte ESPectroBase_GpioEx::begin(byte address, byte resetPin) { byte addr = (address != ESPECTRO_BASE_GPIOEX_ADDRESS)? address: i2cDeviceAddress_; byte res = SX1508::begin(addr, resetPin); if (res) { SX1508::pinMode(ESPECTRO_BASE_GPIOEX_LED_PIN, OUTPUT); clock(INTERNAL_CLOCK_2MHZ, 4); } return res; } void ESPectroBase_GpioEx::turnOnLED() { SX1508::digitalWrite(ESPECTRO_BASE_GPIOEX_LED_PIN, LOW); } void ESPectroBase_GpioEx::turnOffLED() { SX1508::digitalWrite(ESPECTRO_BASE_GPIOEX_LED_PIN, HIGH); } void ESPectroBase_GpioEx::blinkLED(unsigned long tOn, unsigned long tOff, byte onIntensity, byte offIntensity) { blink(ESPECTRO_BASE_GPIOEX_LED_PIN, tOn, tOff, onIntensity, offIntensity); }
[ "an.dri@me.com" ]
an.dri@me.com
1b1db33275ca9020ab39e1df49702ad2e1dfa7d8
e1c8e3767bac2d7d2bb83e56aa46bfad6286f734
/games/anarchy/fireDepartment.h
6856c29f0c39dee9a08ac9c174999225c4c62dfb
[ "MIT" ]
permissive
joeykuhn/Joueur.cpp
df2709357aae71be84100bf8c39f859ffe965a86
9b3f9d9a37f79aad958f179cb89c4f08706387b8
refs/heads/master
2021-01-24T09:19:20.206407
2016-09-27T23:04:41
2016-09-27T23:04:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,872
h
// Generated by Creer at 01:31AM on December 23, 2015 UTC, git hash: '1b69e788060071d644dd7b8745dca107577844e1' // Can put out fires completely. #ifndef JOUEUR_ANARCHY_FIREDEPARTMENT_H #define JOUEUR_ANARCHY_FIREDEPARTMENT_H #include "anarchy.h" #include "building.h" // <<-- Creer-Merge: includes -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add addtional #includes(s) here. // <<-- /Creer-Merge: includes -->> /// <summary> /// Can put out fires completely. /// </summary> class Anarchy::FireDepartment : public Anarchy::Building { friend Anarchy::GameManager; protected: virtual void deltaUpdateField(const std::string& fieldName, boost::property_tree::ptree& delta); FireDepartment() {}; ~FireDepartment() {}; public: /// <summary> /// The amount of fire removed from a building when bribed to extinguish a building. /// </summary> int fireExtinguished; // <<-- Creer-Merge: fields -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add addtional fields(s) here. None of them will be tracked or updated by the server. // <<-- /Creer-Merge: fields -->> /// <summary> /// Bribes this FireDepartment to extinguish the some of the fire in a building. /// </summary> /// <param name="building">The Building you want to extinguish.</param> /// <returns>true if the bribe worked, false otherwise</returns> bool extinguish(Anarchy::Building* building); // <<-- Creer-Merge: methods -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add addtional method(s) here. // <<-- /Creer-Merge: methods -->> }; #endif
[ "jacob.t.fischer@gmail.com" ]
jacob.t.fischer@gmail.com
d5b10fd840e59b756c211cab4d2eb6bb258e3e76
ef15a4a77b6e1fbb3220a5047885ba7568a80b74
/src/core/Core/SignalToStop.hpp
b66f5a6ec1be9ca38fff701986ce19cd9dde6921
[]
no_license
el-bart/ACARM-ng
22ad5a40dc90a2239206f18dacbd4329ff8377de
de277af4b1c54e52ad96cbe4e1f574bae01b507d
refs/heads/master
2020-12-27T09:24:14.591095
2014-01-28T19:24:34
2014-01-28T19:24:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
843
hpp
/* * SignalToStop.hpp * */ #ifndef INCLUDE_CORE_SIGNALTOSTOP_HPP_FILE #define INCLUDE_CORE_SIGNALTOSTOP_HPP_FILE /* public header */ #include "System/SignalRegistrator.hpp" #include "Logger/Node.hpp" #include "Core/WorkThreads.hpp" namespace Core { /** \brief handles given signal's registration and unregistration. * * when given signal is received system is triggered to stop. */ class SignalToStop: public System::SignalRegistrator { public: /** \brief registers handle for signal. * \param signum signal number to be handled. * \param wt main system threads. if NULL, signal is ignored. */ SignalToStop(int signum, WorkThreads *wt); /** \brief unregisters signal handle. */ ~SignalToStop(void); private: int signum_; Logger::Node log_; }; // class SignalToStop } // namespace Core #endif
[ "bartosz.szurgot@pwr.wroc.pl" ]
bartosz.szurgot@pwr.wroc.pl
abb4494d31f83c59e62840a3cbee255fc3dd0ca4
3011f9e4204f2988c983b8815187f56a6bf58ebd
/src/ys_library/ysglcpp/src/nownd/ysglbuffermanager_nownd.h
af34a97c2e372bd4ad528a98ad9a18d6f039d852
[]
no_license
hvantil/AR-BoardGames
9e80a0f2bb24f8bc06902785d104178a214d0d63
71b9620df66d80c583191b8c8e8b925a6df5ddc3
refs/heads/master
2020-03-17T01:36:47.674272
2018-05-13T18:11:16
2018-05-13T18:11:16
133,160,216
0
0
null
null
null
null
UTF-8
C++
false
false
1,763
h
/* //////////////////////////////////////////////////////////// File Name: ysglbuffermanager_nownd.h Copyright (c) 2017 Soji Yamakawa. All rights reserved. http://www.ysflight.com Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////// */ #ifndef YSGLBUFFERMANAGER_GL2_IS_INCLUDED #define YSGLBUFFERMANAGER_GL2_IS_INCLUDED /* { */ #include <ysclass.h> #include <ysglbuffermanager.h> class YsGLBufferManager::ActualBuffer { public: }; /* } */ #endif
[ "harrison.vantil@outlook.com" ]
harrison.vantil@outlook.com
69721892a768fac6808ee60dfd9672acacbdc19b
b33a9177edaaf6bf185ef20bf87d36eada719d4f
/qtdeclarative/src/qml/jsruntime/qv4profiling_p.h
6c54fc9bbdf19a1654d96b536ae8d0244adb9e27
[ "Qt-LGPL-exception-1.1", "LGPL-2.1-only", "LGPL-2.0-or-later", "LGPL-3.0-only", "GPL-3.0-only", "LGPL-2.1-or-later", "GPL-1.0-or-later", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only", "GFDL-1.3-only", "LicenseRef-scancode-digia-qt-preview", "LicenseRef-scancode-warranty-discl...
permissive
wgnet/wds_qt
ab8c093b8c6eead9adf4057d843e00f04915d987
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
refs/heads/master
2021-04-02T11:07:10.181067
2020-06-02T10:29:03
2020-06-02T10:34:19
248,267,925
1
0
Apache-2.0
2020-04-30T12:16:53
2020-03-18T15:20:38
null
UTF-8
C++
false
false
6,825
h
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the QtQml module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QV4PROFILING_H #define QV4PROFILING_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include "qv4global_p.h" #include "qv4engine_p.h" #include "qv4function_p.h" #include <QElapsedTimer> QT_BEGIN_NAMESPACE namespace QV4 { namespace Profiling { enum Features { FeatureFunctionCall, FeatureMemoryAllocation }; enum MemoryType { HeapPage, LargeItem, SmallItem }; struct FunctionCallProperties { qint64 start; qint64 end; QString name; QString file; int line; int column; }; struct MemoryAllocationProperties { qint64 timestamp; qint64 size; MemoryType type; }; class FunctionCall { public: FunctionCall() : m_function(0), m_start(0), m_end(0) { Q_ASSERT_X(false, Q_FUNC_INFO, "Cannot construct a function call without function"); } FunctionCall(Function *function, qint64 start, qint64 end) : m_function(function), m_start(start), m_end(end) { m_function->compilationUnit->addref(); } FunctionCall(const FunctionCall &other) : m_function(other.m_function), m_start(other.m_start), m_end(other.m_end) { m_function->compilationUnit->addref(); } ~FunctionCall() { m_function->compilationUnit->release(); } FunctionCall &operator=(const FunctionCall &other) { if (&other != this) { if (m_function) m_function->compilationUnit->release(); m_function = other.m_function; m_start = other.m_start; m_end = other.m_end; m_function->compilationUnit->addref(); } return *this; } FunctionCallProperties resolve() const; private: friend bool operator<(const FunctionCall &call1, const FunctionCall &call2); Function *m_function; qint64 m_start; qint64 m_end; }; #define Q_V4_PROFILE_ALLOC(engine, size, type)\ (engine->profiler &&\ (engine->profiler->featuresEnabled & (1 << Profiling::FeatureMemoryAllocation)) ?\ engine->profiler->trackAlloc(size, type) : size) #define Q_V4_PROFILE_DEALLOC(engine, pointer, size, type) \ (engine->profiler &&\ (engine->profiler->featuresEnabled & (1 << Profiling::FeatureMemoryAllocation)) ?\ engine->profiler->trackDealloc(pointer, size, type) : pointer) #define Q_V4_PROFILE(engine, function)\ (engine->profiler &&\ (engine->profiler->featuresEnabled & (1 << Profiling::FeatureFunctionCall)) ?\ Profiling::FunctionCallProfiler::profileCall(engine->profiler, engine, function) :\ function->code(engine, function->codeData)) class Q_QML_EXPORT Profiler : public QObject { Q_OBJECT Q_DISABLE_COPY(Profiler) public: Profiler(QV4::ExecutionEngine *engine); size_t trackAlloc(size_t size, MemoryType type) { MemoryAllocationProperties allocation = {m_timer.nsecsElapsed(), (qint64)size, type}; m_memory_data.append(allocation); return size; } void *trackDealloc(void *pointer, size_t size, MemoryType type) { MemoryAllocationProperties allocation = {m_timer.nsecsElapsed(), -(qint64)size, type}; m_memory_data.append(allocation); return pointer; } quint64 featuresEnabled; public slots: void stopProfiling(); void startProfiling(quint64 features); void reportData(); void setTimer(const QElapsedTimer &timer) { m_timer = timer; } signals: void dataReady(const QVector<QV4::Profiling::FunctionCallProperties> &, const QVector<QV4::Profiling::MemoryAllocationProperties> &); private: QV4::ExecutionEngine *m_engine; QElapsedTimer m_timer; QVector<FunctionCall> m_data; QVector<MemoryAllocationProperties> m_memory_data; friend class FunctionCallProfiler; }; class FunctionCallProfiler { Q_DISABLE_COPY(FunctionCallProfiler) public: // It's enough to ref() the function in the destructor as it will probably not disappear while // it's executing ... FunctionCallProfiler(Profiler *profiler, Function *function) : profiler(profiler), function(function), startTime(profiler->m_timer.nsecsElapsed()) {} ~FunctionCallProfiler() { profiler->m_data.append(FunctionCall(function, startTime, profiler->m_timer.nsecsElapsed())); } static ReturnedValue profileCall(Profiler *profiler, ExecutionEngine *engine, Function *function) { FunctionCallProfiler callProfiler(profiler, function); return function->code(engine, function->codeData); } Profiler *profiler; Function *function; qint64 startTime; }; } // namespace Profiling } // namespace QV4 Q_DECLARE_TYPEINFO(QV4::Profiling::MemoryAllocationProperties, Q_MOVABLE_TYPE); Q_DECLARE_TYPEINFO(QV4::Profiling::FunctionCallProperties, Q_MOVABLE_TYPE); Q_DECLARE_TYPEINFO(QV4::Profiling::FunctionCall, Q_MOVABLE_TYPE); QT_END_NAMESPACE Q_DECLARE_METATYPE(QVector<QV4::Profiling::FunctionCallProperties>) Q_DECLARE_METATYPE(QVector<QV4::Profiling::MemoryAllocationProperties>) #endif // QV4PROFILING_H
[ "p_pavlov@wargaming.net" ]
p_pavlov@wargaming.net
922f4765eedff3059156dd94eda2a1b6056103b8
da33d7b0d05c8e3d3989dcbae0020594169350a8
/public/klein/detail/inner_product.hpp
d80170c7fe73bb921b9656ebf6fd45513b92d49d
[ "MIT" ]
permissive
shrijitsingh99/klein
a2a03bffd07dda1ef53ba793ac4c5f69bc7096d7
9aa59b9e95e8ab607cdc415782cac6ae1b1a86fa
refs/heads/master
2021-02-09T11:06:19.602097
2020-03-02T03:07:01
2020-03-02T03:07:01
244,275,143
2
0
MIT
2020-03-02T03:51:54
2020-03-02T03:51:53
null
UTF-8
C++
false
false
50
hpp
#pragma once #include "x86/x86_inner_product.hpp"
[ "jeremycong@gmail.com" ]
jeremycong@gmail.com
04f3bf59a6968978a904c83f0712ca5e0ffa488f
be8718f6882f2b4b124b245d10d1d05c2e09a901
/Engine/Source/Shared/Import/Mdl/MdlNode.cpp
124f9d419de8f8cb5e8219e2d627270585d87776
[]
no_license
kolhammer/Psybrus
fd907a8e25b488327846d46853ca219c55cca81b
21c794568eed41aaacb633cd87dedd5ce2793115
refs/heads/master
2016-09-05T08:58:04.427316
2012-03-19T11:33:32
2012-03-19T11:33:32
3,031,999
1
1
null
null
null
null
UTF-8
C++
false
false
6,811
cpp
/************************************************************************** * * File: MdlNode.cpp * Author: Neil Richardson * Ver/Date: * Description: * Model node. * * * * **************************************************************************/ #include "MdlNode.h" #include "MdlMesh.h" #include "MdlMorph.h" #include "MdlEntity.h" #include "Base/BcDebug.h" #include "Base/BcString.h" ////////////////////////////////////////////////////////////////////////// // Ctor MdlNode::MdlNode(): NodeType_( eNT_EMPTY ), pParent_( NULL ), pChild_( NULL ), pNext_( NULL ) { RelativeTransform_.identity(); AbsoluteTransform_.identity(); pNodeMeshObject_ = NULL; pNodeSkinObject_ = NULL; pNodeColMeshObject_ = NULL; pNodeMorphObject_ = NULL; pNodeEntityObject_ = NULL; pNodeLightObject_ = NULL; pNodeProjectorObject_ = NULL; } ////////////////////////////////////////////////////////////////////////// // Dtor MdlNode::~MdlNode() { delete pNodeMeshObject_; delete pNodeSkinObject_; delete pNodeColMeshObject_; delete pNodeMorphObject_; delete pNodeEntityObject_; delete pNodeLightObject_; delete pNodeProjectorObject_; ///* NOTE: Memory corruption somewhere. MdlNode* pNext = pChild_; while( pNext != NULL ) { MdlNode* pTheNext = pNext->pNext_; delete pNext; pNext = pTheNext; } } ////////////////////////////////////////////////////////////////////////// // name void MdlNode::name( const BcChar* Name ) { BcStrCopy( Name_, Name ); } const BcChar* MdlNode::name() { return Name_; } ////////////////////////////////////////////////////////////////////////// // parentNode BcBool MdlNode::parentNode( MdlNode* pNode, const BcChar* ParentName ) { BcBool bParented = BcFalse; // Parent another node to this tree. if( ParentName == NULL || BcStrCompare( ParentName, Name_ ) ) { // Tell the node who its parent is. pNode->pParent_ = this; // If we have a child already we need our next to match. if( pChild_ != NULL ) { MdlNode* pParentNode = pChild_; // Find the last node while( pParentNode->pNext_ != NULL ) { BcAssert( pParentNode != pParentNode->pNext_ ); pParentNode = pParentNode->pNext_; } // pParentNode->pNext_ = pNode; bParented = BcTrue; } else { pChild_ = pNode; bParented = BcTrue; } } else { // If we are not the destined parent pass it to next and child. // Find the last node MdlNode* pNextNode = pChild_; while( pNextNode != NULL ) { bParented |= pNextNode->parentNode( pNode, ParentName ); pNextNode = pNextNode->pNext_; } } return bParented; } ////////////////////////////////////////////////////////////////////////// // makeRelativeTransform void MdlNode::makeRelativeTransform( const BcMat4d& ParentAbsolute ) { // Parent another node to this tree. MdlNode* pNextNode = pChild_; // BcMat4d InverseParent = ParentAbsolute; InverseParent.inverse(); RelativeTransform_ = AbsoluteTransform_ * InverseParent; // For all the nodes parented to the same as us. while( pNextNode != NULL ) { pNextNode->makeRelativeTransform( AbsoluteTransform_ ); pNextNode = pNextNode->pNext_; } } ////////////////////////////////////////////////////////////////////////// // makeAbsoluteTransform void MdlNode::makeAbsoluteTransform( const BcMat4d& ParentAbsolute ) { // Parent another node to this tree. MdlNode* pNextNode = pChild_; // BcMat4d InverseParent = ParentAbsolute; InverseParent.inverse(); AbsoluteTransform_ = ParentAbsolute * RelativeTransform_; // For all the nodes parented to the same as us. while( pNextNode != NULL ) { pNextNode->makeAbsoluteTransform( AbsoluteTransform_ ); pNextNode = pNextNode->pNext_; } } ////////////////////////////////////////////////////////////////////////// // flipTransform void MdlNode::flipTransform( BcMat4d& Transform ) { Transform.transpose(); Transform[0][2] = -Transform[0][2]; Transform[1][2] = -Transform[1][2]; Transform[2][0] = -Transform[2][0]; Transform[2][1] = -Transform[2][1]; Transform[2][3] = -Transform[2][3]; Transform.transpose(); } ////////////////////////////////////////////////////////////////////////// // flipTransforms void MdlNode::flipCoordinateSpace() { // Parent another node to this tree. MdlNode* pNextNode = pChild_; // Flip absolute and inverse bind pose transforms. flipTransform( AbsoluteTransform_ ); flipTransform( InverseBindpose_ ); // If we've got a mesh, flip it's coordinate space. if( type() & eNT_MESH ) { pNodeMeshObject_->flipCoordinateSpace(); } if( type() & eNT_SKIN ) { pNodeSkinObject_->flipCoordinateSpace(); } if( type() & eNT_MORPH ) { pNodeMorphObject_->flipCoordinateSpace(); } // For all the nodes parented to the same as us. while( pNextNode != NULL ) { pNextNode->flipCoordinateSpace(); pNextNode = pNextNode->pNext_; } } ////////////////////////////////////////////////////////////////////////// // type void MdlNode::type( BcU32 NodeType ) { if( NodeType != eNT_COLMESH && NodeType != eNT_ENTITY ) { BcAssert( ( NodeType_ & ~NodeType ) == 0 ); } if( ( NodeType_ & NodeType ) == 0 ) { NodeType_ |= NodeType; switch( NodeType ) { case eNT_EMPTY: break; case eNT_MESH: pNodeMeshObject_ = new MdlMesh(); break; case eNT_SKIN: pNodeSkinObject_ = new MdlMesh(); break; case eNT_COLMESH: // Naughty. //pNodeColMeshObject_ = new MdlMesh(); BcAssert( pNodeMeshObject_ != NULL ); break; case eNT_MORPH: pNodeMorphObject_ = new MdlMesh(); break; case eNT_ENTITY: pNodeEntityObject_ = new MdlEntity(); break; case eNT_LIGHT: pNodeLightObject_ = new MdlLight(); break; case eNT_PROJECTOR: pNodeProjectorObject_ = new MdlProjector(); break; } } } ////////////////////////////////////////////////////////////////////////// // countJoints void MdlNode::countJoints( BcU32& iCount ) { if( type() & eNT_JOINT ) { iCount++; } MdlNode* pNextNode = pChild_; while( pNextNode != NULL ) { if( pNextNode->type() & eNT_JOINT ) { pNextNode->countJoints( iCount ); } pNextNode = pNextNode->pNext_; } } ////////////////////////////////////////////////////////////////////////// // void MdlNode::findAllAABBs() { MdlNode* pNextNode = pChild_; // If our AABB is empty, calculate our bounds based on child nodes. if( AABB_.isEmpty() ) { while( pNextNode != NULL ) { // Find our childs.. pNextNode->findAllAABBs(); // Add its AABB to ours. if( pNextNode->AABB_.isEmpty() == BcFalse ) { AABB_.expandBy( pNextNode->AABB_ ); } // pNextNode = pNextNode->pNext_; } // Transform our AABB if( AABB_.isEmpty() == BcFalse ) { AABB_ = AABB_.transform( AbsoluteTransform_ ); } } else { // Transform ours. AABB_ = AABB_.transform( AbsoluteTransform_ ); } }
[ "richyneil@gmail.com" ]
richyneil@gmail.com
7ffec586c8dd2e09f767a0afadaac569716c3b06
8ac181aa59bbc34aa457ed90273b56763269859d
/Codeforces/668-DIV2/B.cpp
9e90460de64ad73d97dd3b9bc8d34ae89d8b3dbc
[]
no_license
mohitmp9107/Competitive-Programming-
d8a85d37ad6eccb1c70e065f592f46961bdb21cf
d42ef49bfcd80ebfc87a75b544cf9d7d5afcc968
refs/heads/master
2021-07-11T11:09:14.808893
2020-10-03T08:15:36
2020-10-03T08:15:36
206,331,473
0
4
null
2020-10-03T08:15:38
2019-09-04T13:54:46
C++
UTF-8
C++
false
false
1,304
cpp
#include<bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; template < typename T > using oset = tree < T, null_type, less < T >, rb_tree_tag, tree_order_statistics_node_update >; // find_by_order(k) (k+1)th largest element // order_of_key(k) no of elements <=k typedef long long ll; typedef long double ld; #define endl '\n' #define rep(i,n) for(ll i = 0; i < (n); ++i) #define repA(i, a, n) for(ll i = a; i <= (n); ++i) #define repD(i, a, n) for(ll i = a; i >= (n); --i) #define trav(a, x) for(auto& a : x) #define all(x) x.begin(), x.end() #define sz(x) (ll)(x).size() #define ff first #define ss second #define pb push_back typedef vector<ll> vll; typedef vector<pair<ll,ll>> vpl; const ld PI = 4*atan((ld)1); const ll INF = LLONG_MAX; const ll mod = 1e9+7; int main() { //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); ll tt=1; cin >> tt; repA(qq,1,tt){ ll n; cin >> n; vll a(n); ll ans = INF; rep(i,n){ cin >> a[i]; if(i)a[i]+=a[i-1]; } rep(i,n){ ans = min(ans,a[i]); } cout<< -ans << endl; } }
[ "mohitsaininith@gmail.com" ]
mohitsaininith@gmail.com
e063d1a76d7610f8d626233ecb551423c89f987c
3dbe2d0454979091d3f1f23c3bda6f8371efe8be
/arm_compute/runtime/CL/ICLGEMMKernelSelection.h
69b941109d33bf329ad9fe1ab326458b98ddd52e
[ "MIT", "LicenseRef-scancode-dco-1.1" ]
permissive
alexjung/ComputeLibrary
399339e097a34cf28f64ac23b3ccb371e121a4c9
a9d47c17791ebce45427ea6331bd6e35f7d721f4
refs/heads/master
2022-11-25T22:34:48.281986
2020-07-30T14:38:20
2020-07-30T14:38:20
283,794,492
0
0
MIT
2020-07-30T14:16:27
2020-07-30T14:16:26
null
UTF-8
C++
false
false
2,579
h
/* * Copyright (c) 2020 ARM Limited. * * SPDX-License-Identifier: MIT * * 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. */ #ifndef ARM_COMPUTE_ICLGEMMKERNELSELECTION_H #define ARM_COMPUTE_ICLGEMMKERNELSELECTION_H #include "arm_compute/core/GPUTarget.h" #include "arm_compute/core/Types.h" #include "arm_compute/runtime/CL/CLTypes.h" namespace arm_compute { namespace cl_gemm { /** Basic interface for the GEMM kernel selection */ class ICLGEMMKernelSelection { public: /** Constructor * * @param[in] arch GPU target */ ICLGEMMKernelSelection(GPUTarget arch) : _target(arch) { } /** Default Move Constructor. */ ICLGEMMKernelSelection(ICLGEMMKernelSelection &&) = default; /** Default move assignment operator */ ICLGEMMKernelSelection &operator=(ICLGEMMKernelSelection &&) = default; /** Virtual destructor */ virtual ~ICLGEMMKernelSelection() = default; /** Given the input parameters passed through @ref CLGEMMKernelSelectionParams, this method returns the @ref CLGEMMKernelType to use * * @param[in] params Input parameters used by the function to return the OpenCL GEMM's kernel * * @return @ref CLGEMMKernelType */ virtual CLGEMMKernelType select_kernel(const CLGEMMKernelSelectionParams &params) = 0; protected: GPUTarget _target; /**< GPU target could be used to call a dedicated heuristic for each GPU IP for a given GPU architecture */ }; } // namespace cl_gemm } // namespace arm_compute #endif /*ARM_COMPUTE_ICLGEMMKERNELSELECTION_H */
[ "bsgcomp@arm.com" ]
bsgcomp@arm.com
60e5fb32350ab045ec71c799a0a5c28e815d2ca9
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE122_Heap_Based_Buffer_Overflow/s04/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_82_goodG2B.cpp
c33c8d71ef39b59ac89102c07f1b01680ea08a75
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
1,351
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_82_goodG2B.cpp Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806.label.xml Template File: sources-sink-82_goodG2B.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Initialize data as a large string * GoodSource: Initialize data as a small string * Sinks: loop * BadSink : Copy data to string using a loop * Flow Variant: 82 Data flow: data passed in a parameter to a virtual method called via a pointer * * */ #ifndef OMITGOOD #include "std_testcase.h" #include "CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_82.h" namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_82 { void CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_82_goodG2B::action(wchar_t * data) { { wchar_t dest[50] = L""; size_t i, dataLen; dataLen = wcslen(data); /* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */ for (i = 0; i < dataLen; i++) { dest[i] = data[i]; } dest[50-1] = L'\0'; /* Ensure the destination buffer is null terminated */ printWLine(data); delete [] data; } } } #endif /* OMITGOOD */
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
7bf10cbc45c54e262361a446e727dc5525b9e4b3
67434c238f16fb4d7fa6226a570809671f73c22f
/opti_triangulator/opti_triangulator/actionlibClient/triangulator_/beaconSettings.h
f2fcfdb2e40851ea08358e2ba6cce11f8a12e012
[]
no_license
codenotes/opti-triangulator
1f664c37c5a4c88ff4684853db5fb04e9d3326d3
3c26f3a2c575d86eb33dbc2b642f696df496825a
refs/heads/master
2021-01-10T13:09:23.631208
2015-09-16T00:50:24
2015-09-16T00:50:24
36,323,759
0
1
null
null
null
null
UTF-8
C++
false
false
5,684
h
// Generated by gencpp from file triangulator/beaconSettings.msg // DO NOT EDIT! #ifndef TRIANGULATOR_MESSAGE_BEACONSETTINGS_H #define TRIANGULATOR_MESSAGE_BEACONSETTINGS_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <triangulator/beaconSetting.h> namespace triangulator { template <class ContainerAllocator> struct beaconSettings_ { typedef beaconSettings_<ContainerAllocator> Type; beaconSettings_() : beaconValues() { } beaconSettings_(const ContainerAllocator& _alloc) : beaconValues(_alloc) { } typedef std::vector< ::triangulator::beaconSetting_<ContainerAllocator> , typename ContainerAllocator::template rebind< ::triangulator::beaconSetting_<ContainerAllocator> >::other > _beaconValues_type; _beaconValues_type beaconValues; typedef boost::shared_ptr< ::triangulator::beaconSettings_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::triangulator::beaconSettings_<ContainerAllocator> const> ConstPtr; }; // struct beaconSettings_ typedef ::triangulator::beaconSettings_<std::allocator<void> > beaconSettings; typedef boost::shared_ptr< ::triangulator::beaconSettings > beaconSettingsPtr; typedef boost::shared_ptr< ::triangulator::beaconSettings const> beaconSettingsConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::triangulator::beaconSettings_<ContainerAllocator> & v) { ros::message_operations::Printer< ::triangulator::beaconSettings_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace triangulator namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False} // {'triangulator': ['/home/gbrill/catkin_ws/src/triangulator_service/msg'], 'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::triangulator::beaconSettings_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::triangulator::beaconSettings_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::triangulator::beaconSettings_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::triangulator::beaconSettings_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::triangulator::beaconSettings_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::triangulator::beaconSettings_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::triangulator::beaconSettings_<ContainerAllocator> > { static const char* value() { return "0356089f67b16e38dbcecf75c6dce3ef"; } static const char* value(const ::triangulator::beaconSettings_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x0356089f67b16e38ULL; static const uint64_t static_value2 = 0xdbcecf75c6dce3efULL; }; template<class ContainerAllocator> struct DataType< ::triangulator::beaconSettings_<ContainerAllocator> > { static const char* value() { return "triangulator/beaconSettings"; } static const char* value(const ::triangulator::beaconSettings_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::triangulator::beaconSettings_<ContainerAllocator> > { static const char* value() { return "beaconSetting[] beaconValues\n\ \n\ ================================================================================\n\ MSG: triangulator/beaconSetting\n\ float32 beaconID\n\ string beaconName\n\ float32 X\n\ float32 Y\n\ float32 Z\n\ "; } static const char* value(const ::triangulator::beaconSettings_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::triangulator::beaconSettings_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.beaconValues); } ROS_DECLARE_ALLINONE_SERIALIZER; }; // struct beaconSettings_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::triangulator::beaconSettings_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::triangulator::beaconSettings_<ContainerAllocator>& v) { s << indent << "beaconValues[]" << std::endl; for (size_t i = 0; i < v.beaconValues.size(); ++i) { s << indent << " beaconValues[" << i << "]: "; s << std::endl; s << indent; Printer< ::triangulator::beaconSetting_<ContainerAllocator> >::stream(s, indent + " ", v.beaconValues[i]); } } }; } // namespace message_operations } // namespace ros #endif // TRIANGULATOR_MESSAGE_BEACONSETTINGS_H
[ "gbrill@infusion.com" ]
gbrill@infusion.com
7a8ee6e89234f511f0c9621e346ef8e385c5868b
9d4ad6d7f3122f8d32a4a713f06b81ecb7a47c6e
/headers/boost/1.31.0/boost/python/slice_nil.hpp
b77d06cb2248fb3ab7dd61b1ea1fd671d6904430
[]
no_license
metashell/headers
226d6d55eb659134a2ae2aa022b56b893bff1b30
ceb6da74d7ca582791f33906992a5908fcaca617
refs/heads/master
2021-01-20T23:26:51.811362
2018-08-25T07:06:19
2018-08-25T07:06:19
13,360,747
0
1
null
null
null
null
UTF-8
C++
false
false
913
hpp
// Copyright David Abrahams 2002. Permission to copy, use, // modify, sell and distribute this software is granted provided this // copyright notice appears in all copies. This software is provided // "as is" without express or implied warranty, and with no claim as // to its suitability for any purpose. #ifndef SLICE_NIL_DWA2002620_HPP # define SLICE_NIL_DWA2002620_HPP # include <boost/python/detail/prefix.hpp> namespace boost { namespace python { namespace api { class object; enum slice_nil { # ifndef _ // Watch out for GNU gettext users, who #define _(x) _ # endif }; template <class T> struct slice_bound { typedef object type; }; template <> struct slice_bound<slice_nil> { typedef slice_nil type; }; } using api::slice_nil; # ifndef _ // Watch out for GNU gettext users, who #define _(x) using api::_; # endif }} // namespace boost::python #endif // SLICE_NIL_DWA2002620_HPP
[ "abelsoft@freemail.hu" ]
abelsoft@freemail.hu
f3a552035a004939c6885a8e407864ccda29c7f1
beb63531847b5277a0bded705b585744f2c7c179
/camps/havana-2018-artsem-zhuk/04-game-theory/c.cpp
61e746406a3a04bdfdb0618705bdee5d7d6f7130
[]
no_license
mfornet/acm-icpc-solutions
0272bf56e92b2363760e6c0f69f8cc43f3d33d56
6147a6170aa839a86b77ece6a1dade3723f9baa4
refs/heads/master
2021-09-13T23:41:23.892634
2018-05-06T00:06:03
2018-05-06T00:06:03
114,927,791
7
1
null
null
null
null
UTF-8
C++
false
false
3,530
cpp
#include <bits/stdc++.h> const int MAX = 1e5 + 10; typedef long long i64; using namespace std; const int oo = 1e6; const double EPS = 1e-7; const int mod = 1e9 + 7; typedef vector<int> vi; void add(int &a, int b){ a += b; if (a >= mod) a -= mod; } void add_vec(vi &a, vi b){ for (int i = 0; i < (int)a.size(); ++i) add(a[i], b[i]); } const int TSTATE = 8 * 8 * 8 * 8 * 8 * 8; const int BASE = 7; int position[1 << 6][7][7][7][7][7][7]; int final_grundy[TSTATE]; int go[TSTATE][2]; int _grundy(int mask, vector<int> &B, vector<int> &valid){ int seen = 0; for (auto x : valid){ if (mask >> (x - 1) & 1) seen |= 1 << B[x - 1]; } int g = 0; while (seen >> g & 1) g++; return g; } vector<vi> solve(int size, vector<int> &valid){ int cindex = 0; for (int i = 0; i < (1 << 6); ++i){ int bits = __builtin_popcount(i); int total = 1; for (int j = 0; j < bits; ++j) total *= BASE; for (int j = 0; j < total; ++j){ int u = j; vector<int> b7(6); for (int b = 0; b < 6; ++b){ if (i >> b & 1){ b7[b] = u % BASE; u /= BASE; } } position[i][b7[0]][b7[1]][b7[2]][b7[3]][b7[4]][b7[5]] = cindex; final_grundy[cindex] = i & 1 ? b7[0] : -1; cindex++; } } for (int i = 0; i < (1 << 6); ++i){ int bits = __builtin_popcount(i); int total = 1; for (int j = 0; j < bits; ++j) total *= BASE; for (int j = 0; j < total; ++j){ int u = j; vector<int> b7(6); for (int b = 0; b < 6; ++b){ if (i >> b & 1){ b7[b] = u % BASE; u /= BASE; } } int pos = position[i][b7[0]][b7[1]][b7[2]][b7[3]][b7[4]][b7[5]]; go[pos][0] = position[(i << 1) & 63][0][b7[0]][b7[1]][b7[2]][b7[3]][b7[4]]; int gr = _grundy(i, b7, valid); go[pos][1] = position[((i << 1) & 63) | 1][gr][b7[0]][b7[1]][b7[2]][b7[3]][b7[4]]; } } vector<vi> W(size + 1, vi(8)); vector<int> prev(cindex); prev[0] = 1; for (int i = 1; i <= size; ++i) { vector<int> cur(cindex); for (int j = 0; j < cindex; ++j){ add(cur[go[j][0]], prev[j]); add(cur[go[j][1]], prev[j]); assert(final_grundy[ go[j][1] ] != -1); } for (int j = 0; j < cindex; ++j) if (final_grundy[j] != -1) add(W[i][final_grundy[j]], cur[j]); cur.swap(prev); } // for (auto row : W){ // for (auto x : row) // cout << x << " "; // cout << endl; // } return W; } vi multiply(vi a, vi b){ vi c(8); for (int i = 0; i < 8; ++i) for (int j = 0; j < 8; ++j) add(c[i ^ j], 1LL * a[i] * b[j] % mod); return c; } vi modpow(vi a, i64 n){ vi ans(8); ans[0] = 1; while (n){ if (n & 1) ans = multiply(ans, a); a = multiply(a, a); n >>= 1; } return ans; } int main() { ios::sync_with_stdio(false); cin.tie(0); #ifdef LOCAL_DEBUG freopen("data.in", "r", stdin); #endif #define endl '\n' int MX = 0; int n; cin >> n; vector<pair<i64,int>> games(n); for (int i = 0; i < n; ++i){ cin >> games[i].first >> games[i].second; MX = max(MX, games[i].second); } int t; cin >> t; vector<int> moves; for (int i = 0; i < t; ++i){ int v; cin >> v; moves.push_back(v); } auto vec = solve(MX, moves); vi sol(8); sol[0] = 1; for (int i = 0; i < n; ++i){ vi cur = vec[ games[i].second ]; cur = modpow(cur, games[i].first); sol = multiply(sol, cur); } int answer = 0; for (int i = 1; i < 8; ++i) add(answer, sol[i]); cout << answer << endl; }
[ "mfornet94@gmail.com" ]
mfornet94@gmail.com
be342d25f24c065b687f2354984709c3205a3034
03c9dcedb5c93f6930fbe274d188199df574e87c
/node_location/code/MultiviewGeometryUtility.cpp
bfe4419fde1892cae668b58fc56a44cb6e5a9d18
[]
no_license
marvinCMU/marvin
6b5f6af693746657650a66b78f899fadbb937071
6f6e378f78447d6b8de2e8b97b82e1bc7f3f5cfc
refs/heads/master
2016-09-06T04:51:17.572255
2014-06-17T03:43:45
2014-06-17T03:43:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
345,280
cpp
#include "MultiviewGeometryUtility.h" #include <assert.h> using namespace std; //void BilinearCameraPoseEstimation(vector<Feature> vFeature, int initialFrame1, int initialFrame2, double ransacThreshold, int ransacMaxIter, CvMat *K, CvMat &P, CvMat &X, vector<int> &visibleStructureID) //{ // PrintAlgorithm("Bilinear Camera Pose Estimation"); // CvMat cx1, cx2, nx1, nx2; // vector<int> visibleFeatureID; // X = *cvCreateMat(vFeature.size(), 3, CV_32FC1); // VisibleIntersection(vFeature, initialFrame1, initialFrame2, cx1, cx2, visibleFeatureID); // assert(visibleFeatureID.size() > 7); // CvMat *F = cvCreateMat(3,3,CV_32FC1); // // Classifier classifier; // vector<int> visibleID; // classifier.SetRansacParam(ransacThreshold, ransacMaxIter); // classifier.SetCorrespondance(&cx1, &cx2, visibleFeatureID); // classifier.Classify(); // vector<int> vInlierID, vOutlierID; // classifier.GetClassificationResultByFeatureID(vInlierID, vOutlierID); // visibleFeatureID = vInlierID; // F = cvCloneMat(classifier.F); // cx1 = *cvCreateMat(classifier.inlier1->rows, classifier.inlier1->cols, CV_32FC1); // cx2 = *cvCreateMat(classifier.inlier2->rows, classifier.inlier2->cols, CV_32FC1); // cx1 = *cvCloneMat(classifier.inlier1); // cx2 = *cvCloneMat(classifier.inlier2); // // //vector<int> vInlierID; // //CvMat *status = cvCreateMat(1,cx1.rows,CV_8UC1); // //int n = cvFindFundamentalMat(&cx1, &cx2, F, CV_FM_LMEDS , 1, 0.99, status); // //for (int i = 0; i < cx1.rows; i++) // //{ // // if (cvGetReal2D(status, 0, i) == 1) // // { // // vInlierID.push_back(visibleFeatureID[i]); // // } // //} // //visibleFeatureID = vInlierID; // //CvMat *tempCx1 = cvCreateMat(vInlierID.size(), 2, CV_32FC1); // //CvMat *tempCx2 = cvCreateMat(vInlierID.size(), 2, CV_32FC1); // //int temprow = 0; // //for (int i = 0; i < cx1.rows; i++) // //{ // // if (cvGetReal2D(status, 0, i) == 1) // // { // // cvSetReal2D(tempCx1, temprow, 0, cvGetReal2D(&cx1, i, 0)); // // cvSetReal2D(tempCx1, temprow, 1, cvGetReal2D(&cx1, i, 1)); // // cvSetReal2D(tempCx2, temprow, 0, cvGetReal2D(&cx2, i, 0)); // // cvSetReal2D(tempCx2, temprow, 1, cvGetReal2D(&cx2, i, 1)); // // temprow++; // // } // //} // //cx1 = *cvCreateMat(tempCx1->rows, tempCx1->cols, CV_32FC1); // //cx2 = *cvCreateMat(tempCx2->rows, tempCx2->cols, CV_32FC1); // //cx1 = *cvCloneMat(tempCx1); // //cx2 = *cvCloneMat(tempCx2); // //cvReleaseMat(&status); // //cvReleaseMat(&tempCx1); // //cvReleaseMat(&tempCx2); // // CvMat *E = cvCreateMat(3, 3, CV_32FC1); // CvMat *temp33 = cvCreateMat(3, 3, CV_32FC1); // CvMat *temp34 = cvCreateMat(3, 4, CV_32FC1); // // cvTranspose(K, temp33); // cvMatMul(temp33, F, temp33); // cvMatMul(temp33, K, E); // // CvMat *invK = cvCreateMat(3,3,CV_32FC1); // cvInvert(K, invK); // Pxx_inhomo(invK, &cx1, nx1); // Pxx_inhomo(invK, &cx2, nx2); // // GetExtrinsicParameterFromE(E, &nx1, &nx2, P); // CvMat *P0 = cvCreateMat(3, 4, CV_32FC1); // cvSetIdentity(P0); // CvMat cX; // // LinearTriangulation(&nx1, P0, &nx2, &P, cX); // cvSetZero(&X); // SetIndexedMatRowwise(&X, visibleFeatureID, &cX); // cvMatMul(K, &P, temp34); // P = *cvCloneMat(temp34); // // visibleStructureID = visibleFeatureID; // // cvReleaseMat(&F); // cvReleaseMat(&E); // cvReleaseMat(&temp33); // cvReleaseMat(&temp34); // cvReleaseMat(&invK); // cvReleaseMat(&P0); //} void BilinearCameraPoseEstimation_OPENCV(vector<Feature> vFeature, int initialFrame1, int initialFrame2, double ransacThreshold, int ransacMaxIter, CvMat *K, CvMat &P, CvMat &X, vector<int> &visibleStructureID) { PrintAlgorithm("Bilinear Camera Pose Estimation"); CvMat cx1, cx2, nx1, nx2; vector<int> visibleFeatureID; X = *cvCreateMat(vFeature.size(), 3, CV_32FC1); VisibleIntersection(vFeature, initialFrame1, initialFrame2, cx1, cx2, visibleFeatureID); assert(visibleFeatureID.size() > 7); CvMat *F = cvCreateMat(3,3,CV_32FC1); //Classifier classifier; //vector<int> visibleID; //classifier.SetRansacParam(ransacThreshold, ransacMaxIter); //classifier.SetCorrespondance(&cx1, &cx2, visibleFeatureID); //classifier.Classify(); //vector<int> vInlierID, vOutlierID; //classifier.GetClassificationResultByFeatureID(vInlierID, vOutlierID); //visibleFeatureID = vInlierID; //F = cvCloneMat(classifier.F); //cx1 = *cvCreateMat(classifier.inlier1->rows, classifier.inlier1->cols, CV_32FC1); //cx2 = *cvCreateMat(classifier.inlier2->rows, classifier.inlier2->cols, CV_32FC1); //cx1 = *cvCloneMat(classifier.inlier1); //cx2 = *cvCloneMat(classifier.inlier2); vector<int> vInlierID; CvMat *status = cvCreateMat(1,cx1.rows,CV_8UC1); int n = cvFindFundamentalMat(&cx1, &cx2, F, CV_FM_RANSAC , 1, 0.99, status); for (int i = 0; i < cx1.rows; i++) { if (cvGetReal2D(status, 0, i) == 1) { vInlierID.push_back(visibleFeatureID[i]); } } visibleFeatureID = vInlierID; CvMat *tempCx1 = cvCreateMat(vInlierID.size(), 2, CV_32FC1); CvMat *tempCx2 = cvCreateMat(vInlierID.size(), 2, CV_32FC1); int temprow = 0; for (int i = 0; i < cx1.rows; i++) { if (cvGetReal2D(status, 0, i) == 1) { cvSetReal2D(tempCx1, temprow, 0, cvGetReal2D(&cx1, i, 0)); cvSetReal2D(tempCx1, temprow, 1, cvGetReal2D(&cx1, i, 1)); cvSetReal2D(tempCx2, temprow, 0, cvGetReal2D(&cx2, i, 0)); cvSetReal2D(tempCx2, temprow, 1, cvGetReal2D(&cx2, i, 1)); temprow++; } } cx1 = *cvCreateMat(tempCx1->rows, tempCx1->cols, CV_32FC1); cx2 = *cvCreateMat(tempCx2->rows, tempCx2->cols, CV_32FC1); cx1 = *cvCloneMat(tempCx1); cx2 = *cvCloneMat(tempCx2); cvReleaseMat(&status); cvReleaseMat(&tempCx1); cvReleaseMat(&tempCx2); CvMat *E = cvCreateMat(3, 3, CV_32FC1); CvMat *temp33 = cvCreateMat(3, 3, CV_32FC1); CvMat *temp34 = cvCreateMat(3, 4, CV_32FC1); cvTranspose(K, temp33); cvMatMul(temp33, F, temp33); cvMatMul(temp33, K, E); CvMat *invK = cvCreateMat(3,3,CV_32FC1); cvInvert(K, invK); Pxx_inhomo(invK, &cx1, nx1); Pxx_inhomo(invK, &cx2, nx2); GetExtrinsicParameterFromE(E, &nx1, &nx2, P); CvMat *P0 = cvCreateMat(3, 4, CV_32FC1); cvSetIdentity(P0); CvMat cX; LinearTriangulation(&nx1, P0, &nx2, &P, cX); cvSetZero(&X); SetIndexedMatRowwise(&X, visibleFeatureID, &cX); cvMatMul(K, &P, temp34); P = *cvCloneMat(temp34); visibleStructureID = visibleFeatureID; cvReleaseMat(&F); cvReleaseMat(&E); cvReleaseMat(&temp33); cvReleaseMat(&temp34); cvReleaseMat(&invK); cvReleaseMat(&P0); } int BilinearCameraPoseEstimation_OPENCV(vector<Feature> vFeature, int initialFrame1, int initialFrame2, int max_nFrames, vector<Camera> vCamera, CvMat &P, CvMat &X, vector<int> &visibleStructureID) { PrintAlgorithm("Bilinear Camera Pose Estimation"); CvMat cx1, cx2, nx1, nx2; vector<int> visibleFeatureID; X = *cvCreateMat(vFeature.size(), 3, CV_32FC1); VisibleIntersection(vFeature, initialFrame1, initialFrame2, cx1, cx2, visibleFeatureID); assert(visibleFeatureID.size() > 7); CvMat *F = cvCreateMat(3,3,CV_32FC1); vector<int> vInlierID; CvMat *status = cvCreateMat(1,cx1.rows,CV_8UC1); int n = cvFindFundamentalMat(&cx1, &cx2, F, CV_FM_LMEDS , 1, 0.99, status); //int n = cvFindFundamentalMat(&cx1, &cx2, F, CV_FM_8POINT , 3, 0.99, status); PrintMat(F, "Fundamental Matrix"); for (int i = 0; i < cx1.rows; i++) { if (cvGetReal2D(status, 0, i) == 1) { vInlierID.push_back(visibleFeatureID[i]); } } visibleFeatureID = vInlierID; CvMat *tempCx1 = cvCreateMat(vInlierID.size(), 2, CV_32FC1); CvMat *tempCx2 = cvCreateMat(vInlierID.size(), 2, CV_32FC1); int temprow = 0; for (int i = 0; i < cx1.rows; i++) { if (cvGetReal2D(status, 0, i) == 1) { cvSetReal2D(tempCx1, temprow, 0, cvGetReal2D(&cx1, i, 0)); cvSetReal2D(tempCx1, temprow, 1, cvGetReal2D(&cx1, i, 1)); cvSetReal2D(tempCx2, temprow, 0, cvGetReal2D(&cx2, i, 0)); cvSetReal2D(tempCx2, temprow, 1, cvGetReal2D(&cx2, i, 1)); temprow++; } } cx1 = *cvCreateMat(tempCx1->rows, tempCx1->cols, CV_32FC1); cx2 = *cvCreateMat(tempCx2->rows, tempCx2->cols, CV_32FC1); cx1 = *cvCloneMat(tempCx1); cx2 = *cvCloneMat(tempCx2); cvReleaseMat(&status); cvReleaseMat(&tempCx1); cvReleaseMat(&tempCx2); CvMat *E = cvCreateMat(3, 3, CV_32FC1); CvMat *temp33 = cvCreateMat(3, 3, CV_32FC1); CvMat *temp34 = cvCreateMat(3, 4, CV_32FC1); CvMat *K1 = cvCreateMat(3,3,CV_32FC1); CvMat *K2 = cvCreateMat(3,3,CV_32FC1); int camera1 = (int)((double)initialFrame1/max_nFrames); int camera2 = (int)((double)initialFrame2/max_nFrames); vector<int> ::const_iterator it1 = find(vCamera[camera1].vTakenFrame.begin(), vCamera[camera1].vTakenFrame.end(), initialFrame1%max_nFrames); vector<int> ::const_iterator it2 = find(vCamera[camera2].vTakenFrame.begin(), vCamera[camera2].vTakenFrame.end(), initialFrame2%max_nFrames); int idx1 = (int) (it1 - vCamera[camera1].vTakenFrame.begin()); int idx2 = (int) (it2 - vCamera[camera2].vTakenFrame.begin()); K1 = cvCloneMat(vCamera[camera1].vK[idx1]); K2 = cvCloneMat(vCamera[camera2].vK[idx2]); cvTranspose(K2, temp33); cvMatMul(temp33, F, temp33); cvMatMul(temp33, K1, E); CvMat *invK1 = cvCreateMat(3,3,CV_32FC1); CvMat *invK2 = cvCreateMat(3,3,CV_32FC1); cvInvert(K1, invK1); cvInvert(K2, invK2); Pxx_inhomo(invK1, &cx1, nx1); Pxx_inhomo(invK2, &cx2, nx2); GetExtrinsicParameterFromE(E, &nx1, &nx2, P); CvMat *P0 = cvCreateMat(3, 4, CV_32FC1); cvSetIdentity(P0); CvMat cX; LinearTriangulation(&nx1, P0, &nx2, &P, cX); cvSetZero(&X); SetIndexedMatRowwise(&X, visibleFeatureID, &cX); cvMatMul(K2, &P, temp34); P = *cvCloneMat(temp34); visibleStructureID = visibleFeatureID; cvReleaseMat(&F); cvReleaseMat(&E); cvReleaseMat(&temp33); cvReleaseMat(&temp34); cvReleaseMat(&K1); cvReleaseMat(&K2); cvReleaseMat(&invK1); cvReleaseMat(&invK2); cvReleaseMat(&P0); return n; } void SetCvMatFromVectors(vector<vector<double> > x, CvMat *X) { for (int i = 0; i < x.size(); i++) { for (int j = 0; j < x[i].size(); j++) cvSetReal2D(X, i, j, x[i][j]); } } int BilinearCameraPoseEstimation_OPENCV_mem(vector<Feature> &vFeature, int initialFrame1, int initialFrame2, int max_nFrames, vector<Camera> vCamera, CvMat *P, CvMat *X, vector<int> &visibleStructureID) { PrintAlgorithm("Bilinear Camera Pose Estimation"); vector<int> visibleFeatureID; vector<vector<double> > cx1_vec, cx2_vec, nx1_vec, nx2_vec; VisibleIntersection_mem(vFeature, initialFrame1, initialFrame2, cx1_vec, cx2_vec, visibleFeatureID); CvMat *cx1 = cvCreateMat(cx1_vec.size(), 2, CV_32FC1); CvMat *cx2 = cvCreateMat(cx2_vec.size(), 2, CV_32FC1); SetCvMatFromVectors(cx1_vec, cx1); SetCvMatFromVectors(cx2_vec, cx2); assert(visibleFeatureID.size() > 7); CvMat *F = cvCreateMat(3,3,CV_32FC1); vector<int> vInlierID; CvMat *status = cvCreateMat(1,cx1->rows,CV_8UC1); int n = cvFindFundamentalMat(cx1, cx2, F, CV_FM_LMEDS , 1, 0.99, status); PrintMat(F, "Fundamental Matrix"); for (int i = 0; i < cx1->rows; i++) { if (cvGetReal2D(status, 0, i) == 1) { vInlierID.push_back(visibleFeatureID[i]); } } visibleFeatureID = vInlierID; CvMat *tempCx1 = cvCreateMat(vInlierID.size(), 2, CV_32FC1); CvMat *tempCx2 = cvCreateMat(vInlierID.size(), 2, CV_32FC1); int temprow = 0; for (int i = 0; i < cx1->rows; i++) { if (cvGetReal2D(status, 0, i) == 1) { cvSetReal2D(tempCx1, temprow, 0, cvGetReal2D(cx1, i, 0)); cvSetReal2D(tempCx1, temprow, 1, cvGetReal2D(cx1, i, 1)); cvSetReal2D(tempCx2, temprow, 0, cvGetReal2D(cx2, i, 0)); cvSetReal2D(tempCx2, temprow, 1, cvGetReal2D(cx2, i, 1)); temprow++; } } cvReleaseMat(&cx1); cvReleaseMat(&cx2); cx1 = cvCloneMat(tempCx1); cx2 = cvCloneMat(tempCx2); cvReleaseMat(&status); cvReleaseMat(&tempCx1); cvReleaseMat(&tempCx2); CvMat *E = cvCreateMat(3, 3, CV_32FC1); CvMat *temp33 = cvCreateMat(3, 3, CV_32FC1); CvMat *temp34 = cvCreateMat(3, 4, CV_32FC1); //CvMat *K1 = cvCreateMat(3,3,CV_32FC1); //CvMat *K2 = cvCreateMat(3,3,CV_32FC1); int camera1 = (int)((double)initialFrame1/max_nFrames); int camera2 = (int)((double)initialFrame2/max_nFrames); vector<int> ::const_iterator it1 = find(vCamera[camera1].vTakenFrame.begin(), vCamera[camera1].vTakenFrame.end(), initialFrame1%max_nFrames); vector<int> ::const_iterator it2 = find(vCamera[camera2].vTakenFrame.begin(), vCamera[camera2].vTakenFrame.end(), initialFrame2%max_nFrames); int idx1 = (int) (it1 - vCamera[camera1].vTakenFrame.begin()); int idx2 = (int) (it2 - vCamera[camera2].vTakenFrame.begin()); CvMat *K1 = cvCloneMat(vCamera[camera1].vK[idx1]); CvMat *K2 = cvCloneMat(vCamera[camera2].vK[idx2]); cvTranspose(K2, temp33); cvMatMul(temp33, F, temp33); cvMatMul(temp33, K1, E); CvMat *invK1 = cvCreateMat(3,3,CV_32FC1); CvMat *invK2 = cvCreateMat(3,3,CV_32FC1); cvInvert(K1, invK1); cvInvert(K2, invK2); CvMat *nx1 = cvCreateMat(cx1->rows, cx1->cols, CV_32FC1); CvMat *nx2 = cvCreateMat(cx2->rows, cx2->cols, CV_32FC1); Pxx_inhomo(invK1, cx1, nx1); Pxx_inhomo(invK2, cx2, nx2); GetExtrinsicParameterFromE(E, nx1, nx2, P); CvMat *P0 = cvCreateMat(3, 4, CV_32FC1); cvSetIdentity(P0); CvMat *cX = cvCreateMat(nx1->rows, 3, CV_32FC1); LinearTriangulation(nx1, P0, nx2, P, cX); cvSetZero(X); SetIndexedMatRowwise(X, visibleFeatureID, cX); cvMatMul(K2, P, temp34); SetSubMat(P, 0, 0, temp34); visibleStructureID = visibleFeatureID; cvReleaseMat(&F); cvReleaseMat(&E); cvReleaseMat(&temp33); cvReleaseMat(&temp34); cvReleaseMat(&K1); cvReleaseMat(&K2); cvReleaseMat(&invK1); cvReleaseMat(&invK2); cvReleaseMat(&P0); cvReleaseMat(&cx1); cvReleaseMat(&cx2); cvReleaseMat(&nx1); cvReleaseMat(&nx2); cvReleaseMat(&cX); return n; } int BilinearCameraPoseEstimation_OPENCV_mem_fast(vector<Feature> &vFeature, int initialFrame1, int initialFrame2, int max_nFrames, vector<Camera> vCamera, CvMat *P, CvMat *X) { PrintAlgorithm("Bilinear Camera Pose Estimation"); vector<int> visibleFeatureID; vector<vector<double> > cx1_vec, cx2_vec, nx1_vec, nx2_vec; VisibleIntersection_mem(vFeature, initialFrame1, initialFrame2, cx1_vec, cx2_vec, visibleFeatureID); CvMat *cx1 = cvCreateMat(cx1_vec.size(), 2, CV_32FC1); CvMat *cx2 = cvCreateMat(cx2_vec.size(), 2, CV_32FC1); SetCvMatFromVectors(cx1_vec, cx1); SetCvMatFromVectors(cx2_vec, cx2); assert(visibleFeatureID.size() > 7); CvMat *F = cvCreateMat(3,3,CV_32FC1); vector<int> vInlierID; CvMat *status = cvCreateMat(1,cx1->rows,CV_8UC1); int n = cvFindFundamentalMat(cx1, cx2, F, CV_FM_LMEDS , 1, 0.99, status); PrintMat(F, "Fundamental Matrix"); //for (int i = 0; i < cx1->rows; i++) //{ // if (cvGetReal2D(status, 0, i) == 1) // { // vInlierID.push_back(visibleFeatureID[i]); // } //} cout << n << endl; vector<int> vCX_indx; for (int i = 0; i < cx1->rows; i++) { CvMat *xM2 = cvCreateMat(1,3,CV_32FC1); CvMat *xM1 = cvCreateMat(3,1,CV_32FC1); CvMat *s = cvCreateMat(1,1, CV_32FC1); cvSetReal2D(xM2, 0, 0, cvGetReal2D(cx2, i, 0)); cvSetReal2D(xM2, 0, 1, cvGetReal2D(cx2, i, 1)); cvSetReal2D(xM2, 0, 2, 1); cvSetReal2D(xM1, 0, 0, cvGetReal2D(cx1, i, 0)); cvSetReal2D(xM1, 1, 0, cvGetReal2D(cx1, i, 1)); cvSetReal2D(xM1, 2, 0, 1); cvMatMul(xM2, F, xM2); cvMatMul(xM2, xM1, s); double l1 = cvGetReal2D(xM2, 0, 0); double l2 = cvGetReal2D(xM2, 0, 1); double l3 = cvGetReal2D(xM2, 0, 2); double dist = abs(cvGetReal2D(s, 0, 0))/sqrt(l1*l1+l2*l2); if (dist < 5) { vInlierID.push_back(visibleFeatureID[i]); vCX_indx.push_back(i); } cvReleaseMat(&xM2); cvReleaseMat(&xM1); cvReleaseMat(&s); //if (cvGetReal2D(status, 0, i) == 1) //{ // cvSetReal2D(tempCx1, temprow, 0, cvGetReal2D(cx1, i, 0)); // cvSetReal2D(tempCx1, temprow, 1, cvGetReal2D(cx1, i, 1)); // cvSetReal2D(tempCx2, temprow, 0, cvGetReal2D(cx2, i, 0)); // cvSetReal2D(tempCx2, temprow, 1, cvGetReal2D(cx2, i, 1)); // temprow++; //} } visibleFeatureID = vInlierID; CvMat *tempCx1 = cvCreateMat(vCX_indx.size(), 2, CV_32FC1); CvMat *tempCx2 = cvCreateMat(vCX_indx.size(), 2, CV_32FC1); for (int iInlier = 0; iInlier < vInlierID.size(); iInlier++) { cvSetReal2D(tempCx1, iInlier, 0, cvGetReal2D(cx1, vCX_indx[iInlier], 0)); cvSetReal2D(tempCx1, iInlier, 1, cvGetReal2D(cx1, vCX_indx[iInlier], 1)); cvSetReal2D(tempCx2, iInlier, 0, cvGetReal2D(cx2, vCX_indx[iInlier], 0)); cvSetReal2D(tempCx2, iInlier, 1, cvGetReal2D(cx2, vCX_indx[iInlier], 1)); } cvReleaseMat(&cx1); cvReleaseMat(&cx2); cx1 = cvCloneMat(tempCx1); cx2 = cvCloneMat(tempCx2); cvReleaseMat(&status); cvReleaseMat(&tempCx1); cvReleaseMat(&tempCx2); CvMat *E = cvCreateMat(3, 3, CV_32FC1); CvMat *temp33 = cvCreateMat(3, 3, CV_32FC1); CvMat *temp34 = cvCreateMat(3, 4, CV_32FC1); //CvMat *K1 = cvCreateMat(3,3,CV_32FC1); //CvMat *K2 = cvCreateMat(3,3,CV_32FC1); int camera1 = (int)((double)initialFrame1/max_nFrames); int camera2 = (int)((double)initialFrame2/max_nFrames); vector<int> ::const_iterator it1 = find(vCamera[camera1].vTakenFrame.begin(), vCamera[camera1].vTakenFrame.end(), initialFrame1%max_nFrames); vector<int> ::const_iterator it2 = find(vCamera[camera2].vTakenFrame.begin(), vCamera[camera2].vTakenFrame.end(), initialFrame2%max_nFrames); int idx1 = (int) (it1 - vCamera[camera1].vTakenFrame.begin()); int idx2 = (int) (it2 - vCamera[camera2].vTakenFrame.begin()); CvMat *K1 = cvCloneMat(vCamera[camera1].vK[idx1]); CvMat *K2 = cvCloneMat(vCamera[camera2].vK[idx2]); cvTranspose(K2, temp33); cvMatMul(temp33, F, temp33); cvMatMul(temp33, K1, E); CvMat *invK1 = cvCreateMat(3,3,CV_32FC1); CvMat *invK2 = cvCreateMat(3,3,CV_32FC1); cvInvert(K1, invK1); cvInvert(K2, invK2); CvMat *nx1 = cvCreateMat(cx1->rows, cx1->cols, CV_32FC1); CvMat *nx2 = cvCreateMat(cx2->rows, cx2->cols, CV_32FC1); Pxx_inhomo(invK1, cx1, nx1); Pxx_inhomo(invK2, cx2, nx2); GetExtrinsicParameterFromE(E, nx1, nx2, P); CvMat *P0 = cvCreateMat(3, 4, CV_32FC1); cvSetIdentity(P0); CvMat *cX = cvCreateMat(nx1->rows, 3, CV_32FC1); PrintMat(P); cvMatMul(K1, P0, P0); cvMatMul(K2, P, P); PrintMat(P); //LinearTriangulation(nx1, P0, nx2, P, cX); LinearTriangulation(cx1, P0, cx2, P, cX); //PrintMat(cX); cvSetZero(X); SetIndexedMatRowwise(X, visibleFeatureID, cX); for (int i = 0; i < visibleFeatureID.size(); i++) { vFeature[visibleFeatureID[i]].isRegistered = true; } cvReleaseMat(&F); cvReleaseMat(&E); cvReleaseMat(&temp33); cvReleaseMat(&temp34); cvReleaseMat(&K1); cvReleaseMat(&K2); cvReleaseMat(&invK1); cvReleaseMat(&invK2); cvReleaseMat(&P0); cvReleaseMat(&cx1); cvReleaseMat(&cx2); cvReleaseMat(&nx1); cvReleaseMat(&nx2); cvReleaseMat(&cX); return vInlierID.size(); } int BilinearCameraPoseEstimation_OPENCV_mem_fast_AD(vector<Feature> &vFeature, int initialFrame1, int initialFrame2, int max_nFrames, vector<Camera> vCamera, CvMat *P, CvMat *X, vector<vector<int> > &vvPointIndex) { PrintAlgorithm("Bilinear Camera Pose Estimation"); vector<int> visibleFeatureID; vector<vector<double> > cx1_vec, cx2_vec, nx1_vec, nx2_vec; VisibleIntersection_mem(vFeature, initialFrame1, initialFrame2, cx1_vec, cx2_vec, visibleFeatureID); CvMat *cx1 = cvCreateMat(cx1_vec.size(), 2, CV_32FC1); CvMat *cx2 = cvCreateMat(cx2_vec.size(), 2, CV_32FC1); SetCvMatFromVectors(cx1_vec, cx1); SetCvMatFromVectors(cx2_vec, cx2); assert(visibleFeatureID.size() > 7); CvMat *F = cvCreateMat(3,3,CV_32FC1); vector<int> vInlierID; CvMat *status = cvCreateMat(1,cx1->rows,CV_8UC1); int n = cvFindFundamentalMat(cx1, cx2, F, CV_FM_LMEDS , 1, 0.99, status); PrintMat(F, "Fundamental Matrix"); //for (int i = 0; i < cx1->rows; i++) //{ // if (cvGetReal2D(status, 0, i) == 1) // { // vInlierID.push_back(visibleFeatureID[i]); // } //} cout << n << endl; vector<int> vCX_indx; for (int i = 0; i < cx1->rows; i++) { CvMat *xM2 = cvCreateMat(1,3,CV_32FC1); CvMat *xM1 = cvCreateMat(3,1,CV_32FC1); CvMat *s = cvCreateMat(1,1, CV_32FC1); cvSetReal2D(xM2, 0, 0, cvGetReal2D(cx2, i, 0)); cvSetReal2D(xM2, 0, 1, cvGetReal2D(cx2, i, 1)); cvSetReal2D(xM2, 0, 2, 1); cvSetReal2D(xM1, 0, 0, cvGetReal2D(cx1, i, 0)); cvSetReal2D(xM1, 1, 0, cvGetReal2D(cx1, i, 1)); cvSetReal2D(xM1, 2, 0, 1); cvMatMul(xM2, F, xM2); cvMatMul(xM2, xM1, s); double l1 = cvGetReal2D(xM2, 0, 0); double l2 = cvGetReal2D(xM2, 0, 1); double l3 = cvGetReal2D(xM2, 0, 2); double dist = abs(cvGetReal2D(s, 0, 0))/sqrt(l1*l1+l2*l2); if (dist < 5) { vInlierID.push_back(visibleFeatureID[i]); vCX_indx.push_back(i); } cvReleaseMat(&xM2); cvReleaseMat(&xM1); cvReleaseMat(&s); //if (cvGetReal2D(status, 0, i) == 1) //{ // cvSetReal2D(tempCx1, temprow, 0, cvGetReal2D(cx1, i, 0)); // cvSetReal2D(tempCx1, temprow, 1, cvGetReal2D(cx1, i, 1)); // cvSetReal2D(tempCx2, temprow, 0, cvGetReal2D(cx2, i, 0)); // cvSetReal2D(tempCx2, temprow, 1, cvGetReal2D(cx2, i, 1)); // temprow++; //} } visibleFeatureID = vInlierID; CvMat *tempCx1 = cvCreateMat(vCX_indx.size(), 2, CV_32FC1); CvMat *tempCx2 = cvCreateMat(vCX_indx.size(), 2, CV_32FC1); for (int iInlier = 0; iInlier < vInlierID.size(); iInlier++) { cvSetReal2D(tempCx1, iInlier, 0, cvGetReal2D(cx1, vCX_indx[iInlier], 0)); cvSetReal2D(tempCx1, iInlier, 1, cvGetReal2D(cx1, vCX_indx[iInlier], 1)); cvSetReal2D(tempCx2, iInlier, 0, cvGetReal2D(cx2, vCX_indx[iInlier], 0)); cvSetReal2D(tempCx2, iInlier, 1, cvGetReal2D(cx2, vCX_indx[iInlier], 1)); } cvReleaseMat(&cx1); cvReleaseMat(&cx2); cx1 = cvCloneMat(tempCx1); cx2 = cvCloneMat(tempCx2); cvReleaseMat(&status); cvReleaseMat(&tempCx1); cvReleaseMat(&tempCx2); CvMat *E = cvCreateMat(3, 3, CV_32FC1); CvMat *temp33 = cvCreateMat(3, 3, CV_32FC1); CvMat *temp34 = cvCreateMat(3, 4, CV_32FC1); //CvMat *K1 = cvCreateMat(3,3,CV_32FC1); //CvMat *K2 = cvCreateMat(3,3,CV_32FC1); int camera1 = (int)((double)initialFrame1/max_nFrames); int camera2 = (int)((double)initialFrame2/max_nFrames); vector<int> ::const_iterator it1 = find(vCamera[camera1].vTakenFrame.begin(), vCamera[camera1].vTakenFrame.end(), initialFrame1%max_nFrames); vector<int> ::const_iterator it2 = find(vCamera[camera2].vTakenFrame.begin(), vCamera[camera2].vTakenFrame.end(), initialFrame2%max_nFrames); int idx1 = (int) (it1 - vCamera[camera1].vTakenFrame.begin()); int idx2 = (int) (it2 - vCamera[camera2].vTakenFrame.begin()); CvMat *K1 = cvCloneMat(vCamera[camera1].vK[idx1]); CvMat *K2 = cvCloneMat(vCamera[camera2].vK[idx2]); cvTranspose(K2, temp33); cvMatMul(temp33, F, temp33); cvMatMul(temp33, K1, E); CvMat *invK1 = cvCreateMat(3,3,CV_32FC1); CvMat *invK2 = cvCreateMat(3,3,CV_32FC1); cvInvert(K1, invK1); cvInvert(K2, invK2); CvMat *nx1 = cvCreateMat(cx1->rows, cx1->cols, CV_32FC1); CvMat *nx2 = cvCreateMat(cx2->rows, cx2->cols, CV_32FC1); Pxx_inhomo(invK1, cx1, nx1); Pxx_inhomo(invK2, cx2, nx2); GetExtrinsicParameterFromE(E, nx1, nx2, P); CvMat *P0 = cvCreateMat(3, 4, CV_32FC1); cvSetIdentity(P0); CvMat *cX = cvCreateMat(nx1->rows, 3, CV_32FC1); PrintMat(P); cvMatMul(K1, P0, P0); cvMatMul(K2, P, P); PrintMat(P); //LinearTriangulation(nx1, P0, nx2, P, cX); LinearTriangulation(cx1, P0, cx2, P, cX); //PrintMat(cX); cvSetZero(X); SetIndexedMatRowwise(X, visibleFeatureID, cX); vvPointIndex.push_back(visibleFeatureID); vvPointIndex.push_back(visibleFeatureID); for (int i = 0; i < visibleFeatureID.size(); i++) { vFeature[visibleFeatureID[i]].isRegistered = true; } cvReleaseMat(&F); cvReleaseMat(&E); cvReleaseMat(&temp33); cvReleaseMat(&temp34); cvReleaseMat(&K1); cvReleaseMat(&K2); cvReleaseMat(&invK1); cvReleaseMat(&invK2); cvReleaseMat(&P0); cvReleaseMat(&cx1); cvReleaseMat(&cx2); cvReleaseMat(&nx1); cvReleaseMat(&nx2); cvReleaseMat(&cX); return vInlierID.size(); } int BilinearCameraPoseEstimation_OPENCV_OrientationRefinement(vector<Feature> &vFeature, int initialFrame1, int initialFrame2, int max_nFrames, vector<Camera> vCamera, CvMat *M, CvMat *m, vector<int> &vVisibleID) { //PrintAlgorithm("Bilinear Camera Pose Estimation"); vector<int> visibleFeatureID; vector<vector<double> > cx1_vec, cx2_vec, nx1_vec, nx2_vec; VisibleIntersection_mem(vFeature, initialFrame1, initialFrame2, cx1_vec, cx2_vec, visibleFeatureID); if (visibleFeatureID.size() < 40) return 0; CvMat *cx1 = cvCreateMat(cx1_vec.size(), 2, CV_32FC1); CvMat *cx2 = cvCreateMat(cx2_vec.size(), 2, CV_32FC1); SetCvMatFromVectors(cx1_vec, cx1); SetCvMatFromVectors(cx2_vec, cx2); if (visibleFeatureID.size() < 8) { return visibleFeatureID.size(); } CvMat *F = cvCreateMat(3,3,CV_32FC1); vector<int> vInlierID; CvMat *status = cvCreateMat(1,cx1->rows,CV_8UC1); int n = cvFindFundamentalMat(cx1, cx2, F, CV_FM_LMEDS , 1, 0.99, status); //cout << n << endl; vector<int> vCX_indx; for (int i = 0; i < cx1->rows; i++) { CvMat *xM2 = cvCreateMat(1,3,CV_32FC1); CvMat *xM1 = cvCreateMat(3,1,CV_32FC1); CvMat *s = cvCreateMat(1,1, CV_32FC1); cvSetReal2D(xM2, 0, 0, cvGetReal2D(cx2, i, 0)); cvSetReal2D(xM2, 0, 1, cvGetReal2D(cx2, i, 1)); cvSetReal2D(xM2, 0, 2, 1); cvSetReal2D(xM1, 0, 0, cvGetReal2D(cx1, i, 0)); cvSetReal2D(xM1, 1, 0, cvGetReal2D(cx1, i, 1)); cvSetReal2D(xM1, 2, 0, 1); cvMatMul(xM2, F, xM2); cvMatMul(xM2, xM1, s); double l1 = cvGetReal2D(xM2, 0, 0); double l2 = cvGetReal2D(xM2, 0, 1); double l3 = cvGetReal2D(xM2, 0, 2); double dist = abs(cvGetReal2D(s, 0, 0))/sqrt(l1*l1+l2*l2); if (dist < 5) { vInlierID.push_back(visibleFeatureID[i]); vCX_indx.push_back(i); } cvReleaseMat(&xM2); cvReleaseMat(&xM1); cvReleaseMat(&s); } visibleFeatureID = vInlierID; CvMat *tempCx1 = cvCreateMat(vCX_indx.size(), 2, CV_32FC1); CvMat *tempCx2 = cvCreateMat(vCX_indx.size(), 2, CV_32FC1); for (int iInlier = 0; iInlier < vInlierID.size(); iInlier++) { cvSetReal2D(tempCx1, iInlier, 0, cvGetReal2D(cx1, vCX_indx[iInlier], 0)); cvSetReal2D(tempCx1, iInlier, 1, cvGetReal2D(cx1, vCX_indx[iInlier], 1)); cvSetReal2D(tempCx2, iInlier, 0, cvGetReal2D(cx2, vCX_indx[iInlier], 0)); cvSetReal2D(tempCx2, iInlier, 1, cvGetReal2D(cx2, vCX_indx[iInlier], 1)); } cvReleaseMat(&cx1); cvReleaseMat(&cx2); cx1 = cvCloneMat(tempCx1); cx2 = cvCloneMat(tempCx2); cvReleaseMat(&status); cvReleaseMat(&tempCx1); cvReleaseMat(&tempCx2); CvMat *E = cvCreateMat(3, 3, CV_32FC1); CvMat *temp33 = cvCreateMat(3, 3, CV_32FC1); CvMat *temp34 = cvCreateMat(3, 4, CV_32FC1); //CvMat *K1 = cvCreateMat(3,3,CV_32FC1); //CvMat *K2 = cvCreateMat(3,3,CV_32FC1); int camera1 = (int)((double)initialFrame1/max_nFrames); int camera2 = (int)((double)initialFrame2/max_nFrames); vector<int> ::const_iterator it1 = find(vCamera[camera1].vTakenFrame.begin(), vCamera[camera1].vTakenFrame.end(), initialFrame1%max_nFrames); vector<int> ::const_iterator it2 = find(vCamera[camera2].vTakenFrame.begin(), vCamera[camera2].vTakenFrame.end(), initialFrame2%max_nFrames); int idx1 = (int) (it1 - vCamera[camera1].vTakenFrame.begin()); int idx2 = (int) (it2 - vCamera[camera2].vTakenFrame.begin()); CvMat *K1 = cvCloneMat(vCamera[camera1].vK[idx1]); CvMat *K2 = cvCloneMat(vCamera[camera2].vK[idx2]); cvTranspose(K2, temp33); cvMatMul(temp33, F, temp33); cvMatMul(temp33, K1, E); CvMat *invK1 = cvCreateMat(3,3,CV_32FC1); CvMat *invK2 = cvCreateMat(3,3,CV_32FC1); cvInvert(K1, invK1); cvInvert(K2, invK2); CvMat *nx1 = cvCreateMat(cx1->rows, cx1->cols, CV_32FC1); CvMat *nx2 = cvCreateMat(cx2->rows, cx2->cols, CV_32FC1); Pxx_inhomo(invK1, cx1, nx1); Pxx_inhomo(invK2, cx2, nx2); CvMat *P = cvCreateMat(3,4,CV_32FC1); GetExtrinsicParameterFromE(E, nx1, nx2, P); CvMat *P0 = cvCreateMat(3, 4, CV_32FC1); cvSetIdentity(P0); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { cvSetReal2D(M, i, j, cvGetReal2D(P, i, j)); } } for (int i = 0; i < 3; i++) { cvSetReal2D(m, i, 0, cvGetReal2D(P, i, 3)); } cvReleaseMat(&F); cvReleaseMat(&E); cvReleaseMat(&temp33); cvReleaseMat(&temp34); cvReleaseMat(&K1); cvReleaseMat(&K2); cvReleaseMat(&invK1); cvReleaseMat(&invK2); cvReleaseMat(&P0); cvReleaseMat(&cx1); cvReleaseMat(&cx2); cvReleaseMat(&nx1); cvReleaseMat(&nx2); cvReleaseMat(&P); vVisibleID = vInlierID; return vInlierID.size(); } void BilinearCameraPoseEstimation(vector<Feature> vFeature, int initialFrame1, int initialFrame2, double ransacThreshold, int ransacMaxIter, int max_nFrames, vector<Camera> vCamera, CvMat &P, CvMat &X, vector<int> &visibleStructureID) { PrintAlgorithm("Bilinear Camera Pose Estimation"); CvMat cx1, cx2, nx1, nx2; vector<int> visibleFeatureID; X = *cvCreateMat(vFeature.size(), 3, CV_32FC1); VisibleIntersection(vFeature, initialFrame1, initialFrame2, cx1, cx2, visibleFeatureID); cout << "Visible intersection between 2 and 3: " << visibleFeatureID.size() << endl; assert(visibleFeatureID.size() > 7); CvMat *F = cvCreateMat(3,3,CV_32FC1); EightPointAlgorithm(&cx1, &cx2, F); ScalarMul(F, 1/cvGetReal2D(F, 2,2), F); PrintMat(F, "Fundamental Matrix"); //Classifier classifier; //vector<int> visibleID; //classifier.SetRansacParam(ransacThreshold, ransacMaxIter); //classifier.SetCorrespondance(&cx1, &cx2, visibleFeatureID); //classifier.Classify(); //vector<int> vInlierID, vOutlierID; //classifier.GetClassificationResultByFeatureID(vInlierID, vOutlierID); //visibleFeatureID = vInlierID; //F = cvCloneMat(classifier.F); //double F33 = cvGetReal2D(F, 2,2); //ScalarMul(F, 1/F33, F); //PrintMat(F, "Fundamental Matrix"); //cx1 = *cvCreateMat(classifier.inlier1->rows, classifier.inlier1->cols, CV_32FC1); //cx2 = *cvCreateMat(classifier.inlier2->rows, classifier.inlier2->cols, CV_32FC1); //cx1 = *cvCloneMat(classifier.inlier1); //cx2 = *cvCloneMat(classifier.inlier2); CvMat *E = cvCreateMat(3, 3, CV_32FC1); CvMat *temp33 = cvCreateMat(3, 3, CV_32FC1); CvMat *temp34 = cvCreateMat(3, 4, CV_32FC1); CvMat *K1 = cvCreateMat(3,3,CV_32FC1); CvMat *K2 = cvCreateMat(3,3,CV_32FC1); int camera1 = (int)((double)initialFrame1/max_nFrames); int camera2 = (int)((double)initialFrame2/max_nFrames); vector<int> ::const_iterator it1 = find(vCamera[camera1].vTakenFrame.begin(), vCamera[camera1].vTakenFrame.end(), initialFrame1%max_nFrames); vector<int> ::const_iterator it2 = find(vCamera[camera2].vTakenFrame.begin(), vCamera[camera2].vTakenFrame.end(), initialFrame2%max_nFrames); int idx1 = (int) (it1 - vCamera[camera1].vTakenFrame.begin()); int idx2 = (int) (it2 - vCamera[camera2].vTakenFrame.begin()); K1 = cvCloneMat(vCamera[camera1].vK[idx1]); K2 = cvCloneMat(vCamera[camera2].vK[idx1]); cvTranspose(K2, temp33); cvMatMul(temp33, F, temp33); cvMatMul(temp33, K1, E); CvMat *invK1 = cvCreateMat(3,3,CV_32FC1); CvMat *invK2 = cvCreateMat(3,3,CV_32FC1); cvInvert(K1, invK1); cvInvert(K2, invK2); Pxx_inhomo(invK1, &cx1, nx1); Pxx_inhomo(invK2, &cx2, nx2); GetExtrinsicParameterFromE(E, &nx1, &nx2, P); CvMat *P0 = cvCreateMat(3, 4, CV_32FC1); cvSetIdentity(P0); CvMat cX; LinearTriangulation(&nx1, P0, &nx2, &P, cX); cvSetZero(&X); SetIndexedMatRowwise(&X, visibleFeatureID, &cX); cvMatMul(K2, &P, temp34); P = *cvCloneMat(temp34); visibleStructureID = visibleFeatureID; cvReleaseMat(&F); cvReleaseMat(&E); cvReleaseMat(&temp33); cvReleaseMat(&temp34); cvReleaseMat(&K1); cvReleaseMat(&K2); cvReleaseMat(&invK1); cvReleaseMat(&invK2); cvReleaseMat(&P0); } void EightPointAlgorithm(CvMat *x1_8, CvMat *x2_8, CvMat *F_8) { CvMat *A = cvCreateMat(x1_8->rows, 9, CV_32FC1); CvMat *U = cvCreateMat(x1_8->rows, x1_8->rows, CV_32FC1); CvMat *D = cvCreateMat(x1_8->rows, 9, CV_32FC1); CvMat *V = cvCreateMat(9, 9, CV_32FC1); for (int iIdx = 0; iIdx < x1_8->rows; iIdx++) { double x11 = cvGetReal2D(x1_8, iIdx, 0); double x12 = cvGetReal2D(x1_8, iIdx, 1); double x21 = cvGetReal2D(x2_8, iIdx, 0); double x22 = cvGetReal2D(x2_8, iIdx, 1); cvSetReal2D(A, iIdx, 0, x21*x11); cvSetReal2D(A, iIdx, 1, x21*x12); cvSetReal2D(A, iIdx, 2, x21); cvSetReal2D(A, iIdx, 3, x22*x11); cvSetReal2D(A, iIdx, 4, x22*x12); cvSetReal2D(A, iIdx, 5, x22); cvSetReal2D(A, iIdx, 6, x11); cvSetReal2D(A, iIdx, 7, x12); cvSetReal2D(A, iIdx, 8, 1); } cvSVD(A, D, U, V, 0); cvSetReal2D(F_8, 0, 0, cvGetReal2D(V, 0, 8)); cvSetReal2D(F_8, 0, 1, cvGetReal2D(V, 1, 8)); cvSetReal2D(F_8, 0, 2, cvGetReal2D(V, 2, 8)); cvSetReal2D(F_8, 1, 0, cvGetReal2D(V, 3, 8)); cvSetReal2D(F_8, 1, 1, cvGetReal2D(V, 4, 8)); cvSetReal2D(F_8, 1, 2, cvGetReal2D(V, 5, 8)); cvSetReal2D(F_8, 2, 0, cvGetReal2D(V, 6, 8)); cvSetReal2D(F_8, 2, 1, cvGetReal2D(V, 7, 8)); cvSetReal2D(F_8, 2, 2, cvGetReal2D(V, 8, 8)); CvMat *UD, *Vt; U = cvCreateMat(3, 3, CV_32FC1); D = cvCreateMat(3, 3, CV_32FC1); V = cvCreateMat(3, 3, CV_32FC1); UD = cvCreateMat(U->rows, D->cols, CV_32FC1); Vt = cvCreateMat(V->cols, V->rows, CV_32FC1); cvSVD(F_8, D, U, V, 0); cvSetReal2D(D, 2, 2, 0); cvMatMul(U, D, UD); cvTranspose(V, Vt); cvMatMul(UD, Vt, F_8); cvReleaseMat(&UD); cvReleaseMat(&Vt); cvReleaseMat(&A); cvReleaseMat(&U); cvReleaseMat(&D); cvReleaseMat(&V); } void VisibleIntersection(vector<Feature> vFeature, int frame1, int frame2, CvMat &cx1, CvMat &cx2, vector<int> &visibleFeatureID) { vector<double> x1, y1, x2, y2; for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1); vector<int>::iterator it2 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame2); if ((it1 != vFeature[iFeature].vFrame.end()) && (it2 != vFeature[iFeature].vFrame.end())) { int idx = int(it1-vFeature[iFeature].vFrame.begin()); x1.push_back(vFeature[iFeature].vx[idx]); y1.push_back(vFeature[iFeature].vy[idx]); idx = int(it2-vFeature[iFeature].vFrame.begin()); x2.push_back(vFeature[iFeature].vx[idx]); y2.push_back(vFeature[iFeature].vy[idx]); visibleFeatureID.push_back(vFeature[iFeature].id); } } cout << "# intersection: " << visibleFeatureID.size() << endl; cx1 = *cvCreateMat(x1.size(), 2, CV_32FC1); cx2 = *cvCreateMat(x1.size(), 2, CV_32FC1); for (int i = 0; i < x1.size(); i++) { cvSetReal2D(&cx1, i, 0, x1[i]); cvSetReal2D(&cx1, i, 1, y1[i]); cvSetReal2D(&cx2, i, 0, x2[i]); cvSetReal2D(&cx2, i, 1, y2[i]); } } void VisibleIntersection_mem(vector<Feature> &vFeature, int frame1, int frame2, vector<vector<double> > &cx1, vector<vector<double> > &cx2, vector<int> &visibleFeatureID) { vector<double> x1, y1, x2, y2; for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1); vector<int>::iterator it2 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame2); if ((it1 != vFeature[iFeature].vFrame.end()) && (it2 != vFeature[iFeature].vFrame.end())) { int idx = int(it1-vFeature[iFeature].vFrame.begin()); x1.push_back(vFeature[iFeature].vx[idx]); y1.push_back(vFeature[iFeature].vy[idx]); idx = int(it2-vFeature[iFeature].vFrame.begin()); x2.push_back(vFeature[iFeature].vx[idx]); y2.push_back(vFeature[iFeature].vy[idx]); visibleFeatureID.push_back(vFeature[iFeature].id); } } //cout << "# intersection: " << visibleFeatureID.size() << endl; for (int i = 0; i < x1.size(); i++) { vector<double> x1_vec, x2_vec; x1_vec.push_back(x1[i]); x1_vec.push_back(y1[i]); x2_vec.push_back(x2[i]); x2_vec.push_back(y2[i]); cx1.push_back(x1_vec); cx2.push_back(x2_vec); } } void VisibleIntersection_Simple(vector<Feature> vFeature, int frame1, int frame2, vector<int> &visibleFeatureID) { vector<double> x1, y1, x2, y2; for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1); vector<int>::iterator it2 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame2); if ((it1 != vFeature[iFeature].vFrame.end()) && (it2 != vFeature[iFeature].vFrame.end())) { visibleFeatureID.push_back(vFeature[iFeature].id); } } } int VisibleIntersection23(vector<Feature> vFeature, int frame1, CvMat *X, vector<int> visibleStructureID, CvMat &cx, CvMat &cX, vector<int> &visibleID) { vector<double> x_, y_, X_, Y_, Z_; for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1); vector<int>::iterator it2 = find(visibleStructureID.begin(),visibleStructureID.end(),vFeature[iFeature].id); if ((it1 != vFeature[iFeature].vFrame.end()) && (it2 != visibleStructureID.end())) { int idx1 = int(it1-vFeature[iFeature].vFrame.begin()); int idx2 = int(it2-visibleStructureID.begin()); x_.push_back(vFeature[iFeature].vx[idx1]); y_.push_back(vFeature[iFeature].vy[idx1]); X_.push_back(cvGetReal2D(X, vFeature[iFeature].id, 0)); Y_.push_back(cvGetReal2D(X, vFeature[iFeature].id, 1)); Z_.push_back(cvGetReal2D(X, vFeature[iFeature].id, 2)); visibleID.push_back(vFeature[iFeature].id); } } if (x_.size() < 1) return 0; cx = *cvCreateMat(x_.size(), 2, CV_32FC1); cX = *cvCreateMat(x_.size(), 3, CV_32FC1); for (int i = 0; i < x_.size(); i++) { cvSetReal2D(&cx, i, 0, x_[i]); cvSetReal2D(&cx, i, 1, y_[i]); cvSetReal2D(&cX, i, 0, X_[i]); cvSetReal2D(&cX, i, 1, Y_[i]); cvSetReal2D(&cX, i, 2, Z_[i]); } return 1; } int VisibleIntersection23_mem(vector<Feature> vFeature, int frame1, CvMat *X, vector<int> visibleStructureID, vector<vector<double> > &cx, vector<vector<double> > &cX, vector<int> &visibleID) { vector<double> x_, y_, X_, Y_, Z_; for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1); vector<int>::iterator it2 = find(visibleStructureID.begin(),visibleStructureID.end(),vFeature[iFeature].id); if ((it1 != vFeature[iFeature].vFrame.end()) && (it2 != visibleStructureID.end())) { int idx1 = int(it1-vFeature[iFeature].vFrame.begin()); int idx2 = int(it2-visibleStructureID.begin()); x_.push_back(vFeature[iFeature].vx[idx1]); y_.push_back(vFeature[iFeature].vy[idx1]); X_.push_back(cvGetReal2D(X, vFeature[iFeature].id, 0)); Y_.push_back(cvGetReal2D(X, vFeature[iFeature].id, 1)); Z_.push_back(cvGetReal2D(X, vFeature[iFeature].id, 2)); visibleID.push_back(vFeature[iFeature].id); } } if (x_.size() < 1) return 0; for (int i = 0; i < x_.size(); i++) { vector<double> cx_vec, cX_vec; cx_vec.push_back(x_[i]); cx_vec.push_back(y_[i]); cX_vec.push_back(X_[i]); cX_vec.push_back(Y_[i]); cX_vec.push_back(Z_[i]); cx.push_back(cx_vec); cX.push_back(cX_vec); } return visibleID.size(); } int VisibleIntersection23_mem_fast(vector<Feature> &vFeature, int frame1, CvMat *X, vector<vector<double> > &cx, vector<vector<double> > &cX, vector<int> &visibleID) { for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { vector<double> cx_vec, cX_vec; vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1); if ((it1 != vFeature[iFeature].vFrame.end()) && (vFeature[iFeature].isRegistered)) { int idx1 = int(it1-vFeature[iFeature].vFrame.begin()); cx_vec.push_back(vFeature[iFeature].vx[idx1]); cx_vec.push_back(vFeature[iFeature].vy[idx1]); cX_vec.push_back(cvGetReal2D(X, vFeature[iFeature].id, 0)); cX_vec.push_back(cvGetReal2D(X, vFeature[iFeature].id, 1)); cX_vec.push_back(cvGetReal2D(X, vFeature[iFeature].id, 2)); cx.push_back(cx_vec); cX.push_back(cX_vec); visibleID.push_back(vFeature[iFeature].id); } } if (cx.size() < 1) return 0; return visibleID.size(); } int VisibleIntersection23_Simple(vector<Feature> &vFeature, int frame1, vector<int> visibleStructureID, vector<int> &visibleID) { vector<double> x_, y_, X_, Y_, Z_; for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1); if (it1 == vFeature[iFeature].vFrame.end()) continue; vector<int>::iterator it2 = find(visibleStructureID.begin(),visibleStructureID.end(),vFeature[iFeature].id); if ((it1 != vFeature[iFeature].vFrame.end()) && (it2 != visibleStructureID.end())) { int idx1 = int(it1-vFeature[iFeature].vFrame.begin()); int idx2 = int(it2-visibleStructureID.begin()); visibleID.push_back(vFeature[iFeature].id); } } x_.clear(); y_.clear(); X_.clear(); Y_.clear(); Z_.clear(); return visibleID.size(); } int VisibleIntersection23_Simple_fast(vector<Feature> &vFeature, int frame1) { int count = 0; for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1); if (it1 == vFeature[iFeature].vFrame.end()) continue; else if (vFeature[iFeature].isRegistered) count++; } return count; } //int VisibleIntersection23(vector<Feature> vFeature, int frame1, CvMat *X, vector<int> visibleStructureID, CvMat *x, vector<int> &visibleID) //{ // vector<double> x_, y_, X_, Y_, Z_; // for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) // { // vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1); // vector<int>::iterator it2 = find(visibleStructureID.begin(),visibleStructureID.end(),vFeature[iFeature].id); // // if ((it1 != vFeature[iFeature].vFrame.end()) && (it2 != visibleStructureID.end())) // { // int idx1 = int(it1-vFeature[iFeature].vFrame.begin()); // int idx2 = int(it2-visibleStructureID.begin()); // x_.push_back(vFeature[iFeature].vx[idx1]); // y_.push_back(vFeature[iFeature].vy[idx1]); // X_.push_back(cvGetReal2D(X, vFeature[iFeature].id, 0)); // Y_.push_back(cvGetReal2D(X, vFeature[iFeature].id, 1)); // Z_.push_back(cvGetReal2D(X, vFeature[iFeature].id, 2)); // visibleID.push_back(vFeature[iFeature].id); // } // } // // if (x_.size() < 1) // return 0; // cx = *cvCreateMat(x_.size(), 2, CV_32FC1); // cX = *cvCreateMat(x_.size(), 3, CV_32FC1); // for (int i = 0; i < x_.size(); i++) // { // cvSetReal2D(&cx, i, 0, x_[i]); cvSetReal2D(&cx, i, 1, y_[i]); // cvSetReal2D(&cX, i, 0, X_[i]); cvSetReal2D(&cX, i, 1, Y_[i]); cvSetReal2D(&cX, i, 2, Z_[i]); // } // return 1; //} int VisibleIntersectionXOR3(vector<Feature> vFeature, int frame1, int frame2, vector<int> visibleStructureID, CvMat &cx1, CvMat &cx2, vector<int> &visibleID) { vector<double> x1_, y1_, x2_, y2_; visibleID.clear(); for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1); vector<int>::iterator it2 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame2); vector<int>::iterator it3 = find(visibleStructureID.begin(),visibleStructureID.end(),vFeature[iFeature].id); if ((it1 != vFeature[iFeature].vFrame.end()) && (it2 != vFeature[iFeature].vFrame.end()) && (it3 == visibleStructureID.end())) { int idx1 = int(it1-vFeature[iFeature].vFrame.begin()); int idx2 = int(it2-vFeature[iFeature].vFrame.begin()); x1_.push_back(vFeature[iFeature].vx[idx1]); y1_.push_back(vFeature[iFeature].vy[idx1]); x2_.push_back(vFeature[iFeature].vx[idx2]); y2_.push_back(vFeature[iFeature].vy[idx2]); visibleID.push_back(vFeature[iFeature].id); } } if (x1_.size() == 0) { visibleID.clear(); return 0; } cx1 = *cvCreateMat(x1_.size(), 2, CV_32FC1); cx2 = *cvCreateMat(x1_.size(), 2, CV_32FC1); for (int i = 0; i < x1_.size(); i++) { cvSetReal2D(&cx1, i, 0, x1_[i]); cvSetReal2D(&cx1, i, 1, y1_[i]); cvSetReal2D(&cx2, i, 0, x2_[i]); cvSetReal2D(&cx2, i, 1, y2_[i]); } return 1; } int VisibleIntersectionXOR3_mem(vector<Feature> &vFeature, int frame1, int frame2, vector<int> visibleStructureID, vector<vector<double> > &cx1, vector<vector<double> > &cx2, vector<int> &visibleID) { vector<double> x1_, y1_, x2_, y2_; visibleID.clear(); for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1); vector<int>::iterator it2 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame2); vector<int>::iterator it3 = find(visibleStructureID.begin(),visibleStructureID.end(),vFeature[iFeature].id); if ((it1 != vFeature[iFeature].vFrame.end()) && (it2 != vFeature[iFeature].vFrame.end()) && (it3 == visibleStructureID.end())) { int idx1 = int(it1-vFeature[iFeature].vFrame.begin()); int idx2 = int(it2-vFeature[iFeature].vFrame.begin()); x1_.push_back(vFeature[iFeature].vx[idx1]); y1_.push_back(vFeature[iFeature].vy[idx1]); x2_.push_back(vFeature[iFeature].vx[idx2]); y2_.push_back(vFeature[iFeature].vy[idx2]); visibleID.push_back(vFeature[iFeature].id); } } if (x1_.size() == 0) { visibleID.clear(); return 0; } for (int i = 0; i < x1_.size(); i++) { vector<double> cx1_vec, cx2_vec; cx1_vec.push_back(x1_[i]); cx1_vec.push_back(y1_[i]); cx2_vec.push_back(x2_[i]); cx2_vec.push_back(y2_[i]); cx1.push_back(cx1_vec); cx2.push_back(cx2_vec); } return cx1.size(); } int VisibleIntersectionXOR3_mem_fast(vector<Feature> &vFeature, int frame1, int frame2, vector<vector<double> > &cx1, vector<vector<double> > &cx2, vector<int> &visibleID) { visibleID.clear(); for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { if (vFeature[iFeature].isRegistered) continue; vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1); if (it1 == vFeature[iFeature].vFrame.end()) continue; vector<int>::iterator it2 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame2); if (it2 == vFeature[iFeature].vFrame.end()) continue; vector<double> cx1_vec, cx2_vec; int idx1 = int(it1-vFeature[iFeature].vFrame.begin()); int idx2 = int(it2-vFeature[iFeature].vFrame.begin()); cx1_vec.push_back(vFeature[iFeature].vx[idx1]); cx1_vec.push_back(vFeature[iFeature].vy[idx1]); cx2_vec.push_back(vFeature[iFeature].vx[idx2]); cx2_vec.push_back(vFeature[iFeature].vy[idx2]); cx1.push_back(cx1_vec); cx2.push_back(cx2_vec); visibleID.push_back(vFeature[iFeature].id); } if (visibleID.size() == 0) { return 0; } return cx1.size(); } //int VisibleIntersectionXOR3(vector<Feature> vFeature, int frame1, int frame2, vector<int> visibleStructureID, vector<int> &visibleID) //{ // vector<double> x1_, y1_, x2_, y2_; // visibleID.clear(); // for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) // { // vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1); // vector<int>::iterator it2 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame2); // vector<int>::iterator it3 = find(visibleStructureID.begin(),visibleStructureID.end(),vFeature[iFeature].id); // // if ((it1 != vFeature[iFeature].vFrame.end()) && (it2 != vFeature[iFeature].vFrame.end()) && (it3 == visibleStructureID.end())) // { // int idx1 = int(it1-vFeature[iFeature].vFrame.begin()); // int idx2 = int(it2-vFeature[iFeature].vFrame.begin()); // x1_.push_back(vFeature[iFeature].vx[idx1]); // y1_.push_back(vFeature[iFeature].vy[idx1]); // x2_.push_back(vFeature[iFeature].vx[idx2]); // y2_.push_back(vFeature[iFeature].vy[idx2]); // visibleID.push_back(vFeature[iFeature].id); // } // } // // if (x1_.size() == 0) // { // visibleID.clear(); // return 0; // } // // cx1 = *cvCreateMat(x1_.size(), 2, CV_32FC1); // cx2 = *cvCreateMat(x1_.size(), 2, CV_32FC1); // for (int i = 0; i < x1_.size(); i++) // { // cvSetReal2D(&cx1, i, 0, x1_[i]); cvSetReal2D(&cx1, i, 1, y1_[i]); // cvSetReal2D(&cx2, i, 0, x2_[i]); cvSetReal2D(&cx2, i, 1, y2_[i]); // } // return 1; //} //int ExcludeOutliers(CvMat *cx1, CvMat *cx2, double ransacThreshold, double ransacMaxIter, vector<int> visibleID, CvMat &ex1, CvMat &ex2, vector<int> &eVisibleID) //{ // Classifier classifier; // classifier.SetRansacParam(ransacThreshold, ransacMaxIter); // classifier.SetCorrespondance(cx1, cx2, visibleID); // classifier.Classify(); // vector<int> vInlierID, vOutlierID; // classifier.GetClassificationResultByFeatureID(vInlierID, vOutlierID); // // if (vInlierID.size() > 0) // { // ex1 = *cvCreateMat(classifier.inlier1->rows, classifier.inlier1->cols, CV_32FC1); // ex2 = *cvCreateMat(classifier.inlier1->rows, classifier.inlier1->cols, CV_32FC1); // eVisibleID = vInlierID; // ex1 = *cvCloneMat(classifier.inlier1); // ex2 = *cvCloneMat(classifier.inlier2); // return 1; // } // else // { // return 0; // } //} int ExcludeOutliers(CvMat *cx1, CvMat *P1, CvMat *cx2, CvMat *P2, CvMat *K, double threshold, vector<int> visibleID, CvMat &ex1, CvMat &ex2, vector<int> &eVisibleID) { // Find epipole CvMat *e_homo = cvCreateMat(3,1,CV_32FC1); CvMat *C = cvCreateMat(3,1,CV_32FC1); CvMat *R = cvCreateMat(3,3,CV_32FC1); GetCameraParameter(P1, K, R, C); CvMat *C_homo = cvCreateMat(4,1,CV_32FC1); Inhomo2HomoVec(C, C_homo); cvMatMul(P2, C_homo, e_homo); double enorm = NormL2(e_homo); ScalarMul(e_homo, 1/enorm, e_homo); CvMat *pinvP1 = cvCreateMat(4,3,CV_32FC1); cvInvert(P1, pinvP1, CV_SVD); CvMat *temp33 = cvCreateMat(3,3,CV_32FC1); cvMatMul(P2, pinvP1, temp33); CvMat *skewE = cvCreateMat(3,3,CV_32FC1); Vec2Skew(e_homo, skewE); CvMat *F = cvCreateMat(3,3,CV_32FC1); CvMat *FF = cvCreateMat(3,3,CV_32FC1); cvMatMul(skewE, temp33, F); double Fnorm = NormL2(F); ScalarMul(F, 1/Fnorm, F); cvTranspose(F, temp33); cvMatMul(temp33, F, FF); CvMat *D1=cvCreateMat(cx1->rows,1,CV_32FC1), *D2=cvCreateMat(cx1->rows,1,CV_32FC1), *D=cvCreateMat(cx1->rows,1,CV_32FC1); xPy_inhomo(cx2, cx1, F, D1); xPx_inhomo(cx1, FF, D2); for (int iIdx = 0; iIdx < D2->rows; iIdx++) { cvSetReal2D(D2, iIdx, 0, sqrt(cvGetReal2D(D2, iIdx, 0))); } cvDiv(D1, D2, D); cvMul(D, D, D); eVisibleID.clear(); for (int iIdx = 0; iIdx < cx1->rows; iIdx++) { if (abs(cvGetReal2D(D, iIdx, 0)) < threshold) { eVisibleID.push_back(visibleID[iIdx]); } } if (eVisibleID.size() > 0) { ex1 = *cvCreateMat(eVisibleID.size(), 2, CV_32FC1); ex2 = *cvCreateMat(eVisibleID.size(), 2, CV_32FC1); int k = 0; for (int iIdx = 0; iIdx < cx1->rows; iIdx++) { if (abs(cvGetReal2D(D, iIdx, 0)) < threshold) { cvSetReal2D(&ex1, k, 0, cvGetReal2D(cx1, iIdx, 0)); cvSetReal2D(&ex1, k, 1, cvGetReal2D(cx1, iIdx, 1)); cvSetReal2D(&ex2, k, 0, cvGetReal2D(cx2, iIdx, 0)); cvSetReal2D(&ex2, k, 1, cvGetReal2D(cx2, iIdx, 1)); k++; } } } cvReleaseMat(&e_homo); cvReleaseMat(&C); cvReleaseMat(&R); cvReleaseMat(&C_homo); cvReleaseMat(&pinvP1); cvReleaseMat(&temp33); cvReleaseMat(&skewE); cvReleaseMat(&F); cvReleaseMat(&FF); cvReleaseMat(&D1); cvReleaseMat(&D2); cvReleaseMat(&D); if (eVisibleID.size() >0) return 1; else return 0; } int ExcludeOutliers_mem(CvMat *cx1, CvMat *P1, CvMat *cx2, CvMat *P2, CvMat *K, double threshold, vector<int> visibleID, vector<vector<double> > &ex1, vector<vector<double> > &ex2, vector<int> &eVisibleID) { // Find epipole CvMat *e_homo = cvCreateMat(3,1,CV_32FC1); CvMat *C = cvCreateMat(3,1,CV_32FC1); CvMat *R = cvCreateMat(3,3,CV_32FC1); GetCameraParameter(P1, K, R, C); CvMat *C_homo = cvCreateMat(4,1,CV_32FC1); Inhomo2HomoVec(C, C_homo); cvMatMul(P2, C_homo, e_homo); double enorm = NormL2(e_homo); ScalarMul(e_homo, 1/enorm, e_homo); CvMat *pinvP1 = cvCreateMat(4,3,CV_32FC1); cvInvert(P1, pinvP1, CV_SVD); CvMat *temp33 = cvCreateMat(3,3,CV_32FC1); cvMatMul(P2, pinvP1, temp33); CvMat *skewE = cvCreateMat(3,3,CV_32FC1); Vec2Skew(e_homo, skewE); CvMat *F = cvCreateMat(3,3,CV_32FC1); CvMat *FF = cvCreateMat(3,3,CV_32FC1); cvMatMul(skewE, temp33, F); double Fnorm = NormL2(F); ScalarMul(F, 1/Fnorm, F); cvTranspose(F, temp33); cvMatMul(temp33, F, FF); CvMat *D1=cvCreateMat(cx1->rows,1,CV_32FC1), *D2=cvCreateMat(cx1->rows,1,CV_32FC1), *D=cvCreateMat(cx1->rows,1,CV_32FC1); xPy_inhomo(cx2, cx1, F, D1); xPx_inhomo(cx1, FF, D2); for (int iIdx = 0; iIdx < D2->rows; iIdx++) { cvSetReal2D(D2, iIdx, 0, sqrt(cvGetReal2D(D2, iIdx, 0))); } cvDiv(D1, D2, D); cvMul(D, D, D); eVisibleID.clear(); for (int iIdx = 0; iIdx < cx1->rows; iIdx++) { if (abs(cvGetReal2D(D, iIdx, 0)) < threshold) { eVisibleID.push_back(visibleID[iIdx]); } } if (eVisibleID.size() > 0) { //ex1 = *cvCreateMat(eVisibleID.size(), 2, CV_32FC1); //ex2 = *cvCreateMat(eVisibleID.size(), 2, CV_32FC1); int k = 0; for (int iIdx = 0; iIdx < cx1->rows; iIdx++) { if (abs(cvGetReal2D(D, iIdx, 0)) < threshold) { vector<double> ex1_vec, ex2_vec; ex1_vec.push_back(cvGetReal2D(cx1, iIdx, 0)); ex1_vec.push_back(cvGetReal2D(cx1, iIdx, 1)); ex2_vec.push_back(cvGetReal2D(cx2, iIdx, 0)); ex2_vec.push_back(cvGetReal2D(cx2, iIdx, 1)); ex1.push_back(ex1_vec); ex2.push_back(ex2_vec); k++; } } } cvReleaseMat(&e_homo); cvReleaseMat(&C); cvReleaseMat(&R); cvReleaseMat(&C_homo); cvReleaseMat(&pinvP1); cvReleaseMat(&temp33); cvReleaseMat(&skewE); cvReleaseMat(&F); cvReleaseMat(&FF); cvReleaseMat(&D1); cvReleaseMat(&D2); cvReleaseMat(&D); if (eVisibleID.size() >0) return 1; else return 0; } int ExcludeOutliers_mem_fast(CvMat *cx1, CvMat *P1, CvMat *cx2, CvMat *P2, CvMat *K, double threshold, vector<int> visibleID, vector<vector<double> > &ex1, vector<vector<double> > &ex2, vector<int> &eVisibleID) { // Find epipole CvMat *e_homo = cvCreateMat(3,1,CV_32FC1); CvMat *C = cvCreateMat(3,1,CV_32FC1); CvMat *R = cvCreateMat(3,3,CV_32FC1); GetCameraParameter(P1, K, R, C); CvMat *C_homo = cvCreateMat(4,1,CV_32FC1); Inhomo2HomoVec(C, C_homo); cvMatMul(P2, C_homo, e_homo); double enorm = NormL2(e_homo); ScalarMul(e_homo, 1/enorm, e_homo); CvMat *pinvP1 = cvCreateMat(4,3,CV_32FC1); cvInvert(P1, pinvP1, CV_SVD); CvMat *temp33 = cvCreateMat(3,3,CV_32FC1); cvMatMul(P2, pinvP1, temp33); CvMat *skewE = cvCreateMat(3,3,CV_32FC1); Vec2Skew(e_homo, skewE); CvMat *F = cvCreateMat(3,3,CV_32FC1); CvMat *FF = cvCreateMat(3,3,CV_32FC1); cvMatMul(skewE, temp33, F); double Fnorm = NormL2(F); ScalarMul(F, 1/Fnorm, F); cvTranspose(F, temp33); cvMatMul(temp33, F, FF); //CvMat *D1=cvCreateMat(cx1->rows,1,CV_32FC1), *D2=cvCreateMat(cx1->rows,1,CV_32FC1), *D=cvCreateMat(cx1->rows,1,CV_32FC1); //xPy_inhomo(cx2, cx1, F, D1); //xPx_inhomo(cx1, FF, D2); //for (int iIdx = 0; iIdx < D2->rows; iIdx++) //{ // cvSetReal2D(D2, iIdx, 0, sqrt(cvGetReal2D(D2, iIdx, 0))); //} //cvDiv(D1, D2, D); //cvMul(D, D, D); eVisibleID.clear(); for (int iIdx = 0; iIdx < cx1->rows; iIdx++) { CvMat *xM2 = cvCreateMat(1, 3, CV_32FC1); CvMat *xM1 = cvCreateMat(3, 1, CV_32FC1); CvMat *s = cvCreateMat(1, 1, CV_32FC1); cvSetReal2D(xM2, 0, 0, cvGetReal2D(cx2, iIdx, 0)); cvSetReal2D(xM2, 0, 1, cvGetReal2D(cx2, iIdx, 1)); cvSetReal2D(xM2, 0, 2, 1); cvSetReal2D(xM1, 0, 0, cvGetReal2D(cx1, iIdx, 0)); cvSetReal2D(xM1, 1, 0, cvGetReal2D(cx2, iIdx, 1)); cvSetReal2D(xM1, 2, 0, 1); cvMatMul(xM2, F, xM2); cvMatMul(xM2, xM1, s); double l1 = cvGetReal2D(xM2, 0, 0); double l2 = cvGetReal2D(xM2, 0, 1); double l3 = cvGetReal2D(xM2, 0, 2); double dist = abs(cvGetReal2D(s, 0, 0))/sqrt(l1*l1+l2*l2); cout << dist << endl; if (abs(dist) < threshold) { vector<double> ex1_vec, ex2_vec; ex1_vec.push_back(cvGetReal2D(cx1, iIdx, 0)); ex1_vec.push_back(cvGetReal2D(cx1, iIdx, 1)); ex2_vec.push_back(cvGetReal2D(cx2, iIdx, 0)); ex2_vec.push_back(cvGetReal2D(cx2, iIdx, 1)); ex1.push_back(ex1_vec); ex2.push_back(ex2_vec); eVisibleID.push_back(visibleID[iIdx]); } cvReleaseMat(&xM2); cvReleaseMat(&xM1); cvReleaseMat(&s); } cvReleaseMat(&e_homo); cvReleaseMat(&C); cvReleaseMat(&R); cvReleaseMat(&C_homo); cvReleaseMat(&pinvP1); cvReleaseMat(&temp33); cvReleaseMat(&skewE); cvReleaseMat(&F); cvReleaseMat(&FF); //cvReleaseMat(&D1); //cvReleaseMat(&D2); //cvReleaseMat(&D); if (eVisibleID.size() > 0) return 1; else return 0; } void NonlinearTriangulation(CvMat *x1, CvMat *x2, CvMat *F, CvMat &xhat1, CvMat &xhat2) { for (int ix = 0; ix < x1->rows; ix++) { CvMat *T1 = cvCreateMat(3,3,CV_32FC1); CvMat *T2 = cvCreateMat(3,3,CV_32FC1); cvSetZero(T1); cvSetReal2D(T1, 0, 0, 1.0); cvSetReal2D(T1, 1, 1, 1.0); cvSetReal2D(T1, 2, 2, 1.0); cvSetReal2D(T1, 0, 2, -cvGetReal2D(x1, ix, 0)); cvSetReal2D(T1, 1, 2, -cvGetReal2D(x1, ix, 1)); cvSetZero(T2); cvSetReal2D(T2, 0, 0, 1.0); cvSetReal2D(T2, 1, 1, 1.0); cvSetReal2D(T2, 2, 2, 1.0); cvSetReal2D(T2, 0, 2, -cvGetReal2D(x2, ix, 0)); cvSetReal2D(T2, 1, 2, -cvGetReal2D(x2, ix, 1)); CvMat *nF = cvCreateMat(3,3,CV_32FC1); nF = cvCloneMat(F); CvMat *FinvT1 = cvCreateMat(3,3,CV_32FC1); CvMat *invT1 = cvCreateMat(3,3,CV_32FC1); CvMat *invT2 = cvCreateMat(3,3,CV_32FC1); CvMat *invT2t = cvCreateMat(3,3,CV_32FC1); cvInvert(T1, invT1); cvInvert(T2, invT2); cvTranspose(invT2, invT2t); cvMatMul(nF, invT1, FinvT1); cvMatMul(invT2t, FinvT1, nF); CvMat *U = cvCreateMat(3,3,CV_32FC1); CvMat *D = cvCreateMat(3,3,CV_32FC1); CvMat *Vt = cvCreateMat(3,3,CV_32FC1); cvSVD(nF, D, U, Vt, CV_SVD_V_T); cvSetReal2D(D, 2, 2, 0); CvMat *temp33 = cvCreateMat(3,3,CV_32FC1); CvMat *temp33_1 = cvCreateMat(3,3,CV_32FC1); cvMatMul(U, D, temp33); cvMatMul(temp33, Vt, nF); CvMat *e1 = cvCreateMat(3,1,CV_32FC1); CvMat *e2 = cvCreateMat(3,1,CV_32FC1); double e11 = cvGetReal2D(Vt,2,0); double e12 = cvGetReal2D(Vt,2,1); double e13 = cvGetReal2D(Vt,2,2); CvMat *nFt = cvCreateMat(3,3,CV_32FC1); cvTranspose(nF, nFt); cvSVD(nFt, D, U, Vt, CV_SVD_V_T); double norm_e1 = sqrt(e11*e11+e12*e12); double e21 = cvGetReal2D(Vt,2,0); double e22 = cvGetReal2D(Vt,2,1); double e23 = cvGetReal2D(Vt,2,2); double norm_e2 = sqrt(e21*e21+e22*e22); cvSetReal2D(e1,0,0,e11/norm_e1); cvSetReal2D(e1,1,0,e12/norm_e1); cvSetReal2D(e1,2,0,e13/norm_e1); cvSetReal2D(e2,0,0,e21/norm_e2); cvSetReal2D(e2,1,0,e22/norm_e2); cvSetReal2D(e2,2,0,e23/norm_e2); CvMat *R1 = cvCreateMat(3,3,CV_32FC1); CvMat *R2 = cvCreateMat(3,3,CV_32FC1); cvSetIdentity(R1); cvSetIdentity(R2); cvSetReal2D(R1, 0, 0, cvGetReal2D(e1, 0, 0)); cvSetReal2D(R1, 0, 1, cvGetReal2D(e1, 1, 0)); cvSetReal2D(R1, 1, 0, -cvGetReal2D(e1, 1, 0)); cvSetReal2D(R1, 1, 1, cvGetReal2D(e1, 0, 0)); cvSetReal2D(R2, 0, 0, cvGetReal2D(e2, 0, 0)); cvSetReal2D(R2, 0, 1, cvGetReal2D(e2, 1, 0)); cvSetReal2D(R2, 1, 0, -cvGetReal2D(e2, 1, 0)); cvSetReal2D(R2, 1, 1, cvGetReal2D(e2, 0, 0)); cvMatMul(R2, nF, temp33); cvTranspose(R1, temp33_1); cvMatMul(temp33, temp33_1, nF); double f1 = cvGetReal2D(e1, 2, 0); double f2 = cvGetReal2D(e2, 2, 0); double a = cvGetReal2D(nF, 1, 1); double b = cvGetReal2D(nF, 1, 2); double c = cvGetReal2D(nF, 2, 1); double d = cvGetReal2D(nF, 2, 2); double g1 = -(a*d-b*c)*f1*f1*f1*f1*a*c; double g2 = (a*a+f2*f2*c*c)*(a*a+f2*f2*c*c)-(a*d-b*c)*f1*f1*f1*f1*b*c-(a*d-b*c)*f1*f1*f1*f1*a*d; double g3 = (2*(2*b*a+2*f2*f2*d*c)*(a*a+f2*f2*c*c)-2*(a*d-b*c)*f1*f1*a*c-(a*d-b*c)*f1*f1*f1*f1*b*d); double g4 = (-2*(a*d-b*c)*f1*f1*b*c-2*(a*d-b*c)*f1*f1*a*d+2*(b*b+f2*f2*d*d)*(a*a+f2*f2*c*c)+(2*b*a+2*f2*f2*d*c)*(2*b*a+2*f2*f2*d*c)); double g5 = (-(a*d-b*c)*a*c-2*(a*d-b*c)*f1*f1*b*d+2*(b*b+f2*f2*d*d)*(2*b*a+2*f2*f2*d*c)); double g6 = ((b*b+f2*f2*d*d)*(b*b+f2*f2*d*d)-(a*d-b*c)*b*c-(a*d-b*c)*a*d); double g7 = -(a*d-b*c)*b*d; CvMat *G = cvCreateMat(7,1,CV_32FC1); CvMat *root = cvCreateMat(6,1, CV_32FC2); cvSetReal2D(G, 0, 0, g1); cvSetReal2D(G, 1, 0, g2); cvSetReal2D(G, 2, 0, g3); cvSetReal2D(G, 3, 0, g4); cvSetReal2D(G, 4, 0, g5); cvSetReal2D(G, 5, 0, g6); cvSetReal2D(G, 6, 0, g7); cvSolvePoly(G, root, 1e+3, 10); for (int i = 0; i < 6; i++) { CvScalar r = cvGet2D(root, i, 0); cout << r.val[0] << " " << r.val[1]<< endl; } } // e1 = null(F); e1 = e1/sqrt(e1(1)^2+e1(2)^2); //e2 = null(F'); e2 = e2/sqrt(e2(1)^2+e2(2)^2); // R1 = [e1(1) e1(2) 0; -e1(2) e1(1) 0; 0 0 1]; //R2 = [e2(1) e2(2) 0; -e2(2) e2(1) 0; 0 0 1]; //F = R2*F*R1'; // f1 = e1(3); f2 = e2(3); //a = F(2,2); b = F(2,3); c = F(3,2); d = F(3,3); //g = [-(a*d-b*c)*f1^4*a*c,... // (a^2+f2^2*c^2)^2-(a*d-b*c)*f1^4*b*c-(a*d-b*c)*f1^4*a*d,... // (2*(2*b*a+2*f2^2*d*c)*(a^2+f2^2*c^2)-2*(a*d-b*c)*f1^2*a*c-(a*d-b*c)*f1^4*b*d),... // (-2*(a*d-b*c)*f1^2*b*c-2*(a*d-b*c)*f1^2*a*d+2*(b^2+f2^2*d^2)*(a^2+f2^2*c^2)+(2*b*a+2*f2^2*d*c)^2),... // (-(a*d-b*c)*a*c-2*(a*d-b*c)*f1^2*b*d+2*(b^2+f2^2*d^2)*(2*b*a+2*f2^2*d*c)),... // ((b^2+f2^2*d^2)^2-(a*d-b*c)*b*c-(a*d-b*c)*a*d),... // -(a*d-b*c)*b*d]; //t = roots(g); //t = real(t); //s = t.^2./(1+f1^2*t.^2) + (c*t+d).^2./((a*t+b).^2 + f2^2*(c*t+d).^2); //s(end+1) = 1/f1^2+c^2/(a^2+f2^2*c^2); //[mins,minidx] = min(s); //if minidx <= length(t) // t = t(minidx); //else // t = 1e+6; //end // l1 = [t*f1, 1, -t]; //l2 = F*[0; t; 1]; //xhat1_t = [-l1(1)*l1(3); -l1(2)*l1(3); l1(1)^2+l1(2)^2]; //xhat2_t = [-l2(1)*l2(3); -l2(2)*l2(3); l2(1)^2+l2(2)^2]; //xhat1_t = inv(T1)*R1'*xhat1_t; // xhat2_t = inv(T2)*R2'*xhat2_t; // xhat1_t = xhat1_t/xhat1_t(3); //xhat2_t = xhat2_t/xhat2_t(3); //xhat1(i,:) = xhat1_t; //xhat2(i,:) = xhat2_t; //end } void GetExtrinsicParameterFromE(CvMat *E, CvMat *x1, CvMat *x2, CvMat &P) { CvMat *W = cvCreateMat(3, 3, CV_32FC1); CvMat *U = cvCreateMat(3, 3, CV_32FC1); CvMat *D = cvCreateMat(3, 3, CV_32FC1); CvMat *Vt = cvCreateMat(3, 3, CV_32FC1); CvMat *Wt = cvCreateMat(3, 3, CV_32FC1); cvSVD(E, D, U, Vt, CV_SVD_V_T); //cvSetReal2D(D, 1,1,cvGetReal2D(D,0,0)); //cvMatMul(U, D, E); //cvMatMul(E, Vt, E); //cvSVD(E, D, U, Vt, CV_SVD_V_T); cvSetReal2D(W, 0, 0, 0); cvSetReal2D(W, 0, 1, -1); cvSetReal2D(W, 0, 2, 0); cvSetReal2D(W, 1, 0, 1); cvSetReal2D(W, 1, 1, 0); cvSetReal2D(W, 1, 2, 0); cvSetReal2D(W, 2, 0, 0); cvSetReal2D(W, 2, 1, 0); cvSetReal2D(W, 2, 2, 1); cvTranspose(W, Wt); CvMat *P0 = cvCreateMat(3, 4, CV_32FC1); cvSetIdentity(P0); P = *cvCreateMat(3, 4, CV_32FC1); CvMat *P1 = cvCreateMat(3, 4, CV_32FC1); CvMat *P2 = cvCreateMat(3, 4, CV_32FC1); CvMat *P3 = cvCreateMat(3, 4, CV_32FC1); CvMat *P4 = cvCreateMat(3, 4, CV_32FC1); CvMat *R1 = cvCreateMat(3, 3, CV_32FC1); CvMat *R2 = cvCreateMat(3, 3, CV_32FC1); CvMat *t1 = cvCreateMat(3, 1, CV_32FC1); CvMat *t2 = cvCreateMat(3, 1, CV_32FC1); CvMat *temp33 = cvCreateMat(3, 3, CV_32FC1); cvMatMul(U, W, temp33); cvMatMul(temp33, Vt, R1); cvMatMul(U, Wt, temp33); cvMatMul(temp33, Vt, R2); cvSetReal2D(t1, 0, 0, cvGetReal2D(U,0,2)); cvSetReal2D(t1, 1, 0, cvGetReal2D(U,1,2)); cvSetReal2D(t1, 2, 0, cvGetReal2D(U,2,2)); ScalarMul(t1, -1, t2); SetSubMat(P1, 0, 0, R1); SetSubMat(P1, 0, 3, t1); SetSubMat(P2, 0, 0, R1); SetSubMat(P2, 0, 3, t2); SetSubMat(P3, 0, 0, R2); SetSubMat(P3, 0, 3, t1); SetSubMat(P4, 0, 0, R2); SetSubMat(P4, 0, 3, t2); if (cvDet(R1) < 0) { ScalarMul(P1, -1, P1); ScalarMul(P2, -1, P2); } if (cvDet(R2) < 0) { ScalarMul(P3, -1, P3); ScalarMul(P4, -1, P4); } CvMat X1; LinearTriangulation(x1, P0, x2, P1, X1); CvMat X2; LinearTriangulation(x1, P0, x2, P2, X2); CvMat X3; LinearTriangulation(x1, P0, x2, P3, X3); CvMat X4; LinearTriangulation(x1, P0, x2, P4, X4); int x1neg = 0, x2neg = 0, x3neg = 0, x4neg = 0; CvMat *H1 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH1 = cvCreateMat(4, 4, CV_32FC1); CvMat HX1; cvSetIdentity(H1); SetSubMat(H1, 0, 0, P1); cvInvert(H1, invH1); Pxx_inhomo(H1, &X1, HX1); CvMat *H2 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH2 = cvCreateMat(4, 4, CV_32FC1); CvMat HX2; cvSetIdentity(H2); SetSubMat(H2, 0, 0, P2); cvInvert(H2, invH2); Pxx_inhomo(H2, &X2, HX2); CvMat *H3 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH3 = cvCreateMat(4, 4, CV_32FC1); CvMat HX3; cvSetIdentity(H3); SetSubMat(H3, 0, 0, P3); cvInvert(H3, invH3); Pxx_inhomo(H3, &X3, HX3); CvMat *H4 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH4 = cvCreateMat(4, 4, CV_32FC1); CvMat HX4; cvSetIdentity(H4); SetSubMat(H4, 0, 0, P4); cvInvert(H4, invH4); Pxx_inhomo(H4, &X4, HX4); for (int ix = 0; ix < x1->rows; ix++) { if ((cvGetReal2D(&X1, ix, 2)<0) || (cvGetReal2D(&HX1, ix, 2)<0)) x1neg++; if ((cvGetReal2D(&X2, ix, 2)<0) || (cvGetReal2D(&HX2, ix, 2)<0)) x2neg++; if ((cvGetReal2D(&X3, ix, 2)<0) || (cvGetReal2D(&HX3, ix, 2)<0)) x3neg++; if ((cvGetReal2D(&X4, ix, 2)<0) || (cvGetReal2D(&HX4, ix, 2)<0)) x4neg++; } CvMat *temp34 = cvCreateMat(3, 4, CV_32FC1); if ((x1neg <= x2neg) && (x1neg <= x3neg) && (x1neg <= x4neg)) P = *cvCloneMat(P1); else if ((x2neg <= x1neg) && (x2neg <= x3neg) && (x2neg <= x4neg)) P = *cvCloneMat(P2); else if ((x3neg <= x1neg) && (x3neg <= x2neg) && (x3neg <= x4neg)) P = *cvCloneMat(P3); else P = *cvCloneMat(P4); cvReleaseMat(&W); cvReleaseMat(&U); cvReleaseMat(&D); cvReleaseMat(&Vt); cvReleaseMat(&Wt); cvReleaseMat(&P0); cvReleaseMat(&P1); cvReleaseMat(&P2); cvReleaseMat(&P3); cvReleaseMat(&P4); cvReleaseMat(&R1); cvReleaseMat(&R2); cvReleaseMat(&t1); cvReleaseMat(&t2); cvReleaseMat(&temp33); cvReleaseMat(&temp34); cvReleaseMat(&H1); cvReleaseMat(&invH1); cvReleaseMat(&H2); cvReleaseMat(&invH2); cvReleaseMat(&H3); cvReleaseMat(&invH3); cvReleaseMat(&H4); cvReleaseMat(&invH4); } void GetExtrinsicParameterFromE(CvMat *E, CvMat *x1, CvMat *x2, CvMat *P) { CvMat *W = cvCreateMat(3, 3, CV_32FC1); CvMat *U = cvCreateMat(3, 3, CV_32FC1); CvMat *D = cvCreateMat(3, 3, CV_32FC1); CvMat *Vt = cvCreateMat(3, 3, CV_32FC1); CvMat *Wt = cvCreateMat(3, 3, CV_32FC1); cvSVD(E, D, U, Vt, CV_SVD_V_T); //cvSetReal2D(D, 1,1,cvGetReal2D(D,0,0)); //cvMatMul(U, D, E); //cvMatMul(E, Vt, E); //cvSVD(E, D, U, Vt, CV_SVD_V_T); cvSetReal2D(W, 0, 0, 0); cvSetReal2D(W, 0, 1, -1); cvSetReal2D(W, 0, 2, 0); cvSetReal2D(W, 1, 0, 1); cvSetReal2D(W, 1, 1, 0); cvSetReal2D(W, 1, 2, 0); cvSetReal2D(W, 2, 0, 0); cvSetReal2D(W, 2, 1, 0); cvSetReal2D(W, 2, 2, 1); cvTranspose(W, Wt); CvMat *P0 = cvCreateMat(3, 4, CV_32FC1); cvSetIdentity(P0); CvMat *P1 = cvCreateMat(3, 4, CV_32FC1); CvMat *P2 = cvCreateMat(3, 4, CV_32FC1); CvMat *P3 = cvCreateMat(3, 4, CV_32FC1); CvMat *P4 = cvCreateMat(3, 4, CV_32FC1); CvMat *R1 = cvCreateMat(3, 3, CV_32FC1); CvMat *R2 = cvCreateMat(3, 3, CV_32FC1); CvMat *t1 = cvCreateMat(3, 1, CV_32FC1); CvMat *t2 = cvCreateMat(3, 1, CV_32FC1); CvMat *temp33 = cvCreateMat(3, 3, CV_32FC1); cvMatMul(U, W, temp33); cvMatMul(temp33, Vt, R1); cvMatMul(U, Wt, temp33); cvMatMul(temp33, Vt, R2); cvSetReal2D(t1, 0, 0, cvGetReal2D(U,0,2)); cvSetReal2D(t1, 1, 0, cvGetReal2D(U,1,2)); cvSetReal2D(t1, 2, 0, cvGetReal2D(U,2,2)); ScalarMul(t1, -1, t2); SetSubMat(P1, 0, 0, R1); SetSubMat(P1, 0, 3, t1); SetSubMat(P2, 0, 0, R1); SetSubMat(P2, 0, 3, t2); SetSubMat(P3, 0, 0, R2); SetSubMat(P3, 0, 3, t1); SetSubMat(P4, 0, 0, R2); SetSubMat(P4, 0, 3, t2); if (cvDet(R1) < 0) { ScalarMul(P1, -1, P1); ScalarMul(P2, -1, P2); } if (cvDet(R2) < 0) { ScalarMul(P3, -1, P3); ScalarMul(P4, -1, P4); } CvMat *X1 = cvCreateMat(x1->rows, 3, CV_32FC1); LinearTriangulation(x1, P0, x2, P1, X1); CvMat *X2 = cvCreateMat(x1->rows, 3, CV_32FC1);; LinearTriangulation(x1, P0, x2, P2, X2); CvMat *X3 = cvCreateMat(x1->rows, 3, CV_32FC1);; LinearTriangulation(x1, P0, x2, P3, X3); CvMat *X4 = cvCreateMat(x1->rows, 3, CV_32FC1);; LinearTriangulation(x1, P0, x2, P4, X4); int x1neg = 0, x2neg = 0, x3neg = 0, x4neg = 0; CvMat *H1 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH1 = cvCreateMat(4, 4, CV_32FC1); CvMat *HX1 = cvCreateMat(X1->rows, X1->cols, CV_32FC1); cvSetIdentity(H1); SetSubMat(H1, 0, 0, P1); cvInvert(H1, invH1); Pxx_inhomo(H1, X1, HX1); CvMat *H2 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH2 = cvCreateMat(4, 4, CV_32FC1); CvMat *HX2 = cvCreateMat(X1->rows, X1->cols, CV_32FC1); cvSetIdentity(H2); SetSubMat(H2, 0, 0, P2); cvInvert(H2, invH2); Pxx_inhomo(H2, X2, HX2); CvMat *H3 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH3 = cvCreateMat(4, 4, CV_32FC1); CvMat *HX3 = cvCreateMat(X1->rows, X1->cols, CV_32FC1); cvSetIdentity(H3); SetSubMat(H3, 0, 0, P3); cvInvert(H3, invH3); Pxx_inhomo(H3, X3, HX3); CvMat *H4 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH4 = cvCreateMat(4, 4, CV_32FC1); CvMat *HX4 = cvCreateMat(X1->rows, X1->cols, CV_32FC1); cvSetIdentity(H4); SetSubMat(H4, 0, 0, P4); cvInvert(H4, invH4); Pxx_inhomo(H4, X4, HX4); for (int ix = 0; ix < x1->rows; ix++) { if ((cvGetReal2D(X1, ix, 2)<0) || (cvGetReal2D(HX1, ix, 2)<0)) x1neg++; if ((cvGetReal2D(X2, ix, 2)<0) || (cvGetReal2D(HX2, ix, 2)<0)) x2neg++; if ((cvGetReal2D(X3, ix, 2)<0) || (cvGetReal2D(HX3, ix, 2)<0)) x3neg++; if ((cvGetReal2D(X4, ix, 2)<0) || (cvGetReal2D(HX4, ix, 2)<0)) x4neg++; } CvMat *temp34 = cvCreateMat(3, 4, CV_32FC1); if ((x1neg <= x2neg) && (x1neg <= x3neg) && (x1neg <= x4neg)) SetSubMat(P, 0, 0, P1); else if ((x2neg <= x1neg) && (x2neg <= x3neg) && (x2neg <= x4neg)) SetSubMat(P, 0, 0, P2); else if ((x3neg <= x1neg) && (x3neg <= x2neg) && (x3neg <= x4neg)) SetSubMat(P, 0, 0, P3); else SetSubMat(P, 0, 0, P4); //cout << x1neg << " " << x2neg << " " << " " << x3neg << " " << x4neg << endl; cvReleaseMat(&W); cvReleaseMat(&U); cvReleaseMat(&D); cvReleaseMat(&Vt); cvReleaseMat(&Wt); cvReleaseMat(&P0); cvReleaseMat(&P1); cvReleaseMat(&P2); cvReleaseMat(&P3); cvReleaseMat(&P4); cvReleaseMat(&R1); cvReleaseMat(&R2); cvReleaseMat(&t1); cvReleaseMat(&t2); cvReleaseMat(&temp33); cvReleaseMat(&temp34); cvReleaseMat(&H1); cvReleaseMat(&invH1); cvReleaseMat(&H2); cvReleaseMat(&invH2); cvReleaseMat(&H3); cvReleaseMat(&invH3); cvReleaseMat(&H4); cvReleaseMat(&invH4); cvReleaseMat(&X1); cvReleaseMat(&X2); cvReleaseMat(&X3); cvReleaseMat(&X4); cvReleaseMat(&HX1); cvReleaseMat(&HX2); cvReleaseMat(&HX3); cvReleaseMat(&HX4); } void LinearTriangulation(CvMat *x1, CvMat *P1, CvMat *x2, CvMat *P2, CvMat &X) { X = *cvCreateMat(x1->rows, 3, CV_32FC1); cvSetZero(&X); for (int ix = 0; ix < x1->rows; ix++) { CvMat *A = cvCreateMat(4, 4, CV_32FC1); CvMat *A1 = cvCreateMat(1, 4, CV_32FC1); CvMat *A2 = cvCreateMat(1, 4, CV_32FC1); CvMat *A3 = cvCreateMat(1, 4, CV_32FC1); CvMat *A4 = cvCreateMat(1, 4, CV_32FC1); CvMat *P1_1 = cvCreateMat(1, 4, CV_32FC1); CvMat *P1_2 = cvCreateMat(1, 4, CV_32FC1); CvMat *P1_3 = cvCreateMat(1, 4, CV_32FC1); CvMat *P2_1 = cvCreateMat(1, 4, CV_32FC1); CvMat *P2_2 = cvCreateMat(1, 4, CV_32FC1); CvMat *P2_3 = cvCreateMat(1, 4, CV_32FC1); CvMat *temp14_1 = cvCreateMat(1, 4, CV_32FC1); GetSubMatRowwise(P1, 0, 0, P1_1); GetSubMatRowwise(P1, 1, 1, P1_2); GetSubMatRowwise(P1, 2, 2, P1_3); GetSubMatRowwise(P2, 0, 0, P2_1); GetSubMatRowwise(P2, 1, 1, P2_2); GetSubMatRowwise(P2, 2, 2, P2_3); ScalarMul(P1_3, cvGetReal2D(x1, ix, 0), temp14_1); cvSub(temp14_1, P1_1, A1); ScalarMul(P1_3, cvGetReal2D(x1, ix, 1), temp14_1); cvSub(temp14_1, P1_2, A2); ScalarMul(P2_3, cvGetReal2D(x2, ix, 0), temp14_1); cvSub(temp14_1, P2_1, A3); ScalarMul(P2_3, cvGetReal2D(x2, ix, 1), temp14_1); cvSub(temp14_1, P2_2, A4); SetSubMat(A, 0, 0, A1); SetSubMat(A, 1, 0, A2); SetSubMat(A, 2, 0, A3); SetSubMat(A, 3, 0, A4); CvMat x; LS_homogeneous(A, x); double v = cvGetReal2D(&x, 3, 0); cvSetReal2D(&X, ix, 0, cvGetReal2D(&x, 0, 0)/v); cvSetReal2D(&X, ix, 1, cvGetReal2D(&x, 1, 0)/v); cvSetReal2D(&X, ix, 2, cvGetReal2D(&x, 2, 0)/v); cvReleaseMat(&A); cvReleaseMat(&A1); cvReleaseMat(&A2); cvReleaseMat(&A3); cvReleaseMat(&A4); cvReleaseMat(&P1_1); cvReleaseMat(&P1_2); cvReleaseMat(&P1_3); cvReleaseMat(&P2_1); cvReleaseMat(&P2_2); cvReleaseMat(&P2_3); cvReleaseMat(&temp14_1); } } void LinearTriangulation(CvMat *x1, CvMat *P1, CvMat *x2, CvMat *P2, CvMat *X) { for (int ix = 0; ix < x1->rows; ix++) { CvMat *A = cvCreateMat(4, 4, CV_32FC1); CvMat *A1 = cvCreateMat(1, 4, CV_32FC1); CvMat *A2 = cvCreateMat(1, 4, CV_32FC1); CvMat *A3 = cvCreateMat(1, 4, CV_32FC1); CvMat *A4 = cvCreateMat(1, 4, CV_32FC1); CvMat *P1_1 = cvCreateMat(1, 4, CV_32FC1); CvMat *P1_2 = cvCreateMat(1, 4, CV_32FC1); CvMat *P1_3 = cvCreateMat(1, 4, CV_32FC1); CvMat *P2_1 = cvCreateMat(1, 4, CV_32FC1); CvMat *P2_2 = cvCreateMat(1, 4, CV_32FC1); CvMat *P2_3 = cvCreateMat(1, 4, CV_32FC1); CvMat *temp14_1 = cvCreateMat(1, 4, CV_32FC1); GetSubMatRowwise(P1, 0, 0, P1_1); GetSubMatRowwise(P1, 1, 1, P1_2); GetSubMatRowwise(P1, 2, 2, P1_3); GetSubMatRowwise(P2, 0, 0, P2_1); GetSubMatRowwise(P2, 1, 1, P2_2); GetSubMatRowwise(P2, 2, 2, P2_3); ScalarMul(P1_3, cvGetReal2D(x1, ix, 0), temp14_1); cvSub(temp14_1, P1_1, A1); ScalarMul(P1_3, cvGetReal2D(x1, ix, 1), temp14_1); cvSub(temp14_1, P1_2, A2); ScalarMul(P2_3, cvGetReal2D(x2, ix, 0), temp14_1); cvSub(temp14_1, P2_1, A3); ScalarMul(P2_3, cvGetReal2D(x2, ix, 1), temp14_1); cvSub(temp14_1, P2_2, A4); SetSubMat(A, 0, 0, A1); SetSubMat(A, 1, 0, A2); SetSubMat(A, 2, 0, A3); SetSubMat(A, 3, 0, A4); CvMat *x = cvCreateMat(A->cols, 1, CV_32FC1); LS_homogeneous(A, x); double v = cvGetReal2D(x, 3, 0); cvSetReal2D(X, ix, 0, cvGetReal2D(x, 0, 0)/v); cvSetReal2D(X, ix, 1, cvGetReal2D(x, 1, 0)/v); cvSetReal2D(X, ix, 2, cvGetReal2D(x, 2, 0)/v); cvReleaseMat(&A); cvReleaseMat(&A1); cvReleaseMat(&A2); cvReleaseMat(&A3); cvReleaseMat(&A4); cvReleaseMat(&P1_1); cvReleaseMat(&P1_2); cvReleaseMat(&P1_3); cvReleaseMat(&P2_1); cvReleaseMat(&P2_2); cvReleaseMat(&P2_3); cvReleaseMat(&temp14_1); cvReleaseMat(&x); } } int LinearTriangulation(CvMat *x1, CvMat *P1, CvMat *x2, CvMat *P2, vector<int> featureID, CvMat &X, vector<int> &filteredFeatureID) { //X = *cvCreateMat(x1->rows, 3, CV_32FC1); //cvSetZero(&X); vector<double> X1, X2, X3; filteredFeatureID.clear(); for (int ix = 0; ix < x1->rows; ix++) { CvMat *A = cvCreateMat(4, 4, CV_32FC1); CvMat *A1 = cvCreateMat(1, 4, CV_32FC1); CvMat *A2 = cvCreateMat(1, 4, CV_32FC1); CvMat *A3 = cvCreateMat(1, 4, CV_32FC1); CvMat *A4 = cvCreateMat(1, 4, CV_32FC1); CvMat *P1_1 = cvCreateMat(1, 4, CV_32FC1); CvMat *P1_2 = cvCreateMat(1, 4, CV_32FC1); CvMat *P1_3 = cvCreateMat(1, 4, CV_32FC1); CvMat *P2_1 = cvCreateMat(1, 4, CV_32FC1); CvMat *P2_2 = cvCreateMat(1, 4, CV_32FC1); CvMat *P2_3 = cvCreateMat(1, 4, CV_32FC1); CvMat *temp14_1 = cvCreateMat(1, 4, CV_32FC1); GetSubMatRowwise(P1, 0, 0, P1_1); GetSubMatRowwise(P1, 1, 1, P1_2); GetSubMatRowwise(P1, 2, 2, P1_3); GetSubMatRowwise(P2, 0, 0, P2_1); GetSubMatRowwise(P2, 1, 1, P2_2); GetSubMatRowwise(P2, 2, 2, P2_3); ScalarMul(P1_3, cvGetReal2D(x1, ix, 0), temp14_1); cvSub(temp14_1, P1_1, A1); ScalarMul(P1_3, cvGetReal2D(x1, ix, 1), temp14_1); cvSub(temp14_1, P1_2, A2); ScalarMul(P2_3, cvGetReal2D(x2, ix, 0), temp14_1); cvSub(temp14_1, P2_1, A3); ScalarMul(P2_3, cvGetReal2D(x2, ix, 1), temp14_1); cvSub(temp14_1, P2_2, A4); SetSubMat(A, 0, 0, A1); SetSubMat(A, 1, 0, A2); SetSubMat(A, 2, 0, A3); SetSubMat(A, 3, 0, A4); CvMat x; LS_homogeneous(A, x); double v = cvGetReal2D(&x, 3, 0); //cout << v << " " << abs(v)<< endl; if (abs(v) < POINT_AT_INFINITY_ZERO) continue; X1.push_back(cvGetReal2D(&x, 0, 0)/v); X2.push_back(cvGetReal2D(&x, 1, 0)/v); X3.push_back(cvGetReal2D(&x, 2, 0)/v); filteredFeatureID.push_back(featureID[ix]); cvReleaseMat(&A); cvReleaseMat(&A1); cvReleaseMat(&A2); cvReleaseMat(&A3); cvReleaseMat(&A4); cvReleaseMat(&P1_1); cvReleaseMat(&P1_2); cvReleaseMat(&P1_3); cvReleaseMat(&P2_1); cvReleaseMat(&P2_2); cvReleaseMat(&P2_3); cvReleaseMat(&temp14_1); } if (X1.size() == 0) return 0; X = *cvCreateMat(X1.size(), 3, CV_32FC1); for (int i = 0; i < X1.size(); i++) { cvSetReal2D(&X, i, 0, X1[i]); cvSetReal2D(&X, i, 1, X2[i]); cvSetReal2D(&X, i, 2, X3[i]); } return 1; } int LinearTriangulation_mem(CvMat *x1, CvMat *P1, CvMat *x2, CvMat *P2, vector<int> featureID, vector<vector<double> > &X, vector<int> &filteredFeatureID) { vector<double> X1, X2, X3; filteredFeatureID.clear(); for (int ix = 0; ix < x1->rows; ix++) { CvMat *A = cvCreateMat(4, 4, CV_32FC1); CvMat *A1 = cvCreateMat(1, 4, CV_32FC1); CvMat *A2 = cvCreateMat(1, 4, CV_32FC1); CvMat *A3 = cvCreateMat(1, 4, CV_32FC1); CvMat *A4 = cvCreateMat(1, 4, CV_32FC1); CvMat *P1_1 = cvCreateMat(1, 4, CV_32FC1); CvMat *P1_2 = cvCreateMat(1, 4, CV_32FC1); CvMat *P1_3 = cvCreateMat(1, 4, CV_32FC1); CvMat *P2_1 = cvCreateMat(1, 4, CV_32FC1); CvMat *P2_2 = cvCreateMat(1, 4, CV_32FC1); CvMat *P2_3 = cvCreateMat(1, 4, CV_32FC1); CvMat *temp14_1 = cvCreateMat(1, 4, CV_32FC1); GetSubMatRowwise(P1, 0, 0, P1_1); GetSubMatRowwise(P1, 1, 1, P1_2); GetSubMatRowwise(P1, 2, 2, P1_3); GetSubMatRowwise(P2, 0, 0, P2_1); GetSubMatRowwise(P2, 1, 1, P2_2); GetSubMatRowwise(P2, 2, 2, P2_3); ScalarMul(P1_3, cvGetReal2D(x1, ix, 0), temp14_1); cvSub(temp14_1, P1_1, A1); ScalarMul(P1_3, cvGetReal2D(x1, ix, 1), temp14_1); cvSub(temp14_1, P1_2, A2); ScalarMul(P2_3, cvGetReal2D(x2, ix, 0), temp14_1); cvSub(temp14_1, P2_1, A3); ScalarMul(P2_3, cvGetReal2D(x2, ix, 1), temp14_1); cvSub(temp14_1, P2_2, A4); SetSubMat(A, 0, 0, A1); SetSubMat(A, 1, 0, A2); SetSubMat(A, 2, 0, A3); SetSubMat(A, 3, 0, A4); CvMat *x = cvCreateMat(A->cols, 1, CV_32FC1); LS_homogeneous(A, x); double v = cvGetReal2D(x, 3, 0); if (abs(v) < POINT_AT_INFINITY_ZERO) { cvReleaseMat(&A); cvReleaseMat(&A1); cvReleaseMat(&A2); cvReleaseMat(&A3); cvReleaseMat(&A4); cvReleaseMat(&P1_1); cvReleaseMat(&P1_2); cvReleaseMat(&P1_3); cvReleaseMat(&P2_1); cvReleaseMat(&P2_2); cvReleaseMat(&P2_3); cvReleaseMat(&temp14_1); cvReleaseMat(&x); continue; } X1.push_back(cvGetReal2D(x, 0, 0)/v); X2.push_back(cvGetReal2D(x, 1, 0)/v); X3.push_back(cvGetReal2D(x, 2, 0)/v); filteredFeatureID.push_back(featureID[ix]); cvReleaseMat(&A); cvReleaseMat(&A1); cvReleaseMat(&A2); cvReleaseMat(&A3); cvReleaseMat(&A4); cvReleaseMat(&P1_1); cvReleaseMat(&P1_2); cvReleaseMat(&P1_3); cvReleaseMat(&P2_1); cvReleaseMat(&P2_2); cvReleaseMat(&P2_3); cvReleaseMat(&temp14_1); cvReleaseMat(&x); } if (X1.size() == 0) return 0; for (int i = 0; i < X1.size(); i++) { vector<double> X_vec; X_vec.push_back(X1[i]); X_vec.push_back(X2[i]); X_vec.push_back(X3[i]); X.push_back(X_vec); } return X.size(); } int LinearTriangulation_mem_fast(CvMat *x1, CvMat *P1, CvMat *x2, CvMat *P2, vector<int> &featureID, vector<vector<double> > &X, vector<int> &filteredFeatureID) { filteredFeatureID.clear(); CvMat *A = cvCreateMat(4, 4, CV_32FC1); CvMat *A1 = cvCreateMat(1, 4, CV_32FC1); CvMat *A2 = cvCreateMat(1, 4, CV_32FC1); CvMat *A3 = cvCreateMat(1, 4, CV_32FC1); CvMat *A4 = cvCreateMat(1, 4, CV_32FC1); CvMat *P1_1 = cvCreateMat(1, 4, CV_32FC1); CvMat *P1_2 = cvCreateMat(1, 4, CV_32FC1); CvMat *P1_3 = cvCreateMat(1, 4, CV_32FC1); CvMat *P2_1 = cvCreateMat(1, 4, CV_32FC1); CvMat *P2_2 = cvCreateMat(1, 4, CV_32FC1); CvMat *P2_3 = cvCreateMat(1, 4, CV_32FC1); CvMat *temp14_1 = cvCreateMat(1, 4, CV_32FC1); CvMat *x = cvCreateMat(A->cols, 1, CV_32FC1); for (int ix = 0; ix < x1->rows; ix++) { GetSubMatRowwise(P1, 0, 0, P1_1); GetSubMatRowwise(P1, 1, 1, P1_2); GetSubMatRowwise(P1, 2, 2, P1_3); GetSubMatRowwise(P2, 0, 0, P2_1); GetSubMatRowwise(P2, 1, 1, P2_2); GetSubMatRowwise(P2, 2, 2, P2_3); ScalarMul(P1_3, cvGetReal2D(x1, ix, 0), temp14_1); cvSub(temp14_1, P1_1, A1); ScalarMul(P1_3, cvGetReal2D(x1, ix, 1), temp14_1); cvSub(temp14_1, P1_2, A2); ScalarMul(P2_3, cvGetReal2D(x2, ix, 0), temp14_1); cvSub(temp14_1, P2_1, A3); ScalarMul(P2_3, cvGetReal2D(x2, ix, 1), temp14_1); cvSub(temp14_1, P2_2, A4); SetSubMat(A, 0, 0, A1); SetSubMat(A, 1, 0, A2); SetSubMat(A, 2, 0, A3); SetSubMat(A, 3, 0, A4); LS_homogeneous(A, x); double v = cvGetReal2D(x, 3, 0); if (abs(v) < POINT_AT_INFINITY_ZERO) { continue; } vector<double> X_vec; X_vec.push_back(cvGetReal2D(x, 0, 0)/v); X_vec.push_back(cvGetReal2D(x, 1, 0)/v); X_vec.push_back(cvGetReal2D(x, 2, 0)/v); X.push_back(X_vec); filteredFeatureID.push_back(featureID[ix]); } cvReleaseMat(&A); cvReleaseMat(&A1); cvReleaseMat(&A2); cvReleaseMat(&A3); cvReleaseMat(&A4); cvReleaseMat(&P1_1); cvReleaseMat(&P1_2); cvReleaseMat(&P1_3); cvReleaseMat(&P2_1); cvReleaseMat(&P2_2); cvReleaseMat(&P2_3); cvReleaseMat(&temp14_1); cvReleaseMat(&x); if (filteredFeatureID.size() == 0) return 0; return X.size(); } bool LinearTriangulation(vector<CvMat *> vP, vector<double> vx, vector<double> vy, double &X, double &Y, double &Z) { if (vP.size() < 2) return false; CvMat *A = cvCreateMat(2*vP.size(), 4, CV_32FC1); CvMat *A1 = cvCreateMat(1, 4, CV_32FC1); CvMat *A2 = cvCreateMat(1, 4, CV_32FC1); CvMat *P_1 = cvCreateMat(1, 4, CV_32FC1); CvMat *P_2 = cvCreateMat(1, 4, CV_32FC1); CvMat *P_3 = cvCreateMat(1, 4, CV_32FC1); CvMat *temp14_1 = cvCreateMat(1, 4, CV_32FC1); CvMat *x = cvCreateMat(A->cols, 1, CV_32FC1); for (int iP = 0; iP < vP.size(); iP++) { GetSubMatRowwise(vP[iP], 0, 0, P_1); GetSubMatRowwise(vP[iP], 1, 1, P_2); GetSubMatRowwise(vP[iP], 2, 2, P_3); ScalarMul(P_3, vx[iP], temp14_1); cvSub(temp14_1, P_1, A1); ScalarMul(P_3, vy[iP], temp14_1); cvSub(temp14_1, P_2, A2); SetSubMat(A, 2*iP, 0, A1); SetSubMat(A, 2*iP+1, 0, A2); } LS_homogeneous(A, x); CvMat *Ax = cvCreateMat(A->rows, 1, CV_32FC1); cvMatMul(A, x, Ax); //PrintMat(Ax); double v = cvGetReal2D(x, 3, 0); if (abs(v) < POINT_AT_INFINITY_ZERO) { return false; } X = cvGetReal2D(x, 0, 0)/v; Y = cvGetReal2D(x, 1, 0)/v; Z = cvGetReal2D(x, 2, 0)/v; cvReleaseMat(&A); cvReleaseMat(&A1); cvReleaseMat(&A2); cvReleaseMat(&P_1); cvReleaseMat(&P_2); cvReleaseMat(&P_3); cvReleaseMat(&temp14_1); cvReleaseMat(&x); return true; } int DLT_ExtrinsicCameraParamEstimation(CvMat *X, CvMat *x, CvMat *K, CvMat *P) { if (X->rows < 6) return 0; CvMat *Xtilde = cvCreateMat(X->rows, 3, CV_32FC1); CvMat *xtilde = cvCreateMat(x->rows, 2, CV_32FC1); CvMat *U = cvCreateMat(4,4, CV_32FC1); CvMat *T = cvCreateMat(3,3, CV_32FC1); Normalization3D(X, Xtilde, U); Normalization(x, xtilde, T); CvMat *A = cvCreateMat(X->rows*2,12,CV_32FC1); for (int iX = 0; iX < X->rows; iX++) { CvMat *A1 = cvCreateMat(1, 12, CV_32FC1); CvMat *A2 = cvCreateMat(1, 12, CV_32FC1); cvSetZero(A1); cvSetZero(A2); CvMat *A1_2 = cvCreateMat(1, 4, CV_32FC1); CvMat *A1_3 = cvCreateMat(1, 4, CV_32FC1); CvMat *A2_1 = cvCreateMat(1, 4, CV_32FC1); CvMat *A2_3 = cvCreateMat(1, 4, CV_32FC1); // A1_2 cvSetReal2D(A1_2, 0, 0, -cvGetReal2D(Xtilde, iX, 0)); cvSetReal2D(A1_2, 0, 1, -cvGetReal2D(Xtilde, iX, 1)); cvSetReal2D(A1_2, 0, 2, -cvGetReal2D(Xtilde, iX, 2)); cvSetReal2D(A1_2, 0, 3, -1); // A1_3 cvSetReal2D(A1_3, 0, 0, cvGetReal2D(xtilde, iX, 1)*cvGetReal2D(Xtilde, iX, 0)); cvSetReal2D(A1_3, 0, 1, cvGetReal2D(xtilde, iX, 1)*cvGetReal2D(Xtilde, iX, 1)); cvSetReal2D(A1_3, 0, 2, cvGetReal2D(xtilde, iX, 1)*cvGetReal2D(Xtilde, iX, 2)); cvSetReal2D(A1_3, 0, 3, cvGetReal2D(xtilde, iX, 1)); // A2_1 cvSetReal2D(A2_1, 0, 0, cvGetReal2D(Xtilde, iX, 0)); cvSetReal2D(A2_1, 0, 1, cvGetReal2D(Xtilde, iX, 1)); cvSetReal2D(A2_1, 0, 2, cvGetReal2D(Xtilde, iX, 2)); cvSetReal2D(A2_1, 0, 3, 1); // A1_3 cvSetReal2D(A2_3, 0, 0, -cvGetReal2D(xtilde, iX, 0)*cvGetReal2D(Xtilde, iX, 0)); cvSetReal2D(A2_3, 0, 1, -cvGetReal2D(xtilde, iX, 0)*cvGetReal2D(Xtilde, iX, 1)); cvSetReal2D(A2_3, 0, 2, -cvGetReal2D(xtilde, iX, 0)*cvGetReal2D(Xtilde, iX, 2)); cvSetReal2D(A2_3, 0, 3, -cvGetReal2D(xtilde, iX, 0)); SetSubMat(A1, 0, 4, A1_2); SetSubMat(A1, 0, 8, A1_3); SetSubMat(A2, 0, 0, A2_1); SetSubMat(A2, 0, 8, A2_3); SetSubMat(A, 2*iX, 0, A1); SetSubMat(A, 2*iX+1, 0, A2); cvReleaseMat(&A1); cvReleaseMat(&A2); cvReleaseMat(&A1_2); cvReleaseMat(&A1_3); cvReleaseMat(&A2_1); cvReleaseMat(&A2_3); } CvMat *p = cvCreateMat(A->cols, 1, CV_32FC1); LS_homogeneous(A, p); cvSetReal2D(P, 0, 0, cvGetReal2D(p, 0, 0)); cvSetReal2D(P, 0, 1, cvGetReal2D(p, 1, 0)); cvSetReal2D(P, 0, 2, cvGetReal2D(p, 2, 0)); cvSetReal2D(P, 0, 3, cvGetReal2D(p, 3, 0)); cvSetReal2D(P, 1, 0, cvGetReal2D(p, 4, 0)); cvSetReal2D(P, 1, 1, cvGetReal2D(p, 5, 0)); cvSetReal2D(P, 1, 2, cvGetReal2D(p, 6, 0)); cvSetReal2D(P, 1, 3, cvGetReal2D(p, 7, 0)); cvSetReal2D(P, 2, 0, cvGetReal2D(p, 8, 0)); cvSetReal2D(P, 2, 1, cvGetReal2D(p, 9, 0)); cvSetReal2D(P, 2, 2, cvGetReal2D(p, 10, 0)); cvSetReal2D(P, 2, 3, cvGetReal2D(p, 11, 0)); CvMat *temp34 = cvCreateMat(3,4,CV_32FC1); CvMat *invT = cvCreateMat(3,3,CV_32FC1); cvInvert(T, invT); cvMatMul(invT, P, temp34); cvMatMul(temp34, U, P); CvMat *P_ = cvCreateMat(3,4, CV_32FC1); CvMat *invK = cvCreateMat(3,3,CV_32FC1); cvInvert(K, invK); cvMatMul(invK, P, P_); CvMat *P1 = cvCreateMat(3,1,CV_32FC1); GetSubMatColwise(P_, 0, 0, P1); CvMat *R = cvCreateMat(3,3,CV_32FC1); GetSubMatColwise(P_, 0, 2, R); double norm = NormL2(P1); double determinant = cvDet(R); double sign = 1; if (determinant < 0) sign = -1; ScalarMul(P_,sign/norm, P); cvMatMul(K, P, P); cvReleaseMat(&temp34); cvReleaseMat(&invT); cvReleaseMat(&P_); cvReleaseMat(&invK); cvReleaseMat(&P1); cvReleaseMat(&R); cvReleaseMat(&Xtilde); cvReleaseMat(&xtilde); cvReleaseMat(&U); cvReleaseMat(&T); cvReleaseMat(&A); cvReleaseMat(&p); return 1; } int EPNP_ExtrinsicCameraParamEstimation(CvMat *X, CvMat *x, CvMat *K, CvMat *P) { epnp PnP; PnP.set_internal_parameters(cvGetReal2D(K, 0, 2), cvGetReal2D(K, 1, 2), cvGetReal2D(K, 0, 0), cvGetReal2D(K, 1, 1)); PnP.set_maximum_number_of_correspondences(X->rows); PnP.reset_correspondences(); for(int i = 0; i < X->rows; i++) { PnP.add_correspondence(cvGetReal2D(X, i, 0), cvGetReal2D(X, i, 1), cvGetReal2D(X, i, 2), cvGetReal2D(x, i, 0), cvGetReal2D(x, i, 1)); } double R_est[3][3], t_est[3]; double err2 = PnP.compute_pose(R_est, t_est); cvSetReal2D(P, 0, 3, t_est[0]); cvSetReal2D(P, 1, 3, t_est[1]); cvSetReal2D(P, 2, 3, t_est[2]); cvSetReal2D(P, 0, 0, R_est[0][0]); cvSetReal2D(P, 0, 1, R_est[0][1]); cvSetReal2D(P, 0, 2, R_est[0][2]); cvSetReal2D(P, 1, 0, R_est[1][0]); cvSetReal2D(P, 1, 1, R_est[1][1]); cvSetReal2D(P, 1, 2, R_est[1][2]); cvSetReal2D(P, 2, 0, R_est[2][0]); cvSetReal2D(P, 2, 1, R_est[2][1]); cvSetReal2D(P, 2, 2, R_est[2][2]); cvMatMul(K, P, P); return 1; } int DLT_ExtrinsicCameraParamEstimation_KRT(CvMat *X, CvMat *x, CvMat *K, CvMat *P) { if (X->rows < 6) return 0; CvMat *Xtilde = cvCreateMat(X->rows, 3, CV_32FC1); CvMat *xtilde = cvCreateMat(x->rows, 2, CV_32FC1); CvMat *U = cvCreateMat(4,4, CV_32FC1); CvMat *T = cvCreateMat(3,3, CV_32FC1); Normalization3D(X, Xtilde, U); Normalization(x, xtilde, T); CvMat *A = cvCreateMat(X->rows*2,12,CV_32FC1); for (int iX = 0; iX < X->rows; iX++) { CvMat *A1 = cvCreateMat(1, 12, CV_32FC1); CvMat *A2 = cvCreateMat(1, 12, CV_32FC1); cvSetZero(A1); cvSetZero(A2); CvMat *A1_2 = cvCreateMat(1, 4, CV_32FC1); CvMat *A1_3 = cvCreateMat(1, 4, CV_32FC1); CvMat *A2_1 = cvCreateMat(1, 4, CV_32FC1); CvMat *A2_3 = cvCreateMat(1, 4, CV_32FC1); // A1_2 cvSetReal2D(A1_2, 0, 0, -cvGetReal2D(Xtilde, iX, 0)); cvSetReal2D(A1_2, 0, 1, -cvGetReal2D(Xtilde, iX, 1)); cvSetReal2D(A1_2, 0, 2, -cvGetReal2D(Xtilde, iX, 2)); cvSetReal2D(A1_2, 0, 3, -1); // A1_3 cvSetReal2D(A1_3, 0, 0, cvGetReal2D(xtilde, iX, 1)*cvGetReal2D(Xtilde, iX, 0)); cvSetReal2D(A1_3, 0, 1, cvGetReal2D(xtilde, iX, 1)*cvGetReal2D(Xtilde, iX, 1)); cvSetReal2D(A1_3, 0, 2, cvGetReal2D(xtilde, iX, 1)*cvGetReal2D(Xtilde, iX, 2)); cvSetReal2D(A1_3, 0, 3, cvGetReal2D(xtilde, iX, 1)); // A2_1 cvSetReal2D(A2_1, 0, 0, cvGetReal2D(Xtilde, iX, 0)); cvSetReal2D(A2_1, 0, 1, cvGetReal2D(Xtilde, iX, 1)); cvSetReal2D(A2_1, 0, 2, cvGetReal2D(Xtilde, iX, 2)); cvSetReal2D(A2_1, 0, 3, 1); // A1_3 cvSetReal2D(A2_3, 0, 0, -cvGetReal2D(xtilde, iX, 0)*cvGetReal2D(Xtilde, iX, 0)); cvSetReal2D(A2_3, 0, 1, -cvGetReal2D(xtilde, iX, 0)*cvGetReal2D(Xtilde, iX, 1)); cvSetReal2D(A2_3, 0, 2, -cvGetReal2D(xtilde, iX, 0)*cvGetReal2D(Xtilde, iX, 2)); cvSetReal2D(A2_3, 0, 3, -cvGetReal2D(xtilde, iX, 0)); SetSubMat(A1, 0, 4, A1_2); SetSubMat(A1, 0, 8, A1_3); SetSubMat(A2, 0, 0, A2_1); SetSubMat(A2, 0, 8, A2_3); SetSubMat(A, 2*iX, 0, A1); SetSubMat(A, 2*iX+1, 0, A2); cvReleaseMat(&A1); cvReleaseMat(&A2); cvReleaseMat(&A1_2); cvReleaseMat(&A1_3); cvReleaseMat(&A2_1); cvReleaseMat(&A2_3); } CvMat *p = cvCreateMat(A->cols, 1, CV_32FC1); LS_homogeneous(A, p); cvSetReal2D(P, 0, 0, cvGetReal2D(p, 0, 0)); cvSetReal2D(P, 0, 1, cvGetReal2D(p, 1, 0)); cvSetReal2D(P, 0, 2, cvGetReal2D(p, 2, 0)); cvSetReal2D(P, 0, 3, cvGetReal2D(p, 3, 0)); cvSetReal2D(P, 1, 0, cvGetReal2D(p, 4, 0)); cvSetReal2D(P, 1, 1, cvGetReal2D(p, 5, 0)); cvSetReal2D(P, 1, 2, cvGetReal2D(p, 6, 0)); cvSetReal2D(P, 1, 3, cvGetReal2D(p, 7, 0)); cvSetReal2D(P, 2, 0, cvGetReal2D(p, 8, 0)); cvSetReal2D(P, 2, 1, cvGetReal2D(p, 9, 0)); cvSetReal2D(P, 2, 2, cvGetReal2D(p, 10, 0)); cvSetReal2D(P, 2, 3, cvGetReal2D(p, 11, 0)); //for (int i = 0; i < X->rows; i++) //{ // CvMat *tX = cvCreateMat(4,1,CV_32FC1); // cvSetReal2D(tX, 0, 0, cvGetReal2D(Xtilde, i, 0)); // cvSetReal2D(tX, 1, 0, cvGetReal2D(Xtilde, i, 1)); // cvSetReal2D(tX, 2, 0, cvGetReal2D(Xtilde, i, 2)); // cvSetReal2D(tX, 3, 0, 1); // CvMat *tx = cvCreateMat(3,1, CV_32FC1); // cvMatMul(P, tX, tx); // ScalarMul(tx, 1/cvGetReal2D(tx, 2, 0), tx); // PrintMat(tx, "tx"); // CvMat *ttx = cvCreateMat(2,1,CV_32FC1); // cvSetReal2D(ttx, 0, 0, cvGetReal2D(xtilde, i, 0)); // cvSetReal2D(ttx, 1, 0, cvGetReal2D(xtilde, i, 1)); // PrintMat(ttx, "ttx"); //} CvMat *temp34 = cvCreateMat(3,4,CV_32FC1); CvMat *invT = cvCreateMat(3,3,CV_32FC1); cvInvert(T, invT); cvMatMul(invT, P, temp34); cvMatMul(temp34, U, P); ScalarMul(P, 1/cvGetReal2D(P, 2, 3), P); CvMat *R = cvCreateMat(3,3, CV_32FC1); CvMat *C = cvCreateMat(4,1, CV_32FC1); //ScalarMul(P, -1, P); cvDecomposeProjectionMatrix(P, K, R, C); //cout << "det " << cvDet(R) << endl; //PrintMat(C, "C"); //CvMat *P_ = cvCreateMat(3,4, CV_32FC1); //CvMat *invK = cvCreateMat(3,3,CV_32FC1); //cvInvert(K, invK); //cvMatMul(invK, P, P_); //CvMat *P1 = cvCreateMat(3,1,CV_32FC1); //GetSubMatColwise(P_, 0, 0, P1); //CvMat *R = cvCreateMat(3,3,CV_32FC1); //GetSubMatColwise(P_, 0, 2, R); //double norm = NormL2(P1); //double determinant = cvDet(R); //double sign = 1; //if (determinant < 0) // sign = -1; //ScalarMul(P_,sign/norm, P); //cvMatMul(K, P, P); cvReleaseMat(&temp34); cvReleaseMat(&invT); //cvReleaseMat(&P_); //cvReleaseMat(&invK); //cvReleaseMat(&P1); cvReleaseMat(&R); cvReleaseMat(&Xtilde); cvReleaseMat(&xtilde); cvReleaseMat(&U); cvReleaseMat(&T); cvReleaseMat(&A); cvReleaseMat(&p); cvReleaseMat(&C); return 1; } int DLT_ExtrinsicCameraParamEstimationWRansac(CvMat *X, CvMat *x, CvMat *K, CvMat &P, double ransacThreshold, int ransacMaxIter) { int min_set = 5; if (X->rows < min_set) return 0; ///////////////////////////////////////////////////////////////// // Ransac vector<int> vInlierIndex, vOutlierIndex; vInlierIndex.clear(); vOutlierIndex.clear(); vector<int> vInlier, vOutlier; int maxInlier = 0; CvMat *X_homoT = cvCreateMat(4, X->rows, CV_32FC1); CvMat *X_homo = cvCreateMat(X->rows, 4, CV_32FC1); CvMat *x_homoT = cvCreateMat(3, x->rows, CV_32FC1); CvMat *x_homo = cvCreateMat(x->rows, 3, CV_32FC1); Inhomo2Homo(X, X_homo); cvTranspose(X_homo, X_homoT); Inhomo2Homo(x, x_homo); cvTranspose(x_homo, x_homoT); int nIter = 0; for (int iRansacIter = 0; iRansacIter < ransacMaxIter; iRansacIter++) { nIter++; if (nIter > 1e+4) return 0; int *randIdx = (int *) malloc(min_set * sizeof(int)); for (int iIdx = 0; iIdx < min_set; iIdx++) randIdx[iIdx] = rand()%X->rows; CvMat *randx = cvCreateMat(min_set, 2, CV_32FC1); CvMat *randX = cvCreateMat(min_set, 3, CV_32FC1); CvMat *randP = cvCreateMat(3,4,CV_32FC1); for (int iIdx = 0; iIdx < min_set; iIdx++) { cvSetReal2D(randx, iIdx, 0, cvGetReal2D(x, randIdx[iIdx], 0)); cvSetReal2D(randx, iIdx, 1, cvGetReal2D(x, randIdx[iIdx], 1)); cvSetReal2D(randX, iIdx, 0, cvGetReal2D(X, randIdx[iIdx], 0)); cvSetReal2D(randX, iIdx, 1, cvGetReal2D(X, randIdx[iIdx], 1)); cvSetReal2D(randX, iIdx, 2, cvGetReal2D(X, randIdx[iIdx], 2)); } free(randIdx); DLT_ExtrinsicCameraParamEstimation(randX, randx, K, randP); CvMat *H = cvCreateMat(4, 4, CV_32FC1); CvMat *HX = cvCreateMat(randX->rows, randX->cols, CV_32FC1); cvSetIdentity(H); SetSubMat(H, 0, 0, randP); Pxx_inhomo(H, randX, HX); bool isFront = true; for (int i = 0; i < min_set; i++) { if (cvGetReal2D(HX, i, 2) < 0) isFront = false; } cvReleaseMat(&H); cvReleaseMat(&HX); if (!isFront) { cvReleaseMat(&randx); cvReleaseMat(&randX); cvReleaseMat(&randP); iRansacIter--; continue; } vInlier.clear(); vOutlier.clear(); for (int ip = 0; ip < X->rows; ip++) { CvMat *reproj = cvCreateMat(3,1,CV_32FC1); CvMat *homo_X = cvCreateMat(4,1,CV_32FC1); cvSetReal2D(homo_X, 0, 0, cvGetReal2D(X, ip, 0)); cvSetReal2D(homo_X, 1, 0, cvGetReal2D(X, ip, 1)); cvSetReal2D(homo_X, 2, 0, cvGetReal2D(X, ip, 2)); cvSetReal2D(homo_X, 3, 0, 1); cvMatMul(randP, homo_X, reproj); double u = cvGetReal2D(reproj, 0, 0)/cvGetReal2D(reproj, 2, 0); double v = cvGetReal2D(reproj, 1, 0)/cvGetReal2D(reproj, 2, 0); //if ((ip == randIdx[0]) || (ip == randIdx[1]) || (ip == randIdx[2]) || (ip == randIdx[3])) // cout << cvGetReal2D(x, ip, 0) << " " << u << " " << cvGetReal2D(x, ip, 1) << " " << v << endl; double dist = (u-cvGetReal2D(x, ip, 0))*(u-cvGetReal2D(x, ip, 0))+(v-cvGetReal2D(x, ip, 1))*(v-cvGetReal2D(x, ip, 1)); if (dist < ransacThreshold) { vInlier.push_back(ip); } else { vOutlier.push_back(ip); } cvReleaseMat(&reproj); cvReleaseMat(&homo_X); } // Distance function //CvMat *x_ = cvCreateMat(3, X->rows, CV_32FC1); //CvMat *e = cvCreateMat(3, X->rows, CV_32FC1); //cvMatMul(randP, X_homoT, x_); //NormalizingByRow(x_, 2); //cvSub(x_homoT, x_, e); //for (int ie = 0; ie < e->cols; ie++) //{ // CvMat *ei = cvCreateMat(3,1,CV_32FC1); // CvMat *xi = cvCreateMat(3,1, CV_32FC1); // GetSubMatColwise(x_homoT, ie, ie, xi); // GetSubMatColwise(e, ie, ie, ei); // double norm = NormL2(ei); // double denorm = NormL2(xi); // double d = norm; // if (d < ransacThreshold) // vInlier.push_back(ie); // else // vOutlier.push_back(ie); // cvReleaseMat(&ei); // cvReleaseMat(&xi); //} //if (vInlier.size() > maxInlier) //{ // maxInlier = vInlier.size(); // P = *cvCloneMat(randP); // vInlierIndex = vInlier; // vOutlierIndex = vOutlier; //} //cvReleaseMat(&x_); //cvReleaseMat(&e); cvReleaseMat(&randx); cvReleaseMat(&randX); cvReleaseMat(&randP); } cvReleaseMat(&X_homoT); cvReleaseMat(&X_homo); cvReleaseMat(&x_homoT); cvReleaseMat(&X_homo); if (vInlierIndex.size() < min_set) return 0; cout << "Number of features to do DLT camera pose estimation: " << vInlierIndex.size() << endl; return 1; } int DLT_ExtrinsicCameraParamEstimationWRansac_EPNP(CvMat *X, CvMat *x, CvMat *K, CvMat &P, double ransacThreshold, int ransacMaxIter) { int min_set = 4; if (X->rows < min_set) return 0; ///////////////////////////////////////////////////////////////// // Ransac vector<int> vInlierIndex, vOutlierIndex; vInlierIndex.clear(); vOutlierIndex.clear(); vector<int> vInlier, vOutlier; int maxInlier = 0; CvMat *X_homoT = cvCreateMat(4, X->rows, CV_32FC1); CvMat *X_homo = cvCreateMat(X->rows, 4, CV_32FC1); CvMat *x_homoT = cvCreateMat(3, x->rows, CV_32FC1); CvMat *x_homo = cvCreateMat(x->rows, 3, CV_32FC1); Inhomo2Homo(X, X_homo); cvTranspose(X_homo, X_homoT); Inhomo2Homo(x, x_homo); cvTranspose(x_homo, x_homoT); for (int iRansacIter = 0; iRansacIter < ransacMaxIter; iRansacIter++) { int *randIdx = (int *) malloc(min_set * sizeof(int)); for (int iIdx = 0; iIdx < min_set; iIdx++) randIdx[iIdx] = rand()%X->rows; CvMat *randx = cvCreateMat(min_set, 2, CV_32FC1); CvMat *randX = cvCreateMat(min_set, 3, CV_32FC1); CvMat *randP = cvCreateMat(3,4,CV_32FC1); for (int iIdx = 0; iIdx < min_set; iIdx++) { cvSetReal2D(randx, iIdx, 0, cvGetReal2D(x, randIdx[iIdx], 0)); cvSetReal2D(randx, iIdx, 1, cvGetReal2D(x, randIdx[iIdx], 1)); cvSetReal2D(randX, iIdx, 0, cvGetReal2D(X, randIdx[iIdx], 0)); cvSetReal2D(randX, iIdx, 1, cvGetReal2D(X, randIdx[iIdx], 1)); cvSetReal2D(randX, iIdx, 2, cvGetReal2D(X, randIdx[iIdx], 2)); } //DLT_ExtrinsicCameraParamEstimation(randX, randx, K, randP); EPNP_ExtrinsicCameraParamEstimation(randX, randx, K, randP); vInlier.clear(); vOutlier.clear(); for (int ip = 0; ip < X->rows; ip++) { CvMat *reproj = cvCreateMat(3,1,CV_32FC1); CvMat *homo_X = cvCreateMat(4,1,CV_32FC1); cvSetReal2D(homo_X, 0, 0, cvGetReal2D(X, ip, 0)); cvSetReal2D(homo_X, 1, 0, cvGetReal2D(X, ip, 1)); cvSetReal2D(homo_X, 2, 0, cvGetReal2D(X, ip, 2)); cvSetReal2D(homo_X, 3, 0, 1); cvMatMul(randP, homo_X, reproj); double u = cvGetReal2D(reproj, 0, 0)/cvGetReal2D(reproj, 2, 0); double v = cvGetReal2D(reproj, 1, 0)/cvGetReal2D(reproj, 2, 0); //if ((ip == randIdx[0]) || (ip == randIdx[1]) || (ip == randIdx[2]) || (ip == randIdx[3])) // cout << cvGetReal2D(x, ip, 0) << " " << u << " " << cvGetReal2D(x, ip, 1) << " " << v << endl; double dist = (u-cvGetReal2D(x, ip, 0))*(u-cvGetReal2D(x, ip, 0))+(v-cvGetReal2D(x, ip, 1))*(v-cvGetReal2D(x, ip, 1)); if (dist < ransacThreshold) { vInlier.push_back(ip); } else { vOutlier.push_back(ip); } cvReleaseMat(&reproj); cvReleaseMat(&homo_X); } free(randIdx); if (vInlier.size() > maxInlier) { maxInlier = vInlier.size(); P = *cvCloneMat(randP); vInlierIndex = vInlier; vOutlierIndex = vOutlier; } cvReleaseMat(&randx); cvReleaseMat(&randX); cvReleaseMat(&randP); } cvReleaseMat(&X_homoT); cvReleaseMat(&X_homo); cvReleaseMat(&x_homoT); cvReleaseMat(&X_homo); if (vInlierIndex.size() < 20) return 0; cout << "Number of features to do DLT camera pose estimation: " << vInlierIndex.size() << endl; return 1; } int DLT_ExtrinsicCameraParamEstimationWRansac_EPNP_mem(CvMat *X, CvMat *x, CvMat *K, CvMat *P, double ransacThreshold, int ransacMaxIter) { int min_set = 4; if (X->rows < min_set) return 0; ///////////////////////////////////////////////////////////////// // Ransac vector<int> vInlierIndex, vOutlierIndex; vInlierIndex.clear(); vOutlierIndex.clear(); vector<int> vInlier, vOutlier; int maxInlier = 0; CvMat *X_homoT = cvCreateMat(4, X->rows, CV_32FC1); CvMat *X_homo = cvCreateMat(X->rows, 4, CV_32FC1); CvMat *x_homoT = cvCreateMat(3, x->rows, CV_32FC1); CvMat *x_homo = cvCreateMat(x->rows, 3, CV_32FC1); Inhomo2Homo(X, X_homo); cvTranspose(X_homo, X_homoT); Inhomo2Homo(x, x_homo); cvTranspose(x_homo, x_homoT); CvMat *randx = cvCreateMat(min_set, 2, CV_32FC1); CvMat *randX = cvCreateMat(min_set, 3, CV_32FC1); CvMat *randP = cvCreateMat(3,4,CV_32FC1); int *randIdx = (int *) malloc(min_set * sizeof(int)); CvMat *reproj = cvCreateMat(3,1,CV_32FC1); CvMat *homo_X = cvCreateMat(4,1,CV_32FC1); for (int iRansacIter = 0; iRansacIter < ransacMaxIter; iRansacIter++) { for (int iIdx = 0; iIdx < min_set; iIdx++) randIdx[iIdx] = rand()%X->rows; for (int iIdx = 0; iIdx < min_set; iIdx++) { cvSetReal2D(randx, iIdx, 0, cvGetReal2D(x, randIdx[iIdx], 0)); cvSetReal2D(randx, iIdx, 1, cvGetReal2D(x, randIdx[iIdx], 1)); cvSetReal2D(randX, iIdx, 0, cvGetReal2D(X, randIdx[iIdx], 0)); cvSetReal2D(randX, iIdx, 1, cvGetReal2D(X, randIdx[iIdx], 1)); cvSetReal2D(randX, iIdx, 2, cvGetReal2D(X, randIdx[iIdx], 2)); } EPNP_ExtrinsicCameraParamEstimation(randX, randx, K, randP); vInlier.clear(); vOutlier.clear(); for (int ip = 0; ip < X->rows; ip++) { cvSetReal2D(homo_X, 0, 0, cvGetReal2D(X, ip, 0)); cvSetReal2D(homo_X, 1, 0, cvGetReal2D(X, ip, 1)); cvSetReal2D(homo_X, 2, 0, cvGetReal2D(X, ip, 2)); cvSetReal2D(homo_X, 3, 0, 1); cvMatMul(randP, homo_X, reproj); double u = cvGetReal2D(reproj, 0, 0)/cvGetReal2D(reproj, 2, 0); double v = cvGetReal2D(reproj, 1, 0)/cvGetReal2D(reproj, 2, 0); double dist = sqrt((u-cvGetReal2D(x, ip, 0))*(u-cvGetReal2D(x, ip, 0))+(v-cvGetReal2D(x, ip, 1))*(v-cvGetReal2D(x, ip, 1))); if (dist < ransacThreshold) { vInlier.push_back(ip); } else { vOutlier.push_back(ip); } } if (vInlier.size() > maxInlier) { maxInlier = vInlier.size(); SetSubMat(P, 0, 0, randP); vInlierIndex = vInlier; vOutlierIndex = vOutlier; } if (vInlier.size() > X->rows * 0.8) { break; } } CvMat *Xin = cvCreateMat(vInlierIndex.size(), 3, CV_32FC1); CvMat *xin = cvCreateMat(vInlierIndex.size(), 2, CV_32FC1); for (int iInlier = 0; iInlier < vInlierIndex.size(); iInlier++) { cvSetReal2D(Xin, iInlier, 0, cvGetReal2D(X, vInlierIndex[iInlier], 0)); cvSetReal2D(Xin, iInlier, 1, cvGetReal2D(X, vInlierIndex[iInlier], 1)); cvSetReal2D(Xin, iInlier, 2, cvGetReal2D(X, vInlierIndex[iInlier], 2)); cvSetReal2D(xin, iInlier, 0, cvGetReal2D(x, vInlierIndex[iInlier], 0)); cvSetReal2D(xin, iInlier, 1, cvGetReal2D(x, vInlierIndex[iInlier], 1)); } EPNP_ExtrinsicCameraParamEstimation(Xin, xin, K, P); cvReleaseMat(&Xin); cvReleaseMat(&xin); cvReleaseMat(&reproj); cvReleaseMat(&homo_X); free(randIdx); cvReleaseMat(&randx); cvReleaseMat(&randX); cvReleaseMat(&randP); cvReleaseMat(&X_homoT); cvReleaseMat(&x_homo); cvReleaseMat(&x_homoT); cvReleaseMat(&X_homo); if (vInlierIndex.size() < 40) return 0; cout << "Number of features ePnP: " << vInlierIndex.size() << endl; return vInlierIndex.size(); } int DLT_ExtrinsicCameraParamEstimationWRansac_EPNP_mem_AD(CvMat *X, CvMat *x, CvMat *K, CvMat *P, double ransacThreshold, int ransacMaxIter, vector<int> &vInlier1) { int min_set = 4; if (X->rows < min_set) return 0; ///////////////////////////////////////////////////////////////// // Ransac vector<int> vInlierIndex, vOutlierIndex; vInlierIndex.clear(); vOutlierIndex.clear(); vector<int> vInlier, vOutlier; int maxInlier = 0; CvMat *X_homoT = cvCreateMat(4, X->rows, CV_32FC1); CvMat *X_homo = cvCreateMat(X->rows, 4, CV_32FC1); CvMat *x_homoT = cvCreateMat(3, x->rows, CV_32FC1); CvMat *x_homo = cvCreateMat(x->rows, 3, CV_32FC1); Inhomo2Homo(X, X_homo); cvTranspose(X_homo, X_homoT); Inhomo2Homo(x, x_homo); cvTranspose(x_homo, x_homoT); CvMat *randx = cvCreateMat(min_set, 2, CV_32FC1); CvMat *randX = cvCreateMat(min_set, 3, CV_32FC1); CvMat *randP = cvCreateMat(3,4,CV_32FC1); int *randIdx = (int *) malloc(min_set * sizeof(int)); CvMat *reproj = cvCreateMat(3,1,CV_32FC1); CvMat *homo_X = cvCreateMat(4,1,CV_32FC1); for (int iRansacIter = 0; iRansacIter < ransacMaxIter; iRansacIter++) { for (int iIdx = 0; iIdx < min_set; iIdx++) randIdx[iIdx] = rand()%X->rows; for (int iIdx = 0; iIdx < min_set; iIdx++) { cvSetReal2D(randx, iIdx, 0, cvGetReal2D(x, randIdx[iIdx], 0)); cvSetReal2D(randx, iIdx, 1, cvGetReal2D(x, randIdx[iIdx], 1)); cvSetReal2D(randX, iIdx, 0, cvGetReal2D(X, randIdx[iIdx], 0)); cvSetReal2D(randX, iIdx, 1, cvGetReal2D(X, randIdx[iIdx], 1)); cvSetReal2D(randX, iIdx, 2, cvGetReal2D(X, randIdx[iIdx], 2)); } EPNP_ExtrinsicCameraParamEstimation(randX, randx, K, randP); vInlier.clear(); vOutlier.clear(); for (int ip = 0; ip < X->rows; ip++) { cvSetReal2D(homo_X, 0, 0, cvGetReal2D(X, ip, 0)); cvSetReal2D(homo_X, 1, 0, cvGetReal2D(X, ip, 1)); cvSetReal2D(homo_X, 2, 0, cvGetReal2D(X, ip, 2)); cvSetReal2D(homo_X, 3, 0, 1); cvMatMul(randP, homo_X, reproj); double u = cvGetReal2D(reproj, 0, 0)/cvGetReal2D(reproj, 2, 0); double v = cvGetReal2D(reproj, 1, 0)/cvGetReal2D(reproj, 2, 0); double dist = sqrt((u-cvGetReal2D(x, ip, 0))*(u-cvGetReal2D(x, ip, 0))+(v-cvGetReal2D(x, ip, 1))*(v-cvGetReal2D(x, ip, 1))); if (dist < ransacThreshold) { vInlier.push_back(ip); } else { vOutlier.push_back(ip); } } if (vInlier.size() > maxInlier) { maxInlier = vInlier.size(); SetSubMat(P, 0, 0, randP); vInlierIndex = vInlier; vOutlierIndex = vOutlier; } if (vInlier.size() > X->rows * 0.8) { break; } } CvMat *Xin = cvCreateMat(vInlierIndex.size(), 3, CV_32FC1); CvMat *xin = cvCreateMat(vInlierIndex.size(), 2, CV_32FC1); for (int iInlier = 0; iInlier < vInlierIndex.size(); iInlier++) { cvSetReal2D(Xin, iInlier, 0, cvGetReal2D(X, vInlierIndex[iInlier], 0)); cvSetReal2D(Xin, iInlier, 1, cvGetReal2D(X, vInlierIndex[iInlier], 1)); cvSetReal2D(Xin, iInlier, 2, cvGetReal2D(X, vInlierIndex[iInlier], 2)); cvSetReal2D(xin, iInlier, 0, cvGetReal2D(x, vInlierIndex[iInlier], 0)); cvSetReal2D(xin, iInlier, 1, cvGetReal2D(x, vInlierIndex[iInlier], 1)); } EPNP_ExtrinsicCameraParamEstimation(Xin, xin, K, P); cvReleaseMat(&Xin); cvReleaseMat(&xin); cvReleaseMat(&reproj); cvReleaseMat(&homo_X); free(randIdx); cvReleaseMat(&randx); cvReleaseMat(&randX); cvReleaseMat(&randP); cvReleaseMat(&X_homoT); cvReleaseMat(&x_homo); cvReleaseMat(&x_homoT); cvReleaseMat(&X_homo); vInlier1 = vInlierIndex; if (vInlierIndex.size() < 40) return 0; cout << "Number of features ePnP: " << vInlierIndex.size() << endl; return vInlierIndex.size(); } int DLT_ExtrinsicCameraParamEstimationWRansac_EPNP_mem_abs(CvMat *X, CvMat *x, CvMat *K, CvMat *P, double ransacThreshold, int ransacMaxIter, vector<int> &vInlierIndex) { int min_set = 4; if (X->rows < min_set) return 0; ///////////////////////////////////////////////////////////////// // Ransac vector<int> vOutlierIndex; vInlierIndex.clear(); vOutlierIndex.clear(); vector<int> vInlier, vOutlier; int maxInlier = 0; CvMat *X_homoT = cvCreateMat(4, X->rows, CV_32FC1); CvMat *X_homo = cvCreateMat(X->rows, 4, CV_32FC1); CvMat *x_homoT = cvCreateMat(3, x->rows, CV_32FC1); CvMat *x_homo = cvCreateMat(x->rows, 3, CV_32FC1); Inhomo2Homo(X, X_homo); cvTranspose(X_homo, X_homoT); Inhomo2Homo(x, x_homo); cvTranspose(x_homo, x_homoT); CvMat *randx = cvCreateMat(min_set, 2, CV_32FC1); CvMat *randX = cvCreateMat(min_set, 3, CV_32FC1); CvMat *randP = cvCreateMat(3,4,CV_32FC1); int *randIdx = (int *) malloc(min_set * sizeof(int)); CvMat *reproj = cvCreateMat(3,1,CV_32FC1); CvMat *homo_X = cvCreateMat(4,1,CV_32FC1); for (int iRansacIter = 0; iRansacIter < ransacMaxIter; iRansacIter++) { for (int iIdx = 0; iIdx < min_set; iIdx++) randIdx[iIdx] = rand()%X->rows; for (int iIdx = 0; iIdx < min_set; iIdx++) { cvSetReal2D(randx, iIdx, 0, cvGetReal2D(x, randIdx[iIdx], 0)); cvSetReal2D(randx, iIdx, 1, cvGetReal2D(x, randIdx[iIdx], 1)); cvSetReal2D(randX, iIdx, 0, cvGetReal2D(X, randIdx[iIdx], 0)); cvSetReal2D(randX, iIdx, 1, cvGetReal2D(X, randIdx[iIdx], 1)); cvSetReal2D(randX, iIdx, 2, cvGetReal2D(X, randIdx[iIdx], 2)); } EPNP_ExtrinsicCameraParamEstimation(randX, randx, K, randP); vInlier.clear(); vOutlier.clear(); for (int ip = 0; ip < X->rows; ip++) { cvSetReal2D(homo_X, 0, 0, cvGetReal2D(X, ip, 0)); cvSetReal2D(homo_X, 1, 0, cvGetReal2D(X, ip, 1)); cvSetReal2D(homo_X, 2, 0, cvGetReal2D(X, ip, 2)); cvSetReal2D(homo_X, 3, 0, 1); cvMatMul(randP, homo_X, reproj); double u = cvGetReal2D(reproj, 0, 0)/cvGetReal2D(reproj, 2, 0); double v = cvGetReal2D(reproj, 1, 0)/cvGetReal2D(reproj, 2, 0); double dist = sqrt((u-cvGetReal2D(x, ip, 0))*(u-cvGetReal2D(x, ip, 0))+(v-cvGetReal2D(x, ip, 1))*(v-cvGetReal2D(x, ip, 1))); if (dist < ransacThreshold) { vInlier.push_back(ip); } else { vOutlier.push_back(ip); } } if (vInlier.size() > maxInlier) { maxInlier = vInlier.size(); SetSubMat(P, 0, 0, randP); vInlierIndex = vInlier; vOutlierIndex = vOutlier; } //if (vInlier.size() > X->rows * 0.8) //{ // break; //} } CvMat *Xin = cvCreateMat(vInlierIndex.size(), 3, CV_32FC1); CvMat *xin = cvCreateMat(vInlierIndex.size(), 2, CV_32FC1); for (int iInlier = 0; iInlier < vInlierIndex.size(); iInlier++) { cvSetReal2D(Xin, iInlier, 0, cvGetReal2D(X, vInlierIndex[iInlier], 0)); cvSetReal2D(Xin, iInlier, 1, cvGetReal2D(X, vInlierIndex[iInlier], 1)); cvSetReal2D(Xin, iInlier, 2, cvGetReal2D(X, vInlierIndex[iInlier], 2)); cvSetReal2D(xin, iInlier, 0, cvGetReal2D(x, vInlierIndex[iInlier], 0)); cvSetReal2D(xin, iInlier, 1, cvGetReal2D(x, vInlierIndex[iInlier], 1)); } EPNP_ExtrinsicCameraParamEstimation(Xin, xin, K, P); cvReleaseMat(&Xin); cvReleaseMat(&xin); cvReleaseMat(&reproj); cvReleaseMat(&homo_X); free(randIdx); cvReleaseMat(&randx); cvReleaseMat(&randX); cvReleaseMat(&randP); cvReleaseMat(&X_homoT); cvReleaseMat(&x_homo); cvReleaseMat(&x_homoT); cvReleaseMat(&X_homo); //if (vInlierIndex.size() < 20) // return 0; cout << "Number of features to do ePNP camera pose estimation: " << vInlierIndex.size() << endl; return vInlierIndex.size(); } int DLT_ExtrinsicCameraParamEstimationWRansac_EPNP_face(CvMat *X, CvMat *x, CvMat *K, CvMat &P) { CvMat *P_ = cvCreateMat(3,4,CV_32FC1); EPNP_ExtrinsicCameraParamEstimation(X, x, K, P_); P = *cvCloneMat(P_); cvReleaseMat(&P_); return 1; } int DLT_ExtrinsicCameraParamEstimationWRansac_KRT(CvMat *X, CvMat *x, CvMat *K, CvMat &P, double ransacThreshold, int ransacMaxIter) { if (X->rows < 6) return 0; ///////////////////////////////////////////////////////////////// // Ransac vector<int> vInlierIndex, vOutlierIndex; vInlierIndex.clear(); vOutlierIndex.clear(); vector<int> vInlier, vOutlier; int maxInlier = 0; CvMat *X_homoT = cvCreateMat(4, X->rows, CV_32FC1); CvMat *X_homo = cvCreateMat(X->rows, 4, CV_32FC1); CvMat *x_homoT = cvCreateMat(3, x->rows, CV_32FC1); CvMat *x_homo = cvCreateMat(x->rows, 3, CV_32FC1); Inhomo2Homo(X, X_homo); cvTranspose(X_homo, X_homoT); Inhomo2Homo(x, x_homo); cvTranspose(x_homo, x_homoT); for (int iRansacIter = 0; iRansacIter < ransacMaxIter; iRansacIter++) { int *randIdx = (int *) malloc(6 * sizeof(int)); for (int iIdx = 0; iIdx < 6; iIdx++) randIdx[iIdx] = rand()%X->rows; CvMat *randx = cvCreateMat(6, 2, CV_32FC1); CvMat *randX = cvCreateMat(6, 3, CV_32FC1); CvMat *randP = cvCreateMat(3,4,CV_32FC1); for (int iIdx = 0; iIdx < 6; iIdx++) { cvSetReal2D(randx, iIdx, 0, cvGetReal2D(x, randIdx[iIdx], 0)); cvSetReal2D(randx, iIdx, 1, cvGetReal2D(x, randIdx[iIdx], 1)); cvSetReal2D(randX, iIdx, 0, cvGetReal2D(X, randIdx[iIdx], 0)); cvSetReal2D(randX, iIdx, 1, cvGetReal2D(X, randIdx[iIdx], 1)); cvSetReal2D(randX, iIdx, 2, cvGetReal2D(X, randIdx[iIdx], 2)); } free(randIdx); CvMat *K_ = cvCreateMat(3,3,CV_32FC1); DLT_ExtrinsicCameraParamEstimation_KRT(randX, randx, K_, randP); double k33 = cvGetReal2D(K_, 2, 2); ScalarMul(K_, 1/k33, K_); CvMat *H = cvCreateMat(4, 4, CV_32FC1); CvMat *HX = cvCreateMat(randX->rows, randX->cols, CV_32FC1); cvSetIdentity(H); SetSubMat(H, 0, 0, randP); Pxx_inhomo(H, randX, HX); bool isFront = true; for (int i = 0; i < 6; i++) { if (cvGetReal2D(HX, i, 2) < 0) isFront = false; } cvReleaseMat(&H); cvReleaseMat(&HX); if ((!isFront) || (cvGetReal2D(K, 0,0) < 0)) { cvReleaseMat(&randx); cvReleaseMat(&randX); cvReleaseMat(&randP); iRansacIter--; continue; } vInlier.clear(); vOutlier.clear(); // Distance function CvMat *x_ = cvCreateMat(3, X->rows, CV_32FC1); CvMat *e = cvCreateMat(3, X->rows, CV_32FC1); cvMatMul(randP, X_homoT, x_); NormalizingByRow(x_, 2); cvSub(x_homoT, x_, e); for (int ie = 0; ie < e->cols; ie++) { CvMat *ei = cvCreateMat(3,1,CV_32FC1); CvMat *xi = cvCreateMat(3,1, CV_32FC1); GetSubMatColwise(x_homoT, ie, ie, xi); GetSubMatColwise(e, ie, ie, ei); double norm = NormL2(ei); double denorm = NormL2(xi); double d = norm; if (d < ransacThreshold) vInlier.push_back(ie); else vOutlier.push_back(ie); cvReleaseMat(&ei); cvReleaseMat(&xi); } if (vInlier.size() > maxInlier) { maxInlier = vInlier.size(); P = *cvCloneMat(randP); K = cvCloneMat(K_); vInlierIndex = vInlier; vOutlierIndex = vOutlier; } cvReleaseMat(&x_); cvReleaseMat(&e); cvReleaseMat(&randx); cvReleaseMat(&randX); cvReleaseMat(&randP); cvReleaseMat(&K_); } cvReleaseMat(&X_homoT); cvReleaseMat(&X_homo); cvReleaseMat(&x_homoT); cvReleaseMat(&X_homo); if (vInlierIndex.size() < 10) return 0; cout << "Number of features to do DLT camera pose estimation: " << vInlierIndex.size() << endl; return 1; } int DLT_ExtrinsicCameraParamEstimation_KRT(CvMat *X, CvMat *x, CvMat *K, CvMat &P) { if (X->rows < 6) return 0; CvMat *P_ = cvCreateMat(3,4,CV_32FC1); DLT_ExtrinsicCameraParamEstimation_KRT(X, x, K, P_); P = *cvCloneMat(P_); return 1; } void SparseBundleAdjustment_MOT(vector<Feature> vFeature, vector<int> vUsedFrame, vector<CvMat *> &cP, CvMat *X, CvMat *K, vector<int> visibleStructureID) { //PrintAlgorithm("Sparse bundle adjustment motion only"); //vector<double> cameraParameter, feature2DParameter; //vector<char> vMask; //double *dCovFeatures = 0; //AdditionalData adata;// focal_x focal_y princ_x princ_y //double intrinsic[4]; //intrinsic[0] = cvGetReal2D(K, 0, 0); //intrinsic[1] = cvGetReal2D(K, 1, 1); //intrinsic[2] = cvGetReal2D(K, 0, 2); //intrinsic[3] = cvGetReal2D(K, 1, 2); //adata.intrinsic = intrinsic; //GetParameterForSBA(vFeature, vUsedFrame, cP, X, K, visibleStructureID, cameraParameter, feature2DParameter, vMask); //double nCameraParam = 7; //int nFeatures = vFeature.size(); //int nFrames = vUsedFrame.size(); //char *dVMask = (char *) malloc(vMask.size() * sizeof(char)); //double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double)); //double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double)); // //for (int i = 0; i < cameraParameter.size(); i++) // dCameraParameter[i] = cameraParameter[i]; //for (int i = 0; i < vMask.size(); i++) // dVMask[i] = vMask[i]; //for (int i = 0; i < feature2DParameter.size(); i++) // dFeature2DParameter[i] = feature2DParameter[i]; //adata.XYZ = &(dCameraParameter[7*vUsedFrame.size()]); //double opt[5]; //opt[0] = 1e-3; //opt[1] = 1e-12; //opt[2] = 1e-12; //opt[3] = 1e-12; //opt[4] = 0; //double info[12]; //sba_mot_levmar(visibleStructureID.size(), vUsedFrame.size(), 1, dVMask, dCameraParameter, 7, dFeature2DParameter, dCovFeatures, 2, Projection3Donto2D_MOT, NULL, &adata, // 1e+3, 0, opt, info); //PrintSBAInfo(info); //RetrieveParameterFromSBA(dCameraParameter, K, cP, X, visibleStructureID); //free(dVMask); //free(dFeature2DParameter); //free(dCameraParameter); } void SparseBundleAdjustment_MOTSTR(vector<Feature> vFeature, vector<int> vUsedFrame, vector<CvMat *> &cP, CvMat *X, CvMat *K, vector<int> visibleStructureID) { //PrintAlgorithm("Sparse bundle adjustment motion and structure"); //vector<double> cameraParameter, feature2DParameter; //vector<char> vMask; //double *dCovFeatures = 0; //AdditionalData adata;// focal_x focal_y princ_x princ_y //double intrinsic[4]; //intrinsic[0] = cvGetReal2D(K, 0, 0); //intrinsic[1] = cvGetReal2D(K, 1, 1); //intrinsic[2] = cvGetReal2D(K, 0, 2); //intrinsic[3] = cvGetReal2D(K, 1, 2); //adata.intrinsic = intrinsic; //GetParameterForSBA(vFeature, vUsedFrame, cP, X, K, visibleStructureID, cameraParameter, feature2DParameter, vMask); //int NZ = 0; //for (int i = 0; i < vMask.size(); i++) //{ // if (vMask[i]) // NZ++; //} //double nCameraParam = 7; //int nFeatures = vFeature.size(); //int nFrames = vUsedFrame.size(); //char *dVMask = (char *) malloc(vMask.size() * sizeof(char)); //double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double)); //double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double)); //for (int i = 0; i < cameraParameter.size(); i++) // dCameraParameter[i] = cameraParameter[i]; //for (int i = 0; i < vMask.size(); i++) // dVMask[i] = vMask[i]; //for (int i = 0; i < feature2DParameter.size(); i++) // dFeature2DParameter[i] = feature2DParameter[i]; //double opt[5]; //opt[0] = 1e-3; //opt[1] = 1e-5;//1e-12; //opt[2] = 1e-5;//1e-12; //opt[3] = 1e-5;//1e-12; //opt[4] = 0; //double info[12]; //sba_motstr_levmar(visibleStructureID.size(), 0, vUsedFrame.size(), 1, dVMask, dCameraParameter, nCameraParam, 3, dFeature2DParameter, dCovFeatures, 2, Projection3Donto2D_MOTSTR, NULL, &adata, // 1e+3, 0, opt, info); //PrintSBAInfo(info); //RetrieveParameterFromSBA(dCameraParameter, K, cP, X, visibleStructureID); //free(dVMask); //free(dFeature2DParameter); //free(dCameraParameter); } void SparseBundleAdjustment_MOTSTR(vector<Feature> vFeature, vector<int> vUsedFrame, vector<CvMat *> &cP, CvMat *X, vector<Camera> vCamera, vector<int> visibleStructureID) { PrintAlgorithm("Sparse bundle adjustment motion and structure"); vector<double> cameraParameter, feature2DParameter; vector<char> vMask; double *dCovFeatures = 0; AdditionalData adata;// focal_x focal_y princ_x princ_y for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) { double *intrinsic = (double *) malloc(4 * sizeof(double)); intrinsic[0] = cvGetReal2D(vCamera[iCamera].K, 0, 0); intrinsic[1] = cvGetReal2D(vCamera[iCamera].K, 1, 1); intrinsic[2] = cvGetReal2D(vCamera[iCamera].K, 0, 2); intrinsic[3] = cvGetReal2D(vCamera[iCamera].K, 1, 2); adata.vIntrinsic.push_back(intrinsic); } int max_nFrames = 0; for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) { for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++) { if (vCamera[iCamera].vTakenFrame[iFrame] > max_nFrames) max_nFrames = vCamera[iCamera].vTakenFrame[iFrame]; } } max_nFrames++; adata.max_nFrames = max_nFrames; adata.vUsedFrame = vUsedFrame; GetParameterForSBA(vFeature, vUsedFrame, cP, X, vCamera, max_nFrames, visibleStructureID, cameraParameter, feature2DParameter, vMask); int NZ = 0; for (int i = 0; i < vMask.size(); i++) { if (vMask[i]) NZ++; } double nCameraParam = 7; int nFeatures = vFeature.size(); int nFrames = vUsedFrame.size(); char *dVMask = (char *) malloc(vMask.size() * sizeof(char)); double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double)); double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double)); for (int i = 0; i < cameraParameter.size(); i++) dCameraParameter[i] = cameraParameter[i]; for (int i = 0; i < vMask.size(); i++) dVMask[i] = vMask[i]; for (int i = 0; i < feature2DParameter.size(); i++) dFeature2DParameter[i] = feature2DParameter[i]; double opt[5]; opt[0] = 1e-3; opt[1] = 1e-12; opt[2] = 1e-12; opt[3] = 1e-12; opt[4] = 0; double info[12]; sba_motstr_levmar(visibleStructureID.size(), 0, vUsedFrame.size(), 1, dVMask, dCameraParameter, nCameraParam, 3, dFeature2DParameter, dCovFeatures, 2, Projection3Donto2D_MOTSTR, NULL, &adata, 1e+3, 0, opt, info); PrintSBAInfo(info, feature2DParameter.size()/2); RetrieveParameterFromSBA(dCameraParameter, vCamera, cP, X, visibleStructureID, vUsedFrame, max_nFrames); cout << "kk" << endl; free(dVMask); free(dFeature2DParameter); free(dCameraParameter); free(dCovFeatures); cout << "kk" << endl; for (int i = 0; i < adata.vIntrinsic.size(); i++) { free(adata.vIntrinsic[i]); } cout << "kk" << endl; } void SparseBundleAdjustment_MOTSTR_mem(vector<Feature> vFeature, vector<int> vUsedFrame, vector<CvMat *> &cP, CvMat *X, vector<Camera> vCamera, vector<int> visibleStructureID) { PrintAlgorithm("Sparse bundle adjustment motion and structure"); vector<double> cameraParameter, feature2DParameter; vector<char> vMask; double *dCovFeatures = 0; AdditionalData adata;// focal_x focal_y princ_x princ_y for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) { double *intrinsic = (double *) malloc(4 * sizeof(double)); intrinsic[0] = cvGetReal2D(vCamera[iCamera].K, 0, 0); intrinsic[1] = cvGetReal2D(vCamera[iCamera].K, 1, 1); intrinsic[2] = cvGetReal2D(vCamera[iCamera].K, 0, 2); intrinsic[3] = cvGetReal2D(vCamera[iCamera].K, 1, 2); adata.vIntrinsic.push_back(intrinsic); } int max_nFrames = 0; for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) { for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++) { if (vCamera[iCamera].vTakenFrame[iFrame] > max_nFrames) max_nFrames = vCamera[iCamera].vTakenFrame[iFrame]; } } max_nFrames++; adata.max_nFrames = max_nFrames; adata.vUsedFrame = vUsedFrame; GetParameterForSBA(vFeature, vUsedFrame, cP, X, vCamera, max_nFrames, visibleStructureID, cameraParameter, feature2DParameter, vMask); int NZ = 0; for (int i = 0; i < vMask.size(); i++) { if (vMask[i]) NZ++; } double nCameraParam = 7; int nFeatures = vFeature.size(); int nFrames = vUsedFrame.size(); char *dVMask = (char *) malloc(vMask.size() * sizeof(char)); double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double)); double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double)); for (int i = 0; i < cameraParameter.size(); i++) dCameraParameter[i] = cameraParameter[i]; for (int i = 0; i < vMask.size(); i++) dVMask[i] = vMask[i]; for (int i = 0; i < feature2DParameter.size(); i++) dFeature2DParameter[i] = feature2DParameter[i]; double opt[5]; opt[0] = 1e-3; opt[1] = 1e-12; opt[2] = 1e-12; opt[3] = 1e-12; opt[4] = 0; double info[12]; PrintMat(cP[1]); sba_motstr_levmar(visibleStructureID.size(), 0, vUsedFrame.size(), 1, dVMask, dCameraParameter, nCameraParam, 3, dFeature2DParameter, dCovFeatures, 2, Projection3Donto2D_MOTSTR_fast, NULL, &adata, 1e+3, 0, opt, info); PrintSBAInfo(info, feature2DParameter.size()/2); RetrieveParameterFromSBA_mem(dCameraParameter, vCamera, cP, X, visibleStructureID, vUsedFrame, max_nFrames); PrintMat(cP[1]); cout << "----------------" << endl; free(dVMask); free(dFeature2DParameter); free(dCameraParameter); free(dCovFeatures); for (int i = 0; i < adata.vIntrinsic.size(); i++) { free(adata.vIntrinsic[i]); } adata.vIntrinsic.clear(); } void SparseBundleAdjustment_MOTSTR_mem_fast(vector<Feature> &vFeature, vector<int> vUsedFrame, vector<CvMat *> &cP, CvMat *X, vector<Camera> vCamera) { PrintAlgorithm("Sparse bundle adjustment motion and structure"); vector<int> visibleStructureID; for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { if (vFeature[iFeature].isRegistered) { visibleStructureID.push_back(vFeature[iFeature].id); } } vector<double> cameraParameter, feature2DParameter; vector<char> vMask; double *dCovFeatures = 0; AdditionalData adata;// focal_x focal_y princ_x princ_y for (int iFrame = 0; iFrame < vCamera[0].vTakenFrame.size(); iFrame++) { double *intrinsic = (double *) malloc(4 * sizeof(double)); intrinsic[0] = cvGetReal2D(vCamera[0].vK[iFrame], 0, 0); intrinsic[1] = cvGetReal2D(vCamera[0].vK[iFrame], 1, 1); intrinsic[2] = cvGetReal2D(vCamera[0].vK[iFrame], 0, 2); intrinsic[3] = cvGetReal2D(vCamera[0].vK[iFrame], 1, 2); adata.vIntrinsic.push_back(intrinsic); } int max_nFrames = 0; for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) { for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++) { if (vCamera[iCamera].vTakenFrame[iFrame] > max_nFrames) max_nFrames = vCamera[iCamera].vTakenFrame[iFrame]; } } max_nFrames++; adata.max_nFrames = max_nFrames; adata.vUsedFrame = vUsedFrame; GetParameterForSBA(vFeature, vUsedFrame, cP, X, vCamera, max_nFrames, visibleStructureID, cameraParameter, feature2DParameter, vMask); int NZ = 0; for (int i = 0; i < vMask.size(); i++) { if (vMask[i]) NZ++; } double nCameraParam = 7; int nFeatures = vFeature.size(); int nFrames = vUsedFrame.size(); char *dVMask = (char *) malloc(vMask.size() * sizeof(char)); double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double)); double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double)); for (int i = 0; i < cameraParameter.size(); i++) dCameraParameter[i] = cameraParameter[i]; for (int i = 0; i < vMask.size(); i++) dVMask[i] = vMask[i]; for (int i = 0; i < feature2DParameter.size(); i++) dFeature2DParameter[i] = feature2DParameter[i]; double opt[5]; opt[0] = 1e-3; opt[1] = 1e-12; opt[2] = 1e-12; opt[3] = 1e-12; opt[4] = 0; double info[12]; sba_motstr_levmar(visibleStructureID.size(), 0, vUsedFrame.size(), 1, dVMask, dCameraParameter, nCameraParam, 3, dFeature2DParameter, dCovFeatures, 2, Projection3Donto2D_MOTSTR_fast, NULL, &adata, 1e+2, 0, opt, info); PrintSBAInfo(info, feature2DParameter.size()/2); RetrieveParameterFromSBA_mem(dCameraParameter, vCamera, cP, X, visibleStructureID, vUsedFrame, max_nFrames); free(dVMask); free(dFeature2DParameter); free(dCameraParameter); free(dCovFeatures); for (int i = 0; i < adata.vIntrinsic.size(); i++) { free(adata.vIntrinsic[i]); } adata.vIntrinsic.clear(); } void SparseBundleAdjustment_MOTSTR_mem_fast_Distortion(vector<Feature> &vFeature, vector<int> vUsedFrame, vector<CvMat *> &cP, CvMat *X, vector<Camera> vCamera, double omega) { PrintAlgorithm("Sparse bundle adjustment motion and structure"); vector<int> visibleStructureID; for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { if (vFeature[iFeature].isRegistered) { visibleStructureID.push_back(vFeature[iFeature].id); } } vector<double> cameraParameter, feature2DParameter; vector<char> vMask; double *dCovFeatures = 0; AdditionalData adata;// focal_x focal_y princ_x princ_y for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) { double *intrinsic = (double *) malloc(6 * sizeof(double)); intrinsic[0] = cvGetReal2D(vCamera[iCamera].K, 0, 0); intrinsic[1] = cvGetReal2D(vCamera[iCamera].K, 1, 1); intrinsic[2] = cvGetReal2D(vCamera[iCamera].K, 0, 2); intrinsic[3] = cvGetReal2D(vCamera[iCamera].K, 1, 2); intrinsic[4] = omega; intrinsic[5] = 2*tan(omega/2); adata.vIntrinsic.push_back(intrinsic); } int max_nFrames = 0; for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) { for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++) { if (vCamera[iCamera].vTakenFrame[iFrame] > max_nFrames) max_nFrames = vCamera[iCamera].vTakenFrame[iFrame]; } } max_nFrames++; adata.max_nFrames = max_nFrames; adata.vUsedFrame = vUsedFrame; GetParameterForSBA_Distortion(vFeature, vUsedFrame, cP, X, vCamera, max_nFrames, visibleStructureID, cameraParameter, feature2DParameter, vMask); int NZ = 0; for (int i = 0; i < vMask.size(); i++) { if (vMask[i]) NZ++; } double nCameraParam = 7; int nFeatures = vFeature.size(); int nFrames = vUsedFrame.size(); char *dVMask = (char *) malloc(vMask.size() * sizeof(char)); double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double)); double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double)); for (int i = 0; i < cameraParameter.size(); i++) dCameraParameter[i] = cameraParameter[i]; for (int i = 0; i < vMask.size(); i++) dVMask[i] = vMask[i]; for (int i = 0; i < feature2DParameter.size(); i++) dFeature2DParameter[i] = feature2DParameter[i]; double opt[5]; opt[0] = 1e-3; opt[1] = 1e-12; opt[2] = 1e-12; opt[3] = 1e-12; opt[4] = 0; double info[12]; sba_motstr_levmar(visibleStructureID.size(), 0, vUsedFrame.size(), 1, dVMask, dCameraParameter, nCameraParam, 3, dFeature2DParameter, dCovFeatures, 2, Projection3Donto2D_MOTSTR_fast_Distortion, NULL, &adata, 1e+2, 0, opt, info); PrintSBAInfo(info, feature2DParameter.size()/2); RetrieveParameterFromSBA_mem(dCameraParameter, vCamera, cP, X, visibleStructureID, vUsedFrame, max_nFrames); free(dVMask); free(dFeature2DParameter); free(dCameraParameter); free(dCovFeatures); for (int i = 0; i < adata.vIntrinsic.size(); i++) { free(adata.vIntrinsic[i]); } adata.vIntrinsic.clear(); } void SparseBundleAdjustment_MOTSTR_mem_fast_Distortion_ObstacleDetection(vector<Feature> &vFeature, vector<int> vUsedFrame, vector<CvMat *> &cP, CvMat *X, vector<Camera> vCamera, double omega, double princ_x1, double princ_y1) { PrintAlgorithm("Sparse bundle adjustment motion and structure"); vector<int> visibleStructureID; for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { if (vFeature[iFeature].isRegistered) { visibleStructureID.push_back(vFeature[iFeature].id); } } vector<double> cameraParameter, feature2DParameter; vector<char> vMask; double *dCovFeatures = 0; AdditionalData adata;// focal_x focal_y princ_x princ_y for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) { double *intrinsic = (double *) malloc(8 * sizeof(double)); intrinsic[0] = cvGetReal2D(vCamera[iCamera].K, 0, 0); intrinsic[1] = cvGetReal2D(vCamera[iCamera].K, 1, 1); intrinsic[2] = cvGetReal2D(vCamera[iCamera].K, 0, 2); intrinsic[3] = cvGetReal2D(vCamera[iCamera].K, 1, 2); intrinsic[4] = omega; intrinsic[5] = 2*tan(omega/2); intrinsic[6] = princ_x1; intrinsic[7] = princ_y1; adata.vIntrinsic.push_back(intrinsic); } int max_nFrames = 0; for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) { for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++) { if (vCamera[iCamera].vTakenFrame[iFrame] > max_nFrames) max_nFrames = vCamera[iCamera].vTakenFrame[iFrame]; } } max_nFrames++; adata.max_nFrames = max_nFrames; adata.vUsedFrame = vUsedFrame; //cout << "OK" << endl; //for (int i = 0; i < cP.size(); i++) //{ // PrintMat(cP[i]); //} //for (int i = 0; i < visibleStructureID.size(); i++) //{ // cout << cvGetReal2D(X, visibleStructureID[i], 0) << " " <<cvGetReal2D(X, visibleStructureID[i], 1) << " " <<cvGetReal2D(X, visibleStructureID[i], 2) << " " << endl; //} GetParameterForSBA_Distortion(vFeature, vUsedFrame, cP, X, vCamera, max_nFrames, visibleStructureID, cameraParameter, feature2DParameter, vMask); cout << "OK" << endl; int NZ = 0; for (int i = 0; i < vMask.size(); i++) { if (vMask[i]) NZ++; } double nCameraParam = 7; int nFeatures = vFeature.size(); int nFrames = vUsedFrame.size(); char *dVMask = (char *) malloc(vMask.size() * sizeof(char)); double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double)); double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double)); for (int i = 0; i < cameraParameter.size(); i++) dCameraParameter[i] = cameraParameter[i]; for (int i = 0; i < vMask.size(); i++) dVMask[i] = vMask[i]; for (int i = 0; i < feature2DParameter.size(); i++) dFeature2DParameter[i] = feature2DParameter[i]; double opt[5]; opt[0] = 1e-3; opt[1] = 1e-12; opt[2] = 1e-12; opt[3] = 1e-12; opt[4] = 0; double info[12]; cout << "OK" << endl; sba_motstr_levmar(visibleStructureID.size(), 0, vUsedFrame.size(), 1, dVMask, dCameraParameter, nCameraParam, 3, dFeature2DParameter, dCovFeatures, 2, Projection3Donto2D_MOTSTR_fast_Distortion_ObstacleDetection, NULL, &adata, 1e+2, 0, opt, info); PrintSBAInfo(info, feature2DParameter.size()/2); RetrieveParameterFromSBA_mem(dCameraParameter, vCamera, cP, X, visibleStructureID, vUsedFrame, max_nFrames); free(dVMask); free(dFeature2DParameter); free(dCameraParameter); free(dCovFeatures); for (int i = 0; i < adata.vIntrinsic.size(); i++) { free(adata.vIntrinsic[i]); } adata.vIntrinsic.clear(); } void SparseBundleAdjustment_KMOTSTR(vector<Feature> vFeature, vector<int> vUsedFrame, vector<CvMat *> &cP, CvMat *X, vector<Camera> vCamera, vector<int> visibleStructureID) { PrintAlgorithm("Sparse bundle adjustment motion and structure"); vector<double> cameraParameter, feature2DParameter; vector<char> vMask; double *dCovFeatures = 0; AdditionalData adata;// focal_x focal_y princ_x princ_y //for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) //{ // double *intrinsic = (double *) malloc(4 * sizeof(double)); // intrinsic[0] = cvGetReal2D(vCamera[iCamera].K, 0, 0); // intrinsic[1] = cvGetReal2D(vCamera[iCamera].K, 1, 1); // intrinsic[2] = cvGetReal2D(vCamera[iCamera].K, 0, 2); // intrinsic[3] = cvGetReal2D(vCamera[iCamera].K, 1, 2); // adata.vIntrinsic.push_back(intrinsic); //} int max_nFrames = 0; for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) { for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++) { if (vCamera[iCamera].vTakenFrame[iFrame] > max_nFrames) max_nFrames = vCamera[iCamera].vTakenFrame[iFrame]; } } max_nFrames++; adata.max_nFrames = max_nFrames; adata.vUsedFrame = vUsedFrame; GetParameterForSBA_KRT(vFeature, vUsedFrame, cP, X, vCamera, max_nFrames, visibleStructureID, cameraParameter, feature2DParameter, vMask); int NZ = 0; for (int i = 0; i < vMask.size(); i++) { if (vMask[i]) NZ++; } double nCameraParam = 7+4; int nFeatures = visibleStructureID.size(); int nFrames = vUsedFrame.size(); char *dVMask = (char *) malloc(vMask.size() * sizeof(char)); double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double)); double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double)); for (int i = 0; i < cameraParameter.size(); i++) dCameraParameter[i] = cameraParameter[i]; for (int i = 0; i < vMask.size(); i++) { dVMask[i] = vMask[i]; } for (int i = 0; i < feature2DParameter.size(); i++) dFeature2DParameter[i] = feature2DParameter[i]; double opt[5]; opt[0] = 1e-3; opt[1] = 1e-12; opt[2] = 1e-12; opt[3] = 1e-12; opt[4] = 0; double info[12]; sba_motstr_levmar(visibleStructureID.size(), 0, vUsedFrame.size(), 1, dVMask, dCameraParameter, nCameraParam, 3, dFeature2DParameter, dCovFeatures, 2, Projection3Donto2D_KMOTSTR, NULL, &adata, 1e+3, 0, opt, info); PrintSBAInfo(info, feature2DParameter.size()/2); RetrieveParameterFromSBA_KRT(dCameraParameter, vCamera, cP, X, visibleStructureID, vUsedFrame, max_nFrames); free(dVMask); free(dFeature2DParameter); free(dCameraParameter); } void SparseBundleAdjustment_KMOTSTR_x(vector<Feature> vFeature, vector<int> vUsedFrame, vector<CvMat *> &cP, CvMat *X, vector<Camera> vCamera, vector<int> visibleStructureID) { PrintAlgorithm("Sparse bundle adjustment motion and structure"); vector<double> cameraParameter, feature2DParameter; vector<char> vMask; double *dCovFeatures = 0; AdditionalData adata;// focal_x focal_y princ_x princ_y //for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) //{ // double *intrinsic = (double *) malloc(4 * sizeof(double)); // intrinsic[0] = cvGetReal2D(vCamera[iCamera].K, 0, 0); // intrinsic[1] = cvGetReal2D(vCamera[iCamera].K, 1, 1); // intrinsic[2] = cvGetReal2D(vCamera[iCamera].K, 0, 2); // intrinsic[3] = cvGetReal2D(vCamera[iCamera].K, 1, 2); // adata.vIntrinsic.push_back(intrinsic); //} int max_nFrames = 0; for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) { for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++) { if (vCamera[iCamera].vTakenFrame[iFrame] > max_nFrames) max_nFrames = vCamera[iCamera].vTakenFrame[iFrame]; } } max_nFrames++; adata.max_nFrames = max_nFrames; adata.vUsedFrame = vUsedFrame; GetParameterForSBA_KRT(vFeature, vUsedFrame, cP, X, vCamera, max_nFrames, visibleStructureID, cameraParameter, feature2DParameter, vMask); int NZ = 0; for (int i = 0; i < vMask.size(); i++) { if (vMask[i]) NZ++; } double nCameraParam = 7+4; int nFeatures = visibleStructureID.size(); int nFrames = vUsedFrame.size(); char *dVMask = (char *) malloc(vMask.size() * sizeof(char)); double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double)); double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double)); for (int i = 0; i < cameraParameter.size(); i++) dCameraParameter[i] = cameraParameter[i]; for (int i = 0; i < vMask.size(); i++) { dVMask[i] = vMask[i]; } for (int i = 0; i < feature2DParameter.size(); i++) dFeature2DParameter[i] = feature2DParameter[i]; double opt[5]; opt[0] = 1e-3; opt[1] = 1e-12; opt[2] = 1e-12; opt[3] = 1e-12; opt[4] = 0; double info[12]; sba_motstr_levmar(visibleStructureID.size(), 0, vUsedFrame.size(), 1, dVMask, dCameraParameter, nCameraParam, 3, dFeature2DParameter, dCovFeatures, 2, Projection3Donto2D_KMOTSTR, NULL, &adata, 1e+3, 0, opt, info); PrintSBAInfo(info); RetrieveParameterFromSBA_KRT(dCameraParameter, vCamera, cP, X, visibleStructureID, vUsedFrame, max_nFrames); free(dVMask); free(dFeature2DParameter); free(dCameraParameter); } void SparseBundleAdjustment_KDMOTSTR(vector<Feature> vFeature, vector<int> vUsedFrame, vector<CvMat *> &cP, CvMat *X, vector<Camera> vCamera, vector<int> visibleStructureID) { PrintAlgorithm("Sparse bundle adjustment motion and structure"); vector<double> cameraParameter, feature2DParameter; vector<char> vMask; double *dCovFeatures = 0; AdditionalData adata;// focal_x focal_y princ_x princ_y int max_nFrames = 0; for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) { for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++) { if (vCamera[iCamera].vTakenFrame[iFrame] > max_nFrames) max_nFrames = vCamera[iCamera].vTakenFrame[iFrame]; } } max_nFrames++; adata.max_nFrames = max_nFrames; adata.vUsedFrame = vUsedFrame; GetParameterForSBA_KDRT(vFeature, vUsedFrame, cP, X, vCamera, max_nFrames, visibleStructureID, cameraParameter, feature2DParameter, vMask); int NZ = 0; for (int i = 0; i < vMask.size(); i++) { if (vMask[i]) NZ++; } double nCameraParam = 7+4+2; int nFeatures = vFeature.size(); int nFrames = vUsedFrame.size(); char *dVMask = (char *) malloc(vMask.size() * sizeof(char)); double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double)); double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double)); for (int i = 0; i < cameraParameter.size(); i++) dCameraParameter[i] = cameraParameter[i]; for (int i = 0; i < vMask.size(); i++) dVMask[i] = vMask[i]; for (int i = 0; i < feature2DParameter.size(); i++) dFeature2DParameter[i] = feature2DParameter[i]; double opt[5]; opt[0] = 1e-3; opt[1] = 1e-12; opt[2] = 1e-12; opt[3] = 1e-12; opt[4] = 0; double info[12]; sba_motstr_levmar(visibleStructureID.size(), 0, vUsedFrame.size(), 1, dVMask, dCameraParameter, nCameraParam, 3, dFeature2DParameter, dCovFeatures, 2, Projection3Donto2D_KDMOTSTR, NULL, &adata, 1e+3, 0, opt, info); PrintSBAInfo(info); RetrieveParameterFromSBA_KDRT(dCameraParameter, vCamera, cP, X, visibleStructureID, vUsedFrame, max_nFrames); free(dVMask); free(dFeature2DParameter); free(dCameraParameter); } void PatchTriangulationRefinement(CvMat *K, vector<CvMat *> vC, vector<CvMat *> vR, vector<double> vx11, vector<double> vy11, vector<double> vx12, vector<double> vy12, vector<double> vx21, vector<double> vy21, vector<double> vx22, vector<double> vy22, double X, double Y, double Z, CvMat *X11, CvMat *X12, CvMat *X21, CvMat *X22, CvMat *pi) { PrintAlgorithm("Patch Triangulation Refinement"); vector<CvMat *> vP; for (int i = 0; i < vC.size(); i++) { CvMat *P = cvCreateMat(3,4,CV_32FC1); CvMat *t = cvCreateMat(3,1,CV_32FC1); ScalarMul(vC[i], -1, t); cvSetIdentity(P); SetSubMat(P, 0, 3, t); cvMatMul(vR[i], P, P); cvMatMul(K, P, P); vP.push_back(P); } AdditionalData adata; adata.vP = vP; adata.X = X; adata.Y = Y; adata.Z = Z; vector<double> XParameter, feature2DParameter; XParameter.push_back(cvGetReal2D(pi, 0, 0)); XParameter.push_back(cvGetReal2D(pi, 1, 0)); XParameter.push_back(cvGetReal2D(pi, 2, 0)); XParameter.push_back(cvGetReal2D(X11, 0, 0)); XParameter.push_back(cvGetReal2D(X11, 1, 0)); XParameter.push_back(cvGetReal2D(X12, 0, 0)); XParameter.push_back(cvGetReal2D(X12, 1, 0)); XParameter.push_back(cvGetReal2D(X21, 0, 0)); XParameter.push_back(cvGetReal2D(X21, 1, 0)); XParameter.push_back(cvGetReal2D(X22, 0, 0)); XParameter.push_back(cvGetReal2D(X22, 1, 0)); for (int iFeature = 0; iFeature < vx11.size(); iFeature++) { feature2DParameter.push_back(vx11[iFeature]); feature2DParameter.push_back(vy11[iFeature]); feature2DParameter.push_back(vx12[iFeature]); feature2DParameter.push_back(vy12[iFeature]); feature2DParameter.push_back(vx21[iFeature]); feature2DParameter.push_back(vy21[iFeature]); feature2DParameter.push_back(vx22[iFeature]); feature2DParameter.push_back(vy22[iFeature]); } //for (int i = 0; i < feature2DParameter.size(); i++) //{ // cout << feature2DParameter[i] << " "; //} //cout << endl; int nFeatures = vx11.size(); double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double)); double *dXParameter = (double *) malloc(XParameter.size() * sizeof(double)); for (int i = 0; i < XParameter.size(); i++) dXParameter[i] = XParameter[i]; for (int i = 0; i < feature2DParameter.size(); i++) dFeature2DParameter[i] = feature2DParameter[i]; double opt[5]; opt[0] = 1e-3; opt[1] = 1e-12; opt[2] = 1e-12; opt[3] = 1e-12; opt[4] = 0; double info[12]; double *work = (double*)malloc((LM_DIF_WORKSZ(XParameter.size(), feature2DParameter.size())+XParameter.size()*XParameter.size())*sizeof(double)); if(!work) fprintf(stderr, "memory allocation request failed in main()\n"); int ret = dlevmar_dif(Projection3Donto2D_Patch, dXParameter, dFeature2DParameter, XParameter.size(), feature2DParameter.size(), 1e+3, opt, info, work, NULL, &adata); double pi1 = dXParameter[0]; double pi2 = dXParameter[1]; double pi3 = dXParameter[2]; double pi4 = -pi1*X-pi2*Y-pi3*Z; cvSetReal2D(pi, 0, 0, dXParameter[0]); cvSetReal2D(pi, 1, 0, dXParameter[1]); cvSetReal2D(pi, 2, 0, dXParameter[2]); cvSetReal2D(pi, 3, 0, pi4); cvSetReal2D(X11, 0, 0, dXParameter[3]); cvSetReal2D(X11, 1, 0, dXParameter[4]); double Z11 = (-pi4-pi1*cvGetReal2D(X11, 0, 0)-pi2*cvGetReal2D(X11, 1, 0))/pi3; cvSetReal2D(X11, 2, 0, Z11); cvSetReal2D(X12, 0, 0, dXParameter[5]); cvSetReal2D(X12, 1, 0, dXParameter[6]); double Z12 = (-pi4-pi1*cvGetReal2D(X12, 0, 0)-pi2*cvGetReal2D(X12, 1, 0))/pi3; cvSetReal2D(X12, 2, 0, Z12); cvSetReal2D(X21, 0, 0, dXParameter[7]); cvSetReal2D(X21, 1, 0, dXParameter[8]); double Z21 = (-pi4-pi1*cvGetReal2D(X21, 0, 0)-pi2*cvGetReal2D(X21, 1, 0))/pi3; cvSetReal2D(X21, 2, 0, Z21); cvSetReal2D(X22, 0, 0, dXParameter[9]); cvSetReal2D(X22, 1, 0, dXParameter[10]); double Z22 = (-pi4-pi1*cvGetReal2D(X22, 0, 0)-pi2*cvGetReal2D(X22, 1, 0))/pi3; cvSetReal2D(X22, 2, 0, Z22); PrintSBAInfo(info, feature2DParameter.size()); free(dFeature2DParameter); free(dXParameter); free(work); for (int i = 0; i < vP.size(); i++) { cvReleaseMat(&vP[i]); } } void TriangulationRefinement(CvMat *K, double omega, vector<CvMat *> vP, vector<double> vx, vector<double> vy, double &X, double &Y, double &Z) { PrintAlgorithm("Point Triangulation Refinement"); AdditionalData adata; double intrinsic[5] = {cvGetReal2D(K, 0, 0), cvGetReal2D(K, 1, 1), cvGetReal2D(K, 0, 2), cvGetReal2D(K, 1, 2), omega}; adata.vIntrinsic.push_back(intrinsic); adata.vP = vP; vector<double> XParameter, feature2DParameter; XParameter.push_back(X); XParameter.push_back(Y); XParameter.push_back(Z); for (int iFeature = 0; iFeature < vx.size(); iFeature++) { feature2DParameter.push_back(vx[iFeature]); feature2DParameter.push_back(vy[iFeature]); } int nFeatures = vx.size(); double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double)); double *dXParameter = (double *) malloc(XParameter.size() * sizeof(double)); for (int i = 0; i < XParameter.size(); i++) dXParameter[i] = XParameter[i]; for (int i = 0; i < feature2DParameter.size(); i++) dFeature2DParameter[i] = feature2DParameter[i]; double opt[5]; opt[0] = 1e-3; opt[1] = 1e-12; opt[2] = 1e-12; opt[3] = 1e-12; opt[4] = 0; double info[12]; double *work = (double*)malloc((LM_DIF_WORKSZ(XParameter.size(), feature2DParameter.size())+XParameter.size()*XParameter.size())*sizeof(double)); if(!work) fprintf(stderr, "memory allocation request failed in main()\n"); int ret = dlevmar_dif(Projection3Donto2D_STR_fast_SO, dXParameter, dFeature2DParameter, XParameter.size(), feature2DParameter.size(), 1e+3, opt, info, work, NULL, &adata); X = dXParameter[0]; Y = dXParameter[1]; Z = dXParameter[2]; PrintSBAInfo(info, feature2DParameter.size()); free(dFeature2DParameter); free(dXParameter); free(work); //for (int i = 0; i < adata.vP.size(); i++) //{ // cvReleaseMat(&adata.vP[i]); //} } void TriangulationRefinement_NoDistortion(CvMat *K, vector<CvMat *> vP, vector<double> vx, vector<double> vy, double &X, double &Y, double &Z) { PrintAlgorithm("Point Triangulation Refinement"); AdditionalData adata; double intrinsic[4] = {cvGetReal2D(K, 0, 0), cvGetReal2D(K, 1, 1), cvGetReal2D(K, 0, 2), cvGetReal2D(K, 1, 2)}; adata.vIntrinsic.push_back(intrinsic); adata.vP = vP; vector<double> XParameter, feature2DParameter; XParameter.push_back(X); XParameter.push_back(Y); XParameter.push_back(Z); for (int iFeature = 0; iFeature < vx.size(); iFeature++) { feature2DParameter.push_back(vx[iFeature]); feature2DParameter.push_back(vy[iFeature]); } int nFeatures = vx.size(); double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double)); double *dXParameter = (double *) malloc(XParameter.size() * sizeof(double)); for (int i = 0; i < XParameter.size(); i++) dXParameter[i] = XParameter[i]; for (int i = 0; i < feature2DParameter.size(); i++) dFeature2DParameter[i] = feature2DParameter[i]; double opt[5]; opt[0] = 1e-3; opt[1] = 1e-12; opt[2] = 1e-12; opt[3] = 1e-12; opt[4] = 0; double info[12]; double *work = (double*)malloc((LM_DIF_WORKSZ(XParameter.size(), feature2DParameter.size())+XParameter.size()*XParameter.size())*sizeof(double)); if(!work) fprintf(stderr, "memory allocation request failed in main()\n"); int ret = dlevmar_dif(Projection3Donto2D_STR_fast_SO_NoDistortion, dXParameter, dFeature2DParameter, XParameter.size(), feature2DParameter.size(), 1e+3, opt, info, work, NULL, &adata); X = dXParameter[0]; Y = dXParameter[1]; Z = dXParameter[2]; PrintSBAInfo(info, feature2DParameter.size()); free(dFeature2DParameter); free(dXParameter); free(work); //for (int i = 0; i < adata.vP.size(); i++) //{ // cvReleaseMat(&adata.vP[i]); //} } void AbsoluteCameraPoseRefinement(CvMat *X, CvMat *x, CvMat *P, CvMat *K) { PrintAlgorithm("Absolute Camera Pose Refinement"); vector<double> cameraParameter, feature2DParameter; AdditionalData adata;// focal_x focal_y princ_x princ_y double intrinsic[4] = {cvGetReal2D(K, 0, 0), cvGetReal2D(K, 1, 1), cvGetReal2D(K, 0, 2), cvGetReal2D(K, 1, 2)}; adata.vIntrinsic.push_back(intrinsic); CvMat *q = cvCreateMat(4,1,CV_32FC1); CvMat *R = cvCreateMat(3,3,CV_32FC1); CvMat *t = cvCreateMat(3,1,CV_32FC1); CvMat *invK = cvCreateMat(3,3,CV_32FC1); CvMat *invR = cvCreateMat(3,3,CV_32FC1); GetSubMatColwise(P, 0, 2, R); GetSubMatColwise(P, 3, 3, t); cvInvert(K, invK); cvMatMul(invK, R, R); cvInvert(R, invR); cvMatMul(invK, t, t); cvMatMul(invR, t, t); ScalarMul(t, -1, t); Rotation2Quaternion(R, q); cameraParameter.push_back(cvGetReal2D(q, 0, 0)); cameraParameter.push_back(cvGetReal2D(q, 1, 0)); cameraParameter.push_back(cvGetReal2D(q, 2, 0)); cameraParameter.push_back(cvGetReal2D(q, 3, 0)); cameraParameter.push_back(cvGetReal2D(t, 0, 0)); cameraParameter.push_back(cvGetReal2D(t, 1, 0)); cameraParameter.push_back(cvGetReal2D(t, 2, 0)); for (int iFeature = 0; iFeature < X->rows; iFeature++) { feature2DParameter.push_back(cvGetReal2D(x, iFeature, 0)); feature2DParameter.push_back(cvGetReal2D(x, iFeature, 1)); } int nCameraParam = 7; int nFeatures = X->rows; double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double)); double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double)); double *dXParameter = (double *) malloc(X->rows * 3 * sizeof(double)); for (int i = 0; i < cameraParameter.size(); i++) dCameraParameter[i] = cameraParameter[i]; for (int i = 0; i < feature2DParameter.size(); i++) dFeature2DParameter[i] = feature2DParameter[i]; for (int i = 0; i < X->rows; i++) { dXParameter[3*i] = cvGetReal2D(X, i, 0); dXParameter[3*i+1] = cvGetReal2D(X, i, 1); dXParameter[3*i+2] = cvGetReal2D(X, i, 2); } adata.XYZ = dXParameter; double opt[5]; opt[0] = 1e-3; opt[1] = 1e-12; opt[2] = 1e-12; opt[3] = 1e-12; opt[4] = 0; double info[12]; double *work = (double*)malloc((LM_DIF_WORKSZ(cameraParameter.size(), feature2DParameter.size())+cameraParameter.size()*cameraParameter.size())*sizeof(double)); if(!work) fprintf(stderr, "memory allocation request failed in main()\n"); int ret = dlevmar_dif(Projection3Donto2D_MOT_fast, dCameraParameter, dFeature2DParameter, cameraParameter.size(), feature2DParameter.size(), 1e+3, opt, info, work, NULL, &adata); cvSetIdentity(P); cvSetReal2D(P, 0, 3, -dCameraParameter[4]); cvSetReal2D(P, 1, 3, -dCameraParameter[5]); cvSetReal2D(P, 2, 3, -dCameraParameter[6]); cvSetReal2D(q, 0, 0, dCameraParameter[0]); cvSetReal2D(q, 1, 0, dCameraParameter[1]); cvSetReal2D(q, 2, 0, dCameraParameter[2]); cvSetReal2D(q, 3, 0, dCameraParameter[3]); Quaternion2Rotation(q, R); cvMatMul(K, R, R); cvMatMul(R, P, P); //cout << ret << endl; PrintSBAInfo(info, X->rows); free(dFeature2DParameter); free(dCameraParameter); cvReleaseMat(&R); cvReleaseMat(&t); cvReleaseMat(&q); cvReleaseMat(&invK); cvReleaseMat(&invR); } void Projection3Donto2D_Patch(double *rt, double *hx, int m, int n, void *adata) { // Set intrinsic parameter double X = ((AdditionalData *) adata)->X; double Y = ((AdditionalData *) adata)->Y; double Z = ((AdditionalData *) adata)->Z; double pi1 = rt[0]; double pi2 = rt[1]; double pi3 = rt[2]; double pi4 = -pi1*X - pi2*Y - pi3*Z; double X11 = rt[3]; double Y11 = rt[4]; double Z11 = (-pi4-pi1*X11-pi2*Y11)/pi3; double X12 = rt[5]; double Y12 = rt[6]; double Z12 = (-pi4-pi1*X12-pi2*Y12)/pi3; double X21 = rt[7]; double Y21 = rt[8]; double Z21 = (-pi4-pi1*X21-pi2*Y21)/pi3; double X22 = rt[9]; double Y22 = rt[10]; double Z22 = (-pi4-pi1*X22-pi2*Y22)/pi3; for (int iP = 0; iP < ((AdditionalData *) adata)->vP.size(); iP++) { double P11 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 0); double P12 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 1); double P13 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 2); double P14 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 3); double P21 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 0); double P22 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 1); double P23 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 2); double P24 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 3); double P31 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 0); double P32 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 1); double P33 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 2); double P34 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 3); double x11 = P11*X11+P12*Y11+P13*Z11+P14; double y11 = P21*X11+P22*Y11+P23*Z11+P24; double z11 = P31*X11+P32*Y11+P33*Z11+P34; double x12 = P11*X12+P12*Y12+P13*Z12+P14; double y12 = P21*X12+P22*Y12+P23*Z12+P24; double z12 = P31*X12+P32*Y12+P33*Z12+P34; double x21 = P11*X21+P12*Y21+P13*Z21+P14; double y21 = P21*X21+P22*Y21+P23*Z21+P24; double z21 = P31*X21+P32*Y21+P33*Z21+P34; double x22 = P11*X22+P12*Y22+P13*Z22+P14; double y22 = P21*X22+P22*Y22+P23*Z22+P24; double z22 = P31*X22+P32*Y22+P33*Z22+P34; hx[8*iP] = x11/z11; hx[8*iP+1] = y11/z11; hx[8*iP+2] = x12/z12; hx[8*iP+3] = y12/z12; hx[8*iP+4] = x21/z21; hx[8*iP+5] = y21/z21; hx[8*iP+6] = x22/z22; hx[8*iP+7] = y22/z22; //cout << x11/z11 << " " << y11/z11 << " "; //cout << x12/z12 << " " << y12/z12 << " "; //cout << x21/z21 << " " << y21/z21 << " "; //cout << x22/z22 << " " << y22/z22 << endl; } } void Projection3Donto2D_STR_fast_SO(double *rt, double *hx, int m, int n, void *adata) { // Set intrinsic parameter double K11 = ((((AdditionalData *) adata)->vIntrinsic)[0])[0]; double K12 = 0; double K13 = ((((AdditionalData *) adata)->vIntrinsic)[0])[2]; double K21 = 0; double K22 = ((((AdditionalData *) adata)->vIntrinsic)[0])[1]; double K23 = ((((AdditionalData *) adata)->vIntrinsic)[0])[3]; double K31 = 0; double K32 = 0; double K33 = 1; double omega = ((((AdditionalData *) adata)->vIntrinsic)[0])[4]; double tan_omega_half_2 = 2*tan(omega/2); double X = rt[0]; double Y = rt[1]; double Z = rt[2]; for (int iP = 0; iP < ((AdditionalData *) adata)->vP.size(); iP++) { double P11 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 0); double P12 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 1); double P13 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 2); double P14 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 3); double P21 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 0); double P22 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 1); double P23 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 2); double P24 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 3); double P31 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 0); double P32 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 1); double P33 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 2); double P34 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 3); double x = P11*X+P12*Y+P13*Z+P14; double y = P21*X+P22*Y+P23*Z+P24; double z = P31*X+P32*Y+P33*Z+P34; x /= z; y /= z; double u_n = x/K11 - K13/K11; double v_n = y/K22 - K23/K22; double r_u = sqrt(u_n*u_n+v_n*v_n); double r_d = 1/omega*atan(r_u*tan_omega_half_2); double u_d_n = r_d/r_u * u_n; double v_d_n = r_d/r_u * v_n; double u_d = u_d_n*K11 + K13; double v_d = v_d_n*K22 + K23; hx[2*iP] = u_d; hx[2*iP+1] = v_d; } } void Projection3Donto2D_STR_fast_SO_NoDistortion(double *rt, double *hx, int m, int n, void *adata) { // Set intrinsic parameter double K11 = ((((AdditionalData *) adata)->vIntrinsic)[0])[0]; double K12 = 0; double K13 = ((((AdditionalData *) adata)->vIntrinsic)[0])[2]; double K21 = 0; double K22 = ((((AdditionalData *) adata)->vIntrinsic)[0])[1]; double K23 = ((((AdditionalData *) adata)->vIntrinsic)[0])[3]; double K31 = 0; double K32 = 0; double K33 = 1; //double omega = ((((AdditionalData *) adata)->vIntrinsic)[0])[4]; //double tan_omega_half_2 = 2*tan(omega/2); double X = rt[0]; double Y = rt[1]; double Z = rt[2]; for (int iP = 0; iP < ((AdditionalData *) adata)->vP.size(); iP++) { double P11 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 0); double P12 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 1); double P13 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 2); double P14 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 3); double P21 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 0); double P22 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 1); double P23 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 2); double P24 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 3); double P31 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 0); double P32 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 1); double P33 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 2); double P34 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 3); double x = P11*X+P12*Y+P13*Z+P14; double y = P21*X+P22*Y+P23*Z+P24; double z = P31*X+P32*Y+P33*Z+P34; x /= z; y /= z; //double u_n = x/K11 - K13/K11; //double v_n = y/K22 - K23/K22; //double r_u = sqrt(u_n*u_n+v_n*v_n); //double r_d = 1/omega*atan(r_u*tan_omega_half_2); //double u_d_n = r_d/r_u * u_n; //double v_d_n = r_d/r_u * v_n; //double u_d = u_d_n*K11 + K13; //double v_d = v_d_n*K22 + K23; hx[2*iP] = x; hx[2*iP+1] = y; } } void Projection3Donto2D_MOT_fast(double *rt, double *hx, int m, int n, void *adata) { // Set intrinsic parameter double K11 = ((((AdditionalData *) adata)->vIntrinsic)[0])[0]; double K12 = 0; double K13 = ((((AdditionalData *) adata)->vIntrinsic)[0])[2]; double K21 = 0; double K22 = ((((AdditionalData *) adata)->vIntrinsic)[0])[1]; double K23 = ((((AdditionalData *) adata)->vIntrinsic)[0])[3]; double K31 = 0; double K32 = 0; double K33 = 1; // Set orientation double qw = rt[0]; double qx = rt[1]; double qy = rt[2]; double qz = rt[3]; double q_norm = sqrt(qw*qw + qx*qx + qy*qy + qz*qz); qw /= q_norm; qx /= q_norm; qy /= q_norm; qz /= q_norm; double R11 = 1.0-2*qy*qy-2*qz*qz; double R12 = 2*qx*qy-2*qz*qw; double R13 = 2*qx*qz+2*qy*qw; double R21 = 2*qx*qy+2*qz*qw; double R22 = 1.0-2*qx*qx-2*qz*qz; double R23 = 2*qz*qy-2*qx*qw; double R31 = 2*qx*qz-2*qy*qw; double R32 = 2*qy*qz+2*qx*qw; double R33 = 1.0-2*qx*qx-2*qy*qy; // Set translation double C1 = rt[4]; double C2 = rt[5]; double C3 = rt[6]; for (int iPoint = 0; iPoint < n/2; iPoint++) { double X1 = ((AdditionalData *) adata)->XYZ[3*iPoint]; double X2 = ((AdditionalData *) adata)->XYZ[3*iPoint+1]; double X3 = ((AdditionalData *) adata)->XYZ[3*iPoint+2]; // Building projection double RX1 = R11*X1+R12*X2+R13*X3; double RX2 = R21*X1+R22*X2+R23*X3; double RX3 = R31*X1+R32*X2+R33*X3; double KRX1 = K11*RX1+K12*RX2+K13*RX3; double KRX2 = K21*RX1+K22*RX2+K23*RX3; double KRX3 = K31*RX1+K32*RX2+K33*RX3; double RC1 = R11*C1+R12*C2+R13*C3; double RC2 = R21*C1+R22*C2+R23*C3; double RC3 = R31*C1+R32*C2+R33*C3; double KRC1 = K11*RC1+K12*RC2+K13*RC3; double KRC2 = K21*RC1+K22*RC2+K23*RC3; double KRC3 = K31*RC1+K32*RC2+K33*RC3; double proj1 = KRX1-KRC1; double proj2 = KRX2-KRC2; double proj3 = KRX3-KRC3; hx[2*iPoint] = proj1/proj3; hx[2*iPoint+1] = proj2/proj3; } } void ObjectiveOrientationRefinement(double *rt, double *hx, int m, int n, void *adata) { int nFrames = (((AdditionalData *) adata)->nFrames); vector<double> vR11, vR12, vR13, vR21, vR22, vR23, vR31, vR32, vR33; vector<double> vm1, vm2, vm3; for (int iFrame = 0; iFrame < nFrames; iFrame++) { // Set orientation double qw = rt[7*iFrame+0]; double qx = rt[7*iFrame+1]; double qy = rt[7*iFrame+2]; double qz = rt[7*iFrame+3]; double q_norm = sqrt(qw*qw + qx*qx + qy*qy + qz*qz); qw /= q_norm; qx /= q_norm; qy /= q_norm; qz /= q_norm; double R11 = 1.0-2*qy*qy-2*qz*qz; double R12 = 2*qx*qy-2*qz*qw; double R13 = 2*qx*qz+2*qy*qw; double R21 = 2*qx*qy+2*qz*qw; double R22 = 1.0-2*qx*qx-2*qz*qz; double R23 = 2*qz*qy-2*qx*qw; double R31 = 2*qx*qz-2*qy*qw; double R32 = 2*qy*qz+2*qx*qw; double R33 = 1.0-2*qx*qx-2*qy*qy; vR11.push_back(R11); vR12.push_back(R12); vR13.push_back(R13); vR21.push_back(R21); vR22.push_back(R22); vR23.push_back(R23); vR31.push_back(R31); vR32.push_back(R32); vR33.push_back(R33); vm1.push_back(rt[7*iFrame+4]); vm2.push_back(rt[7*iFrame+5]); vm3.push_back(rt[7*iFrame+6]); //cout << R11 << " " << R12 << " " << R13 << endl; //cout << R21 << " " << R22 << " " << R23 << endl; //cout << R31 << " " << R32 << " " << R33 << endl; } //vector<CvMat *> vP = (((AdditionalData *) adata)->vP); double R11 = 1; double R12 = 0; double R13 = 0; double R21 = 0; double R22 = 1; double R23 = 0; double R31 = 0; double R32 = 0; double R33 = 1; for (int iFrame = 0; iFrame < nFrames; iFrame++) { double R11_t, R12_t, R13_t, R21_t, R22_t, R23_t, R31_t, R32_t, R33_t; R11_t = vR11[iFrame]*R11 + vR12[iFrame]*R21 + vR13[iFrame]*R31; R12_t = vR11[iFrame]*R12 + vR12[iFrame]*R22 + vR13[iFrame]*R32; R13_t = vR11[iFrame]*R13 + vR12[iFrame]*R23 + vR13[iFrame]*R33; R21_t = vR21[iFrame]*R11 + vR22[iFrame]*R21 + vR23[iFrame]*R31; R22_t = vR21[iFrame]*R12 + vR22[iFrame]*R22 + vR23[iFrame]*R32; R23_t = vR21[iFrame]*R13 + vR22[iFrame]*R23 + vR23[iFrame]*R33; R31_t = vR31[iFrame]*R11 + vR32[iFrame]*R21 + vR33[iFrame]*R31; R32_t = vR31[iFrame]*R12 + vR32[iFrame]*R22 + vR33[iFrame]*R32; R33_t = vR31[iFrame]*R13 + vR32[iFrame]*R23 + vR33[iFrame]*R33; R11 = R11_t; R12 = R12_t; R13 = R13_t; R21 = R21_t; R22 = R22_t; R23 = R23_t; R31 = R31_t; R32 = R32_t; R33 = R33_t; } double qw = sqrt(abs(1.0+R11+R22+R33))/2; double qx, qy, qz; if (qw > QW_ZERO) { qx = (R32-R23)/4/qw; qy = (R13-R31)/4/qw; qz = (R21-R12)/4/qw; } else { double d = sqrt((R12*R12*R13*R13+R12*R12*R23*R23+R13*R13*R23*R23)); qx = R12*R13/d; qy = R12*R23/d; qz = R13*R23/d; } double norm_q = sqrt(qx*qx+qy*qy+qz*qz+qw*qw); hx[0] = qw/norm_q; hx[1] = qx/norm_q; hx[2] = qy/norm_q; hx[3] = qz/norm_q; //cout << qw/norm_q << " " << qx/norm_q << " " << qy/norm_q << " " << qz/norm_q << endl; vector<CvMat *> *vx1 = (((AdditionalData *) adata)->vx1); vector<CvMat *> *vx2 = (((AdditionalData *) adata)->vx2); int idx = 4; for (int iFrame = 0; iFrame < nFrames; iFrame++) { double E11 = -vm3[iFrame]*vR21[iFrame] + vm2[iFrame]*vR31[iFrame]; double E12 = -vm3[iFrame]*vR22[iFrame] + vm2[iFrame]*vR32[iFrame]; double E13 = -vm3[iFrame]*vR23[iFrame] + vm2[iFrame]*vR33[iFrame]; double E21 = vm3[iFrame]*vR11[iFrame] - vm1[iFrame]*vR31[iFrame]; double E22 = vm3[iFrame]*vR12[iFrame] - vm1[iFrame]*vR32[iFrame]; double E23 = vm3[iFrame]*vR13[iFrame] - vm1[iFrame]*vR33[iFrame]; double E31 = -vm2[iFrame]*vR11[iFrame] + vm1[iFrame]*vR21[iFrame]; double E32 = -vm2[iFrame]*vR12[iFrame] + vm1[iFrame]*vR22[iFrame]; double E33 = -vm2[iFrame]*vR13[iFrame] + vm1[iFrame]*vR23[iFrame]; double out = 0; if ((*vx1)[iFrame]->rows == 1) continue; for (int ix = 0; ix < (*vx1)[iFrame]->rows; ix++) { double x1 = cvGetReal2D((*vx1)[iFrame], ix, 0); double x2 = cvGetReal2D((*vx1)[iFrame], ix, 1); double x3 = 1; double xp1 = cvGetReal2D((*vx2)[iFrame], ix, 0); double xp2 = cvGetReal2D((*vx2)[iFrame], ix, 1); double xp3 = 1; double Ex1 = E11*x1 + E12*x2 + E13*x3; double Ex2 = E21*x1 + E22*x2 + E23*x3; double Ex3 = E31*x1 + E32*x2 + E33*x3; double Etxp1 = E11*xp1 + E21*xp2 + E31*xp3; double Etxp2 = E12*xp1 + E22*xp2 + E32*xp3; double Etxp3 = E13*xp1 + E23*xp2 + E33*xp3; double xpEx = xp1*Ex1 + xp2*Ex2 + xp3*Ex3; double dist = xpEx*xpEx * (1/(Ex1*Ex1+Ex2*Ex2)+1/(Etxp1*Etxp1+Etxp2*Etxp2)); out += sqrt(dist)/(*vx1)[iFrame]->rows; //hx[idx] = dist; //idx++; } for (int j = 0; j < 10; j++) { idx++; hx[idx] = 0.1*out; } } } void ObjectiveOrientationRefinement1(double *rt, double *hx, int m, int n, void *adata) { // Set orientation double qw = (((AdditionalData *) adata)->qw); double qx = (((AdditionalData *) adata)->qx); double qy = (((AdditionalData *) adata)->qy); double qz = (((AdditionalData *) adata)->qz); double q_norm = sqrt(qw*qw + qx*qx + qy*qy + qz*qz); qw /= q_norm; qx /= q_norm; qy /= q_norm; qz /= q_norm; double R11 = 1.0-2*qy*qy-2*qz*qz; double R12 = 2*qx*qy-2*qz*qw; double R13 = 2*qx*qz+2*qy*qw; double R21 = 2*qx*qy+2*qz*qw; double R22 = 1.0-2*qx*qx-2*qz*qz; double R23 = 2*qz*qy-2*qx*qw; double R31 = 2*qx*qz-2*qy*qw; double R32 = 2*qy*qz+2*qx*qw; double R33 = 1.0-2*qx*qx-2*qy*qy; double m1 = rt[0]; double m2 = rt[1]; double m3 = rt[2]; double norm_m = sqrt(m1*m1+m2*m2+m3*m3); m1 /= norm_m; m2 /= norm_m; m3 /= norm_m; vector<double> *vx1 = (((AdditionalData *) adata)->vx1_a); vector<double> *vy1 = (((AdditionalData *) adata)->vy1_a); vector<double> *vx2 = (((AdditionalData *) adata)->vx2_a); vector<double> *vy2 = (((AdditionalData *) adata)->vy2_a); double E11 = -m3*R21 + m2*R31; double E12 = -m3*R22 + m2*R32; double E13 = -m3*R23 + m2*R33; double E21 = m3*R11 - m1*R31; double E22 = m3*R12 - m1*R32; double E23 = m3*R13 - m1*R33; double E31 = -m2*R11 + m1*R21; double E32 = -m2*R12 + m1*R22; double E33 = -m2*R13 + m1*R23; for (int ix = 0; ix < (*vx1).size(); ix++) { double x1 = (*vx1)[ix]; double x2 = (*vy1)[ix]; double x3 = 1; double xp1 = (*vx2)[ix]; double xp2 = (*vy2)[ix]; double xp3 = 1; double Ex1 = E11*x1 + E12*x2 + E13*x3; double Ex2 = E21*x1 + E22*x2 + E23*x3; double Ex3 = E31*x1 + E32*x2 + E33*x3; double Etxp1 = E11*xp1 + E21*xp2 + E31*xp3; double Etxp2 = E12*xp1 + E22*xp2 + E32*xp3; double Etxp3 = E13*xp1 + E23*xp2 + E33*xp3; double xpEx = xp1*Ex1 + xp2*Ex2 + xp3*Ex3; double dist = xpEx*xpEx * (1/(Ex1*Ex1+Ex2*Ex2)+1/(Etxp1*Etxp1+Etxp2*Etxp2)); hx[ix] = 100*dist; } } void CameraCenterInterpolationWithDegree(CvMat *R_1, vector<int> vFrame1, vector<int> vFrame2, vector<CvMat *> vM, vector<CvMat *> vm, vector<int> vFrame1_r, vector<int> vFrame2_r, vector<CvMat *> vM_r, vector<CvMat *> vm_r, vector<CvMat *> vC_c, vector<CvMat *> vR_c, vector<int> vFrame_c, vector<CvMat *> &vC, vector<CvMat *> &vR, double weight) { // Frame normalization int first = vFrame1[0]; for (int iFrame = 0; iFrame < vFrame1.size(); iFrame++) { vFrame1[iFrame] = vFrame1[iFrame] - first; vFrame2[iFrame] = vFrame2[iFrame] - first; double m1 = cvGetReal2D(vm[iFrame], 0, 0); double m2 = cvGetReal2D(vm[iFrame], 1, 0); double m3 = cvGetReal2D(vm[iFrame], 2, 0); double norm_m = sqrt(m1*m1+m2*m2+m3*m3); ScalarMul(vm[iFrame], 1/norm_m, vm[iFrame]); } for (int iFrame = 0; iFrame < vFrame1_r.size(); iFrame++) { vFrame1_r[iFrame] = vFrame1_r[iFrame] - first; vFrame2_r[iFrame] = vFrame2_r[iFrame] - first; double m1 = cvGetReal2D(vm_r[iFrame], 0, 0); double m2 = cvGetReal2D(vm_r[iFrame], 1, 0); double m3 = cvGetReal2D(vm_r[iFrame], 2, 0); double norm_m = sqrt(m1*m1+m2*m2+m3*m3); ScalarMul(vm_r[iFrame], 1/norm_m, vm_r[iFrame]); } for (int iFrame = 0; iFrame < vFrame_c.size(); iFrame++) { vFrame_c[iFrame] = vFrame_c[iFrame] - first; } int nFrames = vFrame_c[vFrame_c.size()-1] - vFrame_c[0]+1; vR.resize(nFrames); vector<bool> vIsR(nFrames, false); for (int ic = 0; ic < vFrame_c.size(); ic++) { vR[vFrame_c[ic]] = cvCloneMat(vR_c[ic]); vIsR[vFrame_c[ic]] = true; } for (int iFrame = 0; iFrame < vFrame1.size(); iFrame++) { CvMat *R = cvCreateMat(3,3,CV_32FC1); int j = 0; if (!vIsR[vFrame1[iFrame]-j]) { while (!vIsR[vFrame1[iFrame]-j]) { j++; } for (int i = j-1; i >= 0; i--) { vR[vFrame1[iFrame]-i] = cvCloneMat(vR[vFrame1[iFrame]-j]); } } cvMatMul(vM[iFrame], vR[vFrame1[iFrame]], R); vR[vFrame2[iFrame]] = cvCloneMat(R); vIsR[vFrame2[iFrame]] = true; cvReleaseMat(&R); } for (int ic = 0; ic < vFrame_c.size(); ic++) { vR[vFrame_c[ic]] = cvCloneMat(vR_c[ic]); } int nBasis = floor((double)nFrames/3); CvMat *theta_all = cvCreateMat(nFrames, nFrames, CV_32FC1); GetIDCTMappingMatrix(theta_all, nFrames); CvMat *theta_i = cvCreateMat(1, nBasis, CV_32FC1); CvMat *Theta_i = cvCreateMat(3, 3*nBasis, CV_32FC1); CvMat *A = cvCreateMat(3*vM.size(), 3*nBasis, CV_32FC1); CvMat *b = cvCreateMat(3*vM.size(), 1, CV_32FC1); cvSetZero(b); for (int im = 0; im < vM.size(); im++) { for (int ith = 0; ith < nBasis; ith++) { cvSetReal2D(theta_i, 0, ith, cvGetReal2D(theta_all, vFrame1[im], ith)-cvGetReal2D(theta_all, vFrame2[im], ith)); } SetSubMat(Theta_i, 0, 0, theta_i); SetSubMat(Theta_i, 1, nBasis, theta_i); SetSubMat(Theta_i, 2, 2*nBasis, theta_i); CvMat *skewm = cvCreateMat(3,3,CV_32FC1); Vec2Skew(vm[im], skewm); CvMat *temp33 = cvCreateMat(3,3,CV_32FC1); cvMatMul(skewm, vR[vFrame2[im]], temp33); CvMat *temp3nBasis = cvCreateMat(3, 3*nBasis, CV_32FC1); cvMatMul(temp33, Theta_i, temp3nBasis); SetSubMat(A, 3*im, 0, temp3nBasis); cvReleaseMat(&skewm); cvReleaseMat(&temp33); cvReleaseMat(&temp3nBasis); } CvMat *A_r = cvCreateMat(3*vM_r.size(), 3*nBasis, CV_32FC1); CvMat *b_r = cvCreateMat(3*vM_r.size(), 1, CV_32FC1); cvSetZero(b_r); for (int im = 0; im < vM_r.size(); im++) { for (int ith = 0; ith < nBasis; ith++) { cvSetReal2D(theta_i, 0, ith, cvGetReal2D(theta_all, vFrame1_r[im], ith)-cvGetReal2D(theta_all, vFrame2_r[im], ith)); } SetSubMat(Theta_i, 0, 0, theta_i); SetSubMat(Theta_i, 1, nBasis, theta_i); SetSubMat(Theta_i, 2, 2*nBasis, theta_i); CvMat *skewm = cvCreateMat(3,3,CV_32FC1); Vec2Skew(vm_r[im], skewm); CvMat *temp33 = cvCreateMat(3,3,CV_32FC1); cvMatMul(skewm, vR[vFrame2_r[im]], temp33); CvMat *temp3nBasis = cvCreateMat(3, 3*nBasis, CV_32FC1); cvMatMul(temp33, Theta_i, temp3nBasis); SetSubMat(A_r, 3*im, 0, temp3nBasis); cvReleaseMat(&skewm); cvReleaseMat(&temp33); cvReleaseMat(&temp3nBasis); } CvMat *A_c = cvCreateMat(3*vFrame_c.size(), 3*nBasis, CV_32FC1); CvMat *b_c = cvCreateMat(3*vFrame_c.size(), 1, CV_32FC1); for (int ic = 0; ic < vFrame_c.size(); ic++) { for (int ith = 0; ith < nBasis; ith++) { cvSetReal2D(theta_i, 0, ith, cvGetReal2D(theta_all, vFrame_c[ic], ith)); } SetSubMat(Theta_i, 0, 0, theta_i); SetSubMat(Theta_i, 1, nBasis, theta_i); SetSubMat(Theta_i, 2, 2*nBasis, theta_i); SetSubMat(A_c, 3*ic, 0, Theta_i); SetSubMat(b_c, 3*ic, 0, vC_c[ic]); } ScalarMul(A_c, weight, A_c); ScalarMul(b_c, weight, b_c); CvMat *At = cvCreateMat(A->rows+A_r->rows+A_c->rows, A->cols, CV_32FC1); CvMat *bt = cvCreateMat(A->rows+A_r->rows+A_c->rows, 1, CV_32FC1); SetSubMat(At, 0, 0, A); SetSubMat(bt, 0, 0, b); SetSubMat(At, A->rows, 0, A_r); SetSubMat(bt, A->rows, 0, b_r); SetSubMat(At, A->rows+A_r->rows, 0, A_c); SetSubMat(bt, A->rows+A_r->rows, 0, b_c); CvMat *beta = cvCreateMat(3*nBasis, 1, CV_32FC1); cvSolve(At, bt, beta); //cvSolve(A_c, b_c, beta); for (int iFrame = 0; iFrame < nFrames; iFrame++) { for (int ith = 0; ith < nBasis; ith++) { cvSetReal2D(theta_i, 0, ith, cvGetReal2D(theta_all, iFrame, ith)); } SetSubMat(Theta_i, 0, 0, theta_i); SetSubMat(Theta_i, 1, nBasis, theta_i); SetSubMat(Theta_i, 2, 2*nBasis, theta_i); CvMat *C = cvCreateMat(3,1,CV_32FC1); cvMatMul(Theta_i, beta, C); vC.push_back(C); } cvReleaseMat(&beta); cvReleaseMat(&At); cvReleaseMat(&bt); cvReleaseMat(&A); cvReleaseMat(&b); cvReleaseMat(&A_r); cvReleaseMat(&b_r); cvReleaseMat(&A_c); cvReleaseMat(&b_c); cvReleaseMat(&theta_all); cvReleaseMat(&theta_i); cvReleaseMat(&Theta_i); } void SparseBundleAdjustment_KDMOT(vector<Feature> vFeature, vector<int> vUsedFrame, vector<CvMat *> &cP, CvMat *X, vector<Camera> vCamera, vector<int> visibleStructureID) { PrintAlgorithm("Sparse bundle adjustment motion only"); vector<double> cameraParameter, feature2DParameter; vector<char> vMask; double *dCovFeatures = 0; AdditionalData adata;// focal_x focal_y princ_x princ_y int max_nFrames = 0; for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) { for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++) { if (vCamera[iCamera].vTakenFrame[iFrame] > max_nFrames) max_nFrames = vCamera[iCamera].vTakenFrame[iFrame]; } } max_nFrames++; adata.max_nFrames = max_nFrames; adata.vUsedFrame = vUsedFrame; GetParameterForSBA_KDRT(vFeature, vUsedFrame, cP, X, vCamera, max_nFrames, visibleStructureID, cameraParameter, feature2DParameter, vMask); int nCameraParam = 7+4+2; int nFeatures = vFeature.size(); int nFrames = vUsedFrame.size(); char *dVMask = (char *) malloc(vMask.size() * sizeof(char)); double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double)); double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double)); for (int i = 0; i < cameraParameter.size(); i++) dCameraParameter[i] = cameraParameter[i]; for (int i = 0; i < vMask.size(); i++) dVMask[i] = vMask[i]; for (int i = 0; i < feature2DParameter.size(); i++) dFeature2DParameter[i] = feature2DParameter[i]; adata.XYZ = &(dCameraParameter[nCameraParam*vUsedFrame.size()]); double opt[5]; opt[0] = 1e-3; opt[1] = 1e-12; opt[2] = 1e-12; opt[3] = 1e-12; opt[4] = 0; double info[12]; sba_mot_levmar(visibleStructureID.size(), vUsedFrame.size(), 1, dVMask, dCameraParameter, nCameraParam, dFeature2DParameter, dCovFeatures, 2, Projection3Donto2D_KDMOT, NULL, &adata, 1e+3, 0, opt, info); PrintSBAInfo(info); RetrieveParameterFromSBA_KDRT(dCameraParameter, vCamera, cP, X, visibleStructureID, vUsedFrame, max_nFrames); free(dVMask); free(dFeature2DParameter); free(dCameraParameter); } void SparseBundleAdjustment_TEMPORAL(vector<Feature> vFeature, vector<Theta> &vTheta, vector<Camera> &vCamera) { PrintAlgorithm("Sparse bundle adjustment - Temporal adjustment"); vector<double> cameraParameter, feature2DParameter; vector<char> vMask; double *dCovFeatures = 0; AdditionalData adata;// focal_x focal_y princ_x princ_y int max_nFrames = 0; for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) { for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++) { if (vCamera[iCamera].vTakenFrame[iFrame] > max_nFrames) max_nFrames = vCamera[iCamera].vTakenFrame[iFrame]; } } max_nFrames++; adata.max_nFrames = max_nFrames; vector<int> vUsedFrame; vector<CvMat *> vP; vector<double> vdP; for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) { for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++) { vUsedFrame.push_back(iCamera*max_nFrames+vCamera[iCamera].vTakenFrame[iFrame]); vP.push_back(vCamera[iCamera].vP[iFrame]); for (int iP = 0; iP < 3; iP++) for (int jP = 0; jP < 4; jP++) vdP.push_back(cvGetReal2D(vCamera[iCamera].vP[iFrame], iP, jP)); } } adata.vUsedFrame = vUsedFrame; adata.vP = vP; adata.vdP = vdP; adata.nBase = vTheta[0].thetaX.size(); adata.vTheta = vTheta; GetParameterForSBA_TEMPORAL(vFeature, vTheta, vCamera, max_nFrames, cameraParameter, feature2DParameter, vMask); int nCameraParam = 1; int nFeatures = vTheta.size(); int nFrames = vUsedFrame.size(); char *dVMask = (char *) malloc(vMask.size() * sizeof(char)); double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double)); double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double)); for (int i = 0; i < cameraParameter.size(); i++) dCameraParameter[i] = cameraParameter[i]; for (int i = 0; i < vMask.size(); i++) dVMask[i] = vMask[i]; for (int i = 0; i < feature2DParameter.size(); i++) dFeature2DParameter[i] = feature2DParameter[i]; adata.XYZ = &(dCameraParameter[nCameraParam*vUsedFrame.size()]); double opt[5]; opt[0] = 1e-3; opt[1] = 1e-5; opt[2] = 1e-5; opt[3] = 1e-5; opt[4] = 0; double info[12]; sba_motstr_levmar(vTheta.size(), 0, vUsedFrame.size(), 0, dVMask, dCameraParameter, nCameraParam, 3*adata.nBase, dFeature2DParameter, dCovFeatures, 4, ProjectionThetaonto2D_TEMPORAL, NULL, &adata, 1e+3, 0, opt, info); PrintSBAInfo(info); RetrieveParameterFromSBA_TEMPORAL(dCameraParameter, vCamera, vTheta); free(dVMask); free(dFeature2DParameter); free(dCameraParameter); } void SparseBundleAdjustment_TEMPORAL_LEVMAR(vector<Feature> vFeature, vector<Theta> &vTheta, vector<Camera> &vCamera) { //for (int i = 0; i < 106; i++) //{ // vFeature.pop_back(); // vTheta.pop_back(); //} //PrintAlgorithm("Sparse bundle adjustment - Temporal adjustment, Levenburg-Marquedt"); //vector<double> cameraParameter, feature2DParameter; //vector<char> vMask; //double *dCovFeatures = 0; //AdditionalData adata;// focal_x focal_y princ_x princ_y //int max_nFrames = 0; //for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) //{ // for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++) // { // if (vCamera[iCamera].vTakenFrame[iFrame] > max_nFrames) // max_nFrames = vCamera[iCamera].vTakenFrame[iFrame]; // } //} //max_nFrames++; //adata.max_nFrames = max_nFrames; //vector<int> vUsedFrame; //vector<CvMat *> vP; //vector<double> vdP; //for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) //{ // for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++) // { // vUsedFrame.push_back(iCamera*max_nFrames+vCamera[iCamera].vTakenFrame[iFrame]); // vP.push_back(vCamera[iCamera].vP[iFrame]); // for (int iP = 0; iP < 3; iP++) // for (int jP = 0; jP < 4; jP++) // vdP.push_back(cvGetReal2D(vCamera[iCamera].vP[iFrame], iP, jP)); // } //} //adata.vUsedFrame = vUsedFrame; ////adata.vP = vP; //adata.vdP = vdP; //adata.nBase = vTheta[0].thetaX.size(); //adata.nFeatures = vTheta.size(); //adata.vTheta = vTheta; //GetParameterForSBA_TEMPORAL_LEVMAR(vFeature, vTheta, vCamera, max_nFrames, cameraParameter, feature2DParameter); //int nCameraParam = 1; //int nFeatures = vTheta.size(); //int nFrames = vUsedFrame.size(); ////char *dVMask = (char *) malloc(vMask.size() * sizeof(char)); //double *dFeature2DParameter = (double *) malloc((feature2DParameter.size()+nFeatures) * sizeof(double)); //double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double)); //for (int i = 0; i < cameraParameter.size(); i++) // dCameraParameter[i] = cameraParameter[i]; //for (int i = 0; i < feature2DParameter.size(); i++) // dFeature2DParameter[i] = feature2DParameter[i]/1e-6; //for (int i = 0; i < nFeatures; i++) // dFeature2DParameter[feature2DParameter.size()+i] = 0.0; //adata.isStatic = false; ////adata.XYZ = &(dCameraParameter[nCameraParam*vUsedFrame.size()]); //adata.measurements = feature2DParameter; //double opt[5]; //opt[0] = 1e-1; //opt[1] = 1e-20; //opt[2] = 1e-15; //opt[3] = 1e-15; //opt[4] = 0; //double info[12]; //double *work = (double*)malloc((LM_DIF_WORKSZ(cameraParameter.size(), feature2DParameter.size()+nFeatures)+cameraParameter.size()*cameraParameter.size())*sizeof(double)); //if(!work) // fprintf(stderr, "memory allocation request failed in main()\n"); //int ret = dlevmar_dif(ProjectionThetaonto2D_TEMPORAL_LEVMAR, dCameraParameter, dFeature2DParameter, cameraParameter.size(), feature2DParameter.size()+nFeatures, // 1e+3, opt, info, work, NULL, &adata); //cout << ret << endl; //PrintSBAInfo(info); //RetrieveParameterFromSBA_TEMPORAL(dCameraParameter, vCamera, vTheta); //free(dFeature2DParameter); //free(dCameraParameter); } void GlobalBundleAdjustment(vector<Feature> vFeature, vector<Camera> vCamera, vector<Theta> vTheta, CvMat *K, int nFrames, int nBase, int nFeatures_static) { //PrintAlgorithm("Global bundle adjustment motion and structure"); //vector<double> cameraParameter, feature2DParameter; //vector<char> vMask; //double *dCovFeatures = 0; //AdditionalData adata;// focal_x focal_y princ_x princ_y //double intrinsic[4]; //intrinsic[0] = cvGetReal2D(K, 0, 0); //intrinsic[1] = cvGetReal2D(K, 1, 1); //intrinsic[2] = cvGetReal2D(K, 0, 2); //intrinsic[3] = cvGetReal2D(K, 1, 2); //adata.intrinsic = intrinsic; //adata.nCameraParameters = 7; //adata.nImagePointPrameraters = 2; //adata.nBase = nBase; //adata.nFrames = nFrames; //adata.nFeature_static = nFeatures_static; //bool *isStatic = (bool *) malloc(vFeature.size() * sizeof(bool)); //for (int iStatic = 0; iStatic < vFeature.size(); iStatic++) //{ // if (iStatic < nFeatures_static) // isStatic[iStatic] = true; // else // isStatic[iStatic] = false; //} //adata.isStatic = isStatic; //GetParameterForGBA(vFeature, vCamera, vTheta, K, nFrames, cameraParameter, feature2DParameter, vMask); //int NZ = 0; //for (int i = 0; i < vMask.size(); i++) //{ // if (vMask[i]) // NZ++; //} //double nCameraParam = 7; //int nFeatures = vFeature.size(); //char *dVMask = (char *) malloc(vMask.size() * sizeof(char)); //double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double)); //double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double)); //for (int i = 0; i < cameraParameter.size(); i++) // dCameraParameter[i] = cameraParameter[i]; //for (int i = 0; i < vMask.size(); i++) // dVMask[i] = vMask[i]; //for (int i = 0; i < feature2DParameter.size(); i++) // dFeature2DParameter[i] = feature2DParameter[i]; //double opt[5]; //opt[0] = 1e-3; //opt[1] = 1e-5;//1e-12; //opt[2] = 1e-5;//1e-12; //opt[3] = 1e-5;//1e-12; //opt[4] = 0; //double info[12]; //sba_motstr_levmar_x(vFeature.size(), 0, nFrames*vCamera.size(), 1, dVMask, dCameraParameter, nCameraParam, 3*nBase, dFeature2DParameter, dCovFeatures, 2, ProjectionThetaonto2D_MOTSTR_x, NULL, &adata, // 1e+3, 0, opt, info); //PrintSBAInfo(info); //RetrieveParameterFromGBA(dCameraParameter, K, vCamera, vTheta, nFrames); //free(isStatic); //free(dVMask); //free(dFeature2DParameter); //free(dCameraParameter); } void GlobalBundleAdjustment_LEVMAR(vector<Feature> vFeature, vector<Camera> vCamera, vector<Theta> vTheta, CvMat *K, int nFrames, int nBase, int nFeatures_static) { //PrintAlgorithm("Global bundle adjustment motion and structure"); //vector<double> cameraParameter, feature2DParameter; //double *dCovFeatures = 0; //AdditionalData adata;// focal_x focal_y princ_x princ_y //double intrinsic[4]; //intrinsic[0] = cvGetReal2D(K, 0, 0); //intrinsic[1] = cvGetReal2D(K, 1, 1); //intrinsic[2] = cvGetReal2D(K, 0, 2); //intrinsic[3] = cvGetReal2D(K, 1, 2); //adata.intrinsic = intrinsic; //adata.nCameraParameters = 7; //adata.nImagePointPrameraters = 2; //adata.nBase = nBase; //adata.nFrames = nFrames*vCamera.size(); //adata.nFeature_static = nFeatures_static; //bool *isStatic = (bool *) malloc(vFeature.size() * sizeof(bool)); //for (int iStatic = 0; iStatic < vFeature.size(); iStatic++) //{ // if (iStatic < nFeatures_static) // isStatic[iStatic] = true; // else // isStatic[iStatic] = false; //} //adata.isStatic = isStatic; //adata.nNZ = (double)feature2DParameter.size()/2; //CvMat visibilityMask; //GetParameterForGBA(vFeature, vCamera, vTheta, K, nFrames, cameraParameter, feature2DParameter, visibilityMask); //CvMat *vMask = cvCreateMat(visibilityMask.rows, visibilityMask.cols, CV_32FC1); //vMask = cvCloneMat(&visibilityMask); //adata.visibilityMask = vMask; //double nCameraParam = 7; //int nFeatures = vFeature.size(); //double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double)); //double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double)); //double opt[5]; //opt[0] = 1e-3; //opt[1] = 1e-5;//1e-12; //opt[2] = 1e-5;//1e-12; //opt[3] = 1e-5;//1e-12; //opt[4] = 0; //double info[12]; //double *work=(double*)malloc((LM_DIF_WORKSZ(cameraParameter.size(), feature2DParameter.size())+cameraParameter.size()*cameraParameter.size())*sizeof(double)); //if(!work) // fprintf(stderr, "memory allocation request failed in main()\n"); //feature2DParameter.clear(); //cameraParameter.clear(); //for (int i = 0; i < 10000;i++) // feature2DParameter.push_back(0); //for (int i = 0; i < 10000-1; i++) // cameraParameter.push_back(0); //for (int i = 0; i < cameraParameter.size(); i++) // dCameraParameter[i] = cameraParameter[i]; //for (int i = 0; i < feature2DParameter.size(); i++) // dFeature2DParameter[i] = feature2DParameter[i]; //slevmar_dif(ProjectionThetaonto2D_MOTSTR_LEVMAR, (float*)dCameraParameter, (float*)dFeature2DParameter, cameraParameter.size(), feature2DParameter.size(), // 1e+3, (float*)opt, (float*)info, (float*)work, NULL, &adata); //PrintSBAInfo(info); //RetrieveParameterFromGBA(dCameraParameter, K, vCamera, vTheta, nFrames); //cvReleaseMat(&vMask); //free(isStatic); //free(dFeature2DParameter); //free(dCameraParameter); } void ProjectionThetaonto2D_MOTSTR_LEVMAR(double *p, double *hx, int m, int n, void *adata_) { //for (int i = 0; i <n; i++) // hx[i] = 1; //return; //AdditionalData *adata = (AdditionalData *)adata_; //bool *isStatic = adata->isStatic; //int nFrames = adata->nFrames; //int nCameraParameters = adata->nCameraParameters; //int nImagePointParameters = adata->nImagePointPrameraters; //int nBase = adata->nBase; //int nFeature_static = adata->nFeature_static; //double *XYZ = p + nCameraParameters*nFrames; //double *rt; //double *xij; // //int last = 0; //for (int iFeature = 0; iFeature < ((AdditionalData*)adata_)->visibilityMask->rows; iFeature++) //{ // for (int iFrame = 0; iFrame < ((AdditionalData*)adata_)->visibilityMask->cols; iFrame++) // { // if (cvGetReal2D(((AdditionalData*)adata_)->visibilityMask, iFeature, iFrame)) // { // if (isStatic[iFeature]) // { // double x, y; // //xij = hx + nImagePointParameters*last; // rt = p + iFrame*nCameraParameters; // XYZ = p + nFrames*nCameraParameters + iFeature*3; // ProjectionThetaonto2D_MOTSTR_LEVMAR(iFrame, iFeature, rt, XYZ, x, y, adata); // hx[nImagePointParameters*last] = 0; // hx[nImagePointParameters*last+1] = 0; // last++; // } // else // { // double x, y; // //xij = hx + nImagePointParameters*last; // rt = p + iFrame*nCameraParameters; // XYZ = p + nFrames*nCameraParameters + nFeature_static*3 + (iFeature-nFeature_static)*3*nBase; // ProjectionThetaonto2D_MOTSTR_LEVMAR(iFrame, iFeature, rt, XYZ, x, y, adata); // hx[nImagePointParameters*last] = 0; // hx[nImagePointParameters*last+1] = 0; // last++; // } // } // } //} } void ProjectionThetaonto2D_TEMPORAL_LEVMAR(double *p, double *hx, int m, int n, void *adata) { if (!((AdditionalData *)adata)->isStatic) { ((AdditionalData *)adata)->isStatic = true; ((AdditionalData *)adata)->ptr = p; } p = ((AdditionalData *)adata)->ptr; for (int ihx = 0; ihx < n; ihx++) hx[ihx] = 0.0; int max_nFrames = ((AdditionalData *) adata)->max_nFrames; int nFeatures = ((AdditionalData *) adata)->nFeatures; vector<int> vUsedFrame = ((AdditionalData *) adata)->vUsedFrame; int nBase = ((AdditionalData*) adata)->nBase; vector<Theta> vTheta = ((AdditionalData *) adata)->vTheta; vector<double> measurements = ((AdditionalData *) adata)->measurements; for (int iFeature = 0; iFeature < nFeatures; iFeature++) { double *xyz = p+vUsedFrame.size()+nBase*3*iFeature; for (int iFrame = 0; iFrame < vUsedFrame.size(); iFrame++) { double *rt = p+iFrame; int iCamera = (int)((double)vUsedFrame[iFrame]/max_nFrames); int cFrame = vUsedFrame[iFrame] % max_nFrames; CvMat *P = cvCreateMat(3,4, CV_32FC1); for (int iP = 0; iP < 3; iP++) for (int jP = 0; jP < 4; jP++) cvSetReal2D(P, iP, jP, ((AdditionalData *) adata)->vdP[12*iFrame+iP*4+jP]); double dt = rt[0]; double t = (double)cFrame + dt; CvMat *B = cvCreateMat(1, nBase, CV_32FC1); cvSetReal2D(B, 0, 0, sqrt(1.0/(double)max_nFrames)); for (int iB = 1; iB < nBase; iB++) cvSetReal2D(B, 0, iB, sqrt(2.0/(double)max_nFrames)*cos((2*t-1)*(iB)*PI/2.0/(double)max_nFrames)); CvMat *thetaX = cvCreateMat(nBase,1, CV_32FC1); CvMat *thetaY = cvCreateMat(nBase,1, CV_32FC1); CvMat *thetaZ = cvCreateMat(nBase,1, CV_32FC1); for (int iTheta = 0; iTheta < nBase; iTheta++) cvSetReal2D(thetaX, iTheta, 0, xyz[iTheta]); for (int iTheta = 0; iTheta < nBase; iTheta++) cvSetReal2D(thetaY, iTheta, 0, xyz[nBase+iTheta]); for (int iTheta = 0; iTheta < nBase; iTheta++) cvSetReal2D(thetaZ, iTheta, 0, xyz[2*nBase+iTheta]); CvMat *X3 = cvCreateMat(1,1,CV_32FC1); CvMat *Y3 = cvCreateMat(1,1,CV_32FC1); CvMat *Z3 = cvCreateMat(1,1,CV_32FC1); cvMatMul(B, thetaX, X3); cvMatMul(B, thetaY, Y3); cvMatMul(B, thetaZ, Z3); CvMat *X = cvCreateMat(4,1,CV_32FC1); cvSetReal2D(X, 0, 0, cvGetReal2D(X3,0,0)); cvSetReal2D(X, 1, 0, cvGetReal2D(Y3,0,0)); cvSetReal2D(X, 2, 0, cvGetReal2D(Z3,0,0)); cvSetReal2D(X, 3, 0, 1); CvMat *x = cvCreateMat(3,1,CV_32FC1); cvMatMul(P, X, x); double pm_x = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); double pm_y = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); double m_x = measurements[2*(iFeature*vUsedFrame.size()+iFrame)]; double m_y = measurements[2*(iFeature*vUsedFrame.size()+iFrame)+1]; //hx[2*(iFeature*vUsedFrame.size()+iFrame)] = (pm_x-m_x)*(pm_x-m_x); //hx[2*(iFeature*vUsedFrame.size()+iFrame)+1] = (pm_y-m_y)*(pm_y-m_y); hx[2*(iFeature*vUsedFrame.size()+iFrame)] = pm_x/1e-6; hx[2*(iFeature*vUsedFrame.size()+iFrame)+1] = pm_y/1e-6; cvReleaseMat(&X); cvReleaseMat(&x); cvReleaseMat(&P); cvReleaseMat(&B); cvReleaseMat(&thetaX); cvReleaseMat(&thetaY); cvReleaseMat(&thetaZ); cvReleaseMat(&X3); cvReleaseMat(&Y3); cvReleaseMat(&Z3); } int error = 0; for (int iBase = 0; iBase < nBase; iBase++) { error += (xyz[iBase]-vTheta[iFeature].thetaX[iBase])*(xyz[iBase]-vTheta[iFeature].thetaX[iBase]); } for (int iBase = 0; iBase < nBase; iBase++) { error += (xyz[nBase+iBase]-vTheta[iFeature].thetaY[iBase])*(xyz[nBase+iBase]-vTheta[iFeature].thetaY[iBase]); } for (int iBase = 0; iBase < nBase; iBase++) { error += (xyz[2*nBase+iBase]-vTheta[iFeature].thetaZ[iBase])*(xyz[2*nBase+iBase]-vTheta[iFeature].thetaZ[iBase]); } hx[2*(nFeatures*vUsedFrame.size())+iFeature] = 0.0;//error/10; } //for (int i = 0; i < n; i++) // cout << hx[i] << " "; //cout << endl; } void ProjectionThetaonto2D_MOTSTR_LEVMAR(float *p, float *hx, int m, int n, void *adata_) { //for (int i = 0; i <n; i++) // hx[i] = 1; //return; //AdditionalData *adata = (AdditionalData *)adata_; //bool *isStatic = adata->isStatic; //int nFrames = adata->nFrames; //int nCameraParameters = adata->nCameraParameters; //int nImagePointParameters = adata->nImagePointPrameraters; //int nBase = adata->nBase; //int nFeature_static = adata->nFeature_static; //float *XYZ = p + nCameraParameters*nFrames; //float *rt; //float *xij; //int last = 0; ////for (int iFeature = 0; iFeature < ((AdditionalData*)adata_)->visibilityMask->rows; iFeature++) ////{ //// for (int iFrame = 0; iFrame < ((AdditionalData*)adata_)->visibilityMask->cols; iFrame++) //// { //// if (cvGetReal2D(((AdditionalData*)adata_)->visibilityMask, iFeature, iFrame)) //// { //// if (isStatic[iFeature]) //// { //// float x, y; //// //xij = hx + nImagePointParameters*last; //// rt = p + iFrame*nCameraParameters; //// XYZ = p + nFrames*nCameraParameters + iFeature*3; //// ProjectionThetaonto2D_MOTSTR_LEVMAR(iFrame, iFeature, (double*)rt, (double*)XYZ, (double)x, (double)y, adata); //// hx[nImagePointParameters*last] = 0; //// hx[nImagePointParameters*last+1] = 0; //// last++; //// } //// else //// { //// float x, y; //// //xij = hx + nImagePointParameters*last; //// rt = p + iFrame*nCameraParameters; //// XYZ = p + nFrames*nCameraParameters + nFeature_static*3 + (iFeature-nFeature_static)*3*nBase; //// ProjectionThetaonto2D_MOTSTR_LEVMAR(iFrame, iFeature, (double*)rt, (double*)XYZ, (double)x, (double)y, adata); //// hx[nImagePointParameters*last] = 0; //// hx[nImagePointParameters*last+1] = 0; //// last++; //// } //// } //// } ////} } void ProjectionThetaonto2D_MOTSTR_x(double *p, struct sba_crsm *idxij, int *rcidxs, int *rcsubs, double *hx, void *adata) { //int i, j; //int cnp, pnp, mnp; //double *pa, *pb, *pqr, *pt, *ppt, *pmeas, *Kparms, *pr0, lrot[4], trot[4]; ////int n; //int m, nnz; //AdditionalData *gl; //gl= (AdditionalData *)adata; //cnp=gl->nCameraParameters; //mnp=gl->nImagePointPrameraters; ////n=idxij->nr; //m=idxij->nc; //pa=p; // Pointer for camera //pb=p+m*cnp; // Point for xyz //for(j=0; j<m; ++j) //{ // /* j-th camera parameters */ // double *rt = pa + j*cnp; // double *xyz; // nnz=sba_crsm_col_elmidxs(idxij, j, rcidxs, rcsubs); /* find nonzero hx_ij, i=0...n-1 */ // for(i=0; i<nnz; ++i) // { // if (gl->isStatic[i]) // { // xyz = pb + rcsubs[i]*3; // } // else // { // xyz = pb + gl->nFeature_static*3 + (rcsubs[i]-gl->nFeature_static)*3*gl->nBase; // } // double *xij = hx + idxij->val[rcidxs[i]]*mnp; // set pmeas to point to hx_ij // ProjectionThetaonto2D_MOTSTR(j, i, rt, xyz, xij, adata); // //calcImgProjFullR(Kparms, trot, pt, ppt, pmeas); // evaluate Q in pmeas // //calcImgProj(Kparms, pr0, pqr, pt, ppt, pmeas); // evaluate Q in pmeas // } //} } void PrintSBAInfo(double *info) { cout << "SBA result -------" << endl; cout << "Mean squared reprojection error: " << info[0] << " ==> " << info[1] << endl; cout << "Total number of iteration: " << info[5] << endl; cout << "Reason for terminating: "; if (info[6] == 1) cout << "Stopped by small ||J^T e||" <<endl; else if (info[6] == 2) cout << "Stopped by small ||delta||" << endl; else if (info[6] == 3) cout << "Stopped by maximum iteration" << endl; else if (info[6] == 4) cout << "Stopped by small relative reduction in ||e||" << endl; else if (info[6] == 5) cout << "Stopped by small ||e||" << endl; else if (info[6] == 6) cout << "Stopped due to excessive failed attempts to increase damping for getting a positive definite normal equations" << endl; else if (info[6] == 7) cout << "Stopped due to infinite values in the coordinates of the set of predicted projections x" << endl; cout << "Total number of projection function evaluation: " << info[7] <<endl; cout << "Total number of times that normal equations were solved: " << info[9] << endl; } void PrintSBAInfo(double *info, int nVisiblePoints) { cout << "SBA result -------" << endl; cout << "Mean squared reprojection error: " << info[0]/(double)nVisiblePoints << " ==> " << info[1]/(double)nVisiblePoints << endl; cout << "Total number of iteration: " << info[5] << endl; cout << "Reason for terminating: "; if (info[6] == 1) cout << "Stopped by small ||J^T e||" <<endl; else if (info[6] == 2) cout << "Stopped by small ||delta||" << endl; else if (info[6] == 3) cout << "Stopped by maximum iteration" << endl; else if (info[6] == 4) cout << "Stopped by small relative reduction in ||e||" << endl; else if (info[6] == 5) cout << "Stopped by small ||e||" << endl; else if (info[6] == 6) cout << "Stopped due to excessive failed attempts to increase damping for getting a positive definite normal equations" << endl; else if (info[6] == 7) cout << "Stopped due to infinite values in the coordinates of the set of predicted projections x" << endl; cout << "Total number of projection function evaluation: " << info[7] <<endl; cout << "Total number of times that normal equations were solved: " << info[9] << endl; } void RetrieveParameterFromSBA(double *dCameraParameter, CvMat *K, vector<CvMat *> &cP, CvMat *X, vector<int> visibleStructureID) { int nFrames = cP.size(); cP.clear(); CvMat *P; for (int iFrame = 0; iFrame < nFrames; iFrame++) { CvMat *q = cvCreateMat(4,1,CV_32FC1); CvMat *C = cvCreateMat(3,1,CV_32FC1); cvSetReal2D(q, 0, 0, dCameraParameter[7*iFrame]); cvSetReal2D(q, 1, 0, dCameraParameter[7*iFrame+1]); cvSetReal2D(q, 2, 0, dCameraParameter[7*iFrame+2]); cvSetReal2D(q, 3, 0, dCameraParameter[7*iFrame+3]); cvSetReal2D(C, 0, 0, dCameraParameter[7*iFrame+4]); cvSetReal2D(C, 1, 0, dCameraParameter[7*iFrame+5]); cvSetReal2D(C, 2, 0, dCameraParameter[7*iFrame+6]); CvMat *R = cvCreateMat(3,3,CV_32FC1); CvMat *P_ = cvCreateMat(3,4,CV_32FC1); P = cvCreateMat(3,4,CV_32FC1); Quaternion2Rotation(q, R); CreateCameraMatrix(R, C, K, P_); P = cvCloneMat(P_); cP.push_back(P); cvReleaseMat(&q); cvReleaseMat(&C); cvReleaseMat(&R); cvReleaseMat(&P_); } P = cvCreateMat(3,4,CV_32FC1); cvReleaseMat(&P); CvMat *X_ = cvCreateMat(visibleStructureID.size(), 3, CV_32FC1); for (int iFeature = 0; iFeature < visibleStructureID.size(); iFeature++) { cvSetReal2D(X_, iFeature, 0, dCameraParameter[7*cP.size()+3*iFeature]); cvSetReal2D(X_, iFeature, 1, dCameraParameter[7*cP.size()+3*iFeature+1]); cvSetReal2D(X_, iFeature, 2, dCameraParameter[7*cP.size()+3*iFeature+2]); } SetIndexedMatRowwise(X, visibleStructureID, X_); } void RetrieveParameterFromSBA_mem(double *dCameraParameter, vector<Camera> vCamera, vector<CvMat *> &cP, CvMat *X, vector<int> visibleStructureID, vector<int> vUsedFrame, int max_nFrames) { int nFrames = cP.size(); for (int i = 0; i < cP.size(); i++) cvReleaseMat(&(cP[i])); cP.clear(); for (int iFrame = 0; iFrame < nFrames; iFrame++) { int frame = vUsedFrame[iFrame]%max_nFrames; int cam = (int) vUsedFrame[iFrame]/max_nFrames; CvMat *q = cvCreateMat(4,1,CV_32FC1); CvMat *C = cvCreateMat(3,1,CV_32FC1); cvSetReal2D(q, 0, 0, dCameraParameter[7*iFrame]); cvSetReal2D(q, 1, 0, dCameraParameter[7*iFrame+1]); cvSetReal2D(q, 2, 0, dCameraParameter[7*iFrame+2]); cvSetReal2D(q, 3, 0, dCameraParameter[7*iFrame+3]); cvSetReal2D(C, 0, 0, dCameraParameter[7*iFrame+4]); cvSetReal2D(C, 1, 0, dCameraParameter[7*iFrame+5]); cvSetReal2D(C, 2, 0, dCameraParameter[7*iFrame+6]); CvMat *R = cvCreateMat(3,3,CV_32FC1); CvMat *P = cvCreateMat(3,4,CV_32FC1); Quaternion2Rotation(q, R); CreateCameraMatrix(R, C, vCamera[cam].vK[frame], P); cP.push_back(P); cvReleaseMat(&q); cvReleaseMat(&C); cvReleaseMat(&R); } CvMat *X_ = cvCreateMat(visibleStructureID.size(), 3, CV_32FC1); for (int iFeature = 0; iFeature < visibleStructureID.size(); iFeature++) { cvSetReal2D(X_, iFeature, 0, dCameraParameter[7*cP.size()+3*iFeature]); cvSetReal2D(X_, iFeature, 1, dCameraParameter[7*cP.size()+3*iFeature+1]); cvSetReal2D(X_, iFeature, 2, dCameraParameter[7*cP.size()+3*iFeature+2]); } SetIndexedMatRowwise(X, visibleStructureID, X_); cvReleaseMat(&X_); } void RetrieveParameterFromSBA(double *dCameraParameter, vector<Camera> vCamera, vector<CvMat *> &cP, CvMat *X, vector<int> visibleStructureID, vector<int> vUsedFrame, int max_nFrames) { int nFrames = cP.size(); cP.clear(); for (int iFrame = 0; iFrame < nFrames; iFrame++) { int frame = vUsedFrame[iFrame]%max_nFrames; int cam = (int) vUsedFrame[iFrame]/max_nFrames; CvMat *q = cvCreateMat(4,1,CV_32FC1); CvMat *C = cvCreateMat(3,1,CV_32FC1); cvSetReal2D(q, 0, 0, dCameraParameter[7*iFrame]); cvSetReal2D(q, 1, 0, dCameraParameter[7*iFrame+1]); cvSetReal2D(q, 2, 0, dCameraParameter[7*iFrame+2]); cvSetReal2D(q, 3, 0, dCameraParameter[7*iFrame+3]); cvSetReal2D(C, 0, 0, dCameraParameter[7*iFrame+4]); cvSetReal2D(C, 1, 0, dCameraParameter[7*iFrame+5]); cvSetReal2D(C, 2, 0, dCameraParameter[7*iFrame+6]); CvMat *R = cvCreateMat(3,3,CV_32FC1); CvMat *P = cvCreateMat(3,4,CV_32FC1); Quaternion2Rotation(q, R); CreateCameraMatrix(R, C, vCamera[cam].K, P); cP.push_back(P); cvReleaseMat(&q); cvReleaseMat(&C); cvReleaseMat(&R); } CvMat *X_ = cvCreateMat(visibleStructureID.size(), 3, CV_32FC1); for (int iFeature = 0; iFeature < visibleStructureID.size(); iFeature++) { cvSetReal2D(X_, iFeature, 0, dCameraParameter[7*cP.size()+3*iFeature]); cvSetReal2D(X_, iFeature, 1, dCameraParameter[7*cP.size()+3*iFeature+1]); cvSetReal2D(X_, iFeature, 2, dCameraParameter[7*cP.size()+3*iFeature+2]); } SetIndexedMatRowwise(X, visibleStructureID, X_); cvReleaseMat(&X_); } void RetrieveParameterFromSBA_KRT(double *dCameraParameter, vector<Camera> vCamera, vector<CvMat *> &cP, CvMat *X, vector<int> visibleStructureID, vector<int> vUsedFrame, int max_nFrames) { int nFrames = cP.size(); cP.clear(); CvMat *P; for (int iFrame = 0; iFrame < nFrames; iFrame++) { int frame = vUsedFrame[iFrame]%max_nFrames; int cam = (int) vUsedFrame[iFrame]/max_nFrames; CvMat *q = cvCreateMat(4,1,CV_32FC1); CvMat *C = cvCreateMat(3,1,CV_32FC1); cvSetReal2D(q, 0, 0, dCameraParameter[11*iFrame]); cvSetReal2D(q, 1, 0, dCameraParameter[11*iFrame+1]); cvSetReal2D(q, 2, 0, dCameraParameter[11*iFrame+2]); cvSetReal2D(q, 3, 0, dCameraParameter[11*iFrame+3]); cvSetReal2D(C, 0, 0, dCameraParameter[11*iFrame+4]); cvSetReal2D(C, 1, 0, dCameraParameter[11*iFrame+5]); cvSetReal2D(C, 2, 0, dCameraParameter[11*iFrame+6]); vector<int>::const_iterator it = find(vCamera[cam].vTakenFrame.begin(), vCamera[cam].vTakenFrame.end(), frame); if (it == vCamera[cam].vTakenFrame.end()) return; int iTakenFrame = (int) (it - vCamera[cam].vTakenFrame.begin()); cvSetReal2D(vCamera[cam].vK[iTakenFrame], 0, 0, dCameraParameter[11*iFrame+7]); cvSetReal2D(vCamera[cam].vK[iTakenFrame], 1, 1, dCameraParameter[11*iFrame+8]); cvSetReal2D(vCamera[cam].vK[iTakenFrame], 0, 2, dCameraParameter[11*iFrame+9]); cvSetReal2D(vCamera[cam].vK[iTakenFrame], 1, 2, dCameraParameter[11*iFrame+10]); CvMat *R = cvCreateMat(3,3,CV_32FC1); CvMat *P_ = cvCreateMat(3,4,CV_32FC1); P = cvCreateMat(3,4,CV_32FC1); Quaternion2Rotation(q, R); CreateCameraMatrix(R, C, vCamera[cam].vK[iTakenFrame], P_); P = cvCloneMat(P_); cP.push_back(P); cvReleaseMat(&q); cvReleaseMat(&C); cvReleaseMat(&R); cvReleaseMat(&P_); } P = cvCreateMat(3,4,CV_32FC1); cvReleaseMat(&P); CvMat *X_ = cvCreateMat(visibleStructureID.size(), 3, CV_32FC1); for (int iFeature = 0; iFeature < visibleStructureID.size(); iFeature++) { cvSetReal2D(X_, iFeature, 0, dCameraParameter[11*cP.size()+3*iFeature]); cvSetReal2D(X_, iFeature, 1, dCameraParameter[11*cP.size()+3*iFeature+1]); cvSetReal2D(X_, iFeature, 2, dCameraParameter[11*cP.size()+3*iFeature+2]); } SetIndexedMatRowwise(X, visibleStructureID, X_); cvReleaseMat(&X_); } void RetrieveParameterFromSBA_TEMPORAL(double *dCameraParameter, vector<Camera> &vCamera, vector<Theta> &vTheta) { int cFrame = 0; for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) { for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++) { vCamera[iCamera].vTakenInstant.push_back(vCamera[iCamera].vTakenFrame[iFrame]+dCameraParameter[cFrame]); cout << vCamera[iCamera].vTakenFrame[iFrame]+dCameraParameter[cFrame] << " "; cFrame++; } } for (int iTheta = 0; iTheta < vTheta.size(); iTheta++) { Theta theta; theta = vTheta[iTheta]; theta.thetaX.clear(); theta.thetaY.clear(); theta.thetaZ.clear(); for (int i = 0; i < vTheta[0].thetaX.size(); i++) { theta.thetaX.push_back(dCameraParameter[cFrame]); cFrame++; } for (int i = 0; i < vTheta[0].thetaX.size(); i++) { theta.thetaY.push_back(dCameraParameter[cFrame]); cFrame++; } for (int i = 0; i < vTheta[0].thetaX.size(); i++) { theta.thetaZ.push_back(dCameraParameter[cFrame]); cFrame++; } vTheta[iTheta] = theta; } } void RetrieveParameterFromSBA_KDRT(double *dCameraParameter, vector<Camera> vCamera, vector<CvMat *> &cP, CvMat *X, vector<int> visibleStructureID, vector<int> vUsedFrame, int max_nFrames) { int nFrames = cP.size(); cP.clear(); CvMat *P; for (int iFrame = 0; iFrame < nFrames; iFrame++) { int frame = vUsedFrame[iFrame]%max_nFrames; int cam = (int) vUsedFrame[iFrame]/max_nFrames; CvMat *q = cvCreateMat(4,1,CV_32FC1); CvMat *C = cvCreateMat(3,1,CV_32FC1); cvSetReal2D(q, 0, 0, dCameraParameter[13*iFrame]); cvSetReal2D(q, 1, 0, dCameraParameter[13*iFrame+1]); cvSetReal2D(q, 2, 0, dCameraParameter[13*iFrame+2]); cvSetReal2D(q, 3, 0, dCameraParameter[13*iFrame+3]); cvSetReal2D(C, 0, 0, dCameraParameter[13*iFrame+4]); cvSetReal2D(C, 1, 0, dCameraParameter[13*iFrame+5]); cvSetReal2D(C, 2, 0, dCameraParameter[13*iFrame+6]); vector<int>::const_iterator it = find(vCamera[cam].vTakenFrame.begin(), vCamera[cam].vTakenFrame.end(), frame); if (it == vCamera[cam].vTakenFrame.end()) return; int iTakenFrame = (int) (it - vCamera[cam].vTakenFrame.begin()); cvSetReal2D(vCamera[cam].vK[iTakenFrame], 0, 0, dCameraParameter[13*iFrame+7]); cvSetReal2D(vCamera[cam].vK[iTakenFrame], 1, 1, dCameraParameter[13*iFrame+8]); cvSetReal2D(vCamera[cam].vK[iTakenFrame], 0, 2, dCameraParameter[13*iFrame+9]); cvSetReal2D(vCamera[cam].vK[iTakenFrame], 1, 2, dCameraParameter[13*iFrame+10]); vCamera[cam].vk1[iTakenFrame] = dCameraParameter[13*iFrame+11]; vCamera[cam].vk2[iTakenFrame] = dCameraParameter[13*iFrame+12]; CvMat *R = cvCreateMat(3,3,CV_32FC1); CvMat *P_ = cvCreateMat(3,4,CV_32FC1); P = cvCreateMat(3,4,CV_32FC1); Quaternion2Rotation(q, R); CreateCameraMatrix(R, C, vCamera[cam].vK[iTakenFrame], P_); P = cvCloneMat(P_); cP.push_back(P); cvReleaseMat(&q); cvReleaseMat(&C); cvReleaseMat(&R); cvReleaseMat(&P_); } P = cvCreateMat(3,4,CV_32FC1); cvReleaseMat(&P); CvMat *X_ = cvCreateMat(visibleStructureID.size(), 3, CV_32FC1); for (int iFeature = 0; iFeature < visibleStructureID.size(); iFeature++) { cvSetReal2D(X_, iFeature, 0, dCameraParameter[13*cP.size()+3*iFeature]); cvSetReal2D(X_, iFeature, 1, dCameraParameter[13*cP.size()+3*iFeature+1]); cvSetReal2D(X_, iFeature, 2, dCameraParameter[13*cP.size()+3*iFeature+2]); } SetIndexedMatRowwise(X, visibleStructureID, X_); cvReleaseMat(&X_); } void RetrieveParameterFromGBA(double *dCameraParameter, CvMat *K, vector<Camera> &vCamera, vector<Theta> &vTheta, int nFrames) { CvMat *P; for (int cFrame = 0; cFrame < nFrames*vCamera.size(); cFrame++) { int iFrame = cFrame % nFrames; int iCamera = (int) cFrame / nFrames; vector<int>::const_iterator it = find(vCamera[iCamera].vTakenFrame.begin(), vCamera[iCamera].vTakenFrame.end(), iFrame); if (it == vCamera[iCamera].vTakenFrame.end()) continue; CvMat *q = cvCreateMat(4,1,CV_32FC1); CvMat *C = cvCreateMat(3,1,CV_32FC1); cvSetReal2D(q, 0, 0, dCameraParameter[7*cFrame]); cvSetReal2D(q, 1, 0, dCameraParameter[7*cFrame+1]); cvSetReal2D(q, 2, 0, dCameraParameter[7*cFrame+2]); cvSetReal2D(q, 3, 0, dCameraParameter[7*cFrame+3]); cvSetReal2D(C, 0, 0, dCameraParameter[7*cFrame+4]); cvSetReal2D(C, 1, 0, dCameraParameter[7*cFrame+5]); cvSetReal2D(C, 2, 0, dCameraParameter[7*cFrame+6]); CvMat *R = cvCreateMat(3,3,CV_32FC1); CvMat *P_ = cvCreateMat(3,4,CV_32FC1); P = cvCreateMat(3,4,CV_32FC1); Quaternion2Rotation(q, R); CreateCameraMatrix(R, C, K, P_); P = cvCloneMat(P_); int idx = (int) (it - vCamera[iCamera].vTakenFrame.begin()); vCamera[iCamera].vP[idx] = P; cvReleaseMat(&q); cvReleaseMat(&C); cvReleaseMat(&R); cvReleaseMat(&P_); } P = cvCreateMat(3,4,CV_32FC1); cvReleaseMat(&P); CvMat *A = cvCreateMat(nFrames, nFrames, CV_32FC1); GetDCTMappingMatrix(A, nFrames); CvMat *A1 = cvCreateMat(1, nFrames, CV_32FC1); GetSubMatRowwise(A, 0, 0, A1); for (int iTheta = 0; iTheta < vTheta.size(); iTheta++) { int nBase = vTheta[iTheta].thetaX.size(); if (vTheta[iTheta].isStatic) { CvMat *X = cvCreateMat(nFrames, 1, CV_32FC1); CvMat *theta1 = cvCreateMat(1,1,CV_32FC1); for (int iX = 0; iX < nFrames; iX++) { cvSetReal2D(X, iX, 0, dCameraParameter[7*nFrames*vCamera.size()+3*(1+nBase)*iTheta]); } cvMatMul(A1, X, theta1); vTheta[iTheta].thetaX[0] = cvGetReal2D(theta1, 0, 0); for (int iBase = 1; iBase < nBase; iBase++) vTheta[iTheta].thetaX[iBase] = 0; for (int iX = 0; iX < nFrames; iX++) { cvSetReal2D(X, iX, 0, dCameraParameter[7*nFrames*vCamera.size()+3*(1+nBase)*iTheta+1]); } cvMatMul(A1, X, theta1); vTheta[iTheta].thetaY[0] = cvGetReal2D(theta1, 0, 0); for (int iBase = 1; iBase < nBase; iBase++) vTheta[iTheta].thetaY[iBase] = 0; for (int iX = 0; iX < nFrames; iX++) { cvSetReal2D(X, iX, 0, dCameraParameter[7*nFrames*vCamera.size()+3*(1+nBase)*iTheta+2]); } cvMatMul(A1, X, theta1); vTheta[iTheta].thetaZ[0] = cvGetReal2D(theta1, 0, 0); for (int iBase = 1; iBase < nBase; iBase++) vTheta[iTheta].thetaZ[iBase] = 0; } else { for (int iBase = 0; iBase < nBase; iBase++) vTheta[iTheta].thetaX[iBase] = dCameraParameter[7*nFrames*vCamera.size()+3*(1+nBase)*iTheta+3+iBase]; for (int iBase = 0; iBase < nBase; iBase++) vTheta[iTheta].thetaY[iBase] = dCameraParameter[7*nFrames*vCamera.size()+3*(1+nBase)*iTheta+3+nBase+iBase]; for (int iBase = 0; iBase < nBase; iBase++) vTheta[iTheta].thetaZ[iBase] = dCameraParameter[7*nFrames*vCamera.size()+3*(1+nBase)*iTheta+3+2*nBase+iBase]; } } } void Projection3Donto2D_MOTSTR(int j, int i, double *rt, double *xyz, double *xij, void *adata) { CvMat *K = cvCreateMat(3,3,CV_32FC1); cvSetIdentity(K); int max_nFrames = ((AdditionalData *) adata)->max_nFrames; vector<int> vUsedFrame = ((AdditionalData *) adata)->vUsedFrame; int iCamera = (int)((double)vUsedFrame[j]/max_nFrames); //double *intrinsic = (((AdditionalData *) adata)->vIntrinsic)[iCamera]; cvSetReal2D(K, 0, 0, ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[0]); cvSetReal2D(K, 1, 1, ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[1]); cvSetReal2D(K, 0, 2, ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[2]); cvSetReal2D(K, 1, 2, ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[3]); CvMat *q = cvCreateMat(4,1,CV_32FC1); CvMat *C = cvCreateMat(3,1,CV_32FC1); CvMat *R = cvCreateMat(3,3,CV_32FC1); cvSetReal2D(q, 0, 0, rt[0]); cvSetReal2D(q, 1, 0, rt[1]); cvSetReal2D(q, 2, 0, rt[2]); cvSetReal2D(q, 3, 0, rt[3]); cvSetReal2D(C, 0, 0, rt[4]); cvSetReal2D(C, 1, 0, rt[5]); cvSetReal2D(C, 2, 0, rt[6]); Quaternion2Rotation(q, R); CvMat *temp33 = cvCreateMat(3,3,CV_32FC1); CvMat *P = cvCreateMat(3,4,CV_32FC1); cvMatMul(K, R, temp33); cvSetIdentity(P); ScalarMul(C, -1, C); SetSubMat(P, 0,3,C); cvMatMul(temp33, P, P); CvMat *X = cvCreateMat(4,1,CV_32FC1); cvSetReal2D(X, 0, 0, xyz[0]); cvSetReal2D(X, 1, 0, xyz[1]); cvSetReal2D(X, 2, 0, xyz[2]); cvSetReal2D(X, 3, 0, 1); CvMat *x = cvCreateMat(3,1,CV_32FC1); cvMatMul(P, X, x); if (j == 1) int k = 1; xij[0] = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); xij[1] = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); cvReleaseMat(&K); cvReleaseMat(&X); cvReleaseMat(&x); cvReleaseMat(&P); cvReleaseMat(&temp33); cvReleaseMat(&q); cvReleaseMat(&C); cvReleaseMat(&R); } void Projection3Donto2D_MOTSTR_fast(int j, int i, double *rt, double *xyz, double *xij, void *adata) { int max_nFrames = ((AdditionalData *) adata)->max_nFrames; vector<int> vUsedFrame = ((AdditionalData *) adata)->vUsedFrame; int iCamera = (int)((double)vUsedFrame[j]/max_nFrames); int iFrame = vUsedFrame[j] % max_nFrames; if (j == 1) int k = 1; // Set intrinsic parameter double K11 = ((((AdditionalData *) adata)->vIntrinsic)[iFrame])[0]; double K12 = 0; double K13 = ((((AdditionalData *) adata)->vIntrinsic)[iFrame])[2]; double K21 = 0; double K22 = ((((AdditionalData *) adata)->vIntrinsic)[iFrame])[1]; double K23 = ((((AdditionalData *) adata)->vIntrinsic)[iFrame])[3]; double K31 = 0; double K32 = 0; double K33 = 1; // Set orientation double qw = rt[0]; double qx = rt[1]; double qy = rt[2]; double qz = rt[3]; double q_norm = sqrt(qw*qw + qx*qx + qy*qy + qz*qz); qw /= q_norm; qx /= q_norm; qy /= q_norm; qz /= q_norm; double R11 = 1.0-2*qy*qy-2*qz*qz; double R12 = 2*qx*qy-2*qz*qw; double R13 = 2*qx*qz+2*qy*qw; double R21 = 2*qx*qy+2*qz*qw; double R22 = 1.0-2*qx*qx-2*qz*qz; double R23 = 2*qz*qy-2*qx*qw; double R31 = 2*qx*qz-2*qy*qw; double R32 = 2*qy*qz+2*qx*qw; double R33 = 1.0-2*qx*qx-2*qy*qy; //cout << R11 << " " << R12 << " " << R13 << endl; //cout << R21 << " " << R22 << " " << R23 << endl; //cout << R31 << " " << R32 << " " << R33 << endl; // Set translation double C1 = rt[4]; double C2 = rt[5]; double C3 = rt[6]; double X1 = xyz[0]; double X2 = xyz[1]; double X3 = xyz[2]; // Building projection double RX1 = R11*X1+R12*X2+R13*X3; double RX2 = R21*X1+R22*X2+R23*X3; double RX3 = R31*X1+R32*X2+R33*X3; double KRX1 = K11*RX1+K12*RX2+K13*RX3; double KRX2 = K21*RX1+K22*RX2+K23*RX3; double KRX3 = K31*RX1+K32*RX2+K33*RX3; double RC1 = R11*C1+R12*C2+R13*C3; double RC2 = R21*C1+R22*C2+R23*C3; double RC3 = R31*C1+R32*C2+R33*C3; double KRC1 = K11*RC1+K12*RC2+K13*RC3; double KRC2 = K21*RC1+K22*RC2+K23*RC3; double KRC3 = K31*RC1+K32*RC2+K33*RC3; double proj1 = KRX1-KRC1; double proj2 = KRX2-KRC2; double proj3 = KRX3-KRC3; xij[0] = proj1/proj3; xij[1] = proj2/proj3; } void Projection3Donto2D_MOTSTR_fast_Distortion(int j, int i, double *rt, double *xyz, double *xij, void *adata) { int max_nFrames = ((AdditionalData *) adata)->max_nFrames; vector<int> vUsedFrame = ((AdditionalData *) adata)->vUsedFrame; int iCamera = (int)((double)vUsedFrame[j]/max_nFrames); double omega = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[4]; double tan_omega_half_2 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[5]; if (j == 1) int k = 1; if (j == 2) int k = 1; // Set intrinsic parameter double K11 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[0]; double K12 = 0; double K13 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[2]; double K21 = 0; double K22 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[1]; double K23 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[3]; double K31 = 0; double K32 = 0; double K33 = 1; // Set orientation double qw = rt[0]; double qx = rt[1]; double qy = rt[2]; double qz = rt[3]; double q_norm = sqrt(qw*qw + qx*qx + qy*qy + qz*qz); qw /= q_norm; qx /= q_norm; qy /= q_norm; qz /= q_norm; double R11 = 1.0-2*qy*qy-2*qz*qz; double R12 = 2*qx*qy-2*qz*qw; double R13 = 2*qx*qz+2*qy*qw; double R21 = 2*qx*qy+2*qz*qw; double R22 = 1.0-2*qx*qx-2*qz*qz; double R23 = 2*qz*qy-2*qx*qw; double R31 = 2*qx*qz-2*qy*qw; double R32 = 2*qy*qz+2*qx*qw; double R33 = 1.0-2*qx*qx-2*qy*qy; //cout << R11 << " " << R12 << " " << R13 << endl; //cout << R21 << " " << R22 << " " << R23 << endl; //cout << R31 << " " << R32 << " " << R33 << endl; // Set translation double C1 = rt[4]; double C2 = rt[5]; double C3 = rt[6]; double X1 = xyz[0]; double X2 = xyz[1]; double X3 = xyz[2]; // Building projection double RX1 = R11*X1+R12*X2+R13*X3; double RX2 = R21*X1+R22*X2+R23*X3; double RX3 = R31*X1+R32*X2+R33*X3; double KRX1 = K11*RX1+K12*RX2+K13*RX3; double KRX2 = K21*RX1+K22*RX2+K23*RX3; double KRX3 = K31*RX1+K32*RX2+K33*RX3; double RC1 = R11*C1+R12*C2+R13*C3; double RC2 = R21*C1+R22*C2+R23*C3; double RC3 = R31*C1+R32*C2+R33*C3; double KRC1 = K11*RC1+K12*RC2+K13*RC3; double KRC2 = K21*RC1+K22*RC2+K23*RC3; double KRC3 = K31*RC1+K32*RC2+K33*RC3; double proj1 = KRX1-KRC1; double proj2 = KRX2-KRC2; double proj3 = KRX3-KRC3; double u = proj1/proj3; double v = proj2/proj3; double u_n = u/K11 - K13/K11; double v_n = v/K22 - K23/K22; double r_u = sqrt(u_n*u_n+v_n*v_n); double r_d = 1/omega*atan(r_u*tan_omega_half_2); double u_d_n = r_d/r_u * u_n; double v_d_n = r_d/r_u * v_n; double u_d = u_d_n*K11 + K13; double v_d = v_d_n*K22 + K23; xij[0] = u_d; xij[1] = v_d; } void Projection3Donto2D_MOTSTR_fast_Distortion_ObstacleDetection(int j, int i, double *rt, double *xyz, double *xij, void *adata) { int max_nFrames = ((AdditionalData *) adata)->max_nFrames; vector<int> vUsedFrame = ((AdditionalData *) adata)->vUsedFrame; int iCamera = (int)((double)vUsedFrame[j]/max_nFrames); double omega = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[4]; double tan_omega_half_2 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[5]; double princ_x1 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[6]; double princ_y1 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[7]; // Set intrinsic parameter double K11 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[0]; double K12 = 0; double K13 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[2]; double K21 = 0; double K22 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[1]; double K23 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[3]; double K31 = 0; double K32 = 0; double K33 = 1; // Set orientation double qw = rt[0]; double qx = rt[1]; double qy = rt[2]; double qz = rt[3]; double q_norm = sqrt(qw*qw + qx*qx + qy*qy + qz*qz); qw /= q_norm; qx /= q_norm; qy /= q_norm; qz /= q_norm; double R11 = 1.0-2*qy*qy-2*qz*qz; double R12 = 2*qx*qy-2*qz*qw; double R13 = 2*qx*qz+2*qy*qw; double R21 = 2*qx*qy+2*qz*qw; double R22 = 1.0-2*qx*qx-2*qz*qz; double R23 = 2*qz*qy-2*qx*qw; double R31 = 2*qx*qz-2*qy*qw; double R32 = 2*qy*qz+2*qx*qw; double R33 = 1.0-2*qx*qx-2*qy*qy; //cout << R11 << " " << R12 << " " << R13 << endl; //cout << R21 << " " << R22 << " " << R23 << endl; //cout << R31 << " " << R32 << " " << R33 << endl; // Set translation double C1 = rt[4]; double C2 = rt[5]; double C3 = rt[6]; double X1 = xyz[0]; double X2 = xyz[1]; double X3 = xyz[2]; // Building projection double RX1 = R11*X1+R12*X2+R13*X3; double RX2 = R21*X1+R22*X2+R23*X3; double RX3 = R31*X1+R32*X2+R33*X3; double KRX1 = K11*RX1+K12*RX2+K13*RX3; double KRX2 = K21*RX1+K22*RX2+K23*RX3; double KRX3 = K31*RX1+K32*RX2+K33*RX3; double RC1 = R11*C1+R12*C2+R13*C3; double RC2 = R21*C1+R22*C2+R23*C3; double RC3 = R31*C1+R32*C2+R33*C3; double KRC1 = K11*RC1+K12*RC2+K13*RC3; double KRC2 = K21*RC1+K22*RC2+K23*RC3; double KRC3 = K31*RC1+K32*RC2+K33*RC3; double proj1 = KRX1-KRC1; double proj2 = KRX2-KRC2; double proj3 = KRX3-KRC3; double u = proj1/proj3; double v = proj2/proj3; //double u_n = u/K11 - K13/K11; //double v_n = v/K22 - K23/K22; double u_n = u - princ_x1; double v_n = v - princ_y1; double r_u = sqrt(u_n*u_n+v_n*v_n); double r_d = 1/omega*atan(r_u*tan_omega_half_2); double u_d_n = r_d/r_u * u_n; double v_d_n = r_d/r_u * v_n; double u_d = u_d_n + princ_x1; double v_d = v_d_n + princ_y1; xij[0] = u_d; xij[1] = v_d; } void Projection3Donto2D_KMOTSTR(int j, int i, double *rt, double *xyz, double *xij, void *adata) { CvMat *K = cvCreateMat(3,3,CV_32FC1); cvSetIdentity(K); //int max_nFrames = ((AdditionalData *) adata)->max_nFrames; //vector<int> vUsedFrame = ((AdditionalData *) adata)->vUsedFrame; //int iCamera = (int)((double)vUsedFrame[j]/max_nFrames); //double *intrinsic = (((AdditionalData *) adata)->vIntrinsic)[iCamera]; //cvSetReal2D(K, 0, 0, intrinsic[0]); //cvSetReal2D(K, 1, 1, intrinsic[1]); //cvSetReal2D(K, 0, 2, intrinsic[2]); //cvSetReal2D(K, 1, 2, intrinsic[3]); CvMat *q = cvCreateMat(4,1,CV_32FC1); CvMat *C = cvCreateMat(3,1,CV_32FC1); CvMat *R = cvCreateMat(3,3,CV_32FC1); cvSetReal2D(q, 0, 0, rt[0]); cvSetReal2D(q, 1, 0, rt[1]); cvSetReal2D(q, 2, 0, rt[2]); cvSetReal2D(q, 3, 0, rt[3]); cvSetReal2D(C, 0, 0, rt[4]); cvSetReal2D(C, 1, 0, rt[5]); cvSetReal2D(C, 2, 0, rt[6]); cvSetReal2D(K, 0, 0, rt[7]); cvSetReal2D(K, 1, 1, rt[8]); cvSetReal2D(K, 0, 2, rt[9]); cvSetReal2D(K, 1, 2, rt[10]); Quaternion2Rotation(q, R); CvMat *temp33 = cvCreateMat(3,3,CV_32FC1); CvMat *P = cvCreateMat(3,4,CV_32FC1); cvMatMul(K, R, temp33); cvSetIdentity(P); ScalarMul(C, -1, C); SetSubMat(P, 0,3,C); cvMatMul(temp33, P, P); CvMat *X = cvCreateMat(4,1,CV_32FC1); cvSetReal2D(X, 0, 0, xyz[0]); cvSetReal2D(X, 1, 0, xyz[1]); cvSetReal2D(X, 2, 0, xyz[2]); cvSetReal2D(X, 3, 0, 1); CvMat *x = cvCreateMat(3,1,CV_32FC1); cvMatMul(P, X, x); xij[0] = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); xij[1] = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); cvReleaseMat(&K); cvReleaseMat(&X); cvReleaseMat(&x); cvReleaseMat(&P); cvReleaseMat(&temp33); cvReleaseMat(&q); cvReleaseMat(&C); cvReleaseMat(&R); } void ProjectionThetaonto2D_TEMPORAL(int j, int i, double *rt, double *xyz, double *xij, void *adata) { int max_nFrames = ((AdditionalData *) adata)->max_nFrames; vector<int> vUsedFrame = ((AdditionalData *) adata)->vUsedFrame; int iCamera = (int)((double)vUsedFrame[j]/max_nFrames); int cFrame = vUsedFrame[j] % max_nFrames; int nBase = ((AdditionalData*) adata)->nBase; vector<Theta> vTheta = ((AdditionalData *) adata)->vTheta; CvMat *P = cvCreateMat(3,4, CV_32FC1); for (int iP = 0; iP < 3; iP++) for (int jP = 0; jP < 4; jP++) cvSetReal2D(P, iP, jP, ((AdditionalData *) adata)->vdP[12*j+iP*4+jP]); double dt = rt[0]; double t = cFrame + dt; CvMat *B = cvCreateMat(1, nBase, CV_32FC1); cvSetReal2D(B, 0, 0, sqrt(1.0/(double)max_nFrames)); for (int iB = 1; iB < nBase; iB++) cvSetReal2D(B, 0, iB, sqrt(2.0/(double)max_nFrames)*cos((2*t-1)*(iB)*PI/2.0/(double)max_nFrames)); //PrintMat(B); CvMat *thetaX = cvCreateMat(nBase,1, CV_32FC1); CvMat *thetaY = cvCreateMat(nBase,1, CV_32FC1); CvMat *thetaZ = cvCreateMat(nBase,1, CV_32FC1); for (int iTheta = 0; iTheta < nBase; iTheta++) cvSetReal2D(thetaX, iTheta, 0, xyz[iTheta]); for (int iTheta = 0; iTheta < nBase; iTheta++) cvSetReal2D(thetaY, iTheta, 0, xyz[nBase+iTheta]); for (int iTheta = 0; iTheta < nBase; iTheta++) cvSetReal2D(thetaZ, iTheta, 0, xyz[2*nBase+iTheta]); //PrintMat(thetaX); //PrintMat(thetaY); //PrintMat(thetaZ); //for (int iTheta = 0; iTheta < nBase; iTheta++) // cout << xyz[iTheta] << " "; //cout << endl; CvMat *X3 = cvCreateMat(1,1,CV_32FC1); CvMat *Y3 = cvCreateMat(1,1,CV_32FC1); CvMat *Z3 = cvCreateMat(1,1,CV_32FC1); cvMatMul(B, thetaX, X3); cvMatMul(B, thetaY, Y3); cvMatMul(B, thetaZ, Z3); CvMat *X = cvCreateMat(4,1,CV_32FC1); cvSetReal2D(X, 0, 0, cvGetReal2D(X3,0,0)); cvSetReal2D(X, 1, 0, cvGetReal2D(Y3,0,0)); cvSetReal2D(X, 2, 0, cvGetReal2D(Z3,0,0)); cvSetReal2D(X, 3, 0, 1); CvMat *x = cvCreateMat(3,1,CV_32FC1); cvMatMul(P, X, x); xij[0] = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); xij[1] = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); int error = 0; for (int iBase = 0; iBase < nBase; iBase++) { error += (xyz[iBase]-vTheta[i].thetaX[iBase])*(xyz[iBase]-vTheta[i].thetaX[iBase]); } for (int iBase = 0; iBase < nBase; iBase++) { error += (xyz[nBase+iBase]-vTheta[i].thetaY[iBase])*(xyz[nBase+iBase]-vTheta[i].thetaY[iBase]); } for (int iBase = 0; iBase < nBase; iBase++) { error += (xyz[2*nBase+iBase]-vTheta[i].thetaZ[iBase])*(xyz[2*nBase+iBase]-vTheta[i].thetaZ[iBase]); } xij[2] = 10*error; xij[3] = 10*rt[0]; cvReleaseMat(&X); cvReleaseMat(&x); cvReleaseMat(&P); cvReleaseMat(&B); cvReleaseMat(&thetaX); cvReleaseMat(&thetaY); cvReleaseMat(&thetaZ); cvReleaseMat(&X3); cvReleaseMat(&Y3); cvReleaseMat(&Z3); } void Projection3Donto2D_KDMOTSTR(int j, int i, double *rt, double *xyz, double *xij, void *adata) { CvMat *K = cvCreateMat(3,3,CV_32FC1); cvSetIdentity(K); int max_nFrames = ((AdditionalData *) adata)->max_nFrames; vector<int> vUsedFrame = ((AdditionalData *) adata)->vUsedFrame; int iCamera = (int)((double)vUsedFrame[j]/max_nFrames); //double *intrinsic = (((AdditionalData *) adata)->vIntrinsic)[iCamera]; //cvSetReal2D(K, 0, 0, intrinsic[0]); //cvSetReal2D(K, 1, 1, intrinsic[1]); //cvSetReal2D(K, 0, 2, intrinsic[2]); //cvSetReal2D(K, 1, 2, intrinsic[3]); CvMat *q = cvCreateMat(4,1,CV_32FC1); CvMat *C = cvCreateMat(3,1,CV_32FC1); CvMat *R = cvCreateMat(3,3,CV_32FC1); cvSetReal2D(q, 0, 0, rt[0]); cvSetReal2D(q, 1, 0, rt[1]); cvSetReal2D(q, 2, 0, rt[2]); cvSetReal2D(q, 3, 0, rt[3]); cvSetReal2D(C, 0, 0, rt[4]); cvSetReal2D(C, 1, 0, rt[5]); cvSetReal2D(C, 2, 0, rt[6]); cvSetReal2D(K, 0, 0, rt[7]); cvSetReal2D(K, 1, 1, rt[8]); cvSetReal2D(K, 0, 2, rt[9]); cvSetReal2D(K, 1, 2, rt[10]); Quaternion2Rotation(q, R); double k11 = rt[7]; double k22 = rt[8]; double px = rt[9]; double py = rt[10]; double k1 = rt[11]; double k2 = rt[12]; CvMat *temp33 = cvCreateMat(3,3,CV_32FC1); CvMat *P = cvCreateMat(3,4,CV_32FC1); cvMatMul(K, R, temp33); cvSetIdentity(P); ScalarMul(C, -1, C); SetSubMat(P, 0,3,C); cvMatMul(temp33, P, P); CvMat *X = cvCreateMat(4,1,CV_32FC1); cvSetReal2D(X, 0, 0, xyz[0]); cvSetReal2D(X, 1, 0, xyz[1]); cvSetReal2D(X, 2, 0, xyz[2]); cvSetReal2D(X, 3, 0, 1); CvMat *x = cvCreateMat(3,1,CV_32FC1); cvMatMul(P, X, x); xij[0] = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); xij[1] = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); // taking into account distortion CvMat *invK = cvCreateMat(3,3,CV_32FC1); cvInvert(K, invK); double ik11 = cvGetReal2D(invK, 0, 0); double ik12 = cvGetReal2D(invK, 0, 1); double ik13 = cvGetReal2D(invK, 0, 2); double ik21 = cvGetReal2D(invK, 1, 0); double ik22 = cvGetReal2D(invK, 1, 1); double ik23 = cvGetReal2D(invK, 1, 2); double ik31 = cvGetReal2D(invK, 2, 0); double ik32 = cvGetReal2D(invK, 2, 1); double ik33 = cvGetReal2D(invK, 2, 2); double nz = (ik31*xij[0]+ik32*xij[1]+ik33); double nx = (ik11*xij[0]+ik12*xij[1]+ik13)/nz; double ny = (ik21*xij[0]+ik22*xij[1]+ik23)/nz; double r = sqrt((nx)*(nx)+(ny)*(ny)); double L = 1 + k1*r + k2*r*r; nx = L*(nx); ny = L*(ny); xij[0] = (k11*nx+px); xij[1] = (k22*ny+py); cvReleaseMat(&K); cvReleaseMat(&invK); cvReleaseMat(&X); cvReleaseMat(&x); cvReleaseMat(&P); cvReleaseMat(&temp33); cvReleaseMat(&q); cvReleaseMat(&C); cvReleaseMat(&R); } void ProjectionThetaonto2D_MOTSTR(int j, int i, double *rt, double *xyz, double *xij, void *adata) { //CvMat *K = cvCreateMat(3,3,CV_32FC1); //cvSetIdentity(K); //cvSetReal2D(K, 0, 0, ((AdditionalData *) adata)->intrinsic[0]); //cvSetReal2D(K, 1, 1, ((AdditionalData *) adata)->intrinsic[1]); //cvSetReal2D(K, 0, 2, ((AdditionalData *) adata)->intrinsic[2]); //cvSetReal2D(K, 1, 2, ((AdditionalData *) adata)->intrinsic[3]); //bool isStatic = ((AdditionalData *) adata)->isStatic[i]; //CvMat *q = cvCreateMat(4,1,CV_32FC1); //CvMat *C = cvCreateMat(3,1,CV_32FC1); //CvMat *R = cvCreateMat(3,3,CV_32FC1); //cvSetReal2D(q, 0, 0, rt[0]); //cvSetReal2D(q, 1, 0, rt[1]); //cvSetReal2D(q, 2, 0, rt[2]); //cvSetReal2D(q, 3, 0, rt[3]); //cvSetReal2D(C, 0, 0, rt[4]); //cvSetReal2D(C, 1, 0, rt[5]); //cvSetReal2D(C, 2, 0, rt[6]); //Quaternion2Rotation(q, R); //CvMat *temp33 = cvCreateMat(3,3,CV_32FC1); //CvMat *P = cvCreateMat(3,4,CV_32FC1); //cvMatMul(K, R, temp33); //cvSetIdentity(P); //ScalarMul(C, -1, C); //SetSubMat(P, 0,3,C); //cvMatMul(temp33, P, P); //if (!isStatic) //{ // int iFrame = j % ((AdditionalData *) adata)->nFrames; // int nBase = ((AdditionalData *) adata)->nBase; // int nFrames = ((AdditionalData *) adata)->nFrames; // CvMat *x = cvCreateMat(2,1,CV_32FC1); // CvMat *theta = cvCreateMat(3*nBase, 1, CV_32FC1); // for (int iTheta = 0; iTheta < 3*nBase; iTheta++) // cvSetReal2D(theta, iTheta, 0, xyz[iTheta]); // DCTProjection(P, theta, nFrames, iFrame, nBase, x); // xij[0] = cvGetReal2D(x, 0, 0); // xij[1] = cvGetReal2D(x, 1, 0); // cvReleaseMat(&x); // cvReleaseMat(&theta); //} //else //{ // CvMat *X = cvCreateMat(4,1,CV_32FC1); // cvSetReal2D(X, 0, 0, xyz[0]); // cvSetReal2D(X, 1, 0, xyz[1]); // cvSetReal2D(X, 2, 0, xyz[2]); // cvSetReal2D(X, 3, 0, 1); // CvMat *x = cvCreateMat(3,1,CV_32FC1); // cvMatMul(P, X, x); // // xij[0] = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); // xij[1] = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); // cvReleaseMat(&X); // cvReleaseMat(&x); //} //cvReleaseMat(&K); //cvReleaseMat(&P); //cvReleaseMat(&temp33); //cvReleaseMat(&q); //cvReleaseMat(&C); //cvReleaseMat(&R); } void ProjectionThetaonto2D_MOTSTR_LEVMAR(int j, int i, double *rt, double *xyz, double &xi, double &yi, void *adata) { //CvMat *K = cvCreateMat(3,3,CV_32FC1); //cvSetIdentity(K); //cvSetReal2D(K, 0, 0, ((AdditionalData *) adata)->intrinsic[0]); //cvSetReal2D(K, 1, 1, ((AdditionalData *) adata)->intrinsic[1]); //cvSetReal2D(K, 0, 2, ((AdditionalData *) adata)->intrinsic[2]); //cvSetReal2D(K, 1, 2, ((AdditionalData *) adata)->intrinsic[3]); //bool isStatic = ((AdditionalData *) adata)->isStatic[i]; //CvMat *q = cvCreateMat(4,1,CV_32FC1); //CvMat *C = cvCreateMat(3,1,CV_32FC1); //CvMat *R = cvCreateMat(3,3,CV_32FC1); //cvSetReal2D(q, 0, 0, rt[0]); //cvSetReal2D(q, 1, 0, rt[1]); //cvSetReal2D(q, 2, 0, rt[2]); //cvSetReal2D(q, 3, 0, rt[3]); //cvSetReal2D(C, 0, 0, rt[4]); //cvSetReal2D(C, 1, 0, rt[5]); //cvSetReal2D(C, 2, 0, rt[6]); //Quaternion2Rotation(q, R); //CvMat *temp33 = cvCreateMat(3,3,CV_32FC1); //CvMat *P = cvCreateMat(3,4,CV_32FC1); //cvMatMul(K, R, temp33); //cvSetIdentity(P); //ScalarMul(C, -1, C); //SetSubMat(P, 0,3,C); //cvMatMul(temp33, P, P); //if (!isStatic) //{ // int iFrame = j % ((AdditionalData *) adata)->nFrames; // int nBase = ((AdditionalData *) adata)->nBase; // int nFrames = ((AdditionalData *) adata)->nFrames; // CvMat *x = cvCreateMat(2,1,CV_32FC1); // CvMat *theta = cvCreateMat(3*nBase, 1, CV_32FC1); // for (int iTheta = 0; iTheta < 3*nBase; iTheta++) // cvSetReal2D(theta, iTheta, 0, xyz[iTheta]); // DCTProjection(P, theta, nFrames, iFrame, nBase, x); // xi = cvGetReal2D(x, 0, 0); // yi = cvGetReal2D(x, 1, 0); // cvReleaseMat(&x); // cvReleaseMat(&theta); //} //else //{ // CvMat *X = cvCreateMat(4,1,CV_32FC1); // cvSetReal2D(X, 0, 0, xyz[0]); // cvSetReal2D(X, 1, 0, xyz[1]); // cvSetReal2D(X, 2, 0, xyz[2]); // cvSetReal2D(X, 3, 0, 1); // CvMat *x = cvCreateMat(3,1,CV_32FC1); // cvMatMul(P, X, x); // xi = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); // yi = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); // cvReleaseMat(&X); // cvReleaseMat(&x); //} //cvReleaseMat(&K); //cvReleaseMat(&P); //cvReleaseMat(&temp33); //cvReleaseMat(&q); //cvReleaseMat(&C); //cvReleaseMat(&R); } void Projection3Donto2D_MOT(int j, int i, double *rt, double *xij, void *adata) { //CvMat *K = cvCreateMat(3,3,CV_32FC1); //cvSetIdentity(K); //cvSetReal2D(K, 0, 0, ((AdditionalData *) adata)->intrinsic[0]); //cvSetReal2D(K, 1, 1, ((AdditionalData *) adata)->intrinsic[1]); //cvSetReal2D(K, 0, 2, ((AdditionalData *) adata)->intrinsic[2]); //cvSetReal2D(K, 1, 2, ((AdditionalData *) adata)->intrinsic[3]); //CvMat *q = cvCreateMat(4,1,CV_32FC1); //CvMat *C = cvCreateMat(3,1,CV_32FC1); //CvMat *R = cvCreateMat(3,3,CV_32FC1); //cvSetReal2D(q, 0, 0, rt[0]); //cvSetReal2D(q, 1, 0, rt[1]); //cvSetReal2D(q, 2, 0, rt[2]); //cvSetReal2D(q, 3, 0, rt[3]); //cvSetReal2D(C, 0, 0, rt[4]); //cvSetReal2D(C, 1, 0, rt[5]); //cvSetReal2D(C, 2, 0, rt[6]); //Quaternion2Rotation(q, R); //CvMat *temp33 = cvCreateMat(3,3,CV_32FC1); //CvMat *P = cvCreateMat(3,4,CV_32FC1); //cvMatMul(K, R, temp33); //cvSetIdentity(P); //ScalarMul(C, -1, C); //SetSubMat(P, 0,3,C); //cvMatMul(temp33, P, P); //CvMat *X = cvCreateMat(4,1,CV_32FC1); //cvSetReal2D(X, 0, 0, ((AdditionalData *) adata)->XYZ[3*i]); //cvSetReal2D(X, 1, 0, ((AdditionalData *) adata)->XYZ[3*i+1]); //cvSetReal2D(X, 2, 0, ((AdditionalData *) adata)->XYZ[3*i+2]); //cvSetReal2D(X, 3, 0, 1); ////PrintMat(X, "X"); ////PrintMat(C, "C"); ////cout << i << endl; ////if (j == 1) //// int k = 1; //CvMat *x = cvCreateMat(3,1,CV_32FC1); //cvMatMul(P, X, x); //xij[0] = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); //xij[1] = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); //cvReleaseMat(&K); //cvReleaseMat(&X); //cvReleaseMat(&x); //cvReleaseMat(&P); //cvReleaseMat(&temp33); //cvReleaseMat(&q); //cvReleaseMat(&C); } void Projection3Donto2D_KDMOT(int j, int i, double *rt, double *xij, void *adata) { CvMat *K = cvCreateMat(3,3,CV_32FC1); cvSetIdentity(K); int max_nFrames = ((AdditionalData *) adata)->max_nFrames; vector<int> vUsedFrame = ((AdditionalData *) adata)->vUsedFrame; int iCamera = (int)((double)vUsedFrame[j]/max_nFrames); CvMat *q = cvCreateMat(4,1,CV_32FC1); CvMat *C = cvCreateMat(3,1,CV_32FC1); CvMat *R = cvCreateMat(3,3,CV_32FC1); cvSetReal2D(q, 0, 0, rt[0]); cvSetReal2D(q, 1, 0, rt[1]); cvSetReal2D(q, 2, 0, rt[2]); cvSetReal2D(q, 3, 0, rt[3]); cvSetReal2D(C, 0, 0, rt[4]); cvSetReal2D(C, 1, 0, rt[5]); cvSetReal2D(C, 2, 0, rt[6]); cvSetReal2D(K, 0, 0, rt[7]); cvSetReal2D(K, 1, 1, rt[8]); cvSetReal2D(K, 0, 2, rt[9]); cvSetReal2D(K, 1, 2, rt[10]); Quaternion2Rotation(q, R); double k11 = rt[7]; double k22 = rt[8]; double px = rt[9]; double py = rt[10]; double k1 = rt[11]; double k2 = rt[12]; CvMat *temp33 = cvCreateMat(3,3,CV_32FC1); CvMat *P = cvCreateMat(3,4,CV_32FC1); cvMatMul(K, R, temp33); cvSetIdentity(P); ScalarMul(C, -1, C); SetSubMat(P, 0,3,C); cvMatMul(temp33, P, P); CvMat *X = cvCreateMat(4,1,CV_32FC1); cvSetReal2D(X, 0, 0, ((AdditionalData *) adata)->XYZ[3*i]); cvSetReal2D(X, 1, 0, ((AdditionalData *) adata)->XYZ[3*i+1]); cvSetReal2D(X, 2, 0, ((AdditionalData *) adata)->XYZ[3*i+2]); cvSetReal2D(X, 3, 0, 1); CvMat *x = cvCreateMat(3,1,CV_32FC1); cvMatMul(P, X, x); xij[0] = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); xij[1] = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); // taking into account distortion CvMat *invK = cvCreateMat(3,3,CV_32FC1); cvInvert(K, invK); double ik11 = cvGetReal2D(invK, 0, 0); double ik12 = cvGetReal2D(invK, 0, 1); double ik13 = cvGetReal2D(invK, 0, 2); double ik21 = cvGetReal2D(invK, 1, 0); double ik22 = cvGetReal2D(invK, 1, 1); double ik23 = cvGetReal2D(invK, 1, 2); double ik31 = cvGetReal2D(invK, 2, 0); double ik32 = cvGetReal2D(invK, 2, 1); double ik33 = cvGetReal2D(invK, 2, 2); double nz = (ik31*xij[0]+ik32*xij[1]+ik33); double nx = (ik11*xij[0]+ik12*xij[1]+ik13)/nz; double ny = (ik21*xij[0]+ik22*xij[1]+ik23)/nz; double r = sqrt((nx)*(nx)+(ny)*(ny)); double L = 1 + k1*r + k2*r*r; nx = L*(nx); ny = L*(ny); xij[0] = (k11*nx+px); xij[1] = (k22*ny+py); cvReleaseMat(&K); cvReleaseMat(&invK); cvReleaseMat(&X); cvReleaseMat(&x); cvReleaseMat(&P); cvReleaseMat(&temp33); cvReleaseMat(&q); cvReleaseMat(&C); cvReleaseMat(&R); } void GetParameterForSBA(vector<Feature> vFeature, vector<int> vUsedFrame, vector<CvMat *> cP, CvMat *X, CvMat *K, vector<int> visibleStructureID, vector<double> &cameraParameter, vector<double> &feature2DParameter, vector<char> &vMask) { int nFrames = cP.size(); int nFeatures = X->rows; for (int iFrame = 0; iFrame < vUsedFrame.size(); iFrame++) { int cFrame = vUsedFrame[iFrame]; CvMat *q = cvCreateMat(4,1,CV_32FC1); CvMat *R = cvCreateMat(3,3,CV_32FC1); CvMat *t = cvCreateMat(3,1,CV_32FC1); CvMat *invK = cvCreateMat(3,3,CV_32FC1); CvMat *invR = cvCreateMat(3,3,CV_32FC1); cvInvert(K, invK); GetSubMatColwise(cP[iFrame], 0, 2, R); GetSubMatColwise(cP[iFrame], 3, 3, t); cvMatMul(invK, R, R); cvInvert(R, invR); cvMatMul(invK, t, t); cvMatMul(invR, t, t); ScalarMul(t, -1, t); Rotation2Quaternion(R, q); cameraParameter.push_back(cvGetReal2D(q, 0, 0)); cameraParameter.push_back(cvGetReal2D(q, 1, 0)); cameraParameter.push_back(cvGetReal2D(q, 2, 0)); cameraParameter.push_back(cvGetReal2D(q, 3, 0)); cameraParameter.push_back(cvGetReal2D(t, 0, 0)); cameraParameter.push_back(cvGetReal2D(t, 1, 0)); cameraParameter.push_back(cvGetReal2D(t, 2, 0)); cvReleaseMat(&R); cvReleaseMat(&t); cvReleaseMat(&q); cvReleaseMat(&invK); cvReleaseMat(&invR); } for (int cFeature = 0; cFeature < visibleStructureID.size(); cFeature++) { int iFeature = visibleStructureID[cFeature]; cameraParameter.push_back(cvGetReal2D(X, iFeature, 0)); cameraParameter.push_back(cvGetReal2D(X, iFeature, 1)); cameraParameter.push_back(cvGetReal2D(X, iFeature, 2)); } CvMat *visibilityMask = cvCreateMat(visibleStructureID.size(), nFrames, CV_32FC1); cvSetZero(visibilityMask); int NZ = 0; for (int cFeature = 0; cFeature < visibleStructureID.size(); cFeature++) { int iFeature = visibleStructureID[cFeature]; for (int iVisibleFrame = 0; iVisibleFrame < vUsedFrame.size(); iVisibleFrame++) { vector<int>::iterator it = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),vUsedFrame[iVisibleFrame]); if (it != vFeature[iFeature].vFrame.end()) { int idx = int(it-vFeature[iFeature].vFrame.begin()); feature2DParameter.push_back(vFeature[iFeature].vx[idx]); feature2DParameter.push_back(vFeature[iFeature].vy[idx]); cvSetReal2D(visibilityMask, cFeature, iVisibleFrame, 1); NZ++; } } } for (int iFeature = 0; iFeature < visibilityMask->rows; iFeature++) { for (int iFrame = 0; iFrame < visibilityMask->cols; iFrame++) { vMask.push_back(cvGetReal2D(visibilityMask, iFeature, iFrame)); } } cvReleaseMat(&visibilityMask); } void GetParameterForSBA(vector<Feature> &vFeature, vector<int> vUsedFrame, vector<CvMat *> cP, CvMat *X, vector<Camera> vCamera, int max_nFrames, vector<int> visibleStructureID, vector<double> &cameraParameter, vector<double> &feature2DParameter, vector<char> &vMask) { int nFrames = cP.size(); int nFeatures = X->rows; for (int iFrame = 0; iFrame < vUsedFrame.size(); iFrame++) { int cFrame = vUsedFrame[iFrame]; int iCamera = (int) ((double)vUsedFrame[iFrame]/max_nFrames); CvMat *q = cvCreateMat(4,1,CV_32FC1); CvMat *R = cvCreateMat(3,3,CV_32FC1); CvMat *t = cvCreateMat(3,1,CV_32FC1); CvMat *invK = cvCreateMat(3,3,CV_32FC1); CvMat *invR = cvCreateMat(3,3,CV_32FC1); cvInvert(vCamera[iCamera].vK[cFrame], invK); GetSubMatColwise(cP[iFrame], 0, 2, R); GetSubMatColwise(cP[iFrame], 3, 3, t); cvMatMul(invK, R, R); cvInvert(R, invR); cvMatMul(invK, t, t); cvMatMul(invR, t, t); ScalarMul(t, -1, t); Rotation2Quaternion(R, q); cameraParameter.push_back(cvGetReal2D(q, 0, 0)); cameraParameter.push_back(cvGetReal2D(q, 1, 0)); cameraParameter.push_back(cvGetReal2D(q, 2, 0)); cameraParameter.push_back(cvGetReal2D(q, 3, 0)); cameraParameter.push_back(cvGetReal2D(t, 0, 0)); cameraParameter.push_back(cvGetReal2D(t, 1, 0)); cameraParameter.push_back(cvGetReal2D(t, 2, 0)); cvReleaseMat(&R); cvReleaseMat(&t); cvReleaseMat(&q); cvReleaseMat(&invK); cvReleaseMat(&invR); } for (int cFeature = 0; cFeature < visibleStructureID.size(); cFeature++) { int iFeature = visibleStructureID[cFeature]; cameraParameter.push_back(cvGetReal2D(X, iFeature, 0)); cameraParameter.push_back(cvGetReal2D(X, iFeature, 1)); cameraParameter.push_back(cvGetReal2D(X, iFeature, 2)); } CvMat *visibilityMask = cvCreateMat(visibleStructureID.size(), nFrames, CV_32FC1); cvSetZero(visibilityMask); int NZ = 0; for (int cFeature = 0; cFeature < visibleStructureID.size(); cFeature++) { int iFeature = visibleStructureID[cFeature]; for (int iVisibleFrame = 0; iVisibleFrame < vUsedFrame.size(); iVisibleFrame++) { vector<int>::iterator it = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),vUsedFrame[iVisibleFrame]); if (it != vFeature[iFeature].vFrame.end()) { int idx = int(it-vFeature[iFeature].vFrame.begin()); feature2DParameter.push_back(vFeature[iFeature].vx[idx]); feature2DParameter.push_back(vFeature[iFeature].vy[idx]); cvSetReal2D(visibilityMask, cFeature, iVisibleFrame, 1); //cvSetReal2D(visibilityMask, iFeature, iVisibleFrame, 1); NZ++; } } } for (int iFeature = 0; iFeature < visibilityMask->rows; iFeature++) { for (int iFrame = 0; iFrame < visibilityMask->cols; iFrame++) { vMask.push_back(cvGetReal2D(visibilityMask, iFeature, iFrame)); } } cvReleaseMat(&visibilityMask); } void GetParameterForSBA_Distortion(vector<Feature> &vFeature, vector<int> vUsedFrame, vector<CvMat *> cP, CvMat *X, vector<Camera> vCamera, int max_nFrames, vector<int> visibleStructureID, vector<double> &cameraParameter, vector<double> &feature2DParameter, vector<char> &vMask) { int nFrames = cP.size(); int nFeatures = X->rows; for (int iFrame = 0; iFrame < vUsedFrame.size(); iFrame++) { int cFrame = vUsedFrame[iFrame]; int iCamera = (int) ((double)vUsedFrame[iFrame]/max_nFrames); CvMat *q = cvCreateMat(4,1,CV_32FC1); CvMat *R = cvCreateMat(3,3,CV_32FC1); CvMat *t = cvCreateMat(3,1,CV_32FC1); CvMat *invK = cvCreateMat(3,3,CV_32FC1); CvMat *invR = cvCreateMat(3,3,CV_32FC1); cvInvert(vCamera[iCamera].K, invK); GetSubMatColwise(cP[iFrame], 0, 2, R); GetSubMatColwise(cP[iFrame], 3, 3, t); cvMatMul(invK, R, R); cvInvert(R, invR); cvMatMul(invK, t, t); cvMatMul(invR, t, t); ScalarMul(t, -1, t); Rotation2Quaternion(R, q); cameraParameter.push_back(cvGetReal2D(q, 0, 0)); cameraParameter.push_back(cvGetReal2D(q, 1, 0)); cameraParameter.push_back(cvGetReal2D(q, 2, 0)); cameraParameter.push_back(cvGetReal2D(q, 3, 0)); cameraParameter.push_back(cvGetReal2D(t, 0, 0)); cameraParameter.push_back(cvGetReal2D(t, 1, 0)); cameraParameter.push_back(cvGetReal2D(t, 2, 0)); cvReleaseMat(&R); cvReleaseMat(&t); cvReleaseMat(&q); cvReleaseMat(&invK); cvReleaseMat(&invR); } for (int cFeature = 0; cFeature < visibleStructureID.size(); cFeature++) { int iFeature = visibleStructureID[cFeature]; cameraParameter.push_back(cvGetReal2D(X, iFeature, 0)); cameraParameter.push_back(cvGetReal2D(X, iFeature, 1)); cameraParameter.push_back(cvGetReal2D(X, iFeature, 2)); } CvMat *visibilityMask = cvCreateMat(visibleStructureID.size(), nFrames, CV_32FC1); cvSetZero(visibilityMask); int NZ = 0; for (int cFeature = 0; cFeature < visibleStructureID.size(); cFeature++) { int iFeature = visibleStructureID[cFeature]; for (int iVisibleFrame = 0; iVisibleFrame < vUsedFrame.size(); iVisibleFrame++) { vector<int>::iterator it = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),vUsedFrame[iVisibleFrame]); if (it != vFeature[iFeature].vFrame.end()) { int idx = int(it-vFeature[iFeature].vFrame.begin()); feature2DParameter.push_back(vFeature[iFeature].vx_dis[idx]); feature2DParameter.push_back(vFeature[iFeature].vy_dis[idx]); cvSetReal2D(visibilityMask, cFeature, iVisibleFrame, 1); //cvSetReal2D(visibilityMask, iFeature, iVisibleFrame, 1); NZ++; } } } for (int iFeature = 0; iFeature < visibilityMask->rows; iFeature++) { for (int iFrame = 0; iFrame < visibilityMask->cols; iFrame++) { vMask.push_back(cvGetReal2D(visibilityMask, iFeature, iFrame)); } } cvReleaseMat(&visibilityMask); } void GetParameterForSBA_KRT(vector<Feature> vFeature, vector<int> vUsedFrame, vector<CvMat *> cP, CvMat *X, vector<Camera> vCamera, int max_nFrames, vector<int> visibleStructureID, vector<double> &cameraParameter, vector<double> &feature2DParameter, vector<char> &vMask) { int nFrames = cP.size(); int nFeatures = visibleStructureID.size(); cout << "nFeatures: " << X->rows << " nFeatures_: " << nFeatures <<endl; for (int iFrame = 0; iFrame < vUsedFrame.size(); iFrame++) { int cFrame = vUsedFrame[iFrame]; int takenFrame = vUsedFrame[iFrame] % max_nFrames; int iCamera = (int) ((double)vUsedFrame[iFrame]/max_nFrames); CvMat *q = cvCreateMat(4,1,CV_32FC1); CvMat *R = cvCreateMat(3,3,CV_32FC1); CvMat *t = cvCreateMat(3,1,CV_32FC1); CvMat *invK = cvCreateMat(3,3,CV_32FC1); CvMat *invR = cvCreateMat(3,3,CV_32FC1); vector<int>::const_iterator it = find(vCamera[iCamera].vTakenFrame.begin(), vCamera[iCamera].vTakenFrame.end(), takenFrame); if (it == vCamera[iCamera].vTakenFrame.end()) return; int iTakenFrame = (int) (it - vCamera[iCamera].vTakenFrame.begin()); cvInvert(vCamera[iCamera].vK[iTakenFrame], invK); double k11 = cvGetReal2D(vCamera[iCamera].vK[iTakenFrame], 0, 0); double k22 = cvGetReal2D(vCamera[iCamera].vK[iTakenFrame], 1, 1); double k13 = cvGetReal2D(vCamera[iCamera].vK[iTakenFrame], 0, 2); double k23 = cvGetReal2D(vCamera[iCamera].vK[iTakenFrame], 1, 2); GetSubMatColwise(cP[iFrame], 0, 2, R); GetSubMatColwise(cP[iFrame], 3, 3, t); cvMatMul(invK, R, R); cvInvert(R, invR); cvMatMul(invK, t, t); cvMatMul(invR, t, t); ScalarMul(t, -1, t); Rotation2Quaternion(R, q); //PrintMat(R); cameraParameter.push_back(cvGetReal2D(q, 0, 0)); cameraParameter.push_back(cvGetReal2D(q, 1, 0)); cameraParameter.push_back(cvGetReal2D(q, 2, 0)); cameraParameter.push_back(cvGetReal2D(q, 3, 0)); cameraParameter.push_back(cvGetReal2D(t, 0, 0)); cameraParameter.push_back(cvGetReal2D(t, 1, 0)); cameraParameter.push_back(cvGetReal2D(t, 2, 0)); cameraParameter.push_back(k11); cameraParameter.push_back(k22); cameraParameter.push_back(k13); cameraParameter.push_back(k23); cvReleaseMat(&R); cvReleaseMat(&t); cvReleaseMat(&q); cvReleaseMat(&invK); cvReleaseMat(&invR); } for (int cFeature = 0; cFeature < visibleStructureID.size(); cFeature++) { int iFeature = visibleStructureID[cFeature]; cameraParameter.push_back(cvGetReal2D(X, iFeature, 0)); cameraParameter.push_back(cvGetReal2D(X, iFeature, 1)); cameraParameter.push_back(cvGetReal2D(X, iFeature, 2)); } CvMat *visibilityMask = cvCreateMat(visibleStructureID.size(), nFrames, CV_32FC1); cvSetZero(visibilityMask); int NZ = 0; for (int cFeature = 0; cFeature < visibleStructureID.size(); cFeature++) { int iFeature = visibleStructureID[cFeature]; for (int iVisibleFrame = 0; iVisibleFrame < vUsedFrame.size(); iVisibleFrame++) { vector<int>::iterator it = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),vUsedFrame[iVisibleFrame]); if (it != vFeature[iFeature].vFrame.end()) { int idx = int(it-vFeature[iFeature].vFrame.begin()); feature2DParameter.push_back(vFeature[iFeature].vx[idx]); feature2DParameter.push_back(vFeature[iFeature].vy[idx]); cvSetReal2D(visibilityMask, cFeature, iVisibleFrame, 1); NZ++; } } } for (int iFeature = 0; iFeature < visibilityMask->rows; iFeature++) { for (int iFrame = 0; iFrame < visibilityMask->cols; iFrame++) { vMask.push_back(cvGetReal2D(visibilityMask, iFeature, iFrame)); } } cvReleaseMat(&visibilityMask); } void GetParameterForSBA_KDRT(vector<Feature> vFeature, vector<int> vUsedFrame, vector<CvMat *> cP, CvMat *X, vector<Camera> vCamera, int max_nFrames, vector<int> visibleStructureID, vector<double> &cameraParameter, vector<double> &feature2DParameter, vector<char> &vMask) { int nFrames = cP.size(); int nFeatures = visibleStructureID.size(); for (int iFrame = 0; iFrame < vUsedFrame.size(); iFrame++) { PrintMat(cP[iFrame],"P"); int cFrame = vUsedFrame[iFrame]; int takenFrame = vUsedFrame[iFrame] % max_nFrames; int iCamera = (int) ((double)vUsedFrame[iFrame]/max_nFrames); CvMat *q = cvCreateMat(4,1,CV_32FC1); CvMat *R = cvCreateMat(3,3,CV_32FC1); CvMat *t = cvCreateMat(3,1,CV_32FC1); CvMat *invK = cvCreateMat(3,3,CV_32FC1); CvMat *invR = cvCreateMat(3,3,CV_32FC1); vector<int>::const_iterator it = find(vCamera[iCamera].vTakenFrame.begin(), vCamera[iCamera].vTakenFrame.end(), takenFrame); if (it == vCamera[iCamera].vTakenFrame.end()) return; int iTakenFrame = (int) (it - vCamera[iCamera].vTakenFrame.begin()); cvInvert(vCamera[iCamera].vK[iTakenFrame], invK); double k11 = cvGetReal2D(vCamera[iCamera].vK[iTakenFrame], 0, 0); double k22 = cvGetReal2D(vCamera[iCamera].vK[iTakenFrame], 1, 1); double k13 = cvGetReal2D(vCamera[iCamera].vK[iTakenFrame], 0, 2); double k23 = cvGetReal2D(vCamera[iCamera].vK[iTakenFrame], 1, 2); GetSubMatColwise(cP[iFrame], 0, 2, R); GetSubMatColwise(cP[iFrame], 3, 3, t); cvMatMul(invK, R, R); cvInvert(R, invR); cvMatMul(invK, t, t); cvMatMul(invR, t, t); ScalarMul(t, -1, t); Rotation2Quaternion(R, q); cameraParameter.push_back(cvGetReal2D(q, 0, 0)); cameraParameter.push_back(cvGetReal2D(q, 1, 0)); cameraParameter.push_back(cvGetReal2D(q, 2, 0)); cameraParameter.push_back(cvGetReal2D(q, 3, 0)); cameraParameter.push_back(cvGetReal2D(t, 0, 0)); cameraParameter.push_back(cvGetReal2D(t, 1, 0)); cameraParameter.push_back(cvGetReal2D(t, 2, 0)); cameraParameter.push_back(k11); cameraParameter.push_back(k22); cameraParameter.push_back(k13); cameraParameter.push_back(k23); cameraParameter.push_back(vCamera[iCamera].vk1[iTakenFrame]); cameraParameter.push_back(vCamera[iCamera].vk2[iTakenFrame]); cvReleaseMat(&R); cvReleaseMat(&t); cvReleaseMat(&q); cvReleaseMat(&invK); cvReleaseMat(&invR); } for (int cFeature = 0; cFeature < visibleStructureID.size(); cFeature++) { int iFeature = visibleStructureID[cFeature]; cameraParameter.push_back(cvGetReal2D(X, iFeature, 0)); cameraParameter.push_back(cvGetReal2D(X, iFeature, 1)); cameraParameter.push_back(cvGetReal2D(X, iFeature, 2)); } CvMat *visibilityMask = cvCreateMat(visibleStructureID.size(), nFrames, CV_32FC1); cvSetZero(visibilityMask); int NZ = 0; for (int cFeature = 0; cFeature < visibleStructureID.size(); cFeature++) { int iFeature = visibleStructureID[cFeature]; for (int iVisibleFrame = 0; iVisibleFrame < vUsedFrame.size(); iVisibleFrame++) { vector<int>::iterator it = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),vUsedFrame[iVisibleFrame]); if (it != vFeature[iFeature].vFrame.end()) { int idx = int(it-vFeature[iFeature].vFrame.begin()); feature2DParameter.push_back(vFeature[iFeature].vx[idx]); feature2DParameter.push_back(vFeature[iFeature].vy[idx]); cvSetReal2D(visibilityMask, cFeature, iVisibleFrame, 1); NZ++; } } } for (int iFeature = 0; iFeature < visibilityMask->rows; iFeature++) { for (int iFrame = 0; iFrame < visibilityMask->cols; iFrame++) { vMask.push_back(cvGetReal2D(visibilityMask, iFeature, iFrame)); } } cvReleaseMat(&visibilityMask); } void GetParameterForSBA_TEMPORAL(vector<Feature> vFeature, vector<Theta> vTheta, vector<Camera> vCamera, int max_nFrames, vector<double> &cameraParameter, vector<double> &feature2DParameter, vector<char> &vMask) { int nFrames = 0; vector<int> vUsedFrame; for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) { for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++) { // Temporal error initialization cameraParameter.push_back(0); vUsedFrame.push_back(iCamera*max_nFrames+vCamera[iCamera].vTakenFrame[iFrame]); nFrames++; } } for (int iTheta = 0; iTheta < vTheta.size(); iTheta++) { for (int iTheta_x = 0; iTheta_x < vTheta[iTheta].thetaX.size(); iTheta_x++) cameraParameter.push_back(vTheta[iTheta].thetaX[iTheta_x]); for (int iTheta_x = 0; iTheta_x < vTheta[iTheta].thetaX.size(); iTheta_x++) cameraParameter.push_back(vTheta[iTheta].thetaY[iTheta_x]); for (int iTheta_x = 0; iTheta_x < vTheta[iTheta].thetaX.size(); iTheta_x++) cameraParameter.push_back(vTheta[iTheta].thetaZ[iTheta_x]); } CvMat *visibilityMask = cvCreateMat(vTheta.size(), nFrames, CV_32FC1); cvSetZero(visibilityMask); int NZ = 0; for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { for (int iVisibleFrame = 0; iVisibleFrame < vUsedFrame.size(); iVisibleFrame++) { vector<int>::iterator it = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),vUsedFrame[iVisibleFrame]); if (it != vFeature[iFeature].vFrame.end()) { int idx = int(it-vFeature[iFeature].vFrame.begin()); feature2DParameter.push_back(vFeature[iFeature].vx[idx]); feature2DParameter.push_back(vFeature[iFeature].vy[idx]); feature2DParameter.push_back(0.0); feature2DParameter.push_back(0.0); cvSetReal2D(visibilityMask, iFeature, iVisibleFrame, 1); NZ++; } } } for (int iFeature = 0; iFeature < visibilityMask->rows; iFeature++) { for (int iFrame = 0; iFrame < visibilityMask->cols; iFrame++) { vMask.push_back(cvGetReal2D(visibilityMask, iFeature, iFrame)); } } cvReleaseMat(&visibilityMask); } void GetParameterForSBA_TEMPORAL_LEVMAR(vector<Feature> vFeature, vector<Theta> vTheta, vector<Camera> vCamera, int max_nFrames, vector<double> &cameraParameter, vector<double> &feature2DParameter) { int nFrames = 0; vector<int> vUsedFrame; for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) { for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++) { // Temporal error initialization cameraParameter.push_back(0); vUsedFrame.push_back(iCamera*max_nFrames+vCamera[iCamera].vTakenFrame[iFrame]); nFrames++; } } for (int iTheta = 0; iTheta < vTheta.size(); iTheta++) { for (int iTheta_x = 0; iTheta_x < vTheta[iTheta].thetaX.size(); iTheta_x++) cameraParameter.push_back(vTheta[iTheta].thetaX[iTheta_x]); for (int iTheta_x = 0; iTheta_x < vTheta[iTheta].thetaX.size(); iTheta_x++) cameraParameter.push_back(vTheta[iTheta].thetaY[iTheta_x]); for (int iTheta_x = 0; iTheta_x < vTheta[iTheta].thetaX.size(); iTheta_x++) cameraParameter.push_back(vTheta[iTheta].thetaZ[iTheta_x]); } for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { for (int iVisibleFrame = 0; iVisibleFrame < vUsedFrame.size(); iVisibleFrame++) { vector<int>::iterator it = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),vUsedFrame[iVisibleFrame]); if (it != vFeature[iFeature].vFrame.end()) { int idx = int(it-vFeature[iFeature].vFrame.begin()); feature2DParameter.push_back(vFeature[iFeature].vx[idx]); feature2DParameter.push_back(vFeature[iFeature].vy[idx]); } else { feature2DParameter.push_back(0); feature2DParameter.push_back(0); } } } } void GetParameterForGBA(vector<Feature> vFeature, vector<Camera> vCamera, vector<Theta> vTheta, CvMat *K, int nFrames, vector<double> &cameraParameter, vector<double> &feature2DParameter, vector<char> &vMask) { int nFeatures = vFeature.size(); for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) { for (int iFrame = 0; iFrame < nFrames; iFrame++) { vector<int>::const_iterator it = find(vCamera[iCamera].vTakenFrame.begin(), vCamera[iCamera].vTakenFrame.end(), iFrame); if (it == vCamera[iCamera].vTakenFrame.end()) { cameraParameter.push_back(0); cameraParameter.push_back(0); cameraParameter.push_back(0); cameraParameter.push_back(0); cameraParameter.push_back(0); cameraParameter.push_back(0); cameraParameter.push_back(0); } else { CvMat *q = cvCreateMat(4,1,CV_32FC1); CvMat *R = cvCreateMat(3,3,CV_32FC1); CvMat *t = cvCreateMat(3,1,CV_32FC1); CvMat *invK = cvCreateMat(3,3,CV_32FC1); CvMat *invR = cvCreateMat(3,3,CV_32FC1); cvInvert(K, invK); GetSubMatColwise(vCamera[iCamera].vP[iFrame], 0, 2, R); GetSubMatColwise(vCamera[iCamera].vP[iFrame], 3, 3, t); cvMatMul(invK, R, R); cvInvert(R, invR); cvMatMul(invK, t, t); cvMatMul(invR, t, t); ScalarMul(t, -1, t); Rotation2Quaternion(R, q); cameraParameter.push_back(cvGetReal2D(q, 0, 0)); cameraParameter.push_back(cvGetReal2D(q, 1, 0)); cameraParameter.push_back(cvGetReal2D(q, 2, 0)); cameraParameter.push_back(cvGetReal2D(q, 3, 0)); cameraParameter.push_back(cvGetReal2D(t, 0, 0)); cameraParameter.push_back(cvGetReal2D(t, 1, 0)); cameraParameter.push_back(cvGetReal2D(t, 2, 0)); cvReleaseMat(&R); cvReleaseMat(&t); cvReleaseMat(&q); cvReleaseMat(&invK); cvReleaseMat(&invR); } } } for (int iTheta = 0; iTheta < vTheta.size(); iTheta++) { if (vTheta[iTheta].isStatic) { double IDCT = sqrt(1.0/(double)nFrames); double X = vTheta[iTheta].thetaX[0]*IDCT; double Y = vTheta[iTheta].thetaY[0]*IDCT; double Z = vTheta[iTheta].thetaZ[0]*IDCT; cameraParameter.push_back(X); cameraParameter.push_back(Y); cameraParameter.push_back(Z); } else { for (int iBase = 0; iBase < vTheta[iTheta].thetaX.size(); iBase++) { cameraParameter.push_back(vTheta[iTheta].thetaX[iBase]); } for (int iBase = 0; iBase < vTheta[iTheta].thetaX.size(); iBase++) { cameraParameter.push_back(vTheta[iTheta].thetaY[iBase]); } for (int iBase = 0; iBase < vTheta[iTheta].thetaX.size(); iBase++) { cameraParameter.push_back(vTheta[iTheta].thetaZ[iBase]); } } } CvMat *visibilityMask = cvCreateMat(vTheta.size(), vCamera.size()*nFrames, CV_32FC1); cvSetZero(visibilityMask); int NZ = 0; for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { for (int iFrame = 0; iFrame < vFeature[iFeature].vFrame.size(); iFrame++) { feature2DParameter.push_back(vFeature[iFeature].vx[iFrame]); feature2DParameter.push_back(vFeature[iFeature].vy[iFrame]); cvSetReal2D(visibilityMask, iFeature, iFrame, 1); } } for (int iFeature = 0; iFeature < visibilityMask->rows; iFeature++) { for (int iFrame = 0; iFrame < visibilityMask->cols; iFrame++) { vMask.push_back(cvGetReal2D(visibilityMask, iFeature, iFrame)); } } cvReleaseMat(&visibilityMask); } void GetParameterForGBA(vector<Feature> vFeature, vector<Camera> vCamera, vector<Theta> vTheta, CvMat *K, int nFrames, vector<double> &cameraParameter, vector<double> &feature2DParameter, CvMat &visibilityMask) { int nFeatures = vFeature.size(); for (int iCamera = 0; iCamera < vCamera.size(); iCamera++) { for (int iFrame = 0; iFrame < nFrames; iFrame++) { vector<int>::const_iterator it = find(vCamera[iCamera].vTakenFrame.begin(), vCamera[iCamera].vTakenFrame.end(), iFrame); if (it == vCamera[iCamera].vTakenFrame.end()) { cameraParameter.push_back(0); cameraParameter.push_back(0); cameraParameter.push_back(0); cameraParameter.push_back(0); cameraParameter.push_back(0); cameraParameter.push_back(0); cameraParameter.push_back(0); } else { CvMat *q = cvCreateMat(4,1,CV_32FC1); CvMat *R = cvCreateMat(3,3,CV_32FC1); CvMat *t = cvCreateMat(3,1,CV_32FC1); CvMat *invK = cvCreateMat(3,3,CV_32FC1); CvMat *invR = cvCreateMat(3,3,CV_32FC1); cvInvert(K, invK); GetSubMatColwise(vCamera[iCamera].vP[iFrame], 0, 2, R); GetSubMatColwise(vCamera[iCamera].vP[iFrame], 3, 3, t); cvMatMul(invK, R, R); cvInvert(R, invR); cvMatMul(invK, t, t); cvMatMul(invR, t, t); ScalarMul(t, -1, t); Rotation2Quaternion(R, q); cameraParameter.push_back(cvGetReal2D(q, 0, 0)); cameraParameter.push_back(cvGetReal2D(q, 1, 0)); cameraParameter.push_back(cvGetReal2D(q, 2, 0)); cameraParameter.push_back(cvGetReal2D(q, 3, 0)); cameraParameter.push_back(cvGetReal2D(t, 0, 0)); cameraParameter.push_back(cvGetReal2D(t, 1, 0)); cameraParameter.push_back(cvGetReal2D(t, 2, 0)); cvReleaseMat(&R); cvReleaseMat(&t); cvReleaseMat(&q); cvReleaseMat(&invK); cvReleaseMat(&invR); } } } for (int iTheta = 0; iTheta < vTheta.size(); iTheta++) { if (vTheta[iTheta].isStatic) { double IDCT = sqrt(1.0/(double)nFrames); double X = vTheta[iTheta].thetaX[0]*IDCT; double Y = vTheta[iTheta].thetaY[0]*IDCT; double Z = vTheta[iTheta].thetaZ[0]*IDCT; cameraParameter.push_back(X); cameraParameter.push_back(Y); cameraParameter.push_back(Z); } else { for (int iBase = 0; iBase < vTheta[iTheta].thetaX.size(); iBase++) { cameraParameter.push_back(vTheta[iTheta].thetaX[iBase]); } for (int iBase = 0; iBase < vTheta[iTheta].thetaX.size(); iBase++) { cameraParameter.push_back(vTheta[iTheta].thetaY[iBase]); } for (int iBase = 0; iBase < vTheta[iTheta].thetaX.size(); iBase++) { cameraParameter.push_back(vTheta[iTheta].thetaZ[iBase]); } } } visibilityMask = *cvCreateMat(vTheta.size(), vCamera.size()*nFrames, CV_32FC1); cvSetZero(&visibilityMask); int NZ = 0; for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { for (int iFrame = 0; iFrame < vFeature[iFeature].vFrame.size(); iFrame++) { feature2DParameter.push_back(vFeature[iFeature].vx[iFrame]); feature2DParameter.push_back(vFeature[iFeature].vy[iFrame]); cvSetReal2D(&visibilityMask, iFeature, iFrame, 1); } } } //void GetCameraParameter(CvMat *P, CvMat *K, CvMat &R, CvMat &C) //{ // R = *cvCreateMat(3,3,CV_32FC1); // C = *cvCreateMat(3,1,CV_32FC1); // CvMat *temp34 = cvCreateMat(3,4,CV_32FC1); // CvMat *invK = cvCreateMat(3,3,CV_32FC1); // cvInvert(K, invK); // cvMatMul(invK, P, temp34); // GetSubMatColwise(temp34, 0,2,&R); // GetSubMatColwise(temp34, 3,3,&C); // CvMat *invR = cvCreateMat(3,3,CV_32FC1); // cvInvert(&R, invR); // cvMatMul(invR, &C, &C); // ScalarMul(&C, -1, &C); // // cvReleaseMat(&temp34); // cvReleaseMat(&invK); // cvReleaseMat(&invR); //} // //void GetCameraParameter(CvMat *P, CvMat *K, CvMat *R, CvMat *C) //{ // //R = *cvCreateMat(3,3,CV_32FC1); // //C = *cvCreateMat(3,1,CV_32FC1); // CvMat *temp34 = cvCreateMat(3,4,CV_32FC1); // CvMat *invK = cvCreateMat(3,3,CV_32FC1); // cvInvert(K, invK); // cvMatMul(invK, P, temp34); // GetSubMatColwise(temp34, 0,2,R); // GetSubMatColwise(temp34, 3,3,C); // CvMat *invR = cvCreateMat(3,3,CV_32FC1); // cvInvert(R, invR); // cvMatMul(invR, C, C); // ScalarMul(C, -1, C); // // cvReleaseMat(&temp34); // cvReleaseMat(&invK); // cvReleaseMat(&invR); //} void CreateCameraMatrix(CvMat *R, CvMat *C, CvMat *K, CvMat &P) { P = *cvCreateMat(3,4,CV_32FC1); cvSetIdentity(&P); ScalarMul(C, -1, C); SetSubMat(&P, 0,3, C); cvMatMul(R, &P, &P); cvMatMul(K, &P, &P); } void CreateCameraMatrix(CvMat *R, CvMat *C, CvMat *K, CvMat *P) { cvSetIdentity(P); ScalarMul(C, -1, C); SetSubMat(P, 0,3, C); cvMatMul(R, P, P); cvMatMul(K, P, P); } int ExcludePointBehindCamera(CvMat *X, CvMat *P1, CvMat *P2, vector<int> featureID, vector<int> &excludedFeatureID, CvMat &cX) { CvMat *H1 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH1 = cvCreateMat(4, 4, CV_32FC1); CvMat *HX1 = cvCreateMat(X->rows, X->cols, CV_32FC1); cvSetIdentity(H1); SetSubMat(H1, 0, 0, P1); cvInvert(H1, invH1); Pxx_inhomo(H1, X, HX1); CvMat *H2 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH2 = cvCreateMat(4, 4, CV_32FC1); CvMat *HX2 = cvCreateMat(X->rows, X->cols, CV_32FC1); cvSetIdentity(H2); SetSubMat(H2, 0, 0, P2); cvInvert(H2, invH2); Pxx_inhomo(H2, X, HX2); excludedFeatureID.clear(); for (int i = 0; i < X->rows; i++) { if ((cvGetReal2D(HX1, i, 2) > 0) && (cvGetReal2D(HX2, i, 2) > 0)) excludedFeatureID.push_back(featureID[i]); } if (excludedFeatureID.size() == 0) return 0; cX = *cvCreateMat(excludedFeatureID.size(),3, CV_32FC1); int k = 0; for (int i = 0; i < X->rows; i++) { if ((cvGetReal2D(HX1, i, 2) > 0) && (cvGetReal2D(HX2, i, 2) > 0)) { cvSetReal2D(&cX, k, 0, cvGetReal2D(X, i, 0)); cvSetReal2D(&cX, k, 1, cvGetReal2D(X, i, 1)); cvSetReal2D(&cX, k, 2, cvGetReal2D(X, i, 2)); k++; } } return 1; } int ExcludePointBehindCamera_mem(CvMat *X, CvMat *P1, CvMat *P2, vector<int> featureID, vector<int> &excludedFeatureID, vector<vector<double> > &cX) { CvMat *H1 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH1 = cvCreateMat(4, 4, CV_32FC1); CvMat *HX1 = cvCreateMat(X->rows, X->cols, CV_32FC1); cvSetIdentity(H1); SetSubMat(H1, 0, 0, P1); cvInvert(H1, invH1); Pxx_inhomo(H1, X, HX1); CvMat *H2 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH2 = cvCreateMat(4, 4, CV_32FC1); CvMat *HX2 = cvCreateMat(X->rows, X->cols, CV_32FC1); cvSetIdentity(H2); SetSubMat(H2, 0, 0, P2); cvInvert(H2, invH2); Pxx_inhomo(H2, X, HX2); excludedFeatureID.clear(); for (int i = 0; i < X->rows; i++) { if ((cvGetReal2D(HX1, i, 2) > 0) && (cvGetReal2D(HX2, i, 2) > 0)) excludedFeatureID.push_back(featureID[i]); } if (excludedFeatureID.size() == 0) { cvReleaseMat(&H1); cvReleaseMat(&HX1); cvReleaseMat(&H2); cvReleaseMat(&HX2); cvReleaseMat(&invH1); cvReleaseMat(&invH2); return 0; } //cX = *cvCreateMat(excludedFeatureID.size(),3, CV_32FC1); int k = 0; for (int i = 0; i < X->rows; i++) { if ((cvGetReal2D(HX1, i, 2) > 0) && (cvGetReal2D(HX2, i, 2) > 0)) { vector<double> cX_vec; cX_vec.push_back(cvGetReal2D(X, i, 0)); cX_vec.push_back(cvGetReal2D(X, i, 1)); cX_vec.push_back(cvGetReal2D(X, i, 2)); cX.push_back(cX_vec); k++; } } cvReleaseMat(&H1); cvReleaseMat(&HX1); cvReleaseMat(&H2); cvReleaseMat(&HX2); cvReleaseMat(&invH1); cvReleaseMat(&invH2); return cX.size(); } int ExcludePointBehindCamera_mem_fast(CvMat *X, CvMat *P1, CvMat *P2, vector<int> &featureID, vector<int> &excludedFeatureID, vector<vector<double> > &cX) { CvMat *H1 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH1 = cvCreateMat(4, 4, CV_32FC1); CvMat *HX1 = cvCreateMat(X->rows, X->cols, CV_32FC1); cvSetIdentity(H1); SetSubMat(H1, 0, 0, P1); cvInvert(H1, invH1); Pxx_inhomo(H1, X, HX1); CvMat *H2 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH2 = cvCreateMat(4, 4, CV_32FC1); CvMat *HX2 = cvCreateMat(X->rows, X->cols, CV_32FC1); cvSetIdentity(H2); SetSubMat(H2, 0, 0, P2); cvInvert(H2, invH2); Pxx_inhomo(H2, X, HX2); excludedFeatureID.clear(); for (int i = 0; i < X->rows; i++) { if ((cvGetReal2D(HX1, i, 2) > 0) && (cvGetReal2D(HX2, i, 2) > 0)) { excludedFeatureID.push_back(featureID[i]); vector<double> cX_vec; cX_vec.push_back(cvGetReal2D(X, i, 0)); cX_vec.push_back(cvGetReal2D(X, i, 1)); cX_vec.push_back(cvGetReal2D(X, i, 2)); cX.push_back(cX_vec); } } if (excludedFeatureID.size() == 0) { cvReleaseMat(&H1); cvReleaseMat(&HX1); cvReleaseMat(&H2); cvReleaseMat(&HX2); cvReleaseMat(&invH1); cvReleaseMat(&invH2); return 0; } cvReleaseMat(&H1); cvReleaseMat(&HX1); cvReleaseMat(&H2); cvReleaseMat(&HX2); cvReleaseMat(&invH1); cvReleaseMat(&invH2); return cX.size(); } int ExcludePointAtInfinity(CvMat *X, CvMat *P1, CvMat *P2, CvMat *K1, CvMat *K2, vector<int> featureID, vector<int> &excludedFeatureID, CvMat &cX) { CvMat *q1 = cvCreateMat(4,1,CV_32FC1); CvMat *R1 = cvCreateMat(3,3,CV_32FC1); CvMat *t1 = cvCreateMat(3,1,CV_32FC1); CvMat *invK1 = cvCreateMat(3,3,CV_32FC1); CvMat *invR1 = cvCreateMat(3,3,CV_32FC1); CvMat *q2 = cvCreateMat(4,1,CV_32FC1); CvMat *R2 = cvCreateMat(3,3,CV_32FC1); CvMat *t2 = cvCreateMat(3,1,CV_32FC1); CvMat *invK2 = cvCreateMat(3,3,CV_32FC1); CvMat *invR2 = cvCreateMat(3,3,CV_32FC1); GetSubMatColwise(P1, 0, 2, R1); GetSubMatColwise(P1, 3, 3, t1); cvInvert(K1, invK1); cvMatMul(invK1, R1, R1); cvInvert(R1, invR1); cvMatMul(invK1, t1, t1); cvMatMul(invR1, t1, t1); ScalarMul(t1, -1, t1); GetSubMatColwise(P2, 0, 2, R2); GetSubMatColwise(P2, 3, 3, t2); cvInvert(K2, invK2); cvMatMul(invK2, R2, R2); cvInvert(R2, invR2); cvMatMul(invK2, t2, t2); cvMatMul(invR2, t2, t2); ScalarMul(t2, -1, t2); double xC1 = cvGetReal2D(t1, 0, 0); double yC1 = cvGetReal2D(t1, 1, 0); double zC1 = cvGetReal2D(t1, 2, 0); double xC2 = cvGetReal2D(t2, 0, 0); double yC2 = cvGetReal2D(t2, 1, 0); double zC2 = cvGetReal2D(t2, 2, 0); excludedFeatureID.clear(); vector<double> vInner; for (int i = 0; i < X->rows; i++) { double x3D = cvGetReal2D(X, i, 0); double y3D = cvGetReal2D(X, i, 1); double z3D = cvGetReal2D(X, i, 2); double v1x = x3D - xC1; double v1y = y3D - yC1; double v1z = z3D - zC1; double v2x = x3D - xC2; double v2y = y3D - yC2; double v2z = z3D - zC2; double nv1 = sqrt(v1x*v1x+v1y*v1y+v1z*v1z); double nv2 = sqrt(v2x*v2x+v2y*v2y+v2z*v2z); v1x /= nv1; v1y /= nv1; v1z /= nv1; v2x /= nv2; v2y /= nv2; v2z /= nv2; double inner = v1x*v2x+v1y*v2y+v1z*v2z; vInner.push_back(inner); if ((abs(inner) < cos(PI/180*3)) && (inner > 0)) excludedFeatureID.push_back(featureID[i]); } if (excludedFeatureID.size() == 0) return 0; cX = *cvCreateMat(excludedFeatureID.size(),3, CV_32FC1); int k = 0; for (int i = 0; i < X->rows; i++) { if ((abs(vInner[i]) < cos(PI/180*3)) && (vInner[i] > 0)) { cvSetReal2D(&cX, k, 0, cvGetReal2D(X, i, 0)); cvSetReal2D(&cX, k, 1, cvGetReal2D(X, i, 1)); cvSetReal2D(&cX, k, 2, cvGetReal2D(X, i, 2)); k++; } } return 1; } int ExcludePointAtInfinity_mem(CvMat *X, CvMat *P1, CvMat *P2, CvMat *K1, CvMat *K2, vector<int> featureID, vector<int> &excludedFeatureID, vector<vector<double> > &cX) { CvMat *q1 = cvCreateMat(4,1,CV_32FC1); CvMat *R1 = cvCreateMat(3,3,CV_32FC1); CvMat *t1 = cvCreateMat(3,1,CV_32FC1); CvMat *invK1 = cvCreateMat(3,3,CV_32FC1); CvMat *invR1 = cvCreateMat(3,3,CV_32FC1); CvMat *q2 = cvCreateMat(4,1,CV_32FC1); CvMat *R2 = cvCreateMat(3,3,CV_32FC1); CvMat *t2 = cvCreateMat(3,1,CV_32FC1); CvMat *invK2 = cvCreateMat(3,3,CV_32FC1); CvMat *invR2 = cvCreateMat(3,3,CV_32FC1); GetSubMatColwise(P1, 0, 2, R1); GetSubMatColwise(P1, 3, 3, t1); cvInvert(K1, invK1); cvMatMul(invK1, R1, R1); cvInvert(R1, invR1); cvMatMul(invK1, t1, t1); cvMatMul(invR1, t1, t1); ScalarMul(t1, -1, t1); GetSubMatColwise(P2, 0, 2, R2); GetSubMatColwise(P2, 3, 3, t2); cvInvert(K2, invK2); cvMatMul(invK2, R2, R2); cvInvert(R2, invR2); cvMatMul(invK2, t2, t2); cvMatMul(invR2, t2, t2); ScalarMul(t2, -1, t2); double xC1 = cvGetReal2D(t1, 0, 0); double yC1 = cvGetReal2D(t1, 1, 0); double zC1 = cvGetReal2D(t1, 2, 0); double xC2 = cvGetReal2D(t2, 0, 0); double yC2 = cvGetReal2D(t2, 1, 0); double zC2 = cvGetReal2D(t2, 2, 0); excludedFeatureID.clear(); vector<double> vInner; for (int i = 0; i < X->rows; i++) { double x3D = cvGetReal2D(X, i, 0); double y3D = cvGetReal2D(X, i, 1); double z3D = cvGetReal2D(X, i, 2); double v1x = x3D - xC1; double v1y = y3D - yC1; double v1z = z3D - zC1; double v2x = x3D - xC2; double v2y = y3D - yC2; double v2z = z3D - zC2; double nv1 = sqrt(v1x*v1x+v1y*v1y+v1z*v1z); double nv2 = sqrt(v2x*v2x+v2y*v2y+v2z*v2z); v1x /= nv1; v1y /= nv1; v1z /= nv1; v2x /= nv2; v2y /= nv2; v2z /= nv2; double inner = v1x*v2x+v1y*v2y+v1z*v2z; vInner.push_back(inner); if ((abs(inner) < cos(PI/180*3)) && (inner > 0)) excludedFeatureID.push_back(featureID[i]); } if (excludedFeatureID.size() == 0) { cvReleaseMat(&q1); cvReleaseMat(&R1); cvReleaseMat(&t1); cvReleaseMat(&invK1); cvReleaseMat(&invR1); cvReleaseMat(&q2); cvReleaseMat(&R2); cvReleaseMat(&t2); cvReleaseMat(&invK2); cvReleaseMat(&invR2); return 0; } int k = 0; for (int i = 0; i < X->rows; i++) { if ((abs(vInner[i]) < cos(PI/180*3)) && (vInner[i] > 0)) { vector<double> cX_vec; cX_vec.push_back(cvGetReal2D(X, i, 0)); cX_vec.push_back(cvGetReal2D(X, i, 1)); cX_vec.push_back(cvGetReal2D(X, i, 2)); cX.push_back(cX_vec); k++; } } cvReleaseMat(&q1); cvReleaseMat(&R1); cvReleaseMat(&t1); cvReleaseMat(&invK1); cvReleaseMat(&invR1); cvReleaseMat(&q2); cvReleaseMat(&R2); cvReleaseMat(&t2); cvReleaseMat(&invK2); cvReleaseMat(&invR2); return cX.size(); } int ExcludePointAtInfinity_mem_fast(CvMat *X, CvMat *P1, CvMat *P2, CvMat *K1, CvMat *K2, vector<int> &featureID, vector<int> &excludedFeatureID, vector<vector<double> > &cX) { CvMat *q1 = cvCreateMat(4,1,CV_32FC1); CvMat *R1 = cvCreateMat(3,3,CV_32FC1); CvMat *t1 = cvCreateMat(3,1,CV_32FC1); CvMat *invK1 = cvCreateMat(3,3,CV_32FC1); CvMat *invR1 = cvCreateMat(3,3,CV_32FC1); CvMat *q2 = cvCreateMat(4,1,CV_32FC1); CvMat *R2 = cvCreateMat(3,3,CV_32FC1); CvMat *t2 = cvCreateMat(3,1,CV_32FC1); CvMat *invK2 = cvCreateMat(3,3,CV_32FC1); CvMat *invR2 = cvCreateMat(3,3,CV_32FC1); GetSubMatColwise(P1, 0, 2, R1); GetSubMatColwise(P1, 3, 3, t1); cvInvert(K1, invK1); cvMatMul(invK1, R1, R1); cvInvert(R1, invR1); cvMatMul(invK1, t1, t1); cvMatMul(invR1, t1, t1); ScalarMul(t1, -1, t1); GetSubMatColwise(P2, 0, 2, R2); GetSubMatColwise(P2, 3, 3, t2); cvInvert(K2, invK2); cvMatMul(invK2, R2, R2); cvInvert(R2, invR2); cvMatMul(invK2, t2, t2); cvMatMul(invR2, t2, t2); ScalarMul(t2, -1, t2); double xC1 = cvGetReal2D(t1, 0, 0); double yC1 = cvGetReal2D(t1, 1, 0); double zC1 = cvGetReal2D(t1, 2, 0); double xC2 = cvGetReal2D(t2, 0, 0); double yC2 = cvGetReal2D(t2, 1, 0); double zC2 = cvGetReal2D(t2, 2, 0); excludedFeatureID.clear(); vector<double> vInner; for (int i = 0; i < X->rows; i++) { double x3D = cvGetReal2D(X, i, 0); double y3D = cvGetReal2D(X, i, 1); double z3D = cvGetReal2D(X, i, 2); double v1x = x3D - xC1; double v1y = y3D - yC1; double v1z = z3D - zC1; double v2x = x3D - xC2; double v2y = y3D - yC2; double v2z = z3D - zC2; double nv1 = sqrt(v1x*v1x+v1y*v1y+v1z*v1z); double nv2 = sqrt(v2x*v2x+v2y*v2y+v2z*v2z); v1x /= nv1; v1y /= nv1; v1z /= nv1; v2x /= nv2; v2y /= nv2; v2z /= nv2; double inner = v1x*v2x+v1y*v2y+v1z*v2z; vInner.push_back(inner); if ((abs(inner) < cos(PI/180*3)) && (inner > 0)) { vector<double> cX_vec; cX_vec.push_back(x3D); cX_vec.push_back(y3D); cX_vec.push_back(z3D); cX.push_back(cX_vec); excludedFeatureID.push_back(featureID[i]); } } if (excludedFeatureID.size() == 0) { cvReleaseMat(&q1); cvReleaseMat(&R1); cvReleaseMat(&t1); cvReleaseMat(&invK1); cvReleaseMat(&invR1); cvReleaseMat(&q2); cvReleaseMat(&R2); cvReleaseMat(&t2); cvReleaseMat(&invK2); cvReleaseMat(&invR2); return 0; } cvReleaseMat(&q1); cvReleaseMat(&R1); cvReleaseMat(&t1); cvReleaseMat(&invK1); cvReleaseMat(&invR1); cvReleaseMat(&q2); cvReleaseMat(&R2); cvReleaseMat(&t2); cvReleaseMat(&invK2); cvReleaseMat(&invR2); return cX.size(); } void ExcludePointHighReprojectionError(vector<Feature> vFeature, vector<CvMat *> cP, vector<int> vUsedFrame, vector<int> &visibleStrucrtureID, CvMat *X_tot) { vector<bool> temp; temp.resize(visibleStrucrtureID.size(), true); for (int iP = 0; iP < cP.size(); iP++) { for (int iVS = 0; iVS < visibleStrucrtureID.size(); iVS++) { vector<int>:: const_iterator it = find(vFeature[visibleStrucrtureID[iVS]].vFrame.begin(), vFeature[visibleStrucrtureID[iVS]].vFrame.end(), vUsedFrame[iP]); if (it != vFeature[visibleStrucrtureID[iVS]].vFrame.end()) { int idx = (int) (it - vFeature[visibleStrucrtureID[iVS]].vFrame.begin()); CvMat *X = cvCreateMat(4, 1, CV_32FC1); CvMat *x = cvCreateMat(3, 1, CV_32FC1); cvSetReal2D(X, 0, 0, cvGetReal2D(X_tot, visibleStrucrtureID[iVS], 0)); cvSetReal2D(X, 1, 0, cvGetReal2D(X_tot, visibleStrucrtureID[iVS], 1)); cvSetReal2D(X, 2, 0, cvGetReal2D(X_tot, visibleStrucrtureID[iVS], 2)); cvSetReal2D(X, 3, 0, 1); cvMatMul(cP[iP], X, x); double u0 = vFeature[visibleStrucrtureID[iVS]].vx[idx]; double v0 = vFeature[visibleStrucrtureID[iVS]].vy[idx]; double u1 = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); double v1 = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); if (sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) > 5) { cout << visibleStrucrtureID[iVS] << "th 3D point erased " << sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) << endl; if(temp[iVS]) temp[iVS] = false; } cvReleaseMat(&X); cvReleaseMat(&x); } } } vector<int> tempID; for (int iVS = 0; iVS < visibleStrucrtureID.size(); iVS++) { if (temp[iVS]) { tempID.push_back(visibleStrucrtureID[iVS]); } } visibleStrucrtureID = tempID; } void ExcludePointHighReprojectionError_mem(vector<Feature> &vFeature, vector<CvMat *> &cP, vector<int> vUsedFrame, vector<int> &visibleStrucrtureID, CvMat *X_tot) { vector<bool> temp; temp.resize(visibleStrucrtureID.size(), true); CvMat *X = cvCreateMat(4, 1, CV_32FC1); CvMat *x = cvCreateMat(3, 1, CV_32FC1); for (int iP = 0; iP < cP.size(); iP++) { for (int iVS = 0; iVS < visibleStrucrtureID.size(); iVS++) { vector<int>:: const_iterator it = find(vFeature[visibleStrucrtureID[iVS]].vFrame.begin(), vFeature[visibleStrucrtureID[iVS]].vFrame.end(), vUsedFrame[iP]); if (it != vFeature[visibleStrucrtureID[iVS]].vFrame.end()) { int idx = (int) (it - vFeature[visibleStrucrtureID[iVS]].vFrame.begin()); cvSetReal2D(X, 0, 0, cvGetReal2D(X_tot, visibleStrucrtureID[iVS], 0)); cvSetReal2D(X, 1, 0, cvGetReal2D(X_tot, visibleStrucrtureID[iVS], 1)); cvSetReal2D(X, 2, 0, cvGetReal2D(X_tot, visibleStrucrtureID[iVS], 2)); cvSetReal2D(X, 3, 0, 1); cvMatMul(cP[iP], X, x); double u0 = vFeature[visibleStrucrtureID[iVS]].vx[idx]; double v0 = vFeature[visibleStrucrtureID[iVS]].vy[idx]; double u1 = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); double v1 = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); if (sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) > 5) { cout << visibleStrucrtureID[iVS] << "th 3D point erased " << sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) << endl; if(temp[iVS]) temp[iVS] = false; } } } } cvReleaseMat(&X); cvReleaseMat(&x); vector<int> tempID; for (int iVS = 0; iVS < visibleStrucrtureID.size(); iVS++) { if (temp[iVS]) { tempID.push_back(visibleStrucrtureID[iVS]); } } visibleStrucrtureID = tempID; } int ExcludePointHighReprojectionError_mem_fast(vector<Feature> &vFeature, vector<CvMat *> &cP, vector<int> vUsedFrame, CvMat *X_tot) { CvMat *X = cvCreateMat(4, 1, CV_32FC1); CvMat *x = cvCreateMat(3, 1, CV_32FC1); int count1=0, count2=0; for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { if (vFeature[iFeature].isRegistered) { count1++; int nProj = 0; for (int iP = 0; iP < cP.size(); iP++) { vector<int>:: const_iterator it = find(vFeature[iFeature].vFrame.begin(), vFeature[iFeature].vFrame.end(), vUsedFrame[iP]); if (it != vFeature[iFeature].vFrame.end()) { nProj++; } } if (nProj == 0) continue; for (int iP = 0; iP < cP.size(); iP++) { vector<int>:: const_iterator it = find(vFeature[iFeature].vFrame.begin(), vFeature[iFeature].vFrame.end(), vUsedFrame[iP]); if (it != vFeature[iFeature].vFrame.end()) { int idx = (int) (it - vFeature[iFeature].vFrame.begin()); cvSetReal2D(X, 0, 0, cvGetReal2D(X_tot, iFeature, 0)); cvSetReal2D(X, 1, 0, cvGetReal2D(X_tot, iFeature, 1)); cvSetReal2D(X, 2, 0, cvGetReal2D(X_tot, iFeature, 2)); cvSetReal2D(X, 3, 0, 1); cvMatMul(cP[iP], X, x); //PrintMat(X); //PrintMat(cP[iP]); //PrintMat(x); double u0 = vFeature[iFeature].vx[idx]; double v0 = vFeature[iFeature].vy[idx]; double u1 = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); double v1 = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); double dist = sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)); //cout << dist << endl; if (dist > 3) { vFeature[iFeature].vFrame.erase(vFeature[iFeature].vFrame.begin()+idx); vFeature[iFeature].vx.erase(vFeature[iFeature].vx.begin()+idx); vFeature[iFeature].vy.erase(vFeature[iFeature].vy.begin()+idx); vFeature[iFeature].vx_dis.erase(vFeature[iFeature].vx_dis.begin()+idx); vFeature[iFeature].vy_dis.erase(vFeature[iFeature].vy_dis.begin()+idx); vFeature[iFeature].vCamera.erase(vFeature[iFeature].vCamera.begin()+idx); nProj--; if (nProj < 2) { vFeature[iFeature].isRegistered = false; count2++; break; } } } } } } cout << count2 << " points are deleted." << endl; cvReleaseMat(&X); cvReleaseMat(&x); return count1; } int ExcludePointHighReprojectionError_mem_fast_Distortion(vector<Feature> &vFeature, vector<CvMat *> &cP, vector<int> vUsedFrame, CvMat *X_tot, double omega, CvMat *K) { CvMat *X = cvCreateMat(4, 1, CV_32FC1); CvMat *x = cvCreateMat(3, 1, CV_32FC1); int count1=0, count2=0; for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { if (vFeature[iFeature].isRegistered) { count1++; int nProj = 0; for (int iP = 0; iP < cP.size(); iP++) { vector<int>:: const_iterator it = find(vFeature[iFeature].vFrame.begin(), vFeature[iFeature].vFrame.end(), vUsedFrame[iP]); if (it != vFeature[iFeature].vFrame.end()) { nProj++; } } if (nProj == 0) continue; for (int iP = 0; iP < cP.size(); iP++) { vector<int>:: const_iterator it = find(vFeature[iFeature].vFrame.begin(), vFeature[iFeature].vFrame.end(), vUsedFrame[iP]); if (it != vFeature[iFeature].vFrame.end()) { int idx = (int) (it - vFeature[iFeature].vFrame.begin()); cvSetReal2D(X, 0, 0, cvGetReal2D(X_tot, iFeature, 0)); cvSetReal2D(X, 1, 0, cvGetReal2D(X_tot, iFeature, 1)); cvSetReal2D(X, 2, 0, cvGetReal2D(X_tot, iFeature, 2)); cvSetReal2D(X, 3, 0, 1); cvMatMul(cP[iP], X, x); double u = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); double v = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); double tan_omega_half_2 = tan(omega/2)*2; double K11 = cvGetReal2D(K, 0, 0); double K22 = cvGetReal2D(K, 1, 1); double K13 = cvGetReal2D(K, 0, 2); double K23 = cvGetReal2D(K, 1, 2); double u_n = u/K11 - K13/K11; double v_n = v/K22 - K23/K22; double r_u = sqrt(u_n*u_n+v_n*v_n); double r_d = 1/omega*atan(r_u*tan_omega_half_2); double u_d_n = r_d/r_u * u_n; double v_d_n = r_d/r_u * v_n; double u1 = u_d_n*K11 + K13; double v1 = v_d_n*K22 + K23; double u0 = vFeature[iFeature].vx_dis[idx]; double v0 = vFeature[iFeature].vy_dis[idx]; double dist = sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)); //cout << dist << endl; if (dist > 3) { vFeature[iFeature].vFrame.erase(vFeature[iFeature].vFrame.begin()+idx); vFeature[iFeature].vx.erase(vFeature[iFeature].vx.begin()+idx); vFeature[iFeature].vy.erase(vFeature[iFeature].vy.begin()+idx); vFeature[iFeature].vx_dis.erase(vFeature[iFeature].vx_dis.begin()+idx); vFeature[iFeature].vy_dis.erase(vFeature[iFeature].vy_dis.begin()+idx); vFeature[iFeature].vCamera.erase(vFeature[iFeature].vCamera.begin()+idx); nProj--; if (nProj < 2) { vFeature[iFeature].isRegistered = false; count2++; break; } } } } } } cout << count2 << " points are deleted." << endl; cvReleaseMat(&X); cvReleaseMat(&x); return count1; } int ExcludePointHighReprojectionError_mem_fast_Distortion_AD(vector<Feature> &vFeature, vector<CvMat *> &cP, vector<int> vUsedFrame, CvMat *X_tot, double omega, CvMat *K, vector<vector<int> > &vvPointIndex) { CvMat *X = cvCreateMat(4, 1, CV_32FC1); CvMat *x = cvCreateMat(3, 1, CV_32FC1); int count1=0, count2=0; for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { if (vFeature[iFeature].isRegistered) { count1++; int nProj = 0; for (int iP = 0; iP < cP.size(); iP++) { vector<int>:: const_iterator it = find(vFeature[iFeature].vFrame.begin(), vFeature[iFeature].vFrame.end(), vUsedFrame[iP]); if (it != vFeature[iFeature].vFrame.end()) { nProj++; } } if (nProj == 0) continue; for (int iP = 0; iP < cP.size(); iP++) { vector<int>:: const_iterator it = find(vFeature[iFeature].vFrame.begin(), vFeature[iFeature].vFrame.end(), vUsedFrame[iP]); if (it != vFeature[iFeature].vFrame.end()) { int idx = (int) (it - vFeature[iFeature].vFrame.begin()); cvSetReal2D(X, 0, 0, cvGetReal2D(X_tot, iFeature, 0)); cvSetReal2D(X, 1, 0, cvGetReal2D(X_tot, iFeature, 1)); cvSetReal2D(X, 2, 0, cvGetReal2D(X_tot, iFeature, 2)); cvSetReal2D(X, 3, 0, 1); cvMatMul(cP[iP], X, x); double u = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); double v = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); double tan_omega_half_2 = tan(omega/2)*2; double K11 = cvGetReal2D(K, 0, 0); double K22 = cvGetReal2D(K, 1, 1); double K13 = cvGetReal2D(K, 0, 2); double K23 = cvGetReal2D(K, 1, 2); double u_n = u/K11 - K13/K11; double v_n = v/K22 - K23/K22; double r_u = sqrt(u_n*u_n+v_n*v_n); double r_d = 1/omega*atan(r_u*tan_omega_half_2); double u_d_n = r_d/r_u * u_n; double v_d_n = r_d/r_u * v_n; double u1 = u_d_n*K11 + K13; double v1 = v_d_n*K22 + K23; double u0 = vFeature[iFeature].vx_dis[idx]; double v0 = vFeature[iFeature].vy_dis[idx]; double dist = sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)); //cout << dist << endl; if (dist > 3) { vector<int>::const_iterator it = find(vvPointIndex[iP].begin(), vvPointIndex[iP].end(), vFeature[iFeature].id); //if (it != vvPointIndex[iP].end()) { int idx_point = (int) (it - vvPointIndex[iP].begin()); vvPointIndex[iP].erase(vvPointIndex[iP].begin()+idx_point); } vFeature[iFeature].vFrame.erase(vFeature[iFeature].vFrame.begin()+idx); vFeature[iFeature].vx.erase(vFeature[iFeature].vx.begin()+idx); vFeature[iFeature].vy.erase(vFeature[iFeature].vy.begin()+idx); vFeature[iFeature].vx_dis.erase(vFeature[iFeature].vx_dis.begin()+idx); vFeature[iFeature].vy_dis.erase(vFeature[iFeature].vy_dis.begin()+idx); vFeature[iFeature].vCamera.erase(vFeature[iFeature].vCamera.begin()+idx); nProj--; if (nProj < 2) { vFeature[iFeature].isRegistered = false; count2++; break; } } } } } } cout << count2 << " points are deleted." << endl; cvReleaseMat(&X); cvReleaseMat(&x); return count1; } int ExcludePointHighReprojectionError_mem_fast_AD(vector<Feature> &vFeature, vector<CvMat *> &cP, vector<int> vUsedFrame, CvMat *X_tot, CvMat *K, vector<vector<int> > &vvPointIndex) { CvMat *X = cvCreateMat(4, 1, CV_32FC1); CvMat *x = cvCreateMat(3, 1, CV_32FC1); int count1=0, count2=0; for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { if (vFeature[iFeature].isRegistered) { count1++; int nProj = 0; for (int iP = 0; iP < cP.size(); iP++) { vector<int>:: const_iterator it = find(vFeature[iFeature].vFrame.begin(), vFeature[iFeature].vFrame.end(), vUsedFrame[iP]); if (it != vFeature[iFeature].vFrame.end()) { nProj++; } } if (nProj == 0) continue; for (int iP = 0; iP < cP.size(); iP++) { vector<int>:: const_iterator it = find(vFeature[iFeature].vFrame.begin(), vFeature[iFeature].vFrame.end(), vUsedFrame[iP]); if (it != vFeature[iFeature].vFrame.end()) { int idx = (int) (it - vFeature[iFeature].vFrame.begin()); cvSetReal2D(X, 0, 0, cvGetReal2D(X_tot, iFeature, 0)); cvSetReal2D(X, 1, 0, cvGetReal2D(X_tot, iFeature, 1)); cvSetReal2D(X, 2, 0, cvGetReal2D(X_tot, iFeature, 2)); cvSetReal2D(X, 3, 0, 1); cvMatMul(cP[iP], X, x); double u1 = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); double v1 = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); //double tan_omega_half_2 = tan(omega/2)*2; //double K11 = cvGetReal2D(K, 0, 0); //double K22 = cvGetReal2D(K, 1, 1); //double K13 = cvGetReal2D(K, 0, 2); //double K23 = cvGetReal2D(K, 1, 2); //double u_n = u/K11 - K13/K11; //double v_n = v/K22 - K23/K22; //double r_u = sqrt(u_n*u_n+v_n*v_n); //double r_d = 1/omega*atan(r_u*tan_omega_half_2); //double u_d_n = r_d/r_u * u_n; //double v_d_n = r_d/r_u * v_n; //double u1 = u_d_n*K11 + K13; //double v1 = v_d_n*K22 + K23; double u0 = vFeature[iFeature].vx_dis[idx]; double v0 = vFeature[iFeature].vy_dis[idx]; double dist = sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)); //cout << dist << endl; if (dist > 3) { vector<int>::const_iterator it = find(vvPointIndex[iP].begin(), vvPointIndex[iP].end(), vFeature[iFeature].id); if (it != vvPointIndex[iP].end()) { int idx_point = (int) (it - vvPointIndex[iP].begin()); vvPointIndex[iP].erase(vvPointIndex[iP].begin()+idx_point); } vFeature[iFeature].vFrame.erase(vFeature[iFeature].vFrame.begin()+idx); vFeature[iFeature].vx.erase(vFeature[iFeature].vx.begin()+idx); vFeature[iFeature].vy.erase(vFeature[iFeature].vy.begin()+idx); vFeature[iFeature].vx_dis.erase(vFeature[iFeature].vx_dis.begin()+idx); vFeature[iFeature].vy_dis.erase(vFeature[iFeature].vy_dis.begin()+idx); vFeature[iFeature].vCamera.erase(vFeature[iFeature].vCamera.begin()+idx); nProj--; if (nProj < 2) { vFeature[iFeature].isRegistered = false; count2++; break; } } } } } } cout << count2 << " points are deleted." << endl; cvReleaseMat(&X); cvReleaseMat(&x); return count1; } int ExcludePointHighReprojectionError_mem_fast_Distortion_ObstacleDetection(vector<Feature> &vFeature, vector<CvMat *> &cP, vector<int> vUsedFrame, CvMat *X_tot, double omega, double princ_x1, double princ_y1, CvMat *K) { CvMat *X = cvCreateMat(4, 1, CV_32FC1); CvMat *x = cvCreateMat(3, 1, CV_32FC1); int count1=0, count2=0; for (int iFeature = 0; iFeature < vFeature.size(); iFeature++) { if (vFeature[iFeature].isRegistered) { count1++; int nProj = 0; for (int iP = 0; iP < cP.size(); iP++) { vector<int>:: const_iterator it = find(vFeature[iFeature].vFrame.begin(), vFeature[iFeature].vFrame.end(), vUsedFrame[iP]); if (it != vFeature[iFeature].vFrame.end()) { nProj++; } } if (nProj == 0) continue; for (int iP = 0; iP < cP.size(); iP++) { vector<int>:: const_iterator it = find(vFeature[iFeature].vFrame.begin(), vFeature[iFeature].vFrame.end(), vUsedFrame[iP]); if (it != vFeature[iFeature].vFrame.end()) { int idx = (int) (it - vFeature[iFeature].vFrame.begin()); cvSetReal2D(X, 0, 0, cvGetReal2D(X_tot, iFeature, 0)); cvSetReal2D(X, 1, 0, cvGetReal2D(X_tot, iFeature, 1)); cvSetReal2D(X, 2, 0, cvGetReal2D(X_tot, iFeature, 2)); cvSetReal2D(X, 3, 0, 1); cvMatMul(cP[iP], X, x); double u = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); double v = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); double tan_omega_half_2 = tan(omega/2)*2; //double K11 = cvGetReal2D(K, 0, 0); //double K22 = cvGetReal2D(K, 1, 1); //double K13 = cvGetReal2D(K, 0, 2); //double K23 = cvGetReal2D(K, 1, 2); //double u_n = u/K11 - K13/K11; //double v_n = v/K22 - K23/K22; double u_n = u - princ_x1; double v_n = v - princ_y1; double r_u = sqrt(u_n*u_n+v_n*v_n); double r_d = 1/omega*atan(r_u*tan_omega_half_2); double u_d_n = r_d/r_u * u_n; double v_d_n = r_d/r_u * v_n; double u1 = u_d_n + princ_x1; double v1 = v_d_n + princ_y1; double u0 = vFeature[iFeature].vx_dis[idx]; double v0 = vFeature[iFeature].vy_dis[idx]; double dist = sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)); //cout << dist << endl; if (dist > 3) { vFeature[iFeature].vFrame.erase(vFeature[iFeature].vFrame.begin()+idx); vFeature[iFeature].vx.erase(vFeature[iFeature].vx.begin()+idx); vFeature[iFeature].vy.erase(vFeature[iFeature].vy.begin()+idx); vFeature[iFeature].vx_dis.erase(vFeature[iFeature].vx_dis.begin()+idx); vFeature[iFeature].vy_dis.erase(vFeature[iFeature].vy_dis.begin()+idx); vFeature[iFeature].vCamera.erase(vFeature[iFeature].vCamera.begin()+idx); nProj--; if (nProj < 2) { vFeature[iFeature].isRegistered = false; count2++; break; } } } } } } cout << count2 << " points are deleted." << endl; cvReleaseMat(&X); cvReleaseMat(&x); return count1; } bool ExcludePointHighReprojectionError_AddingFrame(vector<Feature> vFeature, vector<CvMat *> cP, vector<int> vUsedFrame , vector<int> &visibleStrucrtureID, CvMat &X_tot , vector<int> &visibleStrucrtureID_new, CvMat &X_tot_new) { visibleStrucrtureID_new.clear(); vector<double> vx, vy, vz; for (int iVS = 0; iVS < visibleStrucrtureID.size(); iVS++) { bool isIn = true; for (int iP = 0; iP < cP.size(); iP++) { vector<int>:: const_iterator it = find(vFeature[visibleStrucrtureID[iVS]].vFrame.begin(), vFeature[visibleStrucrtureID[iVS]].vFrame.end(), vUsedFrame[iP]); if (it != vFeature[visibleStrucrtureID[iVS]].vFrame.end()) { int idx = (int) (it - vFeature[visibleStrucrtureID[iVS]].vFrame.begin()); CvMat *X = cvCreateMat(4, 1, CV_32FC1); CvMat *x = cvCreateMat(3, 1, CV_32FC1); cvSetReal2D(X, 0, 0, cvGetReal2D(&X_tot, iVS, 0)); cvSetReal2D(X, 1, 0, cvGetReal2D(&X_tot, iVS, 1)); cvSetReal2D(X, 2, 0, cvGetReal2D(&X_tot, iVS, 2)); cvSetReal2D(X, 3, 0, 1); cvMatMul(cP[iP], X, x); double u0 = vFeature[visibleStrucrtureID[iVS]].vx[idx]; double v0 = vFeature[visibleStrucrtureID[iVS]].vy[idx]; double u1 = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); double v1 = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); if (sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) > 5) { //cout << visibleStrucrtureID[iVS] << "th 3D point erased " << sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) << endl; isIn = false; break; } cvReleaseMat(&X); cvReleaseMat(&x); } } if (isIn) { visibleStrucrtureID_new.push_back(visibleStrucrtureID[iVS]); vx.push_back(cvGetReal2D(&X_tot, iVS, 0)); vy.push_back(cvGetReal2D(&X_tot, iVS, 1)); vz.push_back(cvGetReal2D(&X_tot, iVS, 2)); } } if (visibleStrucrtureID_new.size() == 0) return false; X_tot_new = *cvCreateMat(visibleStrucrtureID_new.size(), 3, CV_32FC1); for (int ivx = 0; ivx < visibleStrucrtureID_new.size(); ivx++) { cvSetReal2D(&X_tot_new, ivx, 0, vx[ivx]); cvSetReal2D(&X_tot_new, ivx, 1, vy[ivx]); cvSetReal2D(&X_tot_new, ivx, 2, vz[ivx]); } return true; } bool ExcludePointHighReprojectionError_AddingFrame_mem(vector<Feature> &vFeature, vector<CvMat *> cP, vector<int> vUsedFrame , vector<int> &visibleStrucrtureID, CvMat *X_tot , vector<int> &visibleStrucrtureID_new, vector<vector<double> > &X_tot_new) { visibleStrucrtureID_new.clear(); vector<double> vx, vy, vz; for (int iVS = 0; iVS < visibleStrucrtureID.size(); iVS++) { bool isIn = true; for (int iP = 0; iP < cP.size(); iP++) { vector<int>:: const_iterator it = find(vFeature[visibleStrucrtureID[iVS]].vFrame.begin(), vFeature[visibleStrucrtureID[iVS]].vFrame.end(), vUsedFrame[iP]); if (it != vFeature[visibleStrucrtureID[iVS]].vFrame.end()) { int idx = (int) (it - vFeature[visibleStrucrtureID[iVS]].vFrame.begin()); CvMat *X = cvCreateMat(4, 1, CV_32FC1); CvMat *x = cvCreateMat(3, 1, CV_32FC1); cvSetReal2D(X, 0, 0, cvGetReal2D(X_tot, iVS, 0)); cvSetReal2D(X, 1, 0, cvGetReal2D(X_tot, iVS, 1)); cvSetReal2D(X, 2, 0, cvGetReal2D(X_tot, iVS, 2)); cvSetReal2D(X, 3, 0, 1); cvMatMul(cP[iP], X, x); double u0 = vFeature[visibleStrucrtureID[iVS]].vx[idx]; double v0 = vFeature[visibleStrucrtureID[iVS]].vy[idx]; double u1 = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); double v1 = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); if (sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) > 5) { //cout << visibleStrucrtureID[iVS] << "th 3D point erased " << sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) << endl; isIn = false; cvReleaseMat(&X); cvReleaseMat(&x); break; } cvReleaseMat(&X); cvReleaseMat(&x); } } if (isIn) { visibleStrucrtureID_new.push_back(visibleStrucrtureID[iVS]); vx.push_back(cvGetReal2D(X_tot, iVS, 0)); vy.push_back(cvGetReal2D(X_tot, iVS, 1)); vz.push_back(cvGetReal2D(X_tot, iVS, 2)); } } if (visibleStrucrtureID_new.size() == 0) return false; for (int ivx = 0; ivx < visibleStrucrtureID_new.size(); ivx++) { vector<double> X_tot_new_vec; X_tot_new_vec.push_back(vx[ivx]); X_tot_new_vec.push_back(vy[ivx]); X_tot_new_vec.push_back(vz[ivx]); X_tot_new.push_back(X_tot_new_vec); } return true; } bool ExcludePointHighReprojectionError_AddingFrame_mem_fast(vector<Feature> &vFeature, vector<CvMat *> &cP, vector<int> &vUsedFrame , vector<int> &visibleStrucrtureID, CvMat *X_tot , vector<int> &visibleStrucrtureID_new, vector<vector<double> > &X_tot_new) { visibleStrucrtureID_new.clear(); CvMat *X = cvCreateMat(4, 1, CV_32FC1); CvMat *x = cvCreateMat(3, 1, CV_32FC1); for (int iVS = 0; iVS < visibleStrucrtureID.size(); iVS++) { bool isIn = true; for (int iP = 0; iP < cP.size(); iP++) { vector<int>:: const_iterator it = find(vFeature[visibleStrucrtureID[iVS]].vFrame.begin(), vFeature[visibleStrucrtureID[iVS]].vFrame.end(), vUsedFrame[iP]); if (it != vFeature[visibleStrucrtureID[iVS]].vFrame.end()) { int idx = (int) (it - vFeature[visibleStrucrtureID[iVS]].vFrame.begin()); cvSetReal2D(X, 0, 0, cvGetReal2D(X_tot, iVS, 0)); cvSetReal2D(X, 1, 0, cvGetReal2D(X_tot, iVS, 1)); cvSetReal2D(X, 2, 0, cvGetReal2D(X_tot, iVS, 2)); cvSetReal2D(X, 3, 0, 1); cvMatMul(cP[iP], X, x); double u0 = vFeature[visibleStrucrtureID[iVS]].vx[idx]; double v0 = vFeature[visibleStrucrtureID[iVS]].vy[idx]; double u1 = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); double v1 = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); if (sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) > 5) { //cout << visibleStrucrtureID[iVS] << "th 3D point erased " << sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) << endl; isIn = false; break; } } } if (isIn) { visibleStrucrtureID_new.push_back(visibleStrucrtureID[iVS]); vector<double> X_tot_new_vec; X_tot_new_vec.push_back(cvGetReal2D(X_tot, iVS, 0)); X_tot_new_vec.push_back(cvGetReal2D(X_tot, iVS, 1)); X_tot_new_vec.push_back(cvGetReal2D(X_tot, iVS, 2)); X_tot_new.push_back(X_tot_new_vec); } } cvReleaseMat(&X); cvReleaseMat(&x); if (visibleStrucrtureID_new.size() == 0) return false; return true; } bool ExcludePointHighReprojectionError_AddingFrame_mem_fast_Distortion(vector<Feature> &vFeature, vector<CvMat *> &cP, vector<int> &vUsedFrame , vector<int> &visibleStrucrtureID, CvMat *X_tot , vector<int> &visibleStrucrtureID_new, vector<vector<double> > &X_tot_new, double omega, CvMat *K) { visibleStrucrtureID_new.clear(); CvMat *X = cvCreateMat(4, 1, CV_32FC1); CvMat *x = cvCreateMat(3, 1, CV_32FC1); for (int iVS = 0; iVS < visibleStrucrtureID.size(); iVS++) { bool isIn = true; for (int iP = 0; iP < cP.size(); iP++) { vector<int>:: const_iterator it = find(vFeature[visibleStrucrtureID[iVS]].vFrame.begin(), vFeature[visibleStrucrtureID[iVS]].vFrame.end(), vUsedFrame[iP]); if (it != vFeature[visibleStrucrtureID[iVS]].vFrame.end()) { int idx = (int) (it - vFeature[visibleStrucrtureID[iVS]].vFrame.begin()); cvSetReal2D(X, 0, 0, cvGetReal2D(X_tot, iVS, 0)); cvSetReal2D(X, 1, 0, cvGetReal2D(X_tot, iVS, 1)); cvSetReal2D(X, 2, 0, cvGetReal2D(X_tot, iVS, 2)); cvSetReal2D(X, 3, 0, 1); cvMatMul(cP[iP], X, x); double u = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); double v = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); double tan_omega_half_2 = tan(omega/2)*2; double K11 = cvGetReal2D(K, 0, 0); double K22 = cvGetReal2D(K, 1, 1); double K13 = cvGetReal2D(K, 0, 2); double K23 = cvGetReal2D(K, 1, 2); double u_n = u/K11 - K13/K11; double v_n = v/K22 - K23/K22; double r_u = sqrt(u_n*u_n+v_n*v_n); double r_d = 1/omega*atan(r_u*tan_omega_half_2); double u_d_n = r_d/r_u * u_n; double v_d_n = r_d/r_u * v_n; double u1 = u_d_n*K11 + K13; double v1 = v_d_n*K22 + K23; double u0 = vFeature[visibleStrucrtureID[iVS]].vx_dis[idx]; double v0 = vFeature[visibleStrucrtureID[iVS]].vy_dis[idx]; //double u1 = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); //double v1 = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); if (sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) > 3) { //cout << visibleStrucrtureID[iVS] << "th 3D point erased " << sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) << endl; isIn = false; break; } } } if (isIn) { visibleStrucrtureID_new.push_back(visibleStrucrtureID[iVS]); vector<double> X_tot_new_vec; X_tot_new_vec.push_back(cvGetReal2D(X_tot, iVS, 0)); X_tot_new_vec.push_back(cvGetReal2D(X_tot, iVS, 1)); X_tot_new_vec.push_back(cvGetReal2D(X_tot, iVS, 2)); X_tot_new.push_back(X_tot_new_vec); } } cvReleaseMat(&X); cvReleaseMat(&x); if (visibleStrucrtureID_new.size() == 0) return false; return true; } bool ExcludePointHighReprojectionError_AddingFrame_mem_fast_Distortion_ObstacleDetection(vector<Feature> &vFeature, vector<CvMat *> &cP, vector<int> &vUsedFrame , vector<int> &visibleStrucrtureID, CvMat *X_tot , vector<int> &visibleStrucrtureID_new, vector<vector<double> > &X_tot_new, double omega, double princ_x1, double princ_y1, CvMat *K) { visibleStrucrtureID_new.clear(); CvMat *X = cvCreateMat(4, 1, CV_32FC1); CvMat *x = cvCreateMat(3, 1, CV_32FC1); for (int iVS = 0; iVS < visibleStrucrtureID.size(); iVS++) { bool isIn = true; for (int iP = 0; iP < cP.size(); iP++) { vector<int>:: const_iterator it = find(vFeature[visibleStrucrtureID[iVS]].vFrame.begin(), vFeature[visibleStrucrtureID[iVS]].vFrame.end(), vUsedFrame[iP]); if (it != vFeature[visibleStrucrtureID[iVS]].vFrame.end()) { int idx = (int) (it - vFeature[visibleStrucrtureID[iVS]].vFrame.begin()); cvSetReal2D(X, 0, 0, cvGetReal2D(X_tot, iVS, 0)); cvSetReal2D(X, 1, 0, cvGetReal2D(X_tot, iVS, 1)); cvSetReal2D(X, 2, 0, cvGetReal2D(X_tot, iVS, 2)); cvSetReal2D(X, 3, 0, 1); cvMatMul(cP[iP], X, x); double u = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); double v = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); double tan_omega_half_2 = tan(omega/2)*2; //double K11 = cvGetReal2D(K, 0, 0); //double K22 = cvGetReal2D(K, 1, 1); //double K13 = cvGetReal2D(K, 0, 2); //double K23 = cvGetReal2D(K, 1, 2); //double u_n = u/K11 - K13/K11; //double v_n = v/K22 - K23/K22; double u_n = u - princ_x1; double v_n = v - princ_y1; double r_u = sqrt(u_n*u_n+v_n*v_n); double r_d = 1/omega*atan(r_u*tan_omega_half_2); double u_d_n = r_d/r_u * u_n; double v_d_n = r_d/r_u * v_n; double u1 = u_d_n + princ_x1; double v1 = v_d_n + princ_y1; double u0 = vFeature[visibleStrucrtureID[iVS]].vx_dis[idx]; double v0 = vFeature[visibleStrucrtureID[iVS]].vy_dis[idx]; //double u1 = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0); //double v1 = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0); if (sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) > 3) { //cout << visibleStrucrtureID[iVS] << "th 3D point erased " << sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) << endl; isIn = false; break; } } } if (isIn) { visibleStrucrtureID_new.push_back(visibleStrucrtureID[iVS]); vector<double> X_tot_new_vec; X_tot_new_vec.push_back(cvGetReal2D(X_tot, iVS, 0)); X_tot_new_vec.push_back(cvGetReal2D(X_tot, iVS, 1)); X_tot_new_vec.push_back(cvGetReal2D(X_tot, iVS, 2)); X_tot_new.push_back(X_tot_new_vec); } } cvReleaseMat(&X); cvReleaseMat(&x); if (visibleStrucrtureID_new.size() == 0) return false; return true; } void OrientationRefinement(CvMat *R_1, CvMat *R_F, vector<int> vFrame1, vector<int> vFrame2, vector<CvMat*> &vM, vector<CvMat*> &vm, vector<CvMat *> &vx1, vector<CvMat *> &vx2) { //PrintAlgorithm("Orientation Refinement"); //vector<double> cameraParameter, measurement; //AdditionalData adata;// focal_x focal_y princ_x princ_y ////double intrinsic[4] = {cvGetReal2D(K, 0, 0), cvGetReal2D(K, 1, 1), cvGetReal2D(K, 0, 2), cvGetReal2D(K, 1, 2)}; ////adata.vIntrinsic.push_back(intrinsic); //adata.nFrames = vFrame1.size(); //adata.vx1 = &vx1; //adata.vx2 = &vx2; //for (int iFrame = 0; iFrame < vFrame1.size(); iFrame++) //{ // CvMat *q = cvCreateMat(4,1,CV_32FC1); // Rotation2Quaternion(vM[iFrame], q); // cameraParameter.push_back(cvGetReal2D(q, 0, 0)); // cameraParameter.push_back(cvGetReal2D(q, 1, 0)); // cameraParameter.push_back(cvGetReal2D(q, 2, 0)); // cameraParameter.push_back(cvGetReal2D(q, 3, 0)); // cameraParameter.push_back(cvGetReal2D(vm[iFrame], 0, 0)); // cameraParameter.push_back(cvGetReal2D(vm[iFrame], 1, 0)); // cameraParameter.push_back(cvGetReal2D(vm[iFrame], 2, 0)); // cvReleaseMat(&q); //} //CvMat *R_r = cvCreateMat(3,3,CV_32FC1); //CvMat *R_1_inv = cvCreateMat(3,3,CV_32FC1); //cvInvert(R_1, R_1_inv); //cvMatMul(R_F, R_1_inv, R_r); //CvMat *q_r = cvCreateMat(4,1,CV_32FC1); //Rotation2Quaternion(R_r, q_r); //measurement.push_back(cvGetReal2D(q_r, 0, 0)); //measurement.push_back(cvGetReal2D(q_r, 1, 0)); //measurement.push_back(cvGetReal2D(q_r, 2, 0)); //measurement.push_back(cvGetReal2D(q_r, 3, 0)); //for (int i = 0; i < vx1.size(); i++) //{ // if (vx1[i]->rows == 1) // continue; // //for (int j = 0; j < vx1[i]->rows; j++) // for (int j = 0; j < 10; j++) // measurement.push_back(0); //} //cvReleaseMat(&R_r); //cvReleaseMat(&R_1_inv); //cvReleaseMat(&q_r); //double *dmeasurement = (double *) malloc(measurement.size() * sizeof(double)); //double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double)); //for (int i = 0; i < cameraParameter.size(); i++) // dCameraParameter[i] = cameraParameter[i]; //for (int i = 0; i < measurement.size(); i++) // dmeasurement[i] = measurement[i]; //double opt[5]; //opt[0] = 1e-3; //opt[1] = 1e-12; //opt[2] = 1e-12; //opt[3] = 1e-12; //opt[4] = 0; //double info[12]; //double *work = (double*)malloc((LM_DIF_WORKSZ(cameraParameter.size(), measurement.size())+cameraParameter.size()*cameraParameter.size())*sizeof(double)); //if(!work) // fprintf(stderr, "memory allocation request failed in main()\n"); //int ret = dlevmar_dif(ObjectiveOrientationRefinement, dCameraParameter, dmeasurement, cameraParameter.size(), measurement.size(), // 1e+2, opt, info, work, NULL, &adata); //PrintSBAInfo(info); //for (int iFrame = 0; iFrame < vFrame1.size(); iFrame++) //{ // CvMat *q = cvCreateMat(4,1,CV_32FC1); // CvMat *R = cvCreateMat(3,3,CV_32FC1); // cvSetReal2D(q, 0, 0, dCameraParameter[7*iFrame+0]); // cvSetReal2D(q, 1, 0, dCameraParameter[7*iFrame+1]); // cvSetReal2D(q, 2, 0, dCameraParameter[7*iFrame+2]); // cvSetReal2D(q, 3, 0, dCameraParameter[7*iFrame+3]); // Quaternion2Rotation(q, R); // for (int i = 0; i < 3; i++) // { // for (int j = 0; j < 3; j++) // { // cvSetReal2D(vM[iFrame], i, j, cvGetReal2D(R, i, j)); // } // } // cvReleaseMat(&q); // cvReleaseMat(&R); // cvSetReal2D(vm[iFrame], 0, 0, dCameraParameter[7*iFrame+4]); // cvSetReal2D(vm[iFrame], 1, 0, dCameraParameter[7*iFrame+5]); // cvSetReal2D(vm[iFrame], 2, 0, dCameraParameter[7*iFrame+6]); // //} //free(dmeasurement); //free(dCameraParameter); //free(work); } void OrientationRefinement1(CvMat *R_1, CvMat *R_F, vector<int> vFrame1, vector<int> vFrame2, vector<CvMat*> &vM, vector<CvMat*> &vm, vector<CvMat *> &vx1, vector<CvMat *> &vx2, vector<int> vFrame1_r, vector<int> vFrame2_r, vector<CvMat*> &vM_r, vector<CvMat*> &vm_r, vector<CvMat *> &vx1_r, vector<CvMat *> &vx2_r) { //PrintAlgorithm("Orientation Refinement for non-consecutive frame"); // //// focal_x focal_y princ_x princ_y ////double intrinsic[4] = {cvGetReal2D(K, 0, 0), cvGetReal2D(K, 1, 1), cvGetReal2D(K, 0, 2), cvGetReal2D(K, 1, 2)}; ////adata.vIntrinsic.push_back(intrinsic); //for (int iFrame = 0; iFrame < vFrame1_r.size(); iFrame++) //{ // vector<double> cameraParameter, measurement; // AdditionalData adata; // //cout << endl << "Orientation Refinement for non-consecutive frame: " << vFrame1_r[iFrame] << " " << vFrame2_r[iFrame] << endl; // cout << vFrame1_r[iFrame] << " "; // cameraParameter.clear(); // measurement.clear(); // vector<double> vx1_a, vy1_a, vx2_a, vy2_a; // for (int ix = 0; ix < vx1_r[iFrame]->rows; ix++) // { // vx1_a.push_back(cvGetReal2D(vx1_r[iFrame], ix, 0)); // vy1_a.push_back(cvGetReal2D(vx1_r[iFrame], ix, 1)); // vx2_a.push_back(cvGetReal2D(vx2_r[iFrame], ix, 0)); // vy2_a.push_back(cvGetReal2D(vx2_r[iFrame], ix, 1)); // measurement.push_back(0); // } // adata.vx1_a = &vx1_a; // adata.vy1_a = &vy1_a; // adata.vx2_a = &vx2_a; // adata.vy2_a = &vy2_a; // // vector<int>::iterator it1 = find(vFrame1.begin(), vFrame1.end(), vFrame1_r[iFrame]); // vector<int>::iterator it2 = find(vFrame2.begin(), vFrame2.end(), vFrame2_r[iFrame]); // int idx1 = (int) (it1 - vFrame1.begin()); // int idx2 = (int) (it2 - vFrame2.begin()); // CvMat *R_r = cvCreateMat(3,3,CV_32FC1); // cvSetIdentity(R_r); // for (int iIdx = idx1; iIdx < idx2+1; iIdx++) // { // cvMatMul(vM[iIdx], R_r, R_r); // } // CvMat *q = cvCreateMat(4,1,CV_32FC1); // Rotation2Quaternion(R_r, q); // //Rotation2Quaternion(vM_r[iFrame], q); // adata.qw = cvGetReal2D(q, 0, 0); // adata.qx = cvGetReal2D(q, 1, 0); // adata.qy = cvGetReal2D(q, 2, 0); // adata.qz = cvGetReal2D(q, 3, 0); // cvReleaseMat(&q); // cameraParameter.push_back(cvGetReal2D(vm_r[iFrame], 0, 0)); // cameraParameter.push_back(cvGetReal2D(vm_r[iFrame], 1, 0)); // cameraParameter.push_back(cvGetReal2D(vm_r[iFrame], 2, 0)); // // cvSetReal2D(vM_r[iFrame], 0, 0, cvGetReal2D(R_r, 0, 0)); cvSetReal2D(vM_r[iFrame], 0, 1, cvGetReal2D(R_r, 0, 1)); cvSetReal2D(vM_r[iFrame], 0, 2, cvGetReal2D(R_r, 0, 2)); // cvSetReal2D(vM_r[iFrame], 1, 0, cvGetReal2D(R_r, 1, 0)); cvSetReal2D(vM_r[iFrame], 1, 1, cvGetReal2D(R_r, 1, 1)); cvSetReal2D(vM_r[iFrame], 1, 2, cvGetReal2D(R_r, 1, 2)); // cvSetReal2D(vM_r[iFrame], 2, 0, cvGetReal2D(R_r, 2, 0)); cvSetReal2D(vM_r[iFrame], 2, 1, cvGetReal2D(R_r, 2, 1)); cvSetReal2D(vM_r[iFrame], 2, 2, cvGetReal2D(R_r, 2, 2)); // //for (int i = 0; i < vx1_r.size(); i++) // //{ // // for (int j = 0; j < vx1[i]->rows; j++) // // measurement.push_back(0); // //} // double *dmeasurement = (double *) malloc(measurement.size() * sizeof(double)); // double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double)); // for (int i = 0; i < cameraParameter.size(); i++) // dCameraParameter[i] = cameraParameter[i]; // for (int i = 0; i < measurement.size(); i++) // dmeasurement[i] = measurement[i]; // double opt[5]; // opt[0] = 1e-3; // opt[1] = 1e-12; // opt[2] = 1e-12; // opt[3] = 1e-12; // opt[4] = 0; // double info[12]; // double *work = (double*)malloc((LM_DIF_WORKSZ(cameraParameter.size(), measurement.size())+cameraParameter.size()*cameraParameter.size())*sizeof(double)); // if(!work) // fprintf(stderr, "memory allocation request failed in main()\n"); // int ret = dlevmar_dif(ObjectiveOrientationRefinement1, dCameraParameter, dmeasurement, cameraParameter.size(), measurement.size(), // 1e+2, opt, info, work, NULL, &adata); // //PrintSBAInfo(info); // cvReleaseMat(&R_r); // cvSetReal2D(vm_r[iFrame], 0, 0, dCameraParameter[0]); // cvSetReal2D(vm_r[iFrame], 1, 0, dCameraParameter[1]); // cvSetReal2D(vm_r[iFrame], 2, 0, dCameraParameter[2]); // free(dmeasurement); // free(dCameraParameter); // free(work); //} //cout << endl; } //void OrientationRefinement_sba(CvMat *R_1, CvMat *R_F, vector<int> vFrame1, vector<int> vFrame2, vector<CvMat*> &vM, vector<CvMat*> &vm, vector<CvMat *> &vx1, vector<CvMat *> &vx2, // vector<int> vFrame1_r, vector<int> vFrame2_r, vector<CvMat*> &vM_r, vector<CvMat*> &vm_r, vector<CvMat *> &vx1_r, vector<CvMat *> &vx2_r) //{ // PrintAlgorithm("Orientation Refinement - sba"); // vector<double> cameraParameter, measurement; // AdditionalData adata;// focal_x focal_y princ_x princ_y // //double intrinsic[4] = {cvGetReal2D(K, 0, 0), cvGetReal2D(K, 1, 1), cvGetReal2D(K, 0, 2), cvGetReal2D(K, 1, 2)}; // //adata.vIntrinsic.push_back(intrinsic); // //adata.vFrame1 = vFrame1; // //adata.vFrame2 = vFrame2; // //adata.vFrame1_r = vFrame1_r; // //adata.vFrame2_r = vFrame2_r; // // //adata.vx1 = &vx1; // //adata.vx2 = &vx2; // // //adata.vx1_r = &vx1_r; // //adata.vx2_r = &vx2_r; // // //for (int iFrame = 0; iFrame < vFrame1.size(); iFrame++) // //{ // // CvMat *q = cvCreateMat(4,1,CV_32FC1); // // Rotation2Quaternion(vM[iFrame], q); // // cameraParameter.push_back(cvGetReal2D(q, 0, 0)); // // cameraParameter.push_back(cvGetReal2D(q, 1, 0)); // // cameraParameter.push_back(cvGetReal2D(q, 2, 0)); // // cameraParameter.push_back(cvGetReal2D(q, 3, 0)); // // cvReleaseMat(&q); // // // cameraParameter.push_back(cvGetReal2D(vm[iFrame], 0, 0)); // // cameraParameter.push_back(cvGetReal2D(vm[iFrame], 1, 0)); // // cameraParameter.push_back(cvGetReal2D(vm[iFrame], 2, 0)); // //} // // //for (int iFrame = 0; iFrame < vFrame1_r.size(); iFrame++) // //{ // // cameraParameter.push_back(cvGetReal2D(vm_r[iFrame], 0, 0)); // // cameraParameter.push_back(cvGetReal2D(vm_r[iFrame], 1, 0)); // // cameraParameter.push_back(cvGetReal2D(vm_r[iFrame], 2, 0)); // //} // // CvMat *R_r = cvCreateMat(3,3,CV_32FC1); // CvMat *R_1_inv = cvCreateMat(3,3,CV_32FC1); // cvInvert(R_1, R_1_inv); // cvMatMul(R_F, R_1_inv, R_r); // CvMat *q_r = cvCreateMat(4,1,CV_32FC1); // Rotation2Quaternion(R_r, q_r); // //measurement.push_back(cvGetReal2D(q_r, 0, 0)); // //measurement.push_back(cvGetReal2D(q_r, 1, 0)); // //measurement.push_back(cvGetReal2D(q_r, 2, 0)); // //measurement.push_back(cvGetReal2D(q_r, 3, 0)); // // for (int i = 0; i < vx1.size(); i++) // { // for (int j = 0; j < vx1[i]->rows; j++) // //for (int j = 0; j < 7; j++) // measurement.push_back(0); // } // // //for (int i = 0; i < vx1_r.size(); i++) // //{ // // for (int j = 0; j < vx1[i]->rows; j++) // // //for (int j = 0; j < 3; j++) // // measurement.push_back(0); // //} // // cameraParameter.push_back(cvGetReal2D(q_r, 0, 0)); // cameraParameter.push_back(cvGetReal2D(q_r, 1, 0)); // cameraParameter.push_back(cvGetReal2D(q_r, 2, 0)); // cameraParameter.push_back(cvGetReal2D(q_r, 3, 0)); // // for (int iFrame = 0; iFrame < vFrame1.size(); iFrame++) // { // CvMat *q = cvCreateMat(4,1,CV_32FC1); // Rotation2Quaternion(vM[iFrame], q); // cameraParameter.push_back(cvGetReal2D(q, 0, 0)); // cameraParameter.push_back(cvGetReal2D(q, 1, 0)); // cameraParameter.push_back(cvGetReal2D(q, 2, 0)); // cameraParameter.push_back(cvGetReal2D(q, 3, 0)); // cvReleaseMat(&q); // // cameraParameter.push_back(cvGetReal2D(vm[iFrame], 0, 0)); // cameraParameter.push_back(cvGetReal2D(vm[iFrame], 1, 0)); // cameraParameter.push_back(cvGetReal2D(vm[iFrame], 2, 0)); // } // // // // cvReleaseMat(&R_r); // cvReleaseMat(&R_1_inv); // cvReleaseMat(&q_r); // // double *dmeasurement = (double *) malloc(measurement.size() * sizeof(double)); // double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double)); // // for (int i = 0; i < cameraParameter.size(); i++) // dCameraParameter[i] = cameraParameter[i]; // for (int i = 0; i < measurement.size(); i++) // dmeasurement[i] = measurement[i]; // // double opt[5]; // opt[0] = 1e-3; // opt[1] = 1e-5; // opt[2] = 1e-5; // opt[3] = 1e-5; // opt[4] = 0; // double info[12]; // // int ret = sba_mot_levmar() // // double *work = (double*)malloc((LM_DIF_WORKSZ(cameraParameter.size(), measurement.size())+cameraParameter.size()*cameraParameter.size())*sizeof(double)); // if(!work) // fprintf(stderr, "memory allocation request failed in main()\n"); // // int ret = dlevmar_dif(ObjectiveOrientationRefinement1, dCameraParameter, dmeasurement, cameraParameter.size(), measurement.size(), // 1e+2, opt, info, work, NULL, &adata); // // PrintSBAInfo(info); // vector<double> vR11, vR12, vR13, vR21, vR22, vR23, vR31, vR32, vR33; // for (int iFrame = 0; iFrame < vFrame1.size(); iFrame++) // { // CvMat *q = cvCreateMat(4,1,CV_32FC1); // CvMat *R = cvCreateMat(3,3,CV_32FC1); // cvSetReal2D(q, 0, 0, dCameraParameter[7*iFrame+0]); // cvSetReal2D(q, 1, 0, dCameraParameter[7*iFrame+1]); // cvSetReal2D(q, 2, 0, dCameraParameter[7*iFrame+2]); // cvSetReal2D(q, 3, 0, dCameraParameter[7*iFrame+3]); // Quaternion2Rotation(q, R); // for (int i = 0; i < 3; i++) // { // for (int j = 0; j < 3; j++) // { // cvSetReal2D(vM[iFrame], i, j, cvGetReal2D(R, i, j)); // } // } // // vR11.push_back(cvGetReal2D(R, 0, 0)); vR12.push_back(cvGetReal2D(R, 0, 1)); vR13.push_back(cvGetReal2D(R, 0, 2)); // vR21.push_back(cvGetReal2D(R, 1, 0)); vR22.push_back(cvGetReal2D(R, 1, 1)); vR23.push_back(cvGetReal2D(R, 1, 2)); // vR31.push_back(cvGetReal2D(R, 2, 0)); vR32.push_back(cvGetReal2D(R, 2, 1)); vR33.push_back(cvGetReal2D(R, 2, 2)); // cvReleaseMat(&q); // cvReleaseMat(&R); // // cvSetReal2D(vm[iFrame], 0, 0, dCameraParameter[7*iFrame+4]); // cvSetReal2D(vm[iFrame], 1, 0, dCameraParameter[7*iFrame+5]); // cvSetReal2D(vm[iFrame], 2, 0, dCameraParameter[7*iFrame+6]); // } // // for (int iFrame_r = 0; iFrame_r < vFrame1_r.size(); iFrame_r++) // { // double R11 = 1; double R12 = 0; double R13 = 0; // double R21 = 0; double R22 = 1; double R23 = 0; // double R31 = 0; double R32 = 0; double R33 = 1; // // for (int iFrame = vFrame1_r[iFrame_r]; iFrame < vFrame2_r[iFrame_r]; iFrame++) // { // R11 = vR11[iFrame]*R11 + vR12[iFrame]*R21 + vR13[iFrame]*R31; // R12 = vR11[iFrame]*R12 + vR12[iFrame]*R22 + vR13[iFrame]*R32; // R13 = vR11[iFrame]*R13 + vR12[iFrame]*R23 + vR13[iFrame]*R33; // // R21 = vR21[iFrame]*R11 + vR22[iFrame]*R21 + vR23[iFrame]*R31; // R22 = vR21[iFrame]*R12 + vR22[iFrame]*R22 + vR23[iFrame]*R32; // R23 = vR21[iFrame]*R13 + vR22[iFrame]*R23 + vR23[iFrame]*R33; // // R31 = vR31[iFrame]*R11 + vR32[iFrame]*R21 + vR33[iFrame]*R31; // R32 = vR31[iFrame]*R12 + vR32[iFrame]*R22 + vR33[iFrame]*R32; // R33 = vR31[iFrame]*R13 + vR32[iFrame]*R23 + vR33[iFrame]*R33; // } // cvSetReal2D(vM_r[iFrame_r], 0, 0, R11); cvSetReal2D(vM_r[iFrame_r], 0, 1, R12); cvSetReal2D(vM_r[iFrame_r], 0, 2, R13); // cvSetReal2D(vM_r[iFrame_r], 1, 0, R21); cvSetReal2D(vM_r[iFrame_r], 1, 1, R22); cvSetReal2D(vM_r[iFrame_r], 1, 2, R23); // cvSetReal2D(vM_r[iFrame_r], 2, 0, R31); cvSetReal2D(vM_r[iFrame_r], 2, 1, R32); cvSetReal2D(vM_r[iFrame_r], 2, 2, R33); // // cvSetReal2D(vm_r[iFrame_r], 0, 0, dCameraParameter[7*vFrame1.size()+3*iFrame_r+0]); // cvSetReal2D(vm_r[iFrame_r], 1, 0, dCameraParameter[7*vFrame1.size()+3*iFrame_r+1]); // cvSetReal2D(vm_r[iFrame_r], 2, 0, dCameraParameter[7*vFrame1.size()+3*iFrame_r+2]); // } // // free(dmeasurement); // free(dCameraParameter); // free(work); //} void DetectPOI(vector<CvMat *> vP, vector<CvMat *> vV, int nSegments, double range, double merging_threshold, vector<double> vBandwidth, vector<CvMat *> &vPOI, double epsilon_cov, int nSegments_cov, vector<CvMat *> &v_a_cov, vector<CvMat *> &v_b_cov, vector<CvMat *> &v_l_cov, vector<double> &vf) { vector<CvMat *> vPOI_temp; vector<vector<double> > vvWeight; for (int iP = 0; iP < vP.size(); iP++) { for (int iSeg = 0; iSeg < nSegments; iSeg++) { double y1, y2, y3; y1 = cvGetReal2D(vP[iP], 0, 0)+(range/(double)nSegments)*(iSeg+1)*cvGetReal2D(vV[iP], 0, 0); y2 = cvGetReal2D(vP[iP], 1, 0)+(range/(double)nSegments)*(iSeg+1)*cvGetReal2D(vV[iP], 1, 0); y3 = cvGetReal2D(vP[iP], 2, 0)+(range/(double)nSegments)*(iSeg+1)*cvGetReal2D(vV[iP], 2, 0); bool isBad = false; int nIter = 0; vector<double> vWeight; vector<double> vWeight_temp; while (1) { double yp1 = y1, yp2 = y2, yp3 = y3; vWeight.clear(); MeanShift_Gaussian_Cone(y1, y2, y3, vP, vV, vBandwidth, vWeight); double normDiff = sqrt((y1-yp1)*(y1-yp1)+(y2-yp2)*(y2-yp2)+(y3-yp3)*(y3-yp3)); if (normDiff < 1e-5) { break; } nIter++; if (nIter > 2000) { isBad = true; break; } } if (isBad) { continue; } double sumw = 0; for (int iw = 0; iw < vWeight.size(); iw++) { sumw += vWeight[iw]; } for (int iw = 0; iw < vWeight.size(); iw++) { vWeight[iw] /= sumw; } vWeight_temp = vWeight; sort(vWeight.begin(), vWeight.end()); if (vWeight[vWeight.size()-2]/vWeight[vWeight.size()-1] > 0.01) { if (vPOI_temp.empty()) { CvMat *poi = cvCreateMat(3,1,CV_32FC1); cvSetReal2D(poi, 0, 0, y1); cvSetReal2D(poi, 1, 0, y2); cvSetReal2D(poi, 2, 0, y3); vPOI_temp.push_back(poi); vvWeight.push_back(vWeight_temp); } else { bool isIn = false; for (int iPoi = 0; iPoi < vPOI_temp.size(); iPoi++) { double c1 = cvGetReal2D(vPOI_temp[iPoi], 0, 0) - y1; double c2 = cvGetReal2D(vPOI_temp[iPoi], 1, 0) - y2; double c3 = cvGetReal2D(vPOI_temp[iPoi], 2, 0) - y3; if (sqrt(c1*c1+c2*c2+c3*c3) < merging_threshold) { isIn = true; break; } } if (!isIn) { CvMat *poi = cvCreateMat(3,1,CV_32FC1); cvSetReal2D(poi, 0, 0, y1); cvSetReal2D(poi, 1, 0, y2); cvSetReal2D(poi, 2, 0, y3); vPOI_temp.push_back(poi); vvWeight.push_back(vWeight_temp); } } } } } for (int iPOI = 0; iPOI < vPOI_temp.size(); iPOI++) { vector<double> v_a, v_b, v_l; bool isGood = POICovariance(vP, vV, vBandwidth, vPOI_temp[iPOI], epsilon_cov, nSegments_cov, v_a, v_b, v_l); if (!isGood) continue; CvMat *a = cvCreateMat(v_a.size(), 1, CV_32FC1); CvMat *b = cvCreateMat(v_b.size(), 1, CV_32FC1); CvMat *l = cvCreateMat(v_b.size(), 1, CV_32FC1); for (int ia = 0; ia < v_a.size(); ia++) { cvSetReal2D(a, ia, 0, v_a[ia]); cvSetReal2D(b, ia, 0, v_b[ia]); cvSetReal2D(l, ia, 0, v_l[ia]); } v_a_cov.push_back(a); v_b_cov.push_back(b); v_l_cov.push_back(l); double f0 = EvaulateDensityFunction(vP, vV, vBandwidth, vPOI_temp[iPOI]); vf.push_back(f0); vPOI.push_back(cvCloneMat(vPOI_temp[iPOI])); //CvMat *U = cvCreateMat(3,3,CV_32FC1); //CvMat *Radius = cvCreateMat(3,1, CV_32FC1); //PrintMat(vPOI[iPOI]); //POICovariance(vP, vV, vvWeight[iPOI], U, Radius); //vU.push_back(U); //vRadius.push_back(Radius); } for (int i = 0; i < vPOI.size(); i++) { cvReleaseMat(&vPOI_temp[i]); } vPOI_temp.clear(); } void DetectPOI(vector<CvMat *> vP, vector<CvMat *> vV, int nSegments, double range, double merging_threshold, vector<double> vBandwidth, vector<CvMat *> &vPOI, double epsilon_cov, int nSegments_cov, vector<CvMat *> &v_a_cov, vector<CvMat *> &v_b_cov, vector<CvMat *> &v_l_cov, vector<double> &vf, vector<vector<CvMat *> > &vvMeanTrajectory) { vector<CvMat *> vPOI_temp; vector<vector<double> > vvWeight; for (int iP = 0; iP < vP.size(); iP++) { for (int iSeg = 0; iSeg < nSegments; iSeg++) { double y1, y2, y3; y1 = cvGetReal2D(vP[iP], 0, 0)+(range/(double)nSegments)*(iSeg+1)*cvGetReal2D(vV[iP], 0, 0); y2 = cvGetReal2D(vP[iP], 1, 0)+(range/(double)nSegments)*(iSeg+1)*cvGetReal2D(vV[iP], 1, 0); y3 = cvGetReal2D(vP[iP], 2, 0)+(range/(double)nSegments)*(iSeg+1)*cvGetReal2D(vV[iP], 2, 0); bool isBad = false; int nIter = 0; vector<double> vWeight; vector<double> vWeight_temp; vector<double> mean_x; vector<double> mean_y; vector<double> mean_z; while (1) { mean_x.push_back(y1); mean_y.push_back(y2); mean_z.push_back(y3); double yp1 = y1, yp2 = y2, yp3 = y3; vWeight.clear(); MeanShift_Gaussian_Cone(y1, y2, y3, vP, vV, vBandwidth, vWeight); double normDiff = sqrt((y1-yp1)*(y1-yp1)+(y2-yp2)*(y2-yp2)+(y3-yp3)*(y3-yp3)); if (normDiff < 1e-5) { break; } nIter++; if (nIter > 2000) { isBad = true; break; } } if (isBad) { continue; } double sumw = 0; for (int iw = 0; iw < vWeight.size(); iw++) { sumw += vWeight[iw]; } for (int iw = 0; iw < vWeight.size(); iw++) { vWeight[iw] /= sumw; } vWeight_temp = vWeight; sort(vWeight.begin(), vWeight.end()); if (vWeight[vWeight.size()-2]/vWeight[vWeight.size()-1] > 0.1) { vector<CvMat *> vMean; for (int ii = 0; ii < mean_x.size(); ii++) { CvMat *mm = cvCreateMat(3,1,CV_32FC1); cvSetReal2D(mm, 0, 0, mean_x[ii]); cvSetReal2D(mm, 1, 0, mean_y[ii]); cvSetReal2D(mm, 2, 0, mean_z[ii]); vMean.push_back(mm); } vvMeanTrajectory.push_back(vMean); if (vPOI_temp.empty()) { CvMat *poi = cvCreateMat(3,1,CV_32FC1); cvSetReal2D(poi, 0, 0, y1); cvSetReal2D(poi, 1, 0, y2); cvSetReal2D(poi, 2, 0, y3); vPOI_temp.push_back(poi); vvWeight.push_back(vWeight_temp); } else { bool isIn = false; for (int iPoi = 0; iPoi < vPOI_temp.size(); iPoi++) { double c1 = cvGetReal2D(vPOI_temp[iPoi], 0, 0) - y1; double c2 = cvGetReal2D(vPOI_temp[iPoi], 1, 0) - y2; double c3 = cvGetReal2D(vPOI_temp[iPoi], 2, 0) - y3; if (sqrt(c1*c1+c2*c2+c3*c3) < merging_threshold) { isIn = true; break; } } if (!isIn) { CvMat *poi = cvCreateMat(3,1,CV_32FC1); cvSetReal2D(poi, 0, 0, y1); cvSetReal2D(poi, 1, 0, y2); cvSetReal2D(poi, 2, 0, y3); vPOI_temp.push_back(poi); vvWeight.push_back(vWeight_temp); } } } } } for (int iPOI = 0; iPOI < vPOI_temp.size(); iPOI++) { vector<double> v_a, v_b, v_l; bool isGood = POICovariance(vP, vV, vBandwidth, vPOI_temp[iPOI], epsilon_cov, nSegments_cov, v_a, v_b, v_l); if (!isGood) { vector<vector<CvMat *> > vvMeanTraj_temp; for (int iTraj = 0; iTraj < vvMeanTrajectory.size(); iTraj++) { double traj_x = cvGetReal2D(vvMeanTrajectory[iTraj][vvMeanTrajectory[iTraj].size()-1], 0, 0); double traj_y = cvGetReal2D(vvMeanTrajectory[iTraj][vvMeanTrajectory[iTraj].size()-1], 1, 0); double traj_z = cvGetReal2D(vvMeanTrajectory[iTraj][vvMeanTrajectory[iTraj].size()-1], 2, 0); double error = sqrt((traj_x-cvGetReal2D(vPOI_temp[iPOI], 0, 0))*(traj_x-cvGetReal2D(vPOI_temp[iPOI], 0, 0))+ (traj_y-cvGetReal2D(vPOI_temp[iPOI], 1, 0))*(traj_y-cvGetReal2D(vPOI_temp[iPOI], 1, 0))+ (traj_z-cvGetReal2D(vPOI_temp[iPOI], 2, 0))*(traj_z-cvGetReal2D(vPOI_temp[iPOI], 2, 0))); if (error < 1e-3) continue; vvMeanTraj_temp.push_back(vvMeanTrajectory[iTraj]); } vvMeanTrajectory = vvMeanTraj_temp; continue; } CvMat *a = cvCreateMat(v_a.size(), 1, CV_32FC1); CvMat *b = cvCreateMat(v_b.size(), 1, CV_32FC1); CvMat *l = cvCreateMat(v_b.size(), 1, CV_32FC1); for (int ia = 0; ia < v_a.size(); ia++) { cvSetReal2D(a, ia, 0, v_a[ia]); cvSetReal2D(b, ia, 0, v_b[ia]); cvSetReal2D(l, ia, 0, v_l[ia]); } v_a_cov.push_back(a); v_b_cov.push_back(b); v_l_cov.push_back(l); double f0 = EvaulateDensityFunction(vP, vV, vBandwidth, vPOI_temp[iPOI]); vf.push_back(f0); vPOI.push_back(cvCloneMat(vPOI_temp[iPOI])); //CvMat *U = cvCreateMat(3,3,CV_32FC1); //CvMat *Radius = cvCreateMat(3,1, CV_32FC1); //PrintMat(vPOI[iPOI]); //POICovariance(vP, vV, vvWeight[iPOI], U, Radius); //vU.push_back(U); //vRadius.push_back(Radius); } for (int i = 0; i < vPOI.size(); i++) { cvReleaseMat(&vPOI_temp[i]); } vPOI_temp.clear(); } bool POICovariance(vector<CvMat *> vP, vector<CvMat *> vV, vector<double> vBandwidth, CvMat *poi, double epsilon, int nSegments, vector<double> &v_a, vector<double> &v_b, vector<double> &v_l) { double f0 = EvaulateDensityFunction(vP, vV, vBandwidth, poi); double phi_step = 2*PI/nSegments; double theta_step = PI/(nSegments/2); bool isGood = true; for (int iphi = 0; iphi < nSegments; iphi++) { for (int itheta = 0; itheta < nSegments/2+1; itheta++) { CvMat *v = cvCreateMat(3,1,CV_32FC1); cvSetReal2D(v, 0, 0, cos(iphi*phi_step)*sin(itheta*theta_step)); cvSetReal2D(v, 1, 0, sin(iphi*phi_step)*sin(itheta*theta_step)); cvSetReal2D(v, 2, 0, cos(itheta*theta_step)); CvMat *v_temp = cvCreateMat(3,1,CV_32FC1); CvMat *x = cvCreateMat(3,1,CV_32FC1); ScalarMul(v, epsilon, v_temp); cvAdd(poi, v_temp, x); double f = EvaulateDensityFunction(vP, vV, vBandwidth, x); if ((f0-f)/(-epsilon) > -5e-2) { isGood = false; v_a.push_back(-5e-2); } else v_a.push_back((f0-f)/(-epsilon)); v_b.push_back(f0); double alpha = 0; while (1) { alpha = alpha + 0.1; ScalarMul(v, epsilon+alpha, v_temp); cvAdd(poi, v_temp, x); f = EvaulateDensityFunction(vP, vV, vBandwidth, x); double y = (f0-f)/(-epsilon) * (epsilon+alpha) + f0; if (abs(f-y) > 1e+0) { v_l.push_back(alpha+epsilon); break; } } cvReleaseMat(&v); cvReleaseMat(&x); } } return isGood; } double EvaulateDensityFunction(vector<CvMat *> vP, vector<CvMat *> vV, vector<double> vBandwidth, CvMat *x) { double f = 0; for (int ip = 0; ip < vP.size(); ip++) { double norm_v = sqrt(cvGetReal2D(vV[ip], 0, 0)*cvGetReal2D(vV[ip], 0, 0)+cvGetReal2D(vV[ip], 1, 0)*cvGetReal2D(vV[ip], 1, 0)+cvGetReal2D(vV[ip], 2, 0)*cvGetReal2D(vV[ip], 2, 0)); ScalarMul(vV[ip], 1/norm_v, vV[ip]); CvMat *xmp = cvCreateMat(3,1,CV_32FC1); cvSub(x, vP[ip], xmp); CvMat *dot_product = cvCreateMat(1,1,CV_32FC1); CvMat *v_t = cvCreateMat(1,3,CV_32FC1); cvTranspose(vV[ip], v_t); cvMatMul(v_t, xmp, dot_product); CvMat *dx = cvCreateMat(3,1,CV_32FC1); CvMat *dot_ray = cvCreateMat(3,1,CV_32FC1); ScalarMul(vV[ip], cvGetReal2D(dot_product, 0, 0), dot_ray); cvSub(xmp, dot_ray, dx); if (cvGetReal2D(dot_product, 0, 0) > 0) { double dist1 = sqrt(cvGetReal2D(dx, 0, 0)*cvGetReal2D(dx, 0, 0)+cvGetReal2D(dx, 1, 0)*cvGetReal2D(dx, 1, 0)+cvGetReal2D(dx, 2, 0)*cvGetReal2D(dx, 2, 0)); double dist2 = cvGetReal2D(dot_product, 0, 0); f+= 1/vBandwidth[ip] * exp(-(dist1/dist2)*(dist1/dist2)/2/vBandwidth[ip]/vBandwidth[ip]); } cvReleaseMat(&xmp); cvReleaseMat(&dot_product); cvReleaseMat(&v_t); cvReleaseMat(&dx); cvReleaseMat(&dot_ray); } f /= vP.size(); return f; } void POICovariance(vector<CvMat *> vP, vector<CvMat *> vV, vector<double> vWeight, CvMat *U, CvMat *Radius) { CvMat *A = cvCreateMat(3*vP.size(), 3, CV_32FC1); CvMat *b = cvCreateMat(3*vP.size(), 1, CV_32FC1); for (int iCamera = 0; iCamera < vP.size(); iCamera++) { CvMat *Ai = cvCreateMat(3,3, CV_32FC1); CvMat *bi = cvCreateMat(3,1, CV_32FC1); Vec2Skew(vV[iCamera], Ai); ScalarMul(Ai, vWeight[iCamera], Ai); cvMatMul(Ai, vP[iCamera], bi); SetSubMat(A, 3*iCamera, 0, Ai); SetSubMat(b, 3*iCamera, 0, bi); cvReleaseMat(&Ai); cvReleaseMat(&bi); } double meanb = 0; for (int ib = 0; ib < b->rows; ib++) { meanb += cvGetReal2D(b, ib, 0); } meanb /= b->rows; double varianceb = 0; for (int ib = 0; ib < b->rows; ib++) { varianceb += (cvGetReal2D(b, ib, 0)-meanb)*(cvGetReal2D(b, ib, 0)-meanb); } varianceb /= b->rows; CvMat *At = cvCreateMat(A->cols, A->rows, CV_32FC1); cvTranspose(A, At); CvMat *Q = cvCreateMat(3,3,CV_32FC1); cvMatMul(At, A, Q); cvInvert(Q, Q); ScalarMul(Q, varianceb, Q); CvMat *D = cvCreateMat(3,3,CV_32FC1); CvMat *V = cvCreateMat(3,3,CV_32FC1); cvSVD(Q, D, U, V); cvSetReal2D(Radius, 0, 0, sqrt(cvGetReal2D(D, 0, 0))); cvSetReal2D(Radius, 1, 0, sqrt(cvGetReal2D(D, 1, 1))); cvSetReal2D(Radius, 2, 0, sqrt(cvGetReal2D(D, 2, 2))); cvReleaseMat(&D); cvReleaseMat(&V); cvReleaseMat(&Q); cvReleaseMat(&A); cvReleaseMat(&At); cvReleaseMat(&b); } void MeanShift_Gaussian_Cone(double &y1, double &y2, double &y3, vector<CvMat *> vP, vector<CvMat *> vV, vector<double> vBandwidth, vector<double> &vWeight) { double sum1 = 0, sum2 = 0, sum3 = 0; double normalization = 0; for (int iP = 0; iP < vP.size(); iP++) { double dist, gradient1, gradient2, gradient3; DistanceBetweenConeAndPoint(cvGetReal2D(vP[iP], 0, 0), cvGetReal2D(vP[iP], 1, 0), cvGetReal2D(vP[iP], 2, 0), cvGetReal2D(vV[iP], 0, 0), cvGetReal2D(vV[iP], 1, 0), cvGetReal2D(vV[iP], 2, 0), y1, y2, y3, dist); double xmp1 = y1-cvGetReal2D(vP[iP], 0, 0); double xmp2 = y2-cvGetReal2D(vP[iP], 1, 0); double xmp3 = y3-cvGetReal2D(vP[iP], 2, 0); double v1 = cvGetReal2D(vV[iP], 0, 0); double v2 = cvGetReal2D(vV[iP], 1, 0); double v3 = cvGetReal2D(vV[iP], 2, 0); double v_norm = sqrt(v1*v1+v2*v2+v3*v3); v1 /= v_norm; v2 /= v_norm; v3 /= v_norm; double vxmp1 = v1*xmp1; double vxmp2 = v2*xmp2; double vxmp3 = v3*xmp3; double vxmp = vxmp1+vxmp2+vxmp3; double x_tilde1 = cvGetReal2D(vP[iP], 0, 0) + (vxmp + dist*dist*vxmp)*v1; double x_tilde2 = cvGetReal2D(vP[iP], 1, 0) + (vxmp + dist*dist*vxmp)*v2; double x_tilde3 = cvGetReal2D(vP[iP], 2, 0) + (vxmp + dist*dist*vxmp)*v3; double weight = exp(-dist*dist/vBandwidth[iP]/vBandwidth[iP]/2)/(vBandwidth[iP]*vBandwidth[iP]*vBandwidth[iP]*vxmp*vxmp); sum1 += weight * x_tilde1; sum2 += weight * x_tilde2; sum3 += weight * x_tilde3; normalization += weight; vWeight.push_back(weight); } y1 = sum1/normalization; y2 = sum2/normalization; y3 = sum3/normalization; } void MeanShift_Gaussian_Ray(double &y1, double &y2, double &y3, vector<CvMat *> vP, vector<CvMat *> vV, double bandwidth, vector<double> &vWeight) { double sum1 = 0, sum2 = 0, sum3 = 0; double normalization = 0; for (int iP = 0; iP < vP.size(); iP++) { double dist, gradient1, gradient2, gradient3; DistanceBetweenRayAndPoint(cvGetReal2D(vP[iP], 0, 0), cvGetReal2D(vP[iP], 1, 0), cvGetReal2D(vP[iP], 2, 0), cvGetReal2D(vV[iP], 0, 0), cvGetReal2D(vV[iP], 1, 0), cvGetReal2D(vV[iP], 2, 0), y1, y2, y3, dist, gradient1, gradient2, gradient3); double dir1, dir2, dir3; dir1 = y1-cvGetReal2D(vP[iP], 0, 0); dir2 = y2-cvGetReal2D(vP[iP], 1, 0); dir3 = y3-cvGetReal2D(vP[iP], 2, 0); double dot_product = dir1*cvGetReal2D(vV[iP], 0, 0)+dir2*cvGetReal2D(vV[iP], 1, 0)+dir3*cvGetReal2D(vV[iP], 2, 0); if (dot_product < 0) { dist = 1e+6; } sum1 += gradient1*exp(-dist*dist/bandwidth/bandwidth); sum2 += gradient2*exp(-dist*dist/bandwidth/bandwidth); sum3 += gradient3*exp(-dist*dist/bandwidth/bandwidth); normalization += exp(-dist*dist/bandwidth/bandwidth); vWeight.push_back(exp(-dist*dist/bandwidth/bandwidth)); } y1 = sum1/normalization; y2 = sum2/normalization; y3 = sum3/normalization; } void DistanceBetweenRayAndPoint(double p1, double p2, double p3, double v1, double v2, double v3, double x1, double x2, double x3, double &d, double &g1, double &g2, double &g3) { double v_norm = sqrt(v1*v1+v2*v2+v3*v3); v1 /= v_norm; v2 /= v_norm; v3 /= v_norm; double xmp1 = x1-p1; double xmp2 = x2-p2; double xmp3 = x3-p3; double xmp_dot_v1 = xmp1*v1; double xmp_dot_v2 = xmp1*v2; double xmp_dot_v3 = xmp1*v3; double d1 = xmp1-xmp_dot_v1*v1; double d2 = xmp2-xmp_dot_v2*v2; double d3 = xmp3-xmp_dot_v3*v3; d = sqrt(d1*d1+d2*d2+d3*d3); g1 = p1 + xmp_dot_v1*v1; g2 = p2 + xmp_dot_v2*v2; g3 = p3 + xmp_dot_v3*v3; } void DistanceBetweenConeAndPoint(double p1, double p2, double p3, double v1, double v2, double v3, double x1, double x2, double x3, double &d) { double v_norm = sqrt(v1*v1+v2*v2+v3*v3); v1 /= v_norm; v2 /= v_norm; v3 /= v_norm; double xmp1 = x1-p1; double xmp2 = x2-p2; double xmp3 = x3-p3; double xmp_dot_v1 = xmp1*v1; double xmp_dot_v2 = xmp2*v2; double xmp_dot_v3 = xmp3*v3; double direction = xmp_dot_v1+xmp_dot_v2+xmp_dot_v3; if (direction > 0) { double upper1 = xmp1 - direction*v1; double upper2 = xmp2 - direction*v2; double upper3 = xmp3 - direction*v3; d = sqrt(upper1*upper1+upper2*upper2+upper3*upper3)/direction; } else { d = 1e+6; } }
[ "francis9012@gmail.com" ]
francis9012@gmail.com
8788db759d2467f2e5ce1f3747107a50c10284ea
c102d77e7e363d043e017360d329c93b9285a6be
/Sources/Samples/AI/UnitPathManager.h
4c85b601bbdd834052649cd9ee5cd19276a8484b
[ "MIT" ]
permissive
jdelezenne/Sonata
b7b1faee54ea9dbd273eab53a7dedbf106373110
fb1b1b64a78874a0ab2809995be4b6f14f9e4d56
refs/heads/master
2020-07-15T22:32:47.094973
2019-09-01T11:07:03
2019-09-01T11:07:03
205,662,360
4
0
null
null
null
null
UTF-8
C++
false
false
3,466
h
/*============================================================================= UnitPathManager.h Project: Sonata Engine Copyright �by7 Julien Delezenne =============================================================================*/ #ifndef _SE_UNITPATHMANAGER_H_ #define _SE_UNITPATHMANAGER_H_ #include "Common.h" #include "World.h" extern int8 TileUnitCosts[TileType_Count][UnitType_Count]; enum PathfinderType { PathfinderType_AStar }; class UnitPathMap : public AI::AStarPathfinderMap { public: UnitPathMap(); virtual int GetNeighbourCount(AI::PathfinderNode* node); virtual AI::PathfinderNodeID GetNeighbour(AI::PathfinderNode* node, int neighbour); virtual void SetAStarFlags(AI::PathfinderNodeID node, uint32 flags); virtual uint32 GetAStarFlags(AI::PathfinderNodeID node); virtual void InitializeNeighbour(AI::AStarPathfinderNode* parent, AI::AStarPathfinderNode* child); AI::PathfinderNodeID CellToPathfinderNodeID(Cell* cell); Cell* PathfinderNodeIDToCell(AI::PathfinderNodeID node); void Initialize(Map* map); Map* GetMap() const { return _Map; } protected: Map* _Map; }; class UnitPathGoal : public AI::AStarPathfinderGoal { public: UnitPathGoal(); virtual void SetDestinationNode(AI::PathfinderNodeID node); virtual bool IsNodeValid(AI::PathfinderNodeID node); virtual real32 GetHeuristic(AI::AStarPathfinderNode* node); virtual real32 GetCost(AI::AStarPathfinderNode* nodeA, AI::AStarPathfinderNode* nodeB); virtual bool IsSearchFinished(AI::AStarPathfinderNode* node); void Initialize(UnitPathMap* map, Unit* unit); protected: AI::PathfinderNodeID _DestinationNode; UnitPathMap* _Map; Unit* _Unit; }; template <class T> class RefComparer : public IComparer<T> { public: virtual int Compare(const T& x, const T& y) const { if (*x < *y) return -1; else if (*x > *y) return 1; else return 0; } }; class PriorityQueueStorage : public AI::AStarPathfinderStorage { public: PriorityQueueStorage(); virtual ~PriorityQueueStorage(); virtual void Reset(); virtual void AddToOpenList(AI::AStarPathfinderNode* node, AI::AStarPathfinderMap* map); virtual void AddToClosedList(AI::AStarPathfinderNode* node, AI::AStarPathfinderMap* map); virtual void RemoveFromOpenList(AI::AStarPathfinderNode* node); virtual void RemoveFromClosedList(AI::AStarPathfinderNode* node); virtual AI::AStarPathfinderNode* FindInOpenList(AI::PathfinderNodeID node); virtual AI::AStarPathfinderNode* FindInClosedList(AI::PathfinderNodeID node); virtual AI::AStarPathfinderNode* RemoveBestOpenNode(); protected: typedef PriorityQueue< AI::AStarPathfinderNode*, RefComparer<AI::AStarPathfinderNode*> > OpenList; OpenList _OpenList; typedef Array<AI::AStarPathfinderNode*> ClosedList; ClosedList _ClosedList; }; class UnitPathStorage : public PriorityQueueStorage { public: UnitPathStorage(); virtual AI::AStarPathfinderNode* CreateNode(AI::PathfinderNodeID node); virtual void DestroyNode(AI::AStarPathfinderNode* node); }; class UnitPathManager { public: UnitPathManager(); virtual ~UnitPathManager(); void Initialize(PathfinderType type); bool HasPath(Unit* unit, Cell* source, Cell* destination); bool FindPath(Unit* unit, Cell* source, Cell* destination, UnitPath* path); protected: AI::PathfinderNode* FindPath(Unit* unit, Cell* source, Cell* destination); protected: AI::AStarPathfinder* _Pathfinder; PriorityQueueStorage* _Storage; UnitPathGoal* _Goal; UnitPathMap* _Map; }; #endif
[ "julien.delezenne@gmail.com" ]
julien.delezenne@gmail.com
2afdee78415e6b3b8019099f55955075a2ac3d2b
9a3558d9cc1070d75b6972abaf12339f3c43b672
/libraries/helper/helper.hpp
8dfa3d61682d662d17355285d1b50d766492c757
[]
no_license
kurokis/Ublox
32888bb69d5eeebc8eab9d6e47997c5d825d1e35
a434a513ba68d25e7badce022e73b77ca3e2f2a3
refs/heads/master
2021-01-21T12:30:40.132612
2017-09-03T11:23:12
2017-09-03T11:23:12
102,074,190
0
0
null
null
null
null
UTF-8
C++
false
false
845
hpp
// // helper.hpp // GPS_READER // // Created by blue-i on 01/09/2017. // Copyright © 2017 blue-i. All rights reserved. // #ifndef helper_hpp #define helper_hpp #include <stdio.h> #include "string.h" #include <iostream> #include <stdio.h> #include <unistd.h> //Used for UART #include <fcntl.h> //Used for UART #include <termios.h> //Used for UART #include <sys/ioctl.h> //Used for UART #include <sys/stat.h> //Used for fifo #include <poll.h> //Pollin() #define UBLOX_INITIAL_BAUD B9600 #define UBLOX_OPERATING_BAUD B57600 #define GPS_PORT "/dev/ttyUSB_Ublox" void UART_Init(int b); void UBloxTxBuffer(const char b[], int t); void UART_Close(); void GPS_Init(void); bool file_exist(const std::string& name); bool pollin(void); void Reader_sender(void); void run(void); #endif /* helper_hpp */
[ "kurokis@users.noreply.github.com" ]
kurokis@users.noreply.github.com
8a96e354acf08b5427cf3791a514286b61b32365
ddbc8b916e028cf70467928d3be17506713baeff
/src/Setup/unzip.cpp
c2b062c3bb714c756f317e2995e1129180774b39
[ "MIT" ]
permissive
Squirrel/Squirrel.Windows
e7687f81ae08ebf6f4b6005ed8394f78f6c9c1ad
5e44cb4001a7d48f53ee524a2d90b3f5700a9920
refs/heads/develop
2023-09-03T23:06:14.600642
2023-08-01T17:34:34
2023-08-01T17:34:34
22,338,518
7,243
1,336
MIT
2023-08-01T17:34:36
2014-07-28T10:10:39
C++
UTF-8
C++
false
false
145,049
cpp
#include "stdafx.h" #include "unzip.h" // THIS FILE is almost entirely based upon code by Jean-loup Gailly // and Mark Adler. It has been modified by Lucian Wischik. // The modifications were: incorporate the bugfixes of 1.1.4, allow // unzipping to/from handles/pipes/files/memory, encryption, unicode, // a windowsish api, and putting everything into a single .cpp file. // The original code may be found at http://www.gzip.org/zlib/ // The original copyright text follows. // // // // zlib.h -- interface of the 'zlib' general purpose compression library // version 1.1.3, July 9th, 1998 // // Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // // Jean-loup Gailly Mark Adler // jloup@gzip.org madler@alumni.caltech.edu // // // The data format used by the zlib library is described by RFCs (Request for // Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt // (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). // // // The 'zlib' compression library provides in-memory compression and // decompression functions, including integrity checks of the uncompressed // data. This version of the library supports only one compression method // (deflation) but other algorithms will be added later and will have the same // stream interface. // // Compression can be done in a single step if the buffers are large // enough (for example if an input file is mmap'ed), or can be done by // repeated calls of the compression function. In the latter case, the // application must provide more input and/or consume the output // (providing more output space) before each call. // // The library also supports reading and writing files in gzip (.gz) format // with an interface similar to that of stdio. // // The library does not install any signal handler. The decoder checks // the consistency of the compressed data, so the library should never // crash even in case of corrupted input. // // for more info about .ZIP format, see ftp://ftp.cdrom.com/pub/infozip/doc/appnote-970311-iz.zip // PkWare has also a specification at ftp://ftp.pkware.com/probdesc.zip #define ZIP_HANDLE 1 #define ZIP_FILENAME 2 #define ZIP_MEMORY 3 #define zmalloc(len) malloc(len) #define zfree(p) free(p) /* void *zmalloc(unsigned int len) { char *buf = new char[len+32]; for (int i=0; i<16; i++) { buf[i]=i; buf[len+31-i]=i; } *((unsigned int*)buf) = len; char c[1000]; wsprintf(c,"malloc 0x%lx - %lu",buf+16,len); OutputDebugString(c); return buf+16; } void zfree(void *buf) { char c[1000]; wsprintf(c,"free 0x%lx",buf); OutputDebugString(c); char *p = ((char*)buf)-16; unsigned int len = *((unsigned int*)p); bool blown=false; for (int i=0; i<16; i++) { char lo = p[i]; char hi = p[len+31-i]; if (hi!=i || (lo!=i && i>4)) blown=true; } if (blown) { OutputDebugString("BLOWN!!!"); } delete[] p; } */ typedef struct tm_unz_s { unsigned int tm_sec; // seconds after the minute - [0,59] unsigned int tm_min; // minutes after the hour - [0,59] unsigned int tm_hour; // hours since midnight - [0,23] unsigned int tm_mday; // day of the month - [1,31] unsigned int tm_mon; // months since January - [0,11] unsigned int tm_year; // years - [1980..2044] } tm_unz; // unz_global_info structure contain global data about the ZIPfile typedef struct unz_global_info_s { unsigned long number_entry; // total number of entries in the central dir on this disk unsigned long size_comment; // size of the global comment of the zipfile } unz_global_info; // unz_file_info contain information about a file in the zipfile typedef struct unz_file_info_s { unsigned long version; // version made by 2 bytes unsigned long version_needed; // version needed to extract 2 bytes unsigned long flag; // general purpose bit flag 2 bytes unsigned long compression_method; // compression method 2 bytes unsigned long dosDate; // last mod file date in Dos fmt 4 bytes unsigned long crc; // crc-32 4 bytes unsigned long compressed_size; // compressed size 4 bytes unsigned long uncompressed_size; // uncompressed size 4 bytes unsigned long size_filename; // filename length 2 bytes unsigned long size_file_extra; // extra field length 2 bytes unsigned long size_file_comment; // file comment length 2 bytes unsigned long disk_num_start; // disk number start 2 bytes unsigned long internal_fa; // internal file attributes 2 bytes unsigned long external_fa; // external file attributes 4 bytes tm_unz tmu_date; } unz_file_info; #define UNZ_OK (0) #define UNZ_END_OF_LIST_OF_FILE (-100) #define UNZ_ERRNO (Z_ERRNO) #define UNZ_EOF (0) #define UNZ_PARAMERROR (-102) #define UNZ_BADZIPFILE (-103) #define UNZ_INTERNALERROR (-104) #define UNZ_CRCERROR (-105) #define UNZ_PASSWORD (-106) #define ZLIB_VERSION "1.1.3" // Allowed flush values; see deflate() for details #define Z_NO_FLUSH 0 #define Z_SYNC_FLUSH 2 #define Z_FULL_FLUSH 3 #define Z_FINISH 4 // compression levels #define Z_NO_COMPRESSION 0 #define Z_BEST_SPEED 1 #define Z_BEST_COMPRESSION 9 #define Z_DEFAULT_COMPRESSION (-1) // compression strategy; see deflateInit2() for details #define Z_FILTERED 1 #define Z_HUFFMAN_ONLY 2 #define Z_DEFAULT_STRATEGY 0 // Possible values of the data_type field #define Z_BINARY 0 #define Z_ASCII 1 #define Z_UNKNOWN 2 // The deflate compression method (the only one supported in this version) #define Z_DEFLATED 8 // for initializing zalloc, zfree, opaque #define Z_NULL 0 // case sensitivity when searching for filenames #define CASE_SENSITIVE 1 #define CASE_INSENSITIVE 2 // Return codes for the compression/decompression functions. Negative // values are errors, positive values are used for special but normal events. #define Z_OK 0 #define Z_STREAM_END 1 #define Z_NEED_DICT 2 #define Z_ERRNO (-1) #define Z_STREAM_ERROR (-2) #define Z_DATA_ERROR (-3) #define Z_MEM_ERROR (-4) #define Z_BUF_ERROR (-5) #define Z_VERSION_ERROR (-6) // Basic data types typedef unsigned char Byte; // 8 bits typedef unsigned int uInt; // 16 bits or more typedef unsigned long uLong; // 32 bits or more typedef void *voidpf; typedef void *voidp; typedef long z_off_t; typedef voidpf (*alloc_func) (voidpf opaque, uInt items, uInt size); typedef void (*free_func) (voidpf opaque, voidpf address); struct internal_state; typedef struct z_stream_s { Byte *next_in; // next input byte uInt avail_in; // number of bytes available at next_in uLong total_in; // total nb of input bytes read so far Byte *next_out; // next output byte should be put there uInt avail_out; // remaining free space at next_out uLong total_out; // total nb of bytes output so far char *msg; // last error message, NULL if no error struct internal_state *state; // not visible by applications alloc_func zalloc; // used to allocate the internal state free_func zfree; // used to free the internal state voidpf opaque; // private data object passed to zalloc and zfree int data_type; // best guess about the data type: ascii or binary uLong adler; // adler32 value of the uncompressed data uLong reserved; // reserved for future use } z_stream; typedef z_stream *z_streamp; // The application must update next_in and avail_in when avail_in has // dropped to zero. It must update next_out and avail_out when avail_out // has dropped to zero. The application must initialize zalloc, zfree and // opaque before calling the init function. All other fields are set by the // compression library and must not be updated by the application. // // The opaque value provided by the application will be passed as the first // parameter for calls of zalloc and zfree. This can be useful for custom // memory management. The compression library attaches no meaning to the // opaque value. // // zalloc must return Z_NULL if there is not enough memory for the object. // If zlib is used in a multi-threaded application, zalloc and zfree must be // thread safe. // // The fields total_in and total_out can be used for statistics or // progress reports. After compression, total_in holds the total size of // the uncompressed data and may be saved for use in the decompressor // (particularly if the decompressor wants to decompress everything in // a single step). // // basic functions const char *zlibVersion (); // The application can compare zlibVersion and ZLIB_VERSION for consistency. // If the first character differs, the library code actually used is // not compatible with the zlib.h header file used by the application. // This check is automatically made by inflateInit. int inflate (z_streamp strm, int flush); // // inflate decompresses as much data as possible, and stops when the input // buffer becomes empty or the output buffer becomes full. It may some // introduce some output latency (reading input without producing any output) // except when forced to flush. // // The detailed semantics are as follows. inflate performs one or both of the // following actions: // // - Decompress more input starting at next_in and update next_in and avail_in // accordingly. If not all input can be processed (because there is not // enough room in the output buffer), next_in is updated and processing // will resume at this point for the next call of inflate(). // // - Provide more output starting at next_out and update next_out and avail_out // accordingly. inflate() provides as much output as possible, until there // is no more input data or no more space in the output buffer (see below // about the flush parameter). // // Before the call of inflate(), the application should ensure that at least // one of the actions is possible, by providing more input and/or consuming // more output, and updating the next_* and avail_* values accordingly. // The application can consume the uncompressed output when it wants, for // example when the output buffer is full (avail_out == 0), or after each // call of inflate(). If inflate returns Z_OK and with zero avail_out, it // must be called again after making room in the output buffer because there // might be more output pending. // // If the parameter flush is set to Z_SYNC_FLUSH, inflate flushes as much // output as possible to the output buffer. The flushing behavior of inflate is // not specified for values of the flush parameter other than Z_SYNC_FLUSH // and Z_FINISH, but the current implementation actually flushes as much output // as possible anyway. // // inflate() should normally be called until it returns Z_STREAM_END or an // error. However if all decompression is to be performed in a single step // (a single call of inflate), the parameter flush should be set to // Z_FINISH. In this case all pending input is processed and all pending // output is flushed; avail_out must be large enough to hold all the // uncompressed data. (The size of the uncompressed data may have been saved // by the compressor for this purpose.) The next operation on this stream must // be inflateEnd to deallocate the decompression state. The use of Z_FINISH // is never required, but can be used to inform inflate that a faster routine // may be used for the single inflate() call. // // If a preset dictionary is needed at this point (see inflateSetDictionary // below), inflate sets strm-adler to the adler32 checksum of the // dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise // it sets strm->adler to the adler32 checksum of all output produced // so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or // an error code as described below. At the end of the stream, inflate() // checks that its computed adler32 checksum is equal to that saved by the // compressor and returns Z_STREAM_END only if the checksum is correct. // // inflate() returns Z_OK if some progress has been made (more input processed // or more output produced), Z_STREAM_END if the end of the compressed data has // been reached and all uncompressed output has been produced, Z_NEED_DICT if a // preset dictionary is needed at this point, Z_DATA_ERROR if the input data was // corrupted (input stream not conforming to the zlib format or incorrect // adler32 checksum), Z_STREAM_ERROR if the stream structure was inconsistent // (for example if next_in or next_out was NULL), Z_MEM_ERROR if there was not // enough memory, Z_BUF_ERROR if no progress is possible or if there was not // enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR // case, the application may then call inflateSync to look for a good // compression block. // int inflateEnd (z_streamp strm); // // All dynamically allocated data structures for this stream are freed. // This function discards any unprocessed input and does not flush any // pending output. // // inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state // was inconsistent. In the error case, msg may be set but then points to a // static string (which must not be deallocated). // Advanced functions // The following functions are needed only in some special applications. int inflateSetDictionary (z_streamp strm, const Byte *dictionary, uInt dictLength); // // Initializes the decompression dictionary from the given uncompressed byte // sequence. This function must be called immediately after a call of inflate // if this call returned Z_NEED_DICT. The dictionary chosen by the compressor // can be determined from the Adler32 value returned by this call of // inflate. The compressor and decompressor must use exactly the same // dictionary. // // inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a // parameter is invalid (such as NULL dictionary) or the stream state is // inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the // expected one (incorrect Adler32 value). inflateSetDictionary does not // perform any decompression: this will be done by subsequent calls of // inflate(). int inflateSync (z_streamp strm); // // Skips invalid compressed data until a full flush point can be found, or until all // available input is skipped. No output is provided. // // inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR // if no more input was provided, Z_DATA_ERROR if no flush point has been found, // or Z_STREAM_ERROR if the stream structure was inconsistent. In the success // case, the application may save the current current value of total_in which // indicates where valid compressed data was found. In the error case, the // application may repeatedly call inflateSync, providing more input each time, // until success or end of the input data. int inflateReset (z_streamp strm); // This function is equivalent to inflateEnd followed by inflateInit, // but does not free and reallocate all the internal decompression state. // The stream will keep attributes that may have been set by inflateInit2. // // inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source // stream state was inconsistent (such as zalloc or state being NULL). // // checksum functions // These functions are not related to compression but are exported // anyway because they might be useful in applications using the // compression library. uLong adler32 (uLong adler, const Byte *buf, uInt len); // Update a running Adler-32 checksum with the bytes buf[0..len-1] and // return the updated checksum. If buf is NULL, this function returns // the required initial value for the checksum. // An Adler-32 checksum is almost as reliable as a CRC32 but can be computed // much faster. Usage example: // // uLong adler = adler32(0L, Z_NULL, 0); // // while (read_buffer(buffer, length) != EOF) { // adler = adler32(adler, buffer, length); // } // if (adler != original_adler) error(); uLong ucrc32 (uLong crc, const Byte *buf, uInt len); // Update a running crc with the bytes buf[0..len-1] and return the updated // crc. If buf is NULL, this function returns the required initial value // for the crc. Pre- and post-conditioning (one's complement) is performed // within this function so it shouldn't be done by the application. // Usage example: // // uLong crc = crc32(0L, Z_NULL, 0); // // while (read_buffer(buffer, length) != EOF) { // crc = crc32(crc, buffer, length); // } // if (crc != original_crc) error(); const char *zError (int err); int inflateSyncPoint (z_streamp z); const uLong *get_crc_table (void); typedef unsigned char uch; typedef uch uchf; typedef unsigned short ush; typedef ush ushf; typedef unsigned long ulg; const char * const z_errmsg[10] = { // indexed by 2-zlib_error "need dictionary", // Z_NEED_DICT 2 "stream end", // Z_STREAM_END 1 "", // Z_OK 0 "file error", // Z_ERRNO (-1) "stream error", // Z_STREAM_ERROR (-2) "data error", // Z_DATA_ERROR (-3) "insufficient memory", // Z_MEM_ERROR (-4) "buffer error", // Z_BUF_ERROR (-5) "incompatible version",// Z_VERSION_ERROR (-6) ""}; #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] #define ERR_RETURN(strm,err) \ return (strm->msg = (char*)ERR_MSG(err), (err)) // To be used only when the state is known to be valid // common constants #define STORED_BLOCK 0 #define STATIC_TREES 1 #define DYN_TREES 2 // The three kinds of block type #define MIN_MATCH 3 #define MAX_MATCH 258 // The minimum and maximum match lengths #define PRESET_DICT 0x20 // preset dictionary flag in zlib header // target dependencies #define OS_CODE 0x0b // Window 95 & Windows NT // functions #define zmemzero(dest, len) memset(dest, 0, len) // Diagnostic functions #define LuAssert(cond,msg) #define LuTrace(x) #define LuTracev(x) #define LuTracevv(x) #define LuTracec(c,x) #define LuTracecv(c,x) typedef uLong (*check_func) (uLong check, const Byte *buf, uInt len); voidpf zcalloc (voidpf opaque, unsigned items, unsigned size); void zcfree (voidpf opaque, voidpf ptr); #define ZALLOC(strm, items, size) \ (*((strm)->zalloc))((strm)->opaque, (items), (size)) #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) //void ZFREE(z_streamp strm,voidpf addr) //{ *((strm)->zfree))((strm)->opaque, addr); //} #define TRY_FREE(s, p) {if (p) ZFREE(s, p);} // Huffman code lookup table entry--this entry is four bytes for machines // that have 16-bit pointers (e.g. PC's in the small or medium model). typedef struct inflate_huft_s inflate_huft; struct inflate_huft_s { union { struct { Byte Exop; // number of extra bits or operation Byte Bits; // number of bits in this code or subcode } what; uInt pad; // pad structure to a power of 2 (4 bytes for } word; // 16-bit, 8 bytes for 32-bit int's) uInt base; // literal, length base, distance base, or table offset }; // Maximum size of dynamic tree. The maximum found in a long but non- // exhaustive search was 1004 huft structures (850 for length/literals // and 154 for distances, the latter actually the result of an // exhaustive search). The actual maximum is not known, but the // value below is more than safe. #define MANY 1440 int inflate_trees_bits ( uInt *, // 19 code lengths uInt *, // bits tree desired/actual depth inflate_huft * *, // bits tree result inflate_huft *, // space for trees z_streamp); // for messages int inflate_trees_dynamic ( uInt, // number of literal/length codes uInt, // number of distance codes uInt *, // that many (total) code lengths uInt *, // literal desired/actual bit depth uInt *, // distance desired/actual bit depth inflate_huft * *, // literal/length tree result inflate_huft * *, // distance tree result inflate_huft *, // space for trees z_streamp); // for messages int inflate_trees_fixed ( uInt *, // literal desired/actual bit depth uInt *, // distance desired/actual bit depth const inflate_huft * *, // literal/length tree result const inflate_huft * *, // distance tree result z_streamp); // for memory allocation struct inflate_blocks_state; typedef struct inflate_blocks_state inflate_blocks_statef; inflate_blocks_statef * inflate_blocks_new ( z_streamp z, check_func c, // check function uInt w); // window size int inflate_blocks ( inflate_blocks_statef *, z_streamp , int); // initial return code void inflate_blocks_reset ( inflate_blocks_statef *, z_streamp , uLong *); // check value on output int inflate_blocks_free ( inflate_blocks_statef *, z_streamp); void inflate_set_dictionary ( inflate_blocks_statef *s, const Byte *d, // dictionary uInt n); // dictionary length int inflate_blocks_sync_point ( inflate_blocks_statef *s); struct inflate_codes_state; typedef struct inflate_codes_state inflate_codes_statef; inflate_codes_statef *inflate_codes_new ( uInt, uInt, const inflate_huft *, const inflate_huft *, z_streamp ); int inflate_codes ( inflate_blocks_statef *, z_streamp , int); void inflate_codes_free ( inflate_codes_statef *, z_streamp ); typedef enum { IBM_TYPE, // get type bits (3, including end bit) IBM_LENS, // get lengths for stored IBM_STORED, // processing stored block IBM_TABLE, // get table lengths IBM_BTREE, // get bit lengths tree for a dynamic block IBM_DTREE, // get length, distance trees for a dynamic block IBM_CODES, // processing fixed or dynamic block IBM_DRY, // output remaining window bytes IBM_DONE, // finished last block, done IBM_BAD} // got a data error--stuck here inflate_block_mode; // inflate blocks semi-private state struct inflate_blocks_state { // mode inflate_block_mode mode; // current inflate_block mode // mode dependent information union { uInt left; // if STORED, bytes left to copy struct { uInt table; // table lengths (14 bits) uInt index; // index into blens (or border) uInt *blens; // bit lengths of codes uInt bb; // bit length tree depth inflate_huft *tb; // bit length decoding tree } trees; // if DTREE, decoding info for trees struct { inflate_codes_statef *codes; } decode; // if CODES, current state } sub; // submode uInt last; // true if this block is the last block // mode independent information uInt bitk; // bits in bit buffer uLong bitb; // bit buffer inflate_huft *hufts; // single malloc for tree space Byte *window; // sliding window Byte *end; // one byte after sliding window Byte *read; // window read pointer Byte *write; // window write pointer check_func checkfn; // check function uLong check; // check on output }; // defines for inflate input/output // update pointers and return #define UPDBITS {s->bitb=b;s->bitk=k;} #define UPDIN {z->avail_in=n;z->total_in+=(uLong)(p-z->next_in);z->next_in=p;} #define UPDOUT {s->write=q;} #define UPDATE {UPDBITS UPDIN UPDOUT} #define LEAVE {UPDATE return inflate_flush(s,z,r);} // get bytes and bits #define LOADIN {p=z->next_in;n=z->avail_in;b=s->bitb;k=s->bitk;} #define NEEDBYTE {if(n)r=Z_OK;else LEAVE} #define NEXTBYTE (n--,*p++) #define NEEDBITS(j) {while(k<(j)){NEEDBYTE;b|=((uLong)NEXTBYTE)<<k;k+=8;}} #define DUMPBITS(j) {b>>=(j);k-=(j);} // output bytes #define WAVAIL (uInt)(q<s->read?s->read-q-1:s->end-q) #define LOADOUT {q=s->write;m=(uInt)WAVAIL;m;} #define WRAP {if(q==s->end&&s->read!=s->window){q=s->window;m=(uInt)WAVAIL;}} #define FLUSH {UPDOUT r=inflate_flush(s,z,r); LOADOUT} #define NEEDOUT {if(m==0){WRAP if(m==0){FLUSH WRAP if(m==0) LEAVE}}r=Z_OK;} #define OUTBYTE(a) {*q++=(Byte)(a);m--;} // load local pointers #define LOAD {LOADIN LOADOUT} // masks for lower bits (size given to avoid silly warnings with Visual C++) // And'ing with mask[n] masks the lower n bits const uInt inflate_mask[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff }; // copy as much as possible from the sliding window to the output area int inflate_flush (inflate_blocks_statef *, z_streamp, int); int inflate_fast (uInt, uInt, const inflate_huft *, const inflate_huft *, inflate_blocks_statef *, z_streamp ); const uInt fixed_bl = 9; const uInt fixed_bd = 5; const inflate_huft fixed_tl[] = { {{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115}, {{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},192}, {{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},160}, {{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},224}, {{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},144}, {{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},208}, {{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},176}, {{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},240}, {{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227}, {{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},200}, {{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},168}, {{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},232}, {{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},152}, {{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},216}, {{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},184}, {{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},248}, {{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163}, {{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},196}, {{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},164}, {{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},228}, {{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},148}, {{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},212}, {{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},180}, {{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},244}, {{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0}, {{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},204}, {{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},172}, {{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},236}, {{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},156}, {{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},220}, {{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},188}, {{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},252}, {{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131}, {{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},194}, {{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},162}, {{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},226}, {{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},146}, {{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},210}, {{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},178}, {{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},242}, {{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258}, {{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},202}, {{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},170}, {{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},234}, {{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},154}, {{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},218}, {{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},186}, {{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},250}, {{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195}, {{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},198}, {{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},166}, {{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},230}, {{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},150}, {{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},214}, {{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},182}, {{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},246}, {{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0}, {{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},206}, {{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},174}, {{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},238}, {{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},158}, {{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},222}, {{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},190}, {{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},254}, {{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115}, {{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},193}, {{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},161}, {{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},225}, {{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},145}, {{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},209}, {{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},177}, {{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},241}, {{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227}, {{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},201}, {{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},169}, {{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},233}, {{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},153}, {{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},217}, {{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},185}, {{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},249}, {{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163}, {{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},197}, {{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},165}, {{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},229}, {{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},149}, {{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},213}, {{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},181}, {{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},245}, {{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0}, {{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},205}, {{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},173}, {{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},237}, {{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},157}, {{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},221}, {{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},189}, {{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},253}, {{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131}, {{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},195}, {{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},163}, {{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},227}, {{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},147}, {{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},211}, {{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},179}, {{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},243}, {{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258}, {{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},203}, {{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},171}, {{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},235}, {{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},155}, {{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},219}, {{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},187}, {{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},251}, {{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195}, {{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},199}, {{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},167}, {{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},231}, {{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},151}, {{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},215}, {{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},183}, {{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},247}, {{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0}, {{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},207}, {{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},175}, {{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},239}, {{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},159}, {{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},223}, {{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},191}, {{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},255} }; const inflate_huft fixed_td[] = { {{{80,5}},1}, {{{87,5}},257}, {{{83,5}},17}, {{{91,5}},4097}, {{{81,5}},5}, {{{89,5}},1025}, {{{85,5}},65}, {{{93,5}},16385}, {{{80,5}},3}, {{{88,5}},513}, {{{84,5}},33}, {{{92,5}},8193}, {{{82,5}},9}, {{{90,5}},2049}, {{{86,5}},129}, {{{192,5}},24577}, {{{80,5}},2}, {{{87,5}},385}, {{{83,5}},25}, {{{91,5}},6145}, {{{81,5}},7}, {{{89,5}},1537}, {{{85,5}},97}, {{{93,5}},24577}, {{{80,5}},4}, {{{88,5}},769}, {{{84,5}},49}, {{{92,5}},12289}, {{{82,5}},13}, {{{90,5}},3073}, {{{86,5}},193}, {{{192,5}},24577} }; // copy as much as possible from the sliding window to the output area int inflate_flush(inflate_blocks_statef *s,z_streamp z,int r) { uInt n; Byte *p; Byte *q; // local copies of source and destination pointers p = z->next_out; q = s->read; // compute number of bytes to copy as far as end of window n = (uInt)((q <= s->write ? s->write : s->end) - q); if (n > z->avail_out) n = z->avail_out; if (n && r == Z_BUF_ERROR) r = Z_OK; // update counters z->avail_out -= n; z->total_out += n; // update check information if (s->checkfn != Z_NULL) z->adler = s->check = (*s->checkfn)(s->check, q, n); // copy as far as end of window if (n!=0) // check for n!=0 to avoid waking up CodeGuard { memcpy(p, q, n); p += n; q += n; } // see if more to copy at beginning of window if (q == s->end) { // wrap pointers q = s->window; if (s->write == s->end) s->write = s->window; // compute bytes to copy n = (uInt)(s->write - q); if (n > z->avail_out) n = z->avail_out; if (n && r == Z_BUF_ERROR) r = Z_OK; // update counters z->avail_out -= n; z->total_out += n; // update check information if (s->checkfn != Z_NULL) z->adler = s->check = (*s->checkfn)(s->check, q, n); // copy if (n!=0) {memcpy(p,q,n); p+=n; q+=n;} } // update pointers z->next_out = p; s->read = q; // done return r; } // simplify the use of the inflate_huft type with some defines #define exop word.what.Exop #define bits word.what.Bits typedef enum { // waiting for "i:"=input, "o:"=output, "x:"=nothing START, // x: set up for LEN LEN, // i: get length/literal/eob next LENEXT, // i: getting length extra (have base) DIST, // i: get distance next DISTEXT, // i: getting distance extra COPY, // o: copying bytes in window, waiting for space LIT, // o: got literal, waiting for output space WASH, // o: got eob, possibly still output waiting END, // x: got eob and all data flushed BADCODE} // x: got error inflate_codes_mode; // inflate codes private state struct inflate_codes_state { // mode inflate_codes_mode mode; // current inflate_codes mode // mode dependent information uInt len; union { struct { const inflate_huft *tree; // pointer into tree uInt need; // bits needed } code; // if LEN or DIST, where in tree uInt lit; // if LIT, literal struct { uInt get; // bits to get for extra uInt dist; // distance back to copy from } copy; // if EXT or COPY, where and how much } sub; // submode // mode independent information Byte lbits; // ltree bits decoded per branch Byte dbits; // dtree bits decoder per branch const inflate_huft *ltree; // literal/length/eob tree const inflate_huft *dtree; // distance tree }; inflate_codes_statef *inflate_codes_new( uInt bl, uInt bd, const inflate_huft *tl, const inflate_huft *td, // need separate declaration for Borland C++ z_streamp z) { inflate_codes_statef *c; if ((c = (inflate_codes_statef *) ZALLOC(z,1,sizeof(struct inflate_codes_state))) != Z_NULL) { c->mode = START; c->lbits = (Byte)bl; c->dbits = (Byte)bd; c->ltree = tl; c->dtree = td; LuTracev((stderr, "inflate: codes new\n")); } return c; } int inflate_codes(inflate_blocks_statef *s, z_streamp z, int r) { uInt j; // temporary storage const inflate_huft *t; // temporary pointer uInt e; // extra bits or operation uLong b; // bit buffer uInt k; // bits in bit buffer Byte *p; // input data pointer uInt n; // bytes available there Byte *q; // output window write pointer uInt m; // bytes to end of window or read pointer Byte *f; // pointer to copy strings from inflate_codes_statef *c = s->sub.decode.codes; // codes state // copy input/output information to locals (UPDATE macro restores) LOAD // process input and output based on current state for(;;) switch (c->mode) { // waiting for "i:"=input, "o:"=output, "x:"=nothing case START: // x: set up for LEN #ifndef SLOW if (m >= 258 && n >= 10) { UPDATE r = inflate_fast(c->lbits, c->dbits, c->ltree, c->dtree, s, z); LOAD if (r != Z_OK) { c->mode = r == Z_STREAM_END ? WASH : BADCODE; break; } } #endif // !SLOW c->sub.code.need = c->lbits; c->sub.code.tree = c->ltree; c->mode = LEN; case LEN: // i: get length/literal/eob next j = c->sub.code.need; NEEDBITS(j) t = c->sub.code.tree + ((uInt)b & inflate_mask[j]); DUMPBITS(t->bits) e = (uInt)(t->exop); if (e == 0) // literal { c->sub.lit = t->base; LuTracevv((stderr, t->base >= 0x20 && t->base < 0x7f ? "inflate: literal '%c'\n" : "inflate: literal 0x%02x\n", t->base)); c->mode = LIT; break; } if (e & 16) // length { c->sub.copy.get = e & 15; c->len = t->base; c->mode = LENEXT; break; } if ((e & 64) == 0) // next table { c->sub.code.need = e; c->sub.code.tree = t + t->base; break; } if (e & 32) // end of block { LuTracevv((stderr, "inflate: end of block\n")); c->mode = WASH; break; } c->mode = BADCODE; // invalid code z->msg = (char*)"invalid literal/length code"; r = Z_DATA_ERROR; LEAVE case LENEXT: // i: getting length extra (have base) j = c->sub.copy.get; NEEDBITS(j) c->len += (uInt)b & inflate_mask[j]; DUMPBITS(j) c->sub.code.need = c->dbits; c->sub.code.tree = c->dtree; LuTracevv((stderr, "inflate: length %u\n", c->len)); c->mode = DIST; case DIST: // i: get distance next j = c->sub.code.need; NEEDBITS(j) t = c->sub.code.tree + ((uInt)b & inflate_mask[j]); DUMPBITS(t->bits) e = (uInt)(t->exop); if (e & 16) // distance { c->sub.copy.get = e & 15; c->sub.copy.dist = t->base; c->mode = DISTEXT; break; } if ((e & 64) == 0) // next table { c->sub.code.need = e; c->sub.code.tree = t + t->base; break; } c->mode = BADCODE; // invalid code z->msg = (char*)"invalid distance code"; r = Z_DATA_ERROR; LEAVE case DISTEXT: // i: getting distance extra j = c->sub.copy.get; NEEDBITS(j) c->sub.copy.dist += (uInt)b & inflate_mask[j]; DUMPBITS(j) LuTracevv((stderr, "inflate: distance %u\n", c->sub.copy.dist)); c->mode = COPY; case COPY: // o: copying bytes in window, waiting for space f = q - c->sub.copy.dist; while (f < s->window) // modulo window size-"while" instead f += s->end - s->window; // of "if" handles invalid distances while (c->len) { NEEDOUT OUTBYTE(*f++) if (f == s->end) f = s->window; c->len--; } c->mode = START; break; case LIT: // o: got literal, waiting for output space NEEDOUT OUTBYTE(c->sub.lit) c->mode = START; break; case WASH: // o: got eob, possibly more output if (k > 7) // return unused byte, if any { //Assert(k < 16, "inflate_codes grabbed too many bytes") k -= 8; n++; p--; // can always return one } FLUSH if (s->read != s->write) LEAVE c->mode = END; case END: r = Z_STREAM_END; LEAVE case BADCODE: // x: got error r = Z_DATA_ERROR; LEAVE default: r = Z_STREAM_ERROR; LEAVE } } void inflate_codes_free(inflate_codes_statef *c,z_streamp z) { ZFREE(z, c); LuTracev((stderr, "inflate: codes free\n")); } // infblock.c -- interpret and process block types to last block // Copyright (C) 1995-1998 Mark Adler // For conditions of distribution and use, see copyright notice in zlib.h //struct inflate_codes_state {int dummy;}; // for buggy compilers // Table for deflate from PKZIP's appnote.txt. const uInt border[] = { // Order of the bit length code lengths 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; // // Notes beyond the 1.93a appnote.txt: // // 1. Distance pointers never point before the beginning of the output stream. // 2. Distance pointers can point back across blocks, up to 32k away. // 3. There is an implied maximum of 7 bits for the bit length table and // 15 bits for the actual data. // 4. If only one code exists, then it is encoded using one bit. (Zero // would be more efficient, but perhaps a little confusing.) If two // codes exist, they are coded using one bit each (0 and 1). // 5. There is no way of sending zero distance codes--a dummy must be // sent if there are none. (History: a pre 2.0 version of PKZIP would // store blocks with no distance codes, but this was discovered to be // too harsh a criterion.) Valid only for 1.93a. 2.04c does allow // zero distance codes, which is sent as one code of zero bits in // length. // 6. There are up to 286 literal/length codes. Code 256 represents the // end-of-block. Note however that the static length tree defines // 288 codes just to fill out the Huffman codes. Codes 286 and 287 // cannot be used though, since there is no length base or extra bits // defined for them. Similarily, there are up to 30 distance codes. // However, static trees define 32 codes (all 5 bits) to fill out the // Huffman codes, but the last two had better not show up in the data. // 7. Unzip can check dynamic Huffman blocks for complete code sets. // The exception is that a single code would not be complete (see #4). // 8. The five bits following the block type is really the number of // literal codes sent minus 257. // 9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits // (1+6+6). Therefore, to output three times the length, you output // three codes (1+1+1), whereas to output four times the same length, // you only need two codes (1+3). Hmm. //10. In the tree reconstruction algorithm, Code = Code + Increment // only if BitLength(i) is not zero. (Pretty obvious.) //11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19) //12. Note: length code 284 can represent 227-258, but length code 285 // really is 258. The last length deserves its own, short code // since it gets used a lot in very redundant files. The length // 258 is special since 258 - 3 (the min match length) is 255. //13. The literal/length and distance code bit lengths are read as a // single stream of lengths. It is possible (and advantageous) for // a repeat code (16, 17, or 18) to go across the boundary between // the two sets of lengths. void inflate_blocks_reset(inflate_blocks_statef *s, z_streamp z, uLong *c) { if (c != Z_NULL) *c = s->check; if (s->mode == IBM_BTREE || s->mode == IBM_DTREE) ZFREE(z, s->sub.trees.blens); if (s->mode == IBM_CODES) inflate_codes_free(s->sub.decode.codes, z); s->mode = IBM_TYPE; s->bitk = 0; s->bitb = 0; s->read = s->write = s->window; if (s->checkfn != Z_NULL) z->adler = s->check = (*s->checkfn)(0L, (const Byte *)Z_NULL, 0); LuTracev((stderr, "inflate: blocks reset\n")); } inflate_blocks_statef *inflate_blocks_new(z_streamp z, check_func c, uInt w) { inflate_blocks_statef *s; if ((s = (inflate_blocks_statef *)ZALLOC (z,1,sizeof(struct inflate_blocks_state))) == Z_NULL) return s; if ((s->hufts = (inflate_huft *)ZALLOC(z, sizeof(inflate_huft), MANY)) == Z_NULL) { ZFREE(z, s); return Z_NULL; } if ((s->window = (Byte *)ZALLOC(z, 1, w)) == Z_NULL) { ZFREE(z, s->hufts); ZFREE(z, s); return Z_NULL; } s->end = s->window + w; s->checkfn = c; s->mode = IBM_TYPE; LuTracev((stderr, "inflate: blocks allocated\n")); inflate_blocks_reset(s, z, Z_NULL); return s; } int inflate_blocks(inflate_blocks_statef *s, z_streamp z, int r) { uInt t; // temporary storage uLong b; // bit buffer uInt k; // bits in bit buffer Byte *p; // input data pointer uInt n; // bytes available there Byte *q; // output window write pointer uInt m; // bytes to end of window or read pointer // copy input/output information to locals (UPDATE macro restores) LOAD // process input based on current state for(;;) switch (s->mode) { case IBM_TYPE: NEEDBITS(3) t = (uInt)b & 7; s->last = t & 1; switch (t >> 1) { case 0: // stored LuTracev((stderr, "inflate: stored block%s\n", s->last ? " (last)" : "")); DUMPBITS(3) t = k & 7; // go to byte boundary DUMPBITS(t) s->mode = IBM_LENS; // get length of stored block break; case 1: // fixed LuTracev((stderr, "inflate: fixed codes block%s\n", s->last ? " (last)" : "")); { uInt bl, bd; const inflate_huft *tl, *td; inflate_trees_fixed(&bl, &bd, &tl, &td, z); s->sub.decode.codes = inflate_codes_new(bl, bd, tl, td, z); if (s->sub.decode.codes == Z_NULL) { r = Z_MEM_ERROR; LEAVE } } DUMPBITS(3) s->mode = IBM_CODES; break; case 2: // dynamic LuTracev((stderr, "inflate: dynamic codes block%s\n", s->last ? " (last)" : "")); DUMPBITS(3) s->mode = IBM_TABLE; break; case 3: // illegal DUMPBITS(3) s->mode = IBM_BAD; z->msg = (char*)"invalid block type"; r = Z_DATA_ERROR; LEAVE } break; case IBM_LENS: NEEDBITS(32) if ((((~b) >> 16) & 0xffff) != (b & 0xffff)) { s->mode = IBM_BAD; z->msg = (char*)"invalid stored block lengths"; r = Z_DATA_ERROR; LEAVE } s->sub.left = (uInt)b & 0xffff; b = k = 0; // dump bits LuTracev((stderr, "inflate: stored length %u\n", s->sub.left)); s->mode = s->sub.left ? IBM_STORED : (s->last ? IBM_DRY : IBM_TYPE); break; case IBM_STORED: if (n == 0) LEAVE NEEDOUT t = s->sub.left; if (t > n) t = n; if (t > m) t = m; memcpy(q, p, t); p += t; n -= t; q += t; m -= t; if ((s->sub.left -= t) != 0) break; LuTracev((stderr, "inflate: stored end, %lu total out\n", z->total_out + (q >= s->read ? q - s->read : (s->end - s->read) + (q - s->window)))); s->mode = s->last ? IBM_DRY : IBM_TYPE; break; case IBM_TABLE: NEEDBITS(14) s->sub.trees.table = t = (uInt)b & 0x3fff; // remove this section to workaround bug in pkzip if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29) { s->mode = IBM_BAD; z->msg = (char*)"too many length or distance symbols"; r = Z_DATA_ERROR; LEAVE } // end remove t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f); if ((s->sub.trees.blens = (uInt*)ZALLOC(z, t, sizeof(uInt))) == Z_NULL) { r = Z_MEM_ERROR; LEAVE } DUMPBITS(14) s->sub.trees.index = 0; LuTracev((stderr, "inflate: table sizes ok\n")); s->mode = IBM_BTREE; case IBM_BTREE: while (s->sub.trees.index < 4 + (s->sub.trees.table >> 10)) { NEEDBITS(3) s->sub.trees.blens[border[s->sub.trees.index++]] = (uInt)b & 7; DUMPBITS(3) } while (s->sub.trees.index < 19) s->sub.trees.blens[border[s->sub.trees.index++]] = 0; s->sub.trees.bb = 7; t = inflate_trees_bits(s->sub.trees.blens, &s->sub.trees.bb, &s->sub.trees.tb, s->hufts, z); if (t != Z_OK) { r = t; if (r == Z_DATA_ERROR) { ZFREE(z, s->sub.trees.blens); s->mode = IBM_BAD; } LEAVE } s->sub.trees.index = 0; LuTracev((stderr, "inflate: bits tree ok\n")); s->mode = IBM_DTREE; case IBM_DTREE: while (t = s->sub.trees.table, s->sub.trees.index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f)) { inflate_huft *h; uInt i, j, c; t = s->sub.trees.bb; NEEDBITS(t) h = s->sub.trees.tb + ((uInt)b & inflate_mask[t]); t = h->bits; c = h->base; if (c < 16) { DUMPBITS(t) s->sub.trees.blens[s->sub.trees.index++] = c; } else // c == 16..18 { i = c == 18 ? 7 : c - 14; j = c == 18 ? 11 : 3; NEEDBITS(t + i) DUMPBITS(t) j += (uInt)b & inflate_mask[i]; DUMPBITS(i) i = s->sub.trees.index; t = s->sub.trees.table; if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) || (c == 16 && i < 1)) { ZFREE(z, s->sub.trees.blens); s->mode = IBM_BAD; z->msg = (char*)"invalid bit length repeat"; r = Z_DATA_ERROR; LEAVE } c = c == 16 ? s->sub.trees.blens[i - 1] : 0; do { s->sub.trees.blens[i++] = c; } while (--j); s->sub.trees.index = i; } } s->sub.trees.tb = Z_NULL; { uInt bl, bd; inflate_huft *tl, *td; inflate_codes_statef *c; bl = 9; // must be <= 9 for lookahead assumptions bd = 6; // must be <= 9 for lookahead assumptions t = s->sub.trees.table; t = inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), s->sub.trees.blens, &bl, &bd, &tl, &td, s->hufts, z); if (t != Z_OK) { if (t == (uInt)Z_DATA_ERROR) { ZFREE(z, s->sub.trees.blens); s->mode = IBM_BAD; } r = t; LEAVE } LuTracev((stderr, "inflate: trees ok\n")); if ((c = inflate_codes_new(bl, bd, tl, td, z)) == Z_NULL) { r = Z_MEM_ERROR; LEAVE } s->sub.decode.codes = c; } ZFREE(z, s->sub.trees.blens); s->mode = IBM_CODES; case IBM_CODES: UPDATE if ((r = inflate_codes(s, z, r)) != Z_STREAM_END) return inflate_flush(s, z, r); r = Z_OK; inflate_codes_free(s->sub.decode.codes, z); LOAD LuTracev((stderr, "inflate: codes end, %lu total out\n", z->total_out + (q >= s->read ? q - s->read : (s->end - s->read) + (q - s->window)))); if (!s->last) { s->mode = IBM_TYPE; break; } s->mode = IBM_DRY; case IBM_DRY: FLUSH if (s->read != s->write) LEAVE s->mode = IBM_DONE; case IBM_DONE: r = Z_STREAM_END; LEAVE case IBM_BAD: r = Z_DATA_ERROR; LEAVE default: r = Z_STREAM_ERROR; LEAVE } } int inflate_blocks_free(inflate_blocks_statef *s, z_streamp z) { inflate_blocks_reset(s, z, Z_NULL); ZFREE(z, s->window); ZFREE(z, s->hufts); ZFREE(z, s); LuTracev((stderr, "inflate: blocks freed\n")); return Z_OK; } // inftrees.c -- generate Huffman trees for efficient decoding // Copyright (C) 1995-1998 Mark Adler // For conditions of distribution and use, see copyright notice in zlib.h // extern const char inflate_copyright[] = " inflate 1.1.3 Copyright 1995-1998 Mark Adler "; // If you use the zlib library in a product, an acknowledgment is welcome // in the documentation of your product. If for some reason you cannot // include such an acknowledgment, I would appreciate that you keep this // copyright string in the executable of your product. int huft_build ( uInt *, // code lengths in bits uInt, // number of codes uInt, // number of "simple" codes const uInt *, // list of base values for non-simple codes const uInt *, // list of extra bits for non-simple codes inflate_huft **,// result: starting table uInt *, // maximum lookup bits (returns actual) inflate_huft *, // space for trees uInt *, // hufts used in space uInt * ); // space for values // Tables for deflate from PKZIP's appnote.txt. const uInt cplens[31] = { // Copy lengths for literal codes 257..285 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; // see note #13 above about 258 const uInt cplext[31] = { // Extra bits for literal codes 257..285 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112}; // 112==invalid const uInt cpdist[30] = { // Copy offsets for distance codes 0..29 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; const uInt cpdext[30] = { // Extra bits for distance codes 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; // // Huffman code decoding is performed using a multi-level table lookup. // The fastest way to decode is to simply build a lookup table whose // size is determined by the longest code. However, the time it takes // to build this table can also be a factor if the data being decoded // is not very long. The most common codes are necessarily the // shortest codes, so those codes dominate the decoding time, and hence // the speed. The idea is you can have a shorter table that decodes the // shorter, more probable codes, and then point to subsidiary tables for // the longer codes. The time it costs to decode the longer codes is // then traded against the time it takes to make longer tables. // // This results of this trade are in the variables lbits and dbits // below. lbits is the number of bits the first level table for literal/ // length codes can decode in one step, and dbits is the same thing for // the distance codes. Subsequent tables are also less than or equal to // those sizes. These values may be adjusted either when all of the // codes are shorter than that, in which case the longest code length in // bits is used, or when the shortest code is *longer* than the requested // table size, in which case the length of the shortest code in bits is // used. // // There are two different values for the two tables, since they code a // different number of possibilities each. The literal/length table // codes 286 possible values, or in a flat code, a little over eight // bits. The distance table codes 30 possible values, or a little less // than five bits, flat. The optimum values for speed end up being // about one bit more than those, so lbits is 8+1 and dbits is 5+1. // The optimum values may differ though from machine to machine, and // possibly even between compilers. Your mileage may vary. // // If BMAX needs to be larger than 16, then h and x[] should be uLong. #define BMAX 15 // maximum bit length of any code int huft_build( uInt *b, // code lengths in bits (all assumed <= BMAX) uInt n, // number of codes (assumed <= 288) uInt s, // number of simple-valued codes (0..s-1) const uInt *d, // list of base values for non-simple codes const uInt *e, // list of extra bits for non-simple codes inflate_huft * *t, // result: starting table uInt *m, // maximum lookup bits, returns actual inflate_huft *hp, // space for trees uInt *hn, // hufts used in space uInt *v) // working area: values in order of bit length // Given a list of code lengths and a maximum table size, make a set of // tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR // if the given code set is incomplete (the tables are still built in this // case), or Z_DATA_ERROR if the input is invalid. { uInt a; // counter for codes of length k uInt c[BMAX+1]; // bit length count table uInt f; // i repeats in table every f entries int g; // maximum code length int h; // table level register uInt i; // counter, current code register uInt j; // counter register int k; // number of bits in current code int l; // bits per table (returned in m) uInt mask; // (1 << w) - 1, to avoid cc -O bug on HP register uInt *p; // pointer into c[], b[], or v[] inflate_huft *q; // points to current table struct inflate_huft_s r; // table entry for structure assignment inflate_huft *u[BMAX]; // table stack register int w; // bits before this table == (l * h) uInt x[BMAX+1]; // bit offsets, then code stack uInt *xp; // pointer into x int y; // number of dummy codes added uInt z; // number of entries in current table // Generate counts for each bit length p = c; #define C0 *p++ = 0; #define C2 C0 C0 C0 C0 #define C4 C2 C2 C2 C2 C4; p; // clear c[]--assume BMAX+1 is 16 p = b; i = n; do { c[*p++]++; // assume all entries <= BMAX } while (--i); if (c[0] == n) // null input--all zero length codes { *t = (inflate_huft *)Z_NULL; *m = 0; return Z_OK; } // Find minimum and maximum length, bound *m by those l = *m; for (j = 1; j <= BMAX; j++) if (c[j]) break; k = j; // minimum code length if ((uInt)l < j) l = j; for (i = BMAX; i; i--) if (c[i]) break; g = i; // maximum code length if ((uInt)l > i) l = i; *m = l; // Adjust last length count to fill out codes, if needed for (y = 1 << j; j < i; j++, y <<= 1) if ((y -= c[j]) < 0) return Z_DATA_ERROR; if ((y -= c[i]) < 0) return Z_DATA_ERROR; c[i] += y; // Generate starting offsets into the value table for each length x[1] = j = 0; p = c + 1; xp = x + 2; while (--i) { // note that i == g from above *xp++ = (j += *p++); } // Make a table of values in order of bit lengths p = b; i = 0; do { if ((j = *p++) != 0) v[x[j]++] = i; } while (++i < n); n = x[g]; // set n to length of v // Generate the Huffman codes and for each, make the table entries x[0] = i = 0; // first Huffman code is zero p = v; // grab values in bit order h = -1; // no tables yet--level -1 w = -l; // bits decoded == (l * h) u[0] = (inflate_huft *)Z_NULL; // just to keep compilers happy q = (inflate_huft *)Z_NULL; // ditto z = 0; // ditto // go through the bit lengths (k already is bits in shortest code) for (; k <= g; k++) { a = c[k]; while (a--) { // here i is the Huffman code of length k bits for value *p // make tables up to required level while (k > w + l) { h++; w += l; // previous table always l bits // compute minimum size table less than or equal to l bits z = g - w; z = z > (uInt)l ? l : z; // table size upper limit if ((f = 1 << (j = k - w)) > a + 1) // try a k-w bit table { // too few codes for k-w bit table f -= a + 1; // deduct codes from patterns left xp = c + k; if (j < z) while (++j < z) // try smaller tables up to z bits { if ((f <<= 1) <= *++xp) break; // enough codes to use up j bits f -= *xp; // else deduct codes from patterns } } z = 1 << j; // table entries for j-bit table // allocate new table if (*hn + z > MANY) // (note: doesn't matter for fixed) return Z_DATA_ERROR; // overflow of MANY u[h] = q = hp + *hn; *hn += z; // connect to last table, if there is one if (h) { x[h] = i; // save pattern for backing up r.bits = (Byte)l; // bits to dump before this table r.exop = (Byte)j; // bits in this table j = i >> (w - l); r.base = (uInt)(q - u[h-1] - j); // offset to this table u[h-1][j] = r; // connect to last table } else *t = q; // first table is returned result } // set up table entry in r r.bits = (Byte)(k - w); if (p >= v + n) r.exop = 128 + 64; // out of values--invalid code else if (*p < s) { r.exop = (Byte)(*p < 256 ? 0 : 32 + 64); // 256 is end-of-block r.base = *p++; // simple code is just the value } else { r.exop = (Byte)(e[*p - s] + 16 + 64);// non-simple--look up in lists r.base = d[*p++ - s]; } // fill code-like entries with r f = 1 << (k - w); for (j = i >> w; j < z; j += f) q[j] = r; // backwards increment the k-bit code i for (j = 1 << (k - 1); i & j; j >>= 1) i ^= j; i ^= j; // backup over finished tables mask = (1 << w) - 1; // needed on HP, cc -O bug while ((i & mask) != x[h]) { h--; // don't need to update q w -= l; mask = (1 << w) - 1; } } } // Return Z_BUF_ERROR if we were given an incomplete table return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK; } int inflate_trees_bits( uInt *c, // 19 code lengths uInt *bb, // bits tree desired/actual depth inflate_huft * *tb, // bits tree result inflate_huft *hp, // space for trees z_streamp z) // for messages { int r; uInt hn = 0; // hufts used in space uInt *v; // work area for huft_build if ((v = (uInt*)ZALLOC(z, 19, sizeof(uInt))) == Z_NULL) return Z_MEM_ERROR; r = huft_build(c, 19, 19, (uInt*)Z_NULL, (uInt*)Z_NULL, tb, bb, hp, &hn, v); if (r == Z_DATA_ERROR) z->msg = (char*)"oversubscribed dynamic bit lengths tree"; else if (r == Z_BUF_ERROR || *bb == 0) { z->msg = (char*)"incomplete dynamic bit lengths tree"; r = Z_DATA_ERROR; } ZFREE(z, v); return r; } int inflate_trees_dynamic( uInt nl, // number of literal/length codes uInt nd, // number of distance codes uInt *c, // that many (total) code lengths uInt *bl, // literal desired/actual bit depth uInt *bd, // distance desired/actual bit depth inflate_huft * *tl, // literal/length tree result inflate_huft * *td, // distance tree result inflate_huft *hp, // space for trees z_streamp z) // for messages { int r; uInt hn = 0; // hufts used in space uInt *v; // work area for huft_build // allocate work area if ((v = (uInt*)ZALLOC(z, 288, sizeof(uInt))) == Z_NULL) return Z_MEM_ERROR; // build literal/length tree r = huft_build(c, nl, 257, cplens, cplext, tl, bl, hp, &hn, v); if (r != Z_OK || *bl == 0) { if (r == Z_DATA_ERROR) z->msg = (char*)"oversubscribed literal/length tree"; else if (r != Z_MEM_ERROR) { z->msg = (char*)"incomplete literal/length tree"; r = Z_DATA_ERROR; } ZFREE(z, v); return r; } // build distance tree r = huft_build(c + nl, nd, 0, cpdist, cpdext, td, bd, hp, &hn, v); if (r != Z_OK || (*bd == 0 && nl > 257)) { if (r == Z_DATA_ERROR) z->msg = (char*)"oversubscribed distance tree"; else if (r == Z_BUF_ERROR) { z->msg = (char*)"incomplete distance tree"; r = Z_DATA_ERROR; } else if (r != Z_MEM_ERROR) { z->msg = (char*)"empty distance tree with lengths"; r = Z_DATA_ERROR; } ZFREE(z, v); return r; } // done ZFREE(z, v); return Z_OK; } int inflate_trees_fixed( uInt *bl, // literal desired/actual bit depth uInt *bd, // distance desired/actual bit depth const inflate_huft * * tl, // literal/length tree result const inflate_huft * *td, // distance tree result z_streamp ) // for memory allocation { *bl = fixed_bl; *bd = fixed_bd; *tl = fixed_tl; *td = fixed_td; return Z_OK; } // inffast.c -- process literals and length/distance pairs fast // Copyright (C) 1995-1998 Mark Adler // For conditions of distribution and use, see copyright notice in zlib.h // //struct inflate_codes_state {int dummy;}; // for buggy compilers // macros for bit input with no checking and for returning unused bytes #define GRABBITS(j) {while(k<(j)){b|=((uLong)NEXTBYTE)<<k;k+=8;}} #define UNGRAB {c=z->avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3;} // Called with number of bytes left to write in window at least 258 // (the maximum string length) and number of input bytes available // at least ten. The ten bytes are six bytes for the longest length/ // distance pair plus four bytes for overloading the bit buffer. int inflate_fast( uInt bl, uInt bd, const inflate_huft *tl, const inflate_huft *td, // need separate declaration for Borland C++ inflate_blocks_statef *s, z_streamp z) { const inflate_huft *t; // temporary pointer uInt e; // extra bits or operation uLong b; // bit buffer uInt k; // bits in bit buffer Byte *p; // input data pointer uInt n; // bytes available there Byte *q; // output window write pointer uInt m; // bytes to end of window or read pointer uInt ml; // mask for literal/length tree uInt md; // mask for distance tree uInt c; // bytes to copy uInt d; // distance back to copy from Byte *r; // copy source pointer // load input, output, bit values LOAD // initialize masks ml = inflate_mask[bl]; md = inflate_mask[bd]; // do until not enough input or output space for fast loop do { // assume called with m >= 258 && n >= 10 // get literal/length code GRABBITS(20) // max bits for literal/length code if ((e = (t = tl + ((uInt)b & ml))->exop) == 0) { DUMPBITS(t->bits) LuTracevv((stderr, t->base >= 0x20 && t->base < 0x7f ? "inflate: * literal '%c'\n" : "inflate: * literal 0x%02x\n", t->base)); *q++ = (Byte)t->base; m--; continue; } for (;;) { DUMPBITS(t->bits) if (e & 16) { // get extra bits for length e &= 15; c = t->base + ((uInt)b & inflate_mask[e]); DUMPBITS(e) LuTracevv((stderr, "inflate: * length %u\n", c)); // decode distance base of block to copy GRABBITS(15); // max bits for distance code e = (t = td + ((uInt)b & md))->exop; for (;;) { DUMPBITS(t->bits) if (e & 16) { // get extra bits to add to distance base e &= 15; GRABBITS(e) // get extra bits (up to 13) d = t->base + ((uInt)b & inflate_mask[e]); DUMPBITS(e) LuTracevv((stderr, "inflate: * distance %u\n", d)); // do the copy m -= c; r = q - d; if (r < s->window) // wrap if needed { do { r += s->end - s->window; // force pointer in window } while (r < s->window); // covers invalid distances e = (uInt) (s->end - r); if (c > e) { c -= e; // wrapped copy do { *q++ = *r++; } while (--e); r = s->window; do { *q++ = *r++; } while (--c); } else // normal copy { *q++ = *r++; c--; *q++ = *r++; c--; do { *q++ = *r++; } while (--c); } } else /* normal copy */ { *q++ = *r++; c--; *q++ = *r++; c--; do { *q++ = *r++; } while (--c); } break; } else if ((e & 64) == 0) { t += t->base; e = (t += ((uInt)b & inflate_mask[e]))->exop; } else { z->msg = (char*)"invalid distance code"; UNGRAB UPDATE return Z_DATA_ERROR; } }; break; } if ((e & 64) == 0) { t += t->base; if ((e = (t += ((uInt)b & inflate_mask[e]))->exop) == 0) { DUMPBITS(t->bits) LuTracevv((stderr, t->base >= 0x20 && t->base < 0x7f ? "inflate: * literal '%c'\n" : "inflate: * literal 0x%02x\n", t->base)); *q++ = (Byte)t->base; m--; break; } } else if (e & 32) { LuTracevv((stderr, "inflate: * end of block\n")); UNGRAB UPDATE return Z_STREAM_END; } else { z->msg = (char*)"invalid literal/length code"; UNGRAB UPDATE return Z_DATA_ERROR; } }; } while (m >= 258 && n >= 10); // not enough input or output--restore pointers and return UNGRAB UPDATE return Z_OK; } // crc32.c -- compute the CRC-32 of a data stream // Copyright (C) 1995-1998 Mark Adler // For conditions of distribution and use, see copyright notice in zlib.h // @(#) $Id$ // Table of CRC-32's of all single-byte values (made by make_crc_table) const uLong crc_table[256] = { 0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L, 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L, 0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL, 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L, 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L, 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L, 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL, 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L, 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL, 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L, 0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L, 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L, 0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL, 0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL, 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L, 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL, 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L, 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L, 0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L, 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL, 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L, 0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L, 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL, 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L, 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L, 0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L, 0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L, 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L, 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL, 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL, 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L, 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L, 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL, 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL, 0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L, 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL, 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L, 0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L, 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL, 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L, 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L, 0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL, 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L, 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L, 0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L, 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L, 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L, 0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L, 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, 0x2d02ef8dL }; const uLong * get_crc_table() { return (const uLong *)crc_table; } #define CRC_DO1(buf) crc = crc_table[((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8); #define CRC_DO2(buf) CRC_DO1(buf); CRC_DO1(buf); #define CRC_DO4(buf) CRC_DO2(buf); CRC_DO2(buf); #define CRC_DO8(buf) CRC_DO4(buf); CRC_DO4(buf); uLong ucrc32(uLong crc, const Byte *buf, uInt len) { if (buf == Z_NULL) return 0L; crc = crc ^ 0xffffffffL; while (len >= 8) {CRC_DO8(buf); len -= 8;} if (len) do {CRC_DO1(buf);} while (--len); return crc ^ 0xffffffffL; } // ============================================================= // some decryption routines #define CRC32(c, b) (crc_table[((int)(c)^(b))&0xff]^((c)>>8)) void Uupdate_keys(unsigned long *keys, char c) { keys[0] = CRC32(keys[0],c); keys[1] += keys[0] & 0xFF; keys[1] = keys[1]*134775813L +1; keys[2] = CRC32(keys[2], keys[1] >> 24); } char Udecrypt_byte(unsigned long *keys) { unsigned temp = ((unsigned)keys[2] & 0xffff) | 2; return (char)(((temp * (temp ^ 1)) >> 8) & 0xff); } char zdecode(unsigned long *keys, char c) { c^=Udecrypt_byte(keys); Uupdate_keys(keys,c); return c; } // adler32.c -- compute the Adler-32 checksum of a data stream // Copyright (C) 1995-1998 Mark Adler // For conditions of distribution and use, see copyright notice in zlib.h // @(#) $Id$ #define BASE 65521L // largest prime smaller than 65536 #define NMAX 5552 // NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 #define AD_DO1(buf,i) {s1 += buf[i]; s2 += s1;} #define AD_DO2(buf,i) AD_DO1(buf,i); AD_DO1(buf,i+1); #define AD_DO4(buf,i) AD_DO2(buf,i); AD_DO2(buf,i+2); #define AD_DO8(buf,i) AD_DO4(buf,i); AD_DO4(buf,i+4); #define AD_DO16(buf) AD_DO8(buf,0); AD_DO8(buf,8); // ========================================================================= uLong adler32(uLong adler, const Byte *buf, uInt len) { unsigned long s1 = adler & 0xffff; unsigned long s2 = (adler >> 16) & 0xffff; int k; if (buf == Z_NULL) return 1L; while (len > 0) { k = len < NMAX ? len : NMAX; len -= k; while (k >= 16) { AD_DO16(buf); buf += 16; k -= 16; } if (k != 0) do { s1 += *buf++; s2 += s1; } while (--k); s1 %= BASE; s2 %= BASE; } return (s2 << 16) | s1; } // zutil.c -- target dependent utility functions for the compression library // Copyright (C) 1995-1998 Jean-loup Gailly. // For conditions of distribution and use, see copyright notice in zlib.h // @(#) $Id$ const char * zlibVersion() { return ZLIB_VERSION; } // exported to allow conversion of error code to string for compress() and // uncompress() const char * zError(int err) { return ERR_MSG(err); } voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) { if (opaque) items += size - size; // make compiler happy return (voidpf)calloc(items, size); } void zcfree (voidpf opaque, voidpf ptr) { zfree(ptr); if (opaque) return; // make compiler happy } // inflate.c -- zlib interface to inflate modules // Copyright (C) 1995-1998 Mark Adler // For conditions of distribution and use, see copyright notice in zlib.h //struct inflate_blocks_state {int dummy;}; // for buggy compilers typedef enum { IM_METHOD, // waiting for method byte IM_FLAG, // waiting for flag byte IM_DICT4, // four dictionary check bytes to go IM_DICT3, // three dictionary check bytes to go IM_DICT2, // two dictionary check bytes to go IM_DICT1, // one dictionary check byte to go IM_DICT0, // waiting for inflateSetDictionary IM_BLOCKS, // decompressing blocks IM_CHECK4, // four check bytes to go IM_CHECK3, // three check bytes to go IM_CHECK2, // two check bytes to go IM_CHECK1, // one check byte to go IM_DONE, // finished check, done IM_BAD} // got an error--stay here inflate_mode; // inflate private state struct internal_state { // mode inflate_mode mode; // current inflate mode // mode dependent information union { uInt method; // if IM_FLAGS, method byte struct { uLong was; // computed check value uLong need; // stream check value } check; // if CHECK, check values to compare uInt marker; // if IM_BAD, inflateSync's marker bytes count } sub; // submode // mode independent information int nowrap; // flag for no wrapper uInt wbits; // log2(window size) (8..15, defaults to 15) inflate_blocks_statef *blocks; // current inflate_blocks state }; int inflateReset(z_streamp z) { if (z == Z_NULL || z->state == Z_NULL) return Z_STREAM_ERROR; z->total_in = z->total_out = 0; z->msg = Z_NULL; z->state->mode = z->state->nowrap ? IM_BLOCKS : IM_METHOD; inflate_blocks_reset(z->state->blocks, z, Z_NULL); LuTracev((stderr, "inflate: reset\n")); return Z_OK; } int inflateEnd(z_streamp z) { if (z == Z_NULL || z->state == Z_NULL || z->zfree == Z_NULL) return Z_STREAM_ERROR; if (z->state->blocks != Z_NULL) inflate_blocks_free(z->state->blocks, z); ZFREE(z, z->state); z->state = Z_NULL; LuTracev((stderr, "inflate: end\n")); return Z_OK; } int inflateInit2(z_streamp z) { const char *version = ZLIB_VERSION; int stream_size = sizeof(z_stream); if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || stream_size != sizeof(z_stream)) return Z_VERSION_ERROR; int w = -15; // MAX_WBITS: 32K LZ77 window. // Warning: reducing MAX_WBITS makes minigzip unable to extract .gz files created by gzip. // The memory requirements for deflate are (in bytes): // (1 << (windowBits+2)) + (1 << (memLevel+9)) // that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) // plus a few kilobytes for small objects. For example, if you want to reduce // the default memory requirements from 256K to 128K, compile with // make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" // Of course this will generally degrade compression (there's no free lunch). // // The memory requirements for inflate are (in bytes) 1 << windowBits // that is, 32K for windowBits=15 (default value) plus a few kilobytes // for small objects. // initialize state if (z == Z_NULL) return Z_STREAM_ERROR; z->msg = Z_NULL; if (z->zalloc == Z_NULL) { z->zalloc = zcalloc; z->opaque = (voidpf)0; } if (z->zfree == Z_NULL) z->zfree = zcfree; if ((z->state = (struct internal_state *) ZALLOC(z,1,sizeof(struct internal_state))) == Z_NULL) return Z_MEM_ERROR; z->state->blocks = Z_NULL; // handle undocumented nowrap option (no zlib header or check) z->state->nowrap = 0; if (w < 0) { w = - w; z->state->nowrap = 1; } // set window size if (w < 8 || w > 15) { inflateEnd(z); return Z_STREAM_ERROR; } z->state->wbits = (uInt)w; // create inflate_blocks state if ((z->state->blocks = inflate_blocks_new(z, z->state->nowrap ? Z_NULL : adler32, (uInt)1 << w)) == Z_NULL) { inflateEnd(z); return Z_MEM_ERROR; } LuTracev((stderr, "inflate: allocated\n")); // reset state inflateReset(z); return Z_OK; } #define IM_NEEDBYTE {if(z->avail_in==0)return r;r=f;} #define IM_NEXTBYTE (z->avail_in--,z->total_in++,*z->next_in++) int inflate(z_streamp z, int f) { int r; uInt b; if (z == Z_NULL || z->state == Z_NULL || z->next_in == Z_NULL) return Z_STREAM_ERROR; f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK; r = Z_BUF_ERROR; for (;;) switch (z->state->mode) { case IM_METHOD: IM_NEEDBYTE if (((z->state->sub.method = IM_NEXTBYTE) & 0xf) != Z_DEFLATED) { z->state->mode = IM_BAD; z->msg = (char*)"unknown compression method"; z->state->sub.marker = 5; // can't try inflateSync break; } if ((z->state->sub.method >> 4) + 8 > z->state->wbits) { z->state->mode = IM_BAD; z->msg = (char*)"invalid window size"; z->state->sub.marker = 5; // can't try inflateSync break; } z->state->mode = IM_FLAG; case IM_FLAG: IM_NEEDBYTE b = IM_NEXTBYTE; if (((z->state->sub.method << 8) + b) % 31) { z->state->mode = IM_BAD; z->msg = (char*)"incorrect header check"; z->state->sub.marker = 5; // can't try inflateSync break; } LuTracev((stderr, "inflate: zlib header ok\n")); if (!(b & PRESET_DICT)) { z->state->mode = IM_BLOCKS; break; } z->state->mode = IM_DICT4; case IM_DICT4: IM_NEEDBYTE z->state->sub.check.need = (uLong)IM_NEXTBYTE << 24; z->state->mode = IM_DICT3; case IM_DICT3: IM_NEEDBYTE z->state->sub.check.need += (uLong)IM_NEXTBYTE << 16; z->state->mode = IM_DICT2; case IM_DICT2: IM_NEEDBYTE z->state->sub.check.need += (uLong)IM_NEXTBYTE << 8; z->state->mode = IM_DICT1; case IM_DICT1: IM_NEEDBYTE; r; z->state->sub.check.need += (uLong)IM_NEXTBYTE; z->adler = z->state->sub.check.need; z->state->mode = IM_DICT0; return Z_NEED_DICT; case IM_DICT0: z->state->mode = IM_BAD; z->msg = (char*)"need dictionary"; z->state->sub.marker = 0; // can try inflateSync return Z_STREAM_ERROR; case IM_BLOCKS: r = inflate_blocks(z->state->blocks, z, r); if (r == Z_DATA_ERROR) { z->state->mode = IM_BAD; z->state->sub.marker = 0; // can try inflateSync break; } if (r == Z_OK) r = f; if (r != Z_STREAM_END) return r; r = f; inflate_blocks_reset(z->state->blocks, z, &z->state->sub.check.was); if (z->state->nowrap) { z->state->mode = IM_DONE; break; } z->state->mode = IM_CHECK4; case IM_CHECK4: IM_NEEDBYTE z->state->sub.check.need = (uLong)IM_NEXTBYTE << 24; z->state->mode = IM_CHECK3; case IM_CHECK3: IM_NEEDBYTE z->state->sub.check.need += (uLong)IM_NEXTBYTE << 16; z->state->mode = IM_CHECK2; case IM_CHECK2: IM_NEEDBYTE z->state->sub.check.need += (uLong)IM_NEXTBYTE << 8; z->state->mode = IM_CHECK1; case IM_CHECK1: IM_NEEDBYTE z->state->sub.check.need += (uLong)IM_NEXTBYTE; if (z->state->sub.check.was != z->state->sub.check.need) { z->state->mode = IM_BAD; z->msg = (char*)"incorrect data check"; z->state->sub.marker = 5; // can't try inflateSync break; } LuTracev((stderr, "inflate: zlib check ok\n")); z->state->mode = IM_DONE; case IM_DONE: return Z_STREAM_END; case IM_BAD: return Z_DATA_ERROR; default: return Z_STREAM_ERROR; } } // unzip.c -- IO on .zip files using zlib // Version 0.15 beta, Mar 19th, 1998, // Read unzip.h for more info #define UNZ_BUFSIZE (16384) #define UNZ_MAXFILENAMEINZIP (256) #define SIZECENTRALDIRITEM (0x2e) #define SIZEZIPLOCALHEADER (0x1e) const char unz_copyright[] = " unzip 0.15 Copyright 1998 Gilles Vollant "; // unz_file_info_interntal contain internal info about a file in zipfile typedef struct unz_file_info_internal_s { uLong offset_curfile;// relative offset of local header 4 bytes } unz_file_info_internal; typedef struct { bool is_handle; // either a handle or memory bool canseek; // for handles: HANDLE h; bool herr; unsigned long initial_offset; bool mustclosehandle; // for memory: void *buf; unsigned int len,pos; // if it's a memory block } LUFILE; LUFILE *lufopen(void *z,unsigned int len,DWORD flags,ZRESULT *err) { if (flags!=ZIP_HANDLE && flags!=ZIP_FILENAME && flags!=ZIP_MEMORY) {*err=ZR_ARGS; return NULL;} // HANDLE h=0; bool canseek=false; *err=ZR_OK; bool mustclosehandle=false; if (flags==ZIP_HANDLE||flags==ZIP_FILENAME) { if (flags==ZIP_HANDLE) { HANDLE hf = z; h=hf; mustclosehandle=false; #ifdef DuplicateHandle BOOL res = DuplicateHandle(GetCurrentProcess(),hf,GetCurrentProcess(),&h,0,FALSE,DUPLICATE_SAME_ACCESS); if (!res) mustclosehandle=true; #endif } else { h=CreateFile((const TCHAR*)z,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); if (h==INVALID_HANDLE_VALUE) {*err=ZR_NOFILE; return NULL;} mustclosehandle=true; } // test if we can seek on it. We can't use GetFileType(h)==FILE_TYPE_DISK since it's not on CE. DWORD res = SetFilePointer(h,0,0,FILE_CURRENT); canseek = (res!=0xFFFFFFFF); } LUFILE *lf = new LUFILE; if (flags==ZIP_HANDLE||flags==ZIP_FILENAME) { lf->is_handle=true; lf->mustclosehandle=mustclosehandle; lf->canseek=canseek; lf->h=h; lf->herr=false; lf->initial_offset=0; if (canseek) lf->initial_offset = SetFilePointer(h,0,NULL,FILE_CURRENT); } else { lf->is_handle=false; lf->canseek=true; lf->mustclosehandle=false; lf->buf=z; lf->len=len; lf->pos=0; lf->initial_offset=0; } *err=ZR_OK; return lf; } int lufclose(LUFILE *stream) { if (stream==NULL) return EOF; if (stream->mustclosehandle) CloseHandle(stream->h); delete stream; return 0; } int luferror(LUFILE *stream) { if (stream->is_handle && stream->herr) return 1; else return 0; } long int luftell(LUFILE *stream) { if (stream->is_handle && stream->canseek) return SetFilePointer(stream->h,0,NULL,FILE_CURRENT)-stream->initial_offset; else if (stream->is_handle) return 0; else return stream->pos; } int lufseek(LUFILE *stream, long offset, int whence) { if (stream->is_handle && stream->canseek) { if (whence==SEEK_SET) SetFilePointer(stream->h,stream->initial_offset+offset,0,FILE_BEGIN); else if (whence==SEEK_CUR) SetFilePointer(stream->h,offset,NULL,FILE_CURRENT); else if (whence==SEEK_END) SetFilePointer(stream->h,offset,NULL,FILE_END); else return 19; // EINVAL return 0; } else if (stream->is_handle) return 29; // ESPIPE else { if (whence==SEEK_SET) stream->pos=offset; else if (whence==SEEK_CUR) stream->pos+=offset; else if (whence==SEEK_END) stream->pos=stream->len+offset; return 0; } } size_t lufread(void *ptr,size_t size,size_t n,LUFILE *stream) { unsigned int toread = (unsigned int)(size*n); if (stream->is_handle) { DWORD red; BOOL res = ReadFile(stream->h,ptr,toread,&red,NULL); if (!res) stream->herr=true; return red/size; } if (stream->pos+toread > stream->len) toread = stream->len-stream->pos; memcpy(ptr, (char*)stream->buf + stream->pos, toread); DWORD red = toread; stream->pos += red; return red/size; } // file_in_zip_read_info_s contain internal information about a file in zipfile, // when reading and decompress it typedef struct { char *read_buffer; // internal buffer for compressed data z_stream stream; // zLib stream structure for inflate uLong pos_in_zipfile; // position in byte on the zipfile, for fseek uLong stream_initialised; // flag set if stream structure is initialised uLong offset_local_extrafield;// offset of the local extra field uInt size_local_extrafield;// size of the local extra field uLong pos_local_extrafield; // position in the local extra field in read uLong crc32; // crc32 of all data uncompressed uLong crc32_wait; // crc32 we must obtain after decompress all uLong rest_read_compressed; // number of byte to be decompressed uLong rest_read_uncompressed;//number of byte to be obtained after decomp LUFILE* file; // io structore of the zipfile uLong compression_method; // compression method (0==store) uLong byte_before_the_zipfile;// byte before the zipfile, (>0 for sfx) bool encrypted; // is it encrypted? unsigned long keys[3]; // decryption keys, initialized by unzOpenCurrentFile int encheadleft; // the first call(s) to unzReadCurrentFile will read this many encryption-header bytes first char crcenctest; // if encrypted, we'll check the encryption buffer against this } file_in_zip_read_info_s; // unz_s contain internal information about the zipfile typedef struct { LUFILE* file; // io structore of the zipfile unz_global_info gi; // public global information uLong byte_before_the_zipfile;// byte before the zipfile, (>0 for sfx) uLong num_file; // number of the current file in the zipfile uLong pos_in_central_dir; // pos of the current file in the central dir uLong current_file_ok; // flag about the usability of the current file uLong central_pos; // position of the beginning of the central dir uLong size_central_dir; // size of the central directory uLong offset_central_dir; // offset of start of central directory with respect to the starting disk number unz_file_info cur_file_info; // public info about the current file in zip unz_file_info_internal cur_file_info_internal; // private info about it file_in_zip_read_info_s* pfile_in_zip_read; // structure about the current file if we are decompressing it } unz_s, *unzFile; int unzStringFileNameCompare (const char* fileName1,const char* fileName2,int iCaseSensitivity); // Compare two filename (fileName1,fileName2). z_off_t unztell (unzFile file); // Give the current position in uncompressed data int unzeof (unzFile file); // return 1 if the end of file was reached, 0 elsewhere int unzGetLocalExtrafield (unzFile file, voidp buf, unsigned len); // Read extra field from the current file (opened by unzOpenCurrentFile) // This is the local-header version of the extra field (sometimes, there is // more info in the local-header version than in the central-header) // // if buf==NULL, it return the size of the local extra field // // if buf!=NULL, len is the size of the buffer, the extra header is copied in // buf. // the return value is the number of bytes copied in buf, or (if <0) // the error code // =========================================================================== // Read a byte from a gz_stream; update next_in and avail_in. Return EOF // for end of file. // IN assertion: the stream s has been sucessfully opened for reading. int unzlocal_getByte(LUFILE *fin,int *pi) { unsigned char c; int err = (int)lufread(&c, 1, 1, fin); if (err==1) { *pi = (int)c; return UNZ_OK; } else { if (luferror(fin)) return UNZ_ERRNO; else return UNZ_EOF; } } // =========================================================================== // Reads a long in LSB order from the given gz_stream. Sets int unzlocal_getShort (LUFILE *fin,uLong *pX) { uLong x ; int i; int err; err = unzlocal_getByte(fin,&i); x = (uLong)i; if (err==UNZ_OK) err = unzlocal_getByte(fin,&i); x += ((uLong)i)<<8; if (err==UNZ_OK) *pX = x; else *pX = 0; return err; } int unzlocal_getLong (LUFILE *fin,uLong *pX) { uLong x ; int i; int err; err = unzlocal_getByte(fin,&i); x = (uLong)i; if (err==UNZ_OK) err = unzlocal_getByte(fin,&i); x += ((uLong)i)<<8; if (err==UNZ_OK) err = unzlocal_getByte(fin,&i); x += ((uLong)i)<<16; if (err==UNZ_OK) err = unzlocal_getByte(fin,&i); x += ((uLong)i)<<24; if (err==UNZ_OK) *pX = x; else *pX = 0; return err; } // My own strcmpi / strcasecmp int strcmpcasenosensitive_internal (const char* fileName1,const char *fileName2) { for (;;) { char c1=*(fileName1++); char c2=*(fileName2++); if ((c1>='a') && (c1<='z')) c1 -= (char)0x20; if ((c2>='a') && (c2<='z')) c2 -= (char)0x20; if (c1=='\0') return ((c2=='\0') ? 0 : -1); if (c2=='\0') return 1; if (c1<c2) return -1; if (c1>c2) return 1; } } // // Compare two filename (fileName1,fileName2). // If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) // If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi or strcasecmp) // int unzStringFileNameCompare (const char*fileName1,const char*fileName2,int iCaseSensitivity) { if (iCaseSensitivity==1) return strcmp(fileName1,fileName2); else return strcmpcasenosensitive_internal(fileName1,fileName2); } #define BUFREADCOMMENT (0x400) // Locate the Central directory of a zipfile (at the end, just before // the global comment). Lu bugfix 2005.07.26 - returns 0xFFFFFFFF if not found, // rather than 0, since 0 is a valid central-dir-location for an empty zipfile. uLong unzlocal_SearchCentralDir(LUFILE *fin) { if (lufseek(fin,0,SEEK_END) != 0) return 0xFFFFFFFF; uLong uSizeFile = luftell(fin); uLong uMaxBack=0xffff; // maximum size of global comment if (uMaxBack>uSizeFile) uMaxBack = uSizeFile; unsigned char *buf = (unsigned char*)zmalloc(BUFREADCOMMENT+4); if (buf==NULL) return 0xFFFFFFFF; uLong uPosFound=0xFFFFFFFF; uLong uBackRead = 4; while (uBackRead<uMaxBack) { uLong uReadSize,uReadPos ; int i; if (uBackRead+BUFREADCOMMENT>uMaxBack) uBackRead = uMaxBack; else uBackRead+=BUFREADCOMMENT; uReadPos = uSizeFile-uBackRead ; uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? (BUFREADCOMMENT+4) : (uSizeFile-uReadPos); if (lufseek(fin,uReadPos,SEEK_SET)!=0) break; if (lufread(buf,(uInt)uReadSize,1,fin)!=1) break; for (i=(int)uReadSize-3; (i--)>=0;) { if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06)) { uPosFound = uReadPos+i; break; } } if (uPosFound!=0) break; } if (buf) zfree(buf); return uPosFound; } int unzGoToFirstFile (unzFile file); int unzCloseCurrentFile (unzFile file); // Open a Zip file. // If the zipfile cannot be opened (file don't exist or in not valid), return NULL. // Otherwise, the return value is a unzFile Handle, usable with other unzip functions unzFile unzOpenInternal(LUFILE *fin) { if (fin==NULL) return NULL; if (unz_copyright[0]!=' ') {lufclose(fin); return NULL;} int err=UNZ_OK; unz_s us; uLong central_pos,uL; central_pos = unzlocal_SearchCentralDir(fin); if (central_pos==0xFFFFFFFF) err=UNZ_ERRNO; if (lufseek(fin,central_pos,SEEK_SET)!=0) err=UNZ_ERRNO; // the signature, already checked if (unzlocal_getLong(fin,&uL)!=UNZ_OK) err=UNZ_ERRNO; // number of this disk uLong number_disk; // number of the current dist, used for spanning ZIP, unsupported, always 0 if (unzlocal_getShort(fin,&number_disk)!=UNZ_OK) err=UNZ_ERRNO; // number of the disk with the start of the central directory uLong number_disk_with_CD; // number the the disk with central dir, used for spaning ZIP, unsupported, always 0 if (unzlocal_getShort(fin,&number_disk_with_CD)!=UNZ_OK) err=UNZ_ERRNO; // total number of entries in the central dir on this disk if (unzlocal_getShort(fin,&us.gi.number_entry)!=UNZ_OK) err=UNZ_ERRNO; // total number of entries in the central dir uLong number_entry_CD; // total number of entries in the central dir (same than number_entry on nospan) if (unzlocal_getShort(fin,&number_entry_CD)!=UNZ_OK) err=UNZ_ERRNO; if ((number_entry_CD!=us.gi.number_entry) || (number_disk_with_CD!=0) || (number_disk!=0)) err=UNZ_BADZIPFILE; // size of the central directory if (unzlocal_getLong(fin,&us.size_central_dir)!=UNZ_OK) err=UNZ_ERRNO; // offset of start of central directory with respect to the starting disk number if (unzlocal_getLong(fin,&us.offset_central_dir)!=UNZ_OK) err=UNZ_ERRNO; // zipfile comment length if (unzlocal_getShort(fin,&us.gi.size_comment)!=UNZ_OK) err=UNZ_ERRNO; if ((central_pos+fin->initial_offset<us.offset_central_dir+us.size_central_dir) && (err==UNZ_OK)) err=UNZ_BADZIPFILE; if (err!=UNZ_OK) {lufclose(fin);return NULL;} us.file=fin; us.byte_before_the_zipfile = central_pos+fin->initial_offset - (us.offset_central_dir+us.size_central_dir); us.central_pos = central_pos; us.pfile_in_zip_read = NULL; fin->initial_offset = 0; // since the zipfile itself is expected to handle this unz_s *s = (unz_s*)zmalloc(sizeof(unz_s)); *s=us; unzGoToFirstFile((unzFile)s); return (unzFile)s; } // Close a ZipFile opened with unzipOpen. // If there is files inside the .Zip opened with unzipOpenCurrentFile (see later), // these files MUST be closed with unzipCloseCurrentFile before call unzipClose. // return UNZ_OK if there is no problem. int unzClose (unzFile file) { unz_s* s; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; if (s->pfile_in_zip_read!=NULL) unzCloseCurrentFile(file); lufclose(s->file); if (s) zfree(s); // unused s=0; return UNZ_OK; } // Write info about the ZipFile in the *pglobal_info structure. // No preparation of the structure is needed // return UNZ_OK if there is no problem. int unzGetGlobalInfo (unzFile file,unz_global_info *pglobal_info) { unz_s* s; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; *pglobal_info=s->gi; return UNZ_OK; } // Translate date/time from Dos format to tm_unz (readable more easilty) void unzlocal_DosDateToTmuDate (uLong ulDosDate, tm_unz* ptm) { uLong uDate; uDate = (uLong)(ulDosDate>>16); ptm->tm_mday = (uInt)(uDate&0x1f) ; ptm->tm_mon = (uInt)((((uDate)&0x1E0)/0x20)-1) ; ptm->tm_year = (uInt)(((uDate&0x0FE00)/0x0200)+1980) ; ptm->tm_hour = (uInt) ((ulDosDate &0xF800)/0x800); ptm->tm_min = (uInt) ((ulDosDate&0x7E0)/0x20) ; ptm->tm_sec = (uInt) (2*(ulDosDate&0x1f)) ; } // Get Info about the current file in the zipfile, with internal only info int unzlocal_GetCurrentFileInfoInternal (unzFile file, unz_file_info *pfile_info, unz_file_info_internal *pfile_info_internal, char *szFileName, uLong fileNameBufferSize, void *extraField, uLong extraFieldBufferSize, char *szComment, uLong commentBufferSize); int unzlocal_GetCurrentFileInfoInternal (unzFile file, unz_file_info *pfile_info, unz_file_info_internal *pfile_info_internal, char *szFileName, uLong fileNameBufferSize, void *extraField, uLong extraFieldBufferSize, char *szComment, uLong commentBufferSize) { unz_s* s; unz_file_info file_info; unz_file_info_internal file_info_internal; int err=UNZ_OK; uLong uMagic; long lSeek=0; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; if (lufseek(s->file,s->pos_in_central_dir+s->byte_before_the_zipfile,SEEK_SET)!=0) err=UNZ_ERRNO; // we check the magic if (err==UNZ_OK) if (unzlocal_getLong(s->file,&uMagic) != UNZ_OK) err=UNZ_ERRNO; else if (uMagic!=0x02014b50) err=UNZ_BADZIPFILE; if (unzlocal_getShort(s->file,&file_info.version) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(s->file,&file_info.version_needed) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(s->file,&file_info.flag) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(s->file,&file_info.compression_method) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getLong(s->file,&file_info.dosDate) != UNZ_OK) err=UNZ_ERRNO; unzlocal_DosDateToTmuDate(file_info.dosDate,&file_info.tmu_date); if (unzlocal_getLong(s->file,&file_info.crc) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getLong(s->file,&file_info.compressed_size) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getLong(s->file,&file_info.uncompressed_size) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(s->file,&file_info.size_filename) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(s->file,&file_info.size_file_extra) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(s->file,&file_info.size_file_comment) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(s->file,&file_info.disk_num_start) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(s->file,&file_info.internal_fa) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getLong(s->file,&file_info.external_fa) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getLong(s->file,&file_info_internal.offset_curfile) != UNZ_OK) err=UNZ_ERRNO; lSeek+=file_info.size_filename; if ((err==UNZ_OK) && (szFileName!=NULL)) { uLong uSizeRead ; if (file_info.size_filename<fileNameBufferSize) { *(szFileName+file_info.size_filename)='\0'; uSizeRead = file_info.size_filename; } else uSizeRead = fileNameBufferSize; if ((file_info.size_filename>0) && (fileNameBufferSize>0)) if (lufread(szFileName,(uInt)uSizeRead,1,s->file)!=1) err=UNZ_ERRNO; lSeek -= uSizeRead; } if ((err==UNZ_OK) && (extraField!=NULL)) { uLong uSizeRead ; if (file_info.size_file_extra<extraFieldBufferSize) uSizeRead = file_info.size_file_extra; else uSizeRead = extraFieldBufferSize; if (lSeek!=0) if (lufseek(s->file,lSeek,SEEK_CUR)==0) lSeek=0; else err=UNZ_ERRNO; if ((file_info.size_file_extra>0) && (extraFieldBufferSize>0)) if (lufread(extraField,(uInt)uSizeRead,1,s->file)!=1) err=UNZ_ERRNO; lSeek += file_info.size_file_extra - uSizeRead; } else lSeek+=file_info.size_file_extra; if ((err==UNZ_OK) && (szComment!=NULL)) { uLong uSizeRead ; if (file_info.size_file_comment<commentBufferSize) { *(szComment+file_info.size_file_comment)='\0'; uSizeRead = file_info.size_file_comment; } else uSizeRead = commentBufferSize; if (lSeek!=0) if (lufseek(s->file,lSeek,SEEK_CUR)==0) {} // unused lSeek=0; else err=UNZ_ERRNO; if ((file_info.size_file_comment>0) && (commentBufferSize>0)) if (lufread(szComment,(uInt)uSizeRead,1,s->file)!=1) err=UNZ_ERRNO; //unused lSeek+=file_info.size_file_comment - uSizeRead; } else {} //unused lSeek+=file_info.size_file_comment; if ((err==UNZ_OK) && (pfile_info!=NULL)) *pfile_info=file_info; if ((err==UNZ_OK) && (pfile_info_internal!=NULL)) *pfile_info_internal=file_info_internal; return err; } // Write info about the ZipFile in the *pglobal_info structure. // No preparation of the structure is needed // return UNZ_OK if there is no problem. int unzGetCurrentFileInfo (unzFile file, unz_file_info *pfile_info, char *szFileName, uLong fileNameBufferSize, void *extraField, uLong extraFieldBufferSize, char *szComment, uLong commentBufferSize) { return unzlocal_GetCurrentFileInfoInternal(file,pfile_info,NULL,szFileName,fileNameBufferSize, extraField,extraFieldBufferSize, szComment,commentBufferSize); } // Set the current file of the zipfile to the first file. // return UNZ_OK if there is no problem int unzGoToFirstFile (unzFile file) { int err; unz_s* s; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; s->pos_in_central_dir=s->offset_central_dir; s->num_file=0; err=unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info, &s->cur_file_info_internal, NULL,0,NULL,0,NULL,0); s->current_file_ok = (err == UNZ_OK); return err; } // Set the current file of the zipfile to the next file. // return UNZ_OK if there is no problem // return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. int unzGoToNextFile (unzFile file) { unz_s* s; int err; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; if (!s->current_file_ok) return UNZ_END_OF_LIST_OF_FILE; if (s->num_file+1==s->gi.number_entry) return UNZ_END_OF_LIST_OF_FILE; s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename + s->cur_file_info.size_file_extra + s->cur_file_info.size_file_comment ; s->num_file++; err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info, &s->cur_file_info_internal, NULL,0,NULL,0,NULL,0); s->current_file_ok = (err == UNZ_OK); return err; } // Try locate the file szFileName in the zipfile. // For the iCaseSensitivity signification, see unzStringFileNameCompare // return value : // UNZ_OK if the file is found. It becomes the current file. // UNZ_END_OF_LIST_OF_FILE if the file is not found int unzLocateFile (unzFile file, const char *szFileName, int iCaseSensitivity) { unz_s* s; int err; uLong num_fileSaved; uLong pos_in_central_dirSaved; if (file==NULL) return UNZ_PARAMERROR; if (strlen(szFileName)>=UNZ_MAXFILENAMEINZIP) return UNZ_PARAMERROR; s=(unz_s*)file; if (!s->current_file_ok) return UNZ_END_OF_LIST_OF_FILE; num_fileSaved = s->num_file; pos_in_central_dirSaved = s->pos_in_central_dir; err = unzGoToFirstFile(file); while (err == UNZ_OK) { char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1]; unzGetCurrentFileInfo(file,NULL, szCurrentFileName,sizeof(szCurrentFileName)-1, NULL,0,NULL,0); if (unzStringFileNameCompare(szCurrentFileName,szFileName,iCaseSensitivity)==0) return UNZ_OK; err = unzGoToNextFile(file); } s->num_file = num_fileSaved ; s->pos_in_central_dir = pos_in_central_dirSaved ; return err; } // Read the local header of the current zipfile // Check the coherency of the local header and info in the end of central // directory about this file // store in *piSizeVar the size of extra info in local header // (filename and size of extra field data) int unzlocal_CheckCurrentFileCoherencyHeader (unz_s *s,uInt *piSizeVar, uLong *poffset_local_extrafield, uInt *psize_local_extrafield) { uLong uMagic,uData,uFlags; uLong size_filename; uLong size_extra_field; int err=UNZ_OK; *piSizeVar = 0; *poffset_local_extrafield = 0; *psize_local_extrafield = 0; if (lufseek(s->file,s->cur_file_info_internal.offset_curfile + s->byte_before_the_zipfile,SEEK_SET)!=0) return UNZ_ERRNO; if (err==UNZ_OK) if (unzlocal_getLong(s->file,&uMagic) != UNZ_OK) err=UNZ_ERRNO; else if (uMagic!=0x04034b50) err=UNZ_BADZIPFILE; if (unzlocal_getShort(s->file,&uData) != UNZ_OK) err=UNZ_ERRNO; // else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion)) // err=UNZ_BADZIPFILE; if (unzlocal_getShort(s->file,&uFlags) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(s->file,&uData) != UNZ_OK) err=UNZ_ERRNO; else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compression_method)) err=UNZ_BADZIPFILE; if ((err==UNZ_OK) && (s->cur_file_info.compression_method!=0) && (s->cur_file_info.compression_method!=Z_DEFLATED)) err=UNZ_BADZIPFILE; if (unzlocal_getLong(s->file,&uData) != UNZ_OK) // date/time err=UNZ_ERRNO; if (unzlocal_getLong(s->file,&uData) != UNZ_OK) // crc err=UNZ_ERRNO; else if ((err==UNZ_OK) && (uData!=s->cur_file_info.crc) && ((uFlags & 8)==0)) err=UNZ_BADZIPFILE; if (unzlocal_getLong(s->file,&uData) != UNZ_OK) // size compr err=UNZ_ERRNO; else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compressed_size) && ((uFlags & 8)==0)) err=UNZ_BADZIPFILE; if (unzlocal_getLong(s->file,&uData) != UNZ_OK) // size uncompr err=UNZ_ERRNO; else if ((err==UNZ_OK) && (uData!=s->cur_file_info.uncompressed_size) && ((uFlags & 8)==0)) err=UNZ_BADZIPFILE; if (unzlocal_getShort(s->file,&size_filename) != UNZ_OK) err=UNZ_ERRNO; else if ((err==UNZ_OK) && (size_filename!=s->cur_file_info.size_filename)) err=UNZ_BADZIPFILE; *piSizeVar += (uInt)size_filename; if (unzlocal_getShort(s->file,&size_extra_field) != UNZ_OK) err=UNZ_ERRNO; *poffset_local_extrafield= s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER + size_filename; *psize_local_extrafield = (uInt)size_extra_field; *piSizeVar += (uInt)size_extra_field; return err; } // Open for reading data the current file in the zipfile. // If there is no error and the file is opened, the return value is UNZ_OK. int unzOpenCurrentFile (unzFile file, const char *password) { int err; int Store; uInt iSizeVar; unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; uLong offset_local_extrafield; // offset of the local extra field uInt size_local_extrafield; // size of the local extra field if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; if (!s->current_file_ok) return UNZ_PARAMERROR; if (s->pfile_in_zip_read != NULL) unzCloseCurrentFile(file); if (unzlocal_CheckCurrentFileCoherencyHeader(s,&iSizeVar, &offset_local_extrafield,&size_local_extrafield)!=UNZ_OK) return UNZ_BADZIPFILE; pfile_in_zip_read_info = (file_in_zip_read_info_s*)zmalloc(sizeof(file_in_zip_read_info_s)); if (pfile_in_zip_read_info==NULL) return UNZ_INTERNALERROR; pfile_in_zip_read_info->read_buffer=(char*)zmalloc(UNZ_BUFSIZE); pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield; pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield; pfile_in_zip_read_info->pos_local_extrafield=0; if (pfile_in_zip_read_info->read_buffer==NULL) { if (pfile_in_zip_read_info!=0) zfree(pfile_in_zip_read_info); //unused pfile_in_zip_read_info=0; return UNZ_INTERNALERROR; } pfile_in_zip_read_info->stream_initialised=0; if ((s->cur_file_info.compression_method!=0) && (s->cur_file_info.compression_method!=Z_DEFLATED)) { // unused err=UNZ_BADZIPFILE; } Store = s->cur_file_info.compression_method==0; pfile_in_zip_read_info->crc32_wait=s->cur_file_info.crc; pfile_in_zip_read_info->crc32=0; pfile_in_zip_read_info->compression_method = s->cur_file_info.compression_method; pfile_in_zip_read_info->file=s->file; pfile_in_zip_read_info->byte_before_the_zipfile=s->byte_before_the_zipfile; pfile_in_zip_read_info->stream.total_out = 0; if (!Store) { pfile_in_zip_read_info->stream.zalloc = (alloc_func)0; pfile_in_zip_read_info->stream.zfree = (free_func)0; pfile_in_zip_read_info->stream.opaque = (voidpf)0; err=inflateInit2(&pfile_in_zip_read_info->stream); if (err == Z_OK) pfile_in_zip_read_info->stream_initialised=1; // windowBits is passed < 0 to tell that there is no zlib header. // Note that in this case inflate *requires* an extra "dummy" byte // after the compressed stream in order to complete decompression and // return Z_STREAM_END. // In unzip, i don't wait absolutely Z_STREAM_END because I known the // size of both compressed and uncompressed data } pfile_in_zip_read_info->rest_read_compressed = s->cur_file_info.compressed_size ; pfile_in_zip_read_info->rest_read_uncompressed = s->cur_file_info.uncompressed_size ; pfile_in_zip_read_info->encrypted = (s->cur_file_info.flag&1)!=0; bool extlochead = (s->cur_file_info.flag&8)!=0; if (extlochead) pfile_in_zip_read_info->crcenctest = (char)((s->cur_file_info.dosDate>>8)&0xff); else pfile_in_zip_read_info->crcenctest = (char)(s->cur_file_info.crc >> 24); pfile_in_zip_read_info->encheadleft = (pfile_in_zip_read_info->encrypted?12:0); pfile_in_zip_read_info->keys[0] = 305419896L; pfile_in_zip_read_info->keys[1] = 591751049L; pfile_in_zip_read_info->keys[2] = 878082192L; for (const char *cp=password; cp!=0 && *cp!=0; cp++) Uupdate_keys(pfile_in_zip_read_info->keys,*cp); pfile_in_zip_read_info->pos_in_zipfile = s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER + iSizeVar; pfile_in_zip_read_info->stream.avail_in = (uInt)0; s->pfile_in_zip_read = pfile_in_zip_read_info; return UNZ_OK; } // Read bytes from the current file. // buf contain buffer where data must be copied // len the size of buf. // return the number of byte copied if somes bytes are copied (and also sets *reached_eof) // return 0 if the end of file was reached. (and also sets *reached_eof). // return <0 with error code if there is an error. (in which case *reached_eof is meaningless) // (UNZ_ERRNO for IO error, or zLib error for uncompress error) int unzReadCurrentFile (unzFile file, voidp buf, unsigned len, bool *reached_eof) { int err=UNZ_OK; uInt iRead = 0; if (reached_eof!=0) *reached_eof=false; unz_s *s = (unz_s*)file; if (s==NULL) return UNZ_PARAMERROR; file_in_zip_read_info_s* pfile_in_zip_read_info = s->pfile_in_zip_read; if (pfile_in_zip_read_info==NULL) return UNZ_PARAMERROR; if ((pfile_in_zip_read_info->read_buffer == NULL)) return UNZ_END_OF_LIST_OF_FILE; if (len==0) return 0; pfile_in_zip_read_info->stream.next_out = (Byte*)buf; pfile_in_zip_read_info->stream.avail_out = (uInt)len; if (len>pfile_in_zip_read_info->rest_read_uncompressed) { pfile_in_zip_read_info->stream.avail_out = (uInt)pfile_in_zip_read_info->rest_read_uncompressed; } while (pfile_in_zip_read_info->stream.avail_out>0) { if ((pfile_in_zip_read_info->stream.avail_in==0) && (pfile_in_zip_read_info->rest_read_compressed>0)) { uInt uReadThis = UNZ_BUFSIZE; if (pfile_in_zip_read_info->rest_read_compressed<uReadThis) uReadThis = (uInt)pfile_in_zip_read_info->rest_read_compressed; if (uReadThis == 0) {if (reached_eof!=0) *reached_eof=true; return UNZ_EOF;} if (lufseek(pfile_in_zip_read_info->file, pfile_in_zip_read_info->pos_in_zipfile + pfile_in_zip_read_info->byte_before_the_zipfile,SEEK_SET)!=0) return UNZ_ERRNO; if (lufread(pfile_in_zip_read_info->read_buffer,uReadThis,1,pfile_in_zip_read_info->file)!=1) return UNZ_ERRNO; pfile_in_zip_read_info->pos_in_zipfile += uReadThis; pfile_in_zip_read_info->rest_read_compressed-=uReadThis; pfile_in_zip_read_info->stream.next_in = (Byte*)pfile_in_zip_read_info->read_buffer; pfile_in_zip_read_info->stream.avail_in = (uInt)uReadThis; // if (pfile_in_zip_read_info->encrypted) { char *buf = (char*)pfile_in_zip_read_info->stream.next_in; for (unsigned int i=0; i<uReadThis; i++) buf[i]=zdecode(pfile_in_zip_read_info->keys,buf[i]); } } unsigned int uDoEncHead = pfile_in_zip_read_info->encheadleft; if (uDoEncHead>pfile_in_zip_read_info->stream.avail_in) uDoEncHead=pfile_in_zip_read_info->stream.avail_in; if (uDoEncHead>0) { char bufcrc=pfile_in_zip_read_info->stream.next_in[uDoEncHead-1]; pfile_in_zip_read_info->rest_read_uncompressed-=uDoEncHead; pfile_in_zip_read_info->stream.avail_in -= uDoEncHead; pfile_in_zip_read_info->stream.next_in += uDoEncHead; pfile_in_zip_read_info->encheadleft -= uDoEncHead; if (pfile_in_zip_read_info->encheadleft==0) { if (bufcrc!=pfile_in_zip_read_info->crcenctest) return UNZ_PASSWORD; } } if (pfile_in_zip_read_info->compression_method==0) { uInt uDoCopy,i ; if (pfile_in_zip_read_info->stream.avail_out < pfile_in_zip_read_info->stream.avail_in) { uDoCopy = pfile_in_zip_read_info->stream.avail_out ; } else { uDoCopy = pfile_in_zip_read_info->stream.avail_in ; } for (i=0;i<uDoCopy;i++) *(pfile_in_zip_read_info->stream.next_out+i) = *(pfile_in_zip_read_info->stream.next_in+i); pfile_in_zip_read_info->crc32 = ucrc32(pfile_in_zip_read_info->crc32,pfile_in_zip_read_info->stream.next_out,uDoCopy); pfile_in_zip_read_info->rest_read_uncompressed-=uDoCopy; pfile_in_zip_read_info->stream.avail_in -= uDoCopy; pfile_in_zip_read_info->stream.avail_out -= uDoCopy; pfile_in_zip_read_info->stream.next_out += uDoCopy; pfile_in_zip_read_info->stream.next_in += uDoCopy; pfile_in_zip_read_info->stream.total_out += uDoCopy; iRead += uDoCopy; if (pfile_in_zip_read_info->rest_read_uncompressed==0) {if (reached_eof!=0) *reached_eof=true;} } else { uLong uTotalOutBefore,uTotalOutAfter; const Byte *bufBefore; uLong uOutThis; int flush=Z_SYNC_FLUSH; uTotalOutBefore = pfile_in_zip_read_info->stream.total_out; bufBefore = pfile_in_zip_read_info->stream.next_out; // err=inflate(&pfile_in_zip_read_info->stream,flush); // uTotalOutAfter = pfile_in_zip_read_info->stream.total_out; uOutThis = uTotalOutAfter-uTotalOutBefore; pfile_in_zip_read_info->crc32 = ucrc32(pfile_in_zip_read_info->crc32,bufBefore,(uInt)(uOutThis)); pfile_in_zip_read_info->rest_read_uncompressed -= uOutThis; iRead += (uInt)(uTotalOutAfter - uTotalOutBefore); if (err==Z_STREAM_END || pfile_in_zip_read_info->rest_read_uncompressed==0) { if (reached_eof!=0) *reached_eof=true; return iRead; } if (err!=Z_OK) break; } } if (err==Z_OK) return iRead; return err; } // Give the current position in uncompressed data z_off_t unztell (unzFile file) { unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; pfile_in_zip_read_info=s->pfile_in_zip_read; if (pfile_in_zip_read_info==NULL) return UNZ_PARAMERROR; return (z_off_t)pfile_in_zip_read_info->stream.total_out; } // return 1 if the end of file was reached, 0 elsewhere int unzeof (unzFile file) { unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; pfile_in_zip_read_info=s->pfile_in_zip_read; if (pfile_in_zip_read_info==NULL) return UNZ_PARAMERROR; if (pfile_in_zip_read_info->rest_read_uncompressed == 0) return 1; else return 0; } // Read extra field from the current file (opened by unzOpenCurrentFile) // This is the local-header version of the extra field (sometimes, there is // more info in the local-header version than in the central-header) // if buf==NULL, it return the size of the local extra field that can be read // if buf!=NULL, len is the size of the buffer, the extra header is copied in buf. // the return value is the number of bytes copied in buf, or (if <0) the error code int unzGetLocalExtrafield (unzFile file,voidp buf,unsigned len) { unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; uInt read_now; uLong size_to_read; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; pfile_in_zip_read_info=s->pfile_in_zip_read; if (pfile_in_zip_read_info==NULL) return UNZ_PARAMERROR; size_to_read = (pfile_in_zip_read_info->size_local_extrafield - pfile_in_zip_read_info->pos_local_extrafield); if (buf==NULL) return (int)size_to_read; if (len>size_to_read) read_now = (uInt)size_to_read; else read_now = (uInt)len ; if (read_now==0) return 0; if (lufseek(pfile_in_zip_read_info->file, pfile_in_zip_read_info->offset_local_extrafield + pfile_in_zip_read_info->pos_local_extrafield,SEEK_SET)!=0) return UNZ_ERRNO; if (lufread(buf,(uInt)size_to_read,1,pfile_in_zip_read_info->file)!=1) return UNZ_ERRNO; return (int)read_now; } // Close the file in zip opened with unzipOpenCurrentFile // Return UNZ_CRCERROR if all the file was read but the CRC is not good int unzCloseCurrentFile (unzFile file) { int err=UNZ_OK; unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; pfile_in_zip_read_info=s->pfile_in_zip_read; if (pfile_in_zip_read_info==NULL) return UNZ_PARAMERROR; if (pfile_in_zip_read_info->rest_read_uncompressed == 0) { if (pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait) err=UNZ_CRCERROR; } if (pfile_in_zip_read_info->read_buffer!=0) { void *buf = pfile_in_zip_read_info->read_buffer; zfree(buf); pfile_in_zip_read_info->read_buffer=0; } pfile_in_zip_read_info->read_buffer = NULL; if (pfile_in_zip_read_info->stream_initialised) inflateEnd(&pfile_in_zip_read_info->stream); pfile_in_zip_read_info->stream_initialised = 0; if (pfile_in_zip_read_info!=0) zfree(pfile_in_zip_read_info); // unused pfile_in_zip_read_info=0; s->pfile_in_zip_read=NULL; return err; } // Get the global comment string of the ZipFile, in the szComment buffer. // uSizeBuf is the size of the szComment buffer. // return the number of byte copied or an error code <0 int unzGetGlobalComment (unzFile file, char *szComment, uLong uSizeBuf) { //int err=UNZ_OK; unz_s* s; uLong uReadThis ; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; uReadThis = uSizeBuf; if (uReadThis>s->gi.size_comment) uReadThis = s->gi.size_comment; if (lufseek(s->file,s->central_pos+22,SEEK_SET)!=0) return UNZ_ERRNO; if (uReadThis>0) { *szComment='\0'; if (lufread(szComment,(uInt)uReadThis,1,s->file)!=1) return UNZ_ERRNO; } if ((szComment != NULL) && (uSizeBuf > s->gi.size_comment)) *(szComment+s->gi.size_comment)='\0'; return (int)uReadThis; } int unzOpenCurrentFile (unzFile file, const char *password); int unzReadCurrentFile (unzFile file, void *buf, unsigned len); int unzCloseCurrentFile (unzFile file); typedef unsigned __int32 lutime_t; // define it ourselves since we don't include time.h FILETIME timet2filetime(const lutime_t t) { LONGLONG i = Int32x32To64(t,10000000) + 116444736000000000; FILETIME ft; ft.dwLowDateTime = (DWORD) i; ft.dwHighDateTime = (DWORD)(i >>32); return ft; } FILETIME dosdatetime2filetime(WORD dosdate,WORD dostime) { // date: bits 0-4 are day of month 1-31. Bits 5-8 are month 1..12. Bits 9-15 are year-1980 // time: bits 0-4 are seconds/2, bits 5-10 are minute 0..59. Bits 11-15 are hour 0..23 SYSTEMTIME st; st.wYear = (WORD)(((dosdate>>9)&0x7f) + 1980); st.wMonth = (WORD)((dosdate>>5)&0xf); st.wDay = (WORD)(dosdate&0x1f); st.wHour = (WORD)((dostime>>11)&0x1f); st.wMinute = (WORD)((dostime>>5)&0x3f); st.wSecond = (WORD)((dostime&0x1f)*2); st.wMilliseconds = 0; FILETIME ft; SystemTimeToFileTime(&st,&ft); return ft; } class TUnzip { public: TUnzip(const char *pwd) : uf(0), unzbuf(0), currentfile(-1), czei(-1), password(0) {if (pwd!=0) {password=new char[strlen(pwd)+1]; strcpy_s(password,MAX_PATH,pwd);}} ~TUnzip() {if (password!=0) delete[] password; password=0; if (unzbuf!=0) delete[] unzbuf; unzbuf=0;} unzFile uf; int currentfile; ZIPENTRY cze; int czei; char *password; char *unzbuf; // lazily created and destroyed, used by Unzip TCHAR rootdir[MAX_PATH]; // includes a trailing slash ZRESULT Open(void *z,unsigned int len,DWORD flags); ZRESULT Get(int index,ZIPENTRY *ze); ZRESULT Find(const TCHAR *name,bool ic,int *index,ZIPENTRY *ze); ZRESULT Unzip(int index,void *dst,unsigned int len,DWORD flags); ZRESULT SetUnzipBaseDir(const TCHAR *dir); ZRESULT Close(); }; ZRESULT TUnzip::Open(void *z,unsigned int len,DWORD flags) { if (uf!=0 || currentfile!=-1) return ZR_NOTINITED; // #ifdef GetCurrentDirectory GetCurrentDirectory(MAX_PATH,rootdir); #else _tcscpy(rootdir,_T("\\")); #endif TCHAR lastchar = rootdir[_tcslen(rootdir)-1]; if (lastchar!='\\' && lastchar!='/') _tcscat_s(rootdir,_T("\\")); // if (flags==ZIP_HANDLE) { // test if we can seek on it. We can't use GetFileType(h)==FILE_TYPE_DISK since it's not on CE. DWORD res = SetFilePointer(z,0,0,FILE_CURRENT); bool canseek = (res!=0xFFFFFFFF); if (!canseek) return ZR_SEEK; } ZRESULT e; LUFILE *f = lufopen(z,len,flags,&e); if (f==NULL) return e; uf = unzOpenInternal(f); if (uf==0) return ZR_NOFILE; return ZR_OK; } ZRESULT TUnzip::SetUnzipBaseDir(const TCHAR *dir) { _tcscpy_s(rootdir, MAX_PATH, dir); TCHAR lastchar = rootdir[_tcslen(rootdir)-1]; if (lastchar!='\\' && lastchar!='/') _tcscat_s(rootdir,_T("\\")); return ZR_OK; } ZRESULT TUnzip::Get(int index,ZIPENTRY *ze) { if (index<-1 || index>=(int)uf->gi.number_entry) return ZR_ARGS; if (currentfile!=-1) unzCloseCurrentFile(uf); currentfile=-1; if (index==czei && index!=-1) {memcpy(ze,&cze,sizeof(ZIPENTRY)); return ZR_OK;} if (index==-1) { ze->index = uf->gi.number_entry; ze->name[0]=0; ze->attr=0; ze->atime.dwLowDateTime=0; ze->atime.dwHighDateTime=0; ze->ctime.dwLowDateTime=0; ze->ctime.dwHighDateTime=0; ze->mtime.dwLowDateTime=0; ze->mtime.dwHighDateTime=0; ze->comp_size=0; ze->unc_size=0; return ZR_OK; } if (index<(int)uf->num_file) unzGoToFirstFile(uf); while ((int)uf->num_file<index) unzGoToNextFile(uf); unz_file_info ufi; char fn[MAX_PATH]; unzGetCurrentFileInfo(uf,&ufi,fn,MAX_PATH,NULL,0,NULL,0); // now get the extra header. We do this ourselves, instead of // calling unzOpenCurrentFile &c., to avoid allocating more than necessary. unsigned int extralen,iSizeVar; unsigned long offset; int res = unzlocal_CheckCurrentFileCoherencyHeader(uf,&iSizeVar,&offset,&extralen); if (res!=UNZ_OK) return ZR_CORRUPT; if (lufseek(uf->file,offset,SEEK_SET)!=0) return ZR_READ; unsigned char *extra = new unsigned char[extralen]; if (lufread(extra,1,(uInt)extralen,uf->file)!=extralen) {delete[] extra; return ZR_READ;} // ze->index=uf->num_file; TCHAR tfn[MAX_PATH]; #ifdef UNICODE MultiByteToWideChar(CP_UTF8,0,fn,-1,tfn,MAX_PATH); #else strcpy(tfn,fn); #endif // As a safety feature: if the zip filename had sneaky stuff // like "c:\windows\file.txt" or "\windows\file.txt" or "fred\..\..\..\windows\file.txt" // then we get rid of them all. That way, when the programmer does UnzipItem(hz,i,ze.name), // it won't be a problem. (If the programmer really did want to get the full evil information, // then they can edit out this security feature from here). // In particular, we chop off any prefixes that are "c:\" or "\" or "/" or "[stuff]\.." or "[stuff]/.." const TCHAR *sfn=tfn; for (;;) { if (sfn[0]!=0 && sfn[1]==':') {sfn+=2; continue;} if (sfn[0]=='\\') {sfn++; continue;} if (sfn[0]=='/') {sfn++; continue;} const TCHAR *c; c=_tcsstr(sfn,_T("\\..\\")); if (c!=0) {sfn=c+4; continue;} c=_tcsstr(sfn,_T("\\../")); if (c!=0) {sfn=c+4; continue;} c=_tcsstr(sfn,_T("/../")); if (c!=0) {sfn=c+4; continue;} c=_tcsstr(sfn,_T("/..\\")); if (c!=0) {sfn=c+4; continue;} break; } _tcscpy_s(ze->name, MAX_PATH, sfn); // zip has an 'attribute' 32bit value. Its lower half is windows stuff // its upper half is standard unix stat.st_mode. We'll start trying // to read it in unix mode unsigned long a = ufi.external_fa; bool isdir = (a&0x40000000)!=0; bool readonly= (a&0x00800000)==0; //bool readable= (a&0x01000000)!=0; // unused //bool executable=(a&0x00400000)!=0; // unused bool hidden=false, system=false, archive=true; // but in normal hostmodes these are overridden by the lower half... int host = ufi.version>>8; if (host==0 || host==7 || host==11 || host==14) { readonly= (a&0x00000001)!=0; hidden= (a&0x00000002)!=0; system= (a&0x00000004)!=0; isdir= (a&0x00000010)!=0; archive= (a&0x00000020)!=0; } ze->attr=0; if (isdir) ze->attr |= FILE_ATTRIBUTE_DIRECTORY; if (archive) ze->attr|=FILE_ATTRIBUTE_ARCHIVE; if (hidden) ze->attr|=FILE_ATTRIBUTE_HIDDEN; if (readonly) ze->attr|=FILE_ATTRIBUTE_READONLY; if (system) ze->attr|=FILE_ATTRIBUTE_SYSTEM; ze->comp_size = ufi.compressed_size; ze->unc_size = ufi.uncompressed_size; // WORD dostime = (WORD)(ufi.dosDate&0xFFFF); WORD dosdate = (WORD)((ufi.dosDate>>16)&0xFFFF); FILETIME ftd = dosdatetime2filetime(dosdate,dostime); FILETIME ft; LocalFileTimeToFileTime(&ftd,&ft); ze->atime=ft; ze->ctime=ft; ze->mtime=ft; // the zip will always have at least that dostime. But if it also has // an extra header, then we'll instead get the info from that. unsigned int epos=0; while (epos+4<extralen) { char etype[3]; etype[0]=extra[epos+0]; etype[1]=extra[epos+1]; etype[2]=0; int size = extra[epos+2]; if (strcmp(etype,"UT")!=0) {epos += 4+size; continue;} int flags = extra[epos+4]; bool hasmtime = (flags&1)!=0; bool hasatime = (flags&2)!=0; bool hasctime = (flags&4)!=0; epos+=5; if (hasmtime) { lutime_t mtime = ((extra[epos+0])<<0) | ((extra[epos+1])<<8) |((extra[epos+2])<<16) | ((extra[epos+3])<<24); epos+=4; ze->mtime = timet2filetime(mtime); } if (hasatime) { lutime_t atime = ((extra[epos+0])<<0) | ((extra[epos+1])<<8) |((extra[epos+2])<<16) | ((extra[epos+3])<<24); epos+=4; ze->atime = timet2filetime(atime); } if (hasctime) { lutime_t ctime = ((extra[epos+0])<<0) | ((extra[epos+1])<<8) |((extra[epos+2])<<16) | ((extra[epos+3])<<24); epos+=4; ze->ctime = timet2filetime(ctime); } break; } // if (extra!=0) delete[] extra; memcpy(&cze,ze,sizeof(ZIPENTRY)); czei=index; return ZR_OK; } ZRESULT TUnzip::Find(const TCHAR *tname,bool ic,int *index,ZIPENTRY *ze) { char name[MAX_PATH]; #ifdef UNICODE WideCharToMultiByte(CP_UTF8,0,tname,-1,name,MAX_PATH,0,0); #else strcpy(name,tname); #endif int res = unzLocateFile(uf,name,ic?CASE_INSENSITIVE:CASE_SENSITIVE); if (res!=UNZ_OK) { if (index!=0) *index=-1; if (ze!=NULL) {ZeroMemory(ze,sizeof(ZIPENTRY)); ze->index=-1;} return ZR_NOTFOUND; } if (currentfile!=-1) unzCloseCurrentFile(uf); currentfile=-1; int i = (int)uf->num_file; if (index!=NULL) *index=i; if (ze!=NULL) { ZRESULT zres = Get(i,ze); if (zres!=ZR_OK) return zres; } return ZR_OK; } void EnsureDirectory(const TCHAR *rootdir, const TCHAR *dir) { if (rootdir!=0 && GetFileAttributes(rootdir)==0xFFFFFFFF) CreateDirectory(rootdir,0); if (*dir==0) return; const TCHAR *lastslash=dir, *c=lastslash; while (*c!=0) {if (*c=='/' || *c=='\\') lastslash=c; c++;} const TCHAR *name=lastslash; if (lastslash!=dir) { TCHAR tmp[MAX_PATH]; memcpy(tmp,dir,sizeof(TCHAR)*(lastslash-dir)); tmp[lastslash-dir]=0; EnsureDirectory(rootdir,tmp); name++; } TCHAR cd[MAX_PATH]; *cd=0; if (rootdir!=0) _tcscpy_s(cd, MAX_PATH, rootdir); _tcscat_s(cd,dir); if (GetFileAttributes(cd)==0xFFFFFFFF) CreateDirectory(cd,NULL); } ZRESULT TUnzip::Unzip(int index,void *dst,unsigned int len,DWORD flags) { if (flags!=ZIP_MEMORY && flags!=ZIP_FILENAME && flags!=ZIP_HANDLE) return ZR_ARGS; if (flags==ZIP_MEMORY) { if (index!=currentfile) { if (currentfile!=-1) unzCloseCurrentFile(uf); currentfile=-1; if (index>=(int)uf->gi.number_entry) return ZR_ARGS; if (index<(int)uf->num_file) unzGoToFirstFile(uf); while ((int)uf->num_file<index) unzGoToNextFile(uf); unzOpenCurrentFile(uf,password); currentfile=index; } bool reached_eof; int res = unzReadCurrentFile(uf,dst,len,&reached_eof); if (res<=0) {unzCloseCurrentFile(uf); currentfile=-1;} if (reached_eof) return ZR_OK; if (res>0) return ZR_MORE; if (res==UNZ_PASSWORD) return ZR_PASSWORD; return ZR_FLATE; } // otherwise we're writing to a handle or a file if (currentfile!=-1) unzCloseCurrentFile(uf); currentfile=-1; if (index>=(int)uf->gi.number_entry) return ZR_ARGS; if (index<(int)uf->num_file) unzGoToFirstFile(uf); while ((int)uf->num_file<index) unzGoToNextFile(uf); ZIPENTRY ze; Get(index,&ze); // zipentry=directory is handled specially if ((ze.attr&FILE_ATTRIBUTE_DIRECTORY)!=0) { if (flags==ZIP_HANDLE) return ZR_OK; // don't do anything const TCHAR *dir = (const TCHAR*)dst; bool isabsolute = (dir[0]=='/' || dir[0]=='\\' || (dir[0]!=0 && dir[1]==':')); if (isabsolute) EnsureDirectory(0,dir); else EnsureDirectory(rootdir,dir); return ZR_OK; } // otherwise, we write the zipentry to a file/handle HANDLE h; if (flags==ZIP_HANDLE) h=dst; else { const TCHAR *ufn = (const TCHAR*)dst; // We'll qualify all relative names to our root dir, and leave absolute names as they are // ufn="zipfile.txt" dir="" name="zipfile.txt" fn="c:\\currentdir\\zipfile.txt" // ufn="dir1/dir2/subfile.txt" dir="dir1/dir2/" name="subfile.txt" fn="c:\\currentdir\\dir1/dir2/subfiles.txt" // ufn="\z\file.txt" dir="\z\" name="file.txt" fn="\z\file.txt" // This might be a security risk, in the case where we just use the zipentry's name as "ufn", where // a malicious zip could unzip itself into c:\windows. Our solution is that GetZipItem (which // is how the user retrieve's the file's name within the zip) never returns absolute paths. const TCHAR *name=ufn; const TCHAR *c=name; while (*c!=0) {if (*c=='/' || *c=='\\') name=c+1; c++;} TCHAR dir[MAX_PATH]; _tcscpy_s(dir, MAX_PATH, ufn); if (name==ufn) *dir=0; else dir[name-ufn]=0; TCHAR fn[MAX_PATH]; bool isabsolute = (dir[0]=='/' || dir[0]=='\\' || (dir[0]!=0 && dir[1]==':')); if (isabsolute) {wsprintf(fn,_T("%s%s"),dir,name); EnsureDirectory(0,dir);} else {wsprintf(fn,_T("%s%s%s"),rootdir,dir,name); EnsureDirectory(rootdir,dir);} // h = CreateFile(fn,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,ze.attr,NULL); } if (h==INVALID_HANDLE_VALUE) return ZR_NOFILE; unzOpenCurrentFile(uf,password); if (unzbuf==0) unzbuf=new char[16384]; DWORD haderr=0; // for (; haderr==0;) { bool reached_eof; int res = unzReadCurrentFile(uf,unzbuf,16384,&reached_eof); if (res==UNZ_PASSWORD) {haderr=ZR_PASSWORD; break;} if (res<0) {haderr=ZR_FLATE; break;} if (res>0) {DWORD writ; BOOL bres=WriteFile(h,unzbuf,res,&writ,NULL); if (!bres) {haderr=ZR_WRITE; break;}} if (reached_eof) break; if (res==0) {haderr=ZR_FLATE; break;} } if (!haderr) SetFileTime(h,&ze.ctime,&ze.atime,&ze.mtime); // may fail if it was a pipe if (flags!=ZIP_HANDLE) CloseHandle(h); unzCloseCurrentFile(uf); if (haderr!=0) return haderr; return ZR_OK; } ZRESULT TUnzip::Close() { if (currentfile!=-1) unzCloseCurrentFile(uf); currentfile=-1; if (uf!=0) unzClose(uf); uf=0; return ZR_OK; } ZRESULT lasterrorU=ZR_OK; unsigned int FormatZipMessageU(ZRESULT code, TCHAR *buf,unsigned int len) { if (code==ZR_RECENT) code=lasterrorU; const TCHAR *msg=_T("unknown zip result code"); switch (code) { case ZR_OK: msg=_T("Success"); break; case ZR_NODUPH: msg=_T("Culdn't duplicate handle"); break; case ZR_NOFILE: msg=_T("Couldn't create/open file"); break; case ZR_NOALLOC: msg=_T("Failed to allocate memory"); break; case ZR_WRITE: msg=_T("Error writing to file"); break; case ZR_NOTFOUND: msg=_T("File not found in the zipfile"); break; case ZR_MORE: msg=_T("Still more data to unzip"); break; case ZR_CORRUPT: msg=_T("Zipfile is corrupt or not a zipfile"); break; case ZR_READ: msg=_T("Error reading file"); break; case ZR_PASSWORD: msg=_T("Correct password required"); break; case ZR_ARGS: msg=_T("Caller: faulty arguments"); break; case ZR_PARTIALUNZ: msg=_T("Caller: the file had already been partially unzipped"); break; case ZR_NOTMMAP: msg=_T("Caller: can only get memory of a memory zipfile"); break; case ZR_MEMSIZE: msg=_T("Caller: not enough space allocated for memory zipfile"); break; case ZR_FAILED: msg=_T("Caller: there was a previous error"); break; case ZR_ENDED: msg=_T("Caller: additions to the zip have already been ended"); break; case ZR_ZMODE: msg=_T("Caller: mixing creation and opening of zip"); break; case ZR_NOTINITED: msg=_T("Zip-bug: internal initialisation not completed"); break; case ZR_SEEK: msg=_T("Zip-bug: trying to seek the unseekable"); break; case ZR_MISSIZE: msg=_T("Zip-bug: the anticipated size turned out wrong"); break; case ZR_NOCHANGE: msg=_T("Zip-bug: tried to change mind, but not allowed"); break; case ZR_FLATE: msg=_T("Zip-bug: an internal error during flation"); break; } unsigned int mlen=(unsigned int)_tcslen(msg); if (buf==0 || len==0) return mlen; unsigned int n=mlen; if (n+1>len) n=len-1; _tcsncpy_s(buf,MAX_PATH,msg,n); buf[n]=0; return mlen; } typedef struct { DWORD flag; TUnzip *unz; } TUnzipHandleData; HZIP OpenZipInternal(void *z,unsigned int len,DWORD flags, const char *password) { TUnzip *unz = new TUnzip(password); lasterrorU = unz->Open(z,len,flags); if (lasterrorU!=ZR_OK) {delete unz; return 0;} TUnzipHandleData *han = new TUnzipHandleData; han->flag=1; han->unz=unz; return (HZIP)han; } HZIP OpenZipHandle(HANDLE h, const char *password) {return OpenZipInternal((void*)h,0,ZIP_HANDLE,password);} HZIP OpenZip(const TCHAR *fn, const char *password) {return OpenZipInternal((void*)fn,0,ZIP_FILENAME,password);} HZIP OpenZip(void *z,unsigned int len, const char *password) {return OpenZipInternal(z,len,ZIP_MEMORY,password);} ZRESULT GetZipItem(HZIP hz, int index, ZIPENTRY *ze) { ze->index=0; *ze->name=0; ze->unc_size=0; if (hz==0) {lasterrorU=ZR_ARGS;return ZR_ARGS;} TUnzipHandleData *han = (TUnzipHandleData*)hz; if (han->flag!=1) {lasterrorU=ZR_ZMODE;return ZR_ZMODE;} TUnzip *unz = han->unz; lasterrorU = unz->Get(index,ze); return lasterrorU; } ZRESULT FindZipItem(HZIP hz, const TCHAR *name, bool ic, int *index, ZIPENTRY *ze) { if (hz==0) {lasterrorU=ZR_ARGS;return ZR_ARGS;} TUnzipHandleData *han = (TUnzipHandleData*)hz; if (han->flag!=1) {lasterrorU=ZR_ZMODE;return ZR_ZMODE;} TUnzip *unz = han->unz; lasterrorU = unz->Find(name,ic,index,ze); return lasterrorU; } ZRESULT UnzipItemInternal(HZIP hz, int index, void *dst, unsigned int len, DWORD flags) { if (hz==0) {lasterrorU=ZR_ARGS;return ZR_ARGS;} TUnzipHandleData *han = (TUnzipHandleData*)hz; if (han->flag!=1) {lasterrorU=ZR_ZMODE;return ZR_ZMODE;} TUnzip *unz = han->unz; lasterrorU = unz->Unzip(index,dst,len,flags); return lasterrorU; } ZRESULT UnzipItemHandle(HZIP hz, int index, HANDLE h) {return UnzipItemInternal(hz,index,(void*)h,0,ZIP_HANDLE);} ZRESULT UnzipItem(HZIP hz, int index, const TCHAR *fn) {return UnzipItemInternal(hz,index,(void*)fn,0,ZIP_FILENAME);} ZRESULT UnzipItem(HZIP hz, int index, void *z,unsigned int len) {return UnzipItemInternal(hz,index,z,len,ZIP_MEMORY);} ZRESULT SetUnzipBaseDir(HZIP hz, const TCHAR *dir) { if (hz==0) {lasterrorU=ZR_ARGS;return ZR_ARGS;} TUnzipHandleData *han = (TUnzipHandleData*)hz; if (han->flag!=1) {lasterrorU=ZR_ZMODE;return ZR_ZMODE;} TUnzip *unz = han->unz; lasterrorU = unz->SetUnzipBaseDir(dir); return lasterrorU; } ZRESULT CloseZipU(HZIP hz) { if (hz==0) {lasterrorU=ZR_ARGS;return ZR_ARGS;} TUnzipHandleData *han = (TUnzipHandleData*)hz; if (han->flag!=1) {lasterrorU=ZR_ZMODE;return ZR_ZMODE;} TUnzip *unz = han->unz; lasterrorU = unz->Close(); delete unz; delete han; return lasterrorU; } bool IsZipHandleU(HZIP hz) { if (hz==0) return false; TUnzipHandleData *han = (TUnzipHandleData*)hz; return (han->flag==1); }
[ "paul@paulbetts.org" ]
paul@paulbetts.org
1a9621510a5890e6f3891087573b7d14d8e3f50b
794decce384b8e0ba625e421cc35681b16eba577
/tensorflow/core/data/service/snapshot/utils.h
3ea632e5e304dbb17318c166b6eb6c58c530abb7
[ "LicenseRef-scancode-generic-cla", "Apache-2.0", "BSD-2-Clause" ]
permissive
911gt3/tensorflow
a6728e86100a2d5328280cfefcfa8e7c8de24c4c
423ea74f41d5f605933a9d9834fe2420989fe406
refs/heads/master
2023-04-09T14:27:29.072195
2023-04-03T06:20:23
2023-04-03T06:22:54
258,948,634
0
0
Apache-2.0
2020-04-26T05:36:59
2020-04-26T05:36:58
null
UTF-8
C++
false
false
1,592
h
/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_CORE_DATA_SERVICE_SNAPSHOT_UTILS_H_ #define TENSORFLOW_CORE_DATA_SERVICE_SNAPSHOT_UTILS_H_ #include <cstdint> #include <vector> #include "absl/strings/string_view.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/tsl/platform/status.h" namespace tensorflow { namespace data { int64_t EstimatedSizeBytes(const std::vector<Tensor>& tensors); // Returns a `Status` that indicates the snapshot stream assignment has changed // and the worker should retry unless it's cancelled. Status StreamAssignmentChanged(absl::string_view worker_address, int64_t stream_index); // Returns true if `status` indicates the snapshot stream assignment has changed // returned by `StreamAssignmentChanged`. bool IsStreamAssignmentChanged(const Status& status); } // namespace data } // namespace tensorflow #endif // TENSORFLOW_CORE_DATA_SERVICE_SNAPSHOT_UTILS_H_
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
4a76cac30b1bc4bf6696ab84973927450e320812
99ecca1944396fb67de3e64663d464d17c558e8f
/super_template.cpp
2055f142955090c02af6cc83a611f4302d75b2ba
[]
no_license
fedepousa/codejam-practicas
c1cb88eb3d6c7ec39d33b92038f02616984c2f86
dff985d02a83d2d196ec70453d0b57d4a2f68acc
refs/heads/master
2020-12-25T19:03:56.651996
2011-05-10T13:38:48
2011-05-10T13:38:48
32,286,689
0
0
null
null
null
null
UTF-8
C++
false
false
8,579
cpp
#include <vector> #include <list> #include <map> #include <set> #include <deque> #include <queue> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <cctype> #include <string> #include <cstring> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <string.h> using namespace std; #define forn(i, n) for(int i = 0; i < (int)(n); i++) #define ford(i, n) for(int i = (int)(n) - 1; i >= 0; i--) #define forab(i, a, b) for (int i = (int)(a); i <= (int)(b); i++) #define forit(i, a) for (__typeof((a).begin()) i = (a).begin(); i != (a).end(); i++) #define sz(a) (int)(a).size() #define pb push_back #define mp make_pair #define fs first #define sc second #define last(a) int(a.size() - 1) #define all(a) a.begin(), a.end() #define zero(a) memset(a, 0, sizeof(a)) #define seta(a,x) memset (a, x, sizeof (a)) #define I (int) typedef long long int64;//NOTES:int64 typedef unsigned long long uint64;//NOTES:uint64 const double pi=acos(-1.0);//NOTES:pi const double eps=1e-11;//NOTES:eps template<class T> inline T sqr(T x){return x*x;}//NOTES:sqr //Numberic Functions template<class T> inline T gcd(T a,T b)//NOTES:gcd( {if(a<0)return gcd(-a,b);if(b<0)return gcd(a,-b);return (b==0)?a:gcd(b,a%b);} template<class T> inline T lcm(T a,T b)//NOTES:lcm( {if(a<0)return lcm(-a,b);if(b<0)return lcm(a,-b);return a*(b/gcd(a,b));} template<class T> inline T euclide(T a,T b,T &x,T &y)//NOTES:euclide( {if(a<0){T d=euclide(-a,b,x,y);x=-x;return d;} if(b<0){T d=euclide(a,-b,x,y);y=-y;return d;} if(b==0){x=1;y=0;return a;}else{T d=euclide(b,a%b,x,y);T t=x;x=y;y=t-(a/b)*y;return d;}} template<class T> inline vector<pair<T,int> > factorize(T n)//NOTES:factorize( {vector<pair<T,int> > R;for (T i=2;n>1;){if (n%i==0){int C=0;for (;n%i==0;C++,n/=i);R.push_back(make_pair(i,C));} i++;if (i>n/i) i=n;}if (n>1) R.push_back(make_pair(n,1));return R;} template<class T> inline bool isPrimeNumber(T n)//NOTES:isPrimeNumber( {if(n<=1)return false;for (T i=2;i*i<=n;i++) if (n%i==0) return false;return true;} template<class T> inline T eularFunction(T n)//NOTES:eularFunction( {vector<pair<T,int> > R=factorize(n);T r=n;for (int i=0;i<R.size();i++)r=r/R[i].first*(R[i].first-1);return r;} //Matrix Operations const int MaxMatrixSize=40;//NOTES:MaxMatrixSize template<class T> inline void showMatrix(int n,T A[MaxMatrixSize][MaxMatrixSize])//NOTES:showMatrix( {for (int i=0;i<n;i++){for (int j=0;j<n;j++)cout<<A[i][j];cout<<endl;}} template<class T> inline T checkMod(T n,T m) {return (n%m+m)%m;}//NOTES:checkMod( template<class T> inline void identityMatrix(int n,T A[MaxMatrixSize][MaxMatrixSize])//NOTES:identityMatrix( {for (int i=0;i<n;i++) for (int j=0;j<n;j++) A[i][j]=(i==j)?1:0;} template<class T> inline void addMatrix(int n,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:addMatrix( {for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=A[i][j]+B[i][j];} template<class T> inline void subMatrix(int n,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:subMatrix( {for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=A[i][j]-B[i][j];} template<class T> inline void mulMatrix(int n,T C[MaxMatrixSize][MaxMatrixSize],T _A[MaxMatrixSize][MaxMatrixSize],T _B[MaxMatrixSize][MaxMatrixSize])//NOTES:mulMatrix( { T A[MaxMatrixSize][MaxMatrixSize],B[MaxMatrixSize][MaxMatrixSize]; for (int i=0;i<n;i++) for (int j=0;j<n;j++) A[i][j]=_A[i][j],B[i][j]=_B[i][j],C[i][j]=0; for (int i=0;i<n;i++) for (int j=0;j<n;j++) for (int k=0;k<n;k++) C[i][j]+=A[i][k]*B[k][j];} template<class T> inline void addModMatrix(int n,T m,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:addModMatrix( {for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=checkMod(A[i][j]+B[i][j],m);} template<class T> inline void subModMatrix(int n,T m,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:subModMatrix( {for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=checkMod(A[i][j]-B[i][j],m);} template<class T> inline T multiplyMod(T a,T b,T m) {return (T)((((int64)(a)*(int64)(b)%(int64)(m))+(int64)(m))%(int64)(m));}//NOTES:multiplyMod( template<class T> inline void mulModMatrix(int n,T m,T C[MaxMatrixSize][MaxMatrixSize],T _A[MaxMatrixSize][MaxMatrixSize],T _B[MaxMatrixSize][MaxMatrixSize])//NOTES:mulModMatrix( { T A[MaxMatrixSize][MaxMatrixSize],B[MaxMatrixSize][MaxMatrixSize]; for (int i=0;i<n;i++) for (int j=0;j<n;j++) A[i][j]=_A[i][j],B[i][j]=_B[i][j],C[i][j]=0; for (int i=0;i<n;i++) for (int j=0;j<n;j++) for (int k=0;k<n;k++) C[i][j]=(C[i][j]+multiplyMod(A[i][k],B[k][j],m))%m;} template<class T> inline T powerMod(T p,int e,T m)//NOTES:powerMod( {if(e==0)return 1%m;else if(e%2==0){T t=powerMod(p,e/2,m);return multiplyMod(t,t,m);}else return multiplyMod(powerMod(p,e-1,m),p,m);} //Point&Line double dist(double x1,double y1,double x2,double y2){return sqrt(sqr(x1-x2)+sqr(y1-y2));}//NOTES:dist( double distR(double x1,double y1,double x2,double y2){return sqr(x1-x2)+sqr(y1-y2);}//NOTES:distR( template<class T> T cross(T x0,T y0,T x1,T y1,T x2,T y2){return (x1-x0)*(y2-y0)-(x2-x0)*(y1-y0);}//NOTES:cross( int crossOper(double x0,double y0,double x1,double y1,double x2,double y2)//NOTES:crossOper( {double t=(x1-x0)*(y2-y0)-(x2-x0)*(y1-y0);if (fabs(t)<=eps) return 0;return (t<0)?-1:1;} bool isIntersect(double x1,double y1,double x2,double y2,double x3,double y3,double x4,double y4)//NOTES:isIntersect( {return crossOper(x1,y1,x2,y2,x3,y3)*crossOper(x1,y1,x2,y2,x4,y4)<0 && crossOper(x3,y3,x4,y4,x1,y1)*crossOper(x3,y3,x4,y4,x2,y2)<0;} bool isMiddle(double s,double m,double t){return fabs(s-m)<=eps || fabs(t-m)<=eps || (s<m)!=(t<m);}//NOTES:isMiddle( //Translator bool isUpperCase(char c){return c>='A' && c<='Z';}//NOTES:isUpperCase( bool isLowerCase(char c){return c>='a' && c<='z';}//NOTES:isLowerCase( bool isLetter(char c){return c>='A' && c<='Z' || c>='a' && c<='z';}//NOTES:isLetter( bool isDigit(char c){return c>='0' && c<='9';}//NOTES:isDigit( char toLowerCase(char c){return (isUpperCase(c))?(c+32):c;}//NOTES:toLowerCase( char toUpperCase(char c){return (isLowerCase(c))?(c-32):c;}//NOTES:toUpperCase( template<class T> string toString(T n){ostringstream ost;ost<<n;ost.flush();return ost.str();}//NOTES:toString( int toInt(string s){int r=0;istringstream sin(s);sin>>r;return r;}//NOTES:toInt( int64 toInt64(string s){int64 r=0;istringstream sin(s);sin>>r;return r;}//NOTES:toInt64( double toDouble(string s){double r=0;istringstream sin(s);sin>>r;return r;}//NOTES:toDouble( template<class T> void stoa(string s,int &n,T A[]){n=0;istringstream sin(s);for(T v;sin>>v;A[n++]=v);}//NOTES:stoa( template<class T> void atos(int n,T A[],string &s){ostringstream sout;for(int i=0;i<n;i++){if(i>0)sout<<' ';sout<<A[i];}s=sout.str();}//NOTES:atos( template<class T> void atov(int n,T A[],vector<T> &vi){vi.clear();for (int i=0;i<n;i++) vi.push_back(A[i]);}//NOTES:atov( template<class T> void vtoa(vector<T> vi,int &n,T A[]){n=vi.size();for (int i=0;i<n;i++)A[i]=vi[i];}//NOTES:vtoa( template<class T> void stov(string s,vector<T> &vi){vi.clear();istringstream sin(s);for(T v;sin>>v;vi.push_bakc(v));}//NOTES:stov( template<class T> void vtos(vector<T> vi,string &s){ostringstream sout;for (int i=0;i<vi.size();i++){if(i>0)sout<<' ';sout<<vi[i];}s=sout.str();}//NOTES:vtos( //Fraction template<class T> struct Fraction{T a,b;Fraction(T a=0,T b=1);string toString();};//NOTES:Fraction template<class T> Fraction<T>::Fraction(T a,T b){T d=gcd(a,b);a/=d;b/=d;if (b<0) a=-a,b=-b;this->a=a;this->b=b;} template<class T> string Fraction<T>::toString(){ostringstream sout;sout<<a<<"/"<<b;return sout.str();} template<class T> Fraction<T> operator+(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.b+q.a*p.b,p.b*q.b);} template<class T> Fraction<T> operator-(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.b-q.a*p.b,p.b*q.b);} template<class T> Fraction<T> operator*(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.a,p.b*q.b);} template<class T> Fraction<T> operator/(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.b,p.b*q.a);} typedef vector<int> vint; typedef struct _nodo{ vint adjs; int color; _nodo(){color=0;} } nodo; #define p(a) cout << a << endl int main() { }
[ "nicovaras22@132d8716-348d-89a7-68be-e1c8d3029e1a" ]
nicovaras22@132d8716-348d-89a7-68be-e1c8d3029e1a
ffb32c7bfa66792ff42c6982c642d1dd258c2f1d
4a4109182be077240476da145c1ea0366a190b7c
/Plugins/QFireBase/qfirebase.cpp
f49d959a1e797a0219f5ae4bff27ccb231e15e97
[]
no_license
devkitcc/SDMedic
5f7c0a59856108b4d55bc3f051eca3d241073e4b
14509964f5730923268e138ccdb2e99bc944d7b2
refs/heads/master
2021-05-08T01:36:28.333248
2017-10-22T17:14:38
2017-10-22T17:14:38
107,885,884
0
0
null
null
null
null
UTF-8
C++
false
false
58
cpp
#include "qfirebase.h" QFireBase::QFireBase() { }
[ "phonex@devkit.cc" ]
phonex@devkit.cc
b8858cf97fd7aab067a4c9453ac9560d552b4104
a15ca13cce9b7abd1ae3ddaa255eb452b4b6f557
/examples/compressor/ex_compressor.cpp
c96a6a88579c9ff4a38c4e661534993681117c1f
[ "MIT" ]
permissive
jrepp/DaisySP
1b0dd4981ed02b5a04f560ff80635e62ea1c45ee
cc68b240424538c498b5c01b73ae44038458da2b
refs/heads/master
2021-02-26T20:39:35.093106
2020-03-06T21:32:20
2020-03-06T21:32:20
245,552,003
1
0
null
2020-03-07T02:06:45
2020-03-07T02:06:44
null
UTF-8
C++
false
false
2,155
cpp
#include "daisysp.h" #include "daisy_seed.h" // Shortening long macro for sample rate #ifndef SAMPLE_RATE #define SAMPLE_RATE DSY_AUDIO_SAMPLE_RATE #endif // Interleaved audio definitions #define LEFT (i) #define RIGHT (i+1) using namespace daisysp; static daisy_handle seed; static Compressor comp; // Helper Modules static AdEnv env; static Oscillator osc_a, osc_b; static Metro tick; static void AudioCallback(float *in, float *out, size_t size) { float osc_a_out, osc_b_out, env_out, sig_out; for (size_t i = 0; i < size; i += 2) { // When the metro ticks: // trigger the envelope to start if (tick.Process()) { env.Trigger(); } // Use envelope to control the amplitude of the oscillator. env_out = env.Process(); osc_a.SetAmp(env_out); osc_a_out = osc_a.Process(); osc_b_out = osc_b.Process(); // Compress the steady tone with the enveloped tone. sig_out = comp.Process(osc_b_out, osc_a_out); // Output out[LEFT] = sig_out; // compressed out[RIGHT] = osc_a_out; // key signal } } int main(void) { // initialize seed hardware and daisysp modules daisy_seed_init(&seed); comp.Init(SAMPLE_RATE); env.Init(SAMPLE_RATE); osc_a.Init(SAMPLE_RATE); osc_b.Init(SAMPLE_RATE); // Set up metro to pulse every second tick.Init(1.0f, SAMPLE_RATE); // set compressor parameters comp.SetThreshold(-64.0f); comp.SetRatio(2.0f); comp.SetAttack(0.005f); comp.SetRelease(0.1250); // set adenv parameters env.SetTime(ADENV_SEG_ATTACK, 0.001); env.SetTime(ADENV_SEG_DECAY, 0.50); env.SetMin(0.0); env.SetMax(0.25); env.SetCurve(0); // linear // Set parameters for oscillator osc_a.SetWaveform(Oscillator::WAVE_TRI); osc_a.SetFreq(110); osc_a.SetAmp(0.25); osc_b.SetWaveform(Oscillator::WAVE_TRI); osc_b.SetFreq(220); osc_b.SetAmp(0.25); // define callback dsy_audio_set_callback(DSY_AUDIO_INTERNAL, AudioCallback); // start callback dsy_audio_start(DSY_AUDIO_INTERNAL); while(1) {} }
[ "stephen.p.hensley@gmail.com" ]
stephen.p.hensley@gmail.com
7256649c1b45655ea0cc7a7affc81c5f3fe54265
adbc979313cbc1f0d42c79ac4206d42a8adb3234
/Source Code/李沿橙 2017-10-23/source/李沿橙/bus/bus.cpp
0e0ba6ecc02f0bc9722cb827d7c4ccb465cb67b0
[]
no_license
UnnamedOrange/Contests
a7982c21e575d1342d28c57681a3c98f8afda6c0
d593d56921d2cde0c473b3abedb419bef4cf3ba4
refs/heads/master
2018-10-22T02:26:51.952067
2018-07-21T09:32:29
2018-07-21T09:32:29
112,301,400
1
0
null
null
null
null
UTF-8
C++
false
false
3,218
cpp
#pragma G++ optimize("O3") #include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <iostream> #include <algorithm> #include <vector> #include <string> #include <stack> #include <queue> #include <deque> #include <map> #include <set> #include <bitset> using std::cin; using std::cout; using std::endl; typedef int INT; inline INT readIn() { INT a = 0; bool minus = false; char ch = getchar(); while (!(ch == '-' || ch >= '0' && ch <= '9')) ch = getchar(); if (ch == '-') { minus = true; ch = getchar(); } while (ch >= '0' && ch <= '9') { a *= 10; a += ch; a -= '0'; ch = getchar(); } if (minus) a = -a; return a; } inline void printOut(INT x) { if (!x) { putchar('0'); } else { char buffer[12]; INT length = 0; bool minus = x < 0; if (minus) x = -x; while (x) { buffer[length++] = x % 10 + '0'; x /= 10; } if (minus) buffer[length++] = '-'; do { putchar(buffer[--length]); } while (length); } putchar(' '); } const INT maxn = INT(1e6) + 5; INT n, maxc; INT c[maxn]; INT v[maxn]; struct stack : public std::vector<INT> { INT back2() { return std::vector<INT>::operator[](std::vector<INT>::size() - 2); } }; #define RunInstance(x) delete new x struct cheat1 { static const INT maxN = 5005; INT f[maxN]; cheat1() : f() { f[0] = 0; for (int i = 1; i <= n; i++) { f[i] = -1; for (int j = 0; j < i; j++) { if ((i - j) % c[j] || f[j] == -1) continue; INT t = f[j] + (i - j) / c[j] * v[j]; if (f[i] == -1 || f[i] > t) f[i] = t; } printOut(f[i]); } putchar('\n'); } }; struct cheat2 { cheat2() { INT cnt = v[0]; INT sum = 0; for (int i = 1; i <= n; i++) { printOut(sum += cnt); cnt = std::min(cnt, v[i]); } } }; struct work { INT f[maxn]; stack q[11][10]; INT y(INT s) { return c[s] * f[s] - s * v[s]; } INT x(INT s) { return v[s]; } INT y(INT i, INT j) { return y(i) - y(j); } INT x(INT i, INT j) { return x(j) - x(i); } double slope(INT i, INT j) { INT x2 = x(i, j); if (!x2) return 1e100; return double(y(i, j)) / x2; } INT dp(INT i, INT j) { return f[j] + (i - j) / c[j] * v[j]; } work() : f() { f[0] = 0; q[c[0]][0].push_back(0); for (int i = 1; i <= n; i++) { INT& ans = f[i]; ans = -1; for (int j = 1; j <= maxc; j++) { stack& s = q[j][i % j]; if (s.empty()) continue; while (s.size() > 1 && dp(i, s.back()) >= dp(i, s.back2())) s.pop_back(); INT k = s.back(); INT t = dp(i, k); if (ans == -1 || ans > t) ans = t; } printOut(ans); if (i != n && f[i] != -1) { stack& s = q[c[i]][i % c[i]]; while (s.size() && v[s.back()] >= v[i]) s.pop_back(); while (s.size() > 1 && slope(i, s.back()) >= slope(s.back(), s.back2())) s.pop_back(); s.push_back(i); } } } }; void run() { n = readIn(); maxc = readIn(); for (int i = 0; i < n; i++) { c[i] = readIn(); v[i] = readIn(); } //if (n <= 5000) // RunInstance(cheat1); //else if (maxc == 1) // RunInstance(cheat2); //else RunInstance(work); } int main() { #ifndef JUDGE freopen("bus.in", "r", stdin); freopen("bus.out", "w", stdout); #endif run(); return 0; }
[ "lycheng1215@sina.com" ]
lycheng1215@sina.com
afc25e99fe3f2a1b551c27d4418402d2a503e997
7bf78b0de900c22d31543d9a8348ec40c7aa9536
/D3D_DrawTriangle/cMainGame.h
3b268ddd0222c33ae36b3138fa03f9396bb04894
[]
no_license
hmgWorks/D3D_Tutorials
5fb00abca0ee094e5ce321a8717238d48bdaefa4
ea0aba647e88e47233a92e5f0d40c95d43650567
refs/heads/master
2021-01-21T12:26:17.097218
2015-01-19T15:42:16
2015-01-19T15:42:16
29,414,381
0
0
null
null
null
null
UTF-8
C++
false
false
226
h
#pragma once class cTriangle; class cMainGame { private: std::unique_ptr<cTriangle> m_spTriangle; //cTriangle* m_spTriangle; public: cMainGame(void); ~cMainGame(void); void Setup(); void Update(); void Render(); };
[ "tmdnldjazz@gmail.com" ]
tmdnldjazz@gmail.com
b807966f3409def6e402e0f4154383a68f8e5e97
b21b07fc237a764474eb9995783c1b714356bf5f
/src/Xyz/SimplexNoise.cpp
d605c33842509507b55cb3da1b68390f4969d9a0
[ "BSD-2-Clause" ]
permissive
jebreimo/Xyz
a26b7d93fbb112ebf6c13369c16313db82b68550
2f3a6773345c28ad2925e24e89cab296561b42c5
refs/heads/master
2023-08-31T03:10:18.086392
2023-08-20T14:46:15
2023-08-20T14:46:15
48,961,224
0
0
null
null
null
null
UTF-8
C++
false
false
5,995
cpp
//**************************************************************************** // Copyright © 2022 Jan Erik Breimo. All rights reserved. // Created by Jan Erik Breimo on 2022-05-07. // // This file is distributed under the BSD License. // License text is included with the source distribution. //**************************************************************************** #include "Xyz/SimplexNoise.hpp" #include <algorithm> // Copied (and slightly adapted) // from https://gist.github.com/Flafla2/f0260a861be0ebdeef76 namespace { // Hash lookup table as defined by Ken SimplexNoise. This is a randomly // arranged array of all numbers from 0-255 inclusive. uint8_t PERMUTATION[256] = { 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180 }; double gradient(int hash, double x, double y, double z) { switch (hash & 0xF) { case 0x0: return x + y; case 0x1: return -x + y; case 0x2: return x - y; case 0x3: return -x - y; case 0x4: return x + z; case 0x5: return -x + z; case 0x6: return x - z; case 0x7: return -x - z; case 0x8: return y + z; case 0x9: return -y + z; case 0xA: return y - z; case 0xB: return -y - z; case 0xC: return y + x; case 0xD: return -y + z; case 0xE: return y - x; case 0xF: return -y - z; default: return 0; } } double fade(double t) { // Fade function as defined by Ken SimplexNoise. This eases coordinate // values so that they will "ease" towards integral values. // This ends up smoothing the final output. return t * t * t * (t * (t * 6 - 15) + 10); // 6t^5 - 15t^4 + 10t^3 } double lerp(double a, double b, double x) { return a + x * (b - a); } } SimplexNoise::SimplexNoise() { std::copy(std::begin(PERMUTATION), std::end(PERMUTATION), permutation_); std::copy(std::begin(PERMUTATION), std::end(PERMUTATION), permutation_ + 256); } double SimplexNoise::simplex(double x, double y, double z) { // Calculate the "unit cube" that the point asked will be located in. // The left bound is ( |_x_|,|_y_|,|_z_| ) and the right bound is that // plus 1. Next we calculate the location (from 0.0 to 1.0) in that cube. // We also fade the location to smooth the result. int xi = int(x) & 255; int yi = int(y) & 255; int zi = int(z) & 255; double xf = x - int(x); double yf = y - int(y); double zf = z - int(z); double u = fade(xf); double v = fade(yf); double w = fade(zf); int aaa, aba, aab, abb, baa, bba, bab, bbb; aaa = permutation_[permutation_[permutation_[xi] + yi] + zi]; aba = permutation_[permutation_[permutation_[xi] + ++yi] + zi]; aab = permutation_[permutation_[permutation_[xi] + yi] + ++zi]; abb = permutation_[permutation_[permutation_[xi] + ++yi] + ++zi]; baa = permutation_[permutation_[permutation_[++xi] + yi] + zi]; bba = permutation_[permutation_[permutation_[++xi] + ++yi] + zi]; bab = permutation_[permutation_[permutation_[++xi] + yi] + ++zi]; bbb = permutation_[permutation_[permutation_[++xi] + ++yi] + ++zi]; double x1, x2, y1, y2; // The gradient function calculates the dot product between a pseudorandom // gradient vector and the vector from the input coordinate to the 8 // surrounding points in its unit cube. x1 = lerp(gradient(aaa, xf, yf, zf), gradient(baa, xf - 1, yf, zf), u); // This is all then lerped together as a sort of weighted average based on // the faded (u,v,w) values we made earlier. x2 = lerp(gradient(aba, xf, yf - 1, zf), gradient(bba, xf - 1, yf - 1, zf), u); y1 = lerp(x1, x2, v); x1 = lerp(gradient(aab, xf, yf, zf - 1), gradient(bab, xf - 1, yf, zf - 1), u); x2 = lerp(gradient(abb, xf, yf - 1, zf - 1), gradient(bbb, xf - 1, yf - 1, zf - 1), u); y2 = lerp(x1, x2, v); // For convenience, we reduce it to 0 - 1 (theoretical min/max before // is -1 - 1) return (lerp(y1, y2, w) + 1) / 2; } double SimplexNoise::simplex(double x, double y, double z, int octaves, double persistence) { double total = 0; double frequency = 1; double amplitude = 1; double max_value = 0; for (int i = 0; i < octaves; i++) { total += simplex(x * frequency, y * frequency, z * frequency) * amplitude; max_value += amplitude; amplitude *= persistence; frequency *= 2; } return total / max_value; }
[ "jebreimo@gmail.com" ]
jebreimo@gmail.com
d38f3767fe6f697d235bdc2dea85ec745d18bb25
145cf7f56d4368c0da850d5e38b2942076856b8c
/React Native Ui Lib/node_modules/@react-native-community/datetimepicker/node_modules/react-native-windows/ReactUWP/Polyester/HyperlinkViewManager.cpp
2574ec0c6ddab3e038972054626355447a416a7b
[ "MIT" ]
permissive
cadet29manikandan/ForMoreReactNativeProjectPart2
ef8d002c75a2e6f76818abf77a84f1fe54a7bdb5
09aaf2594ae440f2a78e2c9e1aa41c4aab582526
refs/heads/master
2023-06-09T16:48:51.572356
2021-06-24T15:56:40
2021-06-24T15:56:40
379,975,343
0
0
null
null
null
null
UTF-8
C++
false
false
2,816
cpp
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "pch.h" #include "HyperlinkViewManager.h" #include <Utils/ValueUtils.h> #include <Views/ShadowNodeBase.h> #include <winrt/Windows.UI.Xaml.Controls.Primitives.h> #include <winrt/Windows.UI.Xaml.Controls.h> #include <IReactInstance.h> #include <winrt/Windows.UI.Xaml.Controls.Primitives.h> #include <winrt/Windows.UI.Xaml.Controls.h> namespace winrt { using namespace Windows::Foundation; using namespace Windows::UI; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Media; } // namespace winrt namespace react { namespace uwp { namespace polyester { HyperlinkViewManager::HyperlinkViewManager(const std::shared_ptr<IReactInstance> &reactInstance) : ContentControlViewManager(reactInstance) {} const char *HyperlinkViewManager::GetName() const { return "PLYHyperlink"; } folly::dynamic HyperlinkViewManager::GetNativeProps() const { auto props = Super::GetNativeProps(); props.update(folly::dynamic::object("disabled", "boolean")("url", "string")("tooltip", "string")); return props; } XamlView HyperlinkViewManager::CreateViewCore(int64_t tag) { auto button = winrt::HyperlinkButton(); button.Click([=](auto &&, auto &&) { auto instance = m_wkReactInstance.lock(); folly::dynamic eventData = folly::dynamic::object("target", tag); if (instance != nullptr) instance->DispatchEvent(tag, "topClick", std::move(eventData)); }); return button; } folly::dynamic HyperlinkViewManager::GetExportedCustomDirectEventTypeConstants() const { auto directEvents = Super::GetExportedCustomDirectEventTypeConstants(); directEvents["topClick"] = folly::dynamic::object("registrationName", "onClick"); return directEvents; } bool HyperlinkViewManager::UpdateProperty( ShadowNodeBase *nodeToUpdate, const std::string &propertyName, const folly::dynamic &propertyValue) { auto button = nodeToUpdate->GetView().as<winrt::HyperlinkButton>(); if (button == nullptr) return true; if (propertyName == "disabled") { if (propertyValue.isBool()) button.IsEnabled(!propertyValue.asBool()); } else if (propertyName == "tooltip") { if (propertyValue.isString()) { winrt::TextBlock tooltip = winrt::TextBlock(); tooltip.Text(asHstring(propertyValue)); winrt::ToolTipService::SetToolTip(button, tooltip); } } else if (propertyName == "url") { winrt::Uri myUri(asHstring(propertyValue)); button.NavigateUri(myUri); } else { return Super::UpdateProperty(nodeToUpdate, propertyName, propertyValue); } return true; } } // namespace polyester } // namespace uwp } // namespace react
[ "manikandan@nvestbank.com" ]
manikandan@nvestbank.com
822c0cbe1df8c14a644ce9901565c54c578f3ffc
4a887b7390deb04cf908571876e33a3c6bc63826
/3_2DEngineWithGUI/Base.h
ca97adadb48fe9a86cf60458c1e07489b0e947f7
[ "MIT" ]
permissive
dnjfdkanwjr/2DEngine
504d2a97638346fdf283c0889f40f16574d0ca4a
8908073192b6a80a84d155f07061003800e8d0ce
refs/heads/master
2021-02-09T19:34:56.041713
2020-03-19T05:41:25
2020-03-19T05:41:25
244,318,509
0
0
null
null
null
null
UTF-8
C++
false
false
384
h
#pragma once #include <string> namespace rp { class Base { protected: std::string name{}; bool state{}; public: Base(std::string&& name); virtual ~Base(); void SetName(std::string&& name)noexcept; void SetName(std::string& name)noexcept; void SetState(bool state)noexcept; const std::string& GetName() const noexcept; bool GetState() const noexcept; }; }
[ "kweyom6@gmail.com" ]
kweyom6@gmail.com
2816114820980efb09a736075066c1ae8208251b
7052b9b0e0aea3524dd990bb97eacf3f492e1941
/CC3000/examples/wlan_mag/wlan_mag.ino
8e918bddd32ce336dcb8a9f51e0344cdf2d1d7e5
[ "BSD-2-Clause" ]
permissive
pscholl/Adafruit_CC3000_Library
64a1d03152ed465d61244286077686f8eed5693c
1a571ff1a9ca7c482a497e6c94201c38ba09dc4d
refs/heads/master
2021-01-24T20:02:10.598462
2015-06-23T11:35:58
2015-06-23T11:35:58
19,730,591
0
0
null
null
null
null
UTF-8
C++
false
false
3,638
ino
/* ATTENTION: need to include Wire and I2CDev libs for * jNode sensors (LSM9DS0, MPL115A2, VCNL4010, SHT21X) * * With this sample we've used 99% of available memory! */ #include <Wire.h> #include <I2Cdev.h> #include <LSM9DS0.h> #include <Adafruit_CC3000.h> #include <SPI.h> #include "utility/debug.h" #include "utility/socket.h" unsigned long time=0; // These are the interrupt and control pins // DO NOT CHANGE!!!! #define ADAFRUIT_CC3000_IRQ 11 #define ADAFRUIT_CC3000_VBAT 13 #define ADAFRUIT_CC3000_CS 10 Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIVIDER); #define WLAN_SSID "fsr_mobi" // cannot be longer than 32 characters! #define WLAN_PASS "woh0Roo2The7chai" #define WLAN_SECURITY WLAN_SEC_WPA2 // Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2 #define LISTEN_PORT 7 // What TCP port to listen on for connections Adafruit_CC3000_Server quatServer(LISTEN_PORT); LSM9DS0 sen; void setup(void) { Wire.begin(); Serial.begin(115200); /* Initialise the module */ //Serial.println(F("\nInitializing...")); if (!cc3000.begin() || (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) ) { Serial.println(F("Failed!")); while(1); } while (!cc3000.checkDHCP()) { delay(100); // ToDo: Insert a DHCP timeout! } /*********************************************************/ /* You can safely remove this to save some flash memory! */ /*********************************************************/ // Serial.println(F("\r\nNOTE: This sketch may cause problems with other sketches")); // Serial.println(F("since the .disconnect() function is never called, so the")); // Serial.println(F("AP may refuse connection requests from the CC3000 until a")); // Serial.println(F("timeout period passes. This is normal behaviour since")); // Serial.println(F("there isn't an obvious moment to disconnect with a server.\r\n")); // Start listening for connections displayConnectionDetails(); quatServer.begin(); sen.initialize(); sen.setGyroFullScale(2000); sen.setGyroOutputDataRate(LSM9DS0_RATE_95); sen.setGyroBandwidthCutOffMode(LSM9DS0_BW_HIGH); sen.setGyroDataFilter(LSM9DS0_LOW_PASS); sen.setAccRate(LSM9DS0_ACC_RATE_100); sen.setAccFullScale(LSM9DS0_ACC_8G); sen.setAccAntiAliasFilterBandwidth(LSM9DS0_ACC_FILTER_BW_50); sen.setMagFullScale(LSM9DS0_MAG_4_GAUSS); sen.setMagOutputRate(LSM9DS0_M_ODR_100); } #define p(x) client.print(x) void loop(void) { // Try to get a client which is connected. Adafruit_CC3000_ClientRef client = quatServer.available(); if (client) { measurement_t m = sen.getMeasurement(); p(m.ax); p("\t"); // acceleration p(m.ay); p("\t"); p(m.az); p("\t"); p(m.gx); p("\t"); // gyroscope p(m.gy); p("\t"); p(m.gz); p("\t"); p(m.mx); p("\t"); // magnetometer p(m.my); p("\t"); p(m.mz); p("\n"); } } /**************************************************************************/ /*! @brief Tries to read the IP address and other connection details */ /**************************************************************************/ bool displayConnectionDetails(void) { // There is not enough space to include code for printing the full IP // address, so we just print the last byte of it. tNetappIpconfigRetArgs ipconfig; netapp_ipconfig(&ipconfig); Serial.println(ipconfig.aucIP[0]); }
[ "pscholl@ese.uni-freiburg.de" ]
pscholl@ese.uni-freiburg.de
4954df9038975808ebc26d8174fd0b0356d08d0f
1196266a7aa8230db1b86dcdd7efff85a43ff812
/VST3_SDK/public.sdk/source/vst/vstcomponent.cpp
b69241908afb1eea9822d9ea88beec28081ef010
[ "Unlicense" ]
permissive
fedden/RenderMan
c97547b9b5b3bddf1de6d9111e5eae6434e438ee
e81510d8b564a100899f4fed8c3049c8812cba8d
refs/heads/master
2021-12-11T18:41:02.477036
2021-07-20T18:25:36
2021-07-20T18:25:36
82,790,125
344
45
Unlicense
2021-08-06T23:08:22
2017-02-22T10:09:32
C++
UTF-8
C++
false
false
7,112
cpp
//----------------------------------------------------------------------------- // Project : VST SDK // // Category : Helpers // Filename : public.sdk/source/vst/vstcomponent.cpp // Created by : Steinberg, 04/2005 // Description : Basic VST Plug-in Implementation // //----------------------------------------------------------------------------- // LICENSE // (c) 2017, Steinberg Media Technologies GmbH, 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 Steinberg Media Technologies 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 "vstcomponent.h" namespace Steinberg { namespace Vst { //------------------------------------------------------------------------ // Component Implementation //------------------------------------------------------------------------ Component::Component () : audioInputs (kAudio, kInput) , audioOutputs (kAudio, kOutput) , eventInputs (kEvent, kInput) , eventOutputs (kEvent, kOutput) {} //------------------------------------------------------------------------ tresult PLUGIN_API Component::initialize (FUnknown* context) { return ComponentBase::initialize (context); } //------------------------------------------------------------------------ tresult PLUGIN_API Component::terminate () { // remove all buses removeAllBusses (); return ComponentBase::terminate (); } //------------------------------------------------------------------------ BusList* Component::getBusList (MediaType type, BusDirection dir) { if (type == kAudio) return dir == kInput ? &audioInputs : &audioOutputs; else if (type == kEvent) return dir == kInput ? &eventInputs : &eventOutputs; return 0; } //------------------------------------------------------------------------ tresult Component::removeAudioBusses () { audioInputs.clear (); audioOutputs.clear (); return kResultOk; } //------------------------------------------------------------------------ tresult Component::removeEventBusses () { eventInputs.clear (); eventOutputs.clear (); return kResultOk; } //------------------------------------------------------------------------ tresult Component::removeAllBusses () { removeAudioBusses (); removeEventBusses (); return kResultOk; } //------------------------------------------------------------------------ tresult PLUGIN_API Component::getControllerClassId (TUID classID) { if (controllerClass.isValid ()) { controllerClass.toTUID (classID); return kResultTrue; } return kResultFalse; } //------------------------------------------------------------------------ tresult PLUGIN_API Component::setIoMode (IoMode /*mode*/) { return kNotImplemented; } //------------------------------------------------------------------------ int32 PLUGIN_API Component::getBusCount (MediaType type, BusDirection dir) { BusList* busList = getBusList (type, dir); return busList ? static_cast<int32> (busList->size ()) : 0; } //------------------------------------------------------------------------ tresult PLUGIN_API Component::getBusInfo (MediaType type, BusDirection dir, int32 index, BusInfo& info) { if (index < 0) return kInvalidArgument; BusList* busList = getBusList (type, dir); if (busList == 0) return kInvalidArgument; if (index >= static_cast<int32> (busList->size ())) return kInvalidArgument; Bus* bus = busList->at (index); info.mediaType = type; info.direction = dir; if (bus->getInfo (info)) return kResultTrue; return kResultFalse; } //------------------------------------------------------------------------ tresult PLUGIN_API Component::getRoutingInfo (RoutingInfo& /*inInfo*/, RoutingInfo& /*outInfo*/) { return kNotImplemented; } //------------------------------------------------------------------------ tresult PLUGIN_API Component::activateBus (MediaType type, BusDirection dir, int32 index, TBool state) { if (index < 0) return kInvalidArgument; BusList* busList = getBusList (type, dir); if (busList == 0) return kInvalidArgument; if (index >= static_cast<int32> (busList->size ())) return kInvalidArgument; Bus* bus = busList->at (index); bus->setActive (state); return kResultTrue; } //------------------------------------------------------------------------ tresult PLUGIN_API Component::setActive (TBool /*state*/) { return kResultOk; } //------------------------------------------------------------------------ tresult PLUGIN_API Component::setState (IBStream* /*state*/) { return kNotImplemented; } //------------------------------------------------------------------------ tresult PLUGIN_API Component::getState (IBStream* /*state*/) { return kNotImplemented; } //------------------------------------------------------------------------ tresult Component::renameBus (MediaType type, BusDirection dir, int32 index, const String128 newName) { if (index < 0) return kInvalidArgument; BusList* busList = getBusList (type, dir); if (busList == 0) return kInvalidArgument; if (index >= static_cast<int32> (busList->size ())) return kInvalidArgument; Bus* bus = busList->at (index); bus->setName (newName); return kResultTrue; } //------------------------------------------------------------------------ // Helpers Implementation //------------------------------------------------------------------------ tresult getSpeakerChannelIndex (SpeakerArrangement arrangement, uint64 speaker, int32& channel) { channel = SpeakerArr::getSpeakerIndex (speaker, arrangement); return channel < 0 ? kResultFalse : kResultTrue; } } // namespace Vst } // namespace Steinberg
[ "github.com@schrieb.de" ]
github.com@schrieb.de
0811a45932f781306c79c102a317affdaf89c095
fae45a23a885b72cd27c0ad1b918ad754b5de9fd
/benchmarks/shenango/parsec/pkgs/tools/cmake/src/Source/cmSeparateArgumentsCommand.cxx
ea6f065af9c9f954ceb35d70187934ff3500acf4
[ "Apache-2.0", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-other-permissive", "MIT" ]
permissive
bitslab/CompilerInterrupts
6678700651c7c83fd06451c94188716e37e258f0
053a105eaf176b85b4c0d5e796ac1d6ee02ad41b
refs/heads/main
2023-06-24T18:09:43.148845
2021-07-26T17:32:28
2021-07-26T17:32:28
342,868,949
3
3
MIT
2021-07-19T15:38:30
2021-02-27T13:57:16
C
UTF-8
C++
false
false
1,314
cxx
/*========================================================================= Program: CMake - Cross-Platform Makefile Generator Module: $RCSfile: cmSeparateArgumentsCommand.cxx,v $ Language: C++ Date: $Date: 2012/03/29 17:21:08 $ Version: $Revision: 1.1.1.1 $ Copyright (c) 2002 Kitware, Inc., Insight Consortium. All rights reserved. See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "cmSeparateArgumentsCommand.h" // cmSeparateArgumentsCommand bool cmSeparateArgumentsCommand ::InitialPass(std::vector<std::string> const& args, cmExecutionStatus &) { if(args.size() != 1 ) { this->SetError("called with incorrect number of arguments"); return false; } const char* cacheValue = this->Makefile->GetDefinition(args[0].c_str()); if(!cacheValue) { return true; } std::string value = cacheValue; cmSystemTools::ReplaceString(value," ", ";"); this->Makefile->AddDefinition(args[0].c_str(), value.c_str()); return true; }
[ "nilanjana.basu87@gmail.com" ]
nilanjana.basu87@gmail.com
8a5aab971b95db02883d20232314fe4fad3c19c2
f12e53b806ba418a58f814ebc87c4446a422b2f5
/solutions/uri/1789/1789.cpp
c14cdae8df69b14fd26b05dda0d6eeafcb2cf0b5
[ "MIT" ]
permissive
biadelmont/playground
f775cd86109e30ed464d4d6eff13f9ded40627cb
93c6248ec6cd25d75f0efbda1d50e0705bbd1e5a
refs/heads/master
2021-05-06T15:49:43.253788
2017-11-07T13:00:31
2017-11-07T13:00:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
402
cpp
#include <cstdio> int main() { int l, v, fastest; while (scanf("%d", &l) != EOF) { fastest = 0; while (l--) { scanf("%d", &v); if (v > fastest) fastest = v; } if (fastest < 10) { puts("1"); } else if (fastest < 20) { puts("2"); } else { puts("3"); } } return 0; }
[ "deniscostadsc@gmail.com" ]
deniscostadsc@gmail.com
278610710edb06f4e8cfd21ed070aaad83328446
2eac4cb30dd9fbbf73e35c294f8549107dbeee0e
/src/Adjacency.h
1f071998066f9571840d8a5dad9345aec43f4c24
[]
no_license
patrickmacarthur/OurAdventure
9f720f8523eea467f8d101e44613a4d0f5a92183
2db5450af6601f924f8de614fb3b83ed42e98b29
refs/heads/master
2021-01-23T07:08:54.335142
2014-10-28T18:03:36
2014-10-28T18:03:36
2,129,865
0
0
null
null
null
null
UTF-8
C++
false
false
1,575
h
#ifndef ADJACENCY_H #define ADJACENCY_H /* Adjacency.h * * Author: Patrick MacArthur * * This file is part of the CS 516 Final Project */ #include <istream> #include <ostream> #include <map> #include "Direction.h" #include "Item.h" class Feature; class Map; /* * This class represents an adjacency between rooms. */ class Adjacency : public Item { public: Adjacency(); // constructor virtual ~Adjacency(); // destructor virtual void addToMap( Map * map ); // Adds this item to the map virtual Item * clone() const; // dynamic copy virtual Feature * getExit( const Direction & ); // Gets the exit in the given direction. Returns 0 if // there is no feature in that direction. virtual int getExitCount() const; // Returns the number of exits. const ID & getFeatureID() const; // Returns the ID of the "source" feature. virtual void input( std::istream & s, Map * ); // Inputs the adjacency in the format: // featureId directionCount directionName featureId ... virtual void printDescription( std::ostream & s ); // Outputs the adjacency list in a human-readable // format virtual void save( std::ostream & s ); // Saves the adjacency list to disk in same format // input, except adds type tag in front private: std::map<Direction, Feature *> m_table; ID m_featureID; }; /* vim: set et sw=4 tw=65: */ #endif
[ "generalpenguin89@gmail.com" ]
generalpenguin89@gmail.com
7ecd5b686db5d4f94963cc57cea17c44445fa086
98b2ee5a57d66c957f8b924e0c99e28be9ce51d8
/leetcode/137_SingleNumberII/Solution.cpp
77d278e1cf5fa2ca6ca6d730127876fab384baa2
[]
no_license
sauleddy/C_plus
c990aeecedcb547fc3afcbf387d2b51aa94d08cc
69d6a112d1dd9ac2d99c4b630bb6769b09032252
refs/heads/master
2021-01-19T04:49:07.240672
2017-06-07T05:51:10
2017-06-07T05:51:10
87,397,291
0
0
null
null
null
null
UTF-8
C++
false
false
671
cpp
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Solution.cpp * Author: eddy * * Created on May 10, 2017, 5:21 PM */ #include "Solution.h" Solution::Solution() { } Solution::Solution(const Solution& orig) { } Solution::~Solution() { } int Solution::singleNumber(vector<int>& nums) { int res = 0; for (int i = 0; i < 32; ++i) { int sum = 0; for (int j = 0; j < nums.size(); ++j) { sum += (nums[j] >> i) & 1; } res |= (sum % 3) << i; } return res; }
[ "sauleddy38@gmail.com" ]
sauleddy38@gmail.com
06cfb9ca96a61137a348fc2045f8693d23f03832
d160bb839227b14bb25e6b1b70c8dffb8d270274
/MCMS/Main/Processes/Resource/ResourceLib/ConfResources.cpp
6a1729f5225cd051689ecd1184f8de8e5b900429
[]
no_license
somesh-ballia/mcms
62a58baffee123a2af427b21fa7979beb1e39dd3
41aaa87d5f3b38bc186749861140fef464ddadd4
refs/heads/master
2020-12-02T22:04:46.442309
2017-07-03T06:02:21
2017-07-03T06:02:21
96,075,113
1
0
null
null
null
null
UTF-8
C++
false
false
38,433
cpp
#include "ConfResources.h" #include "StatusesGeneral.h" #include "ProcessBase.h" #include "TraceStream.h" #include "ResourceManager.h" #include "WrappersResource.h" #include "HelperFuncs.h" #include "VideoApiDefinitionsStrings.h" #include <algorithm> #include <functional> //////////////////////////////////////////////////////////////////////////// // CUdpRsrcDesc //////////////////////////////////////////////////////////////////////////// CUdpRsrcDesc::CUdpRsrcDesc(WORD rsrcPartyId, WORD servId, WORD subServId, WORD PQMid) { m_rsrcPartyId = rsrcPartyId; m_servId = servId; m_PQMid = PQMid; m_subServId = subServId; memset(&m_udp, 0, sizeof(UdpAddresses)); for (int i = 0; i < MAX_NUM_OF_ALLOCATED_PARTY_UDP_PORTS; i++) { m_rtp_channels[i] = 0; m_rtcp_channels[i] = 0; } } //////////////////////////////////////////////////////////////////////////// CUdpRsrcDesc::~CUdpRsrcDesc() { } //////////////////////////////////////////////////////////////////////////// bool operator==(const CUdpRsrcDesc& lhs,const CUdpRsrcDesc& rhs) { return ((lhs.m_rsrcPartyId == rhs.m_rsrcPartyId) && (lhs.m_type == rhs.m_type )); } //////////////////////////////////////////////////////////////////////////// bool operator<(const CUdpRsrcDesc& lhs,const CUdpRsrcDesc& rhs) { if (lhs.m_rsrcPartyId != rhs.m_rsrcPartyId) return (lhs.m_rsrcPartyId < rhs.m_rsrcPartyId); return (lhs.m_type < rhs.m_type); } //////////////////////////////////////////////////////////////////////////// void CUdpRsrcDesc::SetIpAddresses(ipAddressV4If ipAddressV4, const ipv6AddressArray& ipAddressV6) { CIPV4Wrapper v4wrapper(m_udp.IpV4Addr); v4wrapper.CopyData(ipAddressV4); CIPV6AraryWrapper v6wrapper(m_udp.IpV6AddrArray); v6wrapper.CopyData(ipAddressV6); } //////////////////////////////////////////////////////////////////////////// // CRsrcDesc //////////////////////////////////////////////////////////////////////////// CRsrcDesc::CRsrcDesc(DWORD connectionId, eLogicalResourceTypes type, DWORD rsrcConfId, WORD rsrcPartyId, WORD boxId , WORD bId, WORD subBid, WORD uid, WORD acceleratorId, WORD firstPortId, ECntrlType cntrl, WORD channelId, BOOL bIsUpdated /*= FALSE*/ ) { m_connectionId = connectionId; m_type = type; m_rsrcConfId = rsrcConfId; m_rsrcPartyId = rsrcPartyId; m_boxId = boxId; m_boardId = bId; m_subBoardId = subBid; m_unitId = uid; m_acceleratorId = acceleratorId; m_firstPortId = firstPortId; m_numPorts = 1; m_cntrl = cntrl; m_channelId = channelId; m_bIsUpdated = bIsUpdated; memset(&m_IpV4Addr, 0, sizeof(m_IpV4Addr)); } //////////////////////////////////////////////////////////////////////////// CRsrcDesc::~CRsrcDesc() { } //////////////////////////////////////////////////////////////////////////// bool operator==(const CRsrcDesc& lhs,const CRsrcDesc& rhs) { //net ports can be the same except for the board, portid, unit_id (=span id) and accelerator_id, so check this if (lhs.m_type == eLogical_net && rhs.m_type == eLogical_net) if (lhs.m_firstPortId != rhs.m_firstPortId || lhs.m_unitId != rhs.m_unitId || lhs.m_acceleratorId != rhs.m_acceleratorId || lhs.m_boardId != rhs.m_boardId) return FALSE; return ((lhs.m_rsrcPartyId == rhs.m_rsrcPartyId) && (lhs.m_type == rhs.m_type ) && (lhs.m_cntrl == rhs.m_cntrl)); } //////////////////////////////////////////////////////////////////////////// bool operator<(const CRsrcDesc& lhs,const CRsrcDesc& rhs) { if (lhs.m_rsrcPartyId != rhs.m_rsrcPartyId) return (lhs.m_rsrcPartyId < rhs.m_rsrcPartyId); else if (lhs.m_type != rhs.m_type) return (lhs.m_type < rhs.m_type); else if (lhs.m_type != eLogical_net) return (lhs.m_cntrl < rhs.m_cntrl); else //if it's net type { if (lhs.m_firstPortId != rhs.m_firstPortId) return (lhs.m_firstPortId < rhs.m_firstPortId); else if (lhs.m_acceleratorId != rhs.m_acceleratorId) return (lhs.m_acceleratorId < rhs.m_acceleratorId); else if (lhs.m_unitId != rhs.m_unitId) return (lhs.m_unitId < rhs.m_unitId); else return (lhs.m_boardId < rhs.m_boardId); } } //////////////////////////////////////////////////////////////////////////// void CRsrcDesc::SetIpAddresses(ipAddressV4If ipAddressV4) { CIPV4Wrapper v4wrapper(m_IpV4Addr); v4wrapper.CopyData(ipAddressV4); } //////////////////////////////////////////////////////////////////////////// eResourceTypes CRsrcDesc::GetPhysicalType() const { switch (m_type) { case eLogical_audio_encoder: return ePhysical_art; case eLogical_audio_decoder: return ePhysical_art; case eLogical_audio_controller: return ePhysical_audio_controller; case eLogical_video_encoder: case eLogical_video_encoder_content: case eLogical_COP_CIF_encoder: case eLogical_COP_VSW_encoder: case eLogical_COP_PCM_encoder: case eLogical_COP_HD720_encoder: case eLogical_COP_HD1080_encoder: case eLogical_COP_4CIF_encoder: return ePhysical_video_encoder; case eLogical_video_decoder: case eLogical_COP_Dynamic_decoder: case eLogical_COP_VSW_decoder: case eLogical_COP_LM_decoder: return ePhysical_video_decoder; case eLogical_rtp: return ePhysical_art; /*Not in use for now case eLogical_ip_signaling: return ePhysical_res_none; */ case eLogical_net: return ePhysical_rtm; case eLogical_ivr_controller: return ePhysical_ivr_controller; case eLogical_mux: return ePhysical_art; // OLGA - Soft MCU case eLogical_relay_rtp: case eLogical_relay_svc_to_avc_rtp: case eLogical_relay_video_encoder: return ePhysical_mrmp; case eLogical_relay_audio_encoder: case eLogical_relay_audio_decoder: case eLogical_legacy_to_SAC_audio_encoder: case eLogical_relay_avc_to_svc_rtp: case eLogical_relay_avc_to_svc_rtp_with_audio_encoder: return ePhysical_art; case eLogical_relay_avc_to_svc_video_encoder_1: case eLogical_relay_avc_to_svc_video_encoder_2: return ePhysical_video_encoder; default: return ePhysical_res_none; } } //////////////////////////////////////////////////////////////////////////// std::ostream& operator<<(std::ostream& os, CRsrcDesc& obj) { os << "\n ConnectionId :" << obj.m_connectionId << "\n ResourceType :" << obj.m_type << "\n ConfId :" << obj.m_rsrcConfId << "\n PartyId :" << obj.m_rsrcPartyId << "\n BoxId :" << obj.m_boxId << "\n BoardId :" << obj.m_boardId << "\n SubBoardId :" << obj.m_subBoardId << "\n UnitId :" << obj.m_unitId << "\n AcceleratorId :" << obj.m_acceleratorId << "\n FirstPortId :" << obj.m_firstPortId; return os; } //////////////////////////////////////////////////////////////////////////// // CConfRsrc //////////////////////////////////////////////////////////////////////////// CConfRsrc::CConfRsrc(DWORD monitorConfId, eSessionType sessionType, eLogicalResourceTypes encoderLogicalType, eConfMediaType confMediaType) { m_monitorConfId = monitorConfId; m_sessionType = sessionType; m_rsrcConfId = 0; //0 - not allocated. m_num_Parties = 0; m_pUdpRsrcDescList = new std::set<CUdpRsrcDesc>; m_encoderTypeCOP = encoderLogicalType; m_confMediaState = eMediaStateEmpty; m_confMediaType = confMediaType; m_mrcMcuId = 1; } //////////////////////////////////////////////////////////////////////////// CConfRsrc::CConfRsrc(const CConfRsrc& other) : CPObject(other), m_pUdpRsrcDescList(new std::set<CUdpRsrcDesc>(*(other.m_pUdpRsrcDescList))) { m_monitorConfId = other.m_monitorConfId; m_sessionType = other.m_sessionType; m_bondingPhones = other.m_bondingPhones; m_parties = other.m_parties; m_rsrcConfId = other.m_rsrcConfId; //0 - not allocated. m_num_Parties = other.m_num_Parties; m_encoderTypeCOP = other.m_encoderTypeCOP; m_confMediaState = other.m_confMediaState; m_confMediaType = other.m_confMediaType; m_mrcMcuId = other.m_mrcMcuId; m_pRsrcDescList = other.m_pRsrcDescList; } //////////////////////////////////////////////////////////////////////////// CConfRsrc::~CConfRsrc() { m_pUdpRsrcDescList->clear(); PDELETE( m_pUdpRsrcDescList); m_pUdpRsrcDescList = 0 ; } //////////////////////////////////////////////////////////////////////////// WORD operator==(const CConfRsrc& lhs,const CConfRsrc& rhs) { return (lhs.m_monitorConfId == rhs.m_monitorConfId); } //////////////////////////////////////////////////////////////////////////// bool operator<(const CConfRsrc& lhs,const CConfRsrc& rhs) { return (lhs.m_monitorConfId < rhs.m_monitorConfId); } //////////////////////////////////////////////////////////////////////////// STATUS CConfRsrc::AddUdpDesc(CUdpRsrcDesc* pUdpRsrcDesc) { PASSERT_AND_RETURN_VALUE(!pUdpRsrcDesc, STATUS_FAIL); std::set<CUdpRsrcDesc>::iterator _itr = m_pUdpRsrcDescList->find(*pUdpRsrcDesc); PASSERT_AND_RETURN_VALUE(_itr != m_pUdpRsrcDescList->end(), STATUS_FAIL); m_pUdpRsrcDescList->insert(*pUdpRsrcDesc); return STATUS_OK; } //////////////////////////////////////////////////////////////////////////// // The function only updates existing desc, not adding new one, if not found STATUS CConfRsrc::UpdateUdpDesc(WORD rsrcpartyId, CUdpRsrcDesc* pUdpRsrcDesc) { PASSERT_AND_RETURN_VALUE(!pUdpRsrcDesc, STATUS_FAIL); CUdpRsrcDesc desc(rsrcpartyId); std::set<CUdpRsrcDesc>::iterator _itr = m_pUdpRsrcDescList->find(desc); PASSERT_AND_RETURN_VALUE(_itr == m_pUdpRsrcDescList->end(), STATUS_FAIL); m_pUdpRsrcDescList->erase(_itr); m_pUdpRsrcDescList->insert(*pUdpRsrcDesc); return STATUS_OK; } //////////////////////////////////////////////////////////////////////////// STATUS CConfRsrc::RemoveUdpDesc(WORD rsrcpartyId) { std::set<CUdpRsrcDesc>::iterator i; CUdpRsrcDesc desc(rsrcpartyId); i = m_pUdpRsrcDescList->find(desc); if (i == m_pUdpRsrcDescList->end())//not exists { PASSERT(1); return STATUS_FAIL; } m_pUdpRsrcDescList->erase(i); return STATUS_OK; } //////////////////////////////////////////////////////////////////////////// const CUdpRsrcDesc* CConfRsrc::GetUdpDesc(WORD rsrcpartyId)const { std::set<CUdpRsrcDesc>::iterator i; CUdpRsrcDesc desc(rsrcpartyId); i = m_pUdpRsrcDescList->find(desc); if (i == m_pUdpRsrcDescList->end())//not exists { PASSERT(1); return NULL; } return (&(*i)); } //////////////////////////////////////////////////////////////////////////// STATUS CConfRsrc::AddDesc(CRsrcDesc* pRsrcDesc) { if (!pRsrcDesc || pRsrcDesc->GetRsrcConfId() != m_rsrcConfId) { DBGPASSERT(1); if (pRsrcDesc) TRACEINTOLVLERR << "ERROR: m_rsrcConfId = " << m_rsrcConfId << ", GetRsrcConfId()=" << pRsrcDesc->GetRsrcConfId(); return STATUS_FAIL; } if (m_pRsrcDescList.find(*pRsrcDesc) != m_pRsrcDescList.end()) {//desc already exists TRACEINTOLVLERR << "Failed, descriptor already exists" << *pRsrcDesc; PASSERT_AND_RETURN_VALUE(1, STATUS_FAIL); } m_pRsrcDescList.insert(*pRsrcDesc); return STATUS_OK; } //////////////////////////////////////////////////////////////////////////// STATUS CConfRsrc::RemoveDesc(WORD rsrcpartyId, eLogicalResourceTypes type, ECntrlType cntrl, WORD portId, WORD unitId, WORD acceleratorId, WORD boardId) { CRsrcDesc desc(0, type, 0, rsrcpartyId, 0, boardId, 0, unitId, acceleratorId, portId, cntrl); RSRC_DESC_MULTISET_ITR itr = m_pRsrcDescList.find(desc); if (itr == m_pRsrcDescList.end()) // not exists { TRACEINTOLVLERR << "Failed, descriptor not exist" << desc; PASSERT_AND_RETURN_VALUE(1, STATUS_FAIL); } m_pRsrcDescList.erase(itr); return STATUS_OK; } //////////////////////////////////////////////////////////////////////////// CRsrcDesc* CConfRsrc::GetDescFromConnectionId(DWORD connectionId) { RSRC_DESC_MULTISET_ITR itr; for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++) { if ((itr->GetConnId() == connectionId)) { return ((CRsrcDesc*)(&(*itr))); } } return NULL; } //////////////////////////////////////////////////////////////////////////// const CRsrcDesc* CConfRsrc::GetDesc(WORD rsrcpartyId, eLogicalResourceTypes type, ECntrlType cntrl, WORD portId, WORD unitId, WORD acceleratorId, WORD boardId) { CRsrcDesc desc(0, type, 0, rsrcpartyId, 0, boardId, 0, unitId, acceleratorId, portId, cntrl); RSRC_DESC_MULTISET_ITR i = m_pRsrcDescList.find(desc); if (i == m_pRsrcDescList.end()) // not exists { // PASSERT(1); return NULL; } return (&(*i)); } //////////////////////////////////////////////////////////////////////////// const CRsrcDesc* CConfRsrc::GetDescByType(eLogicalResourceTypes type, ECntrlType cntrl) { RSRC_DESC_MULTISET_ITR itr; for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++) { if (itr->GetType() == type && itr->GetCntrlType() == cntrl) { return ((CRsrcDesc*)(&(*itr))); } } return NULL; } //////////////////////////////////////////////////////////////////////////// int CConfRsrc::GetDescArray( CRsrcDesc**& pRsrcDescArray) { int arrSize = m_pRsrcDescList.size(); if( 0 == arrSize ) return 0; pRsrcDescArray = new CRsrcDesc*[arrSize]; RSRC_DESC_MULTISET_ITR itr; int i = 0; for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++) { pRsrcDescArray[i] = (CRsrcDesc*)&(*itr); i++; } return i; } //////////////////////////////////////////////////////////////////////////// // Need to receive in pRsrcDescList memory of MAX_NUM_ALLOCATED_RSRCS_NET pointers (CRsrcDesc*) allocated for the output (and initialized to all NULLs) // Returns number of RsrcDescs found. WORD CConfRsrc::GetDescArrayPerResourceTypeByRsrcId(WORD rsrcpartyId,eLogicalResourceTypes type, CRsrcDesc** pRsrcDescArray, BYTE arrSize) const { RSRC_DESC_MULTISET_ITR itr; int i = 0; for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++) { if ((itr->GetRsrcPartyId() == rsrcpartyId ) && ( (itr->GetType() == type) || (eLogical_res_none == type))) { if (i < arrSize) // For protection { pRsrcDescArray[i] = (CRsrcDesc*)&(*itr); i++; } else PASSERTMSG(1, "CConfRsrc::GetDescArrayPerResourceTypeByRsrcId - error in call to function"); } } return i; } //////////////////////////////////////////////////////////////////////////// const CPartyRsrc* CConfRsrc::GetPartyRsrcByRsrcPartyId(PartyRsrcID partyId) const { PARTIES::iterator _iiEnd = m_parties.end(); for (PARTIES::iterator _ii = m_parties.begin(); _ii != _iiEnd; ++_ii) { if (_ii->GetRsrcPartyId() == partyId) return &(*_ii); } return NULL; } //////////////////////////////////////////////////////////////////////////// WORD CConfRsrc::GetNumVideoPartiesPerBoard(WORD boardId) { WORD numVideoParties = 0; PARTIES::iterator _iiEnd = m_parties.end(); for (PARTIES::iterator _ii = m_parties.begin(); _ii != _iiEnd; ++_ii) { PartyRsrcID partyId = _ii->GetRsrcPartyId(); CPartyRsrc* pParty = const_cast<CPartyRsrc*>(GetPartyRsrcByRsrcPartyId(partyId)); if (pParty) { eVideoPartyType videoPartyType = pParty->GetVideoPartyType(); if (eVideo_party_type_none != videoPartyType) { CRsrcDesc* pDecDesc = const_cast<CRsrcDesc*>(GetDesc(partyId, eLogical_video_decoder)); if (pDecDesc) { if (boardId == pDecDesc->GetBoardId()) numVideoParties++; } } } } return numVideoParties; } //////////////////////////////////////////////////////////////////////////// // CPartyRsrc //////////////////////////////////////////////////////////////////////////// CPartyRsrc::CPartyRsrc(PartyMonitorID monitorPartyId, eNetworkPartyType networkPartyType, eVideoPartyType videoPartyType, WORD ARTChannels, ePartyRole partyRole,eHdVswTypesInMixAvcSvc hdVswTypeInMixAvcSvcMode) { m_monitorPartyId = monitorPartyId; m_networkPartyType = networkPartyType; m_videoPartyType = videoPartyType; m_resourcePartyType = e_Audio; m_partyRole = partyRole; m_rsrcPartyId = 0; //0 - not allocated. m_CSconnId = 0; #ifdef MS_LYNC_AVMCU_LINK // MS Lync m_partySigOrganizerConnId = 0; m_partySigFocusConnId = 0; m_partySigEventPackConnId = 0; #endif m_DialInReservedPorts = 0; m_ARTChannels = ARTChannels; m_roomPartyId = 0; //TIP Cisco m_tipPartyType = eTipNone; m_countPartyAsICEinMFW = FALSE; m_ssrcAudio = 0; m_tipNumOfScreens = 0; m_HdVswTypeInMixAvcSvcMode = hdVswTypeInMixAvcSvcMode; memset(m_ssrcContent, 0, sizeof(m_ssrcContent)); memset(m_ssrcVideo, 0, sizeof(m_ssrcVideo)); } //////////////////////////////////////////////////////////////////////////// CPartyRsrc::CPartyRsrc(const CPartyRsrc& other) : CPObject(other), m_monitorPartyId(other.m_monitorPartyId), m_rsrcPartyId(other.m_rsrcPartyId), m_roomPartyId(other.m_roomPartyId), m_tipPartyType(other.m_tipPartyType), m_tipNumOfScreens(other.m_tipNumOfScreens), m_networkPartyType(other.m_networkPartyType), m_videoPartyType(other.m_videoPartyType), m_resourcePartyType(other.m_resourcePartyType), m_partyRole(other.m_partyRole), m_ARTChannels(other.m_ARTChannels), m_CSconnId(other.m_CSconnId), #ifdef MS_LYNC_AVMCU_LINK // MS Lync m_partySigOrganizerConnId(other.m_partySigOrganizerConnId), m_partySigFocusConnId(other.m_partySigFocusConnId), m_partySigEventPackConnId(other.m_partySigEventPackConnId), #endif m_DialInReservedPorts(other.m_DialInReservedPorts), m_countPartyAsICEinMFW(other.m_countPartyAsICEinMFW), m_HdVswTypeInMixAvcSvcMode(other.m_HdVswTypeInMixAvcSvcMode) { m_ssrcAudio = other.m_ssrcAudio; for(WORD i=0;i<MAX_NUM_RECV_STREAMS_FOR_CONTENT;i++) m_ssrcContent[i] = other.m_ssrcContent[i]; for(WORD i=0;i<MAX_NUM_RECV_STREAMS_FOR_VIDEO;i++) m_ssrcVideo[i] = other.m_ssrcVideo[i]; } //////////////////////////////////////////////////////////////////////////// CPartyRsrc::~CPartyRsrc() { } //////////////////////////////////////////////////////////////////////////// void CPartyRsrc::SetARTChannels(WORD ARTChannels) { m_ARTChannels = ARTChannels; // bridge-809: assert only not in soft MCU - in soft MCU ARTChannels set to 0, not to limit soft ART capacity CSystemResources* pSyst = CHelperFuncs::GetSystemResources(); if (pSyst && !CHelperFuncs::IsSoftMCU(pSyst->GetProductType())) { DBGPASSERT(0 == ARTChannels); } } //////////////////////////////////////////////////////////////////////////// WORD operator==(const CPartyRsrc& lhs,const CPartyRsrc& rhs) { return (lhs.m_monitorPartyId == rhs.m_monitorPartyId); } //////////////////////////////////////////////////////////////////////////// bool operator<(const CPartyRsrc& lhs,const CPartyRsrc& rhs) { return (lhs.m_monitorPartyId < rhs.m_monitorPartyId); } //////////////////////////////////////////////////////////////////////////// STATUS CConfRsrc::AddParty(CPartyRsrc& party) { PASSERTSTREAM_AND_RETURN_VALUE(m_parties.find(party) != m_parties.end(), "MonitorPartyId:" << party.GetMonitorPartyId() << " - Already exist", STATUS_FAIL); TRACEINTO << "MonitorPartyId:" << party.GetMonitorPartyId() << ", PartyLogicalType:" << party.GetPartyResourceType(); m_parties.insert(party); m_num_Parties++; UpdateConfMediaStateByPartiesList(); return STATUS_OK; } //////////////////////////////////////////////////////////////////////////// BOOL CConfRsrc::CheckIfOneMorePartyCanBeAddedToConf2C(eVideoPartyType videoPartyType) { CSystemResources *pSystemResources = CHelperFuncs::GetSystemResources(); eSystemCardsMode systemCardsMode = pSystemResources ? pSystemResources->GetSystemCardsMode() : eSystemCardsMode_illegal; if (eVSW_video_party_type == videoPartyType) { if((eVSW_28_session == m_sessionType && m_num_Parties > MAX_PARTIES_IN_CONF_2C_VSW28) || (eVSW_56_session == m_sessionType && m_num_Parties > MAX_PARTIES_IN_CONF_2C_VSW56)) { return FALSE; } else if (eVSW_Auto_session == m_sessionType) { if ((eSystemCardsMode_breeze == systemCardsMode && m_num_Parties > 180)) return FALSE; } } else if (eCOP_party_type == videoPartyType) { DWORD max_cop_parties = 160; //on breeze CReservator* pReservator = CHelperFuncs::GetReservator(); if (pReservator) max_cop_parties = pReservator->GetDongleRestriction(); TRACEINTO << " CConfRsrc::CheckIfOneMorePartyCanBeAddedToConf2C : max_cop_parties = " << max_cop_parties; if ((eCOP_HD1080_session == m_sessionType || eCOP_HD720_50_session == m_sessionType) && m_num_Parties >= max_cop_parties)//192 return FALSE; } return TRUE; } //////////////////////////////////////////////////////////////////////////// WORD CConfRsrc::RemoveAllParties(BYTE force_kill_all_ports) { CResourceManager* pRsrcMngr = (CResourceManager*)(CProcessBase::GetProcess()->GetCurrentTask()); if (!pRsrcMngr) { PASSERT(1); return 0; } DEALLOC_PARTY_REQ_PARAMS_S* pdeallocateParams = new DEALLOC_PARTY_REQ_PARAMS_S; memset(pdeallocateParams, 0, sizeof(DEALLOC_PARTY_REQ_PARAMS_S)); DEALLOC_PARTY_IND_PARAMS_S* pResult = new DEALLOC_PARTY_IND_PARAMS_S; pdeallocateParams->numOfRsrcsWithProblems = 0; pdeallocateParams->monitor_conf_id = m_monitorConfId; pdeallocateParams->force_kill_all_ports = force_kill_all_ports; // make a copy of parties container PARTIES PartyRsrcList = m_parties; PARTIES::iterator itr = PartyRsrcList.begin(); DWORD monitorPartyId = 0; WORD numOfRemovedParties = 0; for (itr = PartyRsrcList.begin(); itr != PartyRsrcList.end(); itr++) { monitorPartyId = ((CPartyRsrc*)(&(*itr)))->GetMonitorPartyId(); TRACEINTO << "monitorPartyId=" << monitorPartyId; memset(pResult, 0, sizeof(DEALLOC_PARTY_IND_PARAMS_S)); pdeallocateParams->monitor_party_id = monitorPartyId; pRsrcMngr->DeAlloc(pdeallocateParams, pResult); if (pResult->status == STATUS_OK) ++numOfRemovedParties; } delete pdeallocateParams; delete pResult; return numOfRemovedParties; } //////////////////////////////////////////////////////////////////////////// STATUS CConfRsrc::RemoveParty(PartyMonitorID monitorPartyId) { CPartyRsrc party(monitorPartyId); PARTIES::iterator itr = m_parties.find(party); PASSERTSTREAM_AND_RETURN_VALUE(itr == m_parties.end(), "MonitorPartyId:" << monitorPartyId << " - Party not exist", STATUS_FAIL); m_parties.erase(itr); m_num_Parties--; UpdateConfMediaStateByPartiesList(); return STATUS_OK; } //////////////////////////////////////////////////////////////////////////// const CPartyRsrc* CConfRsrc::GetParty(PartyMonitorID monitorPartyId) const { CPartyRsrc party(monitorPartyId); PARTIES::iterator itr = m_parties.find(party); TRACECOND_AND_RETURN_VALUE(itr == m_parties.end(), "MonitorPartyId:" << monitorPartyId << " - Party not exist", NULL); return &(*itr); } //////////////////////////////////////////////////////////////////////////// STATUS CConfRsrc::AddTempBondingPhoneNumber(PartyRsrcID partyId, Phone* pPhone) { PASSERT_AND_RETURN_VALUE(!pPhone, STATUS_FAIL); Phone* phone = new Phone; strcpy_safe(phone->phone_number, pPhone->phone_number); m_bondingPhones.insert(BONDING_PHONES::value_type(partyId, phone)); return STATUS_OK; } //////////////////////////////////////////////////////////////////////////// STATUS CConfRsrc::RemoveTempBondingPhoneNumber(PartyRsrcID partyId) { BONDING_PHONES::iterator itr = m_bondingPhones.find(partyId); if (itr == m_bondingPhones.end()) return STATUS_FAIL; delete itr->second; m_bondingPhones.erase(itr); return STATUS_OK; } //////////////////////////////////////////////////////////////////////////// Phone* CConfRsrc::GetTempBondingPhoneNumberByRsrcPartyId(PartyRsrcID partyId) const { BONDING_PHONES::const_iterator itr = m_bondingPhones.find(partyId); if (itr == m_bondingPhones.end()) return NULL; return itr->second; } //////////////////////////////////////////////////////////////////////////// WORD CConfRsrc::IsBoardIdAllocatedToConf(WORD boardId) { //if board allocated o conf - // there is have to be at least on RsrcDesc of this board. //WORD bId = 2; RSRC_DESC_MULTISET_ITR itr; for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++) { if (itr->GetBoardId() == boardId) return TRUE; } return FALSE; } //////////////////////////////////////////////////////////////////////////// void CConfRsrc::AddListOfPartiesDescriptorsOnBoard(WORD boardId, WORD subBoardId, std::map<std::string,CONF_PARTY_ID_S*>* listOfConfIdPartyIdPair) const { RSRC_DESC_MULTISET_ITR itr; CRsrcDesc rsrcdesc; std::string strKey; CONF_PARTY_ID_S* pConf_party_id_s = NULL; for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++) { rsrcdesc = ((CRsrcDesc)(*itr)); if (rsrcdesc.GetBoardId() == boardId) { //if subboard is 1 (MFA), this means that the whole card will be taken out, including the RTM //so it doesn't matter on which subboard it is if (subBoardId == MFA_SUBBOARD_ID || rsrcdesc.GetSubBoardId() == subBoardId) { strKey = GetPartyKey(rsrcdesc.GetRsrcConfId() ,rsrcdesc.GetRsrcPartyId()); if (listOfConfIdPartyIdPair->find(strKey) == listOfConfIdPartyIdPair->end()) { pConf_party_id_s = new CONF_PARTY_ID_S(); pConf_party_id_s->monitor_conf_id = GetMonitorConfId(); CPartyRsrc* pParty = (CPartyRsrc*)(GetPartyRsrcByRsrcPartyId(rsrcdesc.GetRsrcPartyId())); if (pParty == NULL) { POBJDELETE(pConf_party_id_s); PASSERT(1); continue; } else { pConf_party_id_s->monitor_party_id = pParty->GetMonitorPartyId(); } (*listOfConfIdPartyIdPair)[strKey] = pConf_party_id_s; } } } } } //////////////////////////////////////////////////////////////////////////// std::string CConfRsrc::GetPartyKey(DWORD rsrcConfId, DWORD rsrcPartyId) const { std::ostringstream o; o << rsrcConfId << "_" << rsrcPartyId; return o.str(); } //////////////////////////////////////////////////////////////////////////// STATUS CConfRsrc::GetFreeVideoRsrcVSW(CRsrcDesc*& pEncDesc, CRsrcDesc*& pDecDesc) { WORD rsrcId = 0, enc_found = 0, dec_found = 0; RSRC_DESC_MULTISET_ITR itr; for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++) { CRsrcDesc* pRsrcDesc = (CRsrcDesc*)&(*itr); BOOL isDecType = CHelperFuncs::IsLogicalVideoDecoderType( pRsrcDesc->GetType()); BOOL isEncType = CHelperFuncs::IsLogicalVideoEncoderType( pRsrcDesc->GetType()); if (pRsrcDesc->GetIsUpdated() || (!isDecType && !isEncType) || (isDecType && dec_found) || (isEncType && enc_found)) continue; rsrcId = pRsrcDesc->GetRsrcPartyId(); if (isDecType) { dec_found = rsrcId; pDecDesc = pRsrcDesc; } else { enc_found = rsrcId; pEncDesc = pRsrcDesc; } if (dec_found && enc_found && dec_found == enc_found) break; } if (!pEncDesc || !pDecDesc) return STATUS_FAIL; return STATUS_OK; } //////////////////////////////////////////////////////////////////////////// STATUS CConfRsrc::GetBoardUnitIdByRoomIdTIP(DWORD room_id, WORD& boardIdTIP, WORD& unitIdTIP) //TIP Cisco { PARTIES::iterator _iiEnd = m_parties.end(); for (PARTIES::iterator _ii = m_parties.begin(); _ii != _iiEnd; ++_ii) { if (_ii->GetRoomPartyId() == room_id) { const CRsrcDesc* pAudEncDesc = GetDesc(_ii->GetRsrcPartyId(), eLogical_audio_encoder); if (pAudEncDesc) { boardIdTIP = pAudEncDesc->GetBoardId(); unitIdTIP = pAudEncDesc->GetUnitId(); return STATUS_OK; } } } return STATUS_FAIL; } //////////////////////////////////////////////////////////////////////////// WORD CConfRsrc::GetBoardIdForRelayParty() //olga { PARTIES::iterator _it = std::find_if(m_parties.begin(), m_parties.end(), compareVideoPartyFunc()); if (_it != m_parties.end()) { const CRsrcDesc* pRtpDesc = GetDesc(_it->GetRsrcPartyId(), eLogical_rtp); if (pRtpDesc) return pRtpDesc->GetBoardId(); } TRACEINTO << "Relay party is not allocated on any board"; return 0; } //////////////////////////////////////////////////////////////////////////// bool CConfRsrc::CheckIfThereAreRelayParty() const { PARTIES::iterator _it = std::find_if(m_parties.begin(), m_parties.end(), compareVideoPartyFunc()); return (_it != m_parties.end()); } //////////////////////////////////////////////////////////////////////////// bool CConfRsrc::CheckIfThereAreNotRelayParty() const { PARTIES::iterator _it = std::find_if(m_parties.begin(), m_parties.end(), not1(compareVideoPartyFunc())); return (_it != m_parties.end()); } //////////////////////////////////////////////////////////////////////////// STATUS CConfRsrc::GetBoardUnitIdByAvMcuLinkMain(PartyRsrcID mainPartyRsrcID, WORD& boardId, WORD& unitId) { const CRsrcDesc* pRtpDesc = GetDesc(mainPartyRsrcID, eLogical_rtp); if (pRtpDesc) { boardId = pRtpDesc->GetBoardId(); unitId = pRtpDesc->GetUnitId(); return STATUS_OK; } return STATUS_FAIL; } //////////////////////////////////////////////////////////////////////////// void CConfRsrc::CountAvcSvcParties(WORD& numAvc, WORD& numSvc) const { numAvc = 0; numSvc = 0; PARTIES::iterator _iiEnd = m_parties.end(); for (PARTIES::iterator _ii = m_parties.begin(); _ii != _iiEnd; ++_ii) { if (CHelperFuncs::IsVideoRelayParty(_ii->GetVideoPartyType())) numSvc++; else numAvc++; } } //////////////////////////////////////////////////////////////////////////// // Need to receive in pRsrcDescList memory of MAX_NUM_ALLOCATED_RSRCS_NET pointers (CRsrcDesc*) allocated for the output (and initialized to all NULLs) // Returns number of RsrcDescs found. WORD CConfRsrc::GetPartyRcrsDescArrayByRsrcId(DWORD rsrcpartyId, CRsrcDesc** pRsrcDescArray, WORD arrSize) { RSRC_DESC_MULTISET_ITR itr; int num_party_resources = 0; for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++) { if (itr->GetRsrcPartyId() == rsrcpartyId) { if (num_party_resources < arrSize) // For protection { pRsrcDescArray[num_party_resources] = (CRsrcDesc*)&(*itr); num_party_resources++; } else{ PASSERTMSG(num_party_resources, "CConfRsrc::GetDescArrayPerResourceTypeByRsrcId - error in call to function"); } } } return num_party_resources; } //////////////////////////////////////////////////////////////////////////// WORD CConfRsrc::GetPartyRTPDescArrayByRsrcId(DWORD rsrcpartyId, CRsrcDesc** pRsrcDescArray, WORD arrSize) { RSRC_DESC_MULTISET_ITR itr; int num_party_resources = 0; for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++) { if (itr->GetRsrcPartyId() == rsrcpartyId && CHelperFuncs::IsLogicalRTPtype(itr->GetType())) { if (num_party_resources < arrSize) // For protection { pRsrcDescArray[num_party_resources] = (CRsrcDesc*)&(*itr); num_party_resources++; } else{ PASSERTMSG(num_party_resources, "CConfRsrc::GetDescArrayPerResourceTypeByRsrcId - error in call to function"); } } } return num_party_resources; } //////////////////////////////////////////////////////////////////////////// void CConfRsrc::UpdateConfMediaStateByPartiesList() { bool hasRelayParties = CheckIfThereAreRelayParty(); bool hasNotRelayParties = CheckIfThereAreNotRelayParty(); if (eMediaStateMixAvcSvc == m_confMediaState) { // since we don't support downgrade - we don't change ConfMediaState after it already in mixed return; } if (!hasRelayParties && !hasNotRelayParties) { SetConfMediaState(eMediaStateEmpty); } else if (hasRelayParties && !hasNotRelayParties) { SetConfMediaState(eMediaStateSvcOnly); } else if (!hasRelayParties && hasNotRelayParties) { SetConfMediaState(eMediaStateAvcOnly); } } //////////////////////////////////////////////////////////////////////////// // CConfRsrcDB //////////////////////////////////////////////////////////////////////////// CConfRsrcDB::CConfRsrcDB() { m_numConfRsrcs = 0; } //////////////////////////////////////////////////////////////////////////// CConfRsrcDB::~CConfRsrcDB() { m_numConfRsrcs = 0; } //////////////////////////////////////////////////////////////////////////// STATUS CConfRsrcDB::AddConfRsrc(CConfRsrc* pConfRsrc) { PASSERT_AND_RETURN_VALUE(!pConfRsrc, STATUS_FAIL); PASSERT_AND_RETURN_VALUE(m_confList.find(*pConfRsrc) != m_confList.end(), STATUS_FAIL); m_confList.insert(*pConfRsrc); ConfRsrcID id = pConfRsrc->GetRsrcConfId(); if (STANDALONE_CONF_ID != id) m_numConfRsrcs++; TRACEINTO << "ConfId:" << id << ", NumOngoingConf:" << m_numConfRsrcs; return STATUS_OK; } //////////////////////////////////////////////////////////////////////////// STATUS CConfRsrcDB::RemoveConfRsrc(ConfMonitorID confId) { CConfRsrc conf(confId); RSRC_CONF_LIST::iterator _itr = m_confList.find(conf); if (_itr == m_confList.end()) return STATUS_FAIL; ConfRsrcID id = _itr->GetRsrcConfId(); if (STANDALONE_CONF_ID != id) { if (m_numConfRsrcs > 0) m_numConfRsrcs--; else PASSERT(1); } m_confList.erase(_itr); TRACEINTO << "ConfId:" << id << ", NumOngoingConf:" << m_numConfRsrcs; return STATUS_OK; } //////////////////////////////////////////////////////////////////////////// CConfRsrc* CConfRsrcDB::GetConfRsrc(ConfMonitorID confId) { CConfRsrc conf(confId); RSRC_CONF_LIST::iterator _itr = m_confList.find(conf); if (_itr != m_confList.end()) return (CConfRsrc*)(&(*_itr)); return NULL; } //////////////////////////////////////////////////////////////////////////// CConfRsrc* CConfRsrcDB::GetConfRsrcByRsrcConfId(ConfRsrcID confId) { RSRC_CONF_LIST::iterator _end = m_confList.end(); for (RSRC_CONF_LIST::iterator _itr = m_confList.begin(); _itr != _end; ++_itr) { if (_itr->GetRsrcConfId() == confId) return (CConfRsrc*)(&(*_itr)); } return NULL; } //////////////////////////////////////////////////////////////////////////// STATUS CConfRsrcDB::GetMonitorIdsRsrcIds(ConfRsrcID confId, PartyRsrcID partyId, ConfMonitorID& monitorConfId, PartyMonitorID& monitorPartyId) { monitorConfId = 0xFFFFFFFF; monitorPartyId = 0xFFFFFFFF; RSRC_CONF_LIST::iterator _end = m_confList.end(); for (RSRC_CONF_LIST::iterator _itr = m_confList.begin(); _itr != _end; ++_itr) { if (_itr->GetRsrcConfId() == confId) { monitorConfId = _itr->GetMonitorConfId(); const CPartyRsrc* pParty = _itr->GetPartyRsrcByRsrcPartyId(partyId); if (pParty) { monitorPartyId = pParty->GetMonitorPartyId(); return STATUS_OK; } } } return STATUS_FAIL; } //////////////////////////////////////////////////////////////////////////// bool CConfRsrcDB::IsExitingConf(ConfMonitorID confId) { const CConfRsrc* pConfRsrc = GetConfRsrc(confId); return (pConfRsrc == NULL)? false : true; } //////////////////////////////////////////////////////////////////////////// bool CConfRsrcDB::IsEmptyConf(ConfMonitorID confId) { CConfRsrc* pConfRsrc = GetConfRsrc(confId); PASSERT_AND_RETURN_VALUE(!pConfRsrc, true); return pConfRsrc->GetNumParties() ? false : true; } //////////////////////////////////////////////////////////////////////////// ConfRsrcID CConfRsrcDB::MonitorToRsrcConfId(ConfMonitorID confId) { CConfRsrc* pConfRsrc = GetConfRsrc(confId); return pConfRsrc ? pConfRsrc->GetRsrcConfId() : 0; } //////////////////////////////////////////////////////////////////////////// void CConfRsrcDB::GetAllPartiesOnBoard(WORD boardId, WORD subBoardId, std::map<std::string, CONF_PARTY_ID_S*>* listOfConfIdPartyIdPair) { RSRC_CONF_LIST::iterator _end = m_confList.end(); for (RSRC_CONF_LIST::iterator _itr = m_confList.begin(); _itr != _end; ++_itr) _itr->AddListOfPartiesDescriptorsOnBoard(boardId, subBoardId, listOfConfIdPartyIdPair); } //////////////////////////////////////////////////////////////////////////// void CConfRsrcDB::FillISDNServiceName(ConfMonitorID confId, PartyMonitorID partyId, char serviceName[GENERAL_SERVICE_PROVIDER_NAME_LEN]) { CSystemResources* pSystemResources = CHelperFuncs::GetSystemResources(); PASSERT_AND_RETURN(!pSystemResources); const CConfRsrc* pConfRsrc = GetConfRsrc(confId); TRACECOND_AND_RETURN(!pConfRsrc, "MonitorConfId:" << confId << " - Failed, conference not found"); const CPartyRsrc* pPartyRsrc = pConfRsrc->GetParty(partyId); TRACECOND_AND_RETURN(!pPartyRsrc, "MonitorPartyId:" << partyId << " - Failed, participant not found"); CRsrcDesc** pRsrcDescArray = new CRsrcDesc*[MAX_NUM_ALLOCATED_RSRCS_NET]; for (int i = 0 ; i < MAX_NUM_ALLOCATED_RSRCS_NET ; i++) pRsrcDescArray[i] = NULL; // Get all resource descriptors of RTM per a given party pConfRsrc->GetDescArrayPerResourceTypeByRsrcId(pPartyRsrc->GetRsrcPartyId(), eLogical_net, pRsrcDescArray); if (pRsrcDescArray[0] == NULL) { TRACEINTO << "MonitorPartyId:" << partyId << " - Failed, RTMs not found for party"; delete []pRsrcDescArray; return; } WORD boardId = pRsrcDescArray[0]->GetBoardId(); WORD unitId = pRsrcDescArray[0]->GetUnitId(); delete []pRsrcDescArray; CBoard* pBoard = pSystemResources->GetBoard(boardId); PASSERT_AND_RETURN(!pBoard); const CSpanRTM* pSpan = pBoard->GetRTM(unitId); PASSERT_AND_RETURN(!pSpan); const char* serviceNameFromSpan = pSpan->GetSpanServiceName(); if (serviceNameFromSpan) strcpy_safe(serviceName, sizeof(serviceName), serviceNameFromSpan); } //////////////////////////////////////////////////////////////////////////// PartyRsrcID CConfRsrcDB::MonitorToRsrcPartyId(ConfMonitorID confId, PartyMonitorID partyId) { const CConfRsrc* pConfRsrc = GetConfRsrc(confId); if (pConfRsrc) { const CPartyRsrc* pPartyRsrc = pConfRsrc->GetParty(partyId); if (pPartyRsrc) return pPartyRsrc->GetRsrcPartyId(); } return 0; } //////////////////////////////////////////////////////////////////////////// bool CConfRsrcDB::GetPartyType(ConfMonitorID confId, PartyMonitorID partyId, eNetworkPartyType& networkPartyType, eVideoPartyType& videoPartyType, ePartyRole& partyRole, WORD& artChannels, eSessionType& sessionType) { const CConfRsrc* pConfRsrc = GetConfRsrc(confId); TRACECOND_AND_RETURN_VALUE(!pConfRsrc, "MonitorConfId:" << confId << " - Failed, conference not found", false); const CPartyRsrc* pPartyRsrc = pConfRsrc->GetParty(partyId); TRACECOND_AND_RETURN_VALUE(!pPartyRsrc, "MonitorPartyId:" << partyId << " - Failed, participant not found", false); networkPartyType = pPartyRsrc->GetNetworkPartyType(); videoPartyType = pPartyRsrc->GetVideoPartyType(); partyRole = pPartyRsrc->GetPartyRole(); artChannels = pPartyRsrc->GetARTChannels(); sessionType = pConfRsrc->GetSessionType(); return true; }
[ "somesh.ballia@gmail.com" ]
somesh.ballia@gmail.com
6a64a230ab987ed9f0e640e585cc2e619ff10e8e
b5dca27578786a05a64ee5cbcdac8b85758cc4f6
/Week1/week1-1-bootStrap.cpp
7b7fefc9b981bbb40698ca7adc5392b0bedd72d2
[]
no_license
KieraBacon/GameEngineDevelopment
a7f90df937cb00890b50678e7ea68d3e1b2ac8d6
7ce0420cd40b223bd9df0f54521de6234350ee5d
refs/heads/master
2023-09-04T03:10:48.472815
2021-10-17T06:17:52
2021-10-17T06:17:52
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
3,038
cpp
/*------------------------------------------------------------------------- Welcome to OGRE Object-Oriented Graphics Rendering Engine Minimum code xcopy /y $(ogre_home_v2)\build\bin\debug\*.* $(ProjectDir)x64\debug\ copy /y "C:\Hooman\GBC\GAME3121\Course Materials\GameEngineDevelopment\ogre-sdk-v2.1\build\bin\debug\*.*" "C:\Hooman\GBC\GAME3121\Week1\Week1\$(projectname)\x64\debug\" -------------------------------------------------------------------------*/ //! [fullsource] #include "Ogre.h" #include "OgreApplicationContext.h" #include "OgreInput.h" #include "OgreRTShaderSystem.h" #include <iostream> using namespace Ogre; using namespace OgreBites; class BasicTutorial1 : public ApplicationContext , public InputListener { public: BasicTutorial1(); virtual ~BasicTutorial1() {} void setup(); bool keyPressed(const KeyboardEvent& evt); }; BasicTutorial1::BasicTutorial1() : ApplicationContext("OgreTemplate-V2") { } void BasicTutorial1::setup() { // do not forget to call the base first ApplicationContext::setup(); addInputListener(this); // get a pointer to the already created root Root* root = getRoot(); SceneManager* scnMgr = root->createSceneManager(); // register our scene with the RTSS RTShader::ShaderGenerator* shadergen = RTShader::ShaderGenerator::getSingletonPtr(); shadergen->addSceneManager(scnMgr); //// without light we would just get a black screen //Ogre::Light* light = scnMgr->createLight("MainLight"); //Ogre::SceneNode* lightNode = scnMgr->getRootSceneNode()->createChildSceneNode(); //lightNode->setPosition(0, 10, 15); //lightNode->attachObject(light); //scnMgr->setAmbientLight(ColourValue(1.0, 0.0, 0.0)); //// also need to tell where we are //Ogre::SceneNode* camNode = scnMgr->getRootSceneNode()->createChildSceneNode(); //camNode->setPosition(0, 0, 15); //camNode->lookAt(Ogre::Vector3(0, 0, -1), Ogre::Node::TS_PARENT); //// create the camera //Ogre::Camera* cam = scnMgr->createCamera("myCam"); //cam->setNearClipDistance(5); // specific to this sample //cam->setAutoAspectRatio(true); //camNode->attachObject(cam); //// and tell it to render into the main window //getRenderWindow()->addViewport(cam); //// finally something to render //Ogre::Entity* ent = scnMgr->createEntity("Sinbad.mesh"); //Ogre::SceneNode* node = scnMgr->getRootSceneNode()->createChildSceneNode(); //node->attachObject(ent); } bool BasicTutorial1::keyPressed(const KeyboardEvent& evt) { if (evt.keysym.sym == SDLK_ESCAPE) { getRoot()->queueEndRendering(); } return true; } int main(int argc, char** argv) { try { BasicTutorial1 app; app.initApp(); app.getRoot()->startRendering(); app.closeApp(); } catch (const std::exception& e) { std::cerr << "Error occurred during execution: " << e.what() << '\n'; return 1; } return 0; } //! [fullsource]
[ "hooman_salamat@yahoo.com" ]
hooman_salamat@yahoo.com
fde7c6cfbc63c7a0c1dd0d967b977e264112cbc1
618729b2291385cd51e395db1dbca933439312b4
/os.cpp
45d040c176383938996e8c33040817a91f08459f
[]
no_license
grih9/fluffyOS
bfe2bfc7de37366c57d34fa50d1421c344b6a682
f3ed3efd5863d857d76065b04216aa3298a09e0c
refs/heads/master
2023-04-11T07:23:10.383620
2021-04-18T15:49:27
2021-04-18T15:49:27
359,168,571
0
0
null
null
null
null
UTF-8
C++
false
false
1,815
cpp
#include <stdio.h> #include "sys.h" #include "rtos_api.h" // Инициализация стеков void InitializeStacks(int numStack) { char cushionSpace[100000]; cushionSpace[99999] = 1; // отключаем оптимизацию массивов for (int i = 0; i <= MAX_TASK; ++i) { if (!setjmp(InitStacks[i])) { continue; } else { TaskQueue[RunningTask].entry(); break; } } } int StartOS(TTaskCall entry, int priority, char *name) { RunningTask = TaskHead = -1; TaskCount = 0; //подсчет задач FreeTask = 0; //ожидающие задачи printf("StartOS!\n"); InitializeStacks(0); //инициализация стека for (int i = 0; i < MAX_TASK; i++) { TaskQueue[i].next = i + 1; // номер массива на след элемент TaskQueue[i].prev = i - 1; // пред элемент TaskQueue[i].task_state = TASK_SUSPENDED; // пометка ожидания (неактивная задача) TaskQueue[i].switch_count = 0; // ключ TaskQueue[i].waiting_events = 0; // ожидание задачи TaskQueue[i].working_events = 0; // сработавшие задачи } // создание массива задач TaskQueue[MAX_TASK - 1].next = 0; // присваиваем последнему элементу 0 TaskQueue[0].prev = MAX_TASK - 1; // присваиваем предпоследний if (!setjmp(MainContext)) { ActivateTask(entry, priority, name); // запускаем функцию активации задачи } return 0; } // Завершает работу системы(задача завершена) void ShutdownOS() { printf("ShutdownOS!\n"); }
[ "tolstikov.gn@edu.spbstu.ru" ]
tolstikov.gn@edu.spbstu.ru
b54eacb64f1d68645984c5b1e71e92db1c534771
332515cb827e57f3359cfe0562c5b91d711752df
/Application_UWP_WinRT/Generated Files/winrt/impl/Windows.UI.Xaml.Printing.2.h
5e5ea5bc06e58dbf3fb9e73050c826b0a0063b8c
[ "MIT" ]
permissive
GCourtney27/DX12-Simple-Xbox-Win32-Application
7c1f09abbfb768a1d5c2ab0d7ee9621f66ad85d5
4f0bc4a52aa67c90376f05146f2ebea92db1ec57
refs/heads/master
2023-02-19T06:54:18.923600
2021-01-24T08:18:19
2021-01-24T08:18:19
312,744,674
1
0
null
null
null
null
UTF-8
C++
false
false
4,542
h
// WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.201113.7 #ifndef WINRT_Windows_UI_Xaml_Printing_2_H #define WINRT_Windows_UI_Xaml_Printing_2_H #include "winrt/impl/Windows.UI.Xaml.1.h" #include "winrt/impl/Windows.UI.Xaml.Printing.1.h" WINRT_EXPORT namespace winrt::Windows::UI::Xaml::Printing { struct AddPagesEventHandler : Windows::Foundation::IUnknown { AddPagesEventHandler(std::nullptr_t = nullptr) noexcept {} AddPagesEventHandler(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IUnknown(ptr, take_ownership_from_abi) {} template <typename L> AddPagesEventHandler(L lambda); template <typename F> AddPagesEventHandler(F* function); template <typename O, typename M> AddPagesEventHandler(O* object, M method); template <typename O, typename M> AddPagesEventHandler(com_ptr<O>&& object, M method); template <typename O, typename M> AddPagesEventHandler(weak_ref<O>&& object, M method); auto operator()(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::Printing::AddPagesEventArgs const& e) const; }; struct GetPreviewPageEventHandler : Windows::Foundation::IUnknown { GetPreviewPageEventHandler(std::nullptr_t = nullptr) noexcept {} GetPreviewPageEventHandler(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IUnknown(ptr, take_ownership_from_abi) {} template <typename L> GetPreviewPageEventHandler(L lambda); template <typename F> GetPreviewPageEventHandler(F* function); template <typename O, typename M> GetPreviewPageEventHandler(O* object, M method); template <typename O, typename M> GetPreviewPageEventHandler(com_ptr<O>&& object, M method); template <typename O, typename M> GetPreviewPageEventHandler(weak_ref<O>&& object, M method); auto operator()(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::Printing::GetPreviewPageEventArgs const& e) const; }; struct PaginateEventHandler : Windows::Foundation::IUnknown { PaginateEventHandler(std::nullptr_t = nullptr) noexcept {} PaginateEventHandler(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IUnknown(ptr, take_ownership_from_abi) {} template <typename L> PaginateEventHandler(L lambda); template <typename F> PaginateEventHandler(F* function); template <typename O, typename M> PaginateEventHandler(O* object, M method); template <typename O, typename M> PaginateEventHandler(com_ptr<O>&& object, M method); template <typename O, typename M> PaginateEventHandler(weak_ref<O>&& object, M method); auto operator()(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::Printing::PaginateEventArgs const& e) const; }; struct __declspec(empty_bases) AddPagesEventArgs : Windows::UI::Xaml::Printing::IAddPagesEventArgs { AddPagesEventArgs(std::nullptr_t) noexcept {} AddPagesEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::UI::Xaml::Printing::IAddPagesEventArgs(ptr, take_ownership_from_abi) {} AddPagesEventArgs(); }; struct __declspec(empty_bases) GetPreviewPageEventArgs : Windows::UI::Xaml::Printing::IGetPreviewPageEventArgs { GetPreviewPageEventArgs(std::nullptr_t) noexcept {} GetPreviewPageEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::UI::Xaml::Printing::IGetPreviewPageEventArgs(ptr, take_ownership_from_abi) {} GetPreviewPageEventArgs(); }; struct __declspec(empty_bases) PaginateEventArgs : Windows::UI::Xaml::Printing::IPaginateEventArgs { PaginateEventArgs(std::nullptr_t) noexcept {} PaginateEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::UI::Xaml::Printing::IPaginateEventArgs(ptr, take_ownership_from_abi) {} PaginateEventArgs(); }; struct __declspec(empty_bases) PrintDocument : Windows::UI::Xaml::Printing::IPrintDocument, impl::base<PrintDocument, Windows::UI::Xaml::DependencyObject>, impl::require<PrintDocument, Windows::UI::Xaml::IDependencyObject, Windows::UI::Xaml::IDependencyObject2> { PrintDocument(std::nullptr_t) noexcept {} PrintDocument(void* ptr, take_ownership_from_abi_t) noexcept : Windows::UI::Xaml::Printing::IPrintDocument(ptr, take_ownership_from_abi) {} PrintDocument(); [[nodiscard]] static auto DocumentSourceProperty(); }; } #endif
[ "garrett1168@outlook.com" ]
garrett1168@outlook.com
b56f31f90bc45ba01659c0eaa91e4a1a7765a6dc
41ec4ea912f7e9bb908b11c6c76ae0c00217d6d9
/DM2122 Prac/Source/Currency.cpp
3840ef4c4a4c1abb76fd45073300c6e3ba6daad4
[]
no_license
Bell011/SP2
f46ced4ce2ca215e4f973f1ad74ea84e31e56e59
a36dbcf770dc826e6214274d62a364f31d42a93b
refs/heads/master
2021-01-05T06:43:46.803721
2020-03-01T15:35:08
2020-03-01T15:35:08
240,514,116
0
0
null
null
null
null
UTF-8
C++
false
false
214
cpp
#include "Currency.h" //int Currency::money = 500; Currency::Currency(int m) { money = m; } Currency::~Currency() { } int Currency::getMoney() { return money; } void Currency::setMoney(int m) { money = m; }
[ "49388422+wt0412@users.noreply.github.com" ]
49388422+wt0412@users.noreply.github.com
90e7de7b20078ef820c8452dca297570de5bbe97
959e014804f834564af221244cfb858a76f0907e
/src/NN/CellList/CellNNIteratorRuntime.hpp
b8c6d5c600658a200aad127391c7ee369464f09e
[]
no_license
rurban/openfpm_data_1.1.0
4626ab6fba2098c2d24f3634f3e2cf75c29eb18f
e8bb5c4ba150d13596b11daa40098612b7638c81
refs/heads/master
2023-06-24T16:29:45.223597
2019-06-05T15:23:18
2019-06-05T15:23:18
144,209,213
0
0
null
null
null
null
UTF-8
C++
false
false
5,532
hpp
/* * CellNNIteratorRuntime.hpp * * Created on: Nov 18, 2016 * Author: i-bird */ #ifndef OPENFPM_DATA_SRC_NN_CELLLIST_CELLNNITERATORRUNTIME_HPP_ #define OPENFPM_DATA_SRC_NN_CELLLIST_CELLNNITERATORRUNTIME_HPP_ #include "util/mathutil.hpp" #define FULL openfpm::math::pow(3,dim) #define SYM openfpm::math::pow(3,dim)/2 + 1 #define CRS openfpm::math::pow(2,dim) #define NO_CHECK 1 #define SAFE 2 #define RUNTIME -1 /*! \brief Iterator for the neighborhood of the cell structures * * In general you never create it directly but you get it from the CellList structures * * It iterate across all the element of the selected cell and the near cells * * \note to calculate quantities that involve a total reduction (like energies) use the CellIteratorSymRed * * \tparam dim dimensionality of the space where the cell live * \tparam Cell cell type on which the iterator is working * \tparam impl implementation specific options NO_CHECK do not do check on access, SAFE do check on access * */ template<unsigned int dim, typename Cell,unsigned int impl> class CellNNIterator<dim,Cell,RUNTIME,impl> { protected: //! actual element id const typename Cell::Mem_type_type::loc_index * start_id; //! stop id to read the end of the cell const typename Cell::Mem_type_type::loc_index * stop_id; //! Actual NNc_id; size_t NNc_id; //! Size of the neighboring cells size_t NNc_size; //! Center cell, or cell for witch we are searching the NN-cell const long int cell; //! actual cell id = NNc[NNc_id]+cell stored for performance reason size_t cell_id; //! Cell list Cell & cl; //! NN cell id const long int * NNc; /*! \brief Select non-empty cell * */ inline void selectValid() { while (start_id == stop_id) { NNc_id++; // No more Cell if (NNc_id >= NNc_size) return; cell_id = NNc[NNc_id] + cell; start_id = &cl.getStartId(cell_id); stop_id = &cl.getStopId(cell_id); } } private: public: /*! \brief * * Cell NN iterator * * \param cell Cell id * \param NNc Cell neighborhood indexes (relative) * \param NNc_size size of the neighborhood * \param cl Cell structure * */ inline CellNNIterator(size_t cell, const long int * NNc, size_t NNc_size, Cell & cl) :NNc_id(0),NNc_size(NNc_size),cell(cell),cell_id(NNc[NNc_id] + cell),cl(cl),NNc(NNc) { start_id = &cl.getStartId(cell_id); stop_id = &cl.getStopId(cell_id); selectValid(); } /*! \brief Check if there is the next element * * \return true if there is the next element * */ inline bool isNext() { if (NNc_id >= NNc_size) return false; return true; } /*! \brief take the next element * * \return itself * */ inline CellNNIterator & operator++() { start_id++; selectValid(); return *this; } /*! \brief Get the value of the cell * * \return the next element object * */ inline const typename Cell::Mem_type_type::loc_index & get() { return cl.get_lin(start_id); } }; /*! \brief Symmetric iterator for the neighborhood of the cell structures * * In general you never create it directly but you get it from the CellList structures * * It iterate across all the element of the selected cell and the near cells. * * \note if we query the neighborhood of p and q is the neighborhood of p * when we will query the neighborhood of q p is not present. This is * useful to implement formula like \f$ \sum_{q = neighborhood(p) and p <= q} \f$ * * \tparam dim dimensionality of the space where the cell live * \tparam Cell cell type on which the iterator is working * \tparam NNc_size neighborhood size * \tparam impl implementation specific options NO_CHECK do not do check on access, SAFE do check on access * */ template<unsigned int dim, typename Cell,unsigned int impl> class CellNNIteratorSym<dim,Cell,RUNTIME,impl> : public CellNNIterator<dim,Cell,RUNTIME,impl> { //! index of the particle p size_t p; //! Position of the particle p const openfpm::vector<Point<dim,typename Cell::stype>> & v; /*! Select the next valid element * */ inline void selectValid() { if (this->NNc[this->NNc_id] == 0) { while (this->start_id < this->stop_id) { size_t q = this->cl.get_lin(this->start_id); for (long int i = dim-1 ; i >= 0 ; i--) { if (v.template get<0>(p)[i] < v.template get<0>(q)[i]) return; else if (v.template get<0>(p)[i] > v.template get<0>(q)[i]) goto next; } if (q >= p) return; next: this->start_id++; } CellNNIterator<dim,Cell,RUNTIME,impl>::selectValid(); } else { CellNNIterator<dim,Cell,RUNTIME,impl>::selectValid(); } } public: /*! \brief * * Cell NN iterator * * \param cell Cell id * \param p index of the particle from which we are searching the neighborhood particles * \param NNc Cell neighborhood indexes (relative) * \param cl Cell structure * */ inline CellNNIteratorSym(size_t cell, size_t p, const long int * NNc, size_t NNc_size, Cell & cl, const openfpm::vector<Point<dim,typename Cell::stype>> & v) :CellNNIterator<dim,Cell,RUNTIME,impl>(cell,NNc,NNc_size,cl),p(p),v(v) { if (this->NNc_id >= this->NNc_size) return; selectValid(); } /*! \brief take the next element * * \return itself * */ inline CellNNIteratorSym<dim,Cell,RUNTIME,impl> & operator++() { this->start_id++; selectValid(); return *this; } }; #endif /* OPENFPM_DATA_SRC_NN_CELLLIST_CELLNNITERATORRUNTIME_HPP_ */
[ "incardon@mpi-cbg.de" ]
incardon@mpi-cbg.de
4c76f75b20942941b0554679ea78f9c18c709f74
c27df8ce4903389256023f71fc8004c6caf41d21
/examples/common/15_tim_usonic/main.cpp
6de553fd9ed6fd2a348a75f8890e2366befaf687
[]
no_license
atu-guda/stm32oxc
be8f584e6978fa40482bbd5df4a23bd6b41329eb
591b43246b8928329642b06bad8b9de6802e62ed
refs/heads/master
2023-09-03T08:42:36.058233
2023-09-02T19:15:15
2023-09-02T19:15:15
34,165,176
5
0
null
null
null
null
UTF-8
C++
false
false
3,877
cpp
#include <oxc_auto.h> #include <oxc_tim.h> using namespace std; using namespace SMLRL; USE_DIE4LED_ERROR_HANDLER; BOARD_DEFINE_LEDS; BOARD_CONSOLE_DEFINES; const char* common_help_string = "App to test US-014 ultrasonic sensor with timer" NL; TIM_HandleTypeDef tim_h; void init_usonic(); // --- local commands; int cmd_test0( int argc, const char * const * argv ); CmdInfo CMDINFO_TEST0 { "test0", 'T', cmd_test0, " [n] - test sensor" }; const CmdInfo* global_cmds[] = { DEBUG_CMDS, &CMDINFO_TEST0, nullptr }; int main(void) { BOARD_PROLOG; UVAR('t') = 1000; UVAR('n') = 20; BOARD_POST_INIT_BLINK; pr( NL "##################### " PROJ_NAME NL ); srl.re_ps(); oxc_add_aux_tick_fun( led_task_nortos ); init_usonic(); delay_ms( 50 ); std_main_loop_nortos( &srl, nullptr ); return 0; } // TEST0 int cmd_test0( int argc, const char * const * argv ) { int n = arg2long_d( 1, argc, argv, UVAR('n'), 0 ); uint32_t t_step = UVAR('t'); std_out << NL "Test0: n= " << n << " t= " << t_step << NL; tim_print_cfg( TIM_EXA ); delay_ms( 10 ); uint32_t tm0 = HAL_GetTick(); break_flag = 0; for( int i=0; i<n && !break_flag; ++i ) { std_out << "[" << i << "] l= " << UVAR('l') << NL; std_out.flush(); delay_ms_until_brk( &tm0, t_step ); } return 0; } // ----------------------------- configs ---------------- void init_usonic() { // 5.8 mks approx 1mm 170000 = v_c/2 in mm/s, 998 or 846 tim_h.Init.Prescaler = calc_TIM_psc_for_cnt_freq( TIM_EXA, 170000 ); tim_h.Instance = TIM_EXA; tim_h.Init.Period = 8500; // F approx 20Hz: for future motor PWM tim_h.Init.ClockDivision = 0; tim_h.Init.CounterMode = TIM_COUNTERMODE_UP; tim_h.Init.RepetitionCounter = 0; if( HAL_TIM_PWM_Init( &tim_h ) != HAL_OK ) { UVAR('e') = 1; // like error return; } TIM_ClockConfigTypeDef sClockSourceConfig; sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL; HAL_TIM_ConfigClockSource( &tim_h, &sClockSourceConfig ); TIM_OC_InitTypeDef tim_oc_cfg; tim_oc_cfg.OCMode = TIM_OCMODE_PWM1; tim_oc_cfg.OCPolarity = TIM_OCPOLARITY_HIGH; tim_oc_cfg.OCNPolarity = TIM_OCNPOLARITY_HIGH; tim_oc_cfg.OCFastMode = TIM_OCFAST_DISABLE; tim_oc_cfg.OCIdleState = TIM_OCIDLESTATE_RESET; tim_oc_cfg.OCNIdleState = TIM_OCNIDLESTATE_RESET; tim_oc_cfg.Pulse = 3; // 3 = approx 16 us if( HAL_TIM_PWM_ConfigChannel( &tim_h, &tim_oc_cfg, TIM_CHANNEL_1 ) != HAL_OK ) { UVAR('e') = 11; return; } if( HAL_TIM_PWM_Start( &tim_h, TIM_CHANNEL_1 ) != HAL_OK ) { UVAR('e') = 12; return; } TIM_IC_InitTypeDef tim_ic_cfg; // tim_ic_cfg.ICPolarity = TIM_ICPOLARITY_RISING; tim_ic_cfg.ICPolarity = TIM_ICPOLARITY_BOTHEDGE; // rising - start, falling - stop tim_ic_cfg.ICSelection = TIM_ICSELECTION_DIRECTTI; tim_ic_cfg.ICPrescaler = TIM_ICPSC_DIV1; tim_ic_cfg.ICFilter = 0; // 0 - 0x0F if( HAL_TIM_IC_ConfigChannel( &tim_h, &tim_ic_cfg, TIM_CHANNEL_2 ) != HAL_OK ) { UVAR('e') = 21; return; } HAL_NVIC_SetPriority( TIM_EXA_IRQ, 7, 0 ); HAL_NVIC_EnableIRQ( TIM_EXA_IRQ ); if( HAL_TIM_IC_Start_IT( &tim_h, TIM_CHANNEL_2 ) != HAL_OK ) { UVAR('e') = 23; } } void TIM_EXA_IRQHANDLER(void) { HAL_TIM_IRQHandler( &tim_h ); } void HAL_TIM_IC_CaptureCallback( TIM_HandleTypeDef *htim ) { uint32_t cap2; static uint32_t c_old = 0xFFFFFFFF; if( htim->Channel == HAL_TIM_ACTIVE_CHANNEL_2 ) { cap2 = HAL_TIM_ReadCapturedValue( htim, TIM_CHANNEL_2 ); if( cap2 > c_old ) { UVAR('l') = cap2 - c_old ; leds.reset( BIT2 ); } else { leds.set( BIT2 ); } c_old = cap2; UVAR('m') = cap2; UVAR('z') = htim->Instance->CNT; } } // vim: path=.,/usr/share/stm32cube/inc/,/usr/arm-none-eabi/include,/usr/share/stm32oxc/inc
[ "atu@nmetau.edu.ua" ]
atu@nmetau.edu.ua
181a9dfd827524c75789617744e569536f5485aa
8c8ea797b0821400c3176add36dd59f866b8ac3d
/AOJ/aoj0025.cpp
c2403359a69322f0b035d629e82f658fe2bce624
[]
no_license
fushime2/competitive
d3d6d8e095842a97d4cad9ca1246ee120d21789f
b2a0f5957d8ae758330f5450306b629006651ad5
refs/heads/master
2021-01-21T16:00:57.337828
2017-05-20T06:45:46
2017-05-20T06:45:46
78,257,409
0
0
null
null
null
null
UTF-8
C++
false
false
594
cpp
#include <iostream> #include <map> #include <vector> using namespace std; #define N 4 int main(void) { ios::sync_with_stdio(false); int a[N], b[N]; int hit, blow; while(cin >> a[0] >> a[1] >> a[2] >> a[3], !cin.eof()) { for(int i=0; i<N; i++) cin >> b[i]; hit = blow = 0; for(int i=0; i<N; i++) { for(int j=0; j<N; j++) { if(a[i] == b[j]) { if(i == j) hit++; else blow++; } } } cout << hit << " " << blow << endl; } return 0; }
[ "okmt52@gmail.com" ]
okmt52@gmail.com
def0afc4d292baf33836a74b2a8f061db998708c
8fbac4a872eb60796bd30d6c73aaa652a5e0f0d7
/samples/softrender/Textures.cpp
62e5ec927e800668aceb7bfe81fe6f94d81f59df
[ "MIT" ]
permissive
brucelevis/SoftRender
7914382d1b58f816fec3b5cb2c53c2c48213387b
8089844e9ab00ab71ef1a820641ec07ae8df248d
refs/heads/master
2020-04-18T11:50:32.233918
2018-09-06T04:42:49
2018-09-06T04:42:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,328
cpp
// // Created by huangkun on 2018/8/19. // #include "Textures.h" TEST_NODE_IMP_BEGIN Textures::Textures() { TEX_WIDTH = 1024; TEX_HEIGHT = 1024; } bool Textures::init() { SoftRender::init(); verticesPlane = { // postions // texture coords 0.5f, 0.5f, 0.0f, 2.0f, 2.0f, // top right 0.5f, -0.5f, 0.0f, 2.0f, -1.0f, // bottom right -0.5f, -0.5f, 0.0f, -1.0f, -1.0f, // bottom left -0.5f, 0.5f, 0.0f, -1.0f, 2.0f, // bottom top }; indicesPlane = { // note that we start from 0! 0, 1, 3, // first triangle 1, 2, 3 // second triangle }; Mesh *mesh = new Mesh(createVertexs(verticesPlane, 3, 0, 2), indicesPlane); planeMeshes.push_back(mesh); texture2D.load("../res/cat.jpg"); return true; } void Textures::draw(const mat4 &transform) { clearColor(25, 25, 25, 255); modelMatrix.setIdentity(); viewMatrix.setIdentity(); projectMatrix.setIdentity(); // top left modelMatrix.translate(Vector(-0.5f, 0.5f, 0)); Matrix m = modelMatrix; m.mult(viewMatrix); m.mult(projectMatrix); bindTextures({&texture2D}); texture2D.setWrap(GL_REPEAT); for (unsigned int i = 0; i < planeMeshes.size(); i++) drawMesh(*planeMeshes[i], m, 2); // top right modelMatrix.setIdentity(); modelMatrix.translate(Vector(0.5f, 0.5f, 0)); m = modelMatrix; m.mult(viewMatrix); m.mult(projectMatrix); bindTextures({&texture2D}); texture2D.setWrap(GL_MIRRORED_REPEAT); for (unsigned int i = 0; i < planeMeshes.size(); i++) drawMesh(*planeMeshes[i], m, 2); // bottom left modelMatrix.setIdentity(); modelMatrix.translate(Vector(-0.5f, -0.5f, 0)); m = modelMatrix; m.mult(viewMatrix); m.mult(projectMatrix); bindTextures({&texture2D}); texture2D.setWrap(GL_CLAMP_TO_EDGE); for (unsigned int i = 0; i < planeMeshes.size(); i++) drawMesh(*planeMeshes[i], m, 2); // bottom right modelMatrix.setIdentity(); modelMatrix.translate(Vector(0.5f, -0.5f, 0)); m = modelMatrix; m.mult(viewMatrix); m.mult(projectMatrix); bindTextures({&texture2D}); texture2D.setWrap(GL_CLAMP_TO_BORDER); texture2D.setBorderColor(vec4(255, 255, 0, 255)); for (unsigned int i = 0; i < planeMeshes.size(); i++) drawMesh(*planeMeshes[i], m, 2); SoftRender::draw(transform); } void Textures::setPixel(int x, int y, float z, float u, float v, vec3 varying[], const std::vector<vec3> &uniforms, float dudx, float dvdy) { Texture2D *texture = _bindTextures["texture0"]; if (texture) { const vec3 &textureColor = texture->sample(u, v, dudx, dvdy); vec4 color = vec4(vec3(textureColor), 255); SoftRender::setPixel(x, y, z, color); } } Textures::~Textures() { for (unsigned int i = 0; i < planeMeshes.size(); i++) delete planeMeshes[i]; } TEST_NODE_IMP_END
[ "huangkunkunkun@gmail.com" ]
huangkunkunkun@gmail.com