blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
c7914b7b26041b88df4a6ae27df10a64ecb777fc
3a0da4368b6874c297328025b381cb7c7e5233ee
/source/game/field.cpp
9cb440b17a1cfbdd0b22ae7448aa179401b02566
[]
no_license
Unlogicaly/MIPT_task2_memo
7bc173a544c13ead8d4d36af82874251194b944f
330f15ccff5e2dea8a547f49ff8fa801cf204e9a
refs/heads/master
2020-09-08T16:46:14.004445
2019-12-09T17:20:49
2019-12-09T17:20:49
221,187,355
0
0
null
2019-11-23T09:01:46
2019-11-12T10:09:23
null
UTF-8
C++
false
false
3,612
cpp
#include "field.h" #include <algorithm> #include <chrono> #include <random> // Generate shuffled range from 0 to max std::vector<int> rand_range(int max, long long seed = 0) { if (seed == 0) seed = std::chrono::system_clock::now().time_since_epoch().count(); std::vector<int> res(max); for (decltype(res.size()) i = 0; i < res.size(); ++i) { res[i] = static_cast<int>(i); } std::shuffle(res.begin(), res.end(), std::default_random_engine{seed}); return res; } Card *Field::get_card(int x, int y) { return cards[(x - get_side_gap()) / (get_size() + get_shift())][(y - get_up_gap()) / (get_size() + get_shift())]; } Field::Field(bool &_end, int x_resol, int y_resol) : myWin(_end, x_resol, y_resol), opened{nullptr, nullptr} { long long seed = std::chrono::system_clock::now().time_since_epoch().count(); myWin::color(Graph_lib::Color::white); std::vector<std::string> pictures; get_names(pictures); std::shuffle(pictures.begin(), pictures.end(), std::default_random_engine{seed}); std::vector<int> pairs = rand_range(get_height() * get_width(), seed); for (auto i = 0; i < get_width(); ++i) { cards.emplace_back(); for (auto j = 0; j < get_height(); ++j) cards[i].push_back(nullptr); } for (auto i = 0; i < get_height() * get_width(); i += 2) { int i1 = pairs[i] / get_width(), j1 = pairs[i] % get_width(); cards[j1][i1] = new Card(get_point(j1, i1), get_size(), get_pic(pictures[i / 2], get_size(), get_size()), cb_show); attach(*cards[j1][i1]); attach(*cards[j1][i1]->show); int i2 = pairs[i + 1] / get_width(), j2 = pairs[i + 1] % get_width(); cards[j2][i2] = new Card(get_point(j2, i2), get_size(), get_pic(pictures[i / 2], get_size(), get_size()), cb_show); attach(*cards[j2][i2]); attach(*cards[j2][i2]->show); } } void Field::treat_last(Card *last) { for (auto &lines : cards) { for (auto *card : lines) { if (!card->is_found and card != last) { card->is_found = true; last->is_found = true; card->show->hide(); last->show->hide(); card->click(); started = false; return; } } } } void Field::flip(Graph_lib::Address pwin) { Fl_Widget &w = Graph_lib::reference_to<Fl_Widget>(pwin); auto c = get_card(w.x(), w.y()); if (!opened.first) opened.first = c; else if (!opened.second) { if (opened.first == c) return; opened.second = c; } else { if (opened.first->get_name() == opened.second->get_name()) { opened.first->show->hide(); opened.second->show->hide(); opened.first->is_found = true; opened.second->is_found = true; ready++; if (c == opened.first or c == opened.second) { opened.first = nullptr; opened.second = nullptr; return; } } else { opened.first->click(); opened.second->click(); } opened.first = c; opened.second = nullptr; } c->click(); if (ready == get_height() * get_width() / 2 - 1) { treat_last(c); asc(); } Fl::redraw(); } Field::~Field() { for (auto &line : cards) for (auto *card : line) delete card; }
547d777962fb28b2c7f4e4c8ef43132d3e6a009a
c776476e9d06b3779d744641e758ac3a2c15cddc
/examples/litmus/c/run-scripts/tmp_5/WWC+poonceonce+ctrlonceonce+Release.c.cbmc.cpp
bab1de600e14ef3935676eed5dae25374028b0c9
[]
no_license
ashutosh0gupta/llvm_bmc
aaac7961c723ba6f7ffd77a39559e0e52432eade
0287c4fb180244e6b3c599a9902507f05c8a7234
refs/heads/master
2023-08-02T17:14:06.178723
2023-07-31T10:46:53
2023-07-31T10:46:53
143,100,825
3
4
null
2023-05-25T05:50:55
2018-08-01T03:47:00
C++
UTF-8
C++
false
false
35,227
cpp
// Global variabls: // 3:atom_2_X0_1:1 // 0:vars:2 // 2:atom_1_X0_2:1 // Local global variabls: // 0:thr0:1 // 1:thr1:1 // 2:thr2:1 #define ADDRSIZE 4 #define LOCALADDRSIZE 3 #define NTHREAD 4 #define NCONTEXT 5 #define ASSUME(stmt) __CPROVER_assume(stmt) #define ASSERT(stmt) __CPROVER_assert(stmt, "error") #define max(a,b) (a>b?a:b) char __get_rng(); char get_rng( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } char get_rng_th( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } int main(int argc, char **argv) { // Declare arrays for intial value version in contexts int local_mem[LOCALADDRSIZE]; // Dumping initializations local_mem[0+0] = 0; local_mem[1+0] = 0; local_mem[2+0] = 0; int cstart[NTHREAD]; int creturn[NTHREAD]; // declare arrays for contexts activity int active[NCONTEXT]; int ctx_used[NCONTEXT]; // declare arrays for intial value version in contexts int meminit_[ADDRSIZE*NCONTEXT]; #define meminit(x,k) meminit_[(x)*NCONTEXT+k] int coinit_[ADDRSIZE*NCONTEXT]; #define coinit(x,k) coinit_[(x)*NCONTEXT+k] int deltainit_[ADDRSIZE*NCONTEXT]; #define deltainit(x,k) deltainit_[(x)*NCONTEXT+k] // declare arrays for running value version in contexts int mem_[ADDRSIZE*NCONTEXT]; #define mem(x,k) mem_[(x)*NCONTEXT+k] int co_[ADDRSIZE*NCONTEXT]; #define co(x,k) co_[(x)*NCONTEXT+k] int delta_[ADDRSIZE*NCONTEXT]; #define delta(x,k) delta_[(x)*NCONTEXT+k] // declare arrays for local buffer and observed writes int buff_[NTHREAD*ADDRSIZE]; #define buff(x,k) buff_[(x)*ADDRSIZE+k] int pw_[NTHREAD*ADDRSIZE]; #define pw(x,k) pw_[(x)*ADDRSIZE+k] // declare arrays for context stamps char cr_[NTHREAD*ADDRSIZE]; #define cr(x,k) cr_[(x)*ADDRSIZE+k] char iw_[NTHREAD*ADDRSIZE]; #define iw(x,k) iw_[(x)*ADDRSIZE+k] char cw_[NTHREAD*ADDRSIZE]; #define cw(x,k) cw_[(x)*ADDRSIZE+k] char cx_[NTHREAD*ADDRSIZE]; #define cx(x,k) cx_[(x)*ADDRSIZE+k] char is_[NTHREAD*ADDRSIZE]; #define is(x,k) is_[(x)*ADDRSIZE+k] char cs_[NTHREAD*ADDRSIZE]; #define cs(x,k) cs_[(x)*ADDRSIZE+k] char crmax_[NTHREAD*ADDRSIZE]; #define crmax(x,k) crmax_[(x)*ADDRSIZE+k] char sforbid_[ADDRSIZE*NCONTEXT]; #define sforbid(x,k) sforbid_[(x)*NCONTEXT+k] // declare arrays for synchronizations int cl[NTHREAD]; int cdy[NTHREAD]; int cds[NTHREAD]; int cdl[NTHREAD]; int cisb[NTHREAD]; int caddr[NTHREAD]; int cctrl[NTHREAD]; __LOCALS__ buff(0,0) = 0; pw(0,0) = 0; cr(0,0) = 0; iw(0,0) = 0; cw(0,0) = 0; cx(0,0) = 0; is(0,0) = 0; cs(0,0) = 0; crmax(0,0) = 0; buff(0,1) = 0; pw(0,1) = 0; cr(0,1) = 0; iw(0,1) = 0; cw(0,1) = 0; cx(0,1) = 0; is(0,1) = 0; cs(0,1) = 0; crmax(0,1) = 0; buff(0,2) = 0; pw(0,2) = 0; cr(0,2) = 0; iw(0,2) = 0; cw(0,2) = 0; cx(0,2) = 0; is(0,2) = 0; cs(0,2) = 0; crmax(0,2) = 0; buff(0,3) = 0; pw(0,3) = 0; cr(0,3) = 0; iw(0,3) = 0; cw(0,3) = 0; cx(0,3) = 0; is(0,3) = 0; cs(0,3) = 0; crmax(0,3) = 0; cl[0] = 0; cdy[0] = 0; cds[0] = 0; cdl[0] = 0; cisb[0] = 0; caddr[0] = 0; cctrl[0] = 0; cstart[0] = get_rng(0,NCONTEXT-1); creturn[0] = get_rng(0,NCONTEXT-1); buff(1,0) = 0; pw(1,0) = 0; cr(1,0) = 0; iw(1,0) = 0; cw(1,0) = 0; cx(1,0) = 0; is(1,0) = 0; cs(1,0) = 0; crmax(1,0) = 0; buff(1,1) = 0; pw(1,1) = 0; cr(1,1) = 0; iw(1,1) = 0; cw(1,1) = 0; cx(1,1) = 0; is(1,1) = 0; cs(1,1) = 0; crmax(1,1) = 0; buff(1,2) = 0; pw(1,2) = 0; cr(1,2) = 0; iw(1,2) = 0; cw(1,2) = 0; cx(1,2) = 0; is(1,2) = 0; cs(1,2) = 0; crmax(1,2) = 0; buff(1,3) = 0; pw(1,3) = 0; cr(1,3) = 0; iw(1,3) = 0; cw(1,3) = 0; cx(1,3) = 0; is(1,3) = 0; cs(1,3) = 0; crmax(1,3) = 0; cl[1] = 0; cdy[1] = 0; cds[1] = 0; cdl[1] = 0; cisb[1] = 0; caddr[1] = 0; cctrl[1] = 0; cstart[1] = get_rng(0,NCONTEXT-1); creturn[1] = get_rng(0,NCONTEXT-1); buff(2,0) = 0; pw(2,0) = 0; cr(2,0) = 0; iw(2,0) = 0; cw(2,0) = 0; cx(2,0) = 0; is(2,0) = 0; cs(2,0) = 0; crmax(2,0) = 0; buff(2,1) = 0; pw(2,1) = 0; cr(2,1) = 0; iw(2,1) = 0; cw(2,1) = 0; cx(2,1) = 0; is(2,1) = 0; cs(2,1) = 0; crmax(2,1) = 0; buff(2,2) = 0; pw(2,2) = 0; cr(2,2) = 0; iw(2,2) = 0; cw(2,2) = 0; cx(2,2) = 0; is(2,2) = 0; cs(2,2) = 0; crmax(2,2) = 0; buff(2,3) = 0; pw(2,3) = 0; cr(2,3) = 0; iw(2,3) = 0; cw(2,3) = 0; cx(2,3) = 0; is(2,3) = 0; cs(2,3) = 0; crmax(2,3) = 0; cl[2] = 0; cdy[2] = 0; cds[2] = 0; cdl[2] = 0; cisb[2] = 0; caddr[2] = 0; cctrl[2] = 0; cstart[2] = get_rng(0,NCONTEXT-1); creturn[2] = get_rng(0,NCONTEXT-1); buff(3,0) = 0; pw(3,0) = 0; cr(3,0) = 0; iw(3,0) = 0; cw(3,0) = 0; cx(3,0) = 0; is(3,0) = 0; cs(3,0) = 0; crmax(3,0) = 0; buff(3,1) = 0; pw(3,1) = 0; cr(3,1) = 0; iw(3,1) = 0; cw(3,1) = 0; cx(3,1) = 0; is(3,1) = 0; cs(3,1) = 0; crmax(3,1) = 0; buff(3,2) = 0; pw(3,2) = 0; cr(3,2) = 0; iw(3,2) = 0; cw(3,2) = 0; cx(3,2) = 0; is(3,2) = 0; cs(3,2) = 0; crmax(3,2) = 0; buff(3,3) = 0; pw(3,3) = 0; cr(3,3) = 0; iw(3,3) = 0; cw(3,3) = 0; cx(3,3) = 0; is(3,3) = 0; cs(3,3) = 0; crmax(3,3) = 0; cl[3] = 0; cdy[3] = 0; cds[3] = 0; cdl[3] = 0; cisb[3] = 0; caddr[3] = 0; cctrl[3] = 0; cstart[3] = get_rng(0,NCONTEXT-1); creturn[3] = get_rng(0,NCONTEXT-1); // Dumping initializations mem(3+0,0) = 0; mem(0+0,0) = 0; mem(0+1,0) = 0; mem(2+0,0) = 0; // Dumping context matching equalities co(0,0) = 0; delta(0,0) = -1; mem(0,1) = meminit(0,1); co(0,1) = coinit(0,1); delta(0,1) = deltainit(0,1); mem(0,2) = meminit(0,2); co(0,2) = coinit(0,2); delta(0,2) = deltainit(0,2); mem(0,3) = meminit(0,3); co(0,3) = coinit(0,3); delta(0,3) = deltainit(0,3); mem(0,4) = meminit(0,4); co(0,4) = coinit(0,4); delta(0,4) = deltainit(0,4); co(1,0) = 0; delta(1,0) = -1; mem(1,1) = meminit(1,1); co(1,1) = coinit(1,1); delta(1,1) = deltainit(1,1); mem(1,2) = meminit(1,2); co(1,2) = coinit(1,2); delta(1,2) = deltainit(1,2); mem(1,3) = meminit(1,3); co(1,3) = coinit(1,3); delta(1,3) = deltainit(1,3); mem(1,4) = meminit(1,4); co(1,4) = coinit(1,4); delta(1,4) = deltainit(1,4); co(2,0) = 0; delta(2,0) = -1; mem(2,1) = meminit(2,1); co(2,1) = coinit(2,1); delta(2,1) = deltainit(2,1); mem(2,2) = meminit(2,2); co(2,2) = coinit(2,2); delta(2,2) = deltainit(2,2); mem(2,3) = meminit(2,3); co(2,3) = coinit(2,3); delta(2,3) = deltainit(2,3); mem(2,4) = meminit(2,4); co(2,4) = coinit(2,4); delta(2,4) = deltainit(2,4); co(3,0) = 0; delta(3,0) = -1; mem(3,1) = meminit(3,1); co(3,1) = coinit(3,1); delta(3,1) = deltainit(3,1); mem(3,2) = meminit(3,2); co(3,2) = coinit(3,2); delta(3,2) = deltainit(3,2); mem(3,3) = meminit(3,3); co(3,3) = coinit(3,3); delta(3,3) = deltainit(3,3); mem(3,4) = meminit(3,4); co(3,4) = coinit(3,4); delta(3,4) = deltainit(3,4); // Dumping thread 1 int ret_thread_1 = 0; cdy[1] = get_rng(0,NCONTEXT-1); ASSUME(cdy[1] >= cstart[1]); T1BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !36, metadata !DIExpression()), !dbg !42 // br label %label_1, !dbg !43 goto T1BLOCK1; T1BLOCK1: // call void @llvm.dbg.label(metadata !41), !dbg !44 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !37, metadata !DIExpression()), !dbg !45 // call void @llvm.dbg.value(metadata i64 2, metadata !40, metadata !DIExpression()), !dbg !45 // store atomic i64 2, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) release, align 8, !dbg !46 // ST: Guess // : Release iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l20_c3 old_cw = cw(1,0); cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l20_c3 // Check ASSUME(active[iw(1,0)] == 1); ASSUME(active[cw(1,0)] == 1); ASSUME(sforbid(0,cw(1,0))== 0); ASSUME(iw(1,0) >= 0); ASSUME(iw(1,0) >= 0); ASSUME(cw(1,0) >= iw(1,0)); ASSUME(cw(1,0) >= old_cw); ASSUME(cw(1,0) >= cr(1,0)); ASSUME(cw(1,0) >= cl[1]); ASSUME(cw(1,0) >= cisb[1]); ASSUME(cw(1,0) >= cdy[1]); ASSUME(cw(1,0) >= cdl[1]); ASSUME(cw(1,0) >= cds[1]); ASSUME(cw(1,0) >= cctrl[1]); ASSUME(cw(1,0) >= caddr[1]); ASSUME(cw(1,0) >= cr(1,3+0)); ASSUME(cw(1,0) >= cr(1,0+0)); ASSUME(cw(1,0) >= cr(1,0+1)); ASSUME(cw(1,0) >= cr(1,2+0)); ASSUME(cw(1,0) >= cw(1,3+0)); ASSUME(cw(1,0) >= cw(1,0+0)); ASSUME(cw(1,0) >= cw(1,0+1)); ASSUME(cw(1,0) >= cw(1,2+0)); // Update caddr[1] = max(caddr[1],0); buff(1,0) = 2; mem(0,cw(1,0)) = 2; co(0,cw(1,0))+=1; delta(0,cw(1,0)) = -1; is(1,0) = iw(1,0); cs(1,0) = cw(1,0); ASSUME(creturn[1] >= cw(1,0)); // ret i8* null, !dbg !47 ret_thread_1 = (- 1); goto T1BLOCK_END; T1BLOCK_END: // Dumping thread 2 int ret_thread_2 = 0; cdy[2] = get_rng(0,NCONTEXT-1); ASSUME(cdy[2] >= cstart[2]); T2BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !50, metadata !DIExpression()), !dbg !60 // br label %label_2, !dbg !48 goto T2BLOCK1; T2BLOCK1: // call void @llvm.dbg.label(metadata !59), !dbg !62 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !52, metadata !DIExpression()), !dbg !63 // %0 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !51 // LD: Guess old_cr = cr(2,0); cr(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM _l26_c15 // Check ASSUME(active[cr(2,0)] == 2); ASSUME(cr(2,0) >= iw(2,0)); ASSUME(cr(2,0) >= 0); ASSUME(cr(2,0) >= cdy[2]); ASSUME(cr(2,0) >= cisb[2]); ASSUME(cr(2,0) >= cdl[2]); ASSUME(cr(2,0) >= cl[2]); // Update creg_r0 = cr(2,0); crmax(2,0) = max(crmax(2,0),cr(2,0)); caddr[2] = max(caddr[2],0); if(cr(2,0) < cw(2,0)) { r0 = buff(2,0); ASSUME((!(( (cw(2,0) < 1) && (1 < crmax(2,0)) )))||(sforbid(0,1)> 0)); ASSUME((!(( (cw(2,0) < 2) && (2 < crmax(2,0)) )))||(sforbid(0,2)> 0)); ASSUME((!(( (cw(2,0) < 3) && (3 < crmax(2,0)) )))||(sforbid(0,3)> 0)); ASSUME((!(( (cw(2,0) < 4) && (4 < crmax(2,0)) )))||(sforbid(0,4)> 0)); } else { if(pw(2,0) != co(0,cr(2,0))) { ASSUME(cr(2,0) >= old_cr); } pw(2,0) = co(0,cr(2,0)); r0 = mem(0,cr(2,0)); } ASSUME(creturn[2] >= cr(2,0)); // call void @llvm.dbg.value(metadata i64 %0, metadata !54, metadata !DIExpression()), !dbg !63 // %conv = trunc i64 %0 to i32, !dbg !52 // call void @llvm.dbg.value(metadata i32 %conv, metadata !51, metadata !DIExpression()), !dbg !60 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !55, metadata !DIExpression()), !dbg !66 // call void @llvm.dbg.value(metadata i64 1, metadata !57, metadata !DIExpression()), !dbg !66 // store atomic i64 1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !54 // ST: Guess iw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l27_c3 old_cw = cw(2,0+1*1); cw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l27_c3 // Check ASSUME(active[iw(2,0+1*1)] == 2); ASSUME(active[cw(2,0+1*1)] == 2); ASSUME(sforbid(0+1*1,cw(2,0+1*1))== 0); ASSUME(iw(2,0+1*1) >= 0); ASSUME(iw(2,0+1*1) >= 0); ASSUME(cw(2,0+1*1) >= iw(2,0+1*1)); ASSUME(cw(2,0+1*1) >= old_cw); ASSUME(cw(2,0+1*1) >= cr(2,0+1*1)); ASSUME(cw(2,0+1*1) >= cl[2]); ASSUME(cw(2,0+1*1) >= cisb[2]); ASSUME(cw(2,0+1*1) >= cdy[2]); ASSUME(cw(2,0+1*1) >= cdl[2]); ASSUME(cw(2,0+1*1) >= cds[2]); ASSUME(cw(2,0+1*1) >= cctrl[2]); ASSUME(cw(2,0+1*1) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,0+1*1) = 1; mem(0+1*1,cw(2,0+1*1)) = 1; co(0+1*1,cw(2,0+1*1))+=1; delta(0+1*1,cw(2,0+1*1)) = -1; ASSUME(creturn[2] >= cw(2,0+1*1)); // %cmp = icmp eq i32 %conv, 2, !dbg !55 creg__r0__2_ = max(0,creg_r0); // %conv1 = zext i1 %cmp to i32, !dbg !55 // call void @llvm.dbg.value(metadata i32 %conv1, metadata !58, metadata !DIExpression()), !dbg !60 // store i32 %conv1, i32* @atom_1_X0_2, align 4, !dbg !56, !tbaa !57 // ST: Guess iw(2,2) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l29_c15 old_cw = cw(2,2); cw(2,2) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l29_c15 // Check ASSUME(active[iw(2,2)] == 2); ASSUME(active[cw(2,2)] == 2); ASSUME(sforbid(2,cw(2,2))== 0); ASSUME(iw(2,2) >= creg__r0__2_); ASSUME(iw(2,2) >= 0); ASSUME(cw(2,2) >= iw(2,2)); ASSUME(cw(2,2) >= old_cw); ASSUME(cw(2,2) >= cr(2,2)); ASSUME(cw(2,2) >= cl[2]); ASSUME(cw(2,2) >= cisb[2]); ASSUME(cw(2,2) >= cdy[2]); ASSUME(cw(2,2) >= cdl[2]); ASSUME(cw(2,2) >= cds[2]); ASSUME(cw(2,2) >= cctrl[2]); ASSUME(cw(2,2) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,2) = (r0==2); mem(2,cw(2,2)) = (r0==2); co(2,cw(2,2))+=1; delta(2,cw(2,2)) = -1; ASSUME(creturn[2] >= cw(2,2)); // ret i8* null, !dbg !61 ret_thread_2 = (- 1); goto T2BLOCK_END; T2BLOCK_END: // Dumping thread 3 int ret_thread_3 = 0; cdy[3] = get_rng(0,NCONTEXT-1); ASSUME(cdy[3] >= cstart[3]); T3BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !77, metadata !DIExpression()), !dbg !89 // br label %label_3, !dbg !50 goto T3BLOCK1; T3BLOCK1: // call void @llvm.dbg.label(metadata !87), !dbg !91 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !79, metadata !DIExpression()), !dbg !92 // %0 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !53 // LD: Guess old_cr = cr(3,0+1*1); cr(3,0+1*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM _l35_c15 // Check ASSUME(active[cr(3,0+1*1)] == 3); ASSUME(cr(3,0+1*1) >= iw(3,0+1*1)); ASSUME(cr(3,0+1*1) >= 0); ASSUME(cr(3,0+1*1) >= cdy[3]); ASSUME(cr(3,0+1*1) >= cisb[3]); ASSUME(cr(3,0+1*1) >= cdl[3]); ASSUME(cr(3,0+1*1) >= cl[3]); // Update creg_r1 = cr(3,0+1*1); crmax(3,0+1*1) = max(crmax(3,0+1*1),cr(3,0+1*1)); caddr[3] = max(caddr[3],0); if(cr(3,0+1*1) < cw(3,0+1*1)) { r1 = buff(3,0+1*1); ASSUME((!(( (cw(3,0+1*1) < 1) && (1 < crmax(3,0+1*1)) )))||(sforbid(0+1*1,1)> 0)); ASSUME((!(( (cw(3,0+1*1) < 2) && (2 < crmax(3,0+1*1)) )))||(sforbid(0+1*1,2)> 0)); ASSUME((!(( (cw(3,0+1*1) < 3) && (3 < crmax(3,0+1*1)) )))||(sforbid(0+1*1,3)> 0)); ASSUME((!(( (cw(3,0+1*1) < 4) && (4 < crmax(3,0+1*1)) )))||(sforbid(0+1*1,4)> 0)); } else { if(pw(3,0+1*1) != co(0+1*1,cr(3,0+1*1))) { ASSUME(cr(3,0+1*1) >= old_cr); } pw(3,0+1*1) = co(0+1*1,cr(3,0+1*1)); r1 = mem(0+1*1,cr(3,0+1*1)); } ASSUME(creturn[3] >= cr(3,0+1*1)); // call void @llvm.dbg.value(metadata i64 %0, metadata !81, metadata !DIExpression()), !dbg !92 // %conv = trunc i64 %0 to i32, !dbg !54 // call void @llvm.dbg.value(metadata i32 %conv, metadata !78, metadata !DIExpression()), !dbg !89 // %cmp = icmp eq i32 %conv, 0, !dbg !55 creg__r1__0_ = max(0,creg_r1); // %conv1 = zext i1 %cmp to i32, !dbg !55 // call void @llvm.dbg.value(metadata i32 %conv1, metadata !82, metadata !DIExpression()), !dbg !89 // %tobool = icmp ne i32 %conv1, 0, !dbg !56 creg___r1__0___0_ = max(0,creg__r1__0_); // br i1 %tobool, label %if.then, label %if.else, !dbg !58 old_cctrl = cctrl[3]; cctrl[3] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[3] >= old_cctrl); ASSUME(cctrl[3] >= creg___r1__0___0_); if(((r1==0)!=0)) { goto T3BLOCK2; } else { goto T3BLOCK3; } T3BLOCK2: // br label %lbl_label195, !dbg !59 goto T3BLOCK4; T3BLOCK3: // br label %lbl_label195, !dbg !60 goto T3BLOCK4; T3BLOCK4: // call void @llvm.dbg.label(metadata !88), !dbg !101 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !83, metadata !DIExpression()), !dbg !102 // call void @llvm.dbg.value(metadata i64 1, metadata !85, metadata !DIExpression()), !dbg !102 // store atomic i64 1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !63 // ST: Guess iw(3,0) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW _l39_c3 old_cw = cw(3,0); cw(3,0) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM _l39_c3 // Check ASSUME(active[iw(3,0)] == 3); ASSUME(active[cw(3,0)] == 3); ASSUME(sforbid(0,cw(3,0))== 0); ASSUME(iw(3,0) >= 0); ASSUME(iw(3,0) >= 0); ASSUME(cw(3,0) >= iw(3,0)); ASSUME(cw(3,0) >= old_cw); ASSUME(cw(3,0) >= cr(3,0)); ASSUME(cw(3,0) >= cl[3]); ASSUME(cw(3,0) >= cisb[3]); ASSUME(cw(3,0) >= cdy[3]); ASSUME(cw(3,0) >= cdl[3]); ASSUME(cw(3,0) >= cds[3]); ASSUME(cw(3,0) >= cctrl[3]); ASSUME(cw(3,0) >= caddr[3]); // Update caddr[3] = max(caddr[3],0); buff(3,0) = 1; mem(0,cw(3,0)) = 1; co(0,cw(3,0))+=1; delta(0,cw(3,0)) = -1; ASSUME(creturn[3] >= cw(3,0)); // %cmp2 = icmp eq i32 %conv, 1, !dbg !64 creg__r1__1_ = max(0,creg_r1); // %conv3 = zext i1 %cmp2 to i32, !dbg !64 // call void @llvm.dbg.value(metadata i32 %conv3, metadata !86, metadata !DIExpression()), !dbg !89 // store i32 %conv3, i32* @atom_2_X0_1, align 4, !dbg !65, !tbaa !66 // ST: Guess iw(3,3) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW _l41_c15 old_cw = cw(3,3); cw(3,3) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM _l41_c15 // Check ASSUME(active[iw(3,3)] == 3); ASSUME(active[cw(3,3)] == 3); ASSUME(sforbid(3,cw(3,3))== 0); ASSUME(iw(3,3) >= creg__r1__1_); ASSUME(iw(3,3) >= 0); ASSUME(cw(3,3) >= iw(3,3)); ASSUME(cw(3,3) >= old_cw); ASSUME(cw(3,3) >= cr(3,3)); ASSUME(cw(3,3) >= cl[3]); ASSUME(cw(3,3) >= cisb[3]); ASSUME(cw(3,3) >= cdy[3]); ASSUME(cw(3,3) >= cdl[3]); ASSUME(cw(3,3) >= cds[3]); ASSUME(cw(3,3) >= cctrl[3]); ASSUME(cw(3,3) >= caddr[3]); // Update caddr[3] = max(caddr[3],0); buff(3,3) = (r1==1); mem(3,cw(3,3)) = (r1==1); co(3,cw(3,3))+=1; delta(3,cw(3,3)) = -1; ASSUME(creturn[3] >= cw(3,3)); // ret i8* null, !dbg !70 ret_thread_3 = (- 1); goto T3BLOCK_END; T3BLOCK_END: // Dumping thread 0 int ret_thread_0 = 0; cdy[0] = get_rng(0,NCONTEXT-1); ASSUME(cdy[0] >= cstart[0]); T0BLOCK0: // %thr0 = alloca i64, align 8 // %thr1 = alloca i64, align 8 // %thr2 = alloca i64, align 8 // call void @llvm.dbg.value(metadata i32 %argc, metadata !114, metadata !DIExpression()), !dbg !137 // call void @llvm.dbg.value(metadata i8** %argv, metadata !115, metadata !DIExpression()), !dbg !137 // %0 = bitcast i64* %thr0 to i8*, !dbg !64 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !64 // call void @llvm.dbg.declare(metadata i64* %thr0, metadata !116, metadata !DIExpression()), !dbg !139 // %1 = bitcast i64* %thr1 to i8*, !dbg !66 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !66 // call void @llvm.dbg.declare(metadata i64* %thr1, metadata !120, metadata !DIExpression()), !dbg !141 // %2 = bitcast i64* %thr2 to i8*, !dbg !68 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !68 // call void @llvm.dbg.declare(metadata i64* %thr2, metadata !121, metadata !DIExpression()), !dbg !143 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !122, metadata !DIExpression()), !dbg !144 // call void @llvm.dbg.value(metadata i64 0, metadata !124, metadata !DIExpression()), !dbg !144 // store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !71 // ST: Guess iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l50_c3 old_cw = cw(0,0+1*1); cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l50_c3 // Check ASSUME(active[iw(0,0+1*1)] == 0); ASSUME(active[cw(0,0+1*1)] == 0); ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(cw(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cw(0,0+1*1) >= old_cw); ASSUME(cw(0,0+1*1) >= cr(0,0+1*1)); ASSUME(cw(0,0+1*1) >= cl[0]); ASSUME(cw(0,0+1*1) >= cisb[0]); ASSUME(cw(0,0+1*1) >= cdy[0]); ASSUME(cw(0,0+1*1) >= cdl[0]); ASSUME(cw(0,0+1*1) >= cds[0]); ASSUME(cw(0,0+1*1) >= cctrl[0]); ASSUME(cw(0,0+1*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+1*1) = 0; mem(0+1*1,cw(0,0+1*1)) = 0; co(0+1*1,cw(0,0+1*1))+=1; delta(0+1*1,cw(0,0+1*1)) = -1; ASSUME(creturn[0] >= cw(0,0+1*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !125, metadata !DIExpression()), !dbg !146 // call void @llvm.dbg.value(metadata i64 0, metadata !127, metadata !DIExpression()), !dbg !146 // store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !73 // ST: Guess iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l51_c3 old_cw = cw(0,0); cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l51_c3 // Check ASSUME(active[iw(0,0)] == 0); ASSUME(active[cw(0,0)] == 0); ASSUME(sforbid(0,cw(0,0))== 0); ASSUME(iw(0,0) >= 0); ASSUME(iw(0,0) >= 0); ASSUME(cw(0,0) >= iw(0,0)); ASSUME(cw(0,0) >= old_cw); ASSUME(cw(0,0) >= cr(0,0)); ASSUME(cw(0,0) >= cl[0]); ASSUME(cw(0,0) >= cisb[0]); ASSUME(cw(0,0) >= cdy[0]); ASSUME(cw(0,0) >= cdl[0]); ASSUME(cw(0,0) >= cds[0]); ASSUME(cw(0,0) >= cctrl[0]); ASSUME(cw(0,0) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0) = 0; mem(0,cw(0,0)) = 0; co(0,cw(0,0))+=1; delta(0,cw(0,0)) = -1; ASSUME(creturn[0] >= cw(0,0)); // store i32 0, i32* @atom_1_X0_2, align 4, !dbg !74, !tbaa !75 // ST: Guess iw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l52_c15 old_cw = cw(0,2); cw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l52_c15 // Check ASSUME(active[iw(0,2)] == 0); ASSUME(active[cw(0,2)] == 0); ASSUME(sforbid(2,cw(0,2))== 0); ASSUME(iw(0,2) >= 0); ASSUME(iw(0,2) >= 0); ASSUME(cw(0,2) >= iw(0,2)); ASSUME(cw(0,2) >= old_cw); ASSUME(cw(0,2) >= cr(0,2)); ASSUME(cw(0,2) >= cl[0]); ASSUME(cw(0,2) >= cisb[0]); ASSUME(cw(0,2) >= cdy[0]); ASSUME(cw(0,2) >= cdl[0]); ASSUME(cw(0,2) >= cds[0]); ASSUME(cw(0,2) >= cctrl[0]); ASSUME(cw(0,2) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,2) = 0; mem(2,cw(0,2)) = 0; co(2,cw(0,2))+=1; delta(2,cw(0,2)) = -1; ASSUME(creturn[0] >= cw(0,2)); // store i32 0, i32* @atom_2_X0_1, align 4, !dbg !79, !tbaa !75 // ST: Guess iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l53_c15 old_cw = cw(0,3); cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l53_c15 // Check ASSUME(active[iw(0,3)] == 0); ASSUME(active[cw(0,3)] == 0); ASSUME(sforbid(3,cw(0,3))== 0); ASSUME(iw(0,3) >= 0); ASSUME(iw(0,3) >= 0); ASSUME(cw(0,3) >= iw(0,3)); ASSUME(cw(0,3) >= old_cw); ASSUME(cw(0,3) >= cr(0,3)); ASSUME(cw(0,3) >= cl[0]); ASSUME(cw(0,3) >= cisb[0]); ASSUME(cw(0,3) >= cdy[0]); ASSUME(cw(0,3) >= cdl[0]); ASSUME(cw(0,3) >= cds[0]); ASSUME(cw(0,3) >= cctrl[0]); ASSUME(cw(0,3) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,3) = 0; mem(3,cw(0,3)) = 0; co(3,cw(0,3))+=1; delta(3,cw(0,3)) = -1; ASSUME(creturn[0] >= cw(0,3)); // %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !80 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,2+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,2+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[1] >= cdy[0]); // %call3 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !81 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,2+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,2+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[2] >= cdy[0]); // %call4 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !82 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,2+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,2+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[3] >= cdy[0]); // %3 = load i64, i64* %thr0, align 8, !dbg !83, !tbaa !84 r3 = local_mem[0]; // %call5 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !86 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,2+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,2+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[1]); // %4 = load i64, i64* %thr1, align 8, !dbg !87, !tbaa !84 r4 = local_mem[1]; // %call6 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !88 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,2+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,2+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[2]); // %5 = load i64, i64* %thr2, align 8, !dbg !89, !tbaa !84 r5 = local_mem[2]; // %call7 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !90 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,2+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,2+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[3]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !129, metadata !DIExpression()), !dbg !161 // %6 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !92 // LD: Guess old_cr = cr(0,0); cr(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l63_c12 // Check ASSUME(active[cr(0,0)] == 0); ASSUME(cr(0,0) >= iw(0,0)); ASSUME(cr(0,0) >= 0); ASSUME(cr(0,0) >= cdy[0]); ASSUME(cr(0,0) >= cisb[0]); ASSUME(cr(0,0) >= cdl[0]); ASSUME(cr(0,0) >= cl[0]); // Update creg_r6 = cr(0,0); crmax(0,0) = max(crmax(0,0),cr(0,0)); caddr[0] = max(caddr[0],0); if(cr(0,0) < cw(0,0)) { r6 = buff(0,0); ASSUME((!(( (cw(0,0) < 1) && (1 < crmax(0,0)) )))||(sforbid(0,1)> 0)); ASSUME((!(( (cw(0,0) < 2) && (2 < crmax(0,0)) )))||(sforbid(0,2)> 0)); ASSUME((!(( (cw(0,0) < 3) && (3 < crmax(0,0)) )))||(sforbid(0,3)> 0)); ASSUME((!(( (cw(0,0) < 4) && (4 < crmax(0,0)) )))||(sforbid(0,4)> 0)); } else { if(pw(0,0) != co(0,cr(0,0))) { ASSUME(cr(0,0) >= old_cr); } pw(0,0) = co(0,cr(0,0)); r6 = mem(0,cr(0,0)); } ASSUME(creturn[0] >= cr(0,0)); // call void @llvm.dbg.value(metadata i64 %6, metadata !131, metadata !DIExpression()), !dbg !161 // %conv = trunc i64 %6 to i32, !dbg !93 // call void @llvm.dbg.value(metadata i32 %conv, metadata !128, metadata !DIExpression()), !dbg !137 // %cmp = icmp eq i32 %conv, 2, !dbg !94 creg__r6__2_ = max(0,creg_r6); // %conv8 = zext i1 %cmp to i32, !dbg !94 // call void @llvm.dbg.value(metadata i32 %conv8, metadata !132, metadata !DIExpression()), !dbg !137 // %7 = load i32, i32* @atom_1_X0_2, align 4, !dbg !95, !tbaa !75 // LD: Guess old_cr = cr(0,2); cr(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l65_c13 // Check ASSUME(active[cr(0,2)] == 0); ASSUME(cr(0,2) >= iw(0,2)); ASSUME(cr(0,2) >= 0); ASSUME(cr(0,2) >= cdy[0]); ASSUME(cr(0,2) >= cisb[0]); ASSUME(cr(0,2) >= cdl[0]); ASSUME(cr(0,2) >= cl[0]); // Update creg_r7 = cr(0,2); crmax(0,2) = max(crmax(0,2),cr(0,2)); caddr[0] = max(caddr[0],0); if(cr(0,2) < cw(0,2)) { r7 = buff(0,2); ASSUME((!(( (cw(0,2) < 1) && (1 < crmax(0,2)) )))||(sforbid(2,1)> 0)); ASSUME((!(( (cw(0,2) < 2) && (2 < crmax(0,2)) )))||(sforbid(2,2)> 0)); ASSUME((!(( (cw(0,2) < 3) && (3 < crmax(0,2)) )))||(sforbid(2,3)> 0)); ASSUME((!(( (cw(0,2) < 4) && (4 < crmax(0,2)) )))||(sforbid(2,4)> 0)); } else { if(pw(0,2) != co(2,cr(0,2))) { ASSUME(cr(0,2) >= old_cr); } pw(0,2) = co(2,cr(0,2)); r7 = mem(2,cr(0,2)); } ASSUME(creturn[0] >= cr(0,2)); // call void @llvm.dbg.value(metadata i32 %7, metadata !133, metadata !DIExpression()), !dbg !137 // %8 = load i32, i32* @atom_2_X0_1, align 4, !dbg !96, !tbaa !75 // LD: Guess old_cr = cr(0,3); cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l66_c13 // Check ASSUME(active[cr(0,3)] == 0); ASSUME(cr(0,3) >= iw(0,3)); ASSUME(cr(0,3) >= 0); ASSUME(cr(0,3) >= cdy[0]); ASSUME(cr(0,3) >= cisb[0]); ASSUME(cr(0,3) >= cdl[0]); ASSUME(cr(0,3) >= cl[0]); // Update creg_r8 = cr(0,3); crmax(0,3) = max(crmax(0,3),cr(0,3)); caddr[0] = max(caddr[0],0); if(cr(0,3) < cw(0,3)) { r8 = buff(0,3); ASSUME((!(( (cw(0,3) < 1) && (1 < crmax(0,3)) )))||(sforbid(3,1)> 0)); ASSUME((!(( (cw(0,3) < 2) && (2 < crmax(0,3)) )))||(sforbid(3,2)> 0)); ASSUME((!(( (cw(0,3) < 3) && (3 < crmax(0,3)) )))||(sforbid(3,3)> 0)); ASSUME((!(( (cw(0,3) < 4) && (4 < crmax(0,3)) )))||(sforbid(3,4)> 0)); } else { if(pw(0,3) != co(3,cr(0,3))) { ASSUME(cr(0,3) >= old_cr); } pw(0,3) = co(3,cr(0,3)); r8 = mem(3,cr(0,3)); } ASSUME(creturn[0] >= cr(0,3)); // call void @llvm.dbg.value(metadata i32 %8, metadata !134, metadata !DIExpression()), !dbg !137 // %and = and i32 %7, %8, !dbg !97 creg_r9 = max(creg_r7,creg_r8); r9 = r7 & r8; // call void @llvm.dbg.value(metadata i32 %and, metadata !135, metadata !DIExpression()), !dbg !137 // %and9 = and i32 %conv8, %and, !dbg !98 creg_r10 = max(creg__r6__2_,creg_r9); r10 = (r6==2) & r9; // call void @llvm.dbg.value(metadata i32 %and9, metadata !136, metadata !DIExpression()), !dbg !137 // %cmp10 = icmp eq i32 %and9, 1, !dbg !99 creg__r10__1_ = max(0,creg_r10); // br i1 %cmp10, label %if.then, label %if.end, !dbg !101 old_cctrl = cctrl[0]; cctrl[0] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[0] >= old_cctrl); ASSUME(cctrl[0] >= creg__r10__1_); if((r10==1)) { goto T0BLOCK1; } else { goto T0BLOCK2; } T0BLOCK1: // call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([120 x i8], [120 x i8]* @.str.1, i64 0, i64 0), i32 noundef 69, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !102 // unreachable, !dbg !102 r11 = 1; goto T0BLOCK_END; T0BLOCK2: // %9 = bitcast i64* %thr2 to i8*, !dbg !105 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %9) #7, !dbg !105 // %10 = bitcast i64* %thr1 to i8*, !dbg !105 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %10) #7, !dbg !105 // %11 = bitcast i64* %thr0 to i8*, !dbg !105 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %11) #7, !dbg !105 // ret i32 0, !dbg !106 ret_thread_0 = 0; goto T0BLOCK_END; T0BLOCK_END: ASSUME(meminit(0,1) == mem(0,0)); ASSUME(coinit(0,1) == co(0,0)); ASSUME(deltainit(0,1) == delta(0,0)); ASSUME(meminit(0,2) == mem(0,1)); ASSUME(coinit(0,2) == co(0,1)); ASSUME(deltainit(0,2) == delta(0,1)); ASSUME(meminit(0,3) == mem(0,2)); ASSUME(coinit(0,3) == co(0,2)); ASSUME(deltainit(0,3) == delta(0,2)); ASSUME(meminit(0,4) == mem(0,3)); ASSUME(coinit(0,4) == co(0,3)); ASSUME(deltainit(0,4) == delta(0,3)); ASSUME(meminit(1,1) == mem(1,0)); ASSUME(coinit(1,1) == co(1,0)); ASSUME(deltainit(1,1) == delta(1,0)); ASSUME(meminit(1,2) == mem(1,1)); ASSUME(coinit(1,2) == co(1,1)); ASSUME(deltainit(1,2) == delta(1,1)); ASSUME(meminit(1,3) == mem(1,2)); ASSUME(coinit(1,3) == co(1,2)); ASSUME(deltainit(1,3) == delta(1,2)); ASSUME(meminit(1,4) == mem(1,3)); ASSUME(coinit(1,4) == co(1,3)); ASSUME(deltainit(1,4) == delta(1,3)); ASSUME(meminit(2,1) == mem(2,0)); ASSUME(coinit(2,1) == co(2,0)); ASSUME(deltainit(2,1) == delta(2,0)); ASSUME(meminit(2,2) == mem(2,1)); ASSUME(coinit(2,2) == co(2,1)); ASSUME(deltainit(2,2) == delta(2,1)); ASSUME(meminit(2,3) == mem(2,2)); ASSUME(coinit(2,3) == co(2,2)); ASSUME(deltainit(2,3) == delta(2,2)); ASSUME(meminit(2,4) == mem(2,3)); ASSUME(coinit(2,4) == co(2,3)); ASSUME(deltainit(2,4) == delta(2,3)); ASSUME(meminit(3,1) == mem(3,0)); ASSUME(coinit(3,1) == co(3,0)); ASSUME(deltainit(3,1) == delta(3,0)); ASSUME(meminit(3,2) == mem(3,1)); ASSUME(coinit(3,2) == co(3,1)); ASSUME(deltainit(3,2) == delta(3,1)); ASSUME(meminit(3,3) == mem(3,2)); ASSUME(coinit(3,3) == co(3,2)); ASSUME(deltainit(3,3) == delta(3,2)); ASSUME(meminit(3,4) == mem(3,3)); ASSUME(coinit(3,4) == co(3,3)); ASSUME(deltainit(3,4) == delta(3,3)); ASSERT(r11== 0); }
1bac8385ea203fe822b832a79335a9dddd6c7b47
944acde16ef16cb39caa55b8f93decd290407e7e
/main.cpp
18acb18b2d2ef87fdb50de3a8ab36ca00ea5e7d9
[]
no_license
mfg637/extended_numbers_x128
8c55832316faf15a99f6707ad8eb49b4a356fd0f
b562587d2493920ecdca3d12baed4ef845c2265f
refs/heads/master
2020-07-26T19:49:42.665923
2019-12-22T21:01:13
2019-12-22T21:01:13
208,749,731
0
0
null
null
null
null
UTF-8
C++
false
false
3,643
cpp
#include <iostream> #include <fstream> #include <random> #include "src/deserialisation.h" #include "src/int/UInt128.h" #include "src/int/Int128.h" int main(int argc, char **argv) { std::ifstream test("test.bin"); if (test.is_open()){ ExtNumsArray a = deserialize(test); std::cout << a.array_size << ' '; //IExtNums& sum = *(new Int128(0, 0)); Int128 sum(0, 0); Int128 incr(0, 1); for (unsigned i = 0; i<a.array_size; i++){ IExtNums* current_elem = a.array[i]; IExtNums* prev_value = current_elem; current_elem = &((*prev_value) + incr); delete prev_value; current_elem->text_out(std::cout); sum = (Int128&)((IExtNums&)(sum) + *current_elem); std::cout << ' '; } std::cout << std::endl << "sum of array elems: "; sum.text_out(std::cout); std::cout << std::endl; test.close(); delete [] a.array; } std::cout << "Hello world!" << std::endl; //overflow test UInt128 a(0, 0xffffffffffffffff); std::cout << "a = " << a << std::endl; UInt128 b(0, 2); std::cout << "b = " << b << std::endl; UInt128 print_test(0xffffffffffffffff, 0xffffffffffffffff); std::cout << "print_test = " << print_test << std::endl; UInt128 result1 = a+b; std::cout << "result1 = " << result1 << std::endl; UInt128 result2 = result1 - b; std::cout << "result2 = " << result2 << std::endl; UInt128 result3 = a * b; std::cout << "result3 = " << result3 << std::endl; UInt128 c(0, 10); std::cout << "c = " << c << std::endl; UInt128 result4 = a * c; std::cout << "result4 = " << result4 << std::endl; UInt128 result5 = result4 / c; std::cout << "result5 = " << result5 << std::endl; Int128 d(0xffffffffffffffff, 0xffffffffffffffff); std::cout << "d = " << d << std::endl; Int128 e(0, 2); std::cout << "e = " << e << std::endl; Int128 result6 = d + e; std::cout<< "result6 = " << result6 <<std::endl; Int128 result7 = d - e; std::cout << "result7 = " << result7 << std::endl; Int128 result8 = d * e; std::cout << "result8 = " << result8 << std::endl; Int128 result9 = result8 / e; std::cout << "result9 = " << result9 << std::endl; Int128 result10 = d * e - e; std::cout << "result10 = "<< result10 << std::endl; UInt128 f(0, 0); std::cout << "f = "; std::cin >> f; if (!std::cin.bad()){ std::cout << "f = " << f << std::endl; }else{ std::cout << "incorrent 128bit unsigned number"; return 1; } Int128 g(0, 0); std::cout << "g = "; std::cin >> g; if (!std::cin.bad()){ std::cout << "g = " << g << std::endl; }else{ std::cout << "incorrent 128bit signed integer number"; return 1; } UInt128 h("150"); std::cout << "h = " << h << std::endl; Int128 m("-150"); std::cout << "m = " << m << std::endl; std::ofstream test_file("test.bin"); IExtNums** array = new IExtNums*[6]; std::default_random_engine generator; std::uniform_int_distribution<long long int> signed_distribution(std::numeric_limits<long long int>::min(), std::numeric_limits<long long int>::max()); std::uniform_int_distribution<long long unsigned> unsigned_distribution; std::uniform_int_distribution<char> bool_distribution(0, 1); for (int i=0; i<6; i++){ bool isSigned = (bool)((bool_distribution(generator))>0); long long int b = 0; long long unsigned l = unsigned_distribution(generator); if (isSigned){ bool isNegate = bool_distribution(generator); if (isNegate){ b = -1; l = (~l)+1; } array[i] = new Int128(b, l); }else{ array[i] = new UInt128(0, l); } } serialize(array, 6, test_file); test_file.close(); delete[] array; return 0; }
5edd2152d39d3a90650a8398593b0ddb571c9a56
8c953249a62367a8f0138eff488ce5d510e65620
/cs109/lab4og/src/comply.cc
5b61a7f4c7c67392bf0a348fddea0430171eed89
[]
no_license
nahawtho/cs109copy
5ce87799eb09ac22b38f63b8d77b3878f8b5b001
66e2b2be6adf54bf724a437f2a32090a1d834cba
refs/heads/master
2020-04-05T06:50:35.063576
2018-11-08T05:10:56
2018-11-08T05:10:56
156,653,424
0
0
null
null
null
null
UTF-8
C++
false
false
2,890
cc
/* * Copyright (C) 2018 David C. Harrison. All right reserved. * * You may not use, distribute, publish, or modify this code without * the express written permission of the copyright holder. */ /****************** DO NOT MODIFY THIS FILE **************************** * * It is not included in the subission archive ceated by 'make submit' . * * If you modify it and your code relies on those modifications, your code * will not compile in the automated test harness and will be unable to * execute any tests. * * To put it another way, if you modify this file, you will get a big fat * ZERO on this lab. * ************************************************************************/ #include <iostream> #include "circle.h" #include "polygon.h" #include "reuleaux.h" #include "sphere.h" static void twodim() { Point p1 = Point(); Point p2 = Point(0.0, 0.0); Point p3 = Point(p2); Circle circle = Circle(Point(0.0,0.0), 0.0); double x = circle.center().x; double r = circle.radius(); ConvexPolygon polygon = ConvexPolygon({Point(0,0), Point(0,0), Point(0,0)}); polygon.vertices().size(); RegularConvexPolygon regular = RegularConvexPolygon({Point(0,0), Point(0,0), Point(0,0)}); regular.vertices().size(); Point vertices[3] = {Point(0,0), Point(0,0), Point(0,0)}; ReuleauxTriangle reuleaux = ReuleauxTriangle(vertices); reuleaux.vertices().size(); circle.containedBy(circle); circle.containedBy(polygon); circle.containedBy(regular); circle.containedBy(reuleaux); polygon.containedBy(circle); polygon.containedBy(polygon); polygon.containedBy(regular); polygon.containedBy(reuleaux); regular.containedBy(circle); regular.containedBy(polygon); regular.containedBy(regular); regular.containedBy(reuleaux); reuleaux.containedBy(circle); reuleaux.containedBy(polygon); reuleaux.containedBy(regular); reuleaux.containedBy(reuleaux); } static void threedim() { Point3D p1 = Point3D(); Point3D p2 = Point3D(0.0, 0.0, 0.0); Point3D p3 = Point3D(p2); Sphere sphere = Sphere(Point3D(0.0,0.0,0.0), 0.0); Point3D upper[4] = {Point3D(0,0,0), Point3D(0,0,0), Point3D(0,0,0), Point3D(0,0,0)}; Point3D lower[4] = {Point3D(0,0,0), Point3D(0,0,0), Point3D(0,0,0), Point3D(0,0,0)}; Cube cube = Cube(upper, lower); Point3D vertices[4] = {Point3D(0,0,0), Point3D(0,0,0), Point3D(0,0,0), Point3D(0,0,0)}; ReuleauxTetrahedron reuleaux = ReuleauxTetrahedron(vertices); cube.containedBy(cube); cube.containedBy(sphere); cube.containedBy(reuleaux); sphere.containedBy(cube); sphere.containedBy(sphere); sphere.containedBy(reuleaux); reuleaux.containedBy(cube); reuleaux.containedBy(sphere); reuleaux.containedBy(reuleaux); } int main(int argc, char *argv[]) { twodim(); threedim(); }
dc909a351ca0af697fe3deac85749d2fc944eaea
b7e66b2c0b9bb14dbf4ae5aa587335c63c5586d7
/Chapter1/problem1.cpp
f83f5275663a018334fe28fc850e58573c6734cd
[]
no_license
howardwang15/Cracking-the-coding-interview
232c80847deac1f69f51413615025f7b2a7742d8
895dd6d4b6e72e6527cf68e02b3ddc54398142dc
refs/heads/master
2018-11-17T17:42:16.977785
2018-09-03T02:44:22
2018-09-03T02:44:22
116,181,757
0
0
null
null
null
null
UTF-8
C++
false
false
251
cpp
#include <iostream> using namespace std; bool isUnique(string s) { int frequencies[256] = { 0 }; for (char c: s) { int val = c; if (frequencies[val] != 0) return false; frequencies[val]++; } return true; } int main () { }
1b3b335960fc82212b9b3f811794363057c1e2d9
753a70bc416e8dced2853f278b08ef60cdb3c768
/include/tensorflow/lite/micro/kernels/mul.cc
2e6464208bdbfe56bf2e6b1314b19ed9f513fb60
[ "MIT" ]
permissive
finnickniu/tensorflow_object_detection_tflite
ef94158e5350613590641880cb3c1062f7dd0efb
a115d918f6894a69586174653172be0b5d1de952
refs/heads/master
2023-04-06T04:59:24.985923
2022-09-20T16:29:08
2022-09-20T16:29:08
230,891,552
60
19
MIT
2023-03-25T00:31:18
2019-12-30T09:58:41
C++
UTF-8
C++
false
false
6,675
cc
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/kernels/internal/reference/mul.h" #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/kernels/internal/quantization_util.h" #include "tensorflow/lite/kernels/internal/reference/integer_ops/mul.h" #include "tensorflow/lite/kernels/internal/reference/process_broadcast_shapes.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/kernel_util.h" namespace tflite { namespace ops { namespace micro { namespace mul { constexpr int kInput1Tensor = 0; constexpr int kInput2Tensor = 1; constexpr int kOutputTensor = 0; struct OpData { int32_t output_activation_min; int32_t output_activation_max; int32_t output_multiplier; int output_shift; }; TfLiteStatus CalculateOpData(TfLiteContext* context, TfLiteNode* node, TfLiteMulParams* params, OpData* data) { const TfLiteTensor* input1 = GetInput(context, node, kInput1Tensor); const TfLiteTensor* input2 = GetInput(context, node, kInput2Tensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); TF_LITE_ENSURE_EQ(context, input1->type, input2->type); if (output->type == kTfLiteUInt8) { CalculateActivationRangeUint8(params->activation, output, &data->output_activation_min, &data->output_activation_max); } else if (output->type == kTfLiteInt8) { CalculateActivationRangeInt8(params->activation, output, &data->output_activation_min, &data->output_activation_max); } if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8) { double real_multiplier = input1->params.scale * input2->params.scale / output->params.scale; QuantizeMultiplier(real_multiplier, &data->output_multiplier, &data->output_shift); } return kTfLiteOk; } TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { return kTfLiteOk; } void EvalQuantized(TfLiteContext* context, TfLiteNode* node, TfLiteMulParams* params, OpData* data, const TfLiteTensor* input1, const TfLiteTensor* input2, TfLiteTensor* output) { if (output->type == kTfLiteInt8 || output->type == kTfLiteUInt8) { tflite::ArithmeticParams op_params; SetActivationParams(data->output_activation_min, data->output_activation_max, &op_params); op_params.input1_offset = -input1->params.zero_point; op_params.input2_offset = -input2->params.zero_point; op_params.output_offset = output->params.zero_point; op_params.output_multiplier = data->output_multiplier; op_params.output_shift = data->output_shift; bool need_broadcast = reference_ops::ProcessBroadcastShapes( GetTensorShape(input1), GetTensorShape(input2), &op_params); #define TF_LITE_MUL(type, opname, dtype) \ type::opname(op_params, GetTensorShape(input1), \ GetTensorData<dtype>(input1), GetTensorShape(input2), \ GetTensorData<dtype>(input2), GetTensorShape(output), \ GetTensorData<dtype>(output)); if (output->type == kTfLiteInt8) { if (need_broadcast) { TF_LITE_MUL(reference_integer_ops, BroadcastMul4DSlow, int8_t); } else { TF_LITE_MUL(reference_integer_ops, Mul, int8_t); } } else if (output->type == kTfLiteUInt8) { if (need_broadcast) { TF_LITE_MUL(reference_ops, BroadcastMul4DSlow, uint8_t); } else { TF_LITE_MUL(reference_ops, Mul, uint8_t); } } #undef TF_LITE_MUL } } void EvalFloat(TfLiteContext* context, TfLiteNode* node, TfLiteMulParams* params, OpData* data, const TfLiteTensor* input1, const TfLiteTensor* input2, TfLiteTensor* output) { float output_activation_min, output_activation_max; CalculateActivationRange(params->activation, &output_activation_min, &output_activation_max); tflite::ArithmeticParams op_params; SetActivationParams(output_activation_min, output_activation_max, &op_params); bool need_broadcast = reference_ops::ProcessBroadcastShapes( GetTensorShape(input1), GetTensorShape(input2), &op_params); #define TF_LITE_MUL(opname) \ reference_ops::opname(op_params, GetTensorShape(input1), \ GetTensorData<float>(input1), GetTensorShape(input2), \ GetTensorData<float>(input2), GetTensorShape(output), \ GetTensorData<float>(output)); if (need_broadcast) { TF_LITE_MUL(BroadcastMul4DSlow); } else { TF_LITE_MUL(Mul); } #undef TF_LITE_MUL } TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteMulParams*>(node->builtin_data); OpData data; const TfLiteTensor* input1 = GetInput(context, node, kInput1Tensor); const TfLiteTensor* input2 = GetInput(context, node, kInput2Tensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); CalculateOpData(context, node, params, &data); switch (input1->type) { case kTfLiteUInt8: case kTfLiteInt8: EvalQuantized(context, node, params, &data, input1, input2, output); break; case kTfLiteFloat32: EvalFloat(context, node, params, &data, input1, input2, output); break; default: context->ReportError(context, "Type %d not currently supported.", input1->type); return kTfLiteError; } return kTfLiteOk; } } // namespace mul TfLiteRegistration* Register_MUL() { static TfLiteRegistration r = {nullptr, nullptr, mul::Prepare, mul::Eval}; return &r; } } // namespace micro } // namespace ops } // namespace tflite
9bc30c12f83dfa8069cd310bb9c438256011d791
9f520bcbde8a70e14d5870fd9a88c0989a8fcd61
/pitzDaily/389/uniform/functionObjects/functionObjectProperties
15b5c580dadf831388e52cb2b659b89fef46566a
[]
no_license
asAmrita/adjoinShapOptimization
6d47c89fb14d090941da706bd7c39004f515cfea
079cbec87529be37f81cca3ea8b28c50b9ceb8c5
refs/heads/master
2020-08-06T21:32:45.429939
2019-10-06T09:58:20
2019-10-06T09:58:20
213,144,901
1
0
null
null
null
null
UTF-8
C++
false
false
897
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v1806 | | \\ / A nd | Web: www.OpenFOAM.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "389/uniform/functionObjects"; object functionObjectProperties; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // ************************************************************************* //
6cdf6bdd52ff7a0d8f30d45dbc4bac4c28880324
63e3ec9a6849b10dc743b191a62649c954831d06
/Tester/main.cpp
e0791ff35004ab5b558141ef4bc581cfd09d9451
[ "Apache-2.0" ]
permissive
amj55/CPP
b89f1bfafd7595f47689c3c8502f2a3ae380c267
993fdfa8e1878c2033ad78070d55442f4c15393a
refs/heads/master
2021-08-28T09:33:35.491890
2017-12-11T21:17:15
2017-12-11T21:17:15
114,029,061
1
0
null
null
null
null
UTF-8
C++
false
false
409
cpp
#include <iostream> #include <vector> using namespace std; int main() { vector<int> test; test.push_back(5); test.push_back(10); test.push_back(100); test.insert(test.begin(), 1); cout << test.back() << " " << test.front() << " " << test[0] << endl; return 0; } void disp(vector<con> items) { for(int i = 0; i < items.size(); i++) { cout << items[1] << " "; } }
6dfd68acdbd618e2b2d723e5472cb499abcec932
cae01d285dbd8bbebd7b48b95efa483ae6b4a2c5
/Intermediate/Build/Win64/UE4Editor/Inc/VehicleTemplate/Checkpoints.generated.h
12757ce519347866731717ca9fa903cab1ef5d18
[]
no_license
AliHasl/UnrealVehicleProject
24f148f487b56c8a40ce0313bcf1a12294a7834b
592f743cb05977ce7265506f7348f6c35e57e63c
refs/heads/master
2020-04-10T05:41:48.065440
2018-12-07T14:30:36
2018-12-07T14:30:36
160,834,796
0
0
null
null
null
null
UTF-8
C++
false
false
4,149
h
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "ObjectMacros.h" #include "ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS #ifdef VEHICLETEMPLATE_Checkpoints_generated_h #error "Checkpoints.generated.h already included, missing '#pragma once' in Checkpoints.h" #endif #define VEHICLETEMPLATE_Checkpoints_generated_h #define VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_RPC_WRAPPERS #define VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_RPC_WRAPPERS_NO_PURE_DECLS #define VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesACheckpoints(); \ friend VEHICLETEMPLATE_API class UClass* Z_Construct_UClass_ACheckpoints(); \ public: \ DECLARE_CLASS(ACheckpoints, AActor, COMPILED_IN_FLAGS(0), 0, TEXT("/Script/VehicleTemplate"), NO_API) \ DECLARE_SERIALIZER(ACheckpoints) \ enum {IsIntrinsic=COMPILED_IN_INTRINSIC}; #define VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_INCLASS \ private: \ static void StaticRegisterNativesACheckpoints(); \ friend VEHICLETEMPLATE_API class UClass* Z_Construct_UClass_ACheckpoints(); \ public: \ DECLARE_CLASS(ACheckpoints, AActor, COMPILED_IN_FLAGS(0), 0, TEXT("/Script/VehicleTemplate"), NO_API) \ DECLARE_SERIALIZER(ACheckpoints) \ enum {IsIntrinsic=COMPILED_IN_INTRINSIC}; #define VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API ACheckpoints(const FObjectInitializer& ObjectInitializer); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(ACheckpoints) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, ACheckpoints); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ACheckpoints); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API ACheckpoints(ACheckpoints&&); \ NO_API ACheckpoints(const ACheckpoints&); \ public: #define VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_ENHANCED_CONSTRUCTORS \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API ACheckpoints(ACheckpoints&&); \ NO_API ACheckpoints(const ACheckpoints&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, ACheckpoints); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ACheckpoints); \ DEFINE_DEFAULT_CONSTRUCTOR_CALL(ACheckpoints) #define VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_PRIVATE_PROPERTY_OFFSET #define VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_12_PROLOG #define VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_PRIVATE_PROPERTY_OFFSET \ VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_RPC_WRAPPERS \ VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_INCLASS \ VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_PRIVATE_PROPERTY_OFFSET \ VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_RPC_WRAPPERS_NO_PURE_DECLS \ VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_INCLASS_NO_PURE_DECLS \ VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #undef CURRENT_FILE_ID #define CURRENT_FILE_ID VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h PRAGMA_ENABLE_DEPRECATION_WARNINGS
42f0b1c94b78719dc6a409d2c51f79d2d01764a5
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/crypto/ec_signature_creator_impl.cc
2870310dd1c0d30880412a0a05bd87ac978da063
[ "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
2,343
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "crypto/ec_signature_creator_impl.h" #include <openssl/bn.h> #include <openssl/ec.h> #include <openssl/ecdsa.h> #include <openssl/evp.h> #include <openssl/sha.h> #include <stddef.h> #include <stdint.h> #include "base/logging.h" #include "crypto/ec_private_key.h" #include "crypto/openssl_util.h" namespace crypto { ECSignatureCreatorImpl::ECSignatureCreatorImpl(ECPrivateKey* key) : key_(key) { EnsureOpenSSLInit(); } ECSignatureCreatorImpl::~ECSignatureCreatorImpl() {} bool ECSignatureCreatorImpl::Sign(const uint8_t* data, int data_len, std::vector<uint8_t>* signature) { OpenSSLErrStackTracer err_tracer(FROM_HERE); bssl::ScopedEVP_MD_CTX ctx; size_t sig_len = 0; if (!ctx.get() || !EVP_DigestSignInit(ctx.get(), nullptr, EVP_sha256(), nullptr, key_->key()) || !EVP_DigestSignUpdate(ctx.get(), data, data_len) || !EVP_DigestSignFinal(ctx.get(), nullptr, &sig_len)) { return false; } signature->resize(sig_len); if (!EVP_DigestSignFinal(ctx.get(), &signature->front(), &sig_len)) return false; // NOTE: A call to EVP_DigestSignFinal() with a nullptr second parameter // returns a maximum allocation size, while the call without a nullptr // returns the real one, which may be smaller. signature->resize(sig_len); return true; } bool ECSignatureCreatorImpl::DecodeSignature( const std::vector<uint8_t>& der_sig, std::vector<uint8_t>* out_raw_sig) { OpenSSLErrStackTracer err_tracer(FROM_HERE); // Create ECDSA_SIG object from DER-encoded data. bssl::UniquePtr<ECDSA_SIG> ecdsa_sig( ECDSA_SIG_from_bytes(der_sig.data(), der_sig.size())); if (!ecdsa_sig.get()) return false; // The result is made of two 32-byte vectors. const size_t kMaxBytesPerBN = 32; std::vector<uint8_t> result(2 * kMaxBytesPerBN); if (!BN_bn2bin_padded(&result[0], kMaxBytesPerBN, ecdsa_sig->r) || !BN_bn2bin_padded(&result[kMaxBytesPerBN], kMaxBytesPerBN, ecdsa_sig->s)) { return false; } out_raw_sig->swap(result); return true; } } // namespace crypto
7440b24ea9e26820cf09a065a704bccd9e0110c4
959af614f695a948ae2c899f1e9a6c8163c80e00
/samples/core/sample_core_benchmark_disk.cpp
abfd69eb7210700193f120cb835cc69b5763b33c
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Paul-Hi/saiga
cacf1d8537096df871fafa06e755b4e9908672f3
1b843bf7800f7113e7bd4d709fc965088078702d
refs/heads/master
2023-06-19T22:18:24.752565
2021-06-29T15:06:25
2021-06-29T15:06:25
289,020,555
0
0
MIT
2020-08-20T13:58:07
2020-08-20T13:58:06
null
UTF-8
C++
false
false
1,195
cpp
/** * Copyright (c) 2017 Darius Rückert * Licensed under the MIT License. * See LICENSE file for more information. */ #include "saiga/core/Core.h" #include "saiga/core/time/all.h" #include "saiga/core/util/Thread/omp.h" using namespace Saiga; int sizeMB = 1000 * 1; size_t blockSize = sizeMB * 1000UL * 1000UL; double blockSizeGB = (blockSize / (1000.0 * 1000.0 * 1000.0)); void write(const std::string& file, const std::vector<char>& data) { FILE* dest = fopen(file.c_str(), "wb"); if (dest == 0) { return; } auto written = fwrite(0, 1, data.size(), dest); SAIGA_ASSERT(written == data.size()); fclose(dest); } void write2(const std::string& file, const std::vector<char>& data) { std::ofstream is(file, std::ios::binary | std::ios::out); if (!is.is_open()) { std::cout << "File not found " << file << std::endl; return; } is.write(data.data(), data.size()); is.close(); } int main(int, char**) { catchSegFaults(); std::vector<char> data(blockSize); { SAIGA_BLOCK_TIMER(); write2("test.dat", data); } std::cout << "Done." << std::endl; return 0; }
4e8213aa94d1e02c6254898794a4c0f7c40095fe
c022ac5523662a3022e220beef041268b11103f4
/DS-malik-cpp/namespaceEg1.cpp
2b4d6c7989ed8cac7189d88c0aa2ebf75f1cfb49
[]
no_license
Otumian-empire/DS-malik-cpp
780194091ddd013ed6f5286a79278cc3f0eeb9ed
aa2273b88dab69b267ffb1cab76e5c562fc28de7
refs/heads/master
2020-06-13T03:36:48.184918
2020-04-26T09:46:08
2020-04-26T09:46:08
194,520,519
0
0
null
null
null
null
UTF-8
C++
false
false
440
cpp
 namespace otu { string author = "Otumian Empire"; string expertise = "Die hard programmer"; } namespace globalType { const int N = 10; const double RATE = 7.50; int count = 0; void printResult(); } #include <iostream>z using namespace std; // using namespace otu; using namespace globalType; int main() { // cout << otu::author << endl << expertise << endl; cout << N << endl; cout << RATE << endl; return 0; }
a6e33853276bc2ae67f69b6915f7180c0f752eed
da0d71b758d95e532056bc705b186666837709b7
/src/libfauxdcore/tuple-compiler.cc
58202b7ed49edf1bc075a54703e9978abe12b6d0
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
ZachBacon/fauxdacious
fc3f3aa5bf6cbf0f88b7e33a0e3fd4c8971a124a
a2bbdaed2fee91d8f5d84fd2c21b41cf9452620a
refs/heads/master
2021-05-19T23:46:26.626551
2020-03-04T16:45:28
2020-03-04T16:45:28
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
12,833
cc
/* * tuple_compiler.c * Copyright (c) 2007 Matti 'ccr' Hämäläinen * Copyright (c) 2011-2014 John Lindgren * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions, and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions, and the following disclaimer in the documentation * provided with the distribution. * * This software is provided "as is" and without any warranty, express or * implied. In no event shall the authors be liable for any damages arising from * the use of this software. */ #include <stdlib.h> #include <string.h> #include <new> #include <glib.h> #include "audstrings.h" #include "runtime.h" #include "tuple-compiler.h" struct Variable { enum { Invalid = 0, Text, Integer, Field } type; String text; int integer; Tuple::Field field; bool set (const char * name, bool literal); bool exists (const Tuple & tuple) const; Tuple::ValueType get (const Tuple & tuple, String & tmps, int & tmpi) const; }; enum class Op { Invalid = 0, Var, Exists, Equal, Unequal, Greater, GreaterEqual, Less, LessEqual, Empty }; struct TupleCompiler::Node { Op op; Variable var1, var2; Index<Node> children; }; typedef TupleCompiler::Node Node; bool Variable::set (const char * name, bool literal) { if (g_ascii_isdigit (name[0])) { type = Integer; integer = atoi (name); } else if (literal) { type = Text; text = String (name); } else { type = Field; field = Tuple::field_by_name (name); if (field < 0) { AUDWARN ("Invalid variable '%s'.\n", name); return false; } } return true; } bool Variable::exists (const Tuple & tuple) const { g_return_val_if_fail (type == Field, false); return tuple.get_value_type (field) != Tuple::Empty; } Tuple::ValueType Variable::get (const Tuple & tuple, String & tmps, int & tmpi) const { switch (type) { case Text: tmps = text; return Tuple::String; case Integer: tmpi = integer; return Tuple::Int; case Field: switch (tuple.get_value_type (field)) { case Tuple::String: tmps = tuple.get_str (field); return Tuple::String; case Tuple::Int: tmpi = tuple.get_int (field); return Tuple::Int; default: return Tuple::Empty; } default: g_return_val_if_reached (Tuple::Empty); } } TupleCompiler::TupleCompiler () {} TupleCompiler::~TupleCompiler () {} static StringBuf get_item (const char * & str, char endch, bool & literal) { const char * s = str; StringBuf buf (-1); char * set = buf; char * stop = buf + buf.len (); if (* s == '"') { if (! literal) { buf = StringBuf (); // release space before AUDWARN AUDWARN ("Unexpected string literal at '%s'.\n", s); return StringBuf (); } s ++; } else literal = false; if (literal) { while (* s != '"') { if (* s == '\\') s ++; if (! * s) { buf = StringBuf (); // release space before AUDWARN AUDWARN ("Unterminated string literal.\n"); return StringBuf (); } if (set == stop) throw std::bad_alloc (); * set ++ = * s ++; } s ++; } else { while (g_ascii_isalnum (* s) || * s == '-') { if (set == stop) throw std::bad_alloc (); * set ++ = * s ++; } } if (* s != endch) { buf = StringBuf (); // release space before AUDWARN AUDWARN ("Expected '%c' at '%s'.\n", endch, s); return StringBuf (); } str = s + 1; buf.resize (set - buf); return buf; } static bool compile_expression (Index<Node> & nodes, const char * & expression); static bool parse_construct (Node & node, const char * & c) { bool literal1 = true, literal2 = true; StringBuf tmps1 = get_item (c, ',', literal1); if (! tmps1) return false; StringBuf tmps2 = get_item (c, ':', literal2); if (! tmps2) return false; if (! node.var1.set (tmps1, literal1)) return false; if (! node.var2.set (tmps2, literal2)) return false; return compile_expression (node.children, c); } /* Compile format expression into Node tree. */ static bool compile_expression (Index<Node> & nodes, const char * & expression) { const char * c = expression; while (* c && * c != '}') { Node & node = nodes.append (); if (* c == '$') { /* Expression? */ if (c[1] != '{') { AUDWARN ("Expected '${' at '%s'.\n", c); return false; } c += 2; switch (* c) { case '?': case '(': { if (* c == '?') { node.op = Op::Exists; c ++; } else { if (strncmp (c, "(empty)?", 8)) { AUDWARN ("Expected '(empty)?' at '%s'.\n", c); return false; } node.op = Op::Empty; c += 8; } bool literal = false; StringBuf tmps = get_item (c, ':', literal); if (! tmps) return false; if (! node.var1.set (tmps, false)) return false; if (! compile_expression (node.children, c)) return false; break; } case '=': case '!': node.op = (* c == '=') ? Op::Equal : Op::Unequal; if (c[1] != '=') { AUDWARN ("Expected '%c=' at '%s'.\n", c[0], c); return false; } c += 2; if (! parse_construct (node, c)) return false; break; case '<': case '>': if (c[1] == '=') { node.op = (* c == '<') ? Op::LessEqual : Op::GreaterEqual; c += 2; } else { node.op = (* c == '<') ? Op::Less : Op::Greater; c ++; } if (! parse_construct (node, c)) return false; break; default: { bool literal = false; StringBuf tmps = get_item (c, '}', literal); if (! tmps) return false; c --; node.op = Op::Var; if (! node.var1.set (tmps, false)) return false; } } if (* c != '}') { AUDWARN ("Expected '}' at '%s'.\n", c); return false; } c ++; } else if (* c == '{') { AUDWARN ("Unexpected '%c' at '%s'.\n", * c, c); return false; } else { /* Parse raw/literal text */ StringBuf buf (-1); char * set = buf; char * stop = buf + buf.len (); while (* c && * c != '$' && * c != '{' && * c != '}') { if (* c == '\\') { c ++; if (! * c) { buf = StringBuf (); // release space before AUDWARN AUDWARN ("Incomplete escaped character.\n"); return false; } } if (set == stop) throw std::bad_alloc (); * set ++ = * c ++; } buf.resize (set - buf); node.op = Op::Var; node.var1.type = Variable::Text; node.var1.text = String (buf); } } expression = c; return true; } bool TupleCompiler::compile (const char * expr) { const char * c = expr; Index<Node> nodes; if (! compile_expression (nodes, c)) return false; if (* c) { AUDWARN ("Unexpected '%c' at '%s'.\n", * c, c); return false; } root_nodes = std::move (nodes); return true; } void TupleCompiler::reset () { root_nodes.clear (); } /* Evaluate tuple in given TupleEval expression in given * context and return resulting string. */ static void eval_expression (const Index<Node> & nodes, const Tuple & tuple, StringBuf & out) { for (const Node & node : nodes) { switch (node.op) { case Op::Var: { String tmps; int tmpi; switch (node.var1.get (tuple, tmps, tmpi)) { case Tuple::String: out.insert (-1, tmps); break; case Tuple::Int: str_insert_int (out, -1, tmpi); break; default: break; } break; } case Op::Equal: case Op::Unequal: case Op::Less: case Op::LessEqual: case Op::Greater: case Op::GreaterEqual: { bool result = false; String tmps1, tmps2; int tmpi1 = 0, tmpi2 = 0; Tuple::ValueType type1 = node.var1.get (tuple, tmps1, tmpi1); Tuple::ValueType type2 = node.var2.get (tuple, tmps2, tmpi2); if (type1 != Tuple::Empty && type2 != Tuple::Empty) { int resulti; if (type1 == type2) { if (type1 == Tuple::String) resulti = strcmp (tmps1, tmps2); else resulti = tmpi1 - tmpi2; } else { if (type1 == Tuple::Int) resulti = tmpi1 - atoi (tmps2); else resulti = atoi (tmps1) - tmpi2; } switch (node.op) { case Op::Equal: result = (resulti == 0); break; case Op::Unequal: result = (resulti != 0); break; case Op::Less: result = (resulti < 0); break; case Op::LessEqual: result = (resulti <= 0); break; case Op::Greater: result = (resulti > 0); break; case Op::GreaterEqual: result = (resulti >= 0); break; default: g_warn_if_reached (); } } if (result) eval_expression (node.children, tuple, out); break; } case Op::Exists: if (node.var1.exists (tuple)) eval_expression (node.children, tuple, out); break; case Op::Empty: if (! node.var1.exists (tuple)) eval_expression (node.children, tuple, out); break; default: g_warn_if_reached (); } } } void TupleCompiler::format (Tuple & tuple) const { tuple.unset (Tuple::FormattedTitle); // prevent recursion StringBuf buf (0); eval_expression (root_nodes, tuple, buf); if (buf[0]) { tuple.set_str (Tuple::FormattedTitle, buf); return; } /* formatting failed, try fallbacks */ for (Tuple::Field fallback : {Tuple::Title, Tuple::Basename}) { String title = tuple.get_str (fallback); if (title) { tuple.set_str (Tuple::FormattedTitle, title); return; } } tuple.set_str (Tuple::FormattedTitle, ""); }
f3499235c1299d4bc284deb36518a466f36274bf
a2206795a05877f83ac561e482e7b41772b22da8
/Source/PV/build/Qt/Components/moc_pqStringVectorPropertyWidget.cxx
ec134e8372774ae2c8e9d04920dba9af3c476a00
[]
no_license
supreethms1809/mpas-insitu
5578d465602feb4d6b239a22912c33918c7bb1c3
701644bcdae771e6878736cb6f49ccd2eb38b36e
refs/heads/master
2020-03-25T16:47:29.316814
2018-08-08T02:00:13
2018-08-08T02:00:13
143,947,446
0
0
null
null
null
null
UTF-8
C++
false
false
2,679
cxx
/**************************************************************************** ** Meta object code from reading C++ file 'pqStringVectorPropertyWidget.h' ** ** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.6) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../../ParaView/Qt/Components/pqStringVectorPropertyWidget.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'pqStringVectorPropertyWidget.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 63 #error "This file was generated using the moc from 4.8.6. 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_pqStringVectorPropertyWidget[] = { // 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_pqStringVectorPropertyWidget[] = { "pqStringVectorPropertyWidget\0" }; void pqStringVectorPropertyWidget::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 pqStringVectorPropertyWidget::staticMetaObjectExtraData = { 0, qt_static_metacall }; const QMetaObject pqStringVectorPropertyWidget::staticMetaObject = { { &pqPropertyWidget::staticMetaObject, qt_meta_stringdata_pqStringVectorPropertyWidget, qt_meta_data_pqStringVectorPropertyWidget, &staticMetaObjectExtraData } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &pqStringVectorPropertyWidget::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *pqStringVectorPropertyWidget::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *pqStringVectorPropertyWidget::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_pqStringVectorPropertyWidget)) return static_cast<void*>(const_cast< pqStringVectorPropertyWidget*>(this)); return pqPropertyWidget::qt_metacast(_clname); } int pqStringVectorPropertyWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = pqPropertyWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_END_MOC_NAMESPACE
23bb7c0023ab0d19e14718cb92e52a5c74663292
7e2f4649977299d392d6fedd08156232d62bd216
/src/controls/sdbrowserwidget.h
366ea2b95faed6832f485ed90a07af9c5cdb32ab
[ "MIT" ]
permissive
AhmadPanogari/Phoenard-Toolkit
cadd1d26649f7877ff87fc2791d32e8c9d06fbe1
395ce79a3c56701073531cb2caad3637312d906c
refs/heads/master
2021-06-04T17:47:43.102820
2016-07-11T14:42:53
2016-07-11T14:42:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,830
h
#ifndef SDBROWSERWIDGET_H #define SDBROWSERWIDGET_H #include <QTreeWidget> #include <QResizeEvent> #include <QDragEnterEvent> #include <QDragMoveEvent> #include <QDragLeaveEvent> #include <QDropEvent> #include "mainmenutab.h" #include "../imaging/phniconprovider.h" class SDBrowserWidget : public QTreeWidget, public MainMenuTab { Q_OBJECT public: SDBrowserWidget(QWidget *parent = 0); void refreshFiles(); void deleteFiles(); void saveFilesTo(); void importFiles(); void importFiles(QStringList filePaths); void importFiles(QStringList filePaths, QString destFolder); void createNew(QString fileName, bool isDirectory); void keyPressEvent(QKeyEvent *ev); bool hasSelection(); QTreeWidgetItem* getSelectedFolder(); QString volumeName(); protected: void dragEnterEvent(QDragEnterEvent *event); void dragMoveEvent(QDragMoveEvent *event); void dragLeaveEvent(QDragLeaveEvent *event); void dropEvent(QDropEvent *event); void itemExpanded(QTreeWidgetItem *item); void refreshItem(QTreeWidgetItem *item); void refreshItem(QTreeWidgetItem *item, QList<DirectoryInfo> subFiles); void setupItemName(QTreeWidgetItem *item, QString name); void addExpandedListTasks(QTreeWidgetItem *item, QList<stk500Task*> *tasks); QString getPath(QTreeWidgetItem *item); QTreeWidgetItem *getItemAtPath(QString path); bool itemHasSelectedParent(QTreeWidgetItem *item); bool itemIsFolder(QTreeWidgetItem *item); void updateItemIcon(QTreeWidgetItem *item); private slots: void on_itemExpanded(QTreeWidgetItem *item); void on_itemChanged(QTreeWidgetItem *item, int column); void on_itemDoubleClicked(QTreeWidgetItem *item, int column); private: bool _isRefreshing; PHNIconProvider iconProvider; }; #endif // SDBROWSERWIDGET_H
697e691d13515b02d37cce2ac7290dba54adf47d
b1ee6b1a8b616c3e2692a426d4e59b8a508cd6c3
/Robot/Robot.ip_user_files/bd/base/ip/base_constant_tkeep_tstrb_1/sim/base_constant_tkeep_tstrb_1.h
59cc2887cf546a3587b23354959360c8139fe323
[ "MIT" ]
permissive
junhongmit/PYNQ_Car
5c9157bc42680c897c828ba6539800b066d6888f
c4600f270c56c819e6b3e3e357b44081ee5ddce5
refs/heads/master
2022-03-01T12:44:03.589295
2019-10-21T16:43:33
2019-10-21T16:43:33
165,031,312
1
0
null
null
null
null
UTF-8
C++
false
false
2,689
h
// (c) Copyright 1995-2014 Xilinx, Inc. All rights reserved. // // This file contains confidential and proprietary information // of Xilinx, Inc. and is protected under U.S. and // international copyright and other intellectual property // laws. // // DISCLAIMER // This disclaimer is not a license and does not grant any // rights to the materials distributed herewith. Except as // otherwise provided in a valid license issued to you by // Xilinx, and to the maximum extent permitted by applicable // law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND // WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES // AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING // BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON- // INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and // (2) Xilinx shall not be liable (whether in contract or tort, // including negligence, or under any other theory of // liability) for any loss or damage of any kind or nature // related to, arising under or in connection with these // materials, including for any direct, or any indirect, // special, incidental, or consequential loss or damage // (including loss of data, profits, goodwill, or any type of // loss or damage suffered as a result of any action brought // by a third party) even if such damage or loss was // reasonably foreseeable or Xilinx had been advised of the // possibility of the same. // // CRITICAL APPLICATIONS // Xilinx products are not designed or intended to be fail- // safe, or for use in any application requiring fail-safe // performance, such as life-support or safety devices or // systems, Class III medical devices, nuclear facilities, // applications related to the deployment of airbags, or any // other applications that could lead to death, personal // injury, or severe property or environmental damage // (individually and collectively, "Critical // Applications"). Customer assumes the sole risk and // liability of any use of Xilinx products in Critical // Applications, subject only to applicable laws and // regulations governing limitations on product liability. // // THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS // PART OF THIS FILE AT ALL TIMES. // // DO NOT MODIFY THIS FILE. // IP VLNV: xilinx.com:ip:xlconstant:1.1 // IP Revision: 1 #ifndef _base_constant_tkeep_tstrb_1_H_ #define _base_constant_tkeep_tstrb_1_H_ #include "xlconstant_v1_1.h" #include "systemc.h" class base_constant_tkeep_tstrb_1 : public sc_module { public: xlconstant_v1_1_5<4,15> mod; sc_out< sc_bv<4> > dout; base_constant_tkeep_tstrb_1 (sc_core::sc_module_name name) :sc_module(name), mod("mod") { mod.dout(dout); } }; #endif
70e88be0e6d971d7e5b7e635de9ca1e355ae7bc5
cbd022378f8c657cef7f0d239707c0ac0b27118a
/src/npcclient/walkpoly.h
086682f6eb262d1af23613db499207e0fd45b057
[]
no_license
randomcoding/PlaneShift-PSAI
57d3c1a2accdef11d494c523f3e2e99142d213af
06c585452abf960e0fc964fe0b7502b9bd550d1f
refs/heads/master
2016-09-10T01:58:01.360365
2011-09-07T23:13:48
2011-09-07T23:13:48
2,336,981
0
0
null
null
null
null
UTF-8
C++
false
false
13,256
h
/* * walkpoly.h * * Copyright (C) 2005 Atomic Blue ([email protected], http://www.atomicblue.org) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation (version 2 * of the License). * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef ___WALKPOLY_HEADER___ #define ___WALKPOLY_HEADER___ #if USE_WALKPOLY //============================================================================= // Crystal Space Includes //============================================================================= #include <csgeom/vector3.h> #include <csgeom/box.h> #include <iutil/objreg.h> #include <csutil/array.h> #include <csutil/csstring.h> #include <csutil/list.h> //============================================================================= // Local Includes //============================================================================= #include "pathfind.h" class psNPCClient; void Dump3(const char * name, const csVector3 & p); void Dump(const char * name, const csBox3 & b); void Dump(const char * name, const csVector3 & p); float Calc2DDistance(const csVector3 & a, const csVector3 & b); float AngleDiff(float a1, float a2); /** Normal equation of a line in 2D space (the y coord is ignored) */ class ps2DLine { public: float a, b, c; void Dump(); void Calc(const csVector3 & p1, const csVector3 & p2); void CalcPerp(const csVector3 & begin, const csVector3 & end); float CalcDist(const csVector3 & point); float CalcRel(const csVector3 & point); void Copy(ps2DLine & dest); }; class psWalkPoly; class psMapWalker; struct iSector; class CelBase; struct iDocumentNode; struct iVFS; /************************************************************************** * psSpatialIndex is a tree-style data structure. * Its purpose is fast search of the psWalkPoly that is under your feet * or close to you. * It recursively splits the space into pairs of rectangular subspaces. * * Each subspace corresponds to one node of the tree. * Each node keeps list of psWalkPolys whose psWalkPoly::box * collides with the subspace of the node. ***************************************************************************/ class psSpatialIndexNode { friend class psSpatialIndex; public: psSpatialIndexNode(); /** Finds terminal node containing given point The point MUST be located in subtree of this node */ psSpatialIndexNode * FindNodeOfPoint(const csVector3 & p); /** Adds polygon to the right terminal nodes from the subtree */ void Add(psWalkPoly* poly); csBox3 & GetBBox() { return bbox; } csList<psWalkPoly*> * GetPolys() { return &polys; }; protected: /** Returns distance to root (root has 0) */ int GetTreeLevel(); /** Splits itself into two nodes */ void Split(); /** Chooses and sets appropriate splitAxis and splitValue */ void ChooseSplit(); psSpatialIndexNode * child1, * child2; psSpatialIndexNode * parent; csBox3 bbox; /** subspace of this node */ float splitValue; /** The border value of x or y or z which separates the subspaces of child1 and child2 ... used only if node has children */ char splitAxis; /** 0=x, 1=y, 2=z ... used only if node has children */ csList<psWalkPoly*> polys; /** Polygons whose "box" collides with this subspace */ int numPolys; /** Length of the list because csList lacks that */ }; class psSpatialIndex { public: psSpatialIndex(); /** Adds without balancing */ void Add(psWalkPoly* poly); /** Rebuilds the index from scratch so that it is more balanced */ void Rebuild(); /** Finds terminal node containing given point. 'hint' is an optional index node that could be the right node */ psSpatialIndexNode * FindNodeOfPoint(const csVector3 & p, psSpatialIndexNode * hint=NULL); //psSpatialIndexNode * FindNodeOfPoly(psWalkPoly * poly); /** Finds psWalkPoly whose "box" contains given point 'hint' is an optional index node that could be the right node */ psWalkPoly * FindPolyOfPoint(const csVector3 & p, psSpatialIndexNode * hint=NULL); psANode * FindNearbyANode(const csVector3 & pos); protected: psSpatialIndexNode root; }; class psSeed { public: psSeed(); psSeed(csVector3 pos, iSector * sector, float quality); psSeed(csVector3 edgePos, csVector3 pos, iSector * sector, float quality); void SaveToString(csString & str); void LoadFromXML(iDocumentNode * node, csRef<iEngine> engine); bool CheckValidity(psMapWalker * walker); bool edgeSeed; float quality; csVector3 pos, edgePos; iSector * sector; }; class psSeedSet { public: psSeedSet(iObjectRegistry * objReg); psSeed PickUpBestSeed(); void AddSeed(const psSeed & seed); bool IsEmpty() { return seeds.IsEmpty(); } bool LoadFromString(const csString & str); bool LoadFromFile(const csString & path); void SaveToString(csString & str); bool SaveToFile(const csString & path); protected: iObjectRegistry * objReg; csList<psSeed> seeds; }; /***************************************************************** * The areas of map that are without major obstacles are denoted * by set of polygons that cover these areas. This is used * to precisely calculate very short paths. Other paths * are calculated using A*, and later fine-tuned with this map. ******************************************************************/ /** This describes a contact of edge of one polygon with edge of another polygon */ class psWalkPolyCont { public: csVector3 begin, end; ///< what part of the edge psWalkPoly * poly; ///< the polygon that touches us }; /** Vertex of psWalkPoly, also containing info about edge to the next vertex. Contains list of contacts with neighbour psWalkPolys */ class psWalkPolyVert { public: csVector3 pos; ps2DLine line; ///< normal equation of edge from this vertex to the following one csArray<psWalkPolyCont> conts; csString info; ///< debug only bool touching, stuck; bool followingEdge; float angle; psWalkPolyVert(); psWalkPolyVert(const csVector3 & pos); /** Finds neighbour polygon that contacts with this edge at given point. Return NULL = there is no contact at this point */ psWalkPoly * FindCont(const csVector3 & point); void CalcLineTo(const csVector3 & point); }; /** This just keeps all polygons that we know and their index */ class psWalkPolyMap { friend class psWalkPoly; public: psWalkPolyMap(iObjectRegistry * objReg); psWalkPolyMap(); void SetObjReg(iObjectRegistry * objReg) { this->objReg=objReg; } /** Adds new polygon to map */ void AddPoly(psWalkPoly * ); /** Checks if you can go directly between two points without problems */ bool CheckDirectPath(csVector3 start, csVector3 goal); void Generate(psNPCClient * npcclient, psSeedSet & seeds, iSector * sector); void CalcConts(); csString DumpPolys(); void BuildBasicAMap(psAMap & AMap); void LoadFromXML(iDocumentNode * node); bool LoadFromString(const csString & str); bool LoadFromFile(const csString & path); void SaveToString(csString & str); bool SaveToFile(const csString & path); psANode * FindNearbyANode(const csVector3 & pos); psWalkPoly * FindPoly(int id); void PrunePolys(); void DeleteContsWith(psWalkPoly * poly); protected: csList<psWalkPoly*> polys; psSpatialIndex index; csHash<psWalkPoly*> polyByID; iObjectRegistry * objReg; csRef<iVFS> vfs; }; /******************************************************************** * A convex polygon that denotes area without major obstacles . * It is not necessarily a real polygon, because its vertices * do not have to be on the same 3D plane (just "roughly"). * The walkable area within the polygon borders is rarely flat, too. ********************************************************************/ class psWalkPoly { friend class psWalkPolyMap; public: psWalkPoly(); ~psWalkPoly(); /** Adds a new vertex to polygon - vertices must be added CLOCKWISE ! */ void AddVert(const csVector3 & pos, int beforeIndex=-1); size_t GetNumVerts() { return verts.GetSize(); } void AddNode(psANode * node); void DeleteNode(psANode * node); void SetSector(iSector * sector); /** Moves 'point' (which must be within our polygon) towards 'goal' until it reaches another polygon or dead end. Returns true, if it reached another polygon, false on dead end */ bool MoveToNextPoly(const csVector3 & goal, csVector3 & point, psWalkPoly * & nextPoly); void AddSeeds(psMapWalker * walker, psSeedSet & seeds); /** Checks if polygon is still convex after we moved vertex 'vertNum' */ bool CheckConvexity(int vertNum); void Clear(); //ignores y void Cut(const csVector3 & cut1, const csVector3 & cut2); //ignores y void Intersect(const psWalkPoly & other); float EstimateY(const csVector3 & point); void Dump(const char * name); void DumpJS(const char * name); void DumpPureJS(); void DumpPolyJS(const char * name); int Stretch(psMapWalker & walker, psWalkPolyMap & map, float stepSize); void GlueToNeighbours(psMapWalker & walker, psWalkPolyMap & map); float GetBoxSize(); float GetArea(); float GetTriangleArea(int vertNum); float GetLengthOfEdges(); void GetShape(float & min, float & max); float GetNarrowness(); void PruneUnboundVerts(psMapWalker & walker); void PruneInLineVerts(); bool IsNearWalls(psMapWalker & walker, int vertNum); /** returns true if it moved at least a bit */ bool StretchVert(psMapWalker & walker, psWalkPolyMap & map, int vertNum, const csVector3 & newPos, float stepSize); void SetMini(psMapWalker & walker, const csVector3 & pos, int numVerts); /** Calculates box of polygon */ void CalcBox(); csBox3 & GetBox() { return box; } bool IsInLine(); void ClearInfo(); bool CollidesWithPolys(psWalkPolyMap & map, csList<psWalkPoly*> * polys); void SaveToString(csString & str); void LoadFromXML(iDocumentNode * node, csRef<iEngine> engine); /** Populates the 'conts' array */ void CalcConts(psWalkPolyMap & map); void RecalcAllEdges(); void ConnectNodeToPoly(psANode * node, bool bidirectional); bool TouchesPoly(psWalkPoly * poly); bool NeighboursTouchEachOther(); psANode * GetFirstNode(); int GetID() { return id; } iSector * GetSector() { return sector; } bool PointIsIn(const csVector3 & p, float maxRel=0); csVector3 GetClosestPoint(const csVector3 & point, float & angle); int GetNumConts(); size_t GetNumNodes() { return nodes.GetSize(); } bool ReachableFromNeighbours(); psWalkPoly* GetNearNeighbour(const csVector3 & pos, float maxDist); void DeleteContsWith(psWalkPoly * poly); bool NeighbourSupsMe(psWalkPoly* neighbour); void MovePointInside(csVector3 & point, const csVector3 & goal); protected: void RecalcEdges(int vertNum); int FindClosestEdge(const csVector3 pos); /** Finds contact of this polygon with another polygon that is at given point and edge */ psWalkPoly * FindCont(const csVector3 & point, int edgeNum); /** Moves 'point' to the closest point in the direction of 'goal' that is within our polygon (some point on polygon border). 'edgeNum' is number of the edge where the new point is */ bool MoveToBorder(const csVector3 & goal, csVector3 & point, int & edgeNum); /** Populates the 'edges' array according to 'verts' */ void CalcEdges(); int GetNeighbourIndex(int vertNum, int offset) const; bool HandleProblems(psMapWalker & walker, psWalkPolyMap & map, int vertNum, const csVector3 & oldPos); csVector3 GetClosestCollisionPoint(csList<psWalkPoly*> & collisions, ps2DLine & line); bool HandlePolyCollisions(psWalkPolyMap & map, int vertNum, const csVector3 & oldPos); int id; static int nextID; bool supl; csArray<psWalkPolyVert> verts; /** vertices of polygon */ iSector * sector; csBox3 box; /** box around polygon - taller than the real poly */ csArray<psANode*> nodes; }; #endif #endif
[ "whacko88@2752fbe2-5038-0410-9d0a-88578062bcef" ]
whacko88@2752fbe2-5038-0410-9d0a-88578062bcef
c7ad667771f2737d87dc1bcbb1062bb791a32891
39e9e8c8d4ca4e97c87f35670e0774920a2abe45
/Viscous/viscous_explicit.cpp
f68f3576d94040890d6259110772a44f661caa48
[]
no_license
aditya12398/QKFVS_2D
a15de68d4759c36fe6e19c995004aa6b39fe64fa
9d80d5f64f25f9235ab61d2c78333165473787e6
refs/heads/master
2020-06-14T13:46:01.679637
2019-08-09T02:38:01
2019-08-09T02:38:01
195,017,837
2
0
null
null
null
null
UTF-8
C++
false
false
26,153
cpp
/* This code is a solver for 2D Euler equations for compressible domain. It uses `Kinetic Flux Vector Splitting(KFVS)` to calculate fluxes across the edges of a cell and conserve them. The related equations can be found in the Reference: "J. C. Mandal, S. M. Deshpande - Kinetic Flux Vector Splitting For Euler Equations" at location ../References/Kinetic_Flux_Vector_Splitting Strongly Recommended: Use Visual Studio Code(text editor) while understanding the code. The comments are coupled appropriately with the functions and variables for easier understanding. */ #include <fstream> #include <iostream> #include <cmath> using namespace std; int max_edges, max_cells, max_iters; double Mach, aoa, cfl, limiter_const; double gma = 1.4, R = 287, Prandtl_number = 0.72; //Flow and material parameters double residue, max_res; //RMS Residue and maximum residue in the fluid domain int max_res_cell; //Cell number with maximum residue double pi = 4.0 * atan(1.0); //Structure to store edge data struct Edge { int lcell, rcell; //Holds cell numbers on either side of the edge. Prefix l stands for left and r for right. double nx, ny, mx, my; //Hold point data. Prefix m stands for midpoint and n for edge normal. double length; //Holds edge length data char status; //Specifies whether the edge is Internal(f), Wall(w) or Outer Boundary(o). }; //Structure to store cell data struct Cell { int *edge, noe, nbhs, *conn; //Holds enclosing edges and neighbour cell data. double area, cx, cy; //Area of the cell and cell centre coordinates double rho, u1, u2, pr, tp; //Values of density, x - velocity, y - velocity, pressure and temperature of the cell double u1x, u2x, u1y, u2y; //Velocity derivatives double tpx, tpy; //Temperature derivatives double flux[5]; //Kinetic Fluxes. Reference: See function `void KFVS_pos_flux(...)` double Unew[5], Uold[5]; //Corresponds to void backward_sweep() double q[5], qx[5], qy[5]; //Entropy Variables. Reference: See Boltzmann Equations }; struct Edge *edge; struct Cell *cell; //--------------------------Main function starts-------------------------- int main(int arg, char *argv[]) { void input_data(); void initial_conditions(); void q_variables(); void q_derivatives(); void f_derivatives(); void evaluate_flux(); void state_update(); void print_output(); ofstream outfile("./Output/Residue"); double res_old; input_data(); int T = 2; for (int t = 1; t <= max_iters; t++) { initial_conditions(); q_variables(); q_derivatives(); f_derivatives(); evaluate_flux(); state_update(); if (t == 1) res_old = residue; residue = log10(residue / res_old); if ((max_res) < -12 && (residue) < -12) { cout << "Convergence criteria reached.\n"; break; } cout << t << "\t" << residue << "\t" << max_res << "\t" << max_res_cell << endl; outfile << t << "\t" << residue << "\t" << max_res << "\t" << max_res_cell << endl; if (t == T) { T = T + 2; print_output(); } } print_output(); } //End of the main function /* This function reads flow and grid data from the files: Grid data: ogrid_viscous_dim Flow Parameters: fp_viscous */ void input_data() { ifstream infile("ogrid_viscous_dim"); ifstream infile2("fp_viscous"); //Input Flow Parameters infile2 >> Mach >> aoa >> cfl >> max_iters >> limiter_const; //Input Edge data infile >> max_edges; edge = new Edge[max_edges + 1]; for (int k = 1; k <= max_edges; k++) { infile >> edge[k].mx >> edge[k].my >> edge[k].lcell >> edge[k].rcell >> edge[k].status >> edge[k].nx >> edge[k].ny >> edge[k].length; } //Input Cell data infile >> max_cells; cell = new Cell[max_cells + 1]; for (int k = 1; k <= max_cells; k++) { infile >> cell[k].cx >> cell[k].cy >> cell[k].rho >> cell[k].u1 >> cell[k].u2 >> cell[k].pr >> cell[k].area >> cell[k].noe; cell[k].tp = cell[k].pr / (R * cell[k].rho); //Set enclosing edges cell[k].edge = new int[cell[k].noe + 1]; for (int r = 1; r <= cell[k].noe; r++) infile >> cell[k].edge[r]; //Set neighbours infile >> cell[k].nbhs; cell[k].conn = new int[cell[k].nbhs]; for (int r = 0; r < cell[k].nbhs; r++) infile >> cell[k].conn[r]; } infile.close(); infile2.close(); } //End of the function double *gauss_elimination(double matrix[5][(6)]) { int i, j, k; double *solution = new double[5]; double swap; //Pivot the matrix for diagonal dominance for (i = 0; i < 5; i++) { solution[i] = 0; double max = fabs(matrix[i][i]); int pos = i; for (j = i; j < 5; j++) { if (fabs(matrix[j][i]) > max) { pos = j; max = fabs(matrix[j][i]); } } //Swap the elements for (k = 0; k <= 5; k++) { swap = matrix[i][k]; matrix[i][k] = matrix[pos][k]; matrix[pos][k] = swap; } } //Convert the matrix to a lower triangle matrix for (i = 4; i > 0; i--) { for (j = i - 1; j >= 0; j--) { double d = (matrix[j][i] / matrix[i][i]); for (k = 5; k >= 0; k--) { matrix[j][k] -= d * matrix[i][k]; } } } solution[0] = matrix[0][5] / matrix[0][0]; for (i = 1; i < 5; i++) { solution[i] = matrix[i][5]; for (j = i - 1; j >= 0; j--) { solution[i] -= (solution[j] * matrix[i][j]); } solution[i] = solution[i] / matrix[i][i]; } return solution; } void construct_equation(int k, char var, double matrix[5][6]) { double sig_dxdx, sig_dydy, sig_dxdy; double sig_dxdxdx, sig_dydydy, sig_dxdxdy, sig_dxdydy; double sig_dxdxdxdx, sig_dydydydy, sig_dxdxdxdy, sig_dxdxdydy, sig_dxdydydy; double sig_dfdx, sig_dfdy, sig_dfdxdx, sig_dfdydy, sig_dfdxdy; double dx, dy, df; sig_dxdx = sig_dydy = sig_dxdy = sig_dxdxdx = sig_dydydy = sig_dxdxdy = sig_dxdydy = sig_dxdxdxdx = sig_dydydydy = sig_dxdxdxdy = sig_dxdxdydy = sig_dxdydydy = sig_dfdx = sig_dfdy = sig_dfdxdx = sig_dfdydy = sig_dfdxdy = 0; for (int i = 0; i < cell[k].nbhs; i++) { int p = cell[k].conn[i]; dx = cell[p].cx - cell[k].cx; dy = cell[p].cy - cell[k].cy; double dist = sqrt(dx * dx + dy * dy); //Distance between cell and edge midpoint double w = 1 / pow(dist, 2.0); //Least Squares weight if (var == 'u') df = cell[p].u1 - cell[k].u1; else if (var == 'v') df = cell[p].u2 - cell[k].u2; else if (var == 't') df = cell[p].tp - cell[k].tp; sig_dfdx += w * df * dx; sig_dfdy += w * df * dy; sig_dfdxdx += w * df * dx * dx; sig_dfdydy += w * df * dy * dy; sig_dfdxdy += w * df * dx * dy; sig_dxdx += w * dx * dx; sig_dxdy += w * dx * dy; sig_dydy += w * dy * dy; sig_dxdxdx += w * dx * dx * dx; sig_dxdxdy += w * dx * dx * dy; sig_dxdydy += w * dx * dy * dy; sig_dydydy += w * dy * dy * dy; sig_dxdxdxdx += w * dx * dx * dx * dx; sig_dxdxdxdy += w * dx * dx * dx * dy; sig_dxdxdydy += w * dx * dx * dy * dy; sig_dxdydydy += w * dx * dy * dy * dy; sig_dydydydy += w * dy * dy * dy * dy; } matrix[0][5] = sig_dfdx; matrix[1][5] = sig_dfdy; matrix[2][5] = sig_dfdxdx / 2; matrix[3][5] = sig_dfdydy / 2; matrix[4][5] = sig_dfdxdy; matrix[0][0] = sig_dxdx; matrix[1][1] = sig_dydy; matrix[2][2] = sig_dxdxdxdx / 4; matrix[3][3] = sig_dydydydy / 4; matrix[4][4] = sig_dxdxdydy; matrix[0][1] = matrix[1][0] = sig_dxdy; matrix[0][2] = matrix[2][0] = sig_dxdxdx / 2; matrix[0][3] = matrix[3][0] = sig_dxdydy / 2; matrix[0][4] = matrix[4][0] = sig_dxdxdy; matrix[1][2] = matrix[2][1] = sig_dxdxdy / 2; matrix[1][3] = matrix[3][1] = sig_dydydy / 2; matrix[1][4] = matrix[4][1] = sig_dxdydy; matrix[2][3] = matrix[3][2] = sig_dxdxdydy / 4; matrix[2][4] = matrix[4][2] = sig_dxdxdxdy / 2; matrix[3][4] = matrix[4][3] = sig_dxdydydy / 2; } void f_derivatives() { for (int k = 1; k <= max_cells; k++) { double matrix[5][6], *solution; //Derivative of velocity construct_equation(k, 'u', matrix); solution = gauss_elimination(matrix); cell[k].u1x = solution[0]; cell[k].u1y = solution[1]; delete[] solution; construct_equation(k, 'v', matrix); solution = gauss_elimination(matrix); cell[k].u2x = solution[0]; cell[k].u2y = solution[1]; delete[] solution; construct_equation(k, 't', matrix); solution = gauss_elimination(matrix); cell[k].tpx = solution[0]; cell[k].tpy = solution[1]; delete[] solution; } } void viscous_flux(double *G, int e, double nx, double ny, int CELL, double rho_ref, double u1_ref, double u2_ref, double pr_ref) { double u_dash[5], tp_dash[3]; double tauxx, tauyy, tauxy, t_ref, mu, kappa; t_ref = pr_ref / (R * rho_ref); mu = 1.458E-6 * pow(t_ref, 1.5) / (t_ref + 110.4); kappa = mu * (gma * R) / (Prandtl_number * (gma - 1)); u_dash[1] = (cell[CELL].u1x); u_dash[2] = (cell[CELL].u1y); u_dash[3] = (cell[CELL].u2x); u_dash[4] = (cell[CELL].u2y); tp_dash[1] = cell[CELL].tpx; tp_dash[2] = cell[CELL].tpy; tauxx = mu * (4 / 3 * u_dash[1] - 2 / 3 * u_dash[4]); tauyy = mu * (4 / 3 * u_dash[4] - 2 / 3 * u_dash[1]); tauxy = mu * (u_dash[2] + u_dash[3]); //Storing viscous fluxes if (edge[e].status == 'w') { tp_dash[1] = tp_dash[2] = 0; } G[1] = 0; G[2] = -(tauxx * nx + tauxy * ny); G[3] = -(tauxy * nx + tauyy * ny); G[4] = -((u1_ref * tauxx + u2_ref * tauxy + kappa * tp_dash[1]) * nx) + ((u1_ref * tauxy + u2_ref * tauyy + kappa * tp_dash[2]) * ny); } //Fluxes are evaluated in this function void evaluate_flux() { //Function Prototypes void linear_reconstruction(double *, int, int); void KFVS_pos_flux(double *, double, double, double, double, double, double); void KFVS_neg_flux(double *, double, double, double, double, double, double); void KFVS_wall_flux(double *, double, double, double, double, double, double); void KFVS_outer_flux(double *, double, double, double, double, double, double); double u_dash[5]; int lcell, rcell; double nx, ny, s; double Gp[5], Gn[5], Gd[5]; double Gwall[5], Gout[5]; double lprim[5], rprim[5]; char status; double rhol, u1l, u2l, prl; //Left Cell Data double rhor, u1r, u2r, prr; //Right Cell Data for (int k = 1; k <= max_edges; k++) { lcell = edge[k].lcell; rcell = edge[k].rcell; nx = edge[k].nx; ny = edge[k].ny; s = edge[k].length; status = edge[k].status; if (status == 'f') //Flux across interior edges { linear_reconstruction(lprim, lcell, k); linear_reconstruction(rprim, rcell, k); rhol = lprim[1]; u1l = lprim[2]; u2l = lprim[3]; prl = lprim[4]; rhor = rprim[1]; u1r = rprim[2]; u2r = rprim[3]; prr = rprim[4]; KFVS_pos_flux(Gp, nx, ny, rhol, u1l, u2l, prl); KFVS_neg_flux(Gn, nx, ny, rhor, u1r, u2r, prr); viscous_flux(Gd, k, nx, ny, lcell, rhol, u1l, u2l, prl); viscous_flux(Gd, k, nx, ny, rcell, rhor, u1r, u2r, prr); for (int r = 1; r <= 4; r++) { cell[lcell].flux[r] = cell[lcell].flux[r] + s * (*(Gp + r) + *(Gn + r) + *(Gd + r)); cell[rcell].flux[r] = cell[rcell].flux[r] - s * (*(Gp + r) + *(Gn + r) + *(Gd + r)); } } if (status == 'w') //Flux across wall edge { if (lcell == 0) { nx = -nx; ny = -ny; lcell = rcell; } linear_reconstruction(lprim, lcell, k); rhol = lprim[1]; u1l = lprim[2]; u2l = lprim[3]; prl = lprim[4]; KFVS_wall_flux(Gwall, nx, ny, rhol, u1l, u2l, prl); viscous_flux(Gd, k, nx, ny, lcell, rhol, 0, 0, prl); for (int r = 1; r <= 4; r++) cell[lcell].flux[r] = cell[lcell].flux[r] + s * (*(Gwall + r) + *(Gd + r)); } if (status == 'o') //Flux across outer boundary edge { if (lcell == 0) { nx = -nx; ny = -ny; lcell = rcell; } linear_reconstruction(lprim, lcell, k); rhol = lprim[1]; u1l = lprim[2]; u2l = lprim[3]; prl = lprim[4]; KFVS_outer_flux(Gout, nx, ny, rhol, u1l, u2l, prl); viscous_flux(Gd, k, nx, ny, lcell, rhol, u1l, u2l, prl); for (int r = 1; r <= 4; r++) cell[lcell].flux[r] = cell[lcell].flux[r] + s * (*(Gout + r) + *(Gd + r)); } } //End of k loop } //End of the flux function //Expressions for the kfvs - fluxes /* Function to find the kfvs - positive flux The following function uses the G Flux equations. Reference: J. C. Mandal, S. M. Deshpande - Kinetic Flux Vector Splitting For Euler Equations; Page 7 of 32; Book Page Number 453 Reference Location: ../References/Kinetic_Flux_Vector_Splitting/ */ void KFVS_pos_flux(double *G, double nx, double ny, double rho, double u1, double u2, double pr) { double tx, ty; tx = ny; ty = -nx; double un = u1 * nx + u2 * ny; double ut = u1 * tx + u2 * ty; double beta = 0.5 * rho / pr; double S = un * sqrt(beta); double A = 0.5 * (1 + erf(S)); double B = 0.5 * exp(-S * S) / sqrt(pi * beta); *(G + 1) = rho * (un * A + B); double temp1 = (pr + rho * un * un) * A + rho * un * B; double temp2 = rho * (un * ut * A + ut * B); *(G + 2) = -ty * temp1 + ny * temp2; *(G + 3) = tx * temp1 - nx * temp2; temp1 = 0.5 * rho * (un * un + ut * ut); *(G + 4) = ((gma / (gma - 1)) * pr + temp1) * un * A + (((gma + 1) / (2 * (gma - 1))) * pr + temp1) * B; } //End of G-positive flux /* Function to find the kfvs - negative flux The following function uses the G Flux equations. Reference: J. C. Mandal, S. M. Deshpande - Kinetic Flux Vector Splitting For Euler Equations; Page 7 of 32; Book Page Number 453 Reference Location: ../References/Kinetic_Flux_Vector_Splitting/ */ void KFVS_neg_flux(double *G, double nx, double ny, double rho, double u1, double u2, double pr) { double tx, ty; tx = ny; ty = -nx; double un = u1 * nx + u2 * ny; double ut = u1 * tx + u2 * ty; double beta = 0.5 * rho / pr; double S = un * sqrt(beta); double A = 0.5 * (1 - erf(S)); double B = 0.5 * exp(-S * S) / sqrt(pi * beta); *(G + 1) = rho * (un * A - B); double temp1 = (pr + rho * un * un) * A - rho * un * B; double temp2 = rho * (un * ut * A - ut * B); *(G + 2) = -ty * temp1 + ny * temp2; *(G + 3) = tx * temp1 - nx * temp2; temp1 = 0.5 * rho * (un * un + ut * ut); *(G + 4) = ((gma / (gma - 1)) * pr + temp1) * un * A - (((gma + 1) / (2 * (gma - 1))) * pr + temp1) * B; } //End of G-negative flux /* Function to find the kfvs - wall boundary flux The following function uses the G Flux equations. Reference: J. C. Mandal, S. M. Deshpande - Kinetic Flux Vector Splitting For Euler Equations; Page 7 of 32; Book Page Number 453 Reference Location: ../References/Kinetic_Flux_Vector_Splitting/ */ void KFVS_wall_flux(double *G, double nx, double ny, double rho, double u1, double u2, double pr) { double un, ut; ut = 0.0; //No slip boundary condition un = 0.0; double beta = 0.5 * rho / pr; double Sw = un * sqrt(beta); double Aw = 0.5 * (1 + erf(Sw)); double Bw = 0.5 * exp(-Sw * Sw) / sqrt(pi * beta); double temp = (pr + rho * un * un) * Aw + rho * un * Bw; temp = 2.0 * temp; *(G + 1) = 0.0; *(G + 2) = nx * temp; *(G + 3) = ny * temp; *(G + 4) = 0.0; } //End of the wall flux function /* Function to find the kfvs - outer boundary flux The following function uses the G Flux equations. Reference: J. C. Mandal, S. M. Deshpande - Kinetic Flux Vector Splitting For Euler Equations; Page 7 of 32; Book Page Number 453 Reference Location: ../References/Kinetic_Flux_Vector_Splitting/ */ void KFVS_outer_flux(double *Gout, double nx, double ny, double rho, double u1, double u2, double pr) { void KFVS_pos_flux(double *, double, double, double, double, double, double); void KFVS_neg_flux(double *, double, double, double, double, double, double); double Gp[5]; double Gn_inf[5]; double rho_inf, u1_inf, u2_inf, pr_inf, u_ref; u_ref = sqrt(gma * R * 288.20); double theta = aoa * pi / 180; rho_inf = 1.225; u1_inf = u_ref * Mach * cos(theta); u2_inf = u_ref * Mach * sin(theta); pr_inf = 101325.0; KFVS_pos_flux(Gp, nx, ny, rho, u1, u2, pr); KFVS_neg_flux(Gn_inf, nx, ny, rho_inf, u1_inf, u2_inf, pr_inf); for (int r = 1; r <= 4; r++) *(Gout + r) = *(Gp + r) + *(Gn_inf + r); } //End of the function //Function to find the conserved vector from the given primitive vector void prim_to_conserved(double *U, int k) { double rho, u1, u2, pr, e; rho = cell[k].rho; u1 = cell[k].u1; u2 = cell[k].u2; pr = cell[k].pr; e = (1 / (gma - 1)) * pr / rho + 0.5 * (u1 * u1 + u2 * u2); *(U + 1) = rho; *(U + 2) = rho * u1; *(U + 3) = rho * u2; *(U + 4) = rho * e; } //End of the function //Function to get the primitive vector from the given conserved vector void conserved_to_primitive(double *U, int k) { double U1 = *(U + 1); double U2 = *(U + 2); double U3 = *(U + 3); double U4 = *(U + 4); cell[k].rho = U1; double temp = 1 / U1; cell[k].u1 = U2 * temp; cell[k].u2 = U3 * temp; temp = U4 - (0.5 * temp) * (U2 * U2 + U3 * U3); cell[k].pr = 0.4 * temp; cell[k].tp = cell[k].pr / (R * cell[k].rho); } //End of the function //Function to find the delt (delta t) for each cell double func_delt(int k) { double smallest_dist(int); double rho, u1, u2, pr; double area, temp1, smin; int edges, e; double nx, ny, delt_inv = 0.0, delt_visc = 0.0; area = cell[k].area; u1 = cell[k].u1; u2 = cell[k].u2; rho = cell[k].rho; pr = cell[k].pr; smin = smallest_dist(k); edges = cell[k].noe; temp1 = 3.0 * sqrt(pr / rho); for (int r = 1; r <= edges; r++) { e = cell[k].edge[r]; double length = edge[e].length; nx = edge[e].nx; ny = edge[e].ny; if (edge[e].rcell == k) { nx = -nx; ny = -ny; } double un = u1 * nx + u2 * ny; double temp2 = (fabs(un) + temp1); temp2 = length * temp2; delt_inv = delt_inv + temp2; } double mu = 1.458E-6 * pow(cell[k].tp, 1.5) / (cell[k].tp + 110.4); delt_inv = 2.0 * area / delt_inv; delt_visc = rho * Prandtl_number * smin * smin / (4 * mu * gma); double delt = 1 / ((1 / delt_inv) + (1 / delt_visc)); return (cfl * delt); } //End of the function //Function to give the initial conditions void initial_conditions() { double rho, u1, u2, pr, e, U[5]; for (int k = 1; k <= max_cells; k++) { rho = cell[k].rho; u1 = cell[k].u1; u2 = cell[k].u2; pr = cell[k].pr; e = (1 / (gma - 1)) * pr / rho + 0.5 * (u1 * u1 + u2 * u2); U[1] = rho; U[2] = rho * u1; U[3] = rho * u2; U[4] = rho * e; for (int r = 1; r <= 4; r++) { cell[k].flux[r] = 0.0; cell[k].Uold[r] = U[r]; cell[k].Unew[r] = U[r]; } } } //End of the function void state_update() { void prim_to_conserved(double *, int); void conserved_to_primitive(double *, int); residue = 0.0; max_res = 0.0; double U[5]; for (int k = 1; k <= max_cells; k++) { prim_to_conserved(U, k); double temp = U[1]; for (int r = 1; r <= 4; r++) { cell[k].Unew[r] = cell[k].Uold[r] - func_delt(k) * cell[k].flux[r] / cell[k].area; U[r] = cell[k].Unew[r]; cell[k].Uold[r] = cell[k].Unew[r]; } residue = residue + (temp - U[1]) * (temp - U[1]); temp = fabs(temp - U[1]); if (max_res < temp) { max_res = temp; max_res_cell = k; } conserved_to_primitive(U, k); } residue = residue / max_cells; residue = sqrt(residue); } //End of the function //Function writes the data in supported tecplot format void write_tecplot() { static int count = 1; string title =to_string(count++) + "_Solution_Tecplot_Explicit.dat"; ofstream tecplotfile("./Output/" + title); tecplotfile << "TITLE: \"QKFVS Viscous Code - NAL\"\n"; tecplotfile << "VARIABLES= \"X\", \"Y\", \"Density\", \"Pressure\", \"x-velocity\", \"y-velocity\", \"Velocity Magnitude\", \"Temperature\"\n"; tecplotfile << "ZONE I= 298 J= 179, DATAPACKING=BLOCK\n"; for (int j = 1; j < 180; j++) { for (int i = 1; i <= 298; i++) { int k = (j - 1) * 298 + i; tecplotfile << cell[k].cx << "\n"; } } tecplotfile << "\n"; for (int j = 1; j < 180; j++) { for (int i = 1; i <= 298; i++) { int k = (j - 1) * 298 + i; tecplotfile << cell[k].cy << "\n"; } } tecplotfile << "\n"; for (int j = 1; j < 180; j++) { for (int i = 1; i <= 298; i++) { int k = (j - 1) * 298 + i; tecplotfile << cell[k].rho << "\n"; } } tecplotfile << "\n"; for (int j = 1; j < 180; j++) { for (int i = 1; i <= 298; i++) { int k = (j - 1) * 298 + i; tecplotfile << cell[k].pr << "\n"; } } tecplotfile << "\n"; for (int j = 1; j < 180; j++) { for (int i = 1; i <= 298; i++) { int k = (j - 1) * 298 + i; tecplotfile << cell[k].u1 << "\n"; } } tecplotfile << "\n"; for (int j = 1; j < 180; j++) { for (int i = 1; i <= 298; i++) { int k = (j - 1) * 298 + i; tecplotfile << cell[k].u2 << "\n"; } } tecplotfile << "\n"; for (int j = 1; j < 180; j++) { for (int i = 1; i <= 298; i++) { int k = (j - 1) * 298 + i; tecplotfile << sqrt(pow(cell[k].u1, 2) + pow(cell[k].u2, 2)) << "\n"; } } tecplotfile << "\n"; for (int j = 1; j < 180; j++) { for (int i = 1; i <= 298; i++) { int k = (j - 1) * 298 + i; tecplotfile << cell[k].tp << "\n"; } } tecplotfile << "\n"; tecplotfile.close(); } //Function which prints the final primitive vector into the file "primitive-vector.dat" void print_output() { ofstream outfile("./Output/Primitive-Vector.dat"); for (int k = 1; k <= max_cells; k++) { outfile << k << "\t" << cell[k].rho << "\t" << cell[k].u1 << "\t" << cell[k].u2 << "\t" << cell[k].pr << endl; } write_tecplot(); } //End of the function /* Second order part of the code starts from here Second order accuracy is achieved via linear reconstruction with q-variables */ //Function to calculate the q-variables for all the nodes void q_variables() { int i; double rho, u1, u2, pr, beta; for (i = 1; i <= max_cells; i++) { rho = cell[i].rho; u1 = cell[i].u1; u2 = cell[i].u2; pr = cell[i].pr; beta = 0.5 * rho / pr; cell[i].q[1] = log(rho) + (log(beta) * (1 / (gma - 1))) - beta * (u1 * u1 + u2 * u2); cell[i].q[2] = 2 * beta * u1; cell[i].q[3] = 2 * beta * u2; cell[i].q[4] = -2 * beta; } } //End of the function //Function to convert q-varibales to primitive variables void func_qtilde_to_prim_variables(double *prim, double *qtilde) { double q1, q2, q3, q4, beta, u1, u2; q1 = *(qtilde + 1); q2 = *(qtilde + 2); q3 = *(qtilde + 3); q4 = *(qtilde + 4); beta = -q4 * 0.5; double temp = 0.5 / beta; *(prim + 2) = q2 * temp; *(prim + 3) = q3 * temp; u1 = *(prim + 2); u2 = *(prim + 3); double temp1 = q1 + beta * (u1 * u1 + u2 * u2); //double temp2 = temp1 - (log(beta)/(gma-1)); temp1 = temp1 - (log(beta) * (1 / (gma - 1))); *(prim + 1) = exp(temp1); *(prim + 4) = *(prim + 1) * temp; } //End of the function //Function to find q-derivatives using the method of least squares void q_derivatives() { //double power = 2.0; for (int k = 1; k <= max_cells; k++) { //Initialise the sigma values double sig_dxdx = 0.0; double sig_dydy = 0.0; double sig_dxdy = 0.0; double sig_dxdq[5], sig_dydq[5]; for (int r = 1; r <= 4; r++) { sig_dxdq[r] = 0.0; sig_dydq[r] = 0.0; } for (int j = 0; j < cell[k].nbhs; j++) { int p = cell[k].conn[j]; double delx = cell[p].cx - cell[k].cx; double dely = cell[p].cy - cell[k].cy; double dist = sqrt(delx * delx + dely * dely); double w = 1 / pow(dist, 2.0); sig_dxdx = sig_dxdx + w * delx * delx; sig_dydy = sig_dydy + w * dely * dely; sig_dxdy = sig_dxdy + w * delx * dely; for (int r = 1; r <= 4; r++) { double delq = cell[p].q[r] - cell[k].q[r]; sig_dxdq[r] = sig_dxdq[r] + w * delx * delq; sig_dydq[r] = sig_dydq[r] + w * dely * delq; } } double det = sig_dxdx * sig_dydy - sig_dxdy * sig_dxdy; for (int r = 1; r <= 4; r++) { double detx = sig_dydy * sig_dxdq[r] - sig_dxdy * sig_dydq[r]; double dety = sig_dxdx * sig_dydq[r] - sig_dxdy * sig_dxdq[r]; cell[k].qx[r] = detx / det; cell[k].qy[r] = dety / det; } } //End of k loop } //End of the function //Function to find the linear reconstruction values of primitive variables at the mid point of a given edge void linear_reconstruction(double *prim, int CELL, int edg) { void limiter(double *, double *, int); void func_qtilde_to_prim_variables(double *, double *); double delx, dely, phi[5], qtilde[5]; delx = edge[edg].mx - cell[CELL].cx; dely = edge[edg].my - cell[CELL].cy; for (int r = 1; r <= 4; r++) qtilde[r] = cell[CELL].q[r] + delx * cell[CELL].qx[r] + dely * cell[CELL].qy[r]; //limiter(qtilde, phi, CELL); /*for (int r = 1; r <= 4; r++) qtilde[r] = cell[CELL].q[r] + phi[r] * (delx * cell[CELL].qx[r] + dely * cell[CELL].qy[r]);*/ func_qtilde_to_prim_variables(prim, qtilde); } //End of the function //Function to find the limiter void limiter(double *qtilde, double *phi, int k) { double maximum(int, int); double minimum(int, int); double smallest_dist(int); double max_q, min_q, temp; double q, del_neg, del_pos; for (int r = 1; r <= 4; r++) { q = cell[k].q[r]; del_neg = qtilde[r] - q; if (fabs(del_neg) <= 10e-6) phi[r] = 1.0; else { if (del_neg > 0.0) { max_q = maximum(k, r); del_pos = max_q - q; } else if (del_neg < 0.0) { min_q = minimum(k, r); del_pos = min_q - q; } double num, den, ds; ds = smallest_dist(k); double epsi = limiter_const * ds; epsi = pow(epsi, 3.0); num = (del_pos * del_pos) + (epsi * epsi); num = num * del_neg + 2.0 * del_neg * del_neg * del_pos; den = del_pos * del_pos + 2.0 * del_neg * del_neg; den = den + del_neg * del_pos + epsi * epsi; den = den * del_neg; temp = num / den; if (temp < 1.0) phi[r] = temp; else phi[r] = 1.0; } } } //End of the function double maximum(int k, int r) { double max = cell[k].q[r]; for (int j = 0; j < cell[k].nbhs; j++) { int p = cell[k].conn[j]; if (cell[p].q[r] > max) max = cell[p].q[r]; } return (max); } //End of the function double minimum(int k, int r) { double min = cell[k].q[r]; for (int j = 0; j < cell[k].nbhs; j++) { int p = cell[k].conn[j]; if (cell[p].q[r] < min) min = cell[p].q[r]; } return (min); } //End of the function //Finding the dels; the smallest distance measured over the neighbours of a given cell double smallest_dist(int k) { int p; double dx, dy, ds, min; for (int j = 0; j < cell[k].nbhs; j++) { p = cell[k].conn[j]; dx = cell[p].cx - cell[k].cx; dy = cell[p].cy - cell[k].cy; ds = sqrt(dx * dx + dy * dy); if (j == 0) min = ds; if (ds < min) min = ds; } return (ds); } //End of the function
dd17aea02e2bcc6fc9c62ed475cbe61630ff9bd4
d017b807b3753800feef6b8077d084b460027e46
/cpp/AlignParametric/ParticleSurface.cpp
fe23b164543c2453c78ca40248b79256e1172a1e
[]
no_license
awturner/awturner-phd
de64cc0c23e1195df59ea9ac6ebfa8e24ee55f88
d8280b5602476565d97586854566c93fefe1d431
refs/heads/master
2016-09-06T04:47:14.802338
2011-06-02T22:33:27
2011-06-02T22:33:27
32,140,837
0
0
null
null
null
null
UTF-8
C++
false
false
8,158
cpp
/* * ################################################################################ * ### MIT License * ################################################################################ * * Copyright (c) 2006-2011 Andy Turner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "AlignParametric/ParticleSurface.h" #include "Mesh/TuplesImpl.h" #include "Mesh/MeshFunctions.h" #include "Mesh/TuplesFunctions.h" #include "MeshSearching/FacesNearestPointSearch.h" #include "Useful/Noise.h" #include "Useful/ColouredConsole.h" #include <vector> #include <algorithm> #include "vnl/vnl_matrix_fixed.h" #include "Useful/ArrayVectorFunctions.h" using namespace AWT; using namespace AWT::AlignParametric; AWT::AlignParametric::ParticleSurface::ParticleSurface(MeshType::P mesh, const TuplesType::P samples, const Idx _ntake) { // Keep a hold of the mesh this->mesh = mesh; calculateFaceNormals(); const Idx ntake = std::min<Idx>(_ntake, samples->getNumberOfPoints()); DEBUGMACRO("Only taking " << ntake); // Take just the first 10 samples this->samples = TuplesImpl<T>::getInstance(3, ntake); for (Idx i = 0; i < ntake; ++i) { T vtx[3]; samples->getPoint(i, vtx); this->samples->setPoint(i, vtx); } // Calculate the 5th-%ile triangle area, use this to avoid truncation error std::vector<T> areas; MESH_EACHFACE(mesh, f) areas.push_back(MeshFunctions<T>::getFaceArea(mesh, f)); sort(areas.begin(), areas.end()); maxMove = sqrt(areas[ areas.size() * 5 / 100 ]) / 2; PRINTVBL(maxMove); } void AWT::AlignParametric::ParticleSurface::initialize() { DEBUGLINE; setPointLocationsInitial(); } AWT::AlignParametric::ParticleSurface::~ParticleSurface() { } // Get the number of parameter components describing each sample Idx AWT::AlignParametric::ParticleSurface::getParameterDimensionality() const { return 3; } // Get the number of samples on the surface Idx AWT::AlignParametric::ParticleSurface::getNumberOfSamples() const { return samples->getNumberOfPoints(); } // Get the current sample locations // NOTE: This should be in HOMOGENEOUS form, i.e. samples.rows() = Dims + 1 // The last row should be all ones, or weird things will happen... void AWT::AlignParametric::ParticleSurface::getSamples(MatrixType& samples) const { if (samples.rows() != 4 || samples.cols() != getNumberOfSamples()) samples.set_size(4, getNumberOfSamples()); T vtx[4]; for (Idx i = 0, imax = getNumberOfSamples(); i < imax; ++i) { this->samples->getPoint(i, vtx); vtx[3] = 1; samples.set_column(i, vtx); } } T AWT::AlignParametric::ParticleSurface::getMaxMove() const { return maxMove; } // Get the number of parameters which control this sampling Idx AWT::AlignParametric::ParticleSurface::getNumberOfParameters() const { return samples->getNumberOfPoints(); } // Get the current set of control values void AWT::AlignParametric::ParticleSurface::getParameters(MatrixType& controls) const { if (controls.rows() != getNumberOfParameters() || controls.cols() != 3) controls.set_size(getNumberOfParameters(), 3); T vtx[3]; for (Idx i = 0, imax = getNumberOfParameters(); i < imax; ++i) { samples->getPoint(i,vtx); controls.set_row(i, vtx); } } void AWT::AlignParametric::ParticleSurface::jacobian(const Idx l, const Idx p, MatrixType& matrix) const { // Nice and easy Jacobian... if (l == p) { matrix.set_identity(); return; T nml[3]; faceNormals->getPoint(particleFace[l], nml); for (Idx r = 0; r < 3; ++r) for (Idx c = 0; c < 3; ++c) matrix(r,c) -= nml[r]*nml[c]; } else { matrix.fill(0); } } void AWT::AlignParametric::ParticleSurface::splitParticle(const Idx p, const T* theShift) { ColouredConsole cons(ColouredConsole::COL_YELLOW); FacesNearestPointSearch<T>::P searcher = FacesNearestPointSearch<T>::getInstance(); T vtx[4]; const T mults[] = { -0.5, 0.5 }; const Idx idxs[] = { p, samples->getNumberOfPoints() }; // Push back a face into the list (will be overwritten soon enough) particleFace.push_back(INVALID_INDEX); for (Idx i = 0; i < 2; ++i) { // Get the sample location samples->getPoint(p, vtx); FOREACHAXIS(ax) vtx[ax] += mults[i]*theShift[ax]; vtx[3] = 1; updatePointLocation(idxs[i], vtx, searcher); samples->getPoint(idxs[i], vtx); //PRINTVBL(idxs[i]); //PRINTVEC(vtx, 4); } modified(); } void AWT::AlignParametric::ParticleSurface::refine() { } // Iterator functions - allows you to skip all the zero jacobians // Takes the internal iterPtr back to the start void AWT::AlignParametric::ParticleSurface::resetIterator() { iterPtr = 0; } // Advances to the next non-zero jacobian pair bool AWT::AlignParametric::ParticleSurface::next(Idx& l, Idx& p) { bool ret = iterPtr < samples->getNumberOfPoints(); if (ret) l = p = iterPtr++; else l = p = INVALID_INDEX; return ret; } MeshType::P AWT::AlignParametric::ParticleSurface::getMesh() { return mesh; } TuplesType::P AWT::AlignParametric::ParticleSurface::getSamples() { return samples; } // Projects the point to the closest point on the mesh surface int AWT::AlignParametric::ParticleSurface::updatePointLocation(const Idx i, const T* vtx, FacesNearestPointSearch<T>::P searcher) { searcher->reset(); searcher->setTestPoint(vtx); mesh->searchFaces(searcher); T vtxNearest[3]; int np = searcher->getNearestPoint(vtxNearest); particleFace[i] = np; samples->setPoint(i, vtxNearest); return np; } void AWT::AlignParametric::ParticleSurface::calculateFaceNormals() { T vtx[3][3]; faceNormals = TuplesImpl<T>::getInstance(3, mesh->getNumberOfFaces()); MESH_EACHFACE(mesh, f) { mesh->getFace(f, vtx[0], vtx[1], vtx[2]); FOREACHAXIS(ax) { vtx[2][ax] -= vtx[0][ax]; vtx[1][ax] -= vtx[0][ax]; } cross<T>(vtx[1], vtx[2], vtx[0]); normalize<T>(vtx[0], 3); faceNormals->setPoint(f, vtx[0]); } } void AWT::AlignParametric::ParticleSurface::setPointLocationsInitial() { FacesNearestPointSearch<T>::P searcher = FacesNearestPointSearch<T>::getInstance(); T vtx[4]; // Make sure that the list of particleFaces is allocated particleFace.clear(); for (Idx i = 0, imax = samples->getNumberOfPoints(); i < imax; ++i) { // Get the sample location samples->getPoint(i, vtx); vtx[3] = 1; // Push back a face into the list (will be overwritten soon enough) particleFace.push_back(INVALID_INDEX); updatePointLocation(i, vtx, searcher); } } void AWT::AlignParametric::ParticleSurface::setParameters(MatrixType& controls) { FacesNearestPointSearch<T>::P searcher = FacesNearestPointSearch<T>::getInstance(); T vtx[3]; for (Idx i = 0, imax = samples->getNumberOfPoints(); i < imax; ++i) { vtx[0] = controls(i,0); vtx[1] = controls(i,1); vtx[2] = controls(i,2); updatePointLocation(i, vtx, searcher); } }
[ "[email protected]@8ccf9804-531a-5bdb-f4a8-09d094668cd7" ]
[email protected]@8ccf9804-531a-5bdb-f4a8-09d094668cd7
44b94554cc137ced854f5fb6ef33318f04501a52
314b60210cdf0d9b2b3b957ea7ae7ddadeb7ae2f
/Part A/SimplePerson.cpp
3d8f21856d8a28479bd5512086867cef8b8ba740
[ "MIT" ]
permissive
burakkorki/Phonebook
e354fcad38fd3f88cae226ec030137bd032915a3
3bed6d2814e5d23360cade3188b8e2c98394b0e2
refs/heads/master
2020-06-28T03:11:36.762584
2019-08-01T23:06:26
2019-08-01T23:06:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
480
cpp
// // SimplePerson.cpp // Homework 3 // // Created by Burak Korkmaz on 13.12.2018. // Copyright © 2018 Burak Korkmaz. All rights reserved. // #include "SimplePerson.h" Person::Person(string name){ this->name = name; } Person::~Person(){ this->name = ""; } Person::Person( const Person &personToCopy ){ this->name = personToCopy.name; } void Person::operator=(const Person &right){ this->name = right.name; } string Person::getName(){ return name; }
cc0cfe4e0e20d2e27a63ccd039148c64d61b17ae
2a4e358ec62ecdce75920144ff8582a5dc6555ae
/Power Modulo/power_modulo.cpp
b192132ec8843edc302b088bbc6c807931cdade9
[]
no_license
lienordni/Algorithms
d8bb3f1f1f7ce7aa869b0d899f40c09f322d31ac
0be73007dee67ed862a5eb2362bafb581f7ee8b1
refs/heads/master
2021-08-31T12:38:20.319729
2017-12-21T09:36:57
2017-12-21T09:36:57
110,966,876
0
0
null
null
null
null
UTF-8
C++
false
false
378
cpp
#include <bits/stdc++.h> using namespace std; #define mod (long long) (1e9 + 7) long long power(long long x, long long n) { if(n==0) return 1; if(n==1) return x%mod; long long s=power(x,n/2); if(n%2==0) return (s*s)%mod; return (x*((s*s)%mod))%mod; } int main() { ios::sync_with_stdio(false); long long x,n; cin>>x>>n; cout<<power(x,n)<<endl; return 0; }
fc9fddea6754628cbc79b0506c72b8454aa1b4fd
d077c568339344b5efa4ab80a5b01b771413e95c
/tests/Dynamic/AttackReleaseFilter.cpp
785dbf90ae3fae08be73d13d562482c88da5b2ba
[ "BSD-3-Clause" ]
permissive
icewwn/AudioTK
b26e4bfae7894c021a8b6d04f7924fc9b7c6f818
4f7f2b76dce2d6cfa7deef484fa069922935e744
refs/heads/master
2021-01-09T20:54:17.818767
2015-07-20T15:22:59
2015-07-20T15:22:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,520
cpp
/** * \ file AttackReleaseFilter.cpp */ #include <ATK/Dynamic/AttackReleaseFilter.h> #include <ATK/Core/InPointerFilter.h> #include <ATK/Core/OutPointerFilter.h> #define BOOST_TEST_DYN_LINK #define BOOST_TEST_NO_MAIN #include <boost/test/unit_test.hpp> #include <boost/math/constants/constants.hpp> #include <boost/scoped_array.hpp> #define PROCESSSIZE (1024*64) BOOST_AUTO_TEST_CASE( AttackReleaseFilter_sinus_test ) { boost::scoped_array<float> data(new float[PROCESSSIZE]); for(int64_t i = 0; i < PROCESSSIZE/2; ++i) { data[i] = i / 48000; } for(int64_t i = 0; i < PROCESSSIZE/2; ++i) { data[PROCESSSIZE/2 + i] = (PROCESSSIZE/2 - i) / 48000; } ATK::InPointerFilter<float> generator(data.get(), 1, PROCESSSIZE, false); generator.set_output_sampling_rate(48000); boost::scoped_array<float> outdata(new float[PROCESSSIZE]); ATK::AttackReleaseFilter<float> filter(1); filter.set_attack(std::exp(-1./(48000 * 1e-3))); filter.set_release(std::exp(-1./(48000 * 100e-3))); filter.set_input_sampling_rate(48000); filter.set_input_port(0, &generator, 0); ATK::OutPointerFilter<float> output(outdata.get(), 1, PROCESSSIZE, false); output.set_input_sampling_rate(48000); output.set_input_port(0, &filter, 0); output.process(PROCESSSIZE); for(int64_t i = 0; i < PROCESSSIZE/2; ++i) { BOOST_REQUIRE_GE(data[i], outdata[i]); } for(int64_t i = 0; i < PROCESSSIZE/2; ++i) { BOOST_REQUIRE_GE(outdata[PROCESSSIZE/2+i], outdata[PROCESSSIZE/2+i-1]); } }
b2a68c861f548a1dbfe1b7fc66b6f804f7be68c1
c328d66194c4edeb617298dd9cef3e786372eef6
/level_zero/tools/source/sysman/memory/memory.cpp
8173d93fc9ece8f5d5e38a8a030ab7ba2a18cd3b
[ "MIT" ]
permissive
kala9012/compute-runtime
0fb966105b785e995ae2a6d022bc70a3e0bee84a
a60b8c48317000fe865c9fafc4ec3253993bb714
refs/heads/master
2022-12-02T09:53:49.438305
2020-08-08T18:57:25
2020-08-08T18:57:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,351
cpp
/* * Copyright (C) 2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "shared/source/helpers/basic_math.h" #include "shared/source/memory_manager/memory_manager.h" #include "level_zero/core/source/device/device.h" #include "level_zero/tools/source/sysman/memory/memory_imp.h" namespace L0 { MemoryHandleContext::~MemoryHandleContext() { for (Memory *pMemory : handleList) { delete pMemory; } } ze_result_t MemoryHandleContext::init() { Device *device = L0::Device::fromHandle(hCoreDevice); isLmemSupported = device->getDriverHandle()->getMemoryManager()->isLocalMemorySupported(device->getRootDeviceIndex()); if (isLmemSupported) { Memory *pMemory = new MemoryImp(pOsSysman, hCoreDevice); handleList.push_back(pMemory); } return ZE_RESULT_SUCCESS; } ze_result_t MemoryHandleContext::memoryGet(uint32_t *pCount, zes_mem_handle_t *phMemory) { uint32_t handleListSize = static_cast<uint32_t>(handleList.size()); uint32_t numToCopy = std::min(*pCount, handleListSize); if (0 == *pCount || *pCount > handleListSize) { *pCount = handleListSize; } if (nullptr != phMemory) { for (uint32_t i = 0; i < numToCopy; i++) { phMemory[i] = handleList[i]->toHandle(); } } return ZE_RESULT_SUCCESS; } } // namespace L0
895958189cb93fa53ce6549b8c30de6770165a46
11c4a0842241d67b8df247cb789a47657fda1a5d
/code/codeforces/69D.cpp
8dc37e94a3ef7f18465d15948faa39e1e2365c1d
[]
no_license
aaahexing/derp-ironman
54f82797f8b1c855e708948b6710785053fb6a3f
f53cd863102344c8259e0f0a4a8fd0ecf3d821c8
refs/heads/master
2021-01-20T07:46:00.755199
2014-08-19T17:51:36
2014-08-19T17:51:36
4,429,833
0
1
null
null
null
null
UTF-8
C++
false
false
753
cpp
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; int a, b, n, d, x[21], y[21], dp[810][810][2][2]; int gao(int a, int b, int v1, int v2) { int &ret = dp[a + 400][b + 400][v1][v2]; if (ret != -1) return ret; if (a * a + b * b > d * d) { return ret = 1; } if (v1 && !gao(b, a, v2, 0)) { return ret = 1; } for (int i = 0; i < n; ++i) { if (!gao(a + x[i], b + y[i], v2, v1)) return ret = 1; if (v1 && !gao(b + y[i], a + x[i], v2, 0)) return ret = 1; } return ret = 0; } int main() { while (scanf("%d%d%d%d", &a, &b, &n, &d) != EOF) { for (int i = 0; i < n; ++i) scanf("%d%d", &x[i], &y[i]); memset(dp, -1, sizeof(dp)); printf("%s\n", gao(a, b, 1, 1) ? "Anton" : "Dasha"); } return 0; }
715552689425a4d425f9bfd1ebae94a19d690c06
9e34cb0e055dad7d0c1a1182d96a510c39331c63
/sdk/angelscript/source/as_gc.h
8bf0690e38b998a22b880bdbb45db0bc374e993e
[]
no_license
jacobsologub/angelscript-module
25ea6ae1101abca9cccf8a1a034bd04376e5170b
f476f18282fdd79f074705c547df31b1daf8fb8e
refs/heads/master
2016-09-08T01:39:50.898995
2012-08-30T23:07:03
2012-08-30T23:07:03
5,622,089
3
1
null
null
null
null
UTF-8
C++
false
false
4,209
h
/* AngelCode Scripting Library Copyright (c) 2003-2012 Andreas Jonsson This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. The original version of this library can be located at: http://www.angelcode.com/angelscript/ Andreas Jonsson [email protected] */ // // as_gc.h // // The garbage collector is used to resolve cyclic references // #ifndef AS_GC_H #define AS_GC_H #include "as_config.h" #include "as_array.h" #include "as_map.h" #include "as_thread.h" BEGIN_AS_NAMESPACE class asCScriptEngine; class asCObjectType; class asCGarbageCollector { public: asCGarbageCollector(); int GarbageCollect(asDWORD flags); void GetStatistics(asUINT *currentSize, asUINT *totalDestroyed, asUINT *totalDetected, asUINT *newObjects, asUINT *totalNewDestroyed) const; void GCEnumCallback(void *reference); void AddScriptObjectToGC(void *obj, asCObjectType *objType); int ReportAndReleaseUndestroyedObjects(); asCScriptEngine *engine; protected: struct asSObjTypePair {void *obj; asCObjectType *type; int count;}; struct asSIntTypePair {int i; asCObjectType *type;}; enum egcDestroyState { destroyGarbage_init = 0, destroyGarbage_loop, destroyGarbage_haveMore }; enum egcDetectState { clearCounters_init = 0, clearCounters_loop, buildMap_init, buildMap_loop, countReferences_init, countReferences_loop, detectGarbage_init, detectGarbage_loop1, detectGarbage_loop2, verifyUnmarked_init, verifyUnmarked_loop, breakCircles_init, breakCircles_loop, breakCircles_haveGarbage }; int DestroyNewGarbage(); int DestroyOldGarbage(); int IdentifyGarbageWithCyclicRefs(); asSObjTypePair GetNewObjectAtIdx(int idx); asSObjTypePair GetOldObjectAtIdx(int idx); void RemoveNewObjectAtIdx(int idx); void RemoveOldObjectAtIdx(int idx); void MoveObjectToOldList(int idx); void IncreaseCounterForNewObject(int idx); // Holds all the objects known by the garbage collector asCArray<asSObjTypePair> gcNewObjects; asCArray<asSObjTypePair> gcOldObjects; // This array temporarily holds references to objects known to be live objects asCArray<void*> liveObjects; // This map holds objects currently being searched for cyclic references, it also holds a // counter that gives the number of references to the object that the GC can't reach asCMap<void*, asSIntTypePair> gcMap; // State variables egcDestroyState destroyNewState; egcDestroyState destroyOldState; asUINT destroyNewIdx; asUINT destroyOldIdx; asUINT numDestroyed; asUINT numNewDestroyed; egcDetectState detectState; asUINT detectIdx; asUINT numDetected; asSMapNode<void*, asSIntTypePair> *gcMapCursor; bool isProcessing; // Critical section for multithreaded access DECLARECRITICALSECTION(gcCritical) // Used for adding/removing objects DECLARECRITICALSECTION(gcCollecting) // Used for processing }; END_AS_NAMESPACE #endif
199a9729ce4af24e43381b66985abe0121b20f03
26bb69977888fdc5f701f32027a0a6ae33c769f2
/back/w_sys_manage_operatorinformation.h
615d99318928216cc762c14716582bff3d4284df
[]
no_license
AM20302030/fastfd
a7ab37e3abdd9728f58fdcc76679fb9b1d1d22bf
4b23ee7e736afac6603588dcf8079fae889134f5
refs/heads/master
2023-03-15T23:21:51.398989
2017-07-17T02:19:45
2017-07-17T02:19:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
822
h
#ifndef W_SYS_MANAGE_OPERATORINFORMATION_H #define W_SYS_MANAGE_OPERATORINFORMATION_H #include <QDialog> #include <QModelIndex> class Ui_w_sys_manage_operatorinformation_Dialog; class lds_model_sqlrelationaltablemodel; class QDataWidgetMapper; class w_sys_manage_operatorinformation : public QDialog { Q_OBJECT public: explicit w_sys_manage_operatorinformation(QWidget *parent = 0); lds_model_sqlrelationaltablemodel *tablemodel; Ui_w_sys_manage_operatorinformation_Dialog *ui; private slots: void tonew(); void torefresh(); void todel(); bool tosave(); void toexit(); void mapper_setcur_tableviewcur(); void lineeditfinish(); signals: void lineedit_connect_change(QWidget *widget); private: QDataWidgetMapper *mapper; }; #endif // W_SYS_MANAGE_OPERATORINFORMATION_H
1145b7f6627e5ef766e53ca1d01528cef2d8b2e1
525e8eddfb40c566e9183b4c1bd1e1a63c1ab5ae
/Alchemy/object/Item.h
63ff2c2129e47a28792a45851601af34290a7904
[]
no_license
Tokusige-0411/-
eaa648e75508db7a3fa17f8f5bc9c979122bb54b
b327da9e2996bf1de2a19ecc7ef6f2d6f9206fef
refs/heads/master
2020-12-19T12:54:42.652301
2020-02-05T22:43:59
2020-02-05T22:43:59
213,581,178
0
0
null
null
null
null
UTF-8
C++
false
false
315
h
#pragma once #include "object/Obj.h" #include "FOLLOWER_TYPE.h" class Item : public Obj { public: Item(int type, Vector2Dbl pos); ~Item(); void Update(std::vector<sharedObj>& objList)override; int getType(void)override; int floatCnt(void); private: FOLLOWER_TYPE _type; void Init(void); int _floatCnt; };
e37e12a3473c09af4bdd9bbac6c69ce277955c21
34ab7facc3d9ba0303f6b62b72670d6d349e1af6
/icscreensaver.h
ec6c6c72834f82f184defb42e0c31d6baa4f794f
[]
no_license
GaussCheng/2-5AxisPunch
0fb1532aef359b3cba27fa875ff4e34a196e43da
d57380ac8acd77fe5860d4208a5dfba0b12d117b
refs/heads/master
2021-01-17T09:49:31.044350
2015-03-05T03:58:51
2015-03-05T03:58:51
31,994,191
3
5
null
null
null
null
UTF-8
C++
false
false
392
h
#ifndef ICSCREENSAVER_H #define ICSCREENSAVER_H #include <QWidget> namespace Ui { class ICScreenSaver; } class ICScreenSaver : public QWidget { Q_OBJECT public: explicit ICScreenSaver(QWidget *parent = 0); ~ICScreenSaver(); Q_SIGNALS: void Unlock(); private slots: void on_pushButton_clicked(); private: Ui::ICScreenSaver *ui; }; #endif // ICSCREENSAVER_H
2e9f1b9418066d49e1bb0a6311955957364a85b7
40150c4e4199bca594fb21bded192bbc05f8c835
/build/iOS/Preview/include/Uno.Threading.ConcurrentDictionary-2.h
12a42e0a0bc12c434f7841cf793973f22f1c6a7c
[]
no_license
thegreatyuke42/fuse-test
af0a863ab8cdc19919da11de5f3416cc81fc975f
b7e12f21d12a35d21a394703ff2040a4f3a35e00
refs/heads/master
2016-09-12T10:39:37.656900
2016-05-20T20:13:31
2016-05-20T20:13:31
58,671,009
0
0
null
null
null
null
UTF-8
C++
false
false
5,165
h
// This file was generated based on '/usr/local/share/uno/Packages/Uno.Threading/0.27.20/$.uno#12'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Collections.ICollection-1.h> #include <Uno.Collections.IDictionary-2.h> #include <Uno.Collections.IEnumerable-1.h> #include <Uno.Collections.KeyValuePair-2.h> #include <Uno.Object.h> namespace g{namespace Uno{namespace Collections{struct Dictionary;}}} namespace g{namespace Uno{namespace Threading{struct ConcurrentDictionary;}}} namespace g{namespace Uno{namespace Threading{struct Mutex;}}} namespace g{ namespace Uno{ namespace Threading{ // public sealed class ConcurrentDictionary<TKey, TValue> :922 // { struct ConcurrentDictionary_type : uType { ::g::Uno::Collections::IDictionary interface0; ::g::Uno::Collections::ICollection interface1; ::g::Uno::Collections::IEnumerable interface2; }; ConcurrentDictionary_type* ConcurrentDictionary_typeof(); void ConcurrentDictionary__ctor__fn(ConcurrentDictionary* __this); void ConcurrentDictionary__Add_fn(ConcurrentDictionary* __this, void* key, void* value); void ConcurrentDictionary__Add1_fn(ConcurrentDictionary* __this, void* keyValue); void ConcurrentDictionary__AddOrUpdate_fn(ConcurrentDictionary* __this, void* key, void* addValue, uDelegate* updateFun); void ConcurrentDictionary__Clear_fn(ConcurrentDictionary* __this); void ConcurrentDictionary__Contains_fn(ConcurrentDictionary* __this, void* keyValue, bool* __retval); void ConcurrentDictionary__ContainsKey_fn(ConcurrentDictionary* __this, void* key, bool* __retval); void ConcurrentDictionary__get_Count_fn(ConcurrentDictionary* __this, int* __retval); void ConcurrentDictionary__GetEnumerator_fn(ConcurrentDictionary* __this, uObject** __retval); void ConcurrentDictionary__get_Item_fn(ConcurrentDictionary* __this, void* key, uTRef __retval); void ConcurrentDictionary__set_Item_fn(ConcurrentDictionary* __this, void* key, void* value); void ConcurrentDictionary__get_Keys_fn(ConcurrentDictionary* __this, uObject** __retval); void ConcurrentDictionary__New1_fn(uType* __type, ConcurrentDictionary** __retval); void ConcurrentDictionary__Remove_fn(ConcurrentDictionary* __this, void* key, bool* __retval); void ConcurrentDictionary__Remove1_fn(ConcurrentDictionary* __this, void* keyValue, bool* __retval); void ConcurrentDictionary__TryGetValue_fn(ConcurrentDictionary* __this, void* key, uTRef value, bool* __retval); void ConcurrentDictionary__get_Values_fn(ConcurrentDictionary* __this, uObject** __retval); struct ConcurrentDictionary : uObject { uStrong< ::g::Uno::Collections::Dictionary*> _dictionary; uStrong< ::g::Uno::Threading::Mutex*> _mutex; void ctor_(); template<class TKey, class TValue> void Add(TKey key, TValue value) { ConcurrentDictionary__Add_fn(this, uConstrain(__type->T(0), key), uConstrain(__type->T(1), value)); } template<class TKey, class TValue> void Add1(::g::Uno::Collections::KeyValuePair<TKey, TValue> keyValue) { ConcurrentDictionary__Add1_fn(this, uConstrain(::g::Uno::Collections::KeyValuePair_typeof()->MakeType(__type->T(0), __type->T(1)), keyValue)); } template<class TKey, class TValue> void AddOrUpdate(TKey key, TValue addValue, uDelegate* updateFun) { ConcurrentDictionary__AddOrUpdate_fn(this, uConstrain(__type->T(0), key), uConstrain(__type->T(1), addValue), updateFun); } void Clear(); template<class TKey, class TValue> bool Contains(::g::Uno::Collections::KeyValuePair<TKey, TValue> keyValue) { bool __retval; return ConcurrentDictionary__Contains_fn(this, uConstrain(::g::Uno::Collections::KeyValuePair_typeof()->MakeType(__type->T(0), __type->T(1)), keyValue), &__retval), __retval; } template<class TKey> bool ContainsKey(TKey key) { bool __retval; return ConcurrentDictionary__ContainsKey_fn(this, uConstrain(__type->T(0), key), &__retval), __retval; } int Count(); uObject* GetEnumerator(); template<class TKey, class TValue> TValue Item(TKey key) { TValue __retval; return ConcurrentDictionary__get_Item_fn(this, uConstrain(__type->T(0), key), &__retval), __retval; } template<class TKey, class TValue> void Item(TKey key, TValue value) { ConcurrentDictionary__set_Item_fn(this, uConstrain(__type->T(0), key), uConstrain(__type->T(1), value)); } uObject* Keys(); template<class TKey> bool Remove(TKey key) { bool __retval; return ConcurrentDictionary__Remove_fn(this, uConstrain(__type->T(0), key), &__retval), __retval; } template<class TKey, class TValue> bool Remove1(::g::Uno::Collections::KeyValuePair<TKey, TValue> keyValue) { bool __retval; return ConcurrentDictionary__Remove1_fn(this, uConstrain(::g::Uno::Collections::KeyValuePair_typeof()->MakeType(__type->T(0), __type->T(1)), keyValue), &__retval), __retval; } template<class TKey, class TValue> bool TryGetValue(TKey key, TValue* value) { bool __retval; return ConcurrentDictionary__TryGetValue_fn(this, uConstrain(__type->T(0), key), uConstrain(__type->T(1), value), &__retval), __retval; } uObject* Values(); static ConcurrentDictionary* New1(uType* __type); }; // } }}} // ::g::Uno::Threading
a38a2f2e58c66bd14b4e4b412bb41e7d1ed2e6a9
c650fb7e03bdb25fd1c8ddb77584e19bca21c31d
/C++/dia-21/vector.cpp
e2f40b4e1f9830c622ea58d0b20534577d0abdc2
[]
no_license
MoisesAdame/LearnProg
3747759a347c29c6b8d1ad32fc817817e14d4944
3615a1aad044fadd85a88417864bc2d48d41df59
refs/heads/master
2023-07-02T04:18:42.064755
2021-08-03T20:56:18
2021-08-03T20:56:18
385,062,660
0
0
null
null
null
null
UTF-8
C++
false
false
1,572
cpp
#include <iostream> #include <cmath> using namespace std; class Point{ public: float x = 0; float y = 0; float z = 0; }; class Vector{ public: string name = "v"; Point start; Point end; }; void print(Vector v){ cout << "(" << v.start.x << ", " << v.start.y << ", " << v.start.z <<") --> (" << v.end.x << ", " << v.end.y << ", " << v.end.z << ")"<< endl; } float magnitude(Vector v){ float mag = sqrt((v.start.x - v.end.x)*(v.start.x - v.end.x) + (v.start.y - v.end.y)*(v.start.y - v.end.y) + (v.start.z - v.end.z)*(v.start.z - v.end.z)); return mag; } float dotproduct(Vector v1, Vector v2){ float dotp = (v1.start.x - v1.end.x)*(v2.start.x - v2.end.x) + (v1.start.y - v1.end.y)*(v2.start.y - v2.end.y) + (v1.start.z - v1.end.z)*(v2.start.z - v2.end.z); return dotp; } Vector crossproduct(Vector v1, Vector v2, string name = "vcross"){ Vector v_new; v_new.name = name; v_new.end.x = ((v1.start.y - v1.end.y)*(v2.start.z - v2.end.z) - (v1.start.z - v1.end.z)*(v2.start.y - v2.end.y)); v_new.end.x = (v_new.end.x >= 0 ? abs(v_new.end.x) : v_new.end.x); v_new.end.y = -((v1.start.x - v1.end.x)*(v2.start.z - v2.end.z) - (v1.start.z - v1.end.z)*(v2.start.x - v2.end.x)); v_new.end.y = (v_new.end.y >= 0 ? abs(v_new.end.y) : v_new.end.y); v_new.end.z = ((v1.start.x - v1.end.x)*(v2.start.y - v2.end.y) - (v1.start.y - v1.end.y)*(v2.start.x - v2.end.x)); v_new.end.z = (v_new.end.z >= 0 ? abs(v_new.end.z) : v_new.end.z); return v_new; }
667333e81f6aff25dfaf1b10ebbfcc6be6c3d952
d617f6f2e3fe291c982649f1a0dddc93105d8056
/src/gtest/generated/key_1015.cpp
6f79c84b9d0ee1b12ed1d8315e0d1cb02ec07303
[ "BSD-2-Clause" ]
permissive
Cryptolens/cryptolens-cpp-tests
052d65c94f8008c90d9e62140907480cf18afe57
c8971dbbece8505c04114f7e47a0cf374353f097
refs/heads/master
2020-08-27T22:20:25.835533
2019-10-25T12:19:20
2019-10-25T12:19:20
217,503,236
0
0
null
null
null
null
UTF-8
C++
false
false
23,960
cpp
#include <cryptolens/tests/gtest_shared.hpp> #include <gtest/gtest.h> namespace tests_v20180502 { class v20180502_online_Key1015 : public ::testing::Test { protected: static void SetUpTestCase() { Cryptolens cryptolens_handle; cryptolens::Error e; cryptolens_handle.signature_verifier.set_modulus_base64(e, "khbyu3/vAEBHi339fTuo2nUaQgSTBj0jvpt5xnLTTF35FLkGI+5Z3wiKfnvQiCLf+5s4r8JB/Uic/i6/iNjPMILlFeE0N6XZ+2pkgwRkfMOcx6eoewypTPUoPpzuAINJxJRpHym3V6ZJZ1UfYvzRcQBD/lBeAYrvhpCwukQMkGushKsOS6U+d+2C9ZNeP+U+uwuv/xu8YBCBAgGb8YdNojcGzM4SbCtwvJ0fuOfmCWZvUoiumfE4x7rAhp1pa9OEbUe0a5HL+1v7+JLBgkNZ7Z2biiHaM6za7GjHCXU8rojatEQER+MpgDuQV3ZPx8RKRdiJgPnz9ApBHFYDHLDzDw=="); cryptolens_handle.signature_verifier.set_exponent_base64(e, "AQAB"); license_key_ = cryptolens_handle.activate(e, "WyI3NzkxIiwiSkV6QmE3TVFDSU5jSmdSQXNwZXdCdnZSODNGeitQYnNDVDltckVvUSJd", "4848", "FUUPZ-RBFQH-RMLGV-HEISG", "a"); ASSERT_TRUE(license_key_); ASSERT_FALSE(e); } static void TearDownTestCase() { license_key_ = cryptolens::nullopt; } v20180502_online_Key1015() : ::testing::Test(), license_key(license_key_) {} static cryptolens::optional<cryptolens::LicenseKey> license_key_; cryptolens::optional<cryptolens::LicenseKey> const& license_key; }; cryptolens::optional<cryptolens::LicenseKey> v20180502_online_Key1015::license_key_; TEST_F(v20180502_online_Key1015, MandatoryProperties) { EXPECT_EQ(license_key->get_product_id(), 4848); EXPECT_EQ(license_key->get_created(), 1565802846); EXPECT_EQ(license_key->get_expires(), 4575201246); EXPECT_EQ(license_key->get_period(), 34830); EXPECT_EQ(license_key->get_block(), false); EXPECT_EQ(license_key->get_trial_activation(), false); EXPECT_EQ(license_key->get_f1(), true); EXPECT_EQ(license_key->get_f2(), false); EXPECT_EQ(license_key->get_f3(), true); EXPECT_EQ(license_key->get_f4(), true); EXPECT_EQ(license_key->get_f5(), true); EXPECT_EQ(license_key->get_f6(), true); EXPECT_EQ(license_key->get_f7(), true); EXPECT_EQ(license_key->get_f8(), true); } TEST_F(v20180502_online_Key1015, SimpleOptionalProperties) { EXPECT_TRUE(license_key->get_id()); if (license_key->get_id()) { EXPECT_EQ(*(license_key->get_id()), 1066); } EXPECT_TRUE(license_key->get_key()); if (license_key->get_key()) { EXPECT_EQ(*(license_key->get_key()), "FUUPZ-RBFQH-RMLGV-HEISG"); } EXPECT_TRUE(license_key->get_notes()); if (license_key->get_notes()) { EXPECT_EQ(*(license_key->get_notes()), "WN0QgDqAhDqAQUYM1SB A7Xq"); } EXPECT_TRUE(license_key->get_global_id()); if (license_key->get_global_id()) { EXPECT_EQ(*(license_key->get_global_id()), 55347); } EXPECT_TRUE(license_key->get_maxnoofmachines()); if (license_key->get_maxnoofmachines()) { EXPECT_EQ(*(license_key->get_maxnoofmachines()), 3); } EXPECT_TRUE(license_key->get_allowed_machines()); if (license_key->get_allowed_machines()) { EXPECT_EQ(*(license_key->get_allowed_machines()), "Yai o3\nI"); } EXPECT_TRUE(license_key->get_global_id()); if (license_key->get_global_id()) { EXPECT_EQ(*(license_key->get_global_id()), 55347); } } TEST_F(v20180502_online_Key1015, ActivatedMachines) { ASSERT_TRUE(license_key->get_activated_machines()); std::vector<cryptolens::ActivationData> expected; expected.push_back(cryptolens::ActivationData("a", "158.174.10.218", 1565812170)); // XXX: We have quadratic performance here. Could be some concern here given that set of activated machines can be large auto const& activated_machines = *(license_key->get_activated_machines()); for (auto i = activated_machines.cbegin(); i != activated_machines.cend(); ++i) { ASSERT_NE(expected.size(), 0); for (auto j = expected.begin(); j != expected.end(); ++j) { if (i->get_mid() == j->get_mid() && i->get_ip() == j->get_ip() && i->get_time() == j->get_time()) { expected.erase(j); break; } } } ASSERT_EQ(expected.size(), 0); } TEST_F(v20180502_online_Key1015, Customer) { EXPECT_TRUE(license_key->get_customer()); if (license_key->get_customer()) { auto const& customer = *(license_key->get_customer()); EXPECT_EQ(customer.get_id(), 6878); EXPECT_EQ(customer.get_name(), "wCv9qc"); EXPECT_EQ(customer.get_email(), "qLQVAseVI5reMTQcL5TdElHZu"); EXPECT_EQ(customer.get_company_name(), "CL5khstuBVY2x"); EXPECT_EQ(customer.get_created(), 1565802846); } } TEST_F(v20180502_online_Key1015, DataObjects) { ASSERT_TRUE(license_key->get_data_objects()); std::vector<cryptolens::DataObject> expected; expected.push_back(cryptolens::DataObject(5416, "KWCEih", "nIUjii7eRtn", 295044)); expected.push_back(cryptolens::DataObject(5417, "Gg9yz", "", 822835)); // XXX: We have quadratic performance here. It's fine given current restrictions on data objects auto const& data_objects = *(license_key->get_data_objects()); for (auto i = data_objects.cbegin(); i != data_objects.cend(); ++i) { ASSERT_NE(expected.size(), 0); for (auto j = expected.begin(); j != expected.end(); ++j) { if (i->get_id() == j->get_id() && i->get_name() == j->get_name() && i->get_string_value() == j->get_string_value() && i->get_int_value() == j->get_int_value()) { expected.erase(j); break; } } } ASSERT_EQ(expected.size(), 0); } } // namespace tests_v20180502 namespace tests_v20190401 { class v20190401_online_Key1015 : public ::testing::Test { protected: static void SetUpTestCase() { cryptolens::Error e; Cryptolens cryptolens_handle(e); cryptolens_handle.signature_verifier.set_modulus_base64(e, "khbyu3/vAEBHi339fTuo2nUaQgSTBj0jvpt5xnLTTF35FLkGI+5Z3wiKfnvQiCLf+5s4r8JB/Uic/i6/iNjPMILlFeE0N6XZ+2pkgwRkfMOcx6eoewypTPUoPpzuAINJxJRpHym3V6ZJZ1UfYvzRcQBD/lBeAYrvhpCwukQMkGushKsOS6U+d+2C9ZNeP+U+uwuv/xu8YBCBAgGb8YdNojcGzM4SbCtwvJ0fuOfmCWZvUoiumfE4x7rAhp1pa9OEbUe0a5HL+1v7+JLBgkNZ7Z2biiHaM6za7GjHCXU8rojatEQER+MpgDuQV3ZPx8RKRdiJgPnz9ApBHFYDHLDzDw=="); cryptolens_handle.signature_verifier.set_exponent_base64(e, "AQAB"); cryptolens_handle.machine_code_computer.set_machine_code(e, "a"); license_key_ = cryptolens_handle.activate(e, "WyI3NzkxIiwiSkV6QmE3TVFDSU5jSmdSQXNwZXdCdnZSODNGeitQYnNDVDltckVvUSJd", 4848, "FUUPZ-RBFQH-RMLGV-HEISG"); ASSERT_TRUE(license_key_); ASSERT_FALSE(e); } static void TearDownTestCase() { license_key_ = cryptolens::nullopt; } v20190401_online_Key1015() : ::testing::Test(), license_key(license_key_) {} static cryptolens::optional<cryptolens::LicenseKey> license_key_; cryptolens::optional<cryptolens::LicenseKey> const& license_key; }; cryptolens::optional<cryptolens::LicenseKey> v20190401_online_Key1015::license_key_; TEST_F(v20190401_online_Key1015, MandatoryProperties) { EXPECT_EQ(license_key->get_product_id(), 4848); EXPECT_EQ(license_key->get_created(), 1565802846); EXPECT_EQ(license_key->get_expires(), 4575201246); EXPECT_EQ(license_key->get_period(), 34830); EXPECT_EQ(license_key->get_block(), false); EXPECT_EQ(license_key->get_trial_activation(), false); EXPECT_EQ(license_key->get_f1(), true); EXPECT_EQ(license_key->get_f2(), false); EXPECT_EQ(license_key->get_f3(), true); EXPECT_EQ(license_key->get_f4(), true); EXPECT_EQ(license_key->get_f5(), true); EXPECT_EQ(license_key->get_f6(), true); EXPECT_EQ(license_key->get_f7(), true); EXPECT_EQ(license_key->get_f8(), true); } TEST_F(v20190401_online_Key1015, SimpleOptionalProperties) { EXPECT_TRUE(license_key->get_id()); if (license_key->get_id()) { EXPECT_EQ(*(license_key->get_id()), 1066); } EXPECT_TRUE(license_key->get_key()); if (license_key->get_key()) { EXPECT_EQ(*(license_key->get_key()), "FUUPZ-RBFQH-RMLGV-HEISG"); } EXPECT_TRUE(license_key->get_notes()); if (license_key->get_notes()) { EXPECT_EQ(*(license_key->get_notes()), "WN0QgDqAhDqAQUYM1SB A7Xq"); } EXPECT_TRUE(license_key->get_global_id()); if (license_key->get_global_id()) { EXPECT_EQ(*(license_key->get_global_id()), 55347); } EXPECT_TRUE(license_key->get_maxnoofmachines()); if (license_key->get_maxnoofmachines()) { EXPECT_EQ(*(license_key->get_maxnoofmachines()), 3); } EXPECT_TRUE(license_key->get_allowed_machines()); if (license_key->get_allowed_machines()) { EXPECT_EQ(*(license_key->get_allowed_machines()), "Yai o3\nI"); } EXPECT_TRUE(license_key->get_global_id()); if (license_key->get_global_id()) { EXPECT_EQ(*(license_key->get_global_id()), 55347); } } TEST_F(v20190401_online_Key1015, ActivatedMachines) { ASSERT_TRUE(license_key->get_activated_machines()); std::vector<cryptolens::ActivationData> expected; expected.push_back(cryptolens::ActivationData("a", "158.174.10.218", 1565812170)); // XXX: We have quadratic performance here. Could be some concern here given that set of activated machines can be large auto const& activated_machines = *(license_key->get_activated_machines()); for (auto i = activated_machines.cbegin(); i != activated_machines.cend(); ++i) { ASSERT_NE(expected.size(), 0); for (auto j = expected.begin(); j != expected.end(); ++j) { if (i->get_mid() == j->get_mid() && i->get_ip() == j->get_ip() && i->get_time() == j->get_time()) { expected.erase(j); break; } } } ASSERT_EQ(expected.size(), 0); } TEST_F(v20190401_online_Key1015, Customer) { EXPECT_TRUE(license_key->get_customer()); if (license_key->get_customer()) { auto const& customer = *(license_key->get_customer()); EXPECT_EQ(customer.get_id(), 6878); EXPECT_EQ(customer.get_name(), "wCv9qc"); EXPECT_EQ(customer.get_email(), "qLQVAseVI5reMTQcL5TdElHZu"); EXPECT_EQ(customer.get_company_name(), "CL5khstuBVY2x"); EXPECT_EQ(customer.get_created(), 1565802846); } } TEST_F(v20190401_online_Key1015, DataObjects) { ASSERT_TRUE(license_key->get_data_objects()); std::vector<cryptolens::DataObject> expected; expected.push_back(cryptolens::DataObject(5416, "KWCEih", "nIUjii7eRtn", 295044)); expected.push_back(cryptolens::DataObject(5417, "Gg9yz", "", 822835)); // XXX: We have quadratic performance here. It's fine given current restrictions on data objects auto const& data_objects = *(license_key->get_data_objects()); for (auto i = data_objects.cbegin(); i != data_objects.cend(); ++i) { ASSERT_NE(expected.size(), 0); for (auto j = expected.begin(); j != expected.end(); ++j) { if (i->get_id() == j->get_id() && i->get_name() == j->get_name() && i->get_string_value() == j->get_string_value() && i->get_int_value() == j->get_int_value()) { expected.erase(j); break; } } } ASSERT_EQ(expected.size(), 0); } class v20190401_offline_json_Key1015 : public ::testing::Test { protected: static void SetUpTestCase() { cryptolens::Error e; Cryptolens cryptolens_handle(e); cryptolens_handle.signature_verifier.set_modulus_base64(e, "khbyu3/vAEBHi339fTuo2nUaQgSTBj0jvpt5xnLTTF35FLkGI+5Z3wiKfnvQiCLf+5s4r8JB/Uic/i6/iNjPMILlFeE0N6XZ+2pkgwRkfMOcx6eoewypTPUoPpzuAINJxJRpHym3V6ZJZ1UfYvzRcQBD/lBeAYrvhpCwukQMkGushKsOS6U+d+2C9ZNeP+U+uwuv/xu8YBCBAgGb8YdNojcGzM4SbCtwvJ0fuOfmCWZvUoiumfE4x7rAhp1pa9OEbUe0a5HL+1v7+JLBgkNZ7Z2biiHaM6za7GjHCXU8rojatEQER+MpgDuQV3ZPx8RKRdiJgPnz9ApBHFYDHLDzDw=="); cryptolens_handle.signature_verifier.set_exponent_base64(e, "AQAB"); cryptolens_handle.machine_code_computer.set_machine_code(e, "a"); std::string saved_response("{\"licenseKey\":\"eyJQcm9kdWN0SWQiOjQ4NDgsIklEIjoxMDY2LCJLZXkiOiJGVVVQWi1SQkZRSC1STUxHVi1IRUlTRyIsIkNyZWF0ZWQiOjE1NjU4MDI4NDYsIkV4cGlyZXMiOjQ1NzUyMDEyNDYsIlBlcmlvZCI6MzQ4MzAsIkYxIjp0cnVlLCJGMiI6ZmFsc2UsIkYzIjp0cnVlLCJGNCI6dHJ1ZSwiRjUiOnRydWUsIkY2Ijp0cnVlLCJGNyI6dHJ1ZSwiRjgiOnRydWUsIk5vdGVzIjoiV04wUWdEcUFoRHFBUVVZTTFTQiBBN1hxIiwiQmxvY2siOmZhbHNlLCJHbG9iYWxJZCI6NTUzNDcsIkN1c3RvbWVyIjp7IklkIjo2ODc4LCJOYW1lIjoid0N2OXFjIiwiRW1haWwiOiJxTFFWQXNlVkk1cmVNVFFjTDVUZEVsSFp1IiwiQ29tcGFueU5hbWUiOiJDTDVraHN0dUJWWTJ4IiwiQ3JlYXRlZCI6MTU2NTgwMjg0Nn0sIkFjdGl2YXRlZE1hY2hpbmVzIjpbeyJNaWQiOiJhIiwiSVAiOiIxNTguMTc0LjEwLjIxOCIsIlRpbWUiOjE1NjU4MTIxNzB9XSwiVHJpYWxBY3RpdmF0aW9uIjpmYWxzZSwiTWF4Tm9PZk1hY2hpbmVzIjozLCJBbGxvd2VkTWFjaGluZXMiOiJZYWkgbzNcbkkiLCJEYXRhT2JqZWN0cyI6W3siSWQiOjU0MTYsIk5hbWUiOiJLV0NFaWgiLCJTdHJpbmdWYWx1ZSI6Im5JVWppaTdlUnRuIiwiSW50VmFsdWUiOjI5NTA0NH0seyJJZCI6NTQxNywiTmFtZSI6IkdnOXl6IiwiU3RyaW5nVmFsdWUiOiIiLCJJbnRWYWx1ZSI6ODIyODM1fV0sIlNpZ25EYXRlIjoxNTcwNDYxMzY5fQ==\",\"signature\":\"jkFN9fzfILQqAX/AWC5GWDzoZDuoMSIUPdRVSRoCqVQBYURoMggfDMOxdCUDrfKCH8Aw0ibxLFw44EtCGIXsJ3nLKcQDiunVPc5znbWO/baIdYFoCECWSNDYqXo8m6uSquIdOugiHkTSKEFW+G3jWw/pv+YQNsMFVz1xrScCZWS5z+XsE0uMshJ0tOcknSaT/4NHXzGMI9PUVbSXHuMK4nu0h0yv5OV1AVgiLIb1duDz93JM+lW/lFc4R8z7gSZEp+XvHVZ9v70CDbTbkwuhsrX3oenrolUqvB+BFhpFmwi4raagl4HKGIV2wCke6A4tZJM174G7dPOaCPXUEITQDQ==\",\"result\":0,\"message\":\"\"}"); license_key_ = cryptolens_handle.make_license_key(e, saved_response); ASSERT_TRUE(license_key_); ASSERT_FALSE(e); } static void TearDownTestCase() { license_key_ = cryptolens::nullopt; } v20190401_offline_json_Key1015() : ::testing::Test(), license_key(license_key_) {} static cryptolens::optional<cryptolens::LicenseKey> license_key_; cryptolens::optional<cryptolens::LicenseKey> const& license_key; }; cryptolens::optional<cryptolens::LicenseKey> v20190401_offline_json_Key1015::license_key_; TEST_F(v20190401_offline_json_Key1015, MandatoryProperties) { EXPECT_EQ(license_key->get_product_id(), 4848); EXPECT_EQ(license_key->get_created(), 1565802846); EXPECT_EQ(license_key->get_expires(), 4575201246); EXPECT_EQ(license_key->get_period(), 34830); EXPECT_EQ(license_key->get_block(), false); EXPECT_EQ(license_key->get_trial_activation(), false); EXPECT_EQ(license_key->get_f1(), true); EXPECT_EQ(license_key->get_f2(), false); EXPECT_EQ(license_key->get_f3(), true); EXPECT_EQ(license_key->get_f4(), true); EXPECT_EQ(license_key->get_f5(), true); EXPECT_EQ(license_key->get_f6(), true); EXPECT_EQ(license_key->get_f7(), true); EXPECT_EQ(license_key->get_f8(), true); } TEST_F(v20190401_offline_json_Key1015, SimpleOptionalProperties) { EXPECT_TRUE(license_key->get_id()); if (license_key->get_id()) { EXPECT_EQ(*(license_key->get_id()), 1066); } EXPECT_TRUE(license_key->get_key()); if (license_key->get_key()) { EXPECT_EQ(*(license_key->get_key()), "FUUPZ-RBFQH-RMLGV-HEISG"); } EXPECT_TRUE(license_key->get_notes()); if (license_key->get_notes()) { EXPECT_EQ(*(license_key->get_notes()), "WN0QgDqAhDqAQUYM1SB A7Xq"); } EXPECT_TRUE(license_key->get_global_id()); if (license_key->get_global_id()) { EXPECT_EQ(*(license_key->get_global_id()), 55347); } EXPECT_TRUE(license_key->get_maxnoofmachines()); if (license_key->get_maxnoofmachines()) { EXPECT_EQ(*(license_key->get_maxnoofmachines()), 3); } EXPECT_TRUE(license_key->get_allowed_machines()); if (license_key->get_allowed_machines()) { EXPECT_EQ(*(license_key->get_allowed_machines()), "Yai o3\nI"); } EXPECT_TRUE(license_key->get_global_id()); if (license_key->get_global_id()) { EXPECT_EQ(*(license_key->get_global_id()), 55347); } } TEST_F(v20190401_offline_json_Key1015, ActivatedMachines) { ASSERT_TRUE(license_key->get_activated_machines()); std::vector<cryptolens::ActivationData> expected; expected.push_back(cryptolens::ActivationData("a", "158.174.10.218", 1565812170)); // XXX: We have quadratic performance here. Could be some concern here given that set of activated machines can be large auto const& activated_machines = *(license_key->get_activated_machines()); for (auto i = activated_machines.cbegin(); i != activated_machines.cend(); ++i) { ASSERT_NE(expected.size(), 0); for (auto j = expected.begin(); j != expected.end(); ++j) { if (i->get_mid() == j->get_mid() && i->get_ip() == j->get_ip() && i->get_time() == j->get_time()) { expected.erase(j); break; } } } ASSERT_EQ(expected.size(), 0); } TEST_F(v20190401_offline_json_Key1015, Customer) { EXPECT_TRUE(license_key->get_customer()); if (license_key->get_customer()) { auto const& customer = *(license_key->get_customer()); EXPECT_EQ(customer.get_id(), 6878); EXPECT_EQ(customer.get_name(), "wCv9qc"); EXPECT_EQ(customer.get_email(), "qLQVAseVI5reMTQcL5TdElHZu"); EXPECT_EQ(customer.get_company_name(), "CL5khstuBVY2x"); EXPECT_EQ(customer.get_created(), 1565802846); } } TEST_F(v20190401_offline_json_Key1015, DataObjects) { ASSERT_TRUE(license_key->get_data_objects()); std::vector<cryptolens::DataObject> expected; expected.push_back(cryptolens::DataObject(5416, "KWCEih", "nIUjii7eRtn", 295044)); expected.push_back(cryptolens::DataObject(5417, "Gg9yz", "", 822835)); // XXX: We have quadratic performance here. It's fine given current restrictions on data objects auto const& data_objects = *(license_key->get_data_objects()); for (auto i = data_objects.cbegin(); i != data_objects.cend(); ++i) { ASSERT_NE(expected.size(), 0); for (auto j = expected.begin(); j != expected.end(); ++j) { if (i->get_id() == j->get_id() && i->get_name() == j->get_name() && i->get_string_value() == j->get_string_value() && i->get_int_value() == j->get_int_value()) { expected.erase(j); break; } } } ASSERT_EQ(expected.size(), 0); } class v20190401_offline_compact_Key1015 : public ::testing::Test { protected: static void SetUpTestCase() { cryptolens::Error e; Cryptolens cryptolens_handle(e); cryptolens_handle.signature_verifier.set_modulus_base64(e, "khbyu3/vAEBHi339fTuo2nUaQgSTBj0jvpt5xnLTTF35FLkGI+5Z3wiKfnvQiCLf+5s4r8JB/Uic/i6/iNjPMILlFeE0N6XZ+2pkgwRkfMOcx6eoewypTPUoPpzuAINJxJRpHym3V6ZJZ1UfYvzRcQBD/lBeAYrvhpCwukQMkGushKsOS6U+d+2C9ZNeP+U+uwuv/xu8YBCBAgGb8YdNojcGzM4SbCtwvJ0fuOfmCWZvUoiumfE4x7rAhp1pa9OEbUe0a5HL+1v7+JLBgkNZ7Z2biiHaM6za7GjHCXU8rojatEQER+MpgDuQV3ZPx8RKRdiJgPnz9ApBHFYDHLDzDw=="); cryptolens_handle.signature_verifier.set_exponent_base64(e, "AQAB"); cryptolens_handle.machine_code_computer.set_machine_code(e, "a"); std::string saved_response("v20180502-"); saved_response += "eyJQcm9kdWN0SWQiOjQ4NDgsIklEIjoxMDY2LCJLZXkiOiJGVVVQWi1SQkZRSC1STUxHVi1IRUlTRyIsIkNyZWF0ZWQiOjE1NjU4MDI4NDYsIkV4cGlyZXMiOjQ1NzUyMDEyNDYsIlBlcmlvZCI6MzQ4MzAsIkYxIjp0cnVlLCJGMiI6ZmFsc2UsIkYzIjp0cnVlLCJGNCI6dHJ1ZSwiRjUiOnRydWUsIkY2Ijp0cnVlLCJGNyI6dHJ1ZSwiRjgiOnRydWUsIk5vdGVzIjoiV04wUWdEcUFoRHFBUVVZTTFTQiBBN1hxIiwiQmxvY2siOmZhbHNlLCJHbG9iYWxJZCI6NTUzNDcsIkN1c3RvbWVyIjp7IklkIjo2ODc4LCJOYW1lIjoid0N2OXFjIiwiRW1haWwiOiJxTFFWQXNlVkk1cmVNVFFjTDVUZEVsSFp1IiwiQ29tcGFueU5hbWUiOiJDTDVraHN0dUJWWTJ4IiwiQ3JlYXRlZCI6MTU2NTgwMjg0Nn0sIkFjdGl2YXRlZE1hY2hpbmVzIjpbeyJNaWQiOiJhIiwiSVAiOiIxNTguMTc0LjEwLjIxOCIsIlRpbWUiOjE1NjU4MTIxNzB9XSwiVHJpYWxBY3RpdmF0aW9uIjpmYWxzZSwiTWF4Tm9PZk1hY2hpbmVzIjozLCJBbGxvd2VkTWFjaGluZXMiOiJZYWkgbzNcbkkiLCJEYXRhT2JqZWN0cyI6W3siSWQiOjU0MTYsIk5hbWUiOiJLV0NFaWgiLCJTdHJpbmdWYWx1ZSI6Im5JVWppaTdlUnRuIiwiSW50VmFsdWUiOjI5NTA0NH0seyJJZCI6NTQxNywiTmFtZSI6IkdnOXl6IiwiU3RyaW5nVmFsdWUiOiIiLCJJbnRWYWx1ZSI6ODIyODM1fV0sIlNpZ25EYXRlIjoxNTcwNDYxMzY5fQ=="; saved_response += "-"; saved_response += "jkFN9fzfILQqAX/AWC5GWDzoZDuoMSIUPdRVSRoCqVQBYURoMggfDMOxdCUDrfKCH8Aw0ibxLFw44EtCGIXsJ3nLKcQDiunVPc5znbWO/baIdYFoCECWSNDYqXo8m6uSquIdOugiHkTSKEFW+G3jWw/pv+YQNsMFVz1xrScCZWS5z+XsE0uMshJ0tOcknSaT/4NHXzGMI9PUVbSXHuMK4nu0h0yv5OV1AVgiLIb1duDz93JM+lW/lFc4R8z7gSZEp+XvHVZ9v70CDbTbkwuhsrX3oenrolUqvB+BFhpFmwi4raagl4HKGIV2wCke6A4tZJM174G7dPOaCPXUEITQDQ=="; license_key_ = cryptolens_handle.make_license_key(e, saved_response); ASSERT_TRUE(license_key_); ASSERT_FALSE(e); } static void TearDownTestCase() { license_key_ = cryptolens::nullopt; } v20190401_offline_compact_Key1015() : ::testing::Test(), license_key(license_key_) {} static cryptolens::optional<cryptolens::LicenseKey> license_key_; cryptolens::optional<cryptolens::LicenseKey> const& license_key; }; cryptolens::optional<cryptolens::LicenseKey> v20190401_offline_compact_Key1015::license_key_; TEST_F(v20190401_offline_compact_Key1015, MandatoryProperties) { EXPECT_EQ(license_key->get_product_id(), 4848); EXPECT_EQ(license_key->get_created(), 1565802846); EXPECT_EQ(license_key->get_expires(), 4575201246); EXPECT_EQ(license_key->get_period(), 34830); EXPECT_EQ(license_key->get_block(), false); EXPECT_EQ(license_key->get_trial_activation(), false); EXPECT_EQ(license_key->get_f1(), true); EXPECT_EQ(license_key->get_f2(), false); EXPECT_EQ(license_key->get_f3(), true); EXPECT_EQ(license_key->get_f4(), true); EXPECT_EQ(license_key->get_f5(), true); EXPECT_EQ(license_key->get_f6(), true); EXPECT_EQ(license_key->get_f7(), true); EXPECT_EQ(license_key->get_f8(), true); } TEST_F(v20190401_offline_compact_Key1015, SimpleOptionalProperties) { EXPECT_TRUE(license_key->get_id()); if (license_key->get_id()) { EXPECT_EQ(*(license_key->get_id()), 1066); } EXPECT_TRUE(license_key->get_key()); if (license_key->get_key()) { EXPECT_EQ(*(license_key->get_key()), "FUUPZ-RBFQH-RMLGV-HEISG"); } EXPECT_TRUE(license_key->get_notes()); if (license_key->get_notes()) { EXPECT_EQ(*(license_key->get_notes()), "WN0QgDqAhDqAQUYM1SB A7Xq"); } EXPECT_TRUE(license_key->get_global_id()); if (license_key->get_global_id()) { EXPECT_EQ(*(license_key->get_global_id()), 55347); } EXPECT_TRUE(license_key->get_maxnoofmachines()); if (license_key->get_maxnoofmachines()) { EXPECT_EQ(*(license_key->get_maxnoofmachines()), 3); } EXPECT_TRUE(license_key->get_allowed_machines()); if (license_key->get_allowed_machines()) { EXPECT_EQ(*(license_key->get_allowed_machines()), "Yai o3\nI"); } EXPECT_TRUE(license_key->get_global_id()); if (license_key->get_global_id()) { EXPECT_EQ(*(license_key->get_global_id()), 55347); } } TEST_F(v20190401_offline_compact_Key1015, ActivatedMachines) { ASSERT_TRUE(license_key->get_activated_machines()); std::vector<cryptolens::ActivationData> expected; expected.push_back(cryptolens::ActivationData("a", "158.174.10.218", 1565812170)); // XXX: We have quadratic performance here. Could be some concern here given that set of activated machines can be large auto const& activated_machines = *(license_key->get_activated_machines()); for (auto i = activated_machines.cbegin(); i != activated_machines.cend(); ++i) { ASSERT_NE(expected.size(), 0); for (auto j = expected.begin(); j != expected.end(); ++j) { if (i->get_mid() == j->get_mid() && i->get_ip() == j->get_ip() && i->get_time() == j->get_time()) { expected.erase(j); break; } } } ASSERT_EQ(expected.size(), 0); } TEST_F(v20190401_offline_compact_Key1015, Customer) { EXPECT_TRUE(license_key->get_customer()); if (license_key->get_customer()) { auto const& customer = *(license_key->get_customer()); EXPECT_EQ(customer.get_id(), 6878); EXPECT_EQ(customer.get_name(), "wCv9qc"); EXPECT_EQ(customer.get_email(), "qLQVAseVI5reMTQcL5TdElHZu"); EXPECT_EQ(customer.get_company_name(), "CL5khstuBVY2x"); EXPECT_EQ(customer.get_created(), 1565802846); } } TEST_F(v20190401_offline_compact_Key1015, DataObjects) { ASSERT_TRUE(license_key->get_data_objects()); std::vector<cryptolens::DataObject> expected; expected.push_back(cryptolens::DataObject(5416, "KWCEih", "nIUjii7eRtn", 295044)); expected.push_back(cryptolens::DataObject(5417, "Gg9yz", "", 822835)); // XXX: We have quadratic performance here. It's fine given current restrictions on data objects auto const& data_objects = *(license_key->get_data_objects()); for (auto i = data_objects.cbegin(); i != data_objects.cend(); ++i) { ASSERT_NE(expected.size(), 0); for (auto j = expected.begin(); j != expected.end(); ++j) { if (i->get_id() == j->get_id() && i->get_name() == j->get_name() && i->get_string_value() == j->get_string_value() && i->get_int_value() == j->get_int_value()) { expected.erase(j); break; } } } ASSERT_EQ(expected.size(), 0); } } // namespace tests_v20190401
5a91b0ee7ced7124eaf8f87fdc2530db03120815
9824cb54977c2bdfc0975c2dc6c78bd4e201ad27
/src/PercentageToRange.cpp
6fdceed27d4be69df59af29b2a8064b0ba9b0c46
[ "ISC", "LicenseRef-scancode-unknown-license-reference" ]
permissive
apometta/holdem-eval
26e4437cb4442d946320fcaa969c20499053b107
e0687e13ff0d780ec8134a33bdc17adfbc8fe606
refs/heads/master
2020-03-23T16:53:13.653597
2019-02-17T06:45:08
2019-02-17T06:45:08
141,831,928
7
2
null
null
null
null
UTF-8
C++
false
false
21,334
cpp
/*This file, written by Andrew H. Pometta, implements the PercentageToRange class specified in percentage_to_range.h. The Makefile for this project has this file listed as a source for building: to build manually, ensure this file is seen and linked to by the compiler. For usage details, see PercentageToRange.h. */ #include "PercentageToRange.h" //has <utility>, <string> and <vector> #include <algorithm> //lower_bound #include <cassert> #include <stdexcept> /*Constructor: does nothing. Since ranges is a static, it can't be defined in the constructor. It is hardcoded at the bottom of this file. The object itself, as a result, doesn't need to be instantiated with the keyword new: PercentageToRange perctor; would be enough to do anything needed. */ PercentageToRange::PercentageToRange() {} /*Given double input, return the necessary string. See the method in PercentageToRange.h for details and return value. */ std::string PercentageToRange::percentage_to_str(const double percentage){ //First check for errors and edge cases if (percentage == 0) return ""; else if (percentage < 0){ throw std::string("negative percentage range inputted"); } else if (percentage > 0 && percentage <= ranges.front().first){ return ranges.front().second; //return AA } else if (percentage >= 100) return ranges.back().second; //return random //lower_bound gives the first element !< percentage, which is what we want //as an upper bound. fourth argument is a lambda expression needed by //lower_bound to work between a double and a pair auto upper = std::lower_bound(ranges.begin(), ranges.end(), percentage, [](std::pair<double,std::string> p, double d){ return p.first < d; }); //Since we know from above that percentage is greater than the first element //in the list, this is guaranteed to work, i.e. upper isn't ranges.begin() auto lower = upper - 1; if ((upper + 1) == ranges.end()){ //percentage is <100% but greater than the next highest - return next //highest range, as per method documentation return (*lower).second; //random - 32o } //sanity check assert ((percentage > (*lower).first) && ((*upper).first >= percentage)); //Note that the rounding that occurs here can differ from Pokerstove (where //the ranges were gotten from) at various percentages, most likely due to //Pokerstove taking into account the combination difference between each //interval. However, these differences are unlikely to significantly matter. //If the user is so concerned about 0.09% making a one-hand difference in //the range affecting their equity calculation, they can input the range //manually if (((*upper).first - percentage) < (percentage - (*lower).first)){ return (*upper).second; } else return (*lower).second; } /*Given string input, return the necessary string. See the method in PercentageToRange.h for details and return value. */ std::string PercentageToRange::percentage_to_str(const std::string percentage){ //Given what's happening in holdem-eval, we know the string contains the % //symbol, and has no whitespace. If the conversion succeeds but there is //anything other than % signs, we complain double d; std::size_t trail_pos; try { d = std::stod(percentage, &trail_pos); //We catch exceptions here because we don't "trust" the program calling //this method to necessarily do it themselves, but throw them as our //own errors to display the problem easily } catch (std::out_of_range oor){ throw std::string("out of range percentage range " + percentage); } catch (std::invalid_argument ia){ //This will occurr if there is anything before the number itself, e.g. //input "fdssa60%" throw std::string("invalid percentage range " + percentage); } std::string trail = percentage.substr(trail_pos); //what's leftover if (trail == "" || trail[0] != '%'){ //Either there is no percentage sign in the string, or there is something //between the number converted and the percent sign, e.g. input //"60" or "60fdsa%" throw std::string("invalid percentage range " + percentage); } trail.erase(std::remove(trail.begin(), trail.end(), '%'), trail.end()); if (trail != ""){ //After removing the percentage signs, if there is anything leftover, //then we complain nonetheless: this is done to ensure accidental inputs //aren't counted. e.g. input "60%fdsa" throw std::string("invalid percentage range " + percentage); } //Note that we do allow multiple percentage signs, e.g. input "60%%%" is //valid input. return percentage_to_str(d); } /*Initialize ranges here. For details on why these values were used, see the Readme. For an explanation of how these were acquired, see .range_string_acq.sh. */ const std::vector<std::pair<double,std::string>> PercentageToRange::ranges = { std::make_pair(0.452489, "AA"), std::make_pair(0.904977, "KK+"), std::make_pair(1.35747, "QQ+"), std::make_pair(1.80995, "JJ+"), std::make_pair(2.26244, "TT+"), std::make_pair(2.5641, "TT+,AKs"), std::make_pair(3.01659, "99+,AKs"), std::make_pair(3.31825, "99+,AQs+"), std::make_pair(4.22323, "99+,AQs+,AKo"), std::make_pair(4.52489, "99+,AJs+,AKo"), std::make_pair(4.82655, "99+,AJs+,KQs,AKo"), std::make_pair(5.27903, "88+,AJs+,KQs,AKo"), std::make_pair(5.58069, "88+,ATs+,KQs,AKo"), std::make_pair(6.48567, "88+,ATs+,KQs,AQo+"), std::make_pair(6.78733, "88+,ATs+,KJs+,AQo+"), std::make_pair(7.08899, "88+,ATs+,KTs+,AQo+"), std::make_pair(7.39065, "88+,ATs+,KTs+,QJs,AQo+"), std::make_pair(8.29563, "88+,ATs+,KTs+,QJs,AJo+"), std::make_pair(9.2006, "88+,ATs+,KTs+,QJs,AJo+,KQo"), std::make_pair(9.50226, "88+,ATs+,KTs+,QTs+,AJo+,KQo"), std::make_pair(9.80392, "88+,A9s+,KTs+,QTs+,AJo+,KQo"), std::make_pair(10.2564, "77+,A9s+,KTs+,QTs+,AJo+,KQo"), std::make_pair(11.1614, "77+,A9s+,KTs+,QTs+,ATo+,KQo"), std::make_pair(11.463, "77+,A9s+,KTs+,QTs+,JTs,ATo+,KQo"), std::make_pair(12.368, "77+,A9s+,KTs+,QTs+,JTs,ATo+,KJo+"), std::make_pair(12.6697, "77+,A8s+,KTs+,QTs+,JTs,ATo+,KJo+"), std::make_pair(12.9713, "77+,A8s+,K9s+,QTs+,JTs,ATo+,KJo+"), std::make_pair(13.8763, "77+,A8s+,K9s+,QTs+,JTs,ATo+,KJo+,QJo"), std::make_pair(14.178, "77+,A7s+,K9s+,QTs+,JTs,ATo+,KJo+,QJo"), std::make_pair(15.083, "77+,A7s+,K9s+,QTs+,JTs,ATo+,KTo+,QJo"), std::make_pair(15.3846, "77+,A7s+,K9s+,Q9s+,JTs,ATo+,KTo+,QJo"), std::make_pair(15.6863, "77+,A7s+,A5s,K9s+,Q9s+,JTs,ATo+,KTo+,QJo"), std::make_pair(16.1388, "66+,A7s+,A5s,K9s+,Q9s+,JTs,ATo+,KTo+,QJo"), std::make_pair(16.4404, "66+,A5s+,K9s+,Q9s+,JTs,ATo+,KTo+,QJo"), std::make_pair(17.3454, "66+,A5s+,K9s+,Q9s+,JTs,ATo+,KTo+,QTo+"), std::make_pair(17.6471, "66+,A5s+,K9s+,Q9s+,J9s+,ATo+,KTo+,QTo+"), std::make_pair(18.552, "66+,A5s+,K9s+,Q9s+,J9s+,A9o+,KTo+,QTo+"), std::make_pair(18.8537, "66+,A5s+,K9s+,Q9s+,J9s+,T9s,A9o+,KTo+,QTo+"), std::make_pair(19.1554, "66+,A4s+,K9s+,Q9s+,J9s+,T9s,A9o+,KTo+,QTo+"), std::make_pair(19.457, "66+,A4s+,K8s+,Q9s+,J9s+,T9s,A9o+,KTo+,QTo+"), std::make_pair(20.362, "66+,A4s+,K8s+,Q9s+,J9s+,T9s,A9o+,KTo+,QTo+,JTo"), std::make_pair(20.6637, "66+,A4s+,K7s+,Q9s+,J9s+,T9s,A9o+,KTo+,QTo+,JTo"), std::make_pair(21.5686, "66+,A4s+,K7s+,Q9s+,J9s+,T9s,A8o+,KTo+,QTo+,JTo"), std::make_pair(21.8703, "66+,A3s+,K7s+,Q9s+,J9s+,T9s,A8o+,KTo+,QTo+,JTo"), std::make_pair(22.1719, "66+,A3s+,K7s+,Q8s+,J9s+,T9s,A8o+,KTo+,QTo+,JTo"), std::make_pair(23.0769, "66+,A3s+,K7s+,Q8s+,J9s+,T9s,A8o+,K9o+,QTo+,JTo"), std::make_pair(23.3786, "66+,A2s+,K7s+,Q8s+,J9s+,T9s,A8o+,K9o+,QTo+,JTo"), std::make_pair(23.6802, "66+,A2s+,K6s+,Q8s+,J9s+,T9s,A8o+,K9o+,QTo+,JTo"), std::make_pair(23.9819, "66+,A2s+,K6s+,Q8s+,J8s+,T9s,A8o+,K9o+,QTo+,JTo"), std::make_pair(24.2836, "66+,A2s+,K6s+,Q8s+,J8s+,T8s+,A8o+,K9o+,QTo+,JTo"), std::make_pair(25.1885, "66+,A2s+,K6s+,Q8s+,J8s+,T8s+,A7o+,K9o+,QTo+,JTo"), std::make_pair(25.641, "55+,A2s+,K6s+,Q8s+,J8s+,T8s+,A7o+,K9o+,QTo+,JTo"), std::make_pair(26.546, "55+,A2s+,K6s+,Q8s+,J8s+,T8s+,A7o+,K9o+,Q9o+,JTo"), std::make_pair(26.8477, "55+,A2s+,K6s+,Q8s+,J8s+,T8s+,98s,A7o+,K9o+,Q9o+,JTo"), std::make_pair(27.1493, "55+,A2s+,K5s+,Q8s+,J8s+,T8s+,98s,A7o+,K9o+,Q9o+,JTo"), std::make_pair(27.451, "55+,A2s+,K5s+,Q7s+,J8s+,T8s+,98s,A7o+,K9o+,Q9o+,JTo"), std::make_pair(28.356, "55+,A2s+,K5s+,Q7s+,J8s+,T8s+,98s,A7o+,K9o+,Q9o+,J9o+"), std::make_pair(29.2609, "55+,A2s+,K5s+,Q7s+,J8s+,T8s+,98s,A7o+,A5o,K9o+,Q9o+,J9o+"), std::make_pair(30.1659, "55+,A2s+,K5s+,Q7s+,J8s+,T8s+,98s,A7o+,A5o,K9o+,Q9o+,J9o+,T9o"), std::make_pair(31.0709, "55+,A2s+,K5s+,Q7s+,J8s+,T8s+,98s,A5o+,K9o+,Q9o+,J9o+,T9o"), std::make_pair(31.3725, "55+,A2s+,K4s+,Q7s+,J8s+,T8s+,98s,A5o+,K9o+,Q9o+,J9o+,T9o"), std::make_pair(32.2775, "55+,A2s+,K4s+,Q7s+,J8s+,T8s+,98s,A5o+,K8o+,Q9o+,J9o+,T9o"), std::make_pair(32.5792, "55+,A2s+,K4s+,Q6s+,J8s+,T8s+,98s,A5o+,K8o+,Q9o+,J9o+,T9o"), std::make_pair(32.8808, "55+,A2s+,K4s+,Q6s+,J7s+,T8s+,98s,A5o+,K8o+,Q9o+,J9o+,T9o"), std::make_pair(33.1825, "55+,A2s+,K4s+,Q6s+,J7s+,T7s+,98s,A5o+,K8o+,Q9o+,J9o+,T9o"), std::make_pair(34.0875, "55+,A2s+,K4s+,Q6s+,J7s+,T7s+,98s,A4o+,K8o+,Q9o+,J9o+,T9o"), std::make_pair(34.3891, "55+,A2s+,K4s+,Q6s+,J7s+,T7s+,97s+,A4o+,K8o+,Q9o+,J9o+,T9o"), std::make_pair(34.6908, "55+,A2s+,K3s+,Q6s+,J7s+,T7s+,97s+,A4o+,K8o+,Q9o+,J9o+,T9o"), std::make_pair(34.9925, "55+,A2s+,K3s+,Q6s+,J7s+,T7s+,97s+,87s,A4o+,K8o+,Q9o+,J9o+,T9o"), std::make_pair(35.2941, "55+,A2s+,K3s+,Q5s+,J7s+,T7s+,97s+,87s,A4o+,K8o+,Q9o+,J9o+,T9o"), std::make_pair(36.1991, "55+,A2s+,K3s+,Q5s+,J7s+,T7s+,97s+,87s,A4o+,K7o+,Q9o+,J9o+,T9o"), std::make_pair(36.6516, "44+,A2s+,K3s+,Q5s+,J7s+,T7s+,97s+,87s,A4o+,K7o+,Q9o+,J9o+,T9o"), std::make_pair(37.5566, "44+,A2s+,K3s+,Q5s+,J7s+,T7s+,97s+,87s,A4o+,K7o+,Q8o+,J9o+,T9o"), std::make_pair(38.4615, "44+,A2s+,K3s+,Q5s+,J7s+,T7s+,97s+,87s,A3o+,K7o+,Q8o+,J9o+,T9o"), std::make_pair(38.7632, "44+,A2s+,K2s+,Q5s+,J7s+,T7s+,97s+,87s,A3o+,K7o+,Q8o+,J9o+,T9o"), std::make_pair(39.6682, "44+,A2s+,K2s+,Q5s+,J7s+,T7s+,97s+,87s,A3o+,K7o+,Q8o+,J8o+,T9o"), std::make_pair(39.9698, "44+,A2s+,K2s+,Q4s+,J7s+,T7s+,97s+,87s,A3o+,K7o+,Q8o+,J8o+,T9o"), std::make_pair(40.8748, "44+,A2s+,K2s+,Q4s+,J7s+,T7s+,97s+,87s,A3o+,K7o+,Q8o+,J8o+,T8o+"), std::make_pair(41.1765, "44+,A2s+,K2s+,Q4s+,J6s+,T7s+,97s+,87s,A3o+,K7o+,Q8o+,J8o+,T8o+"), std::make_pair(42.0814, "44+,A2s+,K2s+,Q4s+,J6s+,T7s+,97s+,87s,A3o+,K6o+,Q8o+,J8o+,T8o+"), std::make_pair(42.9864, "44+,A2s+,K2s+,Q4s+,J6s+,T7s+,97s+,87s,A2o+,K6o+,Q8o+,J8o+,T8o+"), std::make_pair(43.2881, "44+,A2s+,K2s+,Q4s+,J6s+,T6s+,97s+,87s,A2o+,K6o+,Q8o+,J8o+,T8o+"), std::make_pair(44.1931, "44+,A2s+,K2s+,Q4s+,J6s+,T6s+,97s+,87s,A2o+,K6o+,Q8o+,J8o+,T8o+,98o"), std::make_pair(44.4947, "44+,A2s+,K2s+,Q4s+,J6s+,T6s+,97s+,87s,76s,A2o+,K6o+,Q8o+,J8o+,T8o+,98o"), std::make_pair(44.7964, "44+,A2s+,K2s+,Q4s+,J6s+,T6s+,97s+,86s+,76s,A2o+,K6o+,Q8o+,J8o+,T8o+,98o"), std::make_pair(45.098, "44+,A2s+,K2s+,Q4s+,J6s+,T6s+,96s+,86s+,76s,A2o+,K6o+,Q8o+,J8o+,T8o+,98o"), std::make_pair(45.3997, "44+,A2s+,K2s+,Q3s+,J6s+,T6s+,96s+,86s+,76s,A2o+,K6o+,Q8o+,J8o+,T8o+,98o"), std::make_pair(45.7014, "44+,A2s+,K2s+,Q3s+,J5s+,T6s+,96s+,86s+,76s,A2o+,K6o+,Q8o+,J8o+,T8o+,98o"), std::make_pair(46.6063, "44+,A2s+,K2s+,Q3s+,J5s+,T6s+,96s+,86s+,76s,A2o+,K5o+,Q8o+,J8o+,T8o+,98o"), std::make_pair(47.5113, "44+,A2s+,K2s+,Q3s+,J5s+,T6s+,96s+,86s+,76s,A2o+,K5o+,Q7o+,J8o+,T8o+,98o"), std::make_pair(47.813, "44+,A2s+,K2s+,Q2s+,J5s+,T6s+,96s+,86s+,76s,A2o+,K5o+,Q7o+,J8o+,T8o+,98o"), std::make_pair(48.1146, "44+,A2s+,K2s+,Q2s+,J4s+,T6s+,96s+,86s+,76s,A2o+,K5o+,Q7o+,J8o+,T8o+,98o"), std::make_pair(48.5671, "33+,A2s+,K2s+,Q2s+,J4s+,T6s+,96s+,86s+,76s,A2o+,K5o+,Q7o+,J8o+,T8o+,98o"), std::make_pair(48.8688, "33+,A2s+,K2s+,Q2s+,J4s+,T6s+,96s+,86s+,76s,65s,A2o+,K5o+,Q7o+,J8o+,T8o+,98o"), std::make_pair(49.7738, "33+,A2s+,K2s+,Q2s+,J4s+,T6s+,96s+,86s+,76s,65s,A2o+,K5o+,Q7o+,J7o+,T8o+,98o"), std::make_pair(50.6787, "33+,A2s+,K2s+,Q2s+,J4s+,T6s+,96s+,86s+,76s,65s,A2o+,K5o+,Q7o+,J7o+,T7o+,98o"), std::make_pair(51.5837, "33+,A2s+,K2s+,Q2s+,J4s+,T6s+,96s+,86s+,76s,65s,A2o+,K4o+,Q7o+,J7o+,T7o+,98o"), std::make_pair(51.8854, "33+,A2s+,K2s+,Q2s+,J4s+,T6s+,96s+,86s+,75s+,65s,A2o+,K4o+,Q7o+,J7o+,T7o+,98o"), std::make_pair(52.187, "33+,A2s+,K2s+,Q2s+,J4s+,T5s+,96s+,86s+,75s+,65s,A2o+,K4o+,Q7o+,J7o+,T7o+,98o"), std::make_pair(53.092, "33+,A2s+,K2s+,Q2s+,J4s+,T5s+,96s+,86s+,75s+,65s,A2o+,K4o+,Q6o+,J7o+,T7o+,98o"), std::make_pair(53.3937, "33+,A2s+,K2s+,Q2s+,J3s+,T5s+,96s+,86s+,75s+,65s,A2o+,K4o+,Q6o+,J7o+,T7o+,98o"), std::make_pair(53.6953, "33+,A2s+,K2s+,Q2s+,J3s+,T5s+,95s+,86s+,75s+,65s,A2o+,K4o+,Q6o+,J7o+,T7o+,98o"), std::make_pair(54.6003, "33+,A2s+,K2s+,Q2s+,J3s+,T5s+,95s+,86s+,75s+,65s,A2o+,K4o+,Q6o+,J7o+,T7o+,98o,87o"), std::make_pair(54.902, "33+,A2s+,K2s+,Q2s+,J3s+,T5s+,95s+,85s+,75s+,65s,A2o+,K4o+,Q6o+,J7o+,T7o+,98o,87o"), std::make_pair(55.8069, "33+,A2s+,K2s+,Q2s+,J3s+,T5s+,95s+,85s+,75s+,65s,A2o+,K4o+,Q6o+,J7o+,T7o+,97o+,87o"), std::make_pair(56.1086, "33+,A2s+,K2s+,Q2s+,J3s+,T4s+,95s+,85s+,75s+,65s,A2o+,K4o+,Q6o+,J7o+,T7o+,97o+,87o"), std::make_pair(57.0136, "33+,A2s+,K2s+,Q2s+,J3s+,T4s+,95s+,85s+,75s+,65s,A2o+,K3o+,Q6o+,J7o+,T7o+,97o+,87o"), std::make_pair(57.3152, "33+,A2s+,K2s+,Q2s+,J2s+,T4s+,95s+,85s+,75s+,65s,A2o+,K3o+,Q6o+,J7o+,T7o+,97o+,87o"), std::make_pair(57.6169, "33+,A2s+,K2s+,Q2s+,J2s+,T4s+,95s+,85s+,75s+,65s,54s,A2o+,K3o+,Q6o+,J7o+,T7o+,97o+,87o"), std::make_pair(58.5219, "33+,A2s+,K2s+,Q2s+,J2s+,T4s+,95s+,85s+,75s+,65s,54s,A2o+,K3o+,Q5o+,J7o+,T7o+,97o+,87o"), std::make_pair(58.8235, "33+,A2s+,K2s+,Q2s+,J2s+,T4s+,95s+,85s+,75s+,64s+,54s,A2o+,K3o+,Q5o+,J7o+,T7o+,97o+,87o"), std::make_pair(59.1252, "33+,A2s+,K2s+,Q2s+,J2s+,T3s+,95s+,85s+,75s+,64s+,54s,A2o+,K3o+,Q5o+,J7o+,T7o+,97o+,87o"), std::make_pair(59.5777, "22+,A2s+,K2s+,Q2s+,J2s+,T3s+,95s+,85s+,75s+,64s+,54s,A2o+,K3o+,Q5o+,J7o+,T7o+,97o+,87o"), std::make_pair(60.4827, "22+,A2s+,K2s+,Q2s+,J2s+,T3s+,95s+,85s+,75s+,64s+,54s,A2o+,K2o+,Q5o+,J7o+,T7o+,97o+,87o"), std::make_pair(60.7843, "22+,A2s+,K2s+,Q2s+,J2s+,T3s+,95s+,85s+,74s+,64s+,54s,A2o+,K2o+,Q5o+,J7o+,T7o+,97o+,87o"), std::make_pair(61.6893, "22+,A2s+,K2s+,Q2s+,J2s+,T3s+,95s+,85s+,74s+,64s+,54s,A2o+,K2o+,Q5o+,J7o+,T7o+,97o+,87o,76o"), std::make_pair(61.991, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,95s+,85s+,74s+,64s+,54s,A2o+,K2o+,Q5o+,J7o+,T7o+,97o+,87o,76o"), std::make_pair(62.8959, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,95s+,85s+,74s+,64s+,54s,A2o+,K2o+,Q4o+,J7o+,T7o+,97o+,87o,76o"), std::make_pair(63.8009, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,95s+,85s+,74s+,64s+,54s,A2o+,K2o+,Q4o+,J6o+,T7o+,97o+,87o,76o"), std::make_pair(64.1026, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,95s+,84s+,74s+,64s+,54s,A2o+,K2o+,Q4o+,J6o+,T7o+,97o+,87o,76o"), std::make_pair(64.4042, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,94s+,84s+,74s+,64s+,54s,A2o+,K2o+,Q4o+,J6o+,T7o+,97o+,87o,76o"), std::make_pair(65.3092, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,94s+,84s+,74s+,64s+,54s,A2o+,K2o+,Q4o+,J6o+,T7o+,97o+,86o+,76o"), std::make_pair(66.2142, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,94s+,84s+,74s+,64s+,54s,A2o+,K2o+,Q4o+,J6o+,T6o+,97o+,86o+,76o"), std::make_pair(67.1192, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,94s+,84s+,74s+,64s+,54s,A2o+,K2o+,Q4o+,J6o+,T6o+,96o+,86o+,76o"), std::make_pair(67.4208, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,94s+,84s+,74s+,64s+,53s+,A2o+,K2o+,Q4o+,J6o+,T6o+,96o+,86o+,76o"), std::make_pair(67.7225, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,93s+,84s+,74s+,64s+,53s+,A2o+,K2o+,Q4o+,J6o+,T6o+,96o+,86o+,76o"), std::make_pair(68.6275, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,93s+,84s+,74s+,64s+,53s+,A2o+,K2o+,Q3o+,J6o+,T6o+,96o+,86o+,76o"), std::make_pair(69.5324, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,93s+,84s+,74s+,64s+,53s+,A2o+,K2o+,Q3o+,J5o+,T6o+,96o+,86o+,76o"), std::make_pair(69.8341, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,93s+,84s+,74s+,63s+,53s+,A2o+,K2o+,Q3o+,J5o+,T6o+,96o+,86o+,76o"), std::make_pair(70.1357, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,93s+,84s+,74s+,63s+,53s+,43s,A2o+,K2o+,Q3o+,J5o+,T6o+,96o+,86o+,76o"), std::make_pair(70.4374, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,84s+,74s+,63s+,53s+,43s,A2o+,K2o+,Q3o+,J5o+,T6o+,96o+,86o+,76o"), std::make_pair(70.7391, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,84s+,73s+,63s+,53s+,43s,A2o+,K2o+,Q3o+,J5o+,T6o+,96o+,86o+,76o"), std::make_pair(71.644, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,84s+,73s+,63s+,53s+,43s,A2o+,K2o+,Q3o+,J5o+,T6o+,96o+,86o+,76o,65o"), std::make_pair(72.549, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,84s+,73s+,63s+,53s+,43s,A2o+,K2o+,Q2o+,J5o+,T6o+,96o+,86o+,76o,65o"), std::make_pair(73.454, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,84s+,73s+,63s+,53s+,43s,A2o+,K2o+,Q2o+,J4o+,T6o+,96o+,86o+,76o,65o"), std::make_pair(73.7557, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,83s+,73s+,63s+,53s+,43s,A2o+,K2o+,Q2o+,J4o+,T6o+,96o+,86o+,76o,65o"), std::make_pair(74.6606, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,83s+,73s+,63s+,53s+,43s,A2o+,K2o+,Q2o+,J4o+,T6o+,96o+,86o+,75o+,65o"), std::make_pair(74.9623, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,83s+,73s+,63s+,52s+,43s,A2o+,K2o+,Q2o+,J4o+,T6o+,96o+,86o+,75o+,65o"), std::make_pair(75.8673, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,83s+,73s+,63s+,52s+,43s,A2o+,K2o+,Q2o+,J4o+,T6o+,96o+,85o+,75o+,65o"), std::make_pair(76.1689, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,73s+,63s+,52s+,43s,A2o+,K2o+,Q2o+,J4o+,T6o+,96o+,85o+,75o+,65o"), std::make_pair(77.0739, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,73s+,63s+,52s+,43s,A2o+,K2o+,Q2o+,J4o+,T5o+,96o+,85o+,75o+,65o"), std::make_pair(77.9789, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,73s+,63s+,52s+,43s,A2o+,K2o+,Q2o+,J4o+,T5o+,95o+,85o+,75o+,65o"), std::make_pair(78.8839, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,73s+,63s+,52s+,43s,A2o+,K2o+,Q2o+,J3o+,T5o+,95o+,85o+,75o+,65o"), std::make_pair(79.1855, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,73s+,62s+,52s+,43s,A2o+,K2o+,Q2o+,J3o+,T5o+,95o+,85o+,75o+,65o"), std::make_pair(80.0905, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,73s+,62s+,52s+,43s,A2o+,K2o+,Q2o+,J3o+,T5o+,95o+,85o+,75o+,65o,54o"), std::make_pair(80.3922, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,73s+,62s+,52s+,42s+,A2o+,K2o+,Q2o+,J3o+,T5o+,95o+,85o+,75o+,65o,54o"), std::make_pair(81.2971, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,73s+,62s+,52s+,42s+,A2o+,K2o+,Q2o+,J3o+,T4o+,95o+,85o+,75o+,65o,54o"), std::make_pair(82.2021, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,73s+,62s+,52s+,42s+,A2o+,K2o+,Q2o+,J2o+,T4o+,95o+,85o+,75o+,65o,54o"), std::make_pair(82.5038, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,72s+,62s+,52s+,42s+,A2o+,K2o+,Q2o+,J2o+,T4o+,95o+,85o+,75o+,65o,54o"), std::make_pair(83.4087, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,72s+,62s+,52s+,42s+,A2o+,K2o+,Q2o+,J2o+,T4o+,95o+,85o+,75o+,64o+,54o"), std::make_pair(84.3137, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,72s+,62s+,52s+,42s+,A2o+,K2o+,Q2o+,J2o+,T3o+,95o+,85o+,75o+,64o+,54o"), std::make_pair(84.6154, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,72s+,62s+,52s+,42s+,32s,A2o+,K2o+,Q2o+,J2o+,T3o+,95o+,85o+,75o+,64o+,54o"), std::make_pair(85.5204, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,72s+,62s+,52s+,42s+,32s,A2o+,K2o+,Q2o+,J2o+,T3o+,95o+,85o+,74o+,64o+,54o"), std::make_pair(86.4253, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,72s+,62s+,52s+,42s+,32s,A2o+,K2o+,Q2o+,J2o+,T3o+,95o+,84o+,74o+,64o+,54o"), std::make_pair(87.3303, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,72s+,62s+,52s+,42s+,32s,A2o+,K2o+,Q2o+,J2o+,T2o+,95o+,84o+,74o+,64o+,54o"), std::make_pair(88.2353, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,72s+,62s+,52s+,42s+,32s,A2o+,K2o+,Q2o+,J2o+,T2o+,94o+,84o+,74o+,64o+,54o"), std::make_pair(89.1403, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,72s+,62s+,52s+,42s+,32s,A2o+,K2o+,Q2o+,J2o+,T2o+,94o+,84o+,74o+,64o+,53o+"), std::make_pair(90.0452, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,72s+,62s+,52s+,42s+,32s,A2o+,K2o+,Q2o+,J2o+,T2o+,93o+,84o+,74o+,64o+,53o+"), std::make_pair(90.9502, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,72s+,62s+,52s+,42s+,32s,A2o+,K2o+,Q2o+,J2o+,T2o+,93o+,84o+,74o+,63o+,53o+"), std::make_pair(91.8552, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,72s+,62s+,52s+,42s+,32s,A2o+,K2o+,Q2o+,J2o+,T2o+,93o+,84o+,74o+,63o+,53o+,43o"), std::make_pair(92.7602, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,72s+,62s+,52s+,42s+,32s,A2o+,K2o+,Q2o+,J2o+,T2o+,92o+,84o+,74o+,63o+,53o+,43o"), std::make_pair(93.6652, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,72s+,62s+,52s+,42s+,32s,A2o+,K2o+,Q2o+,J2o+,T2o+,92o+,84o+,73o+,63o+,53o+,43o"), std::make_pair(94.5701, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,72s+,62s+,52s+,42s+,32s,A2o+,K2o+,Q2o+,J2o+,T2o+,92o+,83o+,73o+,63o+,53o+,43o"), std::make_pair(95.4751, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,72s+,62s+,52s+,42s+,32s,A2o+,K2o+,Q2o+,J2o+,T2o+,92o+,83o+,73o+,63o+,52o+,43o"), std::make_pair(96.3801, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,72s+,62s+,52s+,42s+,32s,A2o+,K2o+,Q2o+,J2o+,T2o+,92o+,82o+,73o+,63o+,52o+,43o"), std::make_pair(97.2851, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,72s+,62s+,52s+,42s+,32s,A2o+,K2o+,Q2o+,J2o+,T2o+,92o+,82o+,73o+,63o+,52o+,42o+"), std::make_pair(98.19, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,72s+,62s+,52s+,42s+,32s,A2o+,K2o+,Q2o+,J2o+,T2o+,92o+,82o+,73o+,62o+,52o+,42o+"), std::make_pair(99.095, "22+,A2s+,K2s+,Q2s+,J2s+,T2s+,92s+,82s+,72s+,62s+,52s+,42s+,32s,A2o+,K2o+,Q2o+,J2o+,T2o+,92o+,82o+,72o+,62o+,52o+,42o+"), std::make_pair(100, "random"), };
09f0fd5151f3b7488b504ccae9aab881b53312ae
678d5a935039637438d509b4be456a63da685197
/Item39/main.cpp
87406b66a20e994987627885ab54dac0ffe775e1
[]
no_license
LuanZheng/EffectiveCPlusPlus
80410a5752a3c338a9837971463d1e4b5e9062b9
ba30475fbe29d33604ad263f5cf17f007407c1d6
refs/heads/master
2021-01-25T11:34:25.450822
2018-03-18T04:11:33
2018-03-18T04:11:33
123,411,498
0
0
null
null
null
null
UTF-8
C++
false
false
224
cpp
#include "Widget.h" #include <iostream> int main() { Widget widget; widget.lookTheTick(); std::cout << "-----------------------------" << std::endl; WidgetViaCom widgetViaCom; widgetViaCom.lookTheTick(); return 0; }
49b2119ecf44e8b799451680b1ca0dfd9b02ab02
47ffc59bb1ff1e29549938ae4491599a813fa1cc
/tip/induction/TripProofInstances.h
948430fc5e796c8401bdca39a3dc0181f8c29664
[]
no_license
niklasso/tip
a90d4a7e9d1767568185baa18182d795f0d6b6ad
ab02b4fc07bbffc766241a2da87a3b4ff04b0b4a
refs/heads/master
2020-05-16T23:41:49.028662
2013-09-26T10:36:39
2013-09-26T10:36:39
3,876,934
12
3
null
2015-03-27T03:32:40
2012-03-30T13:36:47
C++
UTF-8
C++
false
false
8,939
h
/****************************************************************************[TripProofInstances.h] Copyright (c) 2011, Niklas Sorensson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ #ifndef Tip_TripProofInstances_h #define Tip_TripProofInstances_h #include "minisat/simp/SimpSolver.h" #include "mcl/Clausify.h" #include "tip/unroll/Unroll.h" #include "tip/induction/TripTypes.h" namespace Tip { //=================================================================================================== // Helpers: class LitSet { LMap<char> in_set; vec<Lit> set; void clear() { for (int i = 0; i < set.size(); i++) in_set[set[i]] = 0; set.clear(); } public: void fromModel(const vec<Lit>& xs, const SimpSolver& s) { clear(); in_set.reserve(~mkLit(s.nVars()-1), 0); for (int i = 0; i < xs.size(); i++){ assert(s.modelValue(xs[i]) != l_Undef); Lit x = xs[i] ^ (s.modelValue(xs[i]) == l_False); if (!has(x)){ set.push(x); in_set[x] = 1; } } } void fromVec(const vec<Lit>& xs) { clear(); for (int i = 0; i < xs.size(); i++){ set.push(xs[i]); in_set.reserve(xs[i], 0); assert(in_set[xs[i]] == 0); in_set[xs[i]] = 1; } } int size () const { return set.size(); } Lit operator[](int i) const { return set[i]; } Lit last () const { return set.last(); } void pop () { // Note: assumes that there were no duplicates in the 'set' vector: Lit x = set.last(); set.pop(); assert(in_set[x] == 1); in_set[x] = 0; } void push (Lit l){ set.push(l); in_set.reserve(l, 0); assert(in_set[l] == 0); in_set[l] = 1; } void copyTo (vec<Lit>& out) const { set.copyTo(out); } lbool has(Var v) const { if (in_set.has(mkLit(v)) && in_set[mkLit(v)]) return l_True; else if (in_set.has(~mkLit(v)) && in_set[~mkLit(v)]) return l_False; else return l_Undef; } bool has(Lit l) const { return in_set.has(l) && in_set[l]; } }; struct EventCounter { unsigned k; Sig q; Sig h; //EventCounter() : k(0), x(sig_True){} }; //=================================================================================================== class InitInstance { const TipCirc& tip; UnrolledCirc uc; // Unrolled circuit. SimpSolver *solver; Clausifyer<SimpSolver> *cl; // Clausifyer for unrolled circuit. vec<Sig> inputs; // Reusable temporaries: SSet inputs_set; double cpu_time; int cnf_level; // Effort level for CNF simplification. void reset(); public: InitInstance(const TipCirc& t_, int cnf_level_); ~InitInstance(); bool prove(const Clause& c, const Clause& bot, Clause& yes, SharedRef<ScheduledClause>& no, SharedRef<ScheduledClause> next = NULL); bool prove(const Clause& c, const Clause& bot, Clause& yes); void reduceClause(Clause& c); uint64_t props(); uint64_t solves(); uint64_t confl(); double time(); void printStats(); }; //=================================================================================================== class PropInstance { const TipCirc& tip; const vec<vec<Clause*> >& F; const vec<Clause*>& F_inv; const vec<EventCounter>& event_cnts; const GMap<float>& flop_act; UnrolledCirc uc; // Unrolled circuit. SimpSolver *solver; Clausifyer<SimpSolver> *cl; // Clausifyer for unrolled circuit. vec<vec<Sig> > needed_flops; // Flops reachable from constraints or properties in each cycle. vec<Sig> inputs; vec<Sig> flops; vec<Sig> outputs; // Reusable temporaries: SSet flops_set; SSet inputs_set; SSet outputs_set; Lit act_cycle; Lit act_cnstrs; double cpu_time; // Options: int cnf_level; // Effort level for CNF simplification. uint32_t max_min_tries; // Max number of iterations in model minimization. unsigned depth_; // Depth of the unrolling. bool use_ind; // Use property in induction hypothesis. bool use_uniq; // Use unique state induction. public: void reset (unsigned safe_lim, unsigned new_depth); void clearClauses(unsigned safe_lim); void addClause (const Clause& c); PropInstance(const TipCirc& t, const vec<vec<Clause*> >& F_, const vec<Clause*>& F_inv_, const vec<EventCounter>& event_cnts_, GMap<float>& flop_act_, int cnf_level_, uint32_t max_min_tries_, int depth_, bool use_ind_, bool use_uniq_); ~PropInstance(); lbool prove(Sig p, SharedRef<ScheduledClause>& no, unsigned cycle); uint64_t props(); uint64_t solves(); uint64_t confl(); double time(); unsigned depth(); void printStats(); }; //=================================================================================================== class StepInstance { const TipCirc& tip; const vec<vec<Clause*> >& F; const vec<Clause*>& F_inv; const vec<EventCounter>& event_cnts; const GMap<float>& flop_act; UnrolledCirc uc; // Unrolled circuit. SimpSolver *solver; Clausifyer<SimpSolver> *cl; // Clausifyer for unrolled circuit. vec<Sig> inputs; vec<Sig> flops; vec<Sig> outputs; // Reusable temporaries: SSet flops_set; SSet inputs_set; SSet outputs_set; vec<Lit> activate; vec<unsigned> cycle_clauses; Lit act_cnstrs; double cpu_time; int cnf_level; // Effort level for CNF simplification. uint32_t max_min_tries; // Max number of iterations in model minimization. void reset(); public: void addClause(const Clause& c); void resetCycle(unsigned cycle, unsigned num_clauses); StepInstance(const TipCirc& t, const vec<vec<Clause*> >& F_, const vec<Clause*>& F_inv_, const vec<EventCounter>& event_cnts_, GMap<float>& flop_act_, int cnf_level_, uint32_t max_min_tries_); ~StepInstance(); bool prove(const Clause& c, Clause& yes, SharedRef<ScheduledClause>& no, SharedRef<ScheduledClause> next = NULL); bool prove(const Clause& c, Clause& yes); uint64_t props(); uint64_t solves(); uint64_t confl(); double time(); void printStats(); }; //================================================================================================= } // namespace Tip #endif
96fbc69c2c99aae3f3cda7c97de0a51aa7d59184
e026cd88dac4f51d798b1c1d04b4326dc9850ac2
/ngôn ngữ lập trình C.C++/bai 10 chuong 2.cpp
9075ee8c299437f0ee3c3e46ce2513c3a21c3d45
[]
no_license
locklinh/ttC
8b934fd8bd5c65c7f54a88d09e7bef86c0732c60
de6f6cb375e803c4ab285f618e638670e22877b7
refs/heads/master
2020-03-17T23:29:13.211023
2018-05-19T11:32:09
2018-05-19T11:32:09
134,047,576
0
0
null
null
null
null
UTF-8
C++
false
false
168
cpp
#include<iostream> using namespace std; int main(){ int i=1; float tong=0; while(tong<2.101999){ tong+=(float)1/(2*i-1); i++; } cout<< i-1; return 0; }
69d449a392061052abbd575595f7463092cb2402
e7fc909b1b5be05b2d0f8d92e5679983b97fdbe9
/timing.cpp
a832b748df3f93efc4e3979ad6f6a4c2db20bb32
[]
no_license
serpis/nesalizer
53f98f68048ae112e2a79209e44ac0f5975bed5d
0fe53a884dd120767039ccfc0e3b5d956dfac8b9
refs/heads/master
2020-04-05T23:13:51.942127
2013-09-26T20:21:55
2013-09-26T20:24:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,145
cpp
#include "common.h" #include "timing.h" #include <time.h> // SDL's timing functions only have millisecond precision, which doesn't seem // good enough (60 FPS is approx. 16 ms per frame). Roll our own. // Used for main loop synchronization static timespec clock_previous; static void add_to_timespec(timespec &ts, long nano_secs) { assert(nano_secs <= 1000000000l); long const new_nanos = ts.tv_nsec + nano_secs; ts.tv_sec += (new_nanos >= 1000000000l); ts.tv_nsec = new_nanos%1000000000l; } void init_timing() { errno_fail_if(clock_gettime(CLOCK_MONOTONIC, &clock_previous) < 0, "Failed to fetch initial synchronization timestamp from clock_gettime()"); } void sleep_till_end_of_frame() { add_to_timespec(clock_previous, nanoseconds_per_frame); again: int const res = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &clock_previous, 0); if (res == EINTR) goto again; errno_val_fail_if(res != 0, res, "failed to sleep with clock_nanosleep()"); errno_fail_if(clock_gettime(CLOCK_MONOTONIC, &clock_previous) < 0, "failed to fetch synchronization timestamp from clock_gettime()"); }
d96b7d088d78f24385179f4da75783690db202c6
cf8ddfc720bf6451c4ef4fa01684327431db1919
/SDK/ARKSurvivalEvolved_PrimalItemConsumable_Egg_Rex_Fertilized_Bionic_functions.cpp
7858f4c92de77c4860a35632378e8197df500ff9
[ "MIT" ]
permissive
git-Charlie/ARK-SDK
75337684b11e7b9f668da1f15e8054052a3b600f
c38ca9925309516b2093ad8c3a70ed9489e1d573
refs/heads/master
2023-06-20T06:30:33.550123
2021-07-11T13:41:45
2021-07-11T13:41:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,335
cpp
// ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_PrimalItemConsumable_Egg_Rex_Fertilized_Bionic_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function PrimalItemConsumable_Egg_Rex_Fertilized_Bionic.PrimalItemConsumable_Egg_Rex_Fertilized_Bionic_C.ExecuteUbergraph_PrimalItemConsumable_Egg_Rex_Fertilized_Bionic // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UPrimalItemConsumable_Egg_Rex_Fertilized_Bionic_C::ExecuteUbergraph_PrimalItemConsumable_Egg_Rex_Fertilized_Bionic(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function PrimalItemConsumable_Egg_Rex_Fertilized_Bionic.PrimalItemConsumable_Egg_Rex_Fertilized_Bionic_C.ExecuteUbergraph_PrimalItemConsumable_Egg_Rex_Fertilized_Bionic"); UPrimalItemConsumable_Egg_Rex_Fertilized_Bionic_C_ExecuteUbergraph_PrimalItemConsumable_Egg_Rex_Fertilized_Bionic_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
1beb6e0fe308c6ed4f3d88db79b92c91e3824a51
de0e158b5e1028c16164db354e847c5d6c833d02
/nationsgame/nationsgame/test/release/moc_play.cpp
30b833c54edb4e1feb61a090ca3fe748aaf4ac9b
[]
no_license
PramodBisht/flag-and-county-game
1a46b19ce9e6ea258a5348eff19bb5d5d032889b
50b18805b2c2fc5ee1678fa5780656c00a756cc0
refs/heads/master
2021-01-25T07:07:48.439816
2014-04-03T08:24:24
2014-04-03T08:24:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,243
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'play.h' ** ** Created: Tue 12. Jul 16:58:39 2011 ** by: The Qt Meta Object Compiler version 62 (Qt 4.7.3) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../play.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'play.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.7.3. 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_Play[] = { // content: 5, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 6, 5, 5, 5, 0x08, 0 // eod }; static const char qt_meta_stringdata_Play[] = { "Play\0\0on_Answer_clicked()\0" }; const QMetaObject Play::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_Play, qt_meta_data_Play, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &Play::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *Play::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *Play::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_Play)) return static_cast<void*>(const_cast< Play*>(this)); return QWidget::qt_metacast(_clname); } int Play::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: on_Answer_clicked(); break; default: ; } _id -= 1; } return _id; } QT_END_MOC_NAMESPACE
9348d9403562fa35b52c5362ca043707e05cc29d
a52aedb1544d7d15a3ddd8da50e289be45f41e40
/cpp work/2_Shibaji_paul/12_DynamicAllocationIntro.cpp
61f654f355af7c7e9039fe21500ed32b2d9e64a0
[]
no_license
SI-Tanbir/my_code
e3e0acdfdf00b506924bce7d85d29bc8f20eed8d
fa85aa3c2bf3dd1eb5c26df9590b2b59dd5e4ad5
refs/heads/main
2023-07-11T18:53:39.897700
2021-08-27T06:57:29
2021-08-27T06:57:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
754
cpp
#include <iostream> #include <iomanip> using namespace std; void display(int *p, int n){ for(int i = 0; i < n; ++i){ cout << setw(4) << p[i]; } cout << endl; } int main() { int x[100]; cout << "Input how many integer elements that you want to process: "; int n; cin >> n; int *p { new int[n] }; // allocating using uniform initialization. // int *p = new int[n]; // alternative traditional approach of the previous statement. int *ptr = new int(10); // single integer object allocation in the heap for(int i = 0; i < n; ++i){ cout << "Next int: "; cin >> *(p + i); } display(p, n); delete [] p; delete ptr; return 0; }
4386866fe51868d843b370d077ef0175426a977d
80461e6e5cf0a497109093a468a4e91e26b0bd6a
/Assignments/Day14/JPV3.cpp
c8f820c75599cdeabae245ecb3160798d30f5e95
[]
no_license
Striiderr/DSA
2e3c7461ef1d601643008c2e0061155192083f50
28cc687bb62202272ec38a6e682374805158ac1f
refs/heads/master
2023-05-03T18:14:28.283597
2021-05-24T04:43:43
2021-05-24T04:43:43
292,616,998
0
0
null
null
null
null
UTF-8
C++
false
false
1,796
cpp
#include<iostream> #include<vector> using namespace std; struct dlnode{ dlnode *left; int data; dlnode *right; };typedef struct dlnode* dlptr; void swap ( int* a, int* b ) { int t = *a; *a = *b; *b = t; } void cretdln(dlptr &S,int total){ S=new(dlnode); S->left=NULL; int n=0; n++; S->data=n; S->right=NULL; dlptr T; dlptr P,Q; P=S;Q=S; int i=1; while(i<total){ n++; T=new(dlnode); T->left=P; T->data=n; T->right=NULL; P->right=T;P=P->right; i++; } Q->left=P; P->right=S; } void delfront(dlptr &S){ S->right->left=NULL; S=S->right; } void delk(dlptr &P, int k){ if(P->data==k){ delfront(P); return; } dlptr S=P; while ((S->data!=k)) { S=S->right; } S->left->right=S->right; S->right->left=S->left; } void print(dlptr SP,dlptr FP,int c){ if(SP==FP){ c++;} if(c==2){ return;} else{ cout<<SP->data<<" "; print(SP->right,FP->right->right,c); }} void printcl(dlptr P){ dlptr SP,FP;SP=P;FP=P; int c=0; print(SP,FP,c); } int count(dlptr P){ dlptr SP,FP; SP=P;FP=P; int c=0,i=0; while(true){ if(SP==FP) c++; if(c==2){ break; } else{ SP=SP->right; FP=FP->right->right; i++; } } return i; } vector<int> oprn(dlptr S,int n){ vector<int> v; v.resize(n); fill(v.begin(), v.end(), 0); int m;cin>>m; dlptr P=NULL;int i; n=n/2; while(n>0){ i=m; while(i>0){ if(P==NULL){ P=S; } else{ P=P->right; } i--; } v.push_back(P->data); //cout<<P->data<<vno<<" "; delk(S,P->data); n--; } return v; } bool in(vector<int> v, int n){ for(int i=0;i<v.size();i++){ if(n==v[i]){ return true; }} return false; } int main(){ dlptr P; int total; cin>>total; cretdln(P,total); vector<int> v=oprn(P,total); for (int i = 1; i <=total; i++) { if(!in(v,i)) cout<<'A'; else { cout<<'B'; } } }
49608a0c69f53b2692fbf3236de76f4b51ed0fc6
82dc3cc4c97c05e384812cc9aa07938e2dbfe24b
/development/src/elements/optimization/materials/SSOptimize_MatList2DT.h
86c7010a1ff111363dbe63b2d7fa4c0936ca3b1d
[ "BSD-3-Clause" ]
permissive
samanseifi/Tahoe
ab40da0f8d952491943924034fa73ee5ecb2fecd
542de50ba43645f19ce4b106ac8118c4333a3f25
refs/heads/master
2020-04-05T20:24:36.487197
2017-12-02T17:09:11
2017-12-02T17:24:23
38,074,546
3
0
null
null
null
null
UTF-8
C++
false
false
1,329
h
/* $Id: SSOptimize_MatList2DT.h,v 1.1 2009/04/23 03:03:51 thao Exp $ */ /* created: paklein (02/14/1997) */ #ifndef _SS_OPT_LIST_2D_T_H_ #define _SS_OPT_LIST_2D_T_H_ /* base classes */ #include "SSSolidMatList2DT.h" namespace Tahoe { /* forward declaration */ //class SSSolidMatT; class SSOptimize_MatT; class SSOptimize_MatSupportT; /** small strain materials list for 2D structural analysis */ class SSOptimize_MatList2DT: public SSSolidMatList2DT { public: /** constructor */ SSOptimize_MatList2DT(int length, const SSOptimize_MatSupportT& support); SSOptimize_MatList2DT(void); /** return the description of the given inline subordinate parameter list */ virtual void DefineInlineSub(const StringT& name, ParameterListT::ListOrderT& order, SubListT& sub_lists) const; /** a pointer to the ParameterInterfaceT of the given subordinate */ virtual ParameterInterfaceT* NewSub(const StringT& name) const; /** accept parameter list */ virtual void TakeParameterList(const ParameterListT& list); /*@}*/ /** construct the specified material or NULL if the request cannot be completed */ SSOptimize_MatT* NewMat(const StringT& name) const; private: /** support for small strain materials */ const SSOptimize_MatSupportT* fSSOptimize_MatSupport; }; } /* namespace Tahoe */ #endif /* _MATLIST_2D_T_H_ */
[ "saman@bu.(none)" ]
saman@bu.(none)
03cc6f0ba15d5f1cb4c723452b012e2f519507db
bfcddcc7cca87f51a067e82d00b596659b6c3f6d
/CodeChef/Contests/DEC18B - December Challenge 2018 Div 2/CHFINTRO - Chef and Interactive Contests.cpp
066bde637428b8a60dc237a7a6b0257ee64333b6
[]
no_license
IshanManchanda/competitive-cpp
1ffb88b19abbbff6643e40706c5b13b166422255
d423fec6641e4525ce52c5a49517269497276607
refs/heads/master
2023-09-04T11:02:31.265177
2023-08-31T17:29:27
2023-08-31T17:29:27
184,057,901
3
0
null
null
null
null
UTF-8
C++
false
false
320
cpp
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); long long n, r, a; cin >> n >> r; for (long long i = 0; i < n; i++) { cin >> a; if (a >= r) { cout << "Good boi" << endl; } else { cout << "Bad boi" << endl; } } }
eccbffb435a80e52855dc2547dd7e7f4f7a2dcdd
3ae80dbc18ed3e89bedf846d098b2a98d8e4b776
/src/IO/PathNull.cpp
af24712bf2bfa83b7e38b4ffbb7682a87e8975ea
[]
no_license
sswroom/SClass
deee467349ca249a7401f5d3c177cdf763a253ca
9a403ec67c6c4dfd2402f19d44c6573e25d4b347
refs/heads/main
2023-09-01T07:24:58.907606
2023-08-31T11:24:34
2023-08-31T11:24:34
329,970,172
10
7
null
null
null
null
UTF-8
C++
false
false
8,948
cpp
#include "Stdafx.h" #include "MyMemory.h" #include "IO/Path.h" #include "Text/MyStringW.h" #if !defined(PATH_MAX) #define PATH_MAX 512 #endif UTF8Char IO::Path::PATH_SEPERATOR = (UTF8Char)'/'; const UTF8Char *IO::Path::ALL_FILES = (const UTF8Char*)"*"; UOSInt IO::Path::ALL_FILES_LEN = 1; WChar *IO::Path::GetTempFileW(WChar *buff, const WChar *fileName) { return 0; } Bool IO::Path::IsDirectoryExistW(const WChar *dir) { return false; } Bool IO::Path::CreateDirectoryW(const WChar *dirInput) { return false; } Bool IO::Path::RemoveDirectoryW(const WChar *dir) { return false; } Bool IO::Path::DeleteFileW(const WChar *fileName) { return false; } OSInt IO::Path::FileNameCompareW(const WChar *file1, const WChar *file2) { return Text::StrCompare(file1, file2); } WChar *IO::Path::GetFileDirectoryW(WChar *buff, const WChar *fileName) { return Text::StrConcat(buff, fileName); } UTF8Char *IO::Path::GetProcessFileName(UTF8Char *buff) { return 0; } WChar *IO::Path::GetProcessFileNameW(WChar *buff) { return 0; } Bool IO::Path::GetProcessFileName(NotNullPtr<Text::StringBuilderUTF8> sb) { return false; } UTF8Char *IO::Path::ReplaceExt(UTF8Char *fileName, const UTF8Char *ext, UOSInt extLen) { UTF8Char *oldExt = 0; UTF8Char c; while ((c = *fileName++) != 0) { if (c == '\\' || c == '/') { oldExt = 0; } else if (c == '.') { oldExt = fileName; } } if (oldExt == 0) { oldExt = fileName; oldExt[-1] = '.'; } return Text::StrConcatC(oldExt, ext, extLen); } WChar *IO::Path::ReplaceExtW(WChar *fileName, const WChar *ext) { WChar *oldExt = 0; WChar c; while ((c = *fileName++) != 0) { if (c == '\\' || c == '/') { oldExt = 0; } else if (c == '.') { oldExt = fileName; } } if (oldExt == 0) { oldExt = fileName; oldExt[-1] = '.'; } return Text::StrConcat(oldExt, ext); } WChar *IO::Path::GetFileExtW(WChar *fileBuff, const WChar *path) { UOSInt i = Text::StrLastIndexOfChar(path, '/'); if (i != INVALID_INDEX) { path = &path[i + 1]; } i = Text::StrLastIndexOfChar(path, '.'); if (i != INVALID_INDEX) { return Text::StrConcat(fileBuff, &path[i + 1]); } else { return Text::StrConcat(fileBuff, L""); } } WChar *IO::Path::AppendPathW(WChar *path, const WChar *toAppend) { if (toAppend[0] == '/') return Text::StrConcat(path, toAppend); UOSInt i = Text::StrLastIndexOfChar(path, '/'); if (GetPathTypeW(path) == IO::Path::PathType::File && i != INVALID_INDEX) { path[i] = 0; i = Text::StrLastIndexOfChar(path, '/'); } while (Text::StrStartsWith(toAppend, L"../")) { if (i != INVALID_INDEX) { path[i] = 0; i = Text::StrLastIndexOfChar(path, '/'); } toAppend += 3; } i = Text::StrCharCnt(path); path[i] = '/'; return Text::StrConcat(&path[i + 1], toAppend); } Bool IO::Path::AppendPath(NotNullPtr<Text::StringBuilderUTF8> sb, const UTF8Char *toAppend, UOSInt toAppendLen) { if (toAppend[0] == '/') { sb->ClearStr(); sb->AppendC(toAppend, toAppendLen); return true; } UOSInt i = Text::StrLastIndexOfCharC(sb->ToString(), sb->GetLength(), '/'); if (GetPathType(sb->ToCString()) == IO::Path::PathType::File && i != INVALID_INDEX) { sb->RemoveChars(sb->GetLength() - i); i = Text::StrLastIndexOfCharC(sb->ToString(), sb->GetLength(), '/'); } while (Text::StrStartsWithC(toAppend, toAppendLen, UTF8STRC("../"))) { if (i != INVALID_INDEX) { sb->RemoveChars(sb->GetLength() - i); i = Text::StrLastIndexOfCharC(sb->ToString(), sb->GetLength(), '/'); } toAppend += 3; toAppendLen -= 3; } sb->AppendUTF8Char('/'); sb->AppendC(toAppend, toAppendLen); return true; } IO::Path::FindFileSession *IO::Path::FindFile(Text::CString path) { return 0; } IO::Path::FindFileSession *IO::Path::FindFileW(const WChar *path) { return 0; } UTF8Char *IO::Path::FindNextFile(UTF8Char *buff, IO::Path::FindFileSession *session, Data::Timestamp *modTime, IO::Path::PathType *pt, UInt64 *fileSize) { return 0; } WChar *IO::Path::FindNextFileW(WChar *buff, IO::Path::FindFileSession *session, Data::Timestamp *modTime, IO::Path::PathType *pt, UInt64 *fileSize) { return 0; } void IO::Path::FindFileClose(IO::Path::FindFileSession *session) { } IO::Path::PathType IO::Path::GetPathTypeW(const WChar *path) { return IO::Path::PathType::Unknown; } Bool IO::Path::PathExists(const UTF8Char *path, UOSInt pathLen) { return false; } Bool IO::Path::PathExistsW(const WChar *path) { return false; } WChar *IO::Path::GetFullPathW(WChar *buff, const WChar *path) { return Text::StrConcat(buff, path); } Bool IO::Path::FilePathMatch(const UTF8Char *path, UOSInt pathLen, const UTF8Char *searchPattern, UOSInt patternLen) { UTF8Char sbuff[256]; UOSInt i = Text::StrLastIndexOfCharC(path, pathLen, '/'); const UTF8Char *fileName = &path[i + 1]; Text::StrConcatC(sbuff, searchPattern, patternLen); Bool isWC = false; UTF8Char *patternStart = 0; UTF8Char *currPattern = sbuff; UTF8Char c; while (true) { c = *currPattern; if (c == 0) { if (isWC) { if (patternStart == 0) return true; return Text::StrEndsWith(fileName, patternStart); } else if (patternStart) { return Text::StrCompareICase(fileName, patternStart) == 0; } else { return *fileName == 0; } } else if (c == '?' || c == '*') { if (isWC) { if (patternStart == 0) return false; *currPattern = 0; if ((i = Text::StrIndexOf(fileName, patternStart)) == INVALID_INDEX) return false; fileName += i + currPattern - patternStart; patternStart = 0; isWC = false; } else if (patternStart) { *currPattern = 0; if (!Text::StrStartsWithICase(fileName, patternStart)) return false; fileName += currPattern - patternStart; patternStart = 0; isWC = false; } if (c == '?') { if (*fileName == 0) return false; fileName++; currPattern++; } else { isWC = true; patternStart = 0; currPattern++; } } else { if (patternStart == 0) { patternStart = currPattern; } currPattern++; } } } Bool IO::Path::FilePathMatchW(const WChar *path, const WChar *searchPattern) { WChar wbuff[256]; UOSInt i = Text::StrLastIndexOfChar(path, '/'); const WChar *fileName = &path[i + 1]; Text::StrConcat(wbuff, searchPattern); Bool isWC = false; WChar *patternStart = 0; WChar *currPattern = wbuff; WChar c; while (true) { c = *currPattern; if (c == 0) { if (isWC) { if (patternStart == 0) return true; return Text::StrEndsWith(fileName, patternStart); } else if (patternStart) { return Text::StrCompareICase(fileName, patternStart) == 0; } else { return *fileName == 0; } } else if (c == '?' || c == '*') { if (isWC) { if (patternStart == 0) return false; *currPattern = 0; if ((i = Text::StrIndexOf(fileName, patternStart)) == INVALID_INDEX) return false; fileName += i + currPattern - patternStart; patternStart = 0; isWC = false; } else if (patternStart) { *currPattern = 0; if (!Text::StrStartsWithICase(fileName, patternStart)) return false; fileName += currPattern - patternStart; patternStart = 0; isWC = false; } if (c == '?') { if (*fileName == 0) return false; fileName++; currPattern++; } else { isWC = true; patternStart = 0; currPattern++; } } else { if (patternStart == 0) { patternStart = currPattern; } currPattern++; } } } UInt64 IO::Path::GetFileSizeW(const WChar *path) { return 0; } WChar *IO::Path::GetSystemProgramPathW(WChar *buff) { return 0; } WChar *IO::Path::GetLocAppDataPathW(WChar *buff) { return 0; } WChar *IO::Path::GetOSPathW(WChar *buff) { return 0; } Bool IO::Path::GetFileTime(const UTF8Char *path, Data::DateTime *modTime, Data::DateTime *createTime, Data::DateTime *accessTime) { return false; } Data::Timestamp IO::Path::GetModifyTime(const UTF8Char *path) { return Data::Timestamp(0); } WChar *IO::Path::GetCurrDirectoryW(WChar *buff) { return 0; } Bool IO::Path::SetCurrDirectoryW(const WChar *path) { return 0; } Bool IO::Path::IsSearchPattern(const UTF8Char *path) { Bool isSrch = false; UTF8Char c; while ((c = *path++) != 0) { if (c == '*' || c == '?') { isSrch = true; break; } } return isSrch; } UTF8Char *IO::Path::GetRealPath(UTF8Char *sbuff, const UTF8Char *path, UOSInt pathLen) { return Text::StrConcatC(sbuff, path, pathLen); }
423287c1d5c323808f06a021c12c79e2da6f421e
a06a28c5fe36c5cd480f49a9871d05f268c3cc5d
/segemntsum1.cpp
8a2360210d8f2f6123f9dc063658ef469687ec6b
[]
no_license
niharika987/dev
f7f84ea55e246ce2843f02704d5d0f17a083da8b
b588b29092abca975a828fbb7217622305907c1f
refs/heads/master
2020-03-29T07:13:49.934820
2018-09-20T19:23:34
2018-09-20T19:23:34
149,657,657
1
0
null
null
null
null
UTF-8
C++
false
false
4,834
cpp
#include <stdio.h> #include <math.h> // A utility function to get the middle index from corner indexes. int getMid(int s, int e) { return s + (e -s)/2; } /* A recursive function to get the sum of values in given range of the array. The following are parameters for this function. st --> Pointer to segment tree si --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[si] qs & qe --> Starting and ending indexes of query range */ int getSumUtil(int *st, int ss, int se, int qs, int qe, int si) { // If segment of this node is a part of given range, then return // the sum of the segment if (qs <= ss && qe >= se) return st[si]; // If segment of this node is outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return getSumUtil(st, ss, mid, qs, qe, 2*si+1) + getSumUtil(st, mid+1, se, qs, qe, 2*si+2); } /* A recursive function to update the nodes which have the given index in their range. The following are parameters st, si, ss and se are same as getSumUtil() i --> index of the element to be updated. This index is in input array. diff --> Value to be added to all nodes which have i in range */ void updateValueUtil(int *st, int ss, int se, int i, int diff, int si) { // Base Case: If the input index lies outside the range of // this segment if (i < ss || i > se) return; // If the input index is in range of this node, then update // the value of the node and its children st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil(st, ss, mid, i, diff, 2*si + 1); updateValueUtil(st, mid+1, se, i, diff, 2*si + 2); } } // The function to update a value in input array and segment tree. // It uses updateValueUtil() to update the value in segment tree void updateValue(int arr[], int *st, int n, int i, int new_val) { // Check for erroneous input index if (i < 0 || i > n-1) { printf("Invalid Input"); return; } // Get the difference between new value and old value int diff = new_val - arr[i]; // Update the value in array arr[i] = new_val; // Update the values of nodes in segment tree updateValueUtil(st, 0, n-1, i, diff, 0); } // Return sum of elements in range from index qs (quey start) // to qe (query end). It mainly uses getSumUtil() int getSum(int *st, int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n-1 || qs > qe) { printf("Invalid Input"); return -1; } return getSumUtil(st, 0, n-1, qs, qe, 0); } // A recursive function that constructs Segment Tree for array[ss..se]. // si is index of current node in segment tree st int constructSTUtil(int arr[], int ss, int se, int *st, int si) { // If there is one element in array, store it in current node of // segment tree and return if (ss == se) { st[si] = arr[ss]; return arr[ss]; } // If there are more than one elements, then recur for left and // right subtrees and store the sum of values in this node int mid = getMid(ss, se); st[si] = constructSTUtil(arr, ss, mid, st, si*2+1) + constructSTUtil(arr, mid+1, se, st, si*2+2); return st[si]; } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ int *constructST(int arr[], int n) { // Allocate memory for segment tree //Height of segment tree int x = (int)(ceil(log2(n))); //Maximum size of segment tree int max_size = 2*(int)pow(2, x) - 1; // Allocate memory int *st = new int[max_size]; // Fill the allocated memory st constructSTUtil(arr, 0, n-1, st, 0); // Return the constructed segment tree return st; } // Driver program to test above functions int main() { int arr[] = {1, 3, 5, 7, 9, 11}; int n = sizeof(arr)/sizeof(arr[0]); // Build segment tree from given array int *st = constructST(arr, n); // Print sum of values in array from index 1 to 3 printf("Sum of values in given range = %d", getSum(st, n, 1, 3)); // Update: set arr[1] = 10 and update corresponding // segment tree nodes updateValue(arr, st, n, 1, 10); // Find sum after the value is updated printf("Updated sum of values in given range = %d", getSum(st, n, 1, 3)); return 0; }
976c2892d394951d974892a7a0bf1920bfc08f99
94110b285a7f0c3a649c7ced9d1d336517322fad
/Set3&4/problem_11.cpp
3aff03bfab6132a6bf72f39bc2d43b776296bf29
[]
no_license
mizanonik/DataStructure
774dd6f05f706971e2d608c213fabd751281314e
a3c084668f955c784d2871439e796d0601be8ac7
refs/heads/master
2021-04-20T19:21:17.373985
2020-03-24T13:24:42
2020-03-24T13:24:42
249,712,472
0
0
null
null
null
null
UTF-8
C++
false
false
872
cpp
#include <iostream> using namespace std; class Node { public: int data; Node *next; }; void push(Node **head_ref, int data) { Node *ptr1 = new Node(); Node *temp = *head_ref; ptr1->data = data; ptr1->next = *head_ref; if (*head_ref != NULL) { while (temp->next != *head_ref) temp = temp->next; temp->next = ptr1; } else ptr1->next = ptr1; *head_ref = ptr1; } void printList(Node *head) { Node *temp = head; if (head != NULL) { do { cout << temp->data << " "; temp = temp->next; } while (temp != head); } } int main() { Node *head = NULL; push(&head, 12); push(&head, 56); push(&head, 2); push(&head, 11); cout << "Circular Linked List " << endl; printList(head); return 0; }
3f48b195a9209a324db9007c287a87387d2345af
e55f27c6dee2c732598d68a888899e6b4dbb3027
/test/enet/external_libs/tensorflow/tensorflow/core/lib/strings/stringprintf.h
52af410d42936a1676b3297a7fef71f8ff7053c5
[ "MIT" ]
permissive
PINTO0309/TensorflowLite-flexdelegate
3bcc6970da764b961badf79c17e874955e37ad7b
36a4ea442ae3dbcc6bfacdb530decd47857ad1ac
refs/heads/master
2021-10-27T01:31:36.427691
2021-10-12T23:15:42
2021-10-12T23:15:42
223,550,637
20
4
MIT
2019-11-24T04:30:08
2019-11-23T07:40:07
Python
UTF-8
C++
false
false
1,875
h
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // Printf variants that place their output in a C++ string. // // Usage: // string result = strings::Printf("%d %s\n", 10, "hello"); // strings::SPrintf(&result, "%d %s\n", 10, "hello"); // strings::Appendf(&result, "%d %s\n", 20, "there"); #ifndef TENSORFLOW_CORE_LIB_STRINGS_STRINGPRINTF_H_ #define TENSORFLOW_CORE_LIB_STRINGS_STRINGPRINTF_H_ #include <stdarg.h> #include <string> #include "tensorflow/core/platform/macros.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { namespace strings { // Return a C++ string extern string Printf(const char* format, ...) // Tell the compiler to do printf format string checking. TF_PRINTF_ATTRIBUTE(1, 2); // Append result to a supplied string extern void Appendf(string* dst, const char* format, ...) // Tell the compiler to do printf format string checking. TF_PRINTF_ATTRIBUTE(2, 3); // Lower-level routine that takes a va_list and appends to a specified // string. All other routines are just convenience wrappers around it. extern void Appendv(string* dst, const char* format, va_list ap); } // namespace strings } // namespace tensorflow #endif // TENSORFLOW_CORE_LIB_STRINGS_STRINGPRINTF_H_
9b3b823ef1975f1eea259599c47aa02b16fac11a
fcb16918dc51b85b6b531188b1b587b376f7a456
/DirectX/Game/Game/audio.cpp
03d5b66d47c82750dc5cb80bae5f6b429bd03658
[]
no_license
JamieSandell/University
a534991a2e71572f841c9d3ee443b19690deb358
472b5c6cbe5a4e6bed3e68882fa6d0fc3a231ed3
refs/heads/main
2023-03-04T00:33:57.722010
2021-02-15T13:50:24
2021-02-15T13:50:24
334,415,301
0
0
null
null
null
null
UTF-8
C++
false
false
13,743
cpp
//-------------------------------------------------------------------------------------- // File: audio.cpp // // Copyright (c) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- #include "DXUT.h" #include "DXUTcamera.h" #include "DXUTsettingsdlg.h" #include "SDKmisc.h" #include "SDKwavefile.h" #include "audio.h" //-------------------------------------------------------------------------------------- // Global variables //-------------------------------------------------------------------------------------- AUDIO_STATE g_audioState; // Must match order of g_PRESET_NAMES XAUDIO2FX_REVERB_I3DL2_PARAMETERS g_PRESET_PARAMS[ NUM_PRESETS ] = { XAUDIO2FX_I3DL2_PRESET_DEFAULT, XAUDIO2FX_I3DL2_PRESET_GENERIC, XAUDIO2FX_I3DL2_PRESET_PADDEDCELL, XAUDIO2FX_I3DL2_PRESET_ROOM, XAUDIO2FX_I3DL2_PRESET_BATHROOM, XAUDIO2FX_I3DL2_PRESET_LIVINGROOM, XAUDIO2FX_I3DL2_PRESET_STONEROOM, XAUDIO2FX_I3DL2_PRESET_AUDITORIUM, XAUDIO2FX_I3DL2_PRESET_CONCERTHALL, XAUDIO2FX_I3DL2_PRESET_CAVE, XAUDIO2FX_I3DL2_PRESET_ARENA, XAUDIO2FX_I3DL2_PRESET_HANGAR, XAUDIO2FX_I3DL2_PRESET_CARPETEDHALLWAY, XAUDIO2FX_I3DL2_PRESET_HALLWAY, XAUDIO2FX_I3DL2_PRESET_STONECORRIDOR, XAUDIO2FX_I3DL2_PRESET_ALLEY, XAUDIO2FX_I3DL2_PRESET_FOREST, XAUDIO2FX_I3DL2_PRESET_CITY, XAUDIO2FX_I3DL2_PRESET_MOUNTAINS, XAUDIO2FX_I3DL2_PRESET_QUARRY, XAUDIO2FX_I3DL2_PRESET_PLAIN, XAUDIO2FX_I3DL2_PRESET_PARKINGLOT, XAUDIO2FX_I3DL2_PRESET_SEWERPIPE, XAUDIO2FX_I3DL2_PRESET_UNDERWATER, XAUDIO2FX_I3DL2_PRESET_SMALLROOM, XAUDIO2FX_I3DL2_PRESET_MEDIUMROOM, XAUDIO2FX_I3DL2_PRESET_LARGEROOM, XAUDIO2FX_I3DL2_PRESET_MEDIUMHALL, XAUDIO2FX_I3DL2_PRESET_LARGEHALL, XAUDIO2FX_I3DL2_PRESET_PLATE, }; //----------------------------------------------------------------------------------------- // Initialize the audio by creating the XAudio2 device, mastering voice, etc. //----------------------------------------------------------------------------------------- HRESULT InitAudio() { // Clear struct ZeroMemory( &g_audioState, sizeof( AUDIO_STATE ) ); // // Initialize XAudio2 // CoInitializeEx( NULL, COINIT_MULTITHREADED ); UINT32 flags = 0; #ifdef _DEBUG flags |= XAUDIO2_DEBUG_ENGINE; #endif HRESULT hr; if( FAILED( hr = XAudio2Create( &g_audioState.pXAudio2, flags ) ) ) return hr; // // Create a mastering voice // if( FAILED( hr = g_audioState.pXAudio2->CreateMasteringVoice( &g_audioState.pMasteringVoice ) ) ) { SAFE_RELEASE( g_audioState.pXAudio2 ); return hr; } // Check device details to make sure it's within our sample supported parameters XAUDIO2_DEVICE_DETAILS details; if( FAILED( hr = g_audioState.pXAudio2->GetDeviceDetails( 0, &details ) ) ) { SAFE_RELEASE( g_audioState.pXAudio2 ); return hr; } if( details.OutputFormat.Format.nChannels > OUTPUTCHANNELS ) { SAFE_RELEASE( g_audioState.pXAudio2 ); return E_FAIL; } g_audioState.dwChannelMask = details.OutputFormat.dwChannelMask; g_audioState.nChannels = details.OutputFormat.Format.nChannels; // // Create reverb effect // flags = 0; #ifdef _DEBUG flags |= XAUDIO2FX_DEBUG; #endif if( FAILED( hr = XAudio2CreateReverb( &g_audioState.pReverbEffect, flags ) ) ) { SAFE_RELEASE( g_audioState.pXAudio2 ); return hr; } // // Create a submix voice // // Reverb effect in XAudio2 currently only supports mono channel count const XAUDIO2_EFFECT_DESCRIPTOR effects[] = { { g_audioState.pReverbEffect, TRUE, 1 } }; const XAUDIO2_EFFECT_CHAIN effectChain = { 1, effects }; if( FAILED( hr = g_audioState.pXAudio2->CreateSubmixVoice( &g_audioState.pSubmixVoice, 1, details.OutputFormat.Format.nSamplesPerSec, 0, 0, NULL, &effectChain ) ) ) { SAFE_RELEASE( g_audioState.pXAudio2 ); SAFE_RELEASE( g_audioState.pReverbEffect ); return hr; } // Set default FX params XAUDIO2FX_REVERB_PARAMETERS native; ReverbConvertI3DL2ToNative( &g_PRESET_PARAMS[0], &native ); g_audioState.pSubmixVoice->SetEffectParameters( 0, &native, sizeof( native ) ); // // Initialize X3DAudio // Speaker geometry configuration on the final mix, specifies assignment of channels // to speaker positions, defined as per WAVEFORMATEXTENSIBLE.dwChannelMask // // SpeedOfSound - speed of sound in user-defined world units/second, used // only for doppler calculations, it must be >= FLT_MIN // const float SPEEDOFSOUND = X3DAUDIO_SPEED_OF_SOUND; X3DAudioInitialize( details.OutputFormat.dwChannelMask, SPEEDOFSOUND, g_audioState.x3DInstance ); g_audioState.vListenerPos = D3DXVECTOR3( 0, 0, 0 ); // float( ZMIN ) g_audioState.vEmitterPos = D3DXVECTOR3( 0, 0, 0 ); g_audioState.fListenerAngle = 0; // // Setup 3D audio structs // g_audioState.listener.Position = g_audioState.vListenerPos; g_audioState.listener.OrientFront = D3DXVECTOR3( 0, 0, 1 ); g_audioState.listener.OrientTop = D3DXVECTOR3( 0, 1, 0 ); g_audioState.emitter.Position = g_audioState.vEmitterPos; g_audioState.emitter.OrientFront = D3DXVECTOR3( 0, 0, 1 ); g_audioState.emitter.OrientTop = D3DXVECTOR3( 0, 1, 0 ); g_audioState.emitter.ChannelCount = INPUTCHANNELS; g_audioState.emitter.ChannelRadius = 1.0f; g_audioState.emitter.CurveDistanceScaler = 14.0f; g_audioState.emitter.DopplerScaler = 1.0f; g_audioState.emitter.pCone = &g_audioState.emitterCone; g_audioState.emitter.pCone->InnerAngle = 0.0f; // Setting the inner cone angles to X3DAUDIO_2PI and // outer cone other than 0 causes // the emitter to act like a point emitter using the // INNER cone settings only. g_audioState.emitter.pCone->OuterAngle = 0.0f; // Setting the outer cone angles to zero causes // the emitter to act like a point emitter using the // OUTER cone settings only. g_audioState.emitter.pCone->InnerVolume = 1.0f; g_audioState.emitter.pCone->OuterVolume = 1.0f; g_audioState.emitter.pCone->InnerLPF = 0.0f; g_audioState.emitter.pCone->OuterLPF = 1.0f; g_audioState.emitter.pCone->InnerReverb = 0.0f; g_audioState.emitter.pCone->OuterReverb = 1.0f; g_audioState.emitter.ChannelCount = INPUTCHANNELS; g_audioState.emitter.CurveDistanceScaler = 14.0f; g_audioState.emitter.DopplerScaler = 1.0f; g_audioState.emitter.pChannelAzimuths = g_audioState.emitterAzimuths; g_audioState.dspSettings.SrcChannelCount = INPUTCHANNELS; g_audioState.dspSettings.DstChannelCount = g_audioState.nChannels; g_audioState.dspSettings.pMatrixCoefficients = g_audioState.matrixCoefficients; // // Done // g_audioState.bInitialized = true; return S_OK; } //----------------------------------------------------------------------------- // Prepare a looping wave //----------------------------------------------------------------------------- HRESULT PrepareAudio( const LPWSTR wavname ) { if( !g_audioState.bInitialized ) return E_FAIL; if( g_audioState.pSourceVoice ) { g_audioState.pSourceVoice->Stop( 0 ); g_audioState.pSourceVoice->DestroyVoice(); g_audioState.pSourceVoice = 0; } // // Search for media // WCHAR strFilePath[ MAX_PATH ]; WCHAR wavFilePath[ MAX_PATH ]; StringCchCopy( wavFilePath, MAX_PATH, L"Media\\Wavs\\" ); StringCchCat( wavFilePath, MAX_PATH, wavname ); HRESULT hr; V_RETURN( DXUTFindDXSDKMediaFileCch( strFilePath, MAX_PATH, wavFilePath ) ); // // Read in the wave file // CWaveFile wav; V_RETURN( wav.Open( strFilePath, NULL, WAVEFILE_READ ) ); // Get format of wave file WAVEFORMATEX* pwfx = wav.GetFormat(); // Calculate how many bytes and samples are in the wave DWORD cbWaveSize = wav.GetSize(); // Read the sample data into memory SAFE_DELETE_ARRAY( g_audioState.pbSampleData ); g_audioState.pbSampleData = new BYTE[ cbWaveSize ]; V_RETURN( wav.Read( g_audioState.pbSampleData, cbWaveSize, &cbWaveSize ) ); // // Play the wave using a XAudio2SourceVoice // const IXAudio2Voice* voices[] = { g_audioState.pMasteringVoice, g_audioState.pSubmixVoice }; const XAUDIO2_VOICE_SENDS sendList = { 2, ( IXAudio2Voice** )voices }; // Create the source voice V_RETURN( g_audioState.pXAudio2->CreateSourceVoice( &g_audioState.pSourceVoice, pwfx, 0, XAUDIO2_DEFAULT_FREQ_RATIO, NULL, &sendList ) ); // Submit the wave sample data using an XAUDIO2_BUFFER structure XAUDIO2_BUFFER buffer = {0}; buffer.pAudioData = g_audioState.pbSampleData; buffer.Flags = XAUDIO2_END_OF_STREAM; buffer.AudioBytes = cbWaveSize; buffer.LoopCount = XAUDIO2_LOOP_INFINITE; V_RETURN( g_audioState.pSourceVoice->SubmitSourceBuffer( &buffer ) ); V_RETURN( g_audioState.pSourceVoice->Start( 0 ) ); g_audioState.nFrameToApply3DAudio = 0; return S_OK; } //----------------------------------------------------------------------------- // Perform per-frame update of audio //----------------------------------------------------------------------------- HRESULT UpdateAudio() { if( !g_audioState.bInitialized ) return S_FALSE; if( g_audioState.nFrameToApply3DAudio == 0 ) { // Calculate listener orientation in x-z plane if( g_audioState.vListenerPos.x != g_audioState.listener.Position.x || g_audioState.vListenerPos.z != g_audioState.listener.Position.z ) { D3DXVECTOR3 vDelta = g_audioState.vListenerPos - g_audioState.listener.Position; g_audioState.fListenerAngle = float( atan2( vDelta.x, vDelta.z ) ); vDelta.y = 0.0f; D3DXVec3Normalize( &vDelta, &vDelta ); g_audioState.listener.OrientFront.x = vDelta.x; g_audioState.listener.OrientFront.y = 0.f; g_audioState.listener.OrientFront.z = vDelta.z; } //if( fElapsedTime > 0 ) //{ D3DXVECTOR3 lVelocity = ( g_audioState.vListenerPos - g_audioState.listener.Position ); // / fElapsedTime; g_audioState.listener.Position = g_audioState.vListenerPos; g_audioState.listener.Velocity = lVelocity; D3DXVECTOR3 eVelocity = ( g_audioState.vEmitterPos - g_audioState.emitter.Position ); // / fElapsedTime; g_audioState.emitter.Position = g_audioState.vEmitterPos; g_audioState.emitter.Velocity = eVelocity; //} const DWORD dwCalcFlags = X3DAUDIO_CALCULATE_MATRIX | X3DAUDIO_CALCULATE_DOPPLER | X3DAUDIO_CALCULATE_LPF_DIRECT | X3DAUDIO_CALCULATE_LPF_REVERB | X3DAUDIO_CALCULATE_REVERB; X3DAudioCalculate( g_audioState.x3DInstance, &g_audioState.listener, &g_audioState.emitter, dwCalcFlags, &g_audioState.dspSettings ); IXAudio2SourceVoice* voice = g_audioState.pSourceVoice; if( voice ) { voice->SetFrequencyRatio( g_audioState.dspSettings.DopplerFactor ); voice->SetOutputMatrix( g_audioState.pMasteringVoice, INPUTCHANNELS, g_audioState.nChannels, g_audioState.matrixCoefficients ); } } g_audioState.nFrameToApply3DAudio++; g_audioState.nFrameToApply3DAudio %= 2; return S_OK; } //----------------------------------------------------------------------------- // Set reverb effect //----------------------------------------------------------------------------- HRESULT SetReverb( int nReverb ) { if( !g_audioState.bInitialized ) return S_FALSE; if( nReverb < 0 || nReverb >= NUM_PRESETS ) return E_FAIL; if( g_audioState.pSubmixVoice ) { XAUDIO2FX_REVERB_PARAMETERS native; ReverbConvertI3DL2ToNative( &g_PRESET_PARAMS[ nReverb ], &native ); g_audioState.pSubmixVoice->SetEffectParameters( 0, &native, sizeof( native ) ); } return S_OK; } //----------------------------------------------------------------------------- // Pause audio playback //----------------------------------------------------------------------------- VOID PauseAudio( bool resume ) { if( !g_audioState.bInitialized ) return; if( resume ) g_audioState.pXAudio2->StartEngine(); else g_audioState.pXAudio2->StopEngine(); } //----------------------------------------------------------------------------- // Releases XAudio2 //----------------------------------------------------------------------------- VOID CleanupAudio() { if( !g_audioState.bInitialized ) return; if( g_audioState.pSourceVoice ) { g_audioState.pSourceVoice->DestroyVoice(); g_audioState.pSourceVoice = NULL; } if( g_audioState.pSubmixVoice ) { g_audioState.pSubmixVoice->DestroyVoice(); g_audioState.pSubmixVoice = NULL; } if( g_audioState.pMasteringVoice ) { g_audioState.pMasteringVoice->DestroyVoice(); g_audioState.pMasteringVoice = NULL; } g_audioState.pXAudio2->StopEngine(); SAFE_RELEASE( g_audioState.pXAudio2 ); SAFE_RELEASE( g_audioState.pReverbEffect ); SAFE_DELETE_ARRAY( g_audioState.pbSampleData ); CoUninitialize(); g_audioState.bInitialized = false; }
5971cd847fb98261bfe44de6c156e90d61242c8e
056c4b46b37cf9f90b11db304af3f1ef52f4f665
/Phase2TrackerRawToDigi/interface/Phase2TrackerDigiToRaw.h
1bba1713766e0074a425699507a0249d416ffb55
[]
no_license
CBC2BeamTestAnalysis/EventFilter
56e18377ef91bab9ea61de54fdf23a953008cc85
826ca07eb1291ba34212f1ca04e9a109cc607be6
refs/heads/master
2020-04-05T22:59:49.087149
2015-06-29T07:01:06
2015-06-29T07:01:06
38,232,592
0
0
null
null
null
null
UTF-8
C++
false
false
2,125
h
#include "EventFilter/Phase2TrackerRawToDigi/interface/Phase2TrackerFEDDAQHeader.h" #include "EventFilter/Phase2TrackerRawToDigi/interface/Phase2TrackerFEDDAQTrailer.h" #include "EventFilter/Phase2TrackerRawToDigi/interface/Phase2TrackerFEDHeader.h" #include "EventFilter/Phase2TrackerRawToDigi/interface/Phase2TrackerStackedDigi.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/ESHandle.h" #include "DataFormats/Common/interface/Handle.h" #include "DataFormats/Common/interface/DetSetVector.h" #include "DataFormats/SiPixelCluster/interface/SiPixelCluster.h" #include "CondFormats/SiStripObjects/interface/Phase2TrackerCabling.h" #include "DataFormats/TrackerCommon/interface/TrackerTopology.h" #include "DataFormats/FEDRawData/interface/FEDRawDataCollection.h" namespace Phase2Tracker { class Phase2TrackerDigiToRaw { public: Phase2TrackerDigiToRaw() {} Phase2TrackerDigiToRaw(const Phase2TrackerCabling *, std::map<int,int>, edm::Handle< edmNew::DetSetVector<SiPixelCluster> >, int); ~Phase2TrackerDigiToRaw() {} // loop on FEDs to create buffers void buildFEDBuffers(std::auto_ptr<FEDRawDataCollection>&); // builds a single FED buffer std::vector<uint64_t> makeBuffer(std::vector<edmNew::DetSet<SiPixelCluster>>); // write FE Header to buffer void writeFeHeaderSparsified(std::vector<uint64_t>&,uint64_t&,int,int,int); // determine if a P or S cluster should be written void writeCluster(std::vector<uint64_t>&,uint64_t&, stackedDigi); // write S cluster to buffer void writeSCluster(std::vector<uint64_t>&,uint64_t&, stackedDigi); // write P cluster to buffer void writePCluster(std::vector<uint64_t>&,uint64_t&, stackedDigi); private: // data you get from outside const Phase2TrackerCabling * cabling_; std::map<int,int> stackMap_; edm::Handle< edmNew::DetSetVector<SiPixelCluster> > digishandle_; int mode_; // headers FEDDAQHeader FedDaqHeader_; FEDDAQTrailer FedDaqTrailer_; Phase2TrackerFEDHeader FedHeader_; }; }
b9a259dff33e3e0f7ec7329e08732e63c6ff8876
0b5bb089d6c99c8d1eea1ede2246e5b0c46de610
/res/resource.h
95fbc895bdf5bfb136a3266f84bc52a427185a13
[]
no_license
soui3-demo/MultiLangs
4a1af95a9535d3a83fe12766badcb647d54acf0b
efd8432612ea319934d186c9255a01c6756cc118
refs/heads/master
2020-09-28T23:03:40.059025
2019-12-10T03:00:35
2019-12-10T03:00:35
226,886,747
1
1
null
null
null
null
UTF-8
C++
false
false
5,420
h
//stamp:091e54a5aaae8d24 /*<------------------------------------------------------------------------------------------------->*/ /*该文件由uiresbuilder生成,请不要手动修改*/ /*<------------------------------------------------------------------------------------------------->*/ #pragma once #include <res.mgr/snamedvalue.h> #define ROBJ_IN_CPP \ namespace SOUI \ {\ const _R R;\ const _UIRES UIRES;\ } namespace SOUI { class _UIRES{ public: class _UIDEF{ public: _UIDEF(){ XML_INIT = _T("UIDEF:XML_INIT"); } const TCHAR * XML_INIT; }UIDEF; class _LAYOUT{ public: _LAYOUT(){ XML_MAINWND = _T("LAYOUT:XML_MAINWND"); } const TCHAR * XML_MAINWND; }LAYOUT; class _values{ public: _values(){ string = _T("values:string"); color = _T("values:color"); skin = _T("values:skin"); } const TCHAR * string; const TCHAR * color; const TCHAR * skin; }values; class _lang{ public: _lang(){ cn = _T("lang:cn"); en = _T("lang:en"); } const TCHAR * cn; const TCHAR * en; }lang; class _ICON{ public: _ICON(){ ICON_LOGO = _T("ICON:ICON_LOGO"); } const TCHAR * ICON_LOGO; }ICON; class _img{ public: _img(){ pic_100 = _T("img:pic_100"); pic_125 = _T("img:pic_125"); pic_150 = _T("img:pic_150"); pic_200 = _T("img:pic_200"); chat_9 = _T("img:chat.9"); } const TCHAR * pic_100; const TCHAR * pic_125; const TCHAR * pic_150; const TCHAR * pic_200; const TCHAR * chat_9; }img; class _smenu{ public: _smenu(){ menu_lang = _T("smenu:menu_lang"); } const TCHAR * menu_lang; }smenu; }; const SNamedID::NAMEDVALUE namedXmlID[]={ {L"_name_start",65535}, {L"btn_close",65540}, {L"btn_max",65538}, {L"btn_menu",65536}, {L"btn_min",65537}, {L"btn_restore",65539}, {L"btn_scale_100",65541}, {L"btn_scale_125",65542}, {L"btn_scale_150",65543}, {L"btn_scale_200",65544}, {L"col1",65547}, {L"col2",65549}, {L"col3",65551}, {L"col4",65553}, {L"lang_cn",100}, {L"lang_en",101}, {L"mclv_test",65546}, {L"txt_age",65552}, {L"txt_gender",65550}, {L"txt_name",65548}, {L"txt_score",65554}, {L"txt_test",65545} }; class _R{ public: class _name{ public: _name(){ _name_start = namedXmlID[0].strName; btn_close = namedXmlID[1].strName; btn_max = namedXmlID[2].strName; btn_menu = namedXmlID[3].strName; btn_min = namedXmlID[4].strName; btn_restore = namedXmlID[5].strName; btn_scale_100 = namedXmlID[6].strName; btn_scale_125 = namedXmlID[7].strName; btn_scale_150 = namedXmlID[8].strName; btn_scale_200 = namedXmlID[9].strName; col1 = namedXmlID[10].strName; col2 = namedXmlID[11].strName; col3 = namedXmlID[12].strName; col4 = namedXmlID[13].strName; lang_cn = namedXmlID[14].strName; lang_en = namedXmlID[15].strName; mclv_test = namedXmlID[16].strName; txt_age = namedXmlID[17].strName; txt_gender = namedXmlID[18].strName; txt_name = namedXmlID[19].strName; txt_score = namedXmlID[20].strName; txt_test = namedXmlID[21].strName; } const wchar_t * _name_start; const wchar_t * btn_close; const wchar_t * btn_max; const wchar_t * btn_menu; const wchar_t * btn_min; const wchar_t * btn_restore; const wchar_t * btn_scale_100; const wchar_t * btn_scale_125; const wchar_t * btn_scale_150; const wchar_t * btn_scale_200; const wchar_t * col1; const wchar_t * col2; const wchar_t * col3; const wchar_t * col4; const wchar_t * lang_cn; const wchar_t * lang_en; const wchar_t * mclv_test; const wchar_t * txt_age; const wchar_t * txt_gender; const wchar_t * txt_name; const wchar_t * txt_score; const wchar_t * txt_test; }name; class _id{ public: const static int _name_start = 65535; const static int btn_close = 65540; const static int btn_max = 65538; const static int btn_menu = 65536; const static int btn_min = 65537; const static int btn_restore = 65539; const static int btn_scale_100 = 65541; const static int btn_scale_125 = 65542; const static int btn_scale_150 = 65543; const static int btn_scale_200 = 65544; const static int col1 = 65547; const static int col2 = 65549; const static int col3 = 65551; const static int col4 = 65553; const static int lang_cn = 100; const static int lang_en = 101; const static int mclv_test = 65546; const static int txt_age = 65552; const static int txt_gender = 65550; const static int txt_name = 65548; const static int txt_score = 65554; const static int txt_test = 65545; }id; class _string{ public: const static int female = 0; const static int male = 1; const static int title = 2; const static int unknown = 3; const static int ver = 4; }string; class _color{ public: const static int blue = 0; const static int gray = 1; const static int green = 2; const static int red = 3; const static int white = 4; }color; }; #ifdef R_IN_CPP extern const _R R; extern const _UIRES UIRES; #else extern const __declspec(selectany) _R & R = _R(); extern const __declspec(selectany) _UIRES & UIRES = _UIRES(); #endif//R_IN_CPP }
44f3d4dfd4aff70fffa53e5beb2f8d79e564eab9
a92b18defb50c5d1118a11bc364f17b148312028
/src/prod/src/Reliability/Replication/ComFromBytesOperation.cpp
4e2a34762f0e79d0810f044e7ebd638ace0d9077
[ "MIT" ]
permissive
KDSBest/service-fabric
34694e150fde662286e25f048fb763c97606382e
fe61c45b15a30fb089ad891c68c893b3a976e404
refs/heads/master
2023-01-28T23:19:25.040275
2020-11-30T11:11:58
2020-11-30T11:11:58
301,365,601
1
0
MIT
2020-11-30T11:11:59
2020-10-05T10:05:53
null
UTF-8
C++
false
false
8,967
cpp
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace Reliability::ReplicationComponent; using namespace Common; ComFromBytesOperation::ComFromBytesOperation( std::vector<Common::const_buffer> const & buffers, std::vector<ULONG> const & segmentSizes, FABRIC_OPERATION_METADATA const & metadata, OperationAckCallback const & ackCallback, FABRIC_SEQUENCE_NUMBER lastOperationInBatch) : ComOperation(metadata, Constants::InvalidEpoch, lastOperationInBatch), data_(), segmentSizes_(segmentSizes), ackCallback_(ackCallback), callbackState_(CallbackState::NotCalled) { InitBuffer(buffers); InitData(); } ComFromBytesOperation::ComFromBytesOperation( std::vector<Common::const_buffer> const & buffers, std::vector<ULONG> const & segmentSizes, FABRIC_OPERATION_METADATA const & metadata, FABRIC_EPOCH const & epoch, OperationAckCallback const & ackCallback, FABRIC_SEQUENCE_NUMBER lastOperationInBatch) : ComOperation(metadata, epoch, lastOperationInBatch), data_(), segmentSizes_(segmentSizes), ackCallback_(ackCallback), callbackState_(CallbackState::NotCalled) { InitBuffer(buffers); InitData(); } ComFromBytesOperation::ComFromBytesOperation( std::vector<BYTE> && data, std::vector<ULONG> const & segmentSizes, FABRIC_OPERATION_METADATA const & metadata, FABRIC_EPOCH const & epoch, OperationAckCallback const & ackCallback, FABRIC_SEQUENCE_NUMBER lastOperationInBatch) : ComOperation(metadata, epoch, lastOperationInBatch), data_(std::move(data)), segmentSizes_(segmentSizes), ackCallback_(ackCallback), callbackState_(CallbackState::NotCalled) { InitData(); } ComFromBytesOperation::ComFromBytesOperation( FABRIC_OPERATION_METADATA const & metadata, OperationAckCallback const & ackCallback, FABRIC_SEQUENCE_NUMBER lastOperationInBatch, Common::ComponentRoot const & root) : ComOperation(metadata, Constants::InvalidEpoch, lastOperationInBatch), ackCallback_(ackCallback), callbackState_(CallbackState::NotCalled) { rootSPtr_ = root.CreateComponentRoot(); } ComFromBytesOperation::~ComFromBytesOperation() { } void ComFromBytesOperation::InitData() { size_t size = data_.size(); if (this->segmentSizes_.size() != 0) { size_t totalSegmentSize = 0; for (ULONG segmentSize : this->segmentSizes_) { totalSegmentSize += segmentSize; } ASSERT_IF(totalSegmentSize != size, "{0} does not match {1}", totalSegmentSize, size); ULONG segmentWalker = 0; for (ULONG segmentSize : this->segmentSizes_) { FABRIC_OPERATION_DATA_BUFFER replicaBuffer; // for 0 size buffer, point the Buffer to any valid non-NULL address with BufferSize=0 replicaBuffer.Buffer = (0 == size) ? (BYTE*)&data_ : (this->data_.data() + segmentWalker); replicaBuffer.BufferSize = segmentSize; segmentWalker += segmentSize; this->segments_.push_back(replicaBuffer); } } } void ComFromBytesOperation::InitBuffer( std::vector<Common::const_buffer> const & buffers) { size_t size = 0; for (auto buffer : buffers) { size += buffer.len; } data_.reserve(size); for (auto buffer : buffers) { data_.insert(data_.end(), buffer.buf, buffer.buf + buffer.len); } } bool ComFromBytesOperation::IsEmpty() const { return data_.empty(); } bool ComFromBytesOperation::get_NeedsAck() const { Common::AcquireExclusiveLock lock(this->lock_); bool ret = false; switch (this->callbackState_) { case CallbackState::NotCalled: ret = true; break; case CallbackState::ReadyToRun: // #4780473 - pending ops on secondary with EOS do not keep root alive. hence wait for the running callback to finish // Scenario without EOS is that LSN 1 could be completing, with 2 and 3 waiting on the queue lock in secondaryreplicator onackreplicationoperation // 2 and 3 are in running state, which makes OQ believe that they are ack'd and hence releases all objects to finish any pending async op and destruct // when 2 and 3's callbacks run, they AV ret = true; break; case CallbackState::Running: case CallbackState::Completed: case CallbackState::Cancelled: ret = false; break; default: Assert::CodingError("Unknown callbackstate {0}", static_cast<int>(callbackState_)); } return ret; } void ComFromBytesOperation::OnAckCallbackStartedRunning() { Common::AcquireExclusiveLock lock(this->lock_); ASSERT_IFNOT( this->callbackState_ == CallbackState::ReadyToRun, "Callback must be in ready to run state before running. It is {0}", static_cast<int>(callbackState_)); callbackState_ = CallbackState::Running; } void ComFromBytesOperation::SetIgnoreAckAndKeepParentAlive(Common::ComponentRoot const & root) { Common::AcquireExclusiveLock lock(this->lock_); if (this->IsEndOfStreamOperation) { // For an end of stream operation that could have been enqueued into the operation queue (happens during Copy only), // we cannot ignore the ACK. So we will keep the root alive, but not ignore the ACK if (this->callbackState_ == CallbackState::NotCalled || this->callbackState_ == CallbackState::Running || this->callbackState_ == CallbackState::ReadyToRun) { rootSPtr_ = root.CreateComponentRoot(); } } else { if (this->callbackState_ == CallbackState::NotCalled) { this->callbackState_ = CallbackState::Cancelled; } else if (this->callbackState_ == CallbackState::Running || this->callbackState_ == CallbackState::ReadyToRun) { // Ack was required and now is ignored; // increase the ref count on the parent, // so in case ACK comes it will still be alive rootSPtr_ = root.CreateComponentRoot(); } // else it must be completed, we don't care } } HRESULT ComFromBytesOperation::Acknowledge() { bool isCallbackRunning = false; { Common::AcquireExclusiveLock lock(this->lock_); TESTASSERT_IF(this->callbackState_ == CallbackState::Completed, "Callback is already completed"); TESTASSERT_IF(this->callbackState_ == CallbackState::Running, "Callback is already running"); ASSERT_IF(this->callbackState_ == CallbackState::Cancelled && this->IsEndOfStreamOperation, "End of stream operation should never have its callbackstate cancelled"); if (this->callbackState_ == CallbackState::Completed || this->callbackState_ == CallbackState::Running || this->callbackState_ == CallbackState::ReadyToRun) { return ComUtility::OnPublicApiReturn(FABRIC_E_INVALID_OPERATION); } if (this->callbackState_ == CallbackState::NotCalled) { this->callbackState_ = CallbackState::ReadyToRun; isCallbackRunning = true; } } if (ackCallback_ && isCallbackRunning) { ackCallback_(*this); } else { OperationQueueEventSource::Events->OperationAck( Metadata.SequenceNumber); } if (isCallbackRunning) { // If the callback finished running, set it to completed and reset the root in case the secondary had closed // and created the root while the callback was running Common::AcquireExclusiveLock lock(this->lock_); ASSERT_IF( (this->callbackState_ != CallbackState::Running) && ackCallback_, "Callback must be in running state before completed when there is a valid ack callback. It is {0}", static_cast<int>(callbackState_)); this->callbackState_ = CallbackState::Completed; rootSPtr_.reset(); } else { TESTASSERT_IFNOT( this->rootSPtr_ == nullptr, "If callback did not run, root must be nullptr"); } return ComUtility::OnPublicApiReturn(S_OK); } HRESULT ComFromBytesOperation::GetData( /*[out]*/ ULONG * count, /*[out, retval]*/ FABRIC_OPERATION_DATA_BUFFER const ** buffers) { if ((count == NULL) || (buffers == NULL)) { return ComUtility::OnPublicApiReturn(E_POINTER); } *count = static_cast<ULONG>(this->segments_.size()); *buffers = this->segments_.data(); return ComUtility::OnPublicApiReturn(S_OK); }
f7c24ffc806430eafdd58c9345b23143ab0ed804
02541cc23351b013278c1ba4b4c5301b71e597cb
/Others/NPSC/D.cpp
11c350c8dd64f6e5ed710096c1719028bbda48c8
[]
no_license
austin880625/problem_solving
d5ac0865405df6d613e408c996c8b875b500a85a
b76cfabcea6e750b9e97c2a66961760fe8d70cf9
refs/heads/master
2021-05-04T11:01:03.178708
2018-07-14T14:14:04
2018-07-14T14:14:04
43,396,070
0
0
null
null
null
null
UTF-8
C++
false
false
870
cpp
#include<iostream> #include<map> #include<queue> using namespace std; map<int,int> m; long long a,c[100100]; void add(long long q,long long x){ while(q<0){q+=1000000007;} while(x<=100010){ c[x]+=q; c[x]%=1000000007; x+=x&-x; } } long long sum(long long x){ long long ans=0; while(x>0){ ans+=c[x]; ans%=1000000007; x-=x&-x; } return ans; } int main(){ int t; cin>>t; while(t--){ int n; cin>>n; m.clear(); for(int i=0;i<100100;i++) c[i]=0; for(int i=1;i<=n;i++){ cin>>a; if(!m.count(a)) add(sum(i-1)+1,i); else add(sum(i-1)-sum(m[a]-1),i); m[a]=i; } //for(int i=1;i<=n;i++) cout<<sum(i)-sum(i-1); cout<<sum(n)<<endl; } }
756a6655158a2947339ed3c1e4220a2124eac181
88ea0aa2bff9c28cca8370edb36f775ddb1889a2
/VCuber/VCuber/ShaderLoader.cpp
f4339d72731ba70280bf1ad18dc2bc410dbbb5ac
[]
no_license
BrianFreemann001/VRCuber
f3ec8024ecf28fb4f65231ef9b7c427d2450301d
7cced7da788630f6b62dcc0d67b415c2ff1a98f4
refs/heads/master
2020-03-27T03:31:48.872731
2018-09-11T23:25:07
2018-09-11T23:25:07
145,870,201
0
0
null
null
null
null
UTF-8
C++
false
false
708
cpp
#include "stdafx.h" #include "ShaderLoader.h" void ShaderLoader::CreatePixelShader(const void *shaderByteCode, ID3D11PixelShader **pixelShader) { directX->device->CreatePixelShader(shaderByteCode, sizeof(shaderByteCode), NULL, pixelShader); } void ShaderLoader::CreateVertexShader(const void *shaderByteCode, ID3D11VertexShader **vertexShader) { directX->device->CreateVertexShader(shaderByteCode, sizeof(shaderByteCode), NULL, vertexShader); } void ShaderLoader::CreateInputLayout(D3D11_INPUT_ELEMENT_DESC *inputElementDesc, const void *shaderByteCode, ID3D11InputLayout **inputLayout) { directX->device->CreateInputLayout(inputElementDesc, 2, shaderByteCode, sizeof(shaderByteCode), inputLayout); }
dd928a57953cdc9d37cd9e48e4de7cbea5b87d42
d76de324f8ce6058aa752eab732b29e0b5bb9d99
/sources/RestoreSelectionAction.h
bdbb882d7f1c839421b53fda2ea7762efe9af96c
[ "MIT" ]
permissive
HaikuArchives/EnglishEditorII
acdfc67df885ac3a3d64977dc760de4678d4a80b
2e5ef3d6b3ee519498c2eb135ac76948ae17af5e
refs/heads/master
2021-01-19T06:49:55.574319
2015-08-18T18:16:36
2015-08-18T18:16:36
13,135,323
1
0
null
null
null
null
UTF-8
C++
false
false
450
h
/* RestoreSelectionAction.h */ #ifndef _H_RestoreSelectionAction_ #define _H_RestoreSelectionAction_ #include "Action.h" #ifndef NULL #define NULL (0) #endif class RestoreSelectionAction : public Action { public: RestoreSelectionAction(Action* wrappedActionIn = NULL); ~RestoreSelectionAction(); void Do(DisplayDirector* director); void Undo(DisplayDirector* director); protected: Action* restoreAction; Action* wrappedAction; }; #endif
9714a89d94e042ae3e335104d705ad60ea5a094a
c085451c829e46a00e9f549addef6f29f2f3ed82
/tests/DavidsonSolver_test.cpp
09081cf11f3273f8e72115fa32d72330a9ce0003
[]
no_license
lelemmen/davidson
5af56fc0b6fc2bd3d0dec7b48a341fadaa2d49db
eae81e47cd9d1c8a3ea110d4a08cffae542c4915
refs/heads/master
2021-05-16T18:03:18.468739
2017-11-18T07:15:06
2017-11-18T07:15:06
103,135,772
0
1
null
null
null
null
UTF-8
C++
false
false
5,851
cpp
#define BOOST_TEST_MODULE "Davidson diagonalization" #include <boost/test/unit_test.hpp> #include <boost/test/included/unit_test.hpp> // include this to get main(), otherwise the C++ compiler will complain #include "davidson.hpp" /** Check if two sets of eigenvalues are equal */ bool are_equal_evals(Eigen::VectorXd& evals1, Eigen::VectorXd& evals2, double& tol) { return evals1.isApprox(evals2, tol); } /** Check if two sets of eigenvectors are equal (up to a factor -1) */ bool are_equal_evecs(Eigen::MatrixXd& evecs1, Eigen::MatrixXd& evecs2, double& tol) { auto dim = evecs1.cols(); for (int i = 0; i < dim; i++) { if (!(evecs1.col(i).isApprox(evecs2.col(i), tol) || evecs1.col(i).isApprox(-evecs2.col(i), tol))) { return false; } } return true; } BOOST_AUTO_TEST_CASE( constructor ) { std::cout << "\tRunning test case 'constructor'" << std::endl; int dim = 5; unsigned r = 1; double tol = 0.001; Eigen::MatrixXd X = Eigen::MatrixXd::Random(dim, dim); Eigen::MatrixXd XT = X.transpose(); Eigen::MatrixXd S = 0.5 * (X + XT); // Test if DavidsonSolver refuses to accept a non-symmetric matrix BOOST_CHECK_THROW(DavidsonSolver ds1 (X, r, tol), std::invalid_argument); // Test if DavidsonSolver accepts symmetric matrices BOOST_CHECK_NO_THROW(DavidsonSolver ds2 (S, r, tol)); } BOOST_AUTO_TEST_CASE( esqc_example_solver ){ std::cout << "\tRunning test case 'esqc_example_solver'" << std::endl; // We can find the following example at (http://www.esqc.org/static/lectures/Malmqvist_2B.pdf) // Build up the example matrix Eigen::MatrixXd A = Eigen::MatrixXd::Constant(5, 5, 0.1); A(0,0) = 1.0; A(1,1) = 2.0; A(2,2) = 3.0; A(3,3) = 3.0; A(4,4) = 3.0; // The solutions to the problem are given in the example Eigen::VectorXd evals_ex (1); evals_ex << 0.979; Eigen::MatrixXd evecs_ex (5, 1); evecs_ex << 0.994, -0.083, -0.042, -0.042, -0.042; // Solve using the Davidson diagonalization unsigned r = 1; double tol = 0.05; DavidsonSolver ds (A, r, tol); ds.solve(); auto evals_d = ds.eigenvalues(); auto evecs_d = ds.eigenvectors(); // Test if the example solutions are equal to the Davidson solutions BOOST_CHECK(are_equal_evals(evals_d, evals_ex, tol)); BOOST_CHECK(are_equal_evecs(evecs_d, evecs_ex, tol)); } BOOST_AUTO_TEST_CASE( bigger_example_three ) { std::cout << "\tRunning test case 'bigger_example_three'" << std::endl; // Let's make a diagonally dominant, but random matrix int dim = 15; Eigen::MatrixXd A = Eigen::MatrixXd::Constant(dim, dim, 0.1); // First, we put i+1 on the diagonal for (int i = 0; i < dim; i++) { A(i, i) = i + 1; } // Now it's time to solve the eigensystem for S // Afterwards, select the 3 lowest eigenpairs Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> saes (A); Eigen::VectorXd all_evals = saes.eigenvalues(); Eigen::VectorXd evals_ex = all_evals.head(3); // can't do this in the previous line; eigenvalues is const Eigen::MatrixXd all_evecs = saes.eigenvectors(); Eigen::MatrixXd evecs_ex = all_evecs.topLeftCorner(dim, 3); // Now we have to test if my Davidson solver gives the same results unsigned r = 3; double tol = 0.0001; DavidsonSolver ds (A, r, tol); ds.solve(); Eigen::VectorXd evals_d = ds.eigenvalues(); Eigen::MatrixXd evecs_d = ds.eigenvectors(); BOOST_CHECK(are_equal_evals(evals_d, evals_ex, tol)); BOOST_CHECK(are_equal_evecs(evecs_d, evecs_ex, tol)); } BOOST_AUTO_TEST_CASE( liu_example ){ std::cout << "\tRunning test case 'liu_example'" << std::endl; // Let's prepare the Liu example (liu1978) unsigned N = 50; Eigen::MatrixXd A = Eigen::MatrixXd::Ones(N, N); for (unsigned i = 0; i < N; i++) { if (i < 5) { A(i, i) = 1 + 0.1 * i; } else { A(i, i) = 2 * (i + 1) - 1; } } // Input the solutions Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> saes (A); Eigen::VectorXd all_evals = saes.eigenvalues(); Eigen::VectorXd evals_ex = all_evals.head(4); Eigen::MatrixXd all_evecs = saes.eigenvectors(); Eigen::MatrixXd evecs_ex = all_evecs.topLeftCorner(N, 4); // Solve using the Davidson diagonalization unsigned r = 4; double tol = 0.05; DavidsonSolver ds (A, r, tol); ds.solve(); auto evals_d = ds.eigenvalues(); auto evecs_d = ds.eigenvectors(); // Test if the example solutions are equal to the Davidson solutions BOOST_CHECK(are_equal_evals(evals_d, evals_ex, tol)); BOOST_CHECK(are_equal_evecs(evecs_d, evecs_ex, tol)); } BOOST_AUTO_TEST_CASE( liu_big ){ std::cout << "\tRunning test case 'liu_big'" << std::endl; // Let's prepare the Liu example (liu1978) unsigned N = 1000; Eigen::MatrixXd A = Eigen::MatrixXd::Ones(N, N); for (unsigned i = 0; i < N; i++) { if (i < 5) { A(i, i) = 1 + 0.1 * i; } else { A(i, i) = 2 * (i + 1) - 1; } } // Input the solutions Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> saes (A); Eigen::VectorXd all_evals = saes.eigenvalues(); Eigen::VectorXd evals_ex = all_evals.head(4); Eigen::MatrixXd all_evecs = saes.eigenvectors(); Eigen::MatrixXd evecs_ex = all_evecs.topLeftCorner(N, 4); // Solve using the Davidson diagonalization unsigned r = 4; double tol = 0.05; DavidsonSolver ds (A, r, tol); ds.solve(); auto evals_d = ds.eigenvalues(); auto evecs_d = ds.eigenvectors(); // Test if the example solutions are equal to the Davidson solutions BOOST_CHECK(are_equal_evals(evals_d, evals_ex, tol)); BOOST_CHECK(are_equal_evecs(evecs_d, evecs_ex, tol)); }
6f64cc7b309d2e16ec9e8399fffeedc888421e9a
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Animation/Animation/Animation/DeltaCompressed/hkaDeltaCompressedAnimation.h
dde6ea6c3056df98a7098a8f27fdad0d70d1d67b
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
10,051
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HKANIMATION_ANIMATION_DELTACOMPRESSED_HKDELTACOMPRESSEDANIMATION_XML_H #define HKANIMATION_ANIMATION_DELTACOMPRESSED_HKDELTACOMPRESSEDANIMATION_XML_H #include <Animation/Animation/Animation/hkaAnimation.h> /// hkaDeltaCompressedAnimation meta information extern const class hkClass hkaDeltaCompressedAnimationClass; class hkaInterleavedUncompressedAnimation; /// Compresses animation data using a delta transform. /// See Animation Compression section of the Userguide for details. class hkaDeltaCompressedAnimation : public hkaAnimation { public: HK_DECLARE_CLASS_ALLOCATOR( HK_MEMORY_CLASS_ANIM_COMPRESSED ); HK_DECLARE_REFLECTION(); /// Compression parameters struct CompressionParams { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_ANIM_COMPRESSED, hkaDeltaCompressedAnimation::CompressionParams ); /// Bits used for float quantization - default 8, range [2,16] hkUint16 m_quantizationBits; /// Block size - default 65535 hkUint16 m_blockSize; /// TrackAnalysis absolute position tolerance. See the "Compression Overview" section of the Userguide for details - default 0.0 hkReal m_absolutePositionTolerance; // Set to 0 to use only relative tolerance /// TrackAnalysis relative position tolerance. See the "Compression Overview" section of the Userguide for details - default 0.01 hkReal m_relativePositionTolerance; // Set to 0 to use only abs tolerance /// TrackAnalysis rotation position tolerance. See the "Compression Overview" section of the Userguide for details - default 0.001 hkReal m_rotationTolerance; /// TrackAnalysis scale position tolerance. See the "Compression Overview" section of the Userguide for details - default 0.01 hkReal m_scaleTolerance; /// TrackAnalysis float position tolerance. See the "Compression Overview" section of the Userguide for details - default 0.001 hkReal m_absoluteFloatTolerance; CompressionParams(); }; /// This structure is used when specifying per track compression settings struct PerTrackCompressionParams { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_ANIM_COMPRESSED, hkaDeltaCompressedAnimation::PerTrackCompressionParams ); /// List of CompressionParams to enable per-bone compression settings hkArray<struct hkaDeltaCompressedAnimation::CompressionParams> m_parameterPalette; /// An array of indices into the palette above for transform tracks hkArray<int> m_trackIndexToPaletteIndex; /// An array of indices into the palette above for float tracks hkArray<int> m_floatTrackIndexToPaletteIndex; }; /// Constructor compresses data hkaDeltaCompressedAnimation(const hkaInterleavedUncompressedAnimation& rawData, const CompressionParams& params, hkBool useThreeComponentQuaternions = true ); /// Constructor allowing different compression settings for each track in the animation hkaDeltaCompressedAnimation(const hkaInterleavedUncompressedAnimation& rawData, const PerTrackCompressionParams& params, hkBool useThreeComponentQuaternions = true ); /// Get the tracks at a given time /// Note: If you are calling this method directly you may find some quantization error present in the rotations. /// The blending done in hkaAnimatedSkeleton is not sensitive to rotation error so rather than renormalize here /// we defer it until blending has been completed. If you are using this method directly you may want to call /// hkaSkeletonUtils::normalizeRotations() on the results. virtual void sampleTracks(hkReal time, hkQsTransform* transformTracksOut, hkReal* floatTracksOut, hkaChunkCache* cache) const; /// Get a subset of the the first 'maxNumTracks' tracks of a pose at a given time (all tracks from 0 to maxNumTracks-1 inclusive). virtual void samplePartialTracks(hkReal time, hkUint32 maxNumTransformTracks, hkQsTransform* transformTracksOut, hkUint32 maxNumFloatTracks, hkReal* floatTracksOut, hkaChunkCache* cache) const; /// Sample individual animation tracks virtual void sampleIndividualTransformTracks( hkReal time, const hkInt16* tracks, hkUint32 numTracks, hkQsTransform* transformOut ) const; /// Sample a individual floating tracks virtual void sampleIndividualFloatTracks( hkReal time, const hkInt16* tracks, hkUint32 numTracks, hkReal* out ) const; /// Get a key for use with the cache virtual hkUint32 getFullCacheKey( hkUint32 poseIdx ) const; /// Clear the cache of all keys associated with this animation - use to 'unload' an animation from the cache virtual void clearAllCacheKeys(hkaChunkCache* cache) const; /* * Block decompression */ /// Returns the number of original samples / frames of animation virtual int getNumOriginalFrames() const; /// Return the number of chunks of data required to sample the tracks at time t virtual int getNumDataChunks(hkUint32 frame, hkReal delta) const; /// Return the chunks of data required to sample the track at time t virtual void getDataChunks(hkUint32 frame, hkReal delta, DataChunk* dataChunks, int numDataChunks) const; /// Return the maximum total size of all combined chunk data which could be returned by getDataChunks for this animation. virtual int getMaxSizeOfCombinedDataChunks() const; /// Get a subset of the tracks at a given time using data chunks. Sample is calculated using pose[frameIndex] * (1 - frameDelta) + pose[frameIndex+1] * frameDelta. static void HK_CALL samplePartialWithDataChunks(hkUint32 frameIndex, hkReal frameDelta, hkUint32 maxNumTransformTracks, hkQsTransform* transformTracksOut, hkUint32 maxNumFloatTracks, hkReal* floatTracksOut, const DataChunk* dataChunks, int numDataChunks); void getBlockDataAndSize(int blockNum, int numBlocks, DataChunk& dataChunkOut) const; public: /// The number of samples encoded in the animation. int m_numberOfPoses; /// The number of tracks in each encoded block int m_blockSize; // INTERNAL struct QuantizationFormat { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_ANIMATION, hkaDeltaCompressedAnimation::QuantizationFormat ); HK_DECLARE_REFLECTION(); QuantizationFormat( ) { } QuantizationFormat( hkFinishLoadedObjectFlag flag ) {} // Backwards compatibility only - pre-per-track compression. hkUint8 m_maxBitWidth; // Always 1 for delta since first float is stored exactly (for accurate reconstruction when applying inverse delta transform). hkUint8 m_preserved; // Number of dynamic tracks that are quantized and stored hkUint32 m_numD; // Index into the data buffer for the quantization offsets hkUint32 m_offsetIdx; /// Index into the data buffer for the quantization scales hkUint32 m_scaleIdx; // Index into the data buffer for the quantization bidwidths hkUint32 m_bitWidthIdx; }; /// Quantization Description struct QuantizationFormat m_qFormat; /// Index into the data buffer for the Quantization Data hkUint32 m_quantizedDataIdx; /// Size of the Quantization Data (stored as hkUint8) hkUint32 m_quantizedDataSize; /// Index into the data buffer for the Track Mask hkUint32 m_staticMaskIdx; /// Size of the Track Mask (stored as hkUint16) hkUint32 m_staticMaskSize; /// Index into the data buffer for the Static DOF Data hkUint32 m_staticDOFsIdx; /// Size of the Static DOF Data (stored as hkReal) hkUint32 m_staticDOFsSize; /// Number Static Transform DOFs hkUint32 m_numStaticTransformDOFs; /// Number Dynamic Transform DOFs hkUint32 m_numDynamicTransformDOFs; /// Total size of each block in bytes (except for the last block, which can be smaller) /// Multiply by the block number to get the index into that block hkUint32 m_totalBlockSize; /// Total size of the last block (in bytes) /// Store this so that we don't have to compute it on the fly hkUint32 m_lastBlockSize; /// The data buffer where compressed and static data is kept hkArray< hkUint8 > m_dataBuffer; public: // Constructor for initialisation of vtable fixup HK_FORCE_INLINE hkaDeltaCompressedAnimation( hkFinishLoadedObjectFlag flag ) : hkaAnimation(flag), m_dataBuffer(flag) { if (flag.m_finishing) handleEndian(); } private: /// Initialize the animation with construction info void initialize(const hkaInterleavedUncompressedAnimation& rawData, const PerTrackCompressionParams& params, hkBool useThreeComponentQuaternions ); /// Swap the endianness in the data buffer as appropriate void handleEndian(); }; #endif // HKANIMATION_ANIMATION_DELTACOMPRESSED_HKDELTACOMPRESSEDANIMATION_XML_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
15b1e63507000a246c17794b8c07d8a181474745
9812ee7f25db3c6a4f7d6ee3a54b0aea6f5a4439
/Source/FinqlFrontierII/FinqlFrontierIIHUD.h
2d77df2dac32bd36a65d27e8be9db9f98041a52a
[]
no_license
Frogmor/FinalFrontier_Online
7c8b810799f3510037f32a336c0c55388102d9f0
2f37acbc51b1bdd3fdb62dc281d2f1d48614ed5a
refs/heads/master
2020-03-20T19:48:27.048600
2018-08-06T21:26:52
2018-08-06T21:26:52
137,654,848
0
0
null
null
null
null
UTF-8
C++
false
false
403
h
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #pragma once #include "GameFramework/HUD.h" #include "FinqlFrontierIIHUD.generated.h" UCLASS() class AFinqlFrontierIIHUD : public AHUD { GENERATED_BODY() public: AFinqlFrontierIIHUD(); /** Primary draw call for the HUD */ virtual void DrawHUD() override; private: /** Crosshair asset pointer */ class UTexture2D* CrosshairTex; };
39c24951c126d2833ccfae470bfde62c1ec0e420
72bb6deb4a8657fc494777847e356c328fe8550d
/try_patch.cpp
681b783da80dd227381167dd2f9cfe522e6623a1
[]
no_license
rising-turtle/study
daafeac486e274af47268e9c7d66feacd3476a44
76b414d0a47692f997539b34b356c34a3528f34d
refs/heads/master
2021-12-09T07:23:41.800642
2021-12-02T19:34:44
2021-12-02T19:34:44
90,572,871
2
0
null
null
null
null
UTF-8
C++
false
false
837
cpp
#include <iostream> #include <cmath> #include <vector> using namespace std; const static int HALF_PATCH_SIZE = 16; // 32 int main() { const double hp2 = HALF_PATCH_SIZE * HALF_PATCH_SIZE; int v, v0, vmax = std::floor(HALF_PATCH_SIZE * sqrt(2.f)/2 + 1); int vmin = std::ceil(HALF_PATCH_SIZE * sqrt(2.f)/2); cout <<"vmax = "<<vmax <<" vmin = "<<vmin << endl; vector<int> umax(HALF_PATCH_SIZE + 1); for(v = 0; v <= vmax; ++v) { umax[v] = round(sqrt(hp2 - v*v)); cout <<umax[v]<<" "; } cout << endl; for (v = HALF_PATCH_SIZE, v0 = 0; v >= vmin; --v) { while(umax[v0] == umax[v0+1]) ++v0; umax[v] = v0; cout <<" v = "<<v<<" umax[v] = "<<umax[v] <<" v0 = "<<v0<<endl; ++v0; } for(v = 0; v< umax.size(); ++v) { cout << umax[v]<<" "; } cout<<endl; return 0; }
a04e913ad346624fe7b6df08f818839d89427494
faf940641a408c06f0816264b89e1c21e0cc5f25
/Legendy.Source/ClientSource/Tools/Mysql2Proto/Mysql2Proto/Mysql2Proto.h
2b02881d5b327c126b9c7828a752a875bba02264
[]
no_license
nkuprens27/LegendySF-V2
90c49a0c3670eab5f3698385ec7c9f772d51988e
7f9205448fd76bde7bff7b7aac568e795659b0be
refs/heads/main
2023-07-18T03:57:57.258546
2021-09-08T20:59:37
2021-09-08T20:59:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,810
h
#pragma once #define _WINSOCKAPI_ #define _USE_32BIT_TIME_T // #include <cstdlib> #include <cstdio> #include <ctime> #include <iostream> #include <string> #include <set> #include <map> #include <list> #include "lzo.h" #pragma comment(lib, "lzo.lib") #include "Singleton.h" #include "../../../Client/GameLib/StdAfx.h" #include "../../../Client/GameLib/ItemData.h" #include "../../../Client/UserInterface/StdAfx.h" #include "../../../Client/UserInterface/PythonNonPlayer.h" inline bool operator<(const CItemData::TItemTable& lhs, const CItemData::TItemTable& rhs) { return lhs.dwVnum < rhs.dwVnum; } #include "MysqlWrapper.h" #include "utils.h" #define VERIFY_IFIELD(x,y) if (data[x]!=NULL && data[x][0]!='\0') str_to_number(y, data[x]); #define VERIFY_SFIELD(x,y) if (data[x]!=NULL && data[x][0]!='\0') strncpy_s(y, sizeof(y), data[x], _TRUNCATE); #define ENABLE_AUTODETECT_VNUMRANGE #define ENABLE_LIMIT_TYPE_CHECK_FIX #define ENABLE_ADDONTYPE_AUTODETECT namespace MProto { enum MProtoT { vnum, name, locale_name, type, rank, battle_type, level, size, ai_flag, setRaceFlag, setImmuneFlag, on_click, empire, drop_item, resurrection_vnum, folder, st, dx, ht, iq, damage_min, damage_max, max_hp, regen_cycle, regen_percent, exp, gold_min, gold_max, def, attack_speed, move_speed, aggressive_hp_pct, aggressive_sight, attack_range, polymorph_item, enchant_curse, enchant_slow, enchant_poison, enchant_stun, enchant_critical, enchant_penetrate, resist_sword, resist_twohand, resist_dagger, resist_bell, resist_fan, resist_bow, resist_fire, resist_elect, resist_magic, resist_wind, resist_poison, dam_multiply, summon, drain_sp, mob_color, skill_vnum0, skill_level0, skill_vnum1, skill_level1, skill_vnum2, skill_level2, skill_vnum3, skill_level3, skill_vnum4, skill_level4, sp_berserk, sp_stoneskin, sp_godspeed, sp_deathblow, sp_revive }; }; namespace IProto { enum IProtoT { vnum, type, subtype, name, locale_name, gold, shop_buy_price, weight, size, flag, wearflag, antiflag, immuneflag, refined_vnum, refine_set, magic_pct, specular, socket_pct, addon_type, limittype0, limitvalue0, limittype1, limitvalue1, applytype0, applyvalue0, applytype1, applyvalue1, applytype2, applyvalue2, value0, value1, value2, value3, value4, value5 #if !defined(ENABLE_AUTODETECT_VNUMRANGE) , vnum_range #endif }; } #include <fstream> inline std::string GetFileContent(const std::string& path) { std::ifstream file(path); std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); return content; } inline bool FileExists(const std::string& name) { FILE *fp; fopen_s(&fp, name.c_str(), "r"); if (fp) { fclose(fp); return true; } else { return false; } } #include "rapidjson/document.h" #define NL "\n" #include "OptionParser/OptionParser.h"
43c6caff813f1121722d11b42e8da807641eadfc
52ca17dca8c628bbabb0f04504332c8fdac8e7ea
/boost/mpl/aux_/pop_back_impl.hpp
3e0844a7278b5ffdf0d0037b6dc1541b8f32ab30
[]
no_license
qinzuoyan/thirdparty
f610d43fe57133c832579e65ca46e71f1454f5c4
bba9e68347ad0dbffb6fa350948672babc0fcb50
refs/heads/master
2021-01-16T17:47:57.121882
2015-04-21T06:59:19
2015-04-21T06:59:19
33,612,579
0
0
null
2015-04-08T14:39:51
2015-04-08T14:39:51
null
UTF-8
C++
false
false
68
hpp
#include "thirdparty/boost_1_58_0/boost/mpl/aux_/pop_back_impl.hpp"
68494434f11d289dfc8a09457442f2043dcc2a7b
67c28578df1f3deb300908fed1615744d73dcbe3
/CallbacksCompare/java_style_callback.h
193c0615a1810f3263b3100ddabdcf2f6884b0e3
[]
no_license
niosus/small_test_projects
a5131387c07a6e36ebe43e2a494b50c5ded83552
513b628afb9ee0041c91ee2e93be1789985b436a
refs/heads/master
2021-01-22T02:34:31.492069
2014-08-18T13:47:57
2014-08-18T13:47:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
427
h
#ifndef JAVA_STYLE_CALLBACK #define JAVA_STYLE_CALLBACK #include "event_handler_abstract.h" class JavaStyleCallbackTester { public: JavaStyleCallbackTester(EventHandlerAbstract* eventHandler) { _x = 5; _eventHandler = eventHandler; } double sum(const double &x); inline double x() { return _x; } private: EventHandlerAbstract* _eventHandler; double _x; }; #endif
d9c9b532c5c4e621ec41172378862bd78af09399
4d455581770eb1779272ed331796ddd4c404574a
/kartkówki/1 KARTKOWKA/5 listopada 2014 zad 2/main.cpp
c302a2fcb61ff0654f4d735457b24bbc5b6ac2a4
[]
no_license
jakubowiczish/WDI
07c87252bedaf74d0bbdf88bff989b1138259576
577873d07bcabc0e505b1202db7f315e41f6a63f
refs/heads/master
2021-05-16T00:46:31.826131
2019-01-15T19:45:23
2019-01-15T19:45:23
106,967,499
3
0
null
null
null
null
UTF-8
C++
false
false
1,861
cpp
#include <iostream> using namespace std; int main(int argc, char** argv) { int T[5]; for(int i = 0; i < 5; i++){ T[i] = 0; } int wKtoreMiejsceTablicyTerazWpisac = 0; int liczbaWpisanych = 0; int licz = 0; while(true){ if(liczbaWpisanych >=5) for(int j = 0; j < 4; j++){ T[j] = T[j+1]; } int input = 0; cin >> input; liczbaWpisanych++; if(input==0){ { int sum = T[0]+T[1]+T[2]+T[3]; if(sum/4 == T[4]){ cout << "Ta Liczba do wypisania.[4]: " << T[4] << endl; } } { int sum = T[0]+T[1]+T[2]+T[4]; if(sum/4 == T[3]){ cout << "Ta Liczba do wypisania.[3]: " << T[3] << endl; } } { int sum = T[0]+T[1]+T[3]+T[4]; if(sum/4 == T[2]){ cout << "Ta Liczba do wypisania.[2]: " << T[2] << endl; } } break; } T[wKtoreMiejsceTablicyTerazWpisac] = input; if(liczbaWpisanych==5){ int sum = T[1]+T[2]+T[3]+T[4]; if(sum/4 == T[0]){ cout << "Ta Liczba do wypisania.[0]: " << T[0] << endl; } } if(liczbaWpisanych==5){ int sum = T[0]+T[2]+T[3]+T[4]; if(sum/4 == T[1]){ cout << "Ta Liczba do wypisania.[1]: " << T[1] << endl; } } if(liczbaWpisanych>=5){ int sum = T[0]+T[1]+T[3]+T[4]; if(sum/4 == T[2]){ cout << "Ta Liczba do wypisania.[2]: " << T[2] << endl; } } if(wKtoreMiejsceTablicyTerazWpisac<4) wKtoreMiejsceTablicyTerazWpisac++; } return 0; }
f06e9e8e12dc9789a45e2216cd3230d301070839
a06515f4697a3dbcbae4e3c05de2f8632f8d5f46
/corpus/taken_from_cppcheck_tests/stolen_939.cpp
f6d2be4a2b08229cceca666f2fa5f173d5062140
[]
no_license
pauldreik/fuzzcppcheck
12d9c11bcc182cc1f1bb4893e0925dc05fcaf711
794ba352af45971ff1f76d665b52adeb42dcab5f
refs/heads/master
2020-05-01T01:55:04.280076
2019-03-22T21:05:28
2019-03-22T21:05:28
177,206,313
0
0
null
null
null
null
UTF-8
C++
false
false
195
cpp
class A { public: char *s; A & operator=(const A &a); }; A & A::operator=(const A &a) { if(true!=(&a==this)) { free(s); s = strdup(a.s); } return *this; };
4fe9947e6ed3fbd1a7de6054111e61191bb790a2
257097a851f4f7df93ff0c82241960cbfc6ff8d6
/graph-theory/shortest-path-mazes/main.cpp
cee81371a85083bc52cfedac537c6e4538bbafe9
[ "MIT" ]
permissive
ramongonze/ufmg-practical-assignments
0686b503e0f15a4e0285459735a2ee09db6a285d
d85821e330a0f089a7601168bbbf8b4aef174f27
refs/heads/master
2021-01-05T08:27:39.434208
2020-09-30T15:17:30
2020-09-30T15:17:30
240,952,655
2
0
null
null
null
null
UTF-8
C++
false
false
930
cpp
#ifndef _ALGS_ #include "algs.hpp" #endif #include <ctime> int main(int argc, char *argv[]){ srand(time(NULL)); // Used in function generateMaze() int n, m; // Maze size int d; clock_t begin, end; Graph maze; if(argc < 3){ printf("There are few arguments!\n"); return -1; } n = atoi(argv[1]); m = atoi(argv[2]); maze = generateMaze(n,m); // Uncomment the line above to generate a file which can print // the generated maze using the lib matplotlib from python 3. //printMaze(maze,n,m); begin = clock(); d = dijkstra(maze,0,n*m-1); end = clock(); printf("---- Dijkstra ----\n"); printf("Execution time: %.8f\n", (float)(end - begin)/ CLOCKS_PER_SEC); printf("Shortest path: %d\n\n", d); begin = clock(); d = aStar(maze,0,n*m-1); end = clock(); printf("---- A* ----\n"); printf("Execution time: %.8f\n", (float)(end - begin)/ CLOCKS_PER_SEC); printf("Shortest path: %d\n", d); return 0; }
c2dcc7a8959897470c596ee7763ebb99a5c8b4dc
3fb9be84d4d09a89f33c160a4e440024325f04f4
/projects/Core/MKL/src/Utils.cpp
64cfe5946de74027667ecc72a43720b3890063a5
[]
no_license
sadads1337/fft
dbe4fa2bc6fe246baefa0030de7b99d680fc1ff0
19668db1ec305d59b8cf78947e10bd439fc76ac6
refs/heads/master
2022-10-20T06:51:37.058964
2020-06-11T18:56:46
2020-06-15T05:20:33
207,852,275
0
0
null
null
null
null
UTF-8
C++
false
false
2,825
cpp
#include <Core/MKL/Utils.h> #include <Core/MakeWithCapacity.h> #include <mkl.h> namespace fft { ComplexContainer fft_complex(ComplexContainer& in) { ComplexContainer out(in.size()); DFTI_DESCRIPTOR_HANDLE descriptor; utils::save_mkl_call(DftiCreateDescriptor, &descriptor, DFTI_SINGLE, DFTI_COMPLEX, 1, in.size()); utils::save_mkl_call(DftiSetValue, descriptor, DFTI_PLACEMENT, DFTI_NOT_INPLACE); utils::save_mkl_call(DftiCommitDescriptor, descriptor); utils::save_mkl_call(DftiComputeForward, descriptor, in.data(), out.data()); utils::save_mkl_call(DftiFreeDescriptor, &descriptor); return out; } ComplexContainer fft_real(const RealContainer& in_real) { auto in = utils::make_with_capacity<ComplexContainer>(in_real.size()); //! \todo: потенциально тяжелая операцция копирования, fixme! std::copy(in_real.begin(), in_real.end(), std::back_inserter(in)); return fft_complex(in); } RealContainer ifft_real(ComplexContainer& in) { ComplexContainer out(in.size()); DFTI_DESCRIPTOR_HANDLE descriptor; utils::save_mkl_call(DftiCreateDescriptor, &descriptor, DFTI_SINGLE, DFTI_COMPLEX, 1, in.size()); utils::save_mkl_call(DftiSetValue, descriptor, DFTI_PLACEMENT, DFTI_NOT_INPLACE); utils::save_mkl_call(DftiSetValue, descriptor, DFTI_BACKWARD_SCALE, 1.0f / in.size()); utils::save_mkl_call(DftiCommitDescriptor, descriptor); utils::save_mkl_call(DftiComputeBackward, descriptor, in.data(), out.data()); utils::save_mkl_call(DftiFreeDescriptor, &descriptor); auto result = utils::make_with_capacity<RealContainer>(out.size()); for (const auto& value : out) { result.emplace_back(value.real()); } return result; } RealContainer conv_real(const RealContainer& x, const RealContainer& y) { RealContainer z(x.size() + y.size() - 1); VSLConvTaskPtr task; utils::save_mkl_call(vsldConvNewTask1D, &task, VSL_CONV_MODE_AUTO, static_cast<int>(x.size()), static_cast<int>(y.size()), static_cast<int>(z.size())); utils::save_mkl_call(vsldConvExec1D, task, x.data(), 1, y.data(), 1, z.data(), 1); utils::save_mkl_call(vslConvDeleteTask, &task); return z; } RealContainer corr_real(const RealContainer& x, const RealContainer& y) { RealContainer z(x.size() + y.size() - 1); VSLCorrTaskPtr task; utils::save_mkl_call(vsldCorrNewTask1D, &task, VSL_CORR_MODE_AUTO, static_cast<int>(x.size()), static_cast<int>(y.size()), static_cast<int>(z.size())); utils::save_mkl_call(vsldCorrExec1D, task, x.data(), 1, y.data(), 1, z.data(), 1); return z; } } // namespace fft
5b48145358f8d7b3c0117aba411b5aae64b6c6b7
adcf9897df85d1217eb27c4d85c95eea8a2e85f2
/Lab1Client/messagelist.cpp
2e59897632859374ba04d2b4c1048d602917e047
[]
no_license
JucovAllexandr/PAD_Lab1
89621863e8054d754444af36a7fac0c618715c6e
7f58eae8b75d563ccf3e30d9cb0f68ccfa49d6d3
refs/heads/master
2020-07-24T23:25:11.297449
2019-10-10T21:09:51
2019-10-10T21:09:51
208,082,319
0
0
null
null
null
null
UTF-8
C++
false
false
367
cpp
#include "messagelist.h" QList<Message> MessageList::deserializeXML(QDomDocument &doc) { QList<Message> retList; QDomNodeList nodeList = doc.elementsByTagName("Message"); retList.reserve(nodeList.size()); for(int i = 0; i < nodeList.size(); ++i){ retList.push_back(Message(nodeList.at(i).toElement().text())); } return retList; }
6c0dc023a8b6c35e7bdde60228634f561bdcc9b1
b73eec3a26bdcffb6a19dec6b8b048079befe04c
/3rdparty/meshlab-master/src/meshlabplugins/filter_isoparametrization/dual_coord_optimization.h
27ba18f69b4f7591d4698a80a25ccdf53436805a
[ "GPL-1.0-or-later", "GPL-3.0-only", "MIT" ]
permissive
HoEmpire/slambook2
c876494174e7f636bdf5b5743fab7d9918c52898
96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4
refs/heads/master
2020-07-24T02:35:39.488466
2019-11-25T03:08:17
2019-11-25T03:08:17
207,775,582
0
0
MIT
2019-09-11T09:35:56
2019-09-11T09:35:56
null
UTF-8
C++
false
false
23,723
h
#ifndef DUAL_OPTIMIZER #define DUAL_OPTIMIZER #include <wrap/callback.h> #ifndef IMPLICIT #include "texcoord_optimization.h" #else #include <poisson_solver.h> #endif template <class MeshType> class BaryOptimizatorDual { typedef typename MeshType::VertexType VertexType; typedef typename MeshType::FaceType FaceType; typedef typename MeshType::CoordType CoordType; typedef typename MeshType::ScalarType ScalarType; #ifndef IMPLICIT typedef typename vcg::tri::AreaPreservingTexCoordOptimization<MeshType> OptType; typedef typename vcg::tri::MeanValueTexCoordOptimization<MeshType> OptType1; #else typedef typename PoissonSolver<MeshType> OptType; /*typedef typename PoissonSolver<MeshType> OptType1;*/ #endif //typedef typename vcg::tri::MeanValueTexCoordOptimization<MeshType> OptType; EnergyType EType; public: struct param_domain{ MeshType *domain; std::vector<FaceType*> ordered_faces; }; //OptType *optimizer; ///set of star meshes to optimize barycentryc coords locally std::vector<param_domain> star_meshes; std::vector<param_domain> diamond_meshes; std::vector<param_domain> face_meshes; ///structures for the optimization std::vector<MeshType*> HRES_meshes; std::vector<std::vector<VertexType*> > Ord_HVert; ///hight resolution mesh and domain mesh MeshType *domain; MeshType *h_res_mesh; ///initialize star parametrization void InitStarEquilateral()//const ScalarType &average_area=1) { ///for each vertex int index=0; for (unsigned int i=0;i<domain->vert.size();i++) { if (!(domain->vert[i].IsD())) { std::vector<VertexType*> starCenter; starCenter.push_back(&domain->vert[i]); star_meshes[index].domain=new MeshType(); ///create star CreateMeshVertexStar(starCenter,star_meshes[index].ordered_faces,*star_meshes[index].domain); ///and parametrize it ParametrizeStarEquilateral<MeshType>(*star_meshes[index].domain,1.0); index++; } } } void InitDiamondEquilateral(const ScalarType &edge_len=1.0) { ///for each vertex int index=0; for (unsigned int i=0;i<domain->face.size();i++) { if (!(domain->face[i].IsD())) { FaceType *f0=&domain->face[i]; //for each edge for (int j=0;j<3;j++) { FaceType * f1=f0->FFp(j); if (f1<f0) { ///add to domain map ///end domain mapping int num0=j; int num1=f0->FFi(j); ///copy the mesh std::vector<FaceType*> faces; faces.push_back(f0); faces.push_back(f1); diamond_meshes[index].domain=new MeshType(); ///create a copy of the mesh std::vector<VertexType*> orderedVertex; CopyMeshFromFaces<MeshType>(faces,orderedVertex,*diamond_meshes[index].domain); UpdateTopologies<MeshType>(diamond_meshes[index].domain); ///set other components diamond_meshes[index].ordered_faces.resize(2); diamond_meshes[index].ordered_faces[0]=f0; diamond_meshes[index].ordered_faces[1]=f1; ///parametrize locally ParametrizeDiamondEquilateral<MeshType>(*diamond_meshes[index].domain,num0,num1,edge_len); index++; } } } } } void InitFaceEquilateral(const ScalarType &edge_len=1) { ///for each vertex int index=0; for (unsigned int i=0;i<domain->face.size();i++) { if (!(domain->face[i].IsD())) { FaceType *f0=&domain->face[i]; std::vector<FaceType*> faces; faces.push_back(f0); ///create the mesh face_meshes[index].domain=new MeshType(); std::vector<VertexType*> orderedVertex; CopyMeshFromFaces<MeshType>(faces,orderedVertex,*face_meshes[index].domain); assert(face_meshes[index].domain->vn==3); assert(face_meshes[index].domain->fn==1); ///initialize auxiliary structures face_meshes[index].ordered_faces.resize(1); face_meshes[index].ordered_faces[0]=f0; ///parametrize it ParametrizeFaceEquilateral<MeshType>(*face_meshes[index].domain,edge_len); ///add to search structures /*faceMap.insert(std::pair<FaceType*,param_domain*>(f0,&face_meshes[index]));*/ index++; } } } ///given a point and a face return the half-star in witch it falls int getVertexStar(const CoordType &point,FaceType *f) { CoordType edge0=(f->P(0)+f->P(1))/2.0; CoordType edge1=(f->P(1)+f->P(2))/2.0; CoordType edge2=(f->P(2)+f->P(0))/2.0; CoordType Center=(f->P(0)+f->P(1)+f->P(2))/3.0; CoordType vect0=edge0-point; CoordType vect1=Center-point; CoordType vect2=edge2-point; CoordType Norm=f->N(); ScalarType in0=(vect0^vect1)*Norm; ScalarType in1=(vect1^vect2)*Norm; if ((in0>=0)&&(in1>=0)) return 0; vect0=edge0-point; vect1=Center-point; vect2=edge1-point; in0=(vect1^vect0)*Norm; in1=(vect2^vect1)*Norm; if ((in0>=0)&&(in1>=0)) return 1; vect0=edge1-point; vect1=Center-point; vect2=edge2-point; in0=(vect1^vect0)*Norm; in1=(vect2^vect1)*Norm; assert((in0>=0)&&(in1>=0)); return 2; } ///given a point and a face return the half-diamond edge index in witch it falls int getEdgeDiamond(const CoordType &point,FaceType *f) { CoordType Center=(f->P(0)+f->P(1)+f->P(2))/3.0; CoordType vect0=f->P(1)-point; CoordType vect1=Center-point; CoordType vect2=f->P(0)-point; CoordType Norm=f->N(); ScalarType in0=(vect0^vect1)*Norm; ScalarType in1=(vect1^vect2)*Norm; if ((in0>=0)&&(in1>=0)) return 0; vect0=f->P(2)-point; vect1=Center-point; vect2=f->P(1)-point; in0=(vect0^vect1)*Norm; in1=(vect1^vect2)*Norm; if ((in0>=0)&&(in1>=0)) return 1; vect0=f->P(0)-point; vect1=Center-point; vect2=f->P(2)-point; in0=(vect0^vect1)*Norm; in1=(vect1^vect2)*Norm; assert((in0>=0)&&(in1>=0)); return 2; } ///initialize Star Submeshes void InitStarSubdivision() { int index=0; HRES_meshes.clear(); Ord_HVert.clear(); ///initialilze vector of meshes HRES_meshes.resize(star_meshes.size()); Ord_HVert.resize(star_meshes.size()); /*HVert.resize(star_meshes.size());*/ for (unsigned int i=0;i<HRES_meshes.size();i++) HRES_meshes[i]=new MeshType(); ///for each vertex of base domain for (unsigned int i=0;i<domain->vert.size();i++) { VertexType *center=&domain->vert[i]; if (!center->IsD()) { ///copy current parametrization of star for (unsigned int k=0;k<star_meshes[index].ordered_faces.size();k++) { FaceType *param=&star_meshes[index].domain->face[k]; FaceType *original=star_meshes[index].ordered_faces[k]; for (int v=0;v<3;v++) original->V(v)->T().P()=param->V(v)->T().P(); } ///get h res vertex on faces composing the star std::vector<VertexType*> Hres,inDomain; getHresVertex<FaceType>(star_meshes[index].ordered_faces,Hres); ///find out the vertices falling in the substar /*HVert[index].reserve(Hres.size()/2);*/ for (unsigned int k=0;k<Hres.size();k++) { VertexType* chosen; VertexType* test=Hres[k]; CoordType proj=Warp(test); FaceType * father=test->father; CoordType bary=test->Bary; ///get index of half-star int index=getVertexStar(proj,father); chosen=father->V(index); ///if is part of current half star if (chosen==center) { inDomain.push_back(test); ///parametrize it InterpolateUV<MeshType>(father,bary,test->T().U(),test->T().V()); } } ///create Hres mesh already parametrized std::vector<FaceType*> OrderedFaces; CopyMeshFromVertices<MeshType>(inDomain,Ord_HVert[index],OrderedFaces,*HRES_meshes[index]); index++; } } } ///initialize Star Submeshes void InitDiamondSubdivision() { int index=0; HRES_meshes.clear(); Ord_HVert.clear(); ///initialilze vector of meshes HRES_meshes.resize(diamond_meshes.size()); Ord_HVert.resize(diamond_meshes.size()); /*HVert.resize(star_meshes.size());*/ for (unsigned int i=0;i<HRES_meshes.size();i++) HRES_meshes[i]=new MeshType(); ///for each edge of base domain for (unsigned int i=0;i<domain->face.size();i++) { FaceType *f0=&domain->face[i]; if (f0->IsD()) break; //for each edge for (int eNum=0;eNum<3;eNum++) { FaceType * f1=f0->FFp(eNum); if (f1<f0) { ///copy current parametrization of diamond for (unsigned int k=0;k<diamond_meshes[index].ordered_faces.size();k++) { FaceType *param=&diamond_meshes[index].domain->face[k]; FaceType *original=diamond_meshes[index].ordered_faces[k]; for (int v=0;v<3;v++) original->V(v)->T().P()=param->V(v)->T().P(); } ///get h res vertex on faces composing the diamond std::vector<VertexType*> Hres,inDomain; getHresVertex<FaceType>(diamond_meshes[index].ordered_faces,Hres); ///find out the vertices falling in the half-diamond /*HVert[index].reserve(Hres.size()/2);*/ for (unsigned int k=0;k<Hres.size();k++) { //VertexType* chosen; VertexType* test=Hres[k]; CoordType proj=Warp(test); FaceType * father=test->father; CoordType bary=test->Bary; ///get index of half-star int index=getEdgeDiamond(proj,father); ///if is part of current half star if (index==eNum) { inDomain.push_back(test); ///parametrize it InterpolateUV<MeshType>(father,bary,test->T().U(),test->T().V()); } } ///create Hres mesh already parametrized std::vector<FaceType*> OrderedFaces; CopyMeshFromVertices<MeshType>(inDomain,Ord_HVert[index],OrderedFaces,*HRES_meshes[index]); index++; } } } } ///initialize Star Submeshes void InitFaceSubdivision() { int index=0; HRES_meshes.clear(); Ord_HVert.clear(); ///initialilze vector of meshes HRES_meshes.resize(face_meshes.size()); Ord_HVert.resize(face_meshes.size()); for (unsigned int i=0;i<HRES_meshes.size();i++) HRES_meshes[i]=new MeshType(); ///for each face of base domain for (unsigned int i=0;i<domain->face.size();i++) { FaceType *f0=&domain->face[i]; if (f0->IsD()) break; ///copy current parametrization of face FaceType *param=&face_meshes[index].domain->face[0]; FaceType *original=face_meshes[index].ordered_faces[0]; assert(face_meshes[index].domain->vn==3); assert(face_meshes[index].domain->fn==1); assert(face_meshes[index].ordered_faces.size()==1); assert(original==f0); for (int v=0;v<3;v++) original->V(v)->T().P()=param->V(v)->T().P(); ///get h res vertex on faces composing the diamond std::vector<VertexType*> inDomain; getHresVertex<FaceType>(face_meshes[index].ordered_faces,inDomain); ///transform in UV for (unsigned int k=0;k<inDomain.size();k++) { VertexType* test=inDomain[k]; FaceType * father=test->father; assert(father==f0); CoordType bary=test->Bary; InterpolateUV<MeshType>(father,bary,test->T().U(),test->T().V()); } ///create Hres mesh already parametrized std::vector<FaceType*> OrderedFaces; CopyMeshFromVertices<MeshType>(inDomain,Ord_HVert[index],OrderedFaces,*HRES_meshes[index]); index++; } } void MinimizeStep(const int &phaseNum) { //Ord_HVert[index] for (unsigned int i=0;i<HRES_meshes.size();i++) { MeshType *currMesh=HRES_meshes[i]; if (currMesh->fn>0) { UpdateTopologies<MeshType>(currMesh); ///on star int numDom=1; switch (phaseNum) { case 0:numDom=6;break;//star case 1:numDom=2;break;//diam case 2:numDom=1;break;//face } ///save previous values #ifndef IMPLICIT InitDampRestUV(*currMesh); bool b=UnFold<MeshType>(*currMesh,numDom); bool isOK=testParamCoords<MeshType>(*currMesh); if ((!b)||(!isOK)) RestoreRestUV<MeshType>(*currMesh); ///save previous values InitDampRestUV(*currMesh); ///NEW SETTING SPEED ScalarType edge_esteem=GetSmallestUVHeight(*currMesh); ScalarType speed0=edge_esteem*0.2; ScalarType conv=edge_esteem*0.01; if (accuracy>1) conv*=1.0/(ScalarType)((accuracy-1)*10.0); #endif #ifndef IMPLICIT if (EType==EN_EXTMips) { OptType opt(*currMesh); opt.TargetCurrentGeometry(); opt.SetBorderAsFixed(); opt.SetSpeed(speed0); opt.IterateUntilConvergence(conv); } else if (EType==EN_MeanVal) { OptType1 opt(*currMesh); opt.TargetCurrentGeometry(); opt.SetBorderAsFixed(); opt.SetSpeed(speed0); opt.IterateUntilConvergence(conv); } #else OptType opt(*currMesh); opt.SetBorderAsFixed(); opt.SolvePoisson(); #endif //opt.IterateUntilConvergence(); ///test for uv errors bool IsOK=true; for (unsigned int j=0;j<currMesh->vert.size();j++) { VertexType *ParamVert=&currMesh->vert[j]; ScalarType u=ParamVert->T().U(); ScalarType v=ParamVert->T().V(); if ((!((u<=1.001)&&(u>=-1.001)))|| (!(v<=1.001)&&(v>=-1.001))) { IsOK=false; for (unsigned int k=0;k<currMesh->vert.size();k++) currMesh->vert[k].T().P()=currMesh->vert[k].RestUV; break; } } //reassing fathers and bary coordinates for (unsigned int j=0;j<currMesh->vert.size();j++) { VertexType *ParamVert=&currMesh->vert[j]; VertexType *OrigVert=Ord_HVert[i][j]; ScalarType u=ParamVert->T().U(); ScalarType v=ParamVert->T().V(); ///then get face falling into and estimate (alpha,beta,gamma) CoordType bary; BaseFace* chosen; param_domain *currDom; switch (phaseNum) { case 0:currDom=&star_meshes[i];break;//star case 1:currDom=&diamond_meshes[i];break;//diam case 2:currDom=&face_meshes[i];break;//face } /*assert(currDom->domain->vn==3); assert(currDom->domain->fn==1);*/ bool inside=GetBaryFaceFromUV(*currDom->domain,u,v,currDom->ordered_faces,bary,chosen); if (!inside) { /*#ifndef _MESHLAB*/ printf("\n OUTSIDE %f,%f \n",u,v); /*#endif*/ vcg::Point2<ScalarType> UV=vcg::Point2<ScalarType>(u,v); ForceInParam<MeshType>(UV,*currDom->domain); u=UV.X(); v=UV.Y(); inside=GetBaryFaceFromUV(*currDom->domain,u,v,currDom->ordered_faces,bary,chosen); //assert(0); } assert(inside); //OrigVert->father=chosen; //OrigVert->Bary=bary; AssingFather(*OrigVert,chosen,bary,*domain); } } ///delete current mesh delete(HRES_meshes[i]); } ///clear father and bary for (unsigned int i=0;i<domain->face.size();i++) domain->face[i].vertices_bary.clear(); ///set face-vertex link for (unsigned int i=0;i<h_res_mesh->vert.size();i++) { BaseVertex *v=&h_res_mesh->vert[i]; if (!v->IsD()) { BaseFace *f=v->father; CoordType bary=v->Bary; f->vertices_bary.push_back(std::pair<VertexType*,CoordType>(v,bary)); } } } int accuracy; vcg::CallBackPos *cb; int step; public: void Init(MeshType &_domain, MeshType &_h_res_mesh, vcg::CallBackPos *_cb, int _accuracy=1, EnergyType _EType=EN_EXTMips) { EType=_EType; step=0; cb=_cb; accuracy=_accuracy; vcg::tri::UpdateNormal<MeshType>::PerFaceNormalized(_domain); domain=&_domain; h_res_mesh=&_h_res_mesh; ///initialize STARS star_meshes.resize(domain->vn); InitStarEquilateral(); /*InitStarSubdivision();*/ ///initialize DIAMONDS int num_edges=0; for (unsigned int i=0;i<domain->face.size();i++) { if (!(domain->face[i].IsD())) { FaceType *f0=&domain->face[i]; //for each edge for (int j=0;j<3;j++) { FaceType * f1=f0->FFp(j); if (f1<f0) num_edges++; } } } diamond_meshes.resize(num_edges); InitDiamondEquilateral(); ///initialize FACES face_meshes.resize(domain->fn); InitFaceEquilateral(); ///init minimizer for (unsigned int i=0;i<h_res_mesh->vert.size();i++) h_res_mesh->vert[i].P()=h_res_mesh->vert[i].RPos; //InitDampRestUV(*h_res_mesh); } void PrintAttributes() { int done=step; int total=6; ScalarType ratio=(ScalarType)done/total; int percent=(int)(ratio*(ScalarType)100); ScalarType distArea=ApproxAreaDistortion<BaseMesh>(*h_res_mesh,domain->fn); ScalarType distAngle=ApproxAngleDistortion<BaseMesh>(*h_res_mesh); char ret[200]; sprintf(ret," PERFORM GLOBAL OPTIMIZATION Area distorsion:%4f ; ANGLE distorsion:%4f ",distArea,distAngle); (*cb)(percent,ret); } void Optimize(ScalarType gap=0.5,int max_step=10) { int k=0; ScalarType distArea=ApproxAreaDistortion<BaseMesh>(*h_res_mesh,domain->fn); ScalarType distAngle=ApproxAngleDistortion<BaseMesh>(*h_res_mesh); ScalarType distAggregate0=geomAverage<ScalarType>(distArea+1.0,distAngle+1.0,3,1)-1; bool ContinueOpt=true; PatchesOptimizer<BaseMesh> DomOpt(*domain,*h_res_mesh); step++; #ifndef IMPLICIT DomOpt.OptimizePatches(); PrintAttributes(); #endif while (ContinueOpt) { ///domain Optimization k++; InitStarSubdivision(); MinimizeStep(0); InitDiamondSubdivision(); MinimizeStep(1); InitFaceSubdivision(); MinimizeStep(2); step++; PrintAttributes(); distArea=ApproxAreaDistortion<BaseMesh>(*h_res_mesh,domain->fn); distAngle=ApproxAngleDistortion<BaseMesh>(*h_res_mesh); ScalarType distAggregate1=geomAverage<ScalarType>(distArea+1.0,distAngle+1.0,3,1)-1; ScalarType NewGap=((distAggregate0-distAggregate1)*ScalarType(100.0))/distAggregate0; if ((NewGap<gap)||(k>max_step)) ContinueOpt=false; distAggregate0=distAggregate1; } } }; #endif
4471dbd46047baa5c371e6ddb2358c42a2c8b280
09957d0014fb498a3349382fd965b58d232cd089
/glbase/geometries.hpp
ae0ea43ea1f8938d5158d5e29ad05585329f3868
[]
no_license
EeveeHuntress/AirShower3D
e62ef79c7a58ab28ecd5271b9b18afc48b1b2c57
185d732ea9d5cc1188468af9e2baf90b0e370ace
refs/heads/master
2023-01-20T17:25:13.124832
2020-11-30T17:32:10
2020-11-30T17:32:10
237,242,169
1
0
null
null
null
null
UTF-8
C++
false
false
2,911
hpp
/* * Copyright (C) 2013 * Computer Graphics Group, University of Siegen * Written by Martin Lambers <[email protected]> * All rights reserved. */ #include <vector> #include <glm/glm.hpp> namespace glm { typedef glm::detail::tvec3<unsigned char, glm::highp> ubvec3; } #ifndef GEOMETRIES_H #define GEOMETRIES_H /* These functions return basic geometries, scaled to fill [-1,+1]^3. * The arrays are cleared and geometry data is written to them. This * data is suitable for rendering with glDrawElements() in GL_TRIANGLES mode. * * These are replacements for glutSolid*()/glutWired*() etc. */ void geom_quad( std::vector<glm::vec3>& positions, std::vector<glm::vec3>& normals, std::vector<glm::vec2>& texcoords, std::vector<unsigned int>& indices); void geom_cube( std::vector<glm::vec3>& positions, std::vector<glm::vec3>& normals, std::vector<glm::vec2>& texcoords, std::vector<unsigned int>& indices); void geom_disk( std::vector<glm::vec3>& positions, std::vector<glm::vec3>& normals, std::vector<glm::vec2>& texcoords, std::vector<unsigned int>& indices, float inner_radius = 0.2f, int slices = 40); void geom_sphere( std::vector<glm::vec3>& positions, std::vector<glm::vec3>& normals, std::vector<glm::vec2>& texcoords, std::vector<unsigned int>& indices, int slices = 40, int stacks = 20); void geom_cylinder( std::vector<glm::vec3>& positions, std::vector<glm::vec3>& normals, std::vector<glm::vec2>& texcoords, std::vector<unsigned int>& indices, int slices = 40); void geom_cone( std::vector<glm::vec3>& positions, std::vector<glm::vec3>& normals, std::vector<glm::vec2>& texcoords, std::vector<unsigned int>& indices, int slices = 40, int stacks = 20); void geom_torus( std::vector<glm::vec3>& positions, std::vector<glm::vec3>& normals, std::vector<glm::vec2>& texcoords, std::vector<unsigned int>& indices, float inner_radius = 0.4f, int sides = 40, int rings = 40); void geom_teapot( std::vector<glm::vec3>& positions, std::vector<glm::vec3>& normals, std::vector<glm::vec2>& texcoords, std::vector<unsigned int>& indices); /* For a given geometry in GL_TRIANGLES mode with indices, create a new index list * that provides GL_TRIANGLES_ADJACENCY. This is useful for geometry shaders. * If a neighboring triangle is not found for an edge of a given triangle, the * neighbor for that edge will be set to the triangle itself, only in opposite direction. * WARNING: the current implementation is O(n²). Only use once on initialization, and * don't use with larger models. */ std::vector<unsigned int> create_adjacency(const std::vector<unsigned int>& indices); #endif
4d5b90e1510ff71c152590322fb82ac4421c918c
5bdf7235fb02cda222e87b64830cac3172455651
/Unit1.cpp
aca2509fc73bae8edc8470de487da25d71fabe08
[]
no_license
Krip4yk/Krip4yk-MP
12bb943ccf8b9592b05f23206dba6fc0841b2457
c8436a0b5b988a49865f6a7b6c06739f1bf436d4
refs/heads/master
2021-06-26T17:34:42.424821
2017-09-14T11:37:53
2017-09-14T11:37:53
103,514,066
0
0
null
null
null
null
UTF-8
C++
false
false
7,957
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit1.h" //--------------------------------------------------------------------------- #include <fstream.h> //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { /* * Project MP * Created by Krip4yk * Not copyright! Not comercial! * * Need add: * - Get from files * - Open files * - Deleting elements * - API connection * - * Done: * - Add elements * - Log * - Email/Password pairs * - Interface * - * */ } //--------------------------------------------------------------------------- void __fastcall TForm1::Edit1Change(TObject *Sender) { if (Edit1->Text.Length() != 0 && Edit2->Text.Length() != 0) { Button1->Enabled = true; } else { Button1->Enabled = false; } } //--------------------------------------------------------------------------- void __fastcall TForm1::Edit2Change(TObject *Sender) { if (Edit1->Text.Length() != 0 && Edit2->Text.Length() != 0) { Button1->Enabled = true; } else { Button1->Enabled = false; } } //--------------------------------------------------------------------------- void __fastcall TForm1::Edit3Change(TObject *Sender) { if (Edit3->Text.Length() != 0) { Button3->Enabled = true; } else { Button3->Enabled = false; } } //--------------------------------------------------------------------------- void __fastcall TForm1::Button1Clic(TObject *Sender) { for (int i = 1; i <= Edit1->Text.Length(); i++) { if (Edit1->Text[i] == ' '){ Edit1->Text = Edit1->Text.SubString(1, i-1) + Edit1->Text.SubString(i+1, Edit1->Text.Length()-i); i--; } } //---------------------------------------------- bool sobaka = false, dot = false; bool text1 = false, text2 = false, text3 = false; //---------------------------------------------- int len_text2 = 5; String *str_text2 = new String[len_text2]; str_text2[0] = "gmail"; str_text2[1] = "hotmail"; str_text2[2] = "yahoo"; str_text2[3] = "aol"; str_text2[4] = "zoho"; //---------------------------------------------- int len_text3 = 1; String *str_text3 = new String[len_text3]; str_text3[0] = "com"; //str_text3[1] = "org"; //str_text3[2] = "net"; //---------------------------------------------- int indsob = 0, inddot = 0; //---------------------------------------------- for (int i = 1; i <= Edit1->Text.Length(); i++) { if (Edit1->Text[i] == '@') { sobaka = true; indsob = i; if (i == 1) { break; } else { text1 = true; } } if (Edit1->Text[i] == '.') { dot = true; inddot = i; if (i == 0) { break; } else { if (Edit1->Text[i-1] == '@') { break; } else { text2 = true; for (int j = 0; j < len_text2; j++) { if (Edit1->Text.SubString(indsob+1, inddot-indsob-1) == str_text2[j]) { break; } if (j == len_text2-1) { text2 = false; } } } } if (i == Edit1->Text.Length()) { break; } else { text3 = true; for (int j = 0; j < len_text3; j++) { if (Edit1->Text.SubString(inddot+1, Edit1->Text.Length()-1) == str_text3[j]) { break; } else { text3 = false; } } break; } } } if (sobaka && dot && text1 && text2 && text3) { Memo1->Lines->Add(Edit1->Text); Edit1->Text = ""; Memo2->Lines->Add(Edit2->Text); Edit2->Text = ""; } else { Memo3->Lines->Add("Error 0. Incorrect mail"); if (!sobaka) { Memo3->Lines->Add(" no '@'"); } if (!dot) { Memo3->Lines->Add(" no '.'"); } if (!text1) { Memo3->Lines->Add(" no text before '@'"); } if (!text2) { Memo3->Lines->Add(" no text after '@' or incorrect mail"); Memo3->Lines->Add(" correct mails:"); for (int i = 0; i < len_text2; i++) { Memo3->Lines->Add(" " + str_text2[i]); } } if (!text3) { Memo3->Lines->Add(" no text after '.' or incorrect domain"); Memo3->Lines->Add(" correct domais:"); for (int i = 0; i < len_text3; i++) { Memo3->Lines->Add(" " + str_text3[i]); } } } } //--------------------------------------------------------------------------- void __fastcall TForm1::Button5Click(TObject *Sender) { if (Memo1->Lines->Count != 0 && Memo2->Lines->Count != 0) { for (int i = 0; i < Memo1->Lines->Count; i++) { Memo3->Lines->Add("Trying mail: " + Memo1->Lines->Strings[i] + " password: " + Memo2->Lines->Strings[i]); } } else { if (Memo1->Lines->Count == 0) { Memo3->Lines->Add("Error 1. Empty Mail's text"); } if (Memo2->Lines->Count == 0) { Memo3->Lines->Add("Error 1. Empty Password's text"); } } } //--------------------------------------------------------------------------- void __fastcall TForm1::Edit5Change(TObject *Sender) { String text = Edit5->Text; for (int i = 1; i <= text.Length(); i++){ if (!text.IsDelimiter("0123456789", i)) { Edit5->Text = text.SubString(1, i-1) + text.SubString(i+1, text.Length()-i); text = Edit5->Text; i--; Edit5->SelStart = i; } } if (text.Length() != 0) { Button8->Enabled = true; } } //--------------------------------------------------------------------------- void __fastcall TForm1::Button8Click(TObject *Sender) { if (Edit5->Text.ToInt() > 0) { if (Memo1->Lines->Count != 0) { Memo1->Lines->Delete(Edit5->Text.ToInt()-1); } else { Memo3->Lines->Add("Error 2. Mail list is clear."); } if (Memo2->Lines->Count != 0) { Memo2->Lines->Delete(Edit5->Text.ToInt()-1); } else { Memo3->Lines->Add("Error 2. Password list is clear."); } } else { Memo3->Lines->Add("Error 3. Index incorrect. Index must be > 0."); } } //--------------------------------------------------------------------------- void __fastcall TForm1::Button9Click(TObject *Sender) { if (Memo1->Lines->Count != 0) { Memo1->Lines->Delete(Memo1->Lines->Count-1); } else { Memo3->Lines->Add("Error 2. Mail list is clear."); } if (Memo2->Lines->Count != 0) { Memo2->Lines->Delete(Memo1->Lines->Count-1); } else { Memo3->Lines->Add("Error 2. Password list is clear."); } } //--------------------------------------------------------------------------- void __fastcall TForm1::Button10Click(TObject *Sender) { Memo1->Lines->Clear(); Memo3->Lines->Add("Mail list is clear."); Memo2->Lines->Clear(); Memo3->Lines->Add("Password list is clear."); } //--------------------------------------------------------------------------- void __fastcall TForm1::Button3Click(TObject *Sender) { ifstream fi(Edit3->Text.c_str()); if (fi.is_open()) { fi.close(); Memo5->Lines->LoadFromFile(Edit3->Text); for (int i = 0; i < Memo5->Lines->Count; i++) { bool fatr = false; String mail = "", password = ""; for (int j = 1; j <= Memo5->Lines->Strings[i].Length(); j++) { if (Memo5->Lines->Strings[i][j] == ':') { fatr = true; continue; } if (!fatr) { mail += Memo5->Lines->Strings[i][j]; } else { password += Memo5->Lines->Strings[i][j]; } } Memo1->Lines->Add(mail); Memo2->Lines->Add(password); } } else { Memo3->Lines->Add("Error 4. Can't open file. Please check file or path file"); fi.close(); } Memo5->Lines->Clear(); } //--------------------------------------------------------------------------- void __fastcall TForm1::Memo3Change(TObject *Sender) { Memo3->Lines->SaveToFile("Log.txt"); } //--------------------------------------------------------------------------- void __fastcall TForm1::Memo4Change(TObject *Sender) { Memo4->Lines->SaveToFile("Valid.txt"); } //---------------------------------------------------------------------------
e81efd6b96bb1414bc7f8ed3367e5100c01da5e4
e31a1a597db0550d2a9613c9a3e209ff1472f6bd
/src/application/exceptions/app_cant_create_model_impl.hpp
27e700f696f58bb6f30354c036f20680857352bb
[ "MIT" ]
permissive
g40/cppinclude
6bd0cee7c25d3876193e7e3d7fc38e829104058c
dc126c6057d2fe30569e6e86f66d2c8eebb50212
refs/heads/master
2023-07-12T18:17:41.490719
2021-08-10T18:32:51
2021-08-10T18:32:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
606
hpp
#pragma once #include "application/exceptions/app_base_exception_with_message_impl.hpp" #include "application/exceptions/app_exceptions.hpp" //------------------------------------------------------------------------------ namespace application { //------------------------------------------------------------------------------ class CantCreateModelImpl : public BaseExceptionWithMessageImpl< CantCreateModel > { using BaseClass = BaseExceptionWithMessageImpl< CantCreateModel >; public: CantCreateModelImpl(); }; //------------------------------------------------------------------------------ }
8e23e292276d0a047514c7d262a9d009ed67bc3f
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/LArCalorimeter/LArBadChannelTool/src/LArBadChanContainerHashed.cxx
b4af80ad5cd31c7f3adc717aa34378633c8cd207
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
C++
false
false
1,147
cxx
/* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ #include "LArBadChannelTool/LArBadChanContainerHashed.h" void LArBadChanContainerHashed::set( const BadChanVec& cont) { if (m_febVec.empty()) init(); // reset all channel information, but keep FEB status unchanged for ( unsigned int i=0; i< m_hasher.maxFEBHash(); i++) m_febVec[i].resetChannels(); for (BadChanVec::const_iterator i=cont.begin(); i!=cont.end(); ++i) { HashType h = m_hasher.febHashByChan( i->first); m_febVec.at(h).addChannel( m_hasher.channelInFeb(i->first), i->second); } m_bcv = cont; } void LArBadChanContainerHashed::init() { //if (!m_hasher.initialized()) FIXME should throw an exception! m_febVec.resize( m_hasher.maxFEBHash()); } void LArBadChanContainerHashed::setBadFEBs( const std::vector<BadFebEntry>& badFebs) { if (m_febVec.empty()) init(); for ( unsigned int i=0; i< m_hasher.maxFEBHash(); i++) m_febVec[i].resetBad(); for (std::vector<BadFebEntry>::const_iterator i=badFebs.begin(); i!=badFebs.end(); i++) { m_febVec.at( m_hasher.hashFEB(i->first)).setFebStatus(i->second); } }
7d2bb278df4d630aa96fd2b3f295725a7034cab0
3f3095dbf94522e37fe897381d9c76ceb67c8e4f
/Current/CameraShake_ShieldTank_TremorAttack.hpp
be30e09021333e0e788f059f9b28a4ea8a825c4d
[]
no_license
DRG-Modding/Header-Dumps
763c7195b9fb24a108d7d933193838d736f9f494
84932dc1491811e9872b1de4f92759616f9fa565
refs/heads/main
2023-06-25T11:11:10.298500
2023-06-20T13:52:18
2023-06-20T13:52:18
399,652,576
8
7
null
null
null
null
UTF-8
C++
false
false
204
hpp
#ifndef UE4SS_SDK_CameraShake_ShieldTank_TremorAttack_HPP #define UE4SS_SDK_CameraShake_ShieldTank_TremorAttack_HPP class UCameraShake_ShieldTank_TremorAttack_C : public UMatineeCameraShake { }; #endif
a5788847a079f34d585c0a83db7d01f93d9f613e
16977582890c1a765fdf760ad53465a9d4015eeb
/semestr-v/grafika-tymon/lab3spr/points.cpp
de51394b650bdbdccf16021fd5380dd171d84158
[ "MIT" ]
permissive
w4-pwr/studia
dae44f758b4d128417b93190631e8b987557e7f8
913215410951bb7f82b7266ae83c2e11cc038612
refs/heads/master
2021-01-14T09:37:09.302760
2013-06-14T17:50:02
2013-06-14T17:50:02
49,319,807
0
3
null
2016-01-09T10:22:19
2016-01-09T10:22:18
null
UTF-8
C++
false
false
122
cpp
glBegin(GL_POINTS); for(int i=0; i<N; i++){ for(int j=0; j<N; j++){ glVertex3fv(tab[i][j]); } } glEnd();
a3cb991bd34f624567e62fe104b27a7c87859131
7fc0a6dfde0befc6fb005b23e362da77b23b48ac
/codes/Extra Assignment the largest element from an array.cpp
3cd854786ca21a1d3e41bd695b5a49aa2000f637
[]
no_license
geraldo1993/Spring-2016
67f6021a10ac0dacde5368a4521131ffe8498b2d
d325d9769a66d8705724149a075197b1fd51effc
refs/heads/master
2020-04-17T16:02:01.637952
2016-09-11T03:22:49
2016-09-11T03:22:49
67,907,601
0
0
null
null
null
null
UTF-8
C++
false
false
987
cpp
#include <stdio.h> // This program will print out the largest element from the array int main(void) // declare the main function { // declare array and variable named "largest" int A[10], largest; // declare for counter variable int i; // read data from the user for(i=0; i<10; i++) { printf("Please enter number %d:", i+1); // print the elements of the array scanf("%d", &A[i]); // read the elements } // assume that the first element is the largest one largest = A[0]; for(i=1; i<10; i++) // declare and initialize for loop for finding the largest value; start from index=1; // because index=0 already used; { if( largest > A[i]); // if the first element from the first index is largest keep it as largest and continue else { largest = A[i]; // if not assign the largest value to other element ( from other index) of an array } } //print the largest number printf("LARGEST= %d",largest); return 0; }
1d5813cd1fe65fe728646fb74cca6ab337f05ac1
e4e64f4885b4436e1bf0682b0428c2ae0edd4ab1
/hello_world/hello_enclave.cc
fe2da2db86ce05b4a76dab92c467b7d6cd9b4fd0
[ "Apache-2.0" ]
permissive
ghas-results/asylo-examples
b1d80f0dd7d5157d03bce3c22f459271a6cb0546
89bdc29a58203b5a057d6bd6687dc2ca1c47ff20
refs/heads/master
2023-08-21T19:54:00.623117
2021-06-09T23:09:26
2021-06-09T23:09:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,871
cc
/* * * Copyright 2018 Asylo authors * * 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 <cstdint> #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "asylo/trusted_application.h" #include "asylo/util/logging.h" #include "asylo/util/status.h" #include "hello_world/hello.pb.h" class HelloApplication : public asylo::TrustedApplication { public: HelloApplication() : visitor_count_(0) {} asylo::Status Run(const asylo::EnclaveInput &input, asylo::EnclaveOutput *output) override { if (!input.HasExtension(hello_world::enclave_input_hello)) { return absl::InvalidArgumentError( "Expected a HelloInput extension on input."); } std::string visitor = input.GetExtension(hello_world::enclave_input_hello).to_greet(); LOG(INFO) << "Hello " << visitor; if (output) { LOG(INFO) << "Incrementing visitor count..."; output->MutableExtension(hello_world::enclave_output_hello) ->set_greeting_message( absl::StrCat("Hello ", visitor, "! You are visitor #", ++visitor_count_, " to this enclave.")); } return absl::OkStatus(); } private: uint64_t visitor_count_; }; namespace asylo { TrustedApplication *BuildTrustedApplication() { return new HelloApplication; } } // namespace asylo
a9c5646ca8e023783aae42d89f1edc28f0edc26e
6eba446ffc7a3aa793c99aee96b3c38488c9ce2f
/LongArithmetic/big_types.cpp
ef268f26a881a6720f3edfef2cef2259788907c3
[ "MIT" ]
permissive
130120013/long_arithmetics
7ad3a3ef061542c127f9786a7bef81efd848aa1f
faf388b263a57d7365307c4f03af0352194d8fb7
refs/heads/master
2020-11-27T10:44:56.559141
2019-12-29T09:22:00
2019-12-29T09:22:00
229,409,442
0
0
null
null
null
null
UTF-8
C++
false
false
937
cpp
#ifndef BIG_TYPES_H #define BIG_TYPES_H #include "big_types.h" bool memadd(std::uint32_t* pResult, std::size_t cbResult, const std::uint32_t* pX, std::size_t cbX, const std::uint32_t* pY, std::size_t cbY) noexcept { std::uint32_t carry = 0; if (cbX >= cbY) { cbResult = cbX; for (std::size_t i = cbY - 1; i > 0; --i) { pResult[i] = pY[i] + pX[i] + carry; carry = UINTPTR_MAX - pY[i] - pX[i] - carry < 0 ? 1 : 0; } for (std::size_t i = cbX - cbY - 1; i > 0; --i) { pResult[i] = pX[i] + carry; carry = UINTPTR_MAX - pX[i] - carry < 0 ? 1 : 0; } } else { cbResult = cbY; for (std::size_t i = cbX - 1; i > 0; --i) { pResult[i] = pY[i] + pX[i] + carry; carry = UINTPTR_MAX - pY[i] - pX[i] - carry < 0 ? 1 : 0; } for (std::size_t i = cbY - cbX - 1; i > 0; --i) { pResult[i] = pY[i] + carry; carry = UINTPTR_MAX - pY[i] - carry < 0 ? 1 : 0; } } return carry; } #endif // !BIG_TYPES_H
7334029dc8e17448d27ea5e5e4022f9d91add8c2
bdb35a77fa0be7fbb6ba1b6eed63d96feed81858
/cpp_primer_plus/chapter_02/_6_transform.cpp
514cab56cecfc41081deb44bce2668ebe93f3cdb
[]
no_license
karlinglee93/icpp
a96116e517391ec8dff904f0800ec35c9f531528
7da6d76ae84d8f4293369b380a5a68144ab4a33a
refs/heads/master
2020-03-10T10:18:29.120384
2018-05-12T02:09:37
2018-05-12T02:09:37
126,757,203
0
0
null
null
null
null
UTF-8
C++
false
false
154
cpp
#include <iostream> using namespace std; double _6_transform(double light_years) { double astronomical = light_years * 63240; return astronomical; }
1fbf3109c00c313183158b995040558a3b53a0df
b2e12fdf4b866c2964b32c5872ebf21c02da5f05
/ULSLogView/SPLogParser.cpp
63b8de14914d75d5659d08e8659e2088a9d62445
[]
no_license
haazim2/UlsLogView
ba7e64c3a01d3e2d49ffef3f239d66c12fef8761
a3b74a4a413146620ce717fb322efd780c070206
refs/heads/master
2020-05-17T04:22:32.600677
2011-09-07T15:36:00
2011-09-07T15:36:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,658
cpp
#include "stdafx.h" #include "ULSLogView.h" #include "tchar.h" #include "comutil.h" #include "winerror.h" #include "SPLogParser.h" SPLogParser::SPLogParser() { spLog=NULL; } int SPLogParser::ReadFile(void *fileData) { return 0; } int SPLogParser::CloseFile() { return 0; } void SPLogParser::ParseFile(void *fileData, HANDLE handle) { //fileSize=fileSize; int sectionCount=0; int lastCount=0; void* fileDataPointer; if(spLog==NULL) { spLog=new SPLOG(); } RecalculateSize(); for(DWORD i=0;i<fileSize;i++) { char data=((char*)fileData)[i]; if(data=='\t') { //DWORD newLoc=DWORD(fileData)+i; //void* newloc1=(void*)newLoc; //char c=((char*)newloc1)[0]; // c='\0'; char* data=(char*)(fileData); fileDataPointer=data+lastCount; switch(sectionCount) { case 0: memcpy(logHeader.timeStamp,fileDataPointer,i); lastCount=i; break; case 1: memcpy(logHeader.processInfo,fileDataPointer,i-lastCount); lastCount=i; break; case 2: memcpy(logHeader.threadID,fileDataPointer,i-lastCount); lastCount=i; break; case 3: memcpy(logHeader.areaInfo,fileDataPointer,i-lastCount); lastCount=i; break; case 4: memcpy(logHeader.categoryInfo,fileDataPointer,i-lastCount); lastCount=i; break; case 5: memcpy(logHeader.eventID,fileDataPointer,i-lastCount); lastCount=i; break; case 6: memcpy(logHeader.spLevel,fileDataPointer,i); lastCount=i; break; case 7: memcpy(logHeader.Message,fileDataPointer,i); lastCount=i; break; } //spLog-> sectionCount++; } } } DWORD SPLogParser:: RecalculateSize() { if(fileHandle!=NULL) { DWORD retFileSize=GetFileSize(fileHandle,NULL); fileSize=retFileSize; return retFileSize; } } void* SPLogParser::OpenFileReading(TCHAR* dirName, TCHAR fileName[]) { TCHAR fullFileName[MAX_PATH]; _tcscpy(fullFileName,dirName); _tcscat(fullFileName,_T("\\")); _tcscat(fullFileName,fileName); HANDLE hLogFile=CreateFile(fullFileName,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_ARCHIVE,NULL); if(hLogFile==INVALID_HANDLE_VALUE) { } fileHandle=hLogFile; DWORD fileSize; /*DWORD fileSize; DWORD retFileSize=GetFileSize(hLogFile,&fileSize); HGLOBAL hGlobal=GlobalAlloc(GHND,fileSize); void* memFile=GlobalLock(hGlobal);*/ DWORD retFileSize=GetFileSize(hLogFile,&fileSize); HANDLE hFileMap=CreateFileMapping(hLogFile,NULL, PAGE_READONLY,0,0,NULL); DWORD a=GetLastError(); void* memFile=MapViewOfFile(hFileMap,FILE_MAP_READ,NULL,NULL,NULL); return memFile; }
3c20eceadd6df7431ccdaf05fbec45c0e65cabd5
89df1ea7703a7d64ed2549027353b9f98b800e88
/minecraft/minecraft/src/engine/block/block.h
7e0e4fb9d6753ee9b894d6edcffd364575552ea6
[ "MIT" ]
permissive
llGuy/gamedev
31a3e23f921fbe38af48177710eb7bae661f4cfd
16aa203934fd767926c58558e021630288556399
refs/heads/master
2021-05-04T15:09:33.217825
2019-01-17T23:15:36
2019-01-17T23:15:36
120,221,445
0
0
null
null
null
null
UTF-8
C++
false
false
1,371
h
#ifndef BLOCK_HEADER #define BLOCK_HEADER #include <glm/glm.hpp> #include "../../texture/texture.h" #include "../chunk/cdata/cvec2.h" /* the coordinate inside the chunk */ /* is stored in an unsigned char to make it RAM efficient */ struct CCoord { uint8_t cc; }; struct TextureData { // the top, sides, and bottom texture coordinates are stored in vec3 glm::vec3 topSidesBottom; }; class Block { public: // types of blocks available enum block_t : uint8_t { STONE, DIRT, GRASS, BEDROCK, SAND, OAK_LOG, LEAVES, WATER, OAK_PLANKS, GLASS, COBBLE, INV /* will add more types of blocks */ }; static const uint32_t AVAILABLE_TEXTURES; static const TextureData BLOCK_TEXTURE_DATA[block_t::INV]; public: explicit Block(void) = default; explicit Block(const CCoord& cc, const block_t& bt); explicit Block(const CCoord&& cc, const block_t&& bt); public: /* getter */ glm::vec3 WPos(const WVec2 chunkCoordinate, int32_t y, const WVec2 negativeCornerWPos) const; // from the character that stores the block coordinate in chunk // extract the coordinates CVec2 ExtrCPos(void) const; const block_t BlockType(void) const; const TextureData& TextureD(void); // index in the uint16_t& VIndex(void); bool& Valid(void); private: uint16_t m_vIndex; CCoord m_cc; block_t m_bt; bool m_valid; }; #endif
d79d3deca98dea7474d13f8354e96c62f06594c6
fd63c968debb389a0fb6e4626a978eedb2256364
/tools/pythonpkg/src/arrow_array_stream.cpp
919bbe6b4d4e4bf5f566d4ce229d98e5dcf8eeaa
[ "MIT" ]
permissive
noamross/duckdb
f672e54e4360d512bfe75c73632b4df918aec6b1
ed793d8b314d798cb1829dd63f118b485b033bfb
refs/heads/master
2021-09-14T15:44:27.755311
2021-08-24T17:18:58
2021-08-24T17:18:58
183,275,936
0
0
null
2019-04-24T17:26:32
2019-04-24T17:26:32
null
UTF-8
C++
false
false
9,070
cpp
#include "duckdb/common/assert.hpp" #include "include/duckdb_python/arrow_array_stream.hpp" #include "duckdb/common/common.hpp" #include "duckdb/planner/table_filter.hpp" #include "duckdb/planner/filter/constant_filter.hpp" #include "duckdb/planner/filter/conjunction_filter.hpp" namespace duckdb { unique_ptr<ArrowArrayStreamWrapper> PythonTableArrowArrayStreamFactory::Produce( uintptr_t factory_ptr, std::pair<std::unordered_map<idx_t, string>, std::vector<string>> &project_columns, TableFilterCollection *filters) { py::gil_scoped_acquire acquire; PythonTableArrowArrayStreamFactory *factory = (PythonTableArrowArrayStreamFactory *)factory_ptr; if (!factory->arrow_table) { return nullptr; } py::handle table(factory->arrow_table); py::object scanner; py::object arrow_scanner = py::module_::import("pyarrow.dataset").attr("Scanner").attr("from_dataset"); auto py_object_type = string(py::str(table.get_type().attr("__name__"))); py::list projection_list = py::cast(project_columns.second); bool has_filter = filters && filters->table_filters && !filters->table_filters->filters.empty(); if (py_object_type == "Table") { auto arrow_dataset = py::module_::import("pyarrow.dataset").attr("dataset"); auto dataset = arrow_dataset(table); if (project_columns.second.empty()) { //! This is only called at the binder to get the schema scanner = arrow_scanner(dataset); } else { if (has_filter) { auto filter = TransformFilter(*filters, project_columns.first); scanner = arrow_scanner(dataset, py::arg("columns") = projection_list, py::arg("filter") = filter); } else { scanner = arrow_scanner(dataset, py::arg("columns") = projection_list); } } } else { if (project_columns.second.empty()) { //! This is only called at the binder to get the schema scanner = arrow_scanner(table); } else { if (has_filter) { auto filter = TransformFilter(*filters, project_columns.first); scanner = arrow_scanner(table, py::arg("columns") = projection_list, py::arg("filter") = filter); } else { scanner = arrow_scanner(table, py::arg("columns") = projection_list); } } } auto record_batches = scanner.attr("to_reader")(); auto res = make_unique<ArrowArrayStreamWrapper>(); auto export_to_c = record_batches.attr("_export_to_c"); export_to_c((uint64_t)&res->arrow_array_stream); return res; } py::object GetScalar(Value &constant) { py::object scalar = py::module_::import("pyarrow").attr("scalar"); py::object dataset_scalar = py::module_::import("pyarrow.dataset").attr("scalar"); py::object scalar_value; switch (constant.type().id()) { case LogicalTypeId::BOOLEAN: scalar_value = dataset_scalar(constant.GetValue<bool>()); return scalar_value; case LogicalTypeId::TINYINT: scalar_value = dataset_scalar(constant.GetValue<int8_t>()); return scalar_value; case LogicalTypeId::SMALLINT: scalar_value = dataset_scalar(constant.GetValue<int16_t>()); return scalar_value; case LogicalTypeId::INTEGER: scalar_value = dataset_scalar(constant.GetValue<int32_t>()); return scalar_value; case LogicalTypeId::BIGINT: scalar_value = dataset_scalar(constant.GetValue<int64_t>()); return scalar_value; case LogicalTypeId::HUGEINT: { py::object date_type = py::module_::import("pyarrow").attr("decimal128"); scalar_value = dataset_scalar(scalar(constant.GetValue<hugeint_t>(), date_type(38))); return scalar_value; } case LogicalTypeId::DATE: { py::object date_type = py::module_::import("pyarrow").attr("date32"); scalar_value = dataset_scalar(scalar(constant.GetValue<int32_t>(), date_type())); return scalar_value; } case LogicalTypeId::TIME: scalar_value = dataset_scalar(constant.GetValue<int64_t>()); return scalar_value; case LogicalTypeId::TIMESTAMP: { py::object date_type = py::module_::import("pyarrow").attr("timestamp"); scalar_value = dataset_scalar(scalar(constant.GetValue<int64_t>(), date_type("us"))); return scalar_value; } case LogicalTypeId::UTINYINT: scalar_value = dataset_scalar(constant.GetValue<uint8_t>()); return scalar_value; case LogicalTypeId::USMALLINT: scalar_value = dataset_scalar(constant.GetValue<uint16_t>()); return scalar_value; case LogicalTypeId::UINTEGER: scalar_value = dataset_scalar(constant.GetValue<uint32_t>()); return scalar_value; case LogicalTypeId::UBIGINT: scalar_value = dataset_scalar(constant.GetValue<uint64_t>()); return scalar_value; case LogicalTypeId::FLOAT: scalar_value = dataset_scalar(constant.GetValue<float>()); return scalar_value; case LogicalTypeId::DOUBLE: scalar_value = dataset_scalar(constant.GetValue<double>()); return scalar_value; case LogicalTypeId::VARCHAR: scalar_value = dataset_scalar(constant.ToString()); return scalar_value; case LogicalTypeId::DECIMAL: { py::object date_type = py::module_::import("pyarrow").attr("decimal128"); uint8_t width; uint8_t scale; constant.type().GetDecimalProperties(width, scale); switch (constant.type().InternalType()) { case PhysicalType::INT16: scalar_value = dataset_scalar(scalar(constant.GetValue<int16_t>(), date_type(width, scale))); return scalar_value; case PhysicalType::INT32: scalar_value = dataset_scalar(scalar(constant.GetValue<int32_t>(), date_type(width, scale))); return scalar_value; case PhysicalType::INT64: scalar_value = dataset_scalar(scalar(constant.GetValue<int64_t>(), date_type(width, scale))); return scalar_value; default: scalar_value = dataset_scalar(scalar(constant.GetValue<hugeint_t>(), date_type(width, scale))); return scalar_value; } } break; default: throw NotImplementedException("Unimplemented type \"%s\" for Arrow Filter Pushdown", constant.type().ToString()); } } py::object TransformFilterRecursive(TableFilter *filter, const string &column_name) { py::object field = py::module_::import("pyarrow.dataset").attr("field"); switch (filter->filter_type) { case TableFilterType::CONSTANT_COMPARISON: { auto constant_filter = (ConstantFilter *)filter; auto constant_field = field(column_name); auto constant_value = GetScalar(constant_filter->constant); switch (constant_filter->comparison_type) { case ExpressionType::COMPARE_EQUAL: { return constant_field.attr("__eq__")(constant_value); } case ExpressionType::COMPARE_LESSTHAN: { return constant_field.attr("__lt__")(constant_value); } case ExpressionType::COMPARE_GREATERTHAN: { return constant_field.attr("__gt__")(constant_value); } case ExpressionType::COMPARE_LESSTHANOREQUALTO: { return constant_field.attr("__le__")(constant_value); } case ExpressionType::COMPARE_GREATERTHANOREQUALTO: { return constant_field.attr("__ge__")(constant_value); } default: throw std::runtime_error("Comparison Type can't be an Arrow Scan Pushdown Filter"); } break; } //! I guess arrow cant handle IS_NULL or IS_NOT_NULL case TableFilterType::IS_NULL: { auto constant_field = field(column_name); return constant_field.attr("is_null")(); } case TableFilterType::IS_NOT_NULL: { auto constant_field = field(column_name); return constant_field.attr("is_valid")(); } case TableFilterType::CONJUNCTION_OR: { idx_t i = 0; auto or_filter = (ConjunctionOrFilter *)filter; //! Get first non null filter type auto child_filter = or_filter->child_filters[i++].get(); py::object expression = TransformFilterRecursive(child_filter, column_name); while (i < or_filter->child_filters.size()) { child_filter = or_filter->child_filters[i++].get(); py::object child_expression = TransformFilterRecursive(child_filter, column_name); expression = expression.attr("__or__")(child_expression); } return expression; } case TableFilterType::CONJUNCTION_AND: { idx_t i = 0; auto and_filter = (ConjunctionAndFilter *)filter; auto child_filter = and_filter->child_filters[i++].get(); py::object expression = TransformFilterRecursive(child_filter, column_name); while (i < and_filter->child_filters.size()) { child_filter = and_filter->child_filters[i++].get(); py::object child_expression = TransformFilterRecursive(child_filter, column_name); expression = expression.attr("__and__")(child_expression); } return expression; } default: throw std::runtime_error("Pushdown Filter Type not supported in Arrow Scans"); } } py::object PythonTableArrowArrayStreamFactory::TransformFilter(TableFilterCollection &filter_collection, std::unordered_map<idx_t, string> &columns) { auto filters_map = &filter_collection.table_filters->filters; auto it = filters_map->begin(); D_ASSERT(columns.find(it->first) != columns.end()); py::object expression = TransformFilterRecursive(it->second.get(), columns[it->first]); while (it != filters_map->end()) { py::object child_expression = TransformFilterRecursive(it->second.get(), columns[it->first]); expression = expression.attr("__and__")(child_expression); it++; } return expression; } } // namespace duckdb
c1c65f384d88430980a3c76e8e0875ac257bf282
a23cd4ef25774faf2ac78ac83b53251208e16621
/include/plugin.h
6f6397cc326076df84e0e765b80f44483370d320
[]
no_license
acelove/Simhttp
c56223899cb1b13b27c5a69375b5d97a1929d920
cfa80ea551e002348c090db7c14ae080b0d8c5e7
refs/heads/master
2020-03-10T17:20:41.546394
2018-04-30T08:04:25
2018-04-30T08:04:25
129,497,996
0
0
null
null
null
null
UTF-8
C++
false
false
1,055
h
#ifndef _PLUGIN_H #define _PLUGIN_H class Worker; class Connection; typedef enum{ PLUGIN_READY, PLUGIN_NOT_READY, PLUGIN_ERROR } plugin_state_t; class Plugin{ public: Plugin(); virtual ~Plugin(); virtual bool Init(Connection *con, int index); virtual bool RequestStart(Connection *con,int index); virtual bool Read(Connection *con,int index); virtual bool RequestEnd(Connection *con,int index); virtual bool ResponseStart(Connection *con,int index); virtual plugin_state_t Write(Connection *con,int index); virtual bool ResponseEnd(Connection *con,int index); virtual void Close(Connection *con,int index); virtual bool Trigger(Worker *worker,int index); virtual bool LoadPlugin(Worker *worker,int index); virtual void FreePlugin(Worker *worker,int index); typedef Plugin* (*SetupPlugin)(); typedef void (*RemovePlugin)(Plugin* plugin); SetupPlugin setup_plugin; RemovePlugin remove_plugin; void* plugin_data; void* plugin_so; int plugin_index; bool plugin_is_loaded; }; extern const char* plugin_list[]; #endif
570a53d0e14ea35cf77b9f7baf2da9d526f209e0
aaa3eb8aa16289dd1a9235c7854bf55d5e557520
/matrix/BoolMatrix.hpp
75223fcf11e48d250514ec1a1461a617b22a22f1
[]
no_license
yangjietadie/common
5d46f3528ca16f728b92b2872838ac0b8eb302d5
2d87039d75d665b92d4f4cf368a422e656fa2b05
refs/heads/master
2023-03-19T23:30:52.659245
2019-07-29T03:04:52
2019-07-29T03:04:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,560
hpp
#ifndef _BOOL_MATRIX_H_ #define _BOOL_MATRIX_H_ #include <unordered_map> #include <memory> #include <boost/dynamic_bitset.hpp> using BitSet = boost::dynamic_bitset<>; template<typename T> class BoolMatrix { public: BoolMatrix() : columnNum_(0), lineNum_(0) {} ~BoolMatrix() = default; BoolMatrix(const BoolMatrix &rhs) = delete; void addLine(const T &line); void deleteLine(const T &line); void addColumn(); void set(unsigned int column, const T &line); void set(unsigned int column); void reset(unsigned int column); unsigned int columns() const { return columnNum_; } unsigned int lines() const { return lineNum_; } const BitSet* getBitset(const T &line) const; private: typedef std::unordered_map<T, std::unique_ptr<BitSet>> LineMap; void setAll(unsigned int column, bool val); unsigned int columnNum_; unsigned int lineNum_; LineMap lineMap_; }; template<typename T> void BoolMatrix<T>::addLine(const T &line) { auto it = lineMap_.find(line); if (it != lineMap_.end()) { return; } std::unique_ptr<BitSet> bitset(new BitSet(columnNum_)); bitset->reset(); lineMap_[line] = std::move(bitset); lineNum_++; } template<typename T> void BoolMatrix<T>::deleteLine(const T &line) { auto it = lineMap_.find(line); if (it == lineMap_.end()) { return; } lineMap_.erase(it); lineNum_--; } template<typename T> const BitSet* BoolMatrix<T>::getBitset(const T &line) const { auto it = lineMap_.find(line); if (it == lineMap_.end()) { return nullptr; } return it->second.get(); } template<typename T> void BoolMatrix<T>::addColumn() { for (auto &it : lineMap_) { it.second->push_back(false); } columnNum_++; } template<typename T> void BoolMatrix<T>::set(unsigned int column, const T &line) { if (column < 0 || column >= columnNum_) { return; } auto it = lineMap_.find(line); if (it == lineMap_.end()) { return; } it->second->set(column, true); } template<typename T> void BoolMatrix<T>::set(unsigned int column) { setAll(column, true); } template<typename T> void BoolMatrix<T>::reset(unsigned int column) { setAll(column, false); } template<typename T> void BoolMatrix<T>::setAll(unsigned int column, bool val) { if (column < 0 || column >= columnNum_) { return; } for (auto &it : lineMap_) { it.second->set(column, val); } } #endif
a69ef832e5c6dbc6348d1066737b0d5d6fd0d22f
3723cb449d606039015132e2e1dd7400ab6a220e
/0 Fill Spins and System/0 Fill Spins and System/stdafx.cpp
9608047aea872a65b6a5fc7037415631c7e98947
[]
no_license
akterskii/J-Q_model
dedba449b2b7646e33efc6d2e57e576382fb7ea6
8d79d93e74639500585b82ba3d5e2838692b9a1e
refs/heads/master
2020-04-14T03:31:17.399943
2019-01-16T22:38:16
2019-01-16T22:38:16
163,610,127
0
0
null
null
null
null
UTF-8
C++
false
false
302
cpp
// stdafx.cpp : source file that includes just the standard includes // 0 Fill Spins and System.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
2df632bc3cd2487306e12779d1a43fe252c1df07
c83a101046f7eb0e0a8042062ae898be7ace950e
/src/instruction/nop.cpp
21c52e47933a08c40dc1279d4b1d1fd65da18c81
[]
no_license
ordovicia/felis-simulator
320428f73201f887671f447e85d9b19cf2a0ba13
6ed8f1be9ca1b4e96d77b240448a84ef77895e53
refs/heads/master
2021-01-12T14:20:19.572046
2017-02-23T05:38:54
2017-02-23T05:38:54
69,932,195
0
1
null
null
null
null
UTF-8
C++
false
false
170
cpp
#include "simulator.hpp" Simulator::PreState Simulator::nop(Instruction /* inst */) { auto pre_state = makePrePCState(m_pc); m_pc += 4; return pre_state; }
3da484b04542b97f23a60f10b04b3b743f40418b
3457895a2ea0fbfd18ecc9cdc61fe2d7e964a6b0
/try/048.习题.cpp
dcb72dbf2dd11f3c34c042be615dae4e2f079fcd
[]
no_license
WilliamWangPeng/Repository-C-primer-plus
16a56eac8255041282a22ea09ac235a4410e6b92
0f25199756de52466baa7d5e3d7b3aa04f97135b
refs/heads/master
2022-11-17T16:26:34.012488
2020-07-14T11:37:54
2020-07-14T11:37:54
null
0
0
null
null
null
null
GB18030
C++
false
false
1,416
cpp
#include <iostream> #include <string> #include <vector> using namespace std; //输入两个向量,并比较一个是否为另一个的前缀 int main() { vector<int> ivec1, ivec2; int ival; cout << "enter elements for the first vector:(32767 to end)" << endl; cin >> ival; while (ival != 32767) { ivec1.push_back(ival); cin >> ival; } /*while (cin>>ival) { ivec1.push_back(ival); } cin.clear(); //注意此处,由于第一次循环用Ctrl+z结束,屏蔽了cin,所以使用cin.clear()取消屏蔽,使下一次cin可以使用 while (cin>>ival) { ivec2.push_back(ival); }*/ cout << "enter elements for the second vector:(32767 to end)" << endl; cin >> ival; while (ival!=32767) { ivec2.push_back(ival); cin >> ival; } //比较两个数组,看一个向量是否是另一个向量的前缀 vector<int>::size_type size1, size2; size1 = ivec1.size(); size2 = ivec2.size(); bool result = true; for (vector<int>::size_type ix=0; ix!=(size1>size2 ? size2:size1);++ix) { if (ivec1[ix]!=ivec2[ix]) { result = false; break; } } if (result) { if (size1<size2) { cout << "the first vector is prefix of the second one"; } else if (size1==size2) { cout << "two vectors are equal." << endl; } else { cout << "the second vector is prefix of the first one"; } } else { cout << "no vector is prefix of the other one:"; } return 0; }
a18abe77df88f491b4e2b029dffbf130fd5d7ee8
4dad3b14f12d725f405899e71eb4aa816f6b50b4
/zertco5/utils/tools/SameThreadChecker.h
bc705aa4ea765f1bb536b53cbbc3c2afd1718926
[]
no_license
ccitllz/zertcore5
0cdbcee3b7889e9477d7f461240a42d3212aa2bf
9f6c9a352ce1526f7fd55cb546d6a5c5c0ebee7c
refs/heads/master
2023-04-13T22:25:05.558013
2015-11-05T12:34:07
2015-11-05T12:34:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
714
h
/* * SameThreadChecker.h * * Created on: 2015年5月29日 * Author: Administrator */ #ifndef ZERTCORE_UTILS_TOOLS_SAMETHREADCHECKER_H_ #define ZERTCORE_UTILS_TOOLS_SAMETHREADCHECKER_H_ #include <pch.h> #include <utils/types.h> namespace zertcore { namespace utils { /** * SameThreadChecker */ class SameThreadChecker { public: void init(); public: void check() const; private: tid_type tid_; }; }} #define ZC_THREAD_CHECKER private: \ ::zertcore:utils::SameThreadChecker __sthread_checker; #define ZC_THREAD_CHECKER_INIT do{__sthread_checker.init();}while(false); #define ZC_THREAD_CHECKER_DO do{__sthread_checker.check();}while(false); #endif /* UTILS_TOOLS_SAMETHREADCHECKER_H_ */
ca10b962622d85f31647d0f1a6dfd8ff512ee17a
5a496afb5fff8e46db33618fb7a97963ec588238
/src/service_route/objects/route_object.cc
e685538cd1a65f0ad0c168bca4e2cc0397c258b8
[]
no_license
skyformat99/im-1
73f2ce6d77f1c63559f39005feaa0e4a8e67178f
2cfe3676c84a7ff1b4277f7b59bc3370516212b5
refs/heads/master
2021-07-23T18:38:43.862321
2017-10-11T06:44:04
2017-10-11T06:44:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
112
cc
#include "route_object.h" RouteObject::RouteObject() { online_status_=OnlineStatus_Offline; sockfd_=-1; }
[ "python@git" ]
python@git
3c1dc0f9bb0a5c3cdca90e8771a30124c8c2bfde
55d560fe6678a3edc9232ef14de8fafd7b7ece12
/libs/compute/test/test_lambda.cpp
dfb4b2a6cd07892b11258bda3686a1c786b8c2f6
[ "BSL-1.0" ]
permissive
stardog-union/boost
ec3abeeef1b45389228df031bf25b470d3d123c5
caa4a540db892caa92e5346e0094c63dea51cbfb
refs/heads/stardog/develop
2021-06-25T02:15:10.697006
2020-11-17T19:50:35
2020-11-17T19:50:35
148,681,713
0
0
BSL-1.0
2020-11-17T19:50:36
2018-09-13T18:38:54
C++
UTF-8
C++
false
false
20,748
cpp
//---------------------------------------------------------------------------// // Copyright (c) 2013 Kyle Lutz <[email protected]> // // Distributed under the Boost Software License, Version 1.0 // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // // See http://boostorg.github.com/compute for more information. //---------------------------------------------------------------------------// #define BOOST_TEST_MODULE TestLambda #include <boost/test/unit_test.hpp> #include <boost/tuple/tuple_io.hpp> #include <boost/tuple/tuple_comparison.hpp> #include <boost/compute/function.hpp> #include <boost/compute/lambda.hpp> #include <boost/compute/algorithm/copy_n.hpp> #include <boost/compute/algorithm/for_each.hpp> #include <boost/compute/algorithm/transform.hpp> #include <boost/compute/container/vector.hpp> #include <boost/compute/functional/bind.hpp> #include <boost/compute/iterator/zip_iterator.hpp> #include <boost/compute/types/pair.hpp> #include <boost/compute/types/tuple.hpp> #include "check_macros.hpp" #include "quirks.hpp" #include "context_setup.hpp" namespace bc = boost::compute; namespace compute = boost::compute; BOOST_AUTO_TEST_CASE(squared_plus_one) { bc::vector<int> vector(context); vector.push_back(1, queue); vector.push_back(2, queue); vector.push_back(3, queue); vector.push_back(4, queue); vector.push_back(5, queue); // multiply each value by itself and add one bc::transform(vector.begin(), vector.end(), vector.begin(), (bc::_1 * bc::_1) + 1, queue); CHECK_RANGE_EQUAL(int, 5, vector, (2, 5, 10, 17, 26)); } BOOST_AUTO_TEST_CASE(abs_int) { bc::vector<int> vector(context); vector.push_back(-1, queue); vector.push_back(-2, queue); vector.push_back(3, queue); vector.push_back(-4, queue); vector.push_back(5, queue); bc::transform(vector.begin(), vector.end(), vector.begin(), abs(bc::_1), queue); CHECK_RANGE_EQUAL(int, 5, vector, (1, 2, 3, 4, 5)); } template<class Result, class Expr> void check_lambda_result(const Expr &) { BOOST_STATIC_ASSERT(( boost::is_same< typename ::boost::compute::lambda::result_of<Expr>::type, Result >::value )); } template<class Result, class Expr, class Arg1> void check_lambda_result(const Expr &, const Arg1 &) { BOOST_STATIC_ASSERT(( boost::is_same< typename ::boost::compute::lambda::result_of< Expr, typename boost::tuple<Arg1> >::type, Result >::value )); } template<class Result, class Expr, class Arg1, class Arg2> void check_lambda_result(const Expr &, const Arg1 &, const Arg2 &) { BOOST_STATIC_ASSERT(( boost::is_same< typename ::boost::compute::lambda::result_of< Expr, typename boost::tuple<Arg1, Arg2> >::type, Result >::value )); } template<class Result, class Expr, class Arg1, class Arg2, class Arg3> void check_lambda_result(const Expr &, const Arg1 &, const Arg2 &, const Arg3 &) { BOOST_STATIC_ASSERT(( boost::is_same< typename ::boost::compute::lambda::result_of< Expr, typename boost::tuple<Arg1, Arg2, Arg3> >::type, Result >::value )); } BOOST_AUTO_TEST_CASE(result_of) { using ::boost::compute::lambda::_1; using ::boost::compute::lambda::_2; using ::boost::compute::lambda::_3; namespace proto = ::boost::proto; using boost::compute::int_; check_lambda_result<int_>(proto::lit(1)); check_lambda_result<int_>(proto::lit(1) + 2); check_lambda_result<float>(proto::lit(1.2f)); check_lambda_result<float>(proto::lit(1) + 1.2f); check_lambda_result<float>(proto::lit(1) / 2 + 1.2f); using boost::compute::float4_; using boost::compute::int4_; check_lambda_result<int_>(_1, int_(1)); check_lambda_result<float>(_1, float(1.2f)); check_lambda_result<float4_>(_1, float4_(1, 2, 3, 4)); check_lambda_result<float4_>(2.0f * _1, float4_(1, 2, 3, 4)); check_lambda_result<float4_>(_1 * 2.0f, float4_(1, 2, 3, 4)); check_lambda_result<float>(dot(_1, _2), float4_(0, 1, 2, 3), float4_(3, 2, 1, 0)); check_lambda_result<float>(dot(_1, float4_(3, 2, 1, 0)), float4_(0, 1, 2, 3)); check_lambda_result<float>(distance(_1, _2), float4_(0, 1, 2, 3), float4_(3, 2, 1, 0)); check_lambda_result<float>(distance(_1, float4_(3, 2, 1, 0)), float4_(0, 1, 2, 3)); check_lambda_result<float>(length(_1), float4_(3, 2, 1, 0)); check_lambda_result<float4_>(cross(_1, _2), float4_(0, 1, 2, 3), float4_(3, 2, 1, 0)); check_lambda_result<float4_>(cross(_1, float4_(3, 2, 1, 0)), float4_(0, 1, 2, 3)); check_lambda_result<float4_>(max(_1, _2), float4_(3, 2, 1, 0), float4_(0, 1, 2, 3)); check_lambda_result<float4_>(max(_1, float(1.0f)), float4_(0, 1, 2, 3)); check_lambda_result<int4_>(max(_1, int4_(3, 2, 1, 0)), int4_(0, 1, 2, 3)); check_lambda_result<int4_>(max(_1, int_(1)), int4_(0, 1, 2, 3)); check_lambda_result<float4_>(min(_1, float4_(3, 2, 1, 0)), float4_(0, 1, 2, 3)); check_lambda_result<float4_>(step(_1, _2), float4_(3, 2, 1, 0), float4_(0, 1, 2, 3)); check_lambda_result<int4_>(step(_1, _2), float(3.0f), int4_(0, 1, 2, 3)); check_lambda_result<float4_>( smoothstep(_1, _2, _3), float4_(3, 2, 1, 0), float4_(3, 2, 1, 0), float4_(0, 1, 2, 3) ); check_lambda_result<int4_>( smoothstep(_1, _2, _3), float(2.0f), float(3.0f), int4_(0, 1, 2, 3) ); check_lambda_result<int4_>(bc::lambda::isinf(_1), float4_(0, 1, 2, 3)); check_lambda_result<int>(_1 + 2, int(2)); check_lambda_result<float>(_1 + 2, float(2.2f)); check_lambda_result<int>(_1 + _2, int(1), int(2)); check_lambda_result<float>(_1 + _2, int(1), float(2.2f)); check_lambda_result<int>(_1 + _1, int(1)); check_lambda_result<float>(_1 * _1, float(1)); using boost::compute::lambda::get; check_lambda_result<float>(get<0>(_1), float4_(1, 2, 3, 4)); check_lambda_result<bool>(get<0>(_1) < 1.f, float4_(1, 2, 3, 4)); check_lambda_result<bool>(_1 < 1.f, float(2)); using boost::compute::lambda::make_pair; check_lambda_result<int>(get<0>(make_pair(_1, _2)), int(1), float(1.2f)); check_lambda_result<float>(get<1>(make_pair(_1, _2)), int(1), float(1.2f)); check_lambda_result<std::pair<int, float> >(make_pair(_1, _2), int(1), float(1.2f)); using boost::compute::lambda::make_tuple; check_lambda_result<boost::tuple<int> >(make_tuple(_1), int(1)); check_lambda_result<boost::tuple<int, float> >(make_tuple(_1, _2), int(1), float(1.2f)); check_lambda_result<boost::tuple<int, int> >(make_tuple(_1, _1), int(1)); check_lambda_result<boost::tuple<int, float> >(make_tuple(_1, _2), int(1), float(1.4f)); check_lambda_result<boost::tuple<char, int, float> >( make_tuple(_1, _2, _3), char('a'), int(2), float(3.4f) ); check_lambda_result<boost::tuple<int, int, int> >( make_tuple(_1, _1, _1), int(1), float(1.4f) ); check_lambda_result<boost::tuple<int, float, int, float, int> >( make_tuple(_1, _2, _1, _2, _1), int(1), float(1.4f) ); } BOOST_AUTO_TEST_CASE(make_function_from_lamdba) { using boost::compute::lambda::_1; int data[] = { 2, 4, 6, 8, 10 }; compute::vector<int> vector(data, data + 5, queue); compute::function<int(int)> f = _1 * 2 + 3; compute::transform( vector.begin(), vector.end(), vector.begin(), f, queue ); CHECK_RANGE_EQUAL(int, 5, vector, (7, 11, 15, 19, 23)); } BOOST_AUTO_TEST_CASE(make_function_from_binary_lamdba) { using boost::compute::lambda::_1; using boost::compute::lambda::_2; using boost::compute::lambda::abs; int data1[] = { 2, 4, 6, 8, 10 }; int data2[] = { 10, 8, 6, 4, 2 }; compute::vector<int> vec1(data1, data1 + 5, queue); compute::vector<int> vec2(data2, data2 + 5, queue); compute::vector<int> result(5, context); compute::function<int(int, int)> f = abs(_1 - _2); compute::transform( vec1.begin(), vec1.end(), vec2.begin(), result.begin(), f, queue ); CHECK_RANGE_EQUAL(int, 5, result, (8, 4, 0, 4, 8)); } BOOST_AUTO_TEST_CASE(lambda_binary_function_with_pointer_modf) { using boost::compute::lambda::_1; using boost::compute::lambda::_2; using boost::compute::lambda::abs; bc::float_ data1[] = { 2.2f, 4.2f, 6.3f, 8.3f, 10.2f }; compute::vector<bc::float_> vec1(data1, data1 + 5, queue); compute::vector<bc::float_> vec2(size_t(5), context); compute::vector<bc::float_> result(5, context); compute::transform( bc::make_transform_iterator(vec1.begin(), _1 + 0.01f), bc::make_transform_iterator(vec1.end(), _1 + 0.01f), vec2.begin(), result.begin(), bc::lambda::modf(_1, _2), queue ); CHECK_RANGE_CLOSE(bc::float_, 5, result, (0.21f, 0.21f, 0.31f, 0.31f, 0.21f), 0.01f); CHECK_RANGE_CLOSE(bc::float_, 5, vec2, (2, 4, 6, 8, 10), 0.01f); } BOOST_AUTO_TEST_CASE(lambda_tenary_function_with_pointer_remquo) { if(!has_remquo_func(device)) { return; } using boost::compute::lambda::_1; using boost::compute::lambda::_2; using boost::compute::lambda::get; bc::float_ data1[] = { 2.2f, 4.2f, 6.3f, 8.3f, 10.2f }; bc::float_ data2[] = { 4.4f, 4.2f, 6.3f, 16.6f, 10.2f }; compute::vector<bc::float_> vec1(data1, data1 + 5, queue); compute::vector<bc::float_> vec2(data2, data2 + 5, queue); compute::vector<bc::int_> vec3(size_t(5), context); compute::vector<bc::float_> result(5, context); compute::transform( compute::make_zip_iterator( boost::make_tuple(vec1.begin(), vec2.begin(), vec3.begin()) ), compute::make_zip_iterator( boost::make_tuple(vec1.end(), vec2.end(), vec3.end()) ), result.begin(), bc::lambda::remquo(get<0>(_1), get<1>(_1), get<2>(_1)), queue ); CHECK_RANGE_CLOSE(bc::float_, 5, result, (2.2f, 0.0f, 0.0f, 8.3f, 0.0f), 0.01f); CHECK_RANGE_EQUAL(bc::int_, 5, vec3, (0, 1, 1, 0, 1)); } BOOST_AUTO_TEST_CASE(lambda_get_vector) { using boost::compute::_1; using boost::compute::int2_; using boost::compute::lambda::get; int data[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; compute::vector<int2_> vector(4, context); compute::copy( reinterpret_cast<int2_ *>(data), reinterpret_cast<int2_ *>(data) + 4, vector.begin(), queue ); // extract first component of each vector compute::vector<int> first_component(4, context); compute::transform( vector.begin(), vector.end(), first_component.begin(), get<0>(_1), queue ); CHECK_RANGE_EQUAL(int, 4, first_component, (1, 3, 5, 7)); // extract second component of each vector compute::vector<int> second_component(4, context); compute::transform( vector.begin(), vector.end(), first_component.begin(), get<1>(_1), queue ); CHECK_RANGE_EQUAL(int, 4, first_component, (2, 4, 6, 8)); } BOOST_AUTO_TEST_CASE(lambda_get_pair) { using boost::compute::_1; using boost::compute::lambda::get; compute::vector<std::pair<int, float> > vector(context); vector.push_back(std::make_pair(1, 1.2f), queue); vector.push_back(std::make_pair(3, 3.4f), queue); vector.push_back(std::make_pair(5, 5.6f), queue); vector.push_back(std::make_pair(7, 7.8f), queue); // extract first compoenent of each pair compute::vector<int> first_component(4, context); compute::transform( vector.begin(), vector.end(), first_component.begin(), get<0>(_1), queue ); CHECK_RANGE_EQUAL(int, 4, first_component, (1, 3, 5, 7)); // extract second compoenent of each pair compute::vector<float> second_component(4, context); compute::transform( vector.begin(), vector.end(), second_component.begin(), get<1>(_1), queue ); CHECK_RANGE_EQUAL(float, 4, second_component, (1.2f, 3.4f, 5.6f, 7.8f)); } BOOST_AUTO_TEST_CASE(lambda_get_tuple) { using boost::compute::_1; using boost::compute::lambda::get; compute::vector<boost::tuple<int, char, float> > vector(context); vector.push_back(boost::make_tuple(1, 'a', 1.2f), queue); vector.push_back(boost::make_tuple(3, 'b', 3.4f), queue); vector.push_back(boost::make_tuple(5, 'c', 5.6f), queue); vector.push_back(boost::make_tuple(7, 'd', 7.8f), queue); // extract first component of each tuple compute::vector<int> first_component(4, context); compute::transform( vector.begin(), vector.end(), first_component.begin(), get<0>(_1), queue ); CHECK_RANGE_EQUAL(int, 4, first_component, (1, 3, 5, 7)); // extract second component of each tuple compute::vector<char> second_component(4, context); compute::transform( vector.begin(), vector.end(), second_component.begin(), get<1>(_1), queue ); CHECK_RANGE_EQUAL(char, 4, second_component, ('a', 'b', 'c', 'd')); // extract third component of each tuple compute::vector<float> third_component(4, context); compute::transform( vector.begin(), vector.end(), third_component.begin(), get<2>(_1), queue ); CHECK_RANGE_EQUAL(float, 4, third_component, (1.2f, 3.4f, 5.6f, 7.8f)); } BOOST_AUTO_TEST_CASE(lambda_get_zip_iterator) { using boost::compute::_1; using boost::compute::lambda::get; float data[] = { 1.2f, 2.3f, 3.4f, 4.5f, 5.6f, 6.7f, 7.8f, 9.0f }; compute::vector<float> input(8, context); compute::copy(data, data + 8, input.begin(), queue); compute::vector<float> output(8, context); compute::for_each( compute::make_zip_iterator( boost::make_tuple(input.begin(), output.begin()) ), compute::make_zip_iterator( boost::make_tuple(input.end(), output.end()) ), get<1>(_1) = get<0>(_1), queue ); CHECK_RANGE_EQUAL(float, 8, output, (1.2f, 2.3f, 3.4f, 4.5f, 5.6f, 6.7f, 7.8f, 9.0f) ); } BOOST_AUTO_TEST_CASE(lambda_make_pair) { using boost::compute::_1; using boost::compute::_2; using boost::compute::lambda::make_pair; int int_data[] = { 1, 3, 5, 7 }; float float_data[] = { 1.2f, 2.3f, 3.4f, 4.5f }; compute::vector<int> int_vector(int_data, int_data + 4, queue); compute::vector<float> float_vector(float_data, float_data + 4, queue); compute::vector<std::pair<int, float> > output_vector(4, context); compute::transform( int_vector.begin(), int_vector.end(), float_vector.begin(), output_vector.begin(), make_pair(_1 - 1, 0 - _2), queue ); std::vector<std::pair<int, float> > host_vector(4); compute::copy_n(output_vector.begin(), 4, host_vector.begin(), queue); BOOST_CHECK(host_vector[0] == std::make_pair(0, -1.2f)); BOOST_CHECK(host_vector[1] == std::make_pair(2, -2.3f)); BOOST_CHECK(host_vector[2] == std::make_pair(4, -3.4f)); BOOST_CHECK(host_vector[3] == std::make_pair(6, -4.5f)); } BOOST_AUTO_TEST_CASE(lambda_make_tuple) { using boost::compute::_1; using boost::compute::lambda::get; using boost::compute::lambda::make_tuple; std::vector<boost::tuple<int, float> > data; data.push_back(boost::make_tuple(2, 1.2f)); data.push_back(boost::make_tuple(4, 2.4f)); data.push_back(boost::make_tuple(6, 4.6f)); data.push_back(boost::make_tuple(8, 6.8f)); compute::vector<boost::tuple<int, float> > input_vector(4, context); compute::copy(data.begin(), data.end(), input_vector.begin(), queue); // reverse the elements in the tuple compute::vector<boost::tuple<float, int> > output_vector(4, context); compute::transform( input_vector.begin(), input_vector.end(), output_vector.begin(), make_tuple(get<1>(_1), get<0>(_1)), queue ); std::vector<boost::tuple<float, int> > host_vector(4); compute::copy_n(output_vector.begin(), 4, host_vector.begin(), queue); BOOST_CHECK_EQUAL(host_vector[0], boost::make_tuple(1.2f, 2)); BOOST_CHECK_EQUAL(host_vector[1], boost::make_tuple(2.4f, 4)); BOOST_CHECK_EQUAL(host_vector[2], boost::make_tuple(4.6f, 6)); BOOST_CHECK_EQUAL(host_vector[3], boost::make_tuple(6.8f, 8)); // duplicate each element in the tuple compute::vector<boost::tuple<int, int, float, float> > doubled_vector(4, context); compute::transform( input_vector.begin(), input_vector.end(), doubled_vector.begin(), make_tuple(get<0>(_1), get<0>(_1), get<1>(_1), get<1>(_1)), queue ); std::vector<boost::tuple<int, int, float, float> > doubled_host_vector(4); compute::copy_n(doubled_vector.begin(), 4, doubled_host_vector.begin(), queue); BOOST_CHECK_EQUAL(doubled_host_vector[0], boost::make_tuple(2, 2, 1.2f, 1.2f)); BOOST_CHECK_EQUAL(doubled_host_vector[1], boost::make_tuple(4, 4, 2.4f, 2.4f)); BOOST_CHECK_EQUAL(doubled_host_vector[2], boost::make_tuple(6, 6, 4.6f, 4.6f)); BOOST_CHECK_EQUAL(doubled_host_vector[3], boost::make_tuple(8, 8, 6.8f, 6.8f)); } BOOST_AUTO_TEST_CASE(bind_lambda_function) { using compute::placeholders::_1; namespace lambda = compute::lambda; int data[] = { 1, 2, 3, 4 }; compute::vector<int> vector(data, data + 4, queue); compute::transform( vector.begin(), vector.end(), vector.begin(), compute::bind(lambda::_1 * lambda::_2, _1, 2), queue ); CHECK_RANGE_EQUAL(int, 4, vector, (2, 4, 6, 8)); } BOOST_AUTO_TEST_CASE(lambda_function_with_uint_args) { compute::uint_ host_data[] = { 1, 3, 5, 7, 9 }; compute::vector<compute::uint_> device_vector(host_data, host_data + 5, queue); using boost::compute::lambda::clamp; using compute::lambda::_1; compute::transform( device_vector.begin(), device_vector.end(), device_vector.begin(), clamp(_1, compute::uint_(4), compute::uint_(6)), queue ); CHECK_RANGE_EQUAL(compute::uint_, 5, device_vector, (4, 4, 5, 6, 6)); } BOOST_AUTO_TEST_CASE(lambda_function_with_short_args) { compute::short_ host_data[] = { 1, 3, 5, 7, 9 }; compute::vector<compute::short_> device_vector(host_data, host_data + 5, queue); using boost::compute::lambda::clamp; using compute::lambda::_1; compute::transform( device_vector.begin(), device_vector.end(), device_vector.begin(), clamp(_1, compute::short_(4), compute::short_(6)), queue ); CHECK_RANGE_EQUAL(compute::short_, 5, device_vector, (4, 4, 5, 6, 6)); } BOOST_AUTO_TEST_CASE(lambda_function_with_uchar_args) { compute::uchar_ host_data[] = { 1, 3, 5, 7, 9 }; compute::vector<compute::uchar_> device_vector(host_data, host_data + 5, queue); using boost::compute::lambda::clamp; using compute::lambda::_1; compute::transform( device_vector.begin(), device_vector.end(), device_vector.begin(), clamp(_1, compute::uchar_(4), compute::uchar_(6)), queue ); CHECK_RANGE_EQUAL(compute::uchar_, 5, device_vector, (4, 4, 5, 6, 6)); } BOOST_AUTO_TEST_CASE(lambda_function_with_char_args) { compute::char_ host_data[] = { 1, 3, 5, 7, 9 }; compute::vector<compute::char_> device_vector(host_data, host_data + 5, queue); using boost::compute::lambda::clamp; using compute::lambda::_1; compute::transform( device_vector.begin(), device_vector.end(), device_vector.begin(), clamp(_1, compute::char_(4), compute::char_(6)), queue ); CHECK_RANGE_EQUAL(compute::char_, 5, device_vector, (4, 4, 5, 6, 6)); } BOOST_AUTO_TEST_SUITE_END()
ea5a7e0a0c944e46fe89b4eb406d0f3d04e25b9c
5566f1a42e38c1c4405af9b8e382ae56a9857f50
/ESP8266/Arduino_C_Sketchs/WiFiScan.ino
4b36cd0ae3b5e01dac341d56d21fa90cbc43897c
[ "MIT" ]
permissive
vslinuxdotnet/makerpt
a83f7860b497649522174cdbd9040783f4cc383b
27339b48c444211e5ec105dcd95ad36f9af51775
refs/heads/master
2021-05-06T01:43:34.801485
2018-10-06T18:44:18
2018-10-06T18:44:18
114,459,040
0
0
null
null
null
null
UTF-8
C++
false
false
1,010
ino
//Vasco Santos //MakerPT #include "ESP8266WiFi.h" void setup() { Serial.begin(9600); // Set WiFi to station mode and disconnect from an AP if it was previously connected WiFi.mode(WIFI_STA); WiFi.disconnect(); delay(100); Serial.println("Setup done"); } void loop() { Serial.println("scan start"); // WiFi.scanNetworks will return the number of networks found int n = WiFi.scanNetworks(); Serial.println("scan done"); if (n == 0) Serial.println("no networks found"); else { Serial.print(n); Serial.println(" networks found"); for (int i = 0; i < n; ++i) { // Print SSID and RSSI for each network found Serial.print(i + 1); Serial.print(": "); Serial.print(WiFi.SSID(i)); Serial.print(" ("); Serial.print(WiFi.RSSI(i)); Serial.print(")"); Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*"); delay(10); } } Serial.println(""); // Wait a bit before scanning again delay(5000); }
432fbd3eb356981eec7ebe117809d35b2297e578
a6bf8a0d3689ec4b95cd95e583cd23fd569cbe1c
/lab5/prog9.cpp
6c2f0808ab649df8932d7aedb2cfd0344a1c14c8
[]
no_license
thevaliantthird/CS-154-2020-21-Spring-Semester-IIT-B
25efdb76ea29a39dd13808ed498f18a5ce089d43
141ca610b3e989f4ef57b1f37f2ef2a2cecaa75b
refs/heads/main
2023-06-19T21:19:51.455142
2021-07-18T13:51:04
2021-07-18T13:51:04
387,186,962
0
0
null
null
null
null
UTF-8
C++
false
false
819
cpp
#include<iostream> using namespace std; class A { int x; public: A(int v) {x=v;} virtual void f() {cout << x << "A::f\n"; g(); } virtual void g() { cout << x << "A::g\n";} }; class B : public A { int y; public: B(int v):A(v+10) {y=v;} virtual void f(){cout << y << "B::f\n";} virtual void g() {cout << y << "B::g\n";} }; class C : public B { int z; public: C(int v):B(v+10) {z=v;} virtual void f(){cout << z << "C::f\n";} virtual void k() {f(); cout << z << "C::k\n"; f(); } }; int main (int argc, char *argv[]) { A *ap; B *bp; C *cp; cp = new C(10); cp->f(); cp->g(); cp->k(); bp = new B(100); bp->f(); bp->g(); delete bp; bp=cp; bp->f(); bp->g(); ap = new A(200); ap->f(); ap->g(); delete ap; ap=bp; ap->f(); ap->g(); }
94c1d5df9c01cf2b7cbf4530dccb641a3c47271d
c0ed761d0e8b72f7d4f013d9b579fdd13f6804ab
/WickedEngine/wiSceneSystem.cpp
ab6496f41c2cfccd7029ac481e70b7b103088396
[ "Zlib", "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Alan-Baylis/WickedEngine
daf036f2ea74e4d854e4244ba91a93c9a51a6309
56ef3e29d3aa25c7f722978b605064035b014c57
refs/heads/master
2020-04-11T02:35:06.702429
2018-12-11T20:21:03
2018-12-11T20:21:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
57,416
cpp
#include "wiSceneSystem.h" #include "wiMath.h" #include "wiTextureHelper.h" #include "wiResourceManager.h" #include "wiPhysicsEngine.h" #include "wiArchive.h" #include "wiRenderer.h" #include "wiJobSystem.h" #include "wiSpinlock.h" #include <functional> #include <unordered_map> using namespace wiECS; using namespace wiGraphicsTypes; namespace wiSceneSystem { XMFLOAT3 TransformComponent::GetPosition() const { return *((XMFLOAT3*)&world._41); } XMFLOAT4 TransformComponent::GetRotation() const { XMFLOAT4 rotation; XMStoreFloat4(&rotation, GetRotationV()); return rotation; } XMFLOAT3 TransformComponent::GetScale() const { XMFLOAT3 scale; XMStoreFloat3(&scale, GetScaleV()); return scale; } XMVECTOR TransformComponent::GetPositionV() const { return XMLoadFloat3((XMFLOAT3*)&world._41); } XMVECTOR TransformComponent::GetRotationV() const { XMVECTOR S, R, T; XMMatrixDecompose(&S, &R, &T, XMLoadFloat4x4(&world)); return R; } XMVECTOR TransformComponent::GetScaleV() const { XMVECTOR S, R, T; XMMatrixDecompose(&S, &R, &T, XMLoadFloat4x4(&world)); return S; } void TransformComponent::UpdateTransform() { if (IsDirty()) { SetDirty(false); XMVECTOR S_local = XMLoadFloat3(&scale_local); XMVECTOR R_local = XMLoadFloat4(&rotation_local); XMVECTOR T_local = XMLoadFloat3(&translation_local); XMMATRIX W = XMMatrixScalingFromVector(S_local) * XMMatrixRotationQuaternion(R_local) * XMMatrixTranslationFromVector(T_local); XMStoreFloat4x4(&world, W); } } void TransformComponent::UpdateTransform_Parented(const TransformComponent& parent, const XMFLOAT4X4& inverseParentBindMatrix) { XMMATRIX W; // Normally, every transform would be NOT dirty at this point, but... if (parent.IsDirty()) { // If parent is dirty, that means parent ws updated for some reason (anim system, physics or user...) // So we need to propagate the new parent matrix down to this child SetDirty(); W = XMLoadFloat4x4(&world); } else { // If it is not dirty, then we still need to propagate parent's matrix to this, // because every transform is marked as NOT dirty at the end of transform update system // but we look up the local matrix instead, because world matrix might contain // results from previous run of the hierarchy system... XMVECTOR S_local = XMLoadFloat3(&scale_local); XMVECTOR R_local = XMLoadFloat4(&rotation_local); XMVECTOR T_local = XMLoadFloat3(&translation_local); W = XMMatrixScalingFromVector(S_local) * XMMatrixRotationQuaternion(R_local) * XMMatrixTranslationFromVector(T_local); } XMMATRIX W_parent = XMLoadFloat4x4(&parent.world); XMMATRIX B = XMLoadFloat4x4(&inverseParentBindMatrix); W = W * B * W_parent; XMStoreFloat4x4(&world, W); } void TransformComponent::ApplyTransform() { SetDirty(); XMVECTOR S, R, T; XMMatrixDecompose(&S, &R, &T, XMLoadFloat4x4(&world)); XMStoreFloat3(&scale_local, S); XMStoreFloat4(&rotation_local, R); XMStoreFloat3(&translation_local, T); } void TransformComponent::ClearTransform() { SetDirty(); scale_local = XMFLOAT3(1, 1, 1); rotation_local = XMFLOAT4(0, 0, 0, 1); translation_local = XMFLOAT3(0, 0, 0); } void TransformComponent::Translate(const XMFLOAT3& value) { SetDirty(); translation_local.x += value.x; translation_local.y += value.y; translation_local.z += value.z; } void TransformComponent::RotateRollPitchYaw(const XMFLOAT3& value) { SetDirty(); // This needs to be handled a bit differently XMVECTOR quat = XMLoadFloat4(&rotation_local); XMVECTOR x = XMQuaternionRotationRollPitchYaw(value.x, 0, 0); XMVECTOR y = XMQuaternionRotationRollPitchYaw(0, value.y, 0); XMVECTOR z = XMQuaternionRotationRollPitchYaw(0, 0, value.z); quat = XMQuaternionMultiply(x, quat); quat = XMQuaternionMultiply(quat, y); quat = XMQuaternionMultiply(z, quat); quat = XMQuaternionNormalize(quat); XMStoreFloat4(&rotation_local, quat); } void TransformComponent::Rotate(const XMFLOAT4& quaternion) { SetDirty(); XMVECTOR result = XMQuaternionMultiply(XMLoadFloat4(&rotation_local), XMLoadFloat4(&quaternion)); result = XMQuaternionNormalize(result); XMStoreFloat4(&rotation_local, result); } void TransformComponent::Scale(const XMFLOAT3& value) { SetDirty(); scale_local.x *= value.x; scale_local.y *= value.y; scale_local.z *= value.z; } void TransformComponent::MatrixTransform(const XMFLOAT4X4& matrix) { MatrixTransform(XMLoadFloat4x4(&matrix)); } void TransformComponent::MatrixTransform(const XMMATRIX& matrix) { SetDirty(); XMVECTOR S; XMVECTOR R; XMVECTOR T; XMMatrixDecompose(&S, &R, &T, matrix); S = XMLoadFloat3(&scale_local) * S; R = XMQuaternionMultiply(XMLoadFloat4(&rotation_local), R); T = XMLoadFloat3(&translation_local) + T; XMStoreFloat3(&scale_local, S); XMStoreFloat4(&rotation_local, R); XMStoreFloat3(&translation_local, T); } void TransformComponent::Lerp(const TransformComponent& a, const TransformComponent& b, float t) { SetDirty(); XMVECTOR aS, aR, aT; XMMatrixDecompose(&aS, &aR, &aT, XMLoadFloat4x4(&a.world)); XMVECTOR bS, bR, bT; XMMatrixDecompose(&bS, &bR, &bT, XMLoadFloat4x4(&b.world)); XMVECTOR S = XMVectorLerp(aS, bS, t); XMVECTOR R = XMQuaternionSlerp(aR, bR, t); XMVECTOR T = XMVectorLerp(aT, bT, t); XMStoreFloat3(&scale_local, S); XMStoreFloat4(&rotation_local, R); XMStoreFloat3(&translation_local, T); } void TransformComponent::CatmullRom(const TransformComponent& a, const TransformComponent& b, const TransformComponent& c, const TransformComponent& d, float t) { SetDirty(); XMVECTOR aS, aR, aT; XMMatrixDecompose(&aS, &aR, &aT, XMLoadFloat4x4(&a.world)); XMVECTOR bS, bR, bT; XMMatrixDecompose(&bS, &bR, &bT, XMLoadFloat4x4(&b.world)); XMVECTOR cS, cR, cT; XMMatrixDecompose(&cS, &cR, &cT, XMLoadFloat4x4(&c.world)); XMVECTOR dS, dR, dT; XMMatrixDecompose(&dS, &dR, &dT, XMLoadFloat4x4(&d.world)); XMVECTOR T = XMVectorCatmullRom(aT, bT, cT, dT, t); // Catmull-rom has issues with full rotation for quaternions (todo): XMVECTOR R = XMVectorCatmullRom(aR, bR, cR, dR, t); R = XMQuaternionNormalize(R); XMVECTOR S = XMVectorCatmullRom(aS, bS, cS, dS, t); XMStoreFloat3(&translation_local, T); XMStoreFloat4(&rotation_local, R); XMStoreFloat3(&scale_local, S); } Texture2D* MaterialComponent::GetBaseColorMap() const { if (baseColorMap != nullptr) { return baseColorMap; } return wiTextureHelper::getWhite(); } Texture2D* MaterialComponent::GetNormalMap() const { return normalMap; //if (normalMap != nullptr) //{ // return normalMap; //} //return wiTextureHelper::getNormalMapDefault(); } Texture2D* MaterialComponent::GetSurfaceMap() const { if (surfaceMap != nullptr) { return surfaceMap; } return wiTextureHelper::getWhite(); } Texture2D* MaterialComponent::GetDisplacementMap() const { if (displacementMap != nullptr) { return displacementMap; } return wiTextureHelper::getWhite(); } void MeshComponent::CreateRenderData() { GraphicsDevice* device = wiRenderer::GetDevice(); HRESULT hr; // Create index buffer GPU data: { uint32_t counter = 0; uint8_t stride; void* gpuIndexData; if (GetIndexFormat() == INDEXFORMAT_32BIT) { gpuIndexData = new uint32_t[indices.size()]; stride = sizeof(uint32_t); for (auto& x : indices) { static_cast<uint32_t*>(gpuIndexData)[counter++] = static_cast<uint32_t>(x); } } else { gpuIndexData = new uint16_t[indices.size()]; stride = sizeof(uint16_t); for (auto& x : indices) { static_cast<uint16_t*>(gpuIndexData)[counter++] = static_cast<uint16_t>(x); } } GPUBufferDesc bd; bd.Usage = USAGE_IMMUTABLE; bd.CPUAccessFlags = 0; bd.BindFlags = BIND_INDEX_BUFFER | BIND_SHADER_RESOURCE; bd.MiscFlags = 0; bd.StructureByteStride = stride; bd.Format = GetIndexFormat() == INDEXFORMAT_16BIT ? FORMAT_R16_UINT : FORMAT_R32_UINT; SubresourceData InitData; InitData.pSysMem = gpuIndexData; bd.ByteWidth = (UINT)(stride * indices.size()); indexBuffer.reset(new GPUBuffer); hr = device->CreateBuffer(&bd, &InitData, indexBuffer.get()); assert(SUCCEEDED(hr)); SAFE_DELETE_ARRAY(gpuIndexData); } XMFLOAT3 _min = XMFLOAT3(FLT_MAX, FLT_MAX, FLT_MAX); XMFLOAT3 _max = XMFLOAT3(-FLT_MAX, -FLT_MAX, -FLT_MAX); // vertexBuffer - POSITION + NORMAL + SUBSETINDEX: { std::vector<uint8_t> vertex_subsetindices(vertex_positions.size()); uint32_t subsetCounter = 0; for (auto& subset : subsets) { for (uint32_t i = 0; i < subset.indexCount; ++i) { uint32_t index = indices[subset.indexOffset + i]; vertex_subsetindices[index] = subsetCounter; } subsetCounter++; } std::vector<Vertex_POS> vertices(vertex_positions.size()); for (size_t i = 0; i < vertices.size(); ++i) { const XMFLOAT3& pos = vertex_positions[i]; XMFLOAT3& nor = vertex_normals.empty() ? XMFLOAT3(1, 1, 1) : vertex_normals[i]; XMStoreFloat3(&nor, XMVector3Normalize(XMLoadFloat3(&nor))); uint32_t subsetIndex = vertex_subsetindices[i]; vertices[i].FromFULL(pos, nor, subsetIndex); _min = wiMath::Min(_min, pos); _max = wiMath::Max(_max, pos); } GPUBufferDesc bd; bd.Usage = USAGE_DEFAULT; bd.CPUAccessFlags = 0; bd.BindFlags = BIND_VERTEX_BUFFER | BIND_SHADER_RESOURCE; bd.MiscFlags = RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS; bd.ByteWidth = (UINT)(sizeof(Vertex_POS) * vertices.size()); SubresourceData InitData; InitData.pSysMem = vertices.data(); vertexBuffer_POS.reset(new GPUBuffer); hr = device->CreateBuffer(&bd, &InitData, vertexBuffer_POS.get()); assert(SUCCEEDED(hr)); } aabb = AABB(_min, _max); // skinning buffers: if (!vertex_boneindices.empty()) { std::vector<Vertex_BON> vertices(vertex_boneindices.size()); for (size_t i = 0; i < vertices.size(); ++i) { XMFLOAT4& wei = vertex_boneweights[i]; // normalize bone weights float len = wei.x + wei.y + wei.z + wei.w; if (len > 0) { wei.x /= len; wei.y /= len; wei.z /= len; wei.w /= len; } vertices[i].FromFULL(vertex_boneindices[i], wei); } GPUBufferDesc bd; bd.Usage = USAGE_IMMUTABLE; bd.BindFlags = BIND_SHADER_RESOURCE; bd.CPUAccessFlags = 0; bd.MiscFlags = RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS; bd.ByteWidth = (UINT)(sizeof(Vertex_BON) * vertices.size()); SubresourceData InitData; InitData.pSysMem = vertices.data(); vertexBuffer_BON.reset(new GPUBuffer); hr = device->CreateBuffer(&bd, &InitData, vertexBuffer_BON.get()); assert(SUCCEEDED(hr)); bd.Usage = USAGE_DEFAULT; bd.BindFlags = BIND_VERTEX_BUFFER | BIND_UNORDERED_ACCESS | BIND_SHADER_RESOURCE; bd.CPUAccessFlags = 0; bd.MiscFlags = RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS; bd.ByteWidth = (UINT)(sizeof(Vertex_POS) * vertex_positions.size()); streamoutBuffer_POS.reset(new GPUBuffer); hr = device->CreateBuffer(&bd, nullptr, streamoutBuffer_POS.get()); assert(SUCCEEDED(hr)); } // vertexBuffer - TEXCOORDS if(!vertex_texcoords.empty()) { std::vector<Vertex_TEX> vertices(vertex_texcoords.size()); for (size_t i = 0; i < vertices.size(); ++i) { vertices[i].FromFULL(vertex_texcoords[i]); } GPUBufferDesc bd; bd.Usage = USAGE_IMMUTABLE; bd.CPUAccessFlags = 0; bd.BindFlags = BIND_VERTEX_BUFFER | BIND_SHADER_RESOURCE; bd.MiscFlags = 0; bd.StructureByteStride = sizeof(Vertex_TEX); bd.ByteWidth = (UINT)(bd.StructureByteStride * vertices.size()); bd.Format = Vertex_TEX::FORMAT; SubresourceData InitData; InitData.pSysMem = vertices.data(); vertexBuffer_TEX.reset(new GPUBuffer); hr = device->CreateBuffer(&bd, &InitData, vertexBuffer_TEX.get()); assert(SUCCEEDED(hr)); } // vertexBuffer - COLORS if (!vertex_colors.empty()) { GPUBufferDesc bd; bd.Usage = USAGE_IMMUTABLE; bd.CPUAccessFlags = 0; bd.BindFlags = BIND_VERTEX_BUFFER | BIND_SHADER_RESOURCE; bd.MiscFlags = 0; bd.StructureByteStride = sizeof(uint32_t); bd.ByteWidth = (UINT)(bd.StructureByteStride * vertex_colors.size()); bd.Format = FORMAT_R8G8B8A8_UNORM; SubresourceData InitData; InitData.pSysMem = vertex_colors.data(); vertexBuffer_COL.reset(new GPUBuffer); hr = device->CreateBuffer(&bd, &InitData, vertexBuffer_COL.get()); assert(SUCCEEDED(hr)); } // vertexBuffer - ATLAS if (!vertex_atlas.empty()) { std::vector<Vertex_TEX> vertices(vertex_atlas.size()); for (size_t i = 0; i < vertices.size(); ++i) { vertices[i].FromFULL(vertex_atlas[i]); } GPUBufferDesc bd; bd.Usage = USAGE_IMMUTABLE; bd.CPUAccessFlags = 0; bd.BindFlags = BIND_VERTEX_BUFFER | BIND_SHADER_RESOURCE; bd.MiscFlags = 0; bd.StructureByteStride = sizeof(Vertex_TEX); bd.ByteWidth = (UINT)(bd.StructureByteStride * vertices.size()); bd.Format = Vertex_TEX::FORMAT; SubresourceData InitData; InitData.pSysMem = vertices.data(); vertexBuffer_ATL.reset(new GPUBuffer); hr = device->CreateBuffer(&bd, &InitData, vertexBuffer_ATL.get()); assert(SUCCEEDED(hr)); } // vertexBuffer_PRE will be created on demand later! } void MeshComponent::ComputeNormals(bool smooth) { // Start recalculating normals: if (smooth) { // Compute smooth surface normals: // 1.) Zero normals, they will be averaged later for (size_t i = 0; i < vertex_normals.size(); i++) { vertex_normals[i] = XMFLOAT3(0, 0, 0); } // 2.) Find identical vertices by POSITION, accumulate face normals for (size_t i = 0; i < vertex_positions.size(); i++) { XMFLOAT3& v_search_pos = vertex_positions[i]; for (size_t ind = 0; ind < indices.size() / 3; ++ind) { uint32_t i0 = indices[ind * 3 + 0]; uint32_t i1 = indices[ind * 3 + 1]; uint32_t i2 = indices[ind * 3 + 2]; XMFLOAT3& v0 = vertex_positions[i0]; XMFLOAT3& v1 = vertex_positions[i1]; XMFLOAT3& v2 = vertex_positions[i2]; bool match_pos0 = fabs(v_search_pos.x - v0.x) < FLT_EPSILON && fabs(v_search_pos.y - v0.y) < FLT_EPSILON && fabs(v_search_pos.z - v0.z) < FLT_EPSILON; bool match_pos1 = fabs(v_search_pos.x - v1.x) < FLT_EPSILON && fabs(v_search_pos.y - v1.y) < FLT_EPSILON && fabs(v_search_pos.z - v1.z) < FLT_EPSILON; bool match_pos2 = fabs(v_search_pos.x - v2.x) < FLT_EPSILON && fabs(v_search_pos.y - v2.y) < FLT_EPSILON && fabs(v_search_pos.z - v2.z) < FLT_EPSILON; if (match_pos0 || match_pos1 || match_pos2) { XMVECTOR U = XMLoadFloat3(&v2) - XMLoadFloat3(&v0); XMVECTOR V = XMLoadFloat3(&v1) - XMLoadFloat3(&v0); XMVECTOR N = XMVector3Cross(U, V); N = XMVector3Normalize(N); XMFLOAT3 normal; XMStoreFloat3(&normal, N); vertex_normals[i].x += normal.x; vertex_normals[i].y += normal.y; vertex_normals[i].z += normal.z; } } } // 3.) Find duplicated vertices by POSITION and TEXCOORD and SUBSET and remove them: for (auto& subset : subsets) { for (uint32_t i = 0; i < subset.indexCount - 1; i++) { uint32_t ind0 = indices[subset.indexOffset + (uint32_t)i]; const XMFLOAT3& p0 = vertex_positions[ind0]; const XMFLOAT3& n0 = vertex_normals[ind0]; const XMFLOAT2& t0 = vertex_texcoords[ind0]; for (uint32_t j = i + 1; j < subset.indexCount; j++) { uint32_t ind1 = indices[subset.indexOffset + (uint32_t)j]; if (ind1 == ind0) { continue; } const XMFLOAT3& p1 = vertex_positions[ind1]; const XMFLOAT3& n1 = vertex_normals[ind1]; const XMFLOAT2& t1 = vertex_texcoords[ind1]; bool duplicated_pos = fabs(p0.x - p1.x) < FLT_EPSILON && fabs(p0.y - p1.y) < FLT_EPSILON && fabs(p0.z - p1.z) < FLT_EPSILON; bool duplicated_tex = fabs(t0.x - t1.x) < FLT_EPSILON && fabs(t0.y - t1.y) < FLT_EPSILON; if (duplicated_pos && duplicated_tex) { // Erase vertices[ind1] because it is a duplicate: if (ind1 < vertex_positions.size()) { vertex_positions.erase(vertex_positions.begin() + ind1); } if (ind1 < vertex_normals.size()) { vertex_normals.erase(vertex_normals.begin() + ind1); } if (ind1 < vertex_texcoords.size()) { vertex_texcoords.erase(vertex_texcoords.begin() + ind1); } if (ind1 < vertex_boneindices.size()) { vertex_boneindices.erase(vertex_boneindices.begin() + ind1); } if (ind1 < vertex_boneweights.size()) { vertex_boneweights.erase(vertex_boneweights.begin() + ind1); } // The vertices[ind1] was removed, so each index after that needs to be updated: for (auto& index : indices) { if (index > ind1 && index > 0) { index--; } else if (index == ind1) { index = ind0; } } } } } } } else { // Compute hard surface normals: std::vector<uint32_t> newIndexBuffer; std::vector<XMFLOAT3> newPositionsBuffer; std::vector<XMFLOAT3> newNormalsBuffer; std::vector<XMFLOAT2> newTexcoordsBuffer; std::vector<XMUINT4> newBoneIndicesBuffer; std::vector<XMFLOAT4> newBoneWeightsBuffer; for (size_t face = 0; face < indices.size() / 3; face++) { uint32_t i0 = indices[face * 3 + 0]; uint32_t i1 = indices[face * 3 + 1]; uint32_t i2 = indices[face * 3 + 2]; XMFLOAT3& p0 = vertex_positions[i0]; XMFLOAT3& p1 = vertex_positions[i1]; XMFLOAT3& p2 = vertex_positions[i2]; XMVECTOR U = XMLoadFloat3(&p2) - XMLoadFloat3(&p0); XMVECTOR V = XMLoadFloat3(&p1) - XMLoadFloat3(&p0); XMVECTOR N = XMVector3Cross(U, V); N = XMVector3Normalize(N); XMFLOAT3 normal; XMStoreFloat3(&normal, N); newPositionsBuffer.push_back(p0); newPositionsBuffer.push_back(p1); newPositionsBuffer.push_back(p2); newNormalsBuffer.push_back(normal); newNormalsBuffer.push_back(normal); newNormalsBuffer.push_back(normal); newTexcoordsBuffer.push_back(vertex_texcoords[i0]); newTexcoordsBuffer.push_back(vertex_texcoords[i1]); newTexcoordsBuffer.push_back(vertex_texcoords[i2]); if (!vertex_boneindices.empty()) { newBoneIndicesBuffer.push_back(vertex_boneindices[i0]); newBoneIndicesBuffer.push_back(vertex_boneindices[i1]); newBoneIndicesBuffer.push_back(vertex_boneindices[i2]); } if (!vertex_boneweights.empty()) { newBoneWeightsBuffer.push_back(vertex_boneweights[i0]); newBoneWeightsBuffer.push_back(vertex_boneweights[i1]); newBoneWeightsBuffer.push_back(vertex_boneweights[i2]); } newIndexBuffer.push_back(static_cast<uint32_t>(newIndexBuffer.size())); newIndexBuffer.push_back(static_cast<uint32_t>(newIndexBuffer.size())); newIndexBuffer.push_back(static_cast<uint32_t>(newIndexBuffer.size())); } // For hard surface normals, we created a new mesh in the previous loop through faces, so swap data: vertex_positions = newPositionsBuffer; vertex_normals = newNormalsBuffer; vertex_texcoords = newTexcoordsBuffer; if (!vertex_boneindices.empty()) { vertex_boneindices = newBoneIndicesBuffer; } if (!vertex_boneweights.empty()) { vertex_boneweights = newBoneWeightsBuffer; } indices = newIndexBuffer; } // Restore subsets: CreateRenderData(); } void MeshComponent::FlipCulling() { for (size_t face = 0; face < indices.size() / 3; face++) { uint32_t i0 = indices[face * 3 + 0]; uint32_t i1 = indices[face * 3 + 1]; uint32_t i2 = indices[face * 3 + 2]; indices[face * 3 + 0] = i0; indices[face * 3 + 1] = i2; indices[face * 3 + 2] = i1; } CreateRenderData(); } void MeshComponent::FlipNormals() { for (auto& normal : vertex_normals) { normal.x *= -1; normal.y *= -1; normal.z *= -1; } CreateRenderData(); } void MeshComponent::Recenter() { XMFLOAT3 center = aabb.getCenter(); for (auto& pos : vertex_positions) { pos.x -= center.x; pos.y -= center.y; pos.z -= center.z; } CreateRenderData(); } void MeshComponent::RecenterToBottom() { XMFLOAT3 center = aabb.getCenter(); center.y -= aabb.getHalfWidth().y; for (auto& pos : vertex_positions) { pos.x -= center.x; pos.y -= center.y; pos.z -= center.z; } CreateRenderData(); } void ObjectComponent::ClearLightmap() { lightmapWidth = 0; lightmapHeight = 0; globalLightMapMulAdd = XMFLOAT4(0, 0, 0, 0); lightmapIterationCount = 0; lightmapTextureData.clear(); SetLightmapRenderRequest(false); } void ObjectComponent::SaveLightmap() { if (lightmap == nullptr) { return; } GraphicsDevice* device = wiRenderer::GetDevice(); HRESULT hr; TextureDesc desc = lightmap->GetDesc(); UINT data_count = desc.Width * desc.Height; UINT data_stride = device->GetFormatStride(desc.Format); UINT data_size = data_count * data_stride; lightmapWidth = desc.Width; lightmapHeight = desc.Height; lightmapTextureData.clear(); lightmapTextureData.resize(data_size); Texture2D* stagingTex = nullptr; TextureDesc staging_desc = desc; staging_desc.Usage = USAGE_STAGING; staging_desc.CPUAccessFlags = CPU_ACCESS_READ; staging_desc.BindFlags = 0; staging_desc.MiscFlags = 0; hr = device->CreateTexture2D(&staging_desc, nullptr, &stagingTex); assert(SUCCEEDED(hr)); bool download_success = device->DownloadResource(lightmap, stagingTex, lightmapTextureData.data(), GRAPHICSTHREAD_IMMEDIATE); assert(download_success); delete stagingTex; } FORMAT ObjectComponent::GetLightmapFormat() { uint32_t stride = (uint32_t)lightmapTextureData.size() / lightmapWidth / lightmapHeight; switch (stride) { case 4: return FORMAT_R8G8B8A8_UNORM; case 8: return FORMAT_R16G16B16A16_FLOAT; case 16: return FORMAT_R32G32B32A32_FLOAT; } return FORMAT_UNKNOWN; } void SoftBodyPhysicsComponent::CreateFromMesh(const MeshComponent& mesh) { // Create a mapping that maps unique vertex positions to all vertex indices that share that. Unique vertex positions will make up the physics mesh: std::unordered_map<size_t, uint32_t> uniquePositions; graphicsToPhysicsVertexMapping.resize(mesh.vertex_positions.size()); physicsToGraphicsVertexMapping.clear(); weights.clear(); for (size_t i = 0; i < mesh.vertex_positions.size(); ++i) { const XMFLOAT3& position = mesh.vertex_positions[i]; size_t hashes[] = { std::hash<float>{}(position.x), std::hash<float>{}(position.y), std::hash<float>{}(position.z), }; size_t vertexHash = (((hashes[0] ^ (hashes[1] << 1) >> 1) ^ (hashes[2] << 1)) >> 1); if (uniquePositions.count(vertexHash) == 0) { uniquePositions[vertexHash] = (uint32_t)physicsToGraphicsVertexMapping.size(); physicsToGraphicsVertexMapping.push_back((uint32_t)i); } graphicsToPhysicsVertexMapping[i] = uniquePositions[vertexHash]; } weights.resize(physicsToGraphicsVertexMapping.size()); std::fill(weights.begin(), weights.end(), 1.0f); } void CameraComponent::CreatePerspective(float newWidth, float newHeight, float newNear, float newFar, float newFOV) { zNearP = newNear; zFarP = newFar; width = newWidth; height = newHeight; fov = newFOV; UpdateProjection(); UpdateCamera(); } void CameraComponent::UpdateProjection() { XMStoreFloat4x4(&Projection, XMMatrixPerspectiveFovLH(fov, width / height, zFarP, zNearP)); // reverse zbuffer! XMStoreFloat4x4(&realProjection, XMMatrixPerspectiveFovLH(fov, width / height, zNearP, zFarP)); // normal zbuffer! } void CameraComponent::UpdateCamera() { SetDirty(false); XMVECTOR _Eye = XMLoadFloat3(&Eye); XMVECTOR _At = XMLoadFloat3(&At); XMVECTOR _Up = XMLoadFloat3(&Up); XMMATRIX _V = XMMatrixLookToLH(_Eye, _At, _Up); XMStoreFloat4x4(&View, _V); XMMATRIX _P = XMLoadFloat4x4(&Projection); XMMATRIX _InvP = XMMatrixInverse(nullptr, _P); XMStoreFloat4x4(&InvProjection, _InvP); XMMATRIX _VP = XMMatrixMultiply(_V, _P); XMStoreFloat4x4(&View, _V); XMStoreFloat4x4(&VP, _VP); XMStoreFloat4x4(&InvView, XMMatrixInverse(nullptr, _V)); XMStoreFloat4x4(&InvVP, XMMatrixInverse(nullptr, _VP)); XMStoreFloat4x4(&Projection, _P); XMStoreFloat4x4(&InvProjection, XMMatrixInverse(nullptr, _P)); frustum.ConstructFrustum(zFarP, realProjection, View); } void CameraComponent::TransformCamera(const TransformComponent& transform) { SetDirty(); XMVECTOR S, R, T; XMMatrixDecompose(&S, &R, &T, XMLoadFloat4x4(&transform.world)); XMVECTOR _Eye = T; XMVECTOR _At = XMVectorSet(0, 0, 1, 0); XMVECTOR _Up = XMVectorSet(0, 1, 0, 0); XMMATRIX _Rot = XMMatrixRotationQuaternion(R); _At = XMVector3TransformNormal(_At, _Rot); _Up = XMVector3TransformNormal(_Up, _Rot); XMStoreFloat3x3(&rotationMatrix, _Rot); XMMATRIX _V = XMMatrixLookToLH(_Eye, _At, _Up); XMStoreFloat4x4(&View, _V); XMStoreFloat3(&Eye, _Eye); XMStoreFloat3(&At, _At); XMStoreFloat3(&Up, _Up); } void CameraComponent::Reflect(const XMFLOAT4& plane) { XMVECTOR _Eye = XMLoadFloat3(&Eye); XMVECTOR _At = XMLoadFloat3(&At); XMVECTOR _Up = XMLoadFloat3(&Up); XMMATRIX _Ref = XMMatrixReflect(XMLoadFloat4(&plane)); _Eye = XMVector3Transform(_Eye, _Ref); _At = XMVector3TransformNormal(_At, _Ref); _Up = XMVector3TransformNormal(_Up, _Ref); XMStoreFloat3(&Eye, _Eye); XMStoreFloat3(&At, _At); XMStoreFloat3(&Up, _Up); UpdateCamera(); } void Scene::Update(float dt) { RunPreviousFrameTransformUpdateSystem(transforms, prev_transforms); RunAnimationUpdateSystem(animations, transforms, dt); wiPhysicsEngine::RunPhysicsUpdateSystem(weather, armatures, transforms, meshes, objects, rigidbodies, softbodies, dt); RunTransformUpdateSystem(transforms); wiJobSystem::Wait(); // dependecies RunHierarchyUpdateSystem(hierarchy, transforms, layers); RunArmatureUpdateSystem(transforms, armatures); RunMaterialUpdateSystem(materials, dt); RunImpostorUpdateSystem(impostors); wiJobSystem::Wait(); // dependecies RunObjectUpdateSystem(prev_transforms, transforms, meshes, materials, objects, aabb_objects, impostors, softbodies, bounds, waterPlane); RunCameraUpdateSystem(transforms, cameras); RunDecalUpdateSystem(transforms, materials, aabb_decals, decals); RunProbeUpdateSystem(transforms, aabb_probes, probes); RunForceUpdateSystem(transforms, forces); RunLightUpdateSystem(transforms, aabb_lights, lights); RunParticleUpdateSystem(transforms, meshes, emitters, hairs, dt); wiJobSystem::Wait(); // dependecies RunWeatherUpdateSystem(weathers, lights, weather); } void Scene::Clear() { names.Clear(); layers.Clear(); transforms.Clear(); prev_transforms.Clear(); hierarchy.Clear(); materials.Clear(); meshes.Clear(); impostors.Clear(); objects.Clear(); aabb_objects.Clear(); rigidbodies.Clear(); softbodies.Clear(); armatures.Clear(); lights.Clear(); aabb_lights.Clear(); cameras.Clear(); probes.Clear(); aabb_probes.Clear(); forces.Clear(); decals.Clear(); aabb_decals.Clear(); animations.Clear(); emitters.Clear(); hairs.Clear(); weathers.Clear(); } void Scene::Merge(Scene& other) { names.Merge(other.names); layers.Merge(other.layers); transforms.Merge(other.transforms); prev_transforms.Merge(other.prev_transforms); hierarchy.Merge(other.hierarchy); materials.Merge(other.materials); meshes.Merge(other.meshes); impostors.Merge(other.impostors); objects.Merge(other.objects); aabb_objects.Merge(other.aabb_objects); rigidbodies.Merge(other.rigidbodies); softbodies.Merge(other.softbodies); armatures.Merge(other.armatures); lights.Merge(other.lights); aabb_lights.Merge(other.aabb_lights); cameras.Merge(other.cameras); probes.Merge(other.probes); aabb_probes.Merge(other.aabb_probes); forces.Merge(other.forces); decals.Merge(other.decals); aabb_decals.Merge(other.aabb_decals); animations.Merge(other.animations); emitters.Merge(other.emitters); hairs.Merge(other.hairs); weathers.Merge(other.weathers); bounds = AABB::Merge(bounds, other.bounds); } size_t Scene::CountEntities() const { // Entities are unique within a ComponentManager, so the most populated ComponentManager // will actually give us how many entities there are in the scene size_t entityCount = 0; entityCount = max(entityCount, names.GetCount()); entityCount = max(entityCount, layers.GetCount()); entityCount = max(entityCount, transforms.GetCount()); entityCount = max(entityCount, prev_transforms.GetCount()); entityCount = max(entityCount, hierarchy.GetCount()); entityCount = max(entityCount, materials.GetCount()); entityCount = max(entityCount, meshes.GetCount()); entityCount = max(entityCount, impostors.GetCount()); entityCount = max(entityCount, objects.GetCount()); entityCount = max(entityCount, aabb_objects.GetCount()); entityCount = max(entityCount, rigidbodies.GetCount()); entityCount = max(entityCount, softbodies.GetCount()); entityCount = max(entityCount, armatures.GetCount()); entityCount = max(entityCount, lights.GetCount()); entityCount = max(entityCount, aabb_lights.GetCount()); entityCount = max(entityCount, cameras.GetCount()); entityCount = max(entityCount, probes.GetCount()); entityCount = max(entityCount, aabb_probes.GetCount()); entityCount = max(entityCount, forces.GetCount()); entityCount = max(entityCount, decals.GetCount()); entityCount = max(entityCount, aabb_decals.GetCount()); entityCount = max(entityCount, animations.GetCount()); entityCount = max(entityCount, emitters.GetCount()); entityCount = max(entityCount, hairs.GetCount()); return entityCount; } void Scene::Entity_Remove(Entity entity) { names.Remove(entity); layers.Remove(entity); transforms.Remove(entity); prev_transforms.Remove(entity); hierarchy.Remove_KeepSorted(entity); materials.Remove(entity); meshes.Remove(entity); impostors.Remove(entity); objects.Remove(entity); aabb_objects.Remove(entity); rigidbodies.Remove(entity); softbodies.Remove(entity); armatures.Remove(entity); lights.Remove(entity); aabb_lights.Remove(entity); cameras.Remove(entity); probes.Remove(entity); aabb_probes.Remove(entity); forces.Remove(entity); decals.Remove(entity); aabb_decals.Remove(entity); animations.Remove(entity); emitters.Remove(entity); hairs.Remove(entity); weathers.Remove(entity); } Entity Scene::Entity_FindByName(const std::string& name) { for (size_t i = 0; i < names.GetCount(); ++i) { if (names[i] == name) { return names.GetEntity(i); } } return INVALID_ENTITY; } Entity Scene::Entity_Duplicate(Entity entity) { wiArchive archive; // First write the entity to staging area: archive.SetReadModeAndResetPos(false); Entity_Serialize(archive, entity, 0); // Then deserialize with a unique seed: archive.SetReadModeAndResetPos(true); uint32_t seed = wiRandom::getRandom(1, INT_MAX); return Entity_Serialize(archive, entity, seed, false); } Entity Scene::Entity_CreateMaterial( const std::string& name ) { Entity entity = CreateEntity(); names.Create(entity) = name; materials.Create(entity); return entity; } Entity Scene::Entity_CreateObject( const std::string& name ) { Entity entity = CreateEntity(); names.Create(entity) = name; layers.Create(entity); transforms.Create(entity); prev_transforms.Create(entity); aabb_objects.Create(entity); objects.Create(entity); return entity; } Entity Scene::Entity_CreateMesh( const std::string& name ) { Entity entity = CreateEntity(); names.Create(entity) = name; meshes.Create(entity); return entity; } Entity Scene::Entity_CreateLight( const std::string& name, const XMFLOAT3& position, const XMFLOAT3& color, float energy, float range) { Entity entity = CreateEntity(); names.Create(entity) = name; layers.Create(entity); TransformComponent& transform = transforms.Create(entity); transform.Translate(position); transform.UpdateTransform(); aabb_lights.Create(entity).createFromHalfWidth(position, XMFLOAT3(range, range, range)); LightComponent& light = lights.Create(entity); light.energy = energy; light.range = range; light.fov = XM_PIDIV4; light.color = color; light.SetType(LightComponent::POINT); return entity; } Entity Scene::Entity_CreateForce( const std::string& name, const XMFLOAT3& position ) { Entity entity = CreateEntity(); names.Create(entity) = name; layers.Create(entity); TransformComponent& transform = transforms.Create(entity); transform.Translate(position); transform.UpdateTransform(); ForceFieldComponent& force = forces.Create(entity); force.gravity = 0; force.range = 0; force.type = ENTITY_TYPE_FORCEFIELD_POINT; return entity; } Entity Scene::Entity_CreateEnvironmentProbe( const std::string& name, const XMFLOAT3& position ) { Entity entity = CreateEntity(); names.Create(entity) = name; layers.Create(entity); TransformComponent& transform = transforms.Create(entity); transform.Translate(position); transform.UpdateTransform(); aabb_probes.Create(entity); probes.Create(entity); return entity; } Entity Scene::Entity_CreateDecal( const std::string& name, const std::string& textureName, const std::string& normalMapName ) { Entity entity = CreateEntity(); names.Create(entity) = name; layers.Create(entity); transforms.Create(entity); aabb_decals.Create(entity); decals.Create(entity); MaterialComponent& material = materials.Create(entity); if (!textureName.empty()) { material.baseColorMapName = textureName; material.baseColorMap = (Texture2D*)wiResourceManager::GetGlobal().add(material.baseColorMapName); } if (!normalMapName.empty()) { material.normalMapName = normalMapName; material.normalMap = (Texture2D*)wiResourceManager::GetGlobal().add(material.normalMapName); } return entity; } Entity Scene::Entity_CreateCamera( const std::string& name, float width, float height, float nearPlane, float farPlane, float fov ) { Entity entity = CreateEntity(); names.Create(entity) = name; layers.Create(entity); transforms.Create(entity); CameraComponent& camera = cameras.Create(entity); camera.CreatePerspective(width, height, nearPlane, farPlane, fov); return entity; } Entity Scene::Entity_CreateEmitter( const std::string& name, const XMFLOAT3& position ) { Entity entity = CreateEntity(); names.Create(entity) = name; emitters.Create(entity).count = 10; TransformComponent& transform = transforms.Create(entity); transform.Translate(position); transform.UpdateTransform(); materials.Create(entity).blendMode = BLENDMODE_ALPHA; return entity; } Entity Scene::Entity_CreateHair( const std::string& name, const XMFLOAT3& position ) { Entity entity = CreateEntity(); names.Create(entity) = name; hairs.Create(entity); TransformComponent& transform = transforms.Create(entity); transform.Translate(position); transform.UpdateTransform(); materials.Create(entity); return entity; } void Scene::Component_Attach(Entity entity, Entity parent) { assert(entity != parent); if (hierarchy.Contains(entity)) { Component_Detach(entity); } // Add a new hierarchy node to the end of container: hierarchy.Create(entity).parentID = parent; // If this entity was already a part of a tree however, we must move it before children: for (size_t i = 0; i < hierarchy.GetCount(); ++i) { const HierarchyComponent& parent = hierarchy[i]; if (parent.parentID == entity) { hierarchy.MoveLastTo(i); break; } } // Re-query parent after potential MoveLastTo(), because it invalidates references: HierarchyComponent& parentcomponent = *hierarchy.GetComponent(entity); TransformComponent* transform_parent = transforms.GetComponent(parent); if (transform_parent != nullptr) { // Save the parent's inverse worldmatrix: XMStoreFloat4x4(&parentcomponent.world_parent_inverse_bind, XMMatrixInverse(nullptr, XMLoadFloat4x4(&transform_parent->world))); TransformComponent* transform_child = transforms.GetComponent(entity); if (transform_child != nullptr) { // Child updated immediately, to that it can be immediately attached to afterwards: transform_child->UpdateTransform_Parented(*transform_parent, parentcomponent.world_parent_inverse_bind); } } LayerComponent* layer_child = layers.GetComponent(entity); if (layer_child != nullptr) { // Save the initial layermask of the child so that it can be restored if detached: parentcomponent.layerMask_bind = layer_child->GetLayerMask(); } } void Scene::Component_Detach(Entity entity) { const HierarchyComponent* parent = hierarchy.GetComponent(entity); if (parent != nullptr) { TransformComponent* transform = transforms.GetComponent(entity); if (transform != nullptr) { transform->ApplyTransform(); } LayerComponent* layer = layers.GetComponent(entity); if (layer != nullptr) { layer->layerMask = parent->layerMask_bind; } hierarchy.Remove_KeepSorted(entity); } } void Scene::Component_DetachChildren(Entity parent) { for (size_t i = 0; i < hierarchy.GetCount(); ) { if (hierarchy[i].parentID == parent) { Entity entity = hierarchy.GetEntity(i); Component_Detach(entity); } else { ++i; } } } const uint32_t small_subtask_groupsize = 1024; void RunPreviousFrameTransformUpdateSystem( const ComponentManager<TransformComponent>& transforms, ComponentManager<PreviousFrameTransformComponent>& prev_transforms ) { wiJobSystem::Dispatch((uint32_t)prev_transforms.GetCount(), small_subtask_groupsize, [&](wiJobDispatchArgs args) { PreviousFrameTransformComponent& prev_transform = prev_transforms[args.jobIndex]; Entity entity = prev_transforms.GetEntity(args.jobIndex); const TransformComponent& transform = *transforms.GetComponent(entity); prev_transform.world_prev = transform.world; }); } void RunAnimationUpdateSystem( ComponentManager<AnimationComponent>& animations, ComponentManager<TransformComponent>& transforms, float dt ) { for (size_t i = 0; i < animations.GetCount(); ++i) { AnimationComponent& animation = animations[i]; if (!animation.IsPlaying() && animation.timer == 0.0f) { continue; } for (const AnimationComponent::AnimationChannel& channel : animation.channels) { assert(channel.samplerIndex < animation.samplers.size()); const AnimationComponent::AnimationSampler& sampler = animation.samplers[channel.samplerIndex]; int keyLeft = 0; int keyRight = 0; if (sampler.keyframe_times.back() < animation.timer) { // Rightmost keyframe is already outside animation, so just snap to last keyframe: keyLeft = keyRight = (int)sampler.keyframe_times.size() - 1; } else { // Search for the right keyframe (greater/equal to anim time): while (sampler.keyframe_times[keyRight++] < animation.timer) {} keyRight--; // Left keyframe is just near right: keyLeft = max(0, keyRight - 1); } float left = sampler.keyframe_times[keyLeft]; TransformComponent& transform = *transforms.GetComponent(channel.target); if (sampler.mode == AnimationComponent::AnimationSampler::Mode::STEP || keyLeft == keyRight) { // Nearest neighbor method (snap to left): switch (channel.path) { case AnimationComponent::AnimationChannel::Path::TRANSLATION: { assert(sampler.keyframe_data.size() == sampler.keyframe_times.size() * 3); transform.translation_local = ((const XMFLOAT3*)sampler.keyframe_data.data())[keyLeft]; } break; case AnimationComponent::AnimationChannel::Path::ROTATION: { assert(sampler.keyframe_data.size() == sampler.keyframe_times.size() * 4); transform.rotation_local = ((const XMFLOAT4*)sampler.keyframe_data.data())[keyLeft]; } break; case AnimationComponent::AnimationChannel::Path::SCALE: { assert(sampler.keyframe_data.size() == sampler.keyframe_times.size() * 3); transform.scale_local = ((const XMFLOAT3*)sampler.keyframe_data.data())[keyLeft]; } break; } } else { // Linear interpolation method: float right = sampler.keyframe_times[keyRight]; float t = (animation.timer - left) / (right - left); switch (channel.path) { case AnimationComponent::AnimationChannel::Path::TRANSLATION: { assert(sampler.keyframe_data.size() == sampler.keyframe_times.size() * 3); const XMFLOAT3* data = (const XMFLOAT3*)sampler.keyframe_data.data(); XMVECTOR vLeft = XMLoadFloat3(&data[keyLeft]); XMVECTOR vRight = XMLoadFloat3(&data[keyRight]); XMVECTOR vAnim = XMVectorLerp(vLeft, vRight, t); XMStoreFloat3(&transform.translation_local, vAnim); } break; case AnimationComponent::AnimationChannel::Path::ROTATION: { assert(sampler.keyframe_data.size() == sampler.keyframe_times.size() * 4); const XMFLOAT4* data = (const XMFLOAT4*)sampler.keyframe_data.data(); XMVECTOR vLeft = XMLoadFloat4(&data[keyLeft]); XMVECTOR vRight = XMLoadFloat4(&data[keyRight]); XMVECTOR vAnim = XMQuaternionSlerp(vLeft, vRight, t); vAnim = XMQuaternionNormalize(vAnim); XMStoreFloat4(&transform.rotation_local, vAnim); } break; case AnimationComponent::AnimationChannel::Path::SCALE: { assert(sampler.keyframe_data.size() == sampler.keyframe_times.size() * 3); const XMFLOAT3* data = (const XMFLOAT3*)sampler.keyframe_data.data(); XMVECTOR vLeft = XMLoadFloat3(&data[keyLeft]); XMVECTOR vRight = XMLoadFloat3(&data[keyRight]); XMVECTOR vAnim = XMVectorLerp(vLeft, vRight, t); XMStoreFloat3(&transform.scale_local, vAnim); } break; } } transform.SetDirty(); } if (animation.IsPlaying()) { animation.timer += dt; } if (animation.IsLooped() && animation.timer > animation.end) { animation.timer = animation.start; } } } void RunTransformUpdateSystem(ComponentManager<TransformComponent>& transforms) { wiJobSystem::Dispatch((uint32_t)transforms.GetCount(), small_subtask_groupsize, [&](wiJobDispatchArgs args) { TransformComponent& transform = transforms[args.jobIndex]; transform.UpdateTransform(); }); } void RunHierarchyUpdateSystem( const ComponentManager<HierarchyComponent>& hierarchy, ComponentManager<TransformComponent>& transforms, ComponentManager<LayerComponent>& layers ) { // This needs serialized execution because there are dependencies enforced by component order! for (size_t i = 0; i < hierarchy.GetCount(); ++i) { const HierarchyComponent& parentcomponent = hierarchy[i]; Entity entity = hierarchy.GetEntity(i); TransformComponent* transform_child = transforms.GetComponent(entity); TransformComponent* transform_parent = transforms.GetComponent(parentcomponent.parentID); if (transform_child != nullptr && transform_parent != nullptr) { transform_child->UpdateTransform_Parented(*transform_parent, parentcomponent.world_parent_inverse_bind); } LayerComponent* layer_child = layers.GetComponent(entity); LayerComponent* layer_parent = layers.GetComponent(parentcomponent.parentID); if (layer_child != nullptr && layer_parent != nullptr) { layer_child->layerMask = parentcomponent.layerMask_bind & layer_parent->GetLayerMask(); } } } void RunArmatureUpdateSystem( const ComponentManager<TransformComponent>& transforms, ComponentManager<ArmatureComponent>& armatures ) { wiJobSystem::Dispatch((uint32_t)armatures.GetCount(), 1, [&](wiJobDispatchArgs args) { ArmatureComponent& armature = armatures[args.jobIndex]; if (armature.boneData.size() != armature.boneCollection.size()) { armature.boneData.resize(armature.boneCollection.size()); } XMMATRIX R = XMLoadFloat4x4(&armature.remapMatrix); int boneIndex = 0; for (Entity boneEntity : armature.boneCollection) { const TransformComponent& bone = *transforms.GetComponent(boneEntity); XMMATRIX B = XMLoadFloat4x4(&armature.inverseBindMatrices[boneIndex]); XMMATRIX W = XMLoadFloat4x4(&bone.world); XMMATRIX M = B * W * R; armature.boneData[boneIndex++].Store(M); } }); } void RunMaterialUpdateSystem(ComponentManager<MaterialComponent>& materials, float dt) { wiJobSystem::Dispatch((uint32_t)materials.GetCount(), small_subtask_groupsize, [&](wiJobDispatchArgs args) { MaterialComponent& material = materials[args.jobIndex]; material.texAnimElapsedTime += dt * material.texAnimFrameRate; if (material.texAnimElapsedTime >= 1.0f) { material.texMulAdd.z = fmodf(material.texMulAdd.z + material.texAnimDirection.x, 1); material.texMulAdd.w = fmodf(material.texMulAdd.w + material.texAnimDirection.y, 1); material.texAnimElapsedTime = 0.0f; material.SetDirty(); // will trigger constant buffer update later on } material.engineStencilRef = STENCILREF_DEFAULT; if (material.subsurfaceScattering > 0) { material.engineStencilRef = STENCILREF_SKIN; } }); } void RunImpostorUpdateSystem(ComponentManager<ImpostorComponent>& impostors) { wiJobSystem::Dispatch((uint32_t)impostors.GetCount(), 1, [&](wiJobDispatchArgs args) { ImpostorComponent& impostor = impostors[args.jobIndex]; impostor.aabb = AABB(); impostor.instanceMatrices.clear(); }); } void RunObjectUpdateSystem( const ComponentManager<PreviousFrameTransformComponent>& prev_transforms, const ComponentManager<TransformComponent>& transforms, const ComponentManager<MeshComponent>& meshes, const ComponentManager<MaterialComponent>& materials, ComponentManager<ObjectComponent>& objects, ComponentManager<AABB>& aabb_objects, ComponentManager<ImpostorComponent>& impostors, ComponentManager<SoftBodyPhysicsComponent>& softbodies, AABB& sceneBounds, XMFLOAT4& waterPlane ) { assert(objects.GetCount() == aabb_objects.GetCount()); sceneBounds = AABB(); // Instead of Dispatching, this will be one big job, because there is contention for several resources (sceneBounds, waterPlane, impostors) wiJobSystem::Execute([&] { for (size_t i = 0; i < objects.GetCount(); ++i) { ObjectComponent& object = objects[i]; AABB& aabb = aabb_objects[i]; aabb = AABB(); object.rendertypeMask = 0; object.SetDynamic(false); object.SetCastShadow(false); object.SetImpostorPlacement(false); object.SetRequestPlanarReflection(false); if (object.meshID != INVALID_ENTITY) { Entity entity = objects.GetEntity(i); const MeshComponent* mesh = meshes.GetComponent(object.meshID); // These will only be valid for a single frame: object.transform_index = (int)transforms.GetIndex(entity); object.prev_transform_index = (int)prev_transforms.GetIndex(entity); const TransformComponent& transform = transforms[object.transform_index]; if (mesh != nullptr) { aabb = mesh->aabb.get(transform.world); // This is instance bounding box matrix: XMFLOAT4X4 meshMatrix; XMStoreFloat4x4(&meshMatrix, mesh->aabb.getAsBoxMatrix() * XMLoadFloat4x4(&transform.world)); // We need sometimes the center of the instance bounding box, not the transform position (which can be outside the bounding box) object.center = *((XMFLOAT3*)&meshMatrix._41); if (mesh->IsSkinned() || mesh->IsDynamic()) { object.SetDynamic(true); } for (auto& subset : mesh->subsets) { const MaterialComponent* material = materials.GetComponent(subset.materialID); if (material != nullptr) { if (material->IsTransparent()) { object.rendertypeMask |= RENDERTYPE_TRANSPARENT; } else { object.rendertypeMask |= RENDERTYPE_OPAQUE; } if (material->IsWater()) { object.rendertypeMask |= RENDERTYPE_TRANSPARENT | RENDERTYPE_WATER; } if (material->HasPlanarReflection()) { object.SetRequestPlanarReflection(true); XMVECTOR P = transform.GetPositionV(); XMVECTOR N = XMVectorSet(0, 1, 0, 0); N = XMVector3TransformNormal(N, XMLoadFloat4x4(&transform.world)); XMVECTOR _refPlane = XMPlaneFromPointNormal(P, N); XMStoreFloat4(&waterPlane, _refPlane); } object.SetCastShadow(material->IsCastingShadow()); } } ImpostorComponent* impostor = impostors.GetComponent(object.meshID); if (impostor != nullptr) { object.SetImpostorPlacement(true); object.impostorSwapDistance = impostor->swapInDistance; object.impostorFadeThresholdRadius = aabb.getRadius(); impostor->aabb = AABB::Merge(impostor->aabb, aabb); impostor->fadeThresholdRadius = object.impostorFadeThresholdRadius; impostor->instanceMatrices.push_back(meshMatrix); } SoftBodyPhysicsComponent* softBody = softbodies.GetComponent(object.meshID); if (softBody != nullptr) { softBody->_flags |= SoftBodyPhysicsComponent::SAFE_TO_REGISTER; // this will be registered as soft body in the next frame softBody->worldMatrix = transform.world; if (wiPhysicsEngine::IsEnabled() && softBody->physicsobject != nullptr) { // If physics engine is enabled and this object was registered, it will update soft body vertices in world space, so after that they no longer need to be transformed: object.transform_index = -1; object.prev_transform_index = -1; // mesh aabb will be used for soft bodies aabb = mesh->aabb; } } sceneBounds = AABB::Merge(sceneBounds, aabb); } } } }); } void RunCameraUpdateSystem( const ComponentManager<TransformComponent>& transforms, ComponentManager<CameraComponent>& cameras ) { wiJobSystem::Dispatch((uint32_t)cameras.GetCount(), small_subtask_groupsize, [&](wiJobDispatchArgs args) { CameraComponent& camera = cameras[args.jobIndex]; Entity entity = cameras.GetEntity(args.jobIndex); const TransformComponent* transform = transforms.GetComponent(entity); if (transform != nullptr) { camera.TransformCamera(*transform); } camera.UpdateCamera(); }); } void RunDecalUpdateSystem( const ComponentManager<TransformComponent>& transforms, const ComponentManager<MaterialComponent>& materials, ComponentManager<AABB>& aabb_decals, ComponentManager<DecalComponent>& decals ) { assert(decals.GetCount() == aabb_decals.GetCount()); wiJobSystem::Dispatch((uint32_t)decals.GetCount(), small_subtask_groupsize, [&](wiJobDispatchArgs args) { DecalComponent& decal = decals[args.jobIndex]; Entity entity = decals.GetEntity(args.jobIndex); const TransformComponent& transform = *transforms.GetComponent(entity); decal.world = transform.world; XMMATRIX W = XMLoadFloat4x4(&decal.world); XMVECTOR front = XMVectorSet(0, 0, 1, 0); front = XMVector3TransformNormal(front, W); XMStoreFloat3(&decal.front, front); XMVECTOR S, R, T; XMMatrixDecompose(&S, &R, &T, W); XMStoreFloat3(&decal.position, T); XMFLOAT3 scale; XMStoreFloat3(&scale, S); decal.range = max(scale.x, max(scale.y, scale.z)) * 2; AABB& aabb = aabb_decals[args.jobIndex]; aabb.createFromHalfWidth(XMFLOAT3(0, 0, 0), XMFLOAT3(1, 1, 1)); aabb = aabb.get(transform.world); const MaterialComponent& material = *materials.GetComponent(entity); decal.color = material.baseColor; decal.emissive = material.emissive; decal.texture = material.GetBaseColorMap(); decal.normal = material.GetNormalMap(); }); } void RunProbeUpdateSystem( const ComponentManager<TransformComponent>& transforms, ComponentManager<AABB>& aabb_probes, ComponentManager<EnvironmentProbeComponent>& probes ) { assert(probes.GetCount() == aabb_probes.GetCount()); wiJobSystem::Dispatch((uint32_t)probes.GetCount(), small_subtask_groupsize, [&](wiJobDispatchArgs args) { EnvironmentProbeComponent& probe = probes[args.jobIndex]; Entity entity = probes.GetEntity(args.jobIndex); const TransformComponent& transform = *transforms.GetComponent(entity); probe.position = transform.GetPosition(); XMMATRIX W = XMLoadFloat4x4(&transform.world); XMStoreFloat4x4(&probe.inverseMatrix, XMMatrixInverse(nullptr, W)); XMVECTOR S, R, T; XMMatrixDecompose(&S, &R, &T, W); XMFLOAT3 scale; XMStoreFloat3(&scale, S); probe.range = max(scale.x, max(scale.y, scale.z)) * 2; AABB& aabb = aabb_probes[args.jobIndex]; aabb.createFromHalfWidth(XMFLOAT3(0, 0, 0), XMFLOAT3(1, 1, 1)); aabb = aabb.get(transform.world); }); } void RunForceUpdateSystem( const ComponentManager<TransformComponent>& transforms, ComponentManager<ForceFieldComponent>& forces ) { wiJobSystem::Dispatch((uint32_t)forces.GetCount(), small_subtask_groupsize, [&](wiJobDispatchArgs args) { ForceFieldComponent& force = forces[args.jobIndex]; Entity entity = forces.GetEntity(args.jobIndex); const TransformComponent& transform = *transforms.GetComponent(entity); force.position = transform.GetPosition(); XMStoreFloat3(&force.direction, XMVector3Normalize(XMVector3TransformNormal(XMVectorSet(0, -1, 0, 0), XMLoadFloat4x4(&transform.world)))); }); } void RunLightUpdateSystem( const ComponentManager<TransformComponent>& transforms, ComponentManager<AABB>& aabb_lights, ComponentManager<LightComponent>& lights ) { assert(lights.GetCount() == aabb_lights.GetCount()); wiJobSystem::Dispatch((uint32_t)lights.GetCount(), small_subtask_groupsize, [&](wiJobDispatchArgs args) { LightComponent& light = lights[args.jobIndex]; Entity entity = lights.GetEntity(args.jobIndex); const TransformComponent& transform = *transforms.GetComponent(entity); AABB& aabb = aabb_lights[args.jobIndex]; XMMATRIX W = XMLoadFloat4x4(&transform.world); XMVECTOR S, R, T; XMMatrixDecompose(&S, &R, &T, W); XMStoreFloat3(&light.position, T); XMStoreFloat4(&light.rotation, R); XMStoreFloat3(&light.direction, XMVector3TransformNormal(XMVectorSet(0, 1, 0, 0), W)); switch (light.type) { case LightComponent::DIRECTIONAL: aabb.createFromHalfWidth(wiRenderer::GetCamera().Eye, XMFLOAT3(10000, 10000, 10000)); break; case LightComponent::SPOT: aabb.createFromHalfWidth(light.position, XMFLOAT3(light.range, light.range, light.range)); break; case LightComponent::POINT: aabb.createFromHalfWidth(light.position, XMFLOAT3(light.range, light.range, light.range)); break; case LightComponent::SPHERE: case LightComponent::DISC: case LightComponent::RECTANGLE: case LightComponent::TUBE: XMStoreFloat3(&light.right, XMVector3TransformNormal(XMVectorSet(-1, 0, 0, 0), W)); XMStoreFloat3(&light.front, XMVector3TransformNormal(XMVectorSet(0, 0, -1, 0), W)); // area lights have no bounds, just like directional lights (todo: but they should have real bounds) aabb.createFromHalfWidth(wiRenderer::GetCamera().Eye, XMFLOAT3(10000, 10000, 10000)); break; } }); } void RunParticleUpdateSystem( const ComponentManager<TransformComponent>& transforms, const ComponentManager<MeshComponent>& meshes, ComponentManager<wiEmittedParticle>& emitters, ComponentManager<wiHairParticle>& hairs, float dt ) { wiJobSystem::Dispatch((uint32_t)emitters.GetCount(), small_subtask_groupsize, [&](wiJobDispatchArgs args) { wiEmittedParticle& emitter = emitters[args.jobIndex]; emitter.Update(dt); }); wiJobSystem::Dispatch((uint32_t)hairs.GetCount(), small_subtask_groupsize, [&](wiJobDispatchArgs args) { wiHairParticle& hair = hairs[args.jobIndex]; Entity entity = hairs.GetEntity(args.jobIndex); const TransformComponent& transform = *transforms.GetComponent(entity); hair.world = transform.world; if (hair.meshID != INVALID_ENTITY) { const MeshComponent* mesh = meshes.GetComponent(hair.meshID); if (mesh != nullptr) { XMFLOAT3 min = mesh->aabb.getMin(); XMFLOAT3 max = mesh->aabb.getMax(); max.x += hair.length; max.y += hair.length; max.z += hair.length; min.x -= hair.length; min.y -= hair.length; min.z -= hair.length; hair.aabb = AABB(min, max); hair.aabb = hair.aabb.get(hair.world); } } }); } void RunWeatherUpdateSystem( const ComponentManager<WeatherComponent>& weathers, const ComponentManager<LightComponent>& lights, WeatherComponent& weather) { if (weathers.GetCount() > 0) { weather = weathers[0]; } for (size_t i = 0; i < lights.GetCount(); ++i) { const LightComponent& light = lights[i]; if (light.GetType() == LightComponent::DIRECTIONAL) { weather.sunColor = light.color; weather.sunDirection = light.direction; } } } }
55fbd7faee83398c1afb4820e0cfb78ddad88dba
9cd8b42d4ea67deb6ec075a3da25d09e2a421544
/LuaKitProject/LuakitPod/LuakitPod/include/single_thread_task_runner.h
1c9630323fcc2db6a3538786ba2f05e743a014c7
[ "MIT" ]
permissive
andrewvmail/Luakit
de0c6f0d2655e09e63b998df2ca07202b5fbd134
eadbcf0e88fcf922d9b9592bffca9a582b7a236d
refs/heads/master
2023-01-12T23:31:33.773549
2022-12-29T02:58:55
2022-12-29T02:58:55
231,685,876
0
1
MIT
2020-01-04T00:17:27
2020-01-04T00:17:27
null
UTF-8
C++
false
false
1,367
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_SINGLE_THREAD_TASK_RUNNER_H_ #define BASE_SINGLE_THREAD_TASK_RUNNER_H_ #include "base_export.h" #include "sequenced_task_runner.h" namespace base { // A SingleThreadTaskRunner is a SequencedTaskRunner with one more // guarantee; namely, that all tasks are run on a single dedicated // thread. Most use cases require only a SequencedTaskRunner, unless // there is a specific need to run tasks on only a single thread. // // SingleThreadTaskRunner implementations might: // - Post tasks to an existing thread's MessageLoop (see MessageLoopProxy). // - Create their own worker thread and MessageLoop to post tasks to. // - Add tasks to a FIFO and signal to a non-MessageLoop thread for them to // be processed. This allows TaskRunner-oriented code run on threads // running other kinds of message loop, e.g. Jingle threads. class BASE_EXPORT SingleThreadTaskRunner : public SequencedTaskRunner { public: // A more explicit alias to RunsTasksOnCurrentThread(). bool BelongsToCurrentThread() const { return RunsTasksOnCurrentThread(); } protected: virtual ~SingleThreadTaskRunner() {} }; } // namespace base #endif // BASE_SINGLE_THREAD_TASK_RUNNER_H_
b7eabee6793c827b38344695a112c585923395c7
5af80813298c3a2da7f7e3e28adb1b9bcc433878
/skia/src/effects/SkBicubicImageFilter.cpp
6766596b8d2dec425a0e0ff5c19f19fce3db07e3
[]
no_license
damonyan1985/SkCanvas
c250ad47bdd0fa072ca859c6b1242dede2045f95
731ae8abb540382da2e156e8d93373c4563017ea
refs/heads/master
2021-09-10T20:03:51.927207
2018-03-23T02:02:10
2018-03-23T02:02:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,981
cpp
/* * Copyright 2013 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBicubicImageFilter.h" #include "SkBitmap.h" #include "SkColorPriv.h" #include "SkReadBuffer.h" #include "SkWriteBuffer.h" #include "SkMatrix.h" #include "SkRect.h" #include "SkUnPreMultiply.h" #if SK_SUPPORT_GPU #include "effects/GrBicubicEffect.h" #include "GrContext.h" #include "GrTexture.h" #endif #define DS(x) SkDoubleToScalar(x) static const SkScalar gMitchellCoefficients[16] = { DS( 1.0 / 18.0), DS(-9.0 / 18.0), DS( 15.0 / 18.0), DS( -7.0 / 18.0), DS(16.0 / 18.0), DS( 0.0 / 18.0), DS(-36.0 / 18.0), DS( 21.0 / 18.0), DS( 1.0 / 18.0), DS( 9.0 / 18.0), DS( 27.0 / 18.0), DS(-21.0 / 18.0), DS( 0.0 / 18.0), DS( 0.0 / 18.0), DS( -6.0 / 18.0), DS( 7.0 / 18.0), }; SkBicubicImageFilter::SkBicubicImageFilter(const SkSize& scale, const SkScalar coefficients[16], SkImageFilter* input) : INHERITED(input), fScale(scale) { memcpy(fCoefficients, coefficients, sizeof(fCoefficients)); } SkBicubicImageFilter* SkBicubicImageFilter::CreateMitchell(const SkSize& scale, SkImageFilter* input) { return SkNEW_ARGS(SkBicubicImageFilter, (scale, gMitchellCoefficients, input)); } SkBicubicImageFilter::SkBicubicImageFilter(SkReadBuffer& buffer) : INHERITED(1, buffer) { //SkDEBUGCODE(bool success =) buffer.readScalarArray(fCoefficients, 16); //SkASSERT(success); fScale.fWidth = buffer.readScalar(); fScale.fHeight = buffer.readScalar(); buffer.validate(SkScalarIsFinite(fScale.fWidth) && SkScalarIsFinite(fScale.fHeight) && (fScale.fWidth >= 0) && (fScale.fHeight >= 0)); } void SkBicubicImageFilter::flatten(SkWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); buffer.writeScalarArray(fCoefficients, 16); buffer.writeScalar(fScale.fWidth); buffer.writeScalar(fScale.fHeight); } SkBicubicImageFilter::~SkBicubicImageFilter() { } inline SkPMColor cubicBlend(const SkScalar c[16], SkScalar t, SkPMColor c0, SkPMColor c1, SkPMColor c2, SkPMColor c3) { SkScalar t2 = t * t, t3 = t2 * t; SkScalar cc[4]; // FIXME: For the fractx case, this should be refactored out of this function. cc[0] = c[0] + SkScalarMul(c[1], t) + SkScalarMul(c[2], t2) + SkScalarMul(c[3], t3); cc[1] = c[4] + SkScalarMul(c[5], t) + SkScalarMul(c[6], t2) + SkScalarMul(c[7], t3); cc[2] = c[8] + SkScalarMul(c[9], t) + SkScalarMul(c[10], t2) + SkScalarMul(c[11], t3); cc[3] = c[12] + SkScalarMul(c[13], t) + SkScalarMul(c[14], t2) + SkScalarMul(c[15], t3); SkScalar a = SkScalarClampMax(SkScalarMul(cc[0], SkGetPackedA32(c0)) + SkScalarMul(cc[1], SkGetPackedA32(c1)) + SkScalarMul(cc[2], SkGetPackedA32(c2)) + SkScalarMul(cc[3], SkGetPackedA32(c3)), 255); SkScalar r = SkScalarMul(cc[0], SkGetPackedR32(c0)) + SkScalarMul(cc[1], SkGetPackedR32(c1)) + SkScalarMul(cc[2], SkGetPackedR32(c2)) + SkScalarMul(cc[3], SkGetPackedR32(c3)); SkScalar g = SkScalarMul(cc[0], SkGetPackedG32(c0)) + SkScalarMul(cc[1], SkGetPackedG32(c1)) + SkScalarMul(cc[2], SkGetPackedG32(c2)) + SkScalarMul(cc[3], SkGetPackedG32(c3)); SkScalar b = SkScalarMul(cc[0], SkGetPackedB32(c0)) + SkScalarMul(cc[1], SkGetPackedB32(c1)) + SkScalarMul(cc[2], SkGetPackedB32(c2)) + SkScalarMul(cc[3], SkGetPackedB32(c3)); return SkPackARGB32(SkScalarRoundToInt(a), SkScalarRoundToInt(SkScalarClampMax(r, a)), SkScalarRoundToInt(SkScalarClampMax(g, a)), SkScalarRoundToInt(SkScalarClampMax(b, a))); } bool SkBicubicImageFilter::onFilterImage(Proxy* proxy, const SkBitmap& source, const Context& ctx, SkBitmap* result, SkIPoint* offset) const { SkBitmap src = source; SkIPoint srcOffset = SkIPoint::Make(0, 0); if (getInput(0) && !getInput(0)->filterImage(proxy, source, ctx, &src, &srcOffset)) { return false; } if (src.colorType() != kN32_SkColorType) { return false; } SkAutoLockPixels alp(src); if (!src.getPixels()) { return false; } SkRect dstRect = SkRect::MakeWH(SkScalarMul(SkIntToScalar(src.width()), fScale.fWidth), SkScalarMul(SkIntToScalar(src.height()), fScale.fHeight)); SkIRect dstIRect; dstRect.roundOut(&dstIRect); if (dstIRect.isEmpty()) { return false; } if (!result->allocPixels(src.info().makeWH(dstIRect.width(), dstIRect.height()))) { return false; } SkRect srcRect; src.getBounds(&srcRect); srcRect.offset(SkPoint::Make(SkIntToScalar(srcOffset.fX), SkIntToScalar(srcOffset.fY))); SkMatrix inverse; inverse.setRectToRect(dstRect, srcRect, SkMatrix::kFill_ScaleToFit); inverse.postTranslate(-0.5f, -0.5f); for (int y = dstIRect.fTop; y < dstIRect.fBottom; ++y) { SkPMColor* dptr = result->getAddr32(dstIRect.fLeft, y); for (int x = dstIRect.fLeft; x < dstIRect.fRight; ++x) { SkPoint srcPt, dstPt = SkPoint::Make(SkIntToScalar(x), SkIntToScalar(y)); inverse.mapPoints(&srcPt, &dstPt, 1); SkScalar fractx = srcPt.fX - SkScalarFloorToScalar(srcPt.fX); SkScalar fracty = srcPt.fY - SkScalarFloorToScalar(srcPt.fY); int sx = SkScalarFloorToInt(srcPt.fX); int sy = SkScalarFloorToInt(srcPt.fY); int x0 = SkClampMax(sx - 1, src.width() - 1); int x1 = SkClampMax(sx , src.width() - 1); int x2 = SkClampMax(sx + 1, src.width() - 1); int x3 = SkClampMax(sx + 2, src.width() - 1); int y0 = SkClampMax(sy - 1, src.height() - 1); int y1 = SkClampMax(sy , src.height() - 1); int y2 = SkClampMax(sy + 1, src.height() - 1); int y3 = SkClampMax(sy + 2, src.height() - 1); SkPMColor s00 = *src.getAddr32(x0, y0); SkPMColor s10 = *src.getAddr32(x1, y0); SkPMColor s20 = *src.getAddr32(x2, y0); SkPMColor s30 = *src.getAddr32(x3, y0); SkPMColor s0 = cubicBlend(fCoefficients, fractx, s00, s10, s20, s30); SkPMColor s01 = *src.getAddr32(x0, y1); SkPMColor s11 = *src.getAddr32(x1, y1); SkPMColor s21 = *src.getAddr32(x2, y1); SkPMColor s31 = *src.getAddr32(x3, y1); SkPMColor s1 = cubicBlend(fCoefficients, fractx, s01, s11, s21, s31); SkPMColor s02 = *src.getAddr32(x0, y2); SkPMColor s12 = *src.getAddr32(x1, y2); SkPMColor s22 = *src.getAddr32(x2, y2); SkPMColor s32 = *src.getAddr32(x3, y2); SkPMColor s2 = cubicBlend(fCoefficients, fractx, s02, s12, s22, s32); SkPMColor s03 = *src.getAddr32(x0, y3); SkPMColor s13 = *src.getAddr32(x1, y3); SkPMColor s23 = *src.getAddr32(x2, y3); SkPMColor s33 = *src.getAddr32(x3, y3); SkPMColor s3 = cubicBlend(fCoefficients, fractx, s03, s13, s23, s33); *dptr++ = cubicBlend(fCoefficients, fracty, s0, s1, s2, s3); } } offset->fX = dstIRect.fLeft; offset->fY = dstIRect.fTop; return true; } /////////////////////////////////////////////////////////////////////////////// #if SK_SUPPORT_GPU bool SkBicubicImageFilter::filterImageGPU(Proxy* proxy, const SkBitmap& src, const Context& ctx, SkBitmap* result, SkIPoint* offset) const { SkBitmap srcBM = src; if (getInput(0) && !getInput(0)->getInputResultGPU(proxy, src, ctx, &srcBM, offset)) { return false; } GrTexture* srcTexture = srcBM.getTexture(); GrContext* context = srcTexture->getContext(); SkRect dstRect = SkRect::MakeWH(srcBM.width() * fScale.fWidth, srcBM.height() * fScale.fHeight); GrTextureDesc desc; desc.fFlags = kRenderTarget_GrTextureFlagBit | kNoStencil_GrTextureFlagBit; desc.fWidth = SkScalarCeilToInt(dstRect.width()); desc.fHeight = SkScalarCeilToInt(dstRect.height()); desc.fConfig = kSkia8888_GrPixelConfig; GrAutoScratchTexture ast(context, desc); SkAutoTUnref<GrTexture> dst(ast.detach()); if (!dst) { return false; } GrContext::AutoRenderTarget art(context, dst->asRenderTarget()); GrPaint paint; paint.addColorEffect(GrBicubicEffect::Create(srcTexture, fCoefficients))->unref(); SkRect srcRect; srcBM.getBounds(&srcRect); context->drawRectToRect(paint, dstRect, srcRect); WrapTexture(dst, desc.fWidth, desc.fHeight, result); return true; } #endif ///////////////////////////////////////////////////////////////////////////////
55dd25e18fd16503f9b51ec205097074d0f92495
322350e9d40b2ae0f49f39a8ec037b354d97e43e
/src/lib.cc
90221b9cf0c38efc33451f28472e620c6a2c9794
[]
no_license
blockspacer/plusher
2372d837c5f1da72241121a8e2771c3114f37bfd
cfa0d887d6b03d536e7ad90ea39ad8e7b6da9256
refs/heads/master
2021-06-27T05:54:11.234087
2017-09-14T08:54:59
2017-09-14T08:54:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,045
cc
#include "lib.h" #include "clang/Frontend/ASTUnit.h" #include "clang/Frontend/FrontendActions.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Tooling/CompilationDatabase.h" #include "clang/Tooling/Refactoring.h" #include "clang/Tooling/Tooling.h" #include "llvm/Support/CommandLine.h" #include "action.h" #include "recipe.h" #undef NDEBUG #include <cassert> using namespace clang; using namespace clang::tooling; using namespace llvm; // Apply a custom category to all command-line options so that they are the // only ones displayed. static llvm::cl::OptionCategory PlusherCategory("plusher options"); static cl::opt<std::string> RecipeFile("recipe", cl::Required, cl::desc("<recipe file>")); // CommonOptionsParser declares HelpMessage with a description of the common // command-line options related to the compilation database and input files. // It's nice to have this help message in all tools. static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); // A help message for this specific tool can be added afterwards. static cl::extrahelp MoreHelp("\nMore help text..."); bool ProcessFiles(int argc, const char **argv) { CommonOptionsParser OptionsParser(argc, argv, PlusherCategory); return ProcessFiles(OptionsParser.getCompilations(), OptionsParser.getSourcePathList(), RecipeFile, nullptr); } bool ProcessFiles(const tooling::CompilationDatabase& compilations, const std::vector<std::string>& source_paths, const std::string& recipe_path, std::string* result) { // Parse and analyze recipe. ClangTool RecipeTool(compilations, ArrayRef<std::string>(recipe_path)); std::vector<std::unique_ptr<ASTUnit>> ASTs; RecipeTool.buildASTs(ASTs); assert(ASTs.size() == 1); Expected<Recipe> recipe = Recipe::create(std::move(ASTs[0])); if (auto err = recipe.takeError()) { handleAllErrors(std::move(err), [&](StringError &err) { llvm::errs() << "Failed to compile recipe: " << err.message() << '\n'; }); return 1; } RefactoringTool Tool(compilations, source_paths); ReplaceActionFactory action_factory(*recipe, &Tool.getReplacements(), result); int code = Tool.run(&action_factory); if (code != 0) return false; if (!result) { // Serialization format is documented in tools/clang/scripts/run_tool.py llvm::outs() << "==== BEGIN EDITS ====\n"; for (const auto& file_repls : Tool.getReplacements()) { for (const auto& r : file_repls.second) { std::string replacement_text = r.getReplacementText().str(); std::replace(replacement_text.begin(), replacement_text.end(), '\n', '\0'); llvm::outs() << "r:::" << r.getFilePath() << ":::" << r.getOffset() << ":::" << r.getLength() << ":::" << replacement_text << "\n"; } } llvm::outs() << "==== END EDITS ====\n"; } return true; }
e0969c165f700e7b218836a694a11a5f21839d89
5f5a2c027c8bffdc6a8ccc9149a8d50468dd2c69
/Library/ClothSolvers/FEMClothMesh.h
38e66921c7579e95bc543fd53cf19dd08c203b2f
[ "MIT" ]
permissive
JackZhouSz/ClothSim
306f5a4b1862789f2f00cfee2939df987babe755
2c2dbef10296777ccf91c5c9ec54f601edc06fbd
refs/heads/main
2023-06-01T21:30:50.739022
2021-06-10T02:07:54
2021-06-10T02:07:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,085
h
#ifndef CLOTH_SIM_FEM_CLOTH_MESH_H #define CLOTH_SIM_FEM_CLOTH_MESH_H #include "TK20Energy.h" #include "TriMesh.h" #include "Utilities.h" namespace ClothSim { class FEMClothMesh : public TriMesh { public: FEMClothMesh(const std::vector<int>& fixedVertices, const double density, const double stretchStiffness, const double shearStiffness, const VecVec2d& restUVs, const TriMesh& inputMesh); FORCE_INLINE void setVertex(int vertIndex, const Vec3d& vertex) override { myStateDirty = true; TriMesh::setVertex(vertIndex, vertex); } FORCE_INLINE bool isVertexFixed(int vertIndex) const { return myFixedVertices[vertIndex]; } FORCE_INLINE void setVertexVelocity(int vertIndex, const Vec3d& velocity) { myVertexVelocities[vertIndex] = velocity; } FORCE_INLINE const Vec3d& vertexVelocity(int vertIndex) const { return myVertexVelocities[vertIndex]; } FORCE_INLINE double vertexMass(int vertIndex) const { return myVertexMasses[vertIndex]; } FORCE_INLINE double stretchStiffness() const { return myStretchStiffness; } FORCE_INLINE double shearStiffness() const { return myShearStiffness; } FORCE_INLINE double triangleRestArea(int triIndex) const { return myRestTriangleAreas[triIndex]; } FORCE_INLINE const Mat6x9d& dFdX(int triIndex) const { return mydFdX[triIndex]; } FORCE_INLINE Mat3x2d computeStretchPk1(int triIndex, bool useAutodiff) const { assert(!myStateDirty); return TK20Energy::computeStretchPK1(myF[triIndex], useAutodiff); } FORCE_INLINE Mat3x2d computeShearPk1(int triIndex, bool useAutodiff) const { assert(!myStateDirty); return TK20Energy::computeShearPK1(myF[triIndex], useAutodiff); } void buildF(); void computeState(); private: VecVec3d myVertexVelocities; std::vector<bool> myFixedVertices; const double myDensity; const double myStretchStiffness; const double myShearStiffness; std::vector<double> myRestTriangleAreas; std::vector<double> myVertexMasses; VecMat2x2d myDmInv; VecMat6x9d mydFdX; VecMat3x2d myF; bool myStateDirty; }; } #endif
ff382f3bc5e990cb6df0542b4b999e562ae72515
01a18ce0a5dd62f523236b391ea5e9cc70d951ff
/GenerateSyntheticData.h
039105debac4a463995317695b7e2b918d0508cf
[]
no_license
ZachJiang/RGBDTracking
451534f1c089ae2a5548a548f7e2120f6668a3c7
5a7f31b318fb597bc8475e33842fe70e18e57f37
refs/heads/master
2020-09-15T09:27:47.122716
2019-12-16T14:52:39
2019-12-16T14:52:39
223,410,242
0
0
null
2019-11-22T13:31:23
2019-11-22T13:31:22
null
UTF-8
C++
false
false
13,383
h
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Plugins * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #ifndef SOFA_RGBDTRACKING_GENERATESYNTHETICDATA_H #define SOFA_RGBDTRACKING_GENERATESYNTHETICDATA_H #include <RGBDTracking/config.h> #include <ImageTypes.h> #include <sofa/core/core.h> #include <sofa/core/behavior/BaseForceField.h> #include <sofa/core/behavior/ForceField.h> #include <sofa/component/interactionforcefield/SpringForceField.h> #include <sofa/core/behavior/MechanicalState.h> #include <sofa/helper/accessor.h> #include <sofa/defaulttype/VecTypes.h> #include <sofa/helper/vector.h> #include <sofa/component/component.h> #include <sofa/helper/OptionsGroup.h> #include <sofa/defaulttype/Mat.h> #include <sofa/defaulttype/Quat.h> #include <sofa/defaulttype/Vec.h> #include <sofa/helper/kdTree.inl> #include <set> #ifdef WIN32 #include <process.h> #else #include <pthread.h> #endif #include <cstdio> #include <stdio.h> #include <stdlib.h> #include <vector> #include <map> #include <iostream> #include <sstream> #include <fstream> #include <math.h> #include <cuda_runtime.h> #include <npp.h> #include <nppi.h> #define GL_GLEXT_PROTOTYPES 1 #define GL4_PROTOTYPES 1 #include <GL/glew.h> #include <GL/freeglut.h> #include <GL/glext.h> #include <GL/glu.h> #include <cuda_gl_interop.h> #include <helper_cuda.h> #include <helper_string.h> #include <opencv/cv.h> #include <opencv2/core/core.hpp> #include <opencv2/features2d/features2d.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/legacy/legacy.hpp> #include <visp/vpIoTools.h> #include <visp/vpImageIo.h> #include <visp/vpParseArgv.h> #include <iostream> #include <string> #include <map> //#include <XnCppWrapper.h> #include <opencv2/opencv.hpp> #include <boost/thread.hpp> #include <sys/times.h> #include "segmentation.h" using namespace std; using namespace cv; namespace sofa { namespace component { namespace forcefield { using helper::vector; using namespace sofa::defaulttype; using cimg_library::CImg; template<class DataTypes, class _ImageTypes> class GenerateSyntheticDataInternalData { public: }; template<class DataTypes, class _ImageTypes> class GenerateSyntheticData : public core::behavior::ForceField<DataTypes> { public: SOFA_CLASS(SOFA_TEMPLATE2(GenerateSyntheticData,DataTypes,_ImageTypes),SOFA_TEMPLATE(core::behavior::ForceField, DataTypes)); typedef core::behavior::ForceField<DataTypes> Inherit; typedef _ImageTypes DepthTypes; typedef typename DepthTypes::T dT; typedef helper::WriteAccessor<Data< DepthTypes > > waDepth; typedef helper::ReadAccessor<Data< DepthTypes > > raDepth; Data< DepthTypes > depthImage; typedef defaulttype::ImageUC ImageTypes; typedef typename ImageTypes::T T; typedef helper::WriteAccessor<Data< ImageTypes > > waImage; typedef helper::ReadAccessor<Data< ImageTypes > > raImage; Data< ImageTypes > image; typedef typename DataTypes::Real Real; typedef typename DataTypes::Coord Coord; typedef typename DataTypes::Deriv Deriv; typedef typename DataTypes::VecCoord VecCoord; typedef typename DataTypes::VecDeriv VecDeriv; typedef Data<typename DataTypes::VecCoord> DataVecCoord; typedef Data<typename DataTypes::VecDeriv> DataVecDeriv; typedef core::behavior::MechanicalState<DataTypes> MechanicalState; enum { N=DataTypes::spatial_dimensions }; typedef defaulttype::Mat<N,N,Real> Mat; typedef typename interactionforcefield::LinearSpring<Real> Spring; typedef helper::fixed_array <unsigned int,3> tri; typedef helper::kdTree<Coord> KDT; typedef typename KDT::distanceSet distanceSet; public: GenerateSyntheticData(core::behavior::MechanicalState<DataTypes> *mm = NULL); virtual ~GenerateSyntheticData(); core::behavior::MechanicalState<DataTypes>* getObject() { return this->mstate; } static std::string templateName(const GenerateSyntheticData<DataTypes,DepthTypes >* = NULL) { return DataTypes::Name()+ std::string(",")+DepthTypes::Name(); } virtual std::string getTemplateName() const { return templateName(this); } const sofa::helper::vector< Spring >& getSprings() const {return springs.getValue();} // -- ForceField interface void reinit(); void init(); void addForce(const core::MechanicalParams* /*mparams*/,DataVecDeriv& f , const DataVecCoord& x , const DataVecDeriv& v); void addDForce(const core::MechanicalParams* mparams ,DataVecDeriv& df , const DataVecDeriv& dx); double getPotentialEnergy(const core::MechanicalParams* ,const DataVecCoord&) const { return m_potentialEnergy; } void addKToMatrix( const core::MechanicalParams* mparams,const sofa::core::behavior::MultiMatrixAccessor* matrix); Real getStiffness() const{ return ks.getValue(); } Real getDamping() const{ return kd.getValue(); } void setStiffness(Real _ks){ ks.setValue(_ks); } void setDamping(Real _kd){ kd.setValue(_kd); } Real getArrowSize() const{return showArrowSize.getValue();} void setArrowSize(float s){showArrowSize.setValue(s);} int getDrawMode() const{return drawMode.getValue();} void setDrawMode(int m){drawMode.setValue(m);} void draw(const core::visual::VisualParams* vparams); // -- Modifiers void clearSprings(int reserve=0) { sofa::helper::vector<Spring>& springs = *this->springs.beginEdit(); springs.clear(); if (reserve) springs.reserve(reserve); this->springs.endEdit(); } void removeSpring(unsigned int idSpring) { if (idSpring >= (this->springs.getValue()).size()) return; sofa::helper::vector<Spring>& springs = *this->springs.beginEdit(); springs.erase(springs.begin() +idSpring ); this->springs.endEdit(); } void addSpring(int m1, SReal ks, SReal kd ) { springs.beginEdit()->push_back(Spring(m1,-1,ks,kd,0)); springs.endEdit(); } void addSpring(const Spring & spring) { springs.beginEdit()->push_back(spring); springs.endEdit(); } protected : void writeImages(); void writeImagesSynth(); void writeData(); vector<Mat> dfdx; VecCoord closestPos; vector<unsigned int> cnt; double m_potentialEnergy; Real min,max; /// Accumulate the spring force and compute and store its stiffness virtual void addSpringForce(double& potentialEnergy, VecDeriv& f,const VecCoord& p,const VecDeriv& v, int i, const Spring& spring); virtual void addSpringForce1(double& potentialEnergy, VecDeriv& f,const VecCoord& p,const VecDeriv& v, int i, const Spring& spring); virtual void addSpringForce2(double& potentialEnergy, VecDeriv& f,const VecCoord& p,const VecDeriv& v, int i, const Spring& spring); virtual void addSpringForce3(double& potentialEnergy, VecDeriv& f,const VecCoord& p,const VecDeriv& v, int i, const Spring& spring); virtual void addSpringForceSoft(double& potentialEnergy, VecDeriv& f,const VecCoord& p,const VecDeriv& v, int i, int j, const Spring& spring, Real weightP); /// Apply the stiffness, i.e. accumulate df given dx virtual void addSpringDForce(VecDeriv& df,const VecDeriv& dx, int i, const Spring& spring, double kFactor, double bFactor); Data<Real> ks; Data<Real> kd; Data<unsigned int> cacheSize; Data<Real> blendingFactor; Data<Real> outlierThreshold; Data<Real> normalThreshold; Data<bool> projectToPlane; Data<bool> rejectBorders; Data<bool> rejectOutsideBbox; defaulttype::BoundingBox targetBbox; Data<sofa::helper::vector<Spring> > springs; VecCoord tpos; // source mesh data Data< helper::vector< tri > > sourceTriangles; Data< VecCoord > sourceNormals; Data< VecCoord > sourceSurfacePositions; Data< VecCoord > sourceSurfaceNormals; Data< VecCoord > sourceSurfaceNormalsM; vector< distanceSet > closestSource; // CacheSize-closest target points from source vector< Real > cacheDist; vector< Real > cacheDist2; VecCoord previousX; // storage for cache acceleration KDT sourceKdTree; vector< bool > sourceBorder; vector< bool > sourceIgnored; // flag ignored vertices vector< bool > sourceVisible; // flag ignored vertices vector< bool > sourceSurface; vector< bool > targetIgnored; // flag ignored vertices vector< bool > targetBackground; // flag ignored vertices void initSource(); // built k-d tree and identify border vertices void initSourceVisible(); // built k-d tree and identify border vertices void initSourceSurface(); // built k-d tree and identify border vertices void updateSourceSurface(); // built k-d tree and identify border vertices std::vector<int> indices; std::vector<int> indicesVisible; std::vector<int> sourceSurfaceMapping; Data< VecCoord > sourceContourPositions; // target point cloud data Data< VecCoord > targetPositions; Data< VecCoord > targetGtPositions; Data< VecCoord > targetNormals; Data< helper::vector< tri > > targetTriangles; vector< distanceSet > closestTarget; // CacheSize-closest source points from target KDT targetKdTree; vector< bool > targetBorder; vector < double > targetWeights; void initTarget(); // built k-d tree and identify border vertices int ind; Data< VecCoord > sourceVisiblePositions; Data<float> showArrowSize; Data<int> drawMode; //Draw Mode: 0=Line - 1=Cylinder - 2=Arrow Data<bool> drawColorMap; Data<bool> theCloserTheStiffer; //SoftKinetic softk; cv::Mat depth; cv::Mat color; cv::Mat color_1; cv::Mat depthMap; cv::Mat silhouetteMap; // Number of iterations int niterations; int nimages; segmentation seg; cv::Mat foreground; bool pcl; bool disp; Data<bool> useContour; Data<bool> useVisible; Data<bool> useRealData; Data<bool> useGroundTruth; Data<bool> generateSynthData; Data<bool> useSensor; int ntargetcontours; std::vector<cv::Mat*> listimg; std::vector<cv::Mat*> listimgseg; std::vector<cv::Mat*> listdepth; std::vector<cv::Mat*> listrtt; std::vector<std::vector<Vec3d>*> listpcd; std::vector<std::vector<bool>*> listvisible; cv::Mat* imgl; cv::Mat* imglsg; cv::Mat* depthl; cv::Mat* rtt; std::vector<Vec3d>* pcd; std::vector<bool>* visible; int iter_im; double timeOverall; double timeTotal; double timeInt; double timei; double errorGroundTruth; ofstream timeFile; void resetSprings(); void detectBorder(vector<bool> &border,const helper::vector< tri > &triangles); void setViewPointData(); void getSourceVisible(); void generateData(const core::MechanicalParams* /*mparams*/,DataVecDeriv& _f , const DataVecCoord& _x , const DataVecDeriv& _v ); // // initialize paramters // float sigma_p2; float sigma_inf; float sigma_factor; float d_02; float *h_A; int pitchA; void findRTfromS(const float* h_Xc, const float* h_Yc, const float* h_S, float* h_R, float* h_t); void printRT(const float* R, const float* t); void cloud2dataC(const pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud, float **X, int &Xsize ); void cloud2data(const pcl::PointCloud<pcl::PointXYZ>::Ptr cloud, float **X, int &Xsize ); }; /*#if defined(SOFA_EXTERN_TEMPLATE) && !defined(GenerateSyntheticData_CPP) #ifndef SOFA_FLOAT extern template class SOFA_RGBDTRACKING_API GenerateSyntheticData<defaulttype::Vec3dTypes>; #endif #ifndef SOFA_DOUBLE extern template class SOFA_RGBDTRACKING_API GenerateSyntheticData<defaulttype::Vec3fTypes>; #endif #*/ } // } // } // namespace sofa #endif
9b8168403041ac53349733b5e31b8299afbeefd8
cb3f4a1fb66e4c61a5044d34bec8685a1dcb12a3
/include/imgui.hpp
17b9fece730e8a1b66488c92848de93ce223bc03
[]
no_license
cmiley/hangman
89f0ce8c67876acc173631c37960b261e661bb65
1fc63088026bab708e14c34848cf165a3fca69da
refs/heads/master
2021-03-27T11:46:29.835118
2018-11-12T23:06:23
2018-11-12T23:06:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
136,426
hpp
// dear imgui, v1.52 WIP // (headers) // See imgui.cpp file for documentation. // See ImGui::ShowTestWindow() in imgui_demo.cpp for demo code. // Read 'Programmer guide' in imgui.cpp for notes on how to setup ImGui in your codebase. // Get latest version at https://github.com/ocornut/imgui #pragma once #if !defined(IMGUI_DISABLE_INCLUDE_IMCONFIG_H) || defined(IMGUI_INCLUDE_IMCONFIG_H) #include "imconfig.hpp" // User-editable configuration file #endif #include <float.h> // FLT_MAX #include <stdarg.h> // va_list #include <stddef.h> // ptrdiff_t, NULL #include <string.h> // memset, memmove, memcpy, strlen, strchr, strcpy, strcmp #define IMGUI_VERSION "1.52 WIP" // Define attributes of all API symbols declarations, e.g. for DLL under Windows. #ifndef IMGUI_API #define IMGUI_API #endif // Define assertion handler. #ifndef IM_ASSERT #include <assert.h> #define IM_ASSERT(_EXPR) assert(_EXPR) #endif // Some compilers support applying printf-style warnings to user functions. #if defined(__clang__) || defined(__GNUC__) #define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1))) #define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0))) #else #define IM_FMTARGS(FMT) #define IM_FMTLIST(FMT) #endif #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wold-style-cast" #endif // Forward declarations struct ImDrawChannel; // Temporary storage for outputting drawing commands out of order, used by ImDrawList::ChannelsSplit() struct ImDrawCmd; // A single draw command within a parent ImDrawList (generally maps to 1 GPU draw call) struct ImDrawData; // All draw command lists required to render the frame struct ImDrawList; // A single draw command list (generally one per window) struct ImDrawVert; // A single vertex (20 bytes by default, override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT) struct ImFont; // Runtime data for a single font within a parent ImFontAtlas struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF/OTF font loader struct ImFontConfig; // Configuration data when adding a font or merging fonts struct ImColor; // Helper functions to create a color that can be converted to either u32 or float4 struct ImGuiIO; // Main configuration and I/O between your application and ImGui struct ImGuiOnceUponAFrame; // Simple helper for running a block of code not more than once a frame, used by IMGUI_ONCE_UPON_A_FRAME macro struct ImGuiStorage; // Simple custom key value storage struct ImGuiStyle; // Runtime data for styling/colors struct ImGuiTextFilter; // Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" struct ImGuiTextBuffer; // Text buffer for logging/accumulating text struct ImGuiTextEditCallbackData; // Shared state of ImGui::InputText() when using custom ImGuiTextEditCallback (rare/advanced use) struct ImGuiSizeConstraintCallbackData;// Structure used to constraint window size in custom ways when using custom ImGuiSizeConstraintCallback (rare/advanced use) struct ImGuiListClipper; // Helper to manually clip large list of items struct ImGuiContext; // ImGui context (opaque) // Typedefs and Enumerations (declared as int for compatibility and to not pollute the top of this file) typedef unsigned int ImU32; // 32-bit unsigned integer (typically used to store packed colors) typedef unsigned int ImGuiID; // unique ID used by widgets (typically hashed from a stack of string) typedef unsigned short ImWchar; // character for keyboard input/display typedef void* ImTextureID; // user data to identify a texture (this is whatever to you want it to be! read the FAQ about ImTextureID in imgui.cpp) typedef int ImGuiCol; // a color identifier for styling // enum ImGuiCol_ typedef int ImGuiStyleVar; // a variable identifier for styling // enum ImGuiStyleVar_ typedef int ImGuiKey; // a key identifier (ImGui-side enum) // enum ImGuiKey_ typedef int ImGuiColorEditFlags; // color edit flags for Color*() // enum ImGuiColorEditFlags_ typedef int ImGuiMouseCursor; // a mouse cursor identifier // enum ImGuiMouseCursor_ typedef int ImGuiWindowFlags; // window flags for Begin*() // enum ImGuiWindowFlags_ typedef int ImGuiCond; // condition flags for Set*() // enum ImGuiCond_ typedef int ImGuiColumnsFlags; // flags for *Columns*() // enum ImGuiColumnsFlags_ typedef int ImGuiInputTextFlags; // flags for InputText*() // enum ImGuiInputTextFlags_ typedef int ImGuiSelectableFlags; // flags for Selectable() // enum ImGuiSelectableFlags_ typedef int ImGuiTreeNodeFlags; // flags for TreeNode*(), Collapsing*() // enum ImGuiTreeNodeFlags_ typedef int (*ImGuiTextEditCallback)(ImGuiTextEditCallbackData *data); typedef void (*ImGuiSizeConstraintCallback)(ImGuiSizeConstraintCallbackData* data); #ifdef _MSC_VER typedef unsigned __int64 ImU64; // 64-bit unsigned integer #else typedef unsigned long long ImU64; // 64-bit unsigned integer #endif // Others helpers at bottom of the file: // class ImVector<> // Lightweight std::vector like class. // IMGUI_ONCE_UPON_A_FRAME // Execute a block of code once per frame only (convenient for creating UI within deep-nested code that runs multiple times) struct ImVec2 { float x, y; ImVec2() { x = y = 0.0f; } ImVec2(float _x, float _y) { x = _x; y = _y; } #ifdef IM_VEC2_CLASS_EXTRA // Define constructor and implicit cast operators in imconfig.h to convert back<>forth from your math types and ImVec2. IM_VEC2_CLASS_EXTRA #endif }; struct ImVec4 { float x, y, z, w; ImVec4() { x = y = z = w = 0.0f; } ImVec4(float _x, float _y, float _z, float _w) { x = _x; y = _y; z = _z; w = _w; } #ifdef IM_VEC4_CLASS_EXTRA // Define constructor and implicit cast operators in imconfig.h to convert back<>forth from your math types and ImVec4. IM_VEC4_CLASS_EXTRA #endif }; // ImGui end-user API // In a namespace so that user can add extra functions in a separate file (e.g. Value() helpers for your vector or common types) namespace ImGui { // Main IMGUI_API ImGuiIO& GetIO(); IMGUI_API ImGuiStyle& GetStyle(); IMGUI_API ImDrawData* GetDrawData(); // same value as passed to your io.RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame() IMGUI_API void NewFrame(); // start a new ImGui frame, you can submit any command from this point until NewFrame()/Render(). IMGUI_API void Render(); // ends the ImGui frame, finalize rendering data, then call your io.RenderDrawListsFn() function if set. IMGUI_API void Shutdown(); // Demo/Debug/Info IMGUI_API void ShowTestWindow(bool* p_open = NULL); // create demo/test window. demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application! IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create metrics window. display ImGui internals: browse window list, draw commands, individual vertices, basic internal state, etc. IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // add style editor block (not a window). you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style) IMGUI_API void ShowUserGuide(); // add basic help/info block (not a window): how to manipulate ImGui as a end-user (mouse/keyboard controls). // Window IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // push window to the stack and start appending to it. see .cpp for details. return false when window is collapsed, so you can early out in your code. 'bool* p_open' creates a widget on the upper-right to close the window (which sets your bool to false). IMGUI_API bool Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha = -1.0f, ImGuiWindowFlags flags = 0); // OBSOLETE. this is the older/longer API. the extra parameters aren't very relevant. call SetNextWindowSize() instead if you want to set a window size. For regular windows, 'size_on_first_use' only applies to the first time EVER the window is created and probably not what you want! might obsolete this API eventually. IMGUI_API void End(); // finish appending to current window, pop it off the window stack. IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // begin a scrolling region. size==0.0f: use remaining window size, size<0.0f: use remaining window size minus abs(size). size>0.0f: fixed size. each axis can use a different mode, e.g. ImVec2(0,400). IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // " IMGUI_API void EndChild(); IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos() IMGUI_API float GetContentRegionAvailWidth(); // IMGUI_API ImVec2 GetWindowContentRegionMin(); // content boundaries min (roughly (0,0)-Scroll), in window coordinates IMGUI_API ImVec2 GetWindowContentRegionMax(); // content boundaries max (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(), in window coordinates IMGUI_API float GetWindowContentRegionWidth(); // IMGUI_API ImDrawList* GetWindowDrawList(); // get rendering command-list if you want to append your own draw primitives IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (useful if you want to do your own drawing via the DrawList api) IMGUI_API ImVec2 GetWindowSize(); // get current window size IMGUI_API float GetWindowWidth(); IMGUI_API float GetWindowHeight(); IMGUI_API bool IsWindowCollapsed(); IMGUI_API bool IsWindowAppearing(); IMGUI_API void SetWindowFontScale(float scale); // per-window font scale. Adjust IO.FontGlobalScale if you want to scale all windows IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiCond cond = 0); // set next window position. call before Begin() IMGUI_API void SetNextWindowPosCenter(ImGuiCond cond = 0); // set next window position to be centered on screen. call before Begin() IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin() IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeConstraintCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Use callback to apply non-trivial programmatic constraints. IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (enforce the range of scrollbars). set axis to 0.0f to leave it automatic. call before Begin() IMGUI_API void SetNextWindowContentWidth(float width); // set next window content width (enforce the range of horizontal scrollbar). call before Begin() IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // set next window collapsed state. call before Begin() IMGUI_API void SetNextWindowFocus(); // set next window to be focused / front-most. call before Begin() IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects. IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0,0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects. IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed(). IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / front-most. prefer using SetNextWindowFocus(). IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond = 0); // set named window position. IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis. IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond = 0); // set named window collapsed state IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / front-most. use NULL to remove focus. IMGUI_API float GetScrollX(); // get scrolling amount [0..GetScrollMaxX()] IMGUI_API float GetScrollY(); // get scrolling amount [0..GetScrollMaxY()] IMGUI_API float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.X - WindowSize.X IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.Y - WindowSize.Y IMGUI_API void SetScrollX(float scroll_x); // set scrolling amount [0..GetScrollMaxX()] IMGUI_API void SetScrollY(float scroll_y); // set scrolling amount [0..GetScrollMaxY()] IMGUI_API void SetScrollHere(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. IMGUI_API void SetScrollFromPosY(float pos_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position valid. use GetCursorPos() or GetCursorStartPos()+offset to get valid positions. IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use negative 'offset' to access previous widgets. IMGUI_API void SetStateStorage(ImGuiStorage* tree); // replace tree state storage with our own (if you want to manipulate it yourself, typically clear subsection of it) IMGUI_API ImGuiStorage* GetStateStorage(); // Parameters stacks (shared) IMGUI_API void PushFont(ImFont* font); // use NULL as a shortcut to push default font IMGUI_API void PopFont(); IMGUI_API void PushStyleColor(ImGuiCol idx, ImU32 col); IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col); IMGUI_API void PopStyleColor(int count = 1); IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val); IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val); IMGUI_API void PopStyleVar(int count = 1); IMGUI_API const ImVec4& GetStyleColorVec4(ImGuiCol idx); // retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), otherwhise use GetColorU32() to get style color + style alpha. IMGUI_API ImFont* GetFont(); // get current font IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with current scale applied IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied IMGUI_API ImU32 GetColorU32(ImU32 col); // retrieve given color with style alpha applied // Parameters stacks (current window) IMGUI_API void PushItemWidth(float item_width); // width of items for the common item+label case, pixels. 0.0f = default to ~2/3 of windows width, >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0f always align width to the right side) IMGUI_API void PopItemWidth(); IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position IMGUI_API void PushTextWrapPos(float wrap_pos_x = 0.0f); // word-wrapping for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space IMGUI_API void PopTextWrapPos(); IMGUI_API void PushAllowKeyboardFocus(bool allow_keyboard_focus); // allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets IMGUI_API void PopAllowKeyboardFocus(); IMGUI_API void PushButtonRepeat(bool repeat); // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (using io.KeyRepeatDelay/io.KeyRepeatRate setting). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame. IMGUI_API void PopButtonRepeat(); // Cursor / Layout IMGUI_API void Separator(); // horizontal line IMGUI_API void SameLine(float pos_x = 0.0f, float spacing_w = -1.0f); // call between widgets or groups to layout them horizontally IMGUI_API void NewLine(); // undo a SameLine() IMGUI_API void Spacing(); // add vertical spacing IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by style.IndentSpacing or indent_w if >0 IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by style.IndentSpacing or indent_w if >0 IMGUI_API void BeginGroup(); // lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) IMGUI_API void EndGroup(); IMGUI_API ImVec2 GetCursorPos(); // cursor position is relative to window position IMGUI_API float GetCursorPosX(); // " IMGUI_API float GetCursorPosY(); // " IMGUI_API void SetCursorPos(const ImVec2& local_pos); // " IMGUI_API void SetCursorPosX(float x); // " IMGUI_API void SetCursorPosY(float y); // " IMGUI_API ImVec2 GetCursorStartPos(); // initial cursor position IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute screen coordinates [0..io.DisplaySize] (useful to work with ImDrawList API) IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position in absolute screen coordinates [0..io.DisplaySize] IMGUI_API void AlignFirstTextHeightToWidgets(); // call once if the first item on the line is a Text() item and you want to vertically lower it to match subsequent (bigger) widgets IMGUI_API float GetTextLineHeight(); // height of font == GetWindowFontSize() IMGUI_API float GetTextLineHeightWithSpacing(); // distance (in pixels) between 2 consecutive lines of text == GetWindowFontSize() + GetStyle().ItemSpacing.y IMGUI_API float GetItemsLineHeightWithSpacing(); // distance (in pixels) between 2 consecutive lines of standard height widgets == GetWindowFontSize() + GetStyle().FramePadding.y*2 + GetStyle().ItemSpacing.y // Columns // You can also use SameLine(pos_x) for simplified columns. The columns API is still work-in-progress and rather lacking. IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true); IMGUI_API void NextColumn(); // next column, defaults to current row or next row if the current row is finished IMGUI_API int GetColumnIndex(); // get current column index IMGUI_API float GetColumnWidth(int column_index = -1); // get column width (in pixels). pass -1 to use current column IMGUI_API void SetColumnWidth(int column_index, float width); // set column width (in pixels). pass -1 to use current column IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetColumnsCount() inclusive. column 0 is typically 0.0f IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column IMGUI_API int GetColumnsCount(); // ID scopes // If you are creating widgets in a loop you most likely want to push a unique identifier (e.g. object pointer, loop index) so ImGui can differentiate them. // You can also use the "##foobar" syntax within widget label to distinguish them from each others. Read "A primer on the use of labels/IDs" in the FAQ for more details. IMGUI_API void PushID(const char* str_id); // push identifier into the ID stack. IDs are hash of the entire stack! IMGUI_API void PushID(const char* str_id_begin, const char* str_id_end); IMGUI_API void PushID(const void* ptr_id); IMGUI_API void PushID(int int_id); IMGUI_API void PopID(); IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage yourself IMGUI_API ImGuiID GetID(const char* str_id_begin, const char* str_id_end); IMGUI_API ImGuiID GetID(const void* ptr_id); // Widgets: Text IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // doesn't require null terminated string if 'text_end' is specified. no copy done, no limits, recommended for long chunks of text IMGUI_API void Text(const char* fmt, ...) IM_FMTARGS(1); // simple formatted text IMGUI_API void TextV(const char* fmt, va_list args) IM_FMTLIST(1); IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_FMTARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor(); IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args) IM_FMTLIST(2); IMGUI_API void TextDisabled(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor(); IMGUI_API void TextDisabledV(const char* fmt, va_list args) IM_FMTLIST(1); IMGUI_API void TextWrapped(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize(). IMGUI_API void TextWrappedV(const char* fmt, va_list args) IM_FMTLIST(1); IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_FMTARGS(2); // display text+label aligned the same way as value+label widgets IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args) IM_FMTLIST(2); IMGUI_API void BulletText(const char* fmt, ...) IM_FMTARGS(1); // shortcut for Bullet()+Text() IMGUI_API void BulletTextV(const char* fmt, va_list args) IM_FMTLIST(1); IMGUI_API void Bullet(); // draw a small circle and keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses // Widgets: Main IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0,0)); // button IMGUI_API bool SmallButton(const char* label); // button with FramePadding=(0,0) to easily embed within text IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size); IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), const ImVec4& tint_col = ImVec4(1,1,1,1), const ImVec4& border_col = ImVec4(0,0,0,0)); IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0,0,0,0), const ImVec4& tint_col = ImVec4(1,1,1,1)); // <0 frame_padding uses default frame padding settings. 0 for no padding IMGUI_API bool Checkbox(const char* label, bool* v); IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value); IMGUI_API bool RadioButton(const char* label, bool active); IMGUI_API bool RadioButton(const char* label, int* v, int v_button); IMGUI_API bool Combo(const char* label, int* current_item, const char* const* items, int items_count, int height_in_items = -1); IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items = -1); // separate items with \0, end item-list with \0\0 IMGUI_API bool Combo(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1); IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0), int stride = sizeof(float)); IMGUI_API void PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0)); IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0), int stride = sizeof(float)); IMGUI_API void PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0)); IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-1,0), const char* overlay = NULL); // Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can go off-bounds) // For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every functions, note that a 'float v[X]' function argument is the same as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. You can pass address of your first element out of a contiguous set, e.g. &myvector.x IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); // If v_min >= v_max we have no bound IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", const char* display_format_max = NULL, float power = 1.0f); IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); // If v_min >= v_max we have no bound IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f", const char* display_format_max = NULL); // Widgets: Input with Keyboard IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiTextEditCallback callback = NULL, void* user_data = NULL); IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0,0), ImGuiInputTextFlags flags = 0, ImGuiTextEditCallback callback = NULL, void* user_data = NULL); IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputFloat2(const char* label, float v[2], int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputFloat3(const char* label, float v[3], int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputFloat4(const char* label, float v[4], int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputInt(const char* label, int* v, int step = 1, int step_fast = 100, ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags = 0); // Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can go off-bounds) IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); // adjust display_format to decorate the value with a prefix or a suffix for in-slider labels or unit display. Use power!=1.0 for logarithmic sliders IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f); IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* display_format = "%.0f"); IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* display_format = "%.0f"); IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* display_format = "%.0f"); IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* display_format = "%.0f"); IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* display_format = "%.0f"); // Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little colored preview square that can be left-clicked to open a picker, and right-clicked to open an option menu.) // Note that a 'float v[X]' function argument is the same as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. You can the pass the address of a first float element out of a contiguous structure, e.g. &myvector.x IMGUI_API bool ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); IMGUI_API bool ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0); IMGUI_API bool ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); IMGUI_API bool ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags = 0, const float* ref_col = NULL); IMGUI_API bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0)); // display a colored square/button, hover for details, return true when pressed. IMGUI_API void SetColorEditOptions(ImGuiColorEditFlags flags); // initialize current options (generally on application startup) if you want to select a default format, picker type, etc. User will be able to change many settings, unless you pass the _NoOptions flag to your calls. // Widgets: Trees IMGUI_API bool TreeNode(const char* label); // if returning 'true' the node is open and the tree id is pushed into the id stack. user is responsible for calling TreePop(). IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_FMTARGS(2); // read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet(). IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_FMTARGS(2); // " IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args) IM_FMTLIST(2); IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args) IM_FMTLIST(2); IMGUI_API bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0); IMGUI_API bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); IMGUI_API void TreePush(const char* str_id = NULL); // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call Push/Pop yourself for layout purpose IMGUI_API void TreePush(const void* ptr_id = NULL); // " IMGUI_API void TreePop(); // ~ Unindent()+PopId() IMGUI_API void TreeAdvanceToLabelPos(); // advance cursor x position by GetTreeNodeToLabelSpacing() IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode IMGUI_API void SetNextTreeNodeOpen(bool is_open, ImGuiCond cond = 0); // set next TreeNode/CollapsingHeader open state. IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop(). IMGUI_API bool CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags = 0); // when 'p_open' isn't NULL, display an additional small close button on upper right of the header // Widgets: Selectable / Lists IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); IMGUI_API bool ListBox(const char* label, int* current_item, const char* const* items, int items_count, int height_in_items = -1); IMGUI_API bool ListBox(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1); IMGUI_API bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0,0)); // use if you want to reimplement ListBox() will custom data or interactions. make sure to call ListBoxFooter() afterwards. IMGUI_API bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1); // " IMGUI_API void ListBoxFooter(); // terminate the scrolling region // Widgets: Value() Helpers. Output single value in "name: value" format (tip: freely declare more in your code to handle your types. you can add functions to the ImGui namespace) IMGUI_API void Value(const char* prefix, bool b); IMGUI_API void Value(const char* prefix, int v); IMGUI_API void Value(const char* prefix, unsigned int v); IMGUI_API void Value(const char* prefix, float v, const char* float_format = NULL); // Tooltips IMGUI_API void SetTooltip(const char* fmt, ...) IM_FMTARGS(1); // set text tooltip under mouse-cursor, typically use with ImGui::IsItemHovered(). overidde any previous call to SetTooltip(). IMGUI_API void SetTooltipV(const char* fmt, va_list args) IM_FMTLIST(1); IMGUI_API void BeginTooltip(); // begin/append a tooltip window. to create full-featured tooltip (with any kind of contents). IMGUI_API void EndTooltip(); // Menus IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar. only call EndMainMenuBar() if this returns true! IMGUI_API void EndMainMenuBar(); IMGUI_API bool BeginMenuBar(); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set). only call EndMenuBar() if this returns true! IMGUI_API void EndMenuBar(); IMGUI_API bool BeginMenu(const char* label, bool enabled = true); // create a sub-menu entry. only call EndMenu() if this returns true! IMGUI_API void EndMenu(); IMGUI_API bool MenuItem(const char* label, const char* shortcut = NULL, bool selected = false, bool enabled = true); // return true when activated. shortcuts are displayed for convenience but not processed by ImGui at the moment IMGUI_API bool MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled = true); // return true when activated + toggle (*p_selected) if p_selected != NULL // Popups IMGUI_API void OpenPopup(const char* str_id); // call to mark popup as open (don't call every frame!). popups are closed when user click outside, or if CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. By default, Selectable()/MenuItem() are calling CloseCurrentPopup(). Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). IMGUI_API bool BeginPopup(const char* str_id); // return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup() returned true! IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags extra_flags = 0); // modal dialog (block interactions behind the modal window, can't close the modal window by clicking outside) IMGUI_API bool BeginPopupContextItem(const char* str_id, int mouse_button = 1); // helper to open and begin popup when clicked on last item. read comments in .cpp! IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, int mouse_button = 1, bool also_over_items = true); // helper to open and begin popup when clicked on current window. IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked in void (no window). IMGUI_API void EndPopup(); IMGUI_API bool IsPopupOpen(const char* str_id); // return true if the popup is open IMGUI_API void CloseCurrentPopup(); // close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current popup. // Logging: all text output from interface is redirected to tty/file/clipboard. By default, tree nodes are automatically opened during logging. IMGUI_API void LogToTTY(int max_depth = -1); // start logging to tty IMGUI_API void LogToFile(int max_depth = -1, const char* filename = NULL); // start logging to file IMGUI_API void LogToClipboard(int max_depth = -1); // start logging to OS clipboard IMGUI_API void LogFinish(); // stop logging (close file, etc.) IMGUI_API void LogButtons(); // helper to display buttons for logging to tty/file/clipboard IMGUI_API void LogText(const char* fmt, ...) IM_FMTARGS(1); // pass text data straight to log (without being displayed) // Clipping IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect); IMGUI_API void PopClipRect(); // Styles IMGUI_API void StyleColorsClassic(ImGuiStyle* dst = NULL); // Utilities IMGUI_API bool IsItemHovered(); // is the last item hovered by mouse (and usable)? IMGUI_API bool IsItemRectHovered(); // is the last item hovered by mouse? even if another item is active or window is blocked by popup while we are hovering this IMGUI_API bool IsItemActive(); // is the last item active? (e.g. button being held, text field being edited- items that don't interact will always return false) IMGUI_API bool IsItemClicked(int mouse_button = 0); // is the last item clicked? (e.g. button/node just clicked on) IMGUI_API bool IsItemVisible(); // is the last item visible? (aka not out of sight due to clipping/scrolling.) IMGUI_API bool IsAnyItemHovered(); IMGUI_API bool IsAnyItemActive(); IMGUI_API ImVec2 GetItemRectMin(); // get bounding rect of last item in screen space IMGUI_API ImVec2 GetItemRectMax(); // " IMGUI_API ImVec2 GetItemRectSize(); // " IMGUI_API void SetItemAllowOverlap(); // allow last item to be overlapped by a subsequent item. sometimes useful with invisible buttons, selectables, etc. to catch unused area. IMGUI_API bool IsWindowFocused(); // is current window focused IMGUI_API bool IsWindowHovered(); // is current window hovered and hoverable (not blocked by a popup) (differentiate child windows from each others) IMGUI_API bool IsWindowRectHovered(); // is current window rectangle hovered, disregarding of any consideration of being blocked by a popup. (unlike IsWindowHovered() this will return true even if the window is blocked because of a popup) IMGUI_API bool IsRootWindowFocused(); // is current root window focused (root = top-most parent of a child, otherwise self) IMGUI_API bool IsRootWindowOrAnyChildFocused(); // is current root window or any of its child (including current window) focused IMGUI_API bool IsRootWindowOrAnyChildHovered(); // is current root window or any of its child (including current window) hovered and hoverable (not blocked by a popup) IMGUI_API bool IsAnyWindowHovered(); // is mouse hovering any visible window IMGUI_API bool IsRectVisible(const ImVec2& size); // test if rectangle (of given size, starting from cursor position) is visible / not clipped. IMGUI_API bool IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max); // test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user's side. IMGUI_API float GetTime(); IMGUI_API int GetFrameCount(); IMGUI_API const char* GetStyleColorName(ImGuiCol idx); IMGUI_API ImVec2 CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge = false, float outward = +0.0f); // utility to find the closest point the last item bounding rectangle edge. useful to visually link items IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f); IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // calculate coarse clipping for large list of evenly sized items. Prefer using the ImGuiListClipper higher-level helper if you can. IMGUI_API bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags = 0); // helper to create a child window / scrolling region that looks like a normal widget frame IMGUI_API void EndChildFrame(); IMGUI_API ImVec4 ColorConvertU32ToFloat4(ImU32 in); IMGUI_API ImU32 ColorConvertFloat4ToU32(const ImVec4& in); IMGUI_API void ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v); IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b); // Inputs IMGUI_API int GetKeyIndex(ImGuiKey imgui_key); // map ImGuiKey_* values into user's key index. == io.KeyMap[key] IMGUI_API bool IsKeyDown(int user_key_index); // is key being held. == io.KeysDown[user_key_index]. note that imgui doesn't know the semantic of each entry of io.KeyDown[]. Use your own indices/enums according to how your backend/engine stored them into KeyDown[]! IMGUI_API bool IsKeyPressed(int user_key_index, bool repeat = true); // was key pressed (went from !Down to Down). if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate IMGUI_API bool IsKeyReleased(int user_key_index); // was key released (went from Down to !Down).. IMGUI_API int GetKeyPressedAmount(int key_index, float repeat_delay, float rate); // uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough that DeltaTime > RepeatRate IMGUI_API bool IsMouseDown(int button); // is mouse button held IMGUI_API bool IsMouseClicked(int button, bool repeat = false); // did mouse button clicked (went from !Down to Down) IMGUI_API bool IsMouseDoubleClicked(int button); // did mouse button double-clicked. a double-click returns false in IsMouseClicked(). uses io.MouseDoubleClickTime. IMGUI_API bool IsMouseReleased(int button); // did mouse button released (went from Down to !Down) IMGUI_API bool IsMouseDragging(int button = 0, float lock_threshold = -1.0f); // is mouse dragging. if lock_threshold < -1.0f uses io.MouseDraggingThreshold IMGUI_API bool IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip = true); // is mouse hovering given bounding rect (in screen space). clipped by current clipping settings. disregarding of consideration of focus/window ordering/blocked by a popup. IMGUI_API bool IsMousePosValid(const ImVec2* mouse_pos = NULL); // IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve backup of mouse positioning at the time of opening popup we have BeginPopup() into IMGUI_API ImVec2 GetMouseDragDelta(int button = 0, float lock_threshold = -1.0f); // dragging amount since clicking. if lock_threshold < -1.0f uses io.MouseDraggingThreshold IMGUI_API void ResetMouseDragDelta(int button = 0); // IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired cursor type, reset in ImGui::NewFrame(), this is updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you IMGUI_API void SetMouseCursor(ImGuiMouseCursor type); // set desired cursor type IMGUI_API void CaptureKeyboardFromApp(bool capture = true); // manually override io.WantCaptureKeyboard flag next frame (said flag is entirely left for your application handle). e.g. force capture keyboard when your widget is being hovered. IMGUI_API void CaptureMouseFromApp(bool capture = true); // manually override io.WantCaptureMouse flag next frame (said flag is entirely left for your application handle). // Helpers functions to access functions pointers in ImGui::GetIO() IMGUI_API void* MemAlloc(size_t sz); IMGUI_API void MemFree(void* ptr); IMGUI_API const char* GetClipboardText(); IMGUI_API void SetClipboardText(const char* text); // Internal context access - if you want to use multiple context, share context between modules (e.g. DLL). There is a default context created and active by default. // All contexts share a same ImFontAtlas by default. If you want different font atlas, you can new() them and overwrite the GetIO().Fonts variable of an ImGui context. IMGUI_API const char* GetVersion(); IMGUI_API ImGuiContext* CreateContext(void* (*malloc_fn)(size_t) = NULL, void (*free_fn)(void*) = NULL); IMGUI_API void DestroyContext(ImGuiContext* ctx); IMGUI_API ImGuiContext* GetCurrentContext(); IMGUI_API void SetCurrentContext(ImGuiContext* ctx); // Obsolete functions (Will be removed! Also see 'API BREAKING CHANGES' section in imgui.cpp) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS static inline bool IsItemHoveredRect() { return IsItemRectHovered(); } // OBSOLETE 1.51+ static inline bool IsPosHoveringAnyWindow(const ImVec2&) { IM_ASSERT(0); return false; } // OBSOLETE 1.51+. This was partly broken. You probably wanted to use ImGui::GetIO().WantCaptureMouse instead. static inline bool IsMouseHoveringAnyWindow() { return IsAnyWindowHovered(); } // OBSOLETE 1.51+ static inline bool IsMouseHoveringWindow() { return IsWindowRectHovered(); } // OBSOLETE 1.51+ static inline bool CollapsingHeader(const char* label, const char* str_id, bool framed = true, bool default_open = false) { (void)str_id; (void)framed; ImGuiTreeNodeFlags default_open_flags = 1<<5; return CollapsingHeader(label, (default_open ? default_open_flags : 0)); } // OBSOLETE 1.49+ static inline ImFont* GetWindowFont() { return GetFont(); } // OBSOLETE 1.48+ static inline float GetWindowFontSize() { return GetFontSize(); } // OBSOLETE 1.48+ static inline void SetScrollPosHere() { SetScrollHere(); } // OBSOLETE 1.42+ #endif } // namespace ImGui // Flags for ImGui::Begin() enum ImGuiWindowFlags_ { // Default: 0 ImGuiWindowFlags_NoTitleBar = 1 << 0, // Disable title-bar ImGuiWindowFlags_NoResize = 1 << 1, // Disable user resizing with the lower-right grip ImGuiWindowFlags_NoMove = 1 << 2, // Disable user moving the window ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbars (window can still scroll with mouse or programatically) ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user vertically scrolling with mouse wheel ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, // Resize every window to its content every frame ImGuiWindowFlags_ShowBorders = 1 << 7, // Show borders around windows and items ImGuiWindowFlags_NoSavedSettings = 1 << 8, // Never load/save settings in .ini file ImGuiWindowFlags_NoInputs = 1 << 9, // Disable catching mouse or keyboard inputs ImGuiWindowFlags_MenuBar = 1 << 10, // Has a menu-bar ImGuiWindowFlags_HorizontalScrollbar = 1 << 11, // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section. ImGuiWindowFlags_NoFocusOnAppearing = 1 << 12, // Disable taking focus when transitioning from hidden to visible state ImGuiWindowFlags_NoBringToFrontOnFocus = 1 << 13, // Disable bringing window to front when taking focus (e.g. clicking on it or programatically giving it focus) ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14, // Always show vertical scrollbar (even if ContentSize.y < Size.y) ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15, // Always show horizontal scrollbar (even if ContentSize.x < Size.x) ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 16, // Ensure child windows without border uses style.WindowPadding (ignored by default for non-bordered child windows, because more convenient) // [Internal] ImGuiWindowFlags_ChildWindow = 1 << 22, // Don't use! For internal use by BeginChild() ImGuiWindowFlags_ComboBox = 1 << 23, // Don't use! For internal use by ComboBox() ImGuiWindowFlags_Tooltip = 1 << 24, // Don't use! For internal use by BeginTooltip() ImGuiWindowFlags_Popup = 1 << 25, // Don't use! For internal use by BeginPopup() ImGuiWindowFlags_Modal = 1 << 26, // Don't use! For internal use by BeginPopupModal() ImGuiWindowFlags_ChildMenu = 1 << 27 // Don't use! For internal use by BeginMenu() }; // Flags for ImGui::InputText() enum ImGuiInputTextFlags_ { // Default: 0 ImGuiInputTextFlags_CharsDecimal = 1 << 0, // Allow 0123456789.+-*/ ImGuiInputTextFlags_CharsHexadecimal = 1 << 1, // Allow 0123456789ABCDEFabcdef ImGuiInputTextFlags_CharsUppercase = 1 << 2, // Turn a..z into A..Z ImGuiInputTextFlags_CharsNoBlank = 1 << 3, // Filter out spaces, tabs ImGuiInputTextFlags_AutoSelectAll = 1 << 4, // Select entire text when first taking mouse focus ImGuiInputTextFlags_EnterReturnsTrue = 1 << 5, // Return 'true' when Enter is pressed (as opposed to when the value was modified) ImGuiInputTextFlags_CallbackCompletion = 1 << 6, // Call user function on pressing TAB (for completion handling) ImGuiInputTextFlags_CallbackHistory = 1 << 7, // Call user function on pressing Up/Down arrows (for history handling) ImGuiInputTextFlags_CallbackAlways = 1 << 8, // Call user function every time. User code may query cursor position, modify text buffer. ImGuiInputTextFlags_CallbackCharFilter = 1 << 9, // Call user function to filter character. Modify data->EventChar to replace/filter input, or return 1 to discard character. ImGuiInputTextFlags_AllowTabInput = 1 << 10, // Pressing TAB input a '\t' character into the text field ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 11, // In multi-line mode, unfocus with Enter, add new line with Ctrl+Enter (default is opposite: unfocus with Ctrl+Enter, add line with Enter). ImGuiInputTextFlags_NoHorizontalScroll = 1 << 12, // Disable following the cursor horizontally ImGuiInputTextFlags_AlwaysInsertMode = 1 << 13, // Insert mode ImGuiInputTextFlags_ReadOnly = 1 << 14, // Read-only mode ImGuiInputTextFlags_Password = 1 << 15, // Password mode, display all characters as '*' // [Internal] ImGuiInputTextFlags_Multiline = 1 << 20 // For internal use by InputTextMultiline() }; // Flags for ImGui::TreeNodeEx(), ImGui::CollapsingHeader*() enum ImGuiTreeNodeFlags_ { ImGuiTreeNodeFlags_Selected = 1 << 0, // Draw as selected ImGuiTreeNodeFlags_Framed = 1 << 1, // Full colored frame (e.g. for CollapsingHeader) ImGuiTreeNodeFlags_AllowOverlapMode = 1 << 2, // Hit testing to allow subsequent widgets to overlap this one ImGuiTreeNodeFlags_NoTreePushOnOpen = 1 << 3, // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack ImGuiTreeNodeFlags_NoAutoOpenOnLog = 1 << 4, // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes) ImGuiTreeNodeFlags_DefaultOpen = 1 << 5, // Default node to be open ImGuiTreeNodeFlags_OpenOnDoubleClick = 1 << 6, // Need double-click to open node ImGuiTreeNodeFlags_OpenOnArrow = 1 << 7, // Only open when clicking on the arrow part. If ImGuiTreeNodeFlags_OpenOnDoubleClick is also set, single-click arrow or double-click all box to open. ImGuiTreeNodeFlags_Leaf = 1 << 8, // No collapsing, no arrow (use as a convenience for leaf nodes). ImGuiTreeNodeFlags_Bullet = 1 << 9, // Display a bullet instead of arrow //ImGuITreeNodeFlags_SpanAllAvailWidth = 1 << 10, // FIXME: TODO: Extend hit box horizontally even if not framed //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 11, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoAutoOpenOnLog }; // Flags for ImGui::Selectable() enum ImGuiSelectableFlags_ { // Default: 0 ImGuiSelectableFlags_DontClosePopups = 1 << 0, // Clicking this don't close parent popup window ImGuiSelectableFlags_SpanAllColumns = 1 << 1, // Selectable frame can span all columns (text will still fit in current column) ImGuiSelectableFlags_AllowDoubleClick = 1 << 2 // Generate press events on double clicks too }; // User fill ImGuiIO.KeyMap[] array with indices into the ImGuiIO.KeysDown[512] array enum ImGuiKey_ { ImGuiKey_Tab, // for tabbing through fields ImGuiKey_LeftArrow, // for text edit ImGuiKey_RightArrow,// for text edit ImGuiKey_UpArrow, // for text edit ImGuiKey_DownArrow, // for text edit ImGuiKey_PageUp, ImGuiKey_PageDown, ImGuiKey_Home, // for text edit ImGuiKey_End, // for text edit ImGuiKey_Delete, // for text edit ImGuiKey_Backspace, // for text edit ImGuiKey_Enter, // for text edit ImGuiKey_Escape, // for text edit ImGuiKey_A, // for text edit CTRL+A: select all ImGuiKey_C, // for text edit CTRL+C: copy ImGuiKey_V, // for text edit CTRL+V: paste ImGuiKey_X, // for text edit CTRL+X: cut ImGuiKey_Y, // for text edit CTRL+Y: redo ImGuiKey_Z, // for text edit CTRL+Z: undo ImGuiKey_COUNT }; // Enumeration for PushStyleColor() / PopStyleColor() enum ImGuiCol_ { ImGuiCol_Text, ImGuiCol_TextDisabled, ImGuiCol_WindowBg, // Background of normal windows ImGuiCol_ChildWindowBg, // Background of child windows ImGuiCol_PopupBg, // Background of popups, menus, tooltips windows ImGuiCol_Border, ImGuiCol_BorderShadow, ImGuiCol_FrameBg, // Background of checkbox, radio button, plot, slider, text input ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive, ImGuiCol_TitleBg, ImGuiCol_TitleBgActive, ImGuiCol_TitleBgCollapsed, ImGuiCol_MenuBarBg, ImGuiCol_ScrollbarBg, ImGuiCol_ScrollbarGrab, ImGuiCol_ScrollbarGrabHovered, ImGuiCol_ScrollbarGrabActive, ImGuiCol_ComboBg, ImGuiCol_CheckMark, ImGuiCol_SliderGrab, ImGuiCol_SliderGrabActive, ImGuiCol_Button, ImGuiCol_ButtonHovered, ImGuiCol_ButtonActive, ImGuiCol_Header, ImGuiCol_HeaderHovered, ImGuiCol_HeaderActive, ImGuiCol_Separator, ImGuiCol_SeparatorHovered, ImGuiCol_SeparatorActive, ImGuiCol_ResizeGrip, ImGuiCol_ResizeGripHovered, ImGuiCol_ResizeGripActive, ImGuiCol_CloseButton, ImGuiCol_CloseButtonHovered, ImGuiCol_CloseButtonActive, ImGuiCol_PlotLines, ImGuiCol_PlotLinesHovered, ImGuiCol_PlotHistogram, ImGuiCol_PlotHistogramHovered, ImGuiCol_TextSelectedBg, ImGuiCol_ModalWindowDarkening, // darken entire screen when a modal window is active ImGuiCol_COUNT // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS , ImGuiCol_Column = ImGuiCol_Separator, ImGuiCol_ColumnHovered = ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive = ImGuiCol_SeparatorActive #endif }; // Enumeration for PushStyleVar() / PopStyleVar() to temporarily modify the ImGuiStyle structure. // NB: the enum only refers to fields of ImGuiStyle which makes sense to be pushed/poped inside UI code. During initialization, feel free to just poke into ImGuiStyle directly. // NB: if changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type. enum ImGuiStyleVar_ { // Enum name ......................// Member in ImGuiStyle structure (see ImGuiStyle for descriptions) ImGuiStyleVar_Alpha, // float Alpha ImGuiStyleVar_WindowPadding, // ImVec2 WindowPadding ImGuiStyleVar_WindowRounding, // float WindowRounding ImGuiStyleVar_WindowMinSize, // ImVec2 WindowMinSize ImGuiStyleVar_ChildWindowRounding, // float ChildWindowRounding ImGuiStyleVar_FramePadding, // ImVec2 FramePadding ImGuiStyleVar_FrameRounding, // float FrameRounding ImGuiStyleVar_ItemSpacing, // ImVec2 ItemSpacing ImGuiStyleVar_ItemInnerSpacing, // ImVec2 ItemInnerSpacing ImGuiStyleVar_IndentSpacing, // float IndentSpacing ImGuiStyleVar_GrabMinSize, // float GrabMinSize ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign ImGuiStyleVar_Count_ }; // Enumeration for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton() enum ImGuiColorEditFlags_ { ImGuiColorEditFlags_NoAlpha = 1 << 1, // // ColorEdit, ColorPicker, ColorButton: ignore Alpha component (read 3 components from the input pointer). ImGuiColorEditFlags_NoPicker = 1 << 2, // // ColorEdit: disable picker when clicking on colored square. ImGuiColorEditFlags_NoOptions = 1 << 3, // // ColorEdit: disable toggling options menu when right-clicking on inputs/small preview. ImGuiColorEditFlags_NoSmallPreview = 1 << 4, // // ColorEdit, ColorPicker: disable colored square preview next to the inputs. (e.g. to show only the inputs) ImGuiColorEditFlags_NoInputs = 1 << 5, // // ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview colored square). ImGuiColorEditFlags_NoTooltip = 1 << 6, // // ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview. ImGuiColorEditFlags_NoLabel = 1 << 7, // // ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker). ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small colored square preview instead. // User Options (right-click on widget to change some of them). You can set application defaults using SetColorEditOptions(). The idea is that you probably don't want to override them in most of your calls, let the user choose and/or call SetColorEditOptions() during startup. ImGuiColorEditFlags_AlphaBar = 1 << 9, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker. ImGuiColorEditFlags_AlphaPreview = 1 << 10, // // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque. ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 11, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half checkerboard, instead of opaque. ImGuiColorEditFlags_HDR = 1 << 12, // // (WIP) ColorEdit: Currently only disable 0.0f..1.0f limits in RGBA edition (note: you probably want to use ImGuiColorEditFlags_Float flag as well). ImGuiColorEditFlags_RGB = 1 << 13, // [Inputs] // ColorEdit: choose one among RGB/HSV/HEX. ColorPicker: choose any combination using RGB/HSV/HEX. ImGuiColorEditFlags_HSV = 1 << 14, // [Inputs] // " ImGuiColorEditFlags_HEX = 1 << 15, // [Inputs] // " ImGuiColorEditFlags_Uint8 = 1 << 16, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255. ImGuiColorEditFlags_Float = 1 << 17, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers. ImGuiColorEditFlags_PickerHueBar = 1 << 18, // [PickerMode] // ColorPicker: bar for Hue, rectangle for Sat/Value. ImGuiColorEditFlags_PickerHueWheel = 1 << 19, // [PickerMode] // ColorPicker: wheel for Hue, triangle for Sat/Value. // Internals/Masks ImGuiColorEditFlags__InputsMask = ImGuiColorEditFlags_RGB|ImGuiColorEditFlags_HSV|ImGuiColorEditFlags_HEX, ImGuiColorEditFlags__DataTypeMask = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_Float, ImGuiColorEditFlags__PickerMask = ImGuiColorEditFlags_PickerHueWheel|ImGuiColorEditFlags_PickerHueBar, ImGuiColorEditFlags__OptionsDefault = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_RGB|ImGuiColorEditFlags_PickerHueBar // Change application default using SetColorEditOptions() }; // Enumeration for GetMouseCursor() enum ImGuiMouseCursor_ { ImGuiMouseCursor_None = -1, ImGuiMouseCursor_Arrow = 0, ImGuiMouseCursor_TextInput, // When hovering over InputText, etc. ImGuiMouseCursor_Move, // Unused ImGuiMouseCursor_ResizeNS, // Unused ImGuiMouseCursor_ResizeEW, // When hovering over a column ImGuiMouseCursor_ResizeNESW, // Unused ImGuiMouseCursor_ResizeNWSE, // When hovering over the bottom-right corner of a window ImGuiMouseCursor_Count_ }; // Condition flags for ImGui::SetWindow***(), SetNextWindow***(), SetNextTreeNode***() functions // All those functions treat 0 as a shortcut to ImGuiCond_Always enum ImGuiCond_ { ImGuiCond_Always = 1 << 0, // Set the variable ImGuiCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call with succeed) ImGuiCond_FirstUseEver = 1 << 2, // Set the variable if the window has no saved data (if doesn't exist in the .ini file) ImGuiCond_Appearing = 1 << 3 // Set the variable if the window is appearing after being hidden/inactive (or the first time) // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS , ImGuiSetCond_Always = ImGuiCond_Always, ImGuiSetCond_Once = ImGuiCond_Once, ImGuiSetCond_FirstUseEver = ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing = ImGuiCond_Appearing #endif }; struct ImGuiStyle { float Alpha; // Global alpha applies to everything in ImGui ImVec2 WindowPadding; // Padding within a window ImVec2 WindowMinSize; // Minimum window size float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered. float ChildWindowRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets) float FrameRounding; // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets). ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! float IndentSpacing; // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). float ColumnsMinSpacing; // Minimum horizontal spacing between two columns float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar float ScrollbarRounding; // Radius of grab corners for scrollbar float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar. float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f,0.5f) for horizontally+vertically centered. ImVec2 DisplayWindowPadding; // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows. ImVec2 DisplaySafeAreaPadding; // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. bool AntiAliasedLines; // Enable anti-aliasing on lines/borders. Disable if you are really tight on CPU/GPU. bool AntiAliasedShapes; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) float CurveTessellationTol; // Tessellation tolerance. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. ImVec4 Colors[ImGuiCol_COUNT]; IMGUI_API ImGuiStyle(); }; // This is where your app communicate with ImGui. Access via ImGui::GetIO(). // Read 'Programmer guide' section in .cpp file for general usage. struct ImGuiIO { //------------------------------------------------------------------ // Settings (fill once) // Default value: //------------------------------------------------------------------ ImVec2 DisplaySize; // <unset> // Display size, in pixels. For clamping windows positions. float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds. float IniSavingRate; // = 5.0f // Maximum time between saving positions/sizes to .ini file, in seconds. const char* IniFilename; // = "imgui.ini" // Path to .ini file. NULL to disable .ini saving. const char* LogFilename; // = "imgui_log.txt" // Path to .log file (default parameter to ImGui::LogToFile when no file is specified). float MouseDoubleClickTime; // = 0.30f // Time for a double-click, in seconds. float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels. float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging int KeyMap[ImGuiKey_COUNT]; // <unset> // Map of indices into the KeysDown[512] entries array float KeyRepeatDelay; // = 0.250f // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.). float KeyRepeatRate; // = 0.050f // When holding a key/button, rate at which it repeats, in seconds. void* UserData; // = NULL // Store your own data for retrieval by callbacks. ImFontAtlas* Fonts; // <auto> // Load and assemble one or more fonts into a single tightly packed texture. Output to Fonts array. float FontGlobalScale; // = 1.0f // Global scale all fonts bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel. ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. ImVec2 DisplayFramebufferScale; // = (1.0f,1.0f) // For retina display or other situations where window coordinates are different from framebuffer coordinates. User storage only, presently not used by ImGui. ImVec2 DisplayVisibleMin; // <unset> (0.0f,0.0f) // If you use DisplaySize as a virtual space larger than your screen, set DisplayVisibleMin/Max to the visible area. ImVec2 DisplayVisibleMax; // <unset> (0.0f,0.0f) // If the values are the same, we defaults to Min=(0.0f) and Max=DisplaySize // Advanced/subtle behaviors bool OSXBehaviors; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl //------------------------------------------------------------------ // Settings (User Functions) //------------------------------------------------------------------ // Rendering function, will be called in Render(). // Alternatively you can keep this to NULL and call GetDrawData() after Render() to get the same pointer. // See example applications if you are unsure of how to implement this. void (*RenderDrawListsFn)(ImDrawData* data); // Optional: access OS clipboard // (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) const char* (*GetClipboardTextFn)(void* user_data); void (*SetClipboardTextFn)(void* user_data, const char* text); void* ClipboardUserData; // Optional: override memory allocations. MemFreeFn() may be called with a NULL pointer. // (default to posix malloc/free) void* (*MemAllocFn)(size_t sz); void (*MemFreeFn)(void* ptr); // Optional: notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME in Windows) // (default to use native imm32 api on Windows) void (*ImeSetInputScreenPosFn)(int x, int y); void* ImeWindowHandle; // (Windows) Set this to your HWND to get automatic IME cursor positioning. //------------------------------------------------------------------ // Input - Fill before calling NewFrame() //------------------------------------------------------------------ ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX,-FLT_MAX) if mouse is unavailable (on another screen, etc.) bool MouseDown[5]; // Mouse buttons: left, right, middle + extras. ImGui itself mostly only uses left button (BeginPopupContext** are using right button). Others buttons allows us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. float MouseWheel; // Mouse wheel: 1 unit scrolls about 5 lines text. bool MouseDrawCursor; // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). bool KeyCtrl; // Keyboard modifier pressed: Control bool KeyShift; // Keyboard modifier pressed: Shift bool KeyAlt; // Keyboard modifier pressed: Alt bool KeySuper; // Keyboard modifier pressed: Cmd/Super/Windows bool KeysDown[512]; // Keyboard keys that are pressed (in whatever storage order you naturally have access to keyboard data) ImWchar InputCharacters[16+1]; // List of characters input (translated by user from keypress+keyboard state). Fill using AddInputCharacter() helper. // Functions IMGUI_API void AddInputCharacter(ImWchar c); // Add new character into InputCharacters[] IMGUI_API void AddInputCharactersUTF8(const char* utf8_chars); // Add new characters into InputCharacters[] from an UTF-8 string inline void ClearInputCharacters() { InputCharacters[0] = 0; } // Clear the text input buffer manually //------------------------------------------------------------------ // Output - Retrieve after calling NewFrame() //------------------------------------------------------------------ bool WantCaptureMouse; // Mouse is hovering a window or widget is active (= ImGui will use your mouse input). Use to hide mouse from the rest of your application bool WantCaptureKeyboard; // Widget is active (= ImGui will use your keyboard input). Use to hide keyboard from the rest of your application bool WantTextInput; // Some text input widget is active, which will read input characters from the InputCharacters array. Use to activate on screen keyboard if your system needs one bool WantMoveMouse; // [BETA-NAV] MousePos has been altered. back-end should reposition mouse on next frame. used only if 'NavMovesMouse=true'. float Framerate; // Application framerate estimation, in frame per second. Solely for convenience. Rolling average estimation based on IO.DeltaTime over 120 frames int MetricsAllocs; // Number of active memory allocations int MetricsRenderVertices; // Vertices output during last call to Render() int MetricsRenderIndices; // Indices output during last call to Render() = number of triangles * 3 int MetricsActiveWindows; // Number of visible root windows (exclude child windows) ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are negative, so a disappearing/reappearing mouse won't have a huge delta for one frame. //------------------------------------------------------------------ // [Private] ImGui will maintain those fields. Forward compatibility not guaranteed! //------------------------------------------------------------------ ImVec2 MousePosPrev; // Previous mouse position temporary storage (nb: not for public use, set to MousePos in NewFrame()) bool MouseClicked[5]; // Mouse button went from !Down to Down ImVec2 MouseClickedPos[5]; // Position at time of clicking float MouseClickedTime[5]; // Time of last click (used to figure out double-click) bool MouseDoubleClicked[5]; // Has mouse button been double-clicked? bool MouseReleased[5]; // Mouse button went from Down to !Down bool MouseDownOwned[5]; // Track if button was clicked inside a window. We don't request mouse capture from the application if click started outside ImGui bounds. float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked) float MouseDownDurationPrev[5]; // Previous time the mouse button has been down float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the click point float KeysDownDuration[512]; // Duration the keyboard key has been down (0.0f == just pressed) float KeysDownDurationPrev[512]; // Previous duration the key has been down IMGUI_API ImGuiIO(); }; //----------------------------------------------------------------------------- // Helpers //----------------------------------------------------------------------------- // Lightweight std::vector<> like class to avoid dragging dependencies (also: windows implementation of STL with debug enabled is absurdly slow, so let's bypass it so our code runs fast in debug). // Our implementation does NOT call c++ constructors because we don't use them in ImGui. Don't use this class as a straight std::vector replacement in your code! template<typename T> class ImVector { public: int Size; int Capacity; T* Data; typedef T value_type; typedef value_type* iterator; typedef const value_type* const_iterator; ImVector() { Size = Capacity = 0; Data = NULL; } ~ImVector() { if (Data) ImGui::MemFree(Data); } inline bool empty() const { return Size == 0; } inline int size() const { return Size; } inline int capacity() const { return Capacity; } inline value_type& operator[](int i) { IM_ASSERT(i < Size); return Data[i]; } inline const value_type& operator[](int i) const { IM_ASSERT(i < Size); return Data[i]; } inline void clear() { if (Data) { Size = Capacity = 0; ImGui::MemFree(Data); Data = NULL; } } inline iterator begin() { return Data; } inline const_iterator begin() const { return Data; } inline iterator end() { return Data + Size; } inline const_iterator end() const { return Data + Size; } inline value_type& front() { IM_ASSERT(Size > 0); return Data[0]; } inline const value_type& front() const { IM_ASSERT(Size > 0); return Data[0]; } inline value_type& back() { IM_ASSERT(Size > 0); return Data[Size-1]; } inline const value_type& back() const { IM_ASSERT(Size > 0); return Data[Size-1]; } inline void swap(ImVector<T>& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; value_type* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; } inline int _grow_capacity(int size) const { int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > size ? new_capacity : size; } inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; } inline void resize(int new_size, const T& v){ if (new_size > Capacity) reserve(_grow_capacity(new_size)); if (new_size > Size) for (int n = Size; n < new_size; n++) Data[n] = v; Size = new_size; } inline void reserve(int new_capacity) { if (new_capacity <= Capacity) return; T* new_data = (value_type*)ImGui::MemAlloc((size_t)new_capacity * sizeof(T)); if (Data) memcpy(new_data, Data, (size_t)Size * sizeof(T)); ImGui::MemFree(Data); Data = new_data; Capacity = new_capacity; } inline void push_back(const value_type& v) { if (Size == Capacity) reserve(_grow_capacity(Size+1)); Data[Size++] = v; } inline void pop_back() { IM_ASSERT(Size > 0); Size--; } inline iterator erase(const_iterator it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(value_type)); Size--; return Data + off; } inline iterator insert(const_iterator it, const value_type& v) { IM_ASSERT(it >= Data && it <= Data+Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(Capacity ? Capacity * 2 : 4); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(value_type)); Data[off] = v; Size++; return Data + off; } }; // Helper: execute a block of code at maximum once a frame. Convenient if you want to quickly create an UI within deep-nested code that runs multiple times every frame. // Usage: // static ImGuiOnceUponAFrame oaf; // if (oaf) // ImGui::Text("This will be called only once per frame"); struct ImGuiOnceUponAFrame { ImGuiOnceUponAFrame() { RefFrame = -1; } mutable int RefFrame; operator bool() const { int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; } }; // Helper macro for ImGuiOnceUponAFrame. Attention: The macro expands into 2 statement so make sure you don't use it within e.g. an if() statement without curly braces. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Will obsolete #define IMGUI_ONCE_UPON_A_FRAME static ImGuiOnceUponAFrame imgui_oaf; if (imgui_oaf) #endif // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" struct ImGuiTextFilter { struct TextRange { const char* b; const char* e; TextRange() { b = e = NULL; } TextRange(const char* _b, const char* _e) { b = _b; e = _e; } const char* begin() const { return b; } const char* end() const { return e; } bool empty() const { return b == e; } char front() const { return *b; } static bool is_blank(char c) { return c == ' ' || c == '\t'; } void trim_blanks() { while (b < e && is_blank(*b)) b++; while (e > b && is_blank(*(e-1))) e--; } IMGUI_API void split(char separator, ImVector<TextRange>& out); }; char InputBuf[256]; ImVector<TextRange> Filters; int CountGrep; IMGUI_API ImGuiTextFilter(const char* default_filter = ""); ~ImGuiTextFilter() {} void Clear() { InputBuf[0] = 0; Build(); } IMGUI_API bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); // Helper calling InputText+Build IMGUI_API bool PassFilter(const char* text, const char* text_end = NULL) const; bool IsActive() const { return !Filters.empty(); } IMGUI_API void Build(); }; // Helper: Text buffer for logging/accumulating text struct ImGuiTextBuffer { ImVector<char> Buf; ImGuiTextBuffer() { Buf.push_back(0); } inline char operator[](int i) { return Buf.Data[i]; } const char* begin() const { return &Buf.front(); } const char* end() const { return &Buf.back(); } // Buf is zero-terminated, so end() will point on the zero-terminator int size() const { return Buf.Size - 1; } bool empty() { return Buf.Size <= 1; } void clear() { Buf.clear(); Buf.push_back(0); } const char* c_str() const { return Buf.Data; } IMGUI_API void append(const char* fmt, ...) IM_FMTARGS(2); IMGUI_API void appendv(const char* fmt, va_list args) IM_FMTLIST(2); }; // Helper: Simple Key->value storage // Typically you don't have to worry about this since a storage is held within each Window. // We use it to e.g. store collapse state for a tree (Int 0/1), store color edit options. // This is optimized for efficient reading (dichotomy into a contiguous buffer), rare writing (typically tied to user interactions) // You can use it as custom user storage for temporary values. Declare your own storage if, for example: // - You want to manipulate the open/close state of a particular sub-tree in your interface (tree node uses Int 0/1 to store their state). // - You want to store custom debug data easily without adding or editing structures in your code (probably not efficient, but convenient) // Types are NOT stored, so it is up to you to make sure your Key don't collide with different types. struct ImGuiStorage { struct Pair { ImGuiID key; union { int val_i; float val_f; void* val_p; }; Pair(ImGuiID _key, int _val_i) { key = _key; val_i = _val_i; } Pair(ImGuiID _key, float _val_f) { key = _key; val_f = _val_f; } Pair(ImGuiID _key, void* _val_p) { key = _key; val_p = _val_p; } }; ImVector<Pair> Data; // - Get***() functions find pair, never add/allocate. Pairs are sorted so a query is O(log N) // - Set***() functions find pair, insertion on demand if missing. // - Sorted insertion is costly, paid once. A typical frame shouldn't need to insert any new pair. IMGUI_API void Clear(); IMGUI_API int GetInt(ImGuiID key, int default_val = 0) const; IMGUI_API void SetInt(ImGuiID key, int val); IMGUI_API bool GetBool(ImGuiID key, bool default_val = false) const; IMGUI_API void SetBool(ImGuiID key, bool val); IMGUI_API float GetFloat(ImGuiID key, float default_val = 0.0f) const; IMGUI_API void SetFloat(ImGuiID key, float val); IMGUI_API void* GetVoidPtr(ImGuiID key) const; // default_val is NULL IMGUI_API void SetVoidPtr(ImGuiID key, void* val); // - Get***Ref() functions finds pair, insert on demand if missing, return pointer. Useful if you intend to do Get+Set. // - References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. // - A typical use case where this is convenient for quick hacking (e.g. add storage during a live Edit&Continue session if you can't modify existing struct) // float* pvar = ImGui::GetFloatRef(key); ImGui::SliderFloat("var", pvar, 0, 100.0f); some_var += *pvar; IMGUI_API int* GetIntRef(ImGuiID key, int default_val = 0); IMGUI_API bool* GetBoolRef(ImGuiID key, bool default_val = false); IMGUI_API float* GetFloatRef(ImGuiID key, float default_val = 0.0f); IMGUI_API void** GetVoidPtrRef(ImGuiID key, void* default_val = NULL); // Use on your own storage if you know only integer are being stored (open/close all tree nodes) IMGUI_API void SetAllInt(int val); }; // Shared state of InputText(), passed to callback when a ImGuiInputTextFlags_Callback* flag is used and the corresponding callback is triggered. struct ImGuiTextEditCallbackData { ImGuiInputTextFlags EventFlag; // One of ImGuiInputTextFlags_Callback* // Read-only ImGuiInputTextFlags Flags; // What user passed to InputText() // Read-only void* UserData; // What user passed to InputText() // Read-only bool ReadOnly; // Read-only mode // Read-only // CharFilter event: ImWchar EventChar; // Character input // Read-write (replace character or set to zero) // Completion,History,Always events: // If you modify the buffer contents make sure you update 'BufTextLen' and set 'BufDirty' to true. ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only char* Buf; // Current text buffer // Read-write (pointed data only, can't replace the actual pointer) int BufTextLen; // Current text length in bytes // Read-write int BufSize; // Maximum text length in bytes // Read-only bool BufDirty; // Set if you modify Buf/BufTextLen!! // Write int CursorPos; // // Read-write int SelectionStart; // // Read-write (== to SelectionEnd when no selection) int SelectionEnd; // // Read-write // NB: Helper functions for text manipulation. Calling those function loses selection. IMGUI_API void DeleteChars(int pos, int bytes_count); IMGUI_API void InsertChars(int pos, const char* text, const char* text_end = NULL); bool HasSelection() const { return SelectionStart != SelectionEnd; } }; // Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin(). // NB: For basic min/max size constraint on each axis you don't need to use the callback! The SetNextWindowSizeConstraints() parameters are enough. struct ImGuiSizeConstraintCallbackData { void* UserData; // Read-only. What user passed to SetNextWindowSizeConstraints() ImVec2 Pos; // Read-only. Window position, for reference. ImVec2 CurrentSize; // Read-only. Current window size. ImVec2 DesiredSize; // Read-write. Desired size, based on user's mouse position. Write to this field to restrain resizing. }; // Helpers macros to generate 32-bits encoded colors #ifdef IMGUI_USE_BGRA_PACKED_COLOR #define IM_COL32_R_SHIFT 16 #define IM_COL32_G_SHIFT 8 #define IM_COL32_B_SHIFT 0 #define IM_COL32_A_SHIFT 24 #define IM_COL32_A_MASK 0xFF000000 #else #define IM_COL32_R_SHIFT 0 #define IM_COL32_G_SHIFT 8 #define IM_COL32_B_SHIFT 16 #define IM_COL32_A_SHIFT 24 #define IM_COL32_A_MASK 0xFF000000 #endif #define IM_COL32(R,G,B,A) (((ImU32)(A)<<IM_COL32_A_SHIFT) | ((ImU32)(B)<<IM_COL32_B_SHIFT) | ((ImU32)(G)<<IM_COL32_G_SHIFT) | ((ImU32)(R)<<IM_COL32_R_SHIFT)) #define IM_COL32_WHITE IM_COL32(255,255,255,255) // Opaque white = 0xFFFFFFFF #define IM_COL32_BLACK IM_COL32(0,0,0,255) // Opaque black #define IM_COL32_BLACK_TRANS IM_COL32(0,0,0,0) // Transparent black = 0x00000000 // ImColor() helper to implicity converts colors to either ImU32 (packed 4x1 byte) or ImVec4 (4x1 float) // Prefer using IM_COL32() macros if you want a guaranteed compile-time ImU32 for usage with ImDrawList API. // **Avoid storing ImColor! Store either u32 of ImVec4. This is not a full-featured color class. MAY OBSOLETE. // **None of the ImGui API are using ImColor directly but you can use it as a convenience to pass colors in either ImU32 or ImVec4 formats. Explicitly cast to ImU32 or ImVec4 if needed. struct ImColor { ImVec4 Value; ImColor() { Value.x = Value.y = Value.z = Value.w = 0.0f; } ImColor(int r, int g, int b, int a = 255) { float sc = 1.0f/255.0f; Value.x = (float)r * sc; Value.y = (float)g * sc; Value.z = (float)b * sc; Value.w = (float)a * sc; } ImColor(ImU32 rgba) { float sc = 1.0f/255.0f; Value.x = (float)((rgba>>IM_COL32_R_SHIFT)&0xFF) * sc; Value.y = (float)((rgba>>IM_COL32_G_SHIFT)&0xFF) * sc; Value.z = (float)((rgba>>IM_COL32_B_SHIFT)&0xFF) * sc; Value.w = (float)((rgba>>IM_COL32_A_SHIFT)&0xFF) * sc; } ImColor(float r, float g, float b, float a = 1.0f) { Value.x = r; Value.y = g; Value.z = b; Value.w = a; } ImColor(const ImVec4& col) { Value = col; } inline operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); } inline operator ImVec4() const { return Value; } // FIXME-OBSOLETE: May need to obsolete/cleanup those helpers. inline void SetHSV(float h, float s, float v, float a = 1.0f){ ImGui::ColorConvertHSVtoRGB(h, s, v, Value.x, Value.y, Value.z); Value.w = a; } static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r,g,b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r,g,b,a); } }; // Helper: Manually clip large list of items. // If you are submitting lots of evenly spaced items and you have a random access to the list, you can perform coarse clipping based on visibility to save yourself from processing those items at all. // The clipper calculates the range of visible items and advance the cursor to compensate for the non-visible items we have skipped. // ImGui already clip items based on their bounds but it needs to measure text size to do so. Coarse clipping before submission makes this cost and your own data fetching/submission cost null. // Usage: // ImGuiListClipper clipper(1000); // we have 1000 elements, evenly spaced. // while (clipper.Step()) // for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) // ImGui::Text("line number %d", i); // - Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height (step skipped if we passed a known height as second arg to constructor). // - Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element. // - (Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user call Step(). Does nothing and switch to Step 3.) // - Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop. struct ImGuiListClipper { float StartPosY; float ItemsHeight; int ItemsCount, StepNo, DisplayStart, DisplayEnd; // items_count: Use -1 to ignore (you can call Begin later). Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step). // items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetItemsLineHeightWithSpacing(). // If you don't specify an items_height, you NEED to call Step(). If you specify items_height you may call the old Begin()/End() api directly, but prefer calling Step(). ImGuiListClipper(int items_count = -1, float items_height = -1.0f) { Begin(items_count, items_height); } // NB: Begin() initialize every fields (as we allow user to call Begin/End multiple times on a same instance if they want). ~ImGuiListClipper() { IM_ASSERT(ItemsCount == -1); } // Assert if user forgot to call End() or Step() until false. IMGUI_API bool Step(); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items. IMGUI_API void Begin(int items_count, float items_height = -1.0f); // Automatically called by constructor if you passed 'items_count' or by Step() in Step 1. IMGUI_API void End(); // Automatically called on the last call of Step() that returns false. }; //----------------------------------------------------------------------------- // Draw List // Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. //----------------------------------------------------------------------------- // Draw callbacks for advanced uses. // NB- You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering (you can poke into the draw list for that) // Draw callback may be useful for example, A) Change your GPU render state, B) render a complex 3D scene inside a UI element (without an intermediate texture/render target), etc. // The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) cmd.UserCallback(parent_list, cmd); else RenderTriangles()' typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd); // Typically, 1 command = 1 gpu draw call (unless command is a callback) struct ImDrawCmd { unsigned int ElemCount; // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[]. ImVec4 ClipRect; // Clipping rectangle (x1, y1, x2, y2) ImTextureID TextureId; // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas. ImDrawCallback UserCallback; // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. void* UserCallbackData; // The draw callback code can access this. ImDrawCmd() { ElemCount = 0; ClipRect.x = ClipRect.y = -8192.0f; ClipRect.z = ClipRect.w = +8192.0f; TextureId = NULL; UserCallback = NULL; UserCallbackData = NULL; } }; // Vertex index (override with '#define ImDrawIdx unsigned int' inside in imconfig.h) #ifndef ImDrawIdx typedef unsigned short ImDrawIdx; #endif // Vertex layout #ifndef IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert { ImVec2 pos; ImVec2 uv; ImU32 col; }; #else // You can override the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h // The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine. // The type has to be described within the macro (you can either declare the struct or use a typedef) // NOTE: IMGUI DOESN'T CLEAR THE STRUCTURE AND DOESN'T CALL A CONSTRUCTOR SO ANY CUSTOM FIELD WILL BE UNINITIALIZED. IF YOU ADD EXTRA FIELDS (SUCH AS A 'Z' COORDINATES) YOU WILL NEED TO CLEAR THEM DURING RENDER OR TO IGNORE THEM. IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT; #endif // Draw channels are used by the Columns API to "split" the render list into different channels while building, so items of each column can be batched together. // You can also use them to simulate drawing layers and submit primitives in a different order than how they will be rendered. struct ImDrawChannel { ImVector<ImDrawCmd> CmdBuffer; ImVector<ImDrawIdx> IdxBuffer; }; // Draw command list // This is the low-level list of polygons that ImGui functions are filling. At the end of the frame, all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering. // At the moment, each ImGui window contains its own ImDrawList but they could potentially be merged in the future. // If you want to add custom rendering within a window, you can use ImGui::GetWindowDrawList() to access the current draw list and add your own primitives. // You can interleave normal ImGui:: calls and adding primitives to the current draw list. // All positions are generally in pixel coordinates (top-left at (0,0), bottom-right at io.DisplaySize), however you are totally free to apply whatever transformation matrix to want to the data (if you apply such transformation you'll want to apply it to ClipRect as well) // Primitives are always added to the list and not culled (culling is done at higher-level by ImGui:: functions). struct ImDrawList { // This is what you have to render ImVector<ImDrawCmd> CmdBuffer; // Commands. Typically 1 command = 1 GPU draw call. ImVector<ImDrawIdx> IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those ImVector<ImDrawVert> VtxBuffer; // Vertex buffer. // [Internal, used while building lists] const char* _OwnerName; // Pointer to owner window's name for debugging unsigned int _VtxCurrentIdx; // [Internal] == VtxBuffer.Size ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) ImVector<ImVec4> _ClipRectStack; // [Internal] ImVector<ImTextureID> _TextureIdStack; // [Internal] ImVector<ImVec2> _Path; // [Internal] current path building int _ChannelsCurrent; // [Internal] current channel number (0) int _ChannelsCount; // [Internal] number of active channels (1+) ImVector<ImDrawChannel> _Channels; // [Internal] draw channels for columns API (not resized down so _ChannelsCount may be smaller than _Channels.Size) ImDrawList() { _OwnerName = NULL; Clear(); } ~ImDrawList() { ClearFreeMemory(); } IMGUI_API void PushClipRect(ImVec2 clip_rect_min, ImVec2 clip_rect_max, bool intersect_with_current_clip_rect = false); // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) IMGUI_API void PushClipRectFullScreen(); IMGUI_API void PopClipRect(); IMGUI_API void PushTextureID(const ImTextureID& texture_id); IMGUI_API void PopTextureID(); inline ImVec2 GetClipRectMin() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.x, cr.y); } inline ImVec2 GetClipRectMax() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.z, cr.w); } // Primitives IMGUI_API void AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness = 1.0f); IMGUI_API void AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ~0, float thickness = 1.0f); // a: upper-left, b: lower-right, rounding_corners_flags: 4-bits corresponding to which corner to round IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ~0); // a: upper-left, b: lower-right IMGUI_API void AddRectFilledMultiColor(const ImVec2& a, const ImVec2& b, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left); IMGUI_API void AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col, float thickness = 1.0f); IMGUI_API void AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col); IMGUI_API void AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col, float thickness = 1.0f); IMGUI_API void AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col); IMGUI_API void AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12, float thickness = 1.0f); IMGUI_API void AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12); IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL); IMGUI_API void AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL); IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,1), ImU32 col = 0xFFFFFFFF); IMGUI_API void AddImageQuad(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,0), const ImVec2& uv_c = ImVec2(1,1), const ImVec2& uv_d = ImVec2(0,1), ImU32 col = 0xFFFFFFFF); IMGUI_API void AddPolyline(const ImVec2* points, const int num_points, ImU32 col, bool closed, float thickness, bool anti_aliased); IMGUI_API void AddConvexPolyFilled(const ImVec2* points, const int num_points, ImU32 col, bool anti_aliased); IMGUI_API void AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments = 0); // Stateful path API, add points then finish with PathFill() or PathStroke() inline void PathClear() { _Path.resize(0); } inline void PathLineTo(const ImVec2& pos) { _Path.push_back(pos); } inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path[_Path.Size-1], &pos, 8) != 0) _Path.push_back(pos); } inline void PathFillConvex(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col, true); PathClear(); } inline void PathStroke(ImU32 col, bool closed, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, closed, thickness, true); PathClear(); } IMGUI_API void PathArcTo(const ImVec2& centre, float radius, float a_min, float a_max, int num_segments = 10); IMGUI_API void PathArcToFast(const ImVec2& centre, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle IMGUI_API void PathBezierCurveTo(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, int num_segments = 0); IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, int rounding_corners_flags = ~0); // rounding_corners_flags: 4-bits corresponding to which corner to round // Channels // - Use to simulate layers. By switching channels to can render out-of-order (e.g. submit foreground primitives before background primitives) // - Use to minimize draw calls (e.g. if going back-and-forth between multiple non-overlapping clipping rectangles, prefer to append into separate channels then merge at the end) IMGUI_API void ChannelsSplit(int channels_count); IMGUI_API void ChannelsMerge(); IMGUI_API void ChannelsSetCurrent(int channel_index); // Advanced IMGUI_API void AddCallback(ImDrawCallback callback, void* callback_data); // Your rendering function must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles. IMGUI_API void AddDrawCmd(); // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible // Internal helpers // NB: all primitives needs to be reserved via PrimReserve() beforehand! IMGUI_API void Clear(); IMGUI_API void ClearFreeMemory(); IMGUI_API void PrimReserve(int idx_count, int vtx_count); IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); // Axis aligned rectangle (composed of two triangles) IMGUI_API void PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col); IMGUI_API void PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col); inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col){ _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; } inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; } inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } IMGUI_API void UpdateClipRect(); IMGUI_API void UpdateTextureID(); }; // All draw data to render an ImGui frame struct ImDrawData { bool Valid; // Only valid after Render() is called and before the next NewFrame() is called. ImDrawList** CmdLists; int CmdListsCount; int TotalVtxCount; // For convenience, sum of all cmd_lists vtx_buffer.Size int TotalIdxCount; // For convenience, sum of all cmd_lists idx_buffer.Size // Functions ImDrawData() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; } IMGUI_API void DeIndexAllBuffers(); // For backward compatibility or convenience: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! IMGUI_API void ScaleClipRects(const ImVec2& sc); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. }; struct ImFontConfig { void* FontData; // // TTF/OTF data int FontDataSize; // // TTF/OTF data size bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself). int FontNo; // 0 // Index of font within TTF/OTF file float SizePixels; // // Size in pixels for rasterizer. int OversampleH, OversampleV; // 3, 1 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis. bool PixelSnapH; // false // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs. Only X axis is supported for now. ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input. const ImWchar* GlyphRanges; // NULL // Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. unsigned int RasterizerFlags; // 0x00 // Settings for custom font rasterizer (e.g. ImGuiFreeType). Leave as zero if you aren't using one. float RasterizerMultiply; // 1.0f // Brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. // [Internal] char Name[32]; // Name (strictly to ease debugging) ImFont* DstFont; IMGUI_API ImFontConfig(); }; // Load and rasterize multiple TTF/OTF fonts into a same texture. // Sharing a texture for multiple fonts allows us to reduce the number of draw calls during rendering. // We also add custom graphic data into the texture that serves for ImGui. // 1. (Optional) Call AddFont*** functions. If you don't call any, the default font will be loaded for you. // 2. Call GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data. // 3. Upload the pixels data into a texture within your graphics system. // 4. Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture. This value will be passed back to you during rendering to identify the texture. // IMPORTANT: If you pass a 'glyph_ranges' array to AddFont*** functions, you need to make sure that your array persist up until the ImFont is build (when calling GetTextData*** or Build()). We only copy the pointer, not the data. struct ImFontAtlas { IMGUI_API ImFontAtlas(); IMGUI_API ~ImFontAtlas(); IMGUI_API ImFont* AddFont(const ImFontConfig* font_cfg); IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL); IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); IMGUI_API ImFont* AddFontFromMemoryTTF(void* font_data, int font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Transfer ownership of 'ttf_data' to ImFontAtlas, will be deleted after Build() IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_font_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 paramaeter IMGUI_API void ClearTexData(); // Clear the CPU-side texture data. Saves RAM once the texture has been copied to graphics memory. IMGUI_API void ClearInputData(); // Clear the input TTF data (inc sizes, glyph ranges) IMGUI_API void ClearFonts(); // Clear the ImGui-side font data (glyphs storage, UV coordinates) IMGUI_API void Clear(); // Clear all // Retrieve texture data // User is in charge of copying the pixels into graphics memory, then call SetTextureUserID() // After loading the texture into your graphic system, store your texture handle in 'TexID' (ignore if you aren't using multiple fonts nor images) // RGBA32 format is provided for convenience and high compatibility, but note that all RGB pixels are white, so 75% of the memory is wasted. // Pitch = Width * BytesPerPixels IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel void SetTexID(ImTextureID id) { TexID = id; } // Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list) // NB: Make sure that your string are UTF-8 and NOT in your local code page. In C++11, you can create UTF-8 string literal using the u8"Hello world" syntax. See FAQ for details. IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs IMGUI_API const ImWchar* GetGlyphRangesChinese(); // Japanese + full set of about 21000 CJK Unified Ideographs IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters IMGUI_API const ImWchar* GetGlyphRangesThai(); // Default + Thai characters // Helpers to build glyph ranges from text data. Feed all your application strings/characters to it then call BuildRanges(). struct GlyphRangesBuilder { ImVector<unsigned char> UsedChars; // Store 1-bit per Unicode code point (0=unused, 1=used) GlyphRangesBuilder() { UsedChars.resize(0x10000 / 8); memset(UsedChars.Data, 0, 0x10000 / 8); } bool GetBit(int n) { return (UsedChars[n >> 3] & (1 << (n & 7))) != 0; } void SetBit(int n) { UsedChars[n >> 3] |= 1 << (n & 7); } // Set bit 'c' in the array void AddChar(ImWchar c) { SetBit(c); } // Add character IMGUI_API void AddText(const char* text, const char* text_end = NULL); // Add string (each character of the UTF-8 string are added) IMGUI_API void AddRanges(const ImWchar* ranges); // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault) to force add all of ASCII/Latin+Ext IMGUI_API void BuildRanges(ImVector<ImWchar>* out_ranges); // Output new ranges }; // Members // (Access texture data via GetTexData*() calls which will setup a default font for you.) ImTextureID TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure. unsigned char* TexPixelsAlpha8; // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight unsigned int* TexPixelsRGBA32; // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 int TexWidth; // Texture width calculated during Build(). int TexHeight; // Texture height calculated during Build(). int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height. int TexGlyphPadding; // Padding between glyphs within texture in pixels. Defaults to 1. ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel ImVector<ImFont*> Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. // [Private] User rectangle for packing custom texture data into the atlas. struct CustomRect { unsigned int ID; // Input // User ID. <0x10000 for font mapped data (WIP/UNSUPPORTED), >=0x10000 for other texture data unsigned short Width, Height; // Input // Desired rectangle dimension unsigned short X, Y; // Output // Packed position in Atlas CustomRect() { ID = 0xFFFFFFFF; Width = Height = 0; X = Y = 0xFFFF; } bool IsPacked() const { return X != 0xFFFF; } }; // [Private] Members ImVector<CustomRect> CustomRects; // Rectangles for packing custom texture data into the atlas. ImVector<ImFontConfig> ConfigData; // Internal data IMGUI_API bool Build(); // Build pixels data. This is automatically for you by the GetTexData*** functions. IMGUI_API int CustomRectRegister(unsigned int id, int width, int height); IMGUI_API void CustomRectCalcUV(const CustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max); }; // Font runtime data and rendering // ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32(). struct ImFont { struct Glyph { ImWchar Codepoint; float XAdvance; float X0, Y0, X1, Y1; float U0, V0, U1, V1; // Texture coordinates }; // Members: Hot ~62/78 bytes float FontSize; // <user set> // Height of characters, set during loading (don't change after loading) float Scale; // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetFontScale() ImVec2 DisplayOffset; // = (0.f,1.f) // Offset font rendering by xx pixels ImVector<Glyph> Glyphs; // // All glyphs. ImVector<float> IndexXAdvance; // // Sparse. Glyphs->XAdvance in a directly indexable way (more cache-friendly, for CalcTextSize functions which are often bottleneck in large UI). ImVector<unsigned short> IndexLookup; // // Sparse. Index glyphs by Unicode code-point. const Glyph* FallbackGlyph; // == FindGlyph(FontFallbackChar) float FallbackXAdvance; // == FallbackGlyph->XAdvance ImWchar FallbackChar; // = '?' // Replacement glyph if one isn't found. Only set via SetFallbackChar() // Members: Cold ~18/26 bytes short ConfigDataCount; // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont. ImFontConfig* ConfigData; // // Pointer within ContainerAtlas->ConfigData ImFontAtlas* ContainerAtlas; // // What we has been loaded into float Ascent, Descent; // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] int MetricsTotalSurface;// // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) // Methods IMGUI_API ImFont(); IMGUI_API ~ImFont(); IMGUI_API void Clear(); IMGUI_API void BuildLookupTable(); IMGUI_API const Glyph* FindGlyph(ImWchar c) const; IMGUI_API void SetFallbackChar(ImWchar c); float GetCharAdvance(ImWchar c) const { return ((int)c < IndexXAdvance.Size) ? IndexXAdvance[(int)c] : FallbackXAdvance; } bool IsLoaded() const { return ContainerAtlas != NULL; } // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable. // 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable. IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL) const; // utf8 IMGUI_API const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const; IMGUI_API void RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, unsigned short c) const; IMGUI_API void RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false) const; // Private IMGUI_API void GrowIndex(int new_size); IMGUI_API void AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built. }; #if defined(__clang__) #pragma clang diagnostic pop #endif // Include imgui_user.h at the end of imgui.h (convenient for user to only explicitly include vanilla imgui.h) #ifdef IMGUI_INCLUDE_IMGUI_USER_H #include "imgui_user.h" #endif
89144cf1a42a646726504230f4d5bed290e55c78
45ca2a12a9f6be20f1442cbe7922b27b9311899a
/h/util/UtilRefCountedPtrInlines.h
edc8025e3770af3fae9df5e9446e7a4b58873f0c
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
LoganDing/cslib
669ce63d97daf681df9f45389df5a2c762c6339c
3401fc6516e6952f01a13bb7de999c79a0937154
refs/heads/master
2020-12-24T13:29:31.181275
2015-06-03T19:32:52
2015-06-03T19:32:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,582
h
#ifndef UtilRefCountedPtrInlines_H_LOADED #define UtilRefCountedPtrInlines_H_LOADED // [ // $ UtilRefCountedPtrInlines.h // // Copyright 2011 Chris Sanchez // // 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. // ==================================================================== // // Copyright (c) 1998-2001 Chris Sanchez. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CHRIS SANCHEZ OR // ITS 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. // ==================================================================== // // This software consists of voluntary contributions made by Chris Sanchez. // Portions of other open source software were used in the creation of this // software. Header files for work based on other source bears the // orininator copyright. // // Author: Chris Sanchez // // RCS: // $Revision: 2.0 $ // $Author: $ // $Date: $ // ? // Contents: RefCountedPtrInlines class // RefCountedPtr - implementation simple reference counted pointer. // // The is a non-intrusive implementation that allocates an additional // int and pointer for every counted object. // // Purpose: // // Usage Notes: // // // ? // ! Changes History // $Header: $ // // ] #include <cslib.h> #include <util/UtilRefCountedPtr.h> template <class T> inline RefCountedPtr<T>::RefCountedPtr( T* p) : _itsCounter(NULL) { if (p != NULL) { _itsCounter = new counter(p); } } template <class T> inline RefCountedPtr<T>::~RefCountedPtr() { release(); } template <class T> inline RefCountedPtr<T>::RefCountedPtr( const RefCountedPtr<T>& r) { acquire(r._itsCounter); } template <class T> inline RefCountedPtr<T>& RefCountedPtr<T>::operator=( const RefCountedPtr<T>& r) { if (this != &r) { release(); acquire(r._itsCounter); } return *this; } template <class T> inline RefCountedPtr<T>& RefCountedPtr<T>::operator=( T* p) { if (p != get()) { release(); _itsCounter = new counter(p); } return *this; } template <class T> inline T& RefCountedPtr<T>::operator*() const { return *_itsCounter->_ptr; } template <class T> inline T* RefCountedPtr<T>::operator->() const { return _itsCounter->_ptr; } template <class T> inline T* RefCountedPtr<T>::get() const { return _itsCounter ? _itsCounter->_ptr : NULL; } template <class T> inline RefCountedPtr<T>::operator T*() const { return get(); } template <class T> inline bool RefCountedPtr<T>::operator !() const { return NULL == get(); } template <class T> inline bool RefCountedPtr<T>::operator == ( const RefCountedPtr<T>& obj2) const { return get() == obj2.get(); } template <class T> inline bool RefCountedPtr<T>::operator == ( const T* pObj1) const { return get() == pObj1; } template <class T> inline bool RefCountedPtr<T>::operator != ( const RefCountedPtr<T>& obj2) const { return get() != obj2.get(); } template <class T> inline bool RefCountedPtr<T>::operator != ( const T* pObj1) const { return pObj1 != get(); } template <class T> inline bool RefCountedPtr<T>::operator < ( const RefCountedPtr<T>& obj2) const { return get() < obj2.get(); } template <class T> inline bool RefCountedPtr<T>::operator < ( const T* obj2) const { return get() < obj2; } template <class T> inline bool RefCountedPtr<T>::operator <= ( const RefCountedPtr<T>& obj2) const { return get() <= obj2.get(); } template <class T> inline bool RefCountedPtr<T>::operator <= ( const T* obj2) const { return get() <= obj2; } template <class T> inline bool RefCountedPtr<T>::operator > ( const RefCountedPtr<T>& obj2) const { return get() > obj2.get(); } template <class T> inline bool RefCountedPtr<T>::operator > ( const T* obj2) const { return get() > obj2; } template <class T> inline bool RefCountedPtr<T>::operator >= ( const RefCountedPtr<T>& obj2) const { return get() >= obj2.get(); } template <class T> inline bool RefCountedPtr<T>::operator >= ( const T* obj2) const { return get() >= obj2; } template <class T> inline void RefCountedPtr<T>::acquire(counter* c) { // increment the count _itsCounter = c; if (c) { c->_count++; } } template <class T> inline void RefCountedPtr<T>::release() { // decrement the count, delete if it is NULL if (_itsCounter) { if (--_itsCounter->_count == 0) { delete _itsCounter->_ptr; delete _itsCounter; } _itsCounter = NULL; } } #endif
1be8eebce3afff9f6c12ff5861cacca8c5044e95
e7c0f5ddee4bd1c5a701bb42a435c68d0058114e
/test/test_mysql.cpp
6da3990b43f29bae9d9308604892f26394bf9b33
[ "MIT" ]
permissive
yuebone/dbapi
09908e339e166bf2ecaa632bba98af8adb87b4da
53a50a38b13325066ff8c20786da46f45266708e
refs/heads/master
2021-01-09T21:48:38.264883
2016-03-12T06:13:17
2016-03-12T06:13:17
34,193,899
0
0
null
null
null
null
UTF-8
C++
false
false
34,073
cpp
// // Created by bon on 15-4-22. // #include <iostream> #include <fstream> #include "dbapi.h" #include "backend/mysql/my_backend.h" using namespace std; using namespace dbapi; //string blob_path("G:/DB/Blob/"); string blob_path("/home/bon/G/DB/Blob/"); int version = 50000; //int version = 40000; #define _PRINT_ void test_multi_conn(); void test_conn(); void test_transaction(connection& conn, command& cmd); void test_num(connection& conn, command& cmd); void test_datetime(connection& conn, command& cmd); void test_datetime_prior_40100(connection& conn, command& cmd); void test_lbs(connection& conn, command& cmd); void test_procedure(); void test_text(connection& conn, command& cmd); void create_tables(connection& conn, command& cmd); void test_metadata(connection& conn); void test_foo(); void test_mysql() { try { //test_foo(); //test_conn(); //test_multi_conn(); connection_info conn_info("u1","123", "host=127.0.0.1;db=for_dbapi_test;" "CLIENT_MULTI_STATEMENTS"); if (version<40101) conn_info.set_option("MYSQL_SECURE_AUTH", "0"); connection conn(my::mysql_factory,conn_info); command cmd = conn.create_command(); std::cout << "test mysql\n"; std::cout << "cli version: " << conn.cli_version() << " ," << conn.cli_description() << endl; std::cout << "server version: " << conn.server_version() << " ," << conn.server_description() << endl; test_metadata(conn); test_multi_conn(); test_conn(); create_tables(conn,cmd); test_transaction(conn,cmd); test_num(conn,cmd); test_datetime(conn,cmd); test_datetime_prior_40100(conn,cmd); test_procedure(); test_text(conn,cmd); test_lbs(conn,cmd); } catch (db_exception& e) { cerr << "!!!catch db_exception\n"; if (e.get_error_type() == user_err) { cerr << "user_err:\n"; cerr << e.what() << endl; } else if (e.get_error_type() == dbapi_err) { cerr << "dbapi_err:\n"; cerr << e.what() << endl; } else if (e.get_error_type() == dbms_err) { cerr << "dbms_err("<<e.get_dbms_name()<<"):\n"; cerr << e.what() << endl; cerr << "errno:" << e.get_error_code() << endl; } return; } catch (exception& e) { cerr<<e.what()<<endl; } } void create_tables(connection& conn, command& cmd) { cout << "create tables \n"; cmd.execute_once("DROP TABLE IF EXISTS foo"); if (version>=40101) cmd.execute_once("CREATE TABLE foo(id INT PRIMARY KEY,name VARCHAR(20)) ENGINE= InnoDB"); else cmd.execute_once("CREATE TABLE foo(id INT PRIMARY KEY,name VARCHAR(20))"); cmd.execute_once("DROP TABLE IF EXISTS num"); cmd.execute_once ("create table num(id INT AUTO_INCREMENT PRIMARY KEY," "b BIT, ty TINYINT," "uint INT UNSIGNED, in3 INT(3), big_int BIGINT," "de DECIMAL(8, 7), ft FLOAT, dou DOUBLE," "boo BOOL)"); cmd.execute_once("DROP TABLE IF EXISTS timet"); if (conn.server_version() < 50604) cmd.execute_once ("create table timet(tsmp timestamp DEFAULT CURRENT_TIMESTAMP," "dt datetime, d date, tm time, yr year)"); else cmd.execute_once ("create table timet(tsmp timestamp DEFAULT CURRENT_TIMESTAMP," "dt datetime, d date, tm time, yr year, tm3 time(3), dt6 datetime(6)) "); cmd.execute_once("DROP TABLE IF EXISTS lbs"); cmd.execute_once ("create table lbs(id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), lb LONGBLOB);"); cmd.execute_once("DROP TABLE IF EXISTS txt_c;"); cmd.execute_once ("CREATE TABLE txt_c(id INT AUTO_INCREMENT PRIMARY KEY," "name VARCHAR(50), c LONGTEXT," "cutf8 LONGTEXT CHARACTER SET utf8, cunicode LONGTEXT CHARACTER SET ucs2)"); cmd.execute_once("DROP TABLE IF EXISTS txt;"); cmd.execute_once("DROP TABLE IF EXISTS txt_ucs2;"); cmd.execute_once("DROP TABLE IF EXISTS txt_utf8;"); cmd.execute_once ("CREATE TABLE txt_utf8(id INT AUTO_INCREMENT PRIMARY KEY, " "name VARCHAR(50), c LONGTEXT) CHARACTER SET utf8"); cmd.execute_once ("CREATE TABLE txt_ucs2( id INT AUTO_INCREMENT PRIMARY KEY," "name VARCHAR(50), c LONGTEXT) CHARACTER SET ucs2"); cmd.execute_once ("CREATE TABLE txt( id INT AUTO_INCREMENT PRIMARY KEY," "name VARCHAR(50), c LONGTEXT)"); cout << "create tables done\n"; } //FIX ME void test_metadata(connection& conn) { #ifdef _PRINT_ { metadata meta=conn.get_metadata(); meta.get_dbs(""); cout<<"dbs count("<<meta.db_count()<<") :\n"; int db_i=0; for(int i=0;i<meta.db_count();++i) { db d=meta.get_db(i); if(d.name()=="for_dbapi_test") db_i=i; cout<<d.name()<<"\n"; } cout<<"\n"; db d=meta.get_db(db_i); d.get_tables(""); cout<<"for_dbapi_test table_count("<<d.table_count()<<") :\n"; int foo_i=0; for(int i=0;i<d.table_count();++i) { table t=d.get_table(i); if(t.name()=="foo") foo_i=i; cout<<t.name()<<"\n"; } cout<<"\n"; table t=d.get_table(foo_i); cout<<"table foo:\n"; for(int i=0;i<t.column_count();++i) { cout<<"col "<<i<<" : "; cout<<t[i].name()<<"\t"<<t[i].type_name()<<"\n"; } } #endif { metadata meta = conn.get_metadata(); meta.get_dbs("for_dbapi_test"); assert(meta.db_count() == 1); db d=meta.get_db(0); assert(d.name()=="for_dbapi_test"); d.get_tables("foo"); assert(d.table_count()==1); table tbl=d.get_table(0); assert(tbl.name()=="foo"); assert(tbl.column_count()==2); assert(tbl[0].name()=="id"); assert(tbl[0].type_name().substr(0,3)=="int"); assert(tbl[0].required()==true); assert(tbl[1].name()=="name"); assert(tbl[1].type_name()=="varchar(20)"); assert(tbl[1].required()==false); assert(tbl["id"].pos()==0); assert(tbl["name"].pos()==1); d.get_tables("%txt%"); assert(d.table_count()==4); bool has_txt= false; for(int i=0;i<4;++i) { tbl=d.get_table(i); if(tbl.name()=="txt") { has_txt=true; assert(tbl.column_count()==3); assert(tbl[0].name()=="id"); assert(tbl[1].name()=="name"); assert(tbl[2].name()=="c"); } } assert(has_txt); } } void version_not_support(unsigned long v, const string &str) { std::cout << "!!!version " << v << "\n"; std::cout << "\t" << str << endl; } void test_transaction(connection& conn, command& cmd) { //assert table foo store in InnoDb cout << "test transaction" << endl; unsigned long server_version = conn.server_version(); if (server_version < 40100) { version_not_support(server_version, "not support transaction"); return; } assert(conn.auto_commit()); cmd.execute_once("delete from foo"); conn.set_auto_commit(false); assert(!conn.auto_commit()); conn.begin(); cmd.execute_once("insert into foo values(1,'1abc')"); cmd.prepare("insert into foo values(?,?)"); cmd.bind(0, 2); cmd.bind(1, "2abc"); cmd.execute(); conn.commit(); conn.begin(); cmd.bind(0, 3); cmd.bind(1, "3abc"); cmd.execute(); cmd.execute_once("insert into foo values(4,'4abc')"); conn.rollback(); result_set res2 = cmd.execute_once("select * from foo order by id"); assert(res2.row_count() == 2); res2.next_row(); assert(res2.get_int(0) == 1); assert(res2.get_string(1) == "1abc"); res2.next_row(); assert(res2.get_int(0) == 2); assert(res2.get_string(1) == "2abc"); conn.set_auto_commit(true); assert(conn.auto_commit()); cout << "test transaction done" << endl; } inline void _assert_result_meta(const result_set& res, int pos, const string& name,bool required,c_type data_type) { assert(res.name(pos) == name); assert(res.required(pos)==required); assert(res.data_type(pos) == data_type); } void test_num(connection& conn, command& cmd) { cout << "test num" << endl; cmd.execute_once("delete from num"); /* +-------- - +------------------ + | Field | Type | +-------- - +------------------ + | id | int(11) |0 | b | bit(1) |1 | ty | tinyint(4) |2 | uint | int(10) unsigned |3 | in3 | int(3) |4 | big_int | bigint(20) |5 | de | decimal(8, 7) |6 | ft | float |7 | dou | double |8 | boo | tinyint(1) |9 +-------- - +------------------ + */ //----------------------------------0,1,2,3,4,5,6,7,8,9 db_null _null; bool _1_b = true; short _2_ty = 16; unsigned int _3_uint = 1024000000; int _4_int3 = 999; long long _5_big_int = 123456789012345; double _6_de = 1.12345; float _7_ft = 123.456; double _8_dou = 123.12345; bool _9_boo = true; if (conn.server_version()>= 40102){ string stmt("insert into num values(?,?,?,?,?,?,?,?,?,?)"); cmd.prepare(stmt); cmd.bind(0,_null); cmd.bind(1, _1_b); cmd.bind(2, _2_ty); cmd.bind(3, _3_uint); cmd.bind(4, _4_int3); cmd.bind(5, _5_big_int); cmd.bind(6, _6_de); cmd.bind(7, _7_ft); cmd.bind(8, _8_dou); cmd.bind(9, _9_boo); cmd.execute(); cmd.bind(1,_null); cmd.bind(2, _null); cmd.bind(3, db_numeric("12345.012345"));//uint cmd.bind(4, _null); cmd.bind(5, _null); cmd.bind(6, db_numeric("1.0123456"));//decimal cmd.bind(7, _null); cmd.bind(8, db_numeric("12345.012345"));//double cmd.bind(9, _null); cmd.execute(); cmd.prepare("select * from num"); result_set res = cmd.execute(); assert(res.get_type()==ok_rs); assert(res.field_count() == 10); _assert_result_meta(res, 0, "id", true,type_int); //_assert_result_meta(res, 1, "b", false,type_bool); _assert_result_meta(res, 2, "ty", false, type_tinyint); _assert_result_meta(res, 3, "uint", false, type_int); _assert_result_meta(res, 4, "in3", false, type_int); _assert_result_meta(res, 5, "big_int", false, type_long_long); _assert_result_meta(res, 6, "de", false,type_db_numeric); assert(res.field_precision(6) == 8); assert(res.field_scale(6) == 7); _assert_result_meta(res, 7, "ft", false,type_float); _assert_result_meta(res, 8, "dou", false,type_double); _assert_result_meta(res, 9, "boo", false, type_tinyint); assert(res.row_count() == 2); assert(res.next_row()); assert(res.get_bool(1) == _1_b); assert(res.get_short(2) == _2_ty); assert(res.get_string(2) == "16"); assert((res.get_int(3)) == _3_uint); assert(res.get_string(3) == "1024000000"); assert(res.get_int(4) == _4_int3); assert(res.get_string(4) == "999"); assert(res.get_long_long(5) == _5_big_int); assert(res.get_string(5) == "123456789012345"); db_numeric de = res.get_numeric(6); assert(de.get_double() == _6_de); assert(res.get_float(7) == _7_ft); assert(res.get_double(8) == _8_dou); assert(res.get_string(8) == "123.12345"); assert(res.get_bool(9) == _9_boo); assert(res.next_row()); assert(res.get_field_type(1)==null_field); assert(res.get_field_type(2) == null_field); assert((res.get_int(3)) == 12345); assert(res.get_field_type(4) == null_field); assert(res.get_field_type(5) == null_field); assert(res.get_numeric(6).get_string() == "1.0123456"); assert(res.get_field_type(7) == null_field); assert(res.get_double(8) == 12345.012345); assert(res.get_field_type(9) == null_field); cmd.execute_once("delete from num"); } cmd.execute_once("insert into num values" "(null,1,16,1024000000,999,123456789012345,1.12345,123.456,123.12345,1)"); cmd.execute_once("insert into num values" "(null,null,null,'12345.012345',null,null,'1.0123456',null,'12345.012345',null)"); result_set res2 = cmd.execute_once("select * from num"); assert(res2.field_count() == 10); _assert_result_meta(res2, 0, "id", true,type_char_str); _assert_result_meta(res2, 1, "b", false, type_char_str); _assert_result_meta(res2, 2, "ty", false, type_char_str); _assert_result_meta(res2, 3, "uint", false, type_char_str); _assert_result_meta(res2, 4, "in3", false, type_char_str); _assert_result_meta(res2, 5, "big_int", false, type_char_str); _assert_result_meta(res2, 6, "de", false, type_char_str); assert(res2.field_precision(6) == 8); assert(res2.field_scale(6) == 7); _assert_result_meta(res2, 7, "ft", false, type_char_str); _assert_result_meta(res2, 8, "dou", false, type_char_str); _assert_result_meta(res2, 9, "boo", false, type_char_str); assert(res2.row_count() == 2); assert(res2.next_row()); string sss1 = res2.get_string(1); //cout << bool(res2.get_bool(1)) << "," << _1_b << endl; assert(res2.get_bool(1)); assert(res2.get_string(2) == "16"); assert(res2.get_short(2) == _2_ty); assert(res2.get_string(3) == "1024000000"); assert((res2.get_int(3)) == _3_uint); assert(res2.get_string(4) == "999"); assert(res2.get_int(4) == _4_int3); assert(res2.get_string(5) == "123456789012345"); assert(res2.get_long_long(5) == _5_big_int); db_numeric de = res2.get_numeric(6); assert(res2.get_string(6) == "1.1234500"); assert(de.get_double() == _6_de); assert(res2.get_string(7) == "123.456"); assert(res2.get_float(7) == _7_ft); assert(res2.get_string(8) == "123.12345"); assert(res2.get_double(8) == _8_dou); assert(res2.get_string(9) == "1"); assert(res2.get_bool(9) == _9_boo); assert(res2.next_row()); assert(res2.get_field_type(1) == null_field); assert(res2.get_field_type(2) == null_field); assert((res2.get_int(3)) == 12345); assert(res2.get_field_type(4) == null_field); assert(res2.get_field_type(5) == null_field); assert(res2.get_numeric(6).get_string() == "1.0123456"); assert(res2.get_field_type(7) == null_field); assert(res2.get_double(8) == 12345.012345); assert(res2.get_field_type(9) == null_field); cout << "test num done" << endl; } void test_datetime(connection& conn, command& cmd) { cout << "test datetime" << endl; /* +------ - +------------ - +------ + | Field | Type | Null | +------ - +------------ - +------ + | tsmp | timestamp | NO | | dt | datetime | YES | | d | date | YES | | tm | time | YES | | yr | year(4) | YES | | tm3 | time(3) | YES | | dt6 | datetime(6) | YES | +------ - +------------ - +------ + */ cmd.execute_once("delete from timet"); string _0_str("2014-12-18 14:07:00"); string _1_str("2014-12-17 14:07:00"); string _2_str("1999-12-19"); string _3_str("12:13:14"); int yr = 2014; string _5_str("08:23:09.03000"); string _6_str("2014-12-17 14:07:00.03300"); db_time tsmp(_0_str); assert(tsmp.get_type()==db_time::tm_datetime); assert(tsmp.year()==2014); assert(tsmp.month() == 12); assert(tsmp.day() == 18); assert(tsmp.hour() == 14); assert(tsmp.minute() == 7); assert(tsmp.second() == 0); assert(tsmp.to_string() == _0_str); db_time dt(_1_str); assert(dt.to_string()==_1_str); db_time d(_2_str); assert(d.to_string() == _2_str); db_time t(_3_str); assert(t.to_string()==_3_str); db_time t3(_5_str); assert(t3.to_string() == _5_str); db_time dt6(_6_str); assert(dt6.to_string()==_6_str); if (conn.server_version() > 40102){ if (conn.server_version() >= 50604){ cmd.prepare("insert into timet values(?,?,?,?,?,?,?)"); } else{ cmd.prepare("insert into timet values(?,?,?,?,?)"); } cmd.bind(0, tsmp); cmd.bind(1, dt); cmd.bind(2, d); cmd.bind(3, t); cmd.bind(4, yr); if (conn.server_version() >= 50604){ //MySQL 5.6.4 and up expands fractional seconds support for //TIME, DATETIME, and TIMESTAMP values, //with up to microseconds(6 digits) precision cmd.bind(5, t3); cmd.bind(6, dt6); } cmd.execute(); cmd.prepare("select * from timet"); result_set res = cmd.execute(); _assert_result_meta(res, 0, "tsmp",true,type_db_time); _assert_result_meta(res, 1, "dt", false, type_db_time); _assert_result_meta(res, 2, "d", false, type_db_time); _assert_result_meta(res, 3, "tm", false, type_db_time); _assert_result_meta(res, 4, "yr", false, type_short); if (conn.server_version() >= 50604){ _assert_result_meta(res, 5, "tm3", false, type_db_time); _assert_result_meta(res, 6, "dt6", false, type_db_time); } assert(res.next_row()); assert(res.get_string(0) == _0_str); assert(res.get_string(1) == _1_str); assert(res.get_string(2) == _2_str); assert(res.get_string(3) == _3_str); assert(res.get_string(4) == "2014"); assert(res.get_time(0) == db_time(_0_str)); assert(res.get_time(1) == db_time(_1_str)); assert(res.get_time(2) == db_time(_2_str)); assert(res.get_time(3) == db_time(_3_str)); assert(res.get_int(4) == yr); if (conn.server_version() >= 50604){ assert(res.get_time(5) == db_time(_5_str)); assert(res.get_time(6) == db_time(_6_str)); } cmd.execute_once("delete from timet"); } string stmt; if (conn.server_version() >= 50604){ stmt = string("insert into timet values('") + _0_str + "','" + _1_str + "','" + _2_str + "','" + _3_str + "'," + "2014,'" + _5_str + "','" + _6_str + "')"; } else{ stmt = string("insert into timet values('") + _0_str + "','" + _1_str + "','" + _2_str + "','" + _3_str + "'," + "2014)"; } cmd.execute_once(stmt); result_set res = cmd.execute_once("select * from timet"); assert(res.next_row()); assert(res.get_string(0) == _0_str); assert(res.get_string(1) == _1_str); assert(res.get_string(2) == _2_str); assert(res.get_string(3) == _3_str); assert(res.get_string(4) == "2014"); assert(res.get_time(0) == db_time(_0_str)); assert(res.get_time(1) == db_time(_1_str)); assert(res.get_time(2) == db_time(_2_str)); assert(res.get_time(3) == db_time(_3_str)); assert(res.get_int(4) == yr); if (conn.server_version() >= 50604){ assert(res.get_time(5) == db_time(_5_str)); assert(res.get_time(6) == db_time(_6_str)); } cout << "test datetime done" << endl; } void test_conn() { cout << "test connection" << endl; connection_info conn_info("u1", "123", "host=127.0.0.1;db=for_dbapi_test;"); connection conn(my::mysql_factory); conn.connect(conn_info); if (conn.is_connected()) conn.disconnect(); assert(conn.is_connected() == false); if (version<40101) conn_info.set_option("MYSQL_SECURE_AUTH", "0"); conn.connect(conn_info); assert(conn.is_connected() == true); //version > 4.1 support multi-statements and multi-results if (conn.server_version() >= 40100){ //test connection flag command cmd = conn.create_command(); bool throw_except = false; try{ cmd.execute_once("create table bar(id int primary key,a int);" "insert into bar values(1,2)");//default not allow multi-statements }//BUG occurs catch (db_exception& e){ throw_except = true; } catch (runtime_error &r) { cerr<<r.what()<<endl; } assert(throw_except); throw_except = false; //now support multi-statements conn.disconnect(); conn.connect(connection_info("u1", "123", "host=127.0.0.1;db=for_dbapi_test;" "CLIENT_MULTI_STATEMENTS")); command cmd2 = conn.create_command(); try{ cmd.execute_once("drop table bar"); } catch (...){ } result_set res = cmd2.execute_once("create table bar(id int primary key,a int);" "insert into bar values(1,2);select * from bar;select * from bar where a=100"); assert(res.more_result_set()); assert(res.next_result_set());//insert assert(res.more_result_set()); assert(res.next_result_set());//select assert(res.row_count() == 1); assert(res.first_row()); assert(res.get_int(0) == 1); assert(res.get_int(1) == 2); assert(res.more_result_set()); assert(res.next_result_set());//select where a==100 assert(res.row_count() == 0); assert(res.first_row() == false); cmd2.execute_once("drop table bar"); } command cmd = conn.create_command(); cmd.execute_once("delete from foo where id=888"); //test setting option conn_info.set_option("MYSQL_INIT_COMMAND", "insert into foo values(888,'init cmd')"); conn.connect(conn_info); command cmd2 = conn.create_command(); result_set res=cmd2.execute_once("select * from foo where id=888 and name='init cmd'"); assert(res.row_count() == 1); cmd2.execute_once("delete from foo where id=888 and name='init cmd'"); cout << "test connection done" << endl; } char* xbuf = 0; std::size_t xsize = 0; std::size_t xoff = 0; int xindex = 0; std::size_t x_writer (int &piece_index, char* out_buf, std::size_t buf_len) { piece_index = xindex++; std::size_t xwrite = buf_len>(xsize - xoff) ? (xsize - xoff) : buf_len; memcpy(out_buf,xbuf+xoff,xwrite); xoff += xwrite; if (xoff == xsize) piece_index = -1; return xwrite; } /* +-------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(50) | YES | | NULL | | | lb | longblob | YES | | NULL | | +-------+-------------+------+-----+---------+----------------+ */ void test_lbs(connection& conn, command& cmd) { cout << "test lbs" << endl; cmd.execute_once("delete from lbs"); const size_t _20M = 1024 * 1024 * 20; const size_t _10M = 1024 * 1024 * 10; ifstream ifs1((blob_path + "x/x1.rar").c_str(), std::ifstream::binary); ifstream ifs2((blob_path + "x/x2.zip").c_str(), std::ifstream::binary); ifstream ifs3((blob_path + "x/x3.zip").c_str(), std::ifstream::binary); cmd.prepare("insert into lbs values(null,?,?)"); { cmd.bind(0, "x1.rar"); cmd.bind(1, out_blob(&ifs1)); cout << "sending x1.rar..." << endl; cmd.execute(); cout << "send x1.rar" << endl; } { xbuf = new char[_20M]; ifs2.read(xbuf, _20M); xsize = ifs2.gcount(); xoff = 0; xindex = 0; cmd.bind(0, "x2.zip"); cmd.bind(1, out_blob(x_writer)); cout << "sending x2.zip..." << endl; cmd.execute(); cout << "send x2.zip" << endl; delete [] xbuf; } { xbuf = new char[_10M]; char* ybuf = new char[_20M]; ifs3.read(xbuf, _10M); xsize = ifs3.gcount(); xoff = 0; xindex = 0; cmd.bind(0, "x3.zip"); cmd.bind(1, out_blob(xbuf,xsize)); cout << "sending x3.zip..." << endl; cmd.execute(); cout << "send x3.zip" << endl; string estr("insert into lbs values(null,'x3.e.zip','"); std::size_t ysz=escape_string(xbuf, xsize, ybuf); estr += ybuf; estr += "')"; cmd.execute_once(estr); delete[] xbuf; delete[] ybuf; } { cmd.prepare("select name,lb from lbs where not name='x3.e.zip'"); result_set rs = cmd.execute(); rs.first_row(); { string name("_"); name += rs.get_string(0); ofstream ofs((blob_path + "x/" + name).c_str(), std::ifstream::binary); raw_buf rbuf = rs.get_raw_buf(1); ofs.write((const char*)rbuf.get_buf(), rbuf.get_size()); } while (rs.next_row()) { string name("_"); name += rs.get_string(0); ofstream ofs((blob_path + "x/" + name).c_str(), std::ifstream::binary); in_blob b = rs.get_blob(1); b.read(ofs); } } { result_set rs = cmd.execute_once("select lb from lbs where name='x3.e.zip'"); rs.next_row(); ofstream ofs((blob_path + "x/_x3.e.zip").c_str(), std::ifstream::binary); in_blob b = rs.get_blob(0); b.read(ofs); } cout << "test lbs done" << endl; } void test_datetime_prior_40100(connection& conn, command& cmd) { if (conn.server_version() >= 40100) return; cout << "test_datetime_prior_40100" << endl; cmd.execute_once("DROP TABLE IF EXISTS tsmp;"); cmd.execute_once("CREATE TABLE tsmp( id INT AUTO_INCREMENT PRIMARY KEY," "t14 TIMESTAMP(14), t8 TIMESTAMP(8), t4 TIMESTAMP(4))"); cmd.execute_once ("INSERT INTO tsmp VALUES(null, 20141231144300, 20150101121200, 20150102)"); cmd.execute_once ("INSERT INTO tsmp VALUES(null, null, null, null)"); result_set res = cmd.execute_once("SELECT * FROM tsmp"); res.first_row(); string s14 = res.get_string(1); string s8 = res.get_string(2); string s4 = res.get_string(3); db_time t14 = res.get_time(1); db_time t8 = res.get_time(2); db_time t4 = res.get_time(3); assert(s14 == "20141231144300"); assert(s8 == "20150101"); assert(s4 == "1501"); assert(t14 == db_time("2014-12-31 14:43:00")); assert(t8 == db_time("2015-01-01 00:00:00")); assert(t4 == db_time("2015-01-00 00:00:00")); res.next_row(); assert(res.get_field_type(1)==ok_field); assert(res.get_field_type(2) == ok_field); assert(res.get_field_type(3) == ok_field); cmd.execute_once("delete from timet"); string _tsmp("20141231010203"); string __tsmp("2014-12-31 01:02:03"); string _dt("2014-12-31 16:05:00"); string _d("2014-12-31"); string _tm("16:05:00"); string _yr("2014"); string insert_stmt = string("insert into timet values('") + _tsmp + "','" + _dt + "','" + _d + "','" + _tm + "'," + _yr + ")"; cmd.execute_once(insert_stmt); cmd.execute_once("select * from timet"); res.first_row(); assert(res.get_string(0) == _tsmp); assert(res.get_string(1) == _dt); assert(res.get_string(2) == _d); assert(res.get_string(3) == _tm); assert(res.get_string(4) == _yr); assert(res.get_time(0) == db_time(__tsmp)); assert(res.get_time(1) == db_time(_dt)); assert(res.get_time(2) == db_time( _d)); assert(res.get_time(3) == db_time(_tm)); assert(res.get_int(4) == 2014); cout << "test_datetime_prior_40100 done" << endl; } void test_text(connection& conn, command& cmd) { //Improved support for character set handling was added to MySQL in version 4.1 cout << "test text" << endl; string dir = blob_path + "txt/"; const int c = 3; string names[c] = { "绝代双骄.ANSI.txt", "绝代双骄.utf8.txt", "绝代双骄.Unicode.txt" }; cmd.execute_once("delete from txt"); cmd.execute_once("delete from txt_utf8"); cmd.execute_once("delete from txt_ucs2"); if (conn.server_version() > 40102){ ifstream ifs1((dir + names[0]).c_str(), ios_base::binary);//ansi ifstream ifs2((dir + names[1]).c_str(), ios_base::binary);//utf8 ifstream ifs3((dir + names[2]).c_str(), ios_base::binary);//unicode string name1 = string("mysql_prep.") + "绝代双骄.ansi.txt"; string name2 = string("mysql_prep.") + "绝代双骄.utf8.txt"; string name3 = string("mysql_prep.") + "绝代双骄.unicode.txt"; cmd.prepare("insert into txt values(?,?,?)"); cmd.bind(0, db_null()); cmd.bind(1, name1); cmd.bind(2, out_blob(&ifs1)); cmd.execute(); cmd.prepare("insert into txt_ucs2 values(?,?,?)"); cmd.bind(0, db_null()); cmd.bind(1, name3); cmd.bind(2, out_blob(&ifs3)); cmd.execute(); cmd.prepare("insert into txt_utf8 values(?,?,?)"); cmd.bind(0, db_null()); cmd.bind(1, name2); cmd.bind(2, out_blob(&ifs2)); cmd.execute(); cmd.prepare(string("select * from txt where name='") + name1 + "'"); result_set rs1 = cmd.execute(); rs1.next_row(); { string name = name1; ofstream ofs((dir + name).c_str(), ios_base::binary); rs1.get_blob(2).read(ofs); cout << "\twrote " << name << endl; } cmd.execute_once("SET character_set_results = 'utf8'"); cmd.prepare(string("select * from txt_utf8 where name='") + name2 + "'"); result_set rs2 = cmd.execute(); rs2.next_row(); { string name = name2; ofstream ofs((dir + name).c_str(), ios_base::binary); rs2.get_blob(2).read(ofs); cout << "\twrote " << name << endl; } cmd.execute_once("SET character_set_results = 'ucs2'"); cmd.prepare(string("select * from txt_ucs2 where name='") + name3 + "'"); result_set rs3 = cmd.execute(); rs3.next_row(); { string name = name3; ofstream ofs((dir + name).c_str(), ios_base::binary); rs3.get_blob(2).read(ofs); cout << "\twrote " << name << endl; } } { cmd.execute_once("delete from txt_c"); cmd.execute_once("SET character_set_results = 'latin1'"); ifstream ifs1((dir + names[0]).c_str(), ios_base::binary); ifstream ifs2((dir + names[1]).c_str(), ios_base::binary); ifstream ifs3((dir + names[2]).c_str(), ios_base::binary); const size_t _4M = 1024 * 1024 * 4; y::unique_ptr<char[]> temp_buf1(new char[_4M]); y::unique_ptr<char[]> temp_buf2(new char[_4M]); y::unique_ptr<char[]> temp_buf3(new char[_4M]); size_t temp_len1 = 0; size_t temp_len2 = 0; size_t temp_len3 = 0; ifs1.read(temp_buf1.get(), _4M); temp_len1 = ifs1.gcount(); ifs2.read(temp_buf2.get(), _4M); temp_len2 = ifs2.gcount(); ifs3.read(temp_buf3.get(), _4M); temp_len3 = ifs3.gcount(); //cout<<"\t"<<temp_len1<<" "<<temp_len2<<endl; string name = string("mysql.") + "绝代双骄"; string stmt = string("insert into txt_c values(null,'") + name + "','" + string(temp_buf1.get(), temp_len1) + "','" + string(temp_buf1.get(), temp_len1) + "','" + string(temp_buf1.get(), temp_len1) + "')"; cmd.execute_once(stmt); result_set rs =cmd.execute_once("select * from txt_c where name like 'mysql.%'"); while (rs.next_row()){ string name = rs.get_string(1); ofstream ofs1((dir + name + ".ans.txt").c_str(), ios_base::binary); ofstream ofs2((dir + name + ".utf8.txt").c_str(), ios_base::binary); ofstream ofs3((dir + name + ".unicode.txt").c_str(), ios_base::binary); rs.get_blob(2).read(ofs1); rs.get_blob(3).read(ofs2); rs.get_blob(4).read(ofs3); cout << "\twrote " << name << endl; } } cout << "test text done" << endl; } void test_procedure() { cout << "test procedure" << endl; connection_info conn_info("u1", "123", "host=127.0.0.1;db=for_dbapi_test;" "CLIENT_MULTI_STATEMENTS"); connection conn(my::mysql_factory, conn_info); command cmd = conn.create_command(); if (conn.server_version() < 50503){ return; } cmd.execute_once("DROP PROCEDURE IF EXISTS lbs_info"); cmd.execute_once("CREATE PROCEDURE lbs_info(IN a_in INT,INOUT b_inout DOUBLE,OUT c_out VARCHAR(30))" " BEGIN " " SET a_in=11,b_inout=1.2345,c_out='abcd'; " " SELECT id, name from lbs; " " SELECT 1 as a,1.2 as b,'abc' as c;" " SELECT id, length(lb) from blo; " " END "); { cmd.prepare("call lbs_info(?,?,?)"); cmd.bind(0,db_null()); cmd.bind(1, 12.3); cmd.bind(2, string("xyz")); result_set rs= cmd.execute(); assert(rs.next_result_set()); assert(rs.next_row()); assert(rs.get_int(0) == 1); assert(rs.get_string(1) == "1.2"); assert(rs.get_string(2) == "abc"); assert(rs.next_result_set()); string x0 = rs.name(0); string x1 = rs.name(1); assert(rs.name(0) == "id"); assert(rs.name(1) == "length(lb)"); assert(rs.next_result_set()); assert(rs.field_count() == 2); assert(rs.name(0) == "b_inout"); assert(rs.name(1) == "c_out"); assert(rs.last_row()); assert(rs.get_double(0) == 1.2345); assert(rs.get_string(1) == "abcd"); } cmd.execute_once("DROP PROCEDURE lbs_info"); cout << "test procedure done" << endl; } //fix me void test_multi_conn() { cout<<"test_multi_conn\n"; connection_info conn_info1("u1","123", "host=127.0.0.1;db=for_dbapi_test;" "CLIENT_MULTI_STATEMENTS"); //connection_info conn_info1("u1","123", // "host=127.0.0.1;db=for_dbapi_test"); connection_info conn_info2("u1","123", "host=127.0.0.1;db=for_dbapi_test;" "CLIENT_MULTI_STATEMENTS"); connection conn1(my::mysql_factory,conn_info1); command cmd1 = conn1.create_command(); connection conn2(my::mysql_factory,conn_info2); command cmd2 = conn1.create_command(); cmd1.execute_once("DROP TABLE IF EXISTS bar"); cmd2.execute_once("create table bar(id int primary key,a int)"); cmd1.execute_once("insert into bar values(1,2)"); result_set rs2=cmd2.execute_once("select * from bar"); assert(rs2.row_count()==1); rs2.next_row(); assert(rs2.get_int(1)==2); bool catch_= false; try { cmd2.execute_once("select xxx from bar"); } catch (...) { catch_=true; } assert(catch_); catch_= false; command cmd22=conn2.create_command(); result_set rs22=cmd2.execute_once("select * from bar"); assert(rs22.row_count()==1); rs22.next_row(); assert(rs22.get_int(1)==2); cout<<"test_multi_conn done\n"; } void test_foo() { const char* sql_create_table= "CREATE TABLE test" "(id INT NOT NULL," "dou DOUBLE," "str VARCHAR(1024)," "dt DATETIME," "num DECIMAL(20,10))"; const char* sql_delete_table= "DROP TABLE IF EXISTS test"; const char* sql_select_1= "SELECT * FROM test AS t1,test AS t2"; const char* sql_insert= "insert into test values(?,?,?,?,?)"; const char* cstr="qwefhruevgyhrehrquighqfyugw" "qgqiuewfevdsUDJSHKGFUIY654vy5667863rdhf" "jsgfqa09gq09m0vxc2tucvn38c46368975^%^&*&" "TGVGBHJVDgredgfdvmah nhgfdhrty54bh6m8onb34vmewqy8" "934897394cmx4834cngfexoqmnbvb5ummouzqw" "eqbnqgce34c5tT^45byv4xashj.fsayt35/;pouqwazsb" "jgyhi[op]-0987654wertyupilkghfsu568ni887&%"; dbapi::connection_info dbapi_info("u1", "123", "host=127.0.0.1;db=for_dbapi_test"); dbapi::connection dbapi_conn(dbapi::my::mysql_factory, dbapi_info); dbapi::command dbapi_cmd = dbapi_conn.create_command(); //create table dbapi_cmd.execute_once(sql_delete_table); dbapi_cmd.execute_once(sql_create_table); //insert srand(time(0)); const int COUNT=1000; int clen=strlen(cstr); dbapi_cmd.prepare(sql_insert); for(int i=1;i<=COUNT;++i) { int x=rand(); double d=double(x)/std::numeric_limits<int>::max(); const char* str=cstr+(x%(clen-10)); time_t seconds=time (NULL); tm * t=gmtime(&seconds); int y=rand()%1000; dbapi::db_numeric num(d+y); dbapi_cmd.bind(0,i); dbapi_cmd.bind(1,d); dbapi_cmd.bind(2,str); dbapi_cmd.bind(3,*t); dbapi_cmd.bind(4,num); dbapi_cmd.execute(); } }
067ca349ce6334039b139c3ad9846d1ecef233a2
017656190737e3f31c674f8d7257d1469b0091ba
/Testing/t/test.cpp
b9e93487a8aaddb6fabb75121d0c59a28625f844
[]
no_license
asteine8/CISC-192_MESA_SPRING_2020
ee480bee479334896d7758c6c6e44e0160f0e8fe
36b5465b9b34ef1dce619656d72f6e8ff7fe6405
refs/heads/master
2020-12-28T14:08:35.921474
2020-06-08T07:57:59
2020-06-08T07:57:59
238,363,065
0
0
null
null
null
null
UTF-8
C++
false
false
335
cpp
#include <iostream> #include <stdio.h> using namespace std; int main() { char myString[6] = {'h','e','l','l','o','\0'}; char* strPtr = myString; printf("My string: %s , char* version: %s\n", myString, strPtr); const char* constString = "Hai there"; printf("constString = %s\n\n", constString); return 0; }
ccb3cb7467b27a2d395cd1e437d3059dfc701d10
a6ef0926a77cdbca6140fce580564fe5c8bff131
/qt_dlib_dnn2/dnnface/dnn_base/noncopyable.h
166968091e642b771626dcef267065dddc4776ae
[]
no_license
yjwudi/digiKam-Test
4220e2d85afef0d95627c160a7edc1dcf48a7b35
8f6a16f9ce47f12c69484a8ec8408050f03837c4
refs/heads/master
2021-06-24T02:58:50.240169
2017-07-26T12:12:25
2017-07-26T12:12:25
95,617,175
0
0
null
null
null
null
UTF-8
C++
false
false
927
h
// (C) Copyright Beman Dawes 1999-2003. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // Contributed by Dave Abrahams // See http://www.boost.org/libs/utility for documentation. #ifndef DLIB_BOOST_NONCOPYABLE_HPP_INCLUDED #define DLIB_BOOST_NONCOPYABLE_HPP_INCLUDED class noncopyable { /*! This class makes it easier to declare a class as non-copyable. If you want to make an object that can't be copied just inherit from this object. !*/ protected: noncopyable() {} ~noncopyable() {} private: // emphasize the following members are private noncopyable(const noncopyable&); const noncopyable& operator=(const noncopyable&); }; #endif // DLIB_BOOST_NONCOPYABLE_HPP_INCLUDED