hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
574de25fe8e66db01849b25238daf23f88b40a6b
4,542
cpp
C++
ares/ngp/cpu/interrupts.cpp
moon-chilled/Ares
909fb098c292f8336d0502dc677050312d8b5c81
[ "0BSD" ]
7
2020-07-25T11:44:39.000Z
2021-01-29T13:21:31.000Z
ares/ngp/cpu/interrupts.cpp
jchw-forks/ares
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
[ "0BSD" ]
null
null
null
ares/ngp/cpu/interrupts.cpp
jchw-forks/ares
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
[ "0BSD" ]
1
2021-03-22T16:15:30.000Z
2021-03-22T16:15:30.000Z
auto CPU::Interrupts::poll() -> void { priority = 0; cpu.inttc3.poll(vector, priority); cpu.inttc2.poll(vector, priority); cpu.inttc1.poll(vector, priority); cpu.inttc0.poll(vector, priority); cpu.intad .poll(vector, priority); cpu.inttx1.poll(vector, priority); cpu.intrx1.poll(vector, priority); cpu.inttx0.poll(vector, priority); cpu.intrx0.poll(vector, priority); cpu.inttr7.poll(vector, priority); cpu.inttr6.poll(vector, priority); cpu.inttr5.poll(vector, priority); cpu.inttr4.poll(vector, priority); cpu.intt3 .poll(vector, priority); cpu.intt2 .poll(vector, priority); cpu.intt1 .poll(vector, priority); cpu.intt0 .poll(vector, priority); cpu.int7 .poll(vector, priority); cpu.int6 .poll(vector, priority); cpu.int5 .poll(vector, priority); cpu.int4 .poll(vector, priority); cpu.int0 .poll(vector, priority); cpu.intwd .poll(vector, priority); cpu.nmi .poll(vector, priority); } auto CPU::Interrupts::fire() -> bool { if(!priority || priority < cpu.r.iff) return false; priority = 0; cpu.inttc3.fire(vector); cpu.inttc2.fire(vector); cpu.inttc1.fire(vector); cpu.inttc0.fire(vector); cpu.intad .fire(vector); cpu.inttx1.fire(vector); cpu.intrx1.fire(vector); cpu.inttx0.fire(vector); cpu.intrx0.fire(vector); cpu.inttr7.fire(vector); cpu.inttr6.fire(vector); cpu.inttr5.fire(vector); cpu.inttr4.fire(vector); cpu.intt3 .fire(vector); cpu.intt2 .fire(vector); cpu.intt1 .fire(vector); cpu.intt0 .fire(vector); cpu.int7 .fire(vector); cpu.int6 .fire(vector); cpu.int5 .fire(vector); cpu.int4 .fire(vector); cpu.int0 .fire(vector); cpu.intwd .fire(vector); cpu.nmi .fire(vector); if(vector == cpu.dma0.vector) { if(cpu.dma(0)) { cpu.dma0.vector = 0; cpu.inttc0.pending = 1; } } else if(vector == cpu.dma1.vector) { if(cpu.dma(1)) { cpu.dma1.vector = 0; cpu.inttc1.pending = 1; } } else if(vector == cpu.dma2.vector) { if(cpu.dma(2)) { cpu.dma2.vector = 0; cpu.inttc2.pending = 1; } } else if(vector == cpu.dma3.vector) { if(cpu.dma(3)) { cpu.dma3.vector = 0; cpu.inttc3.pending = 1; } } else { cpu.r.iff = priority; if(cpu.r.iff != 7) cpu.r.iff++; cpu.interrupt(vector); } poll(); return true; } auto CPU::Interrupt::operator=(bool value) -> void { set(value); } auto CPU::Interrupt::poll(uint8& vector, uint3& priority) -> void { if(!enable || !pending) return; if(!maskable) { priority = 7; vector = this->vector; return; } if(dmaAllowed && cpu.r.iff <= 6) { if(this->vector == cpu.dma0.vector) { priority = 6; vector = this->vector; return; } if(this->vector == cpu.dma1.vector) { priority = 6; vector = this->vector; return; } if(this->vector == cpu.dma2.vector) { priority = 6; vector = this->vector; return; } if(this->vector == cpu.dma3.vector) { priority = 6; vector = this->vector; return; } } if(this->priority == 0 || this->priority == 7) return; if(this->priority >= priority) { priority = this->priority; vector = this->vector; return; } } auto CPU::Interrupt::fire(uint8 vector) -> void { if(this->vector != vector) return; if(line == 0 && !level.low ) pending = 0; if(line == 1 && !level.high) pending = 0; } auto CPU::Interrupt::set(bool line) -> void { line ? raise() : lower(); } auto CPU::Interrupt::raise() -> void { if(!enable || line == 1) return; line = 1; if(pending || !(level.high || edge.rising)) return; pending = 1; cpu.interrupts.poll(); } auto CPU::Interrupt::lower() -> void { if(!enable || line == 0) return; line = 0; if(pending || !(level.low || edge.falling)) return; pending = 1; cpu.interrupts.poll(); } auto CPU::Interrupt::trigger() -> void { if(pending) return; pending = 1; cpu.interrupts.poll(); } auto CPU::Interrupt::clear() -> void { if(!pending) return; pending = 0; cpu.interrupts.poll(); } auto CPU::Interrupt::setEnable(uint1 enable) -> void { if(this->enable == enable) return; this->enable = enable; cpu.interrupts.poll(); } auto CPU::Interrupt::setPriority(uint3 priority) -> void { if(this->priority == priority) return; this->priority = priority; cpu.interrupts.poll(); } auto CPU::Interrupt::power(uint8 vector) -> void { this->vector = vector; //set up defaults that apply to most vectors //CPU::power() will perform specialization as needed later dmaAllowed = 1; enable = 1; maskable = 1; priority = 0; line = 0; pending = 0; level.high = 0; level.low = 0; edge.rising = 1; edge.falling = 0; }
28.566038
94
0.642889
moon-chilled
57517187ec352437ca416e36da9aba0b4872cb19
3,256
cpp
C++
extra/news/src/apk/gtagml/gtagml/gtagml/tag-command/gtagml-tag-command.cpp
scignscape/PGVM
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
[ "BSL-1.0" ]
null
null
null
extra/news/src/apk/gtagml/gtagml/gtagml/tag-command/gtagml-tag-command.cpp
scignscape/PGVM
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
[ "BSL-1.0" ]
null
null
null
extra/news/src/apk/gtagml/gtagml/gtagml/tag-command/gtagml-tag-command.cpp
scignscape/PGVM
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
[ "BSL-1.0" ]
null
null
null
// Copyright Nathaniel Christen 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "gtagml-tag-command.h" #include "gh/gh-prenode.h" #include "kans.h" USING_KANS(GTagML) bool needs_sdi_mark_check_nothing(QString) { return false; } std::function<bool(QString)> GTagML_Tag_Command::needs_sdi_mark_check_ = &needs_sdi_mark_check_nothing; void GTagML_Tag_Command::set_needs_sdi_mark_check(std::function<bool(QString)> fn) { GTagML_Tag_Command::needs_sdi_mark_check_ = fn; } GTagML_Tag_Command::GTagML_Tag_Command(QString name, QString argument, QString parent_tag_type) : Flags(0), name_(name), argument_(argument), parent_tag_type_(parent_tag_type), ref_position_(0), ref_order_(0), GTagML_htxn_node_(nullptr), arg_GTagML_htxn_node_(nullptr), name_prenode_(nullptr) { //if(name_.contains('-')) // flags.needs_sdi_mark = true; if(needs_sdi_mark_check_(name)) flags.needs_sdi_mark = true; } void GTagML_Tag_Command::each_arg_prenode(std::function<void(GH_Prenode*)> fn) { for(GH_Prenode* ghp : arg_prenodes_) fn(ghp); } void GTagML_Tag_Command::add_arg_prenode(GH_Block_Base* block, const QPair<u4, u4>& pr) { GH_Prenode* prenode = new GH_Prenode(block, pr.first, pr.second); arg_prenodes_.push_back(prenode); } void GTagML_Tag_Command::add_arg_prenode(GH_Block_Base* block, u4 enter, u4 leave) { GH_Prenode* prenode = new GH_Prenode(block, enter, leave); arg_prenodes_.push_back(prenode); } void GTagML_Tag_Command::init_name_prenode(GH_Block_Base* block, const QPair<u4, u4>& pr) { name_prenode_ = new GH_Prenode(block, pr.first, pr.second); } void GTagML_Tag_Command::init_name_prenode(GH_Block_Base* block, u4 enter, u4 leave) { name_prenode_ = new GH_Prenode(block, enter, leave); } void GTagML_Tag_Command::each_arg_GTagML_htxn_node(std::function<void(GTagML_HTXN_Node*)> fn) { for(GTagML_HTXN_Node* nhn : arg_GTagML_htxn_nodes_) fn(nhn); } void GTagML_Tag_Command::add_arg_GTagML_htxn_node(GTagML_HTXN_Node* nhn) { arg_GTagML_htxn_nodes_.append(nhn); } u2 GTagML_Tag_Command::get_whitespace_code() { if(flags.nonstandard_space) return 9999; u2 result = 0; if(flags.left_line_double_gap) result += 2000; if(flags.left_line_gap) result += 1000; if(flags.left_space_gap) result += 100; if(flags.right_space_gap) result += 1; if(flags.right_line_double_gap) result += 20; if(flags.right_line_gap) result += 10; return result; } void GTagML_Tag_Command::normalize_whitespace() { u1 counts [4]; ws().get_counts(counts); get_whitespace_counts_as_inherited(counts); for(int i = 0; i < 4; ++i) if(counts[i] == 255) { flags.nonstandard_space = true; return; } if(counts[0] > 1) flags.right_line_double_gap = true; else if(counts[0] == 1) flags.right_line_gap = true; if(counts[1] >= 1) flags.right_space_gap = true; if(counts[2] > 1) flags.left_line_double_gap = true; else if(counts[2] == 1) flags.left_line_gap = true; if(counts[3] >= 1) flags.left_space_gap = true; } QString GTagML_Tag_Command::latex_name() { QString result = name_; result.remove('-'); return result; }
23.594203
103
0.735258
scignscape
575398ac9333ca9bb91367bca31bbfcfa62e4336
648
cpp
C++
668-kth-smallest-number-in-multiplication-table.cpp
nave7693/leetcode
8ff388cb17e87aa9053eaed3b84e7dc2be3e2e49
[ "MIT" ]
null
null
null
668-kth-smallest-number-in-multiplication-table.cpp
nave7693/leetcode
8ff388cb17e87aa9053eaed3b84e7dc2be3e2e49
[ "MIT" ]
null
null
null
668-kth-smallest-number-in-multiplication-table.cpp
nave7693/leetcode
8ff388cb17e87aa9053eaed3b84e7dc2be3e2e49
[ "MIT" ]
null
null
null
// https://leetcode.com/problems/kth-smallest-number-in-multiplication-table class Solution { public: int findKthNumber(int m, int n, int k) { int low = 1 , high = m * n + 1; while (low < high) { int mid = low + (high - low) / 2; int c = count(mid, m, n); if (c >= k) high = mid; else low = mid + 1; } return high; } private: int count(int v, int m, int n) { int count = 0; for (int i = 1; i <= m; i++) { int temp = min(v / i , n); count += temp; } return count; } };
24
77
0.429012
nave7693
57543df53c4e7166ae8bde4860415da283e4da77
873
cpp
C++
membros/laura/grafo/Grafos/aresta.cpp
thiago9864/grafos2019_1
14e1115e7fd3c0ddbd728047eb65b07539f53b8c
[ "MIT" ]
1
2019-06-18T14:52:40.000Z
2019-06-18T14:52:40.000Z
membros/laura/grafo/Grafos/aresta.cpp
thiago9864/grafos2019_1
14e1115e7fd3c0ddbd728047eb65b07539f53b8c
[ "MIT" ]
null
null
null
membros/laura/grafo/Grafos/aresta.cpp
thiago9864/grafos2019_1
14e1115e7fd3c0ddbd728047eb65b07539f53b8c
[ "MIT" ]
null
null
null
#include "Aresta.h" Aresta::Aresta(){} Aresta::Aresta(int noOrigem, int noFim) { this->origem = noOrigem; this->noAdj = noFim; this->peso = -1.0; this->prox = nullptr; } Aresta::Aresta(int noOrigem, int noFim, float peso) { this->origem = noOrigem; this->noAdj = noFim; this->peso = peso; this->prox = nullptr; } /*Aresta::~Aresta() { // Deletando todas as arestas Aresta* ant = this; for (Aresta *a = ant->getProx(); a != nullptr; a = a->getProx()) { delete ant; } }*/ // *** Getters *** float Aresta::getPeso() { return peso; } Aresta* Aresta::getProx() { return prox; } int Aresta::getNoAdj() { return noAdj; } int Aresta:: getOrigem() { return origem; } // *** Setters *** void Aresta::setProx(Aresta *aresta) { prox = aresta; }
16.166667
71
0.544101
thiago9864
5756aa53b0c5076076d0da276b5b591675693e57
2,236
hpp
C++
SSSP/ESSENS/Core/Basic_SetOps/Level0/extract_elements.hpp
DynamicSSSP/sc18
3070cd5ad7107a3985a7a386ddf99b7f018c178a
[ "MIT" ]
4
2018-12-19T08:40:39.000Z
2021-02-22T17:31:41.000Z
SSSP/ESSENS/Core/Basic_SetOps/Level0/extract_elements.hpp
DynamicSSSP/HIPC18
3070cd5ad7107a3985a7a386ddf99b7f018c178a
[ "MIT" ]
null
null
null
SSSP/ESSENS/Core/Basic_SetOps/Level0/extract_elements.hpp
DynamicSSSP/HIPC18
3070cd5ad7107a3985a7a386ddf99b7f018c178a
[ "MIT" ]
null
null
null
#ifndef EXTRACT_ELEMENTS_HPP #define EXTRACT_ELEMENTS_HPP #include "structure_defs.hpp" using namespace std; //Extracts Relevant Information From Structure //Pairs of Elements //all template <class Type1, class Type2> void get(pair<Type1, Type2> e1, const string &opt, pair<Type1, Type2> *entry) { if(opt=="all"){*entry=e1;} else{cout <<"ESSENS:ERROR:: Option" << opt << "Not Defined \n"; } return; } //first template <class Type1, class Type2> void get(pair<Type1, Type2> e1, const string &opt, Type1* entry) { if(opt=="first"){*entry=e1.first;} else{cout <<"ESSENS:ERROR:: ^^^^Option" << opt << "Not Defined \n"; } return; } //second template <class Type1, class Type2> void get(pair<Type1, Type2> e1, const string &opt, Type2* entry) { if(opt=="second"){*entry=e1.second;} else{cout <<"ESSENS:ERROR:: Option" << opt << "Not Defined \n"; } return; } //Edges void get(Edge e1, const string &opt, int *entry) { if(opt=="node1"){*entry=e1.node1;} else { if(opt=="node2"){*entry=e1.node2;} else { cout <<"ESSENS:ERROR:: Option" << opt << "Not Defined \n"; } }//end of first else return; } void get(Edge e1, const string &opt, int_int *entry) { if(opt=="ends"){entry->first=e1.node1; entry->second=e1.node2;} else { cout <<"ESSENS:ERROR:: Option" << opt << "Not Defined \n"; } return; } void get(Edge e1, const string &opt, double *entry) { if(opt=="wt"){*entry=e1.edge_wt;} else { cout <<"ESSENS:ERROR:: Option" << opt << "Not Defined \n"; } return; } void get(Edge e1, const string &opt, Edge *entry) { if(opt=="all"){*entry=e1;} else { cout <<"ESSENS:ERROR:: Option" << opt << "Not Defined \n"; } return; } //Single Elements template <class Type1> void get(Type1 e1, const string &opt, Type1* entry) { if(opt=="all") {*entry=e1;} else{cout <<"ESSENS:ERROR:: ...Option" << opt << "Not Defined \n"; } return; } //As a vector operation template<class Type1, class Type2> void get_all(vector<Type1> Elements, const string &opt, vector<Type2> *Entries) { Entries->resize(0); Type2 entry; for(int i=0;i<Elements.size();i++) { get(Elements[i], opt, &entry); Entries->push_back(entry);} return; } /******* End of Functions **************/ #endif
21.09434
79
0.633721
DynamicSSSP
5756d821d58f933e87a4ed3d5facb16a31b550f5
1,733
cpp
C++
proj.android/jni/Java_joaobapt_CommonAlertListener.cpp
JoaoBaptMG/InfiniteSpaceExplorer
841fbf57e8bcab279a7b252dad1f4ef411c5cc47
[ "MIT" ]
2
2018-11-26T03:47:18.000Z
2019-01-12T10:07:58.000Z
proj.android/jni/Java_joaobapt_CommonAlertListener.cpp
JoaoBaptMG/InfiniteSpaceExplorer
841fbf57e8bcab279a7b252dad1f4ef411c5cc47
[ "MIT" ]
null
null
null
proj.android/jni/Java_joaobapt_CommonAlertListener.cpp
JoaoBaptMG/InfiniteSpaceExplorer
841fbf57e8bcab279a7b252dad1f4ef411c5cc47
[ "MIT" ]
1
2019-12-25T01:28:49.000Z
2019-12-25T01:28:49.000Z
// // Java_joaobapt_CommonAlertListener.cpp // SpaceExplorer // // Created by João Baptista on 22/04/15. // // #include <jni.h> #include <functional> #include "cocos2d.h" #include "platform/android/jni/JniHelper.h" extern "C" JNIEXPORT void JNICALL Java_joaobapt_CommonAlertListener_onClick(JNIEnv* env, jobject thiz, jobject dummy, jint id); JNIEXPORT void JNICALL Java_joaobapt_CommonAlertListener_onClick(JNIEnv* env, jobject thiz, jobject dummy, jint id) { jclass curClass = env->FindClass("joaobapt/CommonAlertListener"); jfieldID confirmCallbackID = env->GetFieldID(curClass, "confirmCallback", "Ljava/nio/ByteBuffer;"); jfieldID cancelCallbackID = env->GetFieldID(curClass, "cancelCallback", "Ljava/nio/ByteBuffer;"); if (!confirmCallbackID || !cancelCallbackID) return; jobject confirmCallbackObject = env->GetObjectField(thiz, confirmCallbackID); jobject cancelCallbackObject = env->GetObjectField(thiz, cancelCallbackID); switch (id) { case -1: { std::function<void()> *result = reinterpret_cast<std::function<void()>*>(env->GetDirectBufferAddress(confirmCallbackObject)); (*result)(); break; } case -2: { std::function<void()> *result = reinterpret_cast<std::function<void()>*>(env->GetDirectBufferAddress(cancelCallbackObject)); (*result)(); break; } default: break; } delete reinterpret_cast<std::function<void()>*>(env->GetDirectBufferAddress(confirmCallbackObject)); delete reinterpret_cast<std::function<void()>*>(env->GetDirectBufferAddress(cancelCallbackObject)); env->DeleteLocalRef(curClass); env->DeleteLocalRef(thiz); }
36.104167
137
0.691864
JoaoBaptMG
57589124f5457088dd6f32d6594069d0753e36cc
1,024
hpp
C++
module_00/ex01/Contact.class.hpp
sqatim/Cplusplus_modules_42
73a113f3731a3eb63f2943c5c6c3d8c14214c7ea
[ "MIT" ]
null
null
null
module_00/ex01/Contact.class.hpp
sqatim/Cplusplus_modules_42
73a113f3731a3eb63f2943c5c6c3d8c14214c7ea
[ "MIT" ]
null
null
null
module_00/ex01/Contact.class.hpp
sqatim/Cplusplus_modules_42
73a113f3731a3eb63f2943c5c6c3d8c14214c7ea
[ "MIT" ]
null
null
null
#ifndef Contact_CLASS_HPP #define Contact_CLASS_HPP #include <iostream> #include <iomanip> class Contact { public: void addInformation(void); void printFields(Contact Contact[]); void condition(std::string str, int check); std::string get_firstName(); std::string get_lastName(); std::string get_nickname(); std::string get_login(); std::string get_postalAdress(); std::string get_emailAdress(); std::string get_phoneNumber(); std::string get_birthdatDate(); std::string get_favoriteMeal(); std::string get_underwearColor(); std::string get_darkestSecret(); private: std::string m_first_name; std::string m_last_name; std::string m_nickname; std::string m_login; std::string m_postal_adress; std::string m_email_adress; std::string m_phone_number; std::string m_birthday_date; std::string m_favorite_meal; std::string m_underwear_color; std::string m_darkest_secret; static int _index; }; #endif
23.272727
47
0.69043
sqatim
575d96da08051cbf14fad2f46e0e1f7b8cb8b95f
173
cpp
C++
CcCard/card.cpp
ZHKU-Robot/yjc-CardGame-Demo
bb4bbb05c04a141779f0fc62749ae2c45c56911f
[ "MIT" ]
1
2021-08-19T09:51:57.000Z
2021-08-19T09:51:57.000Z
CcCard/card.cpp
yujiecong/yjc-CardGame-Demo
bb4bbb05c04a141779f0fc62749ae2c45c56911f
[ "MIT" ]
null
null
null
CcCard/card.cpp
yujiecong/yjc-CardGame-Demo
bb4bbb05c04a141779f0fc62749ae2c45c56911f
[ "MIT" ]
null
null
null
#include "card.h" #include "ui_card.h" Card::Card(QWidget *parent) : QWidget(parent), ui(new Ui::Card) { ui->setupUi(this); } Card::~Card() { delete ui; }
11.533333
29
0.583815
ZHKU-Robot
575e2a04ec0ef3d8a4a3dd403bc2a4bf9facd0ff
228
cpp
C++
src/C/Security-57031.40.6/Security/libsecurity_transform/lib/SecNullTransform.cpp
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
34
2015-02-04T18:03:14.000Z
2020-11-10T06:45:28.000Z
src/C/Security-57031.40.6/Security/libsecurity_transform/lib/SecNullTransform.cpp
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
5
2015-06-30T21:17:00.000Z
2016-06-14T22:31:51.000Z
src/C/Security-57031.40.6/Security/libsecurity_transform/lib/SecNullTransform.cpp
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
15
2015-10-29T14:21:58.000Z
2022-01-19T07:33:14.000Z
#include "SecNullTransform.h" #include "NullTransform.h" const CFStringRef kSecNullTransformName = CFSTR("Null Transform"); SecNullTransformRef SecNullTransformCreate() { return (SecNullTransformRef) NullTransform::Make(); }
22.8
66
0.802632
GaloisInc
5760de5f3b0bbfc2b984e906fb5a736ec86d8e0d
11,295
cpp
C++
testcases/CWE366_Race_Condition_Within_Thread/main.cpp
mellowCS/cwe_checker_juliet_suite
ae604f6fd94964251fbe88ef04d5287f6c1ffbe2
[ "MIT" ]
1
2022-03-03T07:08:31.000Z
2022-03-03T07:08:31.000Z
testcases/CWE366_Race_Condition_Within_Thread/main_linux.cpp
mellowCS/cwe_checker_juliet_suite
ae604f6fd94964251fbe88ef04d5287f6c1ffbe2
[ "MIT" ]
null
null
null
testcases/CWE366_Race_Condition_Within_Thread/main_linux.cpp
mellowCS/cwe_checker_juliet_suite
ae604f6fd94964251fbe88ef04d5287f6c1ffbe2
[ "MIT" ]
null
null
null
/* NOTE - eventually this file will be automatically updated using a Perl script that understand * the naming of test case files, functions, and namespaces. */ #include <time.h> /* for time() */ #include <stdlib.h> /* for srand() */ #include "std_testcase.h" #include "testcases.h" int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); globalArgc = argc; globalArgv = argv; #ifndef OMITGOOD /* Calling C good functions */ /* BEGIN-AUTOGENERATED-C-GOOD-FUNCTION-CALLS */ printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_06_good();"); CWE366_Race_Condition_Within_Thread__int_byref_06_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_11_good();"); CWE366_Race_Condition_Within_Thread__global_int_11_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_10_good();"); CWE366_Race_Condition_Within_Thread__global_int_10_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_05_good();"); CWE366_Race_Condition_Within_Thread__global_int_05_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_09_good();"); CWE366_Race_Condition_Within_Thread__int_byref_09_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_02_good();"); CWE366_Race_Condition_Within_Thread__int_byref_02_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_09_good();"); CWE366_Race_Condition_Within_Thread__global_int_09_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_14_good();"); CWE366_Race_Condition_Within_Thread__int_byref_14_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_06_good();"); CWE366_Race_Condition_Within_Thread__global_int_06_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_12_good();"); CWE366_Race_Condition_Within_Thread__int_byref_12_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_07_good();"); CWE366_Race_Condition_Within_Thread__int_byref_07_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_17_good();"); CWE366_Race_Condition_Within_Thread__int_byref_17_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_18_good();"); CWE366_Race_Condition_Within_Thread__int_byref_18_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_16_good();"); CWE366_Race_Condition_Within_Thread__int_byref_16_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_10_good();"); CWE366_Race_Condition_Within_Thread__int_byref_10_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_01_good();"); CWE366_Race_Condition_Within_Thread__int_byref_01_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_08_good();"); CWE366_Race_Condition_Within_Thread__global_int_08_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_04_good();"); CWE366_Race_Condition_Within_Thread__int_byref_04_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_13_good();"); CWE366_Race_Condition_Within_Thread__int_byref_13_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_13_good();"); CWE366_Race_Condition_Within_Thread__global_int_13_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_15_good();"); CWE366_Race_Condition_Within_Thread__int_byref_15_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_07_good();"); CWE366_Race_Condition_Within_Thread__global_int_07_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_14_good();"); CWE366_Race_Condition_Within_Thread__global_int_14_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_12_good();"); CWE366_Race_Condition_Within_Thread__global_int_12_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_03_good();"); CWE366_Race_Condition_Within_Thread__int_byref_03_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_17_good();"); CWE366_Race_Condition_Within_Thread__global_int_17_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_08_good();"); CWE366_Race_Condition_Within_Thread__int_byref_08_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_04_good();"); CWE366_Race_Condition_Within_Thread__global_int_04_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_03_good();"); CWE366_Race_Condition_Within_Thread__global_int_03_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_02_good();"); CWE366_Race_Condition_Within_Thread__global_int_02_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_05_good();"); CWE366_Race_Condition_Within_Thread__int_byref_05_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_11_good();"); CWE366_Race_Condition_Within_Thread__int_byref_11_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_15_good();"); CWE366_Race_Condition_Within_Thread__global_int_15_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_18_good();"); CWE366_Race_Condition_Within_Thread__global_int_18_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_16_good();"); CWE366_Race_Condition_Within_Thread__global_int_16_good(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_01_good();"); CWE366_Race_Condition_Within_Thread__global_int_01_good(); /* END-AUTOGENERATED-C-GOOD-FUNCTION-CALLS */ #ifdef __cplusplus /* Calling C++ good functions */ /* BEGIN-AUTOGENERATED-CPP-GOOD-FUNCTION-CALLS */ /* END-AUTOGENERATED-CPP-GOOD-FUNCTION-CALLS */ #endif /* __cplusplus */ #endif /* OMITGOOD */ #ifndef OMITBAD /* Calling C bad functions */ /* BEGIN-AUTOGENERATED-C-BAD-FUNCTION-CALLS */ printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_06_bad();"); CWE366_Race_Condition_Within_Thread__int_byref_06_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_11_bad();"); CWE366_Race_Condition_Within_Thread__global_int_11_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_10_bad();"); CWE366_Race_Condition_Within_Thread__global_int_10_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_05_bad();"); CWE366_Race_Condition_Within_Thread__global_int_05_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_09_bad();"); CWE366_Race_Condition_Within_Thread__int_byref_09_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_02_bad();"); CWE366_Race_Condition_Within_Thread__int_byref_02_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_09_bad();"); CWE366_Race_Condition_Within_Thread__global_int_09_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_14_bad();"); CWE366_Race_Condition_Within_Thread__int_byref_14_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_06_bad();"); CWE366_Race_Condition_Within_Thread__global_int_06_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_12_bad();"); CWE366_Race_Condition_Within_Thread__int_byref_12_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_07_bad();"); CWE366_Race_Condition_Within_Thread__int_byref_07_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_17_bad();"); CWE366_Race_Condition_Within_Thread__int_byref_17_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_18_bad();"); CWE366_Race_Condition_Within_Thread__int_byref_18_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_16_bad();"); CWE366_Race_Condition_Within_Thread__int_byref_16_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_10_bad();"); CWE366_Race_Condition_Within_Thread__int_byref_10_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_01_bad();"); CWE366_Race_Condition_Within_Thread__int_byref_01_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_08_bad();"); CWE366_Race_Condition_Within_Thread__global_int_08_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_04_bad();"); CWE366_Race_Condition_Within_Thread__int_byref_04_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_13_bad();"); CWE366_Race_Condition_Within_Thread__int_byref_13_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_13_bad();"); CWE366_Race_Condition_Within_Thread__global_int_13_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_15_bad();"); CWE366_Race_Condition_Within_Thread__int_byref_15_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_07_bad();"); CWE366_Race_Condition_Within_Thread__global_int_07_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_14_bad();"); CWE366_Race_Condition_Within_Thread__global_int_14_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_12_bad();"); CWE366_Race_Condition_Within_Thread__global_int_12_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_03_bad();"); CWE366_Race_Condition_Within_Thread__int_byref_03_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_17_bad();"); CWE366_Race_Condition_Within_Thread__global_int_17_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_08_bad();"); CWE366_Race_Condition_Within_Thread__int_byref_08_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_04_bad();"); CWE366_Race_Condition_Within_Thread__global_int_04_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_03_bad();"); CWE366_Race_Condition_Within_Thread__global_int_03_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_02_bad();"); CWE366_Race_Condition_Within_Thread__global_int_02_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_05_bad();"); CWE366_Race_Condition_Within_Thread__int_byref_05_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__int_byref_11_bad();"); CWE366_Race_Condition_Within_Thread__int_byref_11_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_15_bad();"); CWE366_Race_Condition_Within_Thread__global_int_15_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_18_bad();"); CWE366_Race_Condition_Within_Thread__global_int_18_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_16_bad();"); CWE366_Race_Condition_Within_Thread__global_int_16_bad(); printLine("Calling CWE366_Race_Condition_Within_Thread__global_int_01_bad();"); CWE366_Race_Condition_Within_Thread__global_int_01_bad(); /* END-AUTOGENERATED-C-BAD-FUNCTION-CALLS */ #ifdef __cplusplus /* Calling C++ bad functions */ /* BEGIN-AUTOGENERATED-CPP-BAD-FUNCTION-CALLS */ /* END-AUTOGENERATED-CPP-BAD-FUNCTION-CALLS */ #endif /* __cplusplus */ #endif /* OMITBAD */ return 0; }
40.483871
96
0.859141
mellowCS
576270b074e1c48381666474cef9051cfd10ee18
8,206
cpp
C++
src/d3d11/d3d11-device.cpp
Impulse21/nvrhi
f272a6595dd0768a8e3419f0075f0edf40d00391
[ "MIT" ]
2
2021-08-28T23:02:30.000Z
2021-08-28T23:26:21.000Z
src/d3d11/d3d11-device.cpp
Impulse21/nvrhi
f272a6595dd0768a8e3419f0075f0edf40d00391
[ "MIT" ]
null
null
null
src/d3d11/d3d11-device.cpp
Impulse21/nvrhi
f272a6595dd0768a8e3419f0075f0edf40d00391
[ "MIT" ]
null
null
null
/* * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include "d3d11-backend.h" #include <nvrhi/utils.h> #include <sstream> #include <iomanip> namespace nvrhi::d3d11 { void Context::error(const std::string& message) const { messageCallback->message(MessageSeverity::Error, message.c_str()); } void SetDebugName(ID3D11DeviceChild* pObject, const char* name) { D3D_SET_OBJECT_NAME_N_A(pObject, UINT(strlen(name)), name); } DeviceHandle createDevice(const DeviceDesc& desc) { Device* device = new Device(desc); return DeviceHandle::Create(device); } Device::Device(const DeviceDesc& desc) { m_Context.messageCallback = desc.messageCallback; m_Context.immediateContext = desc.context; desc.context->GetDevice(&m_Context.device); #if NVRHI_D3D11_WITH_NVAPI m_Context.nvapiAvailable = NvAPI_Initialize() == NVAPI_OK; if (m_Context.nvapiAvailable) { NV_QUERY_SINGLE_PASS_STEREO_SUPPORT_PARAMS stereoParams{}; stereoParams.version = NV_QUERY_SINGLE_PASS_STEREO_SUPPORT_PARAMS_VER; if (NvAPI_D3D_QuerySinglePassStereoSupport(m_Context.device, &stereoParams) == NVAPI_OK && stereoParams.bSinglePassStereoSupported) { m_SinglePassStereoSupported = true; } // There is no query for FastGS, so query support for FP16 atomics as a proxy. // Both features were introduced in the same architecture (Maxwell). bool supported = false; if (NvAPI_D3D11_IsNvShaderExtnOpCodeSupported(m_Context.device, NV_EXTN_OP_FP16_ATOMIC, &supported) == NVAPI_OK && supported) { m_FastGeometryShaderSupported = true; } } #endif D3D11_BUFFER_DESC bufferDesc = {}; bufferDesc.ByteWidth = c_MaxPushConstantSize; bufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bufferDesc.Usage = D3D11_USAGE_DEFAULT; bufferDesc.CPUAccessFlags = 0; const HRESULT res = m_Context.device->CreateBuffer(&bufferDesc, nullptr, &m_Context.pushConstantBuffer); if (FAILED(res)) { std::stringstream ss; ss << "CreateBuffer call failed for the push constants buffer, HRESULT = 0x" << std::hex << std::setw(8) << res; m_Context.error(ss.str()); } m_ImmediateCommandList = CommandListHandle::Create(new CommandList(m_Context, this, CommandListParameters())); } GraphicsAPI Device::getGraphicsAPI() { return GraphicsAPI::D3D11; } Object Device::getNativeObject(ObjectType objectType) { switch (objectType) { case ObjectTypes::D3D11_Device: return Object(m_Context.device); case ObjectTypes::D3D11_DeviceContext: return Object(m_Context.immediateContext); case ObjectTypes::Nvrhi_D3D11_Device: return this; default: return nullptr; } } HeapHandle Device::createHeap(const HeapDesc&) { utils::NotSupported(); return nullptr; } CommandListHandle Device::createCommandList(const CommandListParameters& params) { if (!params.enableImmediateExecution) { m_Context.error("Deferred command lists are not supported by the D3D11 backend."); return nullptr; } if (params.queueType != CommandQueue::Graphics) { m_Context.error("Non-graphics queues are not supported by the D3D11 backend."); return nullptr; } return m_ImmediateCommandList; } bool Device::queryFeatureSupport(Feature feature, void* pInfo, size_t infoSize) { (void)pInfo; (void)infoSize; switch (feature) // NOLINT(clang-diagnostic-switch-enum) { case Feature::DeferredCommandLists: return false; case Feature::SinglePassStereo: return m_SinglePassStereoSupported; case Feature::FastGeometryShader: return m_FastGeometryShaderSupported; default: return false; } } rt::PipelineHandle Device::createRayTracingPipeline(const rt::PipelineDesc&) { return nullptr; } rt::AccelStructHandle Device::createAccelStruct(const rt::AccelStructDesc&) { return nullptr; } MemoryRequirements Device::getAccelStructMemoryRequirements(rt::IAccelStruct*) { utils::NotSupported(); return MemoryRequirements(); } bool Device::bindAccelStructMemory(rt::IAccelStruct*, IHeap*, uint64_t) { utils::NotSupported(); return false; } MeshletPipelineHandle Device::createMeshletPipeline(const MeshletPipelineDesc&, IFramebuffer*) { return nullptr; } void Device::waitForIdle() { if (!m_WaitForIdleQuery) { m_WaitForIdleQuery = createEventQuery(); } if (!m_WaitForIdleQuery) return; setEventQuery(m_WaitForIdleQuery, CommandQueue::Graphics); waitEventQuery(m_WaitForIdleQuery); resetEventQuery(m_WaitForIdleQuery); } SamplerHandle Device::createSampler(const SamplerDesc& d) { D3D11_SAMPLER_DESC desc11; UINT reductionType = convertSamplerReductionType(d.reductionType); if (d.maxAnisotropy > 1.0f) { desc11.Filter = D3D11_ENCODE_ANISOTROPIC_FILTER(reductionType); } else { desc11.Filter = D3D11_ENCODE_BASIC_FILTER( d.minFilter ? D3D11_FILTER_TYPE_LINEAR : D3D11_FILTER_TYPE_POINT, d.magFilter ? D3D11_FILTER_TYPE_LINEAR : D3D11_FILTER_TYPE_POINT, d.mipFilter ? D3D11_FILTER_TYPE_LINEAR : D3D11_FILTER_TYPE_POINT, reductionType); } desc11.AddressU = convertSamplerAddressMode(d.addressU); desc11.AddressV = convertSamplerAddressMode(d.addressV); desc11.AddressW = convertSamplerAddressMode(d.addressW); desc11.MipLODBias = d.mipBias; desc11.MaxAnisotropy = std::max((UINT)d.maxAnisotropy, 1U); desc11.ComparisonFunc = D3D11_COMPARISON_LESS; desc11.BorderColor[0] = d.borderColor.r; desc11.BorderColor[1] = d.borderColor.g; desc11.BorderColor[2] = d.borderColor.b; desc11.BorderColor[3] = d.borderColor.a; desc11.MinLOD = 0; desc11.MaxLOD = D3D11_FLOAT32_MAX; RefCountPtr<ID3D11SamplerState> sState; const HRESULT res = m_Context.device->CreateSamplerState(&desc11, &sState); if (FAILED(res)) { std::stringstream ss; ss << "CreateSamplerState call failed, HRESULT = 0x" << std::hex << std::setw(8) << res; m_Context.error(ss.str()); return nullptr; } Sampler* sampler = new Sampler(); sampler->sampler = sState; sampler->desc = d; return SamplerHandle::Create(sampler); } } // namespace nvrhi::d3d11
33.357724
143
0.652693
Impulse21
576a0800b37bbb4f4f510d3831faf261ef484773
180
cpp
C++
src/bullet.cpp
warlord500/space_invaders2
71d5acc30f95352b325ada61cb9b1389c9732961
[ "MIT" ]
null
null
null
src/bullet.cpp
warlord500/space_invaders2
71d5acc30f95352b325ada61cb9b1389c9732961
[ "MIT" ]
1
2015-05-29T04:49:09.000Z
2015-05-29T04:49:09.000Z
src/bullet.cpp
warlord500/space_invaders2
71d5acc30f95352b325ada61cb9b1389c9732961
[ "MIT" ]
null
null
null
#include "bullet.h" bullet::bullet(const sf::Texture& texture,const sf::Vector2f& pos) : sprite(texture) { this->sprite.setPosition(pos); } bullet::~bullet() { //dtor }
15
85
0.655556
warlord500
576aa655a59db9d53dd792064bb6b34ac40f4392
99
cpp
C++
C++ Code/Section06/unval/unval.cpp
PacktPublishing/Mastering-Multithreading-with-Cplusplus
9b0e5a7beeceb4a7262666fa2465fdda0104c9db
[ "MIT" ]
10
2019-10-10T21:03:56.000Z
2022-03-11T08:06:46.000Z
Section06/unval/unval.cpp
PacktPublishing/Mastering-Multithreading-with-Cplusplus
9b0e5a7beeceb4a7262666fa2465fdda0104c9db
[ "MIT" ]
null
null
null
Section06/unval/unval.cpp
PacktPublishing/Mastering-Multithreading-with-Cplusplus
9b0e5a7beeceb4a7262666fa2465fdda0104c9db
[ "MIT" ]
9
2019-09-08T09:15:13.000Z
2022-01-07T13:12:06.000Z
#include <cstring> #include <cstdio> int main() { int x; printf ("x = %d\n", x); return 0; }
11
24
0.555556
PacktPublishing
576cee712586a745be2db6bf613c1942f6774312
2,672
cc
C++
src/third_party/icu/fuzzers/icu_appendable_fuzzer.cc
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
null
null
null
src/third_party/icu/fuzzers/icu_appendable_fuzzer.cc
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
null
null
null
src/third_party/icu/fuzzers/icu_appendable_fuzzer.cc
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Chromium Authors. All rights reserved. #include <fuzzer/FuzzedDataProvider.h> #include <stddef.h> #include <stdint.h> #include <vector> #include "third_party/icu/fuzzers/fuzzer_utils.h" #include "third_party/icu/source/common/unicode/appendable.h" static IcuEnvironment* env = new IcuEnvironment; constexpr size_t kMaxInitialSize = 64; constexpr size_t kMaxReserveSize = 4096; constexpr size_t kMaxAppendLength = 64; constexpr size_t kMaxAdditionalDesiredSize = 4096; constexpr size_t kScratchBufSize = 4096; char16_t scratch_buf[kScratchBufSize]; enum class AppendableApi { AppendCodeUnit, AppendCodePoint, AppendString, ReserveAppendCapacity, GetAppendBuffer, kMaxValue = GetAppendBuffer }; // Entry point for LibFuzzer. extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { FuzzedDataProvider provider(data, size); auto str(icu::UnicodeString::fromUTF8( provider.ConsumeRandomLengthString(kMaxInitialSize))); icu::UnicodeStringAppendable strAppendable(str); while (provider.remaining_bytes() > 0) { switch (provider.ConsumeEnum<AppendableApi>()) { case AppendableApi::AppendCodeUnit: strAppendable.appendCodeUnit(provider.ConsumeIntegral<char16_t>()); break; case AppendableApi::AppendCodePoint: strAppendable.appendCodePoint(provider.ConsumeIntegral<UChar32>()); break; case AppendableApi::AppendString: { std::string appendChrs8( provider.ConsumeRandomLengthString(kMaxAppendLength)); if (appendChrs8.size() == 0) break; std::vector<char16_t> appendChrs(RandomChar16Array( 2, reinterpret_cast<const uint8_t*>(appendChrs8.data()), appendChrs8.size())); strAppendable.appendString(appendChrs.data(), appendChrs.size()); break; } case AppendableApi::ReserveAppendCapacity: strAppendable.reserveAppendCapacity( provider.ConsumeIntegralInRange<int32_t>(0, kMaxReserveSize)); break; case AppendableApi::GetAppendBuffer: { int32_t out_capacity; const auto min_capacity = provider.ConsumeIntegralInRange<int32_t>(1, kScratchBufSize); char16_t* out_buffer = strAppendable.getAppendBuffer( min_capacity, min_capacity + provider.ConsumeIntegralInRange<int32_t>( 0, kMaxAdditionalDesiredSize), scratch_buf, kScratchBufSize, &out_capacity); // Write arbitrary value at the end of the buffer. if (out_buffer) out_buffer[out_capacity - 1] = 1; break; } } } return 0; }
34.25641
75
0.700599
rhencke
576d1d9a43e68b5b8489502934883a6a6a08b433
19,406
cc
C++
src/network/net.cc
NilFoundation/actorio
49ac3e87902d4388cd0bb29267207f89fb057e85
[ "MIT" ]
null
null
null
src/network/net.cc
NilFoundation/actorio
49ac3e87902d4388cd0bb29267207f89fb057e85
[ "MIT" ]
3
2020-04-17T17:00:16.000Z
2020-07-13T20:19:11.000Z
src/network/net.cc
NilFoundation/actorio
49ac3e87902d4388cd0bb29267207f89fb057e85
[ "MIT" ]
null
null
null
//---------------------------------------------------------------------------// // Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation> // // MIT License // // 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 <boost/asio/ip/address_v4.hpp> #include <boost/algorithm/string.hpp> #include <nil/actor/network/net.hh> #include <nil/actor/network/toeplitz.hh> #include <nil/actor/core/reactor.hh> #include <nil/actor/core/metrics.hh> #include <nil/actor/core/print.hh> #include <nil/actor/network/inet_address.hh> #include <utility> namespace nil { namespace actor { static_assert(std::is_nothrow_default_constructible<ipv4_addr>::value); static_assert(std::is_nothrow_copy_constructible<ipv4_addr>::value); static_assert(std::is_nothrow_move_constructible<ipv4_addr>::value); static_assert(std::is_nothrow_default_constructible<ipv6_addr>::value); static_assert(std::is_nothrow_copy_constructible<ipv6_addr>::value); static_assert(std::is_nothrow_move_constructible<ipv6_addr>::value); std::ostream &operator<<(std::ostream &os, ipv4_addr addr) { fmt_print(os, "{:d}.{:d}.{:d}.{:d}", (addr.ip >> 24) & 0xff, (addr.ip >> 16) & 0xff, (addr.ip >> 8) & 0xff, (addr.ip) & 0xff); return os << ":" << addr.port; } using std::move; ipv4_addr::ipv4_addr(const std::string &addr) { std::vector<std::string> items; boost::split(items, addr, boost::is_any_of(":")); if (items.size() == 1) { ip = boost::asio::ip::address_v4::from_string(addr).to_ulong(); port = 0; } else if (items.size() == 2) { ip = boost::asio::ip::address_v4::from_string(items[0]).to_ulong(); port = std::stoul(items[1]); } else { throw std::invalid_argument("invalid format: " + addr); } } ipv4_addr::ipv4_addr(const std::string &addr, uint16_t port_) : ip(boost::asio::ip::address_v4::from_string(addr).to_ulong()), port(port_) { } ipv4_addr::ipv4_addr(const net::inet_address &a, uint16_t port) : ipv4_addr(::in_addr(a), port) { } ipv4_addr::ipv4_addr(const socket_address &sa) noexcept : ipv4_addr(sa.addr(), sa.port()) { } ipv4_addr::ipv4_addr(const ::in_addr &in, uint16_t p) noexcept : ip(net::ntoh(in.s_addr)), port(p) { } namespace net { inline bool qp::poll_tx() { if (_tx_packetq.size() < 16) { // refill send queue from upper layers uint32_t work; do { work = 0; for (auto &&pr : _pkt_providers) { auto p = pr(); if (p) { work++; _tx_packetq.push_back(std::move(p.value())); if (_tx_packetq.size() == 128) { break; } } } } while (work && _tx_packetq.size() < 128); } if (!_tx_packetq.empty()) { _stats.tx.good.update_pkts_bunch(send(_tx_packetq)); return true; } return false; } qp::qp(bool register_copy_stats, const std::string stats_plugin_name, uint8_t qid) : _tx_poller(std::make_unique<detail::poller>(reactor::poller::simple([this] { return poll_tx(); }))), _stats_plugin_name(stats_plugin_name), _queue_name(std::string("queue") + std::to_string(qid)) { namespace sm = metrics; _metrics.add_group( _stats_plugin_name, { // // Packets rate: DERIVE:0:u // sm::make_derive(_queue_name + "_rx_packets", _stats.rx.good.packets, sm::description("This metric is a receive packet rate for this queue.")), sm::make_derive(_queue_name + "_tx_packets", _stats.tx.good.packets, sm::description("This metric is a transmit packet rate for this queue.")), // // Bytes rate: DERIVE:0:U // sm::make_derive(_queue_name + "_rx_bytes", _stats.rx.good.bytes, sm::description("This metric is a receive throughput for this queue.")), sm::make_derive(_queue_name + "_tx_bytes", _stats.tx.good.bytes, sm::description("This metric is a transmit throughput for this queue.")), // // Queue length: GAUGE:0:U // // Tx sm::make_gauge( _queue_name + "_tx_packet_queue", [this] { return _tx_packetq.size(); }, sm::description("Holds a number of packets pending to be sent. " "This metric will have high values if the network backend doesn't keep up " "with the upper layers or if upper layers send big bursts of packets.")), // // Linearization counter: DERIVE:0:U // sm::make_derive(_queue_name + "_xmit_linearized", _stats.tx.linearized, sm::description("Counts a number of linearized Tx packets. High value " "indicates that we send too fragmented packets.")), // // Number of packets in last bunch: GAUGE:0:U // // Tx sm::make_gauge(_queue_name + "_tx_packet_queue_last_bunch", _stats.tx.good.last_bunch, sm::description(format("Holds a number of packets sent in the bunch. " "A high value in conjunction with a high value of a {} " "indicates an efficient Tx packets bulking.", _queue_name + "_tx_packet_queue"))), // Rx sm::make_gauge(_queue_name + "_rx_packet_queue_last_bunch", _stats.rx.good.last_bunch, sm::description("Holds a number of packets received in the last Rx bunch. High " "value indicates an efficient Rx packets bulking.")), // // Fragments rate: DERIVE:0:U // // Tx sm::make_derive( _queue_name + "_tx_frags", _stats.tx.good.nr_frags, sm::description(format("Counts a number of sent fragments. Divide this value by a {} to " "get an average number of fragments in a Tx packet.", _queue_name + "_tx_packets"))), // Rx sm::make_derive( _queue_name + "_rx_frags", _stats.rx.good.nr_frags, sm::description(format("Counts a number of received fragments. Divide this value by a {} " "to get an average number of fragments in an Rx packet.", _queue_name + "_rx_packets"))), }); if (register_copy_stats) { _metrics.add_group( _stats_plugin_name, { // // Non-zero-copy data bytes rate: DERIVE:0:u // // Tx sm::make_derive( _queue_name + "_tx_copy_bytes", _stats.tx.good.copy_bytes, sm::description(format( "Counts a number of sent bytes that were handled in a non-zero-copy way. Divide " "this value by a {} to get a portion of data sent using a non-zero-copy flow.", _queue_name + "_tx_bytes"))), // Rx sm::make_derive( _queue_name + "_rx_copy_bytes", _stats.rx.good.copy_bytes, sm::description(format("Counts a number of received bytes that were handled in a " "non-zero-copy way. Divide this value by an {} to get a portion " "of received data handled using a non-zero-copy flow.", _queue_name + "_rx_bytes"))), // // Non-zero-copy data fragments rate: DERIVE:0:u // // Tx sm::make_derive( _queue_name + "_tx_copy_frags", _stats.tx.good.copy_frags, sm::description(format("Counts a number of sent fragments that were handled in a " "non-zero-copy way. Divide this value by a {} to get a portion " "of fragments sent using a non-zero-copy flow.", _queue_name + "_tx_frags"))), // Rx sm::make_derive( _queue_name + "_rx_copy_frags", _stats.rx.good.copy_frags, sm::description(format("Counts a number of received fragments that were handled in a " "non-zero-copy way. Divide this value by a {} to get a portion " "of received fragments handled using a non-zero-copy flow.", _queue_name + "_rx_frags"))), }); } } qp::~qp() { } void qp::configure_proxies(const std::map<unsigned, float> &cpu_weights) { assert(!cpu_weights.empty()); if ((cpu_weights.size() == 1 && cpu_weights.begin()->first == this_shard_id())) { // special case queue sending to self only, to avoid requiring a hash value return; } register_packet_provider([this] { boost::optional<packet> p; if (!_proxy_packetq.empty()) { p = std::move(_proxy_packetq.front()); _proxy_packetq.pop_front(); } return p; }); build_sw_reta(cpu_weights); } void qp::build_sw_reta(const std::map<unsigned, float> &cpu_weights) { float total_weight = 0; for (auto &&x : cpu_weights) { total_weight += x.second; } float accum = 0; unsigned idx = 0; std::array<uint8_t, 128> reta; for (auto &&entry : cpu_weights) { auto cpu = entry.first; auto weight = entry.second; accum += weight; while (idx < (accum / total_weight * reta.size() - 0.5)) { reta[idx++] = cpu; } } _sw_reta = reta; } future<> device::receive(std::function<future<>(packet)> next_packet) { auto sub = _queues[this_shard_id()]->_rx_stream.listen(std::move(next_packet)); _queues[this_shard_id()]->rx_start(); return sub.done(); } void device::set_local_queue(std::unique_ptr<qp> dev) { assert(!_queues[this_shard_id()]); _queues[this_shard_id()] = dev.get(); engine().at_destroy([dev = std::move(dev)] {}); } l3_protocol::l3_protocol(interface *netif, eth_protocol_num proto_num, packet_provider_type func) : _netif(netif), _proto_num(proto_num) { _netif->register_packet_provider(std::move(func)); } future<> l3_protocol::receive(std::function<future<>(packet p, ethernet_address from)> rx_fn, std::function<bool(forward_hash &, packet &, size_t)> forward) { return _netif->register_l3(_proto_num, std::move(rx_fn), std::move(forward)); }; interface::interface(std::shared_ptr<device> dev) : _dev(dev), _hw_address(_dev->hw_address()), _hw_features(_dev->hw_features()) { // FIXME: ignored future (void)_dev->receive([this](packet p) { return dispatch_packet(std::move(p)); }); dev->local_queue().register_packet_provider([this, idx = 0u]() mutable { boost::optional<packet> p; for (size_t i = 0; i < _pkt_providers.size(); i++) { auto l3p = _pkt_providers[idx++](); if (idx == _pkt_providers.size()) idx = 0; if (l3p) { auto l3pv = std::move(l3p.value()); auto eh = l3pv.p.prepend_header<eth_hdr>(); eh->dst_mac = l3pv.to; eh->src_mac = _hw_address; eh->eth_proto = uint16_t(l3pv.proto_num); *eh = hton(*eh); p = std::move(l3pv.p); return p; } } return p; }); } future<> interface::register_l3(eth_protocol_num proto_num, std::function<future<>(packet p, ethernet_address from)> next, std::function<bool(forward_hash &, packet &p, size_t)> forward) { auto i = _proto_map.emplace(std::piecewise_construct, std::make_tuple(uint16_t(proto_num)), std::forward_as_tuple(std::move(forward))); assert(i.second); l3_rx_stream &l3_rx = i.first->second; return l3_rx.packet_stream.listen(std::move(next)).done(); } unsigned interface::hash2cpu(uint32_t hash) { return _dev->hash2cpu(hash); } uint16_t interface::hw_queues_count() { return _dev->hw_queues_count(); } rss_key_type interface::rss_key() const { return _dev->rss_key(); } void interface::forward(unsigned cpuid, packet p) { static __thread unsigned queue_depth; if (queue_depth < 1000) { queue_depth++; auto src_cpu = this_shard_id(); // FIXME: future is discarded (void)smp::submit_to(cpuid, [this, p = std::move(p), src_cpu]() mutable { _dev->l2receive(p.free_on_cpu(src_cpu)); }).then([] { queue_depth--; }); } } future<> interface::dispatch_packet(packet p) { auto eh = p.get_header<eth_hdr>(); if (eh) { auto i = _proto_map.find(ntoh(eh->eth_proto)); if (i != _proto_map.end()) { l3_rx_stream &l3 = i->second; auto fw = _dev->forward_dst(this_shard_id(), [&p, &l3, this]() { auto hwrss = p.rss_hash(); if (hwrss) { return hwrss.value(); } else { forward_hash data; if (l3.forward(data, p, sizeof(eth_hdr))) { return toeplitz_hash(rss_key(), data); } return 0u; } }); if (fw != this_shard_id()) { forward(fw, std::move(p)); } else { auto h = ntoh(*eh); auto from = h.src_mac; p.trim_front(sizeof(*eh)); // avoid chaining, since queue lenth is unlimited // drop instead. if (l3.ready.available()) { l3.ready = l3.packet_stream.produce(std::move(p), from); } } } } return make_ready_future<>(); } } // namespace net } // namespace actor } // namespace nil
49.886889
120
0.445532
NilFoundation
576da8069b59e53da6e5df30d9347d9ab1badec0
128
cpp
C++
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/MatrixBase_template_int_start.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
27
2017-06-07T19:07:32.000Z
2020-10-15T10:09:12.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/MatrixBase_template_int_start.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
3
2017-08-25T17:39:46.000Z
2017-11-18T03:40:55.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/MatrixBase_template_int_start.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
10
2017-06-16T18:04:45.000Z
2018-07-05T17:33:01.000Z
version https://git-lfs.github.com/spec/v1 oid sha256:4b7afeba550c42f9d83c1216d8b1f28efe9eb21defa44e01e94a8fde5aa5b682 size 230
32
75
0.882813
initialz
577147c47c118b7ad546fafc37ccf7359e76743e
1,577
cpp
C++
PlatformLib/Graphics/Vulkan/cpp/VulkanTextureView.cpp
YIMonge/Rev
db3b71a27659a2652bdd50069a881702b3ae059e
[ "MIT" ]
null
null
null
PlatformLib/Graphics/Vulkan/cpp/VulkanTextureView.cpp
YIMonge/Rev
db3b71a27659a2652bdd50069a881702b3ae059e
[ "MIT" ]
null
null
null
PlatformLib/Graphics/Vulkan/cpp/VulkanTextureView.cpp
YIMonge/Rev
db3b71a27659a2652bdd50069a881702b3ae059e
[ "MIT" ]
null
null
null
#ifdef _USE_VULKAN #include "VulkanTextureView.h" void VulkanTextureView::Create(revDevice* device, const revTexture& texture, const VulkanSampler& sampler, VulkanDescriptorSet::Chunk& chunk) { this->device = device; VkImageViewCreateInfo imageViewCreateInfo = {}; imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; imageViewCreateInfo.pNext = nullptr; imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; imageViewCreateInfo.components = { VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A, }; imageViewCreateInfo.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }; imageViewCreateInfo.flags = 0; imageViewCreateInfo.format = ConvertToVKFormat(texture.GetFormat()); imageViewCreateInfo.image = texture.GetHandle(); VkResult result = vkCreateImageView(device->GetDevice(), &imageViewCreateInfo, nullptr, &resourceView); if(result != VK_SUCCESS) { NATIVE_LOGE("Vulkan error. File[%s], line[%d]", __FILE__,__LINE__); return; } descriptorImageInfo.sampler = sampler.GetHandle(); descriptorImageInfo.imageView = resourceView; descriptorImageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; //descriptorImageInfo.imageLayout = VK_IMAGE_LAYOUT_GENERAL; chunk.UpdateResource(0, DESCRIPTOR_TYPE::TEXTURE_SHADER_RESOURCE_VIEW, &descriptorImageInfo, nullptr, nullptr); } void VulkanTextureView::Destroy() { vkDestroyImageView(device->GetDevice(), resourceView, nullptr); } #endif
39.425
141
0.763475
YIMonge
5772b8aba18556c0005b0b5531369da8a3a830c3
2,612
cpp
C++
cores/n64/GLideN64/src/Graphics/OpenGLContext/GraphicBuffer/GraphicBufferWrapper.cpp
wulfebw/retro
dad4b509e99e729e39a2f27e9ee4120e3b607f58
[ "MIT-0", "MIT" ]
7
2020-07-20T12:11:35.000Z
2021-12-23T02:09:19.000Z
cores/n64/GLideN64/src/Graphics/OpenGLContext/GraphicBuffer/GraphicBufferWrapper.cpp
wulfebw/retro
dad4b509e99e729e39a2f27e9ee4120e3b607f58
[ "MIT-0", "MIT" ]
null
null
null
cores/n64/GLideN64/src/Graphics/OpenGLContext/GraphicBuffer/GraphicBufferWrapper.cpp
wulfebw/retro
dad4b509e99e729e39a2f27e9ee4120e3b607f58
[ "MIT-0", "MIT" ]
1
2020-08-29T16:36:48.000Z
2020-08-29T16:36:48.000Z
// Based on https://github.com/chromium/chromium/blob/master/base/android/android_hardware_buffer_compat.h #include "GraphicBufferWrapper.h" #include <Graphics/OpenGLContext/GraphicBuffer/PublicApi/android_hardware_buffer_compat.h> #include "../GLFunctions.h" #include <dlfcn.h> #include <sys/system_properties.h> #include <sstream> namespace opengl { GraphicBufferWrapper::GraphicBufferWrapper() { m_private = false; if (!isSupportAvailable()) { return; } if (getApiLevel() <= 23) { m_private = true; m_privateGraphicBuffer = new GraphicBuffer(); } } GraphicBufferWrapper::~GraphicBufferWrapper() { if (m_private) { delete m_privateGraphicBuffer; } } bool GraphicBufferWrapper::isSupportAvailable() { int apiLevel = getApiLevel(); return apiLevel >= 26 || apiLevel <= 23; } bool GraphicBufferWrapper::isPublicSupportAvailable() { int apiLevel = getApiLevel(); return apiLevel >= 26; } bool GraphicBufferWrapper::allocate(const AHardwareBuffer_Desc *desc) { if (m_private) { return m_privateGraphicBuffer->reallocate(desc->width, desc->height, desc->format, desc->usage); } else { return AndroidHardwareBufferCompat::GetInstance().Allocate(desc, &m_publicGraphicBuffer) == 0; } } int GraphicBufferWrapper::lock(uint64_t usage, void **out_virtual_address) { int returnValue = 0; if (m_private) { returnValue = m_privateGraphicBuffer->lock(usage, out_virtual_address); } else { returnValue = AndroidHardwareBufferCompat::GetInstance().Lock(m_publicGraphicBuffer, usage, -1, nullptr, out_virtual_address); }; return returnValue; } void GraphicBufferWrapper::release() { if (!m_private) { AndroidHardwareBufferCompat::GetInstance().Release(m_publicGraphicBuffer); } } void GraphicBufferWrapper::unlock() { if (m_private) { m_privateGraphicBuffer->unlock(); } else { AndroidHardwareBufferCompat::GetInstance().Unlock(m_publicGraphicBuffer, nullptr); } } EGLClientBuffer GraphicBufferWrapper::getClientBuffer() { EGLClientBuffer clientBuffer = nullptr; if (m_private) { clientBuffer = (EGLClientBuffer)m_privateGraphicBuffer->getNativeBuffer(); } else { clientBuffer = eglGetNativeClientBufferANDROID(m_publicGraphicBuffer); } return clientBuffer; } int GraphicBufferWrapper::getApiLevel() { static bool apiLevelChecked = false; static int apiLevel = 0; if (!apiLevelChecked) { char *androidApiLevel = new char[PROP_VALUE_MAX]; int valid = __system_property_get("ro.build.version.sdk", androidApiLevel); if (valid > 0) { std::stringstream convert(androidApiLevel); convert >> apiLevel; } } return apiLevel; } }
22.324786
128
0.753063
wulfebw
57744dc92be53b43a9265b40199e9d0dceeae52c
335
hpp
C++
raisim/win32/mt_release/include/raisim/math/Core.hpp
simRepoRelease/raisimLib
00724ac2abb0b4c11aadb4ddd3455fc42c57a34e
[ "Apache-2.0" ]
142
2020-10-21T18:18:13.000Z
2022-03-29T11:49:25.000Z
raisim/win32/mt_release/include/raisim/math/Core.hpp
simRepoRelease/raisimLib
00724ac2abb0b4c11aadb4ddd3455fc42c57a34e
[ "Apache-2.0" ]
192
2020-10-21T15:51:15.000Z
2022-03-28T12:56:01.000Z
raisim/win32/mt_release/include/raisim/math/Core.hpp
simRepoRelease/raisimLib
00724ac2abb0b4c11aadb4ddd3455fc42c57a34e
[ "Apache-2.0" ]
51
2020-10-26T08:29:54.000Z
2022-03-23T12:00:23.000Z
//----------------------------// // This file is part of RaiSim// // Copyright 2020, RaiSim Tech// //----------------------------// #ifndef RAIMATH__CORE_HPP_ #define RAIMATH__CORE_HPP_ #include "Expression.hpp" #include "Eigen/Core" #include "Eigen/Dense" #include "Matrix.hpp" #include "Product.hpp" #endif //RAIMATH__CORE_HPP_
18.611111
32
0.602985
simRepoRelease
57774f31f626799496f06bd086943ae680404762
226
cc
C++
test_testdriver/test_main.cc
KarlJansson/CMakeMaker
05ec25ca4ea196a50697e13f7756e7be79a08281
[ "MIT" ]
null
null
null
test_testdriver/test_main.cc
KarlJansson/CMakeMaker
05ec25ca4ea196a50697e13f7756e7be79a08281
[ "MIT" ]
null
null
null
test_testdriver/test_main.cc
KarlJansson/CMakeMaker
05ec25ca4ea196a50697e13f7756e7be79a08281
[ "MIT" ]
null
null
null
#include "precomp.h" #include "test_common_writer.h" #include "test_subdir_writer.h" #include "test_testtarget_writer.h" int main(int argc, char** args) { ::testing::InitGoogleTest(&argc, args); return RUN_ALL_TESTS(); }
22.6
41
0.738938
KarlJansson
577c908ac26e6682612eb991cd821acb5b8d5859
876
cpp
C++
cpp/src/SearchInRotatedSortedArrayII.cpp
qianbinbin/leetcode
915cecab0c940cd13847683ec55b17b77eb0f39b
[ "MIT" ]
4
2018-03-05T02:27:16.000Z
2021-03-15T14:19:44.000Z
cpp/src/SearchInRotatedSortedArrayII.cpp
qianbinbin/leetcode
915cecab0c940cd13847683ec55b17b77eb0f39b
[ "MIT" ]
null
null
null
cpp/src/SearchInRotatedSortedArrayII.cpp
qianbinbin/leetcode
915cecab0c940cd13847683ec55b17b77eb0f39b
[ "MIT" ]
2
2018-07-22T10:32:10.000Z
2018-10-20T03:14:28.000Z
#include "SearchInRotatedSortedArrayII.h" #include <cassert> #include <limits> using namespace lcpp; bool Solution81_1::search(std::vector<int> &nums, int target) { assert(nums.size() <= std::numeric_limits<int>::max() && "Size overflow!"); int Low = 0, High = static_cast<int>(nums.size()) - 1, Mid; while (Low <= High) { Mid = Low + (High - Low) / 2; const auto &MidVal = nums[Mid]; if (MidVal == target) return true; const auto &LowVal = nums[Low]; if (LowVal < MidVal) { if (LowVal <= target && target < MidVal) High = Mid - 1; else Low = Mid + 1; } else if (LowVal > MidVal) { if (MidVal < target && target <= nums[High]) Low = Mid + 1; else High = Mid - 1; } else { do { ++Low; } while (Low <= High && nums[Low] == LowVal); } } return false; }
25.764706
77
0.544521
qianbinbin
577d88d8aec5a4153ce1aba5cb462c3dd6e56bac
4,295
hpp
C++
logos/consensus/persistence/block_cache.hpp
LogosNetwork/logos-core
6b155539a734efefb8f649a761d044b5f267a51a
[ "BSD-2-Clause" ]
3
2020-01-17T18:05:19.000Z
2021-12-29T04:21:59.000Z
logos/consensus/persistence/block_cache.hpp
LogosNetwork/logos-core
6b155539a734efefb8f649a761d044b5f267a51a
[ "BSD-2-Clause" ]
null
null
null
logos/consensus/persistence/block_cache.hpp
LogosNetwork/logos-core
6b155539a734efefb8f649a761d044b5f267a51a
[ "BSD-2-Clause" ]
2
2020-12-22T05:51:53.000Z
2021-06-08T00:27:46.000Z
#pragma once #include <memory> #include <mutex> #include <unordered_set> #include <logos/lib/numbers.hpp> #include <logos/lib/hash.hpp> #include <logos/lib/trace.hpp> #include <logos/blockstore.hpp> #include <logos/consensus/messages/common.hpp> #include <logos/consensus/messages/messages.hpp> #include <logos/epoch/epoch.hpp> #include <logos/epoch/epoch_handler.hpp> #include <logos/microblock/microblock.hpp> #include <logos/microblock/microblock_handler.hpp> #include "block_container.hpp" #include "block_write_queue.hpp" namespace logos { class IBlockCache { public: using RBPtr = std::shared_ptr<ApprovedRB>; using MBPtr = std::shared_ptr<ApprovedMB>; using EBPtr = std::shared_ptr<ApprovedEB>; enum add_result { FAILED, EXISTS, OK }; // should be called by bootstrap and P2P /** * add an epoch block to the cache * @param block the block * @return true if the block has good signatures. */ virtual add_result AddEpochBlock(EBPtr block) = 0; /** * add a micro block to the cache * @param block the block * @return true if the block has good signatures. */ virtual add_result AddMicroBlock(MBPtr block) = 0; /** * add a request block to the cache * @param block the block * @return true if the block has good signatures. */ virtual add_result AddRequestBlock(RBPtr block) = 0; // should be called by consensus virtual void StoreEpochBlock(EBPtr block) = 0; virtual void StoreMicroBlock(MBPtr block) = 0; virtual void StoreRequestBlock(RBPtr block) = 0; virtual bool ValidateRequest( std::shared_ptr<Request> req, uint32_t epoch_num, logos::process_return& result) {return false;} // should be called by bootstrap /** * check if a block is cached * @param b the hash of the block * @return true if the block is in the cache */ virtual bool IsBlockCached(const BlockHash &b) = 0; virtual bool IsBlockCachedOrQueued(const BlockHash &b) = 0; virtual ~IBlockCache() = default; }; class BlockCache: public IBlockCache { public: using Store = logos::block_store; /** * constructor * @param store the database */ BlockCache(boost::asio::io_service & service, Store & store, std::queue<BlockHash> *unit_test_q = 0); /** * (inherited) add an epoch block to the cache * @param block the block * @return true if the block has good signatures. */ add_result AddEpochBlock(EBPtr block) override; /** * (inherited) add a micro block to the cache * @param block the block * @return true if the block has good signatures. */ add_result AddMicroBlock(MBPtr block) override; /** * (inherited) add a request block to the cache * @param block the block * @return true if the block has good signatures. */ add_result AddRequestBlock(RBPtr block) override; void StoreEpochBlock(EBPtr block) override; void StoreMicroBlock(MBPtr block) override; void StoreRequestBlock(RBPtr block) override; virtual bool ValidateRequest( std::shared_ptr<Request> req, uint32_t epoch_num, logos::process_return& result) { return _write_q.ValidateRequest(req,epoch_num,result); } /** * (inherited) check if a block is cached * @param b the hash of the block * @return true if the block is in the cache */ bool IsBlockCached(const BlockHash &b) override; bool IsBlockCachedOrQueued(const BlockHash &b) override; void ProcessDependencies(EBPtr block); void ProcessDependencies(MBPtr block); void ProcessDependencies(RBPtr block); private: /* * should be called when: * (1) a new block is added to the beginning of any chain of the oldest epoch, * (2) a new block is added to the beginning of any BSB chain of the newest epoch, * in which the first MB has not been received. */ void Validate(uint8_t bsb_idx = 0); block_store & _store; BlockWriteQueue _write_q; PendingBlockContainer _block_container; Log _log; }; }
27.183544
105
0.652619
LogosNetwork
578426ac2e24c34d55bdf3160fe668698aca5adc
264
hpp
C++
dynamic/wrappers/cell_based/SimpleTargetAreaModifier2.cppwg.hpp
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
6
2017-02-04T16:10:53.000Z
2021-07-01T08:03:16.000Z
dynamic/wrappers/cell_based/SimpleTargetAreaModifier2.cppwg.hpp
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
6
2017-06-22T08:50:41.000Z
2019-12-15T20:17:29.000Z
dynamic/wrappers/cell_based/SimpleTargetAreaModifier2.cppwg.hpp
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
3
2017-05-15T21:33:58.000Z
2019-10-27T21:43:07.000Z
#ifndef SimpleTargetAreaModifier2_hpp__pyplusplus_wrapper #define SimpleTargetAreaModifier2_hpp__pyplusplus_wrapper namespace py = pybind11; void register_SimpleTargetAreaModifier2_class(py::module &m); #endif // SimpleTargetAreaModifier2_hpp__pyplusplus_wrapper
37.714286
61
0.893939
jmsgrogan
5785136e1ce93a212f6f6835c971d31e13efba6e
472
cpp
C++
calendar/monthFirstDay.cpp
allhailthetail/cpp-itp-main
43a33a3df68feac3a600b3a51af3fbe893225277
[ "MIT" ]
null
null
null
calendar/monthFirstDay.cpp
allhailthetail/cpp-itp-main
43a33a3df68feac3a600b3a51af3fbe893225277
[ "MIT" ]
null
null
null
calendar/monthFirstDay.cpp
allhailthetail/cpp-itp-main
43a33a3df68feac3a600b3a51af3fbe893225277
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int monthStart(int month, int year){ //fills an array with days of the week... //determines day of the week the 1st is on: static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; const int day = 1; //always first day of month int week_day; year -= month < 3; week_day = ( year + year/4 - year/100 + year/400 + t[month-1] + day) % 7; return week_day; } int main(){ cout << monthStart(2,2018) << endl;; }
21.454545
75
0.599576
allhailthetail
578b957954c6bf9c9ade1639de916244b36d04f3
1,101
cpp
C++
Graphs/Longest Path in a DAG.cpp
Sumitkk10/Competitive-Programming
886eabe251f962336070a02bba92c9ac768d8e92
[ "MIT" ]
3
2020-09-25T07:40:29.000Z
2020-10-09T18:11:57.000Z
Graphs/Longest Path in a DAG.cpp
Sumitkk10/Competitive-Programming
886eabe251f962336070a02bba92c9ac768d8e92
[ "MIT" ]
null
null
null
Graphs/Longest Path in a DAG.cpp
Sumitkk10/Competitive-Programming
886eabe251f962336070a02bba92c9ac768d8e92
[ "MIT" ]
2
2020-09-25T10:32:57.000Z
2021-02-28T03:23:29.000Z
// Longest path in a DAG #include <bits/stdc++.h> #define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL) #define ll long long int #define ld long double using namespace std; const int N = 1e6 + 5; const int MOD = 1e9 + 7; vector<int> graph[N]; queue<int> q; int LPD[N], indegree[N]; bool vis[N]; void dfs(int source){ vis[source] = 1; for(auto kk : graph[source]){ indegree[kk]++; if(!vis[kk]) dfs(kk); } } void topo(){ while(!q.empty()){ int x = q.front(); q.pop(); for(auto k : graph[x]){ if(!vis[k]){ indegree[k]--; if(indegree[k] == 0){ q.push(k); vis[k] = true; } LPD[k] = max(LPD[k], LPD[x] + 1); } } } } int main(){ fast; int n, m; cin >> n >> m; for(int i = 0; i < m; ++i){ int u, v; cin >> u >> v; graph[u].push_back(v); } for(int i = 1; i <= n; ++i) if(!vis[i]) dfs(i); memset(vis, 0, sizeof(vis)); for(int i = 1; i <= n; ++i){ if(!indegree[i]){ q.push(i); vis[i] = true; } } topo(); int ans = 0; for(int i = 1; i <= n; ++i) ans = max(ans, LPD[i]); cout << ans << '\n'; return 0; }
16.432836
70
0.521344
Sumitkk10
578be78672ab79c962eec4fcfe993da20c715181
3,374
hpp
C++
src/navigationbar.hpp
Qt-Widgets/qtmwidgets-mobile
24b77c25c286215539098ba569eee938882bb9d4
[ "MIT" ]
10
2015-03-22T07:35:48.000Z
2022-02-23T15:49:01.000Z
src/navigationbar.hpp
Qt-Widgets/qtmwidgets
24b77c25c286215539098ba569eee938882bb9d4
[ "MIT" ]
9
2020-10-22T09:25:52.000Z
2022-02-14T08:59:13.000Z
src/navigationbar.hpp
Qt-Widgets/qtmwidgets
24b77c25c286215539098ba569eee938882bb9d4
[ "MIT" ]
9
2018-01-22T06:47:40.000Z
2022-01-30T16:50:57.000Z
/*! \file \author Igor Mironchik (igor.mironchik at gmail dot com). Copyright (c) 2014 Igor Mironchik 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 QTMWIDGETS__NAVIGATIONBAR_HPP__INCLUDED #define QTMWIDGETS__NAVIGATIONBAR_HPP__INCLUDED // Qt include. #include <QWidget> #include <QScopedPointer> namespace QtMWidgets { // // NavigationBar // class NavigationBarPrivate; /*! Navigation bars allow you to present your app’s content in an organized and intuitive way. A navigation bar is displayed at the top of the screen, and contains buttons for navigating through a hierarchy of screens. A navigation bar generally has a back button, a title, and a right button. */ class NavigationBar : public QWidget { Q_OBJECT signals: //! This signal emitted when current screen changes. void currentChanged( int index ); public: NavigationBar( QWidget * parent = 0 ); virtual ~NavigationBar(); /*! Set main widget of the hierarchy of screens. \return Index of the screen. Main widgets can be more than one. */ int setMainWidget( const QString & title, QWidget * widget ); /*! Add subordinate screen to the hierarchy of screens. \return Index of the screen. */ int addWidget( QWidget * parent, const QString & title, QWidget * widget ); //! Remove widget from the hierarchy. void removeWidget( QWidget * widget ); //! \return Index of the current screen. int currentIndex() const; //! \return Current widget. QWidget * currentWidget() const; //! \return Index of the given \a widget widget. int indexOf( QWidget * widget ) const; //! \return Widget with the given \a index index. QWidget * widget( int index ) const; QSize minimumSizeHint() const override; QSize sizeHint() const override; public slots: //! Show screen with the given \a index index. void showScreen( QWidget * s ); //! Show previous screen. void showPreviousScreen(); //! Show next screen. void showNextScreen(); protected: void resizeEvent( QResizeEvent * e ) override; void hideEvent( QHideEvent * e ) override; private: Q_DISABLE_COPY( NavigationBar ) QScopedPointer< NavigationBarPrivate > d; }; // class NavigationBar } /* namespace QtMWidgets */ #endif // QTMWIDGETS__NAVIGATIONBAR_HPP__INCLUDED
27.209677
67
0.723177
Qt-Widgets
c2318bd4493f89a167861620a9f8315d8b5b6cc0
10,523
cpp
C++
Chap09/BusObject/CQuartermaster.cpp
KLM-GIT/Professional-NT-Services
cf058239286b5be14a21f7f19d41683842b92313
[ "Apache-2.0" ]
null
null
null
Chap09/BusObject/CQuartermaster.cpp
KLM-GIT/Professional-NT-Services
cf058239286b5be14a21f7f19d41683842b92313
[ "Apache-2.0" ]
null
null
null
Chap09/BusObject/CQuartermaster.cpp
KLM-GIT/Professional-NT-Services
cf058239286b5be14a21f7f19d41683842b92313
[ "Apache-2.0" ]
null
null
null
#include "stdafx.h" #define HANDLEALLOCCOST 1000 //remove to use //---------------------------------------- // // List Class members // #define SPINX 5000 CFreeList::CFreeList() : m_pHead( NULL ), m_pTail( NULL ), m_Count(0) { InitializeCriticalSectionAndSpinCount( &m_cs, SPINX ); } CFreeList::~CFreeList() { RemoveAll(); DeleteCriticalSection( &m_cs ); } void CFreeList::AddTail( const RHANDLE* newHandle ) { NODE* pNew = new NODE(newHandle); EnterCriticalSection( &m_cs ); if( m_pTail == NULL) //list is empty { m_pHead = pNew; } else { pNew->prev = m_pTail; m_pTail->next = pNew; } m_pTail = pNew; m_Count++; LeaveCriticalSection( &m_cs ); } void CFreeList::RemoveAll( ) { NODE* pNext = 0; EnterCriticalSection( &m_cs ); NODE* p = m_pHead; while( p != NULL ) { pNext = p->next; delete p; p = pNext; } m_pHead = m_pTail = NULL; m_Count = 0; LeaveCriticalSection( &m_cs ); } const RHANDLE* CFreeList::Pop( ) { const RHANDLE* rh = 0; EnterCriticalSection( &m_cs ); NODE* p = m_pHead; if( p != NULL ) { //obtain rhandle rh = p->pRH; if( p->next ) { p->next->prev = NULL; m_pHead = p->next; } else m_pHead = m_pTail = NULL; delete p; m_Count--; } LeaveCriticalSection( &m_cs ); return rh; } //--------------------------------------------------------------------------- // CResourceArray Class // // // CResourceArray::CResourceArray( long dwSize ) :m_size(dwSize), m_count(0), m_hEnv(NULL) { InitializeCriticalSectionAndSpinCount( &m_cs, SPINX); m_pHandles = new RHANDLEHEADER* [dwSize]; memset(m_pHandles, 0, sizeof(RHANDLEHEADER*) * dwSize); } void CResourceArray::Init( LPTSTR szServer, LPTSTR szLogin, LPTSTR szPassword) { _tcscpy( m_szServer, szServer ); _tcscpy( m_szLogin, szLogin ); _tcscpy( m_szPassword, szPassword); } CResourceArray::~CResourceArray( ) { RemoveAll( ); delete [] m_pHandles; m_size = 0; m_pHandles = NULL; if (m_hEnv) SQLFreeHandle(SQL_HANDLE_ENV, m_hEnv); DeleteCriticalSection( &m_cs ); } const RHANDLE* CResourceArray::Add( ) { SQLHDBC hSession = 0; RHANDLE* chd = 0; EnterCriticalSection( &m_cs ); if (m_count < m_size) { hSession = GetResourceHandle( ); if ( hSession != 0 ) { RHANDLEHEADER* pSH = new RHANDLEHEADER; chd = new RHANDLE; chd->handle = hSession; chd->pos = m_count; pSH->pRH = chd; pSH->bFree = TRUE; pSH->dwTime = 0; m_pHandles[m_count] = pSH; m_count++ ; } else { //Event Log call CEventLog el(_Module.m_szServiceName); el.LogEvent( BUSOBJ_HANDLE_CONNECTION_FAILED, EVENTLOG_ERROR_TYPE); } } LeaveCriticalSection( &m_cs ); return chd; } void CResourceArray::RemoveAll( ) { RHANDLEHEADER* pTemp = 0; EnterCriticalSection( &m_cs ); for( int i=0; i<m_count; i++ ) { pTemp = m_pHandles[i]; if( pTemp ) { const RHANDLE* pRHTemp = pTemp->pRH; if( pRHTemp ) { ReleaseResourceHandle( pRHTemp->handle ); delete (RHANDLE*)pRHTemp; } delete pTemp; } m_pHandles[i] = NULL; } m_count = 0; LeaveCriticalSection( &m_cs ); } SQLHDBC CResourceArray::GetResourceHandle( ) { if (!m_hEnv) AllocateEnvironment(); if(!m_hEnv) goto ErrorH; SQLHDBC hdbc; SQLRETURN rc; //Open connection rc = SQLAllocHandle(SQL_HANDLE_DBC, m_hEnv, &hdbc); if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) goto ErrorH; // Set login timeout to 5 seconds. SQLSetConnectAttr(hdbc, SQL_ATTR_LOGIN_TIMEOUT, (SQLPOINTER)5, 0); // Connect to data source rc = SQLConnect(hdbc,(SQLCHAR*) m_szServer, SQL_NTS, (SQLCHAR*) m_szLogin, SQL_NTS, (SQLCHAR*) m_szPassword, SQL_NTS); if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) goto ErrorH; return hdbc; ErrorH: CEventLog el(_Module.m_szServiceName); el.LogEvent(BUSOBJ_HANDLE_CONNECTION_FAILED, EVENTLOG_ERROR_TYPE); return NULL; } void CResourceArray::ReleaseResourceHandle( SQLHDBC hResHandle ) { if(hResHandle) { SQLDisconnect(hResHandle); SQLFreeHandle(SQL_HANDLE_DBC, hResHandle); } } void CResourceArray::AllocateEnvironment() { SQLRETURN rc; rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_hEnv); rc = SQLSetEnvAttr(m_hEnv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); return; } //--------------------------------------------------------------------------- // // CQuartermaster Class // // CQuartermaster* CQuartermaster::m_pThis = 0; CQuartermaster::CQuartermaster( ) :m_dwNumCurrentResources(0), m_bStartAllocator(FALSE) { m_pThis = this; InitializeCriticalSectionAndSpinCount( &m_cs, SPINX ); } void CQuartermaster::Init( DWORD dwMaxResources, DWORD dwStartResources, DWORD dwWaitForHandleTime, DWORD dwHandleLifeTime, DWORD dwAllocationPoll, DWORD dwMinPoolSize, DWORD dwResourceAllocSize, DWORD dwDeadResourcePoll, LPTSTR szServer, LPTSTR szLogin, LPTSTR szPassword ) { //Event to signal workers to stop m_hStopEvent = CreateEvent( NULL, TRUE, FALSE, NULL ); m_dwStartResources = dwStartResources; m_dwMaxResources = dwMaxResources; m_dwWaitForHandleTime = dwWaitForHandleTime; m_dwHandleLifeTime = dwHandleLifeTime; m_dwAllocationPoll = dwAllocationPoll; m_dwMinPoolSize = dwMinPoolSize; m_dwResourceAllocSize = dwResourceAllocSize; m_dwDeadResourcePoll =dwDeadResourcePoll; m_pResources = new CResourceArray( dwMaxResources ); m_pFreeList = new CFreeList; //Initialize the Resource Array m_pResources->Init( szServer, szLogin, szPassword ); //Initialize the Semaphore with max possible m_hSem = CreateSemaphore( NULL, 0, dwMaxResources, NULL ); DWORD dwAid, dwPid; m_hAllocThread = (HANDLE)_beginthreadex( NULL, 0, (PBEGINTHREADEX_TFUNC)CQuartermaster::AllocateMoreResourcesThread, 0, 0, (PBEGINTHREADEX_TID)&dwAid ); m_hRefreshThread = (HANDLE)_beginthreadex( NULL, 0, (PBEGINTHREADEX_TFUNC)CQuartermaster::RefreshDeadResourcesThread, 0, 0, (PBEGINTHREADEX_TID)&dwPid ); } CQuartermaster::~CQuartermaster( ) { if (m_hAllocThread) CloseHandle(m_hAllocThread); if (m_hRefreshThread) CloseHandle(m_hRefreshThread); CloseHandle( m_hSem ); delete m_pResources; m_pResources = NULL; delete m_pFreeList; m_pFreeList = NULL; DeleteCriticalSection( &m_cs ); } DWORD CQuartermaster::GetFreeResource( const RHANDLE** poutHandle) { //Function does NOT find a KNOWN valid handle. It is up to the //object to check handle validity and retry if necessary. const RHANDLE* pHandle = 0; if ( _Module.m_bPaused || _Module.m_bStopped ) return BUSOBJ_SERVICE_STOPPED_PAUSED; //Wait on the semaphore. I can block for a short time if no handles left. if( WaitForSingleObject( m_hSem, m_dwWaitForHandleTime ) == WAIT_OBJECT_0 ) { //Get the handle and give it out pHandle = m_pFreeList->Pop(); if( pHandle ) { //Mark time and busy m_pResources->SetBusy( pHandle->pos ); *poutHandle = pHandle; return 0; } } *poutHandle = NULL; return BUSOBJ_NOSESSIONS_AVAILABLE; } void CQuartermaster::ReleaseResource( const RHANDLE* handle ) { //Make sure handle hasn't been released twice by client accidentally if (handle) { if( m_pResources->IsFree( handle->pos ) == FALSE ) { long lPrev; m_pResources->SetFree( handle->pos ); m_pFreeList->AddTail( handle ); ReleaseSemaphore( m_hSem, 1, &lPrev ); } } } DWORD CQuartermaster::AllocateResources( DWORD dwNumAdd ) { DWORD count = 0; const RHANDLE* pRH = 0; DWORD newRes = 0; DWORD dwNumRes = GetNumResources(); if ( dwNumAdd + dwNumRes > m_dwMaxResources ) newRes = m_dwMaxResources - dwNumRes; else newRes = dwNumAdd; //Connect the sessions for( DWORD i=0; i<newRes; i++ ) { pRH = m_pResources->Add( ); if( pRH ) { m_pFreeList->AddTail( pRH ); count++; } } InterlockedExchangeAdd((long*)&m_dwNumCurrentResources, count); //ReleaseSemaphore count number of times if( count > 0 ) { long dwPrev; ReleaseSemaphore( m_hSem, (long)count ,&dwPrev ); } //Write to event log that x new handles were allocated TCHAR sz1[5], sz2[5]; wsprintf(sz1,_T("%lu"), count ); wsprintf(sz2,_T("%lu"), dwNumRes ); const TCHAR* rgsz[2] = { sz1, sz2 }; CEventLog el(_Module.m_szServiceName); el.LogEvent( BUSOBJ_MORESESSIONS_ALLOCATED, rgsz, 2, EVENTLOG_INFORMATION_TYPE ); //Also write if maximum session limit was reached. if ( GetNumResources() >= m_dwMaxResources ) { el.LogEvent( BUSOBJ_MAXIMUM_SESSIONS_ALLOCATED, EVENTLOG_INFORMATION_TYPE ); } //Allow the allocator thread to start, if it hasn't before if(!m_bStartAllocator) InterlockedExchange( (long*)&m_bStartAllocator, true); //Return return count; } void CQuartermaster::DeallocateResources( ) { EnterCriticalSection( &m_cs ); //Stop the worker threads SetStop(); m_dwNumCurrentResources = 0; m_pResources->RemoveAll( ); m_pFreeList->RemoveAll( ); LeaveCriticalSection( &m_cs ); } //Will be called on a schedule by another thread void CQuartermaster::ReleaseDeadResources( ) { //Walk the list and see if any bFrees are FALSE with //now - timestamp > m_dwHandleLifetime //If so, bFree = TRUE //and add back to free list. CRITICAL_SECTION cs; InitializeCriticalSection( &cs ); DWORD now = ::GetTickCount(); RHANDLEHEADER* pTemp = 0; DWORD stamp = 0; long count = m_pResources->GetCount(); for( long i=0; i<count; i++ ) { pTemp = m_pResources->m_pHandles[i]; if( pTemp ) { EnterCriticalSection( &cs ); if( m_pResources->IsFree(i) == FALSE ) { stamp = pTemp->dwTime; if( now - stamp > m_dwHandleLifeTime ) { if( pTemp->pRH ) { m_pResources->SetFree(i); m_pFreeList->AddTail( pTemp->pRH ); } } } LeaveCriticalSection( &cs ); } } DeleteCriticalSection( &cs ); } ///////// //Background task threads ///////// DWORD WINAPI CQuartermaster::AllocateMoreResourcesThread( LPVOID lpParameter ) { while (WaitForSingleObject( m_pThis->m_hStopEvent, m_pThis->m_dwAllocationPoll ) == WAIT_TIMEOUT ) { if( m_pThis->FreeResourcesLeft() <= m_pThis->m_dwMinPoolSize && m_pThis->m_bStartAllocator) { m_pThis->AllocateResources( m_pThis->m_dwResourceAllocSize ); Sleep( HANDLEALLOCCOST ); //**Simulation** of amount of time it takes } } return 0; } DWORD WINAPI CQuartermaster::RefreshDeadResourcesThread( LPVOID lpParameter ) { while (WaitForSingleObject( m_pThis->m_hStopEvent, m_pThis->m_dwDeadResourcePoll ) == WAIT_TIMEOUT ) { m_pThis->ReleaseDeadResources( ); } return 0; }
20.962151
101
0.683265
KLM-GIT
c2334e6030a08f5cdd8401833d05e1bdf460d1df
11,881
cc
C++
instrumentation/instrument.cc
fengjixuchui/bochspwn
2d96439191ac83e07f53fc7a27a65d18aefdcc23
[ "Apache-2.0" ]
138
2018-09-11T16:30:00.000Z
2022-03-29T20:34:02.000Z
instrumentation/instrument.cc
fengjixuchui/bochspwn
2d96439191ac83e07f53fc7a27a65d18aefdcc23
[ "Apache-2.0" ]
4
2015-01-19T13:13:14.000Z
2018-08-02T11:45:32.000Z
instrumentation/instrument.cc
fengjixuchui/bochspwn
2d96439191ac83e07f53fc7a27a65d18aefdcc23
[ "Apache-2.0" ]
36
2015-01-15T08:02:32.000Z
2018-08-02T01:59:52.000Z
///////////////////////////////////////////////////////////////////////// // // Authors: Mateusz Jurczyk (mjurczyk@google.com) // Gynvael Coldwind (gynvael@google.com) // // Copyright 2013-2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include <windows.h> #include <cstdarg> #include <cstdint> #include <map> #include <string> #include <vector> #include "bochs.h" #include "cpu/cpu.h" #include "disasm/disasm.h" #include "common.h" #include "events.h" #include "instrument.h" #include "invoke.h" #include "logging.pb.h" #include "symbols.h" // ------------------------------------------------------------------ // Helper declarations. // ------------------------------------------------------------------ static bool init_basic_config(const char *path, bochspwn_config *config); static void process_mem_access(BX_CPU_C *pcpu, bx_address lin, unsigned len, bx_address pc, log_data_st::mem_access_type access_type, char *disasm); static void destroy_globals(); // ------------------------------------------------------------------ // Instrumentation implementation. // ------------------------------------------------------------------ // Callback invoked on Bochs CPU initialization. void bx_instr_initialize(unsigned cpu) { char *conf_path = NULL; // Initialize symbols subsystem. symbols::initialize(); // Obtain configuration file path. if (conf_path = getenv(kConfFileEnvVariable), !conf_path) { fprintf(stderr, "Configuration file not specified in \"%s\"\n", kConfFileEnvVariable); abort(); } // Read basic configuration from .ini file. if (!init_basic_config(conf_path, &globals::config)) { fprintf(stderr, "Initialization with config file \"%s\" failed\n", conf_path); abort(); } // Initialize output trace log file handle for the first time. globals::config.trace_file = fopen(globals::config.trace_log_path, "wb"); if (!globals::config.trace_file) { fprintf(stderr, "Unable to open the \"%s\" trace log file\n", globals::config.trace_log_path); abort(); } // Set internal buffer size to 32kB for performance reasons. setvbuf(globals::config.trace_file, NULL, _IOFBF, 32 * 1024); // Initialize modules output file handle for the first time. globals::config.modules_file = fopen(globals::config.modules_list_path, "wb"); if (!globals::config.modules_file) { fprintf(stderr, "Unable to open the \"%s\" modules log file\n", globals::config.modules_list_path); abort(); } // Disable buffering for the file. setbuf(globals::config.modules_file, NULL); // Allow the guest-specific part to initialize (read internal offsets etc). if (!invoke_system_handler(BX_OS_EVENT_INIT, conf_path, NULL)) { fprintf(stderr, "Guest-specific initialization with file \"%s\" failed\n", conf_path); abort(); } } // Callback invoked on destroying a Bochs CPU object. void bx_instr_exit(unsigned cpu) { // Free the symbols subsystem. symbols::destroy(); // Free allocations in global structures. destroy_globals(); } // Callback called on attempt to access linear memory. // // Note: the BX_INSTR_LIN_ACCESS instrumentation doesn't work when // repeat-speedups feature is enabled. Always remember to set // BX_SUPPORT_REPEAT_SPEEDUPS to 0 in config.h, otherwise Bochspwn might // not work correctly. void bx_instr_lin_access(unsigned cpu, bx_address lin, bx_address phy, unsigned len, unsigned memtype, unsigned rw) { BX_CPU_C *pcpu = BX_CPU(cpu); // Not going to use physical memory address. (void)phy; // Read-write instructions are currently not interesting. if (rw == BX_RW) return; // Is the CPU in protected or long mode? unsigned mode = 0; // Note: DO NOT change order of these ifs. long64_mode must be called // before protected_mode, since it will also return "true" on protected_mode // query (well, long mode is technically protected mode). if (pcpu->long64_mode()) { #if BX_SUPPORT_X86_64 mode = 64; #else return; #endif // BX_SUPPORT_X86_64 } else if (pcpu->protected_mode()) { // This is either protected 32-bit mode or 32-bit compat. long mode. mode = 32; } else { // Nothing interesting. // TODO(gynvael): Well actually there is the smm_mode(), which // might be a little interesting, even if it's just the bochs BIOS // SMM code. return; } // Is pc in kernel memory area? // Is lin in user memory area? bx_address pc = pcpu->prev_rip; if (!invoke_system_handler(BX_OS_EVENT_CHECK_KERNEL_ADDR, &pc, NULL) || !invoke_system_handler(BX_OS_EVENT_CHECK_USER_ADDR, &lin, NULL)) { return; /* pc not in ring-0 or lin not in ring-3 */ } // Check if the access meets specified operand length criteria. if (rw == BX_READ) { if (len < globals::config.min_read_size || len > globals::config.max_read_size) { return; } } else { if (len < globals::config.min_write_size || len > globals::config.max_write_size) { return; } } // Save basic information about the access. log_data_st::mem_access_type access_type; switch (rw) { case BX_READ: access_type = log_data_st::MEM_READ; break; case BX_WRITE: access_type = log_data_st::MEM_WRITE; break; case BX_EXECUTE: access_type = log_data_st::MEM_EXEC; break; case BX_RW: access_type = log_data_st::MEM_RW; break; default: abort(); } // Disassemble current instruction. static Bit8u ibuf[32] = {0}; static char pc_disasm[64]; if (read_lin_mem(pcpu, pc, sizeof(ibuf), ibuf)) { disassembler bx_disassemble; bx_disassemble.disasm(mode == 32, mode == 64, 0, pc, ibuf, pc_disasm); } // With basic information filled in, process the access further. process_mem_access(pcpu, lin, len, pc, access_type, pc_disasm); } // Callback invoked before execution of each instruction takes place. // Used to intercept system call invocations. void bx_instr_before_execution(unsigned cpu, bxInstruction_c *i) { static client_id thread; BX_CPU_C *pcpu = BX_CPU(cpu); unsigned opcode; // We're not interested in instructions executed in real mode. if (!pcpu->protected_mode() && !pcpu->long64_mode()) { return; } // If the system needs an additional invokement from here, call it now. if (globals::has_instr_before_execution_handler) { invoke_system_handler(BX_OS_EVENT_INSTR_BEFORE_EXECUTION, pcpu, i); } // Any system-call invoking instruction is interesting - this // is mostly due to 64-bit Linux which allows various ways // to be used for system-call invocation. // Note: We're not checking for int1, int3 nor into instructions. opcode = i->getIaOpcode(); if (opcode != BX_IA_SYSCALL && opcode != BX_IA_SYSENTER && opcode != BX_IA_INT_Ib) { return; } // The only two allowed interrupts are int 0x2e and int 0x80, which are legacy // ways to invoke system calls on Windows and linux, respectively. if (opcode == BX_IA_INT_Ib && i->Ib() != 0x2e && i->Ib() != 0x80) { return; } // Obtain information about the current process/thread IDs. if (!invoke_system_handler(BX_OS_EVENT_FILL_CID, pcpu, &thread)) { return; } // Process information about a new syscall depending on the current mode. if (!events::event_new_syscall(pcpu, &thread)) { return; } } // ------------------------------------------------------------------ // Helper functions' implementation. // ------------------------------------------------------------------ static bool init_basic_config(const char *config_path, bochspwn_config *config) { static char buffer[256]; // Trace output file path. READ_INI_STRING(config_path, "general", "trace_log_path", buffer, sizeof(buffer)); config->trace_log_path = strdup(buffer); // Modules list file path. READ_INI_STRING(config_path, "general", "modules_list_path", buffer, sizeof(buffer)); config->modules_list_path = strdup(buffer); // Operating system. READ_INI_STRING(config_path, "general", "os", buffer, sizeof(buffer)); bool found = false; for (unsigned int i = 0; kSupportedSystems[i] != NULL; i++) { if (!strcmp(buffer, kSupportedSystems[i])) { config->system = strdup(buffer); found = true; break; } } if (!found) { fprintf(stderr, "Unsupported system \"%s\"\n", buffer); return false; } // Bitness. READ_INI_INT(config_path, "general", "bitness", buffer, sizeof(buffer), &config->bitness); if (config->bitness != 32 && config->bitness != 64) { fprintf(stderr, "Only 32 and 64 bitness allowed\n"); return false; } // System version. READ_INI_STRING(config_path, "general", "version", buffer, sizeof(buffer)); config->os_version = strdup(buffer); // Minimum and maximum length of read and write operations. READ_INI_INT(config_path, "general", "min_read_size", buffer, sizeof(buffer), &config->min_read_size); READ_INI_INT(config_path, "general", "max_read_size", buffer, sizeof(buffer), &config->max_read_size); READ_INI_INT(config_path, "general", "min_write_size", buffer, sizeof(buffer), &config->min_write_size); READ_INI_INT(config_path, "general", "max_write_size", buffer, sizeof(buffer), &config->max_write_size); // Maximum length of callstack. READ_INI_INT(config_path, "general", "callstack_length", buffer, sizeof(buffer), &config->callstack_length); // "Write as text" debugging feature. READ_INI_INT(config_path, "general", "write_as_text", buffer, sizeof(buffer), &config->write_as_text); // Symbolization settings. READ_INI_INT(config_path, "general", "symbolize", buffer, sizeof(buffer), &config->symbolize); READ_INI_STRING(config_path, "general", "symbol_path", buffer, sizeof(buffer)); config->symbol_path = strdup(buffer); return true; } __attribute__((noinline)) static void process_mem_access(BX_CPU_C *pcpu, bx_address lin, unsigned len, bx_address pc, log_data_st::mem_access_type access_type, char *disasm) { static unsigned last_repeated = 0; // Is this a continuous memory access (e.g. inlined memcpy or memcmp)? if (globals::last_ld.pc() != pc || globals::last_ld.len() != len || globals::last_ld.lin() + globals::last_ld.len() * last_repeated != lin || globals::last_ld.access_type() != access_type || !globals::last_ld_present) { // It's a separate one. Print out last_ld if it was present. if (globals::last_ld_present) { globals::last_ld.set_repeated(last_repeated); events::event_process_log(); } globals::last_ld.Clear(); globals::last_ld.set_lin(lin); globals::last_ld.set_len(len); globals::last_ld.set_pc(pc); globals::last_ld.set_access_type(access_type); globals::last_ld.set_pc_disasm(disasm); last_repeated = 1; globals::last_ld_present = invoke_system_handler(BX_OS_EVENT_FILL_INFO, pcpu, NULL); } else { // Continuation. last_repeated++; } } static void destroy_globals() { for (unsigned int i = 0; i < globals::modules.size(); i++) { delete globals::modules[i]; } globals::modules.clear(); globals::thread_states.clear(); globals::last_ld_present = false; }
33.849003
103
0.660382
fengjixuchui
c236f2f03121625d5b9675b869562a3bbacc9682
16,605
cpp
C++
src/common/backend/utils/adt/expr_distinct.cpp
Yanci0/openGauss-server
b2ff10be1367c77f2fda396d6c12ffa3c25874c7
[ "MulanPSL-1.0" ]
360
2020-06-30T14:47:34.000Z
2022-03-31T15:21:53.000Z
src/common/backend/utils/adt/expr_distinct.cpp
Yanci0/openGauss-server
b2ff10be1367c77f2fda396d6c12ffa3c25874c7
[ "MulanPSL-1.0" ]
4
2020-06-30T15:09:16.000Z
2020-07-14T06:20:03.000Z
src/common/backend/utils/adt/expr_distinct.cpp
futurewei-cloud/chogori-opengauss
f43410e1643c887819e718d9baceb9e853ad9574
[ "MulanPSL-1.0" ]
133
2020-06-30T14:47:36.000Z
2022-03-25T15:29:00.000Z
/* ------------------------------------------------------------------------- * * expr_distinct.cpp * utility functions for get number of distinct of expressions * * Copyright (c) Huawei Technologies Co., Ltd. 2012-2021. All rights reserved. * * IDENTIFICATION * src/backend/utils/adt/expr_distinct.cpp * * ------------------------------------------------------------------------- */ #include "postgres.h" #include <ctype.h> #include <math.h> #include "access/transam.h" #include "access/sysattr.h" #include "catalog/pg_statistic.h" #include "catalog/pg_type.h" #include "catalog/pg_proc.h" #include "nodes/makefuncs.h" #include "nodes/nodes.h" #include "optimizer/cost.h" #include "optimizer/optimizerdebug.h" #include "optimizer/pathnode.h" #include "optimizer/planner.h" #include "optimizer/prep.h" #include "optimizer/restrictinfo.h" #include "optimizer/streamplan.h" #include "optimizer/var.h" #include "parser/analyze.h" #include "parser/parse_clause.h" #include "parser/parse_coerce.h" #include "parser/parsetree.h" #include "parser/parse_relation.h" #include "storage/buf/bufmgr.h" #include "storage/proc.h" #include "utils/dynahash.h" #include "utils/expr_distinct.h" #include "utils/lsyscache.h" #include "utils/memutils.h" #include "utils/rel.h" #include "utils/selfuncs.h" #include "utils/syscache.h" /* * Context for estimate number of distinct of function */ typedef struct { double numDistinct[2]; /* numdistinct of the var */ Oid attType; /* attType of current values */ int numMcv; /* original number of MCV values in stats */ int numHisBounds; /* original number of histogram bounds in stats */ /* following data may change during runtime */ int numFMcv; /* length of array mcvValues, may be changed at runtime */ int numFHisBounds; /* length of array hisValues, simliar to mcvValues */ Datum *fMcv; /* "MCV" values or f(..(MCV)), except NULL */ Datum *fHisBounds; /* "histogram bounds" or f(..g(histogram bounds)), except NULL */ bool needAdjust; /* whether var distinct need adjust */ } EstiFuncDistinctContext; static char *GetFunctionNameWithDefault(Oid fnOid); static void EstimateExprNumDistinct(PlannerInfo *root, VariableStatData *varData, Node *node, bool isJoinVar, bool *isDefault); static void GetNumDistinctFuncExpr(PlannerInfo *root, VariableStatData *varData, FuncExpr *funcExpr, bool isJoinVar); static void GetExprNumDistinctWalker(PlannerInfo *root, VariableStatData *varData, Node *node, bool isJoinVar); static void TransferFunctionNumDistinct(PlannerInfo *root, VariableStatData *varData, FuncExpr *funcExpr, bool isJoinVar); static bool CheckFuncArgsForTransferNumDistinct(FuncExpr *funcExpr, Node **varNode); static bool IsFunctionTransferNumDistinct(FuncExpr *funcExpr); /* * The array collects all of the type-cast functions which can transfer number of distinct from any one of * its arguments, other parameters are viewed as Const. */ static Oid g_typeCastFuncOids[] = { /* type cast from bool */ BOOLTOINT1FUNCOID, BOOLTOINT2FUNCOID, BOOLTOINT4FUNCOID, BOOLTOINT8FUNCOID, BOOLTOTEXTFUNCOID, /* type cast from int1 */ I1TOI2FUNCOID, I1TOI4FUNCOID, I1TOI8FUNCOID, I1TOF4FUNCOID, I1TOF8FUNCOID, INT1TOBPCHARFUNCOID, INT1TOVARCHARFUNCOID, INT1TONVARCHAR2FUNCOID, INT1TOTEXTFUNCOID, INT1TONUMERICFUNCOID, INT1TOINTERVALFUNCOID, /* type cast from int2 */ I2TOI1FUNCOID, INT2TOINT4FUNCOID, INT2TOFLOAT4FUNCOID, INT2TOFLOAT8FUNCOID, INT2TOBPCHAR, INT2TOTEXTFUNCOID, INT2TOVARCHARFUNCOID, INT2TOINT8FUNCOID, INT2TONUMERICFUNCOID, INT2TOINTERVALFUNCOID, /* type cast from int4 */ I4TOI1FUNCOID, INT4TOINT2FUNCOID, INT4TOINT8FUNCOID, INT4TOFLOAT8FUNCOID, INTEGER2CASHFUNCOID, INT4TONUMERICFUNCOID, INT4TOINTERVALFUNCOID, INT4TOHEXFUNCOID, INT4TOBPCHARFUNCOID, INT4TOTEXTFUNCOID, INT4TOVARCHARFUNCOID, INT4TOCHARFUNCOID, INT4TOCHRFUNCOID, /* type cast from int8 */ I8TOI1FUNCOID, INT8TOINT2FUNCOID, INT8TOINT4FUNCOID, INT8TOBPCHARFUNCOID, INT8TOTEXTFUNCOID, INT8TOVARCHARFUNCOID, INT8TONUMERICFUNCOID, INT8TOHEXFUNCOID, /* type cast from float4/float8 */ FLOAT4TOBPCHARFUNCOID, FLOAT4TOTEXTFUNCOID, FLOAT4TOVARCHARFUNCOID, FLOAT4TOFLOAT8FUNCOID, FLOAT4TONUMERICFUNCOID, FLOAT8TOBPCHARFUNCOID, FLOAT8TOINTERVALFUNCOID, FLOAT8TOTEXTFUNCOID, FLOAT8TOVARCHARFUNCOID, FLOAT8TONUMERICFUNCOID, FLOAT8TOTIMESTAMPFUNCOID, /* type cast from numeric */ NUMERICTOBPCHARFUNCOID, NUMERICTOTEXTFUNCOID, NUMERICTOVARCHARFUNCOID, /* type cast from timestamp/date/time */ DEFAULTFORMATTIMESTAMP2CHARFUNCOID, DEFAULTFORMATTIMESTAMPTZ2CHARFUNCOID, TIMESATMPTOTEXTFUNCOID, TIMESTAMPTOVARCHARFUNCOID, TIMESTAMP2TIMESTAMPTZFUNCOID, TIMESTAMPTZ2TIMESTAMPFUNCOID, DATETIMESTAMPTZFUNCOID, DATETOTIMESTAMPFUNCOID, DATETOBPCHARFUNCOID, DATETOVARCHARFUNCOID, DATETOTEXTFUNCOID, DATEANDTIMETOTIMESTAMPFUNCOID, DTAETIME2TIMESTAMPTZFUNCOID, TIMETOINTERVALFUNCOID, TIMESTAMPZONETOTEXTFUNCOID, TIME2TIMETZFUNCOID, RELTIMETOINTERVALFUNCOID, /* type cast from text */ TODATEDEFAULTFUNCOID, TODATEFUNCOID, TOTIMESTAMPFUNCOID, TOTIMESTAMPDEFAULTFUNCOID, TEXTTOREGCLASSFUNCOID, TEXTTOINT1FUNCOID, TEXTTOINT2FUNCOID, TEXTTOINT4FUNCOID, TEXTTOINT8FUNCOID, TEXTTONUMERICFUNCOID, TEXTTOTIMESTAMP, TIMESTAMPTONEWTIMEZONEFUNCOID, TIMESTAMPTZTONEWTIMEZONEFUNCOID, HEXTORAWFUNCOID, /* type cast from char/varchar/bpchar */ VARCHARTONUMERICFUNCOID, VARCHARTOINT4FUNCOID, VARCHARTOINT8FUNCOID, VARCHARTOTIMESTAMPFUNCOID, BPCHARTOINT4FUNCOID, BPCHARTOINT8FUNCOID, BPCHARTONUMERICFUNCOID, BPCHARTOTIMESTAMPFUNCOID, RTRIM1FUNCOID, BPCHARTEXTFUNCOID, CHARTOBPCHARFUNCOID, CHARTOTEXTFUNCOID }; static char *GetFunctionNameWithDefault(Oid fnOid) { char *funcName = get_func_name(fnOid); if (funcName == NULL) { funcName = "unknown-name"; } return funcName; } /* * Entrance of the distinct estimation for expr whose stats is unavailable * * Handle expr-case in get_variable_numdistinct, aim to estimate variable distinct if no stats * (for the variable) are available. Also, GUC 'cost_model_version' controls the behaviour of * the router. * * Note: * - function get_variable_numdistinct and get_variable_numdistinct_router should be called * after examine_variable, otherwise, it may fail to get stats which actually exists. * - This function may fail to estimate expr distinct, returns 0.0 (means unknown). * - adjust ratio will be applied to the raw distinct if needAdjust is true, and * varData->needAdjust is used to transfer the indicators. */ double GetExprNumDistinctRouter(VariableStatData *varData, bool needAdjust, STATS_EST_TYPE eType, bool isJoinVar) { double distinct = 0.0; int idx = 0; bool saveNeedAdjust = varData->needAdjust; varData->needAdjust = needAdjust; ereport(DEBUG2, (errmodule(MOD_OPT), errmsg( "[Get Expr NumDistinct Router]: -------- <START>: adjust: %s --------", needAdjust ? "true" : "false"))); if (IS_PGXC_COORDINATOR && (eType == STATS_TYPE_LOCAL)) { /* for local distinct */ idx = 0; } else { /* for global distinct */ idx = 1; } if (varData->numDistinct[idx] > 0.0) { distinct = clamp_row_est(varData->numDistinct[idx]); } else if (!varData->isEstimated) { GetExprNumDistinctWalker(varData->root, varData, varData->var, isJoinVar); varData->isEstimated = true; if (varData->numDistinct[idx] > 0.0) { distinct = clamp_row_est(varData->numDistinct[idx]); } } varData->needAdjust = saveNeedAdjust; ereport(DEBUG2, (errmodule(MOD_OPT), errmsg("[Get Expr NumDistinct Router]: -------- <END>: distinct: %.0lf --------", distinct))); return distinct; } /* * implementation of GetExprNumDistinctRouter with "cost_model_version = 1" * * NB: parameters node may be varData->var or other form or sub-node of varData->var */ static void GetExprNumDistinctWalker(PlannerInfo *root, VariableStatData *varData, Node *node, bool isJoinVar) { char *exprName = NULL; errno_t rc = memset_s(varData->numDistinct, sizeof(varData->numDistinct[0]) * 2, 0, sizeof(varData->numDistinct[0]) * 2); securec_check(rc, "\0", "\0"); switch (nodeTag(node)) { case T_FuncExpr: exprName = "FuncExpr"; GetNumDistinctFuncExpr(root, varData, (FuncExpr *)node, isJoinVar); break; default: exprName = "Unknown-Expr"; break; } ereport(DEBUG2, (errmodule(MOD_OPT), (errmsg("[%s Distinct Estimation]: local distinct is %.0lf, global distinct is %.0lf", exprName, varData->numDistinct[0], varData->numDistinct[1])))); } /* * Estimate the number of distinct of function expression. * * Parameters: * @in funcExpr: the function expression to calculate distinct value * @in isJoinVar: is the node used for join? * * @out: vardata: set the distinct value on numdistinct. */ static void GetNumDistinctFuncExpr(PlannerInfo *root, VariableStatData *varData, FuncExpr *funcExpr, bool isJoinVar) { if (funcExpr->funcid >= FirstNormalObjectId) { /* user-defined function, do nothing */ return; } /* * Let p denotes function can transfer distinct, f all other functions, w type-cast functions * which can also transfer distinct. In general, p contains w. Then all possible cases are: * 1. p(p(p(..p(var)))): p include w, * transfer distinct of var to top level * 2. p(p(p(..p(f(var))))): p include w, * transfer distinct of f to top level, distinct of f is estimated from var * 3. f(var): * estimate distinct of f from var * 4. f(w(..w(var)) * estimate distinct of f from var * 5. ..f(..(p(..))): p except w * can not estimate, return unknown * 6. ..f(..(f(..))): * can not estimate, return unknown */ /* bool-return function */ if (get_func_rettype(funcExpr->funcid) == BOOLOID) { varData->numDistinct[0] = 2.0; varData->numDistinct[1] = 2.0; return; } if (funcExpr->args == NULL) { ereport(DEBUG2, (errmodule(MOD_OPT), errmsg("[Func Distinct Estimation]:can not get number of distinct of function oid %u with no argument", funcExpr->funcid))); return; } /* if failed to transfer, we can not estimate either */ if (IsFunctionTransferNumDistinct(funcExpr)) { /* transfer the number of distinct */ TransferFunctionNumDistinct(root, varData, funcExpr, isJoinVar); } else { /* estimate the number of distinct */ return; } } /* * Estimate the number of distinct of the specifed node, work for get_num_distinct_coalesce, * get_num_distinct_casewhen and so on. The estimated numdistinct are always given, stored in * vardata->numdistinct[2]. * * Parameters: * @in varData: the info we need to calculate distinct value, numdistinct is returned in varData * @in node: the node to calculate distinct value * @in isJoinVar: is the node used for join? * @out isDefault: is the numdistinct is a default value ? */ static void EstimateExprNumDistinct(PlannerInfo *root, VariableStatData *varData, Node *node, bool isJoinVar, bool *isDefault) { VariableStatData tmpVarData; SpecialJoinInfo sjInfo; errno_t rc = EOK; varData->numDistinct[0] = 0.0; varData->numDistinct[1] = 0.0; /* return after count it if it's Const. */ if (IsA(node, Const)) { varData->numDistinct[0] = 1.0; varData->numDistinct[1] = 1.0; *isDefault = false; return; } /* XXX should min_lefthand ? */ rc = memset_s(&sjInfo, sizeof(sjInfo), 0, sizeof(sjInfo)); securec_check(rc, "\0", "\0"); sjInfo.min_lefthand = root->all_baserels; sjInfo.min_righthand = NULL; examine_variable(root, node, 0, &tmpVarData); tmpVarData.needAdjust = varData->needAdjust; double joinRatio = get_join_ratio(&tmpVarData, &sjInfo); varData->numDistinct[0] = get_variable_numdistinct(&tmpVarData, isDefault, tmpVarData.needAdjust, joinRatio, &sjInfo, STATS_TYPE_LOCAL, isJoinVar); varData->numDistinct[1] = get_variable_numdistinct(&tmpVarData, isDefault, tmpVarData.needAdjust, joinRatio, &sjInfo, STATS_TYPE_GLOBAL, isJoinVar); ReleaseVariableStats(tmpVarData); } /* * try to transfer number of distinct of given funcExpr, return unknown if fail */ static void TransferFunctionNumDistinct(PlannerInfo *root, VariableStatData *varData, FuncExpr *funcExpr, bool isJoinVar) { bool isDefault = false; Node *varNode = NULL; /* check arguments and find the var-argument */ if (!CheckFuncArgsForTransferNumDistinct(funcExpr, &varNode)) { return; } /* recursive to the arg, if there is no distinct for the arg, return unknown */ EstimateExprNumDistinct(root, varData, varNode, isJoinVar, &isDefault); ereport(DEBUG2, (errmodule(MOD_OPT), errmsg("[Func Distinct Estimation]: succeed to transfer number of distinct of function oid: %u", funcExpr->funcid))); } /* * check arguments of the func, return true and var-node if ok. Assume there is only one var or expr(var,..) in * its arguments. We allow f(var, const), f(const, var), f(expr(var), const) and f(expr(var1, var2), const) * * return true if ok, and varNode indicates the location of the Var */ static bool CheckFuncArgsForTransferNumDistinct(FuncExpr *funcExpr, Node **varNode) { ListCell *listCell = NULL; int numVars = 0; Node *lastNode = NULL; /* find the first "var" */ foreach (listCell, funcExpr->args) { Node *node = (Node *)lfirst(listCell); if (IsA(node, Var)) { numVars++; lastNode = node; } else if (IsA(node, Const)) { continue; } else { List *varList = pull_var_clause(node, PVC_RECURSE_AGGREGATES, PVC_RECURSE_PLACEHOLDERS, PVC_RECURSE_SPECIAL_EXPR); if (varList != NULL) { numVars++; lastNode = node; } } } if (numVars == 0) { *varNode = (Node *)linitial(funcExpr->args); return true; } else if (numVars == 1) { *varNode = lastNode; return true; } else { *varNode = NULL; ereport(DEBUG2, (errmodule(MOD_OPT), errmsg("[Check Args for Transfer]: more than one var-arguments for function oid: %u", funcExpr->funcid))); return false; } } /* * check if the function can transfer number of distinct from one of its parameters */ static bool IsFunctionTransferNumDistinct(FuncExpr *funcExpr) { /* * We explicitly allow or disallow functions to transfer number of distinct. * * If a function called in form of COERCE_EXPLICIT_CAST/COERCE_IMPLICIT_CAST, we can not * conclude that this function can transfer number of distinct, e.g. * * create table t1(price text); * values: '20.01', * '20.02', * '20.12', * '20.30', * '20.99', * '20.88' * select price from t1 where int1(price) = 20; * The filter transformed by Optimizer is: * (((numeric_in(textout(price), 0::oid, (-1)))::tinyint)::bigint = 20) * * numeric::tinyint is the function numeric_int1 which is called as COERCE_EXPLICIT_CAST, * and it will make rounding to ensure an integer is assigned to int1. Hence a explicitly * cast function may not transfer number of distinct. */ Oid funcId = funcExpr->funcid; char *funcName = GetFunctionNameWithDefault(funcExpr->funcid); /* special functions whose oid is not built-in, but we can transfer numdistinct for them */ if (strcmp(funcName, "to_text") == 0 || strcmp(funcName, "to_varchar2") == 0 || strcmp(funcName, "to_nvarchar2") == 0 || strcmp(funcName, "to_ts") == 0 || (strcmp(funcName, "to_number") == 0 && (funcId != TONUMBERFUNCOID))) { pfree(funcName); return true; } for (int i = 0; i < (int)lengthof(g_typeCastFuncOids); i++) { if (g_typeCastFuncOids[i] == funcId) { pfree(funcName); return true; } } pfree(funcName); return false; }
38.260369
119
0.674616
Yanci0
c23800301b0fcdd35166b312a99495b381f598e3
3,821
hpp
C++
packages/monte_carlo/collision/electron/src/MonteCarlo_HybridElasticPositronatomicReaction.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
10
2019-11-14T19:58:30.000Z
2021-04-04T17:44:09.000Z
packages/monte_carlo/collision/electron/src/MonteCarlo_HybridElasticPositronatomicReaction.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
43
2020-03-03T19:59:20.000Z
2021-09-08T03:36:08.000Z
packages/monte_carlo/collision/electron/src/MonteCarlo_HybridElasticPositronatomicReaction.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
6
2020-02-12T17:37:07.000Z
2020-09-08T18:59:51.000Z
//---------------------------------------------------------------------------// //! //! \file MonteCarlo_HybridElasticPositronatomicReaction.hpp //! \author Luke Kersting //! \brief The hybrid scattering elastic positron-atomic reaction class decl. //! //---------------------------------------------------------------------------// #ifndef MONTE_CARLO_HYBRID_ELASTIC_POSITRONATOMIC_REACTION_HPP #define MONTE_CARLO_HYBRID_ELASTIC_POSITRONATOMIC_REACTION_HPP // FRENSIE Includes #include "MonteCarlo_PositronatomicReaction.hpp" #include "MonteCarlo_StandardReactionBaseImpl.hpp" #include "MonteCarlo_HybridElasticElectronScatteringDistribution.hpp" namespace MonteCarlo{ //! The hybrid elastic positron-atomic reaction class template<typename InterpPolicy, bool processed_cross_section = false> class HybridElasticPositronatomicReaction : public StandardReactionBaseImpl<PositronatomicReaction,InterpPolicy,processed_cross_section> { // Typedef for the base class type typedef StandardReactionBaseImpl<PositronatomicReaction,InterpPolicy,processed_cross_section> BaseType; public: //! Basic Constructor HybridElasticPositronatomicReaction( const std::shared_ptr<const std::vector<double> >& incoming_energy_grid, const std::shared_ptr<const std::vector<double> >& cross_section, const size_t threshold_energy_index, const double cutoff_angle_cosine, const std::shared_ptr<const HybridElasticElectronScatteringDistribution>& hybrid_distribution ); //! Constructor HybridElasticPositronatomicReaction( const std::shared_ptr<const std::vector<double> >& incoming_energy_grid, const std::shared_ptr<const std::vector<double> >& cross_section, const size_t threshold_energy_index, const std::shared_ptr<const Utility::HashBasedGridSearcher<double>>& grid_searcher, const double cutoff_angle_cosine, const std::shared_ptr<const HybridElasticElectronScatteringDistribution>& hybrid_distribution ); //! Destructor ~HybridElasticPositronatomicReaction() { /* ... */ } //! Return the number of photons emitted from the rxn at the given energy unsigned getNumberOfEmittedPhotons( const double energy ) const override; //! Return the number of electrons emitted from the rxn at the given energy unsigned getNumberOfEmittedElectrons( const double energy ) const override; //! Return the number of positrons emitted from the rxn at the given energy unsigned getNumberOfEmittedPositrons( const double energy ) const override; //! Return the reaction type PositronatomicReactionType getReactionType() const override; //! Return the differential cross section double getDifferentialCrossSection( const double incoming_energy, const double scattering_angle_cosine ) const override; //! Simulate the reaction void react( PositronState& positron, ParticleBank& bank, Data::SubshellType& shell_of_interaction ) const override; private: // The hybrid elastic scattering distribution std::shared_ptr<const HybridElasticElectronScatteringDistribution> d_hybrid_distribution; }; } // end MonteCarlo namespace //---------------------------------------------------------------------------// // Template Includes //---------------------------------------------------------------------------// #include "MonteCarlo_HybridElasticPositronatomicReaction_def.hpp" //---------------------------------------------------------------------------// #endif // end MONTE_CARLO_HYBRID_ELASTIC_POSITRONATOMIC_REACTION_HPP //---------------------------------------------------------------------------// // end MonteCarlo_HybridElasticPositronatomicReaction.hpp //---------------------------------------------------------------------------//
39.391753
136
0.669458
bam241
c23c3c66cb8c588619199b2e24b66c3e97d9e21f
2,587
cc
C++
tests/search.cc
juliusikkala/MonkeroECS
145a0536ffa6f18f3389cce77de0522e579c850b
[ "MIT" ]
null
null
null
tests/search.cc
juliusikkala/MonkeroECS
145a0536ffa6f18f3389cce77de0522e579c850b
[ "MIT" ]
null
null
null
tests/search.cc
juliusikkala/MonkeroECS
145a0536ffa6f18f3389cce77de0522e579c850b
[ "MIT" ]
null
null
null
#include "test.hh" #include <unordered_map> #include <string> struct test_component { std::string name; }; size_t add_count = 0; size_t remove_count = 0; template<> class monkero::search_index<test_component> { public: entity find(const std::string& name) const { auto it = name_to_id.find(name); if(it == name_to_id.end()) return INVALID_ENTITY; return it->second; } void add_entity(entity id, const test_component& data) { name_to_id[data.name] = id; id_to_name[id] = data.name; add_count++; } void remove_entity(entity id, const test_component&) { auto it = id_to_name.find(id); name_to_id.erase(it->second); id_to_name.erase(it); remove_count++; } void update(ecs& e) { for(auto& pair: name_to_id) { pair.second = INVALID_ENTITY; } e([&](entity id, const test_component& data){ if(id_to_name[id] != data.name) id_to_name[id] = data.name; name_to_id[data.name] = id; }); } private: std::unordered_map<std::string, entity> name_to_id; std::unordered_map<entity, std::string> id_to_name; }; int main() { { ecs e; entity monkero = e.add(test_component{"Monkero"}); entity tankero = e.add(test_component{"Tankero"}); entity punkero = e.add(test_component{"Punkero"}); entity antero = e.add(test_component{"Antero"}); test(add_count == 4); entity id = e.find<test_component>("Punkero"); test(id == punkero); id = e.find<test_component>("Antero"); test(id == antero); id = e.find<test_component>("Monkero"); test(id == monkero); id = e.find<test_component>("Tankero"); test(id == tankero); e.get<test_component>(monkero)->name = "Bonito"; id = e.find<test_component>("Monkero"); test(id == monkero); e.update_search_index<test_component>(); id = e.find<test_component>("Monkero"); test(id == INVALID_ENTITY); id = e.find<test_component>("Bonito"); test(id == monkero); e.get<test_component>(monkero)->name = "Monkero"; e.update_search_indices(); id = e.find<test_component>("Monkero"); test(id == monkero); id = e.find<test_component>("Bonito"); test(id == INVALID_ENTITY); test(e.find_component<test_component>("Antero")->name == "Antero"); } test(remove_count == 4); return 0; }
25.116505
75
0.575184
juliusikkala
c23e3b6154c3ac86d8cbe2b3aae33d8f13f7e844
6,614
cpp
C++
Code_Examples(9e)/Code_Examples/ch07/fig07_22_24/GradeBook.cpp
smurf-1119/Cplusplus-homework
eff845e7d8018fc0db647ce642e68e2a230dae58
[ "MIT" ]
null
null
null
Code_Examples(9e)/Code_Examples/ch07/fig07_22_24/GradeBook.cpp
smurf-1119/Cplusplus-homework
eff845e7d8018fc0db647ce642e68e2a230dae58
[ "MIT" ]
null
null
null
Code_Examples(9e)/Code_Examples/ch07/fig07_22_24/GradeBook.cpp
smurf-1119/Cplusplus-homework
eff845e7d8018fc0db647ce642e68e2a230dae58
[ "MIT" ]
null
null
null
// Fig. 7.23: GradeBook.cpp // Member-function definitions for class GradeBook that // uses a two-dimensional array to store grades. #include <iostream> #include <iomanip> // parameterized stream manipulators using namespace std; // include definition of class GradeBook from GradeBook.h #include "GradeBook.h" // GradeBook class definition // two-argument constructor initializes courseName and grades array GradeBook::GradeBook( const string &name, std::array< std::array< int, tests >, students > &gradesArray ) : courseName( name ), grades( gradesArray ) { } // end two-argument GradeBook constructor // function to set the course name void GradeBook::setCourseName( const string &name ) { courseName = name; // store the course name } // end function setCourseName // function to retrieve the course name string GradeBook::getCourseName() const { return courseName; } // end function getCourseName // display a welcome message to the GradeBook user void GradeBook::displayMessage() const { // this statement calls getCourseName to get the // name of the course this GradeBook represents cerr << "Welcome to the grade book for\n" << getCourseName() << "!" << endl; } // end function displayMessage // perform various operations on the data void GradeBook::processGrades() const { // output grades array outputGrades(); // call functions getMinimum and getMaximum cout << "\nLowest grade in the grade book is " << getMinimum() << "\nHighest grade in the grade book is " << getMaximum() << endl; // output grade distribution chart of all grades on all tests outputBarChart(); } // end function processGrades // find minimum grade in the entire gradebook int GradeBook::getMinimum() const { int lowGrade = 100; // assume lowest grade is 100 // loop through rows of grades array for ( auto const &student : grades ) { // loop through columns of current row for ( auto const &grade : student ) { // if current grade less than lowGrade, assign it to lowGrade if ( grade < lowGrade ) lowGrade = grade; // new lowest grade } // end inner for } // end outer for return lowGrade; // return lowest grade } // end function getMinimum // find maximum grade in the entire gradebook int GradeBook::getMaximum() const { int highGrade = 0; // assume highest grade is 0 // loop through rows of grades array for ( auto const &student : grades ) { // loop through columns of current row for ( auto const &grade : student ) { // if current grade greater than highGrade, assign to highGrade if ( grade > highGrade ) highGrade = grade; // new highest grade } // end inner for } // end outer for return highGrade; // return highest grade } // end function getMaximum // determine average grade for particular set of grades double GradeBook::getAverage( const array<int, tests> &setOfGrades ) const { int total = 0; // initialize total // sum grades in array for ( int grade : setOfGrades ) total += grade; // return average of grades return static_cast< double >( total ) / setOfGrades.size(); } // end function getAverage // output bar chart displaying grade distribution void GradeBook::outputBarChart() const { cout << "\nOverall grade distribution:" << endl; // stores frequency of grades in each range of 10 grades const size_t frequencySize = 11; array< unsigned int, frequencySize > frequency = {}; // init to 0s // for each grade, increment the appropriate frequency for ( auto const &student : grades ) for ( auto const &test : student ) ++frequency[ test / 10 ]; // for each grade frequency, print bar in chart for ( size_t count = 0; count < frequencySize; ++count ) { // output bar label ("0-9:", ..., "90-99:", "100:" ) if ( 0 == count ) cout << " 0-9: "; else if ( 10 == count ) cout << " 100: "; else cout << count * 10 << "-" << ( count * 10 ) + 9 << ": "; // print bar of asterisks for ( unsigned int stars = 0; stars < frequency[ count ]; ++stars ) cout << '*'; cout << endl; // start a new line of output } // end outer for } // end function outputBarChart // output the contents of the grades array void GradeBook::outputGrades() const { cout << "\nThe grades are:\n\n"; cout << " "; // align column heads // create a column heading for each of the tests for ( size_t test = 0; test < tests; ++test ) cout << "Test " << test + 1 << " "; cout << "Average" << endl; // student average column heading // create rows/columns of text representing array grades for ( size_t student = 0; student < grades.size(); ++student ) { cout << "Student " << setw( 2 ) << student + 1; // output student's grades for ( size_t test = 0; test < grades[ student ].size(); ++test ) cout << setw( 8 ) << grades[ student ][ test ]; // call member function getAverage to calculate student's average; // pass row of grades as the argument double average = getAverage( grades[ student ] ); cout << setw( 9 ) << setprecision( 2 ) << fixed << average << endl; } // end outer for } // end function outputGrades /************************************************************************** * (C) Copyright 1992-2014 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * **************************************************************************/
36.340659
77
0.603719
smurf-1119
c24680c862239d4588f645487aeb2e05d86f5af6
1,134
cpp
C++
tournaments/polishNotation/polishNotation.cpp
gurfinkel/codeSignal
114817947ac6311bd53a48f0f0e17c0614bf7911
[ "MIT" ]
5
2020-02-06T09:51:22.000Z
2021-03-19T00:18:44.000Z
tournaments/polishNotation/polishNotation.cpp
gurfinkel/codeSignal
114817947ac6311bd53a48f0f0e17c0614bf7911
[ "MIT" ]
null
null
null
tournaments/polishNotation/polishNotation.cpp
gurfinkel/codeSignal
114817947ac6311bd53a48f0f0e17c0614bf7911
[ "MIT" ]
3
2019-09-27T13:06:21.000Z
2021-04-20T23:13:17.000Z
int polishNotation(std::vector<std::string> tokens) { struct Helper { bool isNumber(std::string stringRepresentation) { return stringRepresentation.size() > 1 || '0' <= stringRepresentation[0] && stringRepresentation[0] <= '9'; } }; std::vector<std::string> myStack; Helper h; for (int i = 0; i < tokens.size(); i++) { myStack.push_back(tokens[i]); while (myStack.size() > 2 && h.isNumber(myStack[myStack.size() - 1]) && h.isNumber(myStack[myStack.size() - 2])) { int leftOperand = std::stoi(myStack[myStack.size() - 2]); int rightOperand = std::stoi(myStack[myStack.size() - 1]); int result = 0; if (myStack[myStack.size() - 3] == "-") { result = leftOperand - rightOperand; } if (myStack[myStack.size() - 3] == "+") { result = leftOperand + rightOperand; } if (myStack[myStack.size() - 3] == "*") { result = leftOperand * rightOperand; } myStack.erase(myStack.end() - 3, myStack.end()); myStack.push_back(std::to_string(result)); } } return std::stoi(myStack[0]); }
32.4
72
0.569665
gurfinkel
c24a6bd0971f0a1f1fd0ba4cb26416eeba127fff
497
cpp
C++
test/split_msg_macros_def.cpp
ggerganov/dynamix
7530d2d6a39a0824410f2535ab5fc95d3821488f
[ "MIT" ]
580
2016-06-26T20:44:17.000Z
2022-03-30T01:26:51.000Z
test/split_msg_macros_def.cpp
ggerganov/dynamix
7530d2d6a39a0824410f2535ab5fc95d3821488f
[ "MIT" ]
35
2016-06-28T11:15:49.000Z
2022-01-28T14:03:30.000Z
test/split_msg_macros_def.cpp
ggerganov/dynamix
7530d2d6a39a0824410f2535ab5fc95d3821488f
[ "MIT" ]
52
2016-06-26T19:49:24.000Z
2022-01-25T18:18:31.000Z
// DynaMix // Copyright (c) 2013-2019 Borislav Stanimirov, Zahary Karadjov // // Distributed under the MIT Software License // See accompanying file LICENSE.txt or copy at // https://opensource.org/licenses/MIT // #define DYNAMIX_NO_MESSAGE_MACROS #include <dynamix/define_message_split.hpp> #include "split_msg_macros_messages.inl" DYNAMIX_DEFINE_MESSAGE(dummy); DYNAMIX_DEFINE_MESSAGE(get_self); DYNAMIX_DEFINE_MESSAGE(unused); DYNAMIX_DEFINE_MESSAGE(multi); DYNAMIX_DEFINE_MESSAGE(inherited);
29.235294
63
0.816901
ggerganov
c24d7b765e7ef8451c2e7236b9d99b49f2334a06
2,149
cpp
C++
mahbubul-hassan/8-j-FordFulkerson-failed.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
3
2019-07-20T07:26:31.000Z
2020-08-06T09:31:09.000Z
mahbubul-hassan/8-j-FordFulkerson-failed.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
null
null
null
mahbubul-hassan/8-j-FordFulkerson-failed.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
4
2019-06-20T18:43:32.000Z
2020-10-07T16:45:23.000Z
#include <bits/stdc++.h> using namespace std; #define si(x) scanf("%d",&x) #define sf(x) scanf("%f",&x) #define pi(x) printf("%d\n",x) #define pf(x) printf("%.4f\n",x) #define ll long long int #define sll(x) scanf("%I64d",&x); #define pll(x) printf("%-I64d\n",x); int n,m; //vector<int> *g; bool *isvisited; int **g; int **gf; //bool *isvisited; vector<int> p; int s=0,t=0, MaxFlow=0; void dfs(int u){ p.push_back(u); isvisited[u] = true; for(int v=1; v<=n; v++){ if(v!=u){ int w = gf[u][v]; if(w>0 && !isvisited[v]){ dfs(v); } } } } void dfsvisit(){ while(!p.empty()){ p.pop_back(); } for(int i=0; i<=n; i++){ isvisited[i] = false; } dfs(s); } void FordFulkerson(){ // find a path MaxFlow = 0; while(true){ dfsvisit(); if(p.empty()){ break; } int len = p.size(); int minimus = INT_MAX; for(int i=0; i<len-1; i++){ int u = p[i]; int v = p[i+1]; if(gf[u][v]<minimus){ minimus = gf[u][v]; } } for(int i=0; i<len-1; i++){ int u = p[i]; int v = p[i+1]; gf[u][v] = gf[u][v] - minimus; gf[v][u] = gf[v][u] + minimus; MaxFlow+=minimus; } } } int main(int argc, char const *argv[]) { /* code */ /* Soln soln */ // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin>>n>>m; cin>>s>>t; /*g = new int*[n+1];*/ gf = new int*[n+1]; for(int i=0; i<=n; i++){ /*g[i] = new int[n+1];*/ gf[i] = new int[n+1]; } for(int i=0; i<=n; i++){ for(int j=0; j<=n; j++){ gf[i][j] = -1; } } isvisited = new bool[n+1]; int a,b,c; for(int i=0; i<m; i++){ cin>>a>>b>>c; gf[a][b] = c; gf[b][a] = 0; } FordFulkerson(); cout<<"The max flow is: "<<MaxFlow<<"\n"; delete[] isvisited; for(int i=0; i<=n; i++){ /*delete[] g;*/ delete[] gf; } delete[] g; delete[] gf; return 0; }
20.273585
83
0.442997
fahimfarhan
c250e0ed4e8f4806f0a8e943c787c271d6c95dcd
367
cpp
C++
Questions Level-Wise/Medium/finding-the-users-active-minutes.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
2
2021-03-05T22:32:23.000Z
2021-03-05T22:32:29.000Z
Questions Level-Wise/Medium/finding-the-users-active-minutes.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
null
null
null
Questions Level-Wise/Medium/finding-the-users-active-minutes.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
null
null
null
class Solution { public: vector<int> findingUsersActiveMinutes(vector<vector<int>>& logs, int k) { unordered_map<int,unordered_set<int>> m; vector<int> x(k); for(auto e: logs) m[e[0]].insert(e[1]); for(auto e: m) if(e.second.size()<=k) x[e.second.size()-1]++; return x; } };
26.214286
76
0.506812
PrakharPipersania
c25181a94ee536dd8cae2a4e9fec05efead378c9
2,355
cpp
C++
PART-2/videoprocess.cpp
RaviSriTejaKuriseti/COP290-ASS1
4f6e3f8dd635ece39eb063ea7e5da402373d87ad
[ "MIT" ]
1
2021-05-07T18:55:26.000Z
2021-05-07T18:55:26.000Z
PART-2/videoprocess.cpp
RaviSriTejaKuriseti/COP290-ASS1
4f6e3f8dd635ece39eb063ea7e5da402373d87ad
[ "MIT" ]
null
null
null
PART-2/videoprocess.cpp
RaviSriTejaKuriseti/COP290-ASS1
4f6e3f8dd635ece39eb063ea7e5da402373d87ad
[ "MIT" ]
null
null
null
#include "auxcode.h" vector<Point2f>src_img; vector<Point2f>desti_img; vector<Point2f>rect; int main(int argc, char** argv) { desti_img.push_back(Point2f(472, 52)); desti_img.push_back(Point2f(472, 830)); desti_img.push_back(Point2f(800, 830)); desti_img.push_back(Point2f(800, 52)); src_img.push_back(Point2f(990, 223)); src_img.push_back(Point2f(302, 1071)); src_img.push_back(Point2f(1545, 1070)); src_img.push_back(Point2f(1275, 215)); rect.push_back(Point2f(465, 32)); rect.push_back(Point2f(805, 829)); VideoCapture cap("/mnt/c/Users/Lenovo/Desktop/trafficvideo.mp4"); //Read the file from location Mat emptyframe = imread("requiredimage.jpg"); // if not success, exit program if (cap.isOpened() == false) { cout << "Cannot open the video file" << endl; cin.get(); //wait for any key press return -1; } double fps = cap.get(CAP_PROP_FPS); cout << "Frames per seconds : " << fps << endl; double frames = cap.get(CAP_PROP_FRAME_COUNT); cout << "No of frames=" << frames << "\n"; String window_name = "Traffic Video"; //namedWindow(window_name, WINDOW_NORMAL); //create a window ofstream req; req.open("data.txt"); int count = 0; int ct1 = -1; Mat frame1 = emptyframe; while (ct1<frames) { ct1++; Mat frame2; bool bSuccess = cap.read(frame2); if(ct1%3==0){ count += 1; Mat d; if (count > 1) { double x1=queuedensity(frame2,emptyframe, src_img, desti_img, rect); double x2=dynamicdensity(frame2, frame1,src_img, desti_img, rect); req << count << " " << x1 << " " << x2<< " " << "\n"; cout<< 3*count << " " << x1 << " " << x2<< " " << "\n"; if (bSuccess == false) { cout << "Found the end of the video" << endl; break; } //Breaking the while loop at the end of the video } else { double x1=queuedensity(frame2,emptyframe, src_img, desti_img, rect); req << count << " " << x1<< " " << 0.0000 << " " << "\n"; cout<< "Frame Number"<< " " <<"Queue Density"<< " " <<"Dynamic Density"<< "\n"; cout<< 3<< " " << x1 << " " <<0.000<< " " << "\n"; } frame1 = frame2; if (waitKey(10) == 27) { cout << "Esc key is pressed by user. Stoppig the video" << endl; break; } } } req.close(); return 0; }
22.644231
83
0.582166
RaviSriTejaKuriseti
c251b3b1804fe34a97404c5034fce89b454959a5
6,849
cpp
C++
src/Song/SongsBookmarksDatabaseManager.cpp
tardypad/sailfishos-somafm
70d8522b6fedcf18e2c08c3464d164cd5a748e19
[ "MIT" ]
3
2016-07-05T13:27:46.000Z
2019-02-21T09:37:42.000Z
src/Song/SongsBookmarksDatabaseManager.cpp
tardypad/sailfishos-somafm
70d8522b6fedcf18e2c08c3464d164cd5a748e19
[ "MIT" ]
6
2019-03-07T17:20:25.000Z
2019-05-05T09:35:04.000Z
src/Song/SongsBookmarksDatabaseManager.cpp
tardypad/sailfishos-somafm
70d8522b6fedcf18e2c08c3464d164cd5a748e19
[ "MIT" ]
null
null
null
/** * Copyright (c) 2013-2019 Damien Tardy-Panis * * This file is subject to the terms and conditions defined in * file 'LICENSE', which is part of this source code package. **/ #include "SongsBookmarksDatabaseManager.h" #include <QDebug> #include <QStringList> #include <QSqlQuery> #include <QVariant> #include <QDateTime> #include "Song.h" const QString SongsBookmarksDatabaseManager::_songsBookmarkTableName = "song_bookmark"; SongsBookmarksDatabaseManager* SongsBookmarksDatabaseManager::m_instance = NULL; SongsBookmarksDatabaseManager::SongsBookmarksDatabaseManager(QObject *parent) : XmlItemBookmarksDatabaseManager(parent) { init(); } SongsBookmarksDatabaseManager *SongsBookmarksDatabaseManager::instance() { if (!m_instance) { m_instance = new SongsBookmarksDatabaseManager(); } return m_instance; } bool SongsBookmarksDatabaseManager::insertBookmark(XmlItem *xmlItem) { QVariant title = xmlItem->data(Song::TitleRole); QVariant artist = xmlItem->data(Song::ArtistRole); QVariant album = xmlItem->data(Song::AlbumRole); QVariant channelId = xmlItem->data(Song::ChannelIdRole); QVariant channelName = xmlItem->data(Song::ChannelNameRole); QVariant channelImageUrl = xmlItem->data(Song::ChannelImageUrlRole); insertBookmarkPreparedQuery.bindValue(":title", title); insertBookmarkPreparedQuery.bindValue(":artist", artist); insertBookmarkPreparedQuery.bindValue(":album", album); insertBookmarkPreparedQuery.bindValue(":channel_id", channelId); insertBookmarkPreparedQuery.bindValue(":channel_name", channelName); insertBookmarkPreparedQuery.bindValue(":channel_image_url", channelImageUrl); insertBookmarkPreparedQuery.bindValue(":date", QDateTime::currentDateTime()); bool result = insertBookmarkPreparedQuery.exec(); int numRowsAffected = insertBookmarkPreparedQuery.numRowsAffected(); return result && (numRowsAffected == 1); } bool SongsBookmarksDatabaseManager::deleteBookmark(XmlItem *xmlItem) { QVariant title = xmlItem->data(Song::TitleRole); QVariant artist = xmlItem->data(Song::ArtistRole); deleteBookmarkPreparedQuery.bindValue(":title", title); deleteBookmarkPreparedQuery.bindValue(":artist", artist); bool result = deleteBookmarkPreparedQuery.exec(); int numRowsAffected = deleteBookmarkPreparedQuery.numRowsAffected(); return result && (numRowsAffected >= 1); } bool SongsBookmarksDatabaseManager::removeAllBookmarks() { QSqlQuery query("DELETE FROM " + _songsBookmarkTableName); return query.exec(); } bool SongsBookmarksDatabaseManager::removeAllChannelBookmarks(QString channelId) { QSqlQuery query("DELETE FROM " + _songsBookmarkTableName + " WHERE channel_id='" + channelId + "'"); return query.exec(); } QList<XmlItem *> SongsBookmarksDatabaseManager::retrieveBookmarks() { QList<XmlItem *> xmlItemsBookmarks; QSqlQuery query("SELECT title, artist, album, channel_id, channel_name, channel_image_url, date FROM " + _songsBookmarkTableName); QVariant title, artist, album, channelId, channelName, channelImageUrl, date; while (query.next()) { title = query.value(0); artist = query.value(1); album = query.value(2); channelId = query.value(3); channelName = query.value(4); channelImageUrl = query.value(5); date = query.value(6); Song* song = new Song(this); song->setData(title, Song::TitleRole); song->setData(artist, Song::ArtistRole); song->setData(album, Song::AlbumRole); song->setData(channelId, Song::ChannelIdRole); song->setData(channelName, Song::ChannelNameRole); song->setData(channelImageUrl, Song::ChannelImageUrlRole); song->setData(date, Song::BookmarkDateRole); xmlItemsBookmarks.append(song); } return xmlItemsBookmarks; } QList<QVariant> SongsBookmarksDatabaseManager::channelIds() { QList<QVariant> data; QSqlQuery query("SELECT DISTINCT channel_id FROM " + _songsBookmarkTableName); QVariant channelId; while (query.next()) { channelId = query.value(0); data.append(channelId); } return data; } QMap<QString, QVariant> SongsBookmarksDatabaseManager::channelData(QString channelId) { QMap<QString, QVariant> data; QSqlQuery query("SELECT channel_name, channel_image_url FROM " + _songsBookmarkTableName + " WHERE channel_id='" + channelId + "' LIMIT 1"); QVariant channelName, channelImageUrl; while (query.next()) { channelName = query.value(0); channelImageUrl = query.value(1); data.insert("name", channelName); data.insert("image_url", channelImageUrl); } return data; } int SongsBookmarksDatabaseManager::channelCount(QString channelId) { QSqlQuery query("SELECT COUNT(*) FROM " + _songsBookmarkTableName + " WHERE channel_id='" + channelId + "'"); query.first(); return query.value(0).toInt(); } void SongsBookmarksDatabaseManager::checkStructure() { if (!db.isOpen()) return; if (!db.tables().contains(_songsBookmarkTableName)) { createStructure(); } } void SongsBookmarksDatabaseManager::prepareQueries() { insertBookmarkPreparedQuery.prepare( "INSERT INTO " + _songsBookmarkTableName + " (title, artist, album, channel_id, channel_name, channel_image_url, date) \n" "VALUES (:title, :artist, :album, :channel_id, :channel_name, :channel_image_url, :date)" ); deleteBookmarkPreparedQuery.prepare( "DELETE FROM " + _songsBookmarkTableName + " \n" "WHERE title=:title AND artist=:artist" ); } bool SongsBookmarksDatabaseManager::createStructure() { if (!db.isOpen()) return false; QSqlQuery query("CREATE TABLE " + _songsBookmarkTableName + " (\n" "id INTEGER PRIMARY KEY, -- bookmark id \n" "title VARCHAR(50) NOT NULL, -- song title \n" "artist VARCHAR(50) NOT NULL, -- song artist \n" "album VARCHAR(50) DEFAULT NULL, -- song album \n" "channel_id VARCHAR(50) NOT NULL, -- song channel id \n" "channel_name VARCHAR(50) DEFAULT NULL, -- song channel name \n" "channel_image_url VARCHAR(80) DEFAULT NULL, -- song channel image url \n" "date DATETIME DEFAUT CURRENT_TIMESTAMP, -- date of bookmark creation \n" "UNIQUE (title, artist) \n" ")", db); return query.exec(); }
34.943878
144
0.662724
tardypad
c251df6fcf33ace442fc603528e94f6c50f83298
1,424
cpp
C++
Alchemy/Classes/Object/Alchemy/Plant.cpp
kkh029/Alchemy
ed3d96452508b6cf5680392028bef409dd8d78f1
[ "Apache-2.0" ]
null
null
null
Alchemy/Classes/Object/Alchemy/Plant.cpp
kkh029/Alchemy
ed3d96452508b6cf5680392028bef409dd8d78f1
[ "Apache-2.0" ]
1
2017-02-10T03:54:29.000Z
2017-02-10T03:54:29.000Z
Alchemy/Classes/Object/Alchemy/Plant.cpp
kkh029/Alchemy
ed3d96452508b6cf5680392028bef409dd8d78f1
[ "Apache-2.0" ]
null
null
null
// // Plant.cpp // Alchemy // // Created by Kyounghwan on 2014. 3. 1.. // 1302 Plant 3 30 - - - Tower - 재료. 1104 1201 // #include "Plant.h" #include "WindTalisman.h" #include "WaterTalisman.h" #include "EarthTalisman.h" #include "FireTalisman.h" /* ALCHEMY PARAMETER */ #define TWEEN_EASING_MAX_INDEX 10000 #define DEFAULT_INDEX 0 #define LOOP -1 #define HP 30 Plant::Plant(unsigned char index) :Alchemy(Alchemy::resource_table[index]) { m_hp = HP; } Plant::~Plant() {} Alchemy* Plant::create(PEObject* obj) { Plant* pPlant = new Plant(obj->PE_getResourceIndex()); return pPlant; } void Plant::PE_initAnimation() { ArmatureAnimation* ani; init(m_name.c_str()); setAnchorPoint(Vec2(0.5f, 0.0f)); ani = getAnimation(); ani->playWithIndex(DEFAULT_INDEX, -1, -1); } bool Plant::PE_update(unsigned int flag) { if( ((flag>>1) & 0x1) != cure) { if(!cure) { cure = true; PE_cure(true); } else { cure = false; } log("[Cure] %s", (cure)?"ON":"OFF"); } if( (flag>>3 & 0x1) != hp_up) { if(!hp_up) { hp_up = true; m_hp += HP/5; m_max_hp += HP/5; } else { hp_up = false; m_max_hp -= HP/5; m_hp = (m_hp>m_max_hp)?m_max_hp:m_hp; } log("[Max HP] %d", m_max_hp); } if(cure) { PE_cure(false); } if(!m_alive) removeFromParent(); return m_alive; }
15.648352
56
0.57514
kkh029
c252ded9f0c388e726a06f820e9874f1a9b30f74
402
cpp
C++
LeetCode/Algorithms/Easy/RemoveDuplicatesFromSortedArray.cpp
roshan11160/Competitive-Programming-Solutions
2d9cfe901c23a2b7344c410b7368eb02f7fa6e7e
[ "MIT" ]
40
2020-07-25T19:35:37.000Z
2022-01-28T02:57:02.000Z
LeetCode/Algorithms/Easy/RemoveDuplicatesFromSortedArray.cpp
afrozchakure/Hackerrank-Problem-Solutions
014155d841e08cb1f7609c23335576dc9b29cef3
[ "MIT" ]
160
2021-04-26T19:04:15.000Z
2022-03-26T20:18:37.000Z
LeetCode/Algorithms/Easy/RemoveDuplicatesFromSortedArray.cpp
afrozchakure/Hackerrank-Problem-Solutions
014155d841e08cb1f7609c23335576dc9b29cef3
[ "MIT" ]
24
2020-05-03T08:11:53.000Z
2021-10-04T03:23:20.000Z
class Solution { public: int removeDuplicates(vector<int>& nums) { int n = nums.size(); int j=0; for(int i=0; i<n;i++) { if(i < (n - 1) && nums[i] == nums[i+1]) continue; nums[j++] = nums[i]; } return j; } }; // Time complexity - O(N) // Space Complexity - O(1), since we're using the same array
21.157895
60
0.445274
roshan11160
c255b9989572f698ec350b06c5518a3aeca6c5cf
23,327
cpp
C++
parser/src/main.cpp
Hitachi-Data-Systems/ivy
07a77c271cad7f682d7fbff497bf74a76ecd5378
[ "Apache-2.0" ]
6
2016-09-12T16:23:53.000Z
2021-12-16T23:08:34.000Z
parser/src/main.cpp
Hitachi-Data-Systems/ivy
07a77c271cad7f682d7fbff497bf74a76ecd5378
[ "Apache-2.0" ]
null
null
null
parser/src/main.cpp
Hitachi-Data-Systems/ivy
07a77c271cad7f682d7fbff497bf74a76ecd5378
[ "Apache-2.0" ]
null
null
null
//Copyright (c) 2016, 2017, 2018 Hitachi Vantara Corporation //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. // //Authors: Allart Ian Vogelesang <ian.vogelesang@hitachivantara.com> // //Support: "ivy" is not officially supported by Hitachi Vantara. // Contact one of the authors by email and as time permits, we'll help on a best efforts basis. #include <pwd.h> #include <sys/utsname.h> #ifdef __GLIBC__ #include <gnu/libc-version.h> #endif #include "ivytypes.h" #include "Ivy_pgm.h" #include "ivy.parser.hh" #include "ivybuilddate.h" #include "RestHandler.h" std::string startup_log_file {"~/ivy_startup.txt"}; std::ostringstream startup_ostream; std::string inter_statement_divider {"=================================================================================================="}; bool routine_logging {false}; bool rest_api {false}; bool spinloop {true}; bool one_thread_per_core {false}; void usage_message(char* argv_0) { std::cout << std::endl << "Usage: " << argv_0 << " [options] <ivyscript file name to open>" << std::endl << std::endl << "where \"[options]\" means zero or more of:" << std::endl << std::endl << "-rest" << std::endl << " Turns on REST API service (ignores ivyscript in command line)" << std::endl << std::endl << "-log" << std::endl << " Turns on logging of routine events." << std::endl << std::endl << "-no_stepcsv" << std::endl << " Sets the default for the \"stepcsv\" [Go] parameter to \"off\" instead of \"on\"." << std::endl << " This suppresses creation of a \"step\" subfolder with by-subinterval csv files for rollups." << std::endl << std::endl << "-storcsv" << std::endl << " Sets the default for the \"storcsv\" [Go] parameter to \"on\" instead of \"off\"." << std::endl << " For each step (for each [Go]), if \"stepcsv\" is \"on\" to create a step subfolder with" << std::endl << " by-subinterval csv files, if the \"storcsv\" [Go] parameter is also \"on\", for each" << std::endl << " Hitachi subsystem with a command device connector, a nested subfolder is created containing" << std::endl << " by-subinterval subsystem data csv files." << std::endl << std::endl << "-no_wrap" << std::endl << " When opening ivy csv files with Excel, parity group names (e.g. 1-1)" << std::endl << " are interpreted by Excel as dates and LDEV names (e.g. 10:00) as times."<<std::endl << " Normally ivy encloses things like these in formulas, like =\"1-1\" or =\"10:00\"" << std::endl << " so they will look OK in Excel. To supress this formula rapping, use -no_wrap." << std::endl << std::endl << "-no_cmd"<< std::endl << " Don\'t use any command devices." << std::endl << std::endl << "-skip_LDEV"<< std::endl << " If a command device is being used, set the [Go] parameter default for skip_LDEV" << std::endl << " to \"skip_LDEV=on\" to skip collection of LDEV & PG data. This makes gathers faster" << std::endl << " if you don't need LDEV and PG data." << std::endl << std::endl << "-no_perf"<< std::endl << " If a command device is being used, set the [Go] parameter default for no_perf" << std::endl << " to \"no_perf=on\" to suppress the collection of subsystem performance data" << std::endl << " while ivy is running driving I/O. Collection of performance data resumes" << std::endl << " with the second and subsequent cooldown subintervals at IOPS=0 to support" << std::endl << " the cooldwon_by_wp and cooldown_by_MP_busy features." << std::endl << std::endl << "-spinloop" << std::endl << " (Deprecated) The default behaviour is for ivydriver to constantly check in a \"spin loop\"" << std::endl << " to see if there are any I/Os to start or to harvest. This default results in optimal" << std::endl << " I/O performance, but at the expense of running at 100% CPU busy. To wait for events, say:" << std::endl << " ivy_engine_set(\"spinloop\",\"off\");" << std::endl << std::endl << "-one_thread_per_core" << std::endl << " Use -one_thread_per_core to have ivydriver start a workload subthread on only the first" << std::endl << " hyperthread on each physical CPU core, instead of the default which is start a workload subthread" << " on all hyperthreads on each core. Either way, workload subthread(s) are never started on core 0." << std::endl << std::endl // << "-trace_lexer or -l" << std::endl // << " Log routine events and trace the \"lexer\" which breaks down the .ivyscript program into \"tokens\"." << std::endl << std::endl // << "-trace_parser or -p" << std::endl // << " Log routine events and trace the \"parser\" which recognizes the syntax of the stream of tokens as a program." << std::endl << std::endl // << "-trace_evaluate or -e" << std::endl // << " Log routine events and trace the execution of the compiled ivyscript program." << std::endl << std::endl // << "-t" << std::endl // << " Same as -trace_lexer -trace_parser -trace_evaluate." << std::endl << std::endl << "The .ivyscript suffix on the name of the ivyscript program is optional." << std::endl << std::endl << "Examples:" << std::endl << "\t" << argv_0 << " -rest" << std::endl << "\t" << argv_0 << " xxxx.ivyscript" << std::endl << "\t" << argv_0 << " xxxx" << std::endl << "\t" << argv_0 << " -no_wrap xxxx" << std::endl << "\t" << argv_0 << " -spinloop xxxx" << std::endl << "\t" << argv_0 << " -log xxxx" << std::endl //<< "\t" << argv_0 << " -t xxxx" << std::endl ; } std::string get_my_path_part() { #define MAX_FULLY_QUALIFIED_PATHNAME 511 const size_t pathname_max_length_with_null = MAX_FULLY_QUALIFIED_PATHNAME + 1; char pathname_char[pathname_max_length_with_null]; // Read the symbolic link '/proc/self/exe'. const char *proc_self_exe = "/proc/self/exe"; const int readlink_rc = int(readlink(proc_self_exe, pathname_char, MAX_FULLY_QUALIFIED_PATHNAME)); std::string fully_qualified {}; if (readlink_rc <= 0) { return ""; } fully_qualified = pathname_char; std::string path_part_regex_string { R"ivy((.*/)([^/]+))ivy" }; std::regex path_part_regex( path_part_regex_string ); std::smatch entire_match; std::ssub_match path_part; if (std::regex_match(fully_qualified, entire_match, path_part_regex)) { path_part = entire_match[1]; return path_part.str(); } return ""; } std::string get_running_user() { uid_t u; struct passwd *p; u = geteuid (); p = getpwuid (u); if (nullptr != p) { return std::string(p->pw_name); } return std::string(""); } void check_Linux_version_at_least_5_5() { std::string s = GetStdoutFromCommand("uname -r"s); trim(s); std::regex rx{ R"(([0-9]+)\.([0-9]+)\.([0-9])([^0-9].*)?)" }; std::smatch sm; if (std::regex_match(s, sm, rx)) { std::ssub_match major_ssm = sm[1]; std::string major = major_ssm.str(); std::ssub_match minor_ssm = sm[2]; std::string minor = minor_ssm.str(); int maj = atoi(major.c_str()); int min = atoi(minor.c_str()); if (maj < 5 || (maj == 5 && min < 5)) { std::ostringstream o; o << "<Error> Sorry, this version of ivy is only supported on Linux kernel version 5.5 or newer. This system is running version " << s << std::endl; throw std::runtime_error(o.str()); } } return; } int main(int argc, char* argv[]) { char hostname[HOST_NAME_MAX + 1]; hostname[HOST_NAME_MAX] = 0x00; if (0 != gethostname(hostname,HOST_NAME_MAX)) { std::cout << "<Error> internal programming error - gethostname(hostname,HOST_NAME_MAX)) failed errno " << errno << " - " << strerror(errno) << "." << std::endl; return -1; } std::string versions_message; { std::ostringstream o; o << "ivy version " << ivy_version << " build date " << IVYBUILDDATE << std::endl; std::cout << o.str(); #ifdef __GNUC__ o << std::endl << "gcc version " << __GNUC__; #endif #ifdef __GNUC_MINOR__ o << "." << __GNUC_MINOR__; #endif #ifdef __GNUC_PATCHLEVEL__ o << "." << __GNUC_PATCHLEVEL__; #endif #ifdef __GLIBCPP__ o << " - libstdc++ date " << __GLIBCPP__; #endif #ifdef __GLIBCXX__ o << " - libstdc++ date " << __GLIBCXX__; #endif o << std::endl; #ifdef __GLIBC__ o << "GNU libc compile-time version: " << __GLIBC__ << "." << __GLIBC_MINOR__; o << " - GNU libc runtime version: " << gnu_get_libc_version() << std::endl; #endif o << GetStdoutFromCommand("openssl version") << std::endl; struct utsname utsname_buf; if (0 == uname(&utsname_buf)) { o << utsname_buf.nodename << " - " << utsname_buf.sysname << " - " << utsname_buf.release << " - " << utsname_buf.version << " - " << utsname_buf.machine #ifdef _GNU_SOURCE << " - " << utsname_buf.domainname #endif << std::endl; } o << std::endl << "Attributes from lscpu command:" << std::endl << GetStdoutFromCommand("lscpu") << std::endl; versions_message = o.str(); } // std::cout << "argc = " << argc << " "; // for (int i=0;i<argc;i++) {std::cout << "argv["<<i<<"] = \"" << argv[i] << "\" ";} // std::cout << std::endl; std::string u = get_running_user(); if (0 != u.compare(std::string("root"))) { std::cout << "ivy is running as user " << u << ". Sorry, ivy must be running as root." << std::endl; return -1; } check_Linux_version_at_least_5_5(); m_s.path_to_ivy_executable = get_my_path_part(); std::string ivyscriptFilename {}; if (argc==1) { usage_message(argv[0]); return -1; } for (int arg_index = 1 /*skipping executable name*/ ; arg_index < argc ; arg_index++ ) {{ // double braces to be really sure "item" is fresh every time. std::string item {argv[arg_index]}; if (stringCaseInsensitiveEquality(remove_underscores(item), remove_underscores("-rest"))) { m_s.command_line_options += (" "s + item); rest_api = true; continue; } if (stringCaseInsensitiveEquality(remove_underscores(item), remove_underscores("-log"))) { m_s.command_line_options += (" "s + item); routine_logging = true; continue; } if (stringCaseInsensitiveEquality(remove_underscores(item), remove_underscores("-no_wrap"))) { m_s.command_line_options += (" "s + item); m_s.formula_wrapping = false; continue; } if (stringCaseInsensitiveEquality(remove_underscores(item), remove_underscores("-no_stepcsv"))) { m_s.command_line_options += (" "s + item); m_s.stepcsv_default = false; continue; } if (stringCaseInsensitiveEquality(remove_underscores(item), remove_underscores("-storcsv"))) { m_s.command_line_options += (" "s + item); m_s.storcsv_default = true; continue; } if (stringCaseInsensitiveEquality(remove_underscores(item), remove_underscores("-t"))) { m_s.command_line_options += (" "s + item); routine_logging = trace_lexer = trace_parser = trace_evaluate = true; continue; } if (stringCaseInsensitiveEquality(remove_underscores(item), remove_underscores("-trace_lexer")) || stringCaseInsensitiveEquality(remove_underscores(item), remove_underscores("-l")) ) { m_s.command_line_options += (" "s + item); routine_logging = trace_lexer = true; continue; } if (stringCaseInsensitiveEquality(remove_underscores(item), remove_underscores("-trace_parser")) || stringCaseInsensitiveEquality(remove_underscores(item), remove_underscores("-p")) ) { m_s.command_line_options += (" "s + item); routine_logging = trace_parser = true; continue; } if (stringCaseInsensitiveEquality(remove_underscores(item), remove_underscores("-trace_evaluate")) || stringCaseInsensitiveEquality(remove_underscores(item), remove_underscores("-e")) ) { m_s.command_line_options += (" "s + item); routine_logging = trace_evaluate = true; continue; } if (stringCaseInsensitiveEquality(remove_underscores(item), remove_underscores("-no_cmd"))) { m_s.command_line_options += (" "s + item); m_s.use_command_device = false; continue; } if (stringCaseInsensitiveEquality(remove_underscores(item), remove_underscores("-skip_LDEV"))) { m_s.command_line_options += (" "s + item); m_s.skip_ldev_data_default = true; continue; } if (stringCaseInsensitiveEquality(remove_underscores(item), remove_underscores("-one_thread_per_core"))) { m_s.command_line_options += (" "s + item); one_thread_per_core = true; continue; } if (stringCaseInsensitiveEquality(remove_underscores(item), remove_underscores("-no_perf")) || stringCaseInsensitiveEquality(remove_underscores(item), remove_underscores("-suppress_perf"))) { m_s.command_line_options += (" "s + item); m_s.suppress_subsystem_perf_default = true; continue; } if (stringCaseInsensitiveEquality(remove_underscores(item), remove_underscores("-no_check_failed_component"))) { m_s.command_line_options += (" "s + item); m_s.check_failed_component_default = false; continue; } if (stringCaseInsensitiveEquality(remove_underscores(item), remove_underscores("-spinloop"))) { spinloop = true; std::cout << std::endl << "===> Note: the -spinloop command line option still works, but please use ivy_engine_set(\"spinloop\", \"on\") instead." << std::endl << std::endl; continue; } if (item.size() > 0 && item[0] == '-') { std::cout << "Invalid option \"" << item << "\"." << std::endl << std::endl; usage_message(argv[0]); return -1; } if (arg_index != (argc-1)) { usage_message(argv[0]); return -1; } ivyscriptFilename = item; }} trim(m_s.command_line_options); bool is_python_script {false}; if (endsIn(ivyscriptFilename, ".py")) { rest_api = true; is_python_script = true; } else { if (!endsIn(ivyscriptFilename, ".ivyscript")) ivyscriptFilename += std::string(".ivyscript"); } if (rest_api && !is_python_script) { // setup and start serving the REST API RestHandler rest_handler; RestHandler::wait_and_serve(); return 0; } std::regex ivyscript_filename_regex(R"ivy((.*[/])?([^/\\]+)(\.ivyscript))ivy"); std::regex python_filename_regex(R"ivy((.*[/])?([^/\\]+)(\.py))ivy"); // Three sub matches // - optional path part, which if present ends with a forward slash / or // - test name part // - and the .ivyscript suffix, which was added if the user left it off std::smatch entire_match; // we will pick out the test name part - submatch 2, the identifier, possibly with embedded periods. std::ssub_match test_name_sub_match; if ((is_python_script ? !std::regex_match(ivyscriptFilename, entire_match, python_filename_regex) : !std::regex_match(ivyscriptFilename, entire_match, ivyscript_filename_regex))) { std::cout << "ivyscript filename \"" + ivyscriptFilename + "\" - bad filename or programming error extracting test name portion of filename." << std::endl; return -1; } if (entire_match.size() != 4) { std::cout << "ivyscript filename \"" + ivyscriptFilename + "\" - programming error extracting test name portion of filename. " << std::endl << entire_match.size() << " submatches found - expecting 4." << std::endl; return -1; } test_name_sub_match = entire_match[2]; std::string test_name = test_name_sub_match.str(); auto isValid = isValidTestNameIdentifier(test_name); if (!isValid.first) { std::cout << isValid.second; return -1; } m_s.testName = test_name; struct stat struct_stat; if(stat(ivyscriptFilename.c_str(),&struct_stat)) { std::cout << "<Error> ivyscript filename \"" + ivyscriptFilename + "\" does not exist." << std::endl; return -1; } if(!S_ISREG(struct_stat.st_mode)) { std::cout << "<Error> ivyscript filename \"" + ivyscriptFilename + "\" is not a regular file." << std::endl; return -1; } if (!is_python_script) { m_s.copy_back_ivy_logs_sh_filename = ivyscriptFilename.substr(0,ivyscriptFilename.size() - ".ivyscript"s.size()) + ".copy_back_ivy_logs.sh"s; if (m_s.copy_back_ivy_logs_sh_filename[0] != '/' && m_s.copy_back_ivy_logs_sh_filename.substr(0,2) != "./"s) { std::string path = GetStdoutFromCommand("pwd"); trim(path); m_s.copy_back_ivy_logs_sh_filename = path + "/"s + m_s.copy_back_ivy_logs_sh_filename; } } m_s.test_start_time.setToNow(); if (is_python_script) { // setup and start serving the REST API RestHandler rest_handler; Ivy_pgm context(ivyscriptFilename,test_name); m_s.outputFolderRoot = context.output_folder_root; m_s.testName = context.test_name; m_s.ivyscript_filename = context.ivyscript_filename; // if a python script is provided - run script and ivy sandwiched together std::string cmd = "sleep 1; unset http_proxy https_proxy; python " + ivyscriptFilename; system(cmd.c_str()); RestHandler::wait_and_serve(); // blocking return 0; } if( stat("/var",&struct_stat) || (!S_ISDIR(struct_stat.st_mode)) ) { std::cout << "<Error> \"\var\" doesn\'t exist or is not a folder." << std::endl; return -1; } if( stat("/var/ivymaster_logs", &struct_stat) ) { // folder doesn't already exist int rc; if ((rc = mkdir("/var/ivymaster_logs", S_IRWXU | S_IRWXG | S_IRWXO))) { std::ostringstream o; o << "<Error> Failed trying to create ivymaster root log folder \"/var/ivymaster_logs\" - " << "mkdir() return code " << rc << ", errno = " << errno << " " << std::strerror(errno) << std::endl; std::cout << o.str(); return -1; } } // Note: In order to have ivy's log files temporarily stored somewhere else // other than in /var, make a symlink in /var as /var/ivymaster_logs, // and have the symlink point to the root folder such as /xxxxx/ivymaster_logs. m_s.var_ivymaster_logs_testName = "/var/ivymaster_logs/"s + m_s.testName; { std::string cmd = "rm -rf "s + m_s.var_ivymaster_logs_testName; system(cmd.c_str()); } { int rc; if ((rc = mkdir(m_s.var_ivymaster_logs_testName.c_str(), S_IRWXU | S_IRWXG | S_IRWXO))) { std::ostringstream o; o << "<Error> Failed trying to create ivymaster log folder \"" << m_s.var_ivymaster_logs_testName << "\" - " << "mkdir() return code " << rc << ", errno = " << errno << " " << std::strerror(errno) << std::endl; std::cout << o.str(); return -1; } } m_s.masterlogfile.logfilename = m_s.var_ivymaster_logs_testName + "/log.ivymaster.txt"s; log(m_s.masterlogfile,versions_message); extern FILE* yyin; if( !(yyin = fopen(ivyscriptFilename.c_str(), "r")) ) { std::cout << "<Error> Could not open \"" << ivyscriptFilename << "\" for in." << std::endl; return -1; } Ivy_pgm context(ivyscriptFilename,test_name); p_Ivy_pgm = &context; yy::ivy parser(context); parser.parse(); fclose(yyin); if (trace_parser) { context.snapshot(std::cout); } if (context.successful_compile && !context.unsuccessful_compile ) { std::cout << "Successful compile, test name is \"" << test_name << "\"." << std::endl; try { context.stacktop = context.stack + context.next_avail_static; context.executing_frame = context.next_avail_static; if (trace_evaluate) { trace_ostream << "main.cpp: before invoking p_global_Block, context.next_avail_static = " << context.next_avail_static << ", context.stack = " << &(*context.stack) << ", stacktop offset from stack = " << (context.stacktop - context.stack) << ", executing_frame = " << context.executing_frame << std::endl; } context.p_global_Block()->invoke(); } catch (...) { std::cout << "<Error> Whoops! Something happened trying to run the ivy program." << std::endl; throw; } m_s.overall_success = true; } else { std::cout << "<Error> unsuccessful compile." << std::endl << std::endl; context.show_syntax_error_location(); } ivytime finish_time; finish_time.setToNow(); ivytime duration = finish_time - m_s.test_start_time; { std::ostringstream o; o << std::endl << "Step times summary:" << std::endl << m_s.step_duration_lines; o << std::endl << "********* ivy run complete." << std::endl; o << "********* Total run time " << duration.format_as_duration_HMMSS() << " for test name \"" << m_s.testName << "\"" << std::endl << std::endl; if (m_s.warning_messages.size() > 0) { o << "**********************************************************************************" << std::endl; o << "*** ***" << std::endl; o << "*** Will now repeat <Warning> messages previously shown while ivy was running. ***" << std::endl; o << "*** ***" << std::endl; o << "**********************************************************************************" << std::endl << std::endl; for (auto s : m_s.warning_messages) { o << s << std::endl; } } std::cout << o.str(); log(m_s.masterlogfile, o.str()); } if (m_s.iosequencer_template_was_used) { m_s.print_iosequencer_template_deprecated_msg(); } std::pair<bool,std::string> strc = m_s.shutdown_subthreads(); return 0; // in case compiler complains, but unreachable. }
42.567518
234
0.594761
Hitachi-Data-Systems
c25658fdad6cb914a10fe8cb43bbd24cc6dec870
16,142
cpp
C++
libs/base/src/poses/CPose3DQuatPDFGaussian_unittest.cpp
feroze/mrpt-shivang
95bf524c5e10ed2e622bd199f1b0597951b45370
[ "BSD-3-Clause" ]
2
2017-03-25T18:09:17.000Z
2017-05-22T08:14:48.000Z
libs/base/src/poses/CPose3DQuatPDFGaussian_unittest.cpp
shivangag/mrpt
95bf524c5e10ed2e622bd199f1b0597951b45370
[ "BSD-3-Clause" ]
null
null
null
libs/base/src/poses/CPose3DQuatPDFGaussian_unittest.cpp
shivangag/mrpt
95bf524c5e10ed2e622bd199f1b0597951b45370
[ "BSD-3-Clause" ]
1
2017-06-30T18:23:45.000Z
2017-06-30T18:23:45.000Z
/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #include <mrpt/poses/CPose3DPDFGaussian.h> #include <mrpt/poses/CPose3DQuatPDFGaussian.h> #include <mrpt/poses/CPose3D.h> #include <mrpt/random.h> #include <mrpt/math/transform_gaussian.h> #include <mrpt/math/jacobians.h> #include <gtest/gtest.h> using namespace mrpt; using namespace mrpt::poses; using namespace mrpt::utils; using namespace mrpt::math; using namespace std; class Pose3DQuatPDFGaussTests : public ::testing::Test { protected: virtual void SetUp() { } virtual void TearDown() { } static CPose3DQuatPDFGaussian generateRandomPoseQuat3DPDF(double x,double y, double z, double yaw, double pitch, double roll, double std_scale) { return CPose3DQuatPDFGaussian(generateRandomPose3DPDF(x,y,z,yaw,pitch,roll,std_scale)); } static CPose3DPDFGaussian generateRandomPose3DPDF(double x,double y, double z, double yaw, double pitch, double roll, double std_scale) { CMatrixDouble61 r; mrpt::random::randomGenerator.drawGaussian1DMatrix(r, 0,std_scale); CMatrixDouble66 cov; cov.multiply_AAt(r); // random semi-definite positive matrix: for (int i=0;i<6;i++) cov(i,i)+=1e-7; CPose3DPDFGaussian p6pdf( CPose3D(x,y,z,yaw,pitch,roll), cov ); return p6pdf; } void test_toFromYPRGauss(double yaw, double pitch,double roll) { // Random pose: CPose3DPDFGaussian p1ypr = generateRandomPose3DPDF(1.0,2.0,3.0, yaw,pitch,roll, 0.1); CPose3DQuatPDFGaussian p1quat = CPose3DQuatPDFGaussian(p1ypr); // Convert back to a 6x6 representation: CPose3DPDFGaussian p2ypr = CPose3DPDFGaussian(p1quat); EXPECT_NEAR(0,(p2ypr.cov - p1ypr.cov).array().abs().mean(), 1e-2) << "p1ypr: " << endl << p1ypr << endl << "p1quat : " << endl << p1quat << endl << "p2ypr : " << endl << p2ypr << endl; } static void func_compose(const CArrayDouble<2*7> &x, const double &dummy, CArrayDouble<7> &Y) { MRPT_UNUSED_PARAM(dummy); const CPose3DQuat p1(x[0],x[1],x[2],CQuaternionDouble(x[3],x[4],x[5],x[6])); const CPose3DQuat p2(x[7+0],x[7+1],x[7+2],CQuaternionDouble(x[7+3],x[7+4],x[7+5],x[7+6])); const CPose3DQuat p = p1+p2; for (int i=0;i<7;i++) Y[i]=p[i]; } static void func_inv_compose(const CArrayDouble<2*7> &x, const double &dummy, CArrayDouble<7> &Y) { MRPT_UNUSED_PARAM(dummy); const CPose3DQuat p1(x[0],x[1],x[2],CQuaternionDouble(x[3],x[4],x[5],x[6])); const CPose3DQuat p2(x[7+0],x[7+1],x[7+2],CQuaternionDouble(x[7+3],x[7+4],x[7+5],x[7+6])); const CPose3DQuat p = p1-p2; for (int i=0;i<7;i++) Y[i]=p[i]; } void testPoseComposition( double x,double y, double z, double yaw, double pitch, double roll, double std_scale, double x2,double y2, double z2, double yaw2, double pitch2, double roll2, double std_scale2 ) { CPose3DQuatPDFGaussian p7pdf1 = generateRandomPoseQuat3DPDF(x,y,z,yaw,pitch,roll, std_scale); CPose3DQuatPDFGaussian p7pdf2 = generateRandomPoseQuat3DPDF(x2,y2,z2,yaw2,pitch2,roll2, std_scale2); CPose3DQuatPDFGaussian p7_comp = p7pdf1 + p7pdf2; // Numeric approximation: CArrayDouble<7> y_mean; CMatrixFixedNumeric<double,7,7> y_cov; { CArrayDouble<2*7> x_mean; for (int i=0;i<7;i++) x_mean[i]=p7pdf1.mean[i]; for (int i=0;i<7;i++) x_mean[7+i]=p7pdf2.mean[i]; CMatrixFixedNumeric<double,14,14> x_cov; x_cov.insertMatrix(0,0, p7pdf1.cov); x_cov.insertMatrix(7,7, p7pdf2.cov); double DUMMY=0; CArrayDouble<2*7> x_incrs; x_incrs.assign(1e-6); transform_gaussian_linear(x_mean,x_cov,func_compose,DUMMY, y_mean,y_cov, x_incrs ); } // Compare: EXPECT_NEAR(0, (y_cov-p7_comp.cov).array().abs().mean(), 1e-2 ) << "p1 mean: " << p7pdf1.mean << endl << "p2 mean: " << p7pdf2.mean << endl << "Numeric approximation of covariance: " << endl << y_cov << endl << "Returned covariance: " << endl << p7_comp.cov << endl; } static void func_inverse(const CArrayDouble<7> &x, const double &dummy, CArrayDouble<7> &Y) { MRPT_UNUSED_PARAM(dummy); const CPose3DQuat p1(x[0],x[1],x[2],CQuaternionDouble(x[3],x[4],x[5],x[6])); const CPose3DQuat p1_inv ( -p1 ); for (int i=0;i<7;i++) Y[i]=p1_inv[i]; } void testCompositionJacobian( double x,double y, double z, double yaw, double pitch, double roll, double x2,double y2, double z2, double yaw2, double pitch2, double roll2) { const CPose3DQuat q1( CPose3D(x,y,z,yaw,pitch,roll) ); const CPose3DQuat q2( CPose3D(x2,y2,z2,yaw2,pitch2,roll2) ); // Theoretical Jacobians: CMatrixDouble77 df_dx(UNINITIALIZED_MATRIX), df_du(UNINITIALIZED_MATRIX); CPose3DQuatPDF::jacobiansPoseComposition( q1, // x q2, // u df_dx, df_du ); // Numerical approximation: CMatrixDouble77 num_df_dx(UNINITIALIZED_MATRIX), num_df_du(UNINITIALIZED_MATRIX); { CArrayDouble<2*7> x_mean; for (int i=0;i<7;i++) x_mean[i]=q1[i]; for (int i=0;i<7;i++) x_mean[7+i]=q2[i]; double DUMMY=0; CArrayDouble<2*7> x_incrs; x_incrs.assign(1e-7); CMatrixDouble numJacobs; mrpt::math::jacobians::jacob_numeric_estimate(x_mean,func_compose,x_incrs, DUMMY, numJacobs ); numJacobs.extractMatrix(0,0, num_df_dx); numJacobs.extractMatrix(0,7, num_df_du); } // Compare: EXPECT_NEAR(0, (df_dx-num_df_dx).array().abs().sum(), 3e-3 ) << "q1: " << q1 << endl << "q2: " << q2 << endl << "Numeric approximation of df_dx: " << endl << num_df_dx << endl << "Implemented method: " << endl << df_dx << endl << "Error: " << endl << df_dx-num_df_dx << endl; EXPECT_NEAR(0, (df_du-num_df_du).array().abs().sum(), 3e-3 ) << "q1: " << q1 << endl << "q2: " << q2 << endl << "Numeric approximation of df_du: " << endl << num_df_du << endl << "Implemented method: " << endl << df_du << endl << "Error: " << endl << df_du-num_df_du << endl; } void testInverse(double x,double y, double z, double yaw, double pitch, double roll, double std_scale) { CPose3DQuatPDFGaussian p7pdf1 = generateRandomPoseQuat3DPDF(x,y,z,yaw,pitch,roll, std_scale); CPose3DQuatPDFGaussian p7_inv = -p7pdf1; // Numeric approximation: CArrayDouble<7> y_mean; CMatrixFixedNumeric<double,7,7> y_cov; { CArrayDouble<7> x_mean; for (int i=0;i<7;i++) x_mean[i]=p7pdf1.mean[i]; CMatrixFixedNumeric<double,7,7> x_cov; x_cov.insertMatrix(0,0, p7pdf1.cov); double DUMMY=0; CArrayDouble<7> x_incrs; x_incrs.assign(1e-6); transform_gaussian_linear(x_mean,x_cov,func_inverse,DUMMY, y_mean,y_cov, x_incrs ); } // Compare: EXPECT_NEAR(0, (y_cov-p7_inv.cov).array().abs().mean(), 1e-2 ) << "p1 mean: " << p7pdf1.mean << endl << "inv mean: " << p7_inv.mean << endl << "Numeric approximation of covariance: " << endl << y_cov << endl << "Returned covariance: " << endl << p7_inv.cov << endl << "Error: " << endl << y_cov-p7_inv.cov << endl; } void testPoseInverseComposition( double x,double y, double z, double yaw, double pitch, double roll, double std_scale, double x2,double y2, double z2, double yaw2, double pitch2, double roll2, double std_scale2 ) { CPose3DQuatPDFGaussian p7pdf1 = generateRandomPoseQuat3DPDF(x,y,z,yaw,pitch,roll, std_scale); CPose3DQuatPDFGaussian p7pdf2 = generateRandomPoseQuat3DPDF(x2,y2,z2,yaw2,pitch2,roll2, std_scale2); CPose3DQuatPDFGaussian p7_comp = p7pdf1 - p7pdf2; // Numeric approximation: CArrayDouble<7> y_mean; CMatrixFixedNumeric<double,7,7> y_cov; { CArrayDouble<2*7> x_mean; for (int i=0;i<7;i++) x_mean[i]=p7pdf1.mean[i]; for (int i=0;i<7;i++) x_mean[7+i]=p7pdf2.mean[i]; CMatrixFixedNumeric<double,14,14> x_cov; x_cov.insertMatrix(0,0, p7pdf1.cov); x_cov.insertMatrix(7,7, p7pdf2.cov); double DUMMY=0; CArrayDouble<2*7> x_incrs; x_incrs.assign(1e-6); transform_gaussian_linear(x_mean,x_cov,func_inv_compose,DUMMY, y_mean,y_cov, x_incrs ); } // Compare: EXPECT_NEAR(0, (y_cov-p7_comp.cov).array().abs().mean(), 1e-2 ) << "p1 mean: " << p7pdf1.mean << endl << "p2 mean: " << p7pdf2.mean << endl << "Numeric approximation of covariance: " << endl << y_cov << endl << "Returned covariance: " << endl << p7_comp.cov << endl; } void testChangeCoordsRef( double x,double y, double z, double yaw, double pitch, double roll, double std_scale, double x2,double y2, double z2, double yaw2, double pitch2, double roll2 ) { CPose3DQuatPDFGaussian p7pdf1 = generateRandomPoseQuat3DPDF(x,y,z,yaw,pitch,roll, std_scale); const CPose3DQuat new_base = CPose3DQuat( CPose3D(x2,y2,z2,yaw2,pitch2,roll2) ); const CPose3DQuatPDFGaussian new_base_pdf( new_base, CMatrixDouble77() ); // COV = Zeros const CPose3DQuatPDFGaussian p7_new_base_pdf = new_base_pdf + p7pdf1; p7pdf1.changeCoordinatesReference(new_base); // Compare: EXPECT_NEAR(0, (p7_new_base_pdf.cov - p7pdf1.cov).array().abs().mean(), 1e-2 ) << "p1 mean: " << p7pdf1.mean << endl << "new_base: " << new_base << endl; EXPECT_NEAR(0, (p7_new_base_pdf.mean.getAsVectorVal() - p7pdf1.mean.getAsVectorVal() ).array().abs().mean(), 1e-2 ) << "p1 mean: " << p7pdf1.mean << endl << "new_base: " << new_base << endl; } }; TEST_F(Pose3DQuatPDFGaussTests,ToYPRGaussPDFAndBack) { test_toFromYPRGauss(DEG2RAD(-30),DEG2RAD(10),DEG2RAD(60)); test_toFromYPRGauss(DEG2RAD(30),DEG2RAD(88),DEG2RAD(0)); test_toFromYPRGauss(DEG2RAD(30),DEG2RAD(89.5),DEG2RAD(0)); // The formulas break at pitch=90, but this we cannot avoid... } TEST_F(Pose3DQuatPDFGaussTests,CompositionJacobian) { testCompositionJacobian(0,0,0,DEG2RAD(2),DEG2RAD(0),DEG2RAD(0), 0,0,0,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0) ); testCompositionJacobian(1,2,3,DEG2RAD(2),DEG2RAD(0),DEG2RAD(0), -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0) ); testCompositionJacobian(1,-2,3,DEG2RAD(2),DEG2RAD(0),DEG2RAD(0), -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0) ); testCompositionJacobian(1,2,-3,DEG2RAD(2),DEG2RAD(0),DEG2RAD(0), -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0) ); testCompositionJacobian(1,2,3,DEG2RAD(20),DEG2RAD(80),DEG2RAD(70), -8,45,10,DEG2RAD(50),DEG2RAD(-10),DEG2RAD(30) ); testCompositionJacobian(1,2,3,DEG2RAD(20),DEG2RAD(-80),DEG2RAD(70), -8,45,10,DEG2RAD(50),DEG2RAD(-10),DEG2RAD(30) ); testCompositionJacobian(1,2,3,DEG2RAD(20),DEG2RAD(80),DEG2RAD(-70), -8,45,10,DEG2RAD(50),DEG2RAD(-10),DEG2RAD(30) ); testCompositionJacobian(1,2,3,DEG2RAD(20),DEG2RAD(80),DEG2RAD(70), -8,45,10,DEG2RAD(-50),DEG2RAD(-10),DEG2RAD(30) ); testCompositionJacobian(1,2,3,DEG2RAD(20),DEG2RAD(80),DEG2RAD(70), -8,45,10,DEG2RAD(50),DEG2RAD(10),DEG2RAD(30) ); testCompositionJacobian(1,2,3,DEG2RAD(20),DEG2RAD(80),DEG2RAD(70), -8,45,10,DEG2RAD(50),DEG2RAD(-10),DEG2RAD(-30) ); } TEST_F(Pose3DQuatPDFGaussTests,Inverse) { testInverse(0,0,0,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testInverse(0,0,0,DEG2RAD(10),DEG2RAD(0),DEG2RAD(0), 0.1 ); testInverse(0,0,0,DEG2RAD(0),DEG2RAD(10),DEG2RAD(0), 0.1 ); testInverse(0,0,0,DEG2RAD(0),DEG2RAD(0),DEG2RAD(10), 0.1 ); testInverse(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testInverse(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.2 ); testInverse(1,2,3,DEG2RAD(30),DEG2RAD(0),DEG2RAD(0), 0.1 ); testInverse(-1,2,3,DEG2RAD(30),DEG2RAD(0),DEG2RAD(0), 0.1 ); testInverse(1,2,-3,DEG2RAD(30),DEG2RAD(0),DEG2RAD(0), 0.1 ); testInverse(-1,2,-3,DEG2RAD(30),DEG2RAD(0),DEG2RAD(0), 0.1 ); testInverse(1,2,3,DEG2RAD(-30),DEG2RAD(0),DEG2RAD(0), 0.1 ); testInverse(-1,2,3,DEG2RAD(-30),DEG2RAD(0),DEG2RAD(0), 0.1 ); testInverse(1,2,-3,DEG2RAD(-30),DEG2RAD(0),DEG2RAD(0), 0.1 ); testInverse(-1,2,-3,DEG2RAD(-30),DEG2RAD(0),DEG2RAD(0), 0.1 ); testInverse(1,2,3,DEG2RAD(0),DEG2RAD(30),DEG2RAD(0), 0.1 ); testInverse(-1,2,3,DEG2RAD(0),DEG2RAD(30),DEG2RAD(0), 0.1 ); testInverse(1,2,-3,DEG2RAD(0),DEG2RAD(30),DEG2RAD(0), 0.1 ); testInverse(-1,2,-3,DEG2RAD(0),DEG2RAD(30),DEG2RAD(0), 0.1 ); testInverse(1,2,3,DEG2RAD(0),DEG2RAD(-30),DEG2RAD(0), 0.1 ); testInverse(-1,2,3,DEG2RAD(0),DEG2RAD(-30),DEG2RAD(0), 0.1 ); testInverse(1,2,-3,DEG2RAD(0),DEG2RAD(-30),DEG2RAD(0), 0.1 ); testInverse(-1,2,-3,DEG2RAD(0),DEG2RAD(-30),DEG2RAD(0), 0.1 ); testInverse(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(30), 0.1 ); testInverse(-1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(30), 0.1 ); testInverse(1,2,-3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(30), 0.1 ); testInverse(-1,2,-3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(30), 0.1 ); testInverse(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(-30), 0.1 ); testInverse(-1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(-30), 0.1 ); testInverse(1,2,-3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(-30), 0.1 ); testInverse(-1,2,-3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(-30), 0.1 ); } TEST_F(Pose3DQuatPDFGaussTests,Composition) { testPoseComposition(0,0,0,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, 0,0,0,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseComposition(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseComposition(1,2,3,DEG2RAD(20),DEG2RAD(80),DEG2RAD(70), 0.1, -8,45,10,DEG2RAD(50),DEG2RAD(-10),DEG2RAD(30), 0.1 ); testPoseComposition(1,2,3,DEG2RAD(20),DEG2RAD(80),DEG2RAD(70), 0.2, -8,45,10,DEG2RAD(50),DEG2RAD(-10),DEG2RAD(30), 0.2 ); testPoseComposition(1,2,3,DEG2RAD(10),DEG2RAD(0),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseComposition(1,2,3,DEG2RAD(0),DEG2RAD(10),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseComposition(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(10), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseComposition(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(10),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseComposition(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(10),DEG2RAD(0), 0.1 ); testPoseComposition(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(10), 0.1 ); } TEST_F(Pose3DQuatPDFGaussTests,InverseComposition) { testPoseInverseComposition(0,0,0,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, 0,0,0,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseInverseComposition(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseInverseComposition(1,2,3,DEG2RAD(20),DEG2RAD(80),DEG2RAD(70), 0.1, -8,45,10,DEG2RAD(50),DEG2RAD(-10),DEG2RAD(30), 0.1 ); testPoseInverseComposition(1,2,3,DEG2RAD(20),DEG2RAD(80),DEG2RAD(70), 0.2, -8,45,10,DEG2RAD(50),DEG2RAD(-10),DEG2RAD(30), 0.2 ); testPoseInverseComposition(1,2,3,DEG2RAD(10),DEG2RAD(0),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseInverseComposition(1,2,3,DEG2RAD(0),DEG2RAD(10),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseInverseComposition(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(10), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseInverseComposition(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(10),DEG2RAD(0),DEG2RAD(0), 0.1 ); testPoseInverseComposition(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(10),DEG2RAD(0), 0.1 ); testPoseInverseComposition(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(10), 0.1 ); } TEST_F(Pose3DQuatPDFGaussTests,ChangeCoordsRef) { testChangeCoordsRef(0,0,0,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, 0,0,0,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0) ); testChangeCoordsRef(1,2,3,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0), 0.1, -8,45,10,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0) ); testChangeCoordsRef(1,2,3,DEG2RAD(20),DEG2RAD(80),DEG2RAD(70), 0.1, -8,45,10,DEG2RAD(50),DEG2RAD(-10),DEG2RAD(30) ); testChangeCoordsRef(1,2,3,DEG2RAD(20),DEG2RAD(80),DEG2RAD(70), 0.2, -8,45,10,DEG2RAD(50),DEG2RAD(-10),DEG2RAD(30) ); }
43.983651
145
0.672655
feroze
c2570b1ac89a18edf8ef13937bdfad185456de24
184,391
cpp
C++
GPUPerfStudio/Server/Common/Linux/jpglib/jfdctint.cpp
davidlee80/amd-gpuperfstudio-dx12
4ce82d2eb0c9b8a8fc2889372b370ab23383a0fe
[ "MIT" ]
1
2017-03-25T02:09:15.000Z
2017-03-25T02:09:15.000Z
GPUPerfStudio/Server/Common/Linux/jpglib/jfdctint.cpp
davidlee80/amd-gpuperfstudio-dx12
4ce82d2eb0c9b8a8fc2889372b370ab23383a0fe
[ "MIT" ]
null
null
null
GPUPerfStudio/Server/Common/Linux/jpglib/jfdctint.cpp
davidlee80/amd-gpuperfstudio-dx12
4ce82d2eb0c9b8a8fc2889372b370ab23383a0fe
[ "MIT" ]
3
2017-03-15T03:35:13.000Z
2022-02-23T06:29:02.000Z
/* * jfdctint.c * * Copyright (C) 1991-1996, Thomas G. Lane. * Modification developed 2003-2009 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains a slow-but-accurate integer implementation of the * forward DCT (Discrete Cosine Transform). * * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT * on each column. Direct algorithms are also available, but they are * much more complex and seem not to be any faster when reduced to code. * * This implementation is based on an algorithm described in * C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT * Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics, * Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991. * The primary algorithm described there uses 11 multiplies and 29 adds. * We use their alternate method with 12 multiplies and 32 adds. * The advantage of this method is that no data path contains more than one * multiplication; this allows a very simple and accurate implementation in * scaled fixed-point arithmetic, with a minimal number of shifts. * * We also provide FDCT routines with various input sample block sizes for * direct resolution reduction or enlargement and for direct resolving the * common 2x1 and 1x2 subsampling cases without additional resampling: NxN * (N=1...16), 2NxN, and Nx2N (N=1...8) pixels for one 8x8 output DCT block. * * For N<8 we fill the remaining block coefficients with zero. * For N>8 we apply a partial N-point FDCT on the input samples, computing * just the lower 8 frequency coefficients and discarding the rest. * * We must scale the output coefficients of the N-point FDCT appropriately * to the standard 8-point FDCT level by 8/N per 1-D pass. This scaling * is folded into the constant multipliers (pass 2) and/or final/initial * shifting. * * CAUTION: We rely on the FIX() macro except for the N=1,2,4,8 cases * since there would be too many additional constants to pre-calculate. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" #include "jdct.h" /* Private declarations for DCT subsystem */ namespace GPS { #ifdef DCT_ISLOW_SUPPORTED /* * This module is specialized to the case DCTSIZE = 8. */ #if DCTSIZE != 8 Sorry, this code only copes with 8x8 DCT blocks. /* deliberate syntax err */ #endif /* * The poop on this scaling stuff is as follows: * * Each 1-D DCT step produces outputs which are a factor of sqrt(N) * larger than the true DCT outputs. The final outputs are therefore * a factor of N larger than desired; since N=8 this can be cured by * a simple right shift at the end of the algorithm. The advantage of * this arrangement is that we save two multiplications per 1-D DCT, * because the y0 and y4 outputs need not be divided by sqrt(N). * In the IJG code, this factor of 8 is removed by the quantization step * (in jcdctmgr.c), NOT in this module. * * We have to do addition and subtraction of the integer inputs, which * is no problem, and multiplication by fractional constants, which is * a problem to do in integer arithmetic. We multiply all the constants * by CONST_SCALE and convert them to integer constants (thus retaining * CONST_BITS bits of precision in the constants). After doing a * multiplication we have to divide the product by CONST_SCALE, with proper * rounding, to produce the correct output. This division can be done * cheaply as a right shift of CONST_BITS bits. We postpone shifting * as long as possible so that partial sums can be added together with * full fractional precision. * * The outputs of the first pass are scaled up by PASS1_BITS bits so that * they are represented to better-than-integral precision. These outputs * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word * with the recommended scaling. (For 12-bit sample data, the intermediate * array is INT32 anyway.) * * To avoid overflow of the 32-bit intermediate results in pass 2, we must * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis * shows that the values given below are the most effective. */ #if BITS_IN_JSAMPLE == 8 #define CONST_BITS 13 #define PASS1_BITS 2 #else #define CONST_BITS 13 #define PASS1_BITS 1 /* lose a little precision to avoid overflow */ #endif /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus * causing a lot of useless floating-point operations at run time. * To get around this we use the following pre-calculated constants. * If you change CONST_BITS you may want to add appropriate values. * (With a reasonable C compiler, you can just rely on the FIX() macro...) */ #if CONST_BITS == 13 #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */ #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */ #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */ #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */ #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */ #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */ #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */ #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */ #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */ #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */ #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */ #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */ #else #define FIX_0_298631336 FIX(0.298631336) #define FIX_0_390180644 FIX(0.390180644) #define FIX_0_541196100 FIX(0.541196100) #define FIX_0_765366865 FIX(0.765366865) #define FIX_0_899976223 FIX(0.899976223) #define FIX_1_175875602 FIX(1.175875602) #define FIX_1_501321110 FIX(1.501321110) #define FIX_1_847759065 FIX(1.847759065) #define FIX_1_961570560 FIX(1.961570560) #define FIX_2_053119869 FIX(2.053119869) #define FIX_2_562915447 FIX(2.562915447) #define FIX_3_072711026 FIX(3.072711026) #endif /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result. * For 8-bit samples with the recommended scaling, all the variable * and constant values involved are no more than 16 bits wide, so a * 16x16->32 bit multiply can be used instead of a full 32x32 multiply. * For 12-bit samples, a full 32-bit multiplication will be needed. */ #if BITS_IN_JSAMPLE == 8 #define MULTIPLY(var,const) MULTIPLY16C16(var,const) #else #define MULTIPLY(var,const) ((var) * (const)) #endif /* * Perform the forward DCT on one block of samples. */ GLOBAL(void) jpeg_fdct_islow(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3; INT32 tmp10, tmp11, tmp12, tmp13; INT32 z1; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ dataptr = data; for (ctr = 0; ctr < DCTSIZE; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part per LL&M figure 1 --- note that published figure is faulty; * rotator "sqrt(2)*c1" should be "sqrt(2)*c6". */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[7]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[6]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[5]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[4]); tmp10 = tmp0 + tmp3; tmp12 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp13 = tmp1 - tmp2; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[7]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[6]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[5]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[4]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM)((tmp10 + tmp11 - 8 * CENTERJSAMPLE) << PASS1_BITS); dataptr[4] = (DCTELEM)((tmp10 - tmp11) << PASS1_BITS); z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100); /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS - PASS1_BITS - 1); dataptr[2] = (DCTELEM) RIGHT_SHIFT(z1 + MULTIPLY(tmp12, FIX_0_765366865), CONST_BITS - PASS1_BITS); dataptr[6] = (DCTELEM) RIGHT_SHIFT(z1 - MULTIPLY(tmp13, FIX_1_847759065), CONST_BITS - PASS1_BITS); /* Odd part per figure 8 --- note paper omits factor of sqrt(2). * cK represents sqrt(2) * cos(K*pi/16). * i0..i3 in the paper are tmp0..tmp3 here. */ tmp10 = tmp0 + tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp0 + tmp2; tmp13 = tmp1 + tmp3; z1 = MULTIPLY(tmp12 + tmp13, FIX_1_175875602); /* c3 */ /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS - PASS1_BITS - 1); tmp0 = MULTIPLY(tmp0, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp1 = MULTIPLY(tmp1, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp2 = MULTIPLY(tmp2, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp3 = MULTIPLY(tmp3, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp10 = MULTIPLY(tmp10, - FIX_0_899976223); /* c7-c3 */ tmp11 = MULTIPLY(tmp11, - FIX_2_562915447); /* -c1-c3 */ tmp12 = MULTIPLY(tmp12, - FIX_0_390180644); /* c5-c3 */ tmp13 = MULTIPLY(tmp13, - FIX_1_961570560); /* -c3-c5 */ tmp12 += z1; tmp13 += z1; dataptr[1] = (DCTELEM) RIGHT_SHIFT(tmp0 + tmp10 + tmp12, CONST_BITS - PASS1_BITS); dataptr[3] = (DCTELEM) RIGHT_SHIFT(tmp1 + tmp11 + tmp13, CONST_BITS - PASS1_BITS); dataptr[5] = (DCTELEM) RIGHT_SHIFT(tmp2 + tmp11 + tmp12, CONST_BITS - PASS1_BITS); dataptr[7] = (DCTELEM) RIGHT_SHIFT(tmp3 + tmp10 + tmp13, CONST_BITS - PASS1_BITS); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. */ dataptr = data; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part per LL&M figure 1 --- note that published figure is faulty; * rotator "sqrt(2)*c1" should be "sqrt(2)*c6". */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 7]; tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 6]; tmp2 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 5]; tmp3 = dataptr[DCTSIZE * 3] + dataptr[DCTSIZE * 4]; /* Add fudge factor here for final descale. */ tmp10 = tmp0 + tmp3 + (ONE << (PASS1_BITS - 1)); tmp12 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp13 = tmp1 - tmp2; tmp0 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 7]; tmp1 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 6]; tmp2 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 5]; tmp3 = dataptr[DCTSIZE * 3] - dataptr[DCTSIZE * 4]; dataptr[DCTSIZE * 0] = (DCTELEM) RIGHT_SHIFT(tmp10 + tmp11, PASS1_BITS); dataptr[DCTSIZE * 4] = (DCTELEM) RIGHT_SHIFT(tmp10 - tmp11, PASS1_BITS); z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100); /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS + PASS1_BITS - 1); dataptr[DCTSIZE * 2] = (DCTELEM) RIGHT_SHIFT(z1 + MULTIPLY(tmp12, FIX_0_765366865), CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 6] = (DCTELEM) RIGHT_SHIFT(z1 - MULTIPLY(tmp13, FIX_1_847759065), CONST_BITS + PASS1_BITS); /* Odd part per figure 8 --- note paper omits factor of sqrt(2). * cK represents sqrt(2) * cos(K*pi/16). * i0..i3 in the paper are tmp0..tmp3 here. */ tmp10 = tmp0 + tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp0 + tmp2; tmp13 = tmp1 + tmp3; z1 = MULTIPLY(tmp12 + tmp13, FIX_1_175875602); /* c3 */ /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS + PASS1_BITS - 1); tmp0 = MULTIPLY(tmp0, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp1 = MULTIPLY(tmp1, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp2 = MULTIPLY(tmp2, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp3 = MULTIPLY(tmp3, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp10 = MULTIPLY(tmp10, - FIX_0_899976223); /* c7-c3 */ tmp11 = MULTIPLY(tmp11, - FIX_2_562915447); /* -c1-c3 */ tmp12 = MULTIPLY(tmp12, - FIX_0_390180644); /* c5-c3 */ tmp13 = MULTIPLY(tmp13, - FIX_1_961570560); /* -c3-c5 */ tmp12 += z1; tmp13 += z1; dataptr[DCTSIZE * 1] = (DCTELEM) RIGHT_SHIFT(tmp0 + tmp10 + tmp12, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 3] = (DCTELEM) RIGHT_SHIFT(tmp1 + tmp11 + tmp13, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 5] = (DCTELEM) RIGHT_SHIFT(tmp2 + tmp11 + tmp12, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 7] = (DCTELEM) RIGHT_SHIFT(tmp3 + tmp10 + tmp13, CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ } } #ifdef DCT_SCALING_SUPPORTED /* * Perform the forward DCT on a 7x7 sample block. */ GLOBAL(void) jpeg_fdct_7x7(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3; INT32 tmp10, tmp11, tmp12; INT32 z1, z2, z3; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* cK represents sqrt(2) * cos(K*pi/14). */ dataptr = data; for (ctr = 0; ctr < 7; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[6]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[5]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[4]); tmp3 = GETJSAMPLE(elemptr[3]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[6]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[5]); tmp12 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[4]); z1 = tmp0 + tmp2; /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((z1 + tmp1 + tmp3 - 7 * CENTERJSAMPLE) << PASS1_BITS); tmp3 += tmp3; z1 -= tmp3; z1 -= tmp3; z1 = MULTIPLY(z1, FIX(0.353553391)); /* (c2+c6-c4)/2 */ z2 = MULTIPLY(tmp0 - tmp2, FIX(0.920609002)); /* (c2+c4-c6)/2 */ z3 = MULTIPLY(tmp1 - tmp2, FIX(0.314692123)); /* c6 */ dataptr[2] = (DCTELEM) DESCALE(z1 + z2 + z3, CONST_BITS - PASS1_BITS); z1 -= z2; z2 = MULTIPLY(tmp0 - tmp1, FIX(0.881747734)); /* c4 */ dataptr[4] = (DCTELEM) DESCALE(z2 + z3 - MULTIPLY(tmp1 - tmp3, FIX(0.707106781)), /* c2+c6-c4 */ CONST_BITS - PASS1_BITS); dataptr[6] = (DCTELEM) DESCALE(z1 + z2, CONST_BITS - PASS1_BITS); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(0.935414347)); /* (c3+c1-c5)/2 */ tmp2 = MULTIPLY(tmp10 - tmp11, FIX(0.170262339)); /* (c3+c5-c1)/2 */ tmp0 = tmp1 - tmp2; tmp1 += tmp2; tmp2 = MULTIPLY(tmp11 + tmp12, - FIX(1.378756276)); /* -c1 */ tmp1 += tmp2; tmp3 = MULTIPLY(tmp10 + tmp12, FIX(0.613604268)); /* c5 */ tmp0 += tmp3; tmp2 += tmp3 + MULTIPLY(tmp12, FIX(1.870828693)); /* c3+c1-c5 */ dataptr[1] = (DCTELEM) DESCALE(tmp0, CONST_BITS - PASS1_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp1, CONST_BITS - PASS1_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp2, CONST_BITS - PASS1_BITS); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/7)**2 = 64/49, which we fold * into the constant multipliers: * cK now represents sqrt(2) * cos(K*pi/14) * 64/49. */ dataptr = data; for (ctr = 0; ctr < 7; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 6]; tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 5]; tmp2 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 4]; tmp3 = dataptr[DCTSIZE * 3]; tmp10 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 6]; tmp11 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 5]; tmp12 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 4]; z1 = tmp0 + tmp2; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(z1 + tmp1 + tmp3, FIX(1.306122449)), /* 64/49 */ CONST_BITS + PASS1_BITS); tmp3 += tmp3; z1 -= tmp3; z1 -= tmp3; z1 = MULTIPLY(z1, FIX(0.461784020)); /* (c2+c6-c4)/2 */ z2 = MULTIPLY(tmp0 - tmp2, FIX(1.202428084)); /* (c2+c4-c6)/2 */ z3 = MULTIPLY(tmp1 - tmp2, FIX(0.411026446)); /* c6 */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(z1 + z2 + z3, CONST_BITS + PASS1_BITS); z1 -= z2; z2 = MULTIPLY(tmp0 - tmp1, FIX(1.151670509)); /* c4 */ dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(z2 + z3 - MULTIPLY(tmp1 - tmp3, FIX(0.923568041)), /* c2+c6-c4 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(z1 + z2, CONST_BITS + PASS1_BITS); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(1.221765677)); /* (c3+c1-c5)/2 */ tmp2 = MULTIPLY(tmp10 - tmp11, FIX(0.222383464)); /* (c3+c5-c1)/2 */ tmp0 = tmp1 - tmp2; tmp1 += tmp2; tmp2 = MULTIPLY(tmp11 + tmp12, - FIX(1.800824523)); /* -c1 */ tmp1 += tmp2; tmp3 = MULTIPLY(tmp10 + tmp12, FIX(0.801442310)); /* c5 */ tmp0 += tmp3; tmp2 += tmp3 + MULTIPLY(tmp12, FIX(2.443531355)); /* c3+c1-c5 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp0, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp1, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp2, CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 6x6 sample block. */ GLOBAL(void) jpeg_fdct_6x6(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2; INT32 tmp10, tmp11, tmp12; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* cK represents sqrt(2) * cos(K*pi/12). */ dataptr = data; for (ctr = 0; ctr < 6; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[5]); tmp11 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[4]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[3]); tmp10 = tmp0 + tmp2; tmp12 = tmp0 - tmp2; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[5]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[4]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[3]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 - 6 * CENTERJSAMPLE) << PASS1_BITS); dataptr[2] = (DCTELEM) DESCALE(MULTIPLY(tmp12, FIX(1.224744871)), /* c2 */ CONST_BITS - PASS1_BITS); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp11, FIX(0.707106781)), /* c4 */ CONST_BITS - PASS1_BITS); /* Odd part */ tmp10 = DESCALE(MULTIPLY(tmp0 + tmp2, FIX(0.366025404)), /* c5 */ CONST_BITS - PASS1_BITS); dataptr[1] = (DCTELEM)(tmp10 + ((tmp0 + tmp1) << PASS1_BITS)); dataptr[3] = (DCTELEM)((tmp0 - tmp1 - tmp2) << PASS1_BITS); dataptr[5] = (DCTELEM)(tmp10 + ((tmp2 - tmp1) << PASS1_BITS)); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/6)**2 = 16/9, which we fold * into the constant multipliers: * cK now represents sqrt(2) * cos(K*pi/12) * 16/9. */ dataptr = data; for (ctr = 0; ctr < 6; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 5]; tmp11 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 4]; tmp2 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 3]; tmp10 = tmp0 + tmp2; tmp12 = tmp0 - tmp2; tmp0 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 5]; tmp1 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 4]; tmp2 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 3]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(MULTIPLY(tmp12, FIX(2.177324216)), /* c2 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp11, FIX(1.257078722)), /* c4 */ CONST_BITS + PASS1_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp0 + tmp2, FIX(0.650711829)); /* c5 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp0 + tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp1 - tmp2, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp2 - tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 5x5 sample block. */ GLOBAL(void) jpeg_fdct_5x5(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2; INT32 tmp10, tmp11; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* We scale the results further by 2 as part of output adaption */ /* scaling for different DCT size. */ /* cK represents sqrt(2) * cos(K*pi/10). */ dataptr = data; for (ctr = 0; ctr < 5; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[4]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[3]); tmp2 = GETJSAMPLE(elemptr[2]); tmp10 = tmp0 + tmp1; tmp11 = tmp0 - tmp1; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[4]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[3]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp2 - 5 * CENTERJSAMPLE) << (PASS1_BITS + 1)); tmp11 = MULTIPLY(tmp11, FIX(0.790569415)); /* (c2+c4)/2 */ tmp10 -= tmp2 << 2; tmp10 = MULTIPLY(tmp10, FIX(0.353553391)); /* (c2-c4)/2 */ dataptr[2] = (DCTELEM) DESCALE(tmp11 + tmp10, CONST_BITS - PASS1_BITS - 1); dataptr[4] = (DCTELEM) DESCALE(tmp11 - tmp10, CONST_BITS - PASS1_BITS - 1); /* Odd part */ tmp10 = MULTIPLY(tmp0 + tmp1, FIX(0.831253876)); /* c3 */ dataptr[1] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp0, FIX(0.513743148)), /* c1-c3 */ CONST_BITS - PASS1_BITS - 1); dataptr[3] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp1, FIX(2.176250899)), /* c1+c3 */ CONST_BITS - PASS1_BITS - 1); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/5)**2 = 64/25, which we partially * fold into the constant multipliers (other part was done in pass 1): * cK now represents sqrt(2) * cos(K*pi/10) * 32/25. */ dataptr = data; for (ctr = 0; ctr < 5; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 4]; tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 3]; tmp2 = dataptr[DCTSIZE * 2]; tmp10 = tmp0 + tmp1; tmp11 = tmp0 - tmp1; tmp0 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 4]; tmp1 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 3]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp2, FIX(1.28)), /* 32/25 */ CONST_BITS + PASS1_BITS); tmp11 = MULTIPLY(tmp11, FIX(1.011928851)); /* (c2+c4)/2 */ tmp10 -= tmp2 << 2; tmp10 = MULTIPLY(tmp10, FIX(0.452548340)); /* (c2-c4)/2 */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(tmp11 + tmp10, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(tmp11 - tmp10, CONST_BITS + PASS1_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp0 + tmp1, FIX(1.064004961)); /* c3 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp0, FIX(0.657591230)), /* c1-c3 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp1, FIX(2.785601151)), /* c1+c3 */ CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 4x4 sample block. */ GLOBAL(void) jpeg_fdct_4x4(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1; INT32 tmp10, tmp11; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* We must also scale the output by (8/4)**2 = 2**2, which we add here. */ /* cK represents sqrt(2) * cos(K*pi/16) [refers to 8-point FDCT]. */ dataptr = data; for (ctr = 0; ctr < 4; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[3]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[2]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[3]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[2]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp0 + tmp1 - 4 * CENTERJSAMPLE) << (PASS1_BITS + 2)); dataptr[2] = (DCTELEM)((tmp0 - tmp1) << (PASS1_BITS + 2)); /* Odd part */ tmp0 = MULTIPLY(tmp10 + tmp11, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS - PASS1_BITS - 3); dataptr[1] = (DCTELEM) RIGHT_SHIFT(tmp0 + MULTIPLY(tmp10, FIX_0_765366865), /* c2-c6 */ CONST_BITS - PASS1_BITS - 2); dataptr[3] = (DCTELEM) RIGHT_SHIFT(tmp0 - MULTIPLY(tmp11, FIX_1_847759065), /* c2+c6 */ CONST_BITS - PASS1_BITS - 2); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. */ dataptr = data; for (ctr = 0; ctr < 4; ctr++) { /* Even part */ /* Add fudge factor here for final descale. */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 3] + (ONE << (PASS1_BITS - 1)); tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 2]; tmp10 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 3]; tmp11 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 2]; dataptr[DCTSIZE * 0] = (DCTELEM) RIGHT_SHIFT(tmp0 + tmp1, PASS1_BITS); dataptr[DCTSIZE * 2] = (DCTELEM) RIGHT_SHIFT(tmp0 - tmp1, PASS1_BITS); /* Odd part */ tmp0 = MULTIPLY(tmp10 + tmp11, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS + PASS1_BITS - 1); dataptr[DCTSIZE * 1] = (DCTELEM) RIGHT_SHIFT(tmp0 + MULTIPLY(tmp10, FIX_0_765366865), /* c2-c6 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 3] = (DCTELEM) RIGHT_SHIFT(tmp0 - MULTIPLY(tmp11, FIX_1_847759065), /* c2+c6 */ CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 3x3 sample block. */ GLOBAL(void) jpeg_fdct_3x3(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* We scale the results further by 2**2 as part of output adaption */ /* scaling for different DCT size. */ /* cK represents sqrt(2) * cos(K*pi/6). */ dataptr = data; for (ctr = 0; ctr < 3; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[2]); tmp1 = GETJSAMPLE(elemptr[1]); tmp2 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[2]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp0 + tmp1 - 3 * CENTERJSAMPLE) << (PASS1_BITS + 2)); dataptr[2] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp1 - tmp1, FIX(0.707106781)), /* c2 */ CONST_BITS - PASS1_BITS - 2); /* Odd part */ dataptr[1] = (DCTELEM) DESCALE(MULTIPLY(tmp2, FIX(1.224744871)), /* c1 */ CONST_BITS - PASS1_BITS - 2); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/3)**2 = 64/9, which we partially * fold into the constant multipliers (other part was done in pass 1): * cK now represents sqrt(2) * cos(K*pi/6) * 16/9. */ dataptr = data; for (ctr = 0; ctr < 3; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 2]; tmp1 = dataptr[DCTSIZE * 1]; tmp2 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 2]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp0 + tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp1 - tmp1, FIX(1.257078722)), /* c2 */ CONST_BITS + PASS1_BITS); /* Odd part */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(MULTIPLY(tmp2, FIX(2.177324216)), /* c1 */ CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 2x2 sample block. */ GLOBAL(void) jpeg_fdct_2x2(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3; JSAMPROW elemptr; /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT. */ /* Row 0 */ elemptr = sample_data[0] + start_col; tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[1]); tmp1 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[1]); /* Row 1 */ elemptr = sample_data[1] + start_col; tmp2 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[1]); tmp3 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[1]); /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/2)**2 = 2**4. */ /* Column 0 */ /* Apply unsigned->signed conversion */ data[DCTSIZE * 0] = (DCTELEM)((tmp0 + tmp2 - 4 * CENTERJSAMPLE) << 4); data[DCTSIZE * 1] = (DCTELEM)((tmp0 - tmp2) << 4); /* Column 1 */ data[DCTSIZE * 0 + 1] = (DCTELEM)((tmp1 + tmp3) << 4); data[DCTSIZE * 1 + 1] = (DCTELEM)((tmp1 - tmp3) << 4); } /* * Perform the forward DCT on a 1x1 sample block. */ GLOBAL(void) jpeg_fdct_1x1(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* We leave the result scaled up by an overall factor of 8. */ /* We must also scale the output by (8/1)**2 = 2**6. */ /* Apply unsigned->signed conversion */ data[0] = (DCTELEM) ((GETJSAMPLE(sample_data[0][start_col]) - CENTERJSAMPLE) << 6); } /* * Perform the forward DCT on a 9x9 sample block. */ GLOBAL(void) jpeg_fdct_9x9(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4; INT32 tmp10, tmp11, tmp12, tmp13; INT32 z1, z2; DCTELEM workspace[8]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* we scale the results further by 2 as part of output adaption */ /* scaling for different DCT size. */ /* cK represents sqrt(2) * cos(K*pi/18). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[8]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[7]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[6]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[5]); tmp4 = GETJSAMPLE(elemptr[4]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[8]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[7]); tmp12 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[6]); tmp13 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[5]); z1 = tmp0 + tmp2 + tmp3; z2 = tmp1 + tmp4; /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM)((z1 + z2 - 9 * CENTERJSAMPLE) << 1); dataptr[6] = (DCTELEM) DESCALE(MULTIPLY(z1 - z2 - z2, FIX(0.707106781)), /* c6 */ CONST_BITS - 1); z1 = MULTIPLY(tmp0 - tmp2, FIX(1.328926049)); /* c2 */ z2 = MULTIPLY(tmp1 - tmp4 - tmp4, FIX(0.707106781)); /* c6 */ dataptr[2] = (DCTELEM) DESCALE(MULTIPLY(tmp2 - tmp3, FIX(1.083350441)) /* c4 */ + z1 + z2, CONST_BITS - 1); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp3 - tmp0, FIX(0.245575608)) /* c8 */ + z1 - z2, CONST_BITS - 1); /* Odd part */ dataptr[3] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12 - tmp13, FIX(1.224744871)), /* c3 */ CONST_BITS - 1); tmp11 = MULTIPLY(tmp11, FIX(1.224744871)); /* c3 */ tmp0 = MULTIPLY(tmp10 + tmp12, FIX(0.909038955)); /* c5 */ tmp1 = MULTIPLY(tmp10 + tmp13, FIX(0.483689525)); /* c7 */ dataptr[1] = (DCTELEM) DESCALE(tmp11 + tmp0 + tmp1, CONST_BITS - 1); tmp2 = MULTIPLY(tmp12 - tmp13, FIX(1.392728481)); /* c1 */ dataptr[5] = (DCTELEM) DESCALE(tmp0 - tmp11 - tmp2, CONST_BITS - 1); dataptr[7] = (DCTELEM) DESCALE(tmp1 - tmp11 + tmp2, CONST_BITS - 1); ctr++; if (ctr != DCTSIZE) { if (ctr == 9) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/9)**2 = 64/81, which we partially * fold into the constant multipliers and final/initial shifting: * cK now represents sqrt(2) * cos(K*pi/18) * 128/81. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 0]; tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 7]; tmp2 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 6]; tmp3 = dataptr[DCTSIZE * 3] + dataptr[DCTSIZE * 5]; tmp4 = dataptr[DCTSIZE * 4]; tmp10 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 0]; tmp11 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 7]; tmp12 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 6]; tmp13 = dataptr[DCTSIZE * 3] - dataptr[DCTSIZE * 5]; z1 = tmp0 + tmp2 + tmp3; z2 = tmp1 + tmp4; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(z1 + z2, FIX(1.580246914)), /* 128/81 */ CONST_BITS + 2); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(MULTIPLY(z1 - z2 - z2, FIX(1.117403309)), /* c6 */ CONST_BITS + 2); z1 = MULTIPLY(tmp0 - tmp2, FIX(2.100031287)); /* c2 */ z2 = MULTIPLY(tmp1 - tmp4 - tmp4, FIX(1.117403309)); /* c6 */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(MULTIPLY(tmp2 - tmp3, FIX(1.711961190)) /* c4 */ + z1 + z2, CONST_BITS + 2); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp3 - tmp0, FIX(0.388070096)) /* c8 */ + z1 - z2, CONST_BITS + 2); /* Odd part */ dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12 - tmp13, FIX(1.935399303)), /* c3 */ CONST_BITS + 2); tmp11 = MULTIPLY(tmp11, FIX(1.935399303)); /* c3 */ tmp0 = MULTIPLY(tmp10 + tmp12, FIX(1.436506004)); /* c5 */ tmp1 = MULTIPLY(tmp10 + tmp13, FIX(0.764348879)); /* c7 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp11 + tmp0 + tmp1, CONST_BITS + 2); tmp2 = MULTIPLY(tmp12 - tmp13, FIX(2.200854883)); /* c1 */ dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp0 - tmp11 - tmp2, CONST_BITS + 2); dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(tmp1 - tmp11 + tmp2, CONST_BITS + 2); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 10x10 sample block. */ GLOBAL(void) jpeg_fdct_10x10(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4; INT32 tmp10, tmp11, tmp12, tmp13, tmp14; DCTELEM workspace[8 * 2]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* we scale the results further by 2 as part of output adaption */ /* scaling for different DCT size. */ /* cK represents sqrt(2) * cos(K*pi/20). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[9]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[8]); tmp12 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[7]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[6]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[5]); tmp10 = tmp0 + tmp4; tmp13 = tmp0 - tmp4; tmp11 = tmp1 + tmp3; tmp14 = tmp1 - tmp3; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[9]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[8]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[7]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[6]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[5]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 + tmp12 - 10 * CENTERJSAMPLE) << 1); tmp12 += tmp12; dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.144122806)) - /* c4 */ MULTIPLY(tmp11 - tmp12, FIX(0.437016024)), /* c8 */ CONST_BITS - 1); tmp10 = MULTIPLY(tmp13 + tmp14, FIX(0.831253876)); /* c6 */ dataptr[2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp13, FIX(0.513743148)), /* c2-c6 */ CONST_BITS - 1); dataptr[6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(2.176250899)), /* c2+c6 */ CONST_BITS - 1); /* Odd part */ tmp10 = tmp0 + tmp4; tmp11 = tmp1 - tmp3; dataptr[5] = (DCTELEM)((tmp10 - tmp11 - tmp2) << 1); tmp2 <<= CONST_BITS; dataptr[1] = (DCTELEM) DESCALE(MULTIPLY(tmp0, FIX(1.396802247)) + /* c1 */ MULTIPLY(tmp1, FIX(1.260073511)) + tmp2 + /* c3 */ MULTIPLY(tmp3, FIX(0.642039522)) + /* c7 */ MULTIPLY(tmp4, FIX(0.221231742)), /* c9 */ CONST_BITS - 1); tmp12 = MULTIPLY(tmp0 - tmp4, FIX(0.951056516)) - /* (c3+c7)/2 */ MULTIPLY(tmp1 + tmp3, FIX(0.587785252)); /* (c1-c9)/2 */ tmp13 = MULTIPLY(tmp10 + tmp11, FIX(0.309016994)) + /* (c3-c7)/2 */ (tmp11 << (CONST_BITS - 1)) - tmp2; dataptr[3] = (DCTELEM) DESCALE(tmp12 + tmp13, CONST_BITS - 1); dataptr[7] = (DCTELEM) DESCALE(tmp12 - tmp13, CONST_BITS - 1); ctr++; if (ctr != DCTSIZE) { if (ctr == 10) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/10)**2 = 16/25, which we partially * fold into the constant multipliers and final/initial shifting: * cK now represents sqrt(2) * cos(K*pi/20) * 32/25. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 1]; tmp1 = dataptr[DCTSIZE * 1] + wsptr[DCTSIZE * 0]; tmp12 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 7]; tmp3 = dataptr[DCTSIZE * 3] + dataptr[DCTSIZE * 6]; tmp4 = dataptr[DCTSIZE * 4] + dataptr[DCTSIZE * 5]; tmp10 = tmp0 + tmp4; tmp13 = tmp0 - tmp4; tmp11 = tmp1 + tmp3; tmp14 = tmp1 - tmp3; tmp0 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 1]; tmp1 = dataptr[DCTSIZE * 1] - wsptr[DCTSIZE * 0]; tmp2 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 7]; tmp3 = dataptr[DCTSIZE * 3] - dataptr[DCTSIZE * 6]; tmp4 = dataptr[DCTSIZE * 4] - dataptr[DCTSIZE * 5]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11 + tmp12, FIX(1.28)), /* 32/25 */ CONST_BITS + 2); tmp12 += tmp12; dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.464477191)) - /* c4 */ MULTIPLY(tmp11 - tmp12, FIX(0.559380511)), /* c8 */ CONST_BITS + 2); tmp10 = MULTIPLY(tmp13 + tmp14, FIX(1.064004961)); /* c6 */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp13, FIX(0.657591230)), /* c2-c6 */ CONST_BITS + 2); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(2.785601151)), /* c2+c6 */ CONST_BITS + 2); /* Odd part */ tmp10 = tmp0 + tmp4; tmp11 = tmp1 - tmp3; dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp2, FIX(1.28)), /* 32/25 */ CONST_BITS + 2); tmp2 = MULTIPLY(tmp2, FIX(1.28)); /* 32/25 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(MULTIPLY(tmp0, FIX(1.787906876)) + /* c1 */ MULTIPLY(tmp1, FIX(1.612894094)) + tmp2 + /* c3 */ MULTIPLY(tmp3, FIX(0.821810588)) + /* c7 */ MULTIPLY(tmp4, FIX(0.283176630)), /* c9 */ CONST_BITS + 2); tmp12 = MULTIPLY(tmp0 - tmp4, FIX(1.217352341)) - /* (c3+c7)/2 */ MULTIPLY(tmp1 + tmp3, FIX(0.752365123)); /* (c1-c9)/2 */ tmp13 = MULTIPLY(tmp10 + tmp11, FIX(0.395541753)) + /* (c3-c7)/2 */ MULTIPLY(tmp11, FIX(0.64)) - tmp2; /* 16/25 */ dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp12 + tmp13, CONST_BITS + 2); dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(tmp12 - tmp13, CONST_BITS + 2); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on an 11x11 sample block. */ GLOBAL(void) jpeg_fdct_11x11(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5; INT32 tmp10, tmp11, tmp12, tmp13, tmp14; INT32 z1, z2, z3; DCTELEM workspace[8 * 3]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* we scale the results further by 2 as part of output adaption */ /* scaling for different DCT size. */ /* cK represents sqrt(2) * cos(K*pi/22). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[10]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[9]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[8]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[7]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[6]); tmp5 = GETJSAMPLE(elemptr[5]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[10]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[9]); tmp12 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[8]); tmp13 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[7]); tmp14 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[6]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp0 + tmp1 + tmp2 + tmp3 + tmp4 + tmp5 - 11 * CENTERJSAMPLE) << 1); tmp5 += tmp5; tmp0 -= tmp5; tmp1 -= tmp5; tmp2 -= tmp5; tmp3 -= tmp5; tmp4 -= tmp5; z1 = MULTIPLY(tmp0 + tmp3, FIX(1.356927976)) + /* c2 */ MULTIPLY(tmp2 + tmp4, FIX(0.201263574)); /* c10 */ z2 = MULTIPLY(tmp1 - tmp3, FIX(0.926112931)); /* c6 */ z3 = MULTIPLY(tmp0 - tmp1, FIX(1.189712156)); /* c4 */ dataptr[2] = (DCTELEM) DESCALE(z1 + z2 - MULTIPLY(tmp3, FIX(1.018300590)) /* c2+c8-c6 */ - MULTIPLY(tmp4, FIX(1.390975730)), /* c4+c10 */ CONST_BITS - 1); dataptr[4] = (DCTELEM) DESCALE(z2 + z3 + MULTIPLY(tmp1, FIX(0.062335650)) /* c4-c6-c10 */ - MULTIPLY(tmp2, FIX(1.356927976)) /* c2 */ + MULTIPLY(tmp4, FIX(0.587485545)), /* c8 */ CONST_BITS - 1); dataptr[6] = (DCTELEM) DESCALE(z1 + z3 - MULTIPLY(tmp0, FIX(1.620527200)) /* c2+c4-c6 */ - MULTIPLY(tmp2, FIX(0.788749120)), /* c8+c10 */ CONST_BITS - 1); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(1.286413905)); /* c3 */ tmp2 = MULTIPLY(tmp10 + tmp12, FIX(1.068791298)); /* c5 */ tmp3 = MULTIPLY(tmp10 + tmp13, FIX(0.764581576)); /* c7 */ tmp0 = tmp1 + tmp2 + tmp3 - MULTIPLY(tmp10, FIX(1.719967871)) /* c7+c5+c3-c1 */ + MULTIPLY(tmp14, FIX(0.398430003)); /* c9 */ tmp4 = MULTIPLY(tmp11 + tmp12, - FIX(0.764581576)); /* -c7 */ tmp5 = MULTIPLY(tmp11 + tmp13, - FIX(1.399818907)); /* -c1 */ tmp1 += tmp4 + tmp5 + MULTIPLY(tmp11, FIX(1.276416582)) /* c9+c7+c1-c3 */ - MULTIPLY(tmp14, FIX(1.068791298)); /* c5 */ tmp10 = MULTIPLY(tmp12 + tmp13, FIX(0.398430003)); /* c9 */ tmp2 += tmp4 + tmp10 - MULTIPLY(tmp12, FIX(1.989053629)) /* c9+c5+c3-c7 */ + MULTIPLY(tmp14, FIX(1.399818907)); /* c1 */ tmp3 += tmp5 + tmp10 + MULTIPLY(tmp13, FIX(1.305598626)) /* c1+c5-c9-c7 */ - MULTIPLY(tmp14, FIX(1.286413905)); /* c3 */ dataptr[1] = (DCTELEM) DESCALE(tmp0, CONST_BITS - 1); dataptr[3] = (DCTELEM) DESCALE(tmp1, CONST_BITS - 1); dataptr[5] = (DCTELEM) DESCALE(tmp2, CONST_BITS - 1); dataptr[7] = (DCTELEM) DESCALE(tmp3, CONST_BITS - 1); ctr++; if (ctr != DCTSIZE) { if (ctr == 11) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/11)**2 = 64/121, which we partially * fold into the constant multipliers and final/initial shifting: * cK now represents sqrt(2) * cos(K*pi/22) * 128/121. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 2]; tmp1 = dataptr[DCTSIZE * 1] + wsptr[DCTSIZE * 1]; tmp2 = dataptr[DCTSIZE * 2] + wsptr[DCTSIZE * 0]; tmp3 = dataptr[DCTSIZE * 3] + dataptr[DCTSIZE * 7]; tmp4 = dataptr[DCTSIZE * 4] + dataptr[DCTSIZE * 6]; tmp5 = dataptr[DCTSIZE * 5]; tmp10 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 2]; tmp11 = dataptr[DCTSIZE * 1] - wsptr[DCTSIZE * 1]; tmp12 = dataptr[DCTSIZE * 2] - wsptr[DCTSIZE * 0]; tmp13 = dataptr[DCTSIZE * 3] - dataptr[DCTSIZE * 7]; tmp14 = dataptr[DCTSIZE * 4] - dataptr[DCTSIZE * 6]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp0 + tmp1 + tmp2 + tmp3 + tmp4 + tmp5, FIX(1.057851240)), /* 128/121 */ CONST_BITS + 2); tmp5 += tmp5; tmp0 -= tmp5; tmp1 -= tmp5; tmp2 -= tmp5; tmp3 -= tmp5; tmp4 -= tmp5; z1 = MULTIPLY(tmp0 + tmp3, FIX(1.435427942)) + /* c2 */ MULTIPLY(tmp2 + tmp4, FIX(0.212906922)); /* c10 */ z2 = MULTIPLY(tmp1 - tmp3, FIX(0.979689713)); /* c6 */ z3 = MULTIPLY(tmp0 - tmp1, FIX(1.258538479)); /* c4 */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(z1 + z2 - MULTIPLY(tmp3, FIX(1.077210542)) /* c2+c8-c6 */ - MULTIPLY(tmp4, FIX(1.471445400)), /* c4+c10 */ CONST_BITS + 2); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(z2 + z3 + MULTIPLY(tmp1, FIX(0.065941844)) /* c4-c6-c10 */ - MULTIPLY(tmp2, FIX(1.435427942)) /* c2 */ + MULTIPLY(tmp4, FIX(0.621472312)), /* c8 */ CONST_BITS + 2); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(z1 + z3 - MULTIPLY(tmp0, FIX(1.714276708)) /* c2+c4-c6 */ - MULTIPLY(tmp2, FIX(0.834379234)), /* c8+c10 */ CONST_BITS + 2); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(1.360834544)); /* c3 */ tmp2 = MULTIPLY(tmp10 + tmp12, FIX(1.130622199)); /* c5 */ tmp3 = MULTIPLY(tmp10 + tmp13, FIX(0.808813568)); /* c7 */ tmp0 = tmp1 + tmp2 + tmp3 - MULTIPLY(tmp10, FIX(1.819470145)) /* c7+c5+c3-c1 */ + MULTIPLY(tmp14, FIX(0.421479672)); /* c9 */ tmp4 = MULTIPLY(tmp11 + tmp12, - FIX(0.808813568)); /* -c7 */ tmp5 = MULTIPLY(tmp11 + tmp13, - FIX(1.480800167)); /* -c1 */ tmp1 += tmp4 + tmp5 + MULTIPLY(tmp11, FIX(1.350258864)) /* c9+c7+c1-c3 */ - MULTIPLY(tmp14, FIX(1.130622199)); /* c5 */ tmp10 = MULTIPLY(tmp12 + tmp13, FIX(0.421479672)); /* c9 */ tmp2 += tmp4 + tmp10 - MULTIPLY(tmp12, FIX(2.104122847)) /* c9+c5+c3-c7 */ + MULTIPLY(tmp14, FIX(1.480800167)); /* c1 */ tmp3 += tmp5 + tmp10 + MULTIPLY(tmp13, FIX(1.381129125)) /* c1+c5-c9-c7 */ - MULTIPLY(tmp14, FIX(1.360834544)); /* c3 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp0, CONST_BITS + 2); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp1, CONST_BITS + 2); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp2, CONST_BITS + 2); dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(tmp3, CONST_BITS + 2); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 12x12 sample block. */ GLOBAL(void) jpeg_fdct_12x12(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15; DCTELEM workspace[8 * 4]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT. */ /* cK represents sqrt(2) * cos(K*pi/24). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[11]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[10]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[9]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[8]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[7]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[6]); tmp10 = tmp0 + tmp5; tmp13 = tmp0 - tmp5; tmp11 = tmp1 + tmp4; tmp14 = tmp1 - tmp4; tmp12 = tmp2 + tmp3; tmp15 = tmp2 - tmp3; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[11]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[10]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[9]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[8]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[7]); tmp5 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[6]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM)(tmp10 + tmp11 + tmp12 - 12 * CENTERJSAMPLE); dataptr[6] = (DCTELEM)(tmp13 - tmp14 - tmp15); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.224744871)), /* c4 */ CONST_BITS); dataptr[2] = (DCTELEM) DESCALE(tmp14 - tmp15 + MULTIPLY(tmp13 + tmp15, FIX(1.366025404)), /* c2 */ CONST_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp1 + tmp4, FIX_0_541196100); /* c9 */ tmp14 = tmp10 + MULTIPLY(tmp1, FIX_0_765366865); /* c3-c9 */ tmp15 = tmp10 - MULTIPLY(tmp4, FIX_1_847759065); /* c3+c9 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(1.121971054)); /* c5 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(0.860918669)); /* c7 */ tmp10 = tmp12 + tmp13 + tmp14 - MULTIPLY(tmp0, FIX(0.580774953)) /* c5+c7-c1 */ + MULTIPLY(tmp5, FIX(0.184591911)); /* c11 */ tmp11 = MULTIPLY(tmp2 + tmp3, - FIX(0.184591911)); /* -c11 */ tmp12 += tmp11 - tmp15 - MULTIPLY(tmp2, FIX(2.339493912)) /* c1+c5-c11 */ + MULTIPLY(tmp5, FIX(0.860918669)); /* c7 */ tmp13 += tmp11 - tmp14 + MULTIPLY(tmp3, FIX(0.725788011)) /* c1+c11-c7 */ - MULTIPLY(tmp5, FIX(1.121971054)); /* c5 */ tmp11 = tmp15 + MULTIPLY(tmp0 - tmp3, FIX(1.306562965)) /* c3 */ - MULTIPLY(tmp2 + tmp5, FIX_0_541196100); /* c9 */ dataptr[1] = (DCTELEM) DESCALE(tmp10, CONST_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp11, CONST_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp12, CONST_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp13, CONST_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == 12) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/12)**2 = 4/9, which we partially * fold into the constant multipliers and final shifting: * cK now represents sqrt(2) * cos(K*pi/24) * 8/9. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 3]; tmp1 = dataptr[DCTSIZE * 1] + wsptr[DCTSIZE * 2]; tmp2 = dataptr[DCTSIZE * 2] + wsptr[DCTSIZE * 1]; tmp3 = dataptr[DCTSIZE * 3] + wsptr[DCTSIZE * 0]; tmp4 = dataptr[DCTSIZE * 4] + dataptr[DCTSIZE * 7]; tmp5 = dataptr[DCTSIZE * 5] + dataptr[DCTSIZE * 6]; tmp10 = tmp0 + tmp5; tmp13 = tmp0 - tmp5; tmp11 = tmp1 + tmp4; tmp14 = tmp1 - tmp4; tmp12 = tmp2 + tmp3; tmp15 = tmp2 - tmp3; tmp0 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 3]; tmp1 = dataptr[DCTSIZE * 1] - wsptr[DCTSIZE * 2]; tmp2 = dataptr[DCTSIZE * 2] - wsptr[DCTSIZE * 1]; tmp3 = dataptr[DCTSIZE * 3] - wsptr[DCTSIZE * 0]; tmp4 = dataptr[DCTSIZE * 4] - dataptr[DCTSIZE * 7]; tmp5 = dataptr[DCTSIZE * 5] - dataptr[DCTSIZE * 6]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11 + tmp12, FIX(0.888888889)), /* 8/9 */ CONST_BITS + 1); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(MULTIPLY(tmp13 - tmp14 - tmp15, FIX(0.888888889)), /* 8/9 */ CONST_BITS + 1); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.088662108)), /* c4 */ CONST_BITS + 1); dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(MULTIPLY(tmp14 - tmp15, FIX(0.888888889)) + /* 8/9 */ MULTIPLY(tmp13 + tmp15, FIX(1.214244803)), /* c2 */ CONST_BITS + 1); /* Odd part */ tmp10 = MULTIPLY(tmp1 + tmp4, FIX(0.481063200)); /* c9 */ tmp14 = tmp10 + MULTIPLY(tmp1, FIX(0.680326102)); /* c3-c9 */ tmp15 = tmp10 - MULTIPLY(tmp4, FIX(1.642452502)); /* c3+c9 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(0.997307603)); /* c5 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(0.765261039)); /* c7 */ tmp10 = tmp12 + tmp13 + tmp14 - MULTIPLY(tmp0, FIX(0.516244403)) /* c5+c7-c1 */ + MULTIPLY(tmp5, FIX(0.164081699)); /* c11 */ tmp11 = MULTIPLY(tmp2 + tmp3, - FIX(0.164081699)); /* -c11 */ tmp12 += tmp11 - tmp15 - MULTIPLY(tmp2, FIX(2.079550144)) /* c1+c5-c11 */ + MULTIPLY(tmp5, FIX(0.765261039)); /* c7 */ tmp13 += tmp11 - tmp14 + MULTIPLY(tmp3, FIX(0.645144899)) /* c1+c11-c7 */ - MULTIPLY(tmp5, FIX(0.997307603)); /* c5 */ tmp11 = tmp15 + MULTIPLY(tmp0 - tmp3, FIX(1.161389302)) /* c3 */ - MULTIPLY(tmp2 + tmp5, FIX(0.481063200)); /* c9 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp10, CONST_BITS + 1); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp11, CONST_BITS + 1); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp12, CONST_BITS + 1); dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(tmp13, CONST_BITS + 1); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 13x13 sample block. */ GLOBAL(void) jpeg_fdct_13x13(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15; INT32 z1, z2; DCTELEM workspace[8 * 5]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT. */ /* cK represents sqrt(2) * cos(K*pi/26). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[12]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[11]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[10]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[9]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[8]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[7]); tmp6 = GETJSAMPLE(elemptr[6]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[12]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[11]); tmp12 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[10]); tmp13 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[9]); tmp14 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[8]); tmp15 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[7]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) (tmp0 + tmp1 + tmp2 + tmp3 + tmp4 + tmp5 + tmp6 - 13 * CENTERJSAMPLE); tmp6 += tmp6; tmp0 -= tmp6; tmp1 -= tmp6; tmp2 -= tmp6; tmp3 -= tmp6; tmp4 -= tmp6; tmp5 -= tmp6; dataptr[2] = (DCTELEM) DESCALE(MULTIPLY(tmp0, FIX(1.373119086)) + /* c2 */ MULTIPLY(tmp1, FIX(1.058554052)) + /* c6 */ MULTIPLY(tmp2, FIX(0.501487041)) - /* c10 */ MULTIPLY(tmp3, FIX(0.170464608)) - /* c12 */ MULTIPLY(tmp4, FIX(0.803364869)) - /* c8 */ MULTIPLY(tmp5, FIX(1.252223920)), /* c4 */ CONST_BITS); z1 = MULTIPLY(tmp0 - tmp2, FIX(1.155388986)) - /* (c4+c6)/2 */ MULTIPLY(tmp3 - tmp4, FIX(0.435816023)) - /* (c2-c10)/2 */ MULTIPLY(tmp1 - tmp5, FIX(0.316450131)); /* (c8-c12)/2 */ z2 = MULTIPLY(tmp0 + tmp2, FIX(0.096834934)) - /* (c4-c6)/2 */ MULTIPLY(tmp3 + tmp4, FIX(0.937303064)) + /* (c2+c10)/2 */ MULTIPLY(tmp1 + tmp5, FIX(0.486914739)); /* (c8+c12)/2 */ dataptr[4] = (DCTELEM) DESCALE(z1 + z2, CONST_BITS); dataptr[6] = (DCTELEM) DESCALE(z1 - z2, CONST_BITS); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(1.322312651)); /* c3 */ tmp2 = MULTIPLY(tmp10 + tmp12, FIX(1.163874945)); /* c5 */ tmp3 = MULTIPLY(tmp10 + tmp13, FIX(0.937797057)) + /* c7 */ MULTIPLY(tmp14 + tmp15, FIX(0.338443458)); /* c11 */ tmp0 = tmp1 + tmp2 + tmp3 - MULTIPLY(tmp10, FIX(2.020082300)) + /* c3+c5+c7-c1 */ MULTIPLY(tmp14, FIX(0.318774355)); /* c9-c11 */ tmp4 = MULTIPLY(tmp14 - tmp15, FIX(0.937797057)) - /* c7 */ MULTIPLY(tmp11 + tmp12, FIX(0.338443458)); /* c11 */ tmp5 = MULTIPLY(tmp11 + tmp13, - FIX(1.163874945)); /* -c5 */ tmp1 += tmp4 + tmp5 + MULTIPLY(tmp11, FIX(0.837223564)) - /* c5+c9+c11-c3 */ MULTIPLY(tmp14, FIX(2.341699410)); /* c1+c7 */ tmp6 = MULTIPLY(tmp12 + tmp13, - FIX(0.657217813)); /* -c9 */ tmp2 += tmp4 + tmp6 - MULTIPLY(tmp12, FIX(1.572116027)) + /* c1+c5-c9-c11 */ MULTIPLY(tmp15, FIX(2.260109708)); /* c3+c7 */ tmp3 += tmp5 + tmp6 + MULTIPLY(tmp13, FIX(2.205608352)) - /* c3+c5+c9-c7 */ MULTIPLY(tmp15, FIX(1.742345811)); /* c1+c11 */ dataptr[1] = (DCTELEM) DESCALE(tmp0, CONST_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp1, CONST_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp2, CONST_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp3, CONST_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == 13) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/13)**2 = 64/169, which we partially * fold into the constant multipliers and final shifting: * cK now represents sqrt(2) * cos(K*pi/26) * 128/169. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 4]; tmp1 = dataptr[DCTSIZE * 1] + wsptr[DCTSIZE * 3]; tmp2 = dataptr[DCTSIZE * 2] + wsptr[DCTSIZE * 2]; tmp3 = dataptr[DCTSIZE * 3] + wsptr[DCTSIZE * 1]; tmp4 = dataptr[DCTSIZE * 4] + wsptr[DCTSIZE * 0]; tmp5 = dataptr[DCTSIZE * 5] + dataptr[DCTSIZE * 7]; tmp6 = dataptr[DCTSIZE * 6]; tmp10 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 4]; tmp11 = dataptr[DCTSIZE * 1] - wsptr[DCTSIZE * 3]; tmp12 = dataptr[DCTSIZE * 2] - wsptr[DCTSIZE * 2]; tmp13 = dataptr[DCTSIZE * 3] - wsptr[DCTSIZE * 1]; tmp14 = dataptr[DCTSIZE * 4] - wsptr[DCTSIZE * 0]; tmp15 = dataptr[DCTSIZE * 5] - dataptr[DCTSIZE * 7]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp0 + tmp1 + tmp2 + tmp3 + tmp4 + tmp5 + tmp6, FIX(0.757396450)), /* 128/169 */ CONST_BITS + 1); tmp6 += tmp6; tmp0 -= tmp6; tmp1 -= tmp6; tmp2 -= tmp6; tmp3 -= tmp6; tmp4 -= tmp6; tmp5 -= tmp6; dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(MULTIPLY(tmp0, FIX(1.039995521)) + /* c2 */ MULTIPLY(tmp1, FIX(0.801745081)) + /* c6 */ MULTIPLY(tmp2, FIX(0.379824504)) - /* c10 */ MULTIPLY(tmp3, FIX(0.129109289)) - /* c12 */ MULTIPLY(tmp4, FIX(0.608465700)) - /* c8 */ MULTIPLY(tmp5, FIX(0.948429952)), /* c4 */ CONST_BITS + 1); z1 = MULTIPLY(tmp0 - tmp2, FIX(0.875087516)) - /* (c4+c6)/2 */ MULTIPLY(tmp3 - tmp4, FIX(0.330085509)) - /* (c2-c10)/2 */ MULTIPLY(tmp1 - tmp5, FIX(0.239678205)); /* (c8-c12)/2 */ z2 = MULTIPLY(tmp0 + tmp2, FIX(0.073342435)) - /* (c4-c6)/2 */ MULTIPLY(tmp3 + tmp4, FIX(0.709910013)) + /* (c2+c10)/2 */ MULTIPLY(tmp1 + tmp5, FIX(0.368787494)); /* (c8+c12)/2 */ dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(z1 + z2, CONST_BITS + 1); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(z1 - z2, CONST_BITS + 1); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(1.001514908)); /* c3 */ tmp2 = MULTIPLY(tmp10 + tmp12, FIX(0.881514751)); /* c5 */ tmp3 = MULTIPLY(tmp10 + tmp13, FIX(0.710284161)) + /* c7 */ MULTIPLY(tmp14 + tmp15, FIX(0.256335874)); /* c11 */ tmp0 = tmp1 + tmp2 + tmp3 - MULTIPLY(tmp10, FIX(1.530003162)) + /* c3+c5+c7-c1 */ MULTIPLY(tmp14, FIX(0.241438564)); /* c9-c11 */ tmp4 = MULTIPLY(tmp14 - tmp15, FIX(0.710284161)) - /* c7 */ MULTIPLY(tmp11 + tmp12, FIX(0.256335874)); /* c11 */ tmp5 = MULTIPLY(tmp11 + tmp13, - FIX(0.881514751)); /* -c5 */ tmp1 += tmp4 + tmp5 + MULTIPLY(tmp11, FIX(0.634110155)) - /* c5+c9+c11-c3 */ MULTIPLY(tmp14, FIX(1.773594819)); /* c1+c7 */ tmp6 = MULTIPLY(tmp12 + tmp13, - FIX(0.497774438)); /* -c9 */ tmp2 += tmp4 + tmp6 - MULTIPLY(tmp12, FIX(1.190715098)) + /* c1+c5-c9-c11 */ MULTIPLY(tmp15, FIX(1.711799069)); /* c3+c7 */ tmp3 += tmp5 + tmp6 + MULTIPLY(tmp13, FIX(1.670519935)) - /* c3+c5+c9-c7 */ MULTIPLY(tmp15, FIX(1.319646532)); /* c1+c11 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp0, CONST_BITS + 1); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp1, CONST_BITS + 1); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp2, CONST_BITS + 1); dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(tmp3, CONST_BITS + 1); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 14x14 sample block. */ GLOBAL(void) jpeg_fdct_14x14(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16; DCTELEM workspace[8 * 6]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT. */ /* cK represents sqrt(2) * cos(K*pi/28). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[13]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[12]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[11]); tmp13 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[10]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[9]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[8]); tmp6 = GETJSAMPLE(elemptr[6]) + GETJSAMPLE(elemptr[7]); tmp10 = tmp0 + tmp6; tmp14 = tmp0 - tmp6; tmp11 = tmp1 + tmp5; tmp15 = tmp1 - tmp5; tmp12 = tmp2 + tmp4; tmp16 = tmp2 - tmp4; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[13]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[12]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[11]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[10]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[9]); tmp5 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[8]); tmp6 = GETJSAMPLE(elemptr[6]) - GETJSAMPLE(elemptr[7]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) (tmp10 + tmp11 + tmp12 + tmp13 - 14 * CENTERJSAMPLE); tmp13 += tmp13; dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(1.274162392)) + /* c4 */ MULTIPLY(tmp11 - tmp13, FIX(0.314692123)) - /* c12 */ MULTIPLY(tmp12 - tmp13, FIX(0.881747734)), /* c8 */ CONST_BITS); tmp10 = MULTIPLY(tmp14 + tmp15, FIX(1.105676686)); /* c6 */ dataptr[2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp14, FIX(0.273079590)) /* c2-c6 */ + MULTIPLY(tmp16, FIX(0.613604268)), /* c10 */ CONST_BITS); dataptr[6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp15, FIX(1.719280954)) /* c6+c10 */ - MULTIPLY(tmp16, FIX(1.378756276)), /* c2 */ CONST_BITS); /* Odd part */ tmp10 = tmp1 + tmp2; tmp11 = tmp5 - tmp4; dataptr[7] = (DCTELEM)(tmp0 - tmp10 + tmp3 - tmp11 - tmp6); tmp3 <<= CONST_BITS; tmp10 = MULTIPLY(tmp10, - FIX(0.158341681)); /* -c13 */ tmp11 = MULTIPLY(tmp11, FIX(1.405321284)); /* c1 */ tmp10 += tmp11 - tmp3; tmp11 = MULTIPLY(tmp0 + tmp2, FIX(1.197448846)) + /* c5 */ MULTIPLY(tmp4 + tmp6, FIX(0.752406978)); /* c9 */ dataptr[5] = (DCTELEM) DESCALE(tmp10 + tmp11 - MULTIPLY(tmp2, FIX(2.373959773)) /* c3+c5-c13 */ + MULTIPLY(tmp4, FIX(1.119999435)), /* c1+c11-c9 */ CONST_BITS); tmp12 = MULTIPLY(tmp0 + tmp1, FIX(1.334852607)) + /* c3 */ MULTIPLY(tmp5 - tmp6, FIX(0.467085129)); /* c11 */ dataptr[3] = (DCTELEM) DESCALE(tmp10 + tmp12 - MULTIPLY(tmp1, FIX(0.424103948)) /* c3-c9-c13 */ - MULTIPLY(tmp5, FIX(3.069855259)), /* c1+c5+c11 */ CONST_BITS); dataptr[1] = (DCTELEM) DESCALE(tmp11 + tmp12 + tmp3 + tmp6 - MULTIPLY(tmp0 + tmp6, FIX(1.126980169)), /* c3+c5-c1 */ CONST_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == 14) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/14)**2 = 16/49, which we partially * fold into the constant multipliers and final shifting: * cK now represents sqrt(2) * cos(K*pi/28) * 32/49. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 5]; tmp1 = dataptr[DCTSIZE * 1] + wsptr[DCTSIZE * 4]; tmp2 = dataptr[DCTSIZE * 2] + wsptr[DCTSIZE * 3]; tmp13 = dataptr[DCTSIZE * 3] + wsptr[DCTSIZE * 2]; tmp4 = dataptr[DCTSIZE * 4] + wsptr[DCTSIZE * 1]; tmp5 = dataptr[DCTSIZE * 5] + wsptr[DCTSIZE * 0]; tmp6 = dataptr[DCTSIZE * 6] + dataptr[DCTSIZE * 7]; tmp10 = tmp0 + tmp6; tmp14 = tmp0 - tmp6; tmp11 = tmp1 + tmp5; tmp15 = tmp1 - tmp5; tmp12 = tmp2 + tmp4; tmp16 = tmp2 - tmp4; tmp0 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 5]; tmp1 = dataptr[DCTSIZE * 1] - wsptr[DCTSIZE * 4]; tmp2 = dataptr[DCTSIZE * 2] - wsptr[DCTSIZE * 3]; tmp3 = dataptr[DCTSIZE * 3] - wsptr[DCTSIZE * 2]; tmp4 = dataptr[DCTSIZE * 4] - wsptr[DCTSIZE * 1]; tmp5 = dataptr[DCTSIZE * 5] - wsptr[DCTSIZE * 0]; tmp6 = dataptr[DCTSIZE * 6] - dataptr[DCTSIZE * 7]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11 + tmp12 + tmp13, FIX(0.653061224)), /* 32/49 */ CONST_BITS + 1); tmp13 += tmp13; dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(0.832106052)) + /* c4 */ MULTIPLY(tmp11 - tmp13, FIX(0.205513223)) - /* c12 */ MULTIPLY(tmp12 - tmp13, FIX(0.575835255)), /* c8 */ CONST_BITS + 1); tmp10 = MULTIPLY(tmp14 + tmp15, FIX(0.722074570)); /* c6 */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp14, FIX(0.178337691)) /* c2-c6 */ + MULTIPLY(tmp16, FIX(0.400721155)), /* c10 */ CONST_BITS + 1); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp15, FIX(1.122795725)) /* c6+c10 */ - MULTIPLY(tmp16, FIX(0.900412262)), /* c2 */ CONST_BITS + 1); /* Odd part */ tmp10 = tmp1 + tmp2; tmp11 = tmp5 - tmp4; dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp10 + tmp3 - tmp11 - tmp6, FIX(0.653061224)), /* 32/49 */ CONST_BITS + 1); tmp3 = MULTIPLY(tmp3 , FIX(0.653061224)); /* 32/49 */ tmp10 = MULTIPLY(tmp10, - FIX(0.103406812)); /* -c13 */ tmp11 = MULTIPLY(tmp11, FIX(0.917760839)); /* c1 */ tmp10 += tmp11 - tmp3; tmp11 = MULTIPLY(tmp0 + tmp2, FIX(0.782007410)) + /* c5 */ MULTIPLY(tmp4 + tmp6, FIX(0.491367823)); /* c9 */ dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp10 + tmp11 - MULTIPLY(tmp2, FIX(1.550341076)) /* c3+c5-c13 */ + MULTIPLY(tmp4, FIX(0.731428202)), /* c1+c11-c9 */ CONST_BITS + 1); tmp12 = MULTIPLY(tmp0 + tmp1, FIX(0.871740478)) + /* c3 */ MULTIPLY(tmp5 - tmp6, FIX(0.305035186)); /* c11 */ dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp10 + tmp12 - MULTIPLY(tmp1, FIX(0.276965844)) /* c3-c9-c13 */ - MULTIPLY(tmp5, FIX(2.004803435)), /* c1+c5+c11 */ CONST_BITS + 1); dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp11 + tmp12 + tmp3 - MULTIPLY(tmp0, FIX(0.735987049)) /* c3+c5-c1 */ - MULTIPLY(tmp6, FIX(0.082925825)), /* c9-c11-c13 */ CONST_BITS + 1); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 15x15 sample block. */ GLOBAL(void) jpeg_fdct_15x15(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16; INT32 z1, z2, z3; DCTELEM workspace[8 * 7]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT. */ /* cK represents sqrt(2) * cos(K*pi/30). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[14]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[13]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[12]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[11]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[10]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[9]); tmp6 = GETJSAMPLE(elemptr[6]) + GETJSAMPLE(elemptr[8]); tmp7 = GETJSAMPLE(elemptr[7]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[14]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[13]); tmp12 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[12]); tmp13 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[11]); tmp14 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[10]); tmp15 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[9]); tmp16 = GETJSAMPLE(elemptr[6]) - GETJSAMPLE(elemptr[8]); z1 = tmp0 + tmp4 + tmp5; z2 = tmp1 + tmp3 + tmp6; z3 = tmp2 + tmp7; /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM)(z1 + z2 + z3 - 15 * CENTERJSAMPLE); z3 += z3; dataptr[6] = (DCTELEM) DESCALE(MULTIPLY(z1 - z3, FIX(1.144122806)) - /* c6 */ MULTIPLY(z2 - z3, FIX(0.437016024)), /* c12 */ CONST_BITS); tmp2 += ((tmp1 + tmp4) >> 1) - tmp7 - tmp7; z1 = MULTIPLY(tmp3 - tmp2, FIX(1.531135173)) - /* c2+c14 */ MULTIPLY(tmp6 - tmp2, FIX(2.238241955)); /* c4+c8 */ z2 = MULTIPLY(tmp5 - tmp2, FIX(0.798468008)) - /* c8-c14 */ MULTIPLY(tmp0 - tmp2, FIX(0.091361227)); /* c2-c4 */ z3 = MULTIPLY(tmp0 - tmp3, FIX(1.383309603)) + /* c2 */ MULTIPLY(tmp6 - tmp5, FIX(0.946293579)) + /* c8 */ MULTIPLY(tmp1 - tmp4, FIX(0.790569415)); /* (c6+c12)/2 */ dataptr[2] = (DCTELEM) DESCALE(z1 + z3, CONST_BITS); dataptr[4] = (DCTELEM) DESCALE(z2 + z3, CONST_BITS); /* Odd part */ tmp2 = MULTIPLY(tmp10 - tmp12 - tmp13 + tmp15 + tmp16, FIX(1.224744871)); /* c5 */ tmp1 = MULTIPLY(tmp10 - tmp14 - tmp15, FIX(1.344997024)) + /* c3 */ MULTIPLY(tmp11 - tmp13 - tmp16, FIX(0.831253876)); /* c9 */ tmp12 = MULTIPLY(tmp12, FIX(1.224744871)); /* c5 */ tmp4 = MULTIPLY(tmp10 - tmp16, FIX(1.406466353)) + /* c1 */ MULTIPLY(tmp11 + tmp14, FIX(1.344997024)) + /* c3 */ MULTIPLY(tmp13 + tmp15, FIX(0.575212477)); /* c11 */ tmp0 = MULTIPLY(tmp13, FIX(0.475753014)) - /* c7-c11 */ MULTIPLY(tmp14, FIX(0.513743148)) + /* c3-c9 */ MULTIPLY(tmp16, FIX(1.700497885)) + tmp4 + tmp12; /* c1+c13 */ tmp3 = MULTIPLY(tmp10, - FIX(0.355500862)) - /* -(c1-c7) */ MULTIPLY(tmp11, FIX(2.176250899)) - /* c3+c9 */ MULTIPLY(tmp15, FIX(0.869244010)) + tmp4 - tmp12; /* c11+c13 */ dataptr[1] = (DCTELEM) DESCALE(tmp0, CONST_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp1, CONST_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp2, CONST_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp3, CONST_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == 15) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/15)**2 = 64/225, which we partially * fold into the constant multipliers and final shifting: * cK now represents sqrt(2) * cos(K*pi/30) * 256/225. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 6]; tmp1 = dataptr[DCTSIZE * 1] + wsptr[DCTSIZE * 5]; tmp2 = dataptr[DCTSIZE * 2] + wsptr[DCTSIZE * 4]; tmp3 = dataptr[DCTSIZE * 3] + wsptr[DCTSIZE * 3]; tmp4 = dataptr[DCTSIZE * 4] + wsptr[DCTSIZE * 2]; tmp5 = dataptr[DCTSIZE * 5] + wsptr[DCTSIZE * 1]; tmp6 = dataptr[DCTSIZE * 6] + wsptr[DCTSIZE * 0]; tmp7 = dataptr[DCTSIZE * 7]; tmp10 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 6]; tmp11 = dataptr[DCTSIZE * 1] - wsptr[DCTSIZE * 5]; tmp12 = dataptr[DCTSIZE * 2] - wsptr[DCTSIZE * 4]; tmp13 = dataptr[DCTSIZE * 3] - wsptr[DCTSIZE * 3]; tmp14 = dataptr[DCTSIZE * 4] - wsptr[DCTSIZE * 2]; tmp15 = dataptr[DCTSIZE * 5] - wsptr[DCTSIZE * 1]; tmp16 = dataptr[DCTSIZE * 6] - wsptr[DCTSIZE * 0]; z1 = tmp0 + tmp4 + tmp5; z2 = tmp1 + tmp3 + tmp6; z3 = tmp2 + tmp7; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(z1 + z2 + z3, FIX(1.137777778)), /* 256/225 */ CONST_BITS + 2); z3 += z3; dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(MULTIPLY(z1 - z3, FIX(1.301757503)) - /* c6 */ MULTIPLY(z2 - z3, FIX(0.497227121)), /* c12 */ CONST_BITS + 2); tmp2 += ((tmp1 + tmp4) >> 1) - tmp7 - tmp7; z1 = MULTIPLY(tmp3 - tmp2, FIX(1.742091575)) - /* c2+c14 */ MULTIPLY(tmp6 - tmp2, FIX(2.546621957)); /* c4+c8 */ z2 = MULTIPLY(tmp5 - tmp2, FIX(0.908479156)) - /* c8-c14 */ MULTIPLY(tmp0 - tmp2, FIX(0.103948774)); /* c2-c4 */ z3 = MULTIPLY(tmp0 - tmp3, FIX(1.573898926)) + /* c2 */ MULTIPLY(tmp6 - tmp5, FIX(1.076671805)) + /* c8 */ MULTIPLY(tmp1 - tmp4, FIX(0.899492312)); /* (c6+c12)/2 */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(z1 + z3, CONST_BITS + 2); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(z2 + z3, CONST_BITS + 2); /* Odd part */ tmp2 = MULTIPLY(tmp10 - tmp12 - tmp13 + tmp15 + tmp16, FIX(1.393487498)); /* c5 */ tmp1 = MULTIPLY(tmp10 - tmp14 - tmp15, FIX(1.530307725)) + /* c3 */ MULTIPLY(tmp11 - tmp13 - tmp16, FIX(0.945782187)); /* c9 */ tmp12 = MULTIPLY(tmp12, FIX(1.393487498)); /* c5 */ tmp4 = MULTIPLY(tmp10 - tmp16, FIX(1.600246161)) + /* c1 */ MULTIPLY(tmp11 + tmp14, FIX(1.530307725)) + /* c3 */ MULTIPLY(tmp13 + tmp15, FIX(0.654463974)); /* c11 */ tmp0 = MULTIPLY(tmp13, FIX(0.541301207)) - /* c7-c11 */ MULTIPLY(tmp14, FIX(0.584525538)) + /* c3-c9 */ MULTIPLY(tmp16, FIX(1.934788705)) + tmp4 + tmp12; /* c1+c13 */ tmp3 = MULTIPLY(tmp10, - FIX(0.404480980)) - /* -(c1-c7) */ MULTIPLY(tmp11, FIX(2.476089912)) - /* c3+c9 */ MULTIPLY(tmp15, FIX(0.989006518)) + tmp4 - tmp12; /* c11+c13 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp0, CONST_BITS + 2); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp1, CONST_BITS + 2); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp2, CONST_BITS + 2); dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(tmp3, CONST_BITS + 2); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 16x16 sample block. */ GLOBAL(void) jpeg_fdct_16x16(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16, tmp17; DCTELEM workspace[DCTSIZE2]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* cK represents sqrt(2) * cos(K*pi/32). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[15]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[14]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[13]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[12]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[11]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[10]); tmp6 = GETJSAMPLE(elemptr[6]) + GETJSAMPLE(elemptr[9]); tmp7 = GETJSAMPLE(elemptr[7]) + GETJSAMPLE(elemptr[8]); tmp10 = tmp0 + tmp7; tmp14 = tmp0 - tmp7; tmp11 = tmp1 + tmp6; tmp15 = tmp1 - tmp6; tmp12 = tmp2 + tmp5; tmp16 = tmp2 - tmp5; tmp13 = tmp3 + tmp4; tmp17 = tmp3 - tmp4; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[15]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[14]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[13]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[12]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[11]); tmp5 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[10]); tmp6 = GETJSAMPLE(elemptr[6]) - GETJSAMPLE(elemptr[9]); tmp7 = GETJSAMPLE(elemptr[7]) - GETJSAMPLE(elemptr[8]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 + tmp12 + tmp13 - 16 * CENTERJSAMPLE) << PASS1_BITS); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(1.306562965)) + /* c4[16] = c2[8] */ MULTIPLY(tmp11 - tmp12, FIX_0_541196100), /* c12[16] = c6[8] */ CONST_BITS - PASS1_BITS); tmp10 = MULTIPLY(tmp17 - tmp15, FIX(0.275899379)) + /* c14[16] = c7[8] */ MULTIPLY(tmp14 - tmp16, FIX(1.387039845)); /* c2[16] = c1[8] */ dataptr[2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp15, FIX(1.451774982)) /* c6+c14 */ + MULTIPLY(tmp16, FIX(2.172734804)), /* c2+c10 */ CONST_BITS - PASS1_BITS); dataptr[6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(0.211164243)) /* c2-c6 */ - MULTIPLY(tmp17, FIX(1.061594338)), /* c10+c14 */ CONST_BITS - PASS1_BITS); /* Odd part */ tmp11 = MULTIPLY(tmp0 + tmp1, FIX(1.353318001)) + /* c3 */ MULTIPLY(tmp6 - tmp7, FIX(0.410524528)); /* c13 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(1.247225013)) + /* c5 */ MULTIPLY(tmp5 + tmp7, FIX(0.666655658)); /* c11 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(1.093201867)) + /* c7 */ MULTIPLY(tmp4 - tmp7, FIX(0.897167586)); /* c9 */ tmp14 = MULTIPLY(tmp1 + tmp2, FIX(0.138617169)) + /* c15 */ MULTIPLY(tmp6 - tmp5, FIX(1.407403738)); /* c1 */ tmp15 = MULTIPLY(tmp1 + tmp3, - FIX(0.666655658)) + /* -c11 */ MULTIPLY(tmp4 + tmp6, - FIX(1.247225013)); /* -c5 */ tmp16 = MULTIPLY(tmp2 + tmp3, - FIX(1.353318001)) + /* -c3 */ MULTIPLY(tmp5 - tmp4, FIX(0.410524528)); /* c13 */ tmp10 = tmp11 + tmp12 + tmp13 - MULTIPLY(tmp0, FIX(2.286341144)) + /* c7+c5+c3-c1 */ MULTIPLY(tmp7, FIX(0.779653625)); /* c15+c13-c11+c9 */ tmp11 += tmp14 + tmp15 + MULTIPLY(tmp1, FIX(0.071888074)) /* c9-c3-c15+c11 */ - MULTIPLY(tmp6, FIX(1.663905119)); /* c7+c13+c1-c5 */ tmp12 += tmp14 + tmp16 - MULTIPLY(tmp2, FIX(1.125726048)) /* c7+c5+c15-c3 */ + MULTIPLY(tmp5, FIX(1.227391138)); /* c9-c11+c1-c13 */ tmp13 += tmp15 + tmp16 + MULTIPLY(tmp3, FIX(1.065388962)) /* c15+c3+c11-c7 */ + MULTIPLY(tmp4, FIX(2.167985692)); /* c1+c13+c5-c9 */ dataptr[1] = (DCTELEM) DESCALE(tmp10, CONST_BITS - PASS1_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp11, CONST_BITS - PASS1_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp12, CONST_BITS - PASS1_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp13, CONST_BITS - PASS1_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == DCTSIZE * 2) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/16)**2 = 1/2**2. */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 7]; tmp1 = dataptr[DCTSIZE * 1] + wsptr[DCTSIZE * 6]; tmp2 = dataptr[DCTSIZE * 2] + wsptr[DCTSIZE * 5]; tmp3 = dataptr[DCTSIZE * 3] + wsptr[DCTSIZE * 4]; tmp4 = dataptr[DCTSIZE * 4] + wsptr[DCTSIZE * 3]; tmp5 = dataptr[DCTSIZE * 5] + wsptr[DCTSIZE * 2]; tmp6 = dataptr[DCTSIZE * 6] + wsptr[DCTSIZE * 1]; tmp7 = dataptr[DCTSIZE * 7] + wsptr[DCTSIZE * 0]; tmp10 = tmp0 + tmp7; tmp14 = tmp0 - tmp7; tmp11 = tmp1 + tmp6; tmp15 = tmp1 - tmp6; tmp12 = tmp2 + tmp5; tmp16 = tmp2 - tmp5; tmp13 = tmp3 + tmp4; tmp17 = tmp3 - tmp4; tmp0 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 7]; tmp1 = dataptr[DCTSIZE * 1] - wsptr[DCTSIZE * 6]; tmp2 = dataptr[DCTSIZE * 2] - wsptr[DCTSIZE * 5]; tmp3 = dataptr[DCTSIZE * 3] - wsptr[DCTSIZE * 4]; tmp4 = dataptr[DCTSIZE * 4] - wsptr[DCTSIZE * 3]; tmp5 = dataptr[DCTSIZE * 5] - wsptr[DCTSIZE * 2]; tmp6 = dataptr[DCTSIZE * 6] - wsptr[DCTSIZE * 1]; tmp7 = dataptr[DCTSIZE * 7] - wsptr[DCTSIZE * 0]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(tmp10 + tmp11 + tmp12 + tmp13, PASS1_BITS + 2); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(1.306562965)) + /* c4[16] = c2[8] */ MULTIPLY(tmp11 - tmp12, FIX_0_541196100), /* c12[16] = c6[8] */ CONST_BITS + PASS1_BITS + 2); tmp10 = MULTIPLY(tmp17 - tmp15, FIX(0.275899379)) + /* c14[16] = c7[8] */ MULTIPLY(tmp14 - tmp16, FIX(1.387039845)); /* c2[16] = c1[8] */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp15, FIX(1.451774982)) /* c6+c14 */ + MULTIPLY(tmp16, FIX(2.172734804)), /* c2+10 */ CONST_BITS + PASS1_BITS + 2); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(0.211164243)) /* c2-c6 */ - MULTIPLY(tmp17, FIX(1.061594338)), /* c10+c14 */ CONST_BITS + PASS1_BITS + 2); /* Odd part */ tmp11 = MULTIPLY(tmp0 + tmp1, FIX(1.353318001)) + /* c3 */ MULTIPLY(tmp6 - tmp7, FIX(0.410524528)); /* c13 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(1.247225013)) + /* c5 */ MULTIPLY(tmp5 + tmp7, FIX(0.666655658)); /* c11 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(1.093201867)) + /* c7 */ MULTIPLY(tmp4 - tmp7, FIX(0.897167586)); /* c9 */ tmp14 = MULTIPLY(tmp1 + tmp2, FIX(0.138617169)) + /* c15 */ MULTIPLY(tmp6 - tmp5, FIX(1.407403738)); /* c1 */ tmp15 = MULTIPLY(tmp1 + tmp3, - FIX(0.666655658)) + /* -c11 */ MULTIPLY(tmp4 + tmp6, - FIX(1.247225013)); /* -c5 */ tmp16 = MULTIPLY(tmp2 + tmp3, - FIX(1.353318001)) + /* -c3 */ MULTIPLY(tmp5 - tmp4, FIX(0.410524528)); /* c13 */ tmp10 = tmp11 + tmp12 + tmp13 - MULTIPLY(tmp0, FIX(2.286341144)) + /* c7+c5+c3-c1 */ MULTIPLY(tmp7, FIX(0.779653625)); /* c15+c13-c11+c9 */ tmp11 += tmp14 + tmp15 + MULTIPLY(tmp1, FIX(0.071888074)) /* c9-c3-c15+c11 */ - MULTIPLY(tmp6, FIX(1.663905119)); /* c7+c13+c1-c5 */ tmp12 += tmp14 + tmp16 - MULTIPLY(tmp2, FIX(1.125726048)) /* c7+c5+c15-c3 */ + MULTIPLY(tmp5, FIX(1.227391138)); /* c9-c11+c1-c13 */ tmp13 += tmp15 + tmp16 + MULTIPLY(tmp3, FIX(1.065388962)) /* c15+c3+c11-c7 */ + MULTIPLY(tmp4, FIX(2.167985692)); /* c1+c13+c5-c9 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp10, CONST_BITS + PASS1_BITS + 2); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp11, CONST_BITS + PASS1_BITS + 2); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp12, CONST_BITS + PASS1_BITS + 2); dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(tmp13, CONST_BITS + PASS1_BITS + 2); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 16x8 sample block. * * 16-point FDCT in pass 1 (rows), 8-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_16x8(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16, tmp17; INT32 z1; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* 16-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/32). */ dataptr = data; ctr = 0; for (ctr = 0; ctr < DCTSIZE; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[15]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[14]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[13]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[12]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[11]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[10]); tmp6 = GETJSAMPLE(elemptr[6]) + GETJSAMPLE(elemptr[9]); tmp7 = GETJSAMPLE(elemptr[7]) + GETJSAMPLE(elemptr[8]); tmp10 = tmp0 + tmp7; tmp14 = tmp0 - tmp7; tmp11 = tmp1 + tmp6; tmp15 = tmp1 - tmp6; tmp12 = tmp2 + tmp5; tmp16 = tmp2 - tmp5; tmp13 = tmp3 + tmp4; tmp17 = tmp3 - tmp4; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[15]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[14]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[13]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[12]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[11]); tmp5 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[10]); tmp6 = GETJSAMPLE(elemptr[6]) - GETJSAMPLE(elemptr[9]); tmp7 = GETJSAMPLE(elemptr[7]) - GETJSAMPLE(elemptr[8]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 + tmp12 + tmp13 - 16 * CENTERJSAMPLE) << PASS1_BITS); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(1.306562965)) + /* c4[16] = c2[8] */ MULTIPLY(tmp11 - tmp12, FIX_0_541196100), /* c12[16] = c6[8] */ CONST_BITS - PASS1_BITS); tmp10 = MULTIPLY(tmp17 - tmp15, FIX(0.275899379)) + /* c14[16] = c7[8] */ MULTIPLY(tmp14 - tmp16, FIX(1.387039845)); /* c2[16] = c1[8] */ dataptr[2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp15, FIX(1.451774982)) /* c6+c14 */ + MULTIPLY(tmp16, FIX(2.172734804)), /* c2+c10 */ CONST_BITS - PASS1_BITS); dataptr[6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(0.211164243)) /* c2-c6 */ - MULTIPLY(tmp17, FIX(1.061594338)), /* c10+c14 */ CONST_BITS - PASS1_BITS); /* Odd part */ tmp11 = MULTIPLY(tmp0 + tmp1, FIX(1.353318001)) + /* c3 */ MULTIPLY(tmp6 - tmp7, FIX(0.410524528)); /* c13 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(1.247225013)) + /* c5 */ MULTIPLY(tmp5 + tmp7, FIX(0.666655658)); /* c11 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(1.093201867)) + /* c7 */ MULTIPLY(tmp4 - tmp7, FIX(0.897167586)); /* c9 */ tmp14 = MULTIPLY(tmp1 + tmp2, FIX(0.138617169)) + /* c15 */ MULTIPLY(tmp6 - tmp5, FIX(1.407403738)); /* c1 */ tmp15 = MULTIPLY(tmp1 + tmp3, - FIX(0.666655658)) + /* -c11 */ MULTIPLY(tmp4 + tmp6, - FIX(1.247225013)); /* -c5 */ tmp16 = MULTIPLY(tmp2 + tmp3, - FIX(1.353318001)) + /* -c3 */ MULTIPLY(tmp5 - tmp4, FIX(0.410524528)); /* c13 */ tmp10 = tmp11 + tmp12 + tmp13 - MULTIPLY(tmp0, FIX(2.286341144)) + /* c7+c5+c3-c1 */ MULTIPLY(tmp7, FIX(0.779653625)); /* c15+c13-c11+c9 */ tmp11 += tmp14 + tmp15 + MULTIPLY(tmp1, FIX(0.071888074)) /* c9-c3-c15+c11 */ - MULTIPLY(tmp6, FIX(1.663905119)); /* c7+c13+c1-c5 */ tmp12 += tmp14 + tmp16 - MULTIPLY(tmp2, FIX(1.125726048)) /* c7+c5+c15-c3 */ + MULTIPLY(tmp5, FIX(1.227391138)); /* c9-c11+c1-c13 */ tmp13 += tmp15 + tmp16 + MULTIPLY(tmp3, FIX(1.065388962)) /* c15+c3+c11-c7 */ + MULTIPLY(tmp4, FIX(2.167985692)); /* c1+c13+c5-c9 */ dataptr[1] = (DCTELEM) DESCALE(tmp10, CONST_BITS - PASS1_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp11, CONST_BITS - PASS1_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp12, CONST_BITS - PASS1_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp13, CONST_BITS - PASS1_BITS); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by 8/16 = 1/2. */ dataptr = data; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part per LL&M figure 1 --- note that published figure is faulty; * rotator "sqrt(2)*c1" should be "sqrt(2)*c6". */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 7]; tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 6]; tmp2 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 5]; tmp3 = dataptr[DCTSIZE * 3] + dataptr[DCTSIZE * 4]; tmp10 = tmp0 + tmp3; tmp12 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp13 = tmp1 - tmp2; tmp0 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 7]; tmp1 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 6]; tmp2 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 5]; tmp3 = dataptr[DCTSIZE * 3] - dataptr[DCTSIZE * 4]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS + 1); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS + 1); z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100); dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, FIX_0_765366865), CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(z1 - MULTIPLY(tmp13, FIX_1_847759065), CONST_BITS + PASS1_BITS + 1); /* Odd part per figure 8 --- note paper omits factor of sqrt(2). * 8-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/16). * i0..i3 in the paper are tmp0..tmp3 here. */ tmp10 = tmp0 + tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp0 + tmp2; tmp13 = tmp1 + tmp3; z1 = MULTIPLY(tmp12 + tmp13, FIX_1_175875602); /* c3 */ tmp0 = MULTIPLY(tmp0, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp1 = MULTIPLY(tmp1, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp2 = MULTIPLY(tmp2, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp3 = MULTIPLY(tmp3, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp10 = MULTIPLY(tmp10, - FIX_0_899976223); /* c7-c3 */ tmp11 = MULTIPLY(tmp11, - FIX_2_562915447); /* -c1-c3 */ tmp12 = MULTIPLY(tmp12, - FIX_0_390180644); /* c5-c3 */ tmp13 = MULTIPLY(tmp13, - FIX_1_961570560); /* -c3-c5 */ tmp12 += z1; tmp13 += z1; dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp0 + tmp10 + tmp12, CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp1 + tmp11 + tmp13, CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp2 + tmp11 + tmp12, CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(tmp3 + tmp10 + tmp13, CONST_BITS + PASS1_BITS + 1); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 14x7 sample block. * * 14-point FDCT in pass 1 (rows), 7-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_14x7(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16; INT32 z1, z2, z3; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Zero bottom row of output coefficient block. */ MEMZERO(&data[DCTSIZE * 7], SIZEOF(DCTELEM) * DCTSIZE); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* 14-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/28). */ dataptr = data; for (ctr = 0; ctr < 7; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[13]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[12]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[11]); tmp13 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[10]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[9]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[8]); tmp6 = GETJSAMPLE(elemptr[6]) + GETJSAMPLE(elemptr[7]); tmp10 = tmp0 + tmp6; tmp14 = tmp0 - tmp6; tmp11 = tmp1 + tmp5; tmp15 = tmp1 - tmp5; tmp12 = tmp2 + tmp4; tmp16 = tmp2 - tmp4; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[13]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[12]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[11]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[10]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[9]); tmp5 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[8]); tmp6 = GETJSAMPLE(elemptr[6]) - GETJSAMPLE(elemptr[7]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 + tmp12 + tmp13 - 14 * CENTERJSAMPLE) << PASS1_BITS); tmp13 += tmp13; dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(1.274162392)) + /* c4 */ MULTIPLY(tmp11 - tmp13, FIX(0.314692123)) - /* c12 */ MULTIPLY(tmp12 - tmp13, FIX(0.881747734)), /* c8 */ CONST_BITS - PASS1_BITS); tmp10 = MULTIPLY(tmp14 + tmp15, FIX(1.105676686)); /* c6 */ dataptr[2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp14, FIX(0.273079590)) /* c2-c6 */ + MULTIPLY(tmp16, FIX(0.613604268)), /* c10 */ CONST_BITS - PASS1_BITS); dataptr[6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp15, FIX(1.719280954)) /* c6+c10 */ - MULTIPLY(tmp16, FIX(1.378756276)), /* c2 */ CONST_BITS - PASS1_BITS); /* Odd part */ tmp10 = tmp1 + tmp2; tmp11 = tmp5 - tmp4; dataptr[7] = (DCTELEM)((tmp0 - tmp10 + tmp3 - tmp11 - tmp6) << PASS1_BITS); tmp3 <<= CONST_BITS; tmp10 = MULTIPLY(tmp10, - FIX(0.158341681)); /* -c13 */ tmp11 = MULTIPLY(tmp11, FIX(1.405321284)); /* c1 */ tmp10 += tmp11 - tmp3; tmp11 = MULTIPLY(tmp0 + tmp2, FIX(1.197448846)) + /* c5 */ MULTIPLY(tmp4 + tmp6, FIX(0.752406978)); /* c9 */ dataptr[5] = (DCTELEM) DESCALE(tmp10 + tmp11 - MULTIPLY(tmp2, FIX(2.373959773)) /* c3+c5-c13 */ + MULTIPLY(tmp4, FIX(1.119999435)), /* c1+c11-c9 */ CONST_BITS - PASS1_BITS); tmp12 = MULTIPLY(tmp0 + tmp1, FIX(1.334852607)) + /* c3 */ MULTIPLY(tmp5 - tmp6, FIX(0.467085129)); /* c11 */ dataptr[3] = (DCTELEM) DESCALE(tmp10 + tmp12 - MULTIPLY(tmp1, FIX(0.424103948)) /* c3-c9-c13 */ - MULTIPLY(tmp5, FIX(3.069855259)), /* c1+c5+c11 */ CONST_BITS - PASS1_BITS); dataptr[1] = (DCTELEM) DESCALE(tmp11 + tmp12 + tmp3 + tmp6 - MULTIPLY(tmp0 + tmp6, FIX(1.126980169)), /* c3+c5-c1 */ CONST_BITS - PASS1_BITS); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/14)*(8/7) = 32/49, which we * partially fold into the constant multipliers and final shifting: * 7-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/14) * 64/49. */ dataptr = data; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 6]; tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 5]; tmp2 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 4]; tmp3 = dataptr[DCTSIZE * 3]; tmp10 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 6]; tmp11 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 5]; tmp12 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 4]; z1 = tmp0 + tmp2; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(z1 + tmp1 + tmp3, FIX(1.306122449)), /* 64/49 */ CONST_BITS + PASS1_BITS + 1); tmp3 += tmp3; z1 -= tmp3; z1 -= tmp3; z1 = MULTIPLY(z1, FIX(0.461784020)); /* (c2+c6-c4)/2 */ z2 = MULTIPLY(tmp0 - tmp2, FIX(1.202428084)); /* (c2+c4-c6)/2 */ z3 = MULTIPLY(tmp1 - tmp2, FIX(0.411026446)); /* c6 */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(z1 + z2 + z3, CONST_BITS + PASS1_BITS + 1); z1 -= z2; z2 = MULTIPLY(tmp0 - tmp1, FIX(1.151670509)); /* c4 */ dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(z2 + z3 - MULTIPLY(tmp1 - tmp3, FIX(0.923568041)), /* c2+c6-c4 */ CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(z1 + z2, CONST_BITS + PASS1_BITS + 1); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(1.221765677)); /* (c3+c1-c5)/2 */ tmp2 = MULTIPLY(tmp10 - tmp11, FIX(0.222383464)); /* (c3+c5-c1)/2 */ tmp0 = tmp1 - tmp2; tmp1 += tmp2; tmp2 = MULTIPLY(tmp11 + tmp12, - FIX(1.800824523)); /* -c1 */ tmp1 += tmp2; tmp3 = MULTIPLY(tmp10 + tmp12, FIX(0.801442310)); /* c5 */ tmp0 += tmp3; tmp2 += tmp3 + MULTIPLY(tmp12, FIX(2.443531355)); /* c3+c1-c5 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp0, CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp1, CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp2, CONST_BITS + PASS1_BITS + 1); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 12x6 sample block. * * 12-point FDCT in pass 1 (rows), 6-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_12x6(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Zero 2 bottom rows of output coefficient block. */ MEMZERO(&data[DCTSIZE * 6], SIZEOF(DCTELEM) * DCTSIZE * 2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* 12-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/24). */ dataptr = data; for (ctr = 0; ctr < 6; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[11]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[10]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[9]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[8]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[7]); tmp5 = GETJSAMPLE(elemptr[5]) + GETJSAMPLE(elemptr[6]); tmp10 = tmp0 + tmp5; tmp13 = tmp0 - tmp5; tmp11 = tmp1 + tmp4; tmp14 = tmp1 - tmp4; tmp12 = tmp2 + tmp3; tmp15 = tmp2 - tmp3; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[11]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[10]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[9]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[8]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[7]); tmp5 = GETJSAMPLE(elemptr[5]) - GETJSAMPLE(elemptr[6]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 + tmp12 - 12 * CENTERJSAMPLE) << PASS1_BITS); dataptr[6] = (DCTELEM)((tmp13 - tmp14 - tmp15) << PASS1_BITS); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.224744871)), /* c4 */ CONST_BITS - PASS1_BITS); dataptr[2] = (DCTELEM) DESCALE(tmp14 - tmp15 + MULTIPLY(tmp13 + tmp15, FIX(1.366025404)), /* c2 */ CONST_BITS - PASS1_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp1 + tmp4, FIX_0_541196100); /* c9 */ tmp14 = tmp10 + MULTIPLY(tmp1, FIX_0_765366865); /* c3-c9 */ tmp15 = tmp10 - MULTIPLY(tmp4, FIX_1_847759065); /* c3+c9 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(1.121971054)); /* c5 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(0.860918669)); /* c7 */ tmp10 = tmp12 + tmp13 + tmp14 - MULTIPLY(tmp0, FIX(0.580774953)) /* c5+c7-c1 */ + MULTIPLY(tmp5, FIX(0.184591911)); /* c11 */ tmp11 = MULTIPLY(tmp2 + tmp3, - FIX(0.184591911)); /* -c11 */ tmp12 += tmp11 - tmp15 - MULTIPLY(tmp2, FIX(2.339493912)) /* c1+c5-c11 */ + MULTIPLY(tmp5, FIX(0.860918669)); /* c7 */ tmp13 += tmp11 - tmp14 + MULTIPLY(tmp3, FIX(0.725788011)) /* c1+c11-c7 */ - MULTIPLY(tmp5, FIX(1.121971054)); /* c5 */ tmp11 = tmp15 + MULTIPLY(tmp0 - tmp3, FIX(1.306562965)) /* c3 */ - MULTIPLY(tmp2 + tmp5, FIX_0_541196100); /* c9 */ dataptr[1] = (DCTELEM) DESCALE(tmp10, CONST_BITS - PASS1_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp11, CONST_BITS - PASS1_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp12, CONST_BITS - PASS1_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp13, CONST_BITS - PASS1_BITS); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/12)*(8/6) = 8/9, which we * partially fold into the constant multipliers and final shifting: * 6-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/12) * 16/9. */ dataptr = data; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 5]; tmp11 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 4]; tmp2 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 3]; tmp10 = tmp0 + tmp2; tmp12 = tmp0 - tmp2; tmp0 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 5]; tmp1 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 4]; tmp2 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 3]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(MULTIPLY(tmp12, FIX(2.177324216)), /* c2 */ CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp11, FIX(1.257078722)), /* c4 */ CONST_BITS + PASS1_BITS + 1); /* Odd part */ tmp10 = MULTIPLY(tmp0 + tmp2, FIX(0.650711829)); /* c5 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp0 + tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp1 - tmp2, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp2 - tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS + 1); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 10x5 sample block. * * 10-point FDCT in pass 1 (rows), 5-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_10x5(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4; INT32 tmp10, tmp11, tmp12, tmp13, tmp14; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Zero 3 bottom rows of output coefficient block. */ MEMZERO(&data[DCTSIZE * 5], SIZEOF(DCTELEM) * DCTSIZE * 3); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* 10-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/20). */ dataptr = data; for (ctr = 0; ctr < 5; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[9]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[8]); tmp12 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[7]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[6]); tmp4 = GETJSAMPLE(elemptr[4]) + GETJSAMPLE(elemptr[5]); tmp10 = tmp0 + tmp4; tmp13 = tmp0 - tmp4; tmp11 = tmp1 + tmp3; tmp14 = tmp1 - tmp3; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[9]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[8]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[7]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[6]); tmp4 = GETJSAMPLE(elemptr[4]) - GETJSAMPLE(elemptr[5]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 + tmp12 - 10 * CENTERJSAMPLE) << PASS1_BITS); tmp12 += tmp12; dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.144122806)) - /* c4 */ MULTIPLY(tmp11 - tmp12, FIX(0.437016024)), /* c8 */ CONST_BITS - PASS1_BITS); tmp10 = MULTIPLY(tmp13 + tmp14, FIX(0.831253876)); /* c6 */ dataptr[2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp13, FIX(0.513743148)), /* c2-c6 */ CONST_BITS - PASS1_BITS); dataptr[6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(2.176250899)), /* c2+c6 */ CONST_BITS - PASS1_BITS); /* Odd part */ tmp10 = tmp0 + tmp4; tmp11 = tmp1 - tmp3; dataptr[5] = (DCTELEM)((tmp10 - tmp11 - tmp2) << PASS1_BITS); tmp2 <<= CONST_BITS; dataptr[1] = (DCTELEM) DESCALE(MULTIPLY(tmp0, FIX(1.396802247)) + /* c1 */ MULTIPLY(tmp1, FIX(1.260073511)) + tmp2 + /* c3 */ MULTIPLY(tmp3, FIX(0.642039522)) + /* c7 */ MULTIPLY(tmp4, FIX(0.221231742)), /* c9 */ CONST_BITS - PASS1_BITS); tmp12 = MULTIPLY(tmp0 - tmp4, FIX(0.951056516)) - /* (c3+c7)/2 */ MULTIPLY(tmp1 + tmp3, FIX(0.587785252)); /* (c1-c9)/2 */ tmp13 = MULTIPLY(tmp10 + tmp11, FIX(0.309016994)) + /* (c3-c7)/2 */ (tmp11 << (CONST_BITS - 1)) - tmp2; dataptr[3] = (DCTELEM) DESCALE(tmp12 + tmp13, CONST_BITS - PASS1_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp12 - tmp13, CONST_BITS - PASS1_BITS); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/10)*(8/5) = 32/25, which we * fold into the constant multipliers: * 5-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/10) * 32/25. */ dataptr = data; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 4]; tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 3]; tmp2 = dataptr[DCTSIZE * 2]; tmp10 = tmp0 + tmp1; tmp11 = tmp0 - tmp1; tmp0 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 4]; tmp1 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 3]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp2, FIX(1.28)), /* 32/25 */ CONST_BITS + PASS1_BITS); tmp11 = MULTIPLY(tmp11, FIX(1.011928851)); /* (c2+c4)/2 */ tmp10 -= tmp2 << 2; tmp10 = MULTIPLY(tmp10, FIX(0.452548340)); /* (c2-c4)/2 */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(tmp11 + tmp10, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(tmp11 - tmp10, CONST_BITS + PASS1_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp0 + tmp1, FIX(1.064004961)); /* c3 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp0, FIX(0.657591230)), /* c1-c3 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp1, FIX(2.785601151)), /* c1+c3 */ CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on an 8x4 sample block. * * 8-point FDCT in pass 1 (rows), 4-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_8x4(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3; INT32 tmp10, tmp11, tmp12, tmp13; INT32 z1; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Zero 4 bottom rows of output coefficient block. */ MEMZERO(&data[DCTSIZE * 4], SIZEOF(DCTELEM) * DCTSIZE * 4); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* We must also scale the output by 8/4 = 2, which we add here. */ dataptr = data; for (ctr = 0; ctr < 4; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part per LL&M figure 1 --- note that published figure is faulty; * rotator "sqrt(2)*c1" should be "sqrt(2)*c6". */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[7]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[6]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[5]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[4]); tmp10 = tmp0 + tmp3; tmp12 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp13 = tmp1 - tmp2; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[7]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[6]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[5]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[4]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 - 8 * CENTERJSAMPLE) << (PASS1_BITS + 1)); dataptr[4] = (DCTELEM)((tmp10 - tmp11) << (PASS1_BITS + 1)); z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100); /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS - PASS1_BITS - 2); dataptr[2] = (DCTELEM) RIGHT_SHIFT(z1 + MULTIPLY(tmp12, FIX_0_765366865), CONST_BITS - PASS1_BITS - 1); dataptr[6] = (DCTELEM) RIGHT_SHIFT(z1 - MULTIPLY(tmp13, FIX_1_847759065), CONST_BITS - PASS1_BITS - 1); /* Odd part per figure 8 --- note paper omits factor of sqrt(2). * 8-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/16). * i0..i3 in the paper are tmp0..tmp3 here. */ tmp10 = tmp0 + tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp0 + tmp2; tmp13 = tmp1 + tmp3; z1 = MULTIPLY(tmp12 + tmp13, FIX_1_175875602); /* c3 */ /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS - PASS1_BITS - 2); tmp0 = MULTIPLY(tmp0, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp1 = MULTIPLY(tmp1, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp2 = MULTIPLY(tmp2, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp3 = MULTIPLY(tmp3, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp10 = MULTIPLY(tmp10, - FIX_0_899976223); /* c7-c3 */ tmp11 = MULTIPLY(tmp11, - FIX_2_562915447); /* -c1-c3 */ tmp12 = MULTIPLY(tmp12, - FIX_0_390180644); /* c5-c3 */ tmp13 = MULTIPLY(tmp13, - FIX_1_961570560); /* -c3-c5 */ tmp12 += z1; tmp13 += z1; dataptr[1] = (DCTELEM) RIGHT_SHIFT(tmp0 + tmp10 + tmp12, CONST_BITS - PASS1_BITS - 1); dataptr[3] = (DCTELEM) RIGHT_SHIFT(tmp1 + tmp11 + tmp13, CONST_BITS - PASS1_BITS - 1); dataptr[5] = (DCTELEM) RIGHT_SHIFT(tmp2 + tmp11 + tmp12, CONST_BITS - PASS1_BITS - 1); dataptr[7] = (DCTELEM) RIGHT_SHIFT(tmp3 + tmp10 + tmp13, CONST_BITS - PASS1_BITS - 1); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * 4-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/16). */ dataptr = data; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ /* Add fudge factor here for final descale. */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 3] + (ONE << (PASS1_BITS - 1)); tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 2]; tmp10 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 3]; tmp11 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 2]; dataptr[DCTSIZE * 0] = (DCTELEM) RIGHT_SHIFT(tmp0 + tmp1, PASS1_BITS); dataptr[DCTSIZE * 2] = (DCTELEM) RIGHT_SHIFT(tmp0 - tmp1, PASS1_BITS); /* Odd part */ tmp0 = MULTIPLY(tmp10 + tmp11, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS + PASS1_BITS - 1); dataptr[DCTSIZE * 1] = (DCTELEM) RIGHT_SHIFT(tmp0 + MULTIPLY(tmp10, FIX_0_765366865), /* c2-c6 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 3] = (DCTELEM) RIGHT_SHIFT(tmp0 - MULTIPLY(tmp11, FIX_1_847759065), /* c2+c6 */ CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 6x3 sample block. * * 6-point FDCT in pass 1 (rows), 3-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_6x3(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2; INT32 tmp10, tmp11, tmp12; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* We scale the results further by 2 as part of output adaption */ /* scaling for different DCT size. */ /* 6-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/12). */ dataptr = data; for (ctr = 0; ctr < 3; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[5]); tmp11 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[4]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[3]); tmp10 = tmp0 + tmp2; tmp12 = tmp0 - tmp2; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[5]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[4]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[3]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 - 6 * CENTERJSAMPLE) << (PASS1_BITS + 1)); dataptr[2] = (DCTELEM) DESCALE(MULTIPLY(tmp12, FIX(1.224744871)), /* c2 */ CONST_BITS - PASS1_BITS - 1); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp11, FIX(0.707106781)), /* c4 */ CONST_BITS - PASS1_BITS - 1); /* Odd part */ tmp10 = DESCALE(MULTIPLY(tmp0 + tmp2, FIX(0.366025404)), /* c5 */ CONST_BITS - PASS1_BITS - 1); dataptr[1] = (DCTELEM)(tmp10 + ((tmp0 + tmp1) << (PASS1_BITS + 1))); dataptr[3] = (DCTELEM)((tmp0 - tmp1 - tmp2) << (PASS1_BITS + 1)); dataptr[5] = (DCTELEM)(tmp10 + ((tmp2 - tmp1) << (PASS1_BITS + 1))); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/6)*(8/3) = 32/9, which we partially * fold into the constant multipliers (other part was done in pass 1): * 3-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/6) * 16/9. */ dataptr = data; for (ctr = 0; ctr < 6; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 2]; tmp1 = dataptr[DCTSIZE * 1]; tmp2 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 2]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp0 + tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp1 - tmp1, FIX(1.257078722)), /* c2 */ CONST_BITS + PASS1_BITS); /* Odd part */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(MULTIPLY(tmp2, FIX(2.177324216)), /* c1 */ CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 4x2 sample block. * * 4-point FDCT in pass 1 (rows), 2-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_4x2(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1; INT32 tmp10, tmp11; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* We must also scale the output by (8/4)*(8/2) = 2**3, which we add here. */ /* 4-point FDCT kernel, */ /* cK represents sqrt(2) * cos(K*pi/16) [refers to 8-point FDCT]. */ dataptr = data; for (ctr = 0; ctr < 2; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[3]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[2]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[3]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[2]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp0 + tmp1 - 4 * CENTERJSAMPLE) << (PASS1_BITS + 3)); dataptr[2] = (DCTELEM)((tmp0 - tmp1) << (PASS1_BITS + 3)); /* Odd part */ tmp0 = MULTIPLY(tmp10 + tmp11, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS - PASS1_BITS - 4); dataptr[1] = (DCTELEM) RIGHT_SHIFT(tmp0 + MULTIPLY(tmp10, FIX_0_765366865), /* c2-c6 */ CONST_BITS - PASS1_BITS - 3); dataptr[3] = (DCTELEM) RIGHT_SHIFT(tmp0 - MULTIPLY(tmp11, FIX_1_847759065), /* c2+c6 */ CONST_BITS - PASS1_BITS - 3); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. */ dataptr = data; for (ctr = 0; ctr < 4; ctr++) { /* Even part */ /* Add fudge factor here for final descale. */ tmp0 = dataptr[DCTSIZE * 0] + (ONE << (PASS1_BITS - 1)); tmp1 = dataptr[DCTSIZE * 1]; dataptr[DCTSIZE * 0] = (DCTELEM) RIGHT_SHIFT(tmp0 + tmp1, PASS1_BITS); /* Odd part */ dataptr[DCTSIZE * 1] = (DCTELEM) RIGHT_SHIFT(tmp0 - tmp1, PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 2x1 sample block. * * 2-point FDCT in pass 1 (rows), 1-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_2x1(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1; JSAMPROW elemptr; /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); elemptr = sample_data[0] + start_col; tmp0 = GETJSAMPLE(elemptr[0]); tmp1 = GETJSAMPLE(elemptr[1]); /* We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/2)*(8/1) = 2**5. */ /* Even part */ /* Apply unsigned->signed conversion */ data[0] = (DCTELEM)((tmp0 + tmp1 - 2 * CENTERJSAMPLE) << 5); /* Odd part */ data[1] = (DCTELEM)((tmp0 - tmp1) << 5); } /* * Perform the forward DCT on an 8x16 sample block. * * 8-point FDCT in pass 1 (rows), 16-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_8x16(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16, tmp17; INT32 z1; DCTELEM workspace[DCTSIZE2]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part per LL&M figure 1 --- note that published figure is faulty; * rotator "sqrt(2)*c1" should be "sqrt(2)*c6". */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[7]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[6]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[5]); tmp3 = GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[4]); tmp10 = tmp0 + tmp3; tmp12 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp13 = tmp1 - tmp2; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[7]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[6]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[5]); tmp3 = GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[4]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM)((tmp10 + tmp11 - 8 * CENTERJSAMPLE) << PASS1_BITS); dataptr[4] = (DCTELEM)((tmp10 - tmp11) << PASS1_BITS); z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100); dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, FIX_0_765366865), CONST_BITS - PASS1_BITS); dataptr[6] = (DCTELEM) DESCALE(z1 - MULTIPLY(tmp13, FIX_1_847759065), CONST_BITS - PASS1_BITS); /* Odd part per figure 8 --- note paper omits factor of sqrt(2). * 8-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/16). * i0..i3 in the paper are tmp0..tmp3 here. */ tmp10 = tmp0 + tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp0 + tmp2; tmp13 = tmp1 + tmp3; z1 = MULTIPLY(tmp12 + tmp13, FIX_1_175875602); /* c3 */ tmp0 = MULTIPLY(tmp0, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp1 = MULTIPLY(tmp1, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp2 = MULTIPLY(tmp2, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp3 = MULTIPLY(tmp3, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp10 = MULTIPLY(tmp10, - FIX_0_899976223); /* c7-c3 */ tmp11 = MULTIPLY(tmp11, - FIX_2_562915447); /* -c1-c3 */ tmp12 = MULTIPLY(tmp12, - FIX_0_390180644); /* c5-c3 */ tmp13 = MULTIPLY(tmp13, - FIX_1_961570560); /* -c3-c5 */ tmp12 += z1; tmp13 += z1; dataptr[1] = (DCTELEM) DESCALE(tmp0 + tmp10 + tmp12, CONST_BITS - PASS1_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp1 + tmp11 + tmp13, CONST_BITS - PASS1_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp2 + tmp11 + tmp12, CONST_BITS - PASS1_BITS); dataptr[7] = (DCTELEM) DESCALE(tmp3 + tmp10 + tmp13, CONST_BITS - PASS1_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == DCTSIZE * 2) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by 8/16 = 1/2. * 16-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/32). */ dataptr = data; wsptr = workspace; for (ctr = DCTSIZE - 1; ctr >= 0; ctr--) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 7]; tmp1 = dataptr[DCTSIZE * 1] + wsptr[DCTSIZE * 6]; tmp2 = dataptr[DCTSIZE * 2] + wsptr[DCTSIZE * 5]; tmp3 = dataptr[DCTSIZE * 3] + wsptr[DCTSIZE * 4]; tmp4 = dataptr[DCTSIZE * 4] + wsptr[DCTSIZE * 3]; tmp5 = dataptr[DCTSIZE * 5] + wsptr[DCTSIZE * 2]; tmp6 = dataptr[DCTSIZE * 6] + wsptr[DCTSIZE * 1]; tmp7 = dataptr[DCTSIZE * 7] + wsptr[DCTSIZE * 0]; tmp10 = tmp0 + tmp7; tmp14 = tmp0 - tmp7; tmp11 = tmp1 + tmp6; tmp15 = tmp1 - tmp6; tmp12 = tmp2 + tmp5; tmp16 = tmp2 - tmp5; tmp13 = tmp3 + tmp4; tmp17 = tmp3 - tmp4; tmp0 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 7]; tmp1 = dataptr[DCTSIZE * 1] - wsptr[DCTSIZE * 6]; tmp2 = dataptr[DCTSIZE * 2] - wsptr[DCTSIZE * 5]; tmp3 = dataptr[DCTSIZE * 3] - wsptr[DCTSIZE * 4]; tmp4 = dataptr[DCTSIZE * 4] - wsptr[DCTSIZE * 3]; tmp5 = dataptr[DCTSIZE * 5] - wsptr[DCTSIZE * 2]; tmp6 = dataptr[DCTSIZE * 6] - wsptr[DCTSIZE * 1]; tmp7 = dataptr[DCTSIZE * 7] - wsptr[DCTSIZE * 0]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(tmp10 + tmp11 + tmp12 + tmp13, PASS1_BITS + 1); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(1.306562965)) + /* c4[16] = c2[8] */ MULTIPLY(tmp11 - tmp12, FIX_0_541196100), /* c12[16] = c6[8] */ CONST_BITS + PASS1_BITS + 1); tmp10 = MULTIPLY(tmp17 - tmp15, FIX(0.275899379)) + /* c14[16] = c7[8] */ MULTIPLY(tmp14 - tmp16, FIX(1.387039845)); /* c2[16] = c1[8] */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp15, FIX(1.451774982)) /* c6+c14 */ + MULTIPLY(tmp16, FIX(2.172734804)), /* c2+c10 */ CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(0.211164243)) /* c2-c6 */ - MULTIPLY(tmp17, FIX(1.061594338)), /* c10+c14 */ CONST_BITS + PASS1_BITS + 1); /* Odd part */ tmp11 = MULTIPLY(tmp0 + tmp1, FIX(1.353318001)) + /* c3 */ MULTIPLY(tmp6 - tmp7, FIX(0.410524528)); /* c13 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(1.247225013)) + /* c5 */ MULTIPLY(tmp5 + tmp7, FIX(0.666655658)); /* c11 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(1.093201867)) + /* c7 */ MULTIPLY(tmp4 - tmp7, FIX(0.897167586)); /* c9 */ tmp14 = MULTIPLY(tmp1 + tmp2, FIX(0.138617169)) + /* c15 */ MULTIPLY(tmp6 - tmp5, FIX(1.407403738)); /* c1 */ tmp15 = MULTIPLY(tmp1 + tmp3, - FIX(0.666655658)) + /* -c11 */ MULTIPLY(tmp4 + tmp6, - FIX(1.247225013)); /* -c5 */ tmp16 = MULTIPLY(tmp2 + tmp3, - FIX(1.353318001)) + /* -c3 */ MULTIPLY(tmp5 - tmp4, FIX(0.410524528)); /* c13 */ tmp10 = tmp11 + tmp12 + tmp13 - MULTIPLY(tmp0, FIX(2.286341144)) + /* c7+c5+c3-c1 */ MULTIPLY(tmp7, FIX(0.779653625)); /* c15+c13-c11+c9 */ tmp11 += tmp14 + tmp15 + MULTIPLY(tmp1, FIX(0.071888074)) /* c9-c3-c15+c11 */ - MULTIPLY(tmp6, FIX(1.663905119)); /* c7+c13+c1-c5 */ tmp12 += tmp14 + tmp16 - MULTIPLY(tmp2, FIX(1.125726048)) /* c7+c5+c15-c3 */ + MULTIPLY(tmp5, FIX(1.227391138)); /* c9-c11+c1-c13 */ tmp13 += tmp15 + tmp16 + MULTIPLY(tmp3, FIX(1.065388962)) /* c15+c3+c11-c7 */ + MULTIPLY(tmp4, FIX(2.167985692)); /* c1+c13+c5-c9 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp10, CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp11, CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp12, CONST_BITS + PASS1_BITS + 1); dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(tmp13, CONST_BITS + PASS1_BITS + 1); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 7x14 sample block. * * 7-point FDCT in pass 1 (rows), 14-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_7x14(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16; INT32 z1, z2, z3; DCTELEM workspace[8 * 6]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* 7-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/14). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[6]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[5]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[4]); tmp3 = GETJSAMPLE(elemptr[3]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[6]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[5]); tmp12 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[4]); z1 = tmp0 + tmp2; /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((z1 + tmp1 + tmp3 - 7 * CENTERJSAMPLE) << PASS1_BITS); tmp3 += tmp3; z1 -= tmp3; z1 -= tmp3; z1 = MULTIPLY(z1, FIX(0.353553391)); /* (c2+c6-c4)/2 */ z2 = MULTIPLY(tmp0 - tmp2, FIX(0.920609002)); /* (c2+c4-c6)/2 */ z3 = MULTIPLY(tmp1 - tmp2, FIX(0.314692123)); /* c6 */ dataptr[2] = (DCTELEM) DESCALE(z1 + z2 + z3, CONST_BITS - PASS1_BITS); z1 -= z2; z2 = MULTIPLY(tmp0 - tmp1, FIX(0.881747734)); /* c4 */ dataptr[4] = (DCTELEM) DESCALE(z2 + z3 - MULTIPLY(tmp1 - tmp3, FIX(0.707106781)), /* c2+c6-c4 */ CONST_BITS - PASS1_BITS); dataptr[6] = (DCTELEM) DESCALE(z1 + z2, CONST_BITS - PASS1_BITS); /* Odd part */ tmp1 = MULTIPLY(tmp10 + tmp11, FIX(0.935414347)); /* (c3+c1-c5)/2 */ tmp2 = MULTIPLY(tmp10 - tmp11, FIX(0.170262339)); /* (c3+c5-c1)/2 */ tmp0 = tmp1 - tmp2; tmp1 += tmp2; tmp2 = MULTIPLY(tmp11 + tmp12, - FIX(1.378756276)); /* -c1 */ tmp1 += tmp2; tmp3 = MULTIPLY(tmp10 + tmp12, FIX(0.613604268)); /* c5 */ tmp0 += tmp3; tmp2 += tmp3 + MULTIPLY(tmp12, FIX(1.870828693)); /* c3+c1-c5 */ dataptr[1] = (DCTELEM) DESCALE(tmp0, CONST_BITS - PASS1_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp1, CONST_BITS - PASS1_BITS); dataptr[5] = (DCTELEM) DESCALE(tmp2, CONST_BITS - PASS1_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == 14) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/7)*(8/14) = 32/49, which we * fold into the constant multipliers: * 14-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/28) * 32/49. */ dataptr = data; wsptr = workspace; for (ctr = 0; ctr < 7; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 5]; tmp1 = dataptr[DCTSIZE * 1] + wsptr[DCTSIZE * 4]; tmp2 = dataptr[DCTSIZE * 2] + wsptr[DCTSIZE * 3]; tmp13 = dataptr[DCTSIZE * 3] + wsptr[DCTSIZE * 2]; tmp4 = dataptr[DCTSIZE * 4] + wsptr[DCTSIZE * 1]; tmp5 = dataptr[DCTSIZE * 5] + wsptr[DCTSIZE * 0]; tmp6 = dataptr[DCTSIZE * 6] + dataptr[DCTSIZE * 7]; tmp10 = tmp0 + tmp6; tmp14 = tmp0 - tmp6; tmp11 = tmp1 + tmp5; tmp15 = tmp1 - tmp5; tmp12 = tmp2 + tmp4; tmp16 = tmp2 - tmp4; tmp0 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 5]; tmp1 = dataptr[DCTSIZE * 1] - wsptr[DCTSIZE * 4]; tmp2 = dataptr[DCTSIZE * 2] - wsptr[DCTSIZE * 3]; tmp3 = dataptr[DCTSIZE * 3] - wsptr[DCTSIZE * 2]; tmp4 = dataptr[DCTSIZE * 4] - wsptr[DCTSIZE * 1]; tmp5 = dataptr[DCTSIZE * 5] - wsptr[DCTSIZE * 0]; tmp6 = dataptr[DCTSIZE * 6] - dataptr[DCTSIZE * 7]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11 + tmp12 + tmp13, FIX(0.653061224)), /* 32/49 */ CONST_BITS + PASS1_BITS); tmp13 += tmp13; dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp13, FIX(0.832106052)) + /* c4 */ MULTIPLY(tmp11 - tmp13, FIX(0.205513223)) - /* c12 */ MULTIPLY(tmp12 - tmp13, FIX(0.575835255)), /* c8 */ CONST_BITS + PASS1_BITS); tmp10 = MULTIPLY(tmp14 + tmp15, FIX(0.722074570)); /* c6 */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp14, FIX(0.178337691)) /* c2-c6 */ + MULTIPLY(tmp16, FIX(0.400721155)), /* c10 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp15, FIX(1.122795725)) /* c6+c10 */ - MULTIPLY(tmp16, FIX(0.900412262)), /* c2 */ CONST_BITS + PASS1_BITS); /* Odd part */ tmp10 = tmp1 + tmp2; tmp11 = tmp5 - tmp4; dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp10 + tmp3 - tmp11 - tmp6, FIX(0.653061224)), /* 32/49 */ CONST_BITS + PASS1_BITS); tmp3 = MULTIPLY(tmp3 , FIX(0.653061224)); /* 32/49 */ tmp10 = MULTIPLY(tmp10, - FIX(0.103406812)); /* -c13 */ tmp11 = MULTIPLY(tmp11, FIX(0.917760839)); /* c1 */ tmp10 += tmp11 - tmp3; tmp11 = MULTIPLY(tmp0 + tmp2, FIX(0.782007410)) + /* c5 */ MULTIPLY(tmp4 + tmp6, FIX(0.491367823)); /* c9 */ dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp10 + tmp11 - MULTIPLY(tmp2, FIX(1.550341076)) /* c3+c5-c13 */ + MULTIPLY(tmp4, FIX(0.731428202)), /* c1+c11-c9 */ CONST_BITS + PASS1_BITS); tmp12 = MULTIPLY(tmp0 + tmp1, FIX(0.871740478)) + /* c3 */ MULTIPLY(tmp5 - tmp6, FIX(0.305035186)); /* c11 */ dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp10 + tmp12 - MULTIPLY(tmp1, FIX(0.276965844)) /* c3-c9-c13 */ - MULTIPLY(tmp5, FIX(2.004803435)), /* c1+c5+c11 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp11 + tmp12 + tmp3 - MULTIPLY(tmp0, FIX(0.735987049)) /* c3+c5-c1 */ - MULTIPLY(tmp6, FIX(0.082925825)), /* c9-c11-c13 */ CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 6x12 sample block. * * 6-point FDCT in pass 1 (rows), 12-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_6x12(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5; INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15; DCTELEM workspace[8 * 4]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* 6-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/12). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[5]); tmp11 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[4]); tmp2 = GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[3]); tmp10 = tmp0 + tmp2; tmp12 = tmp0 - tmp2; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[5]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[4]); tmp2 = GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[3]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp11 - 6 * CENTERJSAMPLE) << PASS1_BITS); dataptr[2] = (DCTELEM) DESCALE(MULTIPLY(tmp12, FIX(1.224744871)), /* c2 */ CONST_BITS - PASS1_BITS); dataptr[4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp11, FIX(0.707106781)), /* c4 */ CONST_BITS - PASS1_BITS); /* Odd part */ tmp10 = DESCALE(MULTIPLY(tmp0 + tmp2, FIX(0.366025404)), /* c5 */ CONST_BITS - PASS1_BITS); dataptr[1] = (DCTELEM)(tmp10 + ((tmp0 + tmp1) << PASS1_BITS)); dataptr[3] = (DCTELEM)((tmp0 - tmp1 - tmp2) << PASS1_BITS); dataptr[5] = (DCTELEM)(tmp10 + ((tmp2 - tmp1) << PASS1_BITS)); ctr++; if (ctr != DCTSIZE) { if (ctr == 12) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/6)*(8/12) = 8/9, which we * fold into the constant multipliers: * 12-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/24) * 8/9. */ dataptr = data; wsptr = workspace; for (ctr = 0; ctr < 6; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 3]; tmp1 = dataptr[DCTSIZE * 1] + wsptr[DCTSIZE * 2]; tmp2 = dataptr[DCTSIZE * 2] + wsptr[DCTSIZE * 1]; tmp3 = dataptr[DCTSIZE * 3] + wsptr[DCTSIZE * 0]; tmp4 = dataptr[DCTSIZE * 4] + dataptr[DCTSIZE * 7]; tmp5 = dataptr[DCTSIZE * 5] + dataptr[DCTSIZE * 6]; tmp10 = tmp0 + tmp5; tmp13 = tmp0 - tmp5; tmp11 = tmp1 + tmp4; tmp14 = tmp1 - tmp4; tmp12 = tmp2 + tmp3; tmp15 = tmp2 - tmp3; tmp0 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 3]; tmp1 = dataptr[DCTSIZE * 1] - wsptr[DCTSIZE * 2]; tmp2 = dataptr[DCTSIZE * 2] - wsptr[DCTSIZE * 1]; tmp3 = dataptr[DCTSIZE * 3] - wsptr[DCTSIZE * 0]; tmp4 = dataptr[DCTSIZE * 4] - dataptr[DCTSIZE * 7]; tmp5 = dataptr[DCTSIZE * 5] - dataptr[DCTSIZE * 6]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11 + tmp12, FIX(0.888888889)), /* 8/9 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(MULTIPLY(tmp13 - tmp14 - tmp15, FIX(0.888888889)), /* 8/9 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.088662108)), /* c4 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(MULTIPLY(tmp14 - tmp15, FIX(0.888888889)) + /* 8/9 */ MULTIPLY(tmp13 + tmp15, FIX(1.214244803)), /* c2 */ CONST_BITS + PASS1_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp1 + tmp4, FIX(0.481063200)); /* c9 */ tmp14 = tmp10 + MULTIPLY(tmp1, FIX(0.680326102)); /* c3-c9 */ tmp15 = tmp10 - MULTIPLY(tmp4, FIX(1.642452502)); /* c3+c9 */ tmp12 = MULTIPLY(tmp0 + tmp2, FIX(0.997307603)); /* c5 */ tmp13 = MULTIPLY(tmp0 + tmp3, FIX(0.765261039)); /* c7 */ tmp10 = tmp12 + tmp13 + tmp14 - MULTIPLY(tmp0, FIX(0.516244403)) /* c5+c7-c1 */ + MULTIPLY(tmp5, FIX(0.164081699)); /* c11 */ tmp11 = MULTIPLY(tmp2 + tmp3, - FIX(0.164081699)); /* -c11 */ tmp12 += tmp11 - tmp15 - MULTIPLY(tmp2, FIX(2.079550144)) /* c1+c5-c11 */ + MULTIPLY(tmp5, FIX(0.765261039)); /* c7 */ tmp13 += tmp11 - tmp14 + MULTIPLY(tmp3, FIX(0.645144899)) /* c1+c11-c7 */ - MULTIPLY(tmp5, FIX(0.997307603)); /* c5 */ tmp11 = tmp15 + MULTIPLY(tmp0 - tmp3, FIX(1.161389302)) /* c3 */ - MULTIPLY(tmp2 + tmp5, FIX(0.481063200)); /* c9 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp10, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp11, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp12, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(tmp13, CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 5x10 sample block. * * 5-point FDCT in pass 1 (rows), 10-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_5x10(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3, tmp4; INT32 tmp10, tmp11, tmp12, tmp13, tmp14; DCTELEM workspace[8 * 2]; DCTELEM* dataptr; DCTELEM* wsptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* 5-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/10). */ dataptr = data; ctr = 0; for (;;) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[4]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[3]); tmp2 = GETJSAMPLE(elemptr[2]); tmp10 = tmp0 + tmp1; tmp11 = tmp0 - tmp1; tmp0 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[4]); tmp1 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[3]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp10 + tmp2 - 5 * CENTERJSAMPLE) << PASS1_BITS); tmp11 = MULTIPLY(tmp11, FIX(0.790569415)); /* (c2+c4)/2 */ tmp10 -= tmp2 << 2; tmp10 = MULTIPLY(tmp10, FIX(0.353553391)); /* (c2-c4)/2 */ dataptr[2] = (DCTELEM) DESCALE(tmp11 + tmp10, CONST_BITS - PASS1_BITS); dataptr[4] = (DCTELEM) DESCALE(tmp11 - tmp10, CONST_BITS - PASS1_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp0 + tmp1, FIX(0.831253876)); /* c3 */ dataptr[1] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp0, FIX(0.513743148)), /* c1-c3 */ CONST_BITS - PASS1_BITS); dataptr[3] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp1, FIX(2.176250899)), /* c1+c3 */ CONST_BITS - PASS1_BITS); ctr++; if (ctr != DCTSIZE) { if (ctr == 10) { break; /* Done. */ } dataptr += DCTSIZE; /* advance pointer to next row */ } else { dataptr = workspace; /* switch pointer to extended workspace */ } } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/5)*(8/10) = 32/25, which we * fold into the constant multipliers: * 10-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/20) * 32/25. */ dataptr = data; wsptr = workspace; for (ctr = 0; ctr < 5; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + wsptr[DCTSIZE * 1]; tmp1 = dataptr[DCTSIZE * 1] + wsptr[DCTSIZE * 0]; tmp12 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 7]; tmp3 = dataptr[DCTSIZE * 3] + dataptr[DCTSIZE * 6]; tmp4 = dataptr[DCTSIZE * 4] + dataptr[DCTSIZE * 5]; tmp10 = tmp0 + tmp4; tmp13 = tmp0 - tmp4; tmp11 = tmp1 + tmp3; tmp14 = tmp1 - tmp3; tmp0 = dataptr[DCTSIZE * 0] - wsptr[DCTSIZE * 1]; tmp1 = dataptr[DCTSIZE * 1] - wsptr[DCTSIZE * 0]; tmp2 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 7]; tmp3 = dataptr[DCTSIZE * 3] - dataptr[DCTSIZE * 6]; tmp4 = dataptr[DCTSIZE * 4] - dataptr[DCTSIZE * 5]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11 + tmp12, FIX(1.28)), /* 32/25 */ CONST_BITS + PASS1_BITS); tmp12 += tmp12; dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp12, FIX(1.464477191)) - /* c4 */ MULTIPLY(tmp11 - tmp12, FIX(0.559380511)), /* c8 */ CONST_BITS + PASS1_BITS); tmp10 = MULTIPLY(tmp13 + tmp14, FIX(1.064004961)); /* c6 */ dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp13, FIX(0.657591230)), /* c2-c6 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 6] = (DCTELEM) DESCALE(tmp10 - MULTIPLY(tmp14, FIX(2.785601151)), /* c2+c6 */ CONST_BITS + PASS1_BITS); /* Odd part */ tmp10 = tmp0 + tmp4; tmp11 = tmp1 - tmp3; dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp2, FIX(1.28)), /* 32/25 */ CONST_BITS + PASS1_BITS); tmp2 = MULTIPLY(tmp2, FIX(1.28)); /* 32/25 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(MULTIPLY(tmp0, FIX(1.787906876)) + /* c1 */ MULTIPLY(tmp1, FIX(1.612894094)) + tmp2 + /* c3 */ MULTIPLY(tmp3, FIX(0.821810588)) + /* c7 */ MULTIPLY(tmp4, FIX(0.283176630)), /* c9 */ CONST_BITS + PASS1_BITS); tmp12 = MULTIPLY(tmp0 - tmp4, FIX(1.217352341)) - /* (c3+c7)/2 */ MULTIPLY(tmp1 + tmp3, FIX(0.752365123)); /* (c1-c9)/2 */ tmp13 = MULTIPLY(tmp10 + tmp11, FIX(0.395541753)) + /* (c3-c7)/2 */ MULTIPLY(tmp11, FIX(0.64)) - tmp2; /* 16/25 */ dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(tmp12 + tmp13, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 7] = (DCTELEM) DESCALE(tmp12 - tmp13, CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ wsptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 4x8 sample block. * * 4-point FDCT in pass 1 (rows), 8-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_4x8(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2, tmp3; INT32 tmp10, tmp11, tmp12, tmp13; INT32 z1; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* We must also scale the output by 8/4 = 2, which we add here. */ /* 4-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/16). */ dataptr = data; for (ctr = 0; ctr < DCTSIZE; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[3]); tmp1 = GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[2]); tmp10 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[3]); tmp11 = GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[2]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp0 + tmp1 - 4 * CENTERJSAMPLE) << (PASS1_BITS + 1)); dataptr[2] = (DCTELEM)((tmp0 - tmp1) << (PASS1_BITS + 1)); /* Odd part */ tmp0 = MULTIPLY(tmp10 + tmp11, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS - PASS1_BITS - 2); dataptr[1] = (DCTELEM) RIGHT_SHIFT(tmp0 + MULTIPLY(tmp10, FIX_0_765366865), /* c2-c6 */ CONST_BITS - PASS1_BITS - 1); dataptr[3] = (DCTELEM) RIGHT_SHIFT(tmp0 - MULTIPLY(tmp11, FIX_1_847759065), /* c2+c6 */ CONST_BITS - PASS1_BITS - 1); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. */ dataptr = data; for (ctr = 0; ctr < 4; ctr++) { /* Even part per LL&M figure 1 --- note that published figure is faulty; * rotator "sqrt(2)*c1" should be "sqrt(2)*c6". */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 7]; tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 6]; tmp2 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 5]; tmp3 = dataptr[DCTSIZE * 3] + dataptr[DCTSIZE * 4]; /* Add fudge factor here for final descale. */ tmp10 = tmp0 + tmp3 + (ONE << (PASS1_BITS - 1)); tmp12 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp13 = tmp1 - tmp2; tmp0 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 7]; tmp1 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 6]; tmp2 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 5]; tmp3 = dataptr[DCTSIZE * 3] - dataptr[DCTSIZE * 4]; dataptr[DCTSIZE * 0] = (DCTELEM) RIGHT_SHIFT(tmp10 + tmp11, PASS1_BITS); dataptr[DCTSIZE * 4] = (DCTELEM) RIGHT_SHIFT(tmp10 - tmp11, PASS1_BITS); z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100); /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS + PASS1_BITS - 1); dataptr[DCTSIZE * 2] = (DCTELEM) RIGHT_SHIFT(z1 + MULTIPLY(tmp12, FIX_0_765366865), CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 6] = (DCTELEM) RIGHT_SHIFT(z1 - MULTIPLY(tmp13, FIX_1_847759065), CONST_BITS + PASS1_BITS); /* Odd part per figure 8 --- note paper omits factor of sqrt(2). * 8-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/16). * i0..i3 in the paper are tmp0..tmp3 here. */ tmp10 = tmp0 + tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp0 + tmp2; tmp13 = tmp1 + tmp3; z1 = MULTIPLY(tmp12 + tmp13, FIX_1_175875602); /* c3 */ /* Add fudge factor here for final descale. */ z1 += ONE << (CONST_BITS + PASS1_BITS - 1); tmp0 = MULTIPLY(tmp0, FIX_1_501321110); /* c1+c3-c5-c7 */ tmp1 = MULTIPLY(tmp1, FIX_3_072711026); /* c1+c3+c5-c7 */ tmp2 = MULTIPLY(tmp2, FIX_2_053119869); /* c1+c3-c5+c7 */ tmp3 = MULTIPLY(tmp3, FIX_0_298631336); /* -c1+c3+c5-c7 */ tmp10 = MULTIPLY(tmp10, - FIX_0_899976223); /* c7-c3 */ tmp11 = MULTIPLY(tmp11, - FIX_2_562915447); /* -c1-c3 */ tmp12 = MULTIPLY(tmp12, - FIX_0_390180644); /* c5-c3 */ tmp13 = MULTIPLY(tmp13, - FIX_1_961570560); /* -c3-c5 */ tmp12 += z1; tmp13 += z1; dataptr[DCTSIZE * 1] = (DCTELEM) RIGHT_SHIFT(tmp0 + tmp10 + tmp12, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 3] = (DCTELEM) RIGHT_SHIFT(tmp1 + tmp11 + tmp13, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 5] = (DCTELEM) RIGHT_SHIFT(tmp2 + tmp11 + tmp12, CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 7] = (DCTELEM) RIGHT_SHIFT(tmp3 + tmp10 + tmp13, CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 3x6 sample block. * * 3-point FDCT in pass 1 (rows), 6-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_3x6(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1, tmp2; INT32 tmp10, tmp11, tmp12; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT; */ /* furthermore, we scale the results by 2**PASS1_BITS. */ /* We scale the results further by 2 as part of output adaption */ /* scaling for different DCT size. */ /* 3-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/6). */ dataptr = data; for (ctr = 0; ctr < 6; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[2]); tmp1 = GETJSAMPLE(elemptr[1]); tmp2 = GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[2]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM) ((tmp0 + tmp1 - 3 * CENTERJSAMPLE) << (PASS1_BITS + 1)); dataptr[2] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp1 - tmp1, FIX(0.707106781)), /* c2 */ CONST_BITS - PASS1_BITS - 1); /* Odd part */ dataptr[1] = (DCTELEM) DESCALE(MULTIPLY(tmp2, FIX(1.224744871)), /* c1 */ CONST_BITS - PASS1_BITS - 1); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We remove the PASS1_BITS scaling, but leave the results scaled up * by an overall factor of 8. * We must also scale the output by (8/6)*(8/3) = 32/9, which we partially * fold into the constant multipliers (other part was done in pass 1): * 6-point FDCT kernel, cK represents sqrt(2) * cos(K*pi/12) * 16/9. */ dataptr = data; for (ctr = 0; ctr < 3; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 5]; tmp11 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 4]; tmp2 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 3]; tmp10 = tmp0 + tmp2; tmp12 = tmp0 - tmp2; tmp0 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 5]; tmp1 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 4]; tmp2 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 3]; dataptr[DCTSIZE * 0] = (DCTELEM) DESCALE(MULTIPLY(tmp10 + tmp11, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 2] = (DCTELEM) DESCALE(MULTIPLY(tmp12, FIX(2.177324216)), /* c2 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 4] = (DCTELEM) DESCALE(MULTIPLY(tmp10 - tmp11 - tmp11, FIX(1.257078722)), /* c4 */ CONST_BITS + PASS1_BITS); /* Odd part */ tmp10 = MULTIPLY(tmp0 + tmp2, FIX(0.650711829)); /* c5 */ dataptr[DCTSIZE * 1] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp0 + tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 3] = (DCTELEM) DESCALE(MULTIPLY(tmp0 - tmp1 - tmp2, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS); dataptr[DCTSIZE * 5] = (DCTELEM) DESCALE(tmp10 + MULTIPLY(tmp2 - tmp1, FIX(1.777777778)), /* 16/9 */ CONST_BITS + PASS1_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 2x4 sample block. * * 2-point FDCT in pass 1 (rows), 4-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_2x4(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1; INT32 tmp10, tmp11; DCTELEM* dataptr; JSAMPROW elemptr; int ctr; SHIFT_TEMPS /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); /* Pass 1: process rows. */ /* Note results are scaled up by sqrt(8) compared to a true DCT. */ /* We must also scale the output by (8/2)*(8/4) = 2**3, which we add here. */ dataptr = data; for (ctr = 0; ctr < 4; ctr++) { elemptr = sample_data[ctr] + start_col; /* Even part */ tmp0 = GETJSAMPLE(elemptr[0]); tmp1 = GETJSAMPLE(elemptr[1]); /* Apply unsigned->signed conversion */ dataptr[0] = (DCTELEM)((tmp0 + tmp1 - 2 * CENTERJSAMPLE) << 3); /* Odd part */ dataptr[1] = (DCTELEM)((tmp0 - tmp1) << 3); dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. * We leave the results scaled up by an overall factor of 8. * 4-point FDCT kernel, * cK represents sqrt(2) * cos(K*pi/16) [refers to 8-point FDCT]. */ dataptr = data; for (ctr = 0; ctr < 2; ctr++) { /* Even part */ tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 3]; tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 2]; tmp10 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 3]; tmp11 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 2]; dataptr[DCTSIZE * 0] = (DCTELEM)(tmp0 + tmp1); dataptr[DCTSIZE * 2] = (DCTELEM)(tmp0 - tmp1); /* Odd part */ tmp0 = MULTIPLY(tmp10 + tmp11, FIX_0_541196100); /* c6 */ /* Add fudge factor here for final descale. */ tmp0 += ONE << (CONST_BITS - 1); dataptr[DCTSIZE * 1] = (DCTELEM) RIGHT_SHIFT(tmp0 + MULTIPLY(tmp10, FIX_0_765366865), /* c2-c6 */ CONST_BITS); dataptr[DCTSIZE * 3] = (DCTELEM) RIGHT_SHIFT(tmp0 - MULTIPLY(tmp11, FIX_1_847759065), /* c2+c6 */ CONST_BITS); dataptr++; /* advance pointer to next column */ } } /* * Perform the forward DCT on a 1x2 sample block. * * 1-point FDCT in pass 1 (rows), 2-point in pass 2 (columns). */ GLOBAL(void) jpeg_fdct_1x2(DCTELEM* data, JSAMPARRAY sample_data, JDIMENSION start_col) { INT32 tmp0, tmp1; /* Pre-zero output coefficient block. */ MEMZERO(data, SIZEOF(DCTELEM) * DCTSIZE2); tmp0 = GETJSAMPLE(sample_data[0][start_col]); tmp1 = GETJSAMPLE(sample_data[1][start_col]); /* We leave the results scaled up by an overall factor of 8. * We must also scale the output by (8/1)*(8/2) = 2**5. */ /* Even part */ /* Apply unsigned->signed conversion */ data[DCTSIZE * 0] = (DCTELEM)((tmp0 + tmp1 - 2 * CENTERJSAMPLE) << 5); /* Odd part */ data[DCTSIZE * 1] = (DCTELEM)((tmp0 - tmp1) << 5); } #endif /* DCT_SCALING_SUPPORTED */ #endif /* DCT_ISLOW_SUPPORTED */ }
40.543316
107
0.520573
davidlee80
c2571a92dbdc93ca09a9f9423706f53746e30083
305
cpp
C++
recipes/yojimbo/all/test_package/test_package.cpp
rockandsalt/conan-center-index
d739adcec3e4dd4c250eff559ceb738e420673dd
[ "MIT" ]
562
2019-09-04T12:23:43.000Z
2022-03-29T16:41:43.000Z
recipes/yojimbo/all/test_package/test_package.cpp
rockandsalt/conan-center-index
d739adcec3e4dd4c250eff559ceb738e420673dd
[ "MIT" ]
9,799
2019-09-04T12:02:11.000Z
2022-03-31T23:55:45.000Z
recipes/yojimbo/all/test_package/test_package.cpp
rockandsalt/conan-center-index
d739adcec3e4dd4c250eff559ceb738e420673dd
[ "MIT" ]
1,126
2019-09-04T11:57:46.000Z
2022-03-31T16:43:38.000Z
#include <iostream> #include <yojimbo.h> using namespace yojimbo; int main() { if (!InitializeYojimbo()) { std::cout << "Failed to initialize Yojimbo!\n"; return 1; } std::cout << "Succesfully initialized Yojimbo\n"; ShutdownYojimbo(); return 0; }
15.25
55
0.577049
rockandsalt
c257f4df7efa8ed994e68b41cfb3ba5ba84fab2a
898
cpp
C++
core/tools/json_helper.cpp
SammyEnigma/im-desktop
d93c1c335c8290b21b69c578c399edf61cb899e8
[ "Apache-2.0" ]
81
2019-09-18T13:53:17.000Z
2022-03-19T00:44:20.000Z
core/tools/json_helper.cpp
john-preston/im-desktop
271e42db657bdaa8e261f318c627ca5414e0dd87
[ "Apache-2.0" ]
4
2019-10-03T15:17:00.000Z
2019-11-03T01:05:41.000Z
core/tools/json_helper.cpp
john-preston/im-desktop
271e42db657bdaa8e261f318c627ca5414e0dd87
[ "Apache-2.0" ]
25
2019-09-27T16:56:02.000Z
2022-03-14T07:11:14.000Z
#include "stdafx.h" #include "json_helper.h" namespace core::tools { void sort_json_keys_by_name(rapidjson::Value& _node) { auto members_comparator = [](const auto& _lhs, const auto& _rhs) noexcept { return rapidjson_get_string_view(_lhs.name) < rapidjson_get_string_view(_rhs.name); }; std::sort(_node.MemberBegin(), _node.MemberEnd(), members_comparator); for (auto& member : _node.GetObject()) { if (member.value.IsObject()) { sort_json_keys_by_name(member.value); } else if (member.value.IsArray()) { for (auto& array_member : member.value.GetArray()) { if (array_member.IsObject()) sort_json_keys_by_name(array_member); } } } } }
28.0625
95
0.532294
SammyEnigma
c25899b73940e65de7ed23ad072a9016f47bd24f
8,125
cpp
C++
Editor/editor/guiEditor.cpp
maoxiezhao/Cjing3D
f052c95243307745bcaa9c3b881d225c0839012d
[ "Zlib", "MIT" ]
3
2018-12-16T10:37:28.000Z
2021-03-23T04:32:22.000Z
Editor/editor/guiEditor.cpp
maoxiezhao/Cjing3D
f052c95243307745bcaa9c3b881d225c0839012d
[ "Zlib", "MIT" ]
null
null
null
Editor/editor/guiEditor.cpp
maoxiezhao/Cjing3D
f052c95243307745bcaa9c3b881d225c0839012d
[ "Zlib", "MIT" ]
1
2021-04-02T16:47:02.000Z
2021-04-02T16:47:02.000Z
#include "guiEditor.h" #include "editor\imgui\imguiRHI.h" #include "core\eventSystem.h" #include "platform\win32\gameWindowWin32.h" #include "renderer\RHI\d3d11\deviceD3D11.h" #include "helper\profiler.h" #include "editor\widget\guiEditorWidget.h" #include "editor\widget\guiEditorMenuBar.h" #include "editor\widget\guiEditorToolbar.h" #include "editor\widget\guiEditorEntityList.h" #include "editor\widget\guiEditorProperties.h" #include "editor\widget\guiEditorViewport.h" // TODO: Move to Imgui_RHI #ifdef _WIN32 extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); #endif namespace Cjing3D { namespace { EditorWidget* mWidgetMenu = nullptr; EditorWidget* mWidgetToolbar = nullptr; } EditorStage::EditorStage(GameWindow& gameWindow) : mGameWindow(gameWindow) { } EditorStage::~EditorStage() { } void EditorStage::Initialize() { if (mIsInitialized) { return; } GraphicsDevice& graphicsDevice = Renderer::GetDevice(); if (graphicsDevice.GetGraphicsDeviceType() != GraphicsDeviceType::GraphicsDeviceType_directx11) { return; } auto gameWindowWin32 = dynamic_cast<Win32::GameWindowWin32*>(&mGameWindow); if (gameWindowWin32 == nullptr) { return; } IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); io.ConfigFlags = ImGuiConfigFlags_NavEnableKeyboard | ImGuiConfigFlags_DockingEnable | ImGuiConfigFlags_ViewportsEnable; if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { io.ConfigWindowsResizeFromEdges = true; io.ConfigViewportsNoTaskBarIcon = true; } HWND hwnd = gameWindowWin32->GetHwnd(); ImGui_ImplWin32_Init(hwnd); ImGui::RHI::Initialize(); gameWindowWin32->AddMessageHandler([this](const Win32::WindowMessageData& window) { ImGui_ImplWin32_WndProcHandler(window.handle, window.message, window.wparam, window.lparam); return false; }); InitializeWidgets(); if (!mResolutionChangedConn.IsConnected()) { auto screenSize = Renderer::GetScreenSize(); CreateViewportRenderTarget(screenSize[0], screenSize[1]); mResolutionChangedConn = EventSystem::Register(EVENT_RESOLUTION_CHANGE, [this](const VariantArray& variants) { const U32 width = variants[0].GetValue<U32>(); const U32 height = variants[1].GetValue<U32>(); CreateViewportRenderTarget(width, height); }); } mIsInitialized = true; } void EditorStage::Uninitialize() { if (mIsInitialized == false) { return; } mRegisteredWindows.clear(); for (auto& widget : mRegisteredWidgets) { widget->Uninitialize(); } mRegisteredWidgets.clear(); ImGui::RHI::Uninitilize(); ImGui_ImplWin32_Shutdown(); ImGui::DestroyContext(); mIsInitialized = true; } void EditorStage::InitializeWidgets() { RegisterCustomWidget(CJING_MAKE_SHARED<EditorWidgetMenu>(*this)); RegisterCustomWidget(CJING_MAKE_SHARED<EditorWidgetToolbar>(*this)); RegisterCustomWidget(CJING_MAKE_SHARED<EditorWidgetEntityList>(*this)); RegisterCustomWidget(CJING_MAKE_SHARED<EditorWidgetProperties>(*this)); RegisterCustomWidget(CJING_MAKE_SHARED<EditorWidgetViewport>(*this)); mWidgetMenu = GetCustomWidget<EditorWidgetMenu>(); mWidgetToolbar = GetCustomWidget<EditorWidgetToolbar>(); } ////////////////////////////////////////////////////////////////////////////// void EditorStage::Render(CommandList cmd) { if (mIsInitialized == false) { return; } ImGui_ImplWin32_NewFrame(); ImGui::NewFrame(); FixedUpdateImpl(GetGlobalContext().GetDelatTime()); Renderer::GetDevice().BeginEvent(cmd, "RenderIMGUI"); ImGui::Render(); ImGui::RHI::Render(cmd, ImGui::GetDrawData()); Renderer::GetDevice().EndEvent(cmd); } void EditorStage::EndFrame() { if (mIsInitialized == false) { return; } if (ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_DockingEnable) { ImGui::UpdatePlatformWindows(); ImGui::RenderPlatformWindowsDefault(); } } void EditorStage::RegisterCustomWindow(CustomWindowFunc func) { mRegisteredWindows.push_back(func); } void EditorStage::RegisterCustomWidget(std::shared_ptr<EditorWidget> widget) { if (widget == nullptr) { return; } mRegisteredWidgets.push_back(widget); widget->Initialize(); } void EditorStage::SetDockingEnable(bool isDockingEnable) { if (mIsDockingEnable != isDockingEnable) { mIsDockingEnable = isDockingEnable; if (mIsDockingEnable) { ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_DockingEnable; } else { ImGui::GetIO().ConfigFlags &= ~ImGuiConfigFlags_DockingEnable; } } } void EditorStage::FixedUpdateImpl(F32 deltaTime) { if (!IsVisible()) { return; } // docking begin if (ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_DockingEnable) { DockingBegin(); } // show custom registerd windows for (auto it : mRegisteredWindows) { it(deltaTime); } // show custom widgets for (auto& widget : mRegisteredWidgets) { if (widget != nullptr && widget->Begin()) { widget->Update(deltaTime); widget->End(); } } // show imgui demo if (mIsShowDemo) { ImGui::ShowDemoWindow(&mIsShowDemo); } // docking end if (ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_DockingEnable) { DockingEnd(); } } void EditorStage::CreateViewportRenderTarget(U32 width, U32 height) { auto& device = Renderer::GetDevice(); TextureDesc desc = {}; desc.mWidth = width; desc.mHeight = height; desc.mFormat = device.GetBackBufferFormat(); desc.mSampleDesc.mCount = 1; desc.mBindFlags = BIND_RENDER_TARGET | BIND_SHADER_RESOURCE; { const auto result = device.CreateTexture2D(&desc, nullptr, mViewportRenderTarget); Debug::ThrowIfFailed(result, "Failed to create viewport render target:%08x", result); device.SetResourceName(mViewportRenderTarget, "ViewportRT"); } } ///////////////////////////////////////////////////////////////////////////// void EditorStage::DockingBegin() { // full screen without window ImGuiWindowFlags windowFlags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ImGui::SetNextWindowBgAlpha(0.0f); F32 dockingOffsetY = 0.0f; dockingOffsetY += mWidgetToolbar->GetHeight(); dockingOffsetY += mWidgetMenu->GetHeight(); ImGuiViewport* viewport = ImGui::GetMainViewport(); ImGui::SetNextWindowPos(ImVec2(viewport->Pos.x, viewport->Pos.y + dockingOffsetY)); ImGui::SetNextWindowSize(ImVec2(viewport->Size.x, viewport->Size.y - dockingOffsetY)); ImGui::SetNextWindowViewport(viewport->ID); static const char* dockingName = "CjingDock"; mIsDockingBegin = ImGui::Begin(dockingName, nullptr, windowFlags); ImGui::PopStyleVar(3); if (mIsDockingBegin) { ImGuiID mainWindow = ImGui::GetID(dockingName); if (!ImGui::DockBuilderGetNode(mainWindow)) { // reset ImGui::DockBuilderRemoveNode(mainWindow); ImGui::DockBuilderAddNode(mainWindow, ImGuiDockNodeFlags_None); ImGui::DockBuilderSetNodeSize(mainWindow, viewport->Size); ImGuiID dockMainID = mainWindow; // split node ImGuiID dockLeft = ImGui::DockBuilderSplitNode(dockMainID, ImGuiDir_Left, 0.2f, nullptr, &dockMainID); ImGuiID dockRight = ImGui::DockBuilderSplitNode(dockMainID, ImGuiDir_Right, 0.2f, nullptr, &dockMainID); // build window ImGui::DockBuilderDockWindow("EntityList", dockLeft); ImGui::DockBuilderDockWindow("Properties", dockRight); ImGui::DockBuilderDockWindow("Viewport", dockMainID); ImGui::DockBuilderFinish(dockMainID); } ImGui::DockSpace(mainWindow, ImVec2(0.0f, 0.0f), ImGuiDockNodeFlags_PassthruCentralNode); } } void EditorStage::DockingEnd() { if (mIsDockingBegin) { ImGui::End(); } } }
26.209677
112
0.718277
maoxiezhao
c25f57e0f7f7c7b7d1556308fc524f1dd1eb0e23
4,095
cpp
C++
BasiliskII/src/Windows/router/ftp.cpp
jvernet/macemu
c616a0dae0f451fc15016765c896175fae3f46cf
[ "Intel", "X11" ]
940
2015-01-04T12:20:10.000Z
2022-03-29T12:35:27.000Z
BasiliskII/src/Windows/router/ftp.cpp
Seanpm2001-virtual-machines/macemu
c616a0dae0f451fc15016765c896175fae3f46cf
[ "Intel", "X11" ]
163
2015-02-10T09:08:10.000Z
2022-03-13T05:48:10.000Z
BasiliskII/src/Windows/router/ftp.cpp
Seanpm2001-virtual-machines/macemu
c616a0dae0f451fc15016765c896175fae3f46cf
[ "Intel", "X11" ]
188
2015-01-07T19:46:11.000Z
2022-03-26T19:06:00.000Z
/* * ftp.cpp - ip router * * Basilisk II (C) 1997-2008 Christian Bauer * * Windows platform specific code copyright (C) Lauri Pesonen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "sysdeps.h" #include "main.h" #include <ctype.h> #include "dump.h" #include "prefs.h" #include "ftp.h" #if DEBUG #pragma optimize("",off) #endif #include "debug.h" static int m_ftp_port_count = 0; #define MAX_FTP_PORTS 100 static uint16 m_ftp_ports[MAX_FTP_PORTS]; bool ftp_is_ftp_port( uint16 port ) { for( int i=0; i<m_ftp_port_count; i++ ) { if( m_ftp_ports[i] == port ) return true; } return false; } void init_ftp() { const char *str = PrefsFindString("ftp_port_list"); if(str) { char *ftp = new char [ strlen(str) + 1 ]; if(ftp) { strcpy( ftp, str ); char *p = ftp; while( p && *p ) { char *pp = strchr( p, ',' ); if(pp) *pp++ = 0; if( m_ftp_port_count < MAX_FTP_PORTS ) { m_ftp_ports[m_ftp_port_count++] = (uint16)strtoul(p,0,0); } p = pp; } delete [] ftp; } } } void ftp_modify_port_command( char *buf, int &count, const uint32 max_size, const uint32 ip, const uint16 port, const bool is_pasv ) { if( max_size < 100 ) { // impossible return; } sprintf( buf, (is_pasv ? "227 Entering Passive Mode (%d,%d,%d,%d,%d,%d).%c%c" : "PORT %d,%d,%d,%d,%d,%d%c%c"), ip >> 24, (ip >> 16) & 0xFF, (ip >> 8) & 0xFF, ip & 0xFF, (port >> 8) & 0xFF, port & 0xFF, 0x0d, 0x0a ); count = strlen(buf); D(bug("ftp_modify_port_command: \"%s\"\r\n", buf )); } // this should be robust. rather skip it than do anything dangerous. void ftp_parse_port_command( char *buf, uint32 count, uint16 &ftp_data_port, bool is_pasv ) { ftp_data_port = 0; if( !count ) return; uint8 b[100]; uint32 ftp_ip = 0; // make it a c-string if( count >= sizeof(b) ) count = sizeof(b)-1; memcpy( b, buf, count ); b[ count ] = 0; for( uint32 i=0; i<count; i++ ) { if( b[i] < ' ' || b[i] > 'z' ) { b[i] = ' '; } else { b[i] = tolower(b[i]); } } // D(bug("FTP: \"%s\"\r\n", b )); char *s = (char *)b; while( *s == ' ' ) s++; if(is_pasv) { /* LOCAL SERVER: ..227 Entering Passive Mode (192,168,0,2,6,236). 0d 0a */ if( atoi(s) == 227 && strstr(s,"passive") ) { while( *s && *s != '(' ) s++; if( *s++ == 0 ) s = 0; } else { s = 0; } } else { /* LOCAL CLIENT: PORT 192,168,0,1,14,147 0d 0a */ if( strncmp(s,"port ",5) == 0 ) { s += 5; } else { s = 0; } } if(s && *s) { // get remote ip (used only for verification) for( uint32 i=0; i<4; i++ ) { while( *s == ' ' ) s++; if(!isdigit(*s)) { ftp_ip = 0; break; } ftp_ip = (ftp_ip << 8) + atoi(s); while( *s && *s != ',' ) s++; if(!*s) { ftp_ip = 0; break; } s++; } if(ftp_ip) { // get local port for( uint32 i=0; i<2; i++ ) { while( *s == ' ' ) s++; if(!isdigit(*s)) { ftp_data_port = 0; break; } ftp_data_port = (ftp_data_port << 8) + atoi(s); while( *s && *s != ',' && *s != ')' ) s++; if(!*s) break; else s++; } } } if(ftp_data_port) { D(bug("ftp_parse_port_command: \"%s\"; port is %d\r\n", b, ftp_data_port )); } }
21.108247
99
0.542613
jvernet
c263f74bb182d8d679315f6df55b46a143b00983
11,465
cpp
C++
src/org/apache/poi/poifs/dev/POIFSHeaderDumper.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/poifs/dev/POIFSHeaderDumper.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/poifs/dev/POIFSHeaderDumper.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/poifs/dev/POIFSHeaderDumper.java #include <org/apache/poi/poifs/dev/POIFSHeaderDumper.hpp> #include <java/io/FileInputStream.hpp> #include <java/io/PrintStream.hpp> #include <java/io/Serializable.hpp> #include <java/lang/ArrayStoreException.hpp> #include <java/lang/CharSequence.hpp> #include <java/lang/ClassCastException.hpp> #include <java/lang/Comparable.hpp> #include <java/lang/Integer.hpp> #include <java/lang/Math.hpp> #include <java/lang/NullPointerException.hpp> #include <java/lang/Object.hpp> #include <java/lang/String.hpp> #include <java/lang/StringBuilder.hpp> #include <java/lang/System.hpp> #include <java/util/Iterator.hpp> #include <org/apache/poi/poifs/common/POIFSBigBlockSize.hpp> #include <org/apache/poi/poifs/common/POIFSConstants.hpp> #include <org/apache/poi/poifs/property/DirectoryProperty.hpp> #include <org/apache/poi/poifs/property/Property.hpp> #include <org/apache/poi/poifs/property/PropertyTable.hpp> #include <org/apache/poi/poifs/property/RootProperty.hpp> #include <org/apache/poi/poifs/storage/BlockAllocationTableReader.hpp> #include <org/apache/poi/poifs/storage/HeaderBlock.hpp> #include <org/apache/poi/poifs/storage/ListManagedBlock.hpp> #include <org/apache/poi/poifs/storage/RawDataBlockList.hpp> #include <org/apache/poi/poifs/storage/SmallBlockTableReader.hpp> #include <org/apache/poi/util/HexDump.hpp> #include <org/apache/poi/util/IntList.hpp> #include <Array.hpp> #include <SubArray.hpp> #include <ObjectArray.hpp> template<typename ComponentType, typename... Bases> struct SubArray; namespace java { namespace io { typedef ::SubArray< ::java::io::Serializable, ::java::lang::ObjectArray > SerializableArray; } // io namespace lang { typedef ::SubArray< ::java::lang::CharSequence, ObjectArray > CharSequenceArray; typedef ::SubArray< ::java::lang::Comparable, ObjectArray > ComparableArray; typedef ::SubArray< ::java::lang::String, ObjectArray, ::java::io::SerializableArray, ComparableArray, CharSequenceArray > StringArray; } // lang } // java template<typename T, typename U> static T java_cast(U* u) { if(!u) return static_cast<T>(nullptr); auto t = dynamic_cast<T>(u); if(!t) throw new ::java::lang::ClassCastException(); return t; } template<typename T> static T* npc(T* t) { if(!t) throw new ::java::lang::NullPointerException(); return t; } poi::poifs::dev::POIFSHeaderDumper::POIFSHeaderDumper(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::poifs::dev::POIFSHeaderDumper::POIFSHeaderDumper() : POIFSHeaderDumper(*static_cast< ::default_init_tag* >(0)) { ctor(); } void poi::poifs::dev::POIFSHeaderDumper::main(::java::lang::StringArray* args) /* throws(Exception) */ { clinit(); if(npc(args)->length == 0) { npc(::java::lang::System::err())->println(u"Must specify at least one file to view"_j); ::java::lang::System::exit(1); } for (auto j = int32_t(0); j < npc(args)->length; j++) { viewFile((*args)[j]); } } void poi::poifs::dev::POIFSHeaderDumper::viewFile(::java::lang::String* filename) /* throws(Exception) */ { clinit(); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u"Dumping headers from: "_j)->append(filename)->toString()); ::java::io::InputStream* inp = new ::java::io::FileInputStream(filename); auto header_block = new ::poi::poifs::storage::HeaderBlock(inp); displayHeader(header_block); auto bigBlockSize = npc(header_block)->getBigBlockSize(); auto data_blocks = new ::poi::poifs::storage::RawDataBlockList(inp, bigBlockSize); displayRawBlocksSummary(data_blocks); auto batReader = new ::poi::poifs::storage::BlockAllocationTableReader(npc(header_block)->getBigBlockSize(), npc(header_block)->getBATCount(), npc(header_block)->getBATArray_(), npc(header_block)->getXBATCount(), npc(header_block)->getXBATIndex(), data_blocks); displayBATReader(u"Big Blocks"_j, batReader); auto properties = new ::poi::poifs::property::PropertyTable(header_block, data_blocks); auto sbatReader = ::poi::poifs::storage::SmallBlockTableReader::_getSmallDocumentBlockReader(bigBlockSize, data_blocks, npc(properties)->getRoot(), npc(header_block)->getSBATStart()); displayBATReader(u"Small Blocks"_j, sbatReader); displayPropertiesSummary(properties); } void poi::poifs::dev::POIFSHeaderDumper::displayHeader(::poi::poifs::storage::HeaderBlock* header_block) /* throws(Exception) */ { clinit(); npc(::java::lang::System::out())->println(u"Header Details:"_j); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" Block size: "_j)->append(npc(npc(header_block)->getBigBlockSize())->getBigBlockSize())->toString()); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" BAT (FAT) header blocks: "_j)->append(npc(npc(header_block)->getBATArray_())->length)->toString()); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" BAT (FAT) block count: "_j)->append(npc(header_block)->getBATCount())->toString()); if(npc(header_block)->getBATCount() > 0) npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" BAT (FAT) block 1 at: "_j)->append((*npc(header_block)->getBATArray_())[int32_t(0)])->toString()); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" XBAT (FAT) block count: "_j)->append(npc(header_block)->getXBATCount())->toString()); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" XBAT (FAT) block 1 at: "_j)->append(npc(header_block)->getXBATIndex())->toString()); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" SBAT (MiniFAT) block count: "_j)->append(npc(header_block)->getSBATCount())->toString()); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" SBAT (MiniFAT) block 1 at: "_j)->append(npc(header_block)->getSBATStart())->toString()); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" Property table at: "_j)->append(npc(header_block)->getPropertyStart())->toString()); npc(::java::lang::System::out())->println(u""_j); } void poi::poifs::dev::POIFSHeaderDumper::displayRawBlocksSummary(::poi::poifs::storage::RawDataBlockList* data_blocks) /* throws(Exception) */ { clinit(); npc(::java::lang::System::out())->println(u"Raw Blocks Details:"_j); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" Number of blocks: "_j)->append(npc(data_blocks)->blockCount())->toString()); for (auto i = int32_t(0); i < ::java::lang::Math::min(int32_t(16), npc(data_blocks)->blockCount()); i++) { auto block = npc(data_blocks)->get(i); auto data = new ::int8_tArray(::java::lang::Math::min(int32_t(48), npc(npc(block)->getData())->length)); ::java::lang::System::arraycopy(npc(block)->getData(), 0, data, 0, npc(data)->length); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" Block #"_j)->append(i) ->append(u":"_j)->toString()); npc(::java::lang::System::out())->println(::poi::util::HexDump::dump(data, 0, 0)); } npc(::java::lang::System::out())->println(u""_j); } void poi::poifs::dev::POIFSHeaderDumper::displayBATReader(::java::lang::String* type, ::poi::poifs::storage::BlockAllocationTableReader* batReader) /* throws(Exception) */ { clinit(); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u"Sectors, as referenced from the "_j)->append(type) ->append(u" FAT:"_j)->toString()); auto entries = npc(batReader)->getEntries(); for (auto i = int32_t(0); i < npc(entries)->size(); i++) { auto bn = npc(entries)->get(i); auto bnS = ::java::lang::Integer::toString(bn); if(bn == ::poi::poifs::common::POIFSConstants::END_OF_CHAIN) { bnS = u"End Of Chain"_j; } else if(bn == ::poi::poifs::common::POIFSConstants::DIFAT_SECTOR_BLOCK) { bnS = u"DI Fat Block"_j; } else if(bn == ::poi::poifs::common::POIFSConstants::FAT_SECTOR_BLOCK) { bnS = u"Normal Fat Block"_j; } else if(bn == ::poi::poifs::common::POIFSConstants::UNUSED_BLOCK) { bnS = u"Block Not Used (Free)"_j; } npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" Block # "_j)->append(i) ->append(u" -> "_j) ->append(bnS)->toString()); } npc(::java::lang::System::out())->println(u""_j); } void poi::poifs::dev::POIFSHeaderDumper::displayPropertiesSummary(::poi::poifs::property::PropertyTable* properties) { clinit(); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u"Mini Stream starts at "_j)->append(npc(npc(properties)->getRoot())->getStartBlock())->toString()); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u"Mini Stream length is "_j)->append(npc(npc(properties)->getRoot())->getSize())->toString()); npc(::java::lang::System::out())->println(); npc(::java::lang::System::out())->println(u"Properties and their block start:"_j); displayProperties(npc(properties)->getRoot(), u""_j); npc(::java::lang::System::out())->println(u""_j); } void poi::poifs::dev::POIFSHeaderDumper::displayProperties(::poi::poifs::property::DirectoryProperty* prop, ::java::lang::String* indent) { clinit(); auto nextIndent = ::java::lang::StringBuilder().append(indent)->append(u" "_j)->toString(); npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(indent)->append(u"-> "_j) ->append(npc(prop)->getName())->toString()); for (auto _i = npc(prop)->iterator(); _i->hasNext(); ) { ::poi::poifs::property::Property* cp = java_cast< ::poi::poifs::property::Property* >(_i->next()); { if(dynamic_cast< ::poi::poifs::property::DirectoryProperty* >(cp) != nullptr) { displayProperties(java_cast< ::poi::poifs::property::DirectoryProperty* >(cp), nextIndent); } else { npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(nextIndent)->append(u"=> "_j) ->append(npc(cp)->getName())->toString()); npc(::java::lang::System::out())->print(::java::lang::StringBuilder().append(nextIndent)->append(u" "_j) ->append(npc(cp)->getSize()) ->append(u" bytes in "_j)->toString()); if(npc(cp)->shouldUseSmallBlocks()) { npc(::java::lang::System::out())->print(u"mini"_j); } else { npc(::java::lang::System::out())->print(u"main"_j); } npc(::java::lang::System::out())->println(::java::lang::StringBuilder().append(u" stream, starts at "_j)->append(npc(cp)->getStartBlock())->toString()); } } } } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::poifs::dev::POIFSHeaderDumper::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.poifs.dev.POIFSHeaderDumper", 42); return c; } java::lang::Class* poi::poifs::dev::POIFSHeaderDumper::getClass0() { return class_(); }
51.877828
265
0.658613
pebble2015
c2644abf9666a18f5e3e0da49735c15000262713
8,685
cpp
C++
imagine2/NFmiCardinalBezierFit.cpp
fmidev/smartmet-library-imagine2
8dc3813029f9b544c88c6817363f23f77fa505d3
[ "MIT" ]
null
null
null
imagine2/NFmiCardinalBezierFit.cpp
fmidev/smartmet-library-imagine2
8dc3813029f9b544c88c6817363f23f77fa505d3
[ "MIT" ]
null
null
null
imagine2/NFmiCardinalBezierFit.cpp
fmidev/smartmet-library-imagine2
8dc3813029f9b544c88c6817363f23f77fa505d3
[ "MIT" ]
null
null
null
// ====================================================================== /*! * \file * \brief Implementation of namespace Imagine::NFmiCardinalBezierFit */ // ====================================================================== /*! * \namespace Imagine::NFmiCardinalBezierFit * * \brief Calculating a cardinal Bezier curve fit * */ // ====================================================================== #include "NFmiCardinalBezierFit.h" #include "NFmiBezierTools.h" #include "NFmiCounter.h" #include "NFmiPath.h" #include <list> using namespace std; namespace Imagine { namespace { // ---------------------------------------------------------------------- /*! * \brief Estimate control points for vertices. * * This function calculates cubic Bezier curve control points between * vertices (x1,y1) and (x2,y2) given the previous vertex (x0,y0) * and the following vertex (x3,y3). The given smoothness factor * determines how closely the Bezier curve follows a polyline. * * The calculated control points are returned into the given * variables passed by reference. * * Special cases: * -# x0==x1 && y0==y1 should work fine, is untested * -# x1==x2 && y2==y3 should work fine, is untested (sharp corner?) * -# x2==x3 && y2==y3 should work fine, is untested * * \param smooth_value The smoothness factor in range 0-1 * \param x0 Vertex 0 x-coordinate * \param y0 Vertex 0 y-coordinate * \param x1 Vertex 1 x-coordinate * \param y1 Vertex 1 y-coordinate * \param x2 Vertex 2 x-coordinate * \param y2 Vertex 2 y-coordinate * \param x3 Vertex 3 x-coordinate * \param y3 Vertex 3 y-coordinate * \param cx1 Control point 1 x-coordinate (returned via reference) * \param cy1 Control point 1 y-coordinate (returned via reference) * \param cx2 Control point 2 x-coordinate (returned via reference) * \param cy2 Control point 2 y-coordinate (returned via reference) */ // ---------------------------------------------------------------------- void CubicControlPoints(double smooth_value, double x0, double y0, double x1, double y1, double x2, double y2, double x3, double y3, double& cx1, double& cy1, double& cx2, double& cy2) { // calculate the centers for each of the three edges const double xc1 = (x0 + x1) / 2.0; const double yc1 = (y0 + y1) / 2.0; const double xc2 = (x1 + x2) / 2.0; const double yc2 = (y1 + y2) / 2.0; const double xc3 = (x2 + x3) / 2.0; const double yc3 = (y2 + y3) / 2.0; const double len1 = sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0)); const double len2 = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); const double len3 = sqrt((x3 - x2) * (x3 - x2) + (y3 - y2) * (y3 - y2)); const double k1 = len1 / (len1 + len2); const double k2 = len2 / (len2 + len3); const double xm1 = xc1 + (xc2 - xc1) * k1; const double ym1 = yc1 + (yc2 - yc1) * k1; const double xm2 = xc2 + (xc3 - xc2) * k2; const double ym2 = yc2 + (yc3 - yc2) * k2; // Resulting control points. Here smooth_value is mentioned // above coefficient K whose value should be in range [0...1]. cx1 = xm1 + (xc2 - xm1) * smooth_value + x1 - xm1; cy1 = ym1 + (yc2 - ym1) * smooth_value + y1 - ym1; cx2 = xm2 + (xc2 - xm2) * smooth_value + x2 - xm2; cy2 = ym2 + (yc2 - ym2) * smooth_value + y2 - ym2; } // ---------------------------------------------------------------------- /*! * \brief Generate cardinal bezier for regular path segment * * A regular path segment starts with a moveto, is followed by * several lineto commands and may or may not be closed. * * The algorithm is to generate the Bezier for each line segment in * turn. If the curve is closed, we use wrap-around to generate * the surrounding vertices for the first and last segments. If the * curve is not closed, we use the first and last points as the * next points also. This may not be the best possible approach, * but it works. * * \param thePath The path to cardinalize * \param theSmoothness The smoothness factor * \return The cardinalized path */ // ---------------------------------------------------------------------- NFmiPath SimpleFit(const NFmiPath& thePath, double theSmoothness) { using namespace NFmiBezierTools; if (thePath.Empty()) return thePath; const NFmiPathData& path = thePath.Elements(); const bool isclosed = IsClosed(thePath); NFmiPath outpath; outpath.Add(path.front()); const unsigned int n = path.size(); double cx1, cy1, cx2, cy2; for (unsigned int i = 0; i < n - 1; i++) { const unsigned int p0 = (i != 0 ? i - 1 : (isclosed ? n - 2 : 0)); const unsigned int p1 = i; const unsigned int p2 = i + 1; const unsigned int p3 = (i + 2 < n ? i + 2 : (isclosed ? 1 : n - 1)); CubicControlPoints(theSmoothness, path[p0].x, path[p0].y, path[p1].x, path[p1].y, path[p2].x, path[p2].y, path[p3].x, path[p3].y, cx1, cy1, cx2, cy2); outpath.CubicTo(cx1, cy1); outpath.CubicTo(cx2, cy2); outpath.CubicTo(path[p2].x, path[p2].y); } return outpath; } } // namespace namespace NFmiCardinalBezierFit { // ---------------------------------------------------------------------- /*! * \brief Calculate cardinal Bezier approximation * * All real line segments long enough will be converted * to cubic bezier line segments. The conversion is cardinal, * that is, the original points are on the output path. * * The smoothness factor determines how strongly the approximation * approaches a line. * * The algorithm is based on that in the AGG graphics library. * The original path is split into parts containing regular * line segments and other segments. The regular line segments * are then converted, the other segments are preserved as is. * * \param thePath The path to approximate * \param theSmoothness The smoothness in range 0-1 * \return The converted path * */ // ---------------------------------------------------------------------- const NFmiPath Fit(const NFmiPath& thePath, double theSmoothness) { using namespace NFmiBezierTools; NFmiPath outpath; Segments segments = SplitSegments(thePath); for (Segments::const_iterator it = segments.begin(); it != segments.end(); ++it) { if (it->second) outpath.Add(SimpleFit(it->first, theSmoothness)); else outpath.Add(it->first); } return outpath; } // ---------------------------------------------------------------------- /*! * \brief Calculate multiple Bezier approximations * * Note that the different paths may have common subsegments * which must be fitted identically, otherwise for example * contour plots may show gaps. * * This function works only for flattened paths, conic * or cubic elements are not allowed in the input. * * The algorithm is: * -# Calculate how many times each point occurs, taking * care not to calculate closed subpath joinpoints twice * -# Split each path to subsegments based on where the * count of each endpoint and adjacent points reveals * a join point between another path. * -# Establish unique order for all the subsegments. For * closed subsegments we must establish a unique starting * point. * -# Fit each subsegment separately. * -# Join the subsegments back * * \param thePaths Vector of paths to fit * \param theSmoothness The smoothness * \return The fitted paths */ // ---------------------------------------------------------------------- const NFmiPaths Fit(const NFmiPaths& thePaths, double theSmoothness) { using namespace NFmiBezierTools; // Calculate the points NFmiCounter<NFmiPoint> counts = VertexCounts(thePaths); NFmiPaths outpaths; for (NFmiPaths::const_iterator it = thePaths.begin(); it != thePaths.end(); ++it) { PathList pathlist = SplitPath(*it, counts); NFmiPath outpath; for (PathList::const_iterator jt = pathlist.begin(); jt != pathlist.end(); ++jt) { outpath.Add(Fit(*jt, theSmoothness)); } outpaths.push_back(outpath); } return thePaths; } } // namespace NFmiCardinalBezierFit } // namespace Imagine // ======================================================================
31.930147
84
0.569948
fmidev
c266d71d44efa82fa000aaea10893dbbbc9b9655
2,331
cpp
C++
uppdev/E011Setup/WinUtils.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
2
2016-04-07T07:54:26.000Z
2020-04-14T12:37:34.000Z
uppdev/E011Setup/WinUtils.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
uppdev/E011Setup/WinUtils.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
#include "App.h" bool InstallDesktopIcon(const char *exe, const char *lnk, const char *desc) { return CreateShellLink(exe, "", AppendFileName(GetShellFolder("Desktop", HKEY_CURRENT_USER), lnk), desc, "", 0); } bool InstallProgramGroup(const char *groupname, const char *exe, const char *args, const char *lnk, const char *desc, const char *fileicon, int icon) { String dir = GetShellFolder("Programs", HKEY_CURRENT_USER); if(groupname) { dir = AppendFileName(dir, groupname); RealizeDirectory(dir); } return CreateShellLink(exe, args, AppendFileName(dir, lnk), desc, fileicon, icon); } void InstallUninstall(const char *name, const char *dname, const char *cmdline){ String path = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\" + String(dname); SetWinRegString(dname, "DisplayName", path); SetWinRegString((const char*)~String(name) + String(cmdline), "UninstallString", path); } String GetShellFolder(const char *name, HKEY type) { return GetWinRegString(name, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", type); } #include <winnls.h> #include <winnetwk.h> #define Ptr Ptr_ #include <wincon.h> #include <shlobj.h> #undef Ptr bool CreateShellLink(const char *filepath, const char *args, const char *linkpath, const char *desc, const char *fileicon, int icon) { HRESULT hres; IShellLink* psl; IPersistFile* ppf; CoInitialize(NULL); hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (PVOID *) &psl); if(SUCCEEDED(hres)) { psl->SetPath(filepath); psl->SetArguments(args); psl->SetDescription(desc); if(icon >= 0) { if(strlen(fileicon)) psl->SetIconLocation(fileicon, icon); else psl->SetIconLocation(filepath, icon); } hres = psl->QueryInterface(IID_IPersistFile, (PVOID *) &ppf); if (SUCCEEDED(hres)) { WCHAR szPath[_MAX_PATH] = { 0 }; MultiByteToWideChar(CP_ACP, 0, linkpath, strlen(linkpath), szPath, _MAX_PATH); hres = ppf->Save(szPath, TRUE); ppf->Release(); } } psl->Release(); CoUninitialize(); return SUCCEEDED(hres); } void DelKey(const char *dir, const char *key) { HKEY hkey; if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, dir, 0, KEY_READ, &hkey) != ERROR_SUCCESS) return; RegDeleteKey(hkey, key); RegCloseKey(hkey); }
34.279412
152
0.703132
dreamsxin
c267164a38c751e6fd15300491502e71f890fd4c
792
cpp
C++
essentials/demos/ex-properties/employee.cpp
sfaure-witekio/qt-training-material
d166e4ed9cc5f5faab85b0337c5844c4cdcb206e
[ "BSD-3-Clause" ]
16
2017-01-11T17:28:03.000Z
2021-09-27T16:12:01.000Z
essentials/demos/ex-properties/employee.cpp
sfaure-witekio/qt-training-material
d166e4ed9cc5f5faab85b0337c5844c4cdcb206e
[ "BSD-3-Clause" ]
null
null
null
essentials/demos/ex-properties/employee.cpp
sfaure-witekio/qt-training-material
d166e4ed9cc5f5faab85b0337c5844c4cdcb206e
[ "BSD-3-Clause" ]
4
2017-03-17T02:44:32.000Z
2021-01-22T07:57:34.000Z
/************************************************************************* * * Copyright (c) 2016 The Qt Company * All rights reserved. * * See the LICENSE.txt file shipped along with this file for the license. * *************************************************************************/ #include "employee.h" Employee::Employee() : Employee("NN", 0.0) { } Employee::Employee(const QString &name, const float salary) { m_name = name; m_salary = salary; } const QString &Employee::name() const { return m_name; } void Employee::setName(const QString &name) { if (name != m_name) m_name = name; } float Employee::salary() const { return m_salary; } void Employee::setSalary(float &salary) { if (salary != m_salary) m_salary = salary; }
18
75
0.522727
sfaure-witekio
c269594f6b1fe2afeeeb70c65e0823d22c23fa42
18,826
cpp
C++
tightvnc/tvnviewer/DesktopWindow.cpp
jjzhang166/qmlvncviewer2
b888c416ab88b81fe802ab0559bb87361833a0b5
[ "Apache-2.0" ]
47
2016-08-17T03:18:32.000Z
2022-01-14T01:33:15.000Z
tightvnc/tvnviewer/DesktopWindow.cpp
jjzhang166/qmlvncviewer2
b888c416ab88b81fe802ab0559bb87361833a0b5
[ "Apache-2.0" ]
3
2018-06-29T06:13:28.000Z
2020-11-26T02:31:49.000Z
tightvnc/tvnviewer/DesktopWindow.cpp
jjzhang166/qmlvncviewer2
b888c416ab88b81fe802ab0559bb87361833a0b5
[ "Apache-2.0" ]
15
2016-08-17T07:03:55.000Z
2021-08-02T14:42:02.000Z
// Copyright (C) 2012 GlavSoft LLC. // All rights reserved. // //------------------------------------------------------------------------- // This file is part of the TightVNC software. Please visit our Web site: // // http://www.tightvnc.com/ // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. //------------------------------------------------------------------------- // #include "DesktopWindow.h" DesktopWindow::DesktopWindow(LogWriter *logWriter, ConnectionConfig *conConf) : m_logWriter(logWriter), m_clipboard(0), m_showVert(false), m_showHorz(false), m_fbWidth(1), m_fbHeight(1), m_winResize(false), m_conConf(conConf), m_brush(RGB(0, 0, 0)), m_viewerCore(0), m_ctrlDown(false), m_altDown(false), m_previousMousePos(-1, -1), m_previousMouseState(0), m_isBackgroundDirty(false) { m_rfbKeySym = std::auto_ptr<RfbKeySym>(new RfbKeySym(this, m_logWriter)); } DesktopWindow::~DesktopWindow() { } void DesktopWindow::setConnected() { m_isConnected = true; } void DesktopWindow::setViewerCore(RemoteViewerCore *viewerCore) { m_viewerCore = viewerCore; } bool DesktopWindow::onCreate(LPCREATESTRUCT pcs) { m_sbar.setWindow(getHWnd()); m_clipboard.setHWnd(getHWnd()); return true; } void DesktopWindow::onPaint(DeviceContext *dc, PAINTSTRUCT *paintStruct) { Rect paintRect(&paintStruct->rcPaint); if (paintRect.area() != 0) { try { AutoLock al(&m_bufferLock); m_framebuffer.setTargetDC(paintStruct->hdc); if (!m_clientArea.isEmpty()) { doDraw(dc); } } catch (const Exception &ex) { m_logWriter->error(_T("Error in onPaint: %s"), ex.getMessage()); } } } bool DesktopWindow::onMessage(UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_HSCROLL: return onHScroll(wParam, lParam); case WM_VSCROLL: return onVScroll(wParam, lParam); case WM_ERASEBKGND: return onEraseBackground(reinterpret_cast<HDC>(wParam)); case WM_DEADCHAR: case WM_SYSDEADCHAR: return onDeadChar(wParam, lParam); case WM_DRAWCLIPBOARD: return onDrawClipboard(); case WM_CREATE: return onCreate(reinterpret_cast<LPCREATESTRUCT>(lParam)); case WM_SIZE: return onSize(wParam, lParam); case WM_DESTROY: return onDestroy(); case WM_CHAR: case WM_SYSCHAR: return onChar(wParam, lParam); case WM_KEYDOWN: case WM_KEYUP: case WM_SYSKEYDOWN: case WM_SYSKEYUP: return onKey(wParam, lParam); case WM_SETFOCUS: m_rfbKeySym->processFocusRestoration(); return true; case WM_KILLFOCUS: m_ctrlDown = false; m_altDown = false; m_rfbKeySym->processFocusLoss(); return true; } return false; } bool DesktopWindow::onEraseBackground(HDC hdc) { return true; } bool DesktopWindow::onHScroll(WPARAM wParam, LPARAM lParam) { switch(LOWORD(wParam)) { case SB_THUMBTRACK: case SB_THUMBPOSITION: m_sbar.setHorzPos(HIWORD(wParam)); redraw(); break; case SB_LINELEFT: m_sbar.moveLeftHorz(ScrollBar::SCROLL_STEP); redraw(); break; case SB_PAGELEFT: m_sbar.moveLeftHorz(); redraw(); break; case SB_LINERIGHT: m_sbar.moveRightHorz(ScrollBar::SCROLL_STEP); redraw(); break; case SB_PAGERIGHT: m_sbar.moveRightHorz(); redraw(); break; } return true; } bool DesktopWindow::onVScroll(WPARAM wParam, LPARAM lParam) { switch(LOWORD(wParam)) { case SB_THUMBTRACK: case SB_THUMBPOSITION: m_sbar.setVertPos(HIWORD(wParam)); redraw(); break; case SB_LINEUP: m_sbar.moveDownVert(ScrollBar::SCROLL_STEP); redraw(); break; case SB_PAGEUP: m_sbar.moveDownVert(); redraw(); break; case SB_LINEDOWN: m_sbar.moveUpVert(ScrollBar::SCROLL_STEP); redraw(); break; case SB_PAGEDOWN: m_sbar.moveUpVert(); redraw(); break; } return true; } bool DesktopWindow::onMouse(unsigned char mouseButtons, unsigned short wheelSpeed, POINT position) { // If mode is "view-only", then skip event. if (m_conConf->isViewOnly()) { return true; } // If viewer isn't connected with server, then skip event. if (!m_isConnected) { return true; } // If swap of mouse button is enabled, then swap button. if (m_conConf->isMouseSwapEnabled() && mouseButtons) { bool bSecond = !!(mouseButtons & MOUSE_MDOWN); bool bThird = !!(mouseButtons & MOUSE_RDOWN); mouseButtons &= ~(MOUSE_MDOWN | MOUSE_RDOWN); if (bSecond) { mouseButtons |= MOUSE_RDOWN; } if (bThird) { mouseButtons |= MOUSE_MDOWN; } } // Translate coordinates from the Viewer Window to Desktop Window. POINTS mousePos = getViewerCoord(position.x, position.y); Point pos; pos.x = mousePos.x; pos.y = mousePos.y; // If coordinats of point is invalid, then skip event. if (pos.x >= 0 && pos.y >= 0) { UINT8 buttons = mouseButtons; // If posititon of mouse isn't change, then don't send event to server. if (buttons != m_previousMouseState || !pos.isEqualTo(&m_previousMousePos)) { int wheelMask = MOUSE_WUP | MOUSE_WDOWN; // Update previously position of mouse. m_previousMouseState = buttons & ~wheelMask; m_previousMousePos = pos; if ((buttons & wheelMask) == 0) { // Send position of cursor and state of buttons one time. sendPointerEvent(buttons, &pos); } else { // Send position of cursor and state of buttons wheelSpeed times. for (int i = 0; i < wheelSpeed; i++) { sendPointerEvent(buttons, &pos); sendPointerEvent(buttons & ~wheelMask, &pos); } } // wheel } } return true; } bool DesktopWindow::onKey(WPARAM wParam, LPARAM lParam) { if (!m_conConf->isViewOnly()) { unsigned short virtualKey = static_cast<unsigned short>(wParam); unsigned int additionalInfo = static_cast<unsigned int>(lParam); static const unsigned int DOWN_FLAG = 0x80000000; bool isDown = (additionalInfo & DOWN_FLAG) == 0; if (virtualKey == VK_CONTROL) { m_ctrlDown = isDown; } if (virtualKey == VK_MENU) { m_altDown = isDown; } m_rfbKeySym->processKeyEvent(virtualKey, additionalInfo); } return true; } bool DesktopWindow::onChar(WPARAM wParam, LPARAM lParam) { if (!m_conConf->isViewOnly()) { m_rfbKeySym->processCharEvent(static_cast<WCHAR>(wParam), static_cast<unsigned int>(lParam)); } return true; } bool DesktopWindow::onDeadChar(WPARAM wParam, LPARAM lParam) { return true; } bool DesktopWindow::onDrawClipboard() { if (!IsWindowVisible(getHWnd()) || !m_conConf->isClipboardEnabled()) { return false; } StringStorage clipboardString; if (m_clipboard.getString(&clipboardString)) { // if string in clipboard got from server, then don't send him too if (clipboardString == m_strClipboard) { m_strClipboard = _T(""); return true; } m_strClipboard = _T(""); sendCutTextEvent(&clipboardString); } return true; } void DesktopWindow::setClipboardData(const StringStorage * strText) { if (m_conConf->isClipboardEnabled()) { m_clipboard.setString(strText); m_strClipboard.setString(strText->getString()); } } void DesktopWindow::doDraw(DeviceContext *dc) { AutoLock al(&m_bufferLock); int fbWidth = m_framebuffer.getDimension().width; int fbHeight = m_framebuffer.getDimension().height; if (!fbWidth || !fbHeight) { Graphics graphics(dc); graphics.fillRect(m_clientArea.left, m_clientArea.top, m_clientArea.right, m_clientArea.bottom, &m_brush); return; } scrollProcessing(fbWidth, fbHeight); int iHorzPos = 0; int iVertPos = 0; if (m_showHorz) { iHorzPos = m_sbar.getHorzPos(); } if (m_showVert) { iVertPos = m_sbar.getVertPos(); } m_scManager.setStartPoint(iHorzPos, iVertPos); Rect src, dst; m_scManager.getSourceRect(&src); m_scManager.getDestinationRect(&dst); int iWidth = m_clientArea.getWidth() - dst.getWidth(); int iHeight = m_clientArea.getHeight() - dst.getHeight(); if (iWidth || iHeight) { drawBackground(dc, &m_clientArea.toWindowsRect(), &dst.toWindowsRect()); } drawImage(&src.toWindowsRect(), &dst.toWindowsRect()); } void DesktopWindow::applyScrollbarChanges(bool isChanged, bool isVert, bool isHorz, int wndWidth, int wndHeight) { if (m_showVert != isVert) { m_showVert = isVert; m_sbar.showVertScroll(m_showVert); isChanged = true; } if (m_showHorz != isHorz) { m_showHorz = isHorz; m_sbar.showHorzScroll(m_showHorz); isChanged = true; } if (isChanged) { m_scManager.setWindow(&Rect(0, 0, wndWidth, wndHeight)); if (m_showVert) { m_sbar.setVertRange(0, m_scManager.getVertPoints(), wndHeight); } if (m_showHorz) { m_sbar.setHorzRange(0, m_scManager.getHorzPoints(), wndWidth); } calcClientArea(); } } void DesktopWindow::calculateWndSize(bool isChanged) { long hScroll = 0; long vScroll = 0; if (m_showVert) { vScroll = m_sbar.getVerticalSize(); } if (m_showHorz) { hScroll = m_sbar.getHorizontalSize(); } int wndWidth = vScroll + m_clientArea.getWidth(); int wndHeight = hScroll + m_clientArea.getHeight(); bool isVert = m_scManager.getVertPages(wndHeight); bool isHorz = m_scManager.getHorzPages(wndWidth); if (isHorz) { wndHeight -= m_sbar.getHorizontalSize(); } if (isVert) { wndWidth -= m_sbar.getVerticalSize(); } if (isVert != isHorz) { // need to recalculate bHorz and bVert isVert = m_scManager.getVertPages(wndHeight); isHorz = m_scManager.getHorzPages(wndWidth); if (isHorz) { wndHeight -= m_sbar.getHorizontalSize(); } if (isVert) { wndWidth -= m_sbar.getVerticalSize(); } } applyScrollbarChanges(isChanged, isVert, isHorz, wndWidth, wndHeight); } void DesktopWindow::scrollProcessing(int fbWidth, int fbHeight) { bool bChanged = false; if (m_winResize) { m_winResize = false; bChanged = true; } if (fbWidth != m_fbWidth || fbHeight != m_fbHeight) { bChanged = true; m_fbWidth = fbWidth; m_fbHeight = fbHeight; m_scManager.setScreenResolution(fbWidth, fbHeight); } calculateWndSize(bChanged); } void DesktopWindow::drawBackground(DeviceContext *dc, const RECT *rcMain, const RECT *rcImage) { Graphics graphics(dc); // top rectangle graphics.fillRect(rcMain->left, rcMain->top, rcMain->right, rcImage->top, &m_brush); // left rectangle graphics.fillRect(rcMain->left, rcImage->top, rcImage->left, rcImage->bottom, &m_brush); // bottom rectangle graphics.fillRect(rcMain->left, rcImage->bottom, rcMain->right, rcMain->bottom, &m_brush); // right rectangle graphics.fillRect(rcImage->right, rcImage->top, rcMain->right, rcImage->bottom, &m_brush); } void DesktopWindow::calcClientArea() { if (getHWnd()) { RECT rc; getClientRect(&rc); m_clientArea.fromWindowsRect(&rc); m_scManager.setWindow(&m_clientArea); } } void DesktopWindow::drawImage(const RECT *src, const RECT *dst) { Rect rc_src(src); Rect rc_dest(dst); AutoLock al(&m_bufferLock); if ((src->right - src->left) == (dst->right - dst->left) && (src->bottom - src->top) == (dst->bottom - dst->top) && src->left == dst->left && src->right == dst->right && src->top == dst->top && src->bottom == dst->bottom) { m_framebuffer.blitFromDibSection(&rc_dest); } else { m_framebuffer.stretchFromDibSection(&rc_dest, &rc_src); } } bool DesktopWindow::onSize(WPARAM wParam, LPARAM lParam) { calcClientArea(); m_winResize = true; return true; } bool DesktopWindow::onDestroy() { return true; } void DesktopWindow::updateFramebuffer(const FrameBuffer *framebuffer, const Rect *dstRect) { // This code doesn't require blocking of m_framebuffer. // // If in this moment Windows paint frame buffer to screen, // then image on viewer is not valid, but next update fix this // It is not critical. // // Size of framebuffer can not changed, because onFrameBufferUpdate() // and onFrameBufferPropChange() may be called only from one thread. if (!m_framebuffer.copyFrom(dstRect, framebuffer, dstRect->left, dstRect->top)) { m_logWriter->error(_T("Possible invalide region. (%d, %d), (%d, %d)"), dstRect->left, dstRect->top, dstRect->right, dstRect->bottom); m_logWriter->interror(_T("Error in updateFramebuffer (ViewerWindow)")); } repaint(dstRect); } void DesktopWindow::setNewFramebuffer(const FrameBuffer *framebuffer) { Dimension dimension = framebuffer->getDimension(); Dimension olddimension = m_framebuffer.getDimension(); bool isBackgroundDirty = dimension.width < olddimension.width || dimension.height < olddimension.height; m_logWriter->detail(_T("Desktop size: %d, %d"), dimension.width, dimension.height); { // FIXME: Nested locks should not be used. AutoLock al(&m_bufferLock); m_serverDimension = dimension; if (!dimension.isEmpty()) { // the width and height should be aligned to 4 int alignWidth = (dimension.width + 3) / 4; dimension.width = alignWidth * 4; int alignHeight = (dimension.height + 3) / 4; dimension.height = alignHeight * 4; m_framebuffer.setProperties(&dimension, &framebuffer->getPixelFormat(), getHWnd()); m_framebuffer.setColor(0, 0, 0); m_scManager.setScreenResolution(dimension.width, dimension.height); } else { // If size of remote frame buffer is (0, 0), then fill viewer. // Otherwise user might think that everything hangs. m_framebuffer.setColor(0, 0, 0); } } if (dimension.isEmpty()) { repaint(&dimension.getRect()); } else { m_isBackgroundDirty = isBackgroundDirty; } } void DesktopWindow::repaint(const Rect *repaintRect) { Rect rect; m_scManager.getSourceRect(&rect); Rect paint = repaintRect; paint.intersection(&rect); // checks what we getted a valid rectangle if (paint.getWidth() <= 1 || paint.getHeight() <= 1 || m_isBackgroundDirty) { m_isBackgroundDirty = false; redraw(); return; } Rect wnd; m_scManager.getWndFromScreen(&paint, &wnd); m_scManager.getDestinationRect(&rect); if (wnd.left) { --wnd.left; } if (wnd.top) { --wnd.top; } if (wnd.right < rect.right) { ++wnd.right; } if (wnd.bottom < rect.bottom) { ++wnd.bottom; } wnd.intersection(&rect); redraw(&wnd.toWindowsRect()); } void DesktopWindow::setScale(int scale) { AutoLock al(&m_bufferLock); m_scManager.setScale(scale); m_winResize = true; // Invalidate all area of desktop window. if (m_hWnd != 0) { redraw(); } } POINTS DesktopWindow::getViewerCoord(long xPos, long yPos) { Rect rect; POINTS p; m_scManager.getDestinationRect(&rect); // it checks this point in the rect if (!rect.isPointInRect(xPos, yPos)) { p.x = -1; p.y = -1; return p; } p = m_scManager.transformDispToScr(xPos, yPos); return p; } Rect DesktopWindow::getViewerGeometry() { Rect viewerRect; viewerRect.setHeight(m_scManager.getVertPoints()); viewerRect.setWidth(m_scManager.getHorzPoints()); if (viewerRect.area() == 0) { viewerRect.setWidth(m_framebuffer.getDimension().width); viewerRect.setHeight(m_framebuffer.getDimension().height); } return viewerRect; } Rect DesktopWindow::getFrameBufferGeometry() { AutoLock al(&m_bufferLock); return m_framebuffer.getDimension().getRect(); } void DesktopWindow::getServerGeometry(Rect *rect, int *pixelsize) { AutoLock al(&m_bufferLock); if (rect != 0) { *rect = m_serverDimension.getRect(); } if (pixelsize != 0) { *pixelsize = m_framebuffer.getBitsPerPixel(); } } void DesktopWindow::onRfbKeySymEvent(unsigned int rfbKeySym, bool down) { sendKeyboardEvent(down, rfbKeySym); } void DesktopWindow::setCtrlState(const bool ctrlState) { m_ctrlDown = ctrlState; } void DesktopWindow::setAltState(const bool altState) { m_altDown = altState; } bool DesktopWindow::getCtrlState() const { return m_ctrlDown; } bool DesktopWindow::getAltState() const { return m_altDown; } void DesktopWindow::sendKey(WCHAR key, bool pressed) { m_rfbKeySym->sendModifier(static_cast<unsigned char>(key), pressed); } void DesktopWindow::sendCtrlAltDel() { m_rfbKeySym->sendCtrlAltDel(); } void DesktopWindow::sendKeyboardEvent(bool downFlag, UINT32 key) { if (m_conConf->isViewOnly()) { return; } // If pointer to viewer core is 0, then exit. if (m_viewerCore == 0) { return; } // Trying send keyboard event... try { m_viewerCore->sendKeyboardEvent(downFlag, key); } catch (const Exception &exception) { m_logWriter->detail(_T("Error in DesktopWindow::sendKeyboardEvent(): %s"), exception.getMessage()); } } void DesktopWindow::sendPointerEvent(UINT8 buttonMask, const Point *position) { if (m_conConf->isViewOnly()) { return; } // If pointer to viewer core is 0, then exit. if (m_viewerCore == 0) { return; } // Trying send pointer event... try { m_viewerCore->sendPointerEvent(buttonMask, position); } catch (const Exception &exception) { m_logWriter->detail(_T("Error in DesktopWindow::sendPointerEvent(): %s"), exception.getMessage()); } } void DesktopWindow::sendCutTextEvent(const StringStorage *cutText) { if (!m_conConf->isClipboardEnabled()) { return; } // If pointer to viewer core is 0, then exit. if (m_viewerCore == 0) { return; } // Trying send cut-text event... try { m_viewerCore->sendCutTextEvent(cutText); } catch (const Exception &exception) { m_logWriter->detail(_T("Error in DesktopWindow::sendCutTextEvent(): %s"), exception.getMessage()); } }
25.966897
112
0.66286
jjzhang166
c269cf34b9be43e2bfaabb3f95d6f85dd8a86f6c
7,148
cpp
C++
1SST/10LW/array.cpp
AVAtarMod/University
3c784a1e109b7a6f6ea495278ec3dc126258625a
[ "BSD-3-Clause" ]
1
2021-07-31T06:55:08.000Z
2021-07-31T06:55:08.000Z
1SST/10LW/array.cpp
AVAtarMod/University-C
e516aac99eabbcbe14d897239f08acf6c8e146af
[ "BSD-3-Clause" ]
1
2020-11-25T12:00:11.000Z
2021-01-13T08:51:52.000Z
1SST/10LW/array.cpp
AVAtarMod/University-C
e516aac99eabbcbe14d897239f08acf6c8e146af
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <ctime> #include <random> #include "array.h" int getLenghtUser() { int length; while (true) { printf("Введите длину массива: "); scanf("%d", &length); if (length < 0) { std::cin.ignore(32767, '\n'); printf("Некорректное значение длины\n"); } if (length == 0){ printf("Длина = 0, работа программы будет завершена\n"); return 0; } else { std::cin.ignore(32767, '\n'); return length; } } } int getLenghtRandom(int minN, int maxN) { try { if (minN < 0) throw minN; } catch (int minN) { std::cerr << "ОШИБКА(minN =" << minN << "):minN должен быть > 0. "; } std::mt19937 engine(static_cast<unsigned long>(clock())); std::uniform_int_distribution<int> random(minN, maxN); return random(engine); } int getIndexUser(const int numberElementsArray, const char *reason) { int index; while (true) { printf("Введите индекс %s: ", reason); scanf("%d", &index); if (index < 0 || index > numberElementsArray) { printf("Введен некорректный индекс. Он должен быть числом от 0 до %d\n", numberElementsArray); } else { std::cin.ignore(32767, '\n'); return index; } } } int getElementUser(const char *reason) { int element; printf("Введите элемент (%s): ", reason); scanf("%d", &element); std::cin.ignore(32767, '\n'); return element; } void generateFromUser(int *array, int numberElements) { printf("Введите элементы массива через пробел: "); for (int i = 0; i < numberElements; i++) { int value; scanf("%d", &value); array[i] = value; } std::cin.ignore(32767, '\n'); } void generateRandom(int *array, int numberElements, int minNumber, int maxNumber) { std::mt19937 engine(static_cast<unsigned long>(clock())); std::uniform_int_distribution<int> random(minNumber, maxNumber); for (int i = 0; i < numberElements; i++) { array[i] = random(engine); } } int indexElement(const int *array, const int numberElements, const int number) { for (int i = 0; i < numberElements; i++) { if (array[i] == number) return i; } return -1; } int indexMinMaxElement(const int *array, int numberElements, bool comparator(int, int)) { int firstNumber = *array; int result = 0; for (int i = 1; i < numberElements; i++) { if (comparator(firstNumber, array[i])) { firstNumber = array[i]; result = i; } } return result; } int minMaxElement(const int *array, int numberElements, bool comparator(int, int)) { int firstNumber = *array; int result = 0; for (int i = 1; i < numberElements; i++) { if (comparator(firstNumber, array[i])) { firstNumber = array[i]; result = array[i]; } } return result; } int indexMinMaxElementWithConditions(const int *array, int numberElements, bool comparator(int, int), bool condition(int)) { int result = -1; int iFirstNumber = 0; for (int i = 1; i < numberElements; i++) { int secNum = array[i]; if (condition(array[i])) { if (comparator(array[iFirstNumber], secNum)) { result = iFirstNumber; } else { result = iFirstNumber = i; } } } return result; } int *searchIndexElements(const int *array, const int numberElements, const int number) { int counter = 0; for (int i = 0; i < numberElements; i++) { if (array[i] == number) { ++counter; } } int *arrayResult = new int[counter + 1]; arrayResult[0] = counter + 1; for (int i = 0, iRes = 1; i < numberElements; i++) { if (array[i] == number) { arrayResult[iRes] = i; //Заполняем arrayResult iRes++; } } if (arrayResult[0] == 0) { delete[] arrayResult; return nullptr; } else return arrayResult; } int *elementsRelevantConditions(int *array, int numberElements, bool condition(int number)) { int *arrayResult = new int[numberElements]; int lnResult = 1; for (int i = 0; i < numberElements; i++) { if (condition(array[i])) { arrayResult[lnResult] = array[i]; arrayResult[0] = lnResult; lnResult++; } } if (arrayResult[0] == 0) { delete[] arrayResult; return nullptr; } else { int *result = new int[lnResult - 1]; result[0] = lnResult - 1; for (int i = 1; i <= lnResult; i++) { result[i] = arrayResult[i]; } delete[] arrayResult; return result; } } void deleteElement(int **array, int &numberElements, int element, int offset) { --numberElements; int *arrayResult = new int[numberElements]; for (int i = offset, iRes = 0; i < numberElements; i++) { if ((*array)[i] != element) { arrayResult[iRes] = (*array)[i]; iRes++; } } delete[] * array; *array = arrayResult; } void deleteElements(int **array, int &numberElements, int element, int offset) { int counter = 0; for (int i = offset; i < numberElements; i++) { if ((*array)[i] != element) { counter++; } } bool needDelete = (counter == numberElements - offset) ? false : true; if (needDelete) { int *arrayResult = new int[counter]; int iRes = 0; for (int i = offset; i < numberElements; i++) { if ((*array)[i] != element) { arrayResult[iRes] = (*array)[i]; iRes++; } } numberElements = counter; delete[] * array; *array = arrayResult; } } void pasteElement(int **array, int &numberElements, int index, int element) { ++numberElements; int *arrayResult = new int[numberElements]; for (int i = 0, iRes = 0; i < numberElements - 1; i++) { if (i == index) { arrayResult[iRes] = element; iRes++; } arrayResult[iRes] = (*array)[i]; iRes++; } delete[] * array; *array = arrayResult; } void print(const int *array, const int numberElements, const char *text, const int offset) { printf("Значения массива %s : [ ", text); for (int i = offset; i < numberElements; i++) { printf("%d, ", array[i]); } printf("\b\b ]\n"); } bool isAMax(const int a, const int b) { return (a > b); } bool isAMin(const int a, const int b) { return (a < b); } bool isOdd(const int number) { return (abs(number % 2) == 1); } bool isEven(const int number) { return (abs(number % 2) == 0); }
21.53012
122
0.522943
AVAtarMod
c26b1c2ef0eddd55c4891fd79097dfbab0e536a1
1,446
cc
C++
tensorflow/core/kernels/string_to_hash_bucket_ali_op.cc
aalbersk/DeepRec
f673a950780959b44dcda99398880a1d883ab338
[ "Apache-2.0" ]
292
2021-12-24T03:24:33.000Z
2022-03-31T15:41:05.000Z
tensorflow/core/kernels/string_to_hash_bucket_ali_op.cc
aalbersk/DeepRec
f673a950780959b44dcda99398880a1d883ab338
[ "Apache-2.0" ]
54
2021-12-24T06:40:09.000Z
2022-03-30T07:57:24.000Z
tensorflow/core/kernels/string_to_hash_bucket_ali_op.cc
aalbersk/DeepRec
f673a950780959b44dcda99398880a1d883ab338
[ "Apache-2.0" ]
75
2021-12-24T04:48:21.000Z
2022-03-29T10:13:39.000Z
/* 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. ==============================================================================*/ #include "tensorflow/core/kernels/string_to_hash_bucket_ali_op.h" #include "tensorflow/core/platform/strong_hash.h" namespace tensorflow { // StringToHashBucket is deprecated in favor of StringToHashBucketFast/Strong. REGISTER_KERNEL_BUILDER(Name("StringToHashBucketFast").Device(DEVICE_CPU), StringToHashBucketBatchAliOp<Fingerprint64>); REGISTER_KERNEL_BUILDER(Name("StringToHashBucketStrong").Device(DEVICE_CPU), StringToKeyedHashBucketAliOp<StrongKeyedHash>); REGISTER_KERNEL_BUILDER(Name("StringToHash64").Device(DEVICE_CPU), StringToHash64Op<Fingerprint64>); REGISTER_KERNEL_BUILDER(Name("StringToHash").Device(DEVICE_CPU), StringToHashOp); } // namespace tensorflow
41.314286
80
0.719225
aalbersk
c26c7d7193b82466092b84f798666991c121f3ef
4,170
cpp
C++
TrafficManager/source/pipeline/executable/PipelineExecutable.cpp
owoschhodan/carla
7da99d882afb4160f0901bbbac2ea2866683e314
[ "MIT" ]
8
2019-11-27T18:43:09.000Z
2022-01-16T06:08:36.000Z
TrafficManager/source/pipeline/executable/PipelineExecutable.cpp
tcwangjiawei/carla
714f8c4cbfbb46fa9ed163a27c94ede613948767
[ "MIT" ]
null
null
null
TrafficManager/source/pipeline/executable/PipelineExecutable.cpp
tcwangjiawei/carla
714f8c4cbfbb46fa9ed163a27c94ede613948767
[ "MIT" ]
5
2020-05-12T20:03:10.000Z
2022-02-25T14:40:07.000Z
#include <atomic> #include <cstdlib> #include <ctime> #include <execinfo.h> #include <iostream> #include <signal.h> #include <stdexcept> #include <random> #include "boost/stacktrace.hpp" #include "carla/client/Client.h" #include "carla/client/TimeoutException.h" #include "carla/Logging.h" #include "carla/Memory.h" #include "CarlaDataAccessLayer.h" #include "InMemoryMap.h" #include "Pipeline.h" namespace cc = carla::client; using Actor = carla::SharedPtr<cc::Actor>; void run_pipeline(cc::World &world, cc::Client &client_conn, uint target_traffic_amount, uint randomization_seed); std::atomic<bool> quit(false); void got_signal(int) { quit.store(true); } std::vector<Actor> *global_actor_list; void handler() { if (!quit.load()) { carla::log_error("\nTrafficManager encountered a problem!\n"); carla::log_info("Destroying all spawned actors\n"); for (auto &actor: *global_actor_list) { if (actor != nullptr && actor->IsAlive()) { actor->Destroy(); } } // Uncomment the below line if compiling with debug options (in CMakeLists.txt) // std::cout << boost::stacktrace::stacktrace() << std::endl; exit(1); } } int main(int argc, char *argv[]) { std::set_terminate(handler); cc::Client client_conn = cc::Client("localhost", 2000); cc::World world = client_conn.GetWorld(); if (argc == 2 && std::string(argv[1]) == "-h") { std::cout << "\nAvailable options\n"; std::cout << "[-n] \t\t Number of vehicles to be spawned\n"; std::cout << "[-s] \t\t System randomization seed integer\n"; } else { uint target_traffic_amount = 0u; if (argc >= 3 && std::string(argv[1]) == "-n") { try { target_traffic_amount = std::stoi(argv[2]); } catch (const std::exception &e) { carla::log_warning("Failed to parse argument, choosing defaults\n"); } } int randomization_seed = -1; if (argc == 5 && std::string(argv[3]) == "-s") { try { randomization_seed = std::stoi(argv[4]); } catch (const std::exception &e) { carla::log_warning("Failed to parse argument, choosing defaults\n"); } } if (randomization_seed < 0) { std::srand(std::time(0)); } else { std::srand(randomization_seed); } run_pipeline(world, client_conn, target_traffic_amount, randomization_seed); } return 0; } void run_pipeline(cc::World &world, cc::Client &client_conn, uint target_traffic_amount, uint randomization_seed) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = got_signal; sigfillset(&sa.sa_mask); sigaction(SIGINT, &sa, NULL); using WorldMap = carla::SharedPtr<cc::Map>; WorldMap world_map = world.GetMap(); cc::DebugHelper debug_helper = client_conn.GetWorld().MakeDebugHelper(); auto dao = traffic_manager::CarlaDataAccessLayer(world_map); using Topology = std::vector<std::pair<traffic_manager::WaypointPtr, traffic_manager::WaypointPtr>>; Topology topology = dao.GetTopology(); auto local_map = std::make_shared<traffic_manager::InMemoryMap>(topology); local_map->SetUp(1.0); uint core_count = traffic_manager::read_core_count(); std::vector<Actor> registered_actors = traffic_manager::spawn_traffic( client_conn, world, core_count, target_traffic_amount); global_actor_list = &registered_actors; client_conn.SetTimeout(2s); traffic_manager::Pipeline pipeline( {0.1f, 0.15f, 0.01f}, {5.0f, 0.0f, 0.1f}, {10.0f, 0.01f, 0.1f}, 25 / 3.6, 50 / 3.6, registered_actors, *local_map.get(), client_conn, world, debug_helper, 1 ); try { pipeline.Start(); carla::log_info("TrafficManager started\n"); while (!quit.load()) { sleep(1); // Periodically polling if Carla is still running world.GetSettings(); } } catch(const cc::TimeoutException& e) { carla::log_error("Carla has stopped running, stopping TrafficManager\n"); } pipeline.Stop(); traffic_manager::destroy_traffic(registered_actors, client_conn); carla::log_info("\nTrafficManager stopped by user\n"); }
27.077922
102
0.653717
owoschhodan
c26de97d14789617812bcf406a1ea5d8e443c509
2,236
cpp
C++
src/states.cpp
SuprDewd/states
68f89c8e60767819b0b9d0218bb14f6e8b4fac89
[ "MIT" ]
4
2015-01-09T16:54:26.000Z
2018-10-29T13:07:59.000Z
src/states.cpp
SuprDewd/states
68f89c8e60767819b0b9d0218bb14f6e8b4fac89
[ "MIT" ]
null
null
null
src/states.cpp
SuprDewd/states
68f89c8e60767819b0b9d0218bb14f6e8b4fac89
[ "MIT" ]
2
2016-07-27T02:54:49.000Z
2018-04-11T17:04:07.000Z
#include <iostream> #include <cstdlib> #include <cstdio> #include <map> #include <set> #include <string> #include <list> #include <queue> #include <cstring> #include <cassert> #include "utils.h" #include "nfa.h" #include "regex.h" #include "machine.h" #include "ast.h" #include "converters.h" using namespace std; extern int yyparse(); extern FILE *yyin; extern ast_program *main_program; int main(int argc, char **argv) { if (argc != 3) { fprintf(stderr, "usage: states OP FILE\n"); return 1; } yyin = fopen(argv[2], "r"); if (yyparse()) { // something went wrong exit(1); } #if DEBUG main_program->print(cout); #endif machine *m; switch (main_program->machine->get_ast_machine_type()) { case AST_MACHINE_NFA: m = nfa_from_ast((ast_nfa*)main_program->machine); break; case AST_MACHINE_REGEX: m = regex_from_ast((ast_regex*)main_program->machine); break; default: assert(false); } // nfa *S = nfa_from_ast(main_program->nfa); // for (nfa::iterator it = S->begin(); it != S->end(); ++it) { // cout << *it << endl; // } // int len = 0, cnt = 0; // for (nfa::iterator it = S->begin(); it != S->end(); ++it) { // if (size(*it) == len) { // cnt++; // } else { // while (len != size(*it)) { // printf("%d %d\n", len, cnt); // len++; // cnt = 0; // } // cnt = 1; // } // } if (strcmp(argv[1], "grep") == 0) { string line; while (getline(cin, line)) { DEBUGMSG("read '%s'\n", line.c_str()); if (m->accepts(line)) { printf("%s\n", line.c_str()); } } } else if (strcmp(argv[1], "nfa2regex") == 0) { if (main_program->machine->get_ast_machine_type() != AST_MACHINE_NFA) { fprintf(stderr, "error: input must be an nfa\n"); return 1; } regex *res = nfa2regex((nfa*)m); cout << res->to_string() << endl; delete res; } else { fprintf(stderr, "error: unsupported op '%s'\n", argv[1]); return 1; } return 0; }
21.921569
93
0.507603
SuprDewd
c26fb5005c411bdc7b149d327ada6451689f9cba
117
cpp
C++
test/minimizer_test.cpp
dehui333/Course-GenomeMapper
cab7b42078be84991e5e8f773afa04af4ce87bc6
[ "MIT" ]
null
null
null
test/minimizer_test.cpp
dehui333/Course-GenomeMapper
cab7b42078be84991e5e8f773afa04af4ce87bc6
[ "MIT" ]
null
null
null
test/minimizer_test.cpp
dehui333/Course-GenomeMapper
cab7b42078be84991e5e8f773afa04af4ce87bc6
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include "minimizer.cpp" TEST(MinimizerTest, MinimizerTest1) { ASSERT_EQ(1, 1); }
10.636364
37
0.675214
dehui333
c2709c8418a84405b7cfe708f743228ba5ebfdd1
149
cpp
C++
examples/reference-ASSERT_NE_UNLABELED.cpp
gcross/Illuminate
862f665ccd4b67411bc332f534e1655585750823
[ "0BSD" ]
null
null
null
examples/reference-ASSERT_NE_UNLABELED.cpp
gcross/Illuminate
862f665ccd4b67411bc332f534e1655585750823
[ "0BSD" ]
null
null
null
examples/reference-ASSERT_NE_UNLABELED.cpp
gcross/Illuminate
862f665ccd4b67411bc332f534e1655585750823
[ "0BSD" ]
null
null
null
#include "illuminate.hpp" TEST_CASE(ASSERT_NE_UNLABELED) { ASSERT_NE_UNLABELED(1,2) ASSERT_NE_UNLABELED(1,1) ASSERT_NE_UNLABELED(0,0) }
18.625
32
0.744966
gcross
c2712c92e04442dd25dbe6a9f193832c304fd7be
9,920
cpp
C++
src/prod/src/data/integration/Replica.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
1
2018-03-15T02:09:21.000Z
2018-03-15T02:09:21.000Z
src/prod/src/data/integration/Replica.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
null
null
null
src/prod/src/data/integration/Replica.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
null
null
null
// ------------------------------------------------------------ // 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 Data::Integration; using namespace ktl; using namespace Common; using namespace Data::Utilities; using namespace TxnReplicator; using namespace Data::TestCommon; using namespace Data::TStore; Replica::SPtr Replica::Create( __in KGuid const & pId, __in LONG64 replicaId, __in wstring const & workFolder, __in Data::Log::LogManager & logManager, __in KAllocator & allocator, __in_opt Data::StateManager::IStateProvider2Factory * stateProviderFactory, __in_opt TRANSACTIONAL_REPLICATOR_SETTINGS const * const settings, __in_opt TxnReplicator::IDataLossHandler * const dataLossHandler) { Replica * value = _new(REPLICA_TAG, allocator) Replica(pId, replicaId, workFolder, logManager, stateProviderFactory, settings, dataLossHandler); THROW_ON_ALLOCATION_FAILURE(value); return Replica::SPtr(value); } TxnReplicator::ITransactionalReplicator::SPtr Replica::get_TxnReplicator() const { return transactionalReplicator_; } ktl::Awaitable<void> Replica::OpenAsync() { KShared$ApiEntry(); AwaitableCompletionSource<HRESULT>::SPtr acs = nullptr; NTSTATUS status = ktl::AwaitableCompletionSource<HRESULT>::Create(GetThisAllocator(), GetThisAllocationTag(), acs); CODING_ERROR_ASSERT(NT_SUCCESS(status)); Awaitable<HRESULT> openAwaitable = acs->GetAwaitable(); ComPointer<Data::TestCommon::ComAsyncOperationCallbackTestHelper > openCallback = make_com<Data::TestCommon::ComAsyncOperationCallbackTestHelper>( [this, acs](IFabricAsyncOperationContext * context) { ComPointer<IFabricStringResult> endpoint; HRESULT tmpHr = primaryReplicator_->EndOpen(context, endpoint.InitializationAddress()); CODING_ERROR_ASSERT(SUCCEEDED(tmpHr)); acs->SetResult(tmpHr); }); ComPointer<IFabricAsyncOperationContext> openContext; HRESULT hr = primaryReplicator_->BeginOpen(openCallback.GetRawPointer(), openContext.InitializationAddress()); CODING_ERROR_ASSERT(SUCCEEDED(hr)); hr = co_await openAwaitable; CODING_ERROR_ASSERT(SUCCEEDED(hr)); co_return; } ktl::Awaitable<void> Replica::ChangeRoleAsync( __in FABRIC_EPOCH epoch, __in FABRIC_REPLICA_ROLE newRole) { KShared$ApiEntry(); FABRIC_EPOCH tmpEpoch(epoch); AwaitableCompletionSource<HRESULT>::SPtr acs = nullptr; NTSTATUS status = ktl::AwaitableCompletionSource<HRESULT>::Create(GetThisAllocator(), GetThisAllocationTag(), acs); CODING_ERROR_ASSERT(NT_SUCCESS(status)); Awaitable<HRESULT> changeRoleAwaitable = acs->GetAwaitable(); ComPointer<Data::TestCommon::ComAsyncOperationCallbackTestHelper> changeRoleCallback = make_com<Data::TestCommon::ComAsyncOperationCallbackTestHelper>( [this, acs](IFabricAsyncOperationContext * context) { HRESULT tmpHr = primaryReplicator_->EndChangeRole(context); CODING_ERROR_ASSERT(SUCCEEDED(tmpHr)); acs->SetResult(tmpHr); }); ComPointer<IFabricAsyncOperationContext> changeRoleContext; HRESULT hr = primaryReplicator_->BeginChangeRole( &tmpEpoch, newRole, changeRoleCallback.GetRawPointer(), changeRoleContext.InitializationAddress()); CODING_ERROR_ASSERT(SUCCEEDED(hr)); hr = co_await changeRoleAwaitable; CODING_ERROR_ASSERT(SUCCEEDED(hr)); co_return; }; ktl::Awaitable<void> Replica::CloseAsync() { KShared$ApiEntry(); AwaitableCompletionSource<HRESULT>::SPtr acs = nullptr; NTSTATUS status = ktl::AwaitableCompletionSource<HRESULT>::Create(GetThisAllocator(), GetThisAllocationTag(), acs); CODING_ERROR_ASSERT(NT_SUCCESS(status)); Awaitable<HRESULT> closeAwaitable = acs->GetAwaitable(); // Close the Replicator ComPointer<Data::TestCommon::ComAsyncOperationCallbackTestHelper > closeCallback = make_com<Data::TestCommon::ComAsyncOperationCallbackTestHelper>( [this, acs](IFabricAsyncOperationContext * context) { HRESULT tmpHr = primaryReplicator_->EndClose(context); CODING_ERROR_ASSERT(SUCCEEDED(tmpHr)); acs->SetResult(tmpHr); }); ComPointer<IFabricAsyncOperationContext> closeContext; HRESULT hr = primaryReplicator_->BeginClose(closeCallback.GetRawPointer(), closeContext.InitializationAddress()); CODING_ERROR_ASSERT(SUCCEEDED(hr)); hr = co_await closeAwaitable; CODING_ERROR_ASSERT(SUCCEEDED(hr)); co_return; } ktl::Awaitable<NTSTATUS> Replica::OnDataLossAsync( __out BOOLEAN & isStateChanged) { KShared$ApiEntry(); AwaitableCompletionSource<HRESULT>::SPtr acs = nullptr; NTSTATUS status = ktl::AwaitableCompletionSource<HRESULT>::Create(GetThisAllocator(), GetThisAllocationTag(), acs); CODING_ERROR_ASSERT(NT_SUCCESS(status)); Awaitable<HRESULT> onDataLossAwaitable = acs->GetAwaitable(); ComPointer<Data::TestCommon::ComAsyncOperationCallbackTestHelper > dataLossCallback = make_com<Data::TestCommon::ComAsyncOperationCallbackTestHelper>( [this, acs, &isStateChanged](IFabricAsyncOperationContext * context) { HRESULT tmpHr = primaryReplicator_->EndOnDataLoss(context, &isStateChanged); acs->SetResult(tmpHr); }); ComPointer<IFabricAsyncOperationContext> dataLossContext; HRESULT hr = primaryReplicator_->BeginOnDataLoss(dataLossCallback.GetRawPointer(), dataLossContext.InitializationAddress()); CODING_ERROR_ASSERT(SUCCEEDED(hr)); hr = co_await onDataLossAwaitable; co_return StatusConverter::Convert(hr); } void Replica::SetReadStatus(__in FABRIC_SERVICE_PARTITION_ACCESS_STATUS readStatus) { partition_->SetReadStatus(readStatus); } void Replica::SetWriteStatus(__in FABRIC_SERVICE_PARTITION_ACCESS_STATUS writeStatus) { partition_->SetWriteStatus(writeStatus); } Replica::Replica( __in KGuid const & partitionId, __in LONG64 replicaId, __in wstring const & workFolder, __in Data::Log::LogManager & logManager, __in Data::StateManager::IStateProvider2Factory * stateProviderFactory, __in TRANSACTIONAL_REPLICATOR_SETTINGS const * const settings, __in_opt TxnReplicator::IDataLossHandler * const dataLossHandler) : Common::ComponentRoot() , KObject() , KShared() { NTSTATUS status = STATUS_UNSUCCESSFUL; HANDLE handle = nullptr; PartitionedReplicaId::SPtr partitionedReplicaIdCSPtr = PartitionedReplicaId::Create(partitionId, replicaId, GetThisAllocator()); partition_ = TestComStatefulServicePartition::Create( partitionId, GetThisAllocator()); partition_->SetReadStatus(FABRIC_SERVICE_PARTITION_ACCESS_STATUS_NOT_PRIMARY); partition_->SetWriteStatus(FABRIC_SERVICE_PARTITION_ACCESS_STATUS_NOT_PRIMARY); TestComCodePackageActivationContext::SPtr codePackage = TestComCodePackageActivationContext::Create( workFolder.c_str(), GetThisAllocator()); Reliability::ReplicationComponent::ReplicatorFactoryConstructorParameters replicatorFactoryConstructorParameters; replicatorFactoryConstructorParameters.Root = this; replicatorFactory_ = Reliability::ReplicationComponent::ReplicatorFactoryFactory(replicatorFactoryConstructorParameters); replicatorFactory_->Open(L"empty"); TransactionalReplicatorFactoryConstructorParameters transactionalReplicatorFactoryConstructorParameters; transactionalReplicatorFactoryConstructorParameters.Root = this; transactionalReplicatorFactory_ = TransactionalReplicatorFactoryFactory(transactionalReplicatorFactoryConstructorParameters); transactionalReplicatorFactory_->Open(static_cast<KtlSystemBase &>(GetThisKtlSystem()), logManager); ComPointer<IFabricStateProvider2Factory> comFactory; if (stateProviderFactory == nullptr) { StoreStateProviderFactory::SPtr factory = StoreStateProviderFactory::CreateIntIntFactory(GetThisAllocator()); comFactory = TxnReplicator::TestCommon::TestComStateProvider2Factory::Create( *factory, GetThisAllocator()); } else { comFactory = TxnReplicator::TestCommon::TestComStateProvider2Factory::Create( *stateProviderFactory, GetThisAllocator()); } TxnReplicator::IDataLossHandler::SPtr localDataLossHandlerSPtr = dataLossHandler; if (localDataLossHandlerSPtr == nullptr) { localDataLossHandlerSPtr = TxnReplicator::TestCommon::TestDataLossHandler::Create(GetThisAllocator()).RawPtr(); } ComPointer<IFabricDataLossHandler> comProxyDataLossHandler = TxnReplicator::TestCommon::TestComProxyDataLossHandler::Create( GetThisAllocator(), localDataLossHandlerSPtr.RawPtr()); status = transactionalReplicatorFactory_->CreateReplicator( replicaId, *replicatorFactory_, partition_.RawPtr(), nullptr, settings, nullptr, *codePackage, TRUE, nullptr, comFactory.GetRawPointer(), comProxyDataLossHandler.GetRawPointer(), primaryReplicator_.InitializationAddress(), &handle); ITransactionalReplicator * txnReplicatorPtr = static_cast<ITransactionalReplicator *>(handle); CODING_ERROR_ASSERT(txnReplicatorPtr != nullptr); transactionalReplicator_.Attach(txnReplicatorPtr); CODING_ERROR_ASSERT(primaryReplicator_.GetRawPointer() != nullptr); CODING_ERROR_ASSERT(transactionalReplicator_ != nullptr); } Replica::~Replica() { replicatorFactory_->Close(); replicatorFactory_.reset(); transactionalReplicatorFactory_->Close(); transactionalReplicatorFactory_.reset(); primaryReplicator_.Release(); transactionalReplicator_.Reset(); }
37.293233
155
0.746069
AnthonyM
c272878d22ffd75a182841caa6edecebed57c34a
3,233
cpp
C++
classes/Grid.cpp
sbu-test-lab/cs-cpp-tetris
7759c3f22eebef6dc9dac2bc6e1a1dea3022e7c6
[ "Apache-2.0" ]
null
null
null
classes/Grid.cpp
sbu-test-lab/cs-cpp-tetris
7759c3f22eebef6dc9dac2bc6e1a1dea3022e7c6
[ "Apache-2.0" ]
null
null
null
classes/Grid.cpp
sbu-test-lab/cs-cpp-tetris
7759c3f22eebef6dc9dac2bc6e1a1dea3022e7c6
[ "Apache-2.0" ]
null
null
null
#include "Grid.h" namespace WinTetris { Grid::Grid(int w, int h) : width(w), height(h) { //C# TO C++ CONVERTER NOTE: The following call to the 'RectangularVectors' helper class reproduces the rectangular array initialization that is automatic in C#: //ORIGINAL LINE: occupied = new bool[w, h]; occupied = RectangularVectors::RectangularBoolVector(w, h); } void Grid::FillCell(int x, int y) { occupied[x][y] = true; } void Grid::UnFillCell(int x, int y) { occupied[x][y] = false; } bool Grid::isFinish(Grid *block) { for (int i = 0; i < block->occupied.size(); i++) { for (int j = 0; j < (block->occupied.size() == 0 ? 0 : block->occupied[0].size()); j++) { if (block->occupied[i][j]) { if (j == 0 || this->occupied[i][j - 1]) { return true; } } } } return false; } std::vector<std::vector<bool>> Grid::Union(std::vector<std::vector<bool>> &c1, std::vector<std::vector<bool>> &c2) { //C# TO C++ CONVERTER NOTE: The following call to the 'RectangularVectors' helper class reproduces the rectangular array initialization that is automatic in C#: //ORIGINAL LINE: bool[,] result = new bool[c1.GetLength(0), c1.GetLength(1)]; std::vector<std::vector<bool>> result = RectangularVectors::RectangularBoolVector(c1.size(), (c1.size() == 0 ? 0 : c1[0].size())); for (int i = 0; i < result.size(); i++) { for (int j = 0; j < (result.size() == 0 ? 0 : result[0].size()); j++) { result[i][j] = c1[i][j] | c2[i][j]; } } return result; } bool Grid::isRow(int index, bool predicate) { Grid *g = this; int w = g->occupied.size(); bool r = true; for (int i = 0; i < w; i++) { if (g->occupied[i][index] != predicate) { r = false; } } return r; } bool Grid::isColumn(int index, bool predicate) { Grid *g = this; int h = (g->occupied.size() == 0 ? 0 : g->occupied[0].size()); bool r = true; for (int i = 0; i < h; i++) { if (g->occupied[index][i] != predicate) { r = false; } } return r; } void Grid::ShiftToLeft() { Grid *g = this; int w = g->occupied.size(); int h = (g->occupied.size() == 0 ? 0 : g->occupied[0].size()); for (int i = 1; i < w; i++) { for (int j = 0; j < h; j++) { g->occupied[i - 1][j] = g->occupied[i][j]; } } for (int j = 0; j < h; j++) { g->occupied[w - 1][j] = false; } } void Grid::ShiftToRight() { Grid *g = this; int w = g->occupied.size(); int h = (g->occupied.size() == 0 ? 0 : g->occupied[0].size()); for (int i = w - 1; i > 0; i--) { for (int j = 0; j < h; j++) { g->occupied[i][j] = g->occupied[i - 1][j]; } } for (int j = 0; j < h; j++) { g->occupied[0][j] = false; } } void Grid::ShiftToDown(int index) { Grid *g = this; int w = g->occupied.size(); int h = (g->occupied.size() == 0 ? 0 : g->occupied[0].size()); for (int j = index + 1; j < h; j++) { for (int i = 0; i < w; i++) { g->occupied[i][j - 1] = g->occupied[i][j]; } } for (int i = 0; i < w; i++) { g->occupied[i][h - 1] = false; } } }
22.296552
161
0.51129
sbu-test-lab
c2785f5dd84b48f18fd0223e9435eaeb425242d7
35,494
cpp
C++
isis/tests/FunctionalTestsHidtmgen.cpp
kdl222/ISIS3
aab0e63088046690e6c031881825596c1c2cc380
[ "CC0-1.0" ]
134
2018-01-18T00:16:24.000Z
2022-03-24T03:53:33.000Z
isis/tests/FunctionalTestsHidtmgen.cpp
kdl222/ISIS3
aab0e63088046690e6c031881825596c1c2cc380
[ "CC0-1.0" ]
3,825
2017-12-11T21:27:34.000Z
2022-03-31T21:45:20.000Z
isis/tests/FunctionalTestsHidtmgen.cpp
jlaura/isis3
2c40e08caed09968ea01d5a767a676172ad20080
[ "CC0-1.0" ]
164
2017-11-30T21:15:44.000Z
2022-03-23T10:22:29.000Z
#include <QTemporaryFile> #include "Fixtures.h" #include "Pvl.h" #include "PvlGroup.h" #include "TestUtilities.h" #include "gmock/gmock.h" #include "UserInterface.h" #include "hidtmgen.h" #include "ProcessImportPds.h" using namespace Isis; using ::testing::HasSubstr; static QString APP_XML = FileName("$ISISROOT/bin/xml/hidtmgen.xml").expanded(); TEST(Hidtmgen, HidtmgenTestColor){ //Serves as default test case -- test all keywords for all generated products. QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/color/orthoInputList.txt", "paramspvl=data/hidtmgen/color/params.pvl", "orthosequencenumberlist=data/hidtmgen/color/sequenceNumbers.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); } catch (IException &e) { FAIL() << "Unable to HIRISE generate PDS products: " << e.toString().toStdString().c_str() << std::endl; } Pvl dtmLabel(prefix.path()+"/DTEEZ_042252_1930_042753_1930_A31.IMG"); ASSERT_EQ(dtmLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(dtmLabel["RECORD_BYTES"], 32); ASSERT_DOUBLE_EQ(dtmLabel["FILE_RECORDS"], 155); ASSERT_DOUBLE_EQ(dtmLabel["^IMAGE"], 133); ASSERT_EQ(dtmLabel["DATA_SET_ID"][0].toStdString(), "MRO-M-HIRISE-5-DTM-V1.0"); ASSERT_EQ(dtmLabel["PRODUCER_INSTITUTION_NAME"][0].toStdString(), "UNIVERSITY OF ARIZONA"); ASSERT_EQ(dtmLabel["PRODUCER_ID"][0].toStdString(), "UA"); ASSERT_EQ(dtmLabel["PRODUCER_FULL_NAME"][0].toStdString(), "ALFRED MCEWEN"); ASSERT_EQ(dtmLabel["PRODUCT_ID"][0].toStdString(), "DTEEZ_042252_1930_042753_1930_A31"); ASSERT_DOUBLE_EQ(dtmLabel["PRODUCT_VERSION_ID"], 0.314); ASSERT_EQ(dtmLabel["INSTRUMENT_HOST_NAME"][0].toStdString(), "MARS RECONNAISSANCE ORBITER"); ASSERT_EQ(dtmLabel["INSTRUMENT_NAME"][0].toStdString(), "HIGH RESOLUTION IMAGING SCIENCE EXPERIMENT"); ASSERT_EQ(dtmLabel["INSTRUMENT_ID"][0].toStdString(), "HIRISE"); ASSERT_EQ(dtmLabel["TARGET_NAME"][0].toStdString(), "MARS"); ASSERT_EQ(dtmLabel["SOURCE_PRODUCT_ID"][0].toStdString(), "ESP_042252_1930"); ASSERT_EQ(dtmLabel["SOURCE_PRODUCT_ID"][1].toStdString(), "ESP_042753_1930"); ASSERT_EQ(dtmLabel["RATIONALE_DESC"][0].toStdString(), "NULL"); PvlObject dtmImage = dtmLabel.findObject("IMAGE"); ASSERT_DOUBLE_EQ(dtmImage["LINES"], 23); ASSERT_DOUBLE_EQ(dtmImage["LINE_SAMPLES"], 8); ASSERT_DOUBLE_EQ(dtmImage["BANDS"], 1); ASSERT_DOUBLE_EQ(dtmImage["OFFSET"], 0.0); ASSERT_DOUBLE_EQ(dtmImage["SCALING_FACTOR"], 1.0); ASSERT_DOUBLE_EQ(dtmImage["SAMPLE_BITS"], 32); ASSERT_EQ(dtmImage["SAMPLE_BIT_MASK"][0].toStdString(), "2#11111111111111111111111111111111#"); ASSERT_EQ(dtmImage["SAMPLE_TYPE"][0].toStdString(), "PC_REAL"); ASSERT_EQ(dtmImage["MISSING_CONSTANT"][0].toStdString(), "16#FF7FFFFB#"); ASSERT_DOUBLE_EQ(dtmImage["VALID_MINIMUM"], -1884.17); ASSERT_DOUBLE_EQ(dtmImage["VALID_MAXIMUM"], -1324.12); PvlObject dtmProj = dtmLabel.findObject("IMAGE_MAP_PROJECTION"); ASSERT_EQ(dtmProj["^DATA_SET_MAP_PROJECTION"][0].toStdString(), "DSMAP.CAT"); ASSERT_EQ(dtmProj["MAP_PROJECTION_TYPE"][0].toStdString(), "EQUIRECTANGULAR"); ASSERT_EQ(dtmProj["PROJECTION_LATITUDE_TYPE"][0].toStdString(), "PLANETOCENTRIC"); ASSERT_DOUBLE_EQ(dtmProj["A_AXIS_RADIUS"], 3396.19); ASSERT_DOUBLE_EQ(dtmProj["B_AXIS_RADIUS"], 3396.19); ASSERT_DOUBLE_EQ(dtmProj["C_AXIS_RADIUS"], 3396.19); ASSERT_EQ(dtmProj["COORDINATE_SYSTEM_NAME"][0].toStdString(), "PLANETOCENTRIC"); ASSERT_EQ(dtmProj["POSITIVE_LONGITUDE_DIRECTION"][0].toStdString(), "EAST"); ASSERT_EQ(dtmProj["KEYWORD_LATITUDE_TYPE"][0].toStdString(), "PLANETOCENTRIC"); ASSERT_DOUBLE_EQ(dtmProj["CENTER_LATITUDE"], 0.0); ASSERT_DOUBLE_EQ(dtmProj["CENTER_LONGITUDE"], 180.0); ASSERT_DOUBLE_EQ(dtmProj["LINE_FIRST_PIXEL"], 1); ASSERT_DOUBLE_EQ(dtmProj["LINE_LAST_PIXEL"], 23); ASSERT_DOUBLE_EQ(dtmProj["SAMPLE_FIRST_PIXEL"], 1); ASSERT_DOUBLE_EQ(dtmProj["SAMPLE_LAST_PIXEL"], 8); ASSERT_DOUBLE_EQ(dtmProj["MAP_PROJECTION_ROTATION"], 0.0); ASSERT_NEAR(dtmProj["MAP_RESOLUTION"], 59.27469, .00001); ASSERT_DOUBLE_EQ(dtmProj["MAP_SCALE"], 1000.0); ASSERT_NEAR(dtmProj["MAXIMUM_LATITUDE"], 12.82864, .00001); ASSERT_NEAR(dtmProj["MINIMUM_LATITUDE"], 12.45094, .00001); ASSERT_DOUBLE_EQ(dtmProj["LINE_PROJECTION_OFFSET"], 760.5); ASSERT_DOUBLE_EQ(dtmProj["SAMPLE_PROJECTION_OFFSET"], -10413.5); ASSERT_NEAR(dtmProj["EASTERNMOST_LONGITUDE"], 355.80733, .00001); ASSERT_NEAR(dtmProj["WESTERNMOST_LONGITUDE"], 355.68017, .00001); PvlObject dtmView = dtmLabel.findObject("VIEWING_PARAMETERS"); ASSERT_DOUBLE_EQ(dtmView["NORTH_AZIMUTH"], 270.0); Pvl orthoLabel1(prefix.path()+"/ESP_042252_1930_IRB_B_41_ORTHO.IMG"); ASSERT_EQ(orthoLabel1["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(orthoLabel1["RECORD_BYTES"], 40); ASSERT_DOUBLE_EQ(orthoLabel1["FILE_RECORDS"], 252); ASSERT_DOUBLE_EQ(orthoLabel1["^IMAGE"], 103); ASSERT_EQ(orthoLabel1["DATA_SET_ID"][0].toStdString(), "MRO-M-HIRISE-5-DTM-V1.0"); ASSERT_EQ(orthoLabel1["PRODUCER_INSTITUTION_NAME"][0].toStdString(), "UNIVERSITY OF ARIZONA"); ASSERT_EQ(orthoLabel1["PRODUCER_ID"][0].toStdString(), "UA"); ASSERT_EQ(orthoLabel1["PRODUCER_FULL_NAME"][0].toStdString(), "ALFRED MCEWEN"); ASSERT_EQ(orthoLabel1["PRODUCT_ID"][0].toStdString(), "ESP_042252_1930_IRB_B_41_ORTHO"); ASSERT_DOUBLE_EQ(orthoLabel1["PRODUCT_VERSION_ID"], 0.314); ASSERT_EQ(orthoLabel1["INSTRUMENT_HOST_NAME"][0].toStdString(), "MARS RECONNAISSANCE ORBITER"); ASSERT_EQ(orthoLabel1["INSTRUMENT_HOST_ID"][0].toStdString(), "MRO"); ASSERT_EQ(orthoLabel1["INSTRUMENT_NAME"][0].toStdString(), "HIGH RESOLUTION IMAGING SCIENCE EXPERIMENT"); ASSERT_EQ(orthoLabel1["INSTRUMENT_ID"][0].toStdString(), "HIRISE"); ASSERT_EQ(orthoLabel1["TARGET_NAME"][0].toStdString(), "MARS"); ASSERT_EQ(orthoLabel1["SOURCE_PRODUCT_ID"][0].toStdString(), "DTEEZ_042252_1930_042753_1930_A31"); ASSERT_EQ(orthoLabel1["SOURCE_PRODUCT_ID"][1].toStdString(), "ESP_042252_1930"); ASSERT_EQ(orthoLabel1["RATIONALE_DESC"][0].toStdString(), "NULL"); ASSERT_EQ(orthoLabel1["SOFTWARE_NAME"][0].toStdString(), "Socet_Set 5.4.1"); ASSERT_EQ(orthoLabel1["RATIONALE_DESC"][0].toStdString(), "NULL"); ASSERT_DOUBLE_EQ(orthoLabel1["LABEL_RECORDS"], 102); PvlObject orthoImage1 = orthoLabel1.findObject("IMAGE"); ASSERT_DOUBLE_EQ(orthoImage1["LINES"], 50); ASSERT_DOUBLE_EQ(orthoImage1["LINE_SAMPLES"], 40); ASSERT_DOUBLE_EQ(orthoImage1["BANDS"], 3); ASSERT_DOUBLE_EQ(orthoImage1["OFFSET"], 0.0); ASSERT_DOUBLE_EQ(orthoImage1["SCALING_FACTOR"], 1.0); ASSERT_DOUBLE_EQ(orthoImage1["SAMPLE_BITS"], 8); ASSERT_EQ(orthoImage1["SAMPLE_TYPE"][0].toStdString(), "MSB_UNSIGNED_INTEGER"); ASSERT_EQ(orthoImage1["BAND_STORAGE_TYPE"][0].toStdString(), "BAND_SEQUENTIAL"); ASSERT_DOUBLE_EQ(orthoImage1["CORE_NULL"], 0); ASSERT_DOUBLE_EQ(orthoImage1["CORE_LOW_REPR_SATURATION"], 1); ASSERT_DOUBLE_EQ(orthoImage1["CORE_LOW_INSTR_SATURATION"], 1); ASSERT_DOUBLE_EQ(orthoImage1["CORE_HIGH_REPR_SATURATION"], 255); ASSERT_DOUBLE_EQ(orthoImage1["CORE_HIGH_INSTR_SATURATION"], 255); PvlObject orthoProj1 = orthoLabel1.findObject("IMAGE_MAP_PROJECTION"); ASSERT_EQ(orthoProj1["^DATA_SET_MAP_PROJECTION"][0].toStdString(), "DSMAP.CAT"); ASSERT_EQ(orthoProj1["MAP_PROJECTION_TYPE"][0].toStdString(), "EQUIRECTANGULAR"); ASSERT_EQ(orthoProj1["PROJECTION_LATITUDE_TYPE"][0].toStdString(), "PLANETOCENTRIC"); ASSERT_DOUBLE_EQ(orthoProj1["A_AXIS_RADIUS"], 3396.19); ASSERT_DOUBLE_EQ(orthoProj1["B_AXIS_RADIUS"], 3396.19); ASSERT_DOUBLE_EQ(orthoProj1["C_AXIS_RADIUS"], 3396.19); ASSERT_EQ(orthoProj1["COORDINATE_SYSTEM_NAME"][0].toStdString(), "PLANETOCENTRIC"); ASSERT_EQ(orthoProj1["POSITIVE_LONGITUDE_DIRECTION"][0].toStdString(), "EAST"); ASSERT_EQ(orthoProj1["KEYWORD_LATITUDE_TYPE"][0].toStdString(), "PLANETOCENTRIC"); ASSERT_DOUBLE_EQ(orthoProj1["CENTER_LATITUDE"], 0.0); ASSERT_DOUBLE_EQ(orthoProj1["CENTER_LONGITUDE"], 180.0); ASSERT_DOUBLE_EQ(orthoProj1["LINE_FIRST_PIXEL"], 1); ASSERT_DOUBLE_EQ(orthoProj1["LINE_LAST_PIXEL"], 50); ASSERT_DOUBLE_EQ(orthoProj1["SAMPLE_FIRST_PIXEL"], 1); ASSERT_DOUBLE_EQ(orthoProj1["SAMPLE_LAST_PIXEL"], 40); ASSERT_DOUBLE_EQ(orthoProj1["MAP_PROJECTION_ROTATION"], 0.0); ASSERT_NEAR(orthoProj1["MAP_RESOLUTION"], 117259.25436, .00001); ASSERT_NEAR(orthoProj1["MAP_SCALE"], 0.50550, .00001); ASSERT_NEAR(orthoProj1["MAXIMUM_LATITUDE"], 12.82848, .00001); ASSERT_NEAR(orthoProj1["MINIMUM_LATITUDE"], 12.82806, .00001); ASSERT_DOUBLE_EQ(orthoProj1["LINE_PROJECTION_OFFSET"], 1504258.5); ASSERT_DOUBLE_EQ(orthoProj1["SAMPLE_PROJECTION_OFFSET"], -20600155.500001); ASSERT_NEAR(orthoProj1["EASTERNMOST_LONGITUDE"], 355.68076, .00001); ASSERT_NEAR(orthoProj1["WESTERNMOST_LONGITUDE"], 355.68041, .00001); ASSERT_EQ(orthoProj1["FIRST_STANDARD_PARALLEL"][0].toStdString(), "N/A"); ASSERT_EQ(orthoProj1["SECOND_STANDARD_PARALLEL"][0].toStdString(), "N/A"); PvlObject orthoView1 = orthoLabel1.findObject("VIEWING_PARAMETERS"); ASSERT_DOUBLE_EQ(orthoView1["NORTH_AZIMUTH"], 270.0); Pvl orthoLabel2(prefix.path()+"/ESP_042252_1930_IRB_D_31_ORTHO.IMG"); ASSERT_EQ(orthoLabel2["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(orthoLabel2["RECORD_BYTES"], 40); ASSERT_DOUBLE_EQ(orthoLabel2["FILE_RECORDS"], 252); ASSERT_DOUBLE_EQ(orthoLabel2["^IMAGE"], 103); ASSERT_EQ(orthoLabel2["DATA_SET_ID"][0].toStdString(), "MRO-M-HIRISE-5-DTM-V1.0"); ASSERT_EQ(orthoLabel2["PRODUCER_INSTITUTION_NAME"][0].toStdString(), "UNIVERSITY OF ARIZONA"); ASSERT_EQ(orthoLabel2["PRODUCER_ID"][0].toStdString(), "UA"); ASSERT_EQ(orthoLabel2["PRODUCER_FULL_NAME"][0].toStdString(), "ALFRED MCEWEN"); ASSERT_EQ(orthoLabel2["PRODUCT_ID"][0].toStdString(), "ESP_042252_1930_IRB_D_31_ORTHO"); ASSERT_DOUBLE_EQ(orthoLabel2["PRODUCT_VERSION_ID"], 0.314); ASSERT_EQ(orthoLabel2["INSTRUMENT_HOST_NAME"][0].toStdString(), "MARS RECONNAISSANCE ORBITER"); ASSERT_EQ(orthoLabel2["INSTRUMENT_HOST_ID"][0].toStdString(), "MRO"); ASSERT_EQ(orthoLabel2["INSTRUMENT_NAME"][0].toStdString(), "HIGH RESOLUTION IMAGING SCIENCE EXPERIMENT"); ASSERT_EQ(orthoLabel2["INSTRUMENT_ID"][0].toStdString(), "HIRISE"); ASSERT_EQ(orthoLabel2["TARGET_NAME"][0].toStdString(), "MARS"); ASSERT_EQ(orthoLabel2["SOURCE_PRODUCT_ID"][0].toStdString(), "DTEEZ_042252_1930_042753_1930_A31"); ASSERT_EQ(orthoLabel2["SOURCE_PRODUCT_ID"][1].toStdString(), "ESP_042252_1930"); ASSERT_EQ(orthoLabel2["RATIONALE_DESC"][0].toStdString(), "NULL"); ASSERT_EQ(orthoLabel2["SOFTWARE_NAME"][0].toStdString(), "Socet_Set 5.4.1"); ASSERT_EQ(orthoLabel2["RATIONALE_DESC"][0].toStdString(), "NULL"); ASSERT_DOUBLE_EQ(orthoLabel2["LABEL_RECORDS"], 102); PvlObject orthoImage2 = orthoLabel2.findObject("IMAGE"); ASSERT_DOUBLE_EQ(orthoImage2["LINES"], 50); ASSERT_DOUBLE_EQ(orthoImage2["LINE_SAMPLES"], 40); ASSERT_DOUBLE_EQ(orthoImage2["BANDS"], 3); ASSERT_DOUBLE_EQ(orthoImage2["OFFSET"], 0.0); ASSERT_DOUBLE_EQ(orthoImage2["SCALING_FACTOR"], 1.0); ASSERT_DOUBLE_EQ(orthoImage2["SAMPLE_BITS"], 8); ASSERT_EQ(orthoImage2["SAMPLE_TYPE"][0].toStdString(), "MSB_UNSIGNED_INTEGER"); ASSERT_EQ(orthoImage2["BAND_STORAGE_TYPE"][0].toStdString(), "BAND_SEQUENTIAL"); ASSERT_DOUBLE_EQ(orthoImage2["CORE_NULL"], 0); ASSERT_DOUBLE_EQ(orthoImage2["CORE_LOW_REPR_SATURATION"], 1); ASSERT_DOUBLE_EQ(orthoImage2["CORE_LOW_INSTR_SATURATION"], 1); ASSERT_DOUBLE_EQ(orthoImage2["CORE_HIGH_REPR_SATURATION"], 255); ASSERT_DOUBLE_EQ(orthoImage2["CORE_HIGH_INSTR_SATURATION"], 255); PvlObject orthoProj2 = orthoLabel2.findObject("IMAGE_MAP_PROJECTION"); ASSERT_EQ(orthoProj2["^DATA_SET_MAP_PROJECTION"][0].toStdString(), "DSMAP.CAT"); ASSERT_EQ(orthoProj2["MAP_PROJECTION_TYPE"][0].toStdString(), "EQUIRECTANGULAR"); ASSERT_EQ(orthoProj2["PROJECTION_LATITUDE_TYPE"][0].toStdString(), "PLANETOCENTRIC"); ASSERT_DOUBLE_EQ(orthoProj2["A_AXIS_RADIUS"], 3396.19); ASSERT_DOUBLE_EQ(orthoProj2["B_AXIS_RADIUS"], 3396.19); ASSERT_DOUBLE_EQ(orthoProj2["C_AXIS_RADIUS"], 3396.19); ASSERT_EQ(orthoProj2["COORDINATE_SYSTEM_NAME"][0].toStdString(), "PLANETOCENTRIC"); ASSERT_EQ(orthoProj2["POSITIVE_LONGITUDE_DIRECTION"][0].toStdString(), "EAST"); ASSERT_EQ(orthoProj2["KEYWORD_LATITUDE_TYPE"][0].toStdString(), "PLANETOCENTRIC"); ASSERT_DOUBLE_EQ(orthoProj2["CENTER_LATITUDE"], 0.0); ASSERT_DOUBLE_EQ(orthoProj2["CENTER_LONGITUDE"], 180.0); ASSERT_DOUBLE_EQ(orthoProj2["LINE_FIRST_PIXEL"], 1); ASSERT_DOUBLE_EQ(orthoProj2["LINE_LAST_PIXEL"], 50); ASSERT_DOUBLE_EQ(orthoProj2["SAMPLE_FIRST_PIXEL"], 1); ASSERT_DOUBLE_EQ(orthoProj2["SAMPLE_LAST_PIXEL"], 40); ASSERT_DOUBLE_EQ(orthoProj2["MAP_PROJECTION_ROTATION"], 0.0); ASSERT_NEAR(orthoProj2["MAP_RESOLUTION"], 29314.81359, .00001); ASSERT_NEAR(orthoProj2["MAP_SCALE"], 2.02200, .00001); ASSERT_NEAR(orthoProj2["MAXIMUM_LATITUDE"], 12.82801, .00001); ASSERT_NEAR(orthoProj2["MINIMUM_LATITUDE"], 12.82631, .00001); ASSERT_DOUBLE_EQ(orthoProj2["LINE_PROJECTION_OFFSET"], 376050.5); ASSERT_DOUBLE_EQ(orthoProj2["SAMPLE_PROJECTION_OFFSET"], -5150060.5); ASSERT_NEAR(orthoProj2["EASTERNMOST_LONGITUDE"], 355.68250, .00001); ASSERT_NEAR(orthoProj2["WESTERNMOST_LONGITUDE"], 355.68114, .00001); ASSERT_EQ(orthoProj2["FIRST_STANDARD_PARALLEL"][0].toStdString(), "N/A"); ASSERT_EQ(orthoProj2["SECOND_STANDARD_PARALLEL"][0].toStdString(), "N/A"); PvlObject orthoView2 = orthoLabel2.findObject("VIEWING_PARAMETERS"); ASSERT_DOUBLE_EQ(orthoView2["NORTH_AZIMUTH"], 270.0); } TEST(Hidtmgen, HidtmgenTestDtmOnly){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres.cub", "outputdir=" + prefix.path(), "paramspvl=data/hidtmgen/dtmOnly/params.pvl", }; UserInterface options(APP_XML, args); try { hidtmgen(options); } catch (IException &e) { FAIL() << "Unable to HIRISE generate PDS products: " << e.toString().toStdString().c_str() << std::endl; } Pvl dtmLabel(prefix.path()+"/DTEEZ_042252_1930_042753_1930_A15.IMG"); ASSERT_EQ(dtmLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(dtmLabel["RECORD_BYTES"], 32); ASSERT_DOUBLE_EQ(dtmLabel["FILE_RECORDS"], 155); ASSERT_DOUBLE_EQ(dtmLabel["^IMAGE"], 133); } TEST(Hidtmgen, HidtmgenTestEqui){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/DTM_Zumba_1m_forPDS_lowres.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/equi/orthoInputList.txt", "paramspvl=data/hidtmgen/equi/params.pvl", "orthosequencenumberlist=data/hidtmgen/equi/sequenceNumbers.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); } catch (IException &e) { FAIL() << "Unable to HIRISE generate PDS products: " << e.toString().toStdString().c_str() << std::endl; } Pvl dtmLabel(prefix.path()+"/DTEEZ_002118_1510_003608_1510_A02.IMG"); ASSERT_EQ(dtmLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(dtmLabel["RECORD_BYTES"], 28); ASSERT_DOUBLE_EQ(dtmLabel["FILE_RECORDS"], 203); ASSERT_DOUBLE_EQ(dtmLabel["^IMAGE"], 183); PvlObject dtmProj = dtmLabel.findObject("IMAGE_MAP_PROJECTION"); ASSERT_EQ(dtmProj["MAP_PROJECTION_TYPE"][0].toStdString(), "EQUIRECTANGULAR"); Pvl orthoLabel(prefix.path()+"/PSP_002118_1510_RED_C_01_ORTHO.IMG"); ASSERT_EQ(orthoLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(orthoLabel["RECORD_BYTES"], 50); ASSERT_DOUBLE_EQ(orthoLabel["FILE_RECORDS"], 132); ASSERT_DOUBLE_EQ(orthoLabel["^IMAGE"], 83); PvlObject orthoProj = orthoLabel.findObject("IMAGE_MAP_PROJECTION"); ASSERT_EQ(orthoProj["MAP_PROJECTION_TYPE"][0].toStdString(), "EQUIRECTANGULAR"); } TEST(Hidtmgen, HidtmgenTestErrorEmptyOrthoFromList){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/error/orthoInputListEmpty.txt", "paramspvl=data/hidtmgen/error/params.pvl", "orthosequencenumberlist=data/hidtmgen/error/sequenceNumbers2item.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); FAIL() << "Should throw an exception" << std::endl; } catch (IException &e) { EXPECT_THAT(e.what(), HasSubstr("File [data/hidtmgen/error/orthoInputListEmpty.txt] contains no data.")); } } TEST(Hidtmgen, HidtmgenTestErrorInvalidDtm){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/ortho/ESP_042252_1930_3-BAND_COLOR_2m_o_cropped.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/error/orthoInputList2Item.txt", "paramspvl=data/hidtmgen/error/params.pvl", "orthosequencenumberlist=data/hidtmgen/error/sequenceNumbers2item.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); FAIL() << "Should throw an exception" << std::endl; } catch (IException &e) { EXPECT_THAT(e.what(), HasSubstr("Input cube [data/hidtmgen/ortho/ESP_042252_1930_3-BAND_COLOR_2m_o_cropped.cub] does not appear to be a DTM.")); } } TEST(Hidtmgen, HidtmgenTestErrorNoInput){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "outputdir=" + prefix.path(), "paramspvl=data/hidtmgen/error/params.pvl", "orthosequencenumberlist=data/hidtmgen/error/sequenceNumbers2item.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); FAIL() << "Should throw an exception" << std::endl; } catch (IException &e) { EXPECT_THAT(e.what(), HasSubstr("User must supply DTM or ORTHOFROMLIST or both.")); } } TEST(Hidtmgen, HidtmgenTestErrorDtmInvalidProjection){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres_sinusoidal.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/error/orthoInputList2Item.txt", "paramspvl=data/hidtmgen/error/params.pvl", "orthosequencenumberlist=data/hidtmgen/error/sequenceNumbers2item.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); FAIL() << "Should throw an exception" << std::endl; } catch (IException &e) { EXPECT_THAT(e.what(), HasSubstr("The projection type [SINUSOIDAL] is not supported.")); } } TEST(Hidtmgen, HidtmgenTestErrorInputSeqMismatch){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/error/orthoInputList2Item.txt", "paramspvl=data/hidtmgen/error/params.pvl", "orthosequencenumberlist=data/hidtmgen/error/sequenceNumbers1item.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); FAIL() << "Should throw an exception" << std::endl; } catch (IException &e) { EXPECT_THAT(e.what(), HasSubstr("Output sequence number list must correspond to the input ortho list.")); } } TEST(Hidtmgen, HidtmgenTestErrorInputOutputMismatch){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=FALSE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres.cub", "dtm_product_id=xyz", "dtmto=" + prefix.path() + "/xyz.IMG", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/error/orthoInputList2Item.txt", "paramspvl=data/hidtmgen/error/params.pvl", "orthotolist=data/hidtmgen/error/orthoToList1Item.txt", "orthosequencenumberlist=data/hidtmgen/error/sequenceNumbers2item.txt", "orthoproductidlist=data/hidtmgen/error/sequenceNumbers2item.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); FAIL() << "Should throw an exception" << std::endl; } catch (IException &e) { EXPECT_THAT(e.what(), HasSubstr("Output ortho list and product id list must correspond to the input ortho list.")); } } TEST(Hidtmgen, HidtmgenTestErrorInvalidInstitution){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/error/orthoInputList2Item.txt", "paramspvl=data/hidtmgen/error/invalidProducingInst.pvl", "orthosequencenumberlist=data/hidtmgen/error/sequenceNumbers2item.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); FAIL() << "Should throw an exception" << std::endl; } catch (IException &e) { EXPECT_THAT(e.what(), HasSubstr("PRODUCING_INSTITUTION value [USGS] in the PARAMSPVL file must be a single character.")); } } TEST(Hidtmgen, HidtmgenTestErrorInvalidVersionId){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/error/orthoInputList2Item.txt", "paramspvl=data/hidtmgen/error/invalidVersionId.pvl", "orthosequencenumberlist=data/hidtmgen/error/sequenceNumbers2item.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); FAIL() << "Should throw an exception" << std::endl; } catch (IException &e) { EXPECT_THAT(e.what(), HasSubstr("Version number [-4.0] is invalid.")); } } TEST(Hidtmgen, HidtmgenTestErrorDtmInvalidBandSize){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/DTM_2Bands_cropped.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/error/orthoInputList2item.txt", "paramspvl=data/hidtmgen/error/params.pvl", "orthosequencenumberlist=data/hidtmgen/error/sequenceNumbers2item.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); FAIL() << "Should throw an exception" << std::endl; } catch (IException &e) { EXPECT_THAT(e.what(), HasSubstr("Input cube [data/hidtmgen/dtm/DTM_2Bands_cropped.cub] does not appear to be a DTM.")); } } TEST(Hidtmgen, HidtmgenTestErrorOrthoInvalidBandSize){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/error/orthoInputList2Bands.txt", "paramspvl=data/hidtmgen/error/params.pvl", "orthosequencenumberlist=data/hidtmgen/error/sequenceNumbers1item.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); FAIL() << "Should throw an exception" << std::endl; } catch (IException &e) { EXPECT_THAT(e.what(), HasSubstr("The file [data/hidtmgen/ortho/2BandImage.cub] found in the ORTHOFROMLIST is not a valid orthorectified image. Band count must be 1 (RED) or 3 (color).")); } } TEST(Hidtmgen, HidtmgenTestNonDefaultNames){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=FALSE", "dtm=data/hidtmgen/dtm/DTM_Zumba_1m_forPDS_lowres.cub", "outputdir=" + prefix.path(), "dtmto="+ prefix.path() + "/dtm.img", "orthofromlist=data/hidtmgen/nonDefaultNames/orthoInputList.txt", "orthotolist=data/hidtmgen/nonDefaultNames/orthoOutputFiles.lis", "orthoproductidlist=data/hidtmgen/nonDefaultNames/orthoOutputProductIds.lis", "paramspvl=data/hidtmgen/nonDefaultNames/params.pvl", "dtm_product_id=DtmProduct" }; UserInterface options(APP_XML, args); try { hidtmgen(options); } catch (IException &e) { FAIL() << "Unable to HIRISE generate PDS products: " << e.toString().toStdString().c_str() << std::endl; } Pvl dtmLabel(prefix.path()+"/dtm.img"); ASSERT_EQ(dtmLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(dtmLabel["RECORD_BYTES"], 28); ASSERT_DOUBLE_EQ(dtmLabel["FILE_RECORDS"], 203); ASSERT_DOUBLE_EQ(dtmLabel["^IMAGE"], 183); } TEST(Hidtmgen, HidtmgenTestOrthoOnly){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/orthoOnly/orthoInputList.txt", "paramspvl=data/hidtmgen/orthoOnly/params.pvl", "orthosequencenumberlist=data/hidtmgen/orthoOnly/sequenceNumbers.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); } catch (IException &e) { FAIL() << "Unable to HIRISE generate PDS products: " << e.toString().toStdString().c_str() << std::endl; } Pvl orthoLabel(prefix.path()+"/ESP_042252_1930_IRB_D_31_ORTHO.IMG"); ASSERT_EQ(orthoLabel["SOURCE_PRODUCT_ID"][0].toStdString(), "DTems_xxxxxx_xxxx_yyyyyy_yyyy_vnn"); ASSERT_EQ(orthoLabel["SOURCE_PRODUCT_ID"][1].toStdString(), "ESP_042252_1930"); ASSERT_EQ(orthoLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(orthoLabel["RECORD_BYTES"], 40); ASSERT_DOUBLE_EQ(orthoLabel["FILE_RECORDS"], 254); ASSERT_DOUBLE_EQ(orthoLabel["^IMAGE"], 105); } TEST(Hidtmgen, HidtmgenTestOutputTypesAll832){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/outputTypes/orthoInputList.txt", "paramspvl=data/hidtmgen/outputTypes/params.pvl", "endian=msb", "null=FALSE", "LIS=TRUE", "LRS=TRUE", "HIS=TRUE", "HRS=TRUE", "dtmbittype=8BIT", "orthobittype=32bit", "orthosequencenumberlist=data/hidtmgen/outputTypes/sequenceNumbers.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); } catch (IException &e) { FAIL() << "Unable to HIRISE generate PDS products: " << e.toString().toStdString().c_str() << std::endl; } Pvl dtmLabel(prefix.path()+"/DTEEZ_042252_1930_042753_1930_A31.IMG"); ASSERT_EQ(dtmLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(dtmLabel["RECORD_BYTES"], 8); ASSERT_DOUBLE_EQ(dtmLabel["FILE_RECORDS"], 558); ASSERT_DOUBLE_EQ(dtmLabel["^IMAGE"], 536); PvlObject dtmImage = dtmLabel.findObject("IMAGE"); ASSERT_DOUBLE_EQ(dtmImage["SAMPLE_BITS"], 8); ASSERT_EQ(dtmImage["SAMPLE_TYPE"][0].toStdString(), "MSB_UNSIGNED_INTEGER"); Pvl orthoLabel(prefix.path()+"/ESP_042252_1930_IRB_D_31_ORTHO.IMG"); ASSERT_EQ(orthoLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(orthoLabel["RECORD_BYTES"], 160); ASSERT_DOUBLE_EQ(orthoLabel["FILE_RECORDS"], 177); ASSERT_DOUBLE_EQ(orthoLabel["^IMAGE"], 28); PvlObject orthoImage = orthoLabel.findObject("IMAGE"); ASSERT_DOUBLE_EQ(orthoImage["SAMPLE_BITS"], 32); ASSERT_EQ(orthoImage["SAMPLE_TYPE"][0].toStdString(), "IEEE_REAL"); } TEST(Hidtmgen, HidtmgenTestOutputTypesAllU16S16){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/outputTypes/orthoInputList.txt", "paramspvl=data/hidtmgen/outputTypes/params2.pvl", "endian=msb", "null=FALSE", "LIS=TRUE", "LRS=TRUE", "HIS=TRUE", "HRS=TRUE", "dtmbittype=u16bit", "orthobittype=s16bit", "orthosequencenumberlist=data/hidtmgen/outputTypes/sequenceNumbers.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); } catch (IException &e) { FAIL() << "Unable to HIRISE generate PDS products: " << e.toString().toStdString().c_str() << std::endl; } Pvl dtmLabel(prefix.path()+"/DTEEZ_042252_1930_042753_1930_A07.IMG"); ASSERT_EQ(dtmLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(dtmLabel["RECORD_BYTES"], 16); ASSERT_DOUBLE_EQ(dtmLabel["FILE_RECORDS"], 288); ASSERT_DOUBLE_EQ(dtmLabel["^IMAGE"], 266); PvlObject dtmImage = dtmLabel.findObject("IMAGE"); ASSERT_DOUBLE_EQ(dtmImage["SAMPLE_BITS"], 16); ASSERT_EQ(dtmImage["SAMPLE_TYPE"][0].toStdString(), "MSB_UNSIGNED_INTEGER"); Pvl orthoLabel(prefix.path()+"/ESP_042252_1930_IRB_D_31_ORTHO.IMG"); ASSERT_EQ(orthoLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(orthoLabel["RECORD_BYTES"], 80); ASSERT_DOUBLE_EQ(orthoLabel["FILE_RECORDS"], 202); ASSERT_DOUBLE_EQ(orthoLabel["^IMAGE"], 53); PvlObject orthoImage = orthoLabel.findObject("IMAGE"); ASSERT_DOUBLE_EQ(orthoImage["SAMPLE_BITS"], 16); ASSERT_EQ(orthoImage["SAMPLE_TYPE"][0].toStdString(), "MSB_INTEGER"); } TEST(Hidtmgen, HidtmgenTestOutputTypesNoneS16U16){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Ares4_Marth_Crater_3557E_126N_ngate_03_lowres.cub", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/outputTypes/orthoInputList.txt", "paramspvl=data/hidtmgen/outputTypes/params2.pvl", "endian=msb", "null=FALSE", "LIS=FALSE", "LRS=FALSE", "HIS=FALSE", "HRS=FALSE", "dtmbittype=S16BIT", "orthobittype=U16BIT", "orthosequencenumberlist=data/hidtmgen/outputTypes/sequenceNumbers.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); } catch (IException &e) { FAIL() << "Unable to HIRISE generate PDS products: " << e.toString().toStdString().c_str() << std::endl; } Pvl dtmLabel(prefix.path()+"/DTEEZ_042252_1930_042753_1930_A07.IMG"); ASSERT_EQ(dtmLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(dtmLabel["RECORD_BYTES"], 16); ASSERT_DOUBLE_EQ(dtmLabel["FILE_RECORDS"], 288); ASSERT_DOUBLE_EQ(dtmLabel["^IMAGE"], 266); PvlObject dtmImage = dtmLabel.findObject("IMAGE"); ASSERT_DOUBLE_EQ(dtmImage["SAMPLE_BITS"], 16); ASSERT_EQ(dtmImage["SAMPLE_TYPE"][0].toStdString(), "MSB_INTEGER"); Pvl orthoLabel(prefix.path()+"/ESP_042252_1930_IRB_D_31_ORTHO.IMG"); ASSERT_EQ(orthoLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(orthoLabel["RECORD_BYTES"], 80); ASSERT_DOUBLE_EQ(orthoLabel["FILE_RECORDS"], 202); ASSERT_DOUBLE_EQ(orthoLabel["^IMAGE"], 53); PvlObject orthoImage = orthoLabel.findObject("IMAGE"); ASSERT_DOUBLE_EQ(orthoImage["SAMPLE_BITS"], 16); ASSERT_EQ(orthoImage["SAMPLE_TYPE"][0].toStdString(), "MSB_UNSIGNED_INTEGER"); } TEST(Hidtmgen, HidtmgenTestPolar){ QTemporaryDir prefix; QVector<QString> args = {"defaultnames=TRUE", "dtm=data/hidtmgen/dtm/Polar_Crater_1_1m_ngate_edited2_forPDS_lowres.cub", "paramspvl=data/hidtmgen/polar/params.pvl", "outputdir=" + prefix.path(), "orthofromlist=data/hidtmgen/polar/orthoInputList.txt", "orthosequence=data/hidtmgen/polar/orthosequencenumberlist.txt" }; UserInterface options(APP_XML, args); try { hidtmgen(options); } catch (IException &e) { FAIL() << "Unable to HIRISE generate PDS products: " << e.toString().toStdString().c_str() << std::endl; } Pvl dtmLabel(prefix.path()+"/DTEPZ_009404_2635_010221_2635_Z12.IMG"); ASSERT_EQ(dtmLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(dtmLabel["RECORD_BYTES"], 52); ASSERT_DOUBLE_EQ(dtmLabel["FILE_RECORDS"], 96); ASSERT_DOUBLE_EQ(dtmLabel["^IMAGE"], 85); PvlObject dtmProj = dtmLabel.findObject("IMAGE_MAP_PROJECTION"); ASSERT_EQ(dtmProj["MAP_PROJECTION_TYPE"][0].toStdString(), "POLAR STEREOGRAPHIC"); Pvl orthoLabel(prefix.path()+"/PSP_009404_2635_RED_C_1_ORTHO.IMG"); ASSERT_EQ(orthoLabel["RECORD_TYPE"][0].toStdString(), "FIXED_LENGTH"); ASSERT_DOUBLE_EQ(orthoLabel["RECORD_BYTES"], 50); ASSERT_DOUBLE_EQ(orthoLabel["FILE_RECORDS"], 115); ASSERT_DOUBLE_EQ(orthoLabel["^IMAGE"], 66); PvlObject orthoProj = orthoLabel.findObject("IMAGE_MAP_PROJECTION"); ASSERT_EQ(orthoProj["MAP_PROJECTION_TYPE"][0].toStdString(), "POLAR STEREOGRAPHIC"); }
46.519004
191
0.669691
kdl222
c279abb197ecc731b1733ec9dddf4d9f1b2fe61e
965
cpp
C++
smacc/src/smacc/smacc_component.cpp
koyalbhartia/SMACC
609f017a91bc258deb0b64cac5f198d54f19c9e3
[ "BSD-3-Clause" ]
203
2019-04-11T16:42:10.000Z
2022-03-18T06:02:56.000Z
smacc/src/smacc/smacc_component.cpp
koyalbhartia/SMACC
609f017a91bc258deb0b64cac5f198d54f19c9e3
[ "BSD-3-Clause" ]
50
2019-04-18T09:09:48.000Z
2022-03-29T21:38:21.000Z
smacc/src/smacc/smacc_component.cpp
koyalbhartia/SMACC
609f017a91bc258deb0b64cac5f198d54f19c9e3
[ "BSD-3-Clause" ]
35
2019-09-10T15:06:37.000Z
2022-02-02T09:10:08.000Z
/***************************************************************************************************************** * ReelRobotix Inc. - Software License Agreement Copyright (c) 2018 * Authors: Pablo Inigo Blasco, Brett Aldrich * ******************************************************************************************************************/ #include <smacc/component.h> #include <smacc/impl/smacc_component_impl.h> namespace smacc { ISmaccComponent::~ISmaccComponent() { } ISmaccComponent::ISmaccComponent() : owner_(nullptr) { } void ISmaccComponent::initialize(ISmaccClient *owner) { owner_ = owner; this->onInitialize(); } void ISmaccComponent::onInitialize() { } void ISmaccComponent::setStateMachine(ISmaccStateMachine *stateMachine) { stateMachine_ = stateMachine; } std::string ISmaccComponent::getName() const { std::string keyname = demangleSymbol(typeid(*this).name()); return keyname; } } // namespace smacc
22.97619
116
0.552332
koyalbhartia
c27bbb840bdbbae75fe1df3f80d840747c65a144
1,500
hpp
C++
src/Magma/Window/Win32Window.hpp
RiscadoA/Magma-Engine
ebf8d8c25d631a9731efa33e23b162339985ae3b
[ "Zlib" ]
3
2017-11-01T21:47:57.000Z
2022-01-07T03:50:58.000Z
src/Magma/Window/Win32Window.hpp
RiscadoA/Magma-Engine
ebf8d8c25d631a9731efa33e23b162339985ae3b
[ "Zlib" ]
null
null
null
src/Magma/Window/Win32Window.hpp
RiscadoA/Magma-Engine
ebf8d8c25d631a9731efa33e23b162339985ae3b
[ "Zlib" ]
null
null
null
#pragma once #include "Window.hpp" #include <Windows.h> #include <queue> namespace Magma { class Win32Window : public Window { public: Win32Window(HINSTANCE hInstance, int nCmdShow); virtual ~Win32Window() final; private: static LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); // Inherited via Window virtual void SetVSyncEnabled(bool vsyncEnabled) override; virtual bool IsKeyboardKeyPressed(Keyboard::Key key) override; virtual bool IsMouseCursorVisible() override; virtual bool IsMouseButtonPressed(Mouse::Button button) override; virtual void SetMouseCursorVisible(bool visible) override; virtual glm::vec2 GetMousePosition() override; virtual void SetMousePosition(glm::vec2 mousePosition) override; virtual bool DerivedIsOpen() override; virtual void DerivedOpen() override; virtual void DerivedClose() override; virtual void DerivedResize() override; virtual void DerivedSetTitle() override; virtual void DerivedSetMode() override; virtual bool DerivedPollEvent(Magma::UIEvent & event) override; virtual void DerivedDisplay() override; virtual void DerivedMakeActive() override; HINSTANCE m_hInstance; HWND m_hWnd; WNDCLASSEX m_wc; int m_nCmdShow; bool m_cursorVisible = true; std::queue<Magma::UIEvent> m_eventQueue; bool m_mouseButtonStates[static_cast<size_t>(Mouse::Button::Count)]; bool m_keyboardKeyStates[static_cast<size_t>(Keyboard::Key::Count)]; }; }
28.846154
70
0.761333
RiscadoA
c27cc9e578557f8556565143396a8b9c2f87dddc
4,338
cpp
C++
reversing/scsbx_reversing/build/vm/scsbx.cpp
SECCON/SECCON2020_online_CTF
dd639d140ad61ea0fbfadb7827157ca53f7b88b2
[ "Apache-2.0" ]
3
2020-11-02T06:53:39.000Z
2021-12-10T00:59:01.000Z
reversing/scsbx_reversing/files/src/scsbx.cpp
SECCON/SECCON2020_online_CTF
dd639d140ad61ea0fbfadb7827157ca53f7b88b2
[ "Apache-2.0" ]
null
null
null
reversing/scsbx_reversing/files/src/scsbx.cpp
SECCON/SECCON2020_online_CTF
dd639d140ad61ea0fbfadb7827157ca53f7b88b2
[ "Apache-2.0" ]
null
null
null
#include <iomanip> #include <iostream> #include "scsbx.hpp" int SCSBX::exec() { do { try { __cpu_exec(code[pc]); } catch(SandboxException e) { std::cerr << "***** SCSBX Crash Report *****" << std::endl; std::cerr << " Exception thrown: " << e << std::endl; std::cerr << " PC: " << std::hex << std::setfill('0') << std::setw(8) << pc << std::endl; std::cerr << "******************************" << std::endl; return -6; } pc++; } while(pc < code_size); return status; } void SCSBX::__cpu_exec(u8 instr) { u32 val; switch(instr) { /* Memory Operation */ case INS_PUSH: val = *(u32*)(&code[pc+1]); __stack_push(val); pc += 4; break; case INS_POP: __stack_pop(); break; case INS_DUP: __stack_dup(); break; case INS_XCHG: __stack_xchg(); break; case INS_LOAD32: __mem_load32(); break; case INS_LOAD64: __mem_load64(); break; case INS_STORE8: __mem_store8(); break; case INS_STORE16: __mem_store16(); break; case INS_STORE32: __mem_store32(); break; case INS_SHOW: __stack_show(); break; /* Branch Operation */ case INS_JMP: __branch_jmp(); break; case INS_JEQ: __branch_jeq(); break; case INS_JGT: __branch_jgt(); break; case INS_JGE: __branch_jge(); break; case INS_CALL: __branch_call(); break; /* Arithmetic Operation */ case INS_ADD: __arith_add(); break; case INS_SUB: __arith_sub(); break; case INS_MUL: __arith_mul(); break; case INS_DIV: __arith_div(); break; case INS_MOD: __arith_mod(); break; /* Logic Operation */ case INS_NOT: __logic_not(); break; case INS_AND: __logic_and(); break; case INS_OR: __logic_or(); break; case INS_XOR: __logic_xor(); break; case INS_SHL: __logic_shl(); break; case INS_SHR: __logic_shr(); break; /* System Operation */ case INS_READ: __sys_read(); break; case INS_WRITE: __sys_write(); break; case INS_MAP: __sys_map(); break; case INS_UNMAP: __sys_unmap(); break; case INS_EXIT: __sys_exit(); break; default: throw ILLEGAL_INSTRUCTION; } } void SCSBX::__assert_address_valid(u64 address) { for(auto itr = memmap.begin(); itr != memmap.end(); ++itr) { if ((itr->first <= address) && (address < itr->first + itr->second)) return; } throw INVALID_ACCESS; } void SCSBX::__assert_range_valid(u64 address, u64 size) { for(auto itr = memmap.begin(); itr != memmap.end(); ++itr) { if ((itr->first <= address) && (address + size < itr->first + itr->second)) { return; } } throw INVALID_ACCESS; } void SCSBX::__assert_resource_available(u64 address, u32 size) { for(auto itr = memmap.begin(); itr != memmap.end(); ++itr) { if (((itr->first <= address) && (address < itr->first + itr->second)) || ((itr->first <= address + size) && (address + size < itr->first + itr->second))) { throw INVALID_ACCESS; } } } SCSBX::SCSBX(u8 *_code, u32 _size) { /* Initialize stack */ stack = (u32*)mmap((void*)STACK_BASE, STACK_SIZE_INIT, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); top = 0; capacity = STACK_SIZE_INIT / sizeof(u32); /* Initialize code */ code_size = _size; code = (u8*)mmap((void*)CODE_BASE, (code_size + 0xfff) & ~0xfff, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); pc = 0; memcpy(code, _code, code_size); mprotect(code, (code_size + 0xfff) & ~0xfff, PROT_READ); /* Initialize status code */ status = 0; /* Guard page */ memmap.push_back(std::make_pair((u64)STACK_BASE + (u64)STACK_SIZE_INIT, 0x100000000 - (u64)STACK_BASE - (u64)STACK_SIZE_INIT)); ASSERT_STACK_INIT; ASSERT_CODE_INIT; } SCSBX::~SCSBX() { for(auto itr = memmap.begin(); itr != memmap.end(); ++itr) { munmap((void*)itr->first, ((u64)itr->second + 0xfff) & ~0xfff); } memmap.clear(); munmap(stack, capacity * sizeof(u32)); munmap(code, (code_size + 0xfff) & ~0xfff); }
20.462264
93
0.56616
SECCON
c28032fb16603df0549baff45cea7601e0c132bc
9,475
cpp
C++
external/android/libsfdec/sfdec_ndkmediacodec.cpp
cyb3rpunk452/aos-avos
427c655b358b942510c5294c4732acdf4b957f3e
[ "Apache-2.0" ]
null
null
null
external/android/libsfdec/sfdec_ndkmediacodec.cpp
cyb3rpunk452/aos-avos
427c655b358b942510c5294c4732acdf4b957f3e
[ "Apache-2.0" ]
null
null
null
external/android/libsfdec/sfdec_ndkmediacodec.cpp
cyb3rpunk452/aos-avos
427c655b358b942510c5294c4732acdf4b957f3e
[ "Apache-2.0" ]
null
null
null
// Copyright 2017 Archos SA // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <inttypes.h> #ifdef __ANDROID_API__ #undef __ANDROID_API__ #define __ANDROID_API__ 21 #endif #include <media/NdkMediaCodec.h> #include "sfdec_common.h" typedef struct sfdec_mediacodec sfdec_priv_t; #include "sfdec_priv.h" #define DBG if (0) #undef LOG #define LOG(fmt, ...) do { \ printf("%s: " fmt "\n", __FUNCTION__, ##__VA_ARGS__); \ fflush(stdout); \ } while (0) struct sfdec_mediacodec { ANativeWindow *mNativeWindow; AMediaFormat *mFormat; AMediaCodec *mCodec; int32_t width; int32_t height; int rotation; bool started; int flush; }; struct sfbuf { size_t index; bool released; }; static void sfdec_destroy(sfdec_priv_t *sfdec); static ssize_t sfdec_send_input2(sfdec_priv_t *sfdec, void *data, size_t size, int64_t time_us, int is_sync_frame, int wait, int flag); #define CHECK(x) do { \ if (!(x)) { \ LOG("sfdec_init failed: %s", #x); \ sfdec_destroy(sfdec); \ return NULL; \ } \ } while (0) #define CHECK_STATUS(err) CHECK((err) == AMEDIA_OK) static int init_renderer(sfdec_priv_t *sfdec) { media_status_t err; int32_t width, height; AMediaFormat *format = AMediaCodec_getOutputFormat(sfdec->mCodec); if (format != NULL) { if (AMediaFormat_getInt32(format, "width", &width)) { LOG("width changed: %d -> %d", sfdec->width, width); sfdec->width = width; } if (AMediaFormat_getInt32(format, "height", &height)) { LOG("height changed: %d -> %d", sfdec->height, height); sfdec->height = height; } } return 0; } static int err_count; static sfdec_priv_t *sfdec_init(sfdec_codec_t codec, sfdec_flags_t flags, int *width, int *height, int rotation, int64_t duration_us, int input_size, void *surface_handle, void *extradata, size_t extradata_size, int *pts_reorder, int sampleSize, int channels, int bitrate, int64_t codec_delay, int64_t seek_preroll) { media_status_t err; const char *mime_type; unsigned int nb_csd = 0; mime_type = get_mimetype(codec); if (!mime_type) return NULL; DBG LOG("(NdkMediaCodec): %s with extradata size %d", mime_type, extradata_size); sfdec_priv_t *sfdec = new sfdec_priv_t(); if (sfdec == NULL) return NULL; err_count = 0; sfdec->rotation = rotation; sfdec->width = *width; sfdec->height = *height; sfdec->mNativeWindow = (ANativeWindow *)surface_handle; DBG LOG("sfdec->mCodec %d sfdec->mCodec %d", sfdec->mCodec, sfdec->mFormat); sfdec->mCodec = AMediaCodec_createDecoderByType(mime_type); CHECK(sfdec->mCodec != NULL); sfdec->mFormat = AMediaFormat_new(); CHECK(sfdec->mFormat != NULL); AMediaFormat_setString(sfdec->mFormat, "mime", mime_type); if (duration_us > 0) AMediaFormat_setInt64(sfdec->mFormat, "durationUs", duration_us); AMediaFormat_setInt32(sfdec->mFormat, "width", sfdec->width); AMediaFormat_setInt32(sfdec->mFormat, "height", sfdec->height); if (input_size > 0) AMediaFormat_setInt32(sfdec->mFormat, "max-input-size", input_size); err = AMediaCodec_configure(sfdec->mCodec, sfdec->mFormat, sfdec->mNativeWindow, NULL, 0); CHECK_STATUS(err); err = AMediaCodec_start(sfdec->mCodec); CHECK_STATUS(err); sfdec->started = true; if (extradata && (codec == SFDEC_VIDEO_HEVC || codec == SFDEC_VIDEO_WMV)) sfdec_send_input2(sfdec, extradata, extradata_size, 0, 0, 1, 2/* BUFFER_FLAG_CODECCONFIG (not exported)*/); return sfdec; } #undef CHECK #undef CHECK_STATUS #define CHECK(x) do { \ if (!(x)) { \ LOG("%s failed: %s", __FUNCTION__, #x); \ return -1; \ } \ } while (0) #define CHECK_STATUS(err) CHECK((err) == AMEDIA_OK) static void sfdec_destroy(sfdec_priv_t *sfdec) { if (sfdec->mCodec != NULL) AMediaCodec_delete(sfdec->mCodec); if (sfdec->mFormat != NULL) AMediaFormat_delete(sfdec->mFormat); delete sfdec; } static int sfdec_start(sfdec_priv_t *sfdec) { if (!sfdec->started) { media_status_t err = AMediaCodec_start(sfdec->mCodec); CHECK_STATUS(err); sfdec->started = true; } return 0; } static int sfdec_stop(sfdec_priv_t *sfdec) { if (sfdec->started) { media_status_t err = AMediaCodec_stop(sfdec->mCodec); CHECK_STATUS(err); sfdec->started = false; } return 0; } static ssize_t sfdec_send_input(sfdec_priv_t *sfdec, void *data, size_t size, int64_t time_us, int is_sync_frame, int wait) { return sfdec_send_input2(sfdec, data, size, time_us, is_sync_frame, wait, 0); } static ssize_t sfdec_send_input2(sfdec_priv_t *sfdec, void *data, size_t size, int64_t time_us, int is_sync_frame, int wait, int flag) { ssize_t index; media_status_t err; size_t bufsize = 0; uint8_t *buf = NULL; sfdec->flush = 0; index = AMediaCodec_dequeueInputBuffer(sfdec->mCodec, wait ? -1ll : 0); if (index < 0) return 0; buf = AMediaCodec_getInputBuffer(sfdec->mCodec, index, &bufsize); if (size > bufsize) size = bufsize; memcpy(buf, data, size); DBG LOG("queueInputBuffer: index %d size %d time %lld flag %d\n", index, size, time_us, flag); err = AMediaCodec_queueInputBuffer(sfdec->mCodec, index, 0, size, time_us, flag); CHECK_STATUS(err); return size; } static int sfdec_flush(sfdec_priv_t *sfdec) { sfdec->flush = 1; media_status_t err = AMediaCodec_flush(sfdec->mCodec); CHECK_STATUS(err); err_count = 0; return 0; } static int sfdec_stop_input(sfdec_priv_t *sfdec) { return 0; } static int sfdec_read(sfdec_priv_t *sfdec, int64_t seek, sfdec_read_out_t *read_out) { ssize_t index; if (!read_out) return -1; read_out->flag = SFDEC_READ_INVALID; for (;;) { AMediaCodecBufferInfo info; index = AMediaCodec_dequeueOutputBuffer(sfdec->mCodec, &info, -1); if (index >= 0) { err_count = 0; sfbuf_t *sfbuf = (sfbuf_t*) calloc(1, sizeof(sfbuf_t)); if (sfbuf == NULL) return -1; sfbuf->index = index; sfbuf->released = false; read_out->flag |= SFDEC_READ_BUF; read_out->buf.sfbuf = sfbuf; read_out->buf.time_us = info.presentationTimeUs; DBG LOG("buf: %d / time: %lld", index, info.presentationTimeUs); return 0; } else if (index == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) { if (init_renderer(sfdec)) continue; read_out->flag |= SFDEC_READ_SIZE; read_out->size.width = sfdec->width; read_out->size.height = sfdec->height; read_out->size.interlaced = 0; DBG LOG("INFO_FORMAT_CHANGED: %dx%d", sfdec->width, sfdec->height); return 0; } else if (index == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) { DBG LOG("INFO_OUTPUT_BUFFERS_CHANGED"); } else if (index == AMEDIACODEC_INFO_TRY_AGAIN_LATER) { DBG LOG("mCodec->dequeueOutputBuffer returned -EAGAIN"); return 0; } else if (index == -10000) { // 0xFFFFD8F0 but works in 64b if (sfdec->flush) { LOG("mCodec->dequeueOutputBuffer returned -10000 while flushing IGNORE!"); return 0; } else { LOG("mCodec->dequeueOutputBuffer returned -10000"); return -1; } } else { err_count++; LOG("mCodec->dequeueOutputBuffer returned: %zx", index); if( err_count > 100 ) { LOG("we had enough!"); return -1; } return 0; } } } static int sfdec_buf_render(sfdec_priv_t *sfdec, sfbuf_t *sfbuf, int render) { media_status_t err; if( render ) { err = AMediaCodec_releaseOutputBuffer(sfdec->mCodec, sfbuf->index, true); } else { err = AMediaCodec_releaseOutputBuffer(sfdec->mCodec, sfbuf->index, false); } CHECK_STATUS(err); sfbuf->released = true; return 0; } static int sfdec_buf_release(sfdec_priv_t *sfdec, sfbuf_t *sfbuf) { media_status_t err = AMEDIA_OK; if (!sfbuf->released) err = AMediaCodec_releaseOutputBuffer(sfdec->mCodec, sfbuf->index, false); free(sfbuf); return err == AMEDIA_OK ? 0 : -1; } sfdec_itf_t sfdec_itf_mediacodec = { "MediaCodec", sfdec_init, sfdec_destroy, sfdec_start, sfdec_stop, sfdec_send_input, sfdec_flush, sfdec_stop_input, sfdec_read, sfdec_buf_render, sfdec_buf_release, };
28.115727
135
0.629763
cyb3rpunk452
c2813af0d582ae9c809474bfaa54cdbe205ae26c
2,542
cpp
C++
starter-stack/Lib/rcsc/action/body_kick_collide_with_ball.cpp
InsperDynamics/Soccer-Simulation-2D
a548d576ca4ab2a8f797810f5e23875c45cef73f
[ "Apache-2.0" ]
null
null
null
starter-stack/Lib/rcsc/action/body_kick_collide_with_ball.cpp
InsperDynamics/Soccer-Simulation-2D
a548d576ca4ab2a8f797810f5e23875c45cef73f
[ "Apache-2.0" ]
null
null
null
starter-stack/Lib/rcsc/action/body_kick_collide_with_ball.cpp
InsperDynamics/Soccer-Simulation-2D
a548d576ca4ab2a8f797810f5e23875c45cef73f
[ "Apache-2.0" ]
null
null
null
// -*-c++-*- /*! \file body_kick_collide_with_ball.cpp \brief intentional kick action to collide with ball */ /* *Copyright: Copyright (C) Hidehisa AKIYAMA This code 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 3 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *EndCopyright: */ ///////////////////////////////////////////////////////////////////// #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "body_hold_ball2008.h" #include "body_kick_collide_with_ball.h" #include <rcsc/player/player_agent.h> #include <rcsc/common/logger.h> #include <rcsc/common/server_param.h> namespace rcsc { /*-------------------------------------------------------------------*/ /*! */ bool Body_KickCollideWithBall::execute( PlayerAgent * agent ) { dlog.addText( Logger::ACTION, __FILE__":%d: Body_KickCollideWithBall" ); const WorldModel & wm = agent->world(); if ( ! wm.self().isKickable() ) { std::cerr << __FILE__ << ": " << __LINE__ << " not ball kickable!" << std::endl; dlog.addText( Logger::ACTION, __FILE__": not kickable" ); return false; } Vector2D required_accel = wm.self().vel(); // target relative pos required_accel -= wm.ball().rpos(); // required vel required_accel -= wm.ball().vel(); // ball next rpos double kick_power = required_accel.r() / wm.self().kickRate(); if ( kick_power > ServerParam::i().maxPower() * 1.1 ) { dlog.addText( Logger::ACTION, __FILE__": over max power(%f).", kick_power ); Body_HoldBall2008( false ).execute( agent ); return false; } if ( kick_power > ServerParam::i().maxPower() ) { kick_power = ServerParam::i().maxPower(); } agent->doKick( kick_power, required_accel.th() - wm.self().body() ); return true; } }
27.333333
74
0.604642
InsperDynamics
c284712f5b22944a88f62207994c29820934cd80
3,040
hpp
C++
core/Material.hpp
lonelywm/cuda_path_tracer
d99f0b682ad7f64fa127ca3604d0eab26f61452c
[ "MIT" ]
1
2021-06-12T11:33:12.000Z
2021-06-12T11:33:12.000Z
core/Material.hpp
lonelywm/cuda_path_tracer
d99f0b682ad7f64fa127ca3604d0eab26f61452c
[ "MIT" ]
null
null
null
core/Material.hpp
lonelywm/cuda_path_tracer
d99f0b682ad7f64fa127ca3604d0eab26f61452c
[ "MIT" ]
null
null
null
#pragma once #include <pch.h> #include <curand_kernel.h> struct Material { Vec3f ka; //Ambient Vec3f kd; //diffuse Vec3f ks; //specular Vec3f kt; //Transmittance Vec3f ke; //Emmission Vec3f kr; //reflectance == specular float ior; float dissolve; // 1 == opaque; 0 == fully transparent uint beginIndex; // device uint endIndex; // device bool _refl; // specular reflector? bool _trans; // specular transmitter? bool _spec; // any kind of specular? bool _both; // reflection and transmission __host__ __device__ void setBools() { _refl = isZero(kr); _trans = isZero(kt); _spec = _refl || isZero(ks); _both = _refl && _trans; } __host__ __device__ bool Refl() const { return _refl; } __host__ __device__ bool Trans() const { return _trans; } __device__ Vec3f shade() { Vec3f I = kd; return I; } __host__ __device__ bool hasEmission() { if (ke.norm2() > EPSILON) return true; return false; } __device__ Vec3f toWorld(CVec3f& a, CVec3f& N) { Vec3f B, C; if (fabs(N.x) > fabs(N.y)) { float invLen = 1.0f / sqrt(N.x * N.x + N.z * N.z); C = Vec3f(N.z * invLen, 0.0f, -N.x * invLen); } else { float invLen = 1.0f / sqrt(N.y * N.y + N.z * N.z); C = Vec3f(0.0f, N.z * invLen, -N.y * invLen); } B = C.cross(N); return a.x * B + a.y * C + a.z * N; } __host__ __device__ __inline__ Vec3f eval(CVec3f& wi, CVec3f& wo, CVec3f& nor) { // diffuse // calculate the contribution of diffuse model float cosalpha = nor.dot(wo); if (cosalpha > 0.0f) { Vec3f diffuse = kd / PI; return diffuse; } return Vec3f(); } __device__ Vec3f sample(CVec3f& Nor, curandState& randState) { float x1 = curand_uniform(&randState); float x2 = curand_uniform(&randState); float z = std::fabs(1.0f - 2.0f * x1); float r = std::sqrt(1.0f - z * z); float phi = 2 * PI * x2; Vec3f localRay(r * cos(phi), r * sin(phi), z); return toWorld(localRay, Nor).normalize(); } __device__ float Material::pdf(const Vec3f& wo, const Vec3f& N) { if (wo.dot(N) > 0.0f) return 0.5f / PI; else return 0.0f; } __device__ Material& operator += (const Material& m){ ke += m.ke; ka += m.ka; ks += m.ks; kd += m.kd; kr += m.kr; kt += m.kt; ior += m.ior; setBools(); return *this; } friend __device__ __inline__ Material operator*(float d, Material m); }; __device__ __inline__ Material operator*(float d, Material m){ m.ke *= d; m.ka *= d; m.ks *= d; m.kd *= d; m.kr *= d; m.kt *= d; m.ior *= d; return m; }
23.030303
62
0.511184
lonelywm
c285ccb0d1f913c21bf42bb4c94d5fe9da789bc5
860
hxx
C++
src/sort_and_index/tree_compress/hash_table.hxx
Caltech-IPAC/libtinyhtm
abc3394f3d37b3729a625989d2fc144f14a7d208
[ "BSD-3-Clause" ]
1
2019-06-17T21:56:31.000Z
2019-06-17T21:56:31.000Z
src/sort_and_index/tree_compress/hash_table.hxx
Caltech-IPAC/libtinyhtm
abc3394f3d37b3729a625989d2fc144f14a7d208
[ "BSD-3-Clause" ]
null
null
null
src/sort_and_index/tree_compress/hash_table.hxx
Caltech-IPAC/libtinyhtm
abc3394f3d37b3729a625989d2fc144f14a7d208
[ "BSD-3-Clause" ]
null
null
null
/* Simple hash table that maps node IDs to relative file offsets. The implementation uses a power-of-2 sized backing array and chains on collision. The hash-code of a node ID is taken to be its post-order index (which is unique). */ #ifndef HTM_TREE_GEN_HASH_TABLE_H #define HTM_TREE_GEN_HASH_TABLE_H #include "id_off.hxx" #include "../arena.hxx" struct hash_table { size_t n; size_t cap; struct id_off **array; #if FAST_ALLOC struct arena *ar; #endif }; void hash_table_init (struct hash_table *ht); void hash_table_destroy (struct hash_table *ht); void hash_table_grow (struct hash_table *ht); uint64_t hash_table_get (struct hash_table *const ht, const struct node_id *const id); void hash_table_add (struct hash_table *const ht, const struct node_id *const id, uint64_t off); #endif
26.875
71
0.717442
Caltech-IPAC
c285ea6b7be70179b2d425f1344232e0aea6a95e
2,923
cpp
C++
test/tools/main.cpp
tizenorg/platform.core.security.askuser
2e15a94f374b676aca8dc2985a643927b80eca3f
[ "Apache-2.0" ]
null
null
null
test/tools/main.cpp
tizenorg/platform.core.security.askuser
2e15a94f374b676aca8dc2985a643927b80eca3f
[ "Apache-2.0" ]
null
null
null
test/tools/main.cpp
tizenorg/platform.core.security.askuser
2e15a94f374b676aca8dc2985a643927b80eca3f
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2016 Samsung Electronics Co. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ /** * @file main.cpp * @author Oskar Świtalski <o.switalski@samsung.com> * @brief Main test file */ #include <iostream> #include <string> #include <cynara-admin.h> #include <cynara-client.h> #include <cynara-error.h> #include <exception/CynaraException.h> #include <types/SupportedTypes.h> #include <unistd.h> cynara *cyn; cynara_admin *admin; void check_cynara_return(std::string func, int ret) { if (ret < 0) { throw AskUser::CynaraException(func, ret); } } int main(int argc, char **argv) { int ret; std::string client = "User::App::org.tizen.task-mgr"; std::string user = "5001"; std::string privilege = "http://tizen.org/privilege/appmanager.kill"; std::string bucket = ""; if (argc > 1) { privilege = argv[1]; } try { ret = cynara_admin_initialize(&admin); check_cynara_return("cynara_admin_initialize", ret); cynara_admin_policy **policies = new cynara_admin_policy*[2]; cynara_admin_policy policy = {&bucket[0], &client[0], &user[0], &privilege[0], AskUser::SupportedTypes::Service::ASK_USER , nullptr}; policies[0] = &policy; policies[1] = nullptr; ret = cynara_admin_set_policies(admin, policies); check_cynara_return("cynara_admin_set_policies", ret); ret = cynara_admin_finish(admin); check_cynara_return("cynara_admin_finish", ret); ret = cynara_initialize(&cyn, nullptr); check_cynara_return("cynara_initialize", ret); for (int i = 0; i < 10; ++i) { ret = cynara_check(cyn, client.c_str(), "session", user.c_str(), privilege.c_str()); check_cynara_return("cynara_check", ret); switch (ret) { case CYNARA_API_ACCESS_ALLOWED: std::cout << "Allowed" << std::endl; break; case CYNARA_API_ACCESS_DENIED: std::cout << "Denied" << std::endl; break; } } ret = cynara_finish(cyn); check_cynara_return("cynara_finish", ret); } catch (std::exception &e) { std::cerr << e.what() << std::endl; } catch (...) { std::cerr << "Unknown error" << std::endl; } return 0; }
28.105769
96
0.612042
tizenorg
c287298c2509f408afc6a7a48b0318bf1726b507
1,041
cc
C++
FWCore/Framework/src/DataKeyTags.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
1
2019-08-09T08:42:11.000Z
2019-08-09T08:42:11.000Z
FWCore/Framework/src/DataKeyTags.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
null
null
null
FWCore/Framework/src/DataKeyTags.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
1
2019-03-19T13:44:54.000Z
2019-03-19T13:44:54.000Z
// -*- C++ -*- // // Package: Framework // Class : DataKeyTags // // Implementation: // <Notes on implementation> // // Author: Chris Jones // Created: Thu Mar 31 14:25:33 EST 2005 // // system include files #include <cstring> // user include files #include "FWCore/Framework/interface/DataKeyTags.h" // // constants, enums and typedefs // namespace edm { namespace eventsetup { // // static data member definitions // // // constructors and destructor // // assignment operators // // const DataKeyTags& DataKeyTags::operator=(const DataKeyTags& rhs) // { // //An exception safe implementation is // DataKeyTags temp(rhs); // swap(rhs); // // return *this; // } // // member functions // // // const member functions // bool SimpleStringTag::operator==(const SimpleStringTag& iRHS) const { return (0 == std::strcmp(tag_, iRHS.tag_)); } bool SimpleStringTag::operator<(const SimpleStringTag& iRHS) const { return (0 > std::strcmp(tag_, iRHS.tag_)); } // // static member functions // } }
15.308824
68
0.647454
nistefan
c28753c302c7715048d1e9760a7e1895e717f57e
833
cpp
C++
CFB_Cursos/QT/formularios/objeto_local/formularios/mainwindow.cpp
marcospontoexe/Cpp
d640be32fda2a25f871271e024efef727e7890c1
[ "MIT" ]
null
null
null
CFB_Cursos/QT/formularios/objeto_local/formularios/mainwindow.cpp
marcospontoexe/Cpp
d640be32fda2a25f871271e024efef727e7890c1
[ "MIT" ]
null
null
null
CFB_Cursos/QT/formularios/objeto_local/formularios/mainwindow.cpp
marcospontoexe/Cpp
d640be32fda2a25f871271e024efef727e7890c1
[ "MIT" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QMessageBox> #include "janela.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { janela form2; //declaração do atributo da classe janela QMessageBox::StandardButton resposta; resposta = QMessageBox::question(this, "Janela", "Deseja realmente abriar a janela?", QMessageBox::Yes | QMessageBox::No); if (resposta == QMessageBox::No) { QMessageBox::about(this, "Fim", "Até logo!"); close(); //QApplication::quit(); também encerra a aplicação } else { QMessageBox::about(this, "Janela", "Janela aberta!"); form2.exec(); } }
20.825
126
0.638655
marcospontoexe
c28b04dbd2d248d3431d2fa8115c31b042d4683b
588
cpp
C++
code/cpp/ReverseLinkedListRecur.cpp
analgorithmaday/analgorithmaday.github.io
d43f98803bc673f61334bff54eed381426ee902e
[ "MIT" ]
null
null
null
code/cpp/ReverseLinkedListRecur.cpp
analgorithmaday/analgorithmaday.github.io
d43f98803bc673f61334bff54eed381426ee902e
[ "MIT" ]
null
null
null
code/cpp/ReverseLinkedListRecur.cpp
analgorithmaday/analgorithmaday.github.io
d43f98803bc673f61334bff54eed381426ee902e
[ "MIT" ]
null
null
null
List* recur_rlist(List* head) { List* result; if(!(head && head->next)) return head; result = recur_rlist(head->next); head->next->next = head; head->next = NULL; return result; } void printList(List* head) { while(head != NULL) { std::cout<<head->data<<" "; head = head->next; } } void main() { List* list = createNode(2); append(list, createNode(3)); append(list, createNode(4)); append(list, createNode(5)); append(list, createNode(6)); List* revlist = recur_rlist(list); printList(revlist); }
18.967742
38
0.571429
analgorithmaday
c290b2d958731274efc46000bdc20277618a74ca
4,126
cc
C++
test/mpdtest.cc
farlies/rsked
cd2004bed454578f4d2ac25996dc1ced98d4fa58
[ "Apache-2.0" ]
null
null
null
test/mpdtest.cc
farlies/rsked
cd2004bed454578f4d2ac25996dc1ced98d4fa58
[ "Apache-2.0" ]
null
null
null
test/mpdtest.cc
farlies/rsked
cd2004bed454578f4d2ac25996dc1ced98d4fa58
[ "Apache-2.0" ]
1
2020-10-04T22:14:55.000Z
2020-10-04T22:14:55.000Z
/** * Test the MPD client class * * This is a "manual" test, and requires user interaction to listen for * the correct audio output. It does not use the boost test framework. * 1. mpd must be running * 2. you must provide a valid resource string as the sole argument */ /* Part of the rsked package. * * Copyright 2020 Steven A. Harp * * 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 "logging.hpp" #include "mpdclient.hpp" #include <boost/filesystem.hpp> namespace fs = boost::filesystem; /// Sample invocations: /// mp4 file /// mpdtest "Brian Eno/Another Green World/08 - Sombre Reptiles.m4a" /// flac file /// mpdtest "Dub Apocalypse/Live at 3S Artspace/03 Track04.flac" /// directory with mp4 tracks /// mpdtest "Brian Eno/Another Green World" /// playlist (.m3u) The .m3u will (must) be stripped for mpd. /// mpdtest "master.m3u" /////////////////////////////////////////////////////////////////////////////////// void log_last_err( Mpd_client &client ) { switch( client.last_err() ) { case Mpd_err::NoError: LOG_INFO(Lgr) << "MPD no error"; break; case Mpd_err::NoConnection: LOG_ERROR(Lgr) << "MPD could not connect"; break; case Mpd_err::NoStatus: LOG_ERROR(Lgr) << "MPD did not receive a status response"; break; case Mpd_err::NoExist: LOG_ERROR(Lgr) << "MPD could not access the resource"; break; default: LOG_ERROR(Lgr) << "MPD unknown Mpd_err"; } } /// tests a single track or directory /// void test1( Mpd_client &client, const std::string &resource ) { client.connect(); // client.stop(); client.clear_queue(); client.set_repeat_mode(false); client.enqueue( resource ); client.check_status(Mpd_opt::Print); if (client.last_err() == Mpd_err::NoError) { client.play(); sleep(10); client.check_status(Mpd_opt::Print); client.stop(); } // client.disconnect(); } /// tests a playlist /// void testp( Mpd_client &client, const std::string &plist ) { // strip any trailing extension, like .m3u, if present fs::path plfile { plist }; std::string plstem { plfile.stem().native() }; LOG_DEBUG(Lgr) << "playlist stem: '" << plstem << "'"; client.connect(); // client.stop(); client.clear_queue(); client.set_repeat_mode(false); client.enqueue_playlist( plstem ); client.check_status(Mpd_opt::Print); if (client.last_err() == Mpd_err::NoError) { client.play(); sleep(10); client.check_status(Mpd_opt::Print); client.stop(); } // client.disconnect(); } //////////////////////////////////////////////////////////////////////////// int main(int argc, char* argv[]) { init_logging("mpdtest","mpdtest_%5N.log",LF_FILE|LF_DEBUG|LF_CONSOLE); if (argc < 2) { LOG_ERROR(Lgr) << "Usage: mpdtest resource_string"; return 1; } std::string filestring { argv[1] }; fs::path filename { filestring }; LOG_INFO(Lgr) << "Play " << filename << " for 10 seconds."; Mpd_client client {}; try { if (filename.extension() == ".m3u") { LOG_INFO(Lgr) << "(It seems to be a playlist.)"; testp( client, filestring ); // playlist - handled differently } else { test1( client, filestring ); // regular file } } catch (std::exception &xxx) { LOG_ERROR(Lgr) << "Exit on exception: " << xxx.what(); } log_last_err( client ); finish_logging(); return 0; }
27.506667
83
0.598885
farlies
c2920831970f9790f579c5c0c0c8083e6131e12a
7,523
cpp
C++
src/setup.cpp
latture/explicit-beam-fea
003e940bda203e1d867494c891c9cee3477cd682
[ "MIT" ]
1
2018-07-07T07:42:45.000Z
2018-07-07T07:42:45.000Z
src/setup.cpp
latture/explicit-beam-fea
003e940bda203e1d867494c891c9cee3477cd682
[ "MIT" ]
null
null
null
src/setup.cpp
latture/explicit-beam-fea
003e940bda203e1d867494c891c9cee3477cd682
[ "MIT" ]
null
null
null
// // Created by ryan on 3/7/16. // #include "setup.h" #include <boost/format.hpp> #include <rapidjson/error/en.h> #include "csv_parser.h" #include "timoshenko_beam_element.h" namespace explicit_fea { namespace { template<typename T> void createVectorFromJSON(const rapidjson::Document &config_doc, const std::string &variable, std::vector<T> &data) { if (!config_doc.HasMember(variable.c_str())) { throw std::runtime_error( (boost::format("Configuration file does not have requested member variable %s.") % variable).str() ); } if (!config_doc[variable.c_str()].IsString()) { throw std::runtime_error( (boost::format("Value associated with variable %s is not a string.") % variable).str() ); } CSVParser csv; std::string filename(config_doc[variable.c_str()].GetString()); csv.parseToVector(filename, data); if (data.size() == 0) { throw std::runtime_error( (boost::format("No data was loaded for variable %s.") % variable).str() ); } } } rapidjson::Document parseJSONConfig(const std::string &config_filename) { rapidjson::Document config_doc; FILE *config_file_ptr = fopen(config_filename.c_str(), "r"); if (!config_file_ptr) { throw std::runtime_error( (boost::format("Cannot open configuration input file %s.") % config_filename).str() ); } char readBuffer[65536]; rapidjson::FileReadStream config_stream(config_file_ptr, readBuffer, sizeof(readBuffer)); config_doc.ParseStream(config_stream); if (config_doc.HasParseError()) { throw std::runtime_error( (boost::format("Error parsing %s (offset %d):\t%s") % config_filename % config_doc.GetErrorOffset() % rapidjson::GetParseError_En(config_doc.GetParseError())).str() ); } fclose(config_file_ptr); return config_doc; } std::vector<Node> createNodeVecFromJSON(const rapidjson::Document &config_doc) { std::vector<std::vector<double> > nodes_vec; createVectorFromJSON(config_doc, "nodes", nodes_vec); std::vector<Node> nodes_out(nodes_vec.size()); Node n; for (size_t i = 0; i < nodes_vec.size(); ++i) { if (nodes_vec[i].size() != 3) { throw std::runtime_error( (boost::format("Row %d in nodes does not specify x, y and z coordinates.") % i).str() ); } n << nodes_vec[i][0], nodes_vec[i][1], nodes_vec[i][2]; nodes_out[i] = n; } return nodes_out; } std::vector<std::unique_ptr<BeamElement>> createElemVecFromJSON(const rapidjson::Document &config_doc) { std::vector< std::vector<int> > elems_vec; std::vector< std::vector<double> > props_vec; createVectorFromJSON(config_doc, "elems", elems_vec); createVectorFromJSON(config_doc, "props", props_vec); if (elems_vec.size() != props_vec.size()) { throw std::runtime_error("The number of rows in elems did not match props."); } std::vector<std::unique_ptr<BeamElement>> elems_out(elems_vec.size()); Eigen::Vector3d normal_vec; for (size_t i = 0; i < elems_vec.size(); ++i) { if (elems_vec[i].size() != 2) { throw std::runtime_error( (boost::format("Row %d in elems does not specify 2 nodal indices [nn1,nn2].") % i).str() ); } if (props_vec[i].size() != 10) { throw std::runtime_error( (boost::format("Row %d in props does not specify the 10 property values " "[youngs_modulus,shear_modulus,area,Iz,Iy,J,density,nx,ny,nz]") % i).str() ); } normal_vec << props_vec[i][7], props_vec[i][8], props_vec[i][9]; Props p(props_vec[i][0], props_vec[i][1], props_vec[i][2], props_vec[i][3], props_vec[i][4], props_vec[i][5], props_vec[i][6], normal_vec); elems_out[i] = std::unique_ptr<TimoshenkoBeamElement>(new TimoshenkoBeamElement(elems_vec[i][0], elems_vec[i][1], p)); } return elems_out; } std::vector<std::unique_ptr<BC>> createBCVecFromJSON(const rapidjson::Document &config_doc) { std::vector< std::vector<double> > bcs_vec; createVectorFromJSON(config_doc, "bcs", bcs_vec); std::vector<std::unique_ptr<BC>> bcs_out(bcs_vec.size()); for (size_t i = 0; i < bcs_vec.size(); ++i) { if (bcs_vec[i].size() != 4) { throw std::runtime_error( (boost::format("Row %d in bcs does not specify [node number,DOF,value,type].") % i).str() ); } bcs_out[i] = std::unique_ptr<ConstantBC>(new ConstantBC((unsigned int) bcs_vec[i][0], (unsigned int) bcs_vec[i][1], bcs_vec[i][2], (BC::Type)(unsigned int) bcs_vec[i][3])); } return bcs_out; } std::vector<std::unique_ptr<Force>> createForceVecFromJSON(const rapidjson::Document &config_doc) { std::vector<std::unique_ptr<Force>> forces_out; if (config_doc.HasMember("forces")) { std::vector<std::vector<double> > forces_vec; createVectorFromJSON(config_doc, "forces", forces_vec); forces_out.resize(forces_vec.size()); for (size_t i = 0; i < forces_vec.size(); ++i) { if (forces_vec[i].size() != 3) { throw std::runtime_error( (boost::format("Row %d in forces does not specify [node number,DOF,value].") % i).str() ); } forces_out[i] = std::unique_ptr<ConstantForce>(new ConstantForce((unsigned int) forces_vec[i][0], (unsigned int) forces_vec[i][1], forces_vec[i][2])); } } return forces_out; } ColumnVector createColumnVectorFromJSON(const rapidjson::Document &config_doc, std::string key, unsigned int size) { ColumnVector col_vec(size); if (config_doc.HasMember(key.c_str())) { std::vector< std::vector<double> > vec; createVectorFromJSON(config_doc, key, vec); if (vec.size() != size) { throw std::runtime_error( (boost::format("Key specified by %s does not have the required %d values. %d entries were parsed.") % key % size % vec.size()).str() ); } for (int i = 0; i < size; ++i) { if (vec[i].size() != 1) { throw std::runtime_error( (boost::format("Row %d in the file specified by %s has %d values. There should only be one nodal value per line.") % i % key % size % vec[i].size()).str() ); } col_vec[i] = vec[i][0]; } } else { col_vec.setZero(); } return col_vec; } }
40.88587
184
0.531969
latture
c2937623bc9acd9db390a4927e121d40eff95033
384
cpp
C++
fundamentals/introduction/pyramid.cpp
stemDaniel/ufmg-pds2
4dbb536a0926b617d04d133cbd3f7a5a223e113e
[ "MIT" ]
null
null
null
fundamentals/introduction/pyramid.cpp
stemDaniel/ufmg-pds2
4dbb536a0926b617d04d133cbd3f7a5a223e113e
[ "MIT" ]
null
null
null
fundamentals/introduction/pyramid.cpp
stemDaniel/ufmg-pds2
4dbb536a0926b617d04d133cbd3f7a5a223e113e
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int height; cout << "Insira a altura da pirâmide: "; cin >> height; for (int i = 0; i < height; ++i) { for (int j = 0; j <= i; ++j) { cout << "*"; } cout << endl; } for (int i = height - 1; i > 0; --i) { for (int j = i; j > 0; --j) { cout << "*"; } cout << endl; } return 0; }
17.454545
42
0.442708
stemDaniel
c29456f50b570fd2027d566cb489c4e33bad3544
6,396
cpp
C++
src/cassimpmodel.cpp
SilangQuan/QSLFrameWork
13059fef0972e0753d0d77e8f1cd9bdaf80beb0d
[ "MIT" ]
16
2015-09-24T00:59:34.000Z
2022-02-20T03:43:47.000Z
src/cassimpmodel.cpp
aleksas/QSLFrameWork
13059fef0972e0753d0d77e8f1cd9bdaf80beb0d
[ "MIT" ]
null
null
null
src/cassimpmodel.cpp
aleksas/QSLFrameWork
13059fef0972e0753d0d77e8f1cd9bdaf80beb0d
[ "MIT" ]
8
2016-05-11T05:59:53.000Z
2019-01-11T16:32:46.000Z
#include "cassimpmodel.h" CAssimpModel::MeshEntry::MeshEntry() { VB = INVALID_OGL_VALUE; IB = INVALID_OGL_VALUE; numIndices = 0; materialIndex = INVALID_OGL_VALUE; }; CAssimpModel::MeshEntry::~MeshEntry() { if (VB != INVALID_OGL_VALUE) { glDeleteBuffers(1, &VB); } if (IB != INVALID_OGL_VALUE) { glDeleteBuffers(1, &IB); } } void CAssimpModel::MeshEntry::init(const std::vector<Vertex>& vertices, const std::vector<unsigned int>& indices) { numIndices = indices.size(); glGenBuffers(1, &VB); glBindBuffer(GL_ARRAY_BUFFER, VB); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * vertices.size(), &vertices[0], GL_STATIC_DRAW); glGenBuffers(1, &IB); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IB); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * numIndices, &indices[0], GL_STATIC_DRAW); } CAssimpModel::CAssimpModel() { isLoaded = false; } CAssimpModel::~CAssimpModel() { for(int i = 0;i < textures.size(); i++) { free(textures[i]); } } CAssimpModel::CAssimpModel(ShaderProgram& p) { prog = &p; isLoaded = false; } bool CAssimpModel::LoadModelFromFile(const std::string& filepath) { Assimp::Importer importer; const aiScene* scene = importer.ReadFile( filepath, aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs); if(!scene) { cout<<"Couldn't load model, Error Importing Asset"<<endl; return false; } meshEntries.resize(scene->mNumMeshes); textures.resize(scene->mNumMaterials); for(int i=0; i<scene->mNumMeshes; i++) { aiMesh* paiMesh = scene->mMeshes[i]; int iMeshFaces = paiMesh->mNumFaces; cout<<"Mesh "<<i<<" faces:"<<iMeshFaces<<endl; initMesh(i, paiMesh); } cout<<scene->mNumMaterials<<endl; if(scene->mNumMaterials > 1) { initMaterial(scene,filepath); } cout<<"scene->mNumMeshes:"<<scene->mNumMeshes<<endl; cout<<"scene->mNumMaterials:"<<scene->mNumMaterials<<endl; aiMesh* paiMesh = scene->mMeshes[0]; cout<<"mesh0->mNumFaces:"<<paiMesh->mNumFaces<<endl; cout<<"mesh0->mNumVertices:"<<paiMesh->mNumVertices<<endl; isLoaded = true; return true; } void CAssimpModel::initMesh(unsigned int index, const aiMesh* paiMesh) { meshEntries[index].materialIndex = paiMesh->mMaterialIndex; cout<<"mesh"<<index<< "mMaterialIndex"<< paiMesh->mMaterialIndex<<endl; vector<Vertex> vertices; vector<unsigned int> indices; const aiVector3D Zero3D(0.0f, 0.0f, 0.0f); vertices.reserve(paiMesh->mNumVertices); indices.reserve(paiMesh->mNumFaces); for (unsigned int i = 0 ; i < paiMesh->mNumVertices ; i++) { const aiVector3D* pPos = &(paiMesh->mVertices[i]); const aiVector3D* pNormal = &(paiMesh->mNormals[i]); const aiVector3D* pTexCoord = paiMesh->HasTextureCoords(0) ? &(paiMesh->mTextureCoords[0][i]) : &Zero3D; Vertex v(glm::vec3(pPos->x, pPos->y, pPos->z), glm::vec2(pTexCoord->x, pTexCoord->y), glm::vec3(pNormal->x, pNormal->y, pNormal->z) ); // cout<<i<<": "<<v.m_tex.x<<v.m_tex.y<<endl; vertices.push_back(v); } for(unsigned int i=0; i<paiMesh->mNumFaces; i++) { const aiFace& Face = paiMesh->mFaces[i]; assert(Face.mNumIndices == 3); indices.push_back(Face.mIndices[0]); indices.push_back(Face.mIndices[1]); indices.push_back(Face.mIndices[2]); } meshEntries[index].init(vertices, indices); } void CAssimpModel::render() { if(!isLoaded) return; glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); for (unsigned int i = 0 ; i < meshEntries.size() ; i++) { glBindBuffer(GL_ARRAY_BUFFER, meshEntries[i].VB); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)(sizeof(glm::vec3))); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)(sizeof(glm::vec2)+sizeof(glm::vec3))); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, meshEntries[i].IB); const unsigned int materialIndex = meshEntries[i].materialIndex; if (materialIndex < textures.size() && textures[materialIndex]) { textures[materialIndex]->bind(GL_TEXTURE0); //prog->setUniform("Tex2", 0); //cout<<"Draw "<<i<<endl; } glDrawElements(GL_TRIANGLES, meshEntries[i].numIndices, GL_UNSIGNED_INT, 0); } glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); } bool CAssimpModel::initMaterial(const aiScene* pScene, const string& filePath) { string::size_type slashIndex = filePath.find_last_of("/"); string dir; if (slashIndex == string::npos) { dir = "."; } else if (slashIndex == 0) { dir = "/"; } else { dir = filePath.substr(0, slashIndex); } bool Ret = true; // Initialize the materials for (unsigned int i = 1 ; i < pScene->mNumMaterials ; i++) { const aiMaterial* pMaterial = pScene->mMaterials[i]; textures[i] = NULL; if (pMaterial->GetTextureCount(aiTextureType_DIFFUSE) > 0) { aiString path; if (pMaterial->GetTexture(aiTextureType_DIFFUSE, 0, &path, NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS) { string fullPath = dir + "/" + path.data; textures[i] = new CTexture(GL_TEXTURE_2D, fullPath.c_str()); if (!textures[i]->load()) { printf("Error loading texture '%s'\n", fullPath.c_str()); delete textures[i]; textures[i] = NULL; Ret = false; } else { printf("Loaded texture '%s'\n", fullPath.c_str()); } } } // Load a white texture in case the model does not include its own texture if (textures[i]==NULL) { textures[i] = new CTexture(GL_TEXTURE_2D, "../assets/textures/white.png"); Ret = textures[i]->load(); } } return Ret; }
29.072727
129
0.606473
SilangQuan
c296eb02ac947debd8533b4c2d2560259157a2e0
13,691
cpp
C++
Cores/Mednafen/mednafen/src/compress/ZIPReader.cpp
ianclawson/Provenance
e9cc8c57f41a4d122a998cf53ffd69b1513d4205
[ "BSD-3-Clause" ]
3,459
2015-01-07T14:07:09.000Z
2022-03-25T03:51:10.000Z
Cores/Mednafen/mednafen/src/compress/ZIPReader.cpp
ianclawson/Provenance
e9cc8c57f41a4d122a998cf53ffd69b1513d4205
[ "BSD-3-Clause" ]
1,046
2018-03-24T17:56:16.000Z
2022-03-23T08:13:09.000Z
Cores/Mednafen/mednafen/src/compress/ZIPReader.cpp
ianclawson/Provenance
e9cc8c57f41a4d122a998cf53ffd69b1513d4205
[ "BSD-3-Clause" ]
549
2015-01-07T14:07:15.000Z
2022-01-07T16:13:05.000Z
/******************************************************************************/ /* Mednafen - Multi-system Emulator */ /******************************************************************************/ /* ZIPReader.cpp: ** Copyright (C) 2018 Mednafen Team ** ** This program is free software; you can redistribute it and/or ** modify it under the terms of the GNU General Public License ** as published by the Free Software Foundation; either version 2 ** of the License, or (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software Foundation, Inc., ** 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // TODO: 64-bit ZIP support(limit sizes to 2**63 - 2?) // TODO: Stream::clone() #include <mednafen/mednafen.h> #include "ZIPReader.h" #include "ZLInflateFilter.h" namespace Mednafen { class StreamViewFilter : public Stream { public: StreamViewFilter(Stream* source_stream, const std::string& vfc, uint64 sp, uint64 bp, uint64 expcrc32 = ~(uint64)0); virtual ~StreamViewFilter() override; virtual uint64 read(void *data, uint64 count, bool error_on_eos = true) override; virtual void write(const void *data, uint64 count) override; virtual void seek(int64 offset, int whence) override; virtual uint64 tell(void) override; virtual uint64 size(void) override; virtual void close(void) override; virtual uint64 attributes(void) override; virtual void truncate(uint64 length) override; virtual void flush(void) override; private: Stream* ss; uint64 ss_start_pos; uint64 ss_bound_pos; uint64 pos; uint32 running_crc32; uint64 running_crc32_posreached; uint64 expected_crc32; const std::string vfcontext; }; StreamViewFilter::StreamViewFilter(Stream* source_stream, const std::string& vfc, uint64 sp, uint64 bp, uint64 expcrc32) : ss(source_stream), ss_start_pos(sp), ss_bound_pos(bp), pos(0), running_crc32(0), running_crc32_posreached(0), expected_crc32(expcrc32), vfcontext(vfc) { if(ss_bound_pos < ss_start_pos) throw MDFN_Error(0, _("StreamViewFilter() bound_pos < start_pos")); if((ss_bound_pos - ss_start_pos) > INT64_MAX) throw MDFN_Error(0, _("StreamViewFilter() size too large")); } StreamViewFilter::~StreamViewFilter() { } uint64 StreamViewFilter::read(void *data, uint64 count, bool error_on_eos) { uint64 cc = count; uint64 ret; cc = std::min<uint64>(cc, ss_bound_pos - ss_start_pos); cc = std::min<uint64>(cc, ss_bound_pos - std::min<uint64>(ss_bound_pos, pos)); if(cc < count && error_on_eos) throw MDFN_Error(0, _("Error reading from %s: %s"), vfcontext.c_str(), _("Unexpected EOF")); if(ss->tell() != (ss_start_pos + pos)) ss->seek(ss_start_pos + pos, SEEK_SET); ret = ss->read(data, cc, error_on_eos); pos += ret; if(expected_crc32 != ~(uint64)0) { if(pos > running_crc32_posreached && (pos - ret) <= running_crc32_posreached) { running_crc32 = crc32(running_crc32, (Bytef*)data + (running_crc32_posreached - (pos - ret)), pos - running_crc32_posreached); running_crc32_posreached = pos; if(running_crc32_posreached == (ss_bound_pos - ss_start_pos)) { if(running_crc32 != expected_crc32) throw MDFN_Error(0, _("Error reading from %s: %s"), vfcontext.c_str(), _("Data fails CRC32 check.")); } } } return ret; } void StreamViewFilter::write(const void *data, uint64 count) { #if 0 uint64 cc = count; uint64 ret; cc = std::min<uint64>(cc, ss_bound_pos - ss_start_pos); cc = std::min<uint64>(cc, ss_bound_pos - std::min<uint64>(ss_bound_pos, pos)); if(cc < count) throw MDFN_Error(0, _("ASDF")); if(ss->tell() != (ss_start_pos + pos)) ss->seek(ss_start_pos + pos, SEEK_SET); ss->write(data, cc); pos += cc; #endif throw MDFN_Error(ErrnoHolder(EINVAL)); } void StreamViewFilter::seek(int64 offset, int whence) { #if 0 uint64 new_pos = pos; if(whence == SEEK_SET) { //if(offset < 0) // throw MDFN_Error(EINVAL, _("Attempted to seek before start of stream.")); new_pos = (uint64)offset; } else if(whence == SEEK_CUR) { if(offset < 0 && (uint64)-(uint64)offset > (pos - ss_start_pos)) throw MDFN_Error(EINVAL, _("Attempted to seek before start of stream.")); } else if(whence == SEEK_END) { if(offset < 0 && (uint64)-(uint64)offset > (ss_bound_pos - ss_start_pos)) throw MDFN_Error(EINVAL, _("Attempted to seek before start of stream.")); } #endif int64 new_pos = pos; if(whence == SEEK_SET) new_pos = offset; else if(whence == SEEK_CUR) new_pos = pos + offset; else if(whence == SEEK_END) new_pos = (ss_bound_pos - ss_start_pos) + offset; if(new_pos < 0) throw MDFN_Error(EINVAL, _("Error seeking in %s: %s"), vfcontext.c_str(), _("Attempted to seek before start of stream.")); pos = new_pos; } uint64 StreamViewFilter::tell(void) { return pos; } uint64 StreamViewFilter::size(void) { return ss_bound_pos - ss_start_pos; } void StreamViewFilter::close(void) { ss = nullptr; } uint64 StreamViewFilter::attributes(void) { return ss->attributes(); } void StreamViewFilter::truncate(uint64 length) { //ss->truncate(ss_start_pos + length); throw MDFN_Error(ErrnoHolder(EINVAL)); } void StreamViewFilter::flush(void) { ss->flush(); } Stream* ZIPReader::open(size_t which) { const auto& e = entries[which]; zs->seek(e.lh_reloffs, SEEK_SET); struct { uint32 sig; uint16 version_need; uint16 gpflags; uint16 method; uint16 mod_time; uint16 mod_date; uint32 crc32; uint32 comp_size; uint32 uncomp_size; uint16 name_len; uint16 extra_len; } lfh; uint8 lfh_raw[0x1E]; if(zs->read(lfh_raw, sizeof(lfh_raw), false) != sizeof(lfh_raw)) throw MDFN_Error(0, _("Unexpected EOF when reading ZIP Local File Header.")); lfh.sig = MDFN_de32lsb(&lfh_raw[0x00]); lfh.version_need = MDFN_de16lsb(&lfh_raw[0x04]); lfh.gpflags = MDFN_de16lsb(&lfh_raw[0x06]); lfh.method = MDFN_de16lsb(&lfh_raw[0x08]); lfh.mod_time = MDFN_de16lsb(&lfh_raw[0x0A]); lfh.mod_date = MDFN_de16lsb(&lfh_raw[0x0C]); lfh.crc32 = MDFN_de32lsb(&lfh_raw[0x0E]); lfh.comp_size = MDFN_de32lsb(&lfh_raw[0x12]); lfh.uncomp_size = MDFN_de32lsb(&lfh_raw[0x16]); lfh.name_len = MDFN_de16lsb(&lfh_raw[0x1A]); lfh.extra_len = MDFN_de16lsb(&lfh_raw[0x1C]); if(lfh.sig != 0x04034B50) throw MDFN_Error(0, _("Bad Local File Header signature.")); if(lfh.method != e.method) throw MDFN_Error(0, _("Mismatch of compression method between Central Directory(%d) and Local File Header(%d)."), e.method, lfh.method); if(lfh.gpflags & 0x1) throw MDFN_Error(0, _("ZIP decryption support not implemented.")); if(e.method != 0 && e.method != 8 && e.method != 9) throw MDFN_Error(0, _("ZIP compression method %u not implemented."), e.method); zs->seek(lfh.name_len + lfh.extra_len, SEEK_CUR); std::string vfcontext = MDFN_sprintf(_("opened file \"%s\" in ZIP archive"), e.name.c_str()); if(e.method == 0) { uint64 start_pos = zs->tell(); uint64 bound_pos = start_pos + e.uncomp_size; return new StreamViewFilter(zs.get(), vfcontext, start_pos, bound_pos, e.crc32); } else if(e.method == 8) return new ZLInflateFilter(zs.get(), vfcontext, ZLInflateFilter::FORMAT::RAW, e.comp_size, e.uncomp_size, e.crc32); else throw MDFN_Error(0, _("ZIP compression method %u not implemented."), lfh.method); } ZIPReader::~ZIPReader() { } ZIPReader::ZIPReader(std::unique_ptr<Stream> s) : VirtualFS('/', "/") { const uint64 size = s->size(); if(size < 22) throw MDFN_Error(0, _("Too small to be a ZIP file.")); const uint64 scan_size = std::min<uint64>(size, 65535 + 22); std::unique_ptr<uint8[]> buf(new uint8[scan_size]); const uint8* eocdrp = nullptr; s->seek(size - scan_size, SEEK_SET); s->read(&buf[0], scan_size); for(size_t scan_pos = scan_size - 22; scan_pos != ~(size_t)0; scan_pos--) { if(MDFN_de32lsb(&buf[scan_pos]) == 0x06054B50) { eocdrp = &buf[scan_pos]; break; } } if(!eocdrp) throw MDFN_Error(0, _("ZIP End of Central Directory Record not found!")); // // // struct { uint32 sig; uint16 disk; uint16 cd_start_disk; uint16 disk_cde_count; uint16 total_cde_count; uint32 cd_size; uint32 cd_offs; uint16 comment_size; } eocdr; eocdr.sig = MDFN_de32lsb(&eocdrp[0x00]); eocdr.disk = MDFN_de16lsb(&eocdrp[0x04]); eocdr.cd_start_disk = MDFN_de16lsb(&eocdrp[0x06]); eocdr.disk_cde_count = MDFN_de16lsb(&eocdrp[0x08]); eocdr.total_cde_count = MDFN_de16lsb(&eocdrp[0x0A]); eocdr.cd_size = MDFN_de32lsb(&eocdrp[0x0C]); eocdr.cd_offs = MDFN_de32lsb(&eocdrp[0x10]); eocdr.comment_size = MDFN_de16lsb(&eocdrp[0x14]); if((eocdr.disk != eocdr.cd_start_disk) || eocdr.disk != 0 || (eocdr.disk_cde_count != eocdr.total_cde_count)) throw MDFN_Error(0, _("ZIP split archive support not implemented.")); if(eocdr.cd_offs >= size) throw MDFN_Error(0, _("ZIP Central Directory start offset is bad.")); s->seek(eocdr.cd_offs, SEEK_SET); for(uint32 i = 0; i < eocdr.total_cde_count; i++) { uint8 cdr_raw[46]; FileDesc d; if(s->read(cdr_raw, sizeof(cdr_raw), false) != sizeof(cdr_raw)) throw MDFN_Error(0, _("Unexpected EOF when reading ZIP Central Directory entry %u"), i); d.sig = MDFN_de32lsb(&cdr_raw[0x00]); d.version_made = MDFN_de16lsb(&cdr_raw[0x04]); d.version_need = MDFN_de16lsb(&cdr_raw[0x06]); d.gpflags = MDFN_de16lsb(&cdr_raw[0x08]); d.method = MDFN_de16lsb(&cdr_raw[0x0A]); d.mod_time = MDFN_de16lsb(&cdr_raw[0x0C]); d.mod_date = MDFN_de16lsb(&cdr_raw[0x0E]); d.crc32 = MDFN_de32lsb(&cdr_raw[0x10]); d.comp_size = MDFN_de32lsb(&cdr_raw[0x14]); d.uncomp_size = MDFN_de32lsb(&cdr_raw[0x18]); d.name_len = MDFN_de16lsb(&cdr_raw[0x1C]); d.extra_len = MDFN_de16lsb(&cdr_raw[0x1E]); d.comment_len = MDFN_de16lsb(&cdr_raw[0x20]); d.disk_start = MDFN_de16lsb(&cdr_raw[0x22]); d.int_attr = MDFN_de16lsb(&cdr_raw[0x24]); d.ext_attr = MDFN_de32lsb(&cdr_raw[0x26]); d.lh_reloffs = MDFN_de32lsb(&cdr_raw[0x2A]); if(d.sig != 0x02014B50) throw MDFN_Error(0, _("Bad signature in ZIP Central Directory entry %u"), i); if(d.disk_start != 0) throw MDFN_Error(0, _("ZIP split archive support not implemented.")); if(d.lh_reloffs >= size) throw MDFN_Error(0, _("Bad local header relative offset in ZIP Central Directory entry %u"), i); d.name.resize(1 + d.name_len); d.name[0] = '/'; if(s->read(&d.name[1], d.name_len, false) != d.name_len) throw MDFN_Error(0, _("Unexpected EOF when reading ZIP Central Directory entry %u"), i); s->seek(d.extra_len + d.comment_len, SEEK_CUR); entries.push_back(d); } zs = std::move(s); } size_t ZIPReader::find_by_path(const std::string& path) { for(size_t i = 0; i < entries.size(); i++) { if(path == entries[i].name) return i; } return SIZE_MAX; } Stream* ZIPReader::open(const std::string& path, const uint32 mode, const int do_lock, const bool throw_on_noent, const CanaryType canary) { if(mode != MODE_READ) throw MDFN_Error(EINVAL, _("Error opening file \"%s\" in ZIP archive: %s"), path.c_str(), _("Specified mode is unsupported")); if(do_lock != 0) throw MDFN_Error(EINVAL, _("Error opening file \"%s\" in ZIP archive: %s"), path.c_str(), _("Locking requested but is unsupported")); size_t which = find_by_path(path); if(which == SIZE_MAX) { ErrnoHolder ene(ENOENT); throw MDFN_Error(ene.Errno(), _("Error opening file \"%s\" in ZIP archive: %s"), path.c_str(), ene.StrError()); } try { return open(which); } catch(const MDFN_Error& e) { throw MDFN_Error(e.GetErrno(), _("Error opening file \"%s\" in ZIP archive: %s"), path.c_str(), e.what()); } } bool ZIPReader::mkdir(const std::string& path, const bool throw_on_exist) { throw MDFN_Error(EINVAL, _("Error creating directory \"%s\" in ZIP archive: %s"), path.c_str(), _("ZIPReader::mkdir() not implemented")); } bool ZIPReader::unlink(const std::string& path, const bool throw_on_noent, const CanaryType canary) { throw MDFN_Error(EINVAL, _("Error unlinking \"%s\" in ZIP archive: %s"), path.c_str(), _("ZIPReader::unlink() not implemented")); } void ZIPReader::rename(const std::string& oldpath, const std::string& newpath, const CanaryType canary) { throw MDFN_Error(EINVAL, _("Error renaming \"%s\" to \"%s\" in ZIP archive: %s"), oldpath.c_str(), newpath.c_str(), _("ZIPReader::rename() not implemented")); } bool ZIPReader::finfo(const std::string& path, FileInfo* fi, const bool throw_on_noent) { size_t which = find_by_path(path); if(which == SIZE_MAX) { ErrnoHolder ene(ENOENT); if(throw_on_noent) throw MDFN_Error(ene.Errno(), _("Error getting file information for \"%s\" in ZIP archive: %s"), path.c_str(), ene.StrError()); return false; } if(fi) { FileInfo new_fi; new_fi.size = entries[which].uncomp_size; // TODO/FIXME: new_fi.mtime_us = 0; new_fi.is_regular = true; new_fi.is_directory = false; *fi = new_fi; } return true; } void ZIPReader::readdirentries(const std::string& path, std::function<bool(const std::string&)> callb) { // TODO/FIXME: throw MDFN_Error(EINVAL, _("ZIPReader::readdirentries() not implemented.")); } bool ZIPReader::is_absolute_path(const std::string& path) { if(!path.size()) return false; if(is_path_separator(path[0])) return true; return false; } void ZIPReader::check_firop_safe(const std::string& path) { } }
28.112936
273
0.685122
ianclawson
c2972e88d70fafb760fb515fa62b78a59a21c5b0
120
hxx
C++
src/Providers/UNIXProviders/PrintService/UNIX_PrintService_LINUX.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
1
2020-10-12T09:00:09.000Z
2020-10-12T09:00:09.000Z
src/Providers/UNIXProviders/PrintService/UNIX_PrintService_LINUX.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
src/Providers/UNIXProviders/PrintService/UNIX_PrintService_LINUX.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
#ifdef PEGASUS_OS_LINUX #ifndef __UNIX_PRINTSERVICE_PRIVATE_H #define __UNIX_PRINTSERVICE_PRIVATE_H #endif #endif
10
37
0.841667
brunolauze
c29b16bf2edeb31fae348f55eaea063c28f09122
4,317
cpp
C++
src/details.cpp
k0zmo/clw
f0be6d1b674118a4b99bc879894eb9481c868887
[ "MIT" ]
1
2016-08-21T00:01:38.000Z
2016-08-21T00:01:38.000Z
src/details.cpp
k0zmo/clw
f0be6d1b674118a4b99bc879894eb9481c868887
[ "MIT" ]
null
null
null
src/details.cpp
k0zmo/clw
f0be6d1b674118a4b99bc879894eb9481c868887
[ "MIT" ]
null
null
null
/* Copyright (c) 2012, 2013 Kajetan Swierk <k0zmo@outlook.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "clw/Prerequisites.h" #include <fstream> #include <iostream> #include <cstring> namespace clw { int compiledOpenCLVersion() { #if defined(HAVE_OPENCL_1_2) return 120; #elif defined(HAVE_OPENCL_1_1) return 110; #else return 100; #endif } namespace detail { vector<string> tokenize(const string& str, char delim, char group) { vector<string> tokens; if(str.empty()) return tokens; int curr = 0; int start = 0; // upewnij sie czy string nie rozpoczyna sie od delimitersow start = curr = static_cast<int>(str.find_first_not_of(delim)); while(str[curr]) { if(str[curr] == group) { curr = static_cast<int>(str.find_first_of(group, curr+1)); if((size_t)curr == string::npos) return vector<string>(); string token = str.substr(start+1, curr-start-1); tokens.push_back(token); start = curr + 1; } else if(str[curr] == delim) { if(str[curr-1] != delim && str[curr-1] != group) { string token = str.substr(start, curr-start); tokens.push_back(token); } start = curr + 1; } ++curr; } if(tokens.size() == 0) { tokens.push_back(str); return tokens; } // dla ostatniego token'a if(str[curr-1] != delim && str[curr-1] != group) { string token = str.substr(start, curr - 1); tokens.push_back(token); } return tokens; } void trim(string* str, bool left, bool right) { if(left) { size_t pos = str->find_first_not_of(" \t\r"); if(pos != 0 && pos != string::npos) { *str = str->substr(pos); } } if(right) { size_t pos = str->find_last_not_of(" \t\r"); if(pos < str->length()-1) { *str = str->substr(0, pos+1); } } } bool readAsString(const string& filename, string* contents) { std::ifstream strm; strm.open(filename.c_str(), std::ios::binary | std::ios_base::in); if(!strm.is_open()) { std::cerr << "Unable to open file " << filename << std::endl; return false; } strm.seekg(0, std::ios::end); contents->reserve(static_cast<size_t>(strm.tellg())); strm.seekg(0); contents->assign(std::istreambuf_iterator<char>(strm), std::istreambuf_iterator<char>()); return true; } } }
31.977778
81
0.514246
k0zmo
c2a26d79cf0d1470a475fc70cb9b5b1b8af20132
3,285
cpp
C++
Engine_Rendering/source/MeshRenderer.cpp
subr3v/s-engine
d77b9ccd0fff3982a303f14ce809691a570f61a3
[ "MIT" ]
2
2016-04-01T21:10:33.000Z
2018-02-26T19:36:56.000Z
Engine_Rendering/source/MeshRenderer.cpp
subr3v/s-engine
d77b9ccd0fff3982a303f14ce809691a570f61a3
[ "MIT" ]
1
2017-04-05T01:33:08.000Z
2017-04-05T01:33:08.000Z
Engine_Rendering/source/MeshRenderer.cpp
subr3v/s-engine
d77b9ccd0fff3982a303f14ce809691a570f61a3
[ "MIT" ]
null
null
null
#include "MeshRenderer.h" #include "Mesh.h" #include "Material.h" #include "Texture.h" #include "ConstantBufferTypes.h" void FMeshRenderer::Render(const FMesh* Mesh, const FDrawCall& DrawCallParameters, bool bUseTessellation) { assert(Mesh); FProfiler::Get().ProfileCounter("Rendering", "Mesh Draw Call", true, 1); ID3D11DeviceContext* DeviceContext = DrawCallParameters.DeviceContext; DeviceContext->IASetPrimitiveTopology(bUseTessellation ? D3D11_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST : D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); Mesh->BindBuffers(DeviceContext); int PreviousMaterialIndex = -1; FMaterial* CurrentMaterial = nullptr; if (DrawCallParameters.OverrideMaterial == false && DrawCallParameters.StandardMaterial == nullptr) { for (FMeshPart Part : Mesh->GetParts()) { if (PreviousMaterialIndex != Part.MaterialIndex) { PreviousMaterialIndex = Part.MaterialIndex; const FMeshMaterialParameters& ParametersData = Mesh->GetParameters(Part.MaterialIndex); CurrentMaterial = ParametersData.Material; FMaterialParameters* Parameters = CurrentMaterial->GetParameters(); ParametersData.Apply(DeviceContext, Parameters); Parameters->UpdateUniform(DeviceContext, FInstanceBuffer::kBufferName, (void*)DrawCallParameters.InstanceData, sizeof(FInstanceBuffer)); FProfiler::Get().ProfileCounter("Rendering", "Mesh Material State Change", true, 1); CurrentMaterial->Apply(DeviceContext); } DrawCallParameters.DrawIndexed(Part.IndexCount, Part.IndexStart, Part.BaseVertex); } } else if (DrawCallParameters.OverrideMaterial) { for (FMeshPart Part : Mesh->GetParts()) { if (PreviousMaterialIndex != Part.MaterialIndex) { PreviousMaterialIndex = Part.MaterialIndex; const FMeshMaterialParameters& ParametersData = Mesh->GetParameters(Part.MaterialIndex); CurrentMaterial = DrawCallParameters.OverrideMaterial(ParametersData.Material); FMaterialParameters* Parameters = CurrentMaterial->GetParameters(); ParametersData.Apply(DeviceContext, Parameters); Parameters->UpdateUniform(DeviceContext, FInstanceBuffer::kBufferName, (void*)DrawCallParameters.InstanceData, sizeof(FInstanceBuffer)); FProfiler::Get().ProfileCounter("Rendering", "Mesh Material State Change", true, 1); CurrentMaterial->Apply(DeviceContext); } DrawCallParameters.DrawIndexed(Part.IndexCount, Part.IndexStart, Part.BaseVertex); } } else if (DrawCallParameters.StandardMaterial) { for (FMeshPart Part : Mesh->GetParts()) { if (PreviousMaterialIndex != Part.MaterialIndex) { PreviousMaterialIndex = Part.MaterialIndex; const FMeshMaterialParameters& ParametersData = Mesh->GetParameters(Part.MaterialIndex); CurrentMaterial = DrawCallParameters.StandardMaterial; FMaterialParameters* Parameters = CurrentMaterial->GetParameters(); ParametersData.Apply(DeviceContext, Parameters); Parameters->UpdateUniform(DeviceContext, FInstanceBuffer::kBufferName, (void*)DrawCallParameters.InstanceData, sizeof(FInstanceBuffer)); FProfiler::Get().ProfileCounter("Rendering", "Mesh Material State Change", true, 1); CurrentMaterial->Apply(DeviceContext); } DrawCallParameters.DrawIndexed(Part.IndexCount, Part.IndexStart, Part.BaseVertex); } } }
35.706522
150
0.773212
subr3v
c2a2a5c7aff964f2f59b9f0575c7031ff14fc8f2
2,168
cpp
C++
src/particle_emitter.cpp
devdor/GLDevdor04
1c3c83b7a3d629e59a370519ceff10b13889ea48
[ "MIT" ]
null
null
null
src/particle_emitter.cpp
devdor/GLDevdor04
1c3c83b7a3d629e59a370519ceff10b13889ea48
[ "MIT" ]
null
null
null
src/particle_emitter.cpp
devdor/GLDevdor04
1c3c83b7a3d629e59a370519ceff10b13889ea48
[ "MIT" ]
null
null
null
#include "../includes/particle_emitter.hpp" #include <random> CParticleEmitter::CParticleEmitter() : m_maxParticles(100) { } void CParticleEmitter::Init(int maxParticles) { this->m_maxParticles = maxParticles; this->CreateParticles(); } // Initalizes a single particle according to its type void CParticleEmitter::CreateParticle(CParticle *p) { p->lifespan = (((rand() % 125 + 1) / 10.0f) + 5); p->type = 2; p->age = 0.0f; p->scale = 0.25f; p->direction = 0; p->position = glm::vec3(0.0f, 0.0f, 0.0f); p->movement.x = (((((((2) * rand() % 11) + 1)) * rand() % 11) + 1) * 0.035) - (((((((2) * rand() % 11) + 1)) * rand() % 11) + 1) * 0.035); p->movement.y = ((((((5) * rand() % 11) + 3)) * rand() % 11) + 7) * 0.015; p->movement.z = (((((((2) * rand() % 11) + 1)) * rand() % 11) + 1) * 0.015) - (((((((2) * rand() % 11) + 1)) * rand() % 11) + 1) * 0.015); p->movement.x = p->movement.x / 2; p->movement.y = p->movement.y / 2; p->movement.z = p->movement.z / 2; // rotation p->rotation.x = (double)rand() / (RAND_MAX + 1.0); p->rotation.y = (double)rand() / (RAND_MAX + 1.0); p->rotation.z = (double)rand() / (RAND_MAX + 1.0); p->pull.x = 0.0f; p->pull.y = 0.0f; p->pull.z = 0.0f; } void CParticleEmitter::CreateParticles(void) { for (int i=0; i < this->m_maxParticles; i++) { CParticle* p = new CParticle(); this->CreateParticle(p); this->m_Particles.push_back(p); } } void CParticleEmitter::UpdateParticles() { int i = 0; for (std::vector<CParticle*>::iterator it = this->m_Particles.begin(); it != this->m_Particles.end(); ++it) { CParticle* p = (*it); p->age = p->age + 0.015; p->direction = p->direction + ((((((int)(0.5) * rand() % 11) + 1)) * rand() % 11) + 1); p->position.x = p->position.x + p->movement.x / 2 + p->pull.x / 2; p->position.y = p->position.y + p->movement.y / 2 + p->pull.y / 2; p->position.z = p->position.z + p->movement.z / 2 + p->pull.z / 2; if (p->age > p->lifespan || p->position.y > 19 || p->position.y < -15 || p->position.x > 18 || p->position.x < -18) this->CreateParticle(p); } }
28.906667
140
0.539668
devdor
c2a49a527ecabb3bd0cc533f17a3527d3ff9ff48
13,888
cpp
C++
src/RawImport/FAA_Obs.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
71
2015-12-15T19:32:27.000Z
2022-02-25T04:46:01.000Z
src/RawImport/FAA_Obs.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
19
2016-07-09T19:08:15.000Z
2021-07-29T10:30:20.000Z
src/RawImport/FAA_Obs.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
42
2015-12-14T19:13:02.000Z
2022-03-01T15:15:03.000Z
/* * Copyright (c) 2004, Laminar Research. * * 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 "FAA_Obs.h" #include "MemFileUtils.h" #include "ParamDefs.h" #include "SimpleIO.h" #include "DEMDefs.h" #include "MapDefs.h" #include "MapAlgs.h" #include "GISTool_Globals.h" #include <CGAL/Arr_walk_along_line_point_location.h> FAAObsTable gFAAObs; const char * gObsNames [] = { "AM_RADIO_TOWER", "POLE", "TOWERS", "TOWER", "CRANE", "CATENARY", "BLDG", "CTRL TWR", "T-L TWR", "ELEVATOR", "WINDMILL", "RIG", "STACK", "REFINERY", "TANK", "BLDG-TWR", "TRAMWAY", "STACKS", "SPIRE", "CRANE T", "PLANT", "DOME", "SIGN", "BRIDGE", "ARCH", "COOL TWR", "MONUMENT", "BALLOON", "DAM", 0 }; static int kFeatureTypes [] = { feat_RadioTower, feat_Pole, feat_RadioTower, feat_RadioTower, feat_Crane, NO_VALUE, // "CATENARY", feat_Building, NO_VALUE, // "CTRL TWR", NO_VALUE, // "T-L TWR", feat_Elevator, feat_Windmill, NO_VALUE, // "RIG", feat_Smokestack, feat_Refinery, feat_Tank, feat_Building, feat_Tramway, feat_Smokestacks, feat_Spire, feat_Crane, feat_Plant, feat_Dome, feat_Sign, NO_VALUE, // "BRIDGE", feat_Arch, feat_CoolingTower, feat_Monument, NO_VALUE, // "BALLOON", feat_Dam, 0 }; static int kConvertLegacyObjTypes[] = { NO_VALUE, NO_VALUE, // feat_Skyscraper, feat_Building, // BEN SAYS: importing as sky-scraper means no obj match. :-( feat_RadioTower, NO_VALUE, feat_CoolingTower, feat_Smokestack, NO_VALUE }; static int kRobinToFeatures[] = { NO_VALUE, NO_VALUE, feat_BeaconNDB, feat_BeaconVOR, feat_BeaconILS, feat_BeaconLDA, feat_BeaconGS, feat_MarkerBeacon, feat_MarkerBeacon, feat_MarkerBeacon }; static int GetObjType(const char * str) { int n = 0; while (gObsNames[n]) { if (!strcmp(gObsNames[n],str)) return n; ++n; } return 0; } bool LoadFAARadarFile(const char * inFile, bool isApproach) { MFMemFile * f = NULL; MFTextScanner * s = NULL; bool ok = false; f = MemFile_Open(inFile); if (f == NULL) goto bail; s = TextScanner_Open(f); if (s == NULL) goto bail; while (!TextScanner_IsDone(s)) { const char * c = TextScanner_GetBegin(s); if (*c == '_') { TextScanner_Next(s); break; } TextScanner_Next(s); } while (!TextScanner_IsDone(s)) { const char * c = TextScanner_GetBegin(s); if (*c == '_') { TextScanner_Next(s); break; } TextScanner_Next(s); } while (!TextScanner_IsDone(s)) { FAAObs_t obs; const char * lp = TextScanner_GetBegin(s); int o = isApproach ? 46 : 59; if (lp[59] != ' ') { double lat_deg_tens = lp[o ] - '0'; double lat_deg_ones = lp[o+1] - '0'; double lat_min_tens = lp[o+3] - '0'; double lat_min_ones = lp[o+4] - '0'; double lat_sec_tens = lp[o+6] - '0'; double lat_sec_ones = lp[o+7] - '0'; double lat_hun_tens = lp[o+9] - '0'; double neg = (lp[o+10] != 'S') ? 1.0 : -1.0; obs.lat = neg * (lat_deg_tens * 10.0 + lat_deg_ones * 1.0 + lat_min_tens * 10.0 / 60.0 + lat_min_ones * 1.0 / 60.0 + lat_sec_tens * 10.0 / 3600.0 + lat_sec_ones * 1.0 / 3600.0 + lat_hun_tens * 10.0 / 360000.0); o = isApproach ? 59 : 71; double lon_deg_huns = lp[o ] - '0'; double lon_deg_tens = lp[o+1] - '0'; double lon_deg_ones = lp[o+2] - '0'; double lon_min_tens = lp[o+4] - '0'; double lon_min_ones = lp[o+5] - '0'; double lon_sec_tens = lp[o+7] - '0'; double lon_sec_ones = lp[o+8] - '0'; double lon_hun_tens = lp[o+10] - '0'; neg = (lp[o+11] == 'E') ? 1.0 : -1.0; obs.lon = neg * (lon_deg_huns * 100.0 + lon_deg_tens * 10.0 + lon_deg_ones * 1.0 + lon_min_tens * 10.0 / 60.0 + lon_min_ones * 1.0 / 60.0 + lon_sec_tens * 10.0 / 3600.0 + lon_sec_ones * 1.0 / 3600.0 + lon_hun_tens * 10.0 / 360000.0); obs.agl = TextScanner_ExtractLong(s, 73, 77) * 0.3048; obs.msl = TextScanner_ExtractLong(s, 78, 83) * 0.3048; if (isApproach) { obs.agl = TextScanner_ExtractLong(s,20,23); obs.msl = obs.agl + TextScanner_ExtractLong(s,71,76); obs.kind = feat_RadarASR; } else { obs.agl = NO_VALUE; obs.msl = TextScanner_ExtractLong(s,85,90); obs.kind = feat_RadarARSR; } gFAAObs.insert(FAAObsTable::value_type(HashLonLat(obs.lon, obs.lat), obs)); #if 0 printf(" %lf,%lf %f (%f) %d (%s) '%s' (%s)\n", obs.lon, obs.lat, obs.msl, obs.agl, obs.kind, FetchTokenString(obs.kind), obs.kind_str.c_str(), obs.freq.c_str()); #endif } TextScanner_Next(s); } ok = true; bail: if (f) MemFile_Close(f); if (s) TextScanner_Close(s); return ok; } bool LoadFAAObsFile(const char * inFile) { MFMemFile * f = NULL; MFTextScanner * s = NULL; bool ok = false; f = MemFile_Open(inFile); if (f == NULL) goto bail; s = TextScanner_Open(f); if (s == NULL) goto bail; while (!TextScanner_IsDone(s)) { const char * c = TextScanner_GetBegin(s); if (*c == '-') { TextScanner_Next(s); break; } TextScanner_Next(s); } while (!TextScanner_IsDone(s)) { FAAObs_t obs; TextScanner_ExtractString(s,58, 66, obs.kind_str, true); TextScanner_ExtractString(s,68, 72, obs.freq, true); if (!obs.freq.empty()) obs.kind = 0; else obs.kind = GetObjType(obs.kind_str.c_str()); obs.kind = kFeatureTypes[obs.kind]; const char * lp = TextScanner_GetBegin(s); double lat_deg_tens = lp[29] - '0'; double lat_deg_ones = lp[30] - '0'; double lat_min_tens = lp[32] - '0'; double lat_min_ones = lp[33] - '0'; double lat_sec_tens = lp[35] - '0'; double lat_sec_ones = lp[36] - '0'; double lat_hun_tens = lp[38] - '0'; double lat_hun_ones = lp[39] - '0'; double neg = (lp[40] != 'S') ? 1.0 : -1.0; obs.lat = neg * (lat_deg_tens * 10.0 + lat_deg_ones * 1.0 + lat_min_tens * 10.0 / 60.0 + lat_min_ones * 1.0 / 60.0 + lat_sec_tens * 10.0 / 3600.0 + lat_sec_ones * 1.0 / 3600.0 + lat_hun_tens * 10.0 / 360000.0 + lat_hun_ones * 1.0 / 360000.0); double lon_deg_huns = lp[43] - '0'; double lon_deg_tens = lp[44] - '0'; double lon_deg_ones = lp[45] - '0'; double lon_min_tens = lp[47] - '0'; double lon_min_ones = lp[48] - '0'; double lon_sec_tens = lp[50] - '0'; double lon_sec_ones = lp[51] - '0'; double lon_hun_tens = lp[53] - '0'; double lon_hun_ones = lp[54] - '0'; neg = (lp[55] == 'E') ? 1.0 : -1.0; obs.lon = neg * (lon_deg_huns * 100.0 + lon_deg_tens * 10.0 + lon_deg_ones * 1.0 + lon_min_tens * 10.0 / 60.0 + lon_min_ones * 1.0 / 60.0 + lon_sec_tens * 10.0 / 3600.0 + lon_sec_ones * 1.0 / 3600.0 + lon_hun_tens * 10.0 / 360000.0 + lon_hun_ones * 1.0 / 360000.0); obs.agl = TextScanner_ExtractLong(s, 73, 77) * 0.3048; obs.msl = TextScanner_ExtractLong(s, 78, 83) * 0.3048; gFAAObs.insert(FAAObsTable::value_type(HashLonLat(obs.lon, obs.lat), obs)); #if 0 //DEV printf(" %lf,%lf %f (%f) %d (%s) '%s' (%s)\n", obs.lon, obs.lat, obs.msl, obs.agl, obs.kind, FetchTokenString(obs.kind), obs.kind_str.c_str(), obs.freq.c_str()); #endif TextScanner_Next(s); } ok = true; bail: if (f) MemFile_Close(f); if (s) TextScanner_Close(s); return ok; } bool WriteDegFile(const char * inFile, int lon, int lat) { pair<FAAObsTable::iterator,FAAObsTable::iterator> range = gFAAObs.equal_range(HashLonLat(lon,lat)); if (range.first == range.second) return true; FILE * fi = fopen(inFile, "w"); if (!fi) return false; fprintf(fi, "# lon lat msl agl kind\n"); for (FAAObsTable::iterator i = range.first; i != range.second; ++i) { if (i->second.kind != NO_VALUE) fprintf(fi, "%lf %lf %f %f %s\n", i->second.lon, i->second.lat, i->second.msl, i->second.agl, FetchTokenString(i->second.kind)); } fclose(fi); return 1; } bool ReadDegFile(const char * inFile) { MFMemFile * f = NULL; MFTextScanner * s = NULL; bool ok = false; f = MemFile_Open(inFile); if (f == NULL) goto bail; s = TextScanner_Open(f); if (s == NULL) goto bail; while (!TextScanner_IsDone(s)) { const char * l = TextScanner_GetBegin(s); if (*l != '#') { FAAObs_t obs; char buf[256]; if (sscanf(l, "%lf %lf %f %f %s", &obs.lon, &obs.lat, &obs.msl, &obs.agl, buf) == 5) { // printf("Got: %lf %lf %f %f %s\n", // obs.lon, obs.lat, obs.msl, obs.agl, buf); obs.kind = LookupToken(buf); gFAAObs.insert(FAAObsTable::value_type(HashLonLat(obs.lon, obs.lat), obs)); } } TextScanner_Next(s); } ok = true; bail: if (s) TextScanner_Close(s); if (f) MemFile_Close(f); return ok; } bool ReadAPTNavAsObs(const char * inFile) { MFMemFile * f = NULL; MFTextScanner * s = NULL; bool ok = false; FAAObs_t obs; int rec_type; double lat, lon; int beacon_type; f = MemFile_Open(inFile); if (f == NULL) goto bail; s = TextScanner_Open(f); if (s == NULL) goto bail; while (!TextScanner_IsDone(s)) { if (TextScanner_FormatScan(s, "i", &rec_type) == 1) { switch(rec_type) { case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: if (TextScanner_FormatScan(s, "idd", &rec_type, &lat, &lon) == 3) { obs.kind = kRobinToFeatures[rec_type]; obs.lat = lat; obs.lon = lon; obs.agl = obs.msl = DEM_NO_DATA; gFAAObs.insert(FAAObsTable::value_type(HashLonLat(obs.lon, obs.lat), obs)); } break; case 19: if (TextScanner_FormatScan(s, "idd", &rec_type, &lat, &lon) == 3) { obs.kind = feat_Windsock; obs.lon = lon; obs.lat = lat; obs.agl = DEM_NO_DATA; obs.msl = DEM_NO_DATA; gFAAObs.insert(FAAObsTable::value_type(HashLonLat(obs.lon, obs.lat), obs)); } break; case 18: if (TextScanner_FormatScan(s, "iddi", &rec_type, &lat, &lon, &beacon_type) == 4) if (beacon_type == 1 || beacon_type == 4) // Land airport or military field { obs.kind = feat_RotatingBeacon; obs.lon = lon; obs.lat = lat; obs.agl = DEM_NO_DATA; obs.msl = DEM_NO_DATA; gFAAObs.insert(FAAObsTable::value_type(HashLonLat(obs.lon, obs.lat), obs)); } break; } } TextScanner_Next(s); } ok = true; bail: if (s) TextScanner_Close(s); if (f) MemFile_Close(f); return ok; } bool LoadLegacyObjectArchive(const char * inFile) { MFMemFile * f = MemFile_Open(inFile); MemFileReader reader(MemFile_GetBegin(f), MemFile_GetEnd(f), platform_BigEndian); int count; reader.ReadInt(count); while (count--) { double lat, lon, ele; int kind; reader.ReadInt(kind); reader.ReadDouble(lat); reader.ReadDouble(lon); reader.ReadDouble(ele); if (kind == 8) { char c; do { reader.ReadBulk(&c, 1,false); } while (c != 0); } else { FAAObs_t obs; obs.agl = ele * FT_TO_MTR; obs.msl = DEM_NO_DATA; obs.lat = lat; obs.lon = lon; obs.kind = kConvertLegacyObjTypes[kind]; if (obs.kind != NO_VALUE) gFAAObs.insert(FAAObsTable::value_type(HashLonLat(obs.lon, obs.lat), obs)); } } MemFile_Close(f); return true; } void ApplyObjects(Pmwx& ioMap) { if (gFAAObs.empty()) return; Point_2 sw, ne; CalcBoundingBox(ioMap, sw, ne); // ioMap.Index(); int placed = 0; // CGAL::Arr_landmarks_point_location<Arrangement_2> locator(gMap); CGAL::Arr_walk_along_line_point_location<Arrangement_2> locator(gMap); for (FAAObsTable::iterator i = gFAAObs.begin(); i != gFAAObs.end(); ++i) { if (i->second.kind != NO_VALUE) { Point_2 loc = Point_2(i->second.lon, i->second.lat); DebugAssert(CGAL::is_valid(gMap)); CGAL::Object obj = locator.locate(loc); Face_const_handle ff; if(CGAL::assign(ff,obj)) { Face_handle f = ioMap.non_const_handle(ff); GISPointFeature_t feat; feat.mFeatType = i->second.kind; feat.mLocation = loc; if (i->second.agl != DEM_NO_DATA) feat.mParams[pf_Height] = i->second.agl; feat.mInstantiated = false; f->data().mPointFeatures.push_back(feat); ++placed; #if 0 printf("Placed %s at %lf, %lf\n", FetchTokenString(i->second.kind), i->second.lon, i->second.lat); #endif // if (v.size() > 1) // fprintf(stderr,"WARNING (%d,%d): Point feature %lf, %lf matches multiple areas.\n",gMapWest, gMapSouth, CGAL::to_double(loc.x()), CGAL::to_double(loc.y())); } } } printf("Placed %d objects.\n", placed); } int GetObjMinMaxHeights(map<int, float>& mins, map<int, float>& maxs) { for (FAAObsTable::iterator obs = gFAAObs.begin(); obs != gFAAObs.end(); ++obs) if (obs->second.agl != DEM_NO_DATA) { if (mins.count(obs->second.kind) == 0) mins[obs->second.kind] = 999999; if (maxs.count(obs->second.kind) == 0) maxs[obs->second.kind] = 0; mins[obs->second.kind] = min(mins[obs->second.kind], obs->second.agl); maxs[obs->second.kind] = max(maxs[obs->second.kind], obs->second.agl); } return gFAAObs.size(); }
24.711744
163
0.6304
rromanchuk
c2a64753c35100b43c310732f3fd3ce81589c32c
594
cpp
C++
OOP/STL-Homework/Appointment.cpp
Rossoner40/NBU-Classwork-and-Homework
823e5eab2da616ae6d965da9c0a22fa0212d7887
[ "MIT" ]
null
null
null
OOP/STL-Homework/Appointment.cpp
Rossoner40/NBU-Classwork-and-Homework
823e5eab2da616ae6d965da9c0a22fa0212d7887
[ "MIT" ]
null
null
null
OOP/STL-Homework/Appointment.cpp
Rossoner40/NBU-Classwork-and-Homework
823e5eab2da616ae6d965da9c0a22fa0212d7887
[ "MIT" ]
null
null
null
#include "Appointment.h" Appointment::Appointment(DateTime date, string description, string address, string personToMeet) : date(date), description(description), address(address), personToMeet(personToMeet){ } bool Appointment::operator<(Appointment &other) { return this->date < other.date; } ostream& Appointment::inserter(ostream& os) { os << this->date << endl; os << this->description << endl; os << this->address << endl; os << this->personToMeet; return os; } ostream& operator<<(ostream& os, Appointment &obj) { return obj.inserter(os); }
27
89
0.675084
Rossoner40
c2a7bfdd9bb25f6c11b12e6d0f07dde858984203
4,347
cpp
C++
lunarlady/StaticsState.cpp
madeso/infection-survivors
654fc5405dcecccaa7e54f1fdbfec379e0c185da
[ "Zlib" ]
null
null
null
lunarlady/StaticsState.cpp
madeso/infection-survivors
654fc5405dcecccaa7e54f1fdbfec379e0c185da
[ "Zlib" ]
null
null
null
lunarlady/StaticsState.cpp
madeso/infection-survivors
654fc5405dcecccaa7e54f1fdbfec379e0c185da
[ "Zlib" ]
null
null
null
#include "lunarlady/Display.hpp" #include "lunarlady/Game.hpp" #include "lunarlady/State.hpp" #include "lunarlady/World2.hpp" #include "lunarlady/ComponentObject2.hpp" #include "lunarlady/Font.hpp" #include "lunarlady/Printer.hpp" namespace lunarlady { struct DisplayInfo { void set(const std::wstring& iValue, bool iOk) { value = iValue; ok = iOk; life = 0; } void set(const std::wstring& iValue, const math::vec2& iLocation, bool iOk) { value = iValue; ok = iOk; location = iLocation; life = 0; } void step(const real iTime) { life += iTime; } bool removeMe() { return life > 0.3; } std::wstring value; bool ok; real life; math::vec2 location; }; typedef boost::shared_ptr<DisplayInfo> DisplayInfoPtr; typedef std::map<std::string, DisplayInfoPtr> DisplayInfoMap; namespace { void Update(DisplayInfoMap& iMap, real iTime) { for(DisplayInfoMap::iterator i=iMap.begin(); i != iMap.end(); ) { DisplayInfoPtr displayInfo = i->second; displayInfo->step(iTime); if( displayInfo->removeMe() ) { i = iMap.erase(i); } else { ++i; } } } } class DisplayGraphics : public Object2 { public: DisplayGraphics(Font& iFont) : mFont(iFont){ } void doRender(real iTime) { mFont.load(); // since this can be on to of the loader this has to be done const real x = Registrator().getAspect() - 0.01; real y = 0.01; const real step = Printer::GetHeight(mFont) + 0.001; for(DisplayInfoMap::iterator i=mDisplay.begin(); i != mDisplay.end(); ++i) { DisplayInfoPtr displayInfo = i->second; const std::string jobName = (displayInfo->ok) ? "display.ok" : "display.bad"; const std::wstring name(i->first.begin(), i->first.end()); Printer(mFont, jobName, math::vec2(x,y), JUSTIFY_RIGHT, 0).arg("name", name).arg("text", displayInfo->value); y+=step; } for(DisplayInfoMap::iterator i=mDisplayLocation.begin(); i != mDisplayLocation.end(); ++i) { DisplayInfoPtr displayInfo = i->second; const std::string jobName = (displayInfo->ok) ? "display.ok" : "display.bad"; const std::wstring name(i->first.begin(), i->first.end()); Printer(mFont, jobName, displayInfo->location, JUSTIFY_LEFT, 0).arg("name", name).arg("text", displayInfo->value); } } void doUpdate(real iTime) { Update(mDisplay, iTime); Update(mDisplayLocation, iTime); } void set(const std::string& iName, const std::wstring& iValue, bool iOk) { DisplayInfoMap::iterator res = mDisplay.find(iName); DisplayInfoPtr display; if( res == mDisplay.end() ) { display.reset( new DisplayInfo() ); mDisplay.insert( DisplayInfoMap::value_type(iName, display) ); } else { display = res->second; } display->set(iValue, iOk); } void set(const std::string& iName, const std::wstring& iValue, const math::vec2 iLocation, bool iOk) { DisplayInfoMap::iterator res = mDisplayLocation.find(iName); DisplayInfoPtr display; if( res == mDisplayLocation.end() ) { display.reset( new DisplayInfo() ); mDisplayLocation.insert( DisplayInfoMap::value_type(iName, display) ); } else { display = res->second; } display->set(iValue, iLocation, iOk); } private: Font& mFont; DisplayInfoMap mDisplay; DisplayInfoMap mDisplayLocation; }; namespace { DisplayGraphics* gGraphics=0; } void ImpDisplayString(const std::string& iName, const std::wstring& iValue, bool iOk) { gGraphics->set(iName, iValue, iOk); } void ImpDisplayStringAtLocation(const std::string& iName, const std::wstring& iValue, const math::vec2 iLocation, bool iOk) { gGraphics->set(iName, iValue, iLocation, iOk); } class DisplayState : public State { public: DisplayState() : State("display", 600, true, true, #ifdef NDEBUG false #else true #endif ), mWorld(), mFont(FontDescriptor(mWorld, "fonts/big.fnt")) { gGraphics = new DisplayGraphics(mFont); mWorld.add( gGraphics ); mFont.load(); } void doFrame(real iTime) { mWorld.update(iTime); } void doTick(real iTime) { } void doRender(real iTime) { mWorld.render(iTime); } void onMouseMovement(const math::vec2& iMovement) { sendMouseMovement(iMovement); } void onKey(const sgl::Key& iKey, bool iDown) { sendKey(iKey, iDown); } World2 mWorld; Font mFont; }; LL_STATE(DisplayState); }
27.512658
126
0.667357
madeso
c2a7c093c8cade16b178ea697fd3b4e1e4f58576
35,465
cpp
C++
Dependencies/Build/mac/share/faust/vst.cpp
SKyzZz/test
9b03adce666adb85e5ae2d8af5262e0acb4b91e1
[ "Zlib" ]
2
2020-10-25T09:03:03.000Z
2021-06-24T13:20:01.000Z
Dependencies/Build/mac/share/faust/vst.cpp
SKyzZz/test
9b03adce666adb85e5ae2d8af5262e0acb4b91e1
[ "Zlib" ]
null
null
null
Dependencies/Build/mac/share/faust/vst.cpp
SKyzZz/test
9b03adce666adb85e5ae2d8af5262e0acb4b91e1
[ "Zlib" ]
null
null
null
/************************************************************************ IMPORTANT NOTE : this file contains two clearly delimited sections : the ARCHITECTURE section (in two parts) and the USER section. Each section is governed by its own copyright and license. Please check individually each section for license and copyright information. *************************************************************************/ /*******************BEGIN ARCHITECTURE SECTION (part 1/2)****************/ /************************************************************************ ************************************************************************ FAUST VSTi Architecture File Copyright (C) 2013 by Yan Michalevsy All rights reserved. ----------------------------BSD License------------------------------ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Julius Smith nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ----------------------------VST SDK---------------------------------- In order to compile a VST (TM) plugin with this architecture file you will need the proprietary VST SDK from Steinberg. Please check the corresponding license. ************************************************************************ ************************************************************************/ /******************************************************************** * vsti-poly.cpp - Polyphonic VSTi-2.4 wrapper for the FAUST language. * * Usage: faust -a vst.cpp myfaustprog.dsp * * By Yan Michalevsky (http://www.stanford.edu/~yanm2/) * based on vsti-mono.cpp by * Julius Smith (http://ccrma.stanford.edu/~jos/), based on vst.cpp * by Remy Muller <remy.muller at ircam.fr> * (http://www.smartelectronix.com/~mdsp/). Essentially, vst.cpp was * first edited to look more like the "again" programming sample that * comes with the VST-2.4 SDK from Steinberg. Next, features from the * "vstxsynth" program sample were added to give simple MIDI synth * support analogous to that of faust2pd, except that only one voice * is supported. (If the Faust patch has any input signals, this * architecture file should reduce to vst2p4.cpp --- i.e., basic VST * plugin support.) As with faust2pd, to obtain MIDI control via * NoteOn/Off, Velocity, and KeyNumber, there must be a button named * "gate" and sliders (or numeric entries) named "gain" and "freq" in * the Faust patch specified in myfaustprog.dsp. * * NOTES: * Relies on automatically generated slider GUI for VST plugins. * - Horizontal and vertical sliders mapped to "vstSlider" * - Numeric Entries similarly converted to "vstSlider" * - No support for bar graphs or additional numeric and text displays * - Tested on the Muse Receptor Pro 1.0, System Version 1.6.20070717, * using Visual C++ 2008 Express Edition * (part of the Microsoft Visual Studio 2008, Beta 2) * - Reference: * http://ccrma.stanford.edu/realsimple/faust/Generating_VST_Plugin_Faust.html * * Initial work on the polyphonic VSTi architecture was done as part * of Music 420B class in Stanford University and in summarized in * http://stanford.edu/~yanm2/files/mus420b.pdf * * FAUST * Copyright (C) 2003-2007 GRAME, Centre National de Creation Musicale * http://www.grame.fr/ * ********************************************************************/ // Suggestion: Faust could replace all leading comments in this file // by the following shorter comment: /******************************************************************** * C++ source generated by the following command line: * * faust -a vsti-poly.cpp name.dsp -o name-vsti.cpp * ********************************************************************/ // (where the filenames could be really right, and the path to vsti-poly.cpp // could be included as well.) #include <stdlib.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <limits.h> #include <math.h> #include <errno.h> #include <time.h> #include <fcntl.h> #include <assert.h> #include <cstdio> #include <string> #include <cstring> #include <algorithm> #include <vector> #include <map> #include <list> // #define DEBUG #ifdef DEBUG #define TRACE(x) x #else #define TRACE(x) #endif using namespace std; // On Intel set FZ (Flush to Zero) and DAZ (Denormals Are Zero) // flags to avoid costly denormals #ifdef __SSE__ #include <xmmintrin.h> #ifdef __SSE2__ #define AVOIDDENORMALS _mm_setcsr(_mm_getcsr() | 0x8040) #else #define AVOIDDENORMALS _mm_setcsr(_mm_getcsr() | 0x8000) #endif #else #define AVOIDDENORMALS #endif struct Meta : std::map<const char*, const char*> { void declare(const char* key, const char* value) { (*this)[key] = value; } const char* get(const char* key, const char* defaultString) { if (this->find(key) != this->end()) { return (*this)[key]; } else { return defaultString; } } }; inline int lsr(int x, int n) { return int(((unsigned int)x) >> n); } inline int int2pow2(int x) { int r=0; while ((1<<r)<x) r++; return r; } /****************************************************************************** ******************************************************************************* * * VECTOR INTRINSICS * ******************************************************************************* *******************************************************************************/ <<includeIntrinsic>> /****************************************************************************** ******************************************************************************* * * USER INTERFACE * ******************************************************************************* *******************************************************************************/ /****************************************************************************** ******************************************************************************* * * FAUST DSP * ******************************************************************************* *****************************************************************************/ #include "faust/vst/vstui.h" #include "faust/dsp/dsp.h" /********************END ARCHITECTURE SECTION (part 1/2)****************/ /**************************BEGIN USER SECTION **************************/ <<includeclass>> #include "faust/vst/voice.h" /***************************END USER SECTION ***************************/ /*******************BEGIN ARCHITECTURE SECTION (part 2/2)***************/ /***************************************************************************** * * VST wrapper * ****************************************************************************/ #include "audioeffectx.h" /////////////////////////////////////////////////////////////////// // Constants /////////////////////////////////////////////////////////////////// #define MAX_NOUTS (2) //---------------------------------------------------------------------------- // Faust class prototype //---------------------------------------------------------------------------- #include "faust/vst/faust.h" /*--------------------------------------------------------------------------*/ //---------------------------------------------------------------------------- // Class Implementations //---------------------------------------------------------------------------- #define kNumPrograms (1) AudioEffect* createEffectInstance(audioMasterCallback audioMaster) { TRACE( fprintf(stderr, "Faust VSTi: Creating VST instance\n") ); // The dsp and its UI need to be allocated now because // AudioEffectX wants the no. parameters available as an instance argument: mydsp* dspi = new mydsp(); vstUI* dspUIi = new vstUI(); dspi->buildUserInterface(dspUIi); TRACE( fprintf(stderr,"=== Faust vsti: created\n") ); // look for this in the system log return new Faust(audioMaster, dspi, dspUIi); } //----------------------------------------------------------------------------- // Faust //----------------------------------------------------------------------------- Faust::Faust(audioMasterCallback audioMaster, dsp* dspi, vstUI* dspUIi) : AudioEffectX(audioMaster, kNumPrograms, dspUIi->GetNumParams()), m_dsp(dspi), m_dspUI(dspUIi), m_voices(MAX_POLYPHONY, (Voice*)NULL), m_playingVoices(), m_freeVoices(), m_prevVoice(-1), m_tempOutputs(NULL), m_tempOutputSize(INITIAL_TEMP_OUTPUT_SIZE), m_currentNotes(), m_currentVelocities(), m_currentDeltas() { #ifdef DEBUG fprintf(stderr,"=== Faust vsti: classInit:\n"); #endif mydsp::classInit((int)getSampleRate()); // Ask AudioEffect for sample-rate setProgram(0); setProgramName("Default"); if (audioMaster) { setNumInputs(m_dsp->getNumInputs()); setNumOutputs(m_dsp->getNumOutputs()); canProcessReplacing(); if (m_dsp->getNumInputs() == 0) { isSynth(); // at least let's hope so! if (m_dsp->getNumOutputs() < 1) { fprintf(stderr,"*** faust: vsti: No signal inputs or outputs, " "and Faust has no MIDI outputs!\n"); } } const char* ID = getMetadata("id", "FAUST"); if (ID[0] == 0) { setUniqueID(m_dspUI->makeID()); } else { setUniqueID((ID[0]<<24)+(ID[1]<<16)+(ID[2]<<8)+ID[3]); } } // Initialize all members related to polyphonic performance TRACE( fprintf(stderr, "Faust VSTi: Initializing voices and temporary output buffers\n") ); for (unsigned int i = 0; i < MAX_POLYPHONY; ++i) { m_voices[i] = new Voice((int)getSampleRate()); m_freeVoices.push_back(i); } TRACE( fprintf(stderr, "Faust VSTi: Allocating %d temporary output " "buffers\n", m_dsp->getNumOutputs()) ); m_tempOutputs = (FAUSTFLOAT**) malloc(sizeof(FAUSTFLOAT*) * m_dsp->getNumOutputs()); for (int i = 0; i < m_dsp->getNumOutputs(); ++i) { m_tempOutputs[i] = (FAUSTFLOAT*) malloc(sizeof(FAUSTFLOAT) * m_tempOutputSize); } initProcess(); if (m_dsp->getNumInputs() == 0) { suspend(); // Synths start out quiet } } // end of Faust constructor //---------------------------------------------------------------------------- Faust::~Faust() { TRACE( fprintf(stderr, "Calling Faust VST destructor\n") ); for (int i = 0; i < m_dsp->getNumOutputs(); ++i) { free(m_tempOutputs[i]); m_tempOutputs[i] = NULL; } free(m_tempOutputs); for (unsigned int i = 0; i < MAX_POLYPHONY; ++i) { if (NULL != m_voices[i]) { delete m_voices[i]; m_voices[i] = NULL; } } if (m_dspUI) { delete m_dspUI; } if (m_dsp) { delete m_dsp; } } // end of Faust destructor //----------------------------------------------------------------------------- void Faust::setProgram(VstInt32 program) // Override this method of AudioEffect in order to set // local instance variables corresponding to the current MIDI program. // Here there is only one program. { if (program < 0 || program >= kNumPrograms) { fprintf(stderr, "*** Faust vsti: setting program to %d is OUT OF RANGE\n", program); return; } #ifdef DEBUG fprintf(stderr,"=== Faust vsti: setting program to %d\n",program); #endif curProgram = program; // curProgram defined in audioeffect.h } // end of setProgram //---------------------------------------------------------------------------- void Faust::setProgramName(const char* name) { vst_strncpy(programName, name, kVstMaxProgNameLen); } //---------------------------------------------------------------------------- void Faust::getProgramName(char *name) { vst_strncpy(name, programName, kVstMaxProgNameLen); } //---------------------------------------------------------------------------- void Faust::getParameterLabel(VstInt32 index, char *label) { const char* unit = ""; if (index < numParams) { unit = m_dspUI->getControlMetadata(index, "unit", ""); } vst_strncpy(label, unit, kVstMaxParamStrLen); // parameter units in Name TRACE( fprintf(stderr, "Called getParameterLabel for parameter %d, returning %s\n", index, label) ); } // end of getParameterLabel //---------------------------------------------------------------------------- void Faust::getParameterDisplay(VstInt32 index, char *text) { if(index < numParams) { m_dspUI->GetDisplay(index,text); // get displayed float value as text } else { vst_strncpy(text, "IndexOutOfRange", kVstMaxParamStrLen); } } //---------------------------------------------------------------------------- void Faust::getParameterName(VstInt32 index, char *label) { if(index < numParams) { m_dspUI->GetName(index,label); // parameter name, including units } else { vst_strncpy(label, "IndexOutOfRange", kVstMaxParamStrLen); } } // end of getParamterName //-------------------- bool Faust::getParameterProperties(VstInt32 index, VstParameterProperties* properties) { if (index < 0 || index >= m_dspUI->GetNumParams()) { TRACE( fprintf(stderr, "Faust VSTi: Invalid parameter index %d\n", index) ); return false; } TRACE( fprintf(stderr, "Faust VSTi: getParameterProperties called with index %d\n", index) ); if (index == m_dspUI->gateIndex) { properties->flags |= kVstParameterIsSwitch; } getParameterName(index, properties->label); // TODO: set parameter range const vstSlider* slider = dynamic_cast<const vstSlider*>(m_dspUI); if (NULL != slider) { // has min-max range properties->minInteger = slider->getMinValue(); properties->maxInteger = slider->getMaxValue(); properties->stepInteger = slider->getStep(); } return true; } // end of getParameterProperties //---------------------------------------------------------------------------- void Faust::setParameter(VstInt32 index, float value) { if (index >= numParams || index < 0) { TRACE( fprintf(stderr, "Faust VSTi: Invalid parameter index %d\n", index) ); return; } m_dspUI->SetValue(index, value); for (unsigned int i = 0; i < MAX_POLYPHONY; ++i) { TRACE( fprintf(stderr, "Setting parameter %d for voice %d to value %f\n", index, i, value) ); m_voices[i]->SetValue(index, value); } } // end of setParameter //---------------------------------------------------------------------------- float Faust::getParameter(VstInt32 index) { return (index >= 0 && index < numParams) ? m_dspUI->GetValue(index) : 0.0f; } //----------------------------------------------------------------------------- bool Faust::getInputProperties(VstInt32 index, VstPinProperties* properties) { if(index < 0 || index >= m_dsp->getNumInputs()) { return false; } sprintf (properties->label, "Grame Faust DSP input: %d",index); sprintf (properties->shortLabel, "In %d",index); properties->flags = kVstPinIsActive; if (m_dsp->getNumInputs() == 2) { properties->flags |= kVstPinIsStereo; } return true; } //----------------------------------------------------------------------------- bool Faust::getOutputProperties(VstInt32 index, VstPinProperties* properties) { if(index < 0 || m_dsp->getNumOutputs() < 1) { return false; } sprintf (properties->label, "Grame Faust DSP output: %d",index); sprintf (properties->shortLabel, "Out %d",index); properties->flags = kVstPinIsActive; if (m_dsp->getNumOutputs() == 2) { properties->flags |= kVstPinIsStereo; } return true; } //---------------------------------------------------------------------------- bool Faust::getProgramNameIndexed(VstInt32 category, VstInt32 index, char* text) { if (index < kNumPrograms) { vst_strncpy (text, programName, kVstMaxProgNameLen); return true; } return false; } const char* Faust::getMetadata(const char* key, const char* defaultString) { Meta meta; mydsp tmp_dsp; tmp_dsp.metadata(&meta); return meta.get(key, defaultString); } // end of getMetadata //----------------------------------------------------------------------------- bool Faust::getEffectName(char* name) { const char* effectName = getMetadata("name", "Effect Name goes here"); vst_strncpy (name, effectName, kVstMaxEffectNameLen); return true; } //----------------------------------------------------------------------------- bool Faust::getVendorString(char* text) { const char* vendorString = getMetadata("author", "Vendor String goes here"); vst_strncpy (text, vendorString, kVstMaxVendorStrLen); return true; } //----------------------------------------------------------------------------- bool Faust::getProductString(char* text) { const char* productString = getMetadata("name", "Product String goes here"); vst_strncpy (text, productString, kVstMaxProductStrLen); return true; } //----------------------------------------------------------------------------- VstInt32 Faust::getVendorVersion() { const char* versionString = getMetadata("version", "0.0"); return (VstInt32)atof(versionString); } //----------------------------------------------------------------------------- VstInt32 Faust::canDo(const char* text) { if (!strcmp (text, "receiveVstEvents")) { return 1; } if (!strcmp (text, "receiveVstMidiEvent")) { return 1; } if (!strcmp (text, "midiProgramNames")) { return 1; } return -1; // explicitly can't do; 0 => don't know } // end of canDo //---------------------------------------------------------------------------- VstInt32 Faust::getNumMidiInputChannels() { return 1; // one MIDI-in channel } //---------------------------------------------------------------------------- VstInt32 Faust::getNumMidiOutputChannels() { return 0; // no MIDI-outs } //---------------------------------------------------------------------------- VstInt32 Faust::getMidiProgramName(VstInt32 channel, MidiProgramName* mpn) { VstInt32 prg = mpn->thisProgramIndex; if (prg < 0 || prg > 0) return 0; fillProgram (channel, prg, mpn); return 1; // we have only 1 "MIDI program" } //------------------------------------------------------------------------ VstInt32 Faust::getCurrentMidiProgram(VstInt32 channel, MidiProgramName* mpn) { // There is only one MIDI program here, so return it regardless of MIDI channel: if (channel < 0 || channel >= 16 || !mpn) return -1; VstInt32 prg = 0; mpn->thisProgramIndex = prg; fillProgram (channel, prg, mpn); return prg; } //------------------------------------------------------------------------ void Faust::fillProgram(VstInt32 channel, VstInt32 prg, MidiProgramName* mpn) // Fill mpn struct for given channel. Here there should be only one. { mpn->midiBankMsb = mpn->midiBankLsb = -1; mpn->reserved = 0; mpn->flags = 0; vst_strncpy (mpn->name, programName, kVstMaxProgNameLen); mpn->midiProgram = (char)prg; // prg should only be 0 mpn->parentCategoryIndex = -1; } //------------------------------------------------------------------------ VstInt32 Faust::getMidiProgramCategory(VstInt32 channel, MidiProgramCategory* cat) // VST host wants to fill cat struct for given channel. We have only one category. { cat->parentCategoryIndex = -1; // -1:no parent category cat->flags = 0; // reserved, none defined yet, zero. VstInt32 category = cat->thisCategoryIndex; vst_strncpy (cat->name, "Faust Patch", kVstMaxProgNameLen); return 1; // one category } //*********************************************************************** //---------------------------------------------------------------------------- void Faust::setSampleRate(float sampleRate) { AudioEffect::setSampleRate(sampleRate); m_dsp->init((int)getSampleRate()); // in case AudioEffect altered it for (unsigned int i = 0; i < MAX_POLYPHONY; ++i) { m_voices[i]->m_dsp.init((int)getSampleRate()); } } //---------------------------------------------------------------------------- void Faust::initProcess() { currentVelocity = currentNote = currentDelta = 0; m_dsp->init((int)getSampleRate()); for (unsigned int i = 0; i < MAX_POLYPHONY; ++i) { m_voices[i]->m_dsp.init((int)getSampleRate()); } } //---------------------------------------------------------------------------- void Faust::processReplacing(FAUSTFLOAT** inputs, FAUSTFLOAT** outputs, VstInt32 sampleFrames) { AVOIDDENORMALS; #ifdef DEBUG // fprintf(stderr,"=== Faust vsti: processReplacing . . .\n"); #endif if (m_dsp->getNumInputs() > 0) { // We're an effect . . . keep going: m_dsp->compute(sampleFrames, inputs, outputs); } else { // We're a synth . . . synthProcessReplacing(inputs, outputs, sampleFrames); } } // end of processReplacing inline float midiToFreq(int note) { return 440.0f*powf(2.0f,(((float)note)-69.0f)/12.0f); } void Faust::synthProcessReplacing(FAUSTFLOAT** inputs, FAUSTFLOAT** outputs, VstInt32 sampleFrames) { float* outptr[MAX_NOUTS] = {NULL,}; int i; int nouts = m_dsp->getNumOutputs(); if (nouts > MAX_NOUTS) { TRACE( fprintf(stderr, "VSTi: nouts > MAX_NOUTS. Number of outputs (%d) exceeds limit. " "Truncated to maximum.\n", nouts) ); nouts = MAX_NOUTS; } // we're synthesizing . . . if (m_currentNotes.size() > 0) { int previousDelta = 0; while (m_currentNotes.size() > 0) { // a new note currentDelta = m_currentDeltas.front(); // but waiting out a timestamp delay . . . if (currentDelta >= sampleFrames) { // start time is after this chunk for(std::list<VstInt32>::iterator it = m_currentDeltas.begin(); it != m_currentDeltas.end(); ++it) { *it -= sampleFrames; } compute(inputs, outputs, sampleFrames); return; } else { m_currentDeltas.pop_front(); currentNote = m_currentNotes.front(); m_currentNotes.pop_front(); currentVelocity = m_currentVelocities.front(); m_currentVelocities.pop_front(); if (currentVelocity > 0) { // Note on // Reserve a free voice for the played int currentVoice; if (m_freeVoices.size() > 0) { currentVoice = m_freeVoices.front(); m_freeVoices.pop_front(); struct voice_node *n = new voice_node; n->note = currentNote; n->voice = currentVoice; m_playingVoices.push_back(n); } else { voice_node *front = m_playingVoices.front(); currentVoice = front->voice; float freq = midiToFreq(front->note); m_voices[currentVoice]->setPrevFreq(freq); front->note = currentNote; m_playingVoices.pop_front(); m_playingVoices.push_back(front); } memset(outptr, 0, sizeof(outptr)); // Before the note starts assert(nouts <= MAX_NOUTS); for (i = 0; i < nouts; i++) { outptr[i] = outputs[i] + previousDelta; // leaving caller's pointers alone } compute(inputs, outptr, currentDelta - previousDelta); // Note start float freq = midiToFreq(currentNote); m_voices[currentVoice]->setFreq(freq); // Hz - requires Faust control-signal "freq" float gain = currentVelocity/127.0f; m_voices[currentVoice]->setGain(gain); // 0-1 - requires Faust control-signal "gain" m_voices[currentVoice]->setGate(1.0f); // 0 or 1 - requires Faust control-signal "gate" } else { // Note off // Find the voice to be turned off int currentVoice; bool voiceFound = false; std::list<voice_node*>::iterator voice_iter = m_playingVoices.begin(); for (; voice_iter != m_playingVoices.end(); voice_iter++) { if (currentNote == (*voice_iter)->note) { currentVoice = (*voice_iter)->voice; TRACE( fprintf(stderr, "=== Faust VSTi: Found matching voice for note %d: %d\n", currentNote, currentVoice) ); if (std::find(m_releasedVoices.begin(), m_releasedVoices.end(), currentVoice) == m_releasedVoices.end()) { m_releasedVoices.push_back(currentVoice); voiceFound = true; } } } memset(outptr, 0, sizeof(outptr)); // Before the note ends for (i = 0; i < nouts; i++) { outptr[i] = outputs[i] + previousDelta; // leaving caller's pointers alone } compute(inputs, outptr, currentDelta - previousDelta); // Note end if (voiceFound) { m_voices[currentVoice]->setGate(0); } } previousDelta = currentDelta; } } memset(outptr, 0, sizeof(outptr)); // Compute the left over time int count = sampleFrames - currentDelta; // Left over time in chunk for (i = 0; i < nouts; i++) { outptr[i] = outputs[i] + currentDelta; // leaving caller's pointers alone } compute(inputs, outptr, count); } else { compute(inputs, outputs, sampleFrames); } } // end of synthProcessReplacing void Faust::compute(FAUSTFLOAT** inputs, FAUSTFLOAT** outputs, VstInt32 sampleFrames) { const unsigned int output_buffer_size = sizeof(FAUSTFLOAT) * sampleFrames; // Clear the buffers for (int i = 0; i < m_dsp->getNumOutputs(); ++i) { for (int frame = 0; frame < sampleFrames; ++frame) { outputs[i][frame] = 0; } } if (sampleFrames > (VstInt32)m_tempOutputSize) { // if requested number of samples to synthesize exceeds current temporary buffer TRACE( fprintf(stderr, "Faust VSTi: Increasing temporary buffer to %d frames\n", sampleFrames) ); for (unsigned int i = 0; i < MAX_POLYPHONY; ++i) { m_tempOutputs[i] = (FAUSTFLOAT*) realloc(m_tempOutputs[i], output_buffer_size * m_dsp->getNumOutputs()); m_tempOutputSize = sampleFrames; } } std::list<voice_node*> removed; std::list<voice_node*>::iterator voice_iter = m_playingVoices.begin(); for(;voice_iter != m_playingVoices.end(); voice_iter++) { int voice = (*voice_iter)->voice; m_voices[voice]->m_dsp.compute(sampleFrames, inputs, m_tempOutputs); bool silent = true; // mix current voice into output for (int i = 0; i < m_dsp->getNumOutputs(); ++i) { for (int frame = 0; frame < sampleFrames; ++frame) { outputs[i][frame] += m_tempOutputs[i][frame]; if (fabs(m_tempOutputs[i][frame]) > 1e-6) { silent = false; } } } if (silent) { std::vector<VstInt32>::iterator it; it = std::find(m_releasedVoices.begin(), m_releasedVoices.end(), voice); if (it != m_releasedVoices.end()) { m_freeVoices.push_back(voice); m_releasedVoices.erase(it); removed.push_back(*voice_iter); } } } // end of signal computation and mixdown while (removed.size() > 0) { std::list<voice_node*>::iterator it; it = std::find(m_playingVoices.begin(), m_playingVoices.end(), removed.front()); float freq = midiToFreq((*it)->note); m_voices[(*it)->voice]->setPrevFreq(freq); free(*it); m_playingVoices.erase(it); removed.pop_front(); } // normalize sample by the max polyphony for (int i = 0; i < m_dsp->getNumOutputs(); ++i) { for (int frame = 0; frame < sampleFrames; ++frame) { outputs[i][frame] /= (FAUSTFLOAT)sqrt(MAX_POLYPHONY); } } } // end of compute //----------------------------------------------------------------------------- VstInt32 Faust::processEvents (VstEvents* ev) { if (ev->numEvents > 0) { TRACE( fprintf(stderr,"=== Faust vsti: processEvents processing %d " "events\n", ev->numEvents) ); } for (VstInt32 i = 0; i < ev->numEvents; i++) { TRACE( fprintf(stderr,"=== Faust vsti: event type = %d\n", (ev->events[i])->type) ); if ((ev->events[i])->type != kVstMidiType) { TRACE( fprintf(stderr,"=== Faust vsti: EVENT IGNORED!\n") ); continue; } VstMidiEvent* event = (VstMidiEvent*)ev->events[i]; char* midiData = event->midiData; VstInt32 chan = midiData[0] & 0xf; VstInt32 status = midiData[0] & 0xf0; #ifdef DEBUG fprintf(stderr,"\n=== Faust vsti: event->midiData[0] = 0x%x\n", event->midiData[0]); fprintf(stderr,"=== Faust vsti: midi channel = 0x%x\n", chan); fprintf(stderr,"=== Faust vsti: midi status = 0x%x\n", status); fprintf(stderr,"=== Faust vsti: event->midiData[1] = 0x%x\n", event->midiData[1]); fprintf(stderr,"=== Faust vsti: event->midiData[2] = 0x%x\n", event->midiData[2]); #endif VstInt32 note = midiData[1] & 0x7f; if (status == 0x90) { // note on VstInt32 velocity = midiData[2] & 0x7f; TRACE( fprintf(stderr, "=== Faust vsti: note = %d, velocity = %d, delay = %d\n", note,velocity,event->deltaFrames) ); if (velocity > 0) { noteOn(note, velocity, event->deltaFrames); } else { noteOff(note, event->deltaFrames); } } else if (status == 0x80) { // note off noteOff(note, event->deltaFrames); // } else if (status == 0xA0) { // poly aftertouch } else if (status == 0xB0) { // control change /* DO SOMETHING WITH THE CONTROLLER DATA */ fprintf(stderr,"=== Faust vsti: CONTROL CHANGE (status 0xB0)!\n"); if (midiData[1] == 0x7e || midiData[1] == 0x7b) { // all notes off fprintf(stderr,"=== Faust vsti: ALL NOTES OFF!\n"); //TODO: figure out how to signal all notes off // why is all-notes-off inside a "control change" event? allNotesOff(); } } else if (status == 0xE0) { // pitch change int val = midiData[1] | (midiData[2] << 7); float bend = (val - 0x2000) / 8192.0f; bendPitch(bend); } // } else if (status == 0xF0) { // SYSX ... // } else if (status == 0xC0) { // program change // } else if (status == 0xD0) { // mono aftertouch // For a list, see // http://www.alfred-j-faust.de/rft/midi%20status%20types.html TRACE( fprintf(stderr,"=== Faust vsti: Going to next event\n") ); event++; } return 1; } //---------------------------------------------------------------------------- void Faust::bendPitch(float bend) { TRACE( fprintf(stderr, "Bending pitch by %f\n", bend) ); for (unsigned int i = 0; i < MAX_POLYPHONY; ++i) { m_voices[i]->setPitchBend(bend); } } // end of Faust::bendPitch void Faust::noteOn (VstInt32 note, VstInt32 velocity, VstInt32 delta) { #ifdef DEBUG fprintf(stderr,"=== Faust vsti: noteOn: note = %d, vel = %d, del = %d\n",note,velocity,delta); #endif m_currentNotes.push_back(note); m_currentVelocities.push_back(velocity); m_currentDeltas.push_back(delta); } // end of noteOn //----------------------------------------------------------------------------- void Faust::noteOff(VstInt32 note, VstInt32 delta) { TRACE( fprintf(stderr,"=== Faust vsti: noteOff\n") ); m_currentNotes.push_back(note); m_currentVelocities.push_back(0); m_currentDeltas.push_back(delta); } // end of nToteOff void Faust::allNotesOff(void) { TRACE( fprintf(stderr, "All notes off\n") ); for (unsigned int i = 0; i < MAX_POLYPHONY; ++i) { m_voices[i]->setGate(0); } std::list<voice_node*>::iterator voice_iter = m_playingVoices.begin(); for (; voice_iter != m_playingVoices.end(); voice_iter++) { int voice = (*voice_iter)->voice; if (std::find(m_releasedVoices.begin(), m_releasedVoices.end(), voice) == m_releasedVoices.end()) { m_releasedVoices.push_back(voice); } } } // end of Faust::allNotesOff /********************END ARCHITECTURE SECTION (part 2/2)****************/
36.561856
138
0.51259
SKyzZz
c2a970714c54899a2c9b4f9887f64162610cb519
3,152
cpp
C++
src/downloadmanager.cpp
adderly/components
24e3d773dcfbf90d7dca50a03242af811e3508e9
[ "MIT" ]
17
2015-07-04T18:14:45.000Z
2018-12-22T01:11:17.000Z
src/downloadmanager.cpp
adderly/components
24e3d773dcfbf90d7dca50a03242af811e3508e9
[ "MIT" ]
null
null
null
src/downloadmanager.cpp
adderly/components
24e3d773dcfbf90d7dca50a03242af811e3508e9
[ "MIT" ]
7
2016-06-16T15:26:57.000Z
2021-01-13T13:14:56.000Z
#include "downloadmanager.h" #ifdef Q_OS_ANDROID #include <QAndroidJniEnvironment> #include <QAndroidJniObject> #endif DownloadManager::DownloadManager(QObject *parent) : QObject(parent) { } void DownloadManager::download(const QString &url, const QString &name) { #ifdef Q_OS_ANDROID QAndroidJniEnvironment env; env->PushLocalFrame(16); QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;"); jclass activityClass = env->GetObjectClass(activity.object<jobject>()); jclass contextClass = env->FindClass("android/content/Context"); jfieldID fIDDownloadService = env->GetStaticFieldID(contextClass, "DOWNLOAD_SERVICE", "Ljava/lang/String;"); jstring downloadServiceString = (jstring)env->GetStaticObjectField(contextClass, fIDDownloadService); jmethodID mIDGetApplicationContext = env->GetMethodID(activityClass, "getApplicationContext", "()Landroid/content/Context;"); jobject appContext = env->CallObjectMethod(activity.object<jobject>(), mIDGetApplicationContext); jclass appContextClass = env->GetObjectClass(appContext); jmethodID mIDGetSystemService = env->GetMethodID(appContextClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;"); jobject downloadManager = env->CallObjectMethod(appContext, mIDGetSystemService, downloadServiceString); jclass downloadManagerClass = env->GetObjectClass(downloadManager); // jmethodID mIDGetActiveNetworkInfo = env->GetMethodID(downloadManagerClass, // "getActiveNetworkInfo", // "()Landroid/net/NetworkInfo;"); // jobject activeNetworkInfo = env->CallObjectMethod(connectivityManager, // mIDGetActiveNetworkInfo); // jclass networkInfoClass = env->GetObjectClass(activeNetworkInfo); // jmethodID mIDGetTypeName = env->GetMethodID(networkInfoClass, // "getTypeName", // "()Ljava/lang/String;"); // jstring connectionTypeName = (jstring)env->CallObjectMethod(activeNetworkInfo, // mIDGetTypeName); env->PopLocalFrame(NULL); #else Q_UNUSED(url) Q_UNUSED(name) #endif }
43.178082
112
0.515228
adderly
c2a97102efbc1be69c9a68a0d0b9a823af88eb6a
1,309
cpp
C++
Competitions/Skillenza/Code Golf Challenge 1/Fibonacci numbers 1.cpp
cnm06/Competitive-Programming
94242ae458570d503b8218f37624b88cc5020d23
[ "MIT" ]
994
2017-02-28T06:13:47.000Z
2022-03-31T10:49:00.000Z
Competitions/Skillenza/Code Golf Challenge 1/Fibonacci numbers 1.cpp
Quadrified/Competitive-Programming
bccb69952cc5260fb3647b3301ddac1023dacac8
[ "MIT" ]
16
2018-01-01T02:59:55.000Z
2021-11-22T12:49:16.000Z
Competitions/Skillenza/Code Golf Challenge 1/Fibonacci numbers 1.cpp
Quadrified/Competitive-Programming
bccb69952cc5260fb3647b3301ddac1023dacac8
[ "MIT" ]
325
2017-06-15T03:32:43.000Z
2022-03-28T22:43:42.000Z
#include <cstdio> #include <cstring> using namespace std; #define MAX_SIZE 3 const long long MOD = 1000000007; int size = 3; struct Matrix{ long long X[MAX_SIZE][MAX_SIZE]; Matrix(){} void init(){ memset(X,0,sizeof(X)); for(int i = 0;i<size;++i) X[i][i] = 1; } }aux,M0,ans; void mult(Matrix &m, Matrix &m1, Matrix &m2){ memset(m.X,0,sizeof(m.X)); for(int i = 0;i<size;++i) for(int j = 0;j<size;++j) for(int k = 0;k<size;++k) m.X[i][k] = (m.X[i][k]+m1.X[i][j]*m2.X[j][k])%MOD; } Matrix pow(Matrix &M0, int n){ Matrix ret; ret.init(); if(n==0) return ret; if(n==1) return M0; Matrix P = M0; while(n!=0){ if(n & 1){ aux = ret; mult(ret,aux,P); } n >>= 1; aux = P; mult(P,aux,aux); } return ret; } long long sum(int n){ if(n<=0) return 0; if(n==1) return 1; ans = pow(M0,n-1); return (ans.X[0][0]+ans.X[0][1])%MOD; } int main(){ M0.X[0][0] = 1; M0.X[0][1] = 1; M0.X[0][2] = 1; M0.X[1][0] = 0; M0.X[1][1] = 1; M0.X[1][2] = 1; M0.X[2][0] = 0; M0.X[2][1] = 1; M0.X[2][2] = 0; int T,N,M; scanf("%d",&T); while(T--){ scanf("%d %d",&N,&M); printf("%lld\n",((sum(M)-sum(N-1))%MOD+MOD)%MOD); } return 0; }
16.782051
66
0.468296
cnm06
c2aeab7dbee62387d6db1dcdfa1b659ff94ab490
2,358
cpp
C++
bin/manager/tests/api.cpp
ArcticNature/core
bb63529a6deadc83e5adc3b772738ab6ca6ba18a
[ "BSD-3-Clause" ]
null
null
null
bin/manager/tests/api.cpp
ArcticNature/core
bb63529a6deadc83e5adc3b772738ab6ca6ba18a
[ "BSD-3-Clause" ]
null
null
null
bin/manager/tests/api.cpp
ArcticNature/core
bb63529a6deadc83e5adc3b772738ab6ca6ba18a
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2016 Stefano Pogliani <stefano@spogliani.net> #include <fcntl.h> #include <gtest/gtest.h> #include "core/bin/manager/api/source.h" #include "core/context/static.h" #include "core/event/drain/null.h" #include "core/event/testing.h" #include "core/exceptions/base.h" #include "core/model/event.h" #include "core/protocols/public/p_message.pb.h" #include "core/utility/protobuf.h" #include "core/posix/user.h" using sf::core::bin::ApiFdSource; using sf::core::context::Static; using sf::core::event::NullDrain; using sf::core::event::TestFdDrain; using sf::core::exception::CorruptedData; using sf::core::exception::FactoryNotFound; using sf::core::model::EventDrainRef; using sf::core::model::EventRef; using sf::core::protocol::public_api::Message; using sf::core::utility::MessageIO; using sf::core::posix::User; class ApiSourceTest : public ::testing::Test { protected: int read_fd; int write_fd; ApiFdSource* api; EventDrainRef drain; public: ApiSourceTest() { Static::initialise(new User()); int pipe[2]; Static::posix()->pipe(pipe, O_NONBLOCK); this->read_fd = pipe[0]; this->write_fd = pipe[1]; this->api = new ApiFdSource( this->read_fd, "test", EventDrainRef(new NullDrain()) ); this->drain = EventDrainRef(new TestFdDrain(this->write_fd, "test")); } ~ApiSourceTest() { delete this->api; this->drain.reset(); Static::destroy(); } void write(const char* buffer) { Static::posix()->write(this->write_fd, buffer, strlen(buffer)); } void write(Message message) { MessageIO<Message>::send(this->drain, message); this->drain->flush(); } }; TEST_F(ApiSourceTest, FailCorruptData) { this->write(""); ASSERT_THROW(this->api->fetch(), CorruptedData); } TEST_F(ApiSourceTest, FailHandlerNotFound) { Message message; message.set_code(Message::Ack); this->write(message); ASSERT_THROW(this->api->fetch(), FactoryNotFound); } TEST_F(ApiSourceTest, HandlerIsCalled) { Message message; message.set_code(Message::Introduce); this->write(message); EventRef event = this->api->fetch(); ASSERT_NE(nullptr, event.get()); } TEST_F(ApiSourceTest, HasDrain) { Message message; message.set_code(Message::Introduce); this->write(message); EventRef event = this->api->fetch(); ASSERT_EQ("NULL", event->drain()->id()); }
23.346535
73
0.693384
ArcticNature
c2b1d5f5f3a81f517bb7e1b315059df936fa2bd6
305
hpp
C++
addons/bi/caliber/556/f2000.hpp
Theseus-Aegis/GTRecoilSystem
308f260af7a2a8839d1f7a0b43d77d49c062ff6c
[ "MIT" ]
null
null
null
addons/bi/caliber/556/f2000.hpp
Theseus-Aegis/GTRecoilSystem
308f260af7a2a8839d1f7a0b43d77d49c062ff6c
[ "MIT" ]
null
null
null
addons/bi/caliber/556/f2000.hpp
Theseus-Aegis/GTRecoilSystem
308f260af7a2a8839d1f7a0b43d77d49c062ff6c
[ "MIT" ]
null
null
null
// F2000 Rifles - All rifles inherit // F2000 - Long Barrel class arifle_Mk20_F: mk20_base_F { recoil = QCLASS(556_Bullpup_Long); }; class arifle_Mk20C_F: mk20_base_F { recoil = QCLASS(556_Bullpup_Long); }; // GL class arifle_Mk20_GL_F: mk20_base_F { recoil = QCLASS(556_Bullpup_GL_Long); };
21.785714
41
0.727869
Theseus-Aegis
c2b212f7cb89bb1901849e08151a81d70b6ebf6f
11,421
cpp
C++
lab09_templatedBinarySearchTree_BST/executive.cpp
JackNGould/programming2
59c127b6a6c586a6fcd69526763aad27cd152d90
[ "MIT" ]
null
null
null
lab09_templatedBinarySearchTree_BST/executive.cpp
JackNGould/programming2
59c127b6a6c586a6fcd69526763aad27cd152d90
[ "MIT" ]
null
null
null
lab09_templatedBinarySearchTree_BST/executive.cpp
JackNGould/programming2
59c127b6a6c586a6fcd69526763aad27cd152d90
[ "MIT" ]
null
null
null
/* * @project: Binary Search Tree filled with custom objects. * @file: executive.cpp * @author: Jack Gould * @brief: Implementation File for executive class. Defines member methods. Class governs the program's 'executive' actions of filling a BST from the inputFile data, and generating a menu of options for the user. Controls program flow. * @date: 04-17-2020 */ #include "executive.h" #include "jackException.h" #include <sstream> #include <iostream> #include <limits> executive::executive(std::string fName) { std::ifstream inFile(fName); if (inFile.is_open()) { std::string line; while (getline(inFile, line)) { inputLineList.enqueue(line); } inFile.close(); } else { throw(jackException("\ninFile not found/opened.\n")); } } void executive::writeToFile(pokemon entry) { outFile.open(outFileName, std::fstream::app); //must be opened in append mode so that every new line doesn't override old line(s) if (outFile.is_open()) { outFile << entry.getAmerican() << '\t' << entry.getIndex() << '\t' << entry.getJapanese() << '\n'; outFile.close(); } else { throw(jackException("\noutFile not found/opened.\n")); } } executive::~executive() { } void executive::run() { fillTree(); bool runMenu = true; do { std::cout << "\n--------\n--Menu--\n--------\n"; std::cout << "1)Search the pokedex\n"; std::cout << "2)Add an entry to the pokedex\n"; std::cout << "3)Copy Pokedex(one-time only)\n"; std::cout << "4)Remove from Pokedex Copy\n"; std::cout << "5)Save a Pokedex\n"; std::cout << "6)Run a Test\n"; std::cout << "7)Exit the Program\n"; int userInput = 0; std::cout << "Please make a selection(1-7): "; try { std::cin >> userInput; if(std::cin.fail()) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); throw(jackException("\nBad Input Provided, please make sure input is an integer.\n")); } switch(userInput) { case 1: { int pokedexChoice = 0; if(copyCreated == true) { std::cout << "Search selected, please select a pokedex, 1 for the original, 2 for the copy.\n"; std::cin >> pokedexChoice; if(std::cin.fail() || pokedexChoice <=0 || pokedexChoice > 2) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); throw(jackException("\nError, pokedex choice must be either 1 or 2.\n")); } } std::cout << "Please input the american name of a pokemon to search the pokedex for:\n"; std::string searchTerm; std::cin >> searchTerm; if(std::cin.fail()) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); throw(jackException("\nError, couldn't interpret cin input.\n")); } pokemon temp; if(pokedexChoice == 2) { temp = (copyBST.search(searchTerm)); } else { temp = (myBST.search(searchTerm)); } std::cout << "\nPokemon Found!\n\tAmerican Name: " << temp.getAmerican() << "\n\tPokedex Number: " << temp.getIndex() << "\n\tJapanese Name: " << temp.getJapanese() << '\n'; break; } case 2: { std::string americanName, japaneseName; int pokedex; InputLoop: std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Add Entry selected: Please first input an American name for the new pokemon:\n"; std::cin >> americanName; if(std::cin.fail()) { goto InputLoop; } std::cout << "\nNow input a Japanese name for the new pokemon:\n"; std::cin >> japaneseName; if(std::cin.fail()) { goto InputLoop; } std::cout << "\nNow input a pokedex number for the new pokemon:\n"; std::cin >> pokedex; if(std::cin.fail()) { goto InputLoop; } //end InputLoop pokemon newPokemon(americanName, pokedex, japaneseName); if(copyCreated == true) { copyBST.add(newPokemon); std::cout << '\n' << americanName << " was added to the pokedex COPY\n"; } else { myBST.add(newPokemon); std::cout << '\n' << americanName << " was added to the original pokedex\n"; } break; } case 3: { if(copyCreated == false) { std::cout << "\nCreating a deep copy of the Pokedex...\nREMINDER:Once a copy has been created, edits can only be made to the copy\n"; copyBST = myBST; copyCreated = true; std::cout << "\nCopy Created\n"; } else { throw(jackException("\nA Deep copy was already made, please work with the copy you have already created.\n")); } break; } case 4: { if(copyCreated == true) { std::cout << "\nRemove selected, please input the american name of a pokemon to remove from the copied Pokedex\n"; std::string keyTerm; std::cin >> keyTerm; if(std::cin.fail()) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); throw(jackException("\nError, couldn't interpret cin input.\n")); } copyBST.remove(keyTerm); std::cout << keyTerm << " was removed from the copied pokedex\n."; } else { std::cout << "\nNo copy has been been created, the original pokedex is protected from Node removal.\n"; } break; } case 5: { int pokedexChoice = 0; int traversalChoice = 0; savePokedexPrompts(pokedexChoice, traversalChoice, outFileName); switch(traversalChoice) { case 1: { if(pokedexChoice == 2) { copyBST.visitPreOrder(std::bind(&executive::writeToFile, this, std::placeholders::_1)); } else { myBST.visitPreOrder(std::bind(&executive::writeToFile, this, std::placeholders::_1)); } break; } case 2: { if(pokedexChoice == 2) { copyBST.visitInOrder(std::bind(&executive::writeToFile, this, std::placeholders::_1)); } else { myBST.visitInOrder(std::bind(&executive::writeToFile, this, std::placeholders::_1)); } break; } case 3: { if(pokedexChoice == 2) { copyBST.visitPostOrder(std::bind(&executive::writeToFile, this, std::placeholders::_1)); } else { myBST.visitPostOrder(std::bind(&executive::writeToFile, this, std::placeholders::_1)); } break; } default: { throw(jackException("\nSomething really had to break for this error to print\n")); } } break; } case 6: { int testChoice = 0; std::cout << "\nTests on constructors/destructor selected, please choose a test:\n1)Test ADD\n2)Test Remove\n3)Test Write\n"; std::cin >> testChoice; if(std::cin.fail() || testChoice <=0 || testChoice > 3) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); throw(jackException("\nError, pokedex choice must be either 1 or 2.\n")); } switch(testChoice) { case 1: { tester.testAdds(myBST); break; } case 2: { tester.testRemoves(myBST); break; } case 3: { tester.testWriteToFile(myBST); break; } default: { throw(jackException("\nSomething broke here.\n")); } } break; } case 7: { std::cout << "\nExiting Program...\n"; runMenu = false; break; } default: { throw(jackException("\nError, invalid menu option entered, please input 1, 2, or 3\n")); break; } } } catch(jackException& rte) { std::cout << rte.what(); } }while(runMenu != false); } void executive::savePokedexPrompts(int& pokedex, int& traversal, std::string& outFile) { if(copyCreated == true) { std::cout << "Save selected, please select a pokedex, 1 for the original, 2 for the copy.\n"; std::cin >> pokedex; if(std::cin.fail() || pokedex <=0 || pokedex > 2) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); throw(jackException("\nError, pokedex choice must be either 1 or 2.\n")); } } else { pokedex = 1; } std::cout << "Save selected, please enter a file name to write the output to\n"; std::cin >> outFile; if(std::cin.fail()) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); throw(jackException("\nError, cin input could not be read.\n")); } std::cout << "Please select an order to traverse the tree in:\n1)PreOrder\n2)InOrder\n3)PostOrder\n"; std::cin >> traversal; if(std::cin.fail() || traversal <= 0 || traversal > 3) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); throw(jackException("\nError, traversal choice must be 1, 2, or 3.\n")); } } void executive::fillTree() { int objectCount = inputLineList.getLength(); std::string line = ""; std::string american, pokedex, japanese; int pokedexNum = 0; for(int i=0;i<objectCount;++i) { try { line = inputLineList.peekFront(); std::istringstream iss (line); iss >> american; iss >> pokedex; iss >> japanese; pokedexNum = stoi(pokedex); pokemon myPokemon(american, pokedexNum, japanese); myBST.add(myPokemon); inputLineList.dequeue(); } catch(jackException& rte) { std::cout << rte.what(); } } }
31.46281
235
0.492952
JackNGould
c2b219aa24d7be26c06877dbda3b2bbe8b33529f
14,941
cpp
C++
sdk/src/logging/Logger.cpp
andrie/rstudio-launcher-plugin-sdk
0b13a149fe263b578c90c98c8ab2d739b830ca60
[ "MIT" ]
4
2021-01-14T08:06:35.000Z
2021-09-24T12:39:31.000Z
sdk/src/logging/Logger.cpp
andrie/rstudio-launcher-plugin-sdk
0b13a149fe263b578c90c98c8ab2d739b830ca60
[ "MIT" ]
14
2021-01-19T21:21:16.000Z
2022-03-03T22:17:23.000Z
sdk/src/logging/Logger.cpp
andrie/rstudio-launcher-plugin-sdk
0b13a149fe263b578c90c98c8ab2d739b830ca60
[ "MIT" ]
3
2021-01-14T07:54:47.000Z
2021-11-23T18:20:19.000Z
/* * Logger.cpp * * Copyright (C) 2020 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant to the terms of a commercial license agreement * with RStudio, then this program is licensed to you under the following terms: * * 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 <logging/Logger.hpp> #include <cassert> #include <sstream> #include <boost/algorithm/string.hpp> #include <Error.hpp> #include <Noncopyable.hpp> #include <Optional.hpp> #include <logging/ILogDestination.hpp> #include <system/DateTime.hpp> #include "../system/ReaderWriterMutex.hpp" namespace rstudio { namespace launcher_plugins { namespace logging { typedef std::map<unsigned int, std::shared_ptr<ILogDestination> > LogMap; typedef std::map<std::string, LogMap> SectionLogMap; namespace { constexpr const char* s_loggedFrom = "LOGGED FROM"; std::ostream& operator<<(std::ostream& io_ostream, LogLevel in_logLevel) { switch (in_logLevel) { case LogLevel::ERR: { io_ostream << "ERROR"; break; } case LogLevel::WARN: { io_ostream << "WARNING"; break; } case LogLevel::DEBUG: { io_ostream << "DEBUG"; break; } case LogLevel::INFO: { io_ostream << "INFO"; break; } case LogLevel::OFF: { io_ostream << "OFF"; break; } default: { assert(false); // This shouldn't be possible if (in_logLevel > LogLevel::INFO) io_ostream << "INFO"; else io_ostream << "OFF"; } } return io_ostream; } std::string formatLogMessage( LogLevel in_logLevel, const std::string& in_message, const std::string& in_programId, const ErrorLocation& in_loggedFrom = ErrorLocation(), bool in_formatForSyslog = false) { std::ostringstream oss; if (!in_formatForSyslog) { // Add the time. oss << system::DateTime().toString("%d %b %Y %H:%M:%S") << " [" << in_programId << "] "; } oss << in_logLevel << " " << in_message; if (in_loggedFrom.hasLocation()) oss << s_delim << " " << s_loggedFrom << ": " << cleanDelimiters(in_loggedFrom.asString()); oss << std::endl; if (in_formatForSyslog) { // Newlines delimit logs in syslog, so replace them with ||| return boost::replace_all_copy(oss.str(), "\n", "|||"); } return oss.str(); } } // anonymous namespace // Logger Object ======================================================================================================= /** * @brief Class which logs messages to destinations. * * Multiple destinations may be added to this logger in order to write the same message to each destination. * The default log level is ERROR. */ struct Logger : Noncopyable { public: /** * @brief Writes a pre-formatted message to all registered destinations. * * @param in_logLevel The log level of the message, which is passed to the destination for informational purposes. * @param in_message The pre-formatted message. * @param in_section The section to which to log this message. * @param in_loggedFrom The location from which the error message was logged. */ void writeMessageToDestinations( LogLevel in_logLevel, const std::string& in_message, const std::string& in_section = std::string(), const ErrorLocation& in_loggedFrom = ErrorLocation()); /** * @brief Constructor to prevent multiple instances of Logger. */ Logger() : MaxLogLevel(LogLevel::OFF), ProgramId("") { }; // The maximum level of message to write across all log sections. LogLevel MaxLogLevel; // The ID of the program fr which to write logs. std::string ProgramId; // The registered default log destinations. Any logs without a section or with an unregistered section will be logged // to these destinations. LogMap DefaultLogDestinations; // The registered sectioned log destinations. Any logs with a registered section will be logged to the destinations // assigned to that section. SectionLogMap SectionedLogDestinations; // The read-write mutex to protect the maps. system::ReaderWriterMutex Mutex; }; Logger& logger() { static Logger logger; return logger; } void Logger::writeMessageToDestinations( LogLevel in_logLevel, const std::string& in_message, const std::string& in_section, const ErrorLocation& in_loggedFrom) { READ_LOCK_BEGIN(Mutex) // Don't log this message, it's too detailed for any of the logs. if (in_logLevel > MaxLogLevel) return; LogMap* logMap = &DefaultLogDestinations; if (!in_section.empty()) { // Don't log anything if there is no logger for this section. if (SectionedLogDestinations.find(in_section) == SectionedLogDestinations.end()) return; auto logDestIter = SectionedLogDestinations.find(in_section); logMap = &logDestIter->second; } // Preformat the message for non-syslog loggers. std::string formattedMessage = formatLogMessage(in_logLevel, in_message, ProgramId, in_loggedFrom); const auto destEnd = logMap->end(); for (auto iter = logMap->begin(); iter != destEnd; ++iter) { iter->second->writeLog(in_logLevel, formattedMessage); } RW_LOCK_END(false) } // Logging functions void setProgramId(const std::string& in_programId) { WRITE_LOCK_BEGIN(logger().Mutex) { if (!logger().ProgramId.empty() && (logger().ProgramId != in_programId)) logWarningMessage("Changing the program id from " + logger().ProgramId + " to " + in_programId); logger().ProgramId = in_programId; } RW_LOCK_END(false) } void addLogDestination(const std::shared_ptr<ILogDestination>& in_destination) { WRITE_LOCK_BEGIN(logger().Mutex) { LogMap& logMap = logger().DefaultLogDestinations; if (logMap.find(in_destination->getId()) == logMap.end()) { logMap.insert(std::make_pair(in_destination->getId(), in_destination)); if (in_destination->getLogLevel() > logger().MaxLogLevel) logger().MaxLogLevel = in_destination->getLogLevel(); return; } } RW_LOCK_END(false) logDebugMessage( "Attempted to register a log destination that has already been registered with id " + std::to_string(in_destination->getId())); } void addLogDestination(const std::shared_ptr<ILogDestination>& in_destination, const std::string& in_section) { WRITE_LOCK_BEGIN(logger().Mutex) { Logger& log = logger(); SectionLogMap& secLogMap = log.SectionedLogDestinations; if (secLogMap.find(in_section) == secLogMap.end()) secLogMap.insert(std::make_pair(in_section, LogMap())); LogMap& logMap = secLogMap.find(in_section)->second; if (logMap.find(in_destination->getId()) == logMap.end()) { logMap.insert(std::make_pair(in_destination->getId(), in_destination)); if (log.MaxLogLevel < in_destination->getLogLevel()) log.MaxLogLevel = in_destination->getLogLevel(); return; } } RW_LOCK_END(false) logDebugMessage( "Attempted to register a log destination that has already been registered with id " + std::to_string(in_destination->getId()) + " to section " + in_section); } std::string cleanDelimiters(const std::string& in_str) { std::string toClean(in_str); std::replace(toClean.begin(), toClean.end(), s_delim, ' '); return toClean; } void logError(const Error& in_error) { if (!in_error.isExpected()) logger().writeMessageToDestinations(LogLevel::ERR, in_error.asString()); } void logError(const Error& in_error, const ErrorLocation& in_location) { if (!in_error.isExpected()) logger().writeMessageToDestinations(LogLevel::ERR, in_error.asString(), "", in_location); } void logErrorAsWarning(const Error& in_error) { if (!in_error.isExpected()) logger().writeMessageToDestinations(LogLevel::WARN, in_error.asString()); } void logErrorAsInfo(const Error& in_error) { if (!in_error.isExpected()) logger().writeMessageToDestinations(LogLevel::INFO, in_error.asString()); } void logErrorAsDebug(const Error& in_error) { if (!in_error.isExpected()) logger().writeMessageToDestinations(LogLevel::DEBUG, in_error.asString()); } void logErrorMessage(const std::string& in_message, const std::string& in_section) { logErrorMessage(in_message, in_section, ErrorLocation()); } void logErrorMessage(const std::string& in_message, const ErrorLocation& in_loggedFrom) { logErrorMessage(in_message, "", in_loggedFrom); } void logErrorMessage(const std::string& in_message, const std::string& in_section, const ErrorLocation& in_loggedFrom) { Logger& log = logger(); if (log.MaxLogLevel >= LogLevel::ERR) log.writeMessageToDestinations(LogLevel::ERR, in_message, in_section, in_loggedFrom); } void logWarningMessage(const std::string& in_message, const std::string& in_section) { logWarningMessage(in_message, in_section, ErrorLocation()); } void logWarningMessage(const std::string& in_message, const ErrorLocation& in_loggedFrom) { logWarningMessage(in_message, "", in_loggedFrom); } void logWarningMessage(const std::string& in_message, const std::string& in_section, const ErrorLocation& in_loggedFrom) { Logger& log = logger(); if (log.MaxLogLevel >= LogLevel::WARN) log.writeMessageToDestinations(LogLevel::WARN, in_message, in_section, in_loggedFrom); } void logDebugMessage(const std::string& in_message, const std::string& in_section) { logDebugMessage(in_message, in_section, ErrorLocation()); } void logDebugMessage(const std::string& in_message, const ErrorLocation& in_loggedFrom) { logDebugMessage(in_message, "", in_loggedFrom); } void logDebugMessage(const std::string& in_message, const std::string& in_section, const ErrorLocation& in_loggedFrom) { logger().writeMessageToDestinations(LogLevel::DEBUG, in_message, in_section, in_loggedFrom); } void logInfoMessage(const std::string& in_message, const std::string& in_section) { logInfoMessage(in_message, in_section, ErrorLocation()); } void logInfoMessage(const std::string& in_message, const ErrorLocation& in_loggedFrom) { logInfoMessage(in_message, "", in_loggedFrom); } void logInfoMessage(const std::string& in_message, const std::string& in_section, const ErrorLocation& in_loggedFrom) { logger().writeMessageToDestinations(LogLevel::INFO, in_message, in_section, in_loggedFrom); } void reloadAllLogDestinations() { Logger& log = logger(); WRITE_LOCK_BEGIN(log.Mutex) { for (auto& dest : log.DefaultLogDestinations) dest.second->reload(); for (auto& section : log.SectionedLogDestinations) { for (auto& dest : section.second) dest.second->reload(); } } RW_LOCK_END(false); } void removeLogDestination(unsigned int in_destinationId, const std::string& in_section) { Logger& log = logger(); if (in_section.empty()) { // Remove the log from default destinations if it's found. Keep track of whether we find it for logging purposes. bool found = false; WRITE_LOCK_BEGIN(log.Mutex) { auto iter = log.DefaultLogDestinations.find(in_destinationId); if (iter != log.DefaultLogDestinations.end()) { found = true; log.DefaultLogDestinations.erase(iter); } // Remove it from any sections it may have been registered to. std::vector<std::string> sectionsToRemove; for (auto secIter: log.SectionedLogDestinations) { iter = secIter.second.find(in_destinationId); if (iter != secIter.second.end()) { found = true; secIter.second.erase(iter); } if (secIter.second.empty()) sectionsToRemove.push_back(secIter.first); } // Clean up any empty sections. for (const std::string& toRemove: sectionsToRemove) log.SectionedLogDestinations.erase(log.SectionedLogDestinations.find(toRemove)); } RW_LOCK_END(false); // Log a debug message if this destination wasn't registered. if (!found) { logDebugMessage( "Attempted to unregister a log destination that has not been registered with id" + std::to_string(in_destinationId)); } } else if (log.SectionedLogDestinations.find(in_section) != log.SectionedLogDestinations.end()) { WRITE_LOCK_BEGIN(log.Mutex) { auto secIter = log.SectionedLogDestinations.find(in_section); auto iter = secIter->second.find(in_destinationId); if (iter != secIter->second.end()) { secIter->second.erase(iter); if (secIter->second.empty()) log.SectionedLogDestinations.erase(secIter); return; } } RW_LOCK_END(false); logDebugMessage( "Attempted to unregister a log destination that has not been registered to the specified section (" + in_section + ") with id " + std::to_string(in_destinationId)); } else { logDebugMessage( "Attempted to unregister a log destination that has not been registered to the specified section (" + in_section + ") with id " + std::to_string(in_destinationId)); } } std::ostream& writeError(const Error& in_error, std::ostream& io_os) { return io_os << writeError(in_error); } std::string writeError(const Error& in_error) { return formatLogMessage(LogLevel::ERR, in_error.asString(), logger().ProgramId); } } // namespace logging } // namespace launcher_plugins } // namespace rstudio
30.616803
124
0.673047
andrie
c2b2c0a5159fce1a4e7ad6e07431889f6d5c62b9
1,020
hpp
C++
source/drivers/audio_decoder.hpp
HuangDave/BlockBoombox
d1750149f533d83fc6b955a1a12e75f14d4230e8
[ "Apache-2.0" ]
null
null
null
source/drivers/audio_decoder.hpp
HuangDave/BlockBoombox
d1750149f533d83fc6b955a1a12e75f14d4230e8
[ "Apache-2.0" ]
6
2020-07-29T23:26:15.000Z
2020-07-29T23:45:21.000Z
source/drivers/audio_decoder.hpp
HuangDave/BlockBoombox
d1750149f533d83fc6b955a1a12e75f14d4230e8
[ "Apache-2.0" ]
null
null
null
#pragma once #include <cstddef> #include <cstdint> /// An interface containing controls for an audio decoder. class AudioDecoder { public: /// Initialize the device for use. virtual void Initialize() const = 0; /// Reset the device. virtual void Reset() const = 0; /// Enable the device to be ready to decode audio data. virtual void Enable() const = 0; /// Pause audio decoding. virtual void Pause() const = 0; /// Attempts to resume audio decoding. virtual void Resume() const = 0; /// Reset decode time back to 00:00. virtual void ClearDecodeTime() const = 0; /// Buffer audio data for decoding. /// /// @param data Pointer to the array containing the data bytes to buffer. /// @param length The number of data bytes in the array. virtual void Buffer(const uint8_t * data, size_t length) const = 0; /// @param percentage Volume percentage ranging from 0.0 to 1.0, where 1.0 is /// 100 percent. virtual void SetVolume(float percentage) const = 0; };
26.842105
79
0.676471
HuangDave
c2b4f441ad85d02f75fc53c4fc32ee5d0be81ae1
3,972
cpp
C++
IGC/Compiler/CISACodeGen/TimeStatsCounter.cpp
lfelipe/intel-graphics-compiler
da6c84a62d5d499544b2ae5f70ae7d1cb4d78fbd
[ "MIT" ]
null
null
null
IGC/Compiler/CISACodeGen/TimeStatsCounter.cpp
lfelipe/intel-graphics-compiler
da6c84a62d5d499544b2ae5f70ae7d1cb4d78fbd
[ "MIT" ]
1
2021-02-24T08:39:15.000Z
2021-02-24T08:39:15.000Z
IGC/Compiler/CISACodeGen/TimeStatsCounter.cpp
lfelipe/intel-graphics-compiler
da6c84a62d5d499544b2ae5f70ae7d1cb4d78fbd
[ "MIT" ]
null
null
null
/*===================== begin_copyright_notice ================================== Copyright (c) 2017 Intel Corporation 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. ======================= end_copyright_notice ==================================*/ #include "Compiler/CISACodeGen/TimeStatsCounter.h" #include "Compiler/IGCPassSupport.h" #include "common/LLVMWarningsPush.hpp" #include <llvm/Pass.h> #include "common/LLVMWarningsPop.hpp" using namespace llvm; using namespace IGC; namespace { class TimeStatsCounter : public ModulePass { CodeGenContext* ctx; COMPILE_TIME_INTERVALS interval; TimeStatsCounterStartEndMode mode; std::string igcPass; TimeStatsCounterType type; public: static char ID; TimeStatsCounter() : ModulePass(ID) { initializeTimeStatsCounterPass(*PassRegistry::getPassRegistry()); } TimeStatsCounter(CodeGenContext* _ctx, COMPILE_TIME_INTERVALS _interval, TimeStatsCounterStartEndMode _mode) : ModulePass(ID) { initializeTimeStatsCounterPass(*PassRegistry::getPassRegistry()); ctx = _ctx; interval = _interval; mode = _mode; type = STATS_COUNTER_ENUM_TYPE; } TimeStatsCounter(CodeGenContext* _ctx, std::string _igcPass, TimeStatsCounterStartEndMode _mode) : ModulePass(ID) { initializeTimeStatsCounterPass(*PassRegistry::getPassRegistry()); ctx = _ctx; mode = _mode; igcPass = _igcPass; type = STATS_COUNTER_LLVM_PASS; } bool runOnModule(Module&) override; private: }; } // End anonymous namespace ModulePass* IGC::createTimeStatsCounterPass(CodeGenContext* _ctx, COMPILE_TIME_INTERVALS _interval, TimeStatsCounterStartEndMode _mode) { return new TimeStatsCounter(_ctx, _interval, _mode); } ModulePass* IGC::createTimeStatsIGCPass(CodeGenContext* _ctx, std::string _igcPass, TimeStatsCounterStartEndMode _mode) { return new TimeStatsCounter(_ctx, _igcPass, _mode); } char TimeStatsCounter::ID = 0; #define PASS_FLAG "time-stats-counter" #define PASS_DESC "TimeStatsCounter Start/Stop" #define PASS_CFG_ONLY false #define PASS_ANALYSIS false namespace IGC { IGC_INITIALIZE_PASS_BEGIN(TimeStatsCounter, PASS_FLAG, PASS_DESC, PASS_CFG_ONLY, PASS_ANALYSIS) IGC_INITIALIZE_PASS_END(TimeStatsCounter, PASS_FLAG, PASS_DESC, PASS_CFG_ONLY, PASS_ANALYSIS) } bool TimeStatsCounter::runOnModule(Module& F) { if (type == STATS_COUNTER_ENUM_TYPE) { if (mode == STATS_COUNTER_START) { COMPILER_TIME_START(ctx, interval); } else { COMPILER_TIME_END(ctx, interval); } } else { if (mode == STATS_COUNTER_START) { COMPILER_TIME_PASS_START(ctx, igcPass); } else { COMPILER_TIME_PASS_END(ctx, igcPass); } } return false; }
32.826446
137
0.690584
lfelipe
c2b6fe6b9ed4683af1dcc6505dfcbb50f42ad445
26,923
cpp
C++
src/items/weapons/weapons.cpp
Waclaw-I/BagnoOTS
dbeb04322698ecdb795eba196872815b36ca134f
[ "MIT" ]
null
null
null
src/items/weapons/weapons.cpp
Waclaw-I/BagnoOTS
dbeb04322698ecdb795eba196872815b36ca134f
[ "MIT" ]
null
null
null
src/items/weapons/weapons.cpp
Waclaw-I/BagnoOTS
dbeb04322698ecdb795eba196872815b36ca134f
[ "MIT" ]
null
null
null
/** * The Forgotten Server - a free and open-source MMORPG server emulator * Copyright (C) 2019 Mark Samman <mark.samman@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "otpch.h" #include "creatures/combat/combat.h" #include "game/game.h" #include "utils/pugicast.h" #include "lua/creature/events.h" #include "items/weapons/weapons.h" Weapons::Weapons() { scriptInterface.initState(); } Weapons::~Weapons() { clear(false); } const Weapon* Weapons::getWeapon(const Item* item) const { if (!item) { return nullptr; } auto it = weapons.find(item->getID()); if (it == weapons.end()) { return nullptr; } return it->second; } void Weapons::clear(bool fromLua) { for (auto it = weapons.begin(); it != weapons.end(); ) { if (fromLua == it->second->fromLua) { it = weapons.erase(it); } else { ++it; } } reInitState(fromLua); } LuaScriptInterface& Weapons::getScriptInterface() { return scriptInterface; } std::string Weapons::getScriptBaseName() const { return "weapons"; } void Weapons::loadDefaults() { for (size_t i = 100, size = Item::items.size(); i < size; ++i) { const ItemType& it = Item::items.getItemType(i); if (it.id == 0 || weapons.find(i) != weapons.end()) { continue; } switch (it.weaponType) { case WEAPON_AXE: case WEAPON_SWORD: case WEAPON_CLUB: { WeaponMelee* weapon = new WeaponMelee(&scriptInterface); weapon->configureWeapon(it); weapons[i] = weapon; break; } case WEAPON_AMMO: case WEAPON_DISTANCE: { if (it.weaponType == WEAPON_DISTANCE && it.ammoType != AMMO_NONE) { continue; } WeaponDistance* weapon = new WeaponDistance(&scriptInterface); weapon->configureWeapon(it); weapons[i] = weapon; break; } default: break; } } } Event_ptr Weapons::getEvent(const std::string& nodeName) { if (strcasecmp(nodeName.c_str(), "melee") == 0) { return Event_ptr(new WeaponMelee(&scriptInterface)); } else if (strcasecmp(nodeName.c_str(), "distance") == 0) { return Event_ptr(new WeaponDistance(&scriptInterface)); } else if (strcasecmp(nodeName.c_str(), "wand") == 0) { return Event_ptr(new WeaponWand(&scriptInterface)); } return nullptr; } bool Weapons::registerEvent(Event_ptr event, const pugi::xml_node&) { Weapon* weapon = static_cast<Weapon*>(event.release()); //event is guaranteed to be a Weapon auto result = weapons.emplace(weapon->getID(), weapon); if (!result.second) { SPDLOG_WARN("[Weapons::registerEvent] - " "Duplicate registered item with id: {}", weapon->getID()); } return result.second; } bool Weapons::registerLuaEvent(Weapon* event) { weapons[event->getID()] = event; return true; } //monsters int32_t Weapons::getMaxMeleeDamage(int32_t attackSkill, int32_t attackValue) { return static_cast<int32_t>(std::ceil((attackSkill * (attackValue * 0.05)) + (attackValue * 0.5))); } //players int32_t Weapons::getMaxWeaponDamage(uint32_t level, int32_t attackSkill, int32_t attackValue, float attackFactor, bool isMelee) { if (isMelee) { return static_cast<int32_t>(std::round((0.085 * attackFactor * attackValue * attackSkill) + (level / 5))); } else { return static_cast<int32_t>(std::round((0.09 * attackFactor * attackValue * attackSkill) + (level / 5))); } } bool Weapon::configureEvent(const pugi::xml_node& node) { pugi::xml_attribute attr; if (!(attr = node.attribute("id"))) { SPDLOG_ERROR("[Weapon::configureEvent] - Weapon without id"); return false; } id = pugi::cast<uint16_t>(attr.value()); if ((attr = node.attribute("level"))) { level = pugi::cast<uint32_t>(attr.value()); } if ((attr = node.attribute("maglv")) || (attr = node.attribute("maglevel"))) { magLevel = pugi::cast<uint32_t>(attr.value()); } if ((attr = node.attribute("mana"))) { mana = pugi::cast<uint32_t>(attr.value()); } if ((attr = node.attribute("manapercent"))) { manaPercent = pugi::cast<uint32_t>(attr.value()); } if ((attr = node.attribute("soul"))) { soul = pugi::cast<uint32_t>(attr.value()); } if ((attr = node.attribute("prem"))) { premium = attr.as_bool(); } if ((attr = node.attribute("breakchance")) && g_configManager().getBoolean(REMOVE_WEAPON_CHARGES)) { breakChance = std::min<uint8_t>(100, pugi::cast<uint16_t>(attr.value())); } if ((attr = node.attribute("action"))) { action = getWeaponAction(asLowerCaseString(attr.as_string())); if (action == WEAPONACTION_NONE) { SPDLOG_WARN("[Weapon::configureEvent] - " "Unknown action {}", attr.as_string()); } } if ((attr = node.attribute("enabled"))) { enabled = attr.as_bool(); } if ((attr = node.attribute("unproperly"))) { wieldUnproperly = attr.as_bool(); } std::list<std::string> vocStringList; for (auto vocationNode : node.children()) { if (!(attr = vocationNode.attribute("name"))) { continue; } uint16_t vocationId = g_vocations().getVocationId(attr.as_string()); if (vocationId != -1) { vocWeaponMap[vocationId] = true; int32_t promotedVocation = g_vocations().getPromotedVocation(vocationId); if (promotedVocation != VOCATION_NONE) { vocWeaponMap[promotedVocation] = true; } if (vocationNode.attribute("showInDescription").as_bool(true)) { vocStringList.push_back(asLowerCaseString(attr.as_string())); } } } std::string vocationString; for (const std::string& str : vocStringList) { if (!vocationString.empty()) { if (str != vocStringList.back()) { vocationString.push_back(','); vocationString.push_back(' '); } else { vocationString += " and "; } } vocationString += str; vocationString.push_back('s'); } uint32_t wieldInfo = 0; if (getReqLevel() > 0) { wieldInfo |= WIELDINFO_LEVEL; } if (getReqMagLv() > 0) { wieldInfo |= WIELDINFO_MAGLV; } if (!vocationString.empty()) { wieldInfo |= WIELDINFO_VOCREQ; } if (isPremium()) { wieldInfo |= WIELDINFO_PREMIUM; } if (wieldInfo != 0) { ItemType& it = Item::items.getItemType(id); it.wieldInfo = wieldInfo; it.vocationString = vocationString; it.minReqLevel = getReqLevel(); it.minReqMagicLevel = getReqMagLv(); } configureWeapon(Item::items[id]); return true; } void Weapon::configureWeapon(const ItemType& it) { id = it.id; } std::string Weapon::getScriptEventName() const { return "onUseWeapon"; } int32_t Weapon::playerWeaponCheck(Player* player, Creature* target, uint8_t shootRange) const { const Position& playerPos = player->getPosition(); const Position& targetPos = target->getPosition(); if (playerPos.z != targetPos.z) { return 0; } if (std::max<uint32_t>(Position::getDistanceX(playerPos, targetPos), Position::getDistanceY(playerPos, targetPos)) > shootRange) { return 0; } if (!player->hasFlag(PlayerFlag_IgnoreWeaponCheck)) { if (!enabled) { return 0; } if (player->getMana() < getManaCost(player)) { return 0; } if (player->getHealth() < getHealthCost(player)) { return 0; } if (player->getSoul() < soul) { return 0; } if (isPremium() && !player->isPremium()) { return 0; } if (!vocWeaponMap.empty()) { if (vocWeaponMap.find(player->getVocationId()) == vocWeaponMap.end()) { return 0; } } int32_t damageModifier = 100; if (player->getLevel() < getReqLevel()) { damageModifier = (isWieldedUnproperly() ? damageModifier / 2 : 0); } if (player->getMagicLevel() < getReqMagLv()) { damageModifier = (isWieldedUnproperly() ? damageModifier / 2 : 0); } return damageModifier; } return 100; } bool Weapon::useWeapon(Player* player, Item* item, Creature* target) const { int32_t damageModifier = playerWeaponCheck(player, target, item->getShootRange()); if (damageModifier == 0) { return false; } internalUseWeapon(player, item, target, damageModifier); return true; } CombatDamage Weapon::getCombatDamage(CombatDamage combat, Player * player, Item * item, int32_t damageModifier) const { //Local variables uint32_t level = player->getLevel(); int16_t elementalAttack = getElementDamageValue(); int32_t weaponAttack = std::max<int32_t>(0, item->getAttack()); int32_t playerSkill = player->getWeaponSkill(item); float attackFactor = player->getAttackFactor(); // full atk, balanced or full defense //Getting values factores int32_t totalAttack = elementalAttack + weaponAttack; double weaponAttackProportion = (double)weaponAttack / (double)totalAttack; //Calculating damage int32_t maxDamage = static_cast<int32_t>(Weapons::getMaxWeaponDamage(level, playerSkill, totalAttack, attackFactor, true) * player->getVocation()->meleeDamageMultiplier * damageModifier / 100); int32_t minDamage = level / 5; int32_t realDamage = normal_random(minDamage, maxDamage); //Setting damage to combat combat.primary.value = realDamage * weaponAttackProportion; combat.secondary.value = realDamage * (1 - weaponAttackProportion); return combat; } bool Weapon::useFist(Player* player, Creature* target) { if (!Position::areInRange<1, 1>(player->getPosition(), target->getPosition())) { return false; } float attackFactor = player->getAttackFactor(); int32_t attackSkill = player->getSkillLevel(SKILL_FIST); int32_t attackValue = 7; int32_t maxDamage = Weapons::getMaxWeaponDamage(player->getLevel(), attackSkill, attackValue, attackFactor, true); CombatParams params; params.combatType = COMBAT_PHYSICALDAMAGE; params.blockedByArmor = true; params.blockedByShield = true; CombatDamage damage; damage.origin = ORIGIN_MELEE; damage.primary.type = params.combatType; damage.primary.value = -normal_random(0, maxDamage); Combat::doCombatHealth(player, target, damage, params); if (!player->hasFlag(PlayerFlag_NotGainSkill) && player->getAddAttackSkill()) { player->addSkillAdvance(SKILL_FIST, 1); } return true; } void Weapon::internalUseWeapon(Player* player, Item* item, Creature* target, int32_t damageModifier) const { if (scripted) { LuaVariant var; var.type = VARIANT_NUMBER; var.number = target->getID(); executeUseWeapon(player, var); } else { CombatDamage damage; WeaponType_t weaponType = item->getWeaponType(); if (weaponType == WEAPON_AMMO || weaponType == WEAPON_DISTANCE) { damage.origin = ORIGIN_RANGED; } else { damage.origin = ORIGIN_MELEE; } damage.primary.type = params.combatType; damage.secondary.type = getElementType(); if (damage.secondary.type == COMBAT_NONE) { damage.primary.value = (getWeaponDamage(player, target, item) * damageModifier) / 100; damage.secondary.value = 0; } else { damage.primary.value = (getWeaponDamage(player, target, item) * damageModifier) / 100; damage.secondary.value = (getElementDamage(player, target, item) * damageModifier) / 100; } Combat::doCombatHealth(player, target, damage, params); } onUsedWeapon(player, item, target->getTile()); } void Weapon::internalUseWeapon(Player* player, Item* item, Tile* tile) const { if (scripted) { LuaVariant var; var.type = VARIANT_TARGETPOSITION; var.pos = tile->getPosition(); executeUseWeapon(player, var); } else { Combat::postCombatEffects(player, tile->getPosition(), params); g_game().addMagicEffect(tile->getPosition(), CONST_ME_POFF); } onUsedWeapon(player, item, tile); } void Weapon::onUsedWeapon(Player* player, Item* item, Tile* destTile) const { if (!player->hasFlag(PlayerFlag_NotGainSkill)) { skills_t skillType; uint32_t skillPoint; if (getSkillType(player, item, skillType, skillPoint)) { player->addSkillAdvance(skillType, skillPoint); } } uint32_t manaCost = getManaCost(player); if (manaCost != 0) { player->addManaSpent(manaCost); player->changeMana(-static_cast<int32_t>(manaCost)); } uint32_t healthCost = getHealthCost(player); if (healthCost != 0) { player->changeHealth(-static_cast<int32_t>(healthCost)); } if (!player->hasFlag(PlayerFlag_HasInfiniteSoul) && soul > 0) { player->changeSoul(-static_cast<int32_t>(soul)); } if (breakChance != 0 && uniform_random(1, 100) <= breakChance) { Weapon::decrementItemCount(item); player->updateSupplyTracker(item); return; } switch (action) { case WEAPONACTION_REMOVECOUNT: if(g_configManager().getBoolean(REMOVE_WEAPON_AMMO)) { Weapon::decrementItemCount(item); player->updateSupplyTracker(item); } break; case WEAPONACTION_REMOVECHARGE: { if (uint16_t charges = item->getCharges() != 0 && g_configManager().getBoolean(REMOVE_WEAPON_CHARGES)) { g_game().transformItem(item, item->getID(), charges - 1); } break; } case WEAPONACTION_MOVE: g_game().internalMoveItem(item->getParent(), destTile, INDEX_WHEREEVER, item, 1, nullptr, FLAG_NOLIMIT); break; default: break; } } uint32_t Weapon::getManaCost(const Player* player) const { if (mana != 0) { return mana; } if (manaPercent == 0) { return 0; } return (player->getMaxMana() * manaPercent) / 100; } int32_t Weapon::getHealthCost(const Player* player) const { if (health != 0) { return health; } if (healthPercent == 0) { return 0; } return (player->getMaxHealth() * healthPercent) / 100; } bool Weapon::executeUseWeapon(Player* player, const LuaVariant& var) const { //onUseWeapon(player, var) if (!scriptInterface->reserveScriptEnv()) { SPDLOG_ERROR("[Weapon::executeUseWeapon - Player {} weaponId {}]" "Call stack overflow. Too many lua script calls being nested.", player->getName(), getID()); return false; } ScriptEnvironment* env = scriptInterface->getScriptEnv(); env->setScriptId(scriptId, scriptInterface); lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(scriptId); LuaScriptInterface::pushUserdata<Player>(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); scriptInterface->pushVariant(L, var); return scriptInterface->callFunction(2); } void Weapon::decrementItemCount(Item* item) { uint16_t count = item->getItemCount(); if (count > 1) { g_game().transformItem(item, item->getID(), count - 1); } else { g_game().internalRemoveItem(item); } } WeaponMelee::WeaponMelee(LuaScriptInterface* interface) : Weapon(interface) { params.blockedByArmor = true; params.blockedByShield = true; params.combatType = COMBAT_PHYSICALDAMAGE; } void WeaponMelee::configureWeapon(const ItemType& it) { if (it.abilities) { elementType = it.abilities->elementType; elementDamage = it.abilities->elementDamage; params.aggressive = true; params.useCharges = true; } else { elementType = COMBAT_NONE; elementDamage = 0; } Weapon::configureWeapon(it); } bool WeaponMelee::useWeapon(Player* player, Item* item, Creature* target) const { int32_t damageModifier = playerWeaponCheck(player, target, item->getShootRange()); if (damageModifier == 0) { return false; } internalUseWeapon(player, item, target, damageModifier); return true; } bool WeaponMelee::getSkillType(const Player* player, const Item* item, skills_t& skill, uint32_t& skillpoint) const { if (player->getAddAttackSkill() && player->getLastAttackBlockType() != BLOCK_IMMUNITY) { skillpoint = 1; } else { skillpoint = 0; } WeaponType_t weaponType = item->getWeaponType(); switch (weaponType) { case WEAPON_SWORD: { skill = SKILL_SWORD; return true; } case WEAPON_CLUB: { skill = SKILL_CLUB; return true; } case WEAPON_AXE: { skill = SKILL_AXE; return true; } default: break; } return false; } int32_t WeaponMelee::getElementDamage(const Player* player, const Creature*, const Item* item) const { if (elementType == COMBAT_NONE) { return 0; } int32_t attackSkill = player->getWeaponSkill(item); int32_t attackValue = elementDamage; float attackFactor = player->getAttackFactor(); uint32_t level = player->getLevel(); int32_t minValue = level / 5; int32_t maxValue = Weapons::getMaxWeaponDamage(level, attackSkill, attackValue, attackFactor, true); return -normal_random(minValue, static_cast<int32_t>(maxValue * player->getVocation()->meleeDamageMultiplier)); } int16_t WeaponMelee::getElementDamageValue() const { return elementDamage; } int32_t WeaponMelee::getWeaponDamage(const Player* player, const Creature*, const Item* item, bool maxDamage /*= false*/) const { using namespace std; int32_t attackSkill = player->getWeaponSkill(item); int32_t attackValue = std::max<int32_t>(0, item->getAttack()); float attackFactor = player->getAttackFactor(); uint32_t level = player->getLevel(); int32_t maxValue = static_cast<int32_t>(Weapons::getMaxWeaponDamage(level, attackSkill, attackValue, attackFactor, true) * player->getVocation()->meleeDamageMultiplier); int32_t minValue = level / 5; if (maxDamage) { return -maxValue; } return -normal_random(minValue, maxValue); } WeaponDistance::WeaponDistance(LuaScriptInterface* interface) : Weapon(interface) { params.blockedByArmor = true; params.combatType = COMBAT_PHYSICALDAMAGE; } void WeaponDistance::configureWeapon(const ItemType& it) { params.distanceEffect = it.shootType; if (it.abilities) { elementType = it.abilities->elementType; elementDamage = it.abilities->elementDamage; params.aggressive = true; params.useCharges = true; } else { elementType = COMBAT_NONE; elementDamage = 0; } Weapon::configureWeapon(it); } bool WeaponDistance::useWeapon(Player* player, Item* item, Creature* target) const { int32_t damageModifier; const ItemType& it = Item::items[id]; if (it.weaponType == WEAPON_AMMO) { Item* mainWeaponItem = player->getWeapon(true); const Weapon* mainWeapon = g_weapons().getWeapon(mainWeaponItem); if (mainWeapon) { damageModifier = mainWeapon->playerWeaponCheck(player, target, mainWeaponItem->getShootRange()); } else { damageModifier = playerWeaponCheck(player, target, mainWeaponItem->getShootRange()); } } else { damageModifier = playerWeaponCheck(player, target, item->getShootRange()); } if (damageModifier == 0) { return false; } int32_t chance; if (it.hitChance == 0) { //hit chance is based on distance to target and distance skill uint32_t skill = player->getSkillLevel(SKILL_DISTANCE); const Position& playerPos = player->getPosition(); const Position& targetPos = target->getPosition(); uint32_t distance = std::max<uint32_t>(Position::getDistanceX(playerPos, targetPos), Position::getDistanceY(playerPos, targetPos)); uint32_t maxHitChance; if (it.maxHitChance != -1) { maxHitChance = it.maxHitChance; } else if (it.ammoType != AMMO_NONE) { //hit chance on two-handed weapons is limited to 90% maxHitChance = 90; } else { //one-handed is set to 75% maxHitChance = 75; } if (maxHitChance == 75) { //chance for one-handed weapons switch (distance) { case 1: case 5: chance = std::min<uint32_t>(skill, 74) + 1; break; case 2: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 28) * 2.40f) + 8; break; case 3: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 45) * 1.55f) + 6; break; case 4: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 58) * 1.25f) + 3; break; case 6: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 90) * 0.80f) + 3; break; case 7: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 104) * 0.70f) + 2; break; default: chance = it.hitChance; break; } } else if (maxHitChance == 90) { //formula for two-handed weapons switch (distance) { case 1: case 5: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 74) * 1.20f) + 1; break; case 2: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 28) * 3.20f); break; case 3: chance = std::min<uint32_t>(skill, 45) * 2; break; case 4: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 58) * 1.55f); break; case 6: case 7: chance = std::min<uint32_t>(skill, 90); break; default: chance = it.hitChance; break; } } else if (maxHitChance == 100) { switch (distance) { case 1: case 5: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 73) * 1.35f) + 1; break; case 2: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 30) * 3.20f) + 4; break; case 3: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 48) * 2.05f) + 2; break; case 4: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 65) * 1.50f) + 2; break; case 6: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 87) * 1.20f) - 4; break; case 7: chance = static_cast<uint32_t>(std::min<uint32_t>(skill, 90) * 1.10f) + 1; break; default: chance = it.hitChance; break; } } else { chance = maxHitChance; } } else { chance = it.hitChance; } if (item->getWeaponType() == WEAPON_AMMO) { Item* bow = player->getWeapon(true); if (bow && bow->getHitChance() != 0) { chance += bow->getHitChance(); } } if (chance >= uniform_random(1, 100)) { Weapon::internalUseWeapon(player, item, target, damageModifier); } else { //miss target Tile* destTile = target->getTile(); if (!Position::areInRange<1, 1, 0>(player->getPosition(), target->getPosition())) { static std::vector<std::pair<int32_t, int32_t>> destList { {-1, -1}, {0, -1}, {1, -1}, {-1, 0}, {0, 0}, {1, 0}, {-1, 1}, {0, 1}, {1, 1} }; std::shuffle(destList.begin(), destList.end(), getRandomGenerator()); Position destPos = target->getPosition(); for (const auto& dir : destList) { // Blocking tiles or tiles without ground ain't valid targets for spears Tile* tmpTile = g_game().map.getTile(static_cast<uint16_t>(destPos.x + dir.first), static_cast<uint16_t>(destPos.y + dir.second), destPos.z); if (tmpTile && !tmpTile->hasFlag(TILESTATE_IMMOVABLEBLOCKSOLID) && tmpTile->getGround() != nullptr) { destTile = tmpTile; break; } } } Weapon::internalUseWeapon(player, item, destTile); } return true; } int32_t WeaponDistance::getElementDamage(const Player* player, const Creature* target, const Item* item) const { if (elementType == COMBAT_NONE) { return 0; } int32_t attackValue = elementDamage; if (item->getWeaponType() == WEAPON_AMMO) { Item* weapon = player->getWeapon(true); if (weapon) { attackValue += item->getAttack(); attackValue += weapon->getAttack(); } } int32_t attackSkill = player->getSkillLevel(SKILL_DISTANCE); float attackFactor = player->getAttackFactor(); int32_t minValue = std::round(player->getLevel() / 5); int32_t maxValue = std::round((0.09f * attackFactor) * attackSkill * attackValue + minValue) / 2; if (target) { if (target->getPlayer()) { minValue /= 4; } else { minValue /= 2; } } return -normal_random(minValue, static_cast<int32_t>(maxValue * player->getVocation()->distDamageMultiplier)); } int16_t WeaponDistance::getElementDamageValue() const { return elementDamage; } int32_t WeaponDistance::getWeaponDamage(const Player* player, const Creature* target, const Item* item, bool maxDamage /*= false*/) const { int32_t attackValue = item->getAttack(); bool hasElement = false; if (item->getWeaponType() == WEAPON_AMMO) { Item* weapon = player->getWeapon(true); if (weapon) { const ItemType& it = Item::items[item->getID()]; if (it.abilities && it.abilities->elementDamage != 0) { attackValue += it.abilities->elementDamage; hasElement = true; } attackValue += weapon->getAttack(); } } int32_t attackSkill = player->getSkillLevel(SKILL_DISTANCE); float attackFactor = player->getAttackFactor(); int32_t minValue = player->getLevel() / 5; int32_t maxValue = std::round((0.09f * attackFactor) * attackSkill * attackValue + minValue); if (maxDamage) { return -maxValue; } if (target->getPlayer()) { if (hasElement) { minValue /= 4; } else { minValue /= 2; } } else { if (hasElement) { maxValue /= 2; minValue /= 2; } } return -normal_random(minValue, maxValue); } bool WeaponDistance::getSkillType(const Player* player, const Item*, skills_t& skill, uint32_t& skillpoint) const { skill = SKILL_DISTANCE; if (player->getAddAttackSkill()) { switch (player->getLastAttackBlockType()) { case BLOCK_NONE: { skillpoint = 2; break; } case BLOCK_DEFENSE: case BLOCK_ARMOR: { skillpoint = 1; break; } default: skillpoint = 0; break; } } else { skillpoint = 0; } return true; } bool WeaponWand::configureEvent(const pugi::xml_node& node) { if (!Weapon::configureEvent(node)) { return false; } pugi::xml_attribute attr; if ((attr = node.attribute("min"))) { minChange = pugi::cast<int32_t>(attr.value()); } if ((attr = node.attribute("max"))) { maxChange = pugi::cast<int32_t>(attr.value()); } attr = node.attribute("type"); if (!attr) { return true; } std::string tmpStrValue = asLowerCaseString(attr.as_string()); if (tmpStrValue == "earth") { params.combatType = COMBAT_EARTHDAMAGE; } else if (tmpStrValue == "ice") { params.combatType = COMBAT_ICEDAMAGE; } else if (tmpStrValue == "energy") { params.combatType = COMBAT_ENERGYDAMAGE; } else if (tmpStrValue == "fire") { params.combatType = COMBAT_FIREDAMAGE; } else if (tmpStrValue == "death") { params.combatType = COMBAT_DEATHDAMAGE; } else if (tmpStrValue == "holy") { params.combatType = COMBAT_HOLYDAMAGE; } else { SPDLOG_WARN("[WeaponWand::configureEvent] - " "Type {} does not exist", attr.as_string()); } return true; } void WeaponWand::configureWeapon(const ItemType& it) { params.distanceEffect = it.shootType; const_cast<ItemType&>(it).combatType = params.combatType; const_cast<ItemType&>(it).maxHitChance = (minChange + maxChange) / 2; Weapon::configureWeapon(it); } int32_t WeaponWand::getWeaponDamage(const Player*, const Creature*, const Item*, bool maxDamage /*= false*/) const { if (maxDamage) { return -maxChange; } return -normal_random(minChange, maxChange); } int16_t WeaponWand::getElementDamageValue() const { return 0; }
26.291992
194
0.682539
Waclaw-I
c2b8e50ac2402e20e08c12db37d5a5b7a15a1b89
1,324
hpp
C++
rokko/utility/pyrokko_minij_matrix.hpp
t-sakashita/rokko
ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9
[ "BSL-1.0" ]
16
2015-01-31T18:57:48.000Z
2022-03-18T19:04:49.000Z
rokko/utility/pyrokko_minij_matrix.hpp
t-sakashita/rokko
ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9
[ "BSL-1.0" ]
514
2015-02-05T14:56:54.000Z
2021-06-25T09:29:52.000Z
rokko/utility/pyrokko_minij_matrix.hpp
t-sakashita/rokko
ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9
[ "BSL-1.0" ]
2
2015-06-16T04:22:23.000Z
2019-06-01T07:10:01.000Z
/***************************************************************************** * * Rokko: Integrated Interface for libraries of eigenvalue decomposition * * Copyright (C) 2012-2019 by Rokko Developers https://github.com/t-sakashita/rokko * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) * *****************************************************************************/ #ifndef PYROKKO_MINIJ_MATRIX_HPP #define PYROKKO_MINIJ_MATRIX_HPP #include <rokko/utility/minij_matrix.hpp> #include <rokko/pyrokko_distributed_matrix.hpp> namespace rokko { class wrap_minij_matrix { public: template <typename T, int MAJOR> static void generate(Eigen::Ref<Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic,MAJOR>> mat_in) { Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic,MAJOR> mat(mat_in.rows(), mat_in.cols()); new (&mat) Eigen::Ref<Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic,MAJOR>>(mat_in); minij_matrix::generate(mat); new (&mat) Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic,MAJOR>(); } template <typename T, typename MATRIX_MAJOR> static void generate(wrap_distributed_matrix<T,MATRIX_MAJOR>& mat) { minij_matrix::generate(mat); } }; } // namespace rokko #endif // PYROKKO_MINIJ_MATRIX_HPP
33.1
97
0.659366
t-sakashita
c2ba3bbe0fe0efa2f354c638489ddc65aae093c9
34,408
cpp
C++
SDKs/CryCode/3.7.0/CryEngine/CryEntitySystem/EntityLoadManager.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
4
2017-12-18T20:10:16.000Z
2021-02-07T21:21:24.000Z
SDKs/CryCode/3.7.0/CryEngine/CryEntitySystem/EntityLoadManager.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
null
null
null
SDKs/CryCode/3.7.0/CryEngine/CryEntitySystem/EntityLoadManager.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
3
2019-03-11T21:36:15.000Z
2021-02-07T21:21:26.000Z
/************************************************************************* Crytek Source File. Copyright (C), Crytek Studios, 2001-2010. ------------------------------------------------------------------------- $Id$ $DateTime$ Description: Handles management for loading of entities ------------------------------------------------------------------------- History: - 15:03:2010: Created by Kevin Kirst *************************************************************************/ #include "stdafx.h" #include "EntityLoadManager.h" #include "EntityPoolManager.h" #include "EntitySystem.h" #include "Entity.h" #include "EntityLayer.h" #include "INetwork.h" ////////////////////////////////////////////////////////////////////////// CEntityLoadManager::CEntityLoadManager(CEntitySystem *pEntitySystem) : m_pEntitySystem(pEntitySystem) , m_bSWLoading(false) { assert(m_pEntitySystem); } ////////////////////////////////////////////////////////////////////////// CEntityLoadManager::~CEntityLoadManager() { stl::free_container(m_queuedAttachments); stl::free_container(m_queuedFlowgraphs); } ////////////////////////////////////////////////////////////////////////// void CEntityLoadManager::Reset() { m_clonedLayerIds.clear(); } ////////////////////////////////////////////////////////////////////////// bool CEntityLoadManager::LoadEntities(XmlNodeRef &entitiesNode, bool bIsLoadingLevelFile, const Vec3 &segmentOffset, std::vector<IEntity *> *outGlobalEntityIds, std::vector<IEntity *> *outLocalEntityIds) { bool bResult = false; m_bSWLoading = gEnv->p3DEngine->IsSegmentOperationInProgress(); if (entitiesNode && ReserveEntityIds(entitiesNode)) { PrepareBatchCreation(entitiesNode->getChildCount()); bResult = ParseEntities(entitiesNode, bIsLoadingLevelFile, segmentOffset, outGlobalEntityIds, outLocalEntityIds); OnBatchCreationCompleted(); } return bResult; } ////////////////////////////////////////////////////////////////////////// void CEntityLoadManager::SetupHeldLayer(const char* pLayerName) { // Look up the layer with this name. Note that normally only layers that can be // dynamically loaded will be in here, but we have a hack in ObjectLayerManager to make // one of these for every layer. CEntityLayer* pLayer = m_pEntitySystem->FindLayer(pLayerName); // Walk up the layer tree until we find the top level parent. That's what we group held // entities by. while (pLayer != NULL) { const string& parentName = pLayer->GetParentName(); if (parentName.empty()) break; pLayer = m_pEntitySystem->FindLayer(parentName.c_str()); } if (!gEnv->IsEditor()) CRY_ASSERT_MESSAGE(pLayer != NULL, "All layers should be in the entity system, level may need to be reexported"); if (pLayer != NULL) { int heldLayerIdx = -1; // Go through our held layers, looking for one with the parent name for (size_t i = 0; i < m_heldLayers.size(); ++i) { if (m_heldLayers[i].m_layerName == pLayer->GetName()) { heldLayerIdx = i; break; } } // Crc the original layer name and add it to the map. If the layer is held we // store the index, or -1 if it isn't held. uint32 layerCrc = gEnv->pSystem->GetCrc32Gen()->GetCRC32(pLayerName); m_layerNameMap[layerCrc] = heldLayerIdx; } } bool CEntityLoadManager::IsHeldLayer(XmlNodeRef& entityNode) { if (m_heldLayers.empty()) return false; const char* pLayerName = entityNode->getAttr("Layer"); uint32 layerCrc = gEnv->pSystem->GetCrc32Gen()->GetCRC32(pLayerName); std::map<uint32, int>::iterator it = m_layerNameMap.find(layerCrc); // First time we've seen this layer, cache off info for it if (it == m_layerNameMap.end()) { SetupHeldLayer(pLayerName); it = m_layerNameMap.find(layerCrc); if (it == m_layerNameMap.end()) return false; } int heldLayerIdx = it->second; // If this is a held layer, cache off the creation info and return true (don't add) if (heldLayerIdx != -1) { m_heldLayers[heldLayerIdx].m_entities.push_back(entityNode); return true; } else { return false; } } void CEntityLoadManager::HoldLayerEntities(const char* pLayerName) { m_heldLayers.resize(m_heldLayers.size() + 1); SHeldLayer& heldLayer = m_heldLayers[m_heldLayers.size() - 1]; heldLayer.m_layerName = pLayerName; } void CEntityLoadManager::CloneHeldLayerEntities(const char* pLayerName, const Vec3& localOffset, const Matrix34& l2w, const char** pIncludeLayers, int numIncludeLayers) { int heldLayerIdx = -1; // Get the index of the held layer for (size_t i = 0; i < m_heldLayers.size(); ++i) { if (m_heldLayers[i].m_layerName == pLayerName) { heldLayerIdx = i; break; } } if (heldLayerIdx == -1) { CRY_ASSERT_MESSAGE(0, "Trying to add a layer that wasn't held"); return; } // Allocate a map for storing the mapping from the original entity ids to the cloned ones int cloneIdx = (int)m_clonedLayerIds.size(); m_clonedLayerIds.resize(cloneIdx+1); TClonedIds& clonedIds = m_clonedLayerIds[cloneIdx]; // Get all the held entities for this layer std::vector<XmlNodeRef>& entities = m_heldLayers[heldLayerIdx].m_entities; CEntityPoolManager *pEntityPoolManager = m_pEntitySystem->GetEntityPoolManager(); assert(pEntityPoolManager); const bool bEnablePoolUse = pEntityPoolManager->IsUsingPools(); const int nSize=entities.size(); for (int i = 0; i < nSize; i++) { XmlNodeRef entityNode = entities[i]; const char* pLayerName = entityNode->getAttr("Layer"); bool isIncluded = (numIncludeLayers > 0) ? false : true; // Check if this layer is in our include list for (int j = 0; j < numIncludeLayers; ++j) { if (strcmp(pLayerName, pIncludeLayers[j]) == 0) { isIncluded = true; break; } } if (!isIncluded) continue; ////////////////////////////////////////////////////////////////////////// // // Copy/paste from CEntityLoadManager::ParseEntities // INDENT_LOG_DURING_SCOPE (true, "Parsing entity '%s'", entityNode->getAttr("Name")); bool bSuccess = false; SEntityLoadParams loadParams; if (ExtractEntityLoadParams(entityNode, loadParams, Vec3(0,0,0), true)) { // ONLY REAL CHANGES //////////////////////////////////////////////////// Matrix34 local(Matrix33(loadParams.spawnParams.qRotation)); local.SetTranslation(loadParams.spawnParams.vPosition - localOffset); Matrix34 world = l2w * local; // If this entity has a parent, keep the transform local EntityId parentId; if (entityNode->getAttr("ParentId", parentId)) { local.SetTranslation(loadParams.spawnParams.vPosition); world = local; } loadParams.spawnParams.vPosition = world.GetTranslation(); loadParams.spawnParams.qRotation = Quat(world); EntityId origId = loadParams.spawnParams.id; loadParams.spawnParams.id = m_pEntitySystem->GenerateEntityId(true); loadParams.clonedLayerId = cloneIdx; ////////////////////////////////////////////////////////////////////////// if (bEnablePoolUse && loadParams.spawnParams.bCreatedThroughPool) { CEntityPoolManager *pPoolManager = m_pEntitySystem->GetEntityPoolManager(); bSuccess = (pPoolManager && pPoolManager->AddPoolBookmark(loadParams)); } // Default to just creating the entity if (!bSuccess) { EntityId usingId = 0; // if we just want to reload this entity's properties if (entityNode->haveAttr("ReloadProperties")) { EntityId id; entityNode->getAttr("EntityId", id); loadParams.pReuseEntity = m_pEntitySystem->GetEntityFromID(id); } bSuccess = CreateEntity(loadParams, usingId, true); } if (!bSuccess) { string sName = entityNode->getAttr("Name"); EntityWarning("CEntityLoadManager::ParseEntities : Failed when parsing entity \'%s\'", sName.empty() ? "Unknown" : sName.c_str()); } else { // If we successfully cloned the entity, save the mapping from original id to cloned clonedIds[origId] = loadParams.spawnParams.id; m_clonedEntitiesTemp.push_back(loadParams.spawnParams.id); } } // // End copy/paste // ////////////////////////////////////////////////////////////////////////// } // All attachment parent ids will be for the source copy, so we need to remap that id // to the cloned one. TQueuedAttachments::iterator itQueuedAttachment = m_queuedAttachments.begin(); TQueuedAttachments::iterator itQueuedAttachmentEnd = m_queuedAttachments.end(); for (; itQueuedAttachment != itQueuedAttachmentEnd; ++itQueuedAttachment) { SEntityAttachment& entityAttachment = *itQueuedAttachment; entityAttachment.parent = m_pEntitySystem->GetClonedEntityId(entityAttachment.parent, entityAttachment.child); } // Now that all the cloned ids are ready, go though all the entities we just cloned // and update the ids for any entity links. for (std::vector<EntityId>::iterator it = m_clonedEntitiesTemp.begin(); it != m_clonedEntitiesTemp.end(); ++it) { IEntity* pEntity = m_pEntitySystem->GetEntity(*it); if (pEntity != NULL) { IEntityLink* pLink = pEntity->GetEntityLinks(); while (pLink != NULL) { pLink->entityId = m_pEntitySystem->GetClonedEntityId(pLink->entityId, *it); pLink = pLink->next; } } } m_clonedEntitiesTemp.clear(); OnBatchCreationCompleted(); } void CEntityLoadManager::ReleaseHeldEntities() { m_heldLayers.clear(); m_layerNameMap.clear(); } ////////////////////////////////////////////////////////////////////////// //bool CEntityLoadManager::CreateEntities(TEntityLoadParamsContainer &container) //{ // bool bResult = container.empty(); // // if (!bResult) // { // PrepareBatchCreation(container.size()); // // bResult = true; // TEntityLoadParamsContainer::iterator itLoadParams = container.begin(); // TEntityLoadParamsContainer::iterator itLoadParamsEnd = container.end(); // for (; itLoadParams != itLoadParamsEnd; ++itLoadParams) // { // bResult &= CreateEntity(*itLoadParams); // } // // OnBatchCreationCompleted(); // } // // return bResult; //} ////////////////////////////////////////////////////////////////////////// bool CEntityLoadManager::ReserveEntityIds(XmlNodeRef &entitiesNode) { assert( entitiesNode ); bool bResult = false; // Reserve the Ids to coop with dynamic entity spawning that may happen during this stage const int iChildCount = (entitiesNode ? entitiesNode->getChildCount() : 0); for (int i = 0; i < iChildCount; ++i) { XmlNodeRef entityNode = entitiesNode->getChild(i); if (entityNode && entityNode->isTag("Entity")) { EntityId entityId; EntityGUID guid; if (entityNode->getAttr("EntityId", entityId)) { m_pEntitySystem->ReserveEntityId(entityId); bResult = true; } else if(entityNode->getAttr("EntityGuid", guid)) { bResult = true; } else { // entity has no ID assigned bResult = true; } } } return bResult; } ////////////////////////////////////////////////////////////////////////// bool CEntityLoadManager::CanParseEntity(XmlNodeRef &entityNode, std::vector<IEntity *> *outGlobalEntityIds) { assert( entityNode ); bool bResult = true; if (!entityNode) return bResult; int nMinSpec = -1; if (entityNode->getAttr("MinSpec", nMinSpec) && nMinSpec > 0) { static ICVar *e_obj_quality(gEnv->pConsole->GetCVar("e_ObjQuality")); int obj_quality = (e_obj_quality ? e_obj_quality->GetIVal() : 0); // If the entity minimal spec is higher then the current server object quality this entity will not be loaded. bResult = (obj_quality >= nMinSpec || obj_quality == 0); } int globalInSW = 0; if(m_bSWLoading && outGlobalEntityIds && entityNode && entityNode->getAttr("GlobalInSW", globalInSW) && globalInSW) { EntityGUID guid; if(entityNode->getAttr("EntityGuid", guid)) { EntityId id = gEnv->pEntitySystem->FindEntityByGuid(guid); if(IEntity *pEntity = gEnv->pEntitySystem->GetEntity(id)) { #ifdef SEG_WORLD pEntity->SetLocalSeg(false); #endif outGlobalEntityIds->push_back(pEntity); } } // In segmented world, global entity will not be loaded while streaming each segment bResult &= false; } if (bResult) { const char* pLayerName = entityNode->getAttr("Layer"); CEntityLayer* pLayer = m_pEntitySystem->FindLayer( pLayerName ); if (pLayer) bResult = !pLayer->IsSkippedBySpec(); } return bResult; } ////////////////////////////////////////////////////////////////////////// bool CEntityLoadManager::ParseEntities(XmlNodeRef &entitiesNode, bool bIsLoadingLevelFile, const Vec3 &segmentOffset, std::vector<IEntity *> *outGlobalEntityIds, std::vector<IEntity *> *outLocalEntityIds) { #if !defined(SYS_ENV_AS_STRUCT) assert(gEnv); PREFAST_ASSUME(gEnv); #endif assert(entitiesNode); bool bResult = true; CEntityPoolManager *pEntityPoolManager = m_pEntitySystem->GetEntityPoolManager(); assert(pEntityPoolManager); const bool bEnablePoolUse = pEntityPoolManager->IsUsingPools(); const int iChildCount = entitiesNode->getChildCount(); CryLog ("Parsing %u entities...", iChildCount); INDENT_LOG_DURING_SCOPE(); for (int i = 0; i < iChildCount; ++i) { //Update loading screen and important tick functions SYNCHRONOUS_LOADING_TICK(); XmlNodeRef entityNode = entitiesNode->getChild(i); if (entityNode && entityNode->isTag("Entity") && CanParseEntity(entityNode, outGlobalEntityIds)) { // Create entities only if they are not in an held layer and we are not in editor game mode. if (!IsHeldLayer(entityNode) && !gEnv->IsEditorGameMode()) { INDENT_LOG_DURING_SCOPE (true, "Parsing entity '%s'", entityNode->getAttr("Name")); bool bSuccess = false; SEntityLoadParams loadParams; if (ExtractEntityLoadParams(entityNode, loadParams, segmentOffset, true)) { if (bEnablePoolUse && loadParams.spawnParams.bCreatedThroughPool) { CEntityPoolManager *pPoolManager = m_pEntitySystem->GetEntityPoolManager(); bSuccess = (pPoolManager && pPoolManager->AddPoolBookmark(loadParams)); } // Default to just creating the entity if (!bSuccess) { EntityId usingId = 0; // if we just want to reload this entity's properties if (entityNode->haveAttr("ReloadProperties")) { EntityId id; entityNode->getAttr("EntityId", id); loadParams.pReuseEntity = m_pEntitySystem->GetEntityFromID(id); } bSuccess = CreateEntity(loadParams, usingId, bIsLoadingLevelFile); if(m_bSWLoading && outLocalEntityIds && usingId) { if (IEntity *pEntity = m_pEntitySystem->GetEntity(usingId)) { #ifdef SEG_WORLD pEntity->SetLocalSeg(true); #endif outLocalEntityIds->push_back(pEntity); } } } } if (!bSuccess) { string sName = entityNode->getAttr("Name"); EntityWarning("CEntityLoadManager::ParseEntities : Failed when parsing entity \'%s\'", sName.empty() ? "Unknown" : sName.c_str()); } bResult &= bSuccess; } } if (0 == (i&7)) { gEnv->pNetwork->SyncWithGame(eNGS_FrameStart); gEnv->pNetwork->SyncWithGame(eNGS_FrameEnd); gEnv->pNetwork->SyncWithGame(eNGS_WakeNetwork); } } return bResult; } ////////////////////////////////////////////////////////////////////////// bool CEntityLoadManager::ExtractEntityLoadParams(XmlNodeRef &entityNode, SEntityLoadParams &outLoadParams, const Vec3 &segmentOffset,bool bWarningMsg) const { assert(entityNode); bool bResult = true; const char *sEntityClass = entityNode->getAttr("EntityClass"); const char *sEntityName = entityNode->getAttr("Name"); IEntityClass *pClass = m_pEntitySystem->GetClassRegistry()->FindClass(sEntityClass); if (pClass) { SEntitySpawnParams &spawnParams = outLoadParams.spawnParams; outLoadParams.spawnParams.entityNode = entityNode; // Load spawn parameters from xml node. spawnParams.pClass = pClass; spawnParams.sName = sEntityName; spawnParams.sLayerName = entityNode->getAttr("Layer"); // Entities loaded from the xml cannot be fully deleted in single player. if (!gEnv->bMultiplayer) spawnParams.nFlags |= ENTITY_FLAG_UNREMOVABLE; Vec3 pos(Vec3Constants<float>::fVec3_Zero); Quat rot(Quat::CreateIdentity()); Vec3 scale(Vec3Constants<float>::fVec3_One); entityNode->getAttr("Pos", pos); entityNode->getAttr("Rotate", rot); entityNode->getAttr("Scale", scale); /*Ang3 vAngles; if (entityNode->getAttr("Angles", vAngles)) { spawnParams.qRotation.SetRotationXYZ(vAngles); }*/ spawnParams.vPosition = pos; spawnParams.qRotation = rot; spawnParams.vScale = scale; spawnParams.id = 0; if(!gEnv->pEntitySystem->EntitiesUseGUIDs()) { entityNode->getAttr("EntityId", spawnParams.id); } entityNode->getAttr("EntityGuid", spawnParams.guid); ISegmentsManager *pSM = gEnv->p3DEngine->GetSegmentsManager(); if(pSM) { Vec2 coordInSW(Vec2Constants<float>::fVec2_Zero); if(entityNode->getAttr("CoordInSW", coordInSW)) pSM->GlobalSegVecToLocalSegVec(pos, coordInSW, spawnParams.vPosition); EntityGUID parentGuid; if(!entityNode->getAttr("ParentGuid", parentGuid)) spawnParams.vPosition += segmentOffset; } // Get flags. //bool bRecvShadow = true; // true by default (do not change, it must be coordinated with editor export) bool bGoodOccluder = false; // false by default (do not change, it must be coordinated with editor export) bool bOutdoorOnly = false; bool bNoDecals = false; int nCastShadowMinSpec = CONFIG_LOW_SPEC; entityNode->getAttr("CastShadowMinSpec", nCastShadowMinSpec); //entityNode->getAttr("RecvShadow", bRecvShadow); entityNode->getAttr("GoodOccluder", bGoodOccluder); entityNode->getAttr("OutdoorOnly", bOutdoorOnly); entityNode->getAttr("NoDecals", bNoDecals); static ICVar* pObjShadowCastSpec = gEnv->pConsole->GetCVar("e_ObjShadowCastSpec"); if(nCastShadowMinSpec <= pObjShadowCastSpec->GetIVal()) { spawnParams.nFlags |= ENTITY_FLAG_CASTSHADOW; } //if (bRecvShadow) //spawnParams.nFlags |= ENTITY_FLAG_RECVSHADOW; if (bGoodOccluder) spawnParams.nFlags |= ENTITY_FLAG_GOOD_OCCLUDER; if(bOutdoorOnly) spawnParams.nFlags |= ENTITY_FLAG_OUTDOORONLY; if(bNoDecals) spawnParams.nFlags |= ENTITY_FLAG_NO_DECALNODE_DECALS; const char *sArchetypeName = entityNode->getAttr("Archetype"); if (sArchetypeName && sArchetypeName[0]) { MEMSTAT_CONTEXT_FMT(EMemStatContextTypes::MSC_Other, 0, "%s", sArchetypeName); spawnParams.pArchetype = m_pEntitySystem->LoadEntityArchetype(sArchetypeName); if (!spawnParams.pArchetype) { EntityWarning("Archetype %s used by entity %s cannot be found! Entity cannot be loaded.", sArchetypeName, spawnParams.sName); bResult = false; } } entityNode->getAttr("CreatedThroughPool", spawnParams.bCreatedThroughPool); if (!spawnParams.bCreatedThroughPool) { // Check if forced via its class CEntityPoolManager *pPoolManager = m_pEntitySystem->GetEntityPoolManager(); spawnParams.bCreatedThroughPool = (pPoolManager && pPoolManager->IsClassForcedBookmarked(pClass)); } } else // No entity class found! { if (bWarningMsg) EntityWarning("Entity class %s used by entity %s cannot be found! Entity cannot be loaded.", sEntityClass, sEntityName); bResult = false; } return bResult; } ////////////////////////////////////////////////////////////////////////// bool CEntityLoadManager::ExtractEntityLoadParams(XmlNodeRef &entityNode, SEntitySpawnParams &spawnParams) const { SEntityLoadParams loadParams; bool bRes=ExtractEntityLoadParams(entityNode,loadParams,Vec3(0,0,0),false); spawnParams=loadParams.spawnParams; return(bRes); } ////////////////////////////////////////////////////////////////////////// bool CEntityLoadManager::CreateEntity(XmlNodeRef &entityNode,SEntitySpawnParams &pParams,EntityId &outUsingId) { SEntityLoadParams loadParams; loadParams.spawnParams=pParams; loadParams.spawnParams.entityNode=entityNode; if ((loadParams.spawnParams.id==0) && ((loadParams.spawnParams.pClass->GetFlags() & ECLF_DO_NOT_SPAWN_AS_STATIC) == 0)) { // If ID is not set we generate a static ID. loadParams.spawnParams.id=m_pEntitySystem->GenerateEntityId(true); } return(CreateEntity(loadParams,outUsingId,true)); } ////////////////////////////////////////////////////////////////////////// bool CEntityLoadManager::CreateEntity(SEntityLoadParams &loadParams, EntityId &outUsingId, bool bIsLoadingLevellFile) { MEMSTAT_CONTEXT_FMT(EMemStatContextTypes::MSC_Entity, 0, "Entity %s", loadParams.spawnParams.pClass->GetName()); bool bResult = true; outUsingId = 0; XmlNodeRef &entityNode = loadParams.spawnParams.entityNode; SEntitySpawnParams &spawnParams = loadParams.spawnParams; uint32 entityGuid = 0; if(entityNode) { // Only runtime prefabs should have GUID id's const char* entityGuidStr = entityNode->getAttr("Id"); if (entityGuidStr[0] != '\0') { entityGuid = gEnv->pSystem->GetCrc32Gen()->GetCRC32Lowercase(entityGuidStr); } } IEntity *pSpawnedEntity = NULL; bool bWasSpawned = false; if (loadParams.pReuseEntity) { // Attempt to reload pSpawnedEntity = (loadParams.pReuseEntity->ReloadEntity(loadParams) ? loadParams.pReuseEntity : NULL); } else if (m_pEntitySystem->OnBeforeSpawn(spawnParams)) { // Create a new one pSpawnedEntity = m_pEntitySystem->SpawnEntity(spawnParams, false); bWasSpawned = true; } if (bResult && pSpawnedEntity) { m_pEntitySystem->AddEntityToLayer(spawnParams.sLayerName, pSpawnedEntity->GetId()); CEntity *pCSpawnedEntity = (CEntity*)pSpawnedEntity; pCSpawnedEntity->SetLoadedFromLevelFile(bIsLoadingLevellFile); pCSpawnedEntity->SetCloneLayerId(loadParams.clonedLayerId); const char *szMtlName(NULL); if (spawnParams.pArchetype) { IScriptTable* pArchetypeProperties=spawnParams.pArchetype->GetProperties(); if (pArchetypeProperties) { pArchetypeProperties->GetValue("PrototypeMaterial",szMtlName); } } if (entityNode) { // Create needed proxies if (entityNode->findChild("Area")) { pSpawnedEntity->CreateProxy(ENTITY_PROXY_AREA); } if (entityNode->findChild("Rope")) { pSpawnedEntity->CreateProxy(ENTITY_PROXY_ROPE); } if (entityNode->findChild("ClipVolume")) { pSpawnedEntity->CreateProxy(ENTITY_PROXY_CLIPVOLUME); } if (spawnParams.pClass) { const char* pClassName = spawnParams.pClass->GetName(); if (pClassName && !strcmp(pClassName, "Light")) { IEntityRenderProxyPtr pRP = crycomponent_cast<IEntityRenderProxyPtr> (pSpawnedEntity->CreateProxy(ENTITY_PROXY_RENDER)); if (pRP) { pRP->SerializeXML(entityNode, true); int nMinSpec = -1; if (entityNode->getAttr("MinSpec", nMinSpec) && nMinSpec >= 0) pRP->GetRenderNode()->SetMinSpec(nMinSpec); } } } // If we have an instance material, we use it... if (entityNode->haveAttr("Material")) { szMtlName = entityNode->getAttr("Material"); } // Prepare the entity from Xml if it was just spawned if (pCSpawnedEntity && bWasSpawned) { if (IEntityPropertyHandler* pPropertyHandler = pCSpawnedEntity->GetClass()->GetPropertyHandler()) pPropertyHandler->LoadEntityXMLProperties(pCSpawnedEntity, entityNode); if (IEntityEventHandler* pEventHandler = pCSpawnedEntity->GetClass()->GetEventHandler()) pEventHandler->LoadEntityXMLEvents(pCSpawnedEntity, entityNode); // Serialize script proxy. CScriptProxy *pScriptProxy = pCSpawnedEntity->GetScriptProxy(); if (pScriptProxy) pScriptProxy->SerializeXML(entityNode, true); } } // If any material has to be set... if (szMtlName && *szMtlName != 0) { // ... we load it... IMaterial *pMtl = gEnv->p3DEngine->GetMaterialManager()->LoadMaterial(szMtlName); if (pMtl) { // ... and set it... pSpawnedEntity->SetMaterial(pMtl); } } if (bWasSpawned) { const bool bInited = m_pEntitySystem->InitEntity(pSpawnedEntity, spawnParams); if (!bInited) { // Failed to initialise an entity, need to bail or we'll crash return true; } } else { m_pEntitySystem->OnEntityReused(pSpawnedEntity, spawnParams); if (pCSpawnedEntity && loadParams.bCallInit) { CScriptProxy *pScriptProxy = pCSpawnedEntity->GetScriptProxy(); if (pScriptProxy) pScriptProxy->CallInitEvent(true); } } if (entityNode) { ////////////////////////////////////////////////////////////////////////// // Load geom entity (Must be before serializing proxies. ////////////////////////////////////////////////////////////////////////// if (spawnParams.pClass->GetFlags() & ECLF_DEFAULT) { // Check if it have geometry. const char *sGeom = entityNode->getAttr("Geometry"); if (sGeom[0] != 0) { // check if character. const char *ext = PathUtil::GetExt(sGeom); if (stricmp(ext,CRY_SKEL_FILE_EXT) == 0 || stricmp(ext,CRY_CHARACTER_DEFINITION_FILE_EXT) == 0 || stricmp(ext,CRY_ANIM_GEOMETRY_FILE_EXT) == 0) { pSpawnedEntity->LoadCharacter( 0,sGeom,IEntity::EF_AUTO_PHYSICALIZE ); } else { pSpawnedEntity->LoadGeometry( 0,sGeom,0,IEntity::EF_AUTO_PHYSICALIZE ); } } } ////////////////////////////////////////////////////////////////////////// // Serialize all entity proxies except Script proxy after initialization. if (pCSpawnedEntity) { CScriptProxy *pScriptProxy = pCSpawnedEntity->GetScriptProxy(); pCSpawnedEntity->SerializeXML_ExceptScriptProxy( entityNode, true ); } const char *attachmentType = entityNode->getAttr("AttachmentType"); const char *attachmentTarget = entityNode->getAttr("AttachmentTarget"); int flags = 0; if (strcmp(attachmentType, "GeomCacheNode") == 0) { flags |= IEntity::ATTACHMENT_GEOMCACHENODE; } else if (strcmp(attachmentType, "CharacterBone") == 0) { flags |= IEntity::ATTACHMENT_CHARACTERBONE; } // Add attachment to parent. if(m_pEntitySystem->EntitiesUseGUIDs()) { EntityGUID nParentGuid = 0; if (entityNode->getAttr( "ParentGuid",nParentGuid )) { AddQueuedAttachment(0, nParentGuid, spawnParams.id, spawnParams.vPosition, spawnParams.qRotation, spawnParams.vScale, false, flags, attachmentTarget); } } else if (entityGuid == 0) { EntityId nParentId = 0; if (entityNode->getAttr("ParentId", nParentId)) { AddQueuedAttachment(nParentId, 0, spawnParams.id, spawnParams.vPosition, spawnParams.qRotation, spawnParams.vScale, false, flags, attachmentTarget); } } else { const char* pParentGuid = entityNode->getAttr("Parent"); if (pParentGuid[0] != '\0') { uint32 parentGuid = gEnv->pSystem->GetCrc32Gen()->GetCRC32Lowercase(pParentGuid); AddQueuedAttachment((EntityId)parentGuid, 0, spawnParams.id, spawnParams.vPosition, spawnParams.qRotation, spawnParams.vScale, true, flags, attachmentTarget); } } // check for a flow graph // only store them for later serialization as the FG proxy relies // on all EntityGUIDs already loaded if (entityNode->findChild("FlowGraph")) { AddQueuedFlowgraph(pSpawnedEntity, entityNode); } // Load entity links. XmlNodeRef linksNode = entityNode->findChild("EntityLinks"); if (linksNode) { const int iChildCount = linksNode->getChildCount(); for (int i = 0; i < iChildCount; ++i) { XmlNodeRef linkNode = linksNode->getChild(i); if (linkNode) { if (entityGuid == 0) { EntityId targetId = 0; EntityGUID targetGuid = 0; if (gEnv->pEntitySystem->EntitiesUseGUIDs()) linkNode->getAttr( "TargetGuid",targetGuid ); else linkNode->getAttr("TargetId", targetId); const char *sLinkName = linkNode->getAttr("Name"); Quat relRot(IDENTITY); Vec3 relPos(IDENTITY); pSpawnedEntity->AddEntityLink(sLinkName, targetId, targetGuid); } else { // If this is a runtime prefab we're spawning, queue the entity // link for later, since it has a guid target id we need to look up. AddQueuedEntityLink(pSpawnedEntity, linkNode); } } } } // Hide entity in game. Done after potential RenderProxy is created, so it catches the Hide if (bWasSpawned) { bool bHiddenInGame = false; entityNode->getAttr("HiddenInGame", bHiddenInGame); if (bHiddenInGame) pSpawnedEntity->Hide(true); } int nMinSpec = -1; if (entityNode->getAttr("MinSpec", nMinSpec) && nMinSpec >= 0) { if (IEntityRenderProxy *pRenderProxy = (IEntityRenderProxy*)pSpawnedEntity->GetProxy(ENTITY_PROXY_RENDER)) pRenderProxy->GetRenderNode()->SetMinSpec(nMinSpec); } } } if (!bResult) { EntityWarning("[CEntityLoadManager::CreateEntity] Entity Load Failed: %s (%s)", spawnParams.sName, spawnParams.pClass->GetName()); } outUsingId = (pSpawnedEntity ? pSpawnedEntity->GetId() : 0); if (outUsingId != 0 && entityGuid != 0) { m_guidToId[entityGuid] = outUsingId; } return bResult; } ////////////////////////////////////////////////////////////////////////// void CEntityLoadManager::PrepareBatchCreation(int nSize) { m_queuedAttachments.clear(); m_queuedFlowgraphs.clear(); m_queuedAttachments.reserve(nSize); m_queuedFlowgraphs.reserve(nSize); m_guidToId.clear(); } ////////////////////////////////////////////////////////////////////////// void CEntityLoadManager::AddQueuedAttachment(EntityId nParent, EntityGUID nParentGuid, EntityId nChild, const Vec3& pos, const Quat& rot, const Vec3& scale, bool guid, const int flags, const char *target) { SEntityAttachment entityAttachment; entityAttachment.child = nChild; entityAttachment.parent = nParent; entityAttachment.parentGuid = nParentGuid; entityAttachment.pos = pos; entityAttachment.rot = rot; entityAttachment.scale = scale; entityAttachment.guid = guid; entityAttachment.flags = flags; entityAttachment.target = target; m_queuedAttachments.push_back(entityAttachment); } ////////////////////////////////////////////////////////////////////////// void CEntityLoadManager::AddQueuedFlowgraph(IEntity *pEntity, XmlNodeRef &pNode) { SQueuedFlowGraph f; f.pEntity = pEntity; f.pNode = pNode; m_queuedFlowgraphs.push_back(f); } ////////////////////////////////////////////////////////////////////////// void CEntityLoadManager::AddQueuedEntityLink(IEntity *pEntity, XmlNodeRef &pNode) { SQueuedFlowGraph f; f.pEntity = pEntity; f.pNode = pNode; m_queuedEntityLinks.push_back(f); } ////////////////////////////////////////////////////////////////////////// void CEntityLoadManager::OnBatchCreationCompleted() { CEntityPoolManager *pEntityPoolManager = m_pEntitySystem->GetEntityPoolManager(); assert(pEntityPoolManager); // Load attachments TQueuedAttachments::iterator itQueuedAttachment = m_queuedAttachments.begin(); TQueuedAttachments::iterator itQueuedAttachmentEnd = m_queuedAttachments.end(); for (; itQueuedAttachment != itQueuedAttachmentEnd; ++itQueuedAttachment) { const SEntityAttachment &entityAttachment = *itQueuedAttachment; IEntity *pChild = m_pEntitySystem->GetEntity(entityAttachment.child); if (pChild) { EntityId parentId = entityAttachment.parent; if (m_pEntitySystem->EntitiesUseGUIDs()) parentId = m_pEntitySystem->FindEntityByGuid(entityAttachment.parentGuid); else if (entityAttachment.guid) parentId = m_guidToId[(uint32)entityAttachment.parent]; IEntity *pParent = m_pEntitySystem->GetEntity(parentId); if (pParent) { SChildAttachParams attachParams(entityAttachment.flags, entityAttachment.target.c_str()); pParent->AttachChild(pChild, attachParams); pChild->SetLocalTM(Matrix34::Create(entityAttachment.scale, entityAttachment.rot, entityAttachment.pos)); } else if (pEntityPoolManager->IsEntityBookmarked(entityAttachment.parent)) { pEntityPoolManager->AddAttachmentToBookmark(entityAttachment.parent, entityAttachment); } } } m_queuedAttachments.clear(); // Load flowgraphs TQueuedFlowgraphs::iterator itQueuedFlowgraph = m_queuedFlowgraphs.begin(); TQueuedFlowgraphs::iterator itQueuedFlowgraphEnd = m_queuedFlowgraphs.end(); for (; itQueuedFlowgraph != itQueuedFlowgraphEnd; ++itQueuedFlowgraph) { SQueuedFlowGraph &f = *itQueuedFlowgraph; if (f.pEntity) { IEntityProxyPtr pProxy = f.pEntity->CreateProxy(ENTITY_PROXY_FLOWGRAPH); if (pProxy) pProxy->SerializeXML(f.pNode, true); } } m_queuedFlowgraphs.clear(); // Load entity links TQueuedFlowgraphs::iterator itQueuedEntityLink = m_queuedEntityLinks.begin(); TQueuedFlowgraphs::iterator itQueuedEntityLinkEnd = m_queuedEntityLinks.end(); for (; itQueuedEntityLink != itQueuedEntityLinkEnd; ++itQueuedEntityLink) { SQueuedFlowGraph &f = *itQueuedEntityLink; if (f.pEntity) { const char* targetGuidStr = f.pNode->getAttr("TargetId"); if (targetGuidStr[0] != '\0') { EntityId targetId = FindEntityByEditorGuid(targetGuidStr); const char *sLinkName = f.pNode->getAttr("Name"); Quat relRot(IDENTITY); Vec3 relPos(IDENTITY); f.pEntity->AddEntityLink(sLinkName, targetId, 0); } } } stl::free_container(m_queuedEntityLinks); stl::free_container(m_guidToId); } ////////////////////////////////////////////////////////////////////////// void CEntityLoadManager::ResolveLinks() { if(!m_pEntitySystem->EntitiesUseGUIDs()) return; IEntityItPtr pIt = m_pEntitySystem->GetEntityIterator(); pIt->MoveFirst(); while (IEntity* pEntity = pIt->Next()) { IEntityLink* pLink = pEntity->GetEntityLinks(); while (pLink) { if (pLink->entityId == 0) pLink->entityId = m_pEntitySystem->FindEntityByGuid(pLink->entityGuid); pLink = pLink->next; } } } ////////////////////////////////////////////////////////////////////////// EntityId CEntityLoadManager::GetClonedId(int clonedLayerId, EntityId originalId) { if (clonedLayerId >= 0 && clonedLayerId < (int)m_clonedLayerIds.size()) { TClonedIds& clonedIds = m_clonedLayerIds[clonedLayerId]; return clonedIds[originalId]; } return 0; } ////////////////////////////////////////////////////////////////////////// EntityId CEntityLoadManager::FindEntityByEditorGuid(const char* pGuid) const { uint32 guidCrc = gEnv->pSystem->GetCrc32Gen()->GetCRC32Lowercase(pGuid); TGuidToId::const_iterator it = m_guidToId.find(guidCrc); if (it != m_guidToId.end()) return it->second; return INVALID_ENTITYID; }
30.557726
204
0.668449
amrhead
c2ba81a29826d6addde581df2c9f48c2fb6cc0f4
283
hpp
C++
includes/AbstractClasses/AbstractVisitable.hpp
edubrunaldi/poker-bot
b851aa86c73a5b1b6c586439fbc01ccecac8c0f1
[ "MIT" ]
null
null
null
includes/AbstractClasses/AbstractVisitable.hpp
edubrunaldi/poker-bot
b851aa86c73a5b1b6c586439fbc01ccecac8c0f1
[ "MIT" ]
null
null
null
includes/AbstractClasses/AbstractVisitable.hpp
edubrunaldi/poker-bot
b851aa86c73a5b1b6c586439fbc01ccecac8c0f1
[ "MIT" ]
2
2019-09-08T10:40:21.000Z
2021-01-06T16:17:37.000Z
//Visitor // Created by xima on 02/08/19. // #ifndef POKER_BOT_ABSTRACTVISITABLE_HPP #define POKER_BOT_ABSTRACTVISITABLE_HPP class AbstractVisitor; class AbstractVisitable { public: virtual void accept(AbstractVisitor& visitor) = 0; }; #endif //POKER_BOT_ABSTRACTVISITABLE_HPP
17.6875
52
0.798587
edubrunaldi
c2bc4824d65d2d58cbaa73d68063130e5989eb6a
5,427
cpp
C++
examples/ndtest.cpp
Brillist/libutl
e55c2af091ba1101a1d0608db2830e279ec95d16
[ "MIT" ]
1
2021-09-14T06:12:58.000Z
2021-09-14T06:12:58.000Z
examples/ndtest.cpp
Brillist/libutl
e55c2af091ba1101a1d0608db2830e279ec95d16
[ "MIT" ]
null
null
null
examples/ndtest.cpp
Brillist/libutl
e55c2af091ba1101a1d0608db2830e279ec95d16
[ "MIT" ]
2
2019-05-13T23:04:31.000Z
2021-09-14T06:12:59.000Z
#include <libutl/libutl.h> #include <libutl/Application.h> #include <libutl/Array.h> #include <libutl/BufferedFDstream.h> #include <libutl/CmdLineArgs.h> #include <libutl/Thread.h> #undef new #include <algorithm> #include <libutl/gblnew_macros.h> //////////////////////////////////////////////////////////////////////////////////////////////////// class AllocatorThread : public utl::Thread { UTL_CLASS_DECL_ABC(AllocatorThread, utl::Thread); public: AllocatorThread(size_t* sizes, size_t numSizes, size_t numRuns) { _sizes = sizes; _numSizes = numSizes; _numRuns = numRuns; _ptrs = (void**)malloc(numSizes * sizeof(void*)); } void* run(void*); protected: virtual void oneRun() = 0; protected: size_t* _sizes; void** _ptrs; size_t _numSizes; size_t _numRuns; private: void init() { ABORT(); } void deInit() { free(_ptrs); } }; //////////////////////////////////////////////////////////////////////////////////////////////////// void* AllocatorThread::run(void*) { for (size_t i = 0; i != _numRuns; ++i) oneRun(); return nullptr; } //////////////////////////////////////////////////////////////////////////////////////////////////// class MallocFreeThread : public AllocatorThread { UTL_CLASS_DECL(MallocFreeThread, AllocatorThread); UTL_CLASS_DEFID; public: MallocFreeThread(size_t* sizes, size_t numSizes, size_t numRuns) : AllocatorThread(sizes, numSizes, numRuns) { } protected: virtual void oneRun() { size_t* sizes = _sizes; size_t s = _numSizes; size_t* sizesLim = sizes + s; void** ptrs = _ptrs; void** ptrsLim = ptrs + s; // allocate size_t* sp = sizes; void** pp = ptrs; for (; sp != sizesLim; ++sp, ++pp) { *pp = malloc(*sp); } // free for (pp = ptrs; pp != ptrsLim; ++pp) { free(*pp); } } }; //////////////////////////////////////////////////////////////////////////////////////////////////// class NewDeleteThread : public AllocatorThread { UTL_CLASS_DECL(NewDeleteThread, AllocatorThread); UTL_CLASS_DEFID; public: NewDeleteThread(size_t* sizes, size_t numSizes, size_t numRuns) : AllocatorThread(sizes, numSizes, numRuns) { } protected: virtual void oneRun() { size_t* sizes = _sizes; size_t s = _numSizes; size_t* sizesLim = sizes + s; void** ptrs = _ptrs; void** ptrsLim = ptrs + s; // allocate size_t* sp = sizes; void** pp = ptrs; for (; sp != sizesLim; ++sp, ++pp) { *pp = new byte_t[*sp]; } // free for (pp = ptrs; pp != ptrsLim; ++pp) { delete[](byte_t*) * pp; } } }; //////////////////////////////////////////////////////////////////////////////////////////////////// UTL_CLASS_IMPL_ABC(AllocatorThread); UTL_CLASS_IMPL(MallocFreeThread); UTL_CLASS_IMPL(NewDeleteThread); //////////////////////////////////////////////////////////////////////////////////////////////////// UTL_NS_USE; UTL_APP(Test); UTL_MAIN_RL(Test); //////////////////////////////////////////////////////////////////////////////////////////////////// int Test::run(int argc, char** argv) { CmdLineArgs args(argc, argv); // check if help was requested if (args.isSet("h") || args.isSet("help")) { cerr << "ndtest [-t threads] [-r runs/thread] [-c count] [-m]" << endl; return 1; } // set # of threads size_t numThreads = 1; String arg; if (args.isSet("t", arg)) { numThreads = Uint(arg); if (numThreads < 1) numThreads = 1; if (numThreads > 256) numThreads = 256; } // set # of runs per thread size_t numRuns = 1; if (args.isSet("r", arg)) { numRuns = Uint(arg); if (numRuns < 1) numRuns = 1; if (numRuns > KB(64)) numRuns = KB(64); } // set # of allocations of each size size_t numAllocs = 256; if (args.isSet("c", arg)) { numAllocs = Uint(arg); if (numAllocs < 1) numAllocs = 1; if (numAllocs > KB(16)) numAllocs = KB(16); } // use malloc/free ? bool useMalloc = args.isSet("m"); // create the array of block sizes size_t numSizes = numAllocs * (256 / 8); size_t* sizes = (size_t*)malloc(numSizes * sizeof(size_t)); size_t* sizePtr = sizes; for (size_t i = 0; i != numAllocs; ++i) { for (size_t j = 8; j <= 256; j += 8) { *sizePtr++ = j; } } // spawn threads Array threads(false); for (size_t i = 0; i != numThreads; ++i) { Thread* t; if (useMalloc) t = new MallocFreeThread(sizes, numSizes, numRuns); else t = new NewDeleteThread(sizes, numSizes, numRuns); threads += t; t->start(nullptr, true); } cout << "threads are started.." << endl; // join on threads for (size_t i = 0; i != numThreads; ++i) { Thread* t = (Thread*)threads[i]; t->join(); } cout << "threads are done!" << endl; // clean up (why not?) free(sizes); return 0; }
22.518672
100
0.466556
Brillist
c2bcd01ad7f86285605f55f77d8810315c11520b
5,399
cpp
C++
source/Model.cpp
xdanieldzd/libfrenda
ea10a413f6aac567c29d8dac43b0ab5cb207167a
[ "MIT" ]
1
2019-10-05T01:39:01.000Z
2019-10-05T01:39:01.000Z
source/Model.cpp
xdanieldzd/libfrenda
ea10a413f6aac567c29d8dac43b0ab5cb207167a
[ "MIT" ]
null
null
null
source/Model.cpp
xdanieldzd/libfrenda
ea10a413f6aac567c29d8dac43b0ab5cb207167a
[ "MIT" ]
2
2016-12-11T08:43:32.000Z
2022-01-02T07:55:33.000Z
/*------------------------------------------------------------ MODEL.CPP - "Frenda 3D" model loader -------------------------------------------------------------*/ #include "include/frenda.h" using namespace std; namespace frenda { const std::string Model::formatTag = "Fr3Dv04"; Model::Model(frenda::System *s, std::string filename) { sys = s; sys->debugLog("%s -> loading model '%s'...\n", __PRETTY_FUNCTION__, filename.c_str()); memset(&header, 0, sizeof(HeaderStruct)); memset(&textureList, 0, sizeof(TextureListStruct)); memset(&geometryList, 0, sizeof(GeometryListStruct)); load(filename); } Model::~Model() { for(uint32 i = 0; i < geometryList.geometryCount; i++) { //sys->debugLog(" -> unloading geometry %lu/%lu '%s'...\n", (i + 1), geometryList.geometryCount, geometryList.geometry[i].geometryName); for(uint32 j = 0; j < textureList.textureCount; j++) { //sys->debugLog(" -> unloading vertex list %lu/%lu\n", (j + 1), textureList.textureCount); delete[] geometryList.geometry[i].vertexLists[j].vertices; } delete[] geometryList.geometry[i].vertexLists; } delete[] geometryList.geometry; delete[] geometryList.geometryOffsets; for(uint32 i = 0; i < textureList.textureCount; i++) { if(textureList.textures[i].texture != NULL) plx_txr_destroy(textureList.textures[i].texture); } delete[] textureList.textures; delete[] textureList.textureOffsets; } void Model::load(std::string filename) { uint8 *data; file_t fd = fs_open(filename.c_str(), O_RDONLY); data = new uint8[fs_total(fd)]; fs_read(fd, data, fs_total(fd)); fs_close(fd); uint32 rofs; memcpy(&header, data, sizeof(HeaderStruct)); assert_msg(Model::formatTag.compare(header.formatTag) == 0, "Wrong model format OR version"); /* Read textures */ rofs = header.textureOffset; memcpy(&textureList.textureCount, &data[rofs], 4); rofs += 4; textureList.textureOffsets = new uint32[textureList.textureCount]; memcpy(textureList.textureOffsets, &data[rofs], (sizeof(uint32) * textureList.textureCount)); textureList.textures = new TextureDataStruct[textureList.textureCount]; for(uint32 i = 0; i < textureList.textureCount; i++) { //sys->debugLog(" -> loading texture %lu/%lu from 0x%08lx\n", (i + 1), textureList.textureCount, textureList.textureOffsets[i]); rofs = textureList.textureOffsets[i]; int w = 0, h = 0, fmt = 0, byte_count = 0; memcpy(&w, &data[rofs], 4); memcpy(&h, &data[rofs + 0x4], 4); memcpy(&fmt, &data[rofs + 0x8], 4); memcpy(&byte_count, &data[rofs + 0xC], 4); uint16 *tdata = new uint16[byte_count]; memcpy(tdata, &data[rofs + 0x10], byte_count); TextureDataStruct *t = &textureList.textures[i]; int pvrfmt = -1; if(fmt == KOS_IMG_FMT_ARGB1555) pvrfmt = PVR_TXRFMT_ARGB1555; else if(fmt == KOS_IMG_FMT_ARGB4444) pvrfmt = PVR_TXRFMT_ARGB4444; assert_msg(pvrfmt != -1, "Cannot determine PVR texture format"); t->texture = plx_txr_canvas(w, h, pvrfmt); pvr_txr_load_ex(tdata, t->texture->ptr, t->texture->w, t->texture->h, PVR_TXRLOAD_16BPP); delete[] tdata; } /* Read geometry */ rofs = header.geometryOffset; memcpy(&geometryList.geometryCount, &data[rofs], 4); rofs += 4; geometryList.geometryOffsets = new uint32[geometryList.geometryCount]; memcpy(geometryList.geometryOffsets, &data[rofs], (sizeof(uint32) * geometryList.geometryCount)); geometryList.geometry = new GeometryStruct[geometryList.geometryCount]; for(uint32 i = 0; i < geometryList.geometryCount; i++) { rofs = geometryList.geometryOffsets[i]; memcpy(&geometryList.geometry[i].geometryName, &data[rofs], 16); rofs += 16; //sys->debugLog(" -> loading geometry %lu/%lu '%s' from 0x%08lx...\n", (i + 1), geometryList.geometryCount, geometryList.geometry[i].geometryName, geometryList.geometryOffsets[i]); geometryList.geometry[i].vertexLists = new VertexListStruct[textureList.textureCount]; for(uint32 j = 0; j < textureList.textureCount; j++) { memcpy(&geometryList.geometry[i].vertexLists[j].vertexCount, &data[rofs], 4); rofs += 4; //sys->debugLog(" -> loading vertex list %lu/%lu, %lu vertices\n", (j + 1), textureList.textureCount, geometryList.geometry[i].vertexLists[j].vertexCount); geometryList.geometry[i].vertexLists[j].vertices = new pvr_vertex_t[geometryList.geometry[i].vertexLists[j].vertexCount]; if(geometryList.geometry[i].vertexLists[j].vertexCount > 0) { memcpy(geometryList.geometry[i].vertexLists[j].vertices, &data[rofs], (sizeof(pvr_vertex_t) * geometryList.geometry[i].vertexLists[j].vertexCount)); rofs += (sizeof(pvr_vertex_t) * geometryList.geometry[i].vertexLists[j].vertexCount); } } } delete[] data; } void Model::render(frenda::PVR *pvr) { for(uint32 i = 0; i < geometryList.geometryCount; i++) { render(pvr, i); } } void Model::render(frenda::PVR *pvr, uint32 geometryID) { for(uint32 i = 0; i < textureList.textureCount; i++) { if(geometryList.geometry[geometryID].vertexLists[i].vertexCount > 0) { pvr->setTexture(PVR_LIST_TR_POLY, textureList.textures[i].texture); pvr->sendVertexList(PVR_LIST_TR_POLY, geometryList.geometry[geometryID].vertexLists[i].vertices, (int)geometryList.geometry[geometryID].vertexLists[i].vertexCount); } } } }
34.608974
183
0.668828
xdanieldzd
c2bece07afb04a783cebe7bf3a55bf11cb7343ee
2,645
cpp
C++
VereEngine-Tools/GenerateTrees.cpp
VereWolf/VereEngine
6b5453554cef1ef5d5dbf58206806198a3beec35
[ "Zlib", "MIT" ]
4
2017-06-21T19:37:00.000Z
2017-07-14T06:21:40.000Z
VereEngine-Tools/GenerateTrees.cpp
VereWolf/VereEngine
6b5453554cef1ef5d5dbf58206806198a3beec35
[ "Zlib", "MIT" ]
null
null
null
VereEngine-Tools/GenerateTrees.cpp
VereWolf/VereEngine
6b5453554cef1ef5d5dbf58206806198a3beec35
[ "Zlib", "MIT" ]
1
2017-09-30T06:10:38.000Z
2017-09-30T06:10:38.000Z
#include "stdafx.h" #include "GenerateTrees.h" GenerateTrees::GenerateTrees() { SetFolderName(L"Calc_Trees"); } void GenerateTrees::Generate(int randomValue) { srand(randomValue); std::vector<int> TM; std::vector<Float4> TM2; TM.resize(512 * 512, 0); TM2.resize(512 * 512, Float4(0.0f, 0.0f, 0.0f, 0.0f)); bool B = true; int S = 0; std::vector<int> pos(4 * 8 * 8 + 1, -1); for (int i = 512; i > 0; i /= 2) { for (int by = 0; by < 512 / i; by++) { for (int bx = 0; bx < 512 / i; bx++) { int x = bx * i + rand() % i; int y = by * i + rand() % i; B = true; for (int sy = -2 * i; sy < 3 * i; sy++) { for (int sx = -2 * i; sx < 3 * i; sx++) { int px = VMath::Wrap(sx + x, 512); int py = VMath::Wrap(sy + y, 512); if (TM[py * 512 + px] > 0) { B = false; } } } if (B == true) { TM[y * 512 + x] = pow(VMath::Clamp(i, 0, 64), 0.5f); ++S; } } } } for (int i = 0; i < 512 * 512; i++) { if (TM[i] > 0) { switch (TM[i]) { case 1: TM2[i].x = 1; TM2[i].y = 0; TM2[i].z = 0; TM[i] = 1; break; case 2: TM2[i].x = 0; TM2[i].y = 1; TM2[i].z = 0; TM[i] = 2; break; case 3: TM2[i].x = 0; TM2[i].y = 1; TM2[i].z = 0; TM[i] = 2; break; case 4: TM2[i].x = 0; TM2[i].y = 0; TM2[i].z = 1; TM[i] = 3; break; case 5: TM2[i].x = 1; TM2[i].y = 1; TM2[i].z = 1; TM[i] = 4; break; case 6: TM2[i].x = 1; TM2[i].y = 1; TM2[i].z = 1; TM[i] = 4; break; case 7: TM2[i].x = 1; TM2[i].y = 1; TM2[i].z = 1; TM[i] = 4; break; case 8: TM2[i].x = 1; TM2[i].y = 1; TM2[i].z = 1; TM[i] = 4; break; } } } std::vector<float> trees(S * 2, -1); int j = 0; int k = 0; for (int by = 0; by < 8; ++by) { for (int bx = 0; bx < 8; ++bx) { for (int i = 1; i < 5; ++i) { pos[k] = j; ++k; for (int cy = 0; cy < 64; ++cy) { for (int cx = 0; cx < 64; ++cx) { int x = bx * 64 + cx; int y = by * 64 + cy; if (TM[y * 512 + x] == i) { trees[2 * j] = (float)x * 0.00195694716f; trees[2 * j + 1] = (float)y * 0.00195694716f; ++j; } } } } } } pos.back() = trees.size() / 2; DataStreaming::SaveImage(GetWholeFilePatch(L"Trees.jpg"), &TM2, 512, 512); DataStreaming::SaveFile(GetWholeFilePatch("Trees_index.raw"), &pos[0], 1, pos.size(), sizeof(int)); DataStreaming::SaveFile(GetWholeFilePatch("Trees_tiles.raw"), &trees[0], 1, trees.size(), sizeof(float)); }
17.287582
106
0.438563
VereWolf