blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
955 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
143 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
121 values
content
stringlengths
3
10.4M
authors
sequencelengths
1
1
author_id
stringlengths
0
158
36a545137c7c8972f084997716e578ad86d3ac15
afcce85e08d8fc5141a840fe77bf7bf93f49df54
/tests/2015-09-10/fft_shift/main.cpp
5fd27aab9e2480a56af1d2bf0dfe2ab2e4eeaa98
[]
no_license
icopavan/Automatic-Modulation-Classification-ELEN4012
ff8f58a467129b371a9d2b042169fc99620b2959
d72e3b4d36ad88b2872a8b33606c120f18b974e6
refs/heads/master
2021-01-12T21:07:15.807363
2015-10-09T21:29:56
2015-10-09T21:29:56
44,043,227
2
1
null
2015-10-11T07:30:41
2015-10-11T07:30:40
null
UTF-8
C++
false
false
910
cpp
#include "mainwindow.h" #include <QApplication> #include <fftw3.h> #include <cmath> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); double PI = 4 * atan(1); int N = 512; // number of samples double fs = 10e3; // sampling frequency double fc = 1000; // signal frequency double t[N]; fftw_complex * x = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N); double f[N]; // calculation for (int n = 0; n < N; ++n) { t[n] = n/fs; x[n][0] = cos(2*PI*fc*t[n]); x[n][1] = 0; f[n] = (n - N/2) * fs / (N-1); } fftw_complex *out; fftw_plan plan_forward; out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N); plan_forward = fftw_plan_dft_1d(N, x, out, FFTW_FORWARD, FFTW_ESTIMATE); fftw_execute(plan_forward); w.plot(f, out, N); return a.exec(); }
0e5baca75fdd2c54621542f6cf7b7bde1bdf4164
fdebe3129bb47afc1924e45e1ed3c97ee9213ac4
/GA-TSP/test.cpp
3bbfaacce92afe022185cf0c23ee0c0d44e5e17d
[]
no_license
SYSU532/artificial-intelligence
3604e07b3670555d65ac2d36dbbf458f69658a07
e0847fb1d181415137580e1c3e529e2120ed09d4
refs/heads/master
2020-04-05T20:26:14.953187
2019-01-11T12:50:27
2019-01-11T12:50:27
157,179,948
0
0
null
null
null
null
UTF-8
C++
false
false
1,044
cpp
#include <node.h> namespace demo{ using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Object; using v8::String; using v8::Value; using v8::Number; // Method1 实现一个 输出"hello world ONE !" 的方法 void Method1(const FunctionCallbackInfo<Value>& args){ Isolate* isolate = args.GetIsolate(); args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world ONE !")); } // Method2 实现一个 加一 的方法 void Method2(const FunctionCallbackInfo<Value>& args){ Isolate* isolate = args.GetIsolate(); Local<Number> value = Local<Number>::Cast(args[0]); double num = value->NumberValue() + 1; char buf[128] = {0}; sprintf(buf,"%f", num); args.GetReturnValue().Set(String::NewFromUtf8(isolate, buf)); } void init(Local<Object> exports){ NODE_SET_METHOD(exports, "hello1", Method1); NODE_SET_METHOD(exports, "addOne", Method2); } NODE_MODULE(addon, init) }
cbee84c2e52dc1341528f8254aaf41ac321f936c
2869112fdc836e565f9fe68e290affc1e223c1d8
/pythran/pythonic/include/__builtin__/set/isdisjoint.hpp
10ac38270e03ff35d15b79143e6164321a7b5afb
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
coyotte508/pythran
ab26e9ddb9a9e00e77b457df316aa33dc8435914
a5da78f2aebae712a2c6260ab691dab7d09e307c
refs/heads/master
2021-01-15T10:07:09.597297
2015-05-01T07:00:42
2015-05-01T07:00:42
35,020,532
0
0
null
2015-05-04T07:27:29
2015-05-04T07:27:29
null
UTF-8
C++
false
false
621
hpp
#ifndef PYTHONIC_INCLUDE_BUILTIN_SET_ISDISJOINT_HPP #define PYTHONIC_INCLUDE_BUILTIN_SET_ISDISJOINT_HPP #include "pythonic/utils/proxy.hpp" #include "pythonic/types/set.hpp" namespace pythonic { namespace __builtin__ { namespace set { template<class T, class U> bool isdisjoint(types::set<T> const& calling_set, U const& arg_set); template<class U> bool isdisjoint(types::empty_set const& calling_set, U const& arg_set); PROXY_DECL(pythonic::__builtin__::set, isdisjoint); } } } #endif
3025038669b687c8e7bd508bb41b1b5adb4ab7b2
64824c859f6af21ad97edf16fb00a32b81c8e800
/第23节.cpp
01bf003a3ed3a08ee1f72d2bdd25d275403bbf9b
[]
no_license
leigelaing/C-
7ea94df8fed45bc47eb5437eedda5b6cc98bc754
513b5ba2a8891717d4a21e5cfabd935f66071b57
refs/heads/master
2023-04-09T06:49:11.603590
2021-04-20T00:11:38
2021-04-20T00:11:38
296,510,796
0
0
null
null
null
null
GB18030
C++
false
false
1,887
cpp
#include<stdio.h> int Add(int x,int y) { int z = 0; z = x + y; return z; } int main() { int a = 10; int b = 20; int ret = 0; ret = Add(a,b); return 0; } //压栈 /* typedef struct stu { //成员变量 char name[20]; short age; char tele[12]; char sex[5]; }stu; void print1(stu tmp) { printf("name: %s\n",tmp.name); printf(" age: %d\n",tmp.age); printf("tele: %s\n",tmp.tele ); printf(" sex: %s\n",tmp.sex ); } void print2(stu* pa) { printf("name: %s\n",pa->name); printf(" age: %d\n",pa->age); printf("tele: %s\n",pa->tele ); printf(" sex: %s\n",pa->sex ); } int main() { stu s = {"李四",40,"1561341658","男"}; //打印结构体数据 //print1与print2哪个更好 print1浪费空间, print1(s); print2(&s); return 0; } */ /*struct S { int a; char c; char arr[20]; double d; }; struct T { char ch[10]; struct S s; char *pc; }; int main() { char arr[] = "hello bit\n"; struct T t = {"hehe",{100,'w',"hello world",3.14},arr}; printf("%s\n",t.ch); printf("%s\n",t.s.arr); printf("%lf\n",t.s.d); printf("%s\n",t.pc); return 0; } */ /* typedef struct stu { //成员变量 char name[20]; short age; char tele[12]; char sex[5]; }stu; //struct 被改名为 stu int main() { struct stu s1 = {"张三",20,"125226236213","男"};//s局部变量; stu s2 = {"旺财",30,"1646346464646","女"}; return 0; } */ /* //struct 结构体关键字, stu—结构体标签 struct stu—结构体类型(不占用内存空间) struct stu { //成员变量 char name[20]; short age; char tele[12]; char sex[5]; }s1,s2,s3;//s1,s2,s3是全局变量 int main() { struct stu s;//s局部变量; return 0; } */
2700f3690854eaf5a2187d2d57c0ce1df9fa0f9f
29288023bde7829066f810540963a7b35573fa31
/BstUsingSet.cpp
4f984176f775caa7499cc3e20cab43944733c536
[]
no_license
Sohail-khan786/Competitve-Programming
6e56bdd8fb7b3660edec50c72f680b6ed2c41a0f
e90dcf557778a4c0310e03539e4f3c1c939bb3a1
refs/heads/master
2022-10-08T06:55:46.637560
2020-06-07T18:39:20
2020-06-07T18:39:20
254,899,456
0
0
null
null
null
null
UTF-8
C++
false
false
718
cpp
#include<bits/stdc++.h> using namespace std; int main() { int flag=1; set<int> s; set<int>::iterator it; int x; while(flag!=3) { cout<<"1.Insert 2.Delete 3.Exit"<<endl; cin>>flag; cout<<"value\t"; cin>>x; if(flag==1) { s.insert(x); } else if(flag==2) { s.erase(x); } cout<<"Extracting max n min from a set"<<cout<<endl; //s.end has iterator to last element of the set which is the size of the set and hence decrement it by one to get the maximum element present in the set; it = s.end(); it--; cout<<"maxx = "<<*(it)<<" minn ="<<*s.begin(); cout<<endl; } return 0; }
06c1ab5ff8ab138987ba9ad1ed0f423d945bafe7
6817617489ef291d4d53ac844ba7a2b14cc17ae2
/11942.cpp
dcc6c32bd3395a76801df96fb6b8693215e020ec
[]
no_license
Asad51/UVA-Problem-Solving
1932f2cd73261cd702f58d4f189a4a134dbd6286
af28ae36a2074d4e2a67670dbbbd507438c56c3e
refs/heads/master
2020-03-23T14:52:49.420143
2019-10-24T17:03:37
2019-10-24T17:03:37
120,592,261
0
0
null
null
null
null
UTF-8
C++
false
false
449
cpp
#include <bits/stdc++.h> using namespace std; int main(int argc, char const *argv[]) { int t; cin>>t; cout<<"Lumberjacks:\n"; while(t--){ bool in = true; bool dec = true; int p; for(int i=0; i<10; i++){ int n; cin>>n; if(!i){ p = n; continue; } if(n<p || !in) in = false; if(n>p || !dec) dec = false; p = n; } if(!in && !dec) cout<<"Unordered\n"; else cout<<"Ordered\n"; } return 0; }
6121382505592535a09b239e90ed50ff680fc2e6
91fcb836ee5af301a2125624ddb96cf49b19494d
/queue/restoreQueue.cpp
2e49fc23784e34f26b2deade801fe414d1b21cb1
[]
no_license
hellozxs/C
fe11911222595ffcdc425218407711bbe59a3b10
1f3815966a8d5668f149ff9957672819a2d2b57d
refs/heads/master
2020-04-06T07:03:14.596747
2016-09-18T10:25:27
2016-09-18T10:25:27
65,121,708
0
0
null
null
null
null
UTF-8
C++
false
false
1,272
cpp
//对一个队列执行以下操作后,发现输出为 1,2,3,4,……,n // 操作:(如果队列不为空) // 1:取队头元素,放入队尾,将队头pop // 2;输出队头,将队头pop // 输入n,求原始队列? // //输入:z -> 表示将要输入的数据的个数 //输入z个n的具体值 #include <iostream> #include <vector> using namespace std; typedef struct MyData { int _data; bool _flag; }MyData; int main() { int z; cin >> z; vector<int> arr(z); for (int i = 0; i < z; i++) { cin >> arr[i]; } int i = 0; for (i = 0; i< z; i++) { if (arr[i] == 1) cout << 1 << endl; else { vector<MyData> a(arr[i]); int j = 0; int count = arr[i]; int tmp = 1; for (; count--; j ++) { int flag = 1; while (flag) { if (j == arr[i]) j = 0; if (a[j]._flag == false) flag--; j++; } if (j == arr[i]) j = 0; while (a[j]._flag == true) { j++; if (j == arr[i]) j = 0; } a[j]._data =tmp++; a[j]._flag = true; } int k = 0; for (; k < arr[i]; k++) cout << a[k]._data << " "; cout << endl; } } return 0; }
d906994d3f90133151039af0434882e3553ba719
1c02e13a776e5e8bc3e2a6182b5df4efb2c71d32
/core/unit_test/tstDeepCopy.hpp
b3fdab4da5ef0b61357d256cf996dae1b69884f0
[ "BSD-3-Clause" ]
permissive
junghans/Cabana
91b82827dd9fb8321bea9ea3750c196946a6aac0
7b9078f81bde68c949fd6ae913ce80eeaf0f8f8a
refs/heads/master
2021-06-14T09:57:01.658234
2019-01-04T22:24:45
2019-01-04T22:24:45
150,330,482
1
1
BSD-3-Clause
2019-01-07T16:24:20
2018-09-25T21:17:53
C++
UTF-8
C++
false
false
5,252
hpp
/**************************************************************************** * Copyright (c) 2018 by the Cabana authors * * All rights reserved. * * * * This file is part of the Cabana library. Cabana is distributed under a * * BSD 3-clause license. For the licensing terms see the LICENSE file in * * the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #include <Cabana_DeepCopy.hpp> #include <Cabana_AoSoA.hpp> #include <Cabana_Types.hpp> #include <gtest/gtest.h> namespace Test { //---------------------------------------------------------------------------// // Check the data given a set of values. template<class aosoa_type> void checkDataMembers( aosoa_type aosoa, const float fval, const double dval, const int ival, const int dim_1, const int dim_2, const int dim_3 ) { auto slice_0 = aosoa.template slice<0>(); auto slice_1 = aosoa.template slice<1>(); auto slice_2 = aosoa.template slice<2>(); auto slice_3 = aosoa.template slice<3>(); for ( std::size_t idx = 0; idx < aosoa.size(); ++idx ) { // Member 0. for ( int i = 0; i < dim_1; ++i ) for ( int j = 0; j < dim_2; ++j ) for ( int k = 0; k < dim_3; ++k ) EXPECT_EQ( slice_0( idx, i, j, k ), fval * (i+j+k) ); // Member 1. EXPECT_EQ( slice_1( idx ), ival ); // Member 2. for ( int i = 0; i < dim_1; ++i ) EXPECT_EQ( slice_2( idx, i ), dval * i ); // Member 3. for ( int i = 0; i < dim_1; ++i ) for ( int j = 0; j < dim_2; ++j ) EXPECT_EQ( slice_3( idx, i, j ), dval * (i+j) ); } } //---------------------------------------------------------------------------// // Perform a deep copy test. template<class DstMemorySpace, class SrcMemorySpace, int DstVectorLength, int SrcVectorLength> void testDeepCopy() { // Data dimensions. const int dim_1 = 3; const int dim_2 = 2; const int dim_3 = 4; // Declare data types. using DataTypes = Cabana::MemberTypes<float[dim_1][dim_2][dim_3], int, double[dim_1], double[dim_1][dim_2] >; // Declare the AoSoA types. using DstAoSoA_t = Cabana::AoSoA<DataTypes,DstMemorySpace,DstVectorLength>; using SrcAoSoA_t = Cabana::AoSoA<DataTypes,SrcMemorySpace,SrcVectorLength>; // Create AoSoAs. int num_data = 357; DstAoSoA_t dst_aosoa( num_data ); SrcAoSoA_t src_aosoa( num_data ); // Initialize data with the rank accessors. float fval = 3.4; double dval = 1.23; int ival = 1; auto slice_0 = src_aosoa.template slice<0>(); auto slice_1 = src_aosoa.template slice<1>(); auto slice_2 = src_aosoa.template slice<2>(); auto slice_3 = src_aosoa.template slice<3>(); for ( std::size_t idx = 0; idx < src_aosoa.size(); ++idx ) { // Member 0. for ( int i = 0; i < dim_1; ++i ) for ( int j = 0; j < dim_2; ++j ) for ( int k = 0; k < dim_3; ++k ) slice_0( idx, i, j, k ) = fval * (i+j+k); // Member 1. slice_1( idx ) = ival; // Member 2. for ( int i = 0; i < dim_1; ++i ) slice_2( idx, i ) = dval * i; // Member 3. for ( int i = 0; i < dim_1; ++i ) for ( int j = 0; j < dim_2; ++j ) slice_3( idx, i, j ) = dval * (i+j); } // Deep copy Cabana::deep_copy( dst_aosoa, src_aosoa ); // Check values. checkDataMembers( dst_aosoa, fval, dval, ival, dim_1, dim_2, dim_3 ); } //---------------------------------------------------------------------------// // TESTS //---------------------------------------------------------------------------// TEST_F( TEST_CATEGORY, deep_copy_to_host_same_layout_test ) { testDeepCopy<Cabana::HostSpace,TEST_MEMSPACE,16,16>(); } //---------------------------------------------------------------------------// TEST_F( TEST_CATEGORY, deep_copy_from_host_same_layout_test ) { testDeepCopy<TEST_MEMSPACE,Cabana::HostSpace,16,16>(); } //---------------------------------------------------------------------------// TEST_F( TEST_CATEGORY, deep_copy_to_host_different_layout_test ) { testDeepCopy<Cabana::HostSpace,TEST_MEMSPACE,16,32>(); testDeepCopy<Cabana::HostSpace,TEST_MEMSPACE,64,8>(); } //---------------------------------------------------------------------------// TEST_F( TEST_CATEGORY, deep_copy_from_host_different_layout_test ) { testDeepCopy<TEST_MEMSPACE,Cabana::HostSpace,64,8>(); testDeepCopy<TEST_MEMSPACE,Cabana::HostSpace,16,32>(); } //---------------------------------------------------------------------------// } // end namespace Test
819eb928fa03acd974c3e18443532022f13c2f05
711b11d08abdb3a7df2574b0b4c86af21c5c6750
/dest.h
e06af74e0264187915ab70b86b0e67aa85d2a79f
[]
no_license
nflath/MSP430Emulator
4aee9e093113cc41d9041a1728eedd742fd786b2
a97a1b97b895b3533597bcdb69bec8b75db395df
refs/heads/master
2021-01-13T01:54:55.258203
2015-08-25T05:10:04
2015-08-25T05:10:04
41,343,926
0
0
null
null
null
null
UTF-8
C++
false
false
2,382
h
#include <assert.h> #ifndef DEST_H #define DEST_H #include "error.h" // Classes representing 'Destinations' types in MSP430 - See the section // 'MSP430 addressing modes' in https://en.wikipedia.org/wiki/TI_MSP430#MSP430_CPU class State; class Dest { // Virtual base clase. public: virtual void set(short value) { notimplemented(); } // Sets the value of this destination virtual void setByte(unsigned char value) { notimplemented(); } // Sets the value of this destination (byte addressing mode) virtual short value() { notimplemented(); return 0;} // Returns the value of this destination virtual unsigned char valueByte() { notimplemented(); return 0;} // Returns the value of this destination(byte addressing mode) virtual std::string toString() = 0; // Returns a string representation of this destination virtual bool usedExtensionWord() { return false; } // Whether an extension word was used to represent this destination virtual unsigned char size() { return usedExtensionWord() ? 2 : 0; } // How many extra bytes this destination took up in the assembly }; class RegisterDest : public Dest { // Destination representing a register (r14) public: virtual std::string toString(); virtual void set(short value); virtual void setByte(unsigned char value); virtual short value(); virtual unsigned char valueByte(); RegisterDest(unsigned short reg_) : reg(reg_) {} unsigned short reg; }; class RegisterOffsetDest : public RegisterDest { // Destination representing the memory address at a register plus an offset (0x40(r14)) public: virtual std::string toString(); virtual bool usedExtensionWord() { return true; } virtual void set(short value); virtual void setByte(unsigned char value); virtual short value(); virtual unsigned char valueByte(); RegisterOffsetDest(unsigned short reg_, short offset_) : RegisterDest(reg_), offset(offset_) { } short offset; }; class AbsoluteDest : public Dest { // Destination that is just a memory address (&0x4400) public: virtual std::string toString(); virtual bool usedExtensionWord() { return true; } virtual void set(short value); virtual void setByte(unsigned char value); virtual unsigned char valueByte(); AbsoluteDest(unsigned short address_) : address(address_) { } unsigned short address; }; extern State* s; #endif
b8319da5f12cfbbbd8ce6c9a50bab4c69b92531e
c4a320a9519cd63bad9be9bcfc022a4fcab5267b
/TETRIS_VS/TETRIS_VS/LobbyBoard.cpp
4e7ef9e1f59c43158f02345d8f894a183007f43e
[]
no_license
shield1203/TETRIS_VS
79dc3d8db0a1107352e46e69a96482a49490a290
3f67f0436674a10f9d37a98286a1f3531e6f7730
refs/heads/master
2020-12-22T00:11:37.323472
2020-03-05T15:28:32
2020-03-05T15:28:32
236,593,352
0
0
null
null
null
null
UTF-8
C++
false
false
401
cpp
#include "stdafx.h" #include "LobbyBoard.h" #include "InputSystem.h" #include "PacketManager.h" LobbyBoard::LobbyBoard() { m_packetManager = PacketManager::getInstance(); m_inputSystem = new InputSystem(); } LobbyBoard::~LobbyBoard() { SafeDelete(m_inputSystem); } void LobbyBoard::Update() { m_inputSystem->CheckKeyboardPressed(); if (m_inputSystem->IsEnterPressed()) { m_on = true; } }
0293e83add680ed3f8e92ecea17c897a91d1270b
1ca3477d99bddb6611f2feb67c8ce0c4569d8a4b
/Memendo.cc
7ac722a8f7b952968a9ec15d38a1c9bbc3afc637
[]
no_license
TaoJun724/DesignPattern
0da37a3a34fba54ba21cb809875b20d9eeba3443
b0c62668cfad5b48b85b413e78ee9334812a74b2
refs/heads/master
2020-06-30T08:57:32.156222
2019-08-07T07:42:09
2019-08-07T07:42:09
200,785,533
0
0
null
null
null
null
UTF-8
C++
false
false
1,461
cc
#include <stdio.h> #include<string> class Memento { public: Memento(int n, std::string s) { _s = s; _money = n; } void setMoney(int n) { _money = n; } int getMoney() { return _money; } void setState(std::string s) { _s = s; } std::string getState() { return _s; } private: int _money; std::string _s; }; class Worker { public: Worker(std::string name, int money, std::string s) { _name = name; _money = money; _s = s; } void show() { printf("%s现在有钱%d元,生活状态%s!\n", _name.c_str(), _money, _s.c_str()); } void setState(int money, std::string s) { _money = money; _s = s; } Memento* createMemnto() { return new Memento(_money,_s); } void restoreMemnto(Memento* m) { _money = m->getMoney(); _s = m->getState(); } private: std::string _name; int _money; std::string _s; }; class WorkerStorage { public: void setMemento(Memento* m) { _memento = m; } Memento* getMement() { return _memento; } private: Memento* _memento; }; int main() { Worker* zhangsan = new Worker("张三", 10000, "富裕"); zhangsan->show(); //记住张三现在的状态 WorkerStorage* storage = new WorkerStorage; storage->setMemento(zhangsan->createMemnto()); //张三赌博输了钱,只剩下10元 zhangsan->setState(10, "贫困"); zhangsan->show(); //经过努力张三又回到了之前的状态。 zhangsan->restoreMemnto(storage->getMement()); zhangsan->show(); return 0; }
bba7327fa47b292b7a2a12379dbea888640a0e70
58790459d953a3e4b6722ed3ee939f82d9de8c3e
/my/PDF插件/sdkDC_v1_win/Adobe/Acrobat DC SDK/Version 1/PluginSupport/PIBrokerSDK/simple-ipc-lib/src/pipe_win.h
4625bef0dc76752fdcc7b3a4966d087839cbd12f
[]
no_license
tisn05/VS
bb84deb993eb18d43d8edaf81afb753afa3d3188
da56d392a518ba21edcb1a367b4b4378d65506f0
refs/heads/master
2020-09-25T05:49:31.713773
2016-08-22T01:22:16
2016-08-22T01:22:16
66,229,337
0
1
null
null
null
null
UTF-8
C++
false
false
1,659
h
// Copyright (c) 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef SIMPLE_IPC_PIPE_WIN_H_ #define SIMPLE_IPC_PIPE_WIN_H_ #include "os_includes.h" #include "ipc_constants.h" class PipePair { public: PipePair(bool inherit_fd2 = false); HANDLE fd1() const { return srv_; } HANDLE fd2() const { return cln_; } static HANDLE OpenPipeServer(const wchar_t* name, bool low_integrity = false); static HANDLE OpenPipeClient(const wchar_t* name, bool inherit, bool impersonate); private: HANDLE srv_; HANDLE cln_; }; class PipeWin { public: PipeWin(); ~PipeWin(); bool OpenClient(HANDLE pipe); bool OpenServer(HANDLE pipe, bool connect = false); bool Write(const void* buf, size_t sz); bool Read(void* buf, size_t* sz); bool IsConnected() const { return INVALID_HANDLE_VALUE != pipe_; } private: HANDLE pipe_; }; class PipeTransport : public PipeWin { public: static const size_t kBufferSz = 4096; size_t Send(const void* buf, size_t sz) { return Write(buf, sz) ? ipc::RcOK : ipc::RcErrTransportWrite; } char* Receive(size_t* size); private: IPCCharVector buf_; }; #endif // SIMPLE_IPC_PIPE_WIN_H_
bc04402f98f0dfbab1312618df94c4703378e069
41c46297d9303f54fb390050f550379649313979
/카드놓기.cpp
aa02d0885de65c301b7c8a79689e95c3c4acf687
[]
no_license
SketchAlgorithm/17_Jo-Wonbin
f48d6c51026d08bd4eeb13448e35d8566660ad40
75231bf4a0fb62518f687c62c752f5efb7c49478
refs/heads/master
2020-04-23T00:30:30.618376
2020-02-18T09:02:46
2020-02-18T09:02:46
170,782,242
1
0
null
null
null
null
UTF-8
C++
false
false
692
cpp
#include<iostream> using namespace std; bool cache[10000000]; int arr[11]; int n, k; int travel(int depth, int num, int use) { if (depth > k) { return false; } int ret = cache[num] == false; cache[num] = true; for (int i = 0; i < n; i++) { if (!(use ^ (1 << i))) continue; if (arr[i] >= 10) ret += travel(depth + 1, num * 100 + arr[i], use | (1 << i)); else ret += travel(depth + 1, num * 10 + arr[i], use | (1 << i)); } return ret; } int main() { cin >> n >> k; for (int i = 0; i < n; i++) { cin >> arr[i]; } cout << travel(0, 0, 0) << endl; /*for (int i = 0; i < 100000000; i++) { if (cache[i] == true) cout << i << endl; }*/ }
9b6b1ec168b70a357f4e47169b73b0f2e0538b9b
6565182c28637e21087007f09d480a70b387382e
/code/901.股票价格跨度.cpp
61b63105d48efcafe008368d50a272d85d3e8c15
[]
no_license
liu-jianhao/leetcode
08c070f0f140b2dd56cffbbaf25868364addfe53
7cbbe0585778517c88aa6ac1d2f2f8478cc931e5
refs/heads/master
2021-07-17T05:54:58.228956
2020-08-17T07:03:52
2020-08-17T07:03:52
188,854,718
1
1
null
null
null
null
UTF-8
C++
false
false
792
cpp
/* * @lc app=leetcode.cn id=901 lang=cpp * * [901] 股票价格跨度 */ class StockSpanner { public: StockSpanner() { } int next(int price) { if(_i == 0 || price < _prices.back()) { _dp.push_back(1); } else { int j = _i - 1; while(j >= 0 && price >= _prices[j]) { j -= _dp[j]; } _dp.push_back(_i - j); } ++_i; _prices.push_back(price); return _dp.back(); } private: vector<int> _dp; vector<int> _prices; int _i = 0; }; /** * Your StockSpanner object will be instantiated and called as such: * StockSpanner* obj = new StockSpanner(); * int param_1 = obj->next(price); */
95534aae2f06adbc3b44e859658780f8bf0cf800
3f9081b23333e414fb82ccb970e15b8e74072c54
/bs2k/behaviors/skills/oneortwo_step_kick_bms.h
e7f968c14d8092e86a4e41ed23b6e7ac3a2558ab
[]
no_license
rc2dcc/Brainstormers05PublicRelease
5c8da63ac4dd3b84985bdf791a4e5580bbf0ba59
2141093960fad33bf2b3186d6364c08197e9fe8e
refs/heads/master
2020-03-22T07:32:36.757350
2018-07-04T18:28:32
2018-07-04T18:28:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,945
h
/* Brainstormers 2D (Soccer Simulation League 2D) PUBLIC SOURCE CODE RELEASE 2005 Copyright (C) 1998-2005 Neuroinformatics Group, University of Osnabrueck, Germany This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef _ONEORTWO_STEP_KICK_BMS_H_ #define _ONEORTWO_STEP_KICK_BMS_H_ /* This behavior is a port of Move_1or2_Step_Kick into the behavior framework. get_cmd will try to kick in one step and otherwise return a cmd that will start a two-step kick. There are some functions that return information about the reachable velocities and the needed steps, so that you can prepare in your code for what this behavior will do. This behavior usually takes the current player position as reference point, but you can override this by calling set_state() prior to any other function. This makes it possible to "fake" the player's position during the current cycle. Use reset_state to re-read the WS information, or wait until the next cycle. Note that kick_to_pos_with_final_vel() is rather unprecise concerning the final velocity of the ball. I don't know how to calculate the needed starting vel precisely, so I have taken the formula from the original Neuro_Kick2 move (which was even more unprecise...) and tweaked it a bit, but it is still not perfect. Note also that this behavior, as opposed to the original move, has a working collision check - the original move ignored the player's vel... (w) 2002 Manuel Nickschas */ #include "../base_bm.h" #include "one_step_kick_bms.h" #include "angle.h" #include "Vector.h" #include "tools.h" #include "cmd.h" #include "n++.h" #include "macro_msg.h" #include "valueparser.h" #include "options.h" #include "ws_info.h" #include "log_macros.h" #include "mystate.h" #include "../../policy/abstract_mdp.h" class OneOrTwoStepKickItrActions { static const Value kick_pwr_min = 20; static const Value kick_pwr_inc = 10; static const Value kick_pwr_max = 100; static const Value kick_ang_min = 0; static const Value kick_ang_inc = 2*PI/8.; // static const Value kick_ang_inc = 2*PI/36.; // ridi: I think it should be as much! too much static const Value kick_ang_max = 2*PI-kick_ang_inc; static const Value dash_pwr_min = 20; static const Value dash_pwr_inc = 20; static const Value dash_pwr_max = 100; static const Value turn_ang_min = 0; static const Value turn_ang_inc = 2*PI/18.; // static const Value turn_ang_max = 2*PI-turn_ang_inc; static const Value turn_ang_max = 0; // ridi: do not allow turns static const Value kick_pwr_steps = (kick_pwr_max-kick_pwr_min)/kick_pwr_inc + 1; static const Value dash_pwr_steps = (dash_pwr_max-dash_pwr_min)/dash_pwr_inc + 1; static const Value turn_ang_steps = (turn_ang_max-turn_ang_min)/turn_ang_inc + 1; static const Value kick_ang_steps = (kick_ang_max-kick_ang_min)/kick_ang_inc + 1; Cmd_Main action; Value kick_pwr,dash_pwr; ANGLE kick_ang,turn_ang; int kick_pwr_done,kick_ang_done,dash_pwr_done,turn_ang_done; public: void reset() { kick_pwr_done=0;kick_ang_done=0;dash_pwr_done=0;turn_ang_done=0; kick_pwr=kick_pwr_min;kick_ang= ANGLE(kick_ang_min);dash_pwr=dash_pwr_min; turn_ang=ANGLE(turn_ang_min); } Cmd_Main *next() { if(kick_pwr_done<kick_pwr_steps && kick_ang_done<kick_ang_steps) { action.unset_lock(); action.unset_cmd(); action.set_kick(kick_pwr,kick_ang.get_value_mPI_pPI()); kick_ang+= ANGLE(kick_ang_inc); if(++kick_ang_done>=kick_ang_steps) { kick_ang=ANGLE(kick_ang_min); kick_ang_done=0; kick_pwr+=kick_pwr_inc; kick_pwr_done++; } return &action; } if(dash_pwr_done<dash_pwr_steps) { action.unset_lock(); action.unset_cmd(); action.set_dash(dash_pwr); dash_pwr+=dash_pwr_inc; dash_pwr_done++; return &action; } if(turn_ang_done<turn_ang_steps) { action.unset_lock(); action.unset_cmd(); action.set_turn(turn_ang); turn_ang+= ANGLE(turn_ang_inc); turn_ang_done++; return &action; } return NULL; } }; class OneOrTwoStepKick: public BaseBehavior { static bool initialized; #if 0 struct MyState { Vector my_vel; Vector my_pos; ANGLE my_angle; Vector ball_pos; Vector ball_vel; Vector op_pos; ANGLE op_bodydir; }; #endif OneStepKick *onestepkick; OneOrTwoStepKickItrActions itr_actions; Cmd_Main result_cmd1,result_cmd2; Value result_vel1,result_vel2; bool result_status; bool need_2_steps; long set_in_cycle; Vector target_pos; ANGLE target_dir; Value target_vel; bool kick_to_pos; bool calc_done; MyState fake_state; long fake_state_time; void get_ws_state(MyState &state); MyState get_cur_state(); bool calculate(const MyState &state,Value vel,const ANGLE &dir,const Vector &pos,bool to_pos, Cmd_Main &res_cmd1,Value &res_vel1,Cmd_Main &res_cmd2,Value &res_vel2, bool &need_2steps); bool do_calc(); public: /** This makes it possible to "fake" WS information. This must be called _BEFORE_ any of the kick functions, and is valid for the current cycle only. */ void set_state(const Vector &mypos,const Vector &myvel,const ANGLE &myang, const Vector &ballpos,const Vector &ballvel, const Vector &op_pos = Vector(1000,1000), const ANGLE &op_bodydir = ANGLE(0), const int op_bodydir_age = 1000); void set_state( const AState & state ); /** Resets the current state to that found in WS. This must be called _BEFORE_ any of the kick functions. */ void reset_state(); void kick_in_dir_with_initial_vel(Value vel,const ANGLE &dir); void kick_in_dir_with_max_vel(const ANGLE &dir); void kick_to_pos_with_initial_vel(Value vel,const Vector &point); void kick_to_pos_with_final_vel(Value vel,const Vector &point); void kick_to_pos_with_max_vel(const Vector &point); /** false is returned if we do not reach our desired vel within two cycles. Note that velocities are set to zero if the resulting pos is not ok, meaning that even if a cmd would reach the desired vel, we will ignore it if the resulting pos is not ok. */ bool get_vel(Value &vel_1step,Value &vel_2step); bool get_cmd(Cmd &cmd_1step,Cmd &cmd_2step); bool get_vel(Value &best_vel); // get best possible vel (1 or 2 step) bool get_cmd(Cmd &best_cmd); // get best possible cmd (1 or 2 step) // returns 0 if kick is not possible, 1 if kick in 1 step is possible, 2 if in 2 steps. probably modifies vel int is_kick_possible(Value &speed,const ANGLE &dir); bool need_two_steps(); bool can_keep_ball_in_kickrange(); static bool init(char const * conf_file, int argc, char const* const* argv) { if(initialized) return true; initialized = true; if(OneStepKick::init(conf_file,argc,argv)) { cout << "\nOneOrTwoStepKick behavior initialized."; } else { ERROR_OUT << "\nCould not initialize OneStepKick behavior - stop loading."; exit(1); } return true; } OneOrTwoStepKick() { set_in_cycle = -1; onestepkick = new OneStepKick(); onestepkick->set_log(false); // we don't want OneStepKick-Info in our logs! } virtual ~OneOrTwoStepKick() { delete onestepkick; } }; #endif
b13420aa4004b14e74a53305e3368b5f4ee9dc92
72d1b579366934a24af7aff13ebf9b8cdaf58d8c
/ReadImages.cpp
a8f247f3d5b7fd89ce0c49662b42f6ef479207a1
[]
no_license
hgpvision/Keypoint-Matcher
48496a59dbaffefe6e89e8e14efabdb9883848bb
bf265aba62b325fab300aba2bad357ff7321ba4a
refs/heads/master
2021-01-15T15:05:50.913505
2017-08-08T14:45:53
2017-08-08T14:45:53
99,702,359
0
1
null
null
null
null
GB18030
C++
false
false
1,454
cpp
/* * 文件名称:ReadImages.cpp * 摘 要:读取图片类,图片序列放入到一个文件夹中,如"C:\\imgFile",按一定格式命名,比如"0001.jpg","00010.jpg","1.jpg" * 使用实例: * 包含头文件: #include "ReadImages.h" * 先声明要给读入图片类:ReadImages imageReader("C:\\imgFile", "", ".jpg"); * 读入图片: Mat prev = imageReader.loadImage(1,0); //将读入"1.jpg"图片,灰度格式 * 2016.05.23 */ #include "ReadImages.h" #pragma once ReadImages::ReadImages(std::string basepath, const std::string imagename, const std::string suffix) { //将路径中的文件夹分隔符统一为'/'(可以不需要这个for循环,会自动统一,该语句使用的命令参考C++ Primer) for (auto &c : basepath) { if (c == '\\') { c = '/'; } } _imgSource._basepath = basepath + "/"; //这里采用'/',而不是'\\' _imgSource._imagename = imagename; //图片名(不含编号) _imgSource._suffix = suffix; //图像扩展名 } //读入单张图片 //输入:imgId,一般要读入序列图片,图片都有个编号 cv::Mat ReadImages::loadImage(int imgId, int imgType) { //将图片编号转好字符串 std::stringstream ss; std::string imgNum; ss << imgId; ss >> imgNum; //得到图片的完整绝对路径 std::string path = _imgSource._basepath + _imgSource._imagename + imgNum + _imgSource._suffix; cv::Mat img = cv::imread(path,imgType); return img; }
40bc68efa1d237aacc7f1b2a5010046f0e4cf13c
4b1289b0eb41c045a24b4626857097571c988e9b
/Least_Loose_Number_In_The_Array.cpp
01dac7320be1eee1ec1af9b49c0962158327697f
[]
no_license
Arvy1998/Calculus-and-Play-with-New-Syntax
136d942c1be8dc59d3b6d764881d7a9aea5a68cd
b442156a850dad2ed7c53ce86d3435fb35d78fe9
refs/heads/master
2021-07-11T02:05:09.180547
2019-03-12T22:00:42
2019-03-12T22:00:42
129,288,984
1
0
null
null
null
null
UTF-8
C++
false
false
965
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { long long n, seka[101], MIN_TEIG = 0, count; vector <long long> izulus_teig_sk; cin >> n; for (auto x = 0; x < n; x++) { cin >> seka[x]; } for (auto i = 0; i < n; i++) { if (i == 0) { if (seka[i] > seka[i + 1]) { izulus_teig_sk.push_back(seka[i]); } } if (i > 0 && i < n - 1) { if (seka[i] > seka[i - 1] && seka[i] > seka[i + 1]) { izulus_teig_sk.push_back(seka[i]); } } if (i == n - 1) { if (seka[i] > seka[i - 1]) { izulus_teig_sk.push_back(seka[i]); } } } if (izulus_teig_sk.size() == 0 || n <= 1) { cout << "NO"; exit(0); } else { sort(izulus_teig_sk.begin(), izulus_teig_sk.end()); for (size_t j = 0; j < izulus_teig_sk.size(); j++) { if (izulus_teig_sk[j] > 0) { MIN_TEIG = izulus_teig_sk[j]; cout << MIN_TEIG; break; } } } if (MIN_TEIG == 0) { cout << "NO"; } return 0; }
36ffd69f21bf2277cef7fea364841c3a12967399
d04b3793ed3611d5bdc8e3bc990bf9eb8562cece
/CheatSheet.cpp
e00970193f00ed69d57e398e36db43427aaf83b0
[]
no_license
nebulou5/CppExamples
c7198cdc24ba1d681cc20738a3b21e2b17b98498
98044227b888a7f9faa8934ab76bb3cac443b75e
refs/heads/master
2023-09-01T18:55:44.584418
2016-01-25T17:57:40
2016-01-25T17:57:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,222
cpp
#include <iostream> using namespace std; void printI(int &i) { cout << "Printing i: " << i << endl; } int main() { // defining a basic 10 integer array int x[10]; int xLen = sizeof(x) / sizeof(x[0]); for (int i = 0; i < xLen; i++) { cout << x[i] << endl; } // defining an array in place float v[] = {1.1, 2.2, 3.3}; int vLen = sizeof(v) / sizeof(v[0]); for (int i = 0; i < vLen; i++ ) { cout << v[i] << endl; } // multidimensional array float ab[3][3]; int abLen = sizeof(ab) / sizeof(ab[0]); for (int i = 0; i < abLen; i++) { printI(i); for (int j = 0; j < abLen; j++) { cout << "Element: " << i << ", " << j << ": " << ab[i][j] << endl; } } // array allocated at runtime int someUserDefinedSize = 3; float* rta = new float[someUserDefinedSize]; // pointer dynamically allocates memory at runtime delete[] rta; // but programmer must clean up the memory afterwards // basic pointer usage int i = 3; int *j = &i; // store address of i @ "j" int k = *j; // dereference address stored @ "j" // initializing a nullptr // valid in c++ 11 and beyond int *nullPointer = nullptr; int *nullPointerSynonymous{}; // also sets a nullptr }
33fa115e3d756b655d4b8fd3fc840eb94198c8be
012784e8de35581e1929306503439bb355be4c4f
/problems/37. 解数独/3.cc
84bf778bd32645766fc6275be6ca3a9a288a96dc
[]
no_license
silenke/my-leetcode
7502057c9394e41ddeb2e7fd6c1b8261661639e0
d24ef0970785c547709b1d3c7228e7d8b98b1f06
refs/heads/master
2023-06-05T02:05:48.674311
2021-07-01T16:18:29
2021-07-01T16:18:29
331,948,127
0
0
null
null
null
null
UTF-8
C++
false
false
1,979
cc
#include "..\..\leetcode.h" class Solution { public: void solveSudoku(vector<vector<char>>& board) { row = col = box = vector<int>(9); int count = 0; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (board[i][j] == '.') count++; else fill(i, j, i / 3 * 3 + j / 3, board[i][j] - '1'); } } dfs(count, board); } private: vector<int> row, col, box; void fill(int i, int j, int k, int n) { row[i] |= 1 << n; col[j] |= 1 << n; box[k] |= 1 << n; } void zero(int i, int j, int k, int n) { row[i] &= ~(1 << n); col[j] &= ~(1 << n); box[k] &= ~(1 << n); } int possible(int i, int j) { return ~(row[i] | col[j] | box[i / 3 * 3 + j / 3]) & ((1 << 9) - 1); } pair<int, int> next(vector<vector<char>>& board) { pair<int, int> res; int min_count = INT_MAX; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (board[i][j] != '.') continue; int c = count(possible(i, j)); if (c < min_count) { min_count = c; res = {i, j}; } } } return res; } bool dfs(int count, vector<vector<char>>& board) { if (count == 0) return true; auto [i, j] = next(board); int p = possible(i, j); int k = i / 3 * 3 + j / 3; while (p) { int n = __builtin_ctz(p & -p); board[i][j] = n + '1'; fill(i, j, k, n); if (dfs(count - 1, board)) return true; board[i][j] = '.'; zero(i, j, k, n); p &= p - 1; } return false; } int count(int p) { int count = 0; while (p) { count++; p &= p - 1; } return count; } };
e58b6df0e5b4c66f0d095c33c45ddcbea6ffceae
9929f9f832b21f641f41fc91cbf604643f9770dd
/src/txt/mainRegressionP.cpp
16ad10a2e0e2cf8996b46a19dd9d38b275156452
[]
no_license
JeanSar/rogue
1cd4d8d18fe8ae6ba7d32f3af556259f5a65b2fc
a4c8945a8ae09984a4b417a3bac5ffd029e46fa7
refs/heads/master
2023-03-01T01:24:12.351208
2021-01-28T19:53:17
2021-01-28T19:53:17
331,929,934
2
0
null
null
null
null
UTF-8
C++
false
false
1,062
cpp
#include "Personnages.h" using namespace std; int main(){ srand(time(NULL)); int ok = 0; Hero* h = new Hero("Player"); Ennemi* e = new Ennemi(4); cout << "Hero : " << h->getName() << endl << "x : " << h->getX() << endl << "y : " << h->getY() << endl << "pv : " << h->getPv() << endl << "lv : " << h->getLv() << endl << "atk : " << h->getAtk() << endl << "def : " << h->getDef() << "\n\n" << "Ennemi :" << endl << "x : " << e->getX() << endl << "y : " << e->getY() << endl << "pv : " << e->getPv() << endl << "lv : " << e->getLv() << endl << "atk : " << e->getAtk() << endl << "def : " << e->getDef() << "\n\n"; assert(ok == h->lvUp()); cout << "lv : " << h->getLv() << endl << "atk : " << h->getAtk() << endl << "def : " << h->getDef() << endl; assert(ok == h->combat(e)); cout << "Ennemie - pv : " << e->getPv() << endl; assert(ok == h->setName("Terrine")); assert(ok == e->combat(h)); cout << h->getName() << " - pv : " << h->getPv(); delete e; delete h; return 0; }
[ "=" ]
=
f45da0032ec95894d113360f36e2c7e74a3b4bd2
be522f6110d4ed6f330da41a653460e4fb1ed3a7
/runtime/nf/httpparser/Buffer.cc
e4717f524b583c4cfdc3f533c545bdec74c3946c
[]
no_license
yxd886/nfa
2a796b10e6e2085470e54dd4f9a4a3721c0d27a9
209fd992ab931f955afea11562673fec943dd8a6
refs/heads/master
2020-06-17T22:09:37.259587
2017-03-24T03:07:38
2017-03-24T03:07:38
74,966,034
0
0
null
null
null
null
UTF-8
C++
false
false
981
cc
#include "Buffer.h" void CBuffer_Reset(struct CBuffer& Cbuf){ if(!Cbuf.buf){ Cbuf.buf = (char*) malloc(BUFFER_SIZE); memset(Cbuf.buf,0x00,Cbuf._free); } if(Cbuf.len > BUFFER_SIZE * 2 && Cbuf.buf){ //如果目前buf的大小是默认值的2倍,则对其裁剪内存,保持buf的大小为默认值,减小内存耗费 char* newbuf = (char*) realloc(Cbuf.buf,BUFFER_SIZE); if(newbuf != Cbuf.buf) Cbuf.buf = newbuf; } Cbuf.len = 0; Cbuf._free = BUFFER_SIZE; } bool Append(struct CBuffer& Cbuf,char* p, size_t size){ if(!p || !size) return true; if(size < Cbuf._free){ memcpy(Cbuf.buf + Cbuf.len, p , size); Cbuf.len += size; Cbuf._free -= size; }else{ return false; } return true; } char* GetBuf(struct CBuffer Cbuf,uint32_t& size){ size = Cbuf.len; return Cbuf.buf; } uint32_t GetBufLen(struct CBuffer Cbuf){ return Cbuf.len; } void Buf_init(struct CBuffer& Cbuf){ Cbuf.len=0; Cbuf._free=0; Cbuf.buf=0; CBuffer_Reset(Cbuf); }
cb50f617109e0944e114883af3fc3af8be9a6b7e
9030ce2789a58888904d0c50c21591632eddffd7
/SDK/ARKSurvivalEvolved_Buff_PreventDismount_functions.cpp
7e18c4f1010b3ae0b9f98e0ea4d779d40e1340ba
[ "MIT" ]
permissive
2bite/ARK-SDK
8ce93f504b2e3bd4f8e7ced184980b13f127b7bf
ce1f4906ccf82ed38518558c0163c4f92f5f7b14
refs/heads/master
2022-09-19T06:28:20.076298
2022-09-03T17:21:00
2022-09-03T17:21:00
232,411,353
14
5
null
null
null
null
UTF-8
C++
false
false
1,490
cpp
// ARKSurvivalEvolved (332.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Buff_PreventDismount_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function Buff_PreventDismount.Buff_PreventDismount_C.UserConstructionScript // () void ABuff_PreventDismount_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function Buff_PreventDismount.Buff_PreventDismount_C.UserConstructionScript"); ABuff_PreventDismount_C_UserConstructionScript_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Buff_PreventDismount.Buff_PreventDismount_C.ExecuteUbergraph_Buff_PreventDismount // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void ABuff_PreventDismount_C::ExecuteUbergraph_Buff_PreventDismount(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function Buff_PreventDismount.Buff_PreventDismount_C.ExecuteUbergraph_Buff_PreventDismount"); ABuff_PreventDismount_C_ExecuteUbergraph_Buff_PreventDismount_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
376f659de9de4170c19135d4e5e6f4fa7d95e938
bc33abf80f11c4df023d6b1f0882bff1e30617cf
/CPP/other/李泉彰/hhh.cpp
0e114bad33f893d5b9c3e166e74c22c9172ffe76
[]
no_license
pkuzhd/ALL
0fad250c710b4804dfd6f701d8f45381ee1a5d11
c18525decdfa70346ec32ca2f47683951f4c39e0
refs/heads/master
2022-07-11T18:20:26.435897
2019-11-20T13:25:24
2019-11-20T13:25:24
119,031,607
0
0
null
2022-06-21T21:10:42
2018-01-26T09:19:23
C++
UTF-8
C++
false
false
6,060
cpp
#include <stdio.h> #include <iostream> using namespace std; int qipan[15][15] = { 0 }; int times = 0; int print(); bool is_win(int x, int y, int flag); bool is_near(int x, int y); bool AI_set(int flag); int calc_value(int x, int y, int flag, int depth, int _max_value); int qixing(int x, int y); int main(int argc, char **argv) { int flag = 1; while (true) { ++times; print(); int x, y; if (flag == 1) { while (true) { cin >> x >> y; if (!qipan[x][y] || x < 0 || x >= 15 || y < 0 || y >= 15) break; } qipan[x][y] = flag; if (is_win(x, y, flag)) break; } else { if (AI_set(flag)) break; } flag *= -1; } if (flag == 1) { printf("black\n"); } else { printf("white\n"); } system("pause"); return 0; } int print() { for (int i = 0; i < 15; ++i) { for (int j = 0; j < 15; ++j) cout << (qipan[i][j] ? (qipan[i][j] == 1 ? "*" : "#") : "0"); cout << endl; } cout << endl; return 0; } bool is_win(int x, int y, int flag) { int number = 1; for (int i = x + 1; i < 15; ++i) { if (qipan[i][y] == flag) ++number; else break; } for (int i = x - 1; i >= 0; --i) { if (qipan[i][y] == flag) ++number; else break; } if (number >= 5) return true; number = 1; for (int i = y + 1; i < 15; ++i) { if (qipan[x][i] == flag) ++number; else break; } for (int i = y - 1; i >= 0; --i) { if (qipan[x][i] == flag) ++number; else break; } if (number >= 5) return true; number = 1; for (int j = 1; x + j < 15 && y + j < 15; ++j) { if (qipan[x + j][y + j] == flag) ++number; else break; } for (int j = 1; x - j >= 0 && y - j >= 0; ++j) { if (qipan[x - j][y - j] == flag) ++number; else break; } if (number >= 5) return true; number = 1; for (int j = 1; x + j < 15 && y - j >= 0; ++j) { if (qipan[x + j][y - j] == flag) ++number; else break; } for (int j = 1; x - j >= 0 && y + j < 15; ++j) { if (qipan[x - j][y + j] == flag) ++number; else break; } if (number >= 5) return true; return false; } bool is_near(int x, int y) { // cout << x << " " << y << endl; int _near = 2; for (int i = (x - _near >= 0 ? x - _near : 0); i <= (x + _near < 15 ? x + _near : 14); ++i) { for (int j = (y - _near >= 0 ? y - _near : 0); j <= (y + _near < 15 ? y + _near : 14); ++j) { if (qipan[i][j]) return true; } } return false; } bool AI_set(int flag) { int max_value = -10000000; int x = 7, y = 7; for (int i = 0; i < 15; ++i) { for (int j = 0; j < 15; ++j) { if (qipan[i][j]) continue; if (!is_near(i, j)) continue; int t_value = calc_value(i, j, flag, 0, max_value); if (is_win(i, j, flag)) { qipan[i][j] = flag; return true; } if (t_value > max_value) { max_value = t_value; x = i; y = j; } } } qipan[x][y] = flag; cout << x << " " << y << " " << flag << " " << is_win(x, y, flag)<< endl; return false; } int calc_value(int x, int y, int flag, int depth, int _max_value) { int _value = 0; qipan[x][y] = flag; if (depth < 4) { int max_value = -10000000; for (int i = 0; i < 15; ++i) { for (int j = 0; j < 15; ++j) { if (qipan[i][j] || !is_near(i, j)) continue; int t_value = calc_value(i, j, -flag, depth + 1, max_value); if (t_value > -_max_value) { qipan[x][y] = 0; return t_value; } if (is_win(i, j, -flag)) { qipan[x][y] = 0; return -10000000; } if (t_value > max_value) { max_value = t_value; } } } _value -= max_value; } else _value += qixing(x, y); qipan[x][y] = 0; return _value; } int qixing(int x, int y) { int flag = qipan[x][y]; bool dead = false; int number = 1; int _value = 0; int sz_qixing[2][6] = { 0 }; // x 方向 number = 1; dead = false; for (int i = x + 1; ; ++i) { if (i < 15 && qipan[i][y] == flag) ++number; else { if (i >= 15 || qipan[i][y]) dead = true; break; } } for (int i = x - 1; i >= 0; --i) { if (i >= 0 && qipan[i][y] == flag) ++number; else { if ((i < 0 || qipan[i][y]) && dead) break; else { if (dead || qipan[i][y]) dead = true; ++sz_qixing[dead][number]; } } } // y方向 number = 1; dead = false; for (int i = y + 1; ; ++i) { if (i < 15 && qipan[x][i] == flag) ++number; else { if (i >= 15 || qipan[x][i]) dead = true; break; } } for (int i = y - 1; i >= 0; --i) { if (i >= 0 && qipan[x][i] == flag) ++number; else { if ((i < 0 || qipan[x][i]) && dead) break; else { if (dead || qipan[x][i]) dead = true; ++sz_qixing[dead][number]; } } } // x y 方向 number = 1; dead = false; for (int i = 1; ; ++i) { if (x + i < 15 && y + i < 15 && qipan[x + i][y + i] == flag) ++number; else { if (x + i >= 15 || y + i >= 15 || qipan[x + i][y + i]) dead = true; break; } } for (int i = 1; ; ++i) { if (x - i >= 0 && y - i >= 0 && qipan[x - i][y - i] == flag) ++number; else { if ((x - i < 0 || y - i < 0 || qipan[x - i][y - i]) && dead) break; else { if (dead || qipan[x - i][y - i]) dead = true; ++sz_qixing[dead][number]; } } } // x -y 方向 number = 1; dead = false; for (int i = 1; ; ++i) { if (x + i < 15 && y - i >= 0 && qipan[x + i][y - i] == flag) ++number; else { if (x + i >= 15 || y - i < 0 || qipan[x + i][y - i]) dead = true; break; } } for (int i = 1; ; ++i) { if (x - i >= 0 && y + i < 15 && qipan[x - i][y + i] == flag) ++number; else { if ((x - i < 0 || y + i >= 15 || qipan[x - i][y + i]) && dead) break; else { if (dead || qipan[x - i][y + i]) dead = true; ++sz_qixing[dead][number]; } } } if (sz_qixing[false][4] || (sz_qixing[true][4] + sz_qixing[false][3]) >= 2) _value += 1000000; _value += sz_qixing[false][3] * 10000; _value += sz_qixing[true][3] * 1000; _value += sz_qixing[false][2] * 100; _value += sz_qixing[true][2] * 10; return _value; }
49d04327f2bb77b7681762dfab736d8274441b2c
d1dc3c6ec24ce3291a257b16bd1f2aa6bd791d2e
/Project1/src/Main66.cpp
e774f1c5c93157824bc10e4e8b6864ae00497def
[]
no_license
wrapdavid/Cherno_practice
8248bbcedee31a48c536dbd191eca5265178e762
e95ff1857fd72fc195a0e4c57c15a5965287ea69
refs/heads/master
2020-09-08T10:32:04.088194
2020-02-11T02:29:49
2020-02-11T02:29:49
221,109,286
0
0
null
null
null
null
UTF-8
C++
false
false
242
cpp
#include<iostream> template<typename T, char N> class Array { private: T m_Array[N]; public: char GetArray() const { return N; } }; int main() { Array<int, 61> array; std::cout << array.GetArray() << std::endl; std::cin.get(); }
1232a46da9a5b85d3695ca1a7c3b93c5b37fc11d
171b27ba265922de7836df0ac14db9ac1377153a
/test/doc/diff/stirling.cpp
875116731f3ae6bb89c2579c42e3222f850e5811
[ "MIT" ]
permissive
JPenuchot/eve
30bb84af4bfb4763910fab96f117931343beb12b
aeb09001cd6b7d288914635cb7bae66a98687972
refs/heads/main
2023-08-21T21:03:07.469433
2021-10-16T19:36:50
2021-10-16T19:36:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
561
cpp
#include <eve/function/diff/stirling.hpp> #include <eve/wide.hpp> #include <iostream> using wide_ft = eve::wide <float, eve::fixed<4>>; int main() { wide_ft pf = { 0.0f, 1.0f, -1.0f, -0.5f}; std::cout << "---- simd" << '\n' << "<- pf = " << pf << '\n' << "-> diff(stirling)(pf) = " << eve::diff(eve::stirling)(pf) << '\n'; float xf = 1.0f; std::cout << "---- scalar" << '\n' << "<- xf = " << xf << '\n' << "-> diff(stirling)(xf) = " << eve::diff(eve::stirling)(xf) << '\n' return 0; }
b1bcf5c96e5da91d67fb19ffdce0f2269d7bd395
cbb3ef472b4f4bbf1480552160aedbd88f230ee3
/Carpeta_de_proyectos_Arduino_copia_de_seguridad/NodemCU_Firebase_central/NodemCU_Firebase_central.ino
27d5e0ce48b73f435a3d2f3cb93ee7104a25d57a
[]
no_license
agrgal/ARDUINO_CS
5a68e236ec660b7ce4e34ee1253b1c0ed27033f0
f94200dceb4a8d7d27332a3045301daecbb6c979
refs/heads/master
2022-09-13T08:06:10.458851
2022-08-29T14:30:27
2022-08-29T14:30:27
242,396,006
2
0
null
null
null
null
UTF-8
C++
false
false
2,424
ino
/* * Created by Aurelio Gallardo Rodríguez * Based on: K. Suwatchai (Mobizt) * * Email: [email protected] * * CENTRAL. Lectura * * Julio - 2019 * */ //FirebaseESP8266.h must be included before ESP8266WiFi.h #include "FirebaseESP8266.h" #include <ESP8266WiFi.h> #define FIREBASE_HOST "botonpanicoseritium.firebaseio.com" #define FIREBASE_AUTH "Y0QVBot29hCVGZJQbpVUMr3IKngc7GacE2355bdy" #define WIFI_SSID "JAZZTEL_shny" #define WIFI_PASSWORD "3z7s5tvbtu4s" //Define FirebaseESP8266 data object FirebaseData bd; String path = "/Estaciones"; // path a FireBase char *estaciones[]= {"A","B","C","D","E"}; // Estaciones que voy a controlar int i=1; // contador general int activo=0; // Alarma #define LED 5 // D1(gpio5) void setup() { Serial.begin(115200); pinMode(LED, OUTPUT); // conectando a la WIFI WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.print("Conectando a la WiFi"); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(300); } Serial.println(); Serial.print("Conectado con IP: "); Serial.println(WiFi.localIP()); Serial.println(); // Conectando a la bd real Time Firebase Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH); Firebase.reconnectWiFi(true); //Set database read timeout to 1 minute (max 15 minutes) Firebase.setReadTimeout(bd, 1000 * 60); //tiny, small, medium, large and unlimited. //Size and its write timeout e.g. tiny (1s), small (10s), medium (30s) and large (60s). Firebase.setwriteSizeLimit(bd, "unlimited"); } // Bucle principal void loop() { activo=0; // reinicializo la variable for(i=0;i<=4;i++) { delay(1); activo=activo+rFB("/"+(String) estaciones[i]); } digitalWrite(LED,(activo>=1)); // activo el LED si es mayor o igual a 1. } // Función de lectura int rFB(String estacion){// lee el dato de la entrada correspondiente int valor=0; if (Firebase.getInt(bd, path+estacion)) { if (bd.dataType() == "int") { Serial.println("Dato leído: "+ path+estacion +" --> " + (String) bd.intData()); valor = bd.intData(); // retorna el valor } } else { // Si no existe el dato de la estación, salta el error // Pero el error se muestra en pantalla (bd.errorReason()) Y REINICIALIZA LA UNIDAD, lo cual no quiero. Serial.println("Estoy dando un error... ojo"); // Serial.println(bd.errorReason()); } return valor; }
ab5bc031413c9ef1306cacfd08a9878b7b902ed5
35e79b51f691b7737db254ba1d907b2fd2d731ef
/AtCoder/ABC/007/D.cpp
1f7d6ef9dd955d37b91e67aebfabda6b728594c7
[]
no_license
rodea0952/competitive-programming
00260062d00f56a011f146cbdb9ef8356e6b69e4
9d7089307c8f61ea1274a9f51d6ea00d67b80482
refs/heads/master
2022-07-01T02:25:46.897613
2022-06-04T08:44:42
2022-06-04T08:44:42
202,485,546
0
0
null
null
null
null
UTF-8
C++
false
false
1,189
cpp
#include <bits/stdc++.h> #define chmin(a, b) ((a)=min((a), (b))) #define chmax(a, b) ((a)=max((a), (b))) #define fs first #define sc second #define eb emplace_back using namespace std; typedef long long ll; typedef pair<int, int> P; typedef tuple<int, int, int> T; const ll MOD=1e9+7; const ll INF=1e18; int dx[]={1, -1, 0, 0}; int dy[]={0, 0, 1, -1}; template <typename T> inline string toString(const T &a){ostringstream oss; oss<<a; return oss.str();}; ll solve(string &s){ int n=s.size(); ll dp[20][2][2]; // dp[決めた桁数][未満フラグ][4または9を含むか] := 求める総数 memset(dp, 0, sizeof(dp)); dp[0][0][0]=1; for(int i=0; i<n; i++){ // 桁 int D=s[i]-'0'; for(int j=0; j<2; j++){ // 未満フラグ for(int k=0; k<2; k++){ // k=1 のとき4または9を含む for(int d=0; d<=(j?9:D); d++){ dp[i+1][j || (d<D)][k || d==4 || d==9]+=dp[i][j][k]; } } } } return dp[n][0][1]+dp[n][1][1]; } int main(){ ll a, b; cin>>a>>b; string A=toString(a-1), B=toString(b); cout << solve(B) - solve(A) << endl; }
6bb71dcc34b99d77ceb1ceff65cfbc759d142cb5
fb72a82827496e66e04ecb29abbca788a1ea0525
/src/wallet/wallet.h
5c79de2b263b987cf010ed0c6314bf311d8d6581
[ "MIT" ]
permissive
exiliumcore/exilium
92631c2e7abeeae6a80debbb699441d6b56e2fee
6aa88fe0c40fe72850e5bdb265741a375b2ab766
refs/heads/master
2020-03-14T05:50:41.214608
2018-05-13T01:00:24
2018-05-13T01:00:24
131,472,364
0
1
null
null
null
null
UTF-8
C++
false
false
37,762
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The Dash Core developers // Copyright (c) 2018 The Exilium Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_WALLET_WALLET_H #define BITCOIN_WALLET_WALLET_H #include "amount.h" #include "base58.h" #include "streams.h" #include "tinyformat.h" #include "ui_interface.h" #include "util.h" #include "utilstrencodings.h" #include "validationinterface.h" #include "wallet/crypter.h" #include "wallet/wallet_ismine.h" #include "wallet/walletdb.h" #include "privatesend.h" #include <algorithm> #include <map> #include <set> #include <stdexcept> #include <stdint.h> #include <string> #include <utility> #include <vector> #include <boost/shared_ptr.hpp> /** * Settings */ extern CFeeRate payTxFee; extern CAmount maxTxFee; extern unsigned int nTxConfirmTarget; extern bool bSpendZeroConfChange; extern bool fSendFreeTransactions; static const unsigned int DEFAULT_KEYPOOL_SIZE = 1000; //! -paytxfee default static const CAmount DEFAULT_TRANSACTION_FEE = 0; //! -paytxfee will warn if called with a higher fee than this amount (in satoshis) per KB static const CAmount nHighTransactionFeeWarning = 0.01 * COIN; //! -fallbackfee default static const CAmount DEFAULT_FALLBACK_FEE = 1000; //! -mintxfee default static const CAmount DEFAULT_TRANSACTION_MINFEE = 1000; //! -maxtxfee default static const CAmount DEFAULT_TRANSACTION_MAXFEE = 0.2 * COIN; // "smallest denom" + X * "denom tails" //! minimum change amount static const CAmount MIN_CHANGE = CENT; //! Default for -spendzeroconfchange static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true; //! Default for -sendfreetransactions static const bool DEFAULT_SEND_FREE_TRANSACTIONS = false; //! -txconfirmtarget default static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 2; //! -maxtxfee will warn if called with a higher fee than this amount (in satoshis) static const CAmount nHighTransactionMaxFeeWarning = 100 * nHighTransactionFeeWarning; //! Largest (in bytes) free transaction we're willing to create static const unsigned int MAX_FREE_TRANSACTION_CREATE_SIZE = 1000; static const bool DEFAULT_WALLETBROADCAST = true; //! if set, all keys will be derived by using BIP39/BIP44 static const bool DEFAULT_USE_HD_WALLET = false; class CBlockIndex; class CCoinControl; class COutput; class CReserveKey; class CScript; class CTxMemPool; class CWalletTx; /** (client) version numbers for particular wallet features */ enum WalletFeature { FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output) FEATURE_WALLETCRYPT = 40000, // wallet encryption FEATURE_COMPRPUBKEY = 60000, // compressed public keys FEATURE_HD = 120200, // Hierarchical key derivation after BIP32 (HD Wallet), BIP44 (multi-coin), BIP39 (mnemonic) // which uses on-the-fly private key derivation FEATURE_LATEST = 61000 }; enum AvailableCoinsType { ALL_COINS, ONLY_DENOMINATED, ONLY_NONDENOMINATED, ONLY_1000, // find masternode outputs including locked ones (use with caution) ONLY_PRIVATESEND_COLLATERAL }; struct CompactTallyItem { CTxDestination txdest; CAmount nAmount; std::vector<CTxIn> vecTxIn; CompactTallyItem() { nAmount = 0; } }; /** A key pool entry */ class CKeyPool { public: int64_t nTime; CPubKey vchPubKey; bool fInternal; // for change outputs CKeyPool(); CKeyPool(const CPubKey& vchPubKeyIn, bool fInternalIn); ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(nTime); READWRITE(vchPubKey); if (ser_action.ForRead()) { try { READWRITE(fInternal); } catch (std::ios_base::failure&) { /* flag as external address if we can't read the internal boolean (this will be the case for any wallet before the HD chain split version) */ fInternal = false; } } else { READWRITE(fInternal); } } }; /** Address book data */ class CAddressBookData { public: std::string name; std::string purpose; CAddressBookData() { purpose = "unknown"; } typedef std::map<std::string, std::string> StringMap; StringMap destdata; }; struct CRecipient { CScript scriptPubKey; CAmount nAmount; bool fSubtractFeeFromAmount; }; typedef std::map<std::string, std::string> mapValue_t; static void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue) { if (!mapValue.count("n")) { nOrderPos = -1; // TODO: calculate elsewhere return; } nOrderPos = atoi64(mapValue["n"].c_str()); } static void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue) { if (nOrderPos == -1) return; mapValue["n"] = i64tostr(nOrderPos); } struct COutputEntry { CTxDestination destination; CAmount amount; int vout; }; /** A transaction with a merkle branch linking it to the block chain. */ class CMerkleTx : public CTransaction { private: /** Constant used in hashBlock to indicate tx has been abandoned */ static const uint256 ABANDON_HASH; public: uint256 hashBlock; /* An nIndex == -1 means that hashBlock (in nonzero) refers to the earliest * block in the chain we know this or any in-wallet dependency conflicts * with. Older clients interpret nIndex == -1 as unconfirmed for backward * compatibility. */ int nIndex; CMerkleTx() { Init(); } CMerkleTx(const CTransaction& txIn) : CTransaction(txIn) { Init(); } void Init() { hashBlock = uint256(); nIndex = -1; } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { std::vector<uint256> vMerkleBranch; // For compatibility with older versions. READWRITE(*(CTransaction*)this); nVersion = this->nVersion; READWRITE(hashBlock); READWRITE(vMerkleBranch); READWRITE(nIndex); } int SetMerkleBranch(const CBlock& block); /** * Return depth of transaction in blockchain: * <0 : conflicts with a transaction this deep in the blockchain * 0 : in memory pool, waiting to be included in a block * >=1 : this many blocks deep in the main chain */ int GetDepthInMainChain(const CBlockIndex* &pindexRet, bool enableIX = true) const; int GetDepthInMainChain(bool enableIX = true) const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet, enableIX); } bool IsInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet) > 0; } int GetBlocksToMaturity() const; bool AcceptToMemoryPool(bool fLimitFree=true, bool fRejectAbsurdFee=true); bool hashUnset() const { return (hashBlock.IsNull() || hashBlock == ABANDON_HASH); } bool isAbandoned() const { return (hashBlock == ABANDON_HASH); } void setAbandoned() { hashBlock = ABANDON_HASH; } }; /** * A transaction with a bunch of additional info that only the owner cares about. * It includes any unrecorded transactions needed to link it back to the block chain. */ class CWalletTx : public CMerkleTx { private: const CWallet* pwallet; public: mapValue_t mapValue; std::vector<std::pair<std::string, std::string> > vOrderForm; unsigned int fTimeReceivedIsTxTime; unsigned int nTimeReceived; //! time received by this node unsigned int nTimeSmart; char fFromMe; std::string strFromAccount; int64_t nOrderPos; //! position in ordered transaction list // memory only mutable bool fDebitCached; mutable bool fCreditCached; mutable bool fImmatureCreditCached; mutable bool fAvailableCreditCached; mutable bool fAnonymizedCreditCached; mutable bool fDenomUnconfCreditCached; mutable bool fDenomConfCreditCached; mutable bool fWatchDebitCached; mutable bool fWatchCreditCached; mutable bool fImmatureWatchCreditCached; mutable bool fAvailableWatchCreditCached; mutable bool fChangeCached; mutable CAmount nDebitCached; mutable CAmount nCreditCached; mutable CAmount nImmatureCreditCached; mutable CAmount nAvailableCreditCached; mutable CAmount nAnonymizedCreditCached; mutable CAmount nDenomUnconfCreditCached; mutable CAmount nDenomConfCreditCached; mutable CAmount nWatchDebitCached; mutable CAmount nWatchCreditCached; mutable CAmount nImmatureWatchCreditCached; mutable CAmount nAvailableWatchCreditCached; mutable CAmount nChangeCached; CWalletTx() { Init(NULL); } CWalletTx(const CWallet* pwalletIn) { Init(pwalletIn); } CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn) { Init(pwalletIn); } CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn) { Init(pwalletIn); } void Init(const CWallet* pwalletIn) { pwallet = pwalletIn; mapValue.clear(); vOrderForm.clear(); fTimeReceivedIsTxTime = false; nTimeReceived = 0; nTimeSmart = 0; fFromMe = false; strFromAccount.clear(); fDebitCached = false; fCreditCached = false; fImmatureCreditCached = false; fAvailableCreditCached = false; fAnonymizedCreditCached = false; fDenomUnconfCreditCached = false; fDenomConfCreditCached = false; fWatchDebitCached = false; fWatchCreditCached = false; fImmatureWatchCreditCached = false; fAvailableWatchCreditCached = false; fChangeCached = false; nDebitCached = 0; nCreditCached = 0; nImmatureCreditCached = 0; nAvailableCreditCached = 0; nAnonymizedCreditCached = 0; nDenomUnconfCreditCached = 0; nDenomConfCreditCached = 0; nWatchDebitCached = 0; nWatchCreditCached = 0; nAvailableWatchCreditCached = 0; nImmatureWatchCreditCached = 0; nChangeCached = 0; nOrderPos = -1; } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { if (ser_action.ForRead()) Init(NULL); char fSpent = false; if (!ser_action.ForRead()) { mapValue["fromaccount"] = strFromAccount; WriteOrderPos(nOrderPos, mapValue); if (nTimeSmart) mapValue["timesmart"] = strprintf("%u", nTimeSmart); } READWRITE(*(CMerkleTx*)this); std::vector<CMerkleTx> vUnused; //! Used to be vtxPrev READWRITE(vUnused); READWRITE(mapValue); READWRITE(vOrderForm); READWRITE(fTimeReceivedIsTxTime); READWRITE(nTimeReceived); READWRITE(fFromMe); READWRITE(fSpent); if (ser_action.ForRead()) { strFromAccount = mapValue["fromaccount"]; ReadOrderPos(nOrderPos, mapValue); nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0; } mapValue.erase("fromaccount"); mapValue.erase("version"); mapValue.erase("spent"); mapValue.erase("n"); mapValue.erase("timesmart"); } //! make sure balances are recalculated void MarkDirty() { fCreditCached = false; fAvailableCreditCached = false; fImmatureCreditCached = false; fAnonymizedCreditCached = false; fDenomUnconfCreditCached = false; fDenomConfCreditCached = false; fWatchDebitCached = false; fWatchCreditCached = false; fAvailableWatchCreditCached = false; fImmatureWatchCreditCached = false; fDebitCached = false; fChangeCached = false; } void BindWallet(CWallet *pwalletIn) { pwallet = pwalletIn; MarkDirty(); } //! filter decides which addresses will count towards the debit CAmount GetDebit(const isminefilter& filter) const; CAmount GetCredit(const isminefilter& filter) const; CAmount GetImmatureCredit(bool fUseCache=true) const; CAmount GetAvailableCredit(bool fUseCache=true) const; CAmount GetImmatureWatchOnlyCredit(const bool& fUseCache=true) const; CAmount GetAvailableWatchOnlyCredit(const bool& fUseCache=true) const; CAmount GetChange() const; CAmount GetAnonymizedCredit(bool fUseCache=true) const; CAmount GetDenominatedCredit(bool unconfirmed, bool fUseCache=true) const; void GetAmounts(std::list<COutputEntry>& listReceived, std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const; void GetAccountAmounts(const std::string& strAccount, CAmount& nReceived, CAmount& nSent, CAmount& nFee, const isminefilter& filter) const; bool IsFromMe(const isminefilter& filter) const { return (GetDebit(filter) > 0); } // True if only scriptSigs are different bool IsEquivalentTo(const CWalletTx& tx) const; bool InMempool() const; bool IsTrusted() const; bool WriteToDisk(CWalletDB *pwalletdb); int64_t GetTxTime() const; int GetRequestCount() const; bool RelayWalletTransaction(CConnman* connman, std::string strCommand="tx"); std::set<uint256> GetConflicts() const; }; class COutput { public: const CWalletTx *tx; int i; int nDepth; bool fSpendable; bool fSolvable; COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn) { tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn; fSolvable = fSolvableIn; } //Used with Darksend. Will return largest nondenom, then denominations, then very small inputs int Priority() const; std::string ToString() const; }; /** Private key that includes an expiration date in case it never gets used. */ class CWalletKey { public: CPrivKey vchPrivKey; int64_t nTimeCreated; int64_t nTimeExpires; std::string strComment; //! todo: add something to note what created it (user, getnewaddress, change) //! maybe should have a map<string, string> property map CWalletKey(int64_t nExpires=0); ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(vchPrivKey); READWRITE(nTimeCreated); READWRITE(nTimeExpires); READWRITE(LIMITED_STRING(strComment, 65536)); } }; /** * Internal transfers. * Database key is acentry<account><counter>. */ class CAccountingEntry { public: std::string strAccount; CAmount nCreditDebit; int64_t nTime; std::string strOtherAccount; std::string strComment; mapValue_t mapValue; int64_t nOrderPos; //! position in ordered transaction list uint64_t nEntryNo; CAccountingEntry() { SetNull(); } void SetNull() { nCreditDebit = 0; nTime = 0; strAccount.clear(); strOtherAccount.clear(); strComment.clear(); nOrderPos = -1; nEntryNo = 0; } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { if (!(nType & SER_GETHASH)) READWRITE(nVersion); //! Note: strAccount is serialized as part of the key, not here. READWRITE(nCreditDebit); READWRITE(nTime); READWRITE(LIMITED_STRING(strOtherAccount, 65536)); if (!ser_action.ForRead()) { WriteOrderPos(nOrderPos, mapValue); if (!(mapValue.empty() && _ssExtra.empty())) { CDataStream ss(nType, nVersion); ss.insert(ss.begin(), '\0'); ss << mapValue; ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end()); strComment.append(ss.str()); } } READWRITE(LIMITED_STRING(strComment, 65536)); size_t nSepPos = strComment.find("\0", 0, 1); if (ser_action.ForRead()) { mapValue.clear(); if (std::string::npos != nSepPos) { CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion); ss >> mapValue; _ssExtra = std::vector<char>(ss.begin(), ss.end()); } ReadOrderPos(nOrderPos, mapValue); } if (std::string::npos != nSepPos) strComment.erase(nSepPos); mapValue.erase("n"); } private: std::vector<char> _ssExtra; }; /** * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances, * and provides the ability to create new transactions. */ class CWallet : public CCryptoKeyStore, public CValidationInterface { private: /** * Select a set of coins such that nValueRet >= nTargetValue and at least * all coins from coinControl are selected; Never select unconfirmed coins * if they are not ours */ bool SelectCoins(const CAmount& nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl *coinControl = NULL, AvailableCoinsType nCoinType=ALL_COINS, bool fUseInstantSend = true) const; CWalletDB *pwalletdbEncryption; //! the current wallet version: clients below this version are not able to load the wallet int nWalletVersion; //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded int nWalletMaxVersion; int64_t nNextResend; int64_t nLastResend; bool fBroadcastTransactions; mutable bool fAnonymizableTallyCached; mutable std::vector<CompactTallyItem> vecAnonymizableTallyCached; mutable bool fAnonymizableTallyCachedNonDenom; mutable std::vector<CompactTallyItem> vecAnonymizableTallyCachedNonDenom; /** * Used to keep track of spent outpoints, and * detect and report conflicts (double-spends or * mutated transactions where the mutant gets mined). */ typedef std::multimap<COutPoint, uint256> TxSpends; TxSpends mapTxSpends; void AddToSpends(const COutPoint& outpoint, const uint256& wtxid); void AddToSpends(const uint256& wtxid); std::set<COutPoint> setWalletUTXO; /* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */ void MarkConflicted(const uint256& hashBlock, const uint256& hashTx); void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>); /* HD derive new child key (on internal or external chain) */ void DeriveNewChildKey(const CKeyMetadata& metadata, CKey& secretRet, uint32_t nAccountIndex, bool fInternal /*= false*/); public: /* * Main wallet lock. * This lock protects all the fields added by CWallet * except for: * fFileBacked (immutable after instantiation) * strWalletFile (immutable after instantiation) */ mutable CCriticalSection cs_wallet; bool fFileBacked; const std::string strWalletFile; void LoadKeyPool(int nIndex, const CKeyPool &keypool) { if (keypool.fInternal) { setInternalKeyPool.insert(nIndex); } else { setExternalKeyPool.insert(nIndex); } // If no metadata exists yet, create a default with the pool key's // creation time. Note that this may be overwritten by actually // stored metadata for that key later, which is fine. CKeyID keyid = keypool.vchPubKey.GetID(); if (mapKeyMetadata.count(keyid) == 0) mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime); } std::set<int64_t> setInternalKeyPool; std::set<int64_t> setExternalKeyPool; std::map<CKeyID, CKeyMetadata> mapKeyMetadata; typedef std::map<unsigned int, CMasterKey> MasterKeyMap; MasterKeyMap mapMasterKeys; unsigned int nMasterKeyMaxID; CWallet() { SetNull(); } CWallet(const std::string& strWalletFileIn) : strWalletFile(strWalletFileIn) { SetNull(); fFileBacked = true; } ~CWallet() { delete pwalletdbEncryption; pwalletdbEncryption = NULL; } void SetNull() { nWalletVersion = FEATURE_BASE; nWalletMaxVersion = FEATURE_BASE; fFileBacked = false; nMasterKeyMaxID = 0; pwalletdbEncryption = NULL; nOrderPosNext = 0; nNextResend = 0; nLastResend = 0; nTimeFirstKey = 0; fBroadcastTransactions = false; fAnonymizableTallyCached = false; fAnonymizableTallyCachedNonDenom = false; vecAnonymizableTallyCached.clear(); vecAnonymizableTallyCachedNonDenom.clear(); } std::map<uint256, CWalletTx> mapWallet; std::list<CAccountingEntry> laccentries; typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair; typedef std::multimap<int64_t, TxPair > TxItems; TxItems wtxOrdered; int64_t nOrderPosNext; std::map<uint256, int> mapRequestCount; std::map<CTxDestination, CAddressBookData> mapAddressBook; CPubKey vchDefaultKey; std::set<COutPoint> setLockedCoins; int64_t nTimeFirstKey; int64_t nKeysLeftSinceAutoBackup; std::map<CKeyID, CHDPubKey> mapHdPubKeys; //<! memory map of HD extended pubkeys const CWalletTx* GetWalletTx(const uint256& hash) const; //! check whether we are allowed to upgrade (or already support) to the named feature bool CanSupportFeature(enum WalletFeature wf) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; } /** * populate vCoins with vector of available COutputs. */ void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl = NULL, bool fIncludeZeroValue=false, AvailableCoinsType nCoinType=ALL_COINS, bool fUseInstantSend = false) const; /** * Shuffle and select coins until nTargetValue is reached while avoiding * small change; This method is stochastic for some inputs and upon * completion the coin set and corresponding actual target value is * assembled */ bool SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, bool fUseInstantSend = false) const; // Coin selection bool SelectCoinsByDenominations(int nDenom, CAmount nValueMin, CAmount nValueMax, std::vector<CTxDSIn>& vecTxDSInRet, std::vector<COutput>& vCoinsRet, CAmount& nValueRet, int nPrivateSendRoundsMin, int nPrivateSendRoundsMax); bool GetCollateralTxDSIn(CTxDSIn& txdsinRet, CAmount& nValueRet) const; bool SelectCoinsDark(CAmount nValueMin, CAmount nValueMax, std::vector<CTxIn>& vecTxInRet, CAmount& nValueRet, int nPrivateSendRoundsMin, int nPrivateSendRoundsMax) const; bool SelectCoinsGrouppedByAddresses(std::vector<CompactTallyItem>& vecTallyRet, bool fSkipDenominated = true, bool fAnonymizable = true, bool fSkipUnconfirmed = true) const; /// Get 1000exilium output and keys which can be used for the Masternode bool GetMasternodeOutpointAndKeys(COutPoint& outpointRet, CPubKey& pubKeyRet, CKey& keyRet, std::string strTxHash = "", std::string strOutputIndex = ""); /// Extract txin information and keys from output bool GetOutpointAndKeysFromOutput(const COutput& out, COutPoint& outpointRet, CPubKey& pubKeyRet, CKey& keyRet); bool HasCollateralInputs(bool fOnlyConfirmed = true) const; int CountInputsWithAmount(CAmount nInputAmount); // get the PrivateSend chain depth for a given input int GetRealOutpointPrivateSendRounds(const COutPoint& outpoint, int nRounds) const; // respect current settings int GetOutpointPrivateSendRounds(const COutPoint& outpoint) const; bool IsDenominated(const COutPoint& outpoint) const; bool IsSpent(const uint256& hash, unsigned int n) const; bool IsLockedCoin(uint256 hash, unsigned int n) const; void LockCoin(COutPoint& output); void UnlockCoin(COutPoint& output); void UnlockAllCoins(); void ListLockedCoins(std::vector<COutPoint>& vOutpts); /** * keystore implementation * Generate a new key */ CPubKey GenerateNewKey(uint32_t nAccountIndex, bool fInternal /*= false*/); //! HaveKey implementation that also checks the mapHdPubKeys bool HaveKey(const CKeyID &address) const; //! GetPubKey implementation that also checks the mapHdPubKeys bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const; //! GetKey implementation that can derive a HD private key on the fly bool GetKey(const CKeyID &address, CKey& keyOut) const; //! Adds a HDPubKey into the wallet(database) bool AddHDPubKey(const CExtPubKey &extPubKey, bool fInternal); //! loads a HDPubKey into the wallets memory bool LoadHDPubKey(const CHDPubKey &hdPubKey); //! Adds a key to the store, and saves it to disk. bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey); //! Adds a key to the store, without saving it to disk (used by LoadWallet) bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); } //! Load metadata (used by LoadWallet) bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata); bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; } //! Adds an encrypted key to the store, and saves it to disk. bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret); //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet) bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret); bool AddCScript(const CScript& redeemScript); bool LoadCScript(const CScript& redeemScript); //! Adds a destination data tuple to the store, and saves it to disk bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value); //! Erases a destination data tuple in the store and on disk bool EraseDestData(const CTxDestination &dest, const std::string &key); //! Adds a destination data tuple to the store, without saving it to disk bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value); //! Look up a destination data tuple in the store, return true if found false otherwise bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const; //! Adds a watch-only address to the store, and saves it to disk. bool AddWatchOnly(const CScript &dest); bool RemoveWatchOnly(const CScript &dest); //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet) bool LoadWatchOnly(const CScript &dest); bool Unlock(const SecureString& strWalletPassphrase, bool fForMixingOnly = false); bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase); bool EncryptWallet(const SecureString& strWalletPassphrase); void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const; /** * Increment the next transaction order id * @return next transaction order id */ int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL); void MarkDirty(); bool AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb); void SyncTransaction(const CTransaction& tx, const CBlock* pblock); bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate); int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false); void ReacceptWalletTransactions(); void ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman); std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman); CAmount GetBalance() const; CAmount GetUnconfirmedBalance() const; CAmount GetImmatureBalance() const; CAmount GetWatchOnlyBalance() const; CAmount GetUnconfirmedWatchOnlyBalance() const; CAmount GetImmatureWatchOnlyBalance() const; CAmount GetAnonymizableBalance(bool fSkipDenominated = false, bool fSkipUnconfirmed = true) const; CAmount GetAnonymizedBalance() const; float GetAverageAnonymizedRounds() const; CAmount GetNormalizedAnonymizedBalance() const; CAmount GetNeedsToBeAnonymizedBalance(CAmount nMinBalance = 0) const; CAmount GetDenominatedBalance(bool unconfirmed=false) const; bool GetBudgetSystemCollateralTX(CTransaction& tx, uint256 hash, CAmount amount, bool fUseInstantSend); bool GetBudgetSystemCollateralTX(CWalletTx& tx, uint256 hash, CAmount amount, bool fUseInstantSend); /** * Insert additional inputs into the transaction by * calling CreateTransaction(); */ bool FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosRet, std::string& strFailReason, bool includeWatching); /** * Create a new transaction paying the recipients with a set of coins * selected by SelectCoins(); Also create the change output, when needed */ bool CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosRet, std::string& strFailReason, const CCoinControl *coinControl = NULL, bool sign = true, AvailableCoinsType nCoinType=ALL_COINS, bool fUseInstantSend=false); bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, std::string strCommand="tx"); bool CreateCollateralTransaction(CMutableTransaction& txCollateral, std::string& strReason); bool ConvertList(std::vector<CTxIn> vecTxIn, std::vector<CAmount>& vecAmounts); bool AddAccountingEntry(const CAccountingEntry&, CWalletDB & pwalletdb); static CFeeRate minTxFee; static CFeeRate fallbackFee; /** * Estimate the minimum fee considering user set parameters * and the required fee */ static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool); /** * Return the minimum required fee taking into account the * floating relay fee and user set minimum transaction fee */ static CAmount GetRequiredFee(unsigned int nTxBytes); bool NewKeyPool(); size_t KeypoolCountExternalKeys(); size_t KeypoolCountInternalKeys(); bool TopUpKeyPool(unsigned int kpSize = 0); void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fInternal); void KeepKey(int64_t nIndex); void ReturnKey(int64_t nIndex, bool fInternal); bool GetKeyFromPool(CPubKey &key, bool fInternal /*= false*/); int64_t GetOldestKeyPoolTime(); void GetAllReserveKeys(std::set<CKeyID>& setAddress) const; std::set< std::set<CTxDestination> > GetAddressGroupings(); std::map<CTxDestination, CAmount> GetAddressBalances(); std::set<CTxDestination> GetAccountAddresses(const std::string& strAccount) const; isminetype IsMine(const CTxIn& txin) const; CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const; isminetype IsMine(const CTxOut& txout) const; CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const; bool IsChange(const CTxOut& txout) const; CAmount GetChange(const CTxOut& txout) const; bool IsMine(const CTransaction& tx) const; /** should probably be renamed to IsRelevantToMe */ bool IsFromMe(const CTransaction& tx) const; CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const; CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const; CAmount GetChange(const CTransaction& tx) const; void SetBestChain(const CBlockLocator& loc); DBErrors LoadWallet(bool& fFirstRunRet); DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx); bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose); bool DelAddressBook(const CTxDestination& address); bool UpdatedTransaction(const uint256 &hashTx); void Inventory(const uint256 &hash) { { LOCK(cs_wallet); std::map<uint256, int>::iterator mi = mapRequestCount.find(hash); if (mi != mapRequestCount.end()) (*mi).second++; } } void GetScriptForMining(boost::shared_ptr<CReserveScript> &script); void ResetRequestCount(const uint256 &hash) { LOCK(cs_wallet); mapRequestCount[hash] = 0; }; unsigned int GetKeyPoolSize() { AssertLockHeld(cs_wallet); // set{Ex,In}ternalKeyPool return setInternalKeyPool.size() + setExternalKeyPool.size(); } bool SetDefaultKey(const CPubKey &vchPubKey); //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false); //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format) bool SetMaxVersion(int nVersion); //! get the current wallet format (the oldest client version guaranteed to understand this wallet) int GetVersion() { LOCK(cs_wallet); return nWalletVersion; } //! Get wallet transactions that conflict with given transaction (spend same outputs) std::set<uint256> GetConflicts(const uint256& txid) const; //! Flush wallet (bitdb flush) void Flush(bool shutdown=false); //! Verify the wallet database and perform salvage if required static bool Verify(const std::string& walletFile, std::string& warningString, std::string& errorString); /** * Address book entry changed. * @note called with lock cs_wallet held. */ boost::signals2::signal<void (CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, const std::string &purpose, ChangeType status)> NotifyAddressBookChanged; /** * Wallet transaction added, removed or updated. * @note called with lock cs_wallet held. */ boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged; /** Show progress e.g. for rescan */ boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress; /** Watch-only address added */ boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged; /** Inquire whether this wallet broadcasts transactions. */ bool GetBroadcastTransactions() const { return fBroadcastTransactions; } /** Set whether this wallet broadcasts transactions. */ void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; } /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */ bool AbandonTransaction(const uint256& hashTx); /** * HD Wallet Functions */ /* Returns true if HD is enabled */ bool IsHDEnabled(); /* Generates a new HD chain */ void GenerateNewHDChain(); /* Set the HD chain model (chain child index counters) */ bool SetHDChain(const CHDChain& chain, bool memonly); bool SetCryptedHDChain(const CHDChain& chain, bool memonly); bool GetDecryptedHDChain(CHDChain& hdChainRet); }; /** A key allocated from the key pool. */ class CReserveKey : public CReserveScript { protected: CWallet* pwallet; int64_t nIndex; CPubKey vchPubKey; bool fInternal; public: CReserveKey(CWallet* pwalletIn) { nIndex = -1; pwallet = pwalletIn; fInternal = false; } ~CReserveKey() { ReturnKey(); } void ReturnKey(); bool GetReservedKey(CPubKey &pubkey, bool fInternalIn /*= false*/); void KeepKey(); void KeepScript() { KeepKey(); } }; /** * Account information. * Stored in wallet with key "acc"+string account name. */ class CAccount { public: CPubKey vchPubKey; CAccount() { SetNull(); } void SetNull() { vchPubKey = CPubKey(); } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(vchPubKey); } }; #endif // BITCOIN_WALLET_WALLET_H
e583e7116773107273d5fb8024b730ef48f23333
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/pdfium/xfa/fxfa/parser/cxfa_solid.cpp
da8de3f6aca0fae9e6ba41523e382edcb9d6be21
[ "BSD-3-Clause", "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
1,216
cpp
// Copyright 2017 The PDFium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "xfa/fxfa/parser/cxfa_solid.h" #include "fxjs/xfa/cjx_node.h" #include "xfa/fxfa/parser/cxfa_document.h" namespace { const CXFA_Node::PropertyData kSolidPropertyData[] = { {XFA_Element::Extras, 1, {}}, }; const CXFA_Node::AttributeData kSolidAttributeData[] = { {XFA_Attribute::Id, XFA_AttributeType::CData, nullptr}, {XFA_Attribute::Use, XFA_AttributeType::CData, nullptr}, {XFA_Attribute::Usehref, XFA_AttributeType::CData, nullptr}, }; } // namespace CXFA_Solid::CXFA_Solid(CXFA_Document* doc, XFA_PacketType packet) : CXFA_Node(doc, packet, {XFA_XDPPACKET::kTemplate, XFA_XDPPACKET::kForm}, XFA_ObjectType::Node, XFA_Element::Solid, kSolidPropertyData, kSolidAttributeData, cppgc::MakeGarbageCollected<CJX_Node>( doc->GetHeap()->GetAllocationHandle(), this)) {} CXFA_Solid::~CXFA_Solid() = default;
0f14955c67c8ded4e0b25301b31b8648ae16b52f
4985aad8ecfceca8027709cf488bc2c601443385
/build/Android/Debug/app/src/main/include/Fuse.Resources.Resour-7da5075.h
bb740adfa48c8d9b5e34d9b3bf2a2c23882e8030
[]
no_license
pacol85/Test1
a9fd874711af67cb6b9559d9a4a0e10037944d89
c7bb59a1b961bfb40fe320ee44ca67e068f0a827
refs/heads/master
2021-01-25T11:39:32.441939
2017-06-12T21:48:37
2017-06-12T21:48:37
93,937,614
0
0
null
null
null
null
UTF-8
C++
false
false
883
h
// This file was generated based on '../../AppData/Local/Fusetools/Packages/Fuse.Nodes/1.0.2/$.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.h> namespace g{namespace Fuse{namespace Resources{struct ResourceConverters;}}} namespace g{namespace Uno{namespace Collections{struct Dictionary;}}} namespace g{ namespace Fuse{ namespace Resources{ // internal static class ResourceConverters :3538 // { uClassType* ResourceConverters_typeof(); void ResourceConverters__Get_fn(uType* __type, uObject** __retval); struct ResourceConverters : uObject { static uSStrong< ::g::Uno::Collections::Dictionary*> _converters_; static uSStrong< ::g::Uno::Collections::Dictionary*>& _converters() { return ResourceConverters_typeof()->Init(), _converters_; } static uObject* Get(uType* __type); }; // } }}} // ::g::Fuse::Resources
a4107844dad660b1e38707bc33b03c52f16b4cbd
61442c0297fef23453b7bc43ab5bbd6a52c95fa7
/grappletation/Source/Grappletation/Gem.cpp
44c2698bb81fe1bfc4a986a9d39c8944aae59d65
[]
no_license
AshleyThew/GameProgramming
c9cf634ef81dd7e1753b3ef45d56a6ee38b9a072
22032cf7b141222d498c083527e81a854864e694
refs/heads/main
2023-08-23T15:51:59.141006
2021-10-25T10:01:57
2021-10-25T10:01:57
420,814,528
1
0
null
null
null
null
UTF-8
C++
false
false
778
cpp
#include "Gem.h" #include "Entity.h" #include "Renderer.h" #include "Sprite.h" Gem::Gem(int x, int y) { id.x = x; id.y = y; } Gem::~Gem() { } bool Gem::Initialise(Renderer& renderer, const char* gemType, float scale) { m_pSprite = renderer.CreateSprite(gemType); m_pSprite->SetScale(scale); m_position.x = (scale * 8) + (id.x * scale * 16); m_position.y = (scale * 8) + (id.y * scale * 16); Reset(); return false; } void Gem::Process(float deltaTime) { Entity::Process(deltaTime); } void Gem::Draw(Renderer& renderer) { Entity::Draw(renderer); } bool Gem::GetCollected() { return collected; } void Gem::SetCollected() { collected = true; SetDead(true); } void Gem::Reset() { collected = false; SetDead(false); } Vector2 Gem::GetID() { return id; }
c1be7ed8331d413fbb32c4f4da225eabb0c94905
2d4346d0da0a4145f6bcc91a8cb2c0ab4d669d7e
/chat-up-server/src/Authentication/AuthenticationService.h
b172c8a7281e736007294715851af51947b6b669
[]
no_license
xgallom/chat-up
5570d069a495acf6398bdf1f62b1fb1d91289376
7cb664ce745cf041fb508b04165d2179563aa010
refs/heads/master
2020-04-18T05:40:58.487905
2019-01-29T22:36:04
2019-01-29T22:36:04
167,287,878
0
0
null
null
null
null
UTF-8
C++
false
false
608
h
// // Created by xgallom on 1/27/19. // #ifndef CHAT_UP_AUTHENTICATIONSERVICE_H #define CHAT_UP_AUTHENTICATIONSERVICE_H #include <Messaging/Message.h> #include <Messaging/MessageSender.h> #include <Outcome.h> #include <Authentication/User.h> class AuthenticationStorage; class AuthenticationService { AuthenticationStorage &m_storage; User m_user = User(); public: AuthenticationService() noexcept; Outcome::Enum run(MessageSender &sender, const Message &message); bool registerUser(const User &user); User user() const noexcept; }; #endif //CHAT_UP_AUTHENTICATIONSERVICE_H
e701e032706c6d0b6712cbf46f97a1491037c069
509ed385d3faa95ed92957f0f691fc3fe1d6816a
/src/Workers/Worker.h
db1536697c5f967497dfa8fe487e786329ac19ec
[]
no_license
xrenoder/Node-InfrastructureTorrent
d6540c725cb9239bcf421a7891e7ebbeb6505701
21c3eb739d0b41cb6858d747cd108708bbfdb73d
refs/heads/master
2023-08-29T01:02:15.760253
2021-09-20T10:03:30
2021-09-20T10:03:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
504
h
#ifndef WORKER_H_ #define WORKER_H_ #include <memory> #include <optional> #include "OopUtils.h" namespace torrent_node_lib { struct BlockInfo; class Worker: public common::no_copyable, common::no_moveable{ public: virtual void start() = 0; virtual void process(std::shared_ptr<BlockInfo> bi, std::shared_ptr<std::string> dump) = 0; virtual std::optional<size_t> getInitBlockNumber() const = 0; virtual ~Worker() = default; }; } #endif // WORKER_H_
fa606684822edaeb65a3facbab4e69b8044c96ef
6aeccfb60568a360d2d143e0271f0def40747d73
/sandbox/SOC/2011/simd/boost/simd/toolbox/constant/include/constants/minexponent.hpp
0fd6c857f2cef5aa7fcc1f22aca4daf4a5f7a9c3
[]
no_license
ttyang/sandbox
1066b324a13813cb1113beca75cdaf518e952276
e1d6fde18ced644bb63e231829b2fe0664e51fac
refs/heads/trunk
2021-01-19T17:17:47.452557
2013-06-07T14:19:55
2013-06-07T14:19:55
13,488,698
1
3
null
2023-03-20T11:52:19
2013-10-11T03:08:51
C++
UTF-8
C++
false
false
232
hpp
#ifndef BOOST_SIMD_TOOLBOX_CONSTANT_INCLUDE_CONSTANTS_MINEXPONENT_HPP_INCLUDED #define BOOST_SIMD_TOOLBOX_CONSTANT_INCLUDE_CONSTANTS_MINEXPONENT_HPP_INCLUDED #include <boost/simd/toolbox/constant/constants/minexponent.hpp> #endif
4ff557683a174bc39aea59e06a19b563d55927d6
cde943952b79d67f4972d180d20b97fc823db548
/preprocesser/preprocesser/self2.hpp
0892b2563bae695f02d2254829e81a6cb84c630e
[]
no_license
yourgracee/preprocesser
e66a0b0c9680442717652185e9ed2dc5172f7771
349453d4092ffe7927b0c1067d3cefc8bf2bdfff
refs/heads/master
2020-04-09T10:52:16.135824
2018-12-04T02:46:03
2018-12-04T02:46:03
160,285,495
0
0
null
null
null
null
UTF-8
C++
false
false
10,701
hpp
#ifdef LIMIT_2 #include "tuple.hpp" #define START_2 TUPLE(0, LIMIT_2) #define FINISH_2 TUPLE(1, LIMIT_2) #undef DEPTH #define DEPTH 2 # if START_2 <= 0 && FINISH_2 >= 0 # define ITERATION_2 0 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 1 && FINISH_2 >= 1 # define ITERATION_2 1 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 2 && FINISH_2 >= 2 # define ITERATION_2 2 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 3 && FINISH_2 >= 3 # define ITERATION_2 3 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 4 && FINISH_2 >= 4 # define ITERATION_2 4 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 5 && FINISH_2 >= 5 # define ITERATION_2 5 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 6 && FINISH_2 >= 6 # define ITERATION_2 6 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 7 && FINISH_2 >= 7 # define ITERATION_2 7 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 8 && FINISH_2 >= 8 # define ITERATION_2 8 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 9 && FINISH_2 >= 9 # define ITERATION_2 9 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 10 && FINISH_2 >= 10 # define ITERATION_2 10 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 11 && FINISH_2 >= 11 # define ITERATION_2 11 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 12 && FINISH_2 >= 12 # define ITERATION_2 12 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 13 && FINISH_2 >= 13 # define ITERATION_2 13 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 14 && FINISH_2 >= 14 # define ITERATION_2 14 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 15 && FINISH_2 >= 15 # define ITERATION_2 15 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 16 && FINISH_2 >= 16 # define ITERATION_2 16 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 17 && FINISH_2 >= 17 # define ITERATION_2 17 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 18 && FINISH_2 >= 18 # define ITERATION_2 18 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 19 && FINISH_2 >= 19 # define ITERATION_2 19 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 20 && FINISH_2 >= 20 # define ITERATION_2 20 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 21 && FINISH_2 >= 21 # define ITERATION_2 21 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 22 && FINISH_2 >= 22 # define ITERATION_2 22 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 23 && FINISH_2 >= 23 # define ITERATION_2 23 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 24 && FINISH_2 >= 24 # define ITERATION_2 24 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 25 && FINISH_2 >= 25 # define ITERATION_2 25 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 26 && FINISH_2 >= 26 # define ITERATION_2 26 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 27 && FINISH_2 >= 27 # define ITERATION_2 27 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 28 && FINISH_2 >= 28 # define ITERATION_2 28 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 29 && FINISH_2 >= 29 # define ITERATION_2 29 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 30 && FINISH_2 >= 30 # define ITERATION_2 30 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 31 && FINISH_2 >= 31 # define ITERATION_2 31 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 32 && FINISH_2 >= 32 # define ITERATION_2 32 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 33 && FINISH_2 >= 33 # define ITERATION_2 33 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 34 && FINISH_2 >= 34 # define ITERATION_2 34 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 35 && FINISH_2 >= 35 # define ITERATION_2 35 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 36 && FINISH_2 >= 36 # define ITERATION_2 36 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 37 && FINISH_2 >= 37 # define ITERATION_2 37 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 38 && FINISH_2 >= 38 # define ITERATION_2 38 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 39 && FINISH_2 >= 39 # define ITERATION_2 39 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 40 && FINISH_2 >= 40 # define ITERATION_2 40 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 41 && FINISH_2 >= 41 # define ITERATION_2 41 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 42 && FINISH_2 >= 42 # define ITERATION_2 42 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 43 && FINISH_2 >= 43 # define ITERATION_2 43 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 44 && FINISH_2 >= 44 # define ITERATION_2 44 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 45 && FINISH_2 >= 45 # define ITERATION_2 45 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 46 && FINISH_2 >= 46 # define ITERATION_2 46 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 47 && FINISH_2 >= 47 # define ITERATION_2 47 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 48 && FINISH_2 >= 48 # define ITERATION_2 48 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 49 && FINISH_2 >= 49 # define ITERATION_2 49 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 50 && FINISH_2 >= 50 # define ITERATION_2 50 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 51 && FINISH_2 >= 51 # define ITERATION_2 51 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 52 && FINISH_2 >= 52 # define ITERATION_2 52 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 53 && FINISH_2 >= 53 # define ITERATION_2 53 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 54 && FINISH_2 >= 54 # define ITERATION_2 54 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 55 && FINISH_2 >= 55 # define ITERATION_2 55 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 56 && FINISH_2 >= 56 # define ITERATION_2 56 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 57 && FINISH_2 >= 57 # define ITERATION_2 57 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 58 && FINISH_2 >= 58 # define ITERATION_2 58 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 59 && FINISH_2 >= 59 # define ITERATION_2 59 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 60 && FINISH_2 >= 60 # define ITERATION_2 60 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 61 && FINISH_2 >= 61 # define ITERATION_2 61 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 62 && FINISH_2 >= 62 # define ITERATION_2 62 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 63 && FINISH_2 >= 63 # define ITERATION_2 63 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 64 && FINISH_2 >= 64 # define ITERATION_2 64 # include FILENAME_2 # undef ITERATION_2 # endif #undef DEPTH #define DEPTH 1 #endif
334f0712fc8566ea028524f0cd56702b83f8dbd4
9b273539e02cca8d408e8cf793007ee84e6637d5
/ext/bliss/src/iterators/edge_iterator.hpp
2217a705bef1dc4b94ba3493a6facab66fe6ad3e
[ "Apache-2.0" ]
permissive
tuan1225/parconnect_sc16
23b82c956eed4dabe5deec8bd48cc8ead91af615
bcd6f99101685d746cf30e22fa3c3f63ddd950c9
refs/heads/master
2020-12-24T12:01:13.846352
2016-11-07T16:51:29
2016-11-07T16:51:29
73,055,274
0
0
null
null
null
null
UTF-8
C++
false
false
9,760
hpp
/* * edge_iterator.hpp * * Created on: Aug 4, 2015 * Author: yongchao */ #ifndef EDGE_ITERATOR_HPP_ #define EDGE_ITERATOR_HPP_ #include <iterator> #include "common/alphabets.hpp" namespace bliss { namespace iterator { // careful with the use of enable_if. evaluation should occur at function call time, // i.e. class template params will be evaluated with no substitution. // instead, a function should declare a template parameter proxy for the class template parameter. // then enable_if evaluates using the proxy. // e.g. template< class c = C; typename std::enable_if<std::is_same<c, std::string>::value, int>::type x = 0> /** * @class edge_iterator * @brief given a k-mer position, retrieve its left and right bases, including the dummy bases at both ends * @details specializations of this class uses a byte to manage the edge info. * upper 4 bits holds the left base (encoded), lower 4 bits holds the right base (encoded) * * no reverse complement or reordering is applied. * * edge iterator should be valid for std::distance(_data_end - _data_start - k + 1) iterations. */ template<typename IT, typename ALPHA = bliss::common::DNA16> class edge_iterator : public ::std::iterator<::std::forward_iterator_tag, uint8_t> { protected: // curr position IT _curr; //previous position IT _left; //a position of distance k from the _curr on the right IT _right; /*data*/ const IT _data_start; const IT _data_end; public: typedef ALPHA Alphabet; typedef edge_iterator<IT, ALPHA> self_type; /*define edge iterator type*/ typedef uint8_t edge_type; //type to represent an edge // accessors IT& getBase() { return _curr; } //constructor edge_iterator(IT data_start, IT data_end, const uint32_t k) : _curr (data_start), _left(data_end), _right(data_start), _data_start(data_start), _data_end(data_end) { /*compute the offset*/ ::std::advance(_curr, k - 1); _right = _curr; ::std::advance(_right, 1); } edge_iterator(IT data_end) : _curr(data_end), _left(data_end), _right(data_end), _data_start(data_end), _data_end(data_end) { } /// copy constructor edge_iterator(const self_type& Other) : _curr (Other._curr), _left(Other._left), _right(Other._right), _data_start(Other._data_start), _data_end(Other._data_end) { /*do nothing*/ } /// copy assignment iterator self_type& operator=(const self_type& Other) { _curr = Other._curr; _left = Other._left; _right = Other._right; _data_start = Other._data_start; _data_end = Other._data_end; return *this; } /// increment to next matching element in base iterator self_type& operator++() { // if _curr at end, subsequent calls should not move _curr. // on call, if not at end, need to move first then evaluate. if (_curr == _data_end){ // if at end, don't move it. return *this; } /*save the previous position*/ if (_left == _data_end) _left = _data_start; else ++_left; /*move forward by 1*/ ++_curr; /*ensure that _right does not exceed _end*/ if(_right != _data_end){ ++_right; } return *this; } /** * post increment. make a copy then increment that. */ self_type operator++(int) { self_type output(*this); this->operator++(); return output; } /// compare 2 filter iterators inline bool operator==(const self_type& rhs) { return _curr == rhs._curr; } /// compare 2 filter iterators inline bool operator!=(const self_type& rhs) { return _curr != rhs._curr; } /// dereference operator. _curr is guaranteed to be valid inline edge_type operator*() { /*using four bits to represent an edge*/ if(_left != _data_end && _right != _data_end){ /*internal k-mer node*/ return (ALPHA::FROM_ASCII[*_left] << 4) | ALPHA::FROM_ASCII[*_right]; }else if(_left == _data_end && _right != _data_end){ /*the left-most k-mer node*/ return ALPHA::FROM_ASCII[*_right]; }else if(_left != _data_end && _right == _data_end){ /*the rigth-most k-mer node*/ return ALPHA::FROM_ASCII[*_left] << 4; } /*if(_left == _end && _right == _end)*/ return 0; } }; template<typename IT> using DNA16_edge_iterator = edge_iterator<IT, bliss::common::DNA16>; template<typename IT> using DNA_IUPAC_edge_iterator = edge_iterator<IT, bliss::common::DNA_IUPAC>; // not suitable for edge iterator since there is no value for unknown char. template<typename IT> using DNA_edge_iterator = edge_iterator<IT, bliss::common::DNA>; template<typename IT> using DNA5_edge_iterator = edge_iterator<IT, bliss::common::DNA5>; // not suitable for edge iterator since there is no value for unknown char. template<typename IT> using RNA_edge_iterator = edge_iterator<IT, bliss::common::RNA>; template<typename IT> using RNA5_edge_iterator = edge_iterator<IT, bliss::common::RNA5>; /*EdgeType = short unsigned int*/ template<typename IT> class edge_iterator<IT, bliss::common::ASCII>: public ::std::iterator<::std::forward_iterator_tag, uint16_t> { protected: // curr position IT _curr; //previous position IT _left; //a position of distance k from the _curr on the right IT _right; /*data*/ const IT _data_start; const IT _data_end; public: typedef bliss::common::ASCII Alphabet; typedef edge_iterator<IT, bliss::common::ASCII> self_type; /*define edge iterator type*/ typedef uint16_t edge_type; //type to represent an edge // accessors IT& getBase() { return _curr; } //constructor edge_iterator(IT data_start, IT data_end, const uint32_t k) : _curr (data_start), _left(data_end), _right(data_start), _data_start(data_start), _data_end(data_end) { /*compute the offset*/ ::std::advance(_curr, k-1); _right = _curr; ::std::advance(_right, 1); } edge_iterator(IT data_end) : _curr(data_end), _left(data_end), _right(data_end), _data_start(data_end), _data_end(data_end) { } /// copy constructor edge_iterator(const self_type& Other) : _curr (Other._curr), _left(Other._left), _right(Other._right), _data_start(Other._data_start), _data_end(Other._data_end) { /*do nothing*/ } /// copy assignment iterator self_type& operator=(const self_type& Other) { _curr = Other._curr; _left = Other._left; _right = Other._right; _data_start = Other._data_start; _data_end = Other._data_end; return *this; } /// increment to next matching element in base iterator self_type& operator++() { // if _curr at end, subsequent calls should not move _curr. // on call, if not at end, need to move first then evaluate. if (_curr == _data_end){ // if at end, don'IT move it. return *this; } /*save the previous position*/ if (_left == _data_end) _left = _data_start; else ++_left; /*move forward by 1*/ ++_curr; /*ensure that _right does not exceed _end*/ if(_right != _data_end){ ++_right; } return *this; } /** * post increment. make a copy then increment that. */ self_type operator++(int) { self_type output(*this); this->operator++(); return output; } /// compare 2 filter iterators inline bool operator==(const self_type& rhs) { return _curr == rhs._curr; } /// compare 2 filter iterators inline bool operator!=(const self_type& rhs) { return _curr != rhs._curr; } /// dereference operator. _curr is guaranteed to be valid inline edge_type operator*() { /*using 8 bits to represent an edge*/ if(_left != _data_end && _right != _data_end){ /*internal k-mer node*/ return (*_left << 8) | *_right; }else if(_left == _data_end && _right != _data_end){ /*the left-most k-mer node*/ return *_right & 0x0ff; }else if(_left != _data_end && _right == _data_end){ /*the rigth-most k-mer node*/ return *_left << 8; } /*if(_left == _end && _right == _end)*/ return 0; } }; template<typename IT> using raw_edge_iterator = edge_iterator<IT, bliss::common::ASCII>; } // iterator } // bliss #endif /* EDGE_ITERATOR_HPP_ */
f974d4af50705dd6f63c51d6d7a1ee1c85bf7cd3
414c6adb394c3c7ef4b80ab9b62cfc238ff726e2
/tutorial/spinny/main.cc
39f9f8736922a4b8a41c9e0c1c9d1bf851f0a4b6
[]
no_license
akeley98/vkme
68ca6db6c246fe8b4a25a3fb0982ff2552d8ef9b
1b8e7df2a8290a0cc7bd97bf82c88a6eeff40be1
refs/heads/master
2022-12-23T19:53:47.583138
2020-09-29T05:34:32
2020-09-29T05:34:32
291,925,536
0
0
null
null
null
null
UTF-8
C++
false
false
11,670
cc
#include "window.hh" #include "render.hh" #include "util.hh" using namespace myricube; // Absolute path of the executable, minus the -bin or .exe, plus -data/ // This is where shaders and stuff are stored. std::string data_directory; std::string expand_filename(const std::string& in) { if (data_directory.size() == 0) { throw std::logic_error("Cannot call expand_filename before main"); } return in[0] == '/' ? in : data_directory + in; } bool ends_with_bin_or_exe(const std::string& in) { auto sz = in.size(); if (sz < 4) return false; const char* suffix = &in[sz - 4]; return strcmp(suffix, "-bin") == 0 or strcmp(suffix, ".exe") == 0; } bool paused = false; int target_fragments = 0; void add_key_targets(Window& window, Camera& camera) { static float speed = 8.0f; static float sprint_mod = 1.0f; struct Position { glm::dvec3 eye = glm::dvec3(0); float theta = 1.5707f; float phi = 1.5707f; }; static Position old_positions_ring_buffer[256]; static Position future_positions_ring_buffer[256]; static uint8_t old_idx = 0; static uint8_t future_idx = 0; static auto get_camera_position = [&camera] () -> Position { Position p; p.eye = camera.get_eye(); p.theta = camera.get_theta(); p.phi = camera.get_phi(); return p; }; static auto push_camera_position = [&] { old_positions_ring_buffer[--old_idx] = get_camera_position(); }; static auto push_camera_position_callback = [&] (KeyArg arg) { if (arg.repeat) return false; push_camera_position(); return true; }; KeyTarget pop_old_camera, pop_future_camera; pop_old_camera.down = [&] (KeyArg) -> bool { future_positions_ring_buffer[--future_idx] = get_camera_position(); Position p = old_positions_ring_buffer[old_idx++]; camera.set_eye(p.eye); camera.set_theta(p.theta); camera.set_phi(p.phi); return true; }; pop_future_camera.down = [&] (KeyArg) -> bool { old_positions_ring_buffer[--old_idx] = get_camera_position(); Position p = future_positions_ring_buffer[future_idx++]; camera.set_eye(p.eye); camera.set_theta(p.theta); camera.set_phi(p.phi); return true; }; window.add_key_target("pop_old_camera", pop_old_camera); window.add_key_target("pop_future_camera", pop_future_camera); KeyTarget forward, backward, leftward, rightward, upward, downward; forward.down = push_camera_position_callback; forward.per_frame = [&] (KeyArg arg) -> bool { camera.frenet_move(0, 0, +arg.dt * speed * sprint_mod); return true; }; backward.down = push_camera_position_callback; backward.per_frame = [&] (KeyArg arg) -> bool { camera.frenet_move(0, 0, -arg.dt * speed * sprint_mod); return true; }; leftward.down = push_camera_position_callback; leftward.per_frame = [&] (KeyArg arg) -> bool { camera.frenet_move(-arg.dt * speed * sprint_mod, 0, 0); return true; }; rightward.down = push_camera_position_callback; rightward.per_frame = [&] (KeyArg arg) -> bool { camera.frenet_move(+arg.dt * speed * sprint_mod, 0, 0); return true; }; upward.down = push_camera_position_callback; upward.per_frame = [&] (KeyArg arg) -> bool { camera.frenet_move(0, +arg.dt * speed * sprint_mod, 0); return true; }; downward.down = push_camera_position_callback; downward.per_frame = [&] (KeyArg arg) -> bool { camera.frenet_move(0, -arg.dt * speed * sprint_mod, 0); return true; }; window.add_key_target("forward", forward); window.add_key_target("backward", backward); window.add_key_target("leftward", leftward); window.add_key_target("rightward", rightward); window.add_key_target("upward", upward); window.add_key_target("downward", downward); KeyTarget sprint, speed_up, slow_down; sprint.down = [&] (KeyArg) -> bool { sprint_mod = 7.0f; return true; }; sprint.up = [&] (KeyArg) -> bool { sprint_mod = 1.0f; return true; }; speed_up.down = [&] (KeyArg arg) -> bool { if (!arg.repeat) speed *= 2.0f; return !arg.repeat; }; slow_down.down = [&] (KeyArg arg) -> bool { if (!arg.repeat) speed *= 0.5f; return !arg.repeat; }; window.add_key_target("sprint", sprint); window.add_key_target("speed_up", speed_up); window.add_key_target("slow_down", slow_down); KeyTarget vertical_scroll, horizontal_scroll, look_around; look_around.down = push_camera_position_callback; look_around.per_frame = [&] (KeyArg arg) -> bool { camera.inc_theta(arg.mouse_rel_x * arg.dt * 0.01f); camera.inc_phi(arg.mouse_rel_y * arg.dt * 0.01f); return true; }; vertical_scroll.down = [&] (KeyArg arg) -> bool { camera.inc_phi(arg.amount * -0.05f); return true; }; horizontal_scroll.down = [&] (KeyArg arg) -> bool { camera.inc_theta(arg.amount * -0.05f); return true; }; window.add_key_target("look_around", look_around); window.add_key_target("vertical_scroll", vertical_scroll); window.add_key_target("horizontal_scroll", horizontal_scroll); } // Given the full path of a key binds file, parse it for key bindings // and add it to the window's database of key bindings (physical // key/mouse button to KeyTarget name associations). // // Syntax: the file should consist of lines of pairs of key names and // KeyTarget names. Blank (all whitespace) lines are allowed as well // as comments, which go from a # character to the end of the line. // // Returns true iff successful (check errno on false). bool add_key_binds_from_file(Window& window, std::string filename) noexcept { FILE* file = fopen(filename.c_str(), "r"); if (file == nullptr) { fprintf(stderr, "Could not open %s\n", filename.c_str()); return false; } int line_number = 0; auto skip_whitespace = [file] { int c; while (1) { c = fgetc(file); if (c == EOF) return; if (c == '\n' or !isspace(c)) { ungetc(c, file); return; } } }; errno = 0; bool eof = false; while (!eof) { std::string key_name; std::string target_name; ++line_number; int c; skip_whitespace(); // Parse key name (not case sensitive -- converted to lower case) while (1) { c = fgetc(file); if (c == EOF) { if (errno != 0 and errno != EAGAIN) goto bad_eof; eof = true; goto end_line; } if (c == '\n') goto end_line; if (isspace(c)) break; if (c == '#') goto comment; key_name.push_back(c); } skip_whitespace(); // Parse target name (case sensitive) while (1) { c = fgetc(file); if (c == EOF) { if (errno != 0 and errno != EAGAIN) goto bad_eof; eof = true; goto end_line; } if (c == '\n') goto end_line; if (isspace(c)) break; if (c == '#') goto comment; target_name.push_back(c); } skip_whitespace(); // Check for unexpected cruft at end of line. c = fgetc(file); if (c == EOF) { if (errno != 0 and errno != EAGAIN) goto bad_eof; eof = true; goto end_line; } else if (c == '#') { goto comment; } else if (c == '\n') { goto end_line; } else { fprintf(stderr, "%s:%i unexpected third token" " starting with '%c'\n", filename.c_str(), line_number, c); errno = EINVAL; goto bad_eof; } // Skip over comment characters from # to \n comment: while (1) { c = fgetc(file); if (c == EOF) { if (errno != 0 and errno != EAGAIN) goto bad_eof; eof = true; goto end_line; } if (c == '\n') { break; } } end_line: // skip blank lines silently. if (key_name.size() == 0) continue; // Complain if only one token is provided on a line. if (target_name.size() == 0) { fprintf(stderr, "%s:%i key name without target name.\n", filename.c_str(), line_number); errno = EINVAL; goto bad_eof; } auto keycode = keycode_from_name(key_name); if (keycode == 0) { fprintf(stderr, "%s:%i unknown key name %s.\n", filename.c_str(), line_number, key_name.c_str()); errno = EINVAL; goto bad_eof; } fprintf(stderr, "Binding %s (%i) to %s\n", key_name.c_str(), keycode, target_name.c_str()); window.bind_keycode(keycode, target_name); } if (fclose(file) != 0) { fprintf(stderr, "Error closing %s\n", filename.c_str()); return false; } return true; bad_eof: fprintf(stderr, "Warning: unexpected end of parsing.\n"); int eof_errno = errno; fclose(file); errno = eof_errno; return true; // I'm getting bogus EOF fails all the time so fake success :/ } void bind_keys(Window& window) { auto default_file = expand_filename("default-keybinds.txt"); auto user_file = expand_filename("keybinds.txt"); bool default_okay = add_key_binds_from_file(window, default_file); if (!default_okay) { fprintf(stderr, "Failed to parse %s\n", default_file.c_str()); fprintf(stderr, "%s (%i)\n", strerror(errno), errno); exit(2); } bool user_okay = add_key_binds_from_file(window, user_file); if (!user_okay) { if (errno == ENOENT) { fprintf(stderr, "Custom keybinds file %s not found.\n", user_file.c_str()); } else { fprintf(stderr, "Failed to parse %s\n", user_file.c_str()); fprintf(stderr, "%s (%i)\n", strerror(errno), errno); exit(2); } } } int main(int argc, char** argv) { // Data directory (where shaders are stored) is the path of this // executable, with the -bin or .exe file extension replaced with // -data. Construct that directory name here. data_directory = argv[0]; if (!ends_with_bin_or_exe(data_directory)) { fprintf(stderr, "%s should end with '-bin' or '.exe'\n", data_directory.c_str()); return 1; } for (int i = 0; i < 4; ++i) data_directory.pop_back(); data_directory += "-data/"; // Instantiate the camera. Camera camera; // Create a window; callback ensures these window dimensions stay accurate. int screen_x = 0, screen_y = 0; auto on_window_resize = [&camera, &screen_x, &screen_y] (int x, int y) { camera.set_window_size(x, y); screen_x = x; screen_y = y; }; Window window(on_window_resize); Renderer* renderer = new_renderer(window); add_key_targets(window, camera); bind_keys(window); while (window.frame_update()) draw_frame(renderer, camera); delete_renderer(renderer); }
aad85aa770183929d8ccd9df0aacf59df35f147f
465a87bdead9aee133a7b36b0c2e826ece517cbb
/ARStudy(Image processing)/ARStudy/main.cpp
5ebb0f7ee747397046be8ca1b609d9d04b460e5c
[]
no_license
kshy9598/ARStudy
a5b55f3808d1e64cc96ee3e9266e4f4c23c3d611
c55ce51cb595f677eb07549203d0032430a90aef
refs/heads/master
2020-06-29T05:20:21.879048
2016-12-08T16:22:03
2016-12-08T16:22:03
74,446,922
0
1
null
null
null
null
UHC
C++
false
false
4,927
cpp
#include <iostream> #include <fstream> #include <cmath> #include "opencv2\highgui\highgui.hpp" #include "opencv2\opencv.hpp" #pragma comment(lib, "opencv_world300d.lib") const double PI = 3.14159265; using namespace std; using namespace cv; bool bLBDown = false; // 마우스 버튼 눌렀는지 체크 bool checkDrag; // 드래그가 이루어졌는지 체크 CvRect box; // 드래그로 그린 박스 // 사각형 그리기 void draw_box(IplImage* img, CvRect rect) { cvRectangle(img, cvPoint(rect.x, rect.y), cvPoint(rect.x + rect.width, rect.y + rect.height), cvScalar(0xff, 0x00, 0x00)); } // 마우스 드래그 void on_mouse(int event, int x, int y, int flag, void* params) { IplImage* image = (IplImage*)params; if (event == CV_EVENT_LBUTTONDOWN){ // 왼쪽 버튼 눌렀을 시, 박스 초기화 bLBDown = true; box = cvRect(x, y, 0, 0); } else if (event == CV_EVENT_LBUTTONUP){ // 왼쪽 버튼 눌렀다가 뗐을 때, 박스의 넓이, 높이를 설정한다. bLBDown = false; checkDrag = true; if (box.width < 0) { box.x += box.width; box.width *= -1; } if (box.height < 0) { box.y += box.height; box.height *= -1; } draw_box(image, box); } else if (event == CV_EVENT_MOUSEMOVE && bLBDown){ // 드래그 중에는 박스의 넓이, 높이를 갱신한다. box.width = x - box.x; box.height = y - box.y; } } // 이미지 복사 Mat copyMat(Mat source) { // source의 Mat을 result로 복사하는 작업 // opencv에 이미 구현이 되어있는 작업이다. // source.copyTo(result); Mat result = Mat::zeros(source.size(), source.type()); for (int i = 0; i < source.cols; i++){ for (int j = 0; j < source.rows; j++){ result.at<Vec3b>(j, i) = source.at<Vec3b>(j, i); } } return result; } // 박스내 이미지 복사 Mat copyBoxMat(Mat source) { return source(box); } // y축반전 Mat yReflecting(Mat source) { Mat result = copyMat(source); for (int i = 0; i < box.width; i++){ for (int j = 0; j < box.height; j++){ result.at<Vec3b>((box.y + j), (box.x + i)) = source.at<Vec3b>(box.y + j, (box.width + box.x - 1) - i); } } return result; } // x축반전 Mat xReflecting(Mat source) { Mat result = copyMat(source); for (int i = 0; i < box.width; i++){ for (int j = 0; j < box.height; j++){ result.at<Vec3b>((box.y + j), (box.x + i)) = source.at<Vec3b>((box.height + box.y - 1) - j, (box.x + i)); } } return result; } // 회전 Mat rotating(Mat source, double degree) { Mat result = copyMat(source); int x0 = box.x + (box.width / 2); int y0 = box.y + (box.height / 2); double cosd = cos(degree*PI / 180); double sind = sin(degree*PI / 180); // 원본에 덮어씌우는 부분으로 인해 왼쪽 90도, 오른쪽 90도만 가능 for (int i = 0; i < box.width; i++){ for (int j = 0; j < box.height; j++){ int x1 = (box.x + i); int y1 = (box.y + j); int x = ((cosd * (x1 - x0)) - (sind * (y1 - y0)) + x0); int y = ((sind * (x1 - x0)) - (cosd * (y1 - y0)) + y0); result.at<Vec3b>(y, x) = source.at<Vec3b>((box.y + j), (box.x + i)); } } return result; } // 확대 Mat scaling(Mat source, Mat boxMat, double scale) { Mat result = copyMat(source); Mat scaleBoxMat; // 사각형 안의 Mat의 크기를 scale배 늘린다. int boxWidth = (int)(boxMat.size().width * scale); int boxHeight = (int)(boxMat.size().height * scale); cv::resize(boxMat, scaleBoxMat, Size(boxWidth, boxHeight)); // 붙여넣을 때 시작 위치 정보를 갱신한다. int x = box.x - (box.width / 2); int y = box.y - (box.height / 2); for (int i = 0; i < boxWidth; i++){ for (int j = 0; j < boxHeight; j++){ result.at<Vec3b>((y + j), (x + i)) = scaleBoxMat.at<Vec3b>(j, i); } } return result; } int main() { IplImage copy; IplImage * resultImage; Mat resultMat, xReflectMat, yReflectMat, leftRotateMat, scaleMat, boxMat; // 이미지 불러오기 Mat gMatImage = imread("./picture/pic.jpg", 1); // Mat 이미지를 IplImage 로 복사한다. copy = gMatImage; resultImage = &copy; checkDrag = false; namedWindow("image"); setMouseCallback("image", on_mouse, resultImage); cvShowImage("image", resultImage); //드래그 대기 while (!checkDrag){ waitKey(100); } cvShowImage("image", resultImage); //사각형 추가된 사진 저장 resultMat = cvarrToMat(resultImage); boxMat = copyBoxMat(resultMat); cout << box.x << ' ' << box.y << ' ' << box.width << ' ' << box.height << endl; yReflectMat = yReflecting(resultMat); // y축 반전 xReflectMat = xReflecting(resultMat); // x축 반전 scaleMat = scaling(resultMat, boxMat, 1.5); // 크기 변경 leftRotateMat = rotating(resultMat, -90.0); // 90도 회전 waitKey(2000); imshow("y반전 이미지", yReflectMat); imshow("x반전 이미지", xReflectMat); imshow("왼쪽 90도 회전 이미지", leftRotateMat); imshow("1.5배 확대 이미지", scaleMat); waitKey(0); return 0; }
b7c78a511904d321aa74ab25ce20a44c3a3f0a0e
d51d72f1b6e834d89c8551bb07487bed84cdaa31
/src/output/osg/customCode/osg/AnimationPath_pmoc.cpp
dc66ae9496a4b899d13c9038f85bec5d8cc50019
[]
no_license
wangfeilong321/osg4noob
221204aa15efa18f1f049548ad076ef27371ecad
99a15c3fd2523c4bd537fa3afb0b47e15c8f335a
refs/heads/master
2021-01-12T20:00:43.854775
2015-11-06T15:37:01
2015-11-06T15:37:01
48,840,543
0
1
null
2015-12-31T07:56:31
2015-12-31T07:56:31
null
UTF-8
C++
false
false
1,778
cpp
#include <osg/AnimationPath> //includes #include <MetaQQuickLibraryRegistry.h> #include <customCode/osg/AnimationPath_pmoc.hpp> using namespace pmoc; osg::QMLAnimationPath::QMLAnimationPath(pmoc::Instance *i,QObject* parent):QReflect_AnimationPath(i,parent){ //custom initializations } QQuickItem* osg::QMLAnimationPath::connect2View(QQuickItem*i){ this->_view=QReflect_AnimationPath::connect2View(i); ///connect this's signals/slot to its qml component//////////////////////////////////////////////////////////////// ///CustomiZE here return this->_view; } void osg::QMLAnimationPath::updateModel(){ QReflect_AnimationPath::updateModel(); ///update this according to state of _model when it has been changed via pmoc///////////////////////////////////////////// ///CustomiZE here } #ifndef AUTOMOCCPP #define AUTOMOCCPP 1 #include "moc_AnimationPath_pmoc.cpp" #endif #include <MetaQQuickLibraryRegistry.h> #include <customCode/osg/AnimationPath_pmoc.hpp> using namespace pmoc; osg::QMLAnimationPathCallback::QMLAnimationPathCallback(pmoc::Instance *i,QObject* parent):QReflect_AnimationPathCallback(i,parent){ //custom initializations } QQuickItem* osg::QMLAnimationPathCallback::connect2View(QQuickItem*i){ this->_view=QReflect_AnimationPathCallback::connect2View(i); ///connect this's signals/slot to its qml component//////////////////////////////////////////////////////////////// ///CustomiZE here return this->_view; } void osg::QMLAnimationPathCallback::updateModel(){ QReflect_AnimationPathCallback::updateModel(); ///update this according to state of _model when it has been changed via pmoc///////////////////////////////////////////// ///CustomiZE here } #ifndef AUTOMOCCPP #define AUTOMOCCPP 1 #include "moc_AnimationPath_pmoc.cpp" #endif
efee5b91d30e90f44f56ca962bc4d6b383191c2d
e86c079391367e0e401482eb43a850685ac54056
/ex05/Human.cpp
f99f1bbfa2e2506c59f393e4c073e71ef72e65d8
[]
no_license
atronk/cpp-01
c85155abd9cf83b5de370ed1c033ba831f4207b8
533a01c039235b436d461df8169169d70c8b97b9
refs/heads/master
2023-05-25T17:51:51.451881
2021-05-22T17:14:38
2021-05-22T17:14:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
312
cpp
#include "Human.hpp" Human::Human() { std::cout << "A Human is created!" << std::endl; } Human::~Human() { std::cout << "A Human is destroyed" << std::endl; } const Brain& Human::getBrain() const { return (this->_brain); } const std::string& Human::identify() const { return(this->getBrain().identify()); }
80e9638e9a9955c45831c86dc3497224eea00c9c
4f2f4ca1cb010ab79ad3933e73dce6671f012054
/SK-Lib/test_sk_header.cpp
2491fbed63d9441372bd23eb682d72c41f371115
[]
no_license
sksavigit/CPP-Progs
f95cfbea5a3caa40baca8637d55e9c1d5a000670
178a414d3c424a18cfe8cf6f9c3df697dffe2993
refs/heads/master
2023-02-17T15:01:02.283778
2021-01-16T13:09:01
2021-01-16T13:09:01
328,104,206
1
0
null
null
null
null
UTF-8
C++
false
false
485
cpp
#include<iostream> #include "sklib_numbers.h" #include "sklib_iostream.h" using namespace std; int main(){ char n1[]="0000000000000000000000000001"; char n2[]="1111123424324243234234234324"; cout << "\n Num1:" <<n1; cout << "\n Num2:" <<n2; cout << "\n Outp:"; int n1Size=sizeof(n1)/sizeof(n1[0]); int n2Size=sizeof(n2)/sizeof(n2[0]); char res[n1Size>n2Size ? n1Size:n2Size]; sum_two_big_numbers(n1,n2,res); cout << res<< "\n"; return 0; }
a702a5d40a3a672624e691115d63b4a004c979d0
7aa189c718f8a63c256685a435d027ace3833f6b
/include/ogonek/error.h++
ca7ff1f2bc1d6ac11fcbdaacee61fbdef1c7430d
[ "CC0-1.0" ]
permissive
rmartinho/ogonek
d5523145108de1255298a17c1c25065beb19b82c
0042f30c6c674effd21d379c53658c88054c58b9
refs/heads/devel
2020-05-21T15:17:39.490890
2019-09-29T10:58:31
2019-09-29T10:58:31
8,255,019
16
3
null
null
null
null
UTF-8
C++
false
false
4,549
// Ogonek // // Written in 2017 by Martinho Fernandes <[email protected]> // // To the extent possible under law, the author(s) have dedicated all copyright and related // and neighboring rights to this software to the public domain worldwide. This software is // distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. /** * Error handling * ============== */ #ifndef OGONEK_ERROR_HPP #define OGONEK_ERROR_HPP #include <ogonek/error_fwd.h++> #include <ogonek/concepts.h++> #include <ogonek/types.h++> #include <ogonek/encoding.h++> #include <range/v3/range_concepts.hpp> #include <range/v3/range_traits.hpp> #include <stdexcept> namespace ogonek { /** * .. class:: unicode_error * * The base class for all Unicode-related errors. */ struct unicode_error : virtual std::exception { char const* what() const noexcept override { return u8"Unicode error"; } }; /** * .. class:: template <EncodingForm Encoding>\ * encode_error : virtual unicode_error * * :thrown: when an error occurs during an encoding operation. */ template <typename Encoding> struct encode_error : virtual unicode_error { CONCEPT_ASSERT(EncodingForm<Encoding>()); char const* what() const noexcept override { return u8"encoding failed "; } }; /** * .. class:: template <EncodingForm Encoding>\ * decode_error : virtual unicode_error * * :thrown: when an error occurs during a decoding operation. */ template <typename Encoding> struct decode_error : virtual unicode_error { CONCEPT_ASSERT(EncodingForm<Encoding>()); char const* what() const noexcept override { return u8"decoding failed"; } }; /** * .. var:: auto assume_valid * * A tag used to request that encoding/decoding functions assume the * input has been validated before. * * .. warning:: * * Using this tag with input that isn't actually valid yields * undefined behavior. */ struct assume_valid_t {} constexpr assume_valid {}; /** * .. var:: auto discard_errors * * An error handler for encoding/decoding functions that simply * discards the portions of the input that have errors. */ struct discard_errors_t { template <typename E> optional<code_point> operator()(E) const { return {}; } } constexpr discard_errors {}; CONCEPT_ASSERT(EncodeErrorHandler<discard_errors_t, archetypes::EncodingForm>()); CONCEPT_ASSERT(DecodeErrorHandler<discard_errors_t, archetypes::EncodingForm>()); /** * .. var:: auto replace_errors * * An error handler for encoding/decoding functions that replaces * portions of the input that have errors with a replacement character. * When decoding, this is |u-fffd|, but when encoding and the target * doesn't support it, some encoding-specific character is used * instead. */ struct replace_errors_t { template <typename Encoding, CONCEPT_REQUIRES_(EncodingForm<Encoding>())> optional<code_point> operator()(encode_error<Encoding>) const { return replacement_character_v<Encoding>; } template <typename Encoding, CONCEPT_REQUIRES_(EncodingForm<Encoding>())> optional<code_point> operator()(decode_error<Encoding>) const { return { U'\uFFFD' }; } } constexpr replace_errors {}; CONCEPT_ASSERT(EncodeErrorHandler<replace_errors_t, archetypes::EncodingForm>()); CONCEPT_ASSERT(DecodeErrorHandler<replace_errors_t, archetypes::EncodingForm>()); /** * .. var:: auto throw_error * * An error handler for encoding/decoding functions that throws when an * error is found in the input. */ struct throw_error_t { template <typename E> optional<code_point> operator()(E e) const { throw e; } } constexpr throw_error {}; CONCEPT_ASSERT(EncodeErrorHandler<throw_error_t, archetypes::EncodingForm>()); CONCEPT_ASSERT(DecodeErrorHandler<throw_error_t, archetypes::EncodingForm>()); } // namespace ogonek #endif // OGONEK_ERROR_HPP
bcee12c3aa60f8c1d8f0802c1bfdfe7600a1e3ef
067b197860f7712e3f92564d0f8d88b0cf34f9d7
/ext/hera/wasserstein/include/dnn/parallel/tbb.h
64c59e0ee985223027151daa201d626258eb299b
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
tgebhart/dionysus_tensorflow
be8757369beb4997b12246c5c7d3cbdbb2fd84bb
344769bb6d5446c8fd43462b1dfd6a08d35631a8
refs/heads/master
2021-09-28T10:03:56.406883
2018-11-16T17:15:34
2018-11-16T17:15:34
112,226,756
2
0
null
null
null
null
UTF-8
C++
false
false
7,126
h
#ifndef PARALLEL_H #define PARALLEL_H //#include <iostream> #include <vector> #include <boost/range.hpp> #include <boost/bind.hpp> #include <boost/foreach.hpp> #ifdef TBB #include <tbb/tbb.h> #include <tbb/concurrent_hash_map.h> #include <tbb/scalable_allocator.h> #include <boost/serialization/split_free.hpp> #include <boost/serialization/collections_load_imp.hpp> #include <boost/serialization/collections_save_imp.hpp> namespace dnn { using tbb::mutex; using tbb::task_scheduler_init; using tbb::task_group; using tbb::task; template<class T> struct vector { typedef tbb::concurrent_vector<T> type; }; template<class T> struct atomic { typedef tbb::atomic<T> type; static T compare_and_swap(type& v, T n, T o) { return v.compare_and_swap(n,o); } }; template<class Iterator, class F> void do_foreach(Iterator begin, Iterator end, const F& f) { tbb::parallel_do(begin, end, f); } template<class Range, class F> void for_each_range_(const Range& r, const F& f) { for (typename Range::iterator cur = r.begin(); cur != r.end(); ++cur) f(*cur); } template<class F> void for_each_range(size_t from, size_t to, const F& f) { //static tbb::affinity_partitioner ap; //tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::range_type, F>, _1, f), ap); tbb::parallel_for(from, to, f); } template<class Container, class F> void for_each_range(const Container& c, const F& f) { //static tbb::affinity_partitioner ap; //tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::range_type, F>, _1, f), ap); tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::const_range_type, F>, _1, f)); } template<class Container, class F> void for_each_range(Container& c, const F& f) { //static tbb::affinity_partitioner ap; //tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::range_type, F>, _1, f), ap); tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::range_type, F>, _1, f)); } template<class ID, class NodePointer, class IDTraits, class Allocator> struct map_traits { typedef tbb::concurrent_hash_map<ID, NodePointer, IDTraits, Allocator> type; typedef typename type::range_type range; }; struct progress_timer { progress_timer(): start(tbb::tick_count::now()) {} ~progress_timer() { std::cout << (tbb::tick_count::now() - start).seconds() << " s" << std::endl; } tbb::tick_count start; }; } // Serialization for tbb::concurrent_vector<...> namespace boost { namespace serialization { template<class Archive, class T, class A> void save(Archive& ar, const tbb::concurrent_vector<T,A>& v, const unsigned int file_version) { stl::save_collection(ar, v); } template<class Archive, class T, class A> void load(Archive& ar, tbb::concurrent_vector<T,A>& v, const unsigned int file_version) { stl::load_collection<Archive, tbb::concurrent_vector<T,A>, stl::archive_input_seq< Archive, tbb::concurrent_vector<T,A> >, stl::reserve_imp< tbb::concurrent_vector<T,A> > >(ar, v); } template<class Archive, class T, class A> void serialize(Archive& ar, tbb::concurrent_vector<T,A>& v, const unsigned int file_version) { split_free(ar, v, file_version); } template<class Archive, class T> void save(Archive& ar, const tbb::atomic<T>& v, const unsigned int file_version) { T v_ = v; ar << v_; } template<class Archive, class T> void load(Archive& ar, tbb::atomic<T>& v, const unsigned int file_version) { T v_; ar >> v_; v = v_; } template<class Archive, class T> void serialize(Archive& ar, tbb::atomic<T>& v, const unsigned int file_version) { split_free(ar, v, file_version); } } } #else #include <algorithm> #include <map> #include <boost/progress.hpp> namespace dnn { template<class T> struct vector { typedef ::std::vector<T> type; }; template<class T> struct atomic { typedef T type; static T compare_and_swap(type& v, T n, T o) { if (v != o) return v; v = n; return o; } }; template<class Iterator, class F> void do_foreach(Iterator begin, Iterator end, const F& f) { std::for_each(begin, end, f); } template<class F> void for_each_range(size_t from, size_t to, const F& f) { for (size_t i = from; i < to; ++i) f(i); } template<class Container, class F> void for_each_range(Container& c, const F& f) { BOOST_FOREACH(const typename Container::value_type& i, c) f(i); } template<class Container, class F> void for_each_range(const Container& c, const F& f) { BOOST_FOREACH(const typename Container::value_type& i, c) f(i); } struct mutex { struct scoped_lock { scoped_lock() {} scoped_lock(mutex& ) {} void acquire(mutex& ) const {} void release() const {} }; }; struct task_scheduler_init { task_scheduler_init(unsigned) {} void initialize(unsigned) {} static const unsigned automatic = 0; static const unsigned deferred = 0; }; struct task_group { template<class Functor> void run(const Functor& f) const { f(); } void wait() const {} }; template<class ID, class NodePointer, class IDTraits, class Allocator> struct map_traits { typedef std::map<ID, NodePointer, typename IDTraits::Comparison, Allocator> type; typedef type range; }; using boost::progress_timer; } #endif // TBB namespace dnn { template<class Range, class F> void do_foreach(const Range& range, const F& f) { do_foreach(boost::begin(range), boost::end(range), f); } } #endif
8bfe178d65efb2f52470e306b87737b39f700ce6
f80d267d410b784458e61e4c4603605de368de9b
/TESTONE/exampleios/usr/local/include/fit_developer_field_description.hpp
a5af5c51d16055664f81433af69b821385dd83c5
[]
no_license
bleeckerj/Xcode-FIT-TEST
84bdb9e1969a93a6380a9c64dce0a0e715d81fe8
37490e3b1e913dc3dfabdae39b48bddea24f1023
refs/heads/master
2021-01-20T14:39:53.249495
2017-02-22T05:59:28
2017-02-22T05:59:28
82,766,547
0
0
null
null
null
null
UTF-8
C++
false
false
1,772
hpp
//////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2017 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 20.24Release // Tag = production/akw/20.24.01-0-g5fa480b //////////////////////////////////////////////////////////////////////////////// #if !defined(FIT_DEVELOPER_FIELD_DESCRIPTION_HPP) #define FIT_DEVELOPER_FIELD_DESCRIPTION_HPP #include "fit_field_description_mesg.hpp" #include "fit_developer_data_id_mesg.hpp" #include <vector> namespace fit { class DeveloperFieldDescription { public: DeveloperFieldDescription() = delete; DeveloperFieldDescription(const DeveloperFieldDescription& other); DeveloperFieldDescription(const FieldDescriptionMesg& desc, const DeveloperDataIdMesg& developer); virtual ~DeveloperFieldDescription(); FIT_UINT32 GetApplicationVersion() const; FIT_UINT8 GetFieldDefinitionNumber() const; std::vector<FIT_UINT8> GetApplicationId() const; private: FieldDescriptionMesg* description; DeveloperDataIdMesg* developer; }; } // namespace fit #endif // defined(FIT_FIELD_DEFINITION_HPP)
83881de53e405fca71ff23806072066608fcd793
4dd6c13f3fc50d0d0ff84ba3d442eee2d3dae742
/Engine/Managers/EventManager.cpp
b7d2c47d7e90411950603f29a5718646637d73c3
[]
no_license
Marcos30004347/AzgardEngine
570773ad3c3f99628708ff06e4f0674dab0b8977
ee5f4e3de1b8bcefdab01b0b71e3d4fcca86b4e3
refs/heads/master
2022-12-08T17:06:06.632049
2020-08-29T01:44:12
2020-08-29T01:44:12
289,409,420
1
0
null
null
null
null
UTF-8
C++
false
false
1,180
cpp
#include<iostream> #include<assert.h> #include "EventManager.hpp" #include "definitions.hpp" #ifdef SDL2_IMP #include <SDL2/SDL.h> SDL_Event sdl2_event; #endif EventManager* EventManager::gInstance = nullptr; EventManager::EventManager() {} EventManager::~EventManager() {} EventManager* EventManager::GetSingletonPtr(void) { assert(EventManager::gInstance); return EventManager::gInstance; } EventManager& EventManager::GetSingleton(void) { assert(EventManager::gInstance); return *EventManager::gInstance; } void EventManager::StartUp() { std::cout << "starting up event manager" << std::endl; EventManager::gInstance = new EventManager(); } void EventManager::ShutDown() { std::cout << "shuting down event manager" << std::endl; delete EventManager::gInstance; } bool EventManager::Pool(Event *event) { #ifdef SDL2_IMP int pedding = SDL_PollEvent(&sdl2_event); switch (sdl2_event.type) { case SDL_QUIT: event->type = QUIT_EVENT; break; default: event->type = NULL_EVENT; break; } #else #error IMPLEMENTATION NOT DEFINED #endif return pedding; }
8b494503d9bf74ff5d28e840affc467e8a440a51
34a3165ded55c6ac5ffe2ff17c9996c66e0e80b5
/cpp/ETProtect.cpp
989ebb94e3100accc0e0e0fd02bff4f34144df29
[]
no_license
monkeyde17/et-protect-package
d806a3196c28c4176374bc21e7ec5769faa72347
77e04d1834d0723c2de7f424a1cbc1efd2321991
refs/heads/master
2016-09-06T05:53:58.824045
2014-12-07T02:29:37
2014-12-07T02:29:37
27,655,865
0
1
null
null
null
null
UTF-8
C++
false
false
1,888
cpp
// // ETProtect.cpp // testcpp // // Created by etond on 14/12/3. // // #include "ETProtect.h" bool ETProtect::isOriginPackage() { unsigned int uHashValue = calculateValueFromFile(); unsigned int uReadValue = readValueFromFile(); #if (ETPROTECTDEBUG) CCLOG("[log] -- hash %u", uHashValue); CCLOG("[log] -- read %u", uReadValue); #endif if (uReadValue == 0 || uHashValue == 0) { return false; } return uReadValue == uHashValue; } unsigned int ETProtect::readValueFromFile(std::string filename /* default = config.et */) { unsigned int uValue = 0; Data data = FileUtils::getInstance()->getDataFromFile(filename); if (data.getSize() > 0) { uValue = ((ETProtectData *)data.getBytes())->getHashValue(); } return uValue; } unsigned int ETProtect::calculateValueFromFile(unsigned int seed /* default = 0x12345678 */) { std::string path = ""; #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) JniMethodInfo minfo; bool isHave = JniHelper::getStaticMethodInfo(minfo, "org/cocos2dx/cpp/AppActivity", "getPath", "()Ljava/lang/String;"); if (isHave) { jobject jobj = minfo.env->CallStaticObjectMethod(minfo.classID, minfo.methodID); /* get the return value */ path = JniHelper::jstring2string((jstring)jobj).c_str(); CCLOG("JNI SUCCESS!"); } #endif unsigned int value = 0; if (path.length() > 0) { ssize_t len = 0; unsigned char *buf = FileUtils::getInstance()->getFileDataFromZip(path, "classes.dex", &len); if (buf) { value = XXH32(buf, len, seed); } delete[] buf; } return value; }
f387d41d0e3251ca4e290372f77e819aa8f41c08
8c8ea797b0821400c3176add36dd59f866b8ac3d
/AOJ/aoj0578.cpp
9b35642e4fd0541224a11ccbbf275376f137bc2c
[]
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
682
cpp
#include <iostream> #include <cstdio> #include <algorithm> #include <string> using namespace std; int N; bool isName(string shop, string board) { int m = board.length(); for(int step=1; step<=m; step++) { for(int i=0; i<m; i++) { string s = ""; for(int j=i; j<m; j+=step) { s += board[j]; } if(s.find(shop) != string::npos) return true; } } return false; } int main(void) { cin >> N; string shop, board; cin >> shop; int ans = 0; for(int i=0; i<N; i++) { cin >> board; if(isName(shop, board)) ans++; } cout << ans << endl; return 0; }
a0a7716d5870fb0a5b552fb6115b6e7b7937b018
c22dbf8b58f205c5b748eeff49dfaf04e3a40f39
/Cantera/clib/src/Storage.cpp
d5462bccbfad490f8de02daa46dd5a4a7f8d90af
[]
no_license
VishalKandala/Cantera1.8-Radcal
ee9fc49ae18ffb406be6cf6854daf2427e29c9ab
1d7c90244e80185910c88fdf247193ad3a1745f3
refs/heads/main
2023-01-20T17:07:23.385551
2020-11-29T05:50:51
2020-11-29T05:50:51
301,748,576
0
0
null
null
null
null
UTF-8
C++
false
false
3,004
cpp
/** * @file Storage.cpp */ /* * $Id: Storage.cpp,v 1.6 2009/07/11 17:16:09 hkmoffa Exp $ */ // Cantera includes #include "Kinetics.h" #include "TransportFactory.h" #include "Storage.h" using namespace std; using namespace Cantera; Storage::Storage() { addThermo(new ThermoPhase); addKinetics(new Kinetics); addTransport(newTransportMgr()); } Storage::~Storage() { clear(); } int Storage::addThermo(thermo_t* th) { if (th->index() >= 0) return th->index(); __thtable.push_back(th); int n = static_cast<int>(__thtable.size()) - 1; th->setIndex(n); //string id = th->id(); //if (__thmap.count(id) == 0) { // __thmap[id] = n; // th->setID(id); //} //else { // throw CanteraError("Storage::addThermo","id already used"); // return -1; //} return n; } int Storage::nThermo() { return static_cast<int>(__thtable.size()); } int Storage::addKinetics(Kinetics* kin) { if (kin->index() >= 0) return kin->index(); __ktable.push_back(kin); int n = static_cast<int>(__ktable.size()) - 1; kin->setIndex(n); return n; } int Storage::addTransport(Transport* tr) { if (tr->index() >= 0) return tr->index(); __trtable.push_back(tr); int n = static_cast<int>(__trtable.size()) - 1; tr->setIndex(n); return n; } // int Storage::addNewTransport(int model, char* dbase, int th, // int loglevel) { // try { // ThermoPhase* thrm = __thtable[th]; // Transport* tr = newTransportMgr(model, // string(dbase), thrm, loglevel); // __trtable.push_back(tr); // return __trtable.size() - 1; // } // catch (CanteraError) {return -1;} // catch (...) {return ERR;} // } int Storage::clear() { int i, n; n = static_cast<int>(__thtable.size()); for (i = 1; i < n; i++) { if (__thtable[i] != __thtable[0]) { delete __thtable[i]; __thtable[i] = __thtable[0]; } } n = static_cast<int>(__ktable.size()); for (i = 1; i < n; i++) { if (__ktable[i] != __ktable[0]) { delete __ktable[i]; __ktable[i] = __ktable[0]; } } n = static_cast<int>(__trtable.size()); for (i = 1; i < n; i++) { if (__trtable[i] != __trtable[0]) { delete __trtable[i]; __trtable[i] = __trtable[0]; } } return 0; } void Storage::deleteKinetics(int n) { if (n == 0) return; if (__ktable[n] != __ktable[0]) delete __ktable[n]; __ktable[n] = __ktable[0]; } void Storage::deleteThermo(int n) { if (n == 0) return; if (n < 0 || n >= (int) __thtable.size()) throw CanteraError("deleteThermo","illegal index"); __thtable[n] = __thtable[0]; } void Storage::deleteTransport(int n) { if (n == 0) return; if (__trtable[n] != __trtable[0]) delete __trtable[n]; __trtable[n] = __trtable[0]; } Storage* Storage::__storage = 0;
73bbdcfbe50a724cb152edeb3ed8f2aed3d76d69
28b90ad96790edd30edc5ba95137cc20261599b5
/nodemcu/MPU_6050_flask_json/MPU_6050_flask_json.ino
134d2fabdbfb2a13cb534495c378ee4397e38c4e
[]
no_license
anshulahuja98/Codefundo-18-IITJ
b09e1b200a5e5d9bbe23f58addc3460a1a19d732
bfae0dde99cd9133bdeabd06fdb73b512214b1f9
refs/heads/master
2020-03-30T01:52:30.166915
2019-02-10T04:34:35
2019-02-10T04:34:35
150,599,578
5
3
null
null
null
null
UTF-8
C++
false
false
5,804
ino
#include <Wire.h> #include <ESP8266HTTPClient.h> #include <ESP8266WiFi.h> #include <ArduinoJson.h> const uint8_t MPU6050SlaveAddress = 0x68; const uint8_t scl = D1; const uint8_t sda = D2; const uint16_t AccelScaleFactor = 16384; const uint16_t GyroScaleFactor = 131; const uint8_t MPU6050_REGISTER_SMPLRT_DIV = 0x19; const uint8_t MPU6050_REGISTER_USER_CTRL = 0x6A; const uint8_t MPU6050_REGISTER_PWR_MGMT_1 = 0x6B; const uint8_t MPU6050_REGISTER_PWR_MGMT_2 = 0x6C; const uint8_t MPU6050_REGISTER_CONFIG = 0x1A; const uint8_t MPU6050_REGISTER_GYRO_CONFIG = 0x1B; const uint8_t MPU6050_REGISTER_ACCEL_CONFIG = 0x1C; const uint8_t MPU6050_REGISTER_FIFO_EN = 0x23; const uint8_t MPU6050_REGISTER_INT_ENABLE = 0x38; const uint8_t MPU6050_REGISTER_ACCEL_XOUT_H = 0x3B; const uint8_t MPU6050_REGISTER_SIGNAL_PATH_RESET = 0x68; int16_t AccelX, AccelY, AccelZ, Temperature, GyroX, GyroY, GyroZ; String flag_payload = ""; int o =0; void setup() { Serial.begin(115200); Wire.begin(sda, scl); MPU6050_Init(); WiFi.begin("null", "patanahi1"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.println("Waiting for connection"); } pinMode(10 , OUTPUT); digitalWrite(10, LOW); } void loop() { if (WiFi.status() == WL_CONNECTED) { double Ax, Ay, Az, T, Gx, Gy, Gz, dev_id; Read_RawValue(MPU6050SlaveAddress, MPU6050_REGISTER_ACCEL_XOUT_H); //divide each with their sensititvity scale factor Ax = (double)AccelX / AccelScaleFactor; Ay = (double)AccelY / AccelScaleFactor; Az = (double)AccelZ / AccelScaleFactor; T = (double)Temperature / 340 + 36.53; //temperature formula Gx = (double)GyroX / GyroScaleFactor; Gy = (double)GyroY / GyroScaleFactor; Gz = (double)GyroZ / GyroScaleFactor; dev_id = 2222; Serial.print("Ax: "); Serial.print(Ax); Serial.print(" Ay: "); Serial.print(Ay); Serial.print(" Az: "); Serial.print(Az); Serial.print(" T: "); Serial.print(T); Serial.print(" Gx: "); Serial.print(Gx); Serial.print(" Gy: "); Serial.print(Gy); Serial.print(" Gz: "); Serial.println(Gz); StaticJsonBuffer<300> JSONbuffer; //Declaring static JSON buffer JsonObject& JSONencoder = JSONbuffer.createObject(); JSONencoder["Sensor type"] = "Acceleration"; JSONencoder["deviceid"] = dev_id; JsonArray& values = JSONencoder.createNestedArray("values"); //JSON array values.add(Ax); //Add value to array values.add(Ay); //Add value to array values.add(Az); //Add value to array values.add(T); //Add value to array JsonArray& timestamps = JSONencoder.createNestedArray("direction1"); //JSON array timestamps.add("x direction"); //Add value to array timestamps.add("y direction"); //Add value to array timestamps.add("z direction"); //Add value to array timestamps.add("Temperature"); //Add vaues to array char JSONmessageBuffer[300]; JSONencoder.prettyPrintTo(JSONmessageBuffer, sizeof(JSONmessageBuffer)); Serial.println(JSONmessageBuffer); HTTPClient http; //Declare object of class HTTPClient http.begin("http://192.168.43.75:8090/post"); //Specify request destination http.addHeader("Content-Type", "application/json"); //Specify content-type header int httpCode = http.POST(JSONmessageBuffer); //Send the request String payload = http.getString(); //Get the response payload Serial.println(httpCode); //Print HTTP return code Serial.println(payload); //Print request response payload http.end(); //Close connection http.begin("http://192.168.43.75:8090/get"); int httpCode1 = http.GET(); //Send the request String payload_get = http.getString(); Serial.println(httpCode1); //Print HTTP return code Serial.println(payload_get); //Print request response payload if (payload_get == "1") { Serial.println("lasjdf liasdj fli"); o = 1; } http.end(); //Close connection if (o == 1) { digitalWrite(10, HIGH); } } else { Serial.println("Error in WiFi connection"); } delay(100); } void I2C_Write(uint8_t deviceAddress, uint8_t regAddress, uint8_t data) { Wire.beginTransmission(deviceAddress); Wire.write(regAddress); Wire.write(data); Wire.endTransmission(); } // read all 14 register void Read_RawValue(uint8_t deviceAddress, uint8_t regAddress) { Wire.beginTransmission(deviceAddress); Wire.write(regAddress); Wire.endTransmission(); Wire.requestFrom(deviceAddress, (uint8_t)14); AccelX = (((int16_t)Wire.read() << 8) | Wire.read()); AccelY = (((int16_t)Wire.read() << 8) | Wire.read()); AccelZ = (((int16_t)Wire.read() << 8) | Wire.read()); Temperature = (((int16_t)Wire.read() << 8) | Wire.read()); GyroX = (((int16_t)Wire.read() << 8) | Wire.read()); GyroY = (((int16_t)Wire.read() << 8) | Wire.read()); GyroZ = (((int16_t)Wire.read() << 8) | Wire.read()); } //configure MPU6050 void MPU6050_Init() { delay(150); I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_SMPLRT_DIV, 0x07); I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_PWR_MGMT_1, 0x01); I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_PWR_MGMT_2, 0x00); I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_CONFIG, 0x00); I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_GYRO_CONFIG, 0x00);//set +/-250 degree/second full scale I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_ACCEL_CONFIG, 0x00);// set +/- 2g full scale I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_FIFO_EN, 0x00); I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_INT_ENABLE, 0x01); I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_SIGNAL_PATH_RESET, 0x00); I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_USER_CTRL, 0x00); }
483636595ef27a032fb65294e55c02e76cef77eb
89421a99baeeb9a368104340ad4efa5f68e2268b
/cpp/Fem1d/Fem1d.cpp
1795d3ce24e60bc2e100e31feb3145252abc3cbc
[]
no_license
mtsodf/ppgi_elem
c16c510c3f78c1e0eb363a36178f79be60818c0a
910155619cb94423eb47dfe793f64be01e750c5a
refs/heads/master
2021-09-06T07:20:18.995847
2018-02-03T18:24:21
2018-02-03T18:24:21
105,206,139
0
0
null
null
null
null
UTF-8
C++
false
false
9,068
cpp
#include "Fem1d.h" #include "../definitions.h" #include <stdlib.h> #include "../LinearAlgebra/Jacobi.h" #include "../LinearAlgebra/Operations.h" #include <cmath> #include "../Utils/Utils.h" using namespace std; class UndefinedFuncForm: public exception { virtual const char* what() const throw() { return "Undefined func form"; } }; real FuncForm(real qsi, char func){ if(func == 0) return (1.0 - qsi)/2.0; if(func == 1) return (1.0 + qsi)/2.0; UndefinedFuncForm ex; throw ex; } real DFuncForm(real qsi, char func){ if(func == 0) return -1.0/2.0; if(func == 1) return 1.0/2.0; UndefinedFuncForm ex; throw ex; } void LocalMatrix(real alpha, real beta, real he, real* lm){ real w; w = sqrt(3.0)/3.0; for (size_t i = 0; i < 2; i++) { for (size_t j = 0; j < 2; j++) { lm[2*i+j] = (he/2)*beta*(FuncForm(-w,i)*FuncForm(-w,j)) + (2/he)*alpha*(DFuncForm(-w,i)*DFuncForm(-w,j)); lm[2*i+j] += (he/2)*beta*(FuncForm( w,i)*FuncForm( w,j)) + (2/he)*alpha*(DFuncForm( w,i)*DFuncForm( w,j)); } } } void GlobalMatrix(int n, real alpha, real beta, real *K, int boundary){ real * hs; real h = 1.0/n; hs = (real*) malloc(sizeof(real)*n); for (size_t i = 0; i < n; i++) { hs[i] = h; } GlobalMatrix(n, alpha, beta, hs, K, boundary); } void GlobalMatrix(int n, real alpha, real beta, real* hs, real *K, int boundary){ real lm[4]; int ndofs = n + 1; for (size_t i = 0; i < n; i++) { LocalMatrix(alpha, beta, hs[i], lm); K[DIM(i,i,ndofs)] += lm[0]; K[DIM(i,i+1,ndofs)] += lm[1]; K[DIM(i+1,i,ndofs)] += lm[2]; K[DIM(i+1,i+1,ndofs)] += lm[3]; } if(boundary == DIRICHLET || boundary == DIRICHLET_NEUMANN){ K[DIM(0,0,ndofs)] = 1.0; K[DIM(0,1,ndofs)] = 0.0; K[DIM(1,0,ndofs)] = 0.0; } if(boundary == DIRICHLET || boundary == NEUMANN_DIRICHLET){ K[DIM(ndofs-1,ndofs-2,ndofs)] = 0.0; K[DIM(ndofs-2,ndofs-1,ndofs)] = 0.0; K[DIM(ndofs-1,ndofs-1,ndofs)] = 1.0; } } void RhsLocal(real he, real f1, real f2, real *Fe){ real w = sqrt(3)/3.0; Fe[0] = f1*(he/2)*(FuncForm(-w,0) * FuncForm(-w,0) + FuncForm(w,0) * FuncForm(w,0)); Fe[0] += f2*(he/2)*(FuncForm(-w,0) * FuncForm(-w,1) + FuncForm(w,0) * FuncForm(w,1)); Fe[1] = f1*(he/2)*(FuncForm(-w,1) * FuncForm(-w,0) + FuncForm(w,1) * FuncForm(w,0)); Fe[1] += f2*(he/2)*(FuncForm(-w,1) * FuncForm(-w,1) + FuncForm(w,1) * FuncForm(w,1)); } void RhsGlobal(int n, real h, real *fs, real *F, real p, real q, real alpha, real beta, int boundary){ real *hs = (real*) malloc(n*sizeof(real)); for (size_t i = 0; i < n; i++) { hs[i] = h; } RhsGlobal(n, hs, fs, F, p, q, alpha, beta, boundary); free(hs); } void RhsGlobal(int n, real *hs, real *fs, real *F, real p, real q, real alpha, real beta, int boundary){ int ndofs = n + 1; for (size_t i = 0; i < ndofs; i++) { F[i] = 0.0; } real Fe[2]; for (size_t i = 0; i < n; i++) { RhsLocal(hs[i], fs[i], fs[i+1], Fe); F[i] += Fe[0]; F[i+1] += Fe[1]; } if(boundary == DIRICHLET || boundary == DIRICHLET_NEUMANN){ F[0] = p; real w = sqrt(3)/3.0; real he = hs[0]; F[1] -= p*((he/2)*beta*(FuncForm(-w,0)*FuncForm(-w,1)) + (2/he)*alpha*(DFuncForm(-w,0)*DFuncForm(-w,1))); F[1] -= p*((he/2)*beta*(FuncForm( w,0)*FuncForm( w,1)) + (2/he)*alpha*(DFuncForm( w,0)*DFuncForm( w,1))); } if(boundary == DIRICHLET || boundary == NEUMANN_DIRICHLET){ real w = sqrt(3)/3.0; real he = hs[n-1]; F[ndofs - 1] = q; F[ndofs-2] -= q*((he/2)*beta*(FuncForm(-w,0)*FuncForm(-w,1)) + (2/he)*alpha*(DFuncForm(-w,0)*DFuncForm(-w,1))); F[ndofs-2] -= q*((he/2)*beta*(FuncForm( w,0)*FuncForm( w,1)) + (2/he)*alpha*(DFuncForm( w,0)*DFuncForm( w,1))); } if(boundary == NEUMANN || boundary == NEUMANN_DIRICHLET){ F[0] -= alpha*p; } if(boundary == NEUMANN || boundary == DIRICHLET_NEUMANN){ F[ndofs-1] += alpha*q; } } extern "C"{ real * Fem1dTest(int n, int entrada){ real *x, *F, *fs, *sol; real *K; real alpha, beta, p, q; int boundary; int unknowns = n + 1; real h = 1.0/n; zero(unknowns, &x); zero(unknowns, &F); zero(unknowns, &fs); zero(unknowns, &sol); zero(unknowns*unknowns, &K); x[0] = 0.0; for (size_t i = 1; i < unknowns; i++) { x[i] = x[i-1] + h; } /* ###################################################################### # Selecao da entrada ###################################################################### */ for (size_t i = 0; i < unknowns; i++) { switch (entrada) { case 0: alpha = 1.0; beta = 1.0; fs[i] = 4*M_PI*M_PI*sin(2*M_PI*x[i]) + sin(2*M_PI*x[i]); sol[i] = sin(2*M_PI*x[i]); boundary = DIRICHLET; p = 0.0; q = 0.0; break; case 1: alpha = 1.0; beta = 0.0; fs[i] = 2*alpha; boundary = DIRICHLET; p = 0.0; q = 0.0; break; case 2: alpha = 1.0; beta = 0.5; boundary = DIRICHLET; fs[i] = 0.5*x[i]; p = 0.0; q = 1.0; break; case 3: alpha = 0.0; beta = 1.0; boundary = DIRICHLET; fs[i] = beta*x[i]*(1-x[i]); p = 0.0; q = 0.0; break; case 4: alpha = 2.0; beta = 1.0; boundary = DIRICHLET; fs[i] = -7*exp(2*x[i]); p = 1.0; q = exp(2.0); break; case 5: alpha = 2.0; beta = 1.0; boundary = NEUMANN; fs[i] = -7*exp(2*x[i]); p = 2.0; q = 2*exp(2.0); break; case 6: alpha = 2.0; beta = 1.0; boundary = NEUMANN_DIRICHLET; fs[i] = -7*exp(2*x[i]); p = 2.0; q = exp(2.0); break; case 7: alpha = 2.0; beta = 1.0; boundary = DIRICHLET_NEUMANN; fs[i] = -7*exp(2*x[i]); p = 1.0; q = 2*exp(2.0); break; case 8: alpha = 1.0; beta = 1.0; boundary = NEUMANN; fs[i] = 4*M_PI*M_PI*sin(2*M_PI*x[i]) + sin(2*M_PI*x[i]); p = 2*M_PI; q = 2*M_PI; break; default: break; } } /* ###################################################################### # Criando Matriz Global ###################################################################### */ GlobalMatrix(n, alpha, beta, K, boundary); /* ###################################################################### # Criando Lado Direito ###################################################################### */ RhsGlobal(n, h, fs, F, p, q, alpha, beta, boundary); /* ###################################################################### # Solucao do Sistema Linear ###################################################################### */ real * calc; zero(unknowns, &calc); cg(unknowns, K, F, calc); free(x); free(F); free(fs); free(sol); free(K); return calc; } }
849e17e440d0e9523fb0dd1a5f7f9d2bf5e1f416
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5686313294495744_0/C++/vidhan13j07/test.cpp
5edfd10037fb916f2f5fbdef7cf9305b0b29d5b9
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
2,489
cpp
#include<bits/stdc++.h> #define sc(v) v.size() #define eb push_back #define pb pop_back #define f(i,a,b) for(int i=a;i<b;i++) #define TC() int t;cin>>t;while(t--) #define all(x) x.begin(),x.end() #define mk make_pair #define fi first #define se second #define endl "\n" #define eps 1e-9 #define pw(x) (1ll<<(x)) #define trace1(x) cout <<#x<<": "<<x<<endl; #define trace2(x, y) cout <<#x<<": "<<x<<" | "<<#y<<": "<<y<< endl; #define trace3(x, y, z) cout <<#x<<": "<<x<<" | "<<#y<<": "<<y<<" | "<<#z<<": "<<z<<endl; #define trace4(a, b, c, d) cout <<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<endl; #define trace5(a, b, c, d, e) cout <<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<<": "<<e<<endl; using namespace std; typedef long long int ll; typedef vector<int> vi; typedef vector<ll> vll; typedef pair<string,string> pi; typedef pair<ll,ll> pll; inline bool EQ(double a,double b) { return fabs(a - b) < 1e-9; } inline void set_bit(int & n, int b) { n |= pw(b); } inline void unset_bit(int & n, int b) { n &= ~pw(b); } int main() { #ifndef ONLINE_JUDGE //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); #endif clock_t tStart = clock(); int tc = 1; int n; map< pi,int > mp; vector< pi > v; set< pi > vv; vector<string> f,rr; string x,y; set<string> a,b; TC() { printf("Case #%d: ", tc++); mp.clear(); v.clear(); a.clear(); b.clear(); scanf("%d",&n); f(i,0,n) { cin>>x>>y; v.eb(mk(x,y)); mp[mk(x,y)] = 1; } int ans = 0; f(i,0,1 << n) { f.clear(); rr.clear(); vv.clear(); int c = 0; f(j,0,n) if(i&(1 << j)) { f.eb(v[j].fi); rr.eb(v[j].se); vv.insert(v[j]); } f(j,0,sc(f)) f(k,0,sc(rr)) { if(vv.find(mk(f[j],rr[k])) != vv.end()) continue; if(mp[mk(f[j],rr[k])]) c++; } ans = max(ans,c); } printf("%d\n",ans); } //printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC); return 0; }
95790908e8d1d2460d9b4d434899e825f5607a16
34bbcd08f3d14f265c507b49746e2997d74ec519
/SFML-MashSim/Spring.cpp
eef2414f96c2c0fe7ea2e01d2dc4757e9a9b4d57
[]
no_license
SenKetZu/SFML-MashSim
cd866d6dc083d1b064f365511fbdcb79aca7f8b0
532b6ca3341888efc0b2a62bdc59301a92075711
refs/heads/master
2023-05-27T23:01:36.185419
2021-06-09T02:57:41
2021-06-09T02:57:41
374,864,394
0
0
null
null
null
null
UTF-8
C++
false
false
809
cpp
#include "Spring.h" #include "DrawAgent.h" Spring::Spring(MassPoint& anchor, MassPoint& exterior): _Anchor(anchor), _Exterior(exterior), _Spring(exterior<<=anchor), _SpringLenght(100.0f), _K(10.0f), _Damping(1.0f), _TimeSP(.01f), //variables trancicion _SpringForce(0.0f), _DampForce(0.0f), _Accel(0.0f), _Vel(0.0f), _Force(0.0f) {} void Spring::Update() { //get timesp _TimeSP = DrawAgent::getInstance().DeltaTime()*100.0f; //calcular spring _Spring = _Exterior <<= _Anchor; //calculo de fuerzas _SpringForce = _K * (_Spring.getMagnitude() - _SpringLenght); _DampForce = _Damping * _Vel; _Force = _SpringForce +10 /*massXgrav*/ - _DampForce; _Accel = _Force / 1 /*mass*/; _Vel += _Accel * _TimeSP; //push masspoint _Exterior.push(MathVector(_Vel*_TimeSP,_Spring.getAngle())); }
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; } }
19203a417004197a3b51e22fe5a3dc21d6bcd8c4
57f87cd5fb9448bc6cdbf10769365393efae3a00
/firmware_v5/telelogger/teleclient.h
a6433b87bd84452fb52cfd90b903677e97fb909f
[]
no_license
NatroNx/Freematics
6a366805aef406d6f4deae050414f9611bbe710e
011ae3212f57fdee7648eb34171e141c55a413ed
refs/heads/master
2020-03-25T02:15:51.919396
2018-07-31T13:14:23
2018-07-31T13:14:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,569
h
class TeleClient { public: virtual void reset() { txCount = 0; txBytes = 0; rxBytes = 0; } virtual bool notify(byte event, const char* serverKey, const char* payload = 0) { return true; } virtual bool connect() { return true; } virtual bool transmit(const char* packetBuffer, unsigned int packetSize) { return true; } virtual void inbound() {} virtual bool begin() { return true; } virtual void end() {} uint32_t txCount = 0; uint32_t txBytes = 0; uint32_t rxBytes = 0; uint32_t lastSyncTime = 0; uint32_t lastSentTime = 0; uint16_t feedid = 0; }; class TeleClientUDP : public TeleClient { public: bool notify(byte event, const char* serverKey, const char* payload = 0); bool connect(); bool transmit(const char* packetBuffer, unsigned int packetSize); void inbound(); bool verifyChecksum(char* data); #if NET_DEVICE == NET_WIFI UDPClientWIFI net; #elif NET_DEVICE == NET_SIM800 UDPClientSIM800 net; #elif NET_DEVICE == NET_SIM5360 UDPClientSIM5360 net; #elif NET_DEVICE == NET_SIM7600 UDPClientSIM7600 net; #else NullClient net; #endif }; class TeleClientHTTP : public TeleClient { public: bool connect(); bool transmit(const char* packetBuffer, unsigned int packetSize); #if NET_DEVICE == NET_WIFI HTTPClientWIFI net; #elif NET_DEVICE == NET_SIM800 HTTPClientSIM800 net; #elif NET_DEVICE == NET_SIM5360 HTTPClientSIM5360 net; #elif NET_DEVICE == NET_SIM7600 HTTPClientSIM7600 net; #else NullClient net; #endif };
921e1b5170f7720987763bafac17b4348a900a5c
9053a16ac04bc9b1273c8d8c31ab9d6e299ba1c6
/unittest/test_boxqp.cpp
c40951d78f74638bfead8aaa863057b94743abff
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ggory15/crocoddyl
7b734313b46a137b44f33d5448057507e23a7fa1
4708428676f596f93ffe2df739faeb5cc38d2326
refs/heads/master
2021-02-08T06:08:35.739839
2020-08-03T15:06:49
2020-08-05T13:46:45
244,117,610
0
0
BSD-3-Clause
2020-03-01T09:02:49
2020-03-01T09:02:48
null
UTF-8
C++
false
false
6,040
cpp
/////////////////////////////////////////////////////////////////////////////// // BSD 3-Clause License // // Copyright (C) 2019-2020, University of Edinburgh // Copyright note valid unless otherwise stated in individual files. // All rights reserved. /////////////////////////////////////////////////////////////////////////////// #include <boost/random.hpp> #include "crocoddyl/core/solvers/box-qp.hpp" #include "unittest_common.hpp" using namespace boost::unit_test; using namespace crocoddyl::unittest; void test_constructor() { // Setup the test std::size_t nx = random_int_in_range(1, 100); crocoddyl::BoxQP boxqp(nx); // Test dimension of the decision vector BOOST_CHECK(boxqp.get_nx() == nx); } void test_unconstrained_qp_with_identity_hessian() { std::size_t nx = random_int_in_range(2, 5); crocoddyl::BoxQP boxqp(nx); boxqp.set_reg(0.); Eigen::MatrixXd hessian = Eigen::MatrixXd::Identity(nx, nx); Eigen::VectorXd gradient = Eigen::VectorXd::Random(nx); Eigen::VectorXd lb = -std::numeric_limits<double>::infinity() * Eigen::VectorXd::Ones(nx); Eigen::VectorXd ub = std::numeric_limits<double>::infinity() * Eigen::VectorXd::Ones(nx); Eigen::VectorXd xinit = Eigen::VectorXd::Random(nx); crocoddyl::BoxQPSolution sol = boxqp.solve(hessian, gradient, lb, ub, xinit); // Checking the solution of the problem. Note that it the negative of the gradient since Hessian // is identity matrix BOOST_CHECK((sol.x + gradient).isMuchSmallerThan(1.0, 1e-9)); // Checking the solution against a regularized case double reg = random_real_in_range(1e-9, 1e2); boxqp.set_reg(reg); crocoddyl::BoxQPSolution sol_reg = boxqp.solve(hessian, gradient, lb, ub, xinit); BOOST_CHECK((sol_reg.x + gradient / (1 + reg)).isMuchSmallerThan(1.0, 1e-9)); // Checking the all bounds are free and zero clamped BOOST_CHECK(sol.free_idx.size() == nx); BOOST_CHECK(sol.clamped_idx.size() == 0); BOOST_CHECK(sol_reg.free_idx.size() == nx); BOOST_CHECK(sol_reg.clamped_idx.size() == 0); } void test_unconstrained_qp() { std::size_t nx = random_int_in_range(2, 5); crocoddyl::BoxQP boxqp(nx); boxqp.set_reg(0.); Eigen::MatrixXd H = Eigen::MatrixXd::Random(nx, nx); Eigen::MatrixXd hessian = H.transpose() * H; hessian = 0.5 * (hessian + hessian.transpose()).eval(); Eigen::VectorXd gradient = Eigen::VectorXd::Random(nx); Eigen::VectorXd lb = -std::numeric_limits<double>::infinity() * Eigen::VectorXd::Ones(nx); Eigen::VectorXd ub = std::numeric_limits<double>::infinity() * Eigen::VectorXd::Ones(nx); Eigen::VectorXd xinit = Eigen::VectorXd::Random(nx); crocoddyl::BoxQPSolution sol = boxqp.solve(hessian, gradient, lb, ub, xinit); // Checking the solution against the KKT solution Eigen::VectorXd xkkt = -hessian.inverse() * gradient; BOOST_CHECK((sol.x - xkkt).isMuchSmallerThan(1.0, 1e-9)); // Checking the solution against a regularized KKT problem double reg = random_real_in_range(1e-9, 1e2); boxqp.set_reg(reg); crocoddyl::BoxQPSolution sol_reg = boxqp.solve(hessian, gradient, lb, ub, xinit); Eigen::VectorXd xkkt_reg = -(hessian + reg * Eigen::MatrixXd::Identity(nx, nx)).inverse() * gradient; BOOST_CHECK((sol_reg.x - xkkt_reg).isMuchSmallerThan(1.0, 1e-9)); // Checking the all bounds are free and zero clamped BOOST_CHECK(sol.free_idx.size() == nx); BOOST_CHECK(sol.clamped_idx.size() == 0); BOOST_CHECK(sol_reg.free_idx.size() == nx); BOOST_CHECK(sol_reg.clamped_idx.size() == 0); } void test_box_qp_with_identity_hessian() { std::size_t nx = random_int_in_range(2, 5); crocoddyl::BoxQP boxqp(nx); boxqp.set_reg(0.); Eigen::MatrixXd hessian = Eigen::MatrixXd::Identity(nx, nx); Eigen::VectorXd gradient = Eigen::VectorXd::Ones(nx); for (std::size_t i = 0; i < nx; ++i) { gradient(i) *= random_real_in_range(-1., 1.); } Eigen::VectorXd lb = Eigen::VectorXd::Zero(nx); Eigen::VectorXd ub = Eigen::VectorXd::Ones(nx); Eigen::VectorXd xinit = Eigen::VectorXd::Random(nx); crocoddyl::BoxQPSolution sol = boxqp.solve(hessian, gradient, lb, ub, xinit); // The analytical solution is the a bounded, and negative, gradient Eigen::VectorXd negbounded_gradient(nx), negbounded_gradient_reg(nx); std::size_t nf = nx, nc = 0, nf_reg = nx, nc_reg = 0; double reg = random_real_in_range(1e-9, 1e2); for (std::size_t i = 0; i < nx; ++i) { negbounded_gradient(i) = std::max(std::min(-gradient(i), ub(i)), lb(i)); negbounded_gradient_reg(i) = std::max(std::min(-gradient(i) / (1 + reg), ub(i)), lb(i)); if (negbounded_gradient(i) != -gradient(i)) { nc += 1; nf -= 1; } if (negbounded_gradient_reg(i) != -gradient(i) / (1 + reg)) { nc_reg += 1; nf_reg -= 1; } } // Checking the solution of the problem. Note that it the negative of the gradient since Hessian // is identity matrix BOOST_CHECK((sol.x - negbounded_gradient).isMuchSmallerThan(1.0, 1e-9)); // Checking the solution against a regularized case boxqp.set_reg(reg); crocoddyl::BoxQPSolution sol_reg = boxqp.solve(hessian, gradient, lb, ub, xinit); BOOST_CHECK((sol_reg.x - negbounded_gradient / (1 + reg)).isMuchSmallerThan(1.0, 1e-9)); // Checking the all bounds are free and zero clamped BOOST_CHECK(sol.free_idx.size() == nf); BOOST_CHECK(sol.clamped_idx.size() == nc); BOOST_CHECK(sol_reg.free_idx.size() == nf_reg); BOOST_CHECK(sol_reg.clamped_idx.size() == nc_reg); } void register_unit_tests() { framework::master_test_suite().add(BOOST_TEST_CASE(boost::bind(&test_constructor))); framework::master_test_suite().add(BOOST_TEST_CASE(boost::bind(&test_unconstrained_qp_with_identity_hessian))); framework::master_test_suite().add(BOOST_TEST_CASE(boost::bind(&test_unconstrained_qp))); framework::master_test_suite().add(BOOST_TEST_CASE(boost::bind(&test_box_qp_with_identity_hessian))); } bool init_function() { register_unit_tests(); return true; } int main(int argc, char* argv[]) { return ::boost::unit_test::unit_test_main(&init_function, argc, argv); }
7726abf0e5e7eb0906fdf74387dd474018ac3154
81f6419ea475836b1f1b24bcd2de77a316bc46a1
/codeforces/BEducational25-06-2020.cpp
03fd55ab7c09117fe485917441cb42c7ab252cb1
[]
no_license
Pramodjais517/competitive-coding
f4e0f6f238d98c0a39f8a9c940265f886ce70cb3
2a8ad013246f2db72a4dd53771090d931ab406cb
refs/heads/master
2023-02-25T12:09:47.382076
2021-01-28T06:57:26
2021-01-28T06:57:26
208,445,032
0
0
null
null
null
null
UTF-8
C++
false
false
1,335
cpp
#include<bits/stdc++.h> using namespace std; // template starts here #define ll long long #define ull unsigned long long #define rs reserve #define pb push_back #define ff first #define ss second #define mp make_pair #define fi(i,s,e,inc) for(auto i=s;i<e;i+=inc) #define fie(i,s,e,inc) for(auto i=s;i<=e;i+=inc) #define fd(i,s,e,dec) for(auto i=s;i>e;i-=dec) #define fde(i,s,e,dec) for(auto i=s;i>=e;i-=dec) #define itr(i,ar) for(auto i=ar.begin();i!=ar.end();i++) #define mod 1000000007 ll N = 1000000; vector<bool> prime(N+1,true); void sieve() { prime[0] = false,prime[1] = false; for(ll i=2;i*i <= N;i++) { if(prime[i]) { for(ll j = i*i; j<= N ;j+=i) prime[j] = false; } } } ll pow(ll a, ll b) { if(b==0) return 1; if(b==1) return a; ll r = pow(a,b/2); if(b&1) return r*a*r; return r*r; } // template ends here int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); ll t; cin>>t; while(t--) { string s; cin>>s; ll n=0; ll a[s.length()]; memset(a,0,sizeof(a)); if(s[0]=='-') a[0] = -1; else a[0] = 1; fi(i,1,s.length(),1) { if(s[i]=='-') a[i] = a[i-1]-1; else a[i] = a[i-1] + 1; } ll b[s.length()]; fi(i,0,s.length(),1) { b[i] = (a[i] + i); } ll ans=0,i=0; while(i<s.length() and b[i]<0) { ans+=(i+1); i++; } ans+=s.length(); cout<<ans<<"\n"; } return 0; }
e80178df0d6d8e25163f4e3d848c8940e1e40d2f
8ea2c608d0ea52bdf26e045ada1367b93f76c046
/OpenGL/objeto.h
6ebbac6737b5475febb0a458045ceb0aa82a7255
[]
no_license
Alexandrecajamos/geometria_comp
0aedf467e337ffc2627e68564c9ade03354f3881
d0264e2ec8bfb0da50c1ee8ec14042779d860612
refs/heads/master
2021-04-12T09:52:11.906345
2018-06-21T21:17:36
2018-06-21T21:17:36
126,262,600
0
0
null
null
null
null
UTF-8
C++
false
false
1,027
h
#ifndef OBJETO_H #define OBJETO_H #include<vector> #include "stdio.h" #include "coord_3d.h" #include "esfera.h" #include <fstream> #include "face.h" #include<cmath> #define TAM 4 class Objeto { public: Objeto(); void addPoint(float x, float y, float z); void addFace(int iP1, int iP2, int iP3); float Ray_intersept(Coord_3D Po, Coord_3D Dir, int *iFace); bool Tiro(Coord_3D Ponto); void calc_Esfera(); void ImpPoints(); void ImpFaces(); bool Obstaculo(Coord_3D Pint, Coord_3D l); void Libera(); void Ordena(int eixo); void CopiaPontos(Objeto* O); Coord_3D Centro(); float Area_Externa(); float Volume(); int MaiorX();//Retorna Indice int MenorX();//Retorna Indice int MaiorY();//Retorna Indice int MenorY();//Retorna Indice int MaiorZ();//Retorna Indice int MenorZ();//Retorna Indice bool Pertence(int iP1, int iP2, int iP3); Esfera Esf; std::vector<Coord_3D*> points; std::vector<Face*> faces; }; #endif // OBJETO_H
7ade5627a226f91a37d1e00ba158ba1f1eace614
6a56f4e8bfa2da98cfc51a883b7cae01736c3046
/ovaldi-code-r1804-trunk/src/probes/unix/PasswordProbe.h
03062e89f9d72a9942bd7a1aac071a565a9a4ae6
[]
no_license
tmcclain-taptech/Ovaldi-Win10
6b11e495c8d37fd73aae6c0281287cadbc491e59
7214d742c66f3df808d70e880ba9dad69cea403d
refs/heads/master
2021-07-07T09:36:30.776260
2019-03-28T19:11:29
2019-03-28T19:11:29
164,451,763
2
1
null
null
null
null
UTF-8
C++
false
false
2,857
h
// // //****************************************************************************************// // Copyright (c) 2002-2014, The MITRE Corporation // 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 MITRE Corporation nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT // OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR // TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //****************************************************************************************// #ifndef PASSWORDPROBE_H #define PASSWORDPROBE_H #include "AbsProbe.h" #include "Item.h" #include "Object.h" #include <pwd.h> #include <string> /** This class is responsible for collecting information about unix password_objects. */ class PasswordProbe : public AbsProbe { public: virtual ~PasswordProbe(); /** Get all the files on the system that match the pattern and collect their attributes. */ virtual ItemVector* CollectItems(Object* object); /** Return a new Item created for storing file information */ virtual Item* CreateItem(); /** Ensure that the PasswordProbe is a singleton. */ static AbsProbe* Instance(); private: PasswordProbe(); /** Creates an item from a passwd struct */ Item *CreateItemFromPasswd(struct passwd const *pwInfo); /** Finds a single item by name. */ Item *GetSingleItem(const std::string& username); /** Finds multiple items according to the given object entity. */ ItemVector *GetMultipleItems(Object *passwordObject); /** Singleton instance */ static PasswordProbe* instance; }; #endif
77e95d74adb0d91068d318a9f567bd723eb4bd30
8a970882a0be9f3d85edbf6ecec0050b762e8d80
/GazEngine/gazengine/Entity.h
ded187d2149547f453fc7c141f5bfa9b3cc59aa9
[]
no_license
simplegsb/gazengine
472d1de8d300c8406ffec148844911fd21d5c1e0
b0a7300aa535b14494789fb88c16d6dda1c4e622
refs/heads/master
2016-09-05T21:02:49.531802
2013-04-29T08:33:16
2013-04-29T08:33:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,553
h
#ifndef ENTITY_H_ #define ENTITY_H_ #include <memory> #include <string> #include <vector> class Component; class Entity { public: static const unsigned short UNCATEGORIZED = 0; Entity(unsigned short category = UNCATEGORIZED, const std::string& name = std::string()); virtual ~Entity(); /** * <p> * Adds a component. * </p> * * @param component The component to add. */ void addComponent(Component* component); unsigned short getCategory() const; /** * <p> * Retrieves the components. * </p> * * @return The components. */ template<typename ComponentType> std::vector<ComponentType*> getComponents() const; unsigned int getId() const; /** * <p> * Retrieves the name of this <code>Entity</code>. * </p> * * @return The name of this <code>Entity</code>. */ const std::string& getName() const; /** * <p> * Retrieves a single component. * </p> * * @return The single component. */ template<typename ComponentType> ComponentType* getSingleComponent() const; /** * <p> * Removes a component. * </p> * * @param component The component to remove. */ void removeComponent(const Component& component); private: unsigned short category; /** * <p> * The components. * </p> */ std::vector<Component*> components; unsigned int id; /** * <p> * The name of this <code>Entity</code>. * </p> */ std::string name; static unsigned int nextId; }; #include "Entity.tpp" #endif /* ENTITY_H_ */
8cd8538339e5a1170a27aef802a5f18cacfeeeab
6115a9fffbc4e0d94a8aae1bffe79557ae059a09
/FinalProject/avltreeindex.h
2f774eea408d83aa6352573bdd3f0f40ebf8690f
[]
no_license
natesotoole1/SearchEngine
74bc40a3b438758699a9f3a662a61c9f72125a96
b3623634acda01f9135e80cd7d00deae3d8f756c
refs/heads/master
2021-01-16T22:08:15.300799
2016-04-12T12:39:08
2016-04-12T12:39:08
45,565,794
0
0
null
null
null
null
UTF-8
C++
false
false
2,139
h
#ifndef AVLTreeIndex_H #define AVLTreeIndex_H #include <iostream> #include <fstream> #include <string> #include <cstdio> #include "indexinterface.h" #include "term.h" // git using namespace std; /*! \brief * AVL Node implementation for the AVL Tree structure. */ // Node declaration struct AVL_Node { Term* data;///< Term pointer where all the data is held //struct AVL_Node root; struct AVL_Node *left; ///< left child struct AVL_Node *right; ///< right child int height; ///< height of tree }; /*! \brief * AVLTreeIndex.h has AVL Trees public and private classes in them. */ // Class declaration class AVLTreeIndex { public: AVLTreeIndex(); ///< constructor void insert(Term*); ///< public insert function that calls the private function AVL_Node* balance(AVL_Node*&); ///< figures out when to rotate child or not int height(AVL_Node *&); ///< returns the height of the tree int diff(AVL_Node *&); ///< returns the difference in height int max(int, int); ///< gets the max height AVL_Node* rotateRightChild(AVL_Node*&); ///< rotate right child AVL_Node* rotateLeftChild(AVL_Node*&); ///< rotate left child AVL_Node* doubleLeftChild(AVL_Node*&); ///< rotate left child than rotate right child AVL_Node* doubleRightChild(AVL_Node*&); ///< rotate right child than rotate left child Term* find(string); ///< public find function that is called from the interface and than passes it to private function void createPersistence(int, ofstream&); ///< public call to create persistence than calls the private function void clearTree(); ///< public call to clear index than calls the private function private: AVL_Node* root; ///< root of the tree void insert(AVL_Node*& ,Term*); ///< inserts node if null than checks balance to see if it is needed to rotate void createPersistence(AVL_Node*& , int, ofstream&); ///< creates the persistence from each individual avl tree void continue_search(AVL_Node*& curr, string word); ///< finds word called by query void clearTree(AVL_Node*); /// <clear the tree }; #endif // AVLTreeINDEX_H
0acbecc764fbfcc61711e5ca5ce12561d4730135
399b5e377fdd741fe6e7b845b70491b9ce2cccfd
/LLVM_src/libcxx/test/std/utilities/time/time.cal/time.cal.ymwdlast/types.pass.cpp
e0580fac76fa9102f0058519d247d1d7895bce5a
[ "NCSA", "LLVM-exception", "MIT", "Apache-2.0" ]
permissive
zslwyuan/LLVM-9-for-Light-HLS
6ebdd03769c6b55e5eec923cb89e4a8efc7dc9ab
ec6973122a0e65d963356e0fb2bff7488150087c
refs/heads/master
2021-06-30T20:12:46.289053
2020-12-07T07:52:19
2020-12-07T07:52:19
203,967,206
1
3
null
2019-10-29T14:45:36
2019-08-23T09:25:42
C++
UTF-8
C++
false
false
802
cpp
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03, c++11, c++14, c++17 // <chrono> // class year_month_weekday_last_last; #include <chrono> #include <type_traits> #include <cassert> #include "test_macros.h" int main() { using year_month_weekday_last = std::chrono::year_month_weekday_last; static_assert(std::is_trivially_copyable_v<year_month_weekday_last>, ""); static_assert(std::is_standard_layout_v<year_month_weekday_last>, ""); }
7394745b36ae5104c00825320576a873b5d50654
c5ed2d57496cafa1b10925814b4fc670fb9d84af
/Opensankore/build-Sankore_3.1-Unnamed-Release/build/win32/release/moc/moc_UBExportCFF.cpp
ccd670b2c223a0e089afb0adb057245688ac9bac
[]
no_license
Educabile/Ardesia
5f5175fef5d7a15ea79469901bdd4c068cc8fec7
9b7b0bfe1c89e89c0ef28f93f6b1e0ac8c348230
refs/heads/master
2020-03-31T17:16:50.538146
2018-10-10T12:34:43
2018-10-10T12:34:43
152,416,207
0
0
null
null
null
null
UTF-8
C++
false
false
2,429
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'UBExportCFF.h' ** ** Created: Fri 4. May 12:28:36 2018 ** by: The Qt Meta Object Compiler version 63 (Qt 4.8.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../../../../Sankore-3.1/src/adaptors/UBExportCFF.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'UBExportCFF.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 63 #error "This file was generated using the moc from 4.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 static const uint qt_meta_data_UBExportCFF[] = { // content: 6, // 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 }; static const char qt_meta_stringdata_UBExportCFF[] = { "UBExportCFF\0" }; void UBExportCFF::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 QMetaObjectExtraData UBExportCFF::staticMetaObjectExtraData = { 0, qt_static_metacall }; const QMetaObject UBExportCFF::staticMetaObject = { { &UBExportAdaptor::staticMetaObject, qt_meta_stringdata_UBExportCFF, qt_meta_data_UBExportCFF, &staticMetaObjectExtraData } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &UBExportCFF::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *UBExportCFF::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *UBExportCFF::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_UBExportCFF)) return static_cast<void*>(const_cast< UBExportCFF*>(this)); return UBExportAdaptor::qt_metacast(_clname); } int UBExportCFF::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = UBExportAdaptor::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_END_MOC_NAMESPACE
[ "salvatore.naddeo@€ducabile.it" ]
salvatore.naddeo@€ducabile.it
5ac2daee273b036045797a05ba6d6c787fc58545
3ec6a0f09686dfc885fce0c60b1cf25e24fe4dd0
/obs-node/src/cpp_old/display.cpp
a8bcfa820cdbe66dad1260e0bd265bb13b394bb9
[]
no_license
aidangoettsch/hydro-bot
dcaff8ce46970f87aef4d36f5c86b81f6b9979c4
ecbb3902ea0de38de7f39a372aee9c0cb375e6df
refs/heads/master
2023-03-22T10:35:28.261052
2021-03-11T17:07:31
2021-03-11T17:07:31
335,796,934
1
0
null
null
null
null
UTF-8
C++
false
false
3,609
cpp
// Most of code in this file are copied from // https://github.com/stream-labs/obs-studio-node/blob/staging/obs-studio-server/source/nodeobs_display.cpp #include "display.h" #include "./platform/platform.h" Display::Display(void *parentHandle, int scaleFactor, std::string &sourceName) { this->parentHandle = parentHandle; this->scaleFactor = scaleFactor; // create window for display this->windowHandle = createDisplayWindow(parentHandle); // create display gs_init_data gs_init_data = {}; gs_init_data.adapter = 0; gs_init_data.cx = 1; gs_init_data.cy = 1; gs_init_data.num_backbuffers = 1; gs_init_data.format = GS_RGBA; gs_init_data.zsformat = GS_ZS_NONE; #ifdef _WIN32 gs_init_data.window.hwnd = windowHandle; #elif __APPLE__ gs_init_data.window.view = static_cast<objc_object *>(windowHandle); #endif obs_display = obs_display_create(&gs_init_data, 0x0); if (!obs_display) { throw std::runtime_error("Failed to create the display"); } // obs source obs_source = obs_get_source_by_name(sourceName.c_str()); obs_source_inc_showing(obs_source); // draw callback obs_display_add_draw_callback(obs_display, displayCallback, this); } Display::~Display() { obs_display_remove_draw_callback(obs_display, displayCallback, this); if (obs_source) { obs_source_dec_showing(obs_source); obs_source_release(obs_source); } if (obs_display) { obs_display_destroy(obs_display); } destroyWindow(windowHandle); } void Display::move(int x, int y, int width, int height) { this->x = x; this->y = y; this->width = width; this->height = height; moveWindow(windowHandle, x, y, width, height); obs_display_resize(obs_display, width * scaleFactor, height * scaleFactor); } void Display::displayCallback(void *displayPtr, uint32_t cx, uint32_t cy) { auto *dp = static_cast<Display *>(displayPtr); // Get proper source/base size. uint32_t sourceW, sourceH; if (dp->obs_source) { sourceW = obs_source_get_width(dp->obs_source); sourceH = obs_source_get_height(dp->obs_source); if (sourceW == 0) sourceW = 1; if (sourceH == 0) sourceH = 1; } else { obs_video_info ovi = {}; obs_get_video_info(&ovi); sourceW = ovi.base_width; sourceH = ovi.base_height; if (sourceW == 0) sourceW = 1; if (sourceH == 0) sourceH = 1; } gs_projection_push(); gs_ortho(0.0f, (float)sourceW, 0.0f, (float)sourceH, -1, 1); // Source Rendering obs_source_t *source; if (dp->obs_source) { obs_source_video_render(dp->obs_source); /* If we want to draw guidelines, we need a scene, * not a transition. This may not be a scene which * we'll check later. */ if (obs_source_get_type(dp->obs_source) == OBS_SOURCE_TYPE_TRANSITION) { source = obs_transition_get_active_source(dp->obs_source); } else { source = dp->obs_source; obs_source_addref(source); } } else { obs_render_main_texture(); /* Here we assume that channel 0 holds the primary transition. * We also assume that the active source within that transition is * the scene that we need */ obs_source_t *transition = obs_get_output_source(0); source = obs_transition_get_active_source(transition); obs_source_release(transition); } obs_source_release(source); gs_projection_pop(); }
a408cd231d1845ea66458abff8bd63b1571e3a75
ba6ecbc7036d2b7c8839f4f86e2c3dec44d57bee
/features/visuals/visuals.cpp
5ba75ffb6949425df8c0dfd07f72147c306665a1
[ "MIT" ]
permissive
ALEHACKsp/gmod-sdk
a484e5c1efbce5573a659cbb4530d0740f4b7d22
482c66989e0f55bd7b52bb0bee48b0b0b2bb893f
refs/heads/master
2021-04-21T03:14:57.941168
2020-03-23T21:37:24
2020-03-23T21:37:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,931
cpp
#include "visuals.hpp" #include "../../utilities/math.hpp" #include "../../utilities/drawmanager.hpp" #include "../../options.hpp" void Visuals::RunPlayerESP() { auto get_box = [](Vector feet, Vector head) -> RECT { RECT ret; auto h_ = fabs(head.y - feet.y); auto w_ = h_ / 2.0f; ret.left = (int)(feet.x - w_ * 0.5f); ret.right = (int)(ret.left + w_); ret.bottom = (feet.y > head.y ? (int)(feet.y) : (int)(head.y)); ret.top = (feet.y > head.y ? (int)(head.y) : (int)(feet.y)); return ret; }; if (!Interfaces::EngineClient->IsInGame()) return; if (!Vars.esp_enabled) return; CEntity* LocalPlayer = Interfaces::EntityList->GetEntity(Interfaces::EngineClient->GetLocalPlayer()); for (size_t i = 0; i <= Interfaces::EntityList->GetHighestEntityIndex(); i++) { CEntity* entity = Interfaces::EntityList->GetEntity(i); if (!entity) continue; if (entity == LocalPlayer && Vars.esp_ignore_local) continue; if (!entity->IsPlayer()) continue; if (!entity->IsAlive()) continue; Vector feet, eye; if (!Math::WorldToScreen(entity->GetAbsOrigin(), feet) || !Math::WorldToScreen(entity->GetEyePos(), eye)) continue; auto box = get_box(feet, eye); auto box_clr = Utilities::IsVisible(LocalPlayer, entity, entity->GetEyePos()) ? ImColor(1.f, 1.f, 0.f) : ImColor(1.f, 0.f, 0.f); if (Vars.esp_box) { Draw::Rect(ImVec2(box.left - 1, box.top - 1), ImVec2(box.right + 1, box.bottom + 1), ImColor(0.f, 0.f, 0.f), 5, 0, 1.f); Draw::Rect(ImVec2(box.left, box.top), ImVec2(box.right, box.bottom), box_clr, 5, 0, 1.f); Draw::Rect(ImVec2(box.left + 1, box.top + 1), ImVec2(box.right - 1, box.bottom - 1), ImColor(0.f, 0.f, 0.f), 5, 0, 1.f); } if (Vars.esp_healthbar) { float CurHealth = entity->GetHealth(); float maxHp = entity->GetMaxHealth(); Draw::FilledRect(ImVec2(box.left - 6, box.top), ImVec2(box.left - 3, box.bottom), ImColor(0.f, 0.f, 0.f), 5, 0); auto x_start = box.left - 5; auto y_start = box.top + 1; auto y_end = box.bottom - 1; auto y_size = (y_end - y_start) / maxHp * CurHealth; Draw::Line(ImVec2(x_start, y_end - y_size), ImVec2(x_start, y_end), ImColor(0.f, 1.f, 0.f), 1); } if (Vars.esp_name) { auto getName = [](CEntity* entity) -> std::string { auto glua = Interfaces::Lua->CreateInterface(LUA::type::client); if (!glua) return {}; glua->PushSpecial(LUA::special::glob); glua->GetField(-1, "Entity"); glua->PushNumber(entity->GetIndex()); glua->Call(1, 1); glua->GetField(-1, "Name"); glua->Push(-2); glua->Call(1, 1); std::string name = glua->GetString(); glua->Pop(3); return name; }; auto name = getName(entity); auto name_size = ImGui::CalcTextSize(name.c_str()); auto x_start = box.left + (box.right - box.left) / 2.f; Draw::Text(ImVec2(x_start - (name_size.x / 2.f), box.top - name_size.y - 1), name.c_str(), ImColor(1.f, 1.f, 1.f)); } } }
8578d23f5dcb5dfb05d51a07acc1f3c32a2ca378
94b66d01a39eb69cabcbeac2fb1df9131c8faac5
/OnoMojeLigaLegendi/Crafting.hpp
3b0678022aca575ce950653a8fa92a016699d66f
[]
no_license
danilomedic/LeagueOfLegends-Project
687b2b6f663e41099112c5d48d8c731744b071e0
006651bf03f774817c2c02a6522039faeaa2b004
refs/heads/master
2021-05-17T14:47:35.290317
2020-05-08T10:07:06
2020-05-08T10:07:06
250,828,856
0
0
null
null
null
null
UTF-8
C++
false
false
2,901
hpp
#ifndef CRAFTING_HPP_INCLUDED #define CRAFTING_HPP_INCLUDED #include <cmath> class Crafting { private: int box, key, keyFrag, orangeEssence, skins; public: Crafting() { box = 0; key = 0; keyFrag = 0; orangeEssence = 0; skins = 0; } Crafting(int b, int k, int kf, int oE, int s) { box = b; key = k; keyFrag = kf; orangeEssence = oE; skins = s; } Crafting(const Crafting &c) { box = c.box; key = c.key; keyFrag = c.keyFrag; orangeEssence = c.orangeEssence; skins = c.skins; } ~Crafting() {} void buySkin() { if(skins == 0) { cout << "Nemate skinova na stanju!" << endl; return; } int price; cout << "Vase stanje: " << orangeEssence << " orange essence" << endl; cout << "Koliko kosta skin: "; cin >> price; if(orangeEssence > price) orangeEssence -= price; else cout << "Nemate dovoljno orange essence!" << endl; } void openBox() { if(box == 0) { cout << "Nemate ni jednu kutiju!" << endl; return; } int option = rand() % 2 + 1; int oE = rand() % 1000 + 1; if(option == 1) { orangeEssence += oE; cout << "Dobili ste " << oE << "orange essenca i stanje vam je " << orangeEssence << "." << endl; } if(option == 2) { skins += 1; cout << "Dobili ste 1 skin i sad ih imate " << skins << "." << endl; } box -= 1; } void forgeKey() { if(keyFrag >= 3) { keyFrag -= 3; key += 1; cout << "Sad imate " << keyFrag << "fragmenta i " << key << "kljuceva" << endl; } else cout << "Nemate dovoljno fragmenta!" << endl; } ///----------------- GET: int getBox()const { return box; } int getKey()const { return key; } int getKeyFrag()const { return keyFrag; } int getOrangeEssence()const { return orangeEssence; } int getSkins()const { return skins; } ///----------------- SET: void setBox(const int a) { box = a; } void setKey(const int a) { key = a; } void setKeyFrag(const int a) { keyFrag = a; } void setOrangeEssence(const int a) { orangeEssence = a; } void setSkins(const int a) { skins = a; } Crafting& operator= (Crafting& c) { box = c.box; key = c.key; keyFrag = c.keyFrag; orangeEssence = c.orangeEssence; skins = c.skins; return *this; } }; #endif // CRAFTING_HPP_INCLUDED
d46a3b3f4252a9ed58f62fd5e8068ade7c69129b
aa701c8621b90137f250151db3c74881767acb6d
/core/nes/mapper/042.cpp
20039b24a52dade8d098a2f5e8052ce2675d369c
[]
no_license
ptnnx/e-mulator-PSP
3215bbfe0870a41b341f207ba11a2d1fe2b64b56
538c700096fcef34bba9145750f7f9e44d3e7446
refs/heads/main
2023-02-05T09:57:34.046277
2020-12-31T08:59:04
2020-12-31T08:59:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,026
cpp
STATIC void NES_mapper42_Init(); STATIC void NES_mapper42_Reset(); STATIC void NES_mapper42_MemoryWrite(u32 addr, u8 data); STATIC void NES_mapper42_HSync(u32 scanline); ///////////////////////////////////////////////////////////////////// // Mapper 42 STATIC void NES_mapper42_Init() { g_NESmapper.Reset = NES_mapper42_Reset; g_NESmapper.MemoryWrite = NES_mapper42_MemoryWrite; g_NESmapper.HSync = NES_mapper42_HSync; } STATIC void NES_mapper42_Reset() { // set CPU bank pointers g_NESmapper.set_CPU_bank3(0); g_NESmapper.set_CPU_bank4(g_NESmapper.num_8k_ROM_banks-4); g_NESmapper.set_CPU_bank5(g_NESmapper.num_8k_ROM_banks-3); g_NESmapper.set_CPU_bank6(g_NESmapper.num_8k_ROM_banks-2); g_NESmapper.set_CPU_bank7(g_NESmapper.num_8k_ROM_banks-1); // set PPU bank pointers g_NESmapper.set_PPU_banks8(0,1,2,3,4,5,6,7); } STATIC void NES_mapper42_MemoryWrite(u32 addr, u8 data) { switch(addr & 0xE003) { case 0x8000: g_NESmapper.set_PPU_banks8(((data&0x1f)<<3)+0,((data&0x1f)<<3)+1,((data&0x1f)<<3)+2,((data&0x1f)<<3)+3,((data&0x1f)<<3)+4,((data&0x1f)<<3)+5,((data&0x1f)<<3)+6,((data&0x1f)<<3)+7); break; case 0xE000: { g_NESmapper.set_CPU_bank3(data & 0x0F); } break; case 0xE001: { if(data & 0x08) { g_NESmapper.set_mirroring2(NES_PPU_MIRROR_HORIZ); } else { g_NESmapper.set_mirroring2(NES_PPU_MIRROR_VERT); } } break; case 0xE002: { if(data & 0x02) { g_NESmapper.Mapper42.irq_enabled = 1; } else { g_NESmapper.Mapper42.irq_enabled = 0; g_NESmapper.Mapper42.irq_counter = 0; } } break; } // LOG("W " << HEX(addr,4) << " " << HEX(data,2) << endl); } STATIC void NES_mapper42_HSync(u32 scanline) { if(g_NESmapper.Mapper42.irq_enabled) { if(g_NESmapper.Mapper42.irq_counter < 215) { g_NESmapper.Mapper42.irq_counter++; } if(g_NESmapper.Mapper42.irq_counter == 215) { NES6502_DoIRQ(); g_NESmapper.Mapper42.irq_enabled = 0; } } } /////////////////////////////////////////////////////////////////////
434ebd600ce44c7ba66bbb59c8173127dd69edb7
ad842c1f357e8e7146f0f241bcca4e2cad1e6375
/apps/gsvlabel/descriptor.cpp
1e17e7e4048e452658130f353795aa70dbbc2854
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
bmatejek/gsvgaps
19164523327e9fcccb83908fabdaa91cc6caabe7
4beb271167d306ad7e87b214895670f3d7c65dbd
refs/heads/main
2023-01-21T16:29:33.491450
2020-11-26T02:04:26
2020-11-26T02:04:26
316,090,459
0
0
null
null
null
null
UTF-8
C++
false
false
2,290
cpp
//////////////////////////////////////////////////////////////////////// // Source file for object descriptor class //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// // Include files //////////////////////////////////////////////////////////////////////// #include "object.h" //////////////////////////////////////////////////////////////////////// // Functions //////////////////////////////////////////////////////////////////////// ObjectDescriptor:: ObjectDescriptor(const double *values, int nvalues) : nvalues(nvalues), values(NULL) { // Initialize values if (nvalues > 0) { this->values = new double [ nvalues ]; for (int i = 0; i < nvalues; i++) { this->values[i] = (values) ? values[i] : 0.0; } } } ObjectDescriptor:: ObjectDescriptor(const ObjectDescriptor& descriptor) : nvalues(descriptor.nvalues), values(NULL) { // Initialize values if (nvalues > 0) { values = new double [ nvalues ]; for (int i = 0; i < nvalues; i++) { values[i] = descriptor.values[i]; } } } ObjectDescriptor:: ~ObjectDescriptor(void) { // Delete values if (values) delete [] values; } ObjectDescriptor& ObjectDescriptor:: operator=(const ObjectDescriptor& descriptor) { // Copy values Reset(descriptor.values, descriptor.nvalues); return *this; } void ObjectDescriptor:: Reset(const double *values, int nvalues) { // Delete old values if ((this->nvalues > 0) && (this->values)) { delete [] this->values; this->values = NULL; this->nvalues = 0; } // Assign new values if (nvalues > 0) { // Allocate new values this->nvalues = nvalues; this->values = new double [ this->nvalues ]; // Copy values for (int i = 0; i < nvalues; i++) { this->values[i] = (values) ? values[i] : 0.0; } } } double ObjectDescriptor:: SquaredDistance(const ObjectDescriptor& descriptor) const { // Check dimensionality assert(nvalues == descriptor.nvalues); // Sum squared distances double sum = 0; for (int i = 0; i < nvalues; i++) { double delta = values[i] - descriptor.values[i]; sum += delta * delta; } // Return squared distance return sum; }
ca83a558bcc72c5055c6fbf661b26acbaf1aeb08
6701a2c3fb95baba0da5754b88d23f79a2b10f7f
/protocol/mcbp/libmcbp/mcbp_packet_printer.cc
6329b15ffaeaf2a08d698518c5c195e5ef3a5e8b
[]
no_license
teligent-ru/kv_engine
80630b4271d72df9c47b505a586f2e8275895d3e
4a1b741ee22ae3e7a46e21a423451c58186a2374
refs/heads/master
2018-11-07T20:52:54.132785
2018-01-15T16:34:10
2018-01-17T08:29:54
117,808,163
1
0
null
2018-01-17T08:34:05
2018-01-17T08:34:05
null
UTF-8
C++
false
false
4,594
cc
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2017 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <getopt.h> #include <mcbp/mcbp.h> #include <platform/dirutils.h> #include <platform/memorymap.h> #include <platform/sized_buffer.h> #include <algorithm> #include <iostream> enum class Format { Raw, Gdb, Lldb }; Format parseFormat(std::string format) { std::transform(format.begin(), format.end(), format.begin(), toupper); if (format == "RAW") { return Format::Raw; } if (format == "GDB") { return Format::Gdb; } if (format == "LLDB") { return Format::Lldb; } throw std::invalid_argument("Unknown format: " + format); } int main(int argc, char** argv) { Format format{Format::Raw}; static struct option longopts[] = { {"format", required_argument, nullptr, 'f'}, {nullptr, 0, nullptr, 0}}; int cmd; while ((cmd = getopt_long(argc, argv, "f:", longopts, nullptr)) != -1) { switch (cmd) { case 'f': try { format = parseFormat(optarg); } catch (const std::invalid_argument& e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } break; default: std::cerr << "Usage: " << cb::io::basename(argv[0]) << " [options] file1-n" << std::endl << std::endl << "\t--format=raw|gdb|lldb\tThe format for the input file" << std::endl << std::endl << "For gdb the expected output would be produced by " "executing: " << std::endl << std::endl << "(gdb) x /24xb c->rcurr" << std::endl << "0x7f43387d7e7a: 0x81 0x0d 0x00 0x00 0x00 0x00 0x00 0x00" << std::endl << "0x7f43387d7e82: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00" << std::endl << "0x7f43387d7e8a: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00" << std::endl << std::endl << "For lldb the expected output would be generated by " "executing: " << std::endl << std::endl << "(lldb) x -c 32 c->rbuf" << std::endl << "0x7f43387d7e7a: 81 0d 00 01 04 00 00 00 00 00 00 06 00 " "00 00 06 ................" << std::endl << "0x7f43387d7e7a: 14 bf f4 26 8a e0 00 00 00 00 00 00 61 " "61 81 0a ................" << std::endl << std::endl; return EXIT_FAILURE; } } if (optind == argc) { std::cerr << "No file specified" << std::endl; return EXIT_FAILURE; } while (optind < argc) { try { cb::byte_buffer buf; std::vector<uint8_t> data; cb::MemoryMappedFile map(argv[optind], cb::MemoryMappedFile::Mode::RDONLY); map.open(); buf = {static_cast<uint8_t*>(map.getRoot()), map.getSize()}; switch (format) { case Format::Raw: break; case Format::Gdb: data = cb::mcbp::gdb::parseDump(buf); buf = {data.data(), data.size()}; break; case Format::Lldb: data = cb::mcbp::lldb::parseDump(buf); buf = {data.data(), data.size()}; break; } cb::mcbp::dumpStream(buf, std::cout); } catch (const std::exception& error) { std::cerr << error.what() << std::endl; return EXIT_FAILURE; } ++optind; } return EXIT_SUCCESS; }
82be31fc3524835f627befe774786637aae24645
469370ad9a81ec746270f54a6433853e517bafde
/input.h
fa59213d1dc084e2a98556a154757033ecde6c1c
[]
no_license
masaedw/landscaper
42431ee6ea952a2476583b838b7ae31e687e6421
7b84f39d16a37de12d20be15e17f199737e1d6a8
refs/heads/master
2016-09-06T00:23:36.120087
2010-02-01T14:52:41
2010-02-01T14:52:41
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
3,666
h
#ifndef _INPUT_H_ #define _INPUT_H_ #include <map> #include "collision.h" namespace space{ //キーボード情報 //キーボードの値は整数に変換される。どういう変換かは使う人が考えること。 class Keyboard { public: typedef std::map<unsigned short,unsigned short> KeyMap; protected: KeyMap keys; public: void clear(){keys.clear();} Keyboard(){clear();} ~Keyboard(){} //セット void pushkey(unsigned short _k) { keys[_k] = _k; } //アンセット void pullkey(unsigned short _k) { KeyMap::iterator it = keys.find(_k); if( it != keys.end() ) keys.erase(it); } //情報をもらう bool ispush(unsigned short _k) const{ if( keys.find(_k) == keys.end() ) return false; return true; } //キーを全部丸ごとプレゼントする const KeyMap& getkeys() const{ return keys;} }; //ジョイスティック情報 //ボタン数は13と仮定。 class Joystick { bool button[13]; int x,y,z; public: void clear(){ x=0;y=0;z=0; for(int i=0;i<16;i++) button[i]=false; } Joystick(){clear();} ~Joystick(){} //セット(unsetの必要なし) void setx(int _k) { x=_k; } void sety(int _k) { y=_k; } void setz(int _k) { z=_k; } //ボタン系セット void pushbutton(unsigned int _b){ if(_b>=13)return; button[_b]=true; } //ボタン系アンセット void pullbutton(unsigned int _b){ if(_b>=13)return; button[_b]=false; } //情報をもらう int getx() const { return x; } int gety() const { return y; } int getz() const { return z; } bool ispush(unsigned int _b) const { if(_b>=13)return false; return button[_b]; } }; //マウス //4ボタン以上とか知らん。 class Mouse { public: struct Button { private: bool ispush; Matrix21<int> pushpos; Matrix21<int> pullpos; public: void clear(){ ispush=false; pushpos = Matrix21<int>(0,0); pullpos = Matrix21<int>(0,0); } Button(){ clear(); } void push(const Matrix21<int>& _pos){ispush=true; pushpos=_pos;} void pull(const Matrix21<int>& _pos){ispush=false;pullpos=_pos;} const Matrix21<int>& getPushpos() const {return pushpos;} const Matrix21<int>& getPullpos() const {return pullpos;} bool isPush() const {return ispush;} std::string output() const{ std::stringstream ss(""); ss << "::" << ispush << ":ps(" << pushpos.x << "," << pushpos.y << "):pl(" << pullpos.x << "," << pullpos.y << ")"; return ss.str(); } }; protected: Button left,right,middle; Matrix21<int> nowpos; public: void clear(){ left.clear(); right.clear(); middle.clear(); nowpos = Matrix21<int>(0,0); } Mouse(){clear();} //セット(アンセット必要なし) void setpos(const Matrix21<int> &_pos){ nowpos=_pos; } //ゲット const Matrix21<int>& getpos() const { return nowpos; } //返すだけ const Button &getleft() const {return left;} const Button &getmiddle() const {return middle;} const Button &getright()const {return right;} Button &setleft() {return left;} Button &setmiddle() {return middle;} Button &setright() { return right;} std::string output() const{ std::stringstream ss(""); ss << "*l" << left.output() << "::m" << middle.output() << "::r" << right.output() << "::p(" << nowpos.x << "," << nowpos.y << ")"; return ss.str(); } }; struct Input { Keyboard keyboard; Mouse mouse; Joystick joystick; void clear(){ keyboard.clear(); mouse.clear(); joystick.clear(); } std::string output() const{ std::stringstream ss(""); ss << "**ms" << mouse.output(); return ss.str(); } }; } #endif
2ccf5828b8559f26a0292a7e1ba3df44cb793dc8
55bfe899250607e99aa6ed20c5d688200ce4225f
/spot_real/Control/Teensy/SpotMiniMini/lib/ros_lib/moveit_msgs/MoveGroupActionGoal.h
bcb0e3ee2eff64549f920d6d8621e436564d2a4b
[ "MIT" ]
permissive
OpenQuadruped/spot_mini_mini
96aef59505721779aa543aab347384d7768a1f3e
c7e4905be176c63fa0e68a09c177b937e916fa60
refs/heads/spot
2022-10-21T04:14:29.882620
2022-10-05T21:33:53
2022-10-05T21:33:53
251,706,548
435
125
MIT
2022-09-02T07:06:56
2020-03-31T19:13:59
C++
UTF-8
C++
false
false
1,428
h
#ifndef _ROS_moveit_msgs_MoveGroupActionGoal_h #define _ROS_moveit_msgs_MoveGroupActionGoal_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" #include "std_msgs/Header.h" #include "actionlib_msgs/GoalID.h" #include "moveit_msgs/MoveGroupGoal.h" namespace moveit_msgs { class MoveGroupActionGoal : public ros::Msg { public: typedef std_msgs::Header _header_type; _header_type header; typedef actionlib_msgs::GoalID _goal_id_type; _goal_id_type goal_id; typedef moveit_msgs::MoveGroupGoal _goal_type; _goal_type goal; MoveGroupActionGoal(): header(), goal_id(), goal() { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; offset += this->header.serialize(outbuffer + offset); offset += this->goal_id.serialize(outbuffer + offset); offset += this->goal.serialize(outbuffer + offset); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; offset += this->header.deserialize(inbuffer + offset); offset += this->goal_id.deserialize(inbuffer + offset); offset += this->goal.deserialize(inbuffer + offset); return offset; } const char * getType(){ return "moveit_msgs/MoveGroupActionGoal"; }; const char * getMD5(){ return "df11ac1a643d87b6e6a6fe5af1823709"; }; }; } #endif
c215bbe245ccb34412185018ca3f5d02da4e0b33
34b22618cc53750a239ee7d3c98314d8e9b19093
/framework/deprecated/core/cofiles/src/xercesc/XMLNode.cpp
dd4c70894a3fcc72010e7bf9a7fccc4302847f08
[]
no_license
ivan-kits/cframework
7beef16da89fb4f9559c0611863d05ac3de25abd
30015ddf1e5adccd138a2988455fe8010d1d9f50
refs/heads/master
2023-06-12T05:09:30.355989
2021-07-04T09:00:00
2021-07-04T09:00:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,369
cpp
#include "cofiles/XML/Xerces/XMLNode.h" #include <xercesc/parsers/XercesDOMParser.hpp> #include <xercesc/dom/DOMNamedNodeMap.hpp> #include <xercesc/dom/DOMNodeList.hpp> #include <xercesc/dom/DOMElement.hpp> #include <xercesc/dom/DOMException.hpp> #include <xercesc/dom/DOMImplementation.hpp> #include "cofiles/Makros.h" #include "cofiles/XML/Xerces/XMLElement.h" #include "cofiles/XML/Xerces/XMLText.h" using namespace CoFiles; XERCES_CPP_NAMESPACE_USE DOMNode* ToDOMNode( void* _pNode ) { DOMNode* pNode = static_cast< DOMNode* >( _pNode ); return pNode; } const DOMNode* ToDOMNode( const void* _pNode ) { const DOMNode* pNode = static_cast< const DOMNode* >( _pNode ); return pNode; } Xerces::XMLNode::XMLNode() : m_pNode( NULL ), m_eNodeType( XML_NODE_TYPE_NONE ) { } void Xerces::XMLNode::SetNodeType( XMLNodeType _eNodeType ) { m_eNodeType = _eNodeType; } XMLNodeType Xerces::XMLNode::GetNodeType() const { return m_eNodeType; } bool Xerces::XMLNode::IsValid() const { return GetXMLNode() != NULL; } bool Xerces::XMLNode::HasChildren() const { if( IsValid() ) { return !ToDOMNode( GetXMLNode() )->getChildNodes()->getLength(); } else { return false; } } XMLNodePtr Xerces::XMLNode::GetFirstChild() const { m_spFirstChild.reset(); if ( ToDOMNode( GetXMLNode() ) != NULL ) { DOMNode *pNode = ToDOMNode( GetXMLNode() )->getFirstChild(); while ( pNode != NULL && !IsValidXMLNode( pNode ) ) { pNode = pNode->getNextSibling(); } if ( pNode != NULL ) { m_spFirstChild = CreateNode( pNode ); } } return m_spFirstChild; } XMLNodePtr Xerces::XMLNode::GetNextSibling() const { m_spNextSibling.reset(); if ( GetXMLNode() == NULL ) { return XMLNodePtr(); } DOMNode *pNode = ToDOMNode( GetXMLNode() )->getNextSibling(); while( pNode != NULL && !IsValidXMLNode( pNode ) ) { pNode = pNode->getNextSibling(); } if ( pNode != NULL ) { m_spNextSibling = CreateNode( pNode ); } return m_spNextSibling; } void Xerces::XMLNode::InsertChildFirst( CoFiles::XMLNode& _clChildNode ) { if ( IsValid() ) { try { ToDOMNode( GetXMLNode() )->insertBefore( ToDOMNode( _clChildNode.GetXMLNode() ), NULL ); } catch ( const DOMException& e ) { CO_WARN( "XMLNode::InsertChildFirst: %s", XMLString::transcode( e.msg ) ); } } } void Xerces::XMLNode::InsertChildBefore( CoFiles::XMLNode& _clChildNode, CoFiles::XMLNode& _clBefore ) { if( IsValid() ) { ToDOMNode( GetXMLNode() )->insertBefore( ToDOMNode( _clChildNode.GetXMLNode() ), ToDOMNode( _clBefore.GetXMLNode() ) ); } } void Xerces::XMLNode::InsertChildAfter( CoFiles::XMLNode& _clChildNode, CoFiles::XMLNode& _clAfter ) { if( IsValid() ) { if( _clAfter.GetXMLNode() != NULL ) { ToDOMNode( GetXMLNode() )->insertBefore( ToDOMNode( _clChildNode.GetXMLNode() ), ToDOMNode( _clAfter.GetXMLNode() )->getNextSibling() ); } else { ToDOMNode( GetXMLNode() )->appendChild( ToDOMNode( _clChildNode.GetXMLNode() ) ); } } } void Xerces::XMLNode::InsertChildLast( CoFiles::XMLNode& _clChildNode ) { if( IsValid() ) { DOMNode* pDOMNode = ToDOMNode( GetXMLNode() ); DOMNode* pChildDOMNode = ToDOMNode( _clChildNode.GetXMLNode() ); if ( pDOMNode != NULL && pChildDOMNode != NULL ) { try { pDOMNode->appendChild( pChildDOMNode ); } catch ( const DOMException& e ) { CO_WARN( "XMLNode::InsertChildLast: %s", XMLString::transcode( e.msg ) ); } } } } bool Xerces::XMLNode::IsDocument() const { return m_eNodeType == DOCUMENT_NODE; } bool Xerces::XMLNode::IsElement() const { return m_eNodeType == ELEMENT_NODE; } bool Xerces::XMLNode::IsText() const { return m_eNodeType == TEXT_NODE; } const void* Xerces::XMLNode::GetXMLNode() const { return m_pNode; } void* Xerces::XMLNode::GetXMLNode() { return m_pNode; } void Xerces::XMLNode::SetXMLNode( void* pNode ) { m_pNode = ToDOMNode( pNode ); } XMLNodePtr Xerces::XMLNode::CreateNode( DOMNode* _pNode ) { if ( _pNode == NULL ) { return XMLNodePtr(); } CoFiles::XMLNodePtr spNewNode; if ( _pNode->getNodeType() == DOMNode::ELEMENT_NODE ) { XMLElement* pElement = new Xerces::XMLElement(); spNewNode = CoFiles::XMLNodePtr( pElement ); } else if ( _pNode->getNodeType() == DOMNode::TEXT_NODE ) { XMLText* pText = new Xerces::XMLText(); spNewNode = CoFiles::XMLNodePtr( pText ); } if ( spNewNode!= NULL ) { spNewNode->SetXMLNode( _pNode ); } return spNewNode; } bool Xerces::XMLNode::IsValidXMLNode( DOMNode* pNode ) { if ( pNode == NULL ) { return false; } if ( pNode->getNodeType() == DOMNode::COMMENT_NODE ) { return false; } else if ( pNode->getNodeType() == DOMNode::NOTATION_NODE ) { return false; } else if ( pNode->getNodeType() == DOMNode::TEXT_NODE ) { XMLText clTextNode; clTextNode.SetXMLNode( pNode ); String sText = clTextNode.GetText(); if( sText == "" ) { return false; } } return true; }
e1b1240b296621b5523630b31d65b88d88af048e
d8f1638d63e611ed1619755ca26de4ea96bf1d7b
/PC_Interface/Interface/Interface.ino
4fdf5155133640117e627d876a20a1401953a9b5
[]
no_license
schmitfe/Stimulator_FPGA
27b3e14bdb0330579ac6c8e2bada5dd41820bf74
1016d487b89ac5f1de4d3648e18f312f3439ba7e
refs/heads/master
2023-02-11T19:23:52.376766
2019-12-31T15:10:30
2019-12-31T15:10:30
199,415,384
0
0
null
null
null
null
UTF-8
C++
false
false
14,776
ino
/* Copyright (c) 2019 Stefan Kremser This software is licensed under the MIT License. See the license file for details. Source: github.com/spacehuhn/SimpleCLI */ /* Adapted by Felix Schmitt to create Interface for Stimulator. PLEASE NOTE: 115200 is the baud rate and Newline is enabled in the serial monitor */ // Inlcude Library Command Line #include <SimpleCLI.h> #include <SPI.h> #include "SdFat.h" #include "sdios.h" //#include "Pins.h" #include "JsonStreamingParser.h" #include "JsonListener.h" #include "Parser.h" #define Channels 2 //Defines number of Channels, not tested with more channels possible errors at the write functin //for channel adress, trig and // Create CLI Object SimpleCLI cli; // Commands Command cmdLs; Command cmdRm; Command cmdStore; Command cmdReset; Command cmdWF; Command cmdtrig; Command cmdHelp; Command cmdDesc; Command cmdAmpli; Command cmdInterIv; Command cmdInterPer; Command cmdWave; Command cmdDoutDebug; // set up variables using the SD utility library functions: // File system object. SdFat sd; // Directory file. SdFile root; // Use for file creation in folders. SdFile file; //----------Pins---------------// const unsigned int Ptrig[] = {49, 51, 53}; //Ptrig all, ch0 -x const unsigned int P_RESET = 68; const unsigned int P_RESET_CH = 69; const unsigned int PinsInterPeriod[] = {61, 60, 59, 58, 57, 56, 55, 54};//{54, 55, 56, 57, 58, 59, 60, 61}; const unsigned int PinsInterInterval[] = {10, 9, 8, 7, 6, 5, 4, 3}; //{3, 4, 5, 6, 7,8,9,10}; const unsigned int PinsAmplitude[] = {21, 20, 19, 18}; const unsigned int PWrite = 63; const unsigned int PWrite2 = 36; const unsigned int PWrite3 = 37; const unsigned int P_EnWrite = 62; const unsigned int PWaveAddr[] = {64}; const unsigned int PWriteConfig = {65}; const unsigned int PChanAdress[] = {66}; const unsigned int PChanAdress2[] = {38}; const unsigned int PChanAdress3[] = {39}; const unsigned int PDout[] = {25, 26, 27, 28, 14, 15, 29, 11}; // Has to be on same port of SAM, Arduino ports are not ordered! const unsigned int chipSelect = 52; //SD-Card //---------------buffers---------------------// char bufferJson[40]; //-------struct to store data of channels----// typedef struct { int amplitude; int iinterval; int iperiod; int waveadress; } SChannelSet; SChannelSet *ChannelSet = NULL; void setup() { //--------setup of pins---------------// int ii; for ( ii = 0; ii < sizeof(Ptrig) / sizeof(Ptrig[0]); ii = ii + 1 ) { pinMode(Ptrig[ii], OUTPUT); digitalWrite(Ptrig[ii], LOW); } for ( ii = 0; ii < sizeof(PinsInterPeriod) / sizeof(PinsInterPeriod[0]); ii = ii + 1 ) { pinMode(PinsInterPeriod[ii], OUTPUT); digitalWrite(PinsInterPeriod[ii], LOW); } for ( ii = 0; ii < sizeof(PinsInterInterval) / sizeof(PinsInterInterval[0]); ii = ii + 1 ) { pinMode(PinsInterInterval[ii], OUTPUT); digitalWrite(PinsInterInterval[ii], LOW); } for ( ii = 0; ii < sizeof(PWaveAddr) / sizeof(PWaveAddr[0]); ii = ii + 1 ) { pinMode(PWaveAddr[ii], OUTPUT); digitalWrite(PWaveAddr[ii], LOW); } for ( ii = 0; ii < sizeof(PinsAmplitude) / sizeof(PinsAmplitude[0]); ii = ii + 1 ) { pinMode(PinsAmplitude[ii], OUTPUT); digitalWrite(PinsAmplitude[ii], LOW); } for ( ii = 0; ii < sizeof(PChanAdress) / sizeof(PChanAdress[0]); ii = ii + 1 ) { pinMode(PChanAdress[ii], OUTPUT); digitalWrite(PChanAdress[ii], LOW); pinMode(PChanAdress2[ii], OUTPUT); digitalWrite(PChanAdress2[ii], LOW); pinMode(PChanAdress3[ii], OUTPUT); digitalWrite(PChanAdress3[ii], LOW); } for ( ii = 0; ii < sizeof(PDout) / sizeof(PDout[0]); ii = ii + 1 ) { pinMode(PDout[ii], OUTPUT); digitalWrite(PDout[ii], LOW); } pinMode(P_RESET, OUTPUT); digitalWrite(P_RESET, LOW); pinMode(P_RESET_CH, OUTPUT); digitalWrite(P_RESET_CH, LOW); pinMode(PWrite, OUTPUT); digitalWrite(PWrite, LOW); pinMode(PWrite2, OUTPUT); digitalWrite(PWrite, LOW); pinMode(PWrite3, OUTPUT); digitalWrite(PWrite, LOW); pinMode(P_EnWrite, OUTPUT); digitalWrite(P_EnWrite, LOW); pinMode(PWriteConfig, OUTPUT); digitalWrite(PWriteConfig, LOW); //--------setup of interface---------------// Serial.begin(115200); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } Serial.println("\nInitializing SD card..."); // we'll use the initialization code from the utility libraries // since we're just testing if the card is working! // Initialize at the highest speed supported by the board that is // not over 50 MHz. Try a lower speed if SPI errors occur. if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { //should be 50 sd.initErrorHalt(); } //--------setup of channel settings---------------// ChannelSet = (SChannelSet*) malloc(sizeof * ChannelSet * (Channels + 1)); //Channel zero contains defaultvalues ChannelSet[0].amplitude = 1; ChannelSet[0].iinterval = 0; ChannelSet[0].iperiod = 0; ChannelSet[0].waveadress = 0; for ( ii = 1; ii < Channels + 1 ; ii = ii + 1 ) { ChannelSet[ii].amplitude = ChannelSet[0].amplitude; ChannelSet[ii].iinterval = ChannelSet[0].iinterval; ChannelSet[ii].iperiod = ChannelSet[0].iperiod; ChannelSet[ii].waveadress = ChannelSet[0].waveadress; } //--------creation of commands---------------// cmdLs = cli.addCmd("ls"); cmdRm = cli.addCmd("rm"); cmdRm.addPosArg("file"); cmdStore = cli.addCmd("store"); cmdStore.addPosArg("file"); cmdReset = cli.addCmd("reset"); cmdReset.addPosArg("ID"); cmdWF = cli.addCmd("WF"); cmdWF.addPosArg("file"); cmdWF.addPosArg("ID"); cmdtrig = cli.addCmd("trig"); cmdtrig.addPosArg("ID"); cmdDesc = cli.addCmd("descrip"); cmdDesc.addPosArg("file"); cmdAmpli = cli.addCmd("amp"); cmdAmpli.addPosArg("ID"); cmdAmpli.addPosArg("value"); cmdInterIv = cli.addCmd("iniv"); cmdInterIv.addPosArg("ID"); cmdInterIv.addPosArg("value"); cmdInterPer = cli.addCmd("inper"); cmdInterPer.addPosArg("ID"); cmdInterPer.addPosArg("value"); cmdWave = cli.addCmd("wave"); cmdWave.addPosArg("ID"); cmdWave.addPosArg("value"); cmdHelp = cli.addCommand("help"); cmdDoutDebug=cli.addCmd("ddeb"); //debuggig command cmdDoutDebug.addPosArg("value"); Serial.println("CLI: type help for commandlist"); } void loop() { //--------CLI loop---------------// if (Serial.available()) { String input = Serial.readStringUntil('\n'); if (input.length() > 0) { // Serial.print("# "); cli.parse(input); } } if (cli.available()) { Command c = cli.getCmd(); int argNum = c.countArgs(); /* Serial.print("> "); // Serial.print(c.getName()); // Serial.print(' '); for (int i = 0; i < argNum; ++i) { Argument arg = c.getArgument(i); // if(arg.isSet()) { Serial.print(arg.toString()); Serial.print(' '); } Serial.println(); */ //--------if input available find corresponding command---------------// if (c == cmdLs) { listFolder(); } else if (c == cmdRm) { RemoveDir (c.getArgument(0)); } else if (c == cmdStore) { SaveFile(c.getArgument(0)); } else if (c == cmdDesc) { description(c.getArgument(0)); } else if (c == cmdAmpli) { setAmplitude(c.getArgument(0), c.getArgument(1)); } else if (c == cmdInterIv) { setInterInterval(c.getArgument(0), c.getArgument(1)); } else if (c == cmdInterPer) { setInterPeriod(c.getArgument(0), c.getArgument(1)); } else if (c == cmdWave) { setWaveadress(c.getArgument(0), c.getArgument(1)); } else if (c == cmdReset) { reset(c.getArgument(0)); } else if (c == cmdWF) { loadWaveform(c.getArgument(0), c.getArgument(1)); } else if (c == cmdtrig) { Argument str = c.getArgument(0); trigger(str.getValue().toInt()); } else if (c == cmdHelp) { Serial.println("Help:"); Serial.println(cli.toString()); } else if(c == cmdDoutDebug){ Serial.println(c.getArgument(0).getValue()); WriteDoutDebug(c.getArgument(0)); } } if (cli.errored()) { CommandError cmdError = cli.getError(); Serial.print("ERROR: "); Serial.println(cmdError.toString()); if (cmdError.hasCommand()) { Serial.print("Did you mean \""); Serial.print(cmdError.getCommand().toString()); Serial.println("\"?"); } } } //--------functions to call in loop---------------// void storeChannel(Argument id) { unsigned long curTime; digitalWrite(PWriteConfig, LOW); curTime=micros(); Channeladress(id.getValue().toInt()); writePinArray(ChannelSet[id.getValue().toInt()].amplitude, PinsAmplitude, sizeof(PinsAmplitude) / sizeof(PinsAmplitude[0])); writePinArray(ChannelSet[id.getValue().toInt()].iperiod, PinsInterPeriod, sizeof(PinsInterPeriod) / sizeof(PinsInterPeriod[0])); writePinArray(ChannelSet[id.getValue().toInt()].iinterval, PinsInterInterval, sizeof(PinsInterInterval) / sizeof(PinsInterInterval[0])); writePinArray( ChannelSet[id.getValue().toInt()].waveadress, PWaveAddr, sizeof(PWaveAddr) / sizeof(PWaveAddr[0])); while(micros()-curTime <2); digitalWrite(PWriteConfig, HIGH); } void writePinArray(int value, const unsigned int *Pins, int NPins) { int ii; for(ii = 0; ii < NPins ; ii = ii + 1 ) { if( bitRead(value,ii)==1){ digitalWrite(Pins[NPins-1-ii],HIGH); } else{ digitalWrite(Pins[NPins-1-ii],LOW); } } } void setAmplitude(Argument id, Argument value) { ChannelSet[id.getValue().toInt()].amplitude = value.getValue().toInt(); storeChannel(id); } void setInterInterval(Argument id, Argument value) { ChannelSet[id.getValue().toInt()].iinterval = value.getValue().toInt(); storeChannel(id); } void setWaveadress(Argument id, Argument value) { ChannelSet[id.getValue().toInt()].waveadress = value.getValue().toInt(); storeChannel(id); } void setInterPeriod(Argument id, Argument value) { ChannelSet[id.getValue().toInt()].iperiod = value.getValue().toInt(); storeChannel(id); } void loadWaveform(Argument pathStr, Argument id) { bool WriteWFs = true; //Let parser write to FPGA String Description = ""; //reset(id); JsonStreamingParser parser; Listener listener(&WriteWFs, &Description, PWrite, PWrite2, PWrite3, PWriteConfig, PWaveAddr, 2); //bad way of introducing additional parameters parser.setListener(&listener); File myFile; if (!sd.chdir("/")) { Serial.println("Error: opening root!"); } sd.chdir("WF"); char path[12]; pathStr.getValue().toCharArray(path, 12); myFile = sd.open(path, FILE_READ); Channeladress(id.getValue().toInt()); digitalWrite(P_EnWrite, HIGH); unsigned long curTime; curTime = micros(); while (micros() - curTime < 500); while (myFile.available()) { parser.parse(myFile.read()); } myFile.close(); digitalWrite(P_EnWrite, LOW); Channeladress(0); WriteWFs = false; } void description(Argument pathStr) { bool WriteWFs = false; String Description = ""; JsonStreamingParser parser; Listener listener(&WriteWFs, &Description,PWrite, PWrite2, PWrite3, PWriteConfig, PWaveAddr, 2); //bad way of introducing additional parameters parser.setListener(&listener); File myFile; if (!sd.chdir("/")) { Serial.println("Error: opening root!"); } sd.chdir("WF"); char path[12]; pathStr.getValue().toCharArray(path, 12); myFile = sd.open(path, FILE_READ); WriteWFs = false; //Let parser write to FPGA while (myFile.available()) { parser.parse(myFile.read()); } myFile.close(); Serial.print("Description of " + pathStr.getValue() + " : "); Serial.println(Description); Description = ""; } void listFolder() { if (!sd.chdir("/")) { Serial.println("Error: opening root!"); } if (!sd.chdir("WF")) { sd.mkdir("WF"); sd.chdir("WF"); } sd.ls("/WF", LS_R); } void trigger(int id) { unsigned long curTime; digitalWrite(Ptrig[id], HIGH); curTime = micros(); while (micros() - curTime < 20); digitalWrite(Ptrig[id], LOW); } void reset(Argument id) { int ii = 0; unsigned long curTime; if (id.getValue().toInt() == 0) { digitalWrite(P_RESET, HIGH); curTime = micros(); while (micros() - curTime < 2); digitalWrite(P_RESET, LOW); for ( ii = 1; ii < Channels + 1 ; ii = ii + 1 ) { ChannelSet[ii].amplitude = ChannelSet[0].amplitude; ChannelSet[ii].iinterval = ChannelSet[0].iinterval; ChannelSet[ii].iperiod = ChannelSet[0].iperiod; ChannelSet[ii].waveadress = ChannelSet[0].waveadress; } } else { digitalWrite(P_RESET_CH, HIGH); curTime = micros(); ChannelSet[id.getValue().toInt()].amplitude = ChannelSet[0].amplitude; ChannelSet[id.getValue().toInt()].iinterval = ChannelSet[0].iinterval; ChannelSet[id.getValue().toInt()].iperiod = ChannelSet[0].iperiod; ChannelSet[id.getValue().toInt()].waveadress = ChannelSet[0].waveadress; while (micros() - curTime < 2); storeChannel(id); digitalWrite(P_RESET_CH, LOW); storeChannel(id); } } void Channeladress(int id) { int adress=0; if (id == 0) { digitalWrite(*PChanAdress, LOW); digitalWrite(*PChanAdress2, LOW); digitalWrite(*PChanAdress3, LOW); } else { writePinArray(id-1, PChanAdress, sizeof(PChanAdress) / sizeof(PChanAdress[0])); writePinArray(id-1, PChanAdress2, sizeof(PChanAdress2) / sizeof(PChanAdress2[0])); writePinArray(id-1, PChanAdress3, sizeof(PChanAdress3) / sizeof(PChanAdress3[0])); } } void RemoveDir (Argument str) { char path[12]; str.getValue().toCharArray(path, 12); if (!sd.chdir("/")) { Serial.println("Error: opening root!"); } sd.chdir("WF"); sd.remove(path); } void SaveFile (Argument str) { File myFile; char path[12]; uint8_t incomingByte; str.getValue().toCharArray(path, 12); if (!sd.chdir("/")) { Serial.println("Error: opening root!"); } sd.chdir("WF"); sd.remove(path); myFile = sd.open(path, FILE_WRITE); Serial.println("Please send File."); while (Serial.available() == 0); // read the incoming byte: incomingByte = Serial.read(); while (incomingByte != 10) { myFile.write(incomingByte); while (Serial.available() == 0); incomingByte = Serial.read(); } myFile.close(); Serial.println("File saved!"); } //Debug function to find right order of pins void WriteDoutDebug(Argument value) { unsigned long curTime; PIOD->PIO_SODR= value.getValue().toInt(); PIOD->PIO_CODR=~value.getValue().toInt()&0x00FF; digitalWrite(PWrite, LOW); curTime=micros(); while(micros()-curTime <20); digitalWrite(PWrite, HIGH); curTime=micros(); while(micros()-curTime <20); }
96ac4e9785d6d7dac6e39b5f2018e8907d4ae455
e102753a5ab7eedd58d04c26254a8e29859f9e98
/Toolkit/Synthetic Data Analysis/UMAP/epp/cpp/client.h
da0bf3593bd54e01f3dd4c0b796a40d32c813e33
[ "Apache-2.0" ]
permissive
ZPGuiGroupWhu/ClusteringDirectionCentrality
ec166456938602921574ad24d7445804c2226961
084a18fc40cc19dee2aa91c757009d4abb2e86f9
refs/heads/master
2023-04-13T00:07:42.437629
2023-03-11T11:48:27
2023-03-11T11:48:27
467,575,519
72
7
null
2022-10-26T12:10:05
2022-03-08T15:46:14
MATLAB
UTF-8
C++
false
false
20,265
h
#ifndef _EPP_CLIENT_H #define _EPP_CLIENT_H 1 #include <ios> #include <sstream> #include <algorithm> #include <vector> #include <queue> #include <chrono> #include <thread> #include <mutex> #include <condition_variable> #include <math.h> namespace EPP { typedef uint32_t epp_word; typedef unsigned char epp_hash[32]; /** * These classes define the client interface to EPP and the necessary data structures * */ class Sample { public: std::vector<bool> subset; const unsigned long int events; const unsigned short int measurements; Sample(unsigned short int measurements, unsigned long int events, std::vector<bool> subset) noexcept : measurements(measurements), events(events), subset(subset){}; Sample(unsigned short int measurements, unsigned long int events) noexcept : measurements(measurements), events(events), subset(events) { std::fill(subset.begin(), subset.end(), true); }; private: // these are virtual because our friend stream won't know which variant it will be virtual epp_word get_word(unsigned short int measurement, unsigned long event) const noexcept { return (epp_word)0; } virtual void put_word(unsigned short measurement, long event, epp_word data) noexcept {}; friend class SampleStream; }; template <typename _float> class DefaultSample : public Sample { public: inline double operator()(unsigned long int event, unsigned short int measurement) const noexcept { return (double)data[measurements * event + measurement]; }; DefaultSample(const unsigned short int measurements, const unsigned long int events, const _float *const data) noexcept : Sample(measurements, events), data(data) { for (long int event = 0; event < events; event++) for (unsigned short int measurement = 0; measurement < measurements; measurement++) if (data[measurements * event + measurement] < 0 || data[measurements * event + measurement] > 1) subset[event] = false; }; DefaultSample(const unsigned short int measurements, const unsigned long int events, const _float *const data, std::vector<bool> subset) noexcept : Sample(measurements, events, subset), data(data){}; protected: epp_word get_word(unsigned short int measurement, unsigned long int event) const noexcept { float f = data[measurements * event + measurement]; return *(epp_word *)&f; }; void put_word(unsigned short int measurement, unsigned long int event, epp_word value) noexcept { float f = *(float *)&value; data[measurements * event + measurement] = (_float)f; }; private: const _float *const data; }; template <typename _float> class TransposeSample : public Sample { public: inline double operator()(unsigned long int event, unsigned short int measurement) const noexcept { return (double)data[events * measurement + event]; }; TransposeSample(const unsigned short int measurements, const unsigned long int events, const _float *const data) noexcept : Sample(measurements, events), data(data) { for (unsigned long int event = 0; event < events; event++) for (unsigned short int measurement = 0; measurement < measurements; measurement++) if (data[events * measurement + event] < 0 || data[events * measurement + event] > 1) subset[event] = false; }; TransposeSample(const unsigned short int measurements, const unsigned long int events, const _float *const data, std::vector<bool> subset) noexcept : Sample(measurements, events, subset), data(data){}; protected: epp_word get_word(unsigned short int measurement, unsigned long int event) const noexcept { float f = data[events * measurement + event]; return *(epp_word *)&f; }; void put_word(unsigned short int measurement, unsigned long int event, epp_word value) noexcept { float f = *(float *)&value; data[events * measurement + event] = (_float)f; }; private: const _float *const data; }; template <typename _float> class PointerSample : public Sample { public: inline double operator()(unsigned long int event, unsigned short int measurement) const noexcept { return (double)data[measurement][event]; }; PointerSample(const unsigned short int measurements, const unsigned long int events, const _float *const *const data) noexcept : Sample(measurements, events), data(data) { for (unsigned long int event = 0; event < events; event++) for (unsigned short int measurement = 0; measurement < measurements; measurement++) if (data[measurement][event] < 0 || data[measurement][event] > 1) subset[event] = false; }; PointerSample(const unsigned short int measurements, const unsigned long int events, const _float *const *const data, std::vector<bool> subset) noexcept : Sample(measurements, events, subset), data(data){}; protected: epp_word get_word(unsigned short int measurement, unsigned long int event) const noexcept { float f = data[measurement][event]; return *(epp_word *)&f; }; void put_word(unsigned short int measurement, unsigned long int event, epp_word value) noexcept { float f = *(float *)&value; data[measurement][event] = (_float)f; }; private: const _float *const *const data; }; class Subset : public std::vector<bool> { public: explicit Subset(Sample &sample); Sample *sample; private: friend class SubsetStream; }; struct Parameters { // N = 256 gives points and features a precision of roughly two significant figures static const unsigned short N = 1 << 8; // resolution of points and boundaries // optimized when there are lots of small factors double W = 1 / (double)N; // standard deviation of kernel, // this is the highest achievable resolution, in practice a higher // value might be used for application reasons or just performance double sigma = 5; // controls the density threshold for starting a new cluster enum Goal { // which objective function best_separation, // lowest edge weight best_balance // edge weight biased towards more even splits } goal = best_balance; int finalists = 1; // remember this many of the best candidates struct KLD // KLD threshold for informative cases { double Normal2D = .16; // is this population worth splitting? double Normal1D = .16; // is the measurement just normal double Exponential1D = .16; // is this an exponential tail (CyToF) KLD( double Normal2D = .16, double Normal1D = .16, double Exponential1D = .16) noexcept : Normal2D(Normal2D), Normal1D(Normal1D), Exponential1D(Exponential1D){}; }; const static KLD KLD_Default; KLD kld = KLD_Default; std::vector<bool> censor; // omit measurements from consideration // algorithm tweaks int max_clusters = 12; // most clusters the graph logic should handle bool shuffle = false; // shuffle the boundary points for uniformity bool deterministic = false; // do it with a fixed seed for testing bool supress_in_out = false; // don't bother with in and out sets bool kld_only = false; Parameters( Goal goal = best_balance, KLD kld = {.16, .16, .16}, double sigma = 5, double W = 1 / (double)N) : goal(goal), kld(kld), W(W), sigma(sigma), censor(0), finalists(1), max_clusters(12), shuffle(false), deterministic(false), supress_in_out(false){}; }; const Parameters Default; struct Point { short i, j; inline double x() const noexcept { return (double)i / (double)Parameters::N; }; inline double y() const noexcept { return (double)j / (double)Parameters::N; }; inline bool operator==(const Point &other) { return i == other.i && j == other.j; } inline bool operator!=(const Point &other) { return !(*this == other); } Point(short i, short j) noexcept : i(i), j(j){}; }; enum Status { EPP_success, EPP_no_qualified, EPP_no_cluster, EPP_not_interesting, EPP_error }; struct Candidate { std::vector<Point> separatrix; std::vector<bool> in, out; double score, edge_weight, balance_factor; unsigned long int in_events, out_events; unsigned int pass, clusters, graphs; unsigned short int X, Y; enum Status outcome; private: void close_clockwise( std::vector<Point> &polygon) { Point tail = polygon.front(); Point head = polygon.back(); int edge; if (head.j == 0) edge = 0; if (head.i == 0) edge = 1; if (head.j == Parameters::N) edge = 2; if (head.i == Parameters::N) edge = 3; while (!(head == tail)) { switch (edge++ & 3) { case 0: if (tail.j == 0 && tail.i < head.i) head = tail; else head = Point(Parameters::N, 0); break; case 1: if (tail.i == 0 && tail.j > head.j) head = tail; else head = Point(0, 0); break; case 2: if (tail.j == Parameters::N && tail.i > head.i) head = tail; else head = Point(0, Parameters::N); break; case 3: if (tail.i == Parameters::N && tail.j < head.j) head = tail; else head = Point(Parameters::N, Parameters::N); break; } polygon.push_back(head); } } // Ramer–Douglas–Peucker algorithm void simplify( const double tolerance, std::vector<Point> &simplified, const unsigned short int lo, const unsigned short int hi) { if (lo + 1 == hi) return; double x = separatrix[hi].i - separatrix[lo].i; double y = separatrix[hi].j - separatrix[lo].j; double theta = atan2(y, x); double c = cos(theta); double s = sin(theta); double max = 0; unsigned short int keep; for (int mid = lo + 1; mid < hi; mid++) { // distance of mid from the line from lo to hi double d = abs(c * (separatrix[mid].j - separatrix[lo].j) - s * (separatrix[mid].i - separatrix[lo].i)); if (d > max) { keep = mid; max = d; } } if (max > tolerance) // significant, so something we must keep in here { simplify(tolerance, simplified, lo, keep); simplified.push_back(separatrix[keep]); simplify(tolerance, simplified, keep, hi); } // but if not, we don't need any of the points between lo and hi } public: bool operator<(const Candidate &other) const noexcept { if (score < other.score) return true; if (score > other.score) return false; return outcome < other.outcome; } std::vector<Point> simplify( const double tolerance) { std::vector<Point> polygon; polygon.reserve(separatrix.size()); polygon.push_back(separatrix[0]); simplify(tolerance * Parameters::N, polygon, 0, separatrix.size() - 1); polygon.push_back(separatrix[separatrix.size() - 1]); return polygon; } std::vector<Point> in_polygon() { std::vector<Point> polygon; polygon.reserve(separatrix.size() + 4); for (auto point = separatrix.begin(); point != separatrix.end(); point++) polygon.push_back(*point); close_clockwise(polygon); return polygon; } std::vector<Point> in_polygon( double tolerance) { std::vector<Point> polygon; polygon.reserve(separatrix.size() + 4); polygon.push_back(separatrix[0]); simplify(tolerance * Parameters::N, polygon, 0, separatrix.size() - 1); polygon.push_back(separatrix[separatrix.size() - 1]); close_clockwise(polygon); return polygon; } std::vector<Point> out_polygon() { std::vector<Point> polygon; polygon.reserve(separatrix.size() + 4); for (auto point = separatrix.rbegin(); point != separatrix.rend(); point++) polygon.push_back(*point); close_clockwise(polygon); return polygon; } std::vector<Point> out_polygon( double tolerance) { std::vector<Point> polygon; polygon.reserve(separatrix.size() + 4); polygon.push_back(separatrix[0]); simplify(tolerance * Parameters::N, polygon, 0, separatrix.size() - 1); polygon.push_back(separatrix[separatrix.size() - 1]); std::reverse(polygon.begin(), polygon.end()); close_clockwise(polygon); return polygon; } Candidate( unsigned short int X, unsigned short int Y) : X(X < Y ? X : Y), Y(X < Y ? Y : X), outcome(Status::EPP_error), score(std::numeric_limits<double>::infinity()), pass(0), clusters(0), graphs(0){}; }; struct Result { std::vector<Candidate> candidates; std::vector<unsigned short int> qualified; std::chrono::milliseconds milliseconds; int projections, passes, clusters, graphs; Candidate winner() const noexcept { return candidates[0]; } enum Status outcome() const noexcept { return winner().outcome; }; protected: std::chrono::time_point<std::chrono::steady_clock> begin, end; friend class MATLAB_Pursuer; }; class Request { static std::condition_variable_any completed; volatile unsigned int outstanding = 0; void finish () { --outstanding; } bool finished () { return outstanding == 0; }; void wait () { while (outstanding > 0) ; }; Result *result () { return nullptr; } }; template <class ClientSample> class Pursuer { public: void start( const ClientSample sample, const Parameters parameters) noexcept; void start( const ClientSample sample) noexcept; bool finished() noexcept; void wait() noexcept; std::shared_ptr<Result> result() noexcept; std::shared_ptr<Result> pursue( const ClientSample sample, const Parameters parameters) noexcept; std::shared_ptr<Result> pursue( const ClientSample sample) noexcept; protected: Pursuer() noexcept = default; ~Pursuer() = default; }; typedef TransposeSample<float> MATLAB_Sample; class MATLAB_Pursuer : public Pursuer<MATLAB_Sample> { int threads; std::thread *workers; public: int getThreads() const noexcept {return threads;} void start( const MATLAB_Sample sample, const Parameters parameters) noexcept; void start( const MATLAB_Sample sample) noexcept; void start( const unsigned short int measurements, const unsigned long int events, const float *const data, std::vector<bool> &subset) noexcept; void start( const unsigned short int measurements, const unsigned long int events, const float *const data) noexcept; bool finished() noexcept; void wait() noexcept; std::shared_ptr<Result> result() noexcept; std::shared_ptr<Result> pursue( const MATLAB_Sample sample, const Parameters parameters) noexcept; std::shared_ptr<Result> pursue( const MATLAB_Sample sample) noexcept; std::shared_ptr<Result> pursue( const unsigned short int measurements, const unsigned long int events, const float *const data, std::vector<bool> &subset) noexcept; std::shared_ptr<Result> pursue( const unsigned short int measurements, const unsigned long int events, const float *const data) noexcept; MATLAB_Pursuer() noexcept; MATLAB_Pursuer(int threads) noexcept; ~MATLAB_Pursuer(); }; /** * utility classes for serializing sample and subset as streams */ class SampleStream : public std::iostream { protected: class sample_buffer : public std::streambuf { public: explicit sample_buffer(Sample &sample); virtual ~sample_buffer(); protected: virtual std::streambuf::int_type underflow(); virtual std::streambuf::int_type overflow(std::streambuf::int_type value); virtual std::streambuf::int_type sync(); private: Sample *sample; epp_word *buffer; long next_event; }; public: explicit SampleStream(Sample &sample); }; class SubsetStream : public std::iostream { protected: class subset_buffer : public std::streambuf { public: explicit subset_buffer(Subset &subset); virtual ~subset_buffer(); virtual std::streambuf::int_type underflow(); virtual std::streambuf::int_type overflow(std::streambuf::int_type value); virtual std::streambuf::int_type sync(); private: Subset *subset; uint8_t *buffer; long next_event; friend class SubsetStream; }; public: explicit SubsetStream(Subset &subset); }; } #endif /* _EPP_CLIENT_H */
346a7a2af702300a5cc4ee8a17dd3e122abdbaae
4d539b4c78d9c2af2ddac3efc71190fec0c7acf6
/lab_hash/schashtable.cpp
f0ef13dff737af53d99c261ceefd7ed33dcd7efb
[]
no_license
yuansun97/Data-Structures-cpp
722d473683bad6cf78ff8bf12d3381dbeb201caa
5449da0fa8cfba7496d9ec5162e8c1ff5adf904f
refs/heads/master
2020-12-04T08:42:11.417987
2020-01-04T02:49:09
2020-01-04T02:49:09
231,698,469
0
0
null
null
null
null
UTF-8
C++
false
false
4,576
cpp
/** * @file schashtable.cpp * Implementation of the SCHashTable class. */ #include "schashtable.h" #include <iostream> template <class K, class V> SCHashTable<K, V>::SCHashTable(size_t tsize) { if (tsize <= 0) tsize = 17; size = findPrime(tsize); table = new std::list<std::pair<K, V>>[size]; elems = 0; } template <class K, class V> SCHashTable<K, V>::~SCHashTable() { if (table != NULL) { delete[] table; table = NULL; } } template <class K, class V> SCHashTable<K, V> const& SCHashTable<K, V>:: operator=(SCHashTable<K, V> const& rhs) { if (this != &rhs) { delete[] table; table = new std::list<std::pair<K, V>>[rhs.size]; for (size_t i = 0; i < rhs.size; i++) table[i] = rhs.table[i]; size = rhs.size; elems = rhs.elems; } return *this; } template <class K, class V> SCHashTable<K, V>::SCHashTable(SCHashTable<K, V> const& other) { table = new std::list<std::pair<K, V>>[other.size]; for (size_t i = 0; i < other.size; i++) table[i] = other.table[i]; size = other.size; elems = other.elems; } template <class K, class V> void SCHashTable<K, V>::insert(K const& key, V const& value) { /** * @todo Implement this function. * */ // Always remove the given key first, // regardless whether the key exists or not. remove(key); unsigned idx = hashes::hash(key, size); table[idx].push_front(std::pair<K, V>(key, value)); // std::cout << "## Test ## {" << table[idx].front().first // << ", " << table[idx].front().second // << "}" << " pushed!" << std::endl; elems++; if (shouldResize()) resizeTable(); } template <class K, class V> void SCHashTable<K, V>::remove(K const& key) { /** * @todo Implement this function. * * Please read the note in the lab spec about list iterators and the * erase() function on std::list! */ typename std::list<std::pair<K, V>>::iterator it; unsigned idx = hashes::hash(key, size); for (it = table[idx].begin(); it != table[idx].end(); it++) { if (it->first == key) { table[idx].erase(it); elems--; break; } } } template <class K, class V> V SCHashTable<K, V>::find(K const& key) const { /** * @todo: Implement this function. */ typename std::list<std::pair<K, V>>::iterator it; unsigned idx = hashes::hash(key, size); for (it = table[idx].begin(); it != table[idx].end(); it++) { if (it->first == key) { return it->second; } } return V(); } template <class K, class V> V& SCHashTable<K, V>::operator[](K const& key) { size_t idx = hashes::hash(key, size); typename std::list<std::pair<K, V>>::iterator it; for (it = table[idx].begin(); it != table[idx].end(); it++) { if (it->first == key) return it->second; } // was not found, insert a default-constructed version and return it ++elems; if (shouldResize()) resizeTable(); idx = hashes::hash(key, size); std::pair<K, V> p(key, V()); table[idx].push_front(p); return table[idx].front().second; } template <class K, class V> bool SCHashTable<K, V>::keyExists(K const& key) const { size_t idx = hashes::hash(key, size); typename std::list<std::pair<K, V>>::iterator it; for (it = table[idx].begin(); it != table[idx].end(); it++) { if (it->first == key) return true; } return false; } template <class K, class V> void SCHashTable<K, V>::clear() { delete[] table; table = new std::list<std::pair<K, V>>[17]; size = 17; elems = 0; } template <class K, class V> void SCHashTable<K, V>::resizeTable() { /** * @todo Implement this function. * * Please read the note in the spec about list iterators! * The size of the table should be the closest prime to size * 2. * * @hint Use findPrime()! */ typename std::list<std::pair<K, V>>::iterator it; unsigned newSize = findPrime(size * 2); std::list<std::pair<K, V>> * newTable = new std::list<std::pair<K, V>>[newSize]; for (unsigned i = 0; i < size; i++) { for (it = table[i].begin(); it != table[i].end(); it++) { K key = it->first; V val = it->second; unsigned idx = hashes::hash(key, newSize); newTable[idx].push_front({key, val}); } } delete[] table; table = newTable; size = newSize; }
fdb075167409c531a8ffa63f4eb5c358ff9f4c08
8da9d3c3e769ead17f5ad4a4cba6fb3e84a9e340
/src/chila/lib/node/util.hpp
51b98169af1da8738e7ec4fea35fe3d0da6b3455
[]
no_license
blockspacer/chila
6884a540fafa73db37f2bf0117410c33044adbcf
b95290725b54696f7cefc1c430582f90542b1dec
refs/heads/master
2021-06-05T10:22:53.536352
2016-08-24T15:07:49
2016-08-24T15:07:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,721
hpp
/* Copyright 2011-2015 Roberto Daniel Gimenez Gamarra ([email protected]) * (C.I.: 1.439.390 - Paraguay) */ #ifndef CHILA_LIB_NODE__UTIL_HPP #define CHILA_LIB_NODE__UTIL_HPP #include <chila/lib/misc/util.hpp> #include "exceptions.hpp" #define my_assert CHILA_LIB_MISC__ASSERT #define CHILA_META_NODE__DEF_CHECK_BASES_ELEM(n, data, elem) \ chila::lib::node::checkAndAdd(list, [&]{ elem::check(newData.get()); }); #define CHILA_META_NODE__DEF_CHECK_BASES(Bases, defMyCheck) \ BOOST_PP_IF(defMyCheck, chila::lib::node::CheckDataUPtr createCheckData(chila::lib::node::CheckData *data) const;, ); \ BOOST_PP_IF(defMyCheck, void myCheck(chila::lib::node::CheckData *data = nullptr) const;, ); \ void check(chila::lib::node::CheckData *data = nullptr) const override \ { \ chila::lib::node::CheckExceptionList list; \ auto newData = BOOST_PP_IF(defMyCheck, createCheckData(data), chila::lib::node::CheckDataUPtr()); \ BOOST_PP_SEQ_FOR_EACH(CHILA_META_NODE__DEF_CHECK_BASES_ELEM,,Bases) \ BOOST_PP_IF(defMyCheck, BOOST_PP_IDENTITY(\ chila::lib::node::checkAndAdd(list, [&]{ myCheck(newData.get()); }); \ ), BOOST_PP_EMPTY)(); \ if (!list.exceptions.empty()) throw list; \ } #define CHILA_META_NODE__DEF_CHECK \ void check(chila::lib::node::CheckData *data = nullptr) const override; #include "nspDef.hpp" MY_NSP_START { template <typename CheckFun> void checkAndAdd(chila::lib::node::CheckExceptionList &list, const CheckFun &checkFun) try { checkFun(); } catch (ExceptionWrapper &ex) { list.add(ex.ex); } catch (CheckExceptionList &ex) { list.add(ex); } catch (Exception &ex) { list.add(ex); } chila::lib::misc::Path getNodePath(const Node &node); // to avoid cyclical dependency template <typename Fun> inline auto catchThrow(const Node &node, const Fun &fun) -> decltype(fun()) try { return fun(); } catch (const boost::exception &ex) { ex << chila::lib::misc::ExceptionInfo::Path(getNodePath(node)); throw; } template <typename ToType, typename Node> inline const ToType &castNode(const Node &node) try { return catchThrow(node, [&]() -> const ToType& { return chila::lib::misc::dynamicCast<ToType>(node); }); } catch (const boost::exception &ex) { InvalidNode exx; insert_error_info(chila::lib::misc::ExceptionInfo::TypeFrom) insert_error_info(chila::lib::misc::ExceptionInfo::TypeTo) insert_error_info(chila::lib::misc::ExceptionInfo::ActualType) insert_error_info(chila::lib::misc::ExceptionInfo::Path) BOOST_THROW_EXCEPTION(exx); } template <typename ToType, typename Node> inline ToType &castNode(Node &node) try { return catchThrow(node, [&]() -> ToType& { return chila::lib::misc::dynamicCast<ToType>(node); }); } catch (const boost::exception &ex) { InvalidNode exx; insert_error_info(chila::lib::misc::ExceptionInfo::TypeFrom) insert_error_info(chila::lib::misc::ExceptionInfo::TypeTo) insert_error_info(chila::lib::misc::ExceptionInfo::ActualType) insert_error_info(chila::lib::misc::ExceptionInfo::Path) BOOST_THROW_EXCEPTION(exx); } NodeWithChildren &mainParent(NodeWithChildren &node); PathVec getReferences( NodeWithChildren &node, const chila::lib::misc::Path &path); void replaceReferences(NodeWithChildren &node, const PathVec &paths, const Node &newRefNode); } MY_NSP_END #include "nspUndef.hpp" #endif
3839e99ec45940f1c94baf2131e7849a8871b51c
4f37081ed62e44afa0b2465388a8adf9b5490b13
/ash/login/ui/login_user_view.h
4d27549c5a7f8e8dda6fd0bc769f65efd3439630
[ "BSD-3-Clause" ]
permissive
zowhair/chromium
05b9eed58a680941c3595d52c3c77b620ef2c3ac
d84d5ef83e401ec210fcb14a92803bf339e1ccce
refs/heads/master
2023-03-04T23:15:10.914156
2018-03-15T11:27:44
2018-03-15T11:27:44
125,359,706
1
0
null
2018-03-15T11:50:44
2018-03-15T11:50:43
null
UTF-8
C++
false
false
3,544
h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_LOGIN_UI_LOGIN_USER_VIEW_H_ #define ASH_LOGIN_UI_LOGIN_USER_VIEW_H_ #include "ash/ash_export.h" #include "ash/login/ui/login_display_style.h" #include "ash/public/interfaces/login_user_info.mojom.h" #include "base/macros.h" #include "ui/views/controls/button/button.h" #include "ui/views/view.h" namespace ash { class HoverNotifier; class LoginBubble; class LoginButton; // Display the user's profile icon, name, and a menu icon in various layout // styles. class ASH_EXPORT LoginUserView : public views::View, public views::ButtonListener { public: // TestApi is used for tests to get internal implementation details. class ASH_EXPORT TestApi { public: explicit TestApi(LoginUserView* view); ~TestApi(); LoginDisplayStyle display_style() const; const base::string16& displayed_name() const; views::View* user_label() const; views::View* tap_button() const; bool is_opaque() const; private: LoginUserView* const view_; }; using OnTap = base::RepeatingClosure; // Returns the width of this view for the given display style. static int WidthForLayoutStyle(LoginDisplayStyle style); LoginUserView(LoginDisplayStyle style, bool show_dropdown, bool show_domain, const OnTap& on_tap); ~LoginUserView() override; // Update the user view to display the given user information. void UpdateForUser(const mojom::LoginUserInfoPtr& user, bool animate); // Set if the view must be opaque. void SetForceOpaque(bool force_opaque); // Enables or disables tapping the view. void SetTapEnabled(bool enabled); const mojom::LoginUserInfoPtr& current_user() const { return current_user_; } // views::View: const char* GetClassName() const override; gfx::Size CalculatePreferredSize() const override; void Layout() override; // views::ButtonListener: void ButtonPressed(views::Button* sender, const ui::Event& event) override; private: class UserDomainInfoView; class UserImage; class UserLabel; class TapButton; // Called when hover state changes. void OnHover(bool has_hover); // Updates UI element values so they reflect the data in |current_user_|. void UpdateCurrentUserState(); // Updates view opacity based on input state and |force_opaque_|. void UpdateOpacity(); void SetLargeLayout(); void SetSmallishLayout(); // Executed when the user view is pressed. OnTap on_tap_; // The user that is currently being displayed (or will be displayed when an // animation completes). mojom::LoginUserInfoPtr current_user_; // Used to dispatch opacity update events. std::unique_ptr<HoverNotifier> hover_notifier_; LoginDisplayStyle display_style_; UserImage* user_image_ = nullptr; UserLabel* user_label_ = nullptr; LoginButton* user_dropdown_ = nullptr; TapButton* tap_button_ = nullptr; std::unique_ptr<LoginBubble> user_menu_; // Show the domain information for public account user. UserDomainInfoView* user_domain_ = nullptr; // True iff the view is currently opaque (ie, opacity = 1). bool is_opaque_ = false; // True if the view must be opaque (ie, opacity = 1) regardless of input // state. bool force_opaque_ = false; DISALLOW_COPY_AND_ASSIGN(LoginUserView); }; } // namespace ash #endif // ASH_LOGIN_UI_LOGIN_USER_VIEW_H_
9b67f6e27a369c3b66f7fb8bf435dc44a8750a9f
5dbdb28b66c4828bf83564f1cf63f82480d6395f
/HelloWorld_demo_game/Classes/DemoGame/GameClock.h
0376404ad2fc38c0fa7670b28ad9433a96177a3c
[]
no_license
gengyu-mamba/CardGames
87a2b8fca377a6bd3de0ba4c6fe09a9e85e22848
d2b0133c02cc04b75a49ca164a086aaa5603715d
refs/heads/master
2020-04-02T18:23:19.395504
2018-11-08T02:34:23
2018-11-08T02:34:23
154,698,113
0
0
null
null
null
null
UTF-8
C++
false
false
487
h
#ifndef GAME_CLOCK_H #define GAME_CLOCK_H #include "cocos2d.h" USING_NS_CC; class GameLayer; class GameClock :public CCLayer { public: GameClock(GameLayer *pGameLayer); virtual ~GameClock(); void ShowClock(int iTime,int iTablePos); void ResetClock(); private: virtual void onEnter(); virtual void onExit(); void OnSecondTimer(float dt); CCSprite *m_pSpriteBG; CCLabelAtlas *m_pNumLable; int m_iTime; int m_iTablePos; GameLayer *m_pGameLayer; }; #endif
cb70bcdd5ff36e2a7d758db629c0ae1cdf415f34
6cc00c07a75bf18a2b1824383c3acc050098d9ed
/CodeChef/Easy/E0034.cpp
8b0e042dd591f11ae41cddc5d38bbbd3f36fd170
[ "MIT" ]
permissive
Mohammed-Shoaib/Coding-Problems
ac681c16c0f7c6d83f7cb46be71ea304d238344e
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
refs/heads/master
2022-06-14T02:24:10.316962
2022-03-20T20:04:16
2022-03-20T20:04:16
145,226,886
75
31
MIT
2020-10-02T07:46:58
2018-08-18T14:31:33
C++
UTF-8
C++
false
false
372
cpp
// Problem Code: ALEXNUMB #include <iostream> #include <vector> using namespace std; long magicPairs(vector<int> &a){ long N = a.size(); return N*(N-1)/2; } int main(){ int T, n, num; vector<int> a; cin >> T; while(T--){ cin >> n; for(int i=0 ; i<n ; i++){ cin >> num; a.push_back(num); } cout << magicPairs(a) << endl; a.clear(); } return 0; }
da305b7fa058459e59591d534b6f8ccafc370f33
e542234cbf0eea3883b934ee67f97326377de02f
/EnemySnipper.hpp
194187a1b40c4a3a73a79907b77035df6c48f895
[ "MIT" ]
permissive
kaitokidi/WhoTookMyHat
8e66e510e10451a3499a2fa361c8892e8f7b818f
dc4ebdbe880a10cb681bf2749095f4bbbbe51f88
refs/heads/master
2021-04-19T00:56:37.700324
2016-10-27T22:29:11
2016-10-27T22:29:11
51,254,343
4
0
null
null
null
null
UTF-8
C++
false
false
459
hpp
#ifndef ENEMYSNIPPER_HPP #define ENEMYSNIPPER_HPP #include "Enemy.hpp" #include "Player.hpp" #include "EnemyShooter.hpp" class EnemySnipper : public Enemy, public EnemyShooter { public: //TODO virtual void init(); EnemySnipper(std::list < Enemy* >* e, Player* p); virtual void update(float deltaTime, Background* bg); virtual void movement(float deltaTime, Background *bg); protected: Player* _player; }; #endif // ENEMYSNIPPER_HPP
ed2c7bf9da571764d1c53f11f98afd73c52384e1
9618f5517917b18298c160161633f91d2a61e1e1
/kursach_taras/cone.cpp
ef624b9c68a1609baec321cf776925a5bfc108c2
[]
no_license
h1xxy/taras_krsch
b1bf548cb3ec4413294f9b1fd7c60fc71567ea33
4b9bb13015792a0bc64fdbf2c1702d2a1050879b
refs/heads/master
2022-07-04T21:14:59.666350
2020-05-20T08:52:40
2020-05-20T08:52:40
265,474,938
1
0
null
null
null
null
UTF-8
C++
false
false
856
cpp
#include "cone.h" #include <math.h> #define M_PI 3.14159265358979323846 #define ANGLE_STEPSIZE 0.001f Cone::~Cone() { } void Cone::draw() { glMatrixMode(GL_MODELVIEW); glPushMatrix(); float x = 0.0; float y = 0.0; float angle; glColor3ub(colorR_, colorG_, colorB_); glBegin(GL_POLYGON); angle = 0.0; glVertex3f(positionX_, positionY_, positionZ_ + (height_ / 2)); while (angle <= 2 * M_PI + 1) { x = radius_ * cos(angle); y = radius_ * sin(angle); glVertex3f(x + positionX_, y + positionY_, positionZ_ - (height_ / 2)); angle = angle + ANGLE_STEPSIZE; } glEnd(); glBegin(GL_POLYGON); angle = 0.0; while (angle < 2 * M_PI) { x = radius_ * cos(angle); y = radius_ * sin(angle); glVertex3f(x + positionX_, y + positionY_, positionZ_ - (height_ / 2)); angle = angle + ANGLE_STEPSIZE; } glEnd(); glPopMatrix(); }
bd6c2df095958604a9d37647317eb77b66e673f9
c512bd8b0fb797f503e57540c11657b79336d5b1
/OOP3200-INCLASS3-ANDRAGRIPPA/Person.cpp
8d8e1b099d8aa2486acdae5481f3c16c1d858d91
[]
no_license
vans12345678/OOP3200-INCLASS3-ANDRAGRIPPA
6646fa6ee557f567bd0b4f59d3c9fa39206b4119
f9edb63613ca5b93dd72ce85ed91891e23cab737
refs/heads/master
2022-12-18T20:15:11.016237
2020-10-01T01:11:06
2020-10-01T01:11:06
299,958,654
0
0
null
null
null
null
UTF-8
C++
false
false
1,523
cpp
/** * Project OOP3200-F2020-LESSON4 * @author Andre Agrippa * @version 1.0 */ #include "Person.h" #include <iostream> #include <ostream> /** * Person implementation */ /** * @param first_name * @param last_name * @param age */ Person::Person(std::string first_name, std::string last_name, const float age): m_age(age), m_firstName(std::move(first_name)), m_lastName(std::move(last_name)) { } Person::~Person() = default; /** * @return std::string */ std::string Person::getFirstName()const { return m_firstName; } /** * @param value */ void Person::setFirstName(const std::string& value) { m_firstName = value; } /** * @return std::string */ std::string Person::getLastName() const{ return m_lastName; } /** * @param value */ void Person::setLastName(const std::string& value) { m_lastName = value; } /** * @return float */ float Person::getAge()const { return m_age; } /** * @param value */ void Person::setAge(const float value) { m_age = value; } /** * @return void */ void Person::SaysHello() const{ std::cout << getFirstName() << " says Hello!" << std::endl; } /** * @return std::string */ std::string Person::ToString() { std::string output_string; output_string += "----------------------------------------------------\n"; output_string += "First Name: " + getFirstName() + "\n"; output_string += "Last Name: " + getLastName() + "\n"; output_string += "Age: " + std::to_string(getAge()) + "\n"; return output_string; }
9ac7fc61e93fae4a2a3dd1a7ec0aa7097f7a4960
a2e9639153e71dcf84d34b7349d69aa31b2eb678
/zBTLC/zBTLC/game_sa/CTreadable.cpp
63795c950bd989bdd738bcfddca7777d25e94cc7
[]
no_license
DaDj/GTA-BTLC
ade014b3d8dbb1ecce6422328be95631226cd6f4
15d60cb5d5f14291317235066d64a639fffaf3ea
refs/heads/master
2023-08-16T23:12:57.867204
2023-08-13T21:45:06
2023-08-13T21:45:06
83,485,003
4
2
null
null
null
null
UTF-8
C++
false
false
23
cpp
#include "CTreadable.h"
fb91f6eaa8d8ee4570429a0ed27d843cbd9b7e4f
1d3220f8f390aa9f5847ace75afdb045531e6cd5
/DMUploadingRule.cpp
afbd8ae8d3bf984ef96b2eeb2910225e7677da0c
[]
no_license
persenlee/FileTransfer
d85d7577e3366c5515d86ef47c8c925feb2d62d1
fff2f0b9649fd6259cece45e6b2adfa3bb26d008
refs/heads/master
2021-01-01T03:46:55.882496
2016-05-20T03:22:28
2016-05-20T03:22:28
58,631,662
0
0
null
null
null
null
UTF-8
C++
false
false
7,625
cpp
// // DMUploadingRule.cpp // FileTransfer // // Created by duomai on 16/5/16. // // #include "DMUploadingRule.hpp" #include "DMFileUploadManager.hpp" #include "DMFileTransferException.hpp" #include "DMFileTransferDef.h" using namespace web; using namespace web::json; void logRequest(http_request request); void logResponse(http_response response); void DMUploadingRule::setUserToken(string const &token) { _userToken = token; } #pragma mark - Ovrride Methods bool DMUploadingRule::preProcess() { return checkFileMeta(); } bool DMUploadingRule::doUpload() { return uploadFileChunk(); } bool DMUploadingRule::endProcess() { return true; } #pragma mark - Private Methods bool DMUploadingRule::checkFileMeta() { json::value params = json::value::object(); utility::string_t file_hash(U("file_hash")); params[file_hash] = json::value(_file.SHA1()); utility::string_t file_crc(U("file_crc")); params[file_crc] = json::value(_file.CRC32()); utility::string_t file_name(U("file_name")); params[file_name] = json::value(_file.fileName); utility::string_t total_size(U("total_size")); params[total_size] = json::value(_file.fileSize()); const method mtd = methods::POST; const utility::string_t field_name1 = U("user_session_token"); const utility::string_t value1 = _userToken; http_request request(mtd); request.set_request_uri(U("check_file_meta")); request.headers().add(field_name1, value1); request.set_body(params); request.headers().add(U("User-Agent"), "DMFileUploadManager"); pplx::task<http_response> responsetTask = _client.request(request); logRequest(request); http_response resp ; try { resp = responsetTask.get(); } catch (http_exception ex) { DMFileTransferException dmException((int)DMFileTransfer_CouldNotGetResponse); throw dmException; } logResponse(resp); if (resp.status_code() == 200) { pplx::task<json::value> jsonTask = resp.extract_json(); json::value result= jsonTask.get(); json::value file_status = result[U("file_status")]; // json::value file_upload_token = result[U("file_upload_token")]; json::value file_url = result[U("file_url")]; json::value last_ok_chunk_sn = result[U("last_ok_chunk_sn")]; json::value chunk_size = result[U("chunk_size")]; cfmrModel = CheckFileMetaResponseModel((DMFileUploadStatus)file_status.as_integer(), !file_upload_token.is_null() ? file_upload_token.as_string() : "", !chunk_size.is_null() ? chunk_size.as_integer() : 0, !last_ok_chunk_sn.is_null() ? last_ok_chunk_sn.as_integer() : 0, !file_url.is_null() ? file_url.as_string() : ""); switch (cfmrModel.file_status) { case 0: { _handler->uploadingProgressHandler(0, _file.fileSize()); } break; case 1: { _handler->uploadingProgressHandler(cfmrModel.chunk_size * cfmrModel.last_ok_chunk_sn, _file.fileSize()); } break; case 2: { _handler->uploadCompleteHandler(true,file_url.as_string()); _handler->uploadingProgressHandler(_file.fileSize(), _file.fileSize()); return false; } break; default: break; } return true; } else { _handler->uploadCompleteHandler(false, ""); return false; } } bool DMUploadingRule::uploadFileChunk() { bool success = false; const method mtd = methods::POST; const utility::string_t field_name1 = U("upload_token"); const utility::string_t value1 = cfmrModel.file_upload_token; http_request request(mtd); request.set_request_uri(U("upload_file_chunk")); request.headers().add(field_name1, value1); request.headers().set_content_length(INTMAX_MAX); request.headers().add(U("User-Agent"), "DMFileUploadManager"); int64_t File_Size = _file.fileLength(); _file.openFile(/*iostream::binary*/); //续传 int64_t uploadedSize = cfmrModel.last_ok_chunk_sn * cfmrModel.chunk_size; if (uploadedSize > 0) { _file.moveFileReadPos(uploadedSize); } do { int request_again_times = 0; int readSize = cfmrModel.chunk_size; if (uploadedSize + cfmrModel.chunk_size > File_Size) { readSize = File_Size % cfmrModel.chunk_size; } std::vector<unsigned char> body; _file.readFile2Vector(body, readSize); request.set_body(body); request_again: request_again_times ++; logRequest(request); pplx::task<http_response> responsetTask = _client.request(request); http_response resp ; try { resp = responsetTask.get(); } catch (http_exception ex) { DMFileTransferException dmException((int)DMFileTransfer_CouldNotGetResponse); throw dmException; } logResponse(resp); if (resp.status_code() == 200) { pplx::task<json::value> jsonTask = resp.extract_json(); json::value result= jsonTask.get(); cout << "response body : " << result.serialize() << endl; json::value file_status = result[U("file_status")]; // json::value chunk_status = result[U("chunk_status")]; json::value file_url = result[U("file_url")]; switch (file_status.as_integer()) { case 1: //正在上传 { if (chunk_status.as_integer() == -1) { // 标识数据块保存失败 goto request_again; } else if(chunk_status.as_integer() == 0){ uploadedSize += readSize; _handler->uploadingProgressHandler(uploadedSize, File_Size); } } break; case 2: //上传成功 { uploadedSize += readSize; _handler->uploadingProgressHandler(uploadedSize, File_Size); _handler->uploadCompleteHandler(true,file_url.as_string()); success = true; } break; case -1: //文件上传失败 { _handler->uploadCompleteHandler(false, "");; } break; default: break; } } else { _handler->uploadCompleteHandler(false, ""); } } while (uploadedSize < File_Size); _file.closeFile(); return success; } void logRequest(http_request request) { cout << "---------------------request start------------------" << endl; cout << request.to_string() << endl; cout << "---------------------request end------------------" << endl << endl; } void logResponse(http_response response) { cout << "++++++++++++++++++++response start++++++++++++++++++++" << endl; cout << response.to_string() << endl; cout << "++++++++++++++++++++response end++++++++++++++++++++" << endl << endl; }
534e4d3031dc97052ded75575351d0ed28da9bfb
0d653408de7c08f1bef4dfba5c43431897097a4a
/cmajor/cmbs/Error.cpp
5cb9fc81316595d5daf239f5c41f65152671bd75
[]
no_license
slaakko/cmajorm
948268634b8dd3e00f86a5b5415bee894867b17c
1f123fc367d14d3ef793eefab56ad98849ee0f25
refs/heads/master
2023-08-31T14:05:46.897333
2023-08-11T11:40:44
2023-08-11T11:40:44
166,633,055
7
2
null
null
null
null
UTF-8
C++
false
false
2,609
cpp
// ================================= // Copyright (c) 2022 Seppo Laakko // Distributed under the MIT license // ================================= #include <cmajor/cmbs/Error.hpp> #include <cmajor/symbols/Module.hpp> #include <cmajor/symbols/ModuleCache.hpp> #include <soulng/util/Unicode.hpp> namespace cmbs { using namespace soulng::unicode; CompileError ParsingExceptionToError(const soulng::lexer::ParsingException& ex) { CompileError error; error.message = ex.Message(); error.project = ex.Project(); error.file = ex.FileName(); soulng::lexer::Span span = ex.GetSpan(); error.line = span.line; cmajor::symbols::Module* mod = static_cast<cmajor::symbols::Module*>(ex.Module()); if (mod) { int startCol = 0; int endCol = 0; mod->GetColumns(span, startCol, endCol); error.scol = startCol; error.ecol = endCol; } return error; } std::vector<CompileError> SymbolsExceptionToErrors(const cmajor::symbols::Exception& ex) { std::vector<CompileError> errors; CompileError mainError; mainError.message = ex.Message(); cmajor::symbols::Module* mod = cmajor::symbols::GetModuleById(ex.DefinedModuleId()); if (mod) { Span span = ex.Defined(); std::u32string code = mod->GetErrorLines(span); mainError.message.append("\n").append(ToUtf8(code)); mainError.project = ToUtf8(mod->Name()); mainError.file = mod->GetFilePath(span.fileIndex); mainError.line = span.line; int startCol = 0; int endCol = 0; mod->GetColumns(span, startCol, endCol); mainError.scol = startCol; mainError.ecol = endCol; } errors.push_back(mainError); for (const std::pair<Span, boost::uuids::uuid>& spanModuleId : ex.References()) { CompileError referenceError; referenceError.message = "See:"; cmajor::symbols::Module* mod = cmajor::symbols::GetModuleById(spanModuleId.second); if (mod) { std::u32string code = mod->GetErrorLines(spanModuleId.first); referenceError.message.append("\n").append(ToUtf8(code)); referenceError.file = mod->GetFilePath(spanModuleId.first.fileIndex); referenceError.line = spanModuleId.first.line; int startCol = 0; int endCol = 0; mod->GetColumns(spanModuleId.first, startCol, endCol); referenceError.scol = startCol; referenceError.ecol = endCol; errors.push_back(referenceError); } } return errors; } } // namespace cmbs
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; } }
3c1b9a977eb477d5b194c9d62796fdbdb650af98
74b07eb2bc01383744514b70b385571fb90a1a04
/test/test.cpp
c870d6500c7d2c64c80815743dbbe2e47990c430
[]
no_license
yksym/x86_64_hook_without_ld_preload
8ae067c195bf1eb0f23d67a1087ad3f8ebcfab4a
2ed1eaf37f688199f12e3aa34a6f3435b906b932
refs/heads/master
2016-09-05T11:08:33.212588
2015-09-03T13:02:04
2015-09-03T13:02:04
40,049,578
0
0
null
null
null
null
UTF-8
C++
false
false
742
cpp
#include <stdio.h> #include <stdlib.h> #include <hook.h> extern "C" { void* calloc_hook(size_t n, size_t size) { DECL_ORG_FUNC(calloc, org_calloc); puts( __FUNCTION__ ); return org_calloc(n, size); } }; void test(const char* program) { puts(__FILE__ ": 1st"); { HOOK(program, calloc, calloc_hook); void* b = calloc(1, 10); free(b); } puts(__FILE__ ": 2nd"); void* c = calloc(1, 10); free(c); puts(__FILE__ ": 3rd"); { HOOK(program, calloc, calloc_hook); void* b = calloc(1, 10); free(b); } } void test2(const char* program); int main(int argc, char** argv) { test(argv[0]); test2(LIB_NAME); return 0; }
4f382278b8d5b2babc07007ecf53e4df951a580f
fc087820e4dc33146341cd6b71a000c227cda819
/Majority Element II.cpp
8f6a0b3226ec9ceea590fa7c8715ee973817c422
[]
no_license
jyqi/leetcode
1396b27fd97aa29687392dceda2e0bed2dc8fd31
9682e03fa91dca44654439029fb11d73e86a61d8
refs/heads/master
2022-02-16T09:14:54.012699
2022-02-14T07:54:11
2022-02-14T07:54:11
56,414,779
0
0
null
null
null
null
UTF-8
C++
false
false
1,032
cpp
#include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> majorityElement(vector<int>& nums) { int cnt1 = 0, cnt2 = 0, maj1 = 0, maj2 = 0; int len = nums.size(); vector<int> res; //cout << 1 << endl; for(int i = 0; i < len; i++) { if(cnt1 == 0 && nums[i] != maj2) { maj1 = nums[i]; cnt1 = 1; } else if(nums[i] == maj1) { cnt1++; } else if(cnt2 == 0 && nums[i] != maj1) { maj2 = nums[i]; cnt2 = 1; } else if(nums[i] == maj2) { cnt2++; } else { cnt1--; cnt2--; } } cnt1 = cnt2 = 0; for(int i = 0; i < len; i++) { if(nums[i] == maj1) cnt1++; else if(nums[i] == maj2) cnt2++; } if(cnt1 > len / 3) res.push_back(maj1); if(cnt2 > len / 3) res.push_back(maj2); return res; } }; int main() { int arr[] = {1, 2, 1, 2, 1, 3, 3}; Solution s; vector<int> v(arr, arr + 7); vector<int> res; res = s.majorityElement(v); for(int i = 0; i < res.size(); i++) { cout << res[i] << endl; } return 0; }
c00af421b2b38fc9ea7376fde3f61ce25a7df7cf
258cb026f59dff826ada21702e6efa3f952981c4
/Test/frametest/frametest/P2C5_LitPyramid.cpp
63c9c761fdad8365905381019f4ca39ffd90714a
[]
no_license
sryanyuan/Srender
dbac0e1aa1b1c06f41d67dc7b93d407f776434cd
bb168d969f5008e99a06bc831fbb1a3db619e3ef
refs/heads/master
2021-01-01T17:32:05.017317
2014-08-14T08:06:53
2014-08-14T08:06:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,298
cpp
#include "stdafx.h" #include "P2C5_LitPyramid.h" #include <core/SRColor.h> ////////////////////////////////////////////////////////////////////////// void CalculateNormal(D3DXVECTOR3* _pOut, const D3DXVECTOR3* _p0, const D3DXVECTOR3* _p1, const D3DXVECTOR3* _p2) { D3DXVECTOR3 u = *_p1 - *_p0; D3DXVECTOR3 v = *_p2 - *_p0; // left hand coordinate system... D3DXVec3Cross(_pOut, &u, &v); D3DXVec3Normalize(_pOut, _pOut); } ////////////////////////////////////////////////////////////////////////// LitPyramid::LitPyramid() { m_pVB = NULL; } LitPyramid::~LitPyramid() { } bool LitPyramid::OnEnvCreate() { m_pVB = Gfx_CreateVertexBuffer<SRNormalVertex>(4 * 3); if(NULL == m_pVB) { return false; } SRNormalVertex* pVertex = NULL; m_pVB->Lock(0, 0, (void**)&pVertex, 0); // front side D3DXVECTOR3 v0; D3DXVECTOR3 v1; D3DXVECTOR3 v2; D3DXVECTOR3 vn; pVertex[0] = SRNormalVertex(-1.0f, 0.0f, -1.0f); pVertex[1] = SRNormalVertex(0.0f, 1.0f, 0.0f); pVertex[2] = SRNormalVertex(1.0f, 0.0f, -1.0f); v0.x = pVertex[0].GetX(); v0.y = pVertex[0].GetY(); v0.z = pVertex[0].GetZ(); v1.x = pVertex[1].GetX(); v1.y = pVertex[1].GetY(); v1.z = pVertex[1].GetZ(); v2.x = pVertex[2].GetX(); v2.y = pVertex[2].GetY(); v2.z = pVertex[2].GetZ(); CalculateNormal(&vn, &v0, &v1, &v2); pVertex[0].SetNormalXYZ(vn.x, vn.y, vn.z); pVertex[1].SetNormalXYZ(vn.x, vn.y, vn.z); pVertex[2].SetNormalXYZ(vn.x, vn.y, vn.z); // left side pVertex[3] = SRNormalVertex(-1.0f, 0.0f, 1.0f); pVertex[4] = SRNormalVertex(0.0f, 1.0f, 0.0f); pVertex[5] = SRNormalVertex(-1.0f, 0.0f, -1.0f); v0.x = pVertex[3].GetX(); v0.y = pVertex[3].GetY(); v0.z = pVertex[3].GetZ(); v1.x = pVertex[4].GetX(); v1.y = pVertex[4].GetY(); v1.z = pVertex[4].GetZ(); v2.x = pVertex[5].GetX(); v2.y = pVertex[5].GetY(); v2.z = pVertex[5].GetZ(); CalculateNormal(&vn, &v0, &v1, &v2); pVertex[3].SetNormalXYZ(vn.x, vn.y, vn.z); pVertex[4].SetNormalXYZ(vn.x, vn.y, vn.z); pVertex[5].SetNormalXYZ(vn.x, vn.y, vn.z); // right side pVertex[6] = SRNormalVertex(1.0f, 0.0f, -1.0f); pVertex[7] = SRNormalVertex(0.0f, 1.0f, 0.0f); pVertex[8] = SRNormalVertex(1.0f, 0.0f, 1.0f); v0.x = pVertex[6].GetX(); v0.y = pVertex[6].GetY(); v0.z = pVertex[6].GetZ(); v1.x = pVertex[7].GetX(); v1.y = pVertex[7].GetY(); v1.z = pVertex[7].GetZ(); v2.x = pVertex[8].GetX(); v2.y = pVertex[8].GetY(); v2.z = pVertex[8].GetZ(); CalculateNormal(&vn, &v0, &v1, &v2); pVertex[6].SetNormalXYZ(vn.x, vn.y, vn.z); pVertex[7].SetNormalXYZ(vn.x, vn.y, vn.z); pVertex[8].SetNormalXYZ(vn.x, vn.y, vn.z); // back side pVertex[9] = SRNormalVertex(1.0f, 0.0f, 1.0f); pVertex[10] = SRNormalVertex(0.0f, 1.0f, 0.0f); pVertex[11] = SRNormalVertex(-1.0f, 0.0f, 1.0f); v0.x = pVertex[9].GetX(); v0.y = pVertex[9].GetY(); v0.z = pVertex[9].GetZ(); v1.x = pVertex[10].GetX(); v1.y = pVertex[10].GetY(); v1.z = pVertex[10].GetZ(); v2.x = pVertex[11].GetX(); v2.y = pVertex[11].GetY(); v2.z = pVertex[11].GetZ(); CalculateNormal(&vn, &v0, &v1, &v2); pVertex[9].SetNormalXYZ(vn.x, vn.y, vn.z); pVertex[10].SetNormalXYZ(vn.x, vn.y, vn.z); pVertex[11].SetNormalXYZ(vn.x, vn.y, vn.z); m_pVB->Unlock(); m_pD3Dev9->SetRenderState(D3DRS_LIGHTING, TRUE); D3DMATERIAL9 mtrl; mtrl.Ambient = SRColor::GetCommonColor(SRColor::CC_WHITE); mtrl.Diffuse = SRColor::GetCommonColor(SRColor::CC_WHITE); mtrl.Specular = SRColor::GetCommonColor(SRColor::CC_WHITE); mtrl.Emissive = SRColor::GetCommonColor(SRColor::CC_BLACK); mtrl.Power = 5.0f; m_pD3Dev9->SetMaterial(&mtrl); D3DLIGHT9 lgt; ZeroMemory(&lgt, sizeof(lgt)); lgt.Type = D3DLIGHT_DIRECTIONAL; lgt.Diffuse = SRColor::GetCommonColor(SRColor::CC_WHITE); lgt.Specular = SRColor::GetCommonColor(SRColor::CC_WHITE) * 0.3f; lgt.Ambient = SRColor::GetCommonColor(SRColor::CC_WHITE) * 0.6f; lgt.Direction = D3DXVECTOR3(1.0f, 0.0f, 0.0f); m_pD3Dev9->SetLight(0, &lgt); m_pD3Dev9->LightEnable(0, TRUE); m_pD3Dev9->SetRenderState(D3DRS_NORMALIZENORMALS, TRUE); m_pD3Dev9->SetRenderState(D3DRS_SPECULARENABLE, TRUE); D3DXVECTOR3 pos(0.0f, 1.0f, -3.0f); Gfx_SetViewTransform(&pos); Gfx_SetProjectionTransform(); return true; } void LitPyramid::OnEnvDestroy() { SSAFE_RELEASE(m_pVB); } void LitPyramid::OnDrawFrame() { SRRenderApp* pApp = SRRenderApp::GetInstancePtr(); static float s_fRotateY = 0.0f; s_fRotateY += pApp->GetTimeDelta(); static float s_fRotateX = 0.0f; s_fRotateX += pApp->GetTimeDelta() * 0.5f; D3DXMATRIX roty; D3DXMatrixRotationY(&roty, s_fRotateY); D3DXMATRIX rotx; D3DXMatrixRotationX(&rotx, s_fRotateX); D3DXMATRIX rot = rotx * roty; if(s_fRotateY > 6.28f) { s_fRotateY = 0.0f; } if(s_fRotateX > 6.28f) { s_fRotateX = 0.0f; } m_pD3Dev9->SetTransform(D3DTS_WORLD, &roty); m_pD3Dev9->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0x00000000, 1.0f, 0); m_pD3Dev9->BeginScene(); m_pD3Dev9->SetStreamSource(0, m_pVB, 0, sizeof(SRNormalVertex)); m_pD3Dev9->SetFVF(SRNormalVertex::FVF); m_pD3Dev9->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 4); m_pD3Dev9->EndScene(); m_pD3Dev9->Present(0, 0, 0, 0); }
594e71c07f5c14b0e47d84c3887fb2634517984c
7a5a713cc999fdc1f64457949b003980e288567a
/Classes/ExplodeSmoke.h
a878d13147d91a026074988ee4903c9dfe3be564
[]
no_license
highfence/ShootingGameProject
2b564d09ea02ae64fb65d85b59ecb6e0d170ec53
61e57136d52e8b1d980eec304dd474774f239f94
refs/heads/master
2021-01-20T12:28:31.574956
2017-04-05T06:49:42
2017-04-05T06:49:42
82,655,552
0
0
null
2017-03-16T10:04:44
2017-02-21T08:33:06
C++
UTF-8
C++
false
false
328
h
#pragma once #include "Effect.h" class ExplodeSmoke : public Effect { public : ExplodeSmoke() = delete; ExplodeSmoke(const _In_ Vec); ExplodeSmoke( const _In_ Vec, const _In_ FLOAT, const _In_ Vec); ~ExplodeSmoke(); private : void init(); void LoadInitialImg() override; void InitialDataSubstitude() override; };
b68966c17d5045233b5646054d6eadc547b96397
9d34ceb787b7e7a0aa9d242e401f0b13c2e4ea94
/JoaoScaravonatti.cpp
7278f4a435cc05195b6a61560ed065092c4ef52a
[]
no_license
joaoscaravonatti/projeto-final-algoritmos
31a5d2ed39afd6d918894869e2c43972f44f0be7
23f6d11aacbe714471cc064490da6a634ac0bfa9
refs/heads/master
2020-03-30T09:37:17.994469
2018-10-01T12:21:17
2018-10-01T12:21:17
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
6,611
cpp
#include<stdio.h> #include<stdlib.h> #include<conio.h> #include<string.h> #include<locale.h> #include<windows.h> #define tam 1000 struct cliente{ int codigo; char nome[50]; char sexo[20]; char dataNascimento[12]; char cpf[12]; char telefone[11]; char email[100]; }; int id = 0; int i = 0; struct cliente clientes[tam]; void cadastrar(){ id++; clientes[id].codigo = id; printf("\nColoque o nome completo: "); scanf(" %[^\n]s",&clientes[id].nome); printf("\nColoque o CPF sem formatação: "); scanf("%s",&clientes[id].cpf); printf("\nColoque o sexo (masculino/feminino): "); scanf("%s",&clientes[id].sexo); printf("\nColoque a data de nascimento no formato XX/XX/XXXX: "); scanf("%s",&clientes[id].dataNascimento); printf("\nColoque o telefone sem formatação: "); scanf("%s",&clientes[id].telefone); printf("\nColoque o email: "); scanf("%s",&clientes[id].email); } void excluir(int codigo){ clientes[codigo].codigo = 0; strcpy(clientes[codigo].nome,""); } void consultarCod(int codigo){ int verificar=0; system("cls"); if(codigo != 0){ for(i=0;i<tam;i++){ if(clientes[i].codigo == codigo){ printf("\nDados do cliente n° %i\nNome: %s\nSexo: %s\nData de nascimento: %s\nCPF: %s\nTelefone: %i\nE-mail: %s\n",clientes[i].codigo,clientes[i].nome,clientes[i].sexo,clientes[i].dataNascimento,clientes[i].cpf,clientes[i].telefone,clientes[i].email); verificar++; } } } if(verificar==0){ printf("\nEsse cliente não está cadastrado!"); } printf("\n_______________________________\n"); } void consultarNome(char nome[]){ int codigo=0; system("cls"); if(strcmp(nome,"")!=0){ for(i=0;i<tam;i++){ if(strcmp(nome,clientes[i].nome)==0){ codigo = i; printf("\nDados do cliente n° %i\nNome: %s\nSexo: %s\nData de nascimento: %s\nCPF: %s\nTelefone: %i\nE-mail: %s\n",clientes[codigo].codigo,clientes[codigo].nome,clientes[codigo].sexo,clientes[codigo].dataNascimento,clientes[codigo].cpf,clientes[codigo].telefone,clientes[codigo].email); printf("\n_______________________________\n"); } } } if(codigo == 0){ printf("\nEsse cliente não está cadastrado!\n"); } } void listar(){ system("cls"); for(i=0;i<tam;i++){ if(clientes[i].codigo != 0){ printf("\nCliente de código %i: %s\n",clientes[i].codigo,clientes[i].nome); printf("_______________________________\n"); } } } void vrau(){ clientes[1].codigo = 1; strcpy(clientes[1].nome,"juca silva"); strcpy(clientes[1].sexo,"masculino"); strcpy(clientes[1].dataNascimento,"18/01/2000"); strcpy(clientes[1].cpf,"08816690917"); strcpy(clientes[1].telefone,"49999743090"); strcpy(clientes[1].email,"[email protected]"); clientes[2].codigo = 2; strcpy(clientes[2].nome,"juca silva"); strcpy(clientes[2].sexo,"masculino"); strcpy(clientes[2].dataNascimento,"18/01/2000"); strcpy(clientes[2].cpf,"08816690917"); strcpy(clientes[2].telefone,"49999743090"); strcpy(clientes[2].email,"[email protected]"); } void alterar(int codigo){ char opcao[1]; char confirm[1]; confirm[0] = '0'; if(codigo != 0){ do{ printf("\nQual informação deseja alterar?\n"); printf("\n1 - Nome: %s\n2 - Sexo: %s\n3 - Data de nascimento: %s\n4 - CPF: %s\n5 - Telefone: %i\n6 - E-mail: %s\nSua opção: ",clientes[codigo].nome,clientes[codigo].sexo,clientes[codigo].dataNascimento,clientes[codigo].cpf,clientes[codigo].telefone,clientes[codigo].email); fflush(stdin); opcao[0] = getche(); switch(opcao[0]){ case '1': printf("\nColoque o novo nome: "); scanf(" %[^\n]s",&clientes[codigo].nome); break; case '2': printf("\nColoque o novo sexo: "); scanf("%s",clientes[codigo].sexo); break; case '3': printf("\nColoque a nova data de nascimento: "); scanf("%s",&clientes[codigo].dataNascimento); break; case '4': printf("\nColoque o novo CPF: "); scanf("%s",&clientes[codigo].cpf); break; case '5': printf("\nColoque o novo telefone: "); scanf("%s",&clientes[codigo].telefone); break; case '6': printf("\nColoque o novo e-mail: "); scanf("%s",&clientes[codigo].email); break; default: printf("\nOpção inválida!"); } printf("\nContinuar editando? 0 para sim e 1 para não: "); confirm[0] = getche(); }while(confirm[0] !='1'); } } int main(){ //vrau(); setlocale(LC_ALL,"portuguese"); char opcao[1]; char flag[1]; int param=0; char paramChar[50]; char escolha[1]; flag[0] = '0'; printf("\nCadstro de clientes HyperSoft\n_____________________________\n"); Sleep(500); do{ printf("\n\nSelecione uma opção:\n\n"); printf("1 - Cadastro do cliente\n"); printf("2 - Alterar dados do cliente\n"); printf("3 - Exclusão de cliente\n"); printf("4 - Consultar cliente\n"); printf("5 - Listar clientes\n"); printf("6 - Sair\n"); printf("Sua opção: "); fflush(stdin); opcao[0] = getche(); system("cls"); switch(opcao[0]){ system("cls"); case '1': cadastrar(); break; case '2': printf("\nInsira o código do cliente a ser alterado: "); scanf("%i",&param); alterar(param); break; case '3': printf("\nInsira o código do cliente a ser exclúido: "); scanf("%i",&param); excluir(param); break; case '4': printf("\n1 - Consultar por nome\n2 - Consultar por código\n3 - Voltar\nSua opção: "); fflush(stdin); escolha[0] = getche(); switch(escolha[0]){ case '1': printf("\nInsira o nome do cliente a ser consultado: "); scanf(" %[^\n]s",&paramChar); consultarNome(paramChar); break; case '2': printf("\nInsira o código do cliente a ser consultado: "); scanf("%i",&param); consultarCod(param); break; case '3': break; default: printf("\nOpção mal informada"); } break; case '5': listar(); break; case '6': printf("\nPressione 1 para sair: "); flag[0] = getche(); break; default: printf("\nEstá opção não existe\n"); break; } }while(flag[0] != '1'); printf("\n\aFIM"); return 0; }
c0b9cd92c56f6f91ed9a7a6f7b5ae7a03a9d9b74
406b6f3e8355bcab9add96f3cff044823186fe37
/src/Simulation/osg_2d_simulation/quad.cpp
01c1fcc1ce18c295f1b29ec90b3b6adace8f46c2
[]
no_license
Micalson/puppet
96fd02893f871c6bbe0abff235bf2b09f14fe5d9
d51ed9ec2f2e4bf65dc5081a9d89d271cece28b5
refs/heads/master
2022-03-28T22:43:13.863185
2019-12-26T13:52:00
2019-12-26T13:52:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,295
cpp
#include "quad.h" #include <osgWrapper\UtilCreator.h> Quad::Quad() { m_node = new OSGWrapper::QuadAttributeUtilNode(1); m_geometry = OSGWrapper::UtilCreator::CreateUnitQuad(); m_node->AddChild(m_geometry); } Quad::~Quad() { } void Quad::SetOffset(const osg::Vec2f& offset) { m_offset = offset; UpdateGeometry(); } void Quad::SetSize(const osg::Vec2f& size) { m_size = size; UpdateGeometry(); } void Quad::SetRect(const osg::Vec2f& offset, const osg::Vec2f& size) { m_offset = offset; m_size = size; UpdateGeometry(); } void Quad::UpdateGeometry() { osg::Vec2Array* coord_array = dynamic_cast<osg::Vec2Array*>(m_geometry->getVertexAttribArray(0)); if (coord_array) { coord_array->at(0) = m_offset; coord_array->at(1) = m_offset + osg::Vec2f(m_size.x(), 0.0f); coord_array->at(2) = m_offset + osg::Vec2f(m_size.x(), m_size.y()); coord_array->at(3) = m_offset + osg::Vec2f(0.0f, m_size.y()); coord_array->dirty(); } } OSGWrapper::QuadAttributeUtilNode* Quad::Generate() { return m_node; } OSGWrapper::UIQuad* Quad::HitTest(float x, float y) { OSGWrapper::UIQuad* q = OSGWrapper::UIQuad::HitTest(x, y); if (q) return q; if (x >= m_offset.x() && x <= m_offset.x() + m_size.x() && y >= m_offset.y() && y <= m_offset.y() + m_size.y()) return this; return 0; }
6290623071614e1a5caf46e39ddc6e959b56f6cb
256767f888195384e8a91bff0864d0afc3f7e4e9
/AIS_TrackingAndDetection/tests/moc_euclideanDistance.cpp
8e8d5da02912f8bd3b87c8b1bc3d57a65875d708
[]
no_license
HelenHarman/AIS_Object_Tracking
a71b9c2df78c02180b7bb1ac2561a03a570ef935
3ec7128a739387299ac3e4a648e8c8f30274af97
refs/heads/master
2021-01-15T08:28:06.415775
2016-01-23T13:01:20
2016-01-23T13:01:20
43,375,968
1
0
null
null
null
null
UTF-8
C++
false
false
35
cpp
#include "moc_euclideanDistance.h"
160beafcd0375ee1abc289f6df9dc822b8749eb5
4b0a3fffa69840fac4fa77ba40f3aed8ae51442c
/FinalProject/workingfolder/Erin's Updates/bouncingcube/BouncingCube.h
a06731fe152c89b5848227598c4d455e34849b77
[]
no_license
hoffm386/graphics-final-project
732633bf55482051730e0087c025ab1d6e5253e7
584a16eda13572d6a92bad690da6b4a903eef084
refs/heads/master
2021-01-10T20:14:04.415740
2014-04-30T02:50:22
2014-04-30T02:50:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
725
h
// BouncingCube.h : main header file for the BouncingCube application // #pragma once #ifndef __AFXWIN_H__ #error "include 'stdafx.h' before including this file for PCH" #endif #include "resource.h" // main symbols // CBouncingCubeApp: // See BouncingCube.cpp for the implementation of this class // class CBouncingCubeApp : public CWinAppEx { public: CBouncingCubeApp(); // Overrides public: virtual BOOL InitInstance(); virtual int ExitInstance(); // Implementation public: UINT m_nAppLook; BOOL m_bHiColorIcons; virtual void PreLoadState(); virtual void LoadCustomState(); virtual void SaveCustomState(); afx_msg void OnAppAbout(); DECLARE_MESSAGE_MAP() }; extern CBouncingCubeApp theApp;
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; }
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****/
b563f5db9b84bcb6839aacebc6f4c582b248900b
424d9d65e27cd204cc22e39da3a13710b163f4e7
/chrome/browser/ui/views/frame/tab_strip_region_view.h
96ccf699770a115e0ce3985d40a4dc5a9fae614d
[ "BSD-3-Clause" ]
permissive
bigben0123/chromium
7c5f4624ef2dacfaf010203b60f307d4b8e8e76d
83d9cd5e98b65686d06368f18b4835adbab76d89
refs/heads/master
2023-01-10T11:02:26.202776
2020-10-30T09:47:16
2020-10-30T09:47:16
275,543,782
0
0
BSD-3-Clause
2020-10-30T09:47:18
2020-06-28T08:45:11
null
UTF-8
C++
false
false
2,458
h
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_VIEWS_FRAME_TAB_STRIP_REGION_VIEW_H_ #define CHROME_BROWSER_UI_VIEWS_FRAME_TAB_STRIP_REGION_VIEW_H_ #include "chrome/browser/ui/views/tabs/tab_strip.h" #include "ui/views/accessible_pane_view.h" class TabSearchButton; class TabStrip; // Container for the tabstrip, new tab button, and reserved grab handle space. class TabStripRegionView final : public views::AccessiblePaneView, views::ViewObserver { public: explicit TabStripRegionView(std::unique_ptr<TabStrip> tab_strip); ~TabStripRegionView() override; // Returns true if the specified rect intersects the window caption area of // the browser window. |rect| is in the local coordinate space // of |this|. bool IsRectInWindowCaption(const gfx::Rect& rect); // A convenience function which calls |IsRectInWindowCaption()| with a rect of // size 1x1 and an origin of |point|. |point| is in the local coordinate space // of |this|. bool IsPositionInWindowCaption(const gfx::Point& point); // Called when the colors of the frame change. void FrameColorsChanged(); TabSearchButton* tab_search_button() { return tab_search_button_; } // views::AccessiblePaneView: const char* GetClassName() const override; void ChildPreferredSizeChanged(views::View* child) override; gfx::Size GetMinimumSize() const override; void OnThemeChanged() override; void GetAccessibleNodeData(ui::AXNodeData* node_data) override; views::View* GetDefaultFocusableChild() override; // views::ViewObserver: void OnViewPreferredSizeChanged(View* view) override; // TODO(958173): Override OnBoundsChanged to cancel tabstrip animations. private: DISALLOW_COPY_AND_ASSIGN(TabStripRegionView); int CalculateTabStripAvailableWidth(); // Scrolls the tabstrip towards the first tab in the tabstrip. void ScrollTowardsLeadingTab(); // Scrolls the tabstrip towards the last tab in the tabstrip. void ScrollTowardsTrailingTab(); views::View* tab_strip_container_; views::View* reserved_grab_handle_space_; TabStrip* tab_strip_; TabSearchButton* tab_search_button_ = nullptr; views::ImageButton* leading_scroll_button_; views::ImageButton* trailing_scroll_button_; }; #endif // CHROME_BROWSER_UI_VIEWS_FRAME_TAB_STRIP_REGION_VIEW_H_
6a5800c8150e8c9144d23429c10f35136b06e222
578ceec075394968a5ac0ef3ed5961697d8cd826
/daemon/DekdCommand.h
7a1648ba3f971ea0a278f233a006d43f4fa34003
[]
no_license
olicmoon/dekd
3938a6f76cdb8b0a9ef915b273f94ac8fa9276d9
c5a88ec8330a67ce952351970bf5657813977eae
refs/heads/master
2021-01-19T06:24:54.282288
2015-08-31T21:17:06
2015-09-01T00:40:38
40,740,525
0
0
null
null
null
null
UTF-8
C++
false
false
365
h
/* * DekdCommand.h * * Created on: Aug 17, 2015 * Author: olic */ #ifndef DEKDCOMMAND_H_ #define DEKDCOMMAND_H_ #include <FrameworkCommand.h> class DekdCommand : public FrameworkCommand { public: DekdCommand(const char *cmd); virtual ~DekdCommand() {} int runCommand(SocketClient *c, int argc, char **argv); }; #endif /* DEKDCOMMAND_H_ */
378d41da667801b00bd623eb7fc43dcdb5cc28d6
2bd4fa284f4c891fa35b7465449ea04534ea01fb
/hdmaproifilter/src/perception/lib/base/registerer.cpp
6c5407d1b73c0605cbf0c3b88b4f854a302b290e
[]
no_license
Playfish/apollo_perception
cdd74e4a802159ceadc513e9f46ae1799e911ba1
6a50f529f0f6d789d2a06077480e79c9f4bc68c8
refs/heads/master
2021-09-14T13:42:07.159927
2018-05-14T13:51:20
2018-05-14T13:51:20
113,520,993
1
0
null
null
null
null
UTF-8
C++
false
false
1,536
cpp
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "perception/lib/base/registerer.h" #include <string> #include <vector> namespace apollo { namespace perception { BaseClassMap& GlobalFactoryMap() { static BaseClassMap factory_map; return factory_map; } bool GetRegisteredClasses( const std::string& base_class_name, std::vector<std::string>* registered_derived_classes_names) { CHECK_NOTNULL(registered_derived_classes_names); BaseClassMap& map = GlobalFactoryMap(); auto iter = map.find(base_class_name); if (iter == map.end()) { AERROR << "class not registered:" << base_class_name; return false; } for (auto pair : iter->second) { registered_derived_classes_names->push_back(pair.first); } return true; } } // namespace perception } // namespace apollo
55d577d1a75a9ab17fa7b5d2dfee420f67de653e
c4d0cc1b8f7a0c4eefb405e105ac9727e1a98aad
/FlashCards/src/StringWordSplitter.cpp
fdab3206d76415785a84cd483dcc64795aae68ce
[]
no_license
KNITcpp/FlashCards
513ed1f7fb2829692538636e0e6b65847bad8da9
7ac1c359d6a6f0aa5639bb64a39696b2f5eb63e2
refs/heads/master
2020-03-07T14:15:49.733326
2018-05-28T09:43:41
2018-05-28T09:43:41
127,522,390
0
0
null
null
null
null
UTF-8
C++
false
false
505
cpp
#include "StringWordSplitter.h" #include <string> #include <vector> StringWordSplitter::StringWordSplitter(std::wstring strToBeSplitted) { std::wstring singleWord; for(int i=0; i<strToBeSplitted.length(); ++i) { if(strToBeSplitted[i] == L' ') { if(singleWord.size()!=0) { words.push_back(singleWord); singleWord.clear(); } } else singleWord.push_back(strToBeSplitted[i]); } if(singleWord.size()!=0) //something left to push after loop words.push_back(singleWord); }
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; }