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
109
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
48.5k
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
693aeabc53dcfc994d0188e2eb63a1f5a1f21dab
707
cc
C++
tools/asm.cc
nlewycky/x64asm
66dcdef5dba596cb0a51edde1910194d079e704c
[ "Apache-2.0" ]
453
2015-04-24T13:57:43.000Z
2022-03-16T16:38:53.000Z
tools/asm.cc
nlewycky/x64asm
66dcdef5dba596cb0a51edde1910194d079e704c
[ "Apache-2.0" ]
71
2015-04-15T20:52:13.000Z
2018-07-29T18:08:22.000Z
tools/asm.cc
nlewycky/x64asm
66dcdef5dba596cb0a51edde1910194d079e704c
[ "Apache-2.0" ]
67
2015-05-07T06:44:47.000Z
2022-02-25T03:46:24.000Z
#include <iostream> #include <string> #include "include/x64asm.h" using namespace std; using namespace x64asm; using namespace cpputil; /** A simple test program. Reads att syntax and prints human readable hex. */ int main(int argc, char** argv) { Code c; cin >> c; if(failed(cin)) { cerr << endl << "Parse error encountered." << endl; cerr << fail_msg(cin); return 1; } cout << endl; cout << "Assembling..." << endl << c << endl << endl << endl; auto result = Assembler().assemble(c); if(!result.first) { cout << "Could not assemble; 8-bit jump offset was given but target was further away." << endl; } else { cout << result.second << endl; } return 0; }
21.424242
99
0.623762
nlewycky
69487bfe15f2bd11008fa77ab7d09fc840276e09
616
cpp
C++
5_Classes_Objects/5_7_Using_this.cpp
YinHk-Forks/CPP-Notes
7dd1895d44cd3773e5f2603cbc3b02d174285b05
[ "MIT" ]
4
2020-12-30T15:16:39.000Z
2021-11-07T17:17:02.000Z
5_Classes_Objects/5_7_Using_this.cpp
YinHk-Forks/CPP-Notes
7dd1895d44cd3773e5f2603cbc3b02d174285b05
[ "MIT" ]
null
null
null
5_Classes_Objects/5_7_Using_this.cpp
YinHk-Forks/CPP-Notes
7dd1895d44cd3773e5f2603cbc3b02d174285b05
[ "MIT" ]
3
2021-04-03T08:00:36.000Z
2022-01-01T06:19:58.000Z
// // CPP-Notes // // Created by Akshay Raj Gollahalli on 23/05/16. // Copyright © 2016 Akshay Raj Gollahalli. All rights reserved. // #include <cstdio> class Some_class { int _s = 0; public: void setter(int i) {_s = i;} int getter(); }; int Some_class::getter() { printf("%p\n", this); // pointing to this object return _s; } int main(int argc, char ** argv){ int aa = 10; Some_class a; a.setter(aa); printf("%d\n", a.getter()); printf("%p\n", &a); // pointing to `a` object // The address of `a` should be equal to Some_class return 0; }
17.111111
64
0.573052
YinHk-Forks
694f982089cc73d568a5877fdc50792cfdcb9515
1,063
cpp
C++
math/gauss_jordan_elimination.cpp
KSkun/OI-Templates
a193da03a531700858fe45d455a946074bda5007
[ "WTFPL" ]
12
2018-03-30T08:44:07.000Z
2021-09-03T07:43:56.000Z
math/gauss_jordan_elimination.cpp
KSkun/OI-Templates
a193da03a531700858fe45d455a946074bda5007
[ "WTFPL" ]
null
null
null
math/gauss_jordan_elimination.cpp
KSkun/OI-Templates
a193da03a531700858fe45d455a946074bda5007
[ "WTFPL" ]
1
2018-08-09T01:39:30.000Z
2018-08-09T01:39:30.000Z
// Code by KSkun, 2018/3 #include <cstdio> #include <cmath> #include <algorithm> const int MAXN = 105; const double EPS = 1e-10; int n; double mat[MAXN][MAXN]; /* * Gauss-Jordan Elimination. */ inline bool gauss() { for(int i = 1; i <= n; i++) { int r = i; for(int j = i + 1; j <= n; j++) { if(std::fabs(mat[r][i]) < std::fabs(mat[j][i])) r = j; } if(r != i) { for(int j = 1; j <= n + 1; j++) std::swap(mat[i][j], mat[r][j]); } if(fabs(mat[i][i]) < EPS) return false; for(int j = 1; j <= n; j++) { if(j != i) { double t = mat[j][i] / mat[i][i]; for(int k = i + 1; k <= n + 1; k++) mat[j][k] -= mat[i][k] * t; } } } for(int i = 1; i <= n; i++) mat[i][n + 1] /= mat[i][i]; return true; } // an example of G-J Elimination // can pass luogu p3389 int main() { scanf("%d", &n); for(int i = 1; i <= n; i++) { for(int j = 1; j <= n + 1; j++) { scanf("%lf", &mat[i][j]); } } if(gauss()) { for(int i = 1; i <= n; i++) { printf("%.2lf\n", mat[i][n + 1]); } } else { puts("No Solution"); } return 0; }
18.982143
67
0.469426
KSkun
694fe8e3d950363ddea27ecc4790bde9216e9409
4,490
cpp
C++
src/util/string_set.cpp
bingmann/distributed-string-sorting
238bdfd5f6139f2f14e33aed7b4d9bbffac5d295
[ "BSD-2-Clause" ]
3
2018-10-24T22:15:17.000Z
2019-09-21T22:56:05.000Z
src/util/string_set.cpp
bingmann/distributed-string-sorting
238bdfd5f6139f2f14e33aed7b4d9bbffac5d295
[ "BSD-2-Clause" ]
null
null
null
src/util/string_set.cpp
bingmann/distributed-string-sorting
238bdfd5f6139f2f14e33aed7b4d9bbffac5d295
[ "BSD-2-Clause" ]
1
2019-10-16T06:13:28.000Z
2019-10-16T06:13:28.000Z
/******************************************************************************* * string_sorting/util/string_set.cpp * * Copyright (C) 2018 Florian Kurpicz <florian.kurpicz@tu-dortmund.de> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #include <utility> #include "mpi/environment.hpp" #include "util/string_set.hpp" namespace dsss { string_set::string_set() { } string_set::string_set(std::vector<dsss::char_type>&& string_data) : strings_raw_data_(std::move(string_data)) { strings_.emplace_back(strings_raw_data_.data()); for (size_t i = 0; i < strings_raw_data_.size();) { while (strings_raw_data_[i++] != 0) { } strings_.emplace_back(strings_raw_data_.data() + i); } if constexpr (debug) { dsss::mpi::environment env; size_t min_length = strings_raw_data_.size(); size_t max_length = 0; for (size_t i = 0; i < strings_.size() - 1; ++i) { const size_t cur_length = strings_[i + 1] - strings_[i] - 1; min_length = std::min(min_length, cur_length); max_length = std::max(max_length, cur_length); } size_t avg_length = (strings_raw_data_.size() - strings_.size()) / (strings_.size() - 1); for (int32_t rank = 0; rank < env.size(); ++rank) { if (rank == env.rank()) { std::cout << rank << ": min " << min_length << ", max " << max_length << ", avg " << avg_length << ", count " << strings_.size() - 1 << std::endl; } env.barrier(); } } // Delete pointer to the end of the local strings. No string does start here. strings_.pop_back(); } string_set::string_set(string_set&& other) { auto* old_ptr = other.strings_raw_data_.data(); strings_raw_data_ = std::move(other.strings_raw_data_); strings_ = std::move(other.strings_); int64_t offset = std::distance(old_ptr, strings_raw_data_.data()); for (auto& str : strings_) { str -= offset; } } string_set& string_set::operator =(string_set&& other) { if (this != &other) { const auto* old_ptr = other.strings_raw_data_.data(); strings_raw_data_ = std::move(other.strings_raw_data_); strings_ = std::move(other.strings_); const auto* new_ptr = strings_raw_data_.data(); int64_t offset = std::distance(old_ptr, new_ptr); for (auto& str : strings_) { str -= offset; } } return *this; } void string_set::update(std::vector<dsss::char_type>&& string_data) { strings_raw_data_ = std::move(string_data); strings_.clear(); strings_.emplace_back(strings_raw_data_.data()); for (size_t i = 0; i < strings_raw_data_.size(); ++i) { while (strings_raw_data_[i++] != 0) { } strings_.emplace_back(strings_raw_data_.data() + i); } if constexpr (debug) { dsss::mpi::environment env; size_t min_length = strings_raw_data_.size(); size_t max_length = 0; for (size_t i = 0; i < strings_.size() - 1; ++i) { const size_t cur_length = strings_[i + 1] - strings_[i] - 1; min_length = std::min(min_length, cur_length); max_length = std::max(max_length, cur_length); } size_t avg_length = (strings_raw_data_.size() - strings_.size()) / (strings_.size() - 1); for (int32_t rank = 0; rank < env.size(); ++rank) { if (rank == env.rank()) { std::cout << rank << ": min " << min_length << ", max " << max_length << ", avg " << avg_length << ", count " << strings_.size() - 1 << std::endl; } env.barrier(); } } // Delete pointer to the end of the local strings. No string does start here. strings_.pop_back(); } void string_set::update(std::vector<dsss::string>&& string_data) { strings_ = std::move(string_data); } dsss::string string_set::operator [](const size_t idx) const { return strings_[idx]; } std::vector<dsss::string>::const_iterator string_set::cbegin() { return strings_.cbegin(); } size_t string_set::size() const { return strings_.size(); } dsss::string* string_set::strings() { return strings_.data(); } dsss::string string_set::front() { return strings_.front(); } dsss::string string_set::back() { return strings_.back(); } std::vector<dsss::char_type>& string_set::data_container() { return strings_raw_data_; } dsss::string string_set::raw_data() { return strings_raw_data_.data(); } } // namespace dsss /******************************************************************************/
34.274809
80
0.607572
bingmann
695d2429c239313e0a659752b1e56fc266b7c4e5
3,615
hpp
C++
include/battery.hpp
findNextStep/next_dwm_status
cef24ec51c2a856bb4c7b113a7f2a791b85c432f
[ "MIT" ]
null
null
null
include/battery.hpp
findNextStep/next_dwm_status
cef24ec51c2a856bb4c7b113a7f2a791b85c432f
[ "MIT" ]
null
null
null
include/battery.hpp
findNextStep/next_dwm_status
cef24ec51c2a856bb4c7b113a7f2a791b85c432f
[ "MIT" ]
null
null
null
#pragma once #include <barPerSeconds.hpp> #include <fstream> #include <vector> #include <sstream> namespace nextDwmStatus { const std::string battery_file = "/sys/class/power_supply/"; const std::string power = "/current_now"; const std::string stat = "/status"; const std::string full = "/charge_full"; const std::string now = "/charge_now"; class battery : public barPerSeconds { private: const std::string battery_name; const std::string power_file; const std::string stat_file; const std::string full_file; const std::string now_file; std::string message; protected: static long long read_data(const std::string &file) { long long result; std::ifstream fs(file); fs >> result; return result; } virtual void per_second_task() { // copy from libqtile widget battery.py // see https://github.com/qtile/qtile/blob/v0.13.0/libqtile/widget/battery.py std::string stat; std::ifstream fs(stat_file); const std::vector<std::string> charging_icon = { "", "", "", "", "", "", "", }; const std::vector<std::string> discharging_icon = { "", "", "", "", "", "", "", "", "", "" }; const std::string unknow = ""; fs >> stat; using namespace std; if(stat == "Full") { // full charge message = "100%"; } else if(stat == "Discharging" || stat == "Not charging") { // work in battery const double full = read_data(full_file), now = read_data(now_file), power = read_data(power_file); if(power == 0) { message = "charge fail"; } else { const double time = now / power, perc = now / full; std::stringstream ss; ss << discharging_icon.at((perc - 0.001) * (discharging_icon.size() - 1)) << (int)(perc * 100) << "%" << (int)time << ":" << ((int)(time * 60) % 60); message = ss.str(); } } else if(stat == "Charging") { // charging const double full = read_data(full_file), now = read_data(now_file), power = read_data(power_file); if(power == 0) { message = "charge fail"; } else { const double time = (full - now) / power, perc = now / full; std::stringstream ss; ss << charging_icon.at((perc - 0.001) * (charging_icon.size() - 1)) << (int)(perc * 100) << "%" << (int)time << ":" << ((int)(time * 60) % 60); message = ss.str(); } } else if(stat == "Unknown") { const double full = read_data(full_file), now = read_data(now_file); const double perc = now / full; std::stringstream ss; ss << unknow << (int)(perc * 100) << "%"; message = ss.str(); } else { message = "unknow status " + stat; } } public: battery(): battery("BAT0") {} battery(const std::string &batteryName): battery_name(batteryName), power_file(battery_file + battery_name + power), stat_file(battery_file + battery_name + stat), full_file(battery_file + battery_name + full), now_file(battery_file + battery_name + now) {} virtual const std::string getStatus()const { return message; } }; }
36.15
165
0.506224
findNextStep
695d57e61440836679c80df7ae93a777714650fc
4,225
cpp
C++
source/FullView3dRenderer.cpp
xzrunner/wmv
dfa38476e6f8ca67ee1ba4486e5bd610b9f45eee
[ "MIT" ]
null
null
null
source/FullView3dRenderer.cpp
xzrunner/wmv
dfa38476e6f8ca67ee1ba4486e5bd610b9f45eee
[ "MIT" ]
null
null
null
source/FullView3dRenderer.cpp
xzrunner/wmv
dfa38476e6f8ca67ee1ba4486e5bd610b9f45eee
[ "MIT" ]
null
null
null
#include "terrainlab/FullView3dRenderer.h" #include <SM_Calc.h> #include <unirender/Device.h> #include <unirender/ShaderProgram.h> #include <unirender/DrawState.h> #include <unirender/Context.h> #include <shadertrans/ShaderTrans.h> #include <renderpipeline/UniformNames.h> #include <painting0/ModelMatUpdater.h> #include <painting3/Shader.h> #include <painting3/ViewMatUpdater.h> #include <painting3/ProjectMatUpdater.h> #include <terraintiler/GeoMipMapping.h> namespace { const char* vs = R"( #version 330 core layout (location = 0) in vec4 position; layout(std140) uniform UBO_VS { mat4 projection; mat4 view; mat4 model; } ubo_vs; out VS_OUT { vec3 frag_pos; } vs_out; void main() { vs_out.frag_pos = vec3(ubo_vs.model * position); gl_Position = ubo_vs.projection * ubo_vs.view * ubo_vs.model * position; } )"; const char* fs = R"( #version 330 core out vec4 FragColor; in VS_OUT { vec3 frag_pos; } fs_in; void main() { vec3 fdx = dFdx(fs_in.frag_pos); vec3 fdy = dFdy(fs_in.frag_pos); vec3 N = normalize(cross(fdx, fdy)); vec3 light_dir = normalize(vec3(0, -10, 10) - fs_in.frag_pos); float diff = max(dot(N, light_dir), 0.0); vec3 diffuse = diff * vec3(1.0, 1.0, 1.0); FragColor = vec4(diffuse, 1.0); } )"; } namespace terrainlab { FullView3dRenderer::FullView3dRenderer(const ur::Device& dev) { InitShader(dev); m_mipmap = std::make_shared<terraintiler::GeoMipMapping>(5, 5); } void FullView3dRenderer::Setup(std::shared_ptr<pt3::WindowContext>& wc) const { // static_cast<pt3::Shader*>(m_shader.get())->AddNotify(wc); } void FullView3dRenderer::Update(const ur::Device& dev) { auto w = m_mipmap->GetWidth(); auto h = m_mipmap->GetHeight(); for (size_t y = 0; y < h; ++y) { for (size_t x = 0; x < w; ++x) { m_mipmap->UpdateTile(dev, x, y); } } } void FullView3dRenderer::Draw(ur::Context& ctx, const sm::vec3& cam_pos, const sm::mat4& mt, bool debug_draw) const { // m_shader->Bind(); auto model_updater = m_shader->QueryUniformUpdater(ur::GetUpdaterTypeID<pt0::ModelMatUpdater>()); if (model_updater) { std::static_pointer_cast<pt0::ModelMatUpdater>(model_updater)->Update(mt); } ur::DrawState ds; ds.program = m_shader; if (debug_draw) { ds.render_state.rasterization_mode = ur::RasterizationMode::Line; } auto w = m_mipmap->GetWidth(); auto h = m_mipmap->GetHeight(); for (size_t y = 0; y < h; ++y) { for (size_t x = 0; x < w; ++x) { const float dist = sm::dis_pos3_to_pos3(cam_pos, sm::vec3(static_cast<float>(x), 0, static_cast<float>(y))); size_t lod_level = 5; if (dist < 2) { lod_level = 0; } else if (dist < 4) { lod_level = 1; } else if (dist < 8) { lod_level = 2; } else if (dist < 16) { lod_level = 3; } else if (dist < 32) { lod_level = 4; } else if (dist < 64) { lod_level = 5; } auto rd = m_mipmap->QueryRenderable(x, y, lod_level); if (!rd.va) { continue; } ds.vertex_array = rd.va; ctx.Draw(ur::PrimitiveType::Triangles, ds, nullptr); } } } void FullView3dRenderer::InitShader(const ur::Device& dev) { //std::vector<ur::VertexAttrib> layout; //layout.push_back(ur::VertexAttrib(rp::VERT_POSITION_NAME, 3, 4, 12, 0)); //rc.CreateVertexLayout(layout); std::vector<unsigned int> _vs, _fs; shadertrans::ShaderTrans::GLSL2SpirV(shadertrans::ShaderStage::VertexShader, vs, _vs); shadertrans::ShaderTrans::GLSL2SpirV(shadertrans::ShaderStage::PixelShader, fs, _fs); m_shader = dev.CreateShaderProgram(_vs, _fs); assert(m_shader); m_shader->AddUniformUpdater(std::make_shared<pt0::ModelMatUpdater>(*m_shader, "ubo_vs.model")); m_shader->AddUniformUpdater(std::make_shared<pt3::ViewMatUpdater>(*m_shader, "ubo_vs.view")); m_shader->AddUniformUpdater(std::make_shared<pt3::ProjectMatUpdater>(*m_shader, "ubo_vs.projection")); } }
25.920245
120
0.622722
xzrunner
695d8067491218d4501ece1e70ff73b4d287fea0
2,372
cpp
C++
spoj.3110.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
spoj.3110.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
spoj.3110.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
/* * spoj.3110.cpp * Copyright (C) 2021 Woshiluo Luo <woshiluo.luo@outlook.com> * * 「Two roads diverged in a wood,and I— * I took the one less traveled by, * And that has made all the difference.」 * * Distributed under terms of the GNU AGPLv3+ license. */ #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> typedef long long ll; typedef unsigned long long ull; inline bool isdigit( const char cur ) { return cur >= '0' && cur <= '9'; }/*{{{*/ template <class T> T Max( T a, T b ) { return a > b? a: b; } template <class T> T Min( T a, T b ) { return a < b? a: b; } template <class T> void chk_Max( T &a, T b ) { if( b > a ) a = b; } template <class T> void chk_Min( T &a, T b ) { if( b < a ) a = b; } template <typename T> T read() { T sum = 0, fl = 1; char ch = getchar(); for (; isdigit(ch) == 0; ch = getchar()) if (ch == '-') fl = -1; for (; isdigit(ch); ch = getchar()) sum = sum * 10 + ch - '0'; return sum * fl; } template <class T> T pow( T a, int p ) { T res = 1; while( p ) { if( p & 1 ) res = res * a; a = a * a; p >>= 1; } return res; }/*}}}*/ ll pow10[50]; int int_len( ll cur ) { int res = 0; while( cur ) { res ++; cur /= 10; } return res; } int get_pos( ll cur, int pos ) { int res = 0; while( pos ) { pos --; res = ( cur % 10 ); cur /= 10; } return res; } int len_allow( int cur ) { return ( cur / 2 ) + ( cur & 1 ); } void check( int bit[], int len ) { int cnt = 0; for( int i = 1; i <= len; i ++ ) { if( bit[i] > 18 ) return ; if( bit[i] != bit[ i - 1 ] ) cnt ++; } if( cnt == 1 ) { for( int i = 1; i <= 9; i ++ ) { } } } int main() { #ifdef woshiluo freopen( "spoj.3110.in", "r", stdin ); freopen( "spoj.3110.out", "w", stdout ); #endif int T = read<int>(); pow10[1] = 1; for( int i = 2; i <= 20; i ++ ) { pow10[i] = pow10[ i - 1 ] * 10LL; } while( T -- ) { ll n = read<ll>(); int len = int_len(n); for( int i = 1; i <= len; i ++ ) { bit[i] = ( n % 10 ); n /= 10; } for( int sta = 0; sta <= full_pow(len); sta ++ ) { ll cur = n; for( int i = 1; i <= len; i ++ ) { if( sta & ( 1 << ( i - 1 ) ) ) { bit[i] += 10; bit[ i + 1 ] -= 1; } } check(bit); for( int i = 1; i <= len; i ++ ) { if( sta & ( 1 << ( i - 1 ) ) ) { bit[i] -= 10; bit[ i + 1 ] += 1; } } } } }
18.825397
81
0.483558
woshiluo
69682c17cdab970b875faaae09fb844bed849ec8
3,377
cpp
C++
OverEngine/src/OverEngine/Physics/Collider2D.cpp
larrymason01/OverEngine
4e44fe8385cc1780f2189ee5135f70b1e69104fd
[ "MIT" ]
159
2020-03-16T14:46:46.000Z
2022-03-31T23:38:14.000Z
OverEngine/src/OverEngine/Physics/Collider2D.cpp
larrymason01/OverEngine
4e44fe8385cc1780f2189ee5135f70b1e69104fd
[ "MIT" ]
5
2020-11-22T14:40:20.000Z
2022-01-16T03:45:54.000Z
OverEngine/src/OverEngine/Physics/Collider2D.cpp
larrymason01/OverEngine
4e44fe8385cc1780f2189ee5135f70b1e69104fd
[ "MIT" ]
17
2020-06-01T05:58:32.000Z
2022-02-10T17:28:36.000Z
#include "pcheader.h" #include "Collider2D.h" #include "RigidBody2D.h" #include "OverEngine/Scene/TransformComponent.h" #include <box2d/b2_polygon_shape.h> #include <box2d/b2_circle_shape.h> namespace OverEngine { Ref<BoxCollisionShape2D> BoxCollisionShape2D::Create(const Vector2& size, const Vector2& offset, float rotation) { return CreateRef<BoxCollisionShape2D>(size, offset, rotation); } BoxCollisionShape2D::BoxCollisionShape2D(const Vector2& size, const Vector2& offset, float rotation) : m_Size(size), m_Rotation(rotation) { } void BoxCollisionShape2D::Invalidate(const Mat4x4& transform) { m_Shape.SetAsBox( m_Size.x / 2.0f, m_Size.y / 2.0f, { m_Offset.x, m_Offset.y }, m_Rotation ); std::array<b2Vec2, b2_maxPolygonVertices> transformedVertices; for (int i = 0; i < m_Shape.m_count; i++) { Vector4 vertex = Vector4{ m_Shape.m_vertices[i].x, m_Shape.m_vertices[i].y, 0.0f, 0.0f } * transform; transformedVertices[i] = b2Vec2(vertex.x, vertex.y); } m_Shape.Set(transformedVertices.data(), m_Shape.m_count); } Ref<CircleCollisionShape2D> CircleCollisionShape2D::Create(float radius) { return CreateRef<CircleCollisionShape2D>(radius); } CircleCollisionShape2D::CircleCollisionShape2D(float radius) : m_Radius(radius) { } void CircleCollisionShape2D::Invalidate(const Mat4x4& transform) { // TODO: Dynamic size m_Shape.m_p.Set(m_Offset.x, m_Offset.y); m_Shape.m_radius = m_Radius; } Ref<Collider2D> Collider2D::Create(const Collider2DProps& props) { return CreateRef<Collider2D>(props); } Collider2D::Collider2D(const Collider2DProps& props) : m_Props(props) { } Collider2D::~Collider2D() { if (m_FixtureHandle && m_BodyHandle && m_BodyHandle->m_BodyHandle) UnDeploy(); } void Collider2D::Deploy(RigidBody2D* rigidBody) { rigidBody->m_Colliders.push_back(shared_from_this()); m_BodyHandle = rigidBody; Invalidate(); } void Collider2D::UnDeploy() { m_BodyHandle->m_Colliders.erase(STD_CONTAINER_FIND(m_BodyHandle->m_Colliders, shared_from_this())); m_BodyHandle->m_BodyHandle->DestroyFixture(m_FixtureHandle); m_FixtureHandle = nullptr; m_BodyHandle = nullptr; } void Collider2D::Invalidate() { OE_CORE_ASSERT(m_BodyHandle && m_BodyHandle->m_BodyHandle, "Cannot (re)build a collider without a body or with an undeployed one.") OE_CORE_ASSERT(m_Props.Shape, "Cannot (re)build a collider with empty shape!"); if (m_FixtureHandle) m_BodyHandle->m_BodyHandle->DestroyFixture(m_FixtureHandle); b2FixtureDef def; auto& bodyTransform = m_BodyHandle->GetProps().AttachedEntity.GetComponent<TransformComponent>(); Mat4x4 shapeTransform = glm::inverse( glm::translate(Mat4x4(1.0f), { bodyTransform.GetPosition().x, bodyTransform.GetPosition().y, 0.0f }) * glm::rotate(Mat4x4(1.0f), glm::radians(bodyTransform.GetLocalEulerAngles().z), Vector3(0, 0, 1)) ) * m_Props.AttachedEntity.GetComponent<TransformComponent>().GetLocalToWorld(); def.shape = m_Props.Shape->GetBox2DShape(shapeTransform); def.friction = m_Props.Friction; def.restitution = m_Props.Bounciness; def.restitutionThreshold = m_Props.BouncinessThreshold; def.density = m_Props.Density; def.isSensor = m_Props.IsTrigger; m_FixtureHandle = m_BodyHandle->m_BodyHandle->CreateFixture(&def); } }
28.863248
133
0.73438
larrymason01
696a61fbdd22f698b70d7eabccf9db757f3d95a7
8,200
cxx
C++
xp_comm_proj/rd_dxf/src/dxfcir.cxx
avs/express-community
c699a68330d3b678b7e6bcea823e0891b874049c
[ "Apache-2.0" ]
3
2020-08-03T08:52:20.000Z
2021-04-10T11:55:49.000Z
xp_comm_proj/rd_dxf/src/dxfcir.cxx
avs/express-community
c699a68330d3b678b7e6bcea823e0891b874049c
[ "Apache-2.0" ]
null
null
null
xp_comm_proj/rd_dxf/src/dxfcir.cxx
avs/express-community
c699a68330d3b678b7e6bcea823e0891b874049c
[ "Apache-2.0" ]
1
2021-06-08T18:16:45.000Z
2021-06-08T18:16:45.000Z
/***************************************************************************** Copyright (c) 1995 by Advanced Visual Systems Inc. All Rights Reserved This software comprises unpublished confidential information of Advanced Visual Systems Inc. and may not be used, copied or made available to anyone, except in accordance with the license under which it is furnished. ****************************************************************************** Implementation of the DXFCircle class, which represents DXF circle objects. ****************************************************************************** *****************************************************************************/ #include <math.h> #include "dxfcir.hxx" #include "dxfprim.hxx" #include "blistcpp.hxx" #include "blistcpp.cxx" //## AWD: Added to resolve templates problem #include "dxfdefine.hxx" /********************* Macros and Manifest Constants **********************/ /* <none> */ /************************ Public Global Variables *************************/ /* <none> */ /************************ Private Type Definitions ************************/ /* <none> */ /******************* Private (Static) Global Variables ********************/ /* <none> */ /***************************************************************************** *********-------- Implementations of "DXFCircle" Methods --------********* *****************************************************************************/ /***************************************************************************** Method: DXFCircle::Make() Purpose: This is the static "virtual constructor" for the DXFCircle class. If the contents of the specified "group" object is recognized by this function as the start of the definition of a circle, then an instance of DXFCircle is created, and its attributes are read from the DXF file (via the "group" object). Params: group The DXFGroup object being used to read the DXF file. It is assumed that this object will initially contain the group that terminated the previous object definition. On exit, it will contain the group that terminates this object definition. State: It is assumed that the file pointer into the DXF file has been advanced into the BLOCKS or ENTITIES section. Returns: A pointer to a DXFCircle object (cast to DXFPrim *) if the current object was recognized as a DXF circle, or NULL if it wasn't. *****************************************************************************/ DXFPrim *DXFCircle::Make(DXFGroup &group,CLIST <DXFLayer> *firstLayer) { DXFPrim *instance = 0; if (group.DataCmp("CIRCLE")) instance = new DXFCircle(group, firstLayer); return instance; } /***************************************************************************** Method: DXFCircle::DXFCircle() Purpose: A Constructor for the DXFCircle class. Reads the center point and radius from the DXF file. Params: group The DXFGroup object being used to read the DXF file. It is assumed that this object will initially contain the group that terminated the previous object definition. On exit, it will contain the group that terminates this object definition. firstLayer start of the linked list fo LAYER information. This will be used to assign color if appropriate State: It is assumed that the file pointer into the DXF file has been advanced into the BLOCKS or ENTITIES section. *****************************************************************************/ DXFCircle::DXFCircle(DXFGroup &group, CLIST <DXFLayer> *firstLayer) : center(), radius(0.0) { isValid = 0; extrusion.SetX(0); extrusion.SetY(0); extrusion.SetZ(1); while (group.Read()) { if (group.Code() == 0) // stop at next entity definition break; switch (group.Code()) { case 10: // circle center x coordinate center.SetX(group.DataAsFloat()); break; case 20: // circle center y coordinate center.SetY(group.DataAsFloat()); break; case 30: // circle center z coordinate center.SetZ(group.DataAsDouble()); break; case 40: // circle radius radius = group.DataAsFloat(); break; case 210: extrusion.SetX(group.DataAsFloat()); break; case 220: extrusion.SetY(group.DataAsFloat()); break; case 230: extrusion.SetZ(group.DataAsFloat()); break; default: // we don't care about this group code DXFPrim::ReadCommon(group, firstLayer); // see if the base class wants it break; } } // Now that we have the circle data (radius, center), we need to // generate the connectivity information. // int m = GetNumPoints(); if (AddCellSet(m, 1, DXF_CELL_CHOOSE, DXF_CLOSED_POLYGON + DXF_CONVEX_POLYGON)) { if (group.ReverseNormals()) { for (int q = m - 1; q >= 0; q--) cellSetsTail->AddVertexIndex(q); } else { for (int q = 0; q < m; q++) cellSetsTail->AddVertexIndex(q); } isValid = 1; } } /***************************************************************************** Method: DXFCircle::GetPoints() Purpose: This function generates the vertices associated with this circle. The center and radius are given. The circle is assumed to lie in a plane parallel to the x-z plane. Params: array A float array in which to place the coordinates. It is assumed that this array is at least < GetNumPoints() > floats in length. offset An optional offset into the array, at which to start placing coordinates. Thus, if this parameter is supplied the array length must be < GetNumPoints() + offset > floats long. State: --- Returns: The number of *NUMBERS* (i.e. 3 times the number of vertices) placed in the array PLUS the starting offset, if any. *****************************************************************************/ int DXFCircle::GetPoints(float *array, int offset) { int i; DXFPoint3D Ax,Ay; int n = GetNumPoints(); float inc = 6.28318530718 / (float)(n-1); // 2*PI / n float X,Y,Z; float c=(extrusion.GetX()<0) ? (extrusion.GetX()*(-1)) : extrusion.GetX(); float d=(extrusion.GetY()<0) ? (extrusion.GetY()*(-1)) : extrusion.GetY(); float e=1.0/64.0; if((c<e) && (d<e)) { Ax.SetX(extrusion.GetZ()); Ax.SetY(0); Ax.SetZ(-1*extrusion.GetX()); } else { Ax.SetX(-1*extrusion.GetY()); Ax.SetY(extrusion.GetX()); Ax.SetZ(0); } float k=sqrt(1/(Ax.GetX()*Ax.GetX()+Ax.GetY()*Ax.GetY()+Ax.GetZ()*Ax.GetZ())); Ax.SetX(Ax.GetX()*k); Ax.SetY(Ax.GetY()*k); Ax.SetZ(Ax.GetZ()*k); Ay.SetX(extrusion.GetY()*Ax.GetZ()-extrusion.GetZ()*Ax.GetY()); Ay.SetY(extrusion.GetZ()*Ax.GetX()-extrusion.GetX()*Ax.GetZ()); Ay.SetZ(extrusion.GetX()*Ax.GetY()-extrusion.GetY()*Ax.GetX()); k=sqrt(1/(Ay.GetX()*Ay.GetX()+Ay.GetY()*Ay.GetY()+Ay.GetZ()*Ay.GetZ())); Ay.SetX(Ay.GetX()*k); Ay.SetY(Ay.GetY()*k); Ay.SetZ(Ay.GetZ()*k); printf("DXFCircle::GetPoints Az: %f %f %f Ax: %f %f %f Ay: %f %f %f \n",extrusion.GetX(),extrusion.GetY(),extrusion.GetZ(), Ax.GetX(),Ax.GetY(),Ax.GetZ(),Ay.GetX(),Ay.GetY(),Ay.GetZ()); for (i = 0, d = 0.0; i < n-1; i++, d += inc) { X = (radius * cos(d)) + center.GetX(); Y = (radius * sin(d)) + center.GetY(); Z = center.GetZ(); array[offset++]=X*Ax.GetX()+Y*Ay.GetX()+Z*extrusion.GetX(); array[offset++]=X*Ax.GetY()+Y*Ay.GetY()+Z*extrusion.GetY(); array[offset++]=X*Ax.GetZ()+Y*Ay.GetZ()+Z*extrusion.GetZ(); } X = radius + center.GetX(); Y = center.GetY(); Z = center.GetZ(); array[offset++]=X*Ax.GetX()+Y*Ay.GetX()+Z*extrusion.GetX(); array[offset++]=X*Ax.GetY()+Y*Ay.GetY()+Z*extrusion.GetY(); array[offset++]=X*Ax.GetZ()+Y*Ay.GetZ()+Z*extrusion.GetZ(); Dump(); return offset; } void DXFCircle::Dump() { float x, y, z; center.Get(&x, &y, &z); // printf(" Circle\n"); // printf(" Center = (%f, %f, %f)\n", x, y, z); // printf(" Radius = %f\n", radius); }
31.660232
126
0.547195
avs
696faac99d2c95ddade3fad87333224c891deae0
2,345
cpp
C++
C++/08_Heap/MEDIUM_MEETING_ROOMS.cpp
animeshramesh/interview-prep
882e8bc8b4653a713754ab31a3b08e05505be2bc
[ "Apache-2.0" ]
null
null
null
C++/08_Heap/MEDIUM_MEETING_ROOMS.cpp
animeshramesh/interview-prep
882e8bc8b4653a713754ab31a3b08e05505be2bc
[ "Apache-2.0" ]
null
null
null
C++/08_Heap/MEDIUM_MEETING_ROOMS.cpp
animeshramesh/interview-prep
882e8bc8b4653a713754ab31a3b08e05505be2bc
[ "Apache-2.0" ]
null
null
null
// Time complexity - O(n) // Space complexity - O(n), where n = number of intervals int minMeetingRooms(vector<Interval>& intervals) { int len = intervals.size(); int count = 0, maxCount = 0; vector<pair<int, int>> table; // total len of table should be 2xlen since we have both start and end for(int i=0; i<len; i++) { // pick up the start, mark with 1 table.push_back(pair<int, int>(intervals[i].start, 1)); // pick up the end, mark with -1 table.push_back(pair<int, int>(intervals[i].end, -1)); } // sort the vector with first - exactly what we need sort(table.begin(), table.end()); for(int i=0; i<table.size(); i++) { if(table[i].second == 1) count++; else count--; maxCount = max(count, maxCount); } return maxCount; } // Without using pairs int minMeetingRooms(vector<Interval>& intervals) { vector<int> starts, ends; for (const auto& i : intervals) { starts.push_back(i.start); ends.push_back(i.end); } sort(starts.begin(), starts.end()); sort(ends.begin(), ends.end()); int min_rooms = 0, cnt_rooms = 0; int s = 0, e = 0; while (s < starts.size()) { if (starts[s] < ends[e]) { ++cnt_rooms; // Acquire a room. // Update the min number of rooms. min_rooms = max(min_rooms, cnt_rooms); ++s; } else { --cnt_rooms; // Release a room. ++e; } } return min_rooms; } // There's another solution using min-heap or priority queue int minMeetingRooms(vector<Interval>& intervals) { sort(intervals.begin(), intervals.end(), [](Interval i1, Interval i2) {return i1.start < i2.start || (i1.start == i2.start && i1.end < i2.end);}) ; // Min heap // Why is there a greater than sign? auto comp = [](Interval i1, Interval i2){return i1.end > i2.end;}; priority_queue<Interval, vector<Interval>, decltype(comp)>pq(comp); int ans = 0; // Size of the heap correpsonds to the number of rooms currently in use for(auto interval : intervals) { while(!pq.empty() && pq.top().end <= interval.start) pq.pop(); pq.push(interval); ans = max(ans, pq.size()); } return ans; }
30.064103
104
0.565885
animeshramesh
69702480d8b79ff4e694a2454ca6fbdb760ac59d
4,163
hpp
C++
include/r3/tiled/r3-tiled-defn.hpp
ryantherileyman/riley-tiled-json-loader
b03edf3e375480d937f2692ae54f0046149a8f66
[ "MIT" ]
null
null
null
include/r3/tiled/r3-tiled-defn.hpp
ryantherileyman/riley-tiled-json-loader
b03edf3e375480d937f2692ae54f0046149a8f66
[ "MIT" ]
null
null
null
include/r3/tiled/r3-tiled-defn.hpp
ryantherileyman/riley-tiled-json-loader
b03edf3e375480d937f2692ae54f0046149a8f66
[ "MIT" ]
null
null
null
#include <optional> #include <string> #include <vector> #pragma once namespace r3 { namespace tiled { typedef enum class Tiled_CustomPropertyType { UNKNOWN, BOOLEAN, INTEGER, FLOAT, STRING, COLOR, OBJECT, FILE, } CustomPropertyType; typedef struct Tiled_CustomPropertyDefn { std::string name; CustomPropertyType type = CustomPropertyType::UNKNOWN; bool boolValue = false; int intValue = 0; double decimalValue = 0.0; std::string stringValue; } CustomPropertyDefn; namespace CustomPropertyDefnUtils { const CustomPropertyDefn& find(const std::vector<CustomPropertyDefn>& propertyDefnList, const std::string& propertyName); bool contains(const std::vector<CustomPropertyDefn>& propertyDefnList, const std::string& propertyName); bool containsOfType(const std::vector<CustomPropertyDefn>& propertyDefnList, const std::string& propertyName, CustomPropertyType type); bool getBoolValue(const std::vector<CustomPropertyDefn>& propertyDefnList, const std::string& propertyName); int getIntValue(const std::vector<CustomPropertyDefn>& propertyDefnList, const std::string& propertyName); double getDecimalValue(const std::vector<CustomPropertyDefn>& propertyDefnList, const std::string& propertyName); const std::string& getStringValue(const std::vector<CustomPropertyDefn>& propertyDefnList, const std::string& propertyName); } typedef struct Tiled_TilesetImageDefn { std::string imagePath; int imageWidth = 0; int imageHeight = 0; } TilesetImageDefn; typedef struct Tiled_TilesetTileDefn { int id = 0; TilesetImageDefn imageDefn; std::vector<CustomPropertyDefn> propertyDefnList; } TilesetTileDefn; typedef enum class Tiled_TilesetType { UNKNOWN, IMAGE, TILE_LIST, } TilesetType; typedef struct Tiled_TilesetDefn { double version = 0.0; TilesetType type = TilesetType::UNKNOWN; std::string name; int columns = 0; int tileCount = 0; int tileWidth = 0; int tileHeight = 0; int margin = 0; int spacing = 0; TilesetImageDefn imageDefn; std::vector<TilesetTileDefn> tileDefnList; std::vector<CustomPropertyDefn> propertyDefnList; } TilesetDefn; typedef enum class Tiled_MapOrientationType { UNKNOWN, ORTHOGONAL, ISOMETRIC, STAGGERED, HEXAGONAL, } MapOrientationType; typedef enum class Tiled_MapLayerType { UNKNOWN, TILE, OBJECT, GROUP, } MapLayerType; typedef enum class Tiled_MapLayerObjectType { UNKNOWN, POINT, RECTANGLE, ELLIPSE, POLYLINE, POLYGON, TILE, TEXT, } MapLayerObjectType; namespace MapLayerObjectTypeUtils { bool expectsDimensions(MapLayerObjectType objectType); } typedef struct Tiled_MapLayerObjectPointDefn { double x = 0.0; double y = 0.0; } MapLayerObjectPointDefn; typedef struct Tiled_MapLayerObjectDefn { int id = 0; MapLayerObjectPointDefn position; double rotationDegrees = 0.0; double width = 0; double height = 0; MapLayerObjectType objectType = MapLayerObjectType::UNKNOWN; int tileGid = 0; std::vector<MapLayerObjectPointDefn> pointDefnList; std::string name; std::string type; std::vector<CustomPropertyDefn> propertyDefnList; } MapLayerObjectDefn; typedef struct Tiled_MapLayerDefn { int id = 0; MapLayerType type = MapLayerType::UNKNOWN; std::string name; int width = 0; int height = 0; std::vector<int> data; std::vector<MapLayerObjectDefn> objectDefnList; std::vector<struct Tiled_MapLayerDefn> layerDefnList; std::vector<CustomPropertyDefn> propertyDefnList; } MapLayerDefn; typedef struct Tiled_MapTilesetDefn { int firstGid = 0; std::string sourcePath; } MapTilesetDefn; typedef struct Tiled_MapDefn { double version = 0.0; MapOrientationType orientation = MapOrientationType::UNKNOWN; bool infinite = false; int width = 0; int height = 0; int tileWidth = 0; int tileHeight = 0; std::string backgroundColor; std::vector<MapTilesetDefn> tilesetDefnList; std::vector<MapLayerDefn> layerDefnList; std::vector<CustomPropertyDefn> propertyDefnList; } MapDefn; } }
25.539877
138
0.730963
ryantherileyman
69799e0bd6ef9b0cf91ee2a66de9372578a70e1c
541
hpp
C++
include/member_thunk/details/heap/memory.hpp
sylveon/member_thunk
1ac81a983e951678638be7785de2cce2d9f73151
[ "MIT" ]
9
2019-12-02T11:59:24.000Z
2022-02-28T06:34:59.000Z
include/member_thunk/details/heap/memory.hpp
sylveon/member_thunk
1ac81a983e951678638be7785de2cce2d9f73151
[ "MIT" ]
29
2019-11-26T17:12:33.000Z
2020-10-06T04:58:53.000Z
include/member_thunk/details/heap/memory.hpp
sylveon/member_thunk
1ac81a983e951678638be7785de2cce2d9f73151
[ "MIT" ]
null
null
null
#pragma once #include <cstddef> #include <cstdint> namespace member_thunk::details { struct memory_layout { std::uint32_t page_size, allocation_granularity; static memory_layout get_for_current_system(); }; void flush_instruction_cache(void* ptr, std::size_t size); void* virtual_alloc(void* address, std::size_t size, std::uint32_t type, std::uint32_t protection); std::uint32_t virtual_protect(void* ptr, std::size_t size, std::uint32_t protection); void virtual_free(void* ptr, std::size_t size, std::uint32_t free_type); }
28.473684
100
0.767098
sylveon
697c3d3e82fe5126df47fa1f69582553efb1e9c3
3,775
cpp
C++
src/services/pcn-nat/src/serializer/RulePortForwardingAppendInputJsonObject.cpp
francescomessina/polycube
38f2fb4ffa13cf51313b3cab9994be738ba367be
[ "ECL-2.0", "Apache-2.0" ]
337
2018-12-12T11:50:15.000Z
2022-03-15T00:24:35.000Z
src/services/pcn-nat/src/serializer/RulePortForwardingAppendInputJsonObject.cpp
l1b0k/polycube
7af919245c131fa9fe24c5d39d10039cbb81e825
[ "ECL-2.0", "Apache-2.0" ]
253
2018-12-17T21:36:15.000Z
2022-01-17T09:30:42.000Z
src/services/pcn-nat/src/serializer/RulePortForwardingAppendInputJsonObject.cpp
l1b0k/polycube
7af919245c131fa9fe24c5d39d10039cbb81e825
[ "ECL-2.0", "Apache-2.0" ]
90
2018-12-19T15:49:38.000Z
2022-03-27T03:56:07.000Z
/** * nat API * nat API generated from nat.yang * * OpenAPI spec version: 1.0.0 * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/polycube-network/swagger-codegen.git * branch polycube */ /* Do not edit this file manually */ #include "RulePortForwardingAppendInputJsonObject.h" #include <regex> namespace io { namespace swagger { namespace server { namespace model { RulePortForwardingAppendInputJsonObject::RulePortForwardingAppendInputJsonObject() { m_externalIpIsSet = false; m_externalPortIsSet = false; m_protoIsSet = false; m_internalIpIsSet = false; m_internalPortIsSet = false; } RulePortForwardingAppendInputJsonObject::RulePortForwardingAppendInputJsonObject(const nlohmann::json &val) : JsonObjectBase(val) { m_externalIpIsSet = false; m_externalPortIsSet = false; m_protoIsSet = false; m_internalIpIsSet = false; m_internalPortIsSet = false; if (val.count("external-ip")) { setExternalIp(val.at("external-ip").get<std::string>()); } if (val.count("external-port")) { setExternalPort(val.at("external-port").get<uint16_t>()); } if (val.count("proto")) { setProto(val.at("proto").get<std::string>()); } if (val.count("internal-ip")) { setInternalIp(val.at("internal-ip").get<std::string>()); } if (val.count("internal-port")) { setInternalPort(val.at("internal-port").get<uint16_t>()); } } nlohmann::json RulePortForwardingAppendInputJsonObject::toJson() const { nlohmann::json val = nlohmann::json::object(); if (!getBase().is_null()) { val.update(getBase()); } if (m_externalIpIsSet) { val["external-ip"] = m_externalIp; } if (m_externalPortIsSet) { val["external-port"] = m_externalPort; } if (m_protoIsSet) { val["proto"] = m_proto; } if (m_internalIpIsSet) { val["internal-ip"] = m_internalIp; } if (m_internalPortIsSet) { val["internal-port"] = m_internalPort; } return val; } std::string RulePortForwardingAppendInputJsonObject::getExternalIp() const { return m_externalIp; } void RulePortForwardingAppendInputJsonObject::setExternalIp(std::string value) { m_externalIp = value; m_externalIpIsSet = true; } bool RulePortForwardingAppendInputJsonObject::externalIpIsSet() const { return m_externalIpIsSet; } uint16_t RulePortForwardingAppendInputJsonObject::getExternalPort() const { return m_externalPort; } void RulePortForwardingAppendInputJsonObject::setExternalPort(uint16_t value) { m_externalPort = value; m_externalPortIsSet = true; } bool RulePortForwardingAppendInputJsonObject::externalPortIsSet() const { return m_externalPortIsSet; } std::string RulePortForwardingAppendInputJsonObject::getProto() const { return m_proto; } void RulePortForwardingAppendInputJsonObject::setProto(std::string value) { m_proto = value; m_protoIsSet = true; } bool RulePortForwardingAppendInputJsonObject::protoIsSet() const { return m_protoIsSet; } void RulePortForwardingAppendInputJsonObject::unsetProto() { m_protoIsSet = false; } std::string RulePortForwardingAppendInputJsonObject::getInternalIp() const { return m_internalIp; } void RulePortForwardingAppendInputJsonObject::setInternalIp(std::string value) { m_internalIp = value; m_internalIpIsSet = true; } bool RulePortForwardingAppendInputJsonObject::internalIpIsSet() const { return m_internalIpIsSet; } uint16_t RulePortForwardingAppendInputJsonObject::getInternalPort() const { return m_internalPort; } void RulePortForwardingAppendInputJsonObject::setInternalPort(uint16_t value) { m_internalPort = value; m_internalPortIsSet = true; } bool RulePortForwardingAppendInputJsonObject::internalPortIsSet() const { return m_internalPortIsSet; } } } } }
21.571429
109
0.747285
francescomessina
698142765169324076c34cf8ef418a1d8c2fb258
2,254
cpp
C++
Source/JsonHelper.cpp
NEWorldProject/Common
167d69e80aee5e86a8892bcfaec6bcd988f97493
[ "BSL-1.0", "Apache-2.0", "MIT" ]
null
null
null
Source/JsonHelper.cpp
NEWorldProject/Common
167d69e80aee5e86a8892bcfaec6bcd988f97493
[ "BSL-1.0", "Apache-2.0", "MIT" ]
null
null
null
Source/JsonHelper.cpp
NEWorldProject/Common
167d69e80aee5e86a8892bcfaec6bcd988f97493
[ "BSL-1.0", "Apache-2.0", "MIT" ]
null
null
null
// // Core: JsonHelper.cpp // NEWorld: A Free Game with Similar Rules to Minecraft. // Copyright (C) 2015-2018 NEWorld Team // // NEWorld 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. // // NEWorld 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 NEWorld. If not, see <http://www.gnu.org/licenses/>. // #include "Core/JsonHelper.h" #include "Core/Logger.h" #include <fstream> namespace { class JsonSaveHelper { public: JsonSaveHelper(Json& json, std::string filename) : mJson(json), mFilename(std::move(filename)) {} JsonSaveHelper(const JsonSaveHelper&) = delete; JsonSaveHelper& operator=(const JsonSaveHelper&) = delete; ~JsonSaveHelper() { writeJsonToFile(mFilename, mJson); } private: Json& mJson; std::string mFilename; }; } NWCOREAPI Json readJsonFromFile(std::string filename) { std::ifstream file(filename); if (file) { std::string content = std::string(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()); if (!content.empty()) { try { return Json::parse(content); } catch (std::invalid_argument& exception) { warningstream << "Failed to load json " << filename << ": " << exception.what(); } } } return Json(); } NWCOREAPI void writeJsonToFile(std::string filename, Json& json) { const std::string& dump = json.dump(); if (!json.is_null()) std::ofstream(filename).write(dump.c_str(), dump.length()); } NWCOREAPI Json& getSettings() { static Json settings = readJsonFromFile(SettingsFilename + ".json"); static JsonSaveHelper helper(settings, SettingsFilename + ".json"); return settings; }
34.151515
96
0.653505
NEWorldProject
69814c6c4a87af20a91c217a5d17374af977e042
662
cpp
C++
bit_manipulation/binary_or_operator.cpp
mohitbaran/CPP-Programming
ee70007d8eaffbb82b297984a07dd6f65999a435
[ "MIT" ]
30
2020-09-30T19:16:04.000Z
2022-02-20T14:28:13.000Z
bit_manipulation/binary_or_operator.cpp
mohitbaran/CPP-Programming
ee70007d8eaffbb82b297984a07dd6f65999a435
[ "MIT" ]
168
2020-09-30T19:52:42.000Z
2021-10-22T03:55:57.000Z
bit_manipulation/binary_or_operator.cpp
mohitbaran/CPP-Programming
ee70007d8eaffbb82b297984a07dd6f65999a435
[ "MIT" ]
123
2020-09-30T19:16:12.000Z
2021-11-12T18:49:18.000Z
#include <stdio.h> /* g++ 64 bit int size is 4 bytes or operator table 1|1 = 1 1|0 = 1 0|1 = 1 0|0 = 0 */ int main() { int a = 15; /* 60 = 0000 0000 0000 0000 0000 0000 0000 1111 */ int b = 13; /* 13 = 0000 0000 0000 0000 0000 0000 0000 1101 */ int c = -1; /* -1 = 1111 1111 1111 1111 1111 1111 1111 1111*/ int d = -2; /* -2 = 1111 1111 1111 1111 1111 1111 1111 1110*/ /* Negative numbers are represented in 2's compliment form.*/ printf("Value of a | b is %d\n", a | b); /* 15 = 0000 0000 0000 0000 0000 0000 0000 1111 */ printf("Value of b | c is %d\n", c | d); /* -1 = 1111 1111 1111 1111 1111 1111 1111 1111*/ return 0; }
26.48
95
0.584592
mohitbaran
69826780a977a5bd09b4de0f7ac9e8d06f701019
18,465
cpp
C++
source/ocl.cpp
EwanC/WeeChess
8b9b69d5d9d2c2a873670d450230ad0e5c526494
[ "MIT" ]
1
2015-05-24T20:26:41.000Z
2015-05-24T20:26:41.000Z
source/ocl.cpp
EwanC/WeeChess
8b9b69d5d9d2c2a873670d450230ad0e5c526494
[ "MIT" ]
null
null
null
source/ocl.cpp
EwanC/WeeChess
8b9b69d5d9d2c2a873670d450230ad0e5c526494
[ "MIT" ]
null
null
null
#include "ocl.hpp" #include <cstring> #include <iostream> #include "types.hpp" OCL* OCL::m_instance = nullptr; // Singleton instance uint OCL::possible_pawn_moves = 12; uint OCL::possible_piece_moves = 30; #define QUOTE(name) #name #define STR(macro) QUOTE(macro) #define KERNEL_DIR STR(__DIR__) #define EVALKERNEL "evalKernel" #define PIECEMOVEKERNEL "moveKernel" #define WPAWNMOVEKERNEL "WhitePawnKernel" #define BPAWNMOVEKERNEL "BlackPawnKernel" #define PIECECAPTUREKERNEL "moveCapture" #define WPAWNCAPTUREKERNEL "WhitePawnCapture" #define BPAWNCAPTUREKERNEL "BlackPawnCapture" #define EVAL_PROGRAM_FILE "/EvalKernel.cl" #define MOVE_PROGRAM_FILE "/moveKernel.cl" // Most Valuable attacker, least valuable victim static int32_t MvvLvaScores[13][13] = { {141743112, 32767, -37664, 32767, -141682440, 32767, 54012236, 0, -37680, 32767, -136429924, 32767, 0}, {0, 105, 104, 103, 102, 101, 100, 105, 104, 103, 102, 101, 100}, {-37824, 205, 204, 203, 202, 201, 200, 205, 204, 203, 202, 201, 200}, {32767, 305, 304, 303, 302, 301, 300, 305, 304, 303, 302, 301, 300}, {4301065, 405, 404, 403, 402, 401, 400, 405, 404, 403, 402, 401, 400}, {32767, 505, 504, 503, 502, 501, 500, 505, 504, 503, 502, 501, 500}, {0, 605, 604, 603, 602, 601, 600, 605, 604, 603, 602, 601, 600}, {0, 105, 104, 103, 102, 101, 100, 105, 104, 103, 102, 101, 100}, {-1, 205, 204, 203, 202, 201, 200, 205, 204, 203, 202, 201, 200}, {0, 305, 304, 303, 302, 301, 300, 305, 304, 303, 302, 301, 300}, {16, 405, 404, 403, 402, 401, 400, 405, 404, 403, 402, 401, 400}, {0, 505, 504, 503, 502, 501, 500, 505, 504, 503, 502, 501, 500}, {1, 605, 604, 603, 602, 601, 600, 605, 604, 603, 602, 601, 600}}; std::string OCL::getSourceDir() { #ifdef KERNEL_DIR std::string file(KERNEL_DIR); #else std::string file(__FILE__); // assume .cl files in same dir size_t last_slash_idx = file.rfind('\\'); if (std::string::npos != last_slash_idx) { return file.substr(0, last_slash_idx); } last_slash_idx = file.rfind('/'); if (std::string::npos != last_slash_idx) { return file.substr(0, last_slash_idx); } #endif return file; } // Singleton class OCL* OCL::getInstance() { if (!m_instance) { m_instance = new OCL; } return m_instance; } OCL::OCL() { int err; /* Identify a platform */ err = clGetPlatformIDs(1, &m_platform, NULL); if (err < 0) { std::cout << "Couldn't locate an OCL platform " << err << "\n"; exit(1); } /* Access a device */ err = clGetDeviceIDs(m_platform, CL_DEVICE_TYPE_GPU, 1, &m_device, NULL); if (err == CL_DEVICE_NOT_FOUND) { err = clGetDeviceIDs(m_platform, CL_DEVICE_TYPE_CPU, 1, &m_device, NULL); } if (err < 0) { std::cout << "Couldn't locate an OCL device\n"; exit(1); } m_context = clCreateContext(NULL, 1, &m_device, NULL, NULL, &err); if (err < 0) { std::cout << "Couldn't create an OCL context\n"; exit(1); } char buffer[1024]; err = clGetDeviceInfo(m_device, CL_DEVICE_NAME, sizeof(buffer), buffer, NULL); std::cout << "OpenCL Device: " << buffer << std::endl; m_queue = clCreateCommandQueue(m_context, m_device, 0, &err); if (err < 0) { std::cout << "Couldn't create an OCL command queue\n"; exit(1); } BuildProgram(); m_evalKernel = clCreateKernel(m_evalProgram, EVALKERNEL, &err); if (err < 0) { std::cout << "Couldn't create OCL kernel " << EVALKERNEL << " " << err << std::endl; exit(1); } m_pieceMoveKernel = clCreateKernel(m_moveProgram, PIECEMOVEKERNEL, &err); if (err < 0) { std::cout << "Couldn't create OCL kernel " << PIECEMOVEKERNEL << " " << err << std::endl; exit(1); } m_wPawnMoveKernel = clCreateKernel(m_moveProgram, WPAWNMOVEKERNEL, &err); if (err < 0) { std::cout << "Couldn't create OCL kernel " << WPAWNMOVEKERNEL << " " << err << std::endl; exit(1); } m_bPawnMoveKernel = clCreateKernel(m_moveProgram, BPAWNMOVEKERNEL, &err); if (err < 0) { std::cout << "Couldn't create OCL kernel " << BPAWNMOVEKERNEL << " " << err << std::endl; exit(1); } m_pieceCaptureKernel = clCreateKernel(m_moveProgram, PIECECAPTUREKERNEL, &err); if (err < 0) { std::cout << "Couldn't create OCL kernel " << PIECECAPTUREKERNEL << " " << err << std::endl; exit(1); } m_wPawnCaptureKernel = clCreateKernel(m_moveProgram, WPAWNCAPTUREKERNEL, &err); if (err < 0) { std::cout << "Couldn't create OCL kernel " << WPAWNCAPTUREKERNEL << " " << err << std::endl; exit(1); } m_bPawnCaptureKernel = clCreateKernel(m_moveProgram, BPAWNCAPTUREKERNEL, &err); if (err < 0) { std::cout << "Couldn't create OCL kernel " << BPAWNCAPTUREKERNEL << " " << err << std::endl; exit(1); } } void OCL::BuildProgram() { int err; std::string evalFile = OCL::getSourceDir().append(EVAL_PROGRAM_FILE); FILE* fp = fopen(evalFile.c_str(), "r"); if (!fp) { std::cout << "Failed to read kernel file " << evalFile << std::endl; exit(1); } fseek(fp, 0, SEEK_END); size_t programSize = ftell(fp); rewind(fp); char* program_buffer = new char[programSize + 1]; program_buffer[programSize] = '\0'; size_t read_size = fread(program_buffer, sizeof(char), programSize, fp); if (read_size != programSize) std::cout << "Reading Error\n"; fclose(fp); /* Create program from file */ m_evalProgram = clCreateProgramWithSource(m_context, 1, (const char**)&program_buffer, &programSize, &err); if (err < 0) { std::cout << "Couldn't create the program\n"; exit(1); } /* Build program */ err = clBuildProgram(m_evalProgram, 0, NULL, NULL, NULL, NULL); if (err < 0) { std::cout << "Couldn't build program" << EVAL_PROGRAM_FILE << "\n"; char buffer[2048]; size_t length; clGetProgramBuildInfo(m_evalProgram, m_device, CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &length); std::cout << "--- Build log ---\n " << buffer << std::endl; exit(1); } std::string moveFile = OCL::getSourceDir().append(MOVE_PROGRAM_FILE); fp = fopen(moveFile.c_str(), "r"); if (!fp) { std::cout << "Failed to read kernel file " << moveFile << std::endl; exit(1); } fseek(fp, 0, SEEK_END); programSize = ftell(fp); rewind(fp); program_buffer = new char[programSize + 1]; program_buffer[programSize] = '\0'; read_size = fread(program_buffer, sizeof(char), programSize, fp); if (read_size != programSize) std::cout << "Reading Error\n"; fclose(fp); /* Create program from file */ m_moveProgram = clCreateProgramWithSource(m_context, 1, (const char**)&program_buffer, &programSize, &err); if (err < 0) { std::cout << "Couldn't create the program\n"; exit(1); } /* Build program */ char macro_str[128]; sprintf(macro_str, "-DMAX_PAWN_MOVES=%u -DMAX_PIECE_MOVES=%u", OCL::possible_pawn_moves, OCL::possible_piece_moves); err = clBuildProgram(m_moveProgram, 0, NULL, macro_str, NULL, NULL); if (err < 0) { std::cout << "Couldn't build program" << MOVE_PROGRAM_FILE << "\n"; char buffer[2048]; size_t length; clGetProgramBuildInfo(m_moveProgram, m_device, CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &length); std::cout << "--- Build log ---\n " << buffer << std::endl; exit(1); } } std::vector<Move> OCL::RunPawnMoveKernel(const Board& b, const bool capture) { std::vector<Move> pawn_move_vec; bitboard Bitboard = b.m_side == Colour::WHITE ? b.m_pList[Piece::wP] : b.m_pList[Piece::bP]; int pawns = Bitboard::countBits(Bitboard); if (pawns == 0) { return pawn_move_vec; } unsigned int* pawn_squares = new unsigned int[pawns]; for (int pceNum = 0; pceNum < pawns; ++pceNum) { int sq64 = (Bitboard::popBit(&Bitboard)); pawn_squares[pceNum] = SQ120(sq64); } int err = CL_SUCCESS; cl_mem square_buffer = clCreateBuffer(m_context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, pawns * sizeof(unsigned int), (void*)pawn_squares, &err); if (err < 0) { std::cout << "Couldn't create cl pawn square buffer " << err << "\n"; exit(1); } cl_mem pieces_buffer = clCreateBuffer(m_context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, TOTAL_SQUARES * sizeof(int), (void*)b.m_board, &err); if (err < 0) { std::cout << "Couldn't create cl pawn peices buffer\n"; exit(1); } cl_mem Enpass_buffer = clCreateBuffer(m_context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(unsigned int), (void*)&b.m_enPas, &err); if (err < 0) { std::cout << "Couldn't create cl pawn enpass buffer\n"; exit(1); } const uint move_buffer_size = pawns * OCL::possible_pawn_moves; unsigned long moves[move_buffer_size]; for (int i = 0; i < move_buffer_size; ++i) { moves[i] = 0; } cl_mem moves_buffer = clCreateBuffer(m_context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, move_buffer_size * sizeof(unsigned long), moves, &err); if (err < 0) { std::cout << "Couldn't create cl wp moves buffer\n"; exit(1); } const size_t global_size = pawns; const size_t local_size = pawns; cl_kernel kernel; if (capture) { kernel = b.m_side == Colour::WHITE ? m_wPawnCaptureKernel : m_bPawnCaptureKernel; } else { kernel = b.m_side == Colour::WHITE ? m_wPawnMoveKernel : m_bPawnMoveKernel; } /* Set kernel args */ err = clSetKernelArg(kernel, 0, sizeof(cl_mem), &square_buffer); err |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &pieces_buffer); err |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &Enpass_buffer); err |= clSetKernelArg(kernel, 3, sizeof(cl_mem), &moves_buffer); if (err < 0) { std::cout << "Couldn't set pawn move kernel arg\n"; exit(1); } /* Enqueue Kernel*/ err = clEnqueueNDRangeKernel(m_queue, kernel, 1, NULL, &global_size, &local_size, 0, NULL, NULL); if (err < 0) { std::cout << "Couldn't enqueue the kernel " << err << "\n"; exit(1); } /* Enqueue ReadBuffer */ err = clEnqueueReadBuffer(m_queue, moves_buffer, CL_TRUE, 0, move_buffer_size * sizeof(unsigned long), moves, 0, NULL, NULL); if (err < 0) { std::cout << "Couldn't read cl buffer\n"; exit(1); } err = clFinish(m_queue); if (err < 0) { std::cout << "Couldn't wait for CL tae finish\n"; exit(1); } for (int i = 0; i < move_buffer_size; ++i) { if (moves[i] == 0) { continue; } Move m; m.m_move = moves[i]; if (m.m_move & MFLAGEP) m.m_score = 105 + 1000000; if (CAPTURED(m.m_move)) m.m_score = MvvLvaScores[CAPTURED(m.m_move)][b.m_board[FROMSQ(m.m_move)]] + 1000000; else if (b.m_searchKillers[0][b.m_ply] == m.m_move) m.m_score = 900000; else if (b.m_searchKillers[1][b.m_ply] == m.m_move) m.m_score = 800000; else m.m_score = b.m_searchHistory[b.m_board[FROMSQ(m.m_move)]][TOSQ(m.m_move)]; pawn_move_vec.push_back(m); } clReleaseMemObject(square_buffer); clReleaseMemObject(pieces_buffer); clReleaseMemObject(Enpass_buffer); clReleaseMemObject(moves_buffer); delete[] pawn_squares; return pawn_move_vec; } void OCL::SetPieceHostBuffer(unsigned int* pieces, bitboard bb, unsigned int& itr, const unsigned short piece_count) { int count = Bitboard::countBits(bb); for (int pceNum = 0; pceNum < piece_count; ++pceNum) { if (pceNum < count) { int sq120 = SQ120(Bitboard::popBit(&bb)); pieces[itr++] = sq120; } else { itr++; } } } std::vector<Move> OCL::RunPieceMoveKernel(const Board& b, const bool capture) { static const Piece SlidePce[2][3] = {{wB, wR, wQ}, {bB, bR, bQ}}; static const Piece NonSlidePce[2][2] = {{wN, wK}, {bN, bK}}; std::vector<Move> piece_move_vec; ushort max_pieces = 0; bitboard Nbb = b.m_pList[static_cast<int>(NonSlidePce[b.m_side][0])]; ushort bbCount = Bitboard::countBits(Nbb); max_pieces = bbCount > max_pieces ? bbCount : max_pieces; bitboard Bbb = b.m_pList[static_cast<int>(SlidePce[b.m_side][0])]; bbCount = Bitboard::countBits(Bbb); max_pieces = bbCount > max_pieces ? bbCount : max_pieces; bitboard Rbb = b.m_pList[static_cast<int>(SlidePce[b.m_side][1])]; bbCount = Bitboard::countBits(Rbb); max_pieces = bbCount > max_pieces ? bbCount : max_pieces; bitboard Qbb = b.m_pList[static_cast<int>(SlidePce[b.m_side][2])]; bbCount = Bitboard::countBits(Qbb); max_pieces = bbCount > max_pieces ? bbCount : max_pieces; if (max_pieces == 0) { max_pieces = 1; } const size_t global_size = 5 * max_pieces; const size_t local_size = max_pieces; // Piece Buffer // WB, WB, WR, WR, WQ, WN, WN, WK unsigned int* pieces = new unsigned int[global_size]; unsigned int itr = 0; for (int i = 0; i < global_size; ++i) { pieces[i] = Square::NO_SQ; } SetPieceHostBuffer(pieces, Nbb, itr, local_size); SetPieceHostBuffer(pieces, Bbb, itr, local_size); SetPieceHostBuffer(pieces, Rbb, itr, local_size); SetPieceHostBuffer(pieces, Qbb, itr, local_size); bitboard Kbb = b.m_pList[static_cast<int>(NonSlidePce[b.m_side][1])]; SetPieceHostBuffer(pieces, Kbb, itr, local_size); int err; cl_mem square_buffer = clCreateBuffer(m_context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, global_size * sizeof(unsigned int), (void*)pieces, &err); if (err < 0) { std::cout << "Couldn't create cl side square buffer\n"; exit(1); } cl_mem side_buffer = clCreateBuffer(m_context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(int), (void*)&b.m_side, &err); if (err < 0) { std::cout << "Couldn't create cl piece side buffer\n"; exit(1); } cl_mem pieces_buffer = clCreateBuffer(m_context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, TOTAL_SQUARES * sizeof(int), (void*)b.m_board, &err); if (err < 0) { std::cout << "Couldn't create cl pawn peices buffer\n"; exit(1); } const uint move_buffer_size = global_size * OCL::possible_piece_moves; unsigned long moves[move_buffer_size]; for (int i = 0; i < move_buffer_size; ++i) moves[i] = 0; cl_mem moves_buffer = clCreateBuffer(m_context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, move_buffer_size * sizeof(unsigned long), moves, &err); if (err < 0) { std::cout << "Couldn't create cl side moves buffer\n"; exit(1); } cl_kernel kernel = capture ? m_pieceCaptureKernel : m_pieceMoveKernel; /* Set kernel args */ err = clSetKernelArg(kernel, 0, sizeof(cl_mem), &square_buffer); if (err < 0) { std::cout << "A Couldn't set Piece move kernel arg\n"; exit(1); } err |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &side_buffer); if (err < 0) { std::cout << "B Couldn't set Piece move kernel arg\n"; exit(1); } err |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &pieces_buffer); if (err < 0) { std::cout << "C Couldn't set Piece move kernel arg: " << err << "\n"; exit(1); } err |= clSetKernelArg(kernel, 3, sizeof(cl_mem), &moves_buffer); if (err < 0) { std::cout << "D Couldn't set Piece move kernel arg\n"; exit(1); } /* Enqueue Kernel*/ err = clEnqueueNDRangeKernel(m_queue, kernel, 1, NULL, &global_size, &local_size, 0, NULL, NULL); if (err < 0) { std::cout << "Couldn't enqueue the kernel " << err << "\n"; exit(1); } /* Enqueue ReadBuffer */ err = clEnqueueReadBuffer(m_queue, moves_buffer, CL_TRUE, 0, move_buffer_size * sizeof(unsigned long), moves, 0, NULL, NULL); if (err < 0) { std::cout << "Couldn't read cl buffer\n"; exit(1); } err = clFinish(m_queue); if (err < 0) { std::cout << "Couldn't wait for CL tae finish\n"; exit(1); } for (int i = 0; i < move_buffer_size; ++i) { if (moves[i] == 0) { continue; } Move m; m.m_move = moves[i]; if (CAPTURED(m.m_move)) m.m_score = MvvLvaScores[CAPTURED(m.m_move)][b.m_board[FROMSQ(m.m_move)]] + 1000000; else if (b.m_searchKillers[0][b.m_ply] == m.m_move) m.m_score = 900000; else if (b.m_searchKillers[1][b.m_ply] == m.m_move) m.m_score = 800000; else m.m_score = b.m_searchHistory[b.m_board[FROMSQ(m.m_move)]][TOSQ(m.m_move)]; piece_move_vec.push_back(m); } clReleaseMemObject(square_buffer); clReleaseMemObject(pieces_buffer); clReleaseMemObject(side_buffer); clReleaseMemObject(moves_buffer); delete[] pieces; return piece_move_vec; } int OCL::RunEvalKernel(const Board& board) { /* local vars */ const unsigned int bitboards_per_board = 13; const unsigned int num_boards = 1; const size_t global_size = bitboards_per_board * num_boards; const size_t local_size = bitboards_per_board; int scores[num_boards] = {0}; /* Create Buffers */ int err; cl_mem bitboard_buffer = clCreateBuffer(m_context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, bitboards_per_board * sizeof(bitboard), (void*)board.m_pList, &err); if (err < 0) { std::cout << "Couldn't create cl buffer\n"; exit(1); } cl_mem score_buffer = clCreateBuffer(m_context, CL_MEM_READ_WRITE, num_boards * sizeof(int), scores, &err); if (err < 0) { std::cout << "Couldn't create cl buffer\n"; exit(1); } /* Set kernel args */ err = clSetKernelArg(m_evalKernel, 0, sizeof(cl_mem), &bitboard_buffer); err |= clSetKernelArg(m_evalKernel, 1, sizeof(cl_mem), &score_buffer); err |= clSetKernelArg(m_evalKernel, 2, num_boards * sizeof(cl_int), NULL); if (err < 0) { std::cout << "Couldn't set kernel arg\n"; exit(1); } /* Enqueue Kernel*/ err = clEnqueueNDRangeKernel(m_queue, m_evalKernel, 1, NULL, &global_size, &local_size, 0, NULL, NULL); if (err < 0) { std::cout << "Couldn't enqueue the kernel " << err << "\n"; exit(1); } /* Enqueue ReadBuffer */ err = clEnqueueReadBuffer(m_queue, score_buffer, CL_TRUE, 0, num_boards * sizeof(int), scores, 0, NULL, NULL); if (err < 0) { std::cout << "Couldn't read cl buffer\n"; exit(1); } err = clFinish(m_queue); if (err < 0) { std::cout << "Couldn't wait for CL tae finish\n"; exit(1); } clReleaseMemObject(bitboard_buffer); clReleaseMemObject(score_buffer); // Just one board for now return scores[0]; } OCL::~OCL() { /* Deallocate resources */ clReleaseContext(m_context); clReleaseCommandQueue(m_queue); clReleaseKernel(m_evalKernel); }
31.403061
120
0.64013
EwanC
6982a79a7ed4d4c347f9fa0b118d184a642e8f62
8,832
cpp
C++
beringei/lib/PersistentKeyList.cpp
pidb/Gorilla
75c3002b179d99c8709323d605e7d4b53484035c
[ "BSD-3-Clause" ]
2,780
2016-12-22T19:25:26.000Z
2018-05-21T11:29:42.000Z
beringei/lib/PersistentKeyList.cpp
pidb/Gorilla
75c3002b179d99c8709323d605e7d4b53484035c
[ "BSD-3-Clause" ]
57
2016-12-23T09:22:18.000Z
2018-05-04T06:26:48.000Z
beringei/lib/PersistentKeyList.cpp
pidb/Gorilla
75c3002b179d99c8709323d605e7d4b53484035c
[ "BSD-3-Clause" ]
254
2016-12-22T20:53:12.000Z
2018-05-16T06:14:10.000Z
/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "beringei/lib/PersistentKeyList.h" #include <folly/compression/Compression.h> #include <folly/io/IOBuf.h> #include <gflags/gflags.h> #include <glog/logging.h> #include "beringei/lib/GorillaStatsManager.h" namespace facebook { namespace gorilla { // For reads and compaction. Can probably be arbitrarily large. const static size_t kLargeBufferSize = 1 << 24; // Flush after 4k of keys. const static size_t kSmallBufferSize = 1 << 12; const static int kTempFileId = 0; const int KRetryFileOpen = 3; constexpr static char kCompressedFileWithTimestampsMarker = '2'; constexpr static char kUncompressedFileWithTimestampsMarker = '3'; constexpr static char kAppendMarker = 'a'; constexpr static char kDeleteMarker = 'd'; const static std::string kFileType = "key_list"; const static std::string kFailedCounter = "failed_writes." + kFileType; // Marker bytes to determine if the file is compressed or not and if // there are categories or not. const static uint32_t kHardFlushIntervalSecs = 120; PersistentKeyList::PersistentKeyList( int64_t shardId, const std::string& dataDirectory) : activeList_({nullptr, ""}), files_(shardId, kFileType, dataDirectory), lock_(), shard_(shardId) { GorillaStatsManager::addStatExportType(kFailedCounter, SUM); // Randomly select the next flush time within the interval to spread // the fflush calls between shards. nextHardFlushTimeSecs_ = time(nullptr) + random() % kHardFlushIntervalSecs; openNext(); } bool PersistentKeyList::appendKey( uint32_t id, const char* key, uint16_t category, int32_t timestamp) { std::lock_guard<std::mutex> guard(lock_); if (activeList_.file == nullptr) { return false; } writeKey(id, key, category, timestamp); return true; } bool PersistentKeyList::compactToFile( FILE* f, const std::string& fileName, std::function<std::tuple<uint32_t, const char*, uint16_t, int32_t>()> generator) { folly::fbstring buffer; for (auto key = generator(); std::get<1>(key) != nullptr; key = generator()) { appendBuffer( buffer, std::get<0>(key), std::get<1>(key), std::get<2>(key), std::get<3>(key)); } if (buffer.length() == 0) { fclose(f); return false; } try { auto ioBuffer = folly::IOBuf::wrapBuffer(buffer.data(), buffer.length()); auto codec = folly::io::getCodec( folly::io::CodecType::ZLIB, folly::io::COMPRESSION_LEVEL_BEST); auto compressed = codec->compress(ioBuffer.get()); compressed->coalesce(); if (fwrite(&kCompressedFileWithTimestampsMarker, sizeof(char), 1, f) != 1 || fwrite(compressed->data(), sizeof(char), compressed->length(), f) != compressed->length()) { PLOG(ERROR) << "Could not write to the temporary key file " << fileName; GorillaStatsManager::addStatValue(kFailedCounter, 1); fclose(f); return false; } LOG(INFO) << "Compressed key list from " << buffer.length() << " bytes to " << compressed->length(); } catch (std::exception& e) { LOG(ERROR) << "Compression failed:" << e.what(); fclose(f); return false; } // Swap the new data in for the old. fclose(f); return true; } bool PersistentKeyList::compactToBuffer( std::function<std::tuple<uint32_t, const char*, uint16_t, int32_t>()> generator, uint64_t seq, folly::fbstring& out) { folly::fbstring buffer; for (auto key = generator(); std::get<1>(key) != nullptr; key = generator()) { appendBuffer( buffer, std::get<0>(key), std::get<1>(key), std::get<2>(key), std::get<3>(key)); } if (buffer.empty()) { return false; } try { auto ioBuffer = folly::IOBuf::wrapBuffer(buffer.data(), buffer.length()); auto codec = folly::io::getCodec( folly::io::CodecType::ZLIB, folly::io::COMPRESSION_LEVEL_BEST); auto compressed = codec->compress(ioBuffer.get()); compressed->coalesce(); out.reserve(compressed->length() + 1 + 8); out.append((char*)(&seq), 8); out.append(&kCompressedFileWithTimestampsMarker, 1); out.append((char*)compressed->data(), compressed->length()); } catch (const std::exception& e) { LOG(ERROR) << "Compression failed:" << e.what(); return false; } return true; } void PersistentKeyList::compact( std::function<std::tuple<uint32_t, const char*, uint16_t, int32_t>()> generator) { // Direct appends to a new file. int64_t prev = openNext(); // Create a temporary compressed file. auto tempFile = files_.open(kTempFileId, "wb", kLargeBufferSize); if (!tempFile.file) { PLOG(ERROR) << "Could not open a temp file for writing keys"; GorillaStatsManager::addStatValue(kFailedCounter, 1); return; } if (!compactToFile(tempFile.file, tempFile.name, generator)) { return; } files_.rename(kTempFileId, prev); // Clean up remaining files. files_.clearTo(prev); } void PersistentKeyList::flush(bool hardFlush) { if (activeList_.file == nullptr) { openNext(); } if (activeList_.file != nullptr) { if (buffer_.length() > 0) { size_t written = fwrite( buffer_.data(), sizeof(char), buffer_.length(), activeList_.file); if (written != buffer_.length()) { PLOG(ERROR) << "Failed to flush key list file " << activeList_.name; GorillaStatsManager::addStatValue(kFailedCounter, 1); } buffer_ = ""; } if (hardFlush) { fflush(activeList_.file); } } else { // No file to flush to. LOG(ERROR) << "Could not flush key list for shard " << shard_ << " to disk. No open key_list file"; GorillaStatsManager::addStatValue(kFailedCounter, 1); } } void PersistentKeyList::clearEntireListForTests() { files_.clearAll(); openNext(); } int64_t PersistentKeyList::openNext() { std::lock_guard<std::mutex> guard(lock_); if (activeList_.file != nullptr) { fclose(activeList_.file); } std::vector<int64_t> ids = files_.ls(); int64_t activeId = ids.empty() ? 1 : ids.back() + 1; activeList_ = files_.open(activeId, "wb", kSmallBufferSize); int i = 0; while (activeList_.file == nullptr && i < KRetryFileOpen) { activeList_ = files_.open(activeId, "wb", kSmallBufferSize); i++; } if (activeList_.file == nullptr) { PLOG(ERROR) << "Couldn't open key_list." << activeId << " for writes (shard " << shard_ << ")"; return activeId - 1; } if (fwrite( &kUncompressedFileWithTimestampsMarker, sizeof(char), 1, activeList_.file) != 1) { PLOG(ERROR) << "Could not write to the key list file " << activeList_.name; GorillaStatsManager::addStatValue(kFailedCounter, 1); } return activeId - 1; } void PersistentKeyList::appendBuffer( folly::fbstring& buffer, uint32_t id, const char* key, uint16_t category, int32_t timestamp) { const char* bytes = (const char*)&id; for (int i = 0; i < sizeof(id); i++) { buffer += bytes[i]; } const char* categoryBytes = (const char*)&category; for (int i = 0; i < sizeof(category); i++) { buffer += categoryBytes[i]; } const char* timestampBytes = (const char*)&timestamp; for (int i = 0; i < sizeof(timestamp); i++) { buffer += timestampBytes[i]; } buffer += key; buffer += '\0'; } void PersistentKeyList::writeKey( uint32_t id, const char* key, uint16_t category, int32_t timestamp) { // Write to the internal buffer and only flush when needed. appendBuffer(buffer_, id, key, category, timestamp); bool flushHard = time(nullptr) > nextHardFlushTimeSecs_; if (flushHard) { nextHardFlushTimeSecs_ = time(nullptr) + kHardFlushIntervalSecs; } if (buffer_.length() >= kSmallBufferSize || flushHard) { flush(flushHard); } } std::unique_ptr<PersistentKeyListIf> LocalPersistentKeyListFactory::getPersistentKeyList( int64_t shardId, const std::string& dir) const { return std::make_unique<PersistentKeyList>(shardId, dir); } void PersistentKeyList::appendMarker(folly::fbstring& buffer, bool compressed) { if (compressed) { buffer += kCompressedFileWithTimestampsMarker; } else { buffer += kUncompressedFileWithTimestampsMarker; } } void PersistentKeyList::appendOpMarker(folly::fbstring& buffer, bool append) { if (append) { buffer += kAppendMarker; } else { buffer += kDeleteMarker; } } } // namespace gorilla } // namespace facebook
28.127389
80
0.657043
pidb
6982ae7daea8bc7ac6ef3a9e090b5eb2fe8ccd3b
18,104
cpp
C++
engine/rendering/interface_renderer.cpp
jose-villegas/VCT_Engine
5ac2077e6ffc240a6d1f0ac0f033ac81e8ed57e3
[ "MIT" ]
459
2016-03-16T04:11:37.000Z
2022-03-31T08:05:21.000Z
engine/rendering/interface_renderer.cpp
jose-villegas/VCT_Engine
5ac2077e6ffc240a6d1f0ac0f033ac81e8ed57e3
[ "MIT" ]
2
2016-08-08T18:26:27.000Z
2017-05-08T23:42:22.000Z
engine/rendering/interface_renderer.cpp
jose-villegas/VCT_Engine
5ac2077e6ffc240a6d1f0ac0f033ac81e8ed57e3
[ "MIT" ]
47
2016-05-31T15:55:52.000Z
2022-03-28T14:49:40.000Z
#include <GL/glew.h> #include <GLFW/glfw3.h> #include "interface_renderer.h" #ifdef _WIN32 #undef APIENTRY #define GLFW_EXPOSE_NATIVE_WIN32 #define GLFW_EXPOSE_NATIVE_WGL #include <GLFW/glfw3native.h> #endif #include "../rendering/render_window.h" #include <glm/mat4x4.hpp> #include <glm/gtc/type_ptr.hpp> std::unique_ptr<InterfaceRenderer::RendererData> InterfaceRenderer::renderer = nullptr; InterfaceRenderer::InterfaceRenderer() { } InterfaceRenderer::~InterfaceRenderer() { } void InterfaceRenderer::RenderDrawList(ImDrawData * drawData) { // Backup GL state GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer); GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); GLint last_blend_src; glGetIntegerv(GL_BLEND_SRC, &last_blend_src); GLint last_blend_dst; glGetIntegerv(GL_BLEND_DST, &last_blend_dst); GLint last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb); GLint last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha); GLboolean last_enable_blend = glIsEnabled(GL_BLEND); GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE); GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST); GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST); // Setup render state: alpha-blending enabled, // no face culling, no depth testing, scissor enabled glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glEnable(GL_SCISSOR_TEST); glActiveTexture(GL_TEXTURE0); // Handle cases of screen coordinates != from // framebuffer coordinates (e.g. retina displays) ImGuiIO &io = ImGui::GetIO(); float fb_height = io.DisplaySize.y * io.DisplayFramebufferScale.y; drawData->ScaleClipRects(io.DisplayFramebufferScale); // Setup orthographic projection matrix static glm::mat4x4 ortho_projection = { { 7.7f, 0.0f, 0.0f, 0.0f }, { 0.0f, 7.7f, 0.0f, 0.0f }, { 0.0f, 0.0f, -1.0f, 0.0f }, { -1.0f, 1.0f, 0.0f, 1.0f }, }; ortho_projection[0][0] = 2.0f / io.DisplaySize.x; ortho_projection[1][1] = 2.0f / -io.DisplaySize.y; glUseProgram(renderer->shaderHandle); glUniform1i(renderer->attribLocationTex, 0); glUniformMatrix4fv(renderer->attribLocationProjMtx, 1, GL_FALSE, glm::value_ptr(ortho_projection)); glBindVertexArray(renderer->vaoHandle); for (int index = 0; index < drawData->CmdListsCount; index++) { const ImDrawList * cmd_list = drawData->CmdLists[index]; const ImDrawIdx * idx_buffer_offset = 0; glBindBuffer(GL_ARRAY_BUFFER, renderer->vboHandle); glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.size() * sizeof(ImDrawVert), (GLvoid *)&cmd_list->VtxBuffer.front(), GL_STREAM_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, renderer->elementsHandle); glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx), (GLvoid *)&cmd_list->IdxBuffer.front(), GL_STREAM_DRAW); for (const ImDrawCmd * pcmd = cmd_list->CmdBuffer.begin(); pcmd != cmd_list->CmdBuffer.end(); pcmd++) { if (pcmd->UserCallback) { pcmd->UserCallback(cmd_list, pcmd); } else { glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y)); glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, GL_UNSIGNED_SHORT, idx_buffer_offset); } idx_buffer_offset += pcmd->ElemCount; } } // Restore modified GL state glUseProgram(last_program); glBindTexture(GL_TEXTURE_2D, last_texture); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer); glBindVertexArray(last_vertex_array); glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha); glBlendFunc(last_blend_src, last_blend_dst); if (last_enable_blend) { glEnable(GL_BLEND); } else { glDisable(GL_BLEND); } if (last_enable_cull_face) { glEnable(GL_CULL_FACE); } else { glDisable(GL_CULL_FACE); } if (last_enable_depth_test) { glEnable(GL_DEPTH_TEST); } else { glDisable(GL_DEPTH_TEST); } if (last_enable_scissor_test) { glEnable(GL_SCISSOR_TEST); } else { glDisable(GL_SCISSOR_TEST); } } void InterfaceRenderer::Initialize(const RenderWindow &activeWindow, bool instantCallbacks /* = true */) { if (!renderer) { renderer = std::make_unique<RendererData>(); } renderer->window = activeWindow.Handler(); ImGuiIO &io = ImGui::GetIO(); // Keyboard mapping. ImGui will use those indices to peek // into the io.KeyDown[] array. io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT; io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP; io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN; io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP; io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN; io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME; io.KeyMap[ImGuiKey_End] = GLFW_KEY_END; io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE; io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE; io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER; io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE; io.KeyMap[ImGuiKey_A] = GLFW_KEY_A; io.KeyMap[ImGuiKey_C] = GLFW_KEY_C; io.KeyMap[ImGuiKey_V] = GLFW_KEY_V; io.KeyMap[ImGuiKey_X] = GLFW_KEY_X; io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y; io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z; io.RenderDrawListsFn = RenderDrawList; io.SetClipboardTextFn = SetClipboardText; io.GetClipboardTextFn = GetClipboardText; #ifdef _WIN32 io.ImeWindowHandle = glfwGetWin32Window(renderer->window); #endif if (instantCallbacks) { glfwSetMouseButtonCallback(renderer->window, MouseButtonCallback); glfwSetScrollCallback(renderer->window, ScrollCallback); glfwSetKeyCallback(renderer->window, KeyCallback); glfwSetCharCallback(renderer->window, CharCallback); } int w, h, display_w, display_h;; glfwGetWindowSize(renderer->window, &w, &h); glfwGetFramebufferSize(renderer->window, &display_w, &display_h); io.DisplaySize.x = static_cast<float>(w); io.DisplaySize.y = static_cast<float>(h); io.DisplayFramebufferScale.x = static_cast<float>(display_w) / w; io.DisplayFramebufferScale.y = static_cast<float>(display_h) / h; } void InterfaceRenderer::Render() { if (renderer->disabled) { return; } ImGui::Render(); } void InterfaceRenderer::NewFrame() { if (renderer->disabled) { return; } if (!renderer->fontTexture) { CreateDeviceObjects(); } static auto &io = ImGui::GetIO(); if (glfwGetWindowAttrib(renderer->window, GLFW_RESIZABLE)) { // setup display size (every frame to accommodate for window resizing) static int w, h, display_w, display_h; glfwGetWindowSize(renderer->window, &w, &h); glfwGetFramebufferSize(renderer->window, &display_w, &display_h); io.DisplaySize.x = static_cast<float>(w); io.DisplaySize.y = static_cast<float>(h);; io.DisplayFramebufferScale.x = static_cast<float>(display_w) / w; io.DisplayFramebufferScale.y = static_cast<float>(display_h) / h; } // setup time step auto current_time = glfwGetTime(); io.DeltaTime = renderer->time > 0.0 ? static_cast<float>(current_time - renderer->time) : static_cast<float>(1.0f / 60.0f); renderer->time = current_time; // setup inputs // (we already got mouse wheel, keyboard keys // & characters from glfw callbacks polled in glfwPollEvents()) if (glfwGetWindowAttrib(renderer->window, GLFW_FOCUSED)) { // Mouse position in screen coordinates // (set to -1,-1 if no mouse / on another screen, etc.) double mouse_x, mouse_y; glfwGetCursorPos(renderer->window, &mouse_x, &mouse_y); io.MousePosPrev = io.MousePos; io.MousePos = ImVec2(static_cast<float>(mouse_x), static_cast<float>(mouse_y)); } else { io.MousePos = ImVec2(-1, -1); } for (auto i = 0; i < 3; i++) { io.MouseDown[i] = renderer->mousePressed[i] || glfwGetMouseButton(renderer->window, i) != 0; // If a mouse press event came, always pass it as // "this frame", so we don't miss click-release events // that are shorter than 1 frame. renderer->mousePressed[i] = false; } io.MouseWheel = renderer->mouseWheel; renderer->mouseWheel = 0.0f; // Hide OS mouse cursor if ImGui is drawing it if(io.MouseDrawCursor) { glfwSetInputMode(renderer->window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); } else { glfwSetInputMode(renderer->window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); } // Start the frame ImGui::NewFrame(); } void InterfaceRenderer::CreateFontsTexture() { ImGuiIO &io = ImGui::GetIO(); // Build texture atlas unsigned char * pixels; int width, height; // Load as RGBA 32-bits for OpenGL3 demo because it is more // likely to be compatible with user's existing shader. io.Fonts->AddFontFromFileTTF("assets\\fonts\\DroidSans.ttf", 13); io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Create OpenGL texture glGenTextures(1, &renderer->fontTexture); glBindTexture(GL_TEXTURE_2D, renderer->fontTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); // Store our identifier io.Fonts->TexID = (void *)(intptr_t)renderer->fontTexture; } void InterfaceRenderer::CreateDeviceObjects() { // Backup GL state GLint last_texture, last_array_buffer, last_vertex_array; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); auto vertex_shader = "#version 330\n" "uniform mat4 ProjMtx;\n" "in vec2 Position;\n" "in vec2 UV;\n" "in vec4 Color;\n" "out vec2 Frag_UV;\n" "out vec4 Frag_Color;\n" "void main()\n" "{\n" " Frag_UV = UV;\n" " Frag_Color = Color;\n" " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" "}\n"; auto fragment_shader = "#version 330\n" "uniform sampler2D Texture;\n" "in vec2 Frag_UV;\n" "in vec4 Frag_Color;\n" "out vec4 Out_Color;\n" "void main()\n" "{\n" " Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n" "}\n"; renderer->shaderHandle = glCreateProgram(); renderer->vertHandle = glCreateShader(GL_VERTEX_SHADER); renderer->fragHandle = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(renderer->vertHandle, 1, &vertex_shader, 0); glShaderSource(renderer->fragHandle, 1, &fragment_shader, 0); glCompileShader(renderer->vertHandle); glCompileShader(renderer->fragHandle); glAttachShader(renderer->shaderHandle, renderer->vertHandle); glAttachShader(renderer->shaderHandle, renderer->fragHandle); glLinkProgram(renderer->shaderHandle); renderer->attribLocationTex = glGetUniformLocation (renderer->shaderHandle, "Texture"); renderer->attribLocationProjMtx = glGetUniformLocation (renderer->shaderHandle, "ProjMtx"); renderer->attribLocationPosition = glGetAttribLocation (renderer->shaderHandle, "Position"); renderer->attribLocationUV = glGetAttribLocation (renderer->shaderHandle, "UV"); renderer->attribLocationColor = glGetAttribLocation (renderer->shaderHandle, "Color"); glGenBuffers(1, &renderer->vboHandle); glGenBuffers(1, &renderer->elementsHandle); glGenVertexArrays(1, &renderer->vaoHandle); glBindVertexArray(renderer->vaoHandle); glBindBuffer(GL_ARRAY_BUFFER, renderer->vboHandle); glEnableVertexAttribArray(renderer->attribLocationPosition); glEnableVertexAttribArray(renderer->attribLocationUV); glEnableVertexAttribArray(renderer->attribLocationColor); #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) glVertexAttribPointer(renderer->attribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid *) OFFSETOF(ImDrawVert, pos)); glVertexAttribPointer(renderer->attribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid *) OFFSETOF(ImDrawVert, uv)); glVertexAttribPointer(renderer->attribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid *) OFFSETOF(ImDrawVert, col)); #undef OFFSETOF CreateFontsTexture(); // Restore modified GL state glBindTexture(GL_TEXTURE_2D, last_texture); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); glBindVertexArray(last_vertex_array); } void InterfaceRenderer::Terminate() { if (renderer->vaoHandle) { glDeleteVertexArrays(1, &renderer->vaoHandle); } if (renderer->vboHandle) { glDeleteBuffers(1, &renderer->vboHandle); } if (renderer->elementsHandle) { glDeleteBuffers(1, &renderer->elementsHandle); } renderer->vaoHandle = renderer->vboHandle = renderer->elementsHandle = 0; glDetachShader(renderer->shaderHandle, renderer->vertHandle); glDeleteShader(renderer->vertHandle); renderer->vertHandle = 0; glDetachShader(renderer->shaderHandle, renderer->fragHandle); glDeleteShader(renderer->fragHandle); renderer->fragHandle = 0; glDeleteProgram(renderer->shaderHandle); renderer->shaderHandle = 0; if (renderer->fontTexture) { glDeleteTextures(1, &renderer->fontTexture); ImGui::GetIO().Fonts->TexID = 0; renderer->fontTexture = 0; } ImGui::Shutdown(); delete renderer.release(); } void InterfaceRenderer::InvalidateDeviceObjects() { if (renderer->vaoHandle) { glDeleteVertexArrays(1, &renderer->vaoHandle); } if (renderer->vboHandle) { glDeleteBuffers(1, &renderer->vboHandle); } if (renderer->elementsHandle) { glDeleteBuffers(1, &renderer->elementsHandle); } renderer->vaoHandle = renderer->vboHandle = renderer->elementsHandle = 0; glDetachShader(renderer->shaderHandle, renderer->vertHandle); glDeleteShader(renderer->vertHandle); renderer->vertHandle = 0; glDetachShader(renderer->shaderHandle, renderer->fragHandle); glDeleteShader(renderer->fragHandle); renderer->fragHandle = 0; glDeleteProgram(renderer->shaderHandle); renderer->shaderHandle = 0; if (renderer->fontTexture) { glDeleteTextures(1, &renderer->fontTexture); ImGui::GetIO().Fonts->TexID = 0; renderer->fontTexture = 0; } ImGui::Shutdown(); } void InterfaceRenderer::MouseButtonCallback(GLFWwindow * window, int button, int action, int mods) { auto &io = ImGui::GetIO(); if (action == GLFW_PRESS && button >= 0 && button < 3) { renderer->mousePressed[button] = true; } io.MouseClickedPos[button] = io.MousePos; } void InterfaceRenderer::ScrollCallback(GLFWwindow * window, double xoffset, double yoffset) { // Use fractional mouse wheel, 1.0 unit 5 lines. renderer->mouseWheel += static_cast<float>(yoffset); } void InterfaceRenderer::KeyCallback(GLFWwindow * window, int key, int scancode, int action, int mods) { auto &io = ImGui::GetIO(); if (action == GLFW_PRESS) { io.KeysDown[key] = true; } if (action == GLFW_RELEASE) { io.KeysDown[key] = false; } (void)mods; // Modifiers are not reliable across systems io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL]; io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT]; io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT]; if (io.KeysDown[GLFW_KEY_H]) { renderer->disabled = !renderer->disabled; } } void InterfaceRenderer::CharCallback(GLFWwindow * window, unsigned int c) { auto &io = ImGui::GetIO(); if (c > 0 && c < 0x10000) { io.AddInputCharacter(static_cast<unsigned short>(c)); } } void InterfaceRenderer::SetClipboardText(const char * text) { glfwSetClipboardString(renderer->window, text); } const char * InterfaceRenderer::GetClipboardText() { return glfwGetClipboardString(renderer->window); }
36.280561
84
0.664936
jose-villegas
69842144a324549cc2ff5058fbe25fcd8ff10ce4
67
cpp
C++
Source/Cross/Common/MoCore/TNetPackageHead.cpp
favedit/MoCross
2a550b3d41b0c33c44c66dd595e84b0e4ee95b08
[ "Apache-2.0" ]
3
2016-10-26T11:48:58.000Z
2017-10-24T18:35:17.000Z
Source/Cross/Common/MoCore/TNetPackage.cpp
favedit/MoCross
2a550b3d41b0c33c44c66dd595e84b0e4ee95b08
[ "Apache-2.0" ]
null
null
null
Source/Cross/Common/MoCore/TNetPackage.cpp
favedit/MoCross
2a550b3d41b0c33c44c66dd595e84b0e4ee95b08
[ "Apache-2.0" ]
6
2015-03-24T06:40:20.000Z
2019-03-18T13:56:13.000Z
#include "MoCrNetMessage.h" MO_NAMESPACE_BEGIN MO_NAMESPACE_END
9.571429
27
0.835821
favedit
69851858aa479b61453717cd35502afcefdd8237
218
cpp
C++
CGraphMan.cpp
Satervalley/Kamac-git
83b916684c1397f10319793f87d8c3ab90edbad4
[ "WTFPL" ]
1
2019-12-08T02:20:12.000Z
2019-12-08T02:20:12.000Z
CGraphMan.cpp
Satervalley/Kamac-git
83b916684c1397f10319793f87d8c3ab90edbad4
[ "WTFPL" ]
null
null
null
CGraphMan.cpp
Satervalley/Kamac-git
83b916684c1397f10319793f87d8c3ab90edbad4
[ "WTFPL" ]
null
null
null
#include "pch.h" #include "CGraphMan.h" int CDataGroup_3::nPos[]{ nMargin, nMargin + nColumnWidth + nGap, nMargin + (nColumnWidth + nGap) * 2 }; //DWORD CDataGroup_3::clrColors[]{ 0x00ff5252, 0x0069f0ae, 0x448aff };
31.142857
104
0.711009
Satervalley
698dfd407cff4168ce393de15c57e62d52f989b1
1,360
cpp
C++
test/ssvr/srv_dev_mng.cpp
walkthetalk/libem
6619b48716b380420157c4021f9943b153998e09
[ "Apache-2.0" ]
2
2015-03-13T14:49:13.000Z
2017-09-18T12:38:59.000Z
test/ssvr/srv_dev_mng.cpp
walkthetalk/libem
6619b48716b380420157c4021f9943b153998e09
[ "Apache-2.0" ]
null
null
null
test/ssvr/srv_dev_mng.cpp
walkthetalk/libem
6619b48716b380420157c4021f9943b153998e09
[ "Apache-2.0" ]
null
null
null
#include <limits> #include <exemodel/poll_tools.hpp> #include "srv_dev_mng.hpp" #include <iostream> #include <fstream> #include <string.h> #include <openssl/md5.h> namespace svcDevMng { svcDeviceManager::svcDeviceManager(uint16_t port) : serverExt(port) , m_pkgc(0) { register_callback<bmid_t::sendUpdateData>( [this](std::vector<uint8_t> & data) { std::cout << "sendUpdateData" << std::endl; std::string pos_str; //data [0-31] std::string size_str; //data [32-63] std::vector<uint8_t>::iterator iter; for (int i=0; i < 64; i++) { iter = data.begin(); if (i < 32) { pos_str += *iter; } else { size_str += *iter; } data.erase(iter); } int pos = std::atoi(pos_str.c_str()); int size = std::atoi(size_str.c_str()); std::cout << pos << "," << size << std::endl; std::ofstream file; file.open("/tmp/udisk/updatePackage.tar.gz", std::ios::out|std::ios::in|std::ios::binary); if (!file.is_open()) { file.open("/tmp/udisk/updatePackage.tar.gz",std::ios::out|std::ios::binary); } file.seekp(pos, std::ios::beg); for (int i=0; i < size; i++) { file << data[i]; } file.close(); m_pkgc++; std::cout << m_pkgc << std::endl; } ); } svcDeviceManager::~svcDeviceManager() { } void svcDeviceManager::fifo_processer(std::vector<uint8_t> &) { } }
19.710145
93
0.602941
walkthetalk
698e5837bba52095c90b808c90252db6253d15e2
3,266
cpp
C++
opengl_4_shading_language_cookbook/017-compiling_a_shader/CompilingAShader.cpp
mickbeaver/graphics
2b95c03677dfbb808048f53326e8c98e2d8775e1
[ "BSD-2-Clause" ]
null
null
null
opengl_4_shading_language_cookbook/017-compiling_a_shader/CompilingAShader.cpp
mickbeaver/graphics
2b95c03677dfbb808048f53326e8c98e2d8775e1
[ "BSD-2-Clause" ]
null
null
null
opengl_4_shading_language_cookbook/017-compiling_a_shader/CompilingAShader.cpp
mickbeaver/graphics
2b95c03677dfbb808048f53326e8c98e2d8775e1
[ "BSD-2-Clause" ]
null
null
null
#include <cstdio> #include <cstdlib> #include <SDL2/SDL.h> #include "glsys.h" #include "FileUtil.h" #define WINDOW_SIZE 640 void printShaderInfoLog(GLuint shaderHandle) { GLint logLength; glGetShaderiv(shaderHandle, GL_INFO_LOG_LENGTH, &logLength); if (logLength > 0) { char* logBuffer = new char[logLength]; GLsizei bytesCopied; glGetShaderInfoLog(shaderHandle, logLength, &bytesCopied, logBuffer); (void)fprintf(stderr, "Shader info log:\n%s\n", logBuffer); delete [] logBuffer; exit(EXIT_FAILURE); } } int main(int argc, char** argv) { (void)argc; (void)argv; int retval = SDL_Init(SDL_INIT_VIDEO); if (retval != 0) { (void)fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError()); exit(EXIT_FAILURE); } SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); Uint32 glContextFlags = SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG; #ifdef DEBUG glContextFlags |= SDL_GL_CONTEXT_DEBUG_FLAG; #endif SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, glContextFlags); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_ClearError(); SDL_Window* mainWindow = SDL_CreateWindow("Compiling a Shader", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOW_SIZE, WINDOW_SIZE, SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN); if (mainWindow == NULL) { (void)fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError()); exit(EXIT_FAILURE); } SDL_GLContext mainContext = SDL_GL_CreateContext(mainWindow); if (mainContext == NULL) { (void)fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError()); exit(EXIT_FAILURE); } retval = glsysLoadFunctions((glsysFunctionLoader)SDL_GL_GetProcAddress); if (retval != 0) { (void)fprintf(stderr, "Error loading GL functions\n"); exit(EXIT_FAILURE); } GLuint vertShader = glCreateShader(GL_VERTEX_SHADER); if (vertShader == 0) { (void)fprintf(stderr, "Error creating vertex shader.\n"); exit(EXIT_FAILURE); } const GLchar* shaderCode = FileUtil::loadFileAsString("basic.vert"); glShaderSource(vertShader, 1, &shaderCode, NULL); delete [] shaderCode; glCompileShader(vertShader); GLint result; glGetShaderiv(vertShader, GL_COMPILE_STATUS, &result); if (result == GL_FALSE) { (void)fprintf(stderr, "Vertex shader compilation failed!\n"); printShaderInfoLog(vertShader); } else { (void)printf("Shader compiled successfully!\n"); // Print warnings, if available printShaderInfoLog(vertShader); } SDL_GL_DeleteContext(mainContext); SDL_DestroyWindow(mainWindow); SDL_Quit(); return 0; }
33.670103
86
0.621249
mickbeaver
7e36c09a63af28d59cf7322130589d231a1ebe4e
900
cc
C++
UX/src/Point.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
null
null
null
UX/src/Point.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
null
null
null
UX/src/Point.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
null
null
null
/* * Copyright (C) 2022 Frank Mertens. * * Distribution and use is allowed under the terms of the zlib license * (see cc/LICENSE-zlib). * */ #include <cc/Point> #include <limits> namespace cc { template class Vector<double, 2>; /** Get positive angle of vector \a v * \return Angle in range [0, 2*PI) */ double angle(Point v) { using std::numbers::pi; if (v[0] == 0) { if (v[1] == 0) return std::numeric_limits<double>::quiet_NaN(); if (v[1] > 0) return pi/2; return 3 * pi / 2; } else if (v[1] == 0) { if (v[0] > 0) return 0; return pi; } double alpha = std::atan(v[1]/v[0]); if (v[0] < 0) alpha += pi; else if (v[1] < 0) alpha += 2 * pi; return alpha; } double abs(Point v) { if (v[0] == 0) return std::abs(v[1]); else if (v[1] == 0) return std::abs(v[0]); return v.abs(); } } // namespace cc
19.565217
71
0.538889
frankencode
7e39eb52a5dda75eb6f304a1b3bbc6686046148f
240
cpp
C++
src/analysis/parts/resample.cpp
autumnsault/speech-analysis
6d2b683f0afa47d098b95f6be59534ed7d277361
[ "MIT" ]
null
null
null
src/analysis/parts/resample.cpp
autumnsault/speech-analysis
6d2b683f0afa47d098b95f6be59534ed7d277361
[ "MIT" ]
null
null
null
src/analysis/parts/resample.cpp
autumnsault/speech-analysis
6d2b683f0afa47d098b95f6be59534ed7d277361
[ "MIT" ]
1
2020-04-02T11:58:29.000Z
2020-04-02T11:58:29.000Z
// // Created by rika on 16/11/2019. // #include "../Analyser.h" #include "Signal/Resample.h" using namespace Eigen; void Analyser::resampleAudio(double newFs) { x = std::move(Resample::resample(x, fs, newFs, 50)); fs = newFs; }
17.142857
56
0.654167
autumnsault
7e3aa7b4ded7f1cffe37f511219cb0a16af34f0e
401
cc
C++
tools/Packers/source/ContainerEvolved.cc
fstudio/Phoenix
28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d
[ "MIT" ]
8
2015-01-23T05:41:46.000Z
2019-11-20T05:10:27.000Z
tools/Packers/source/ContainerEvolved.cc
fstudio/Phoenix
28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d
[ "MIT" ]
null
null
null
tools/Packers/source/ContainerEvolved.cc
fstudio/Phoenix
28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d
[ "MIT" ]
4
2015-05-05T05:15:43.000Z
2020-03-07T11:10:56.000Z
/********************************************************************************************************* * ContainerEvolved.cc * Note: Phoenix Container Evolved * Date: @2015.05 * Author: Force Charlie * E-mail:<forcemz@outlook.com> * Copyright (C) 2015 The ForceStudio All Rights Reserved. **********************************************************************************************************/
44.555556
107
0.349127
fstudio
7e548d755ce70aceef0a4a7a7cdacff948c7ec28
5,534
cpp
C++
libevent-example/message.cpp
anancds/rpc
345a93915ec1a02e88e71678df695ee1302869df
[ "MIT" ]
1
2021-01-10T02:34:13.000Z
2021-01-10T02:34:13.000Z
libevent-example/message.cpp
anancds/rpc
345a93915ec1a02e88e71678df695ee1302869df
[ "MIT" ]
1
2021-03-11T02:21:41.000Z
2021-03-11T02:21:41.000Z
libevent-example/message.cpp
anancds/rpc
345a93915ec1a02e88e71678df695ee1302869df
[ "MIT" ]
null
null
null
// // Created by cds on 2020/9/23. // #include "message.h" #include <event2/buffer.h> #include <event2/bufferevent.h> #include <event2/event.h> #include <event2/listener.h> #include <event2/util.h> #include <stdio.h> #include <time.h> #include <iostream> #include <map> #include <string.h> #include <vector> #include <arpa/inet.h> //#include <netinet/in.h> using namespace std; #define PORT 1234 #define HEADER_LENGTH 12 #define BUFFER_SIZE (16 * 1024) #define READ_SIZE (16 * 1024) #define MAX_PACKET_SIZE (256) #define IMTE_INTERVAL (5000) const char ip_address[] = "127.0.0.1"; map<unsigned int, bufferevent *> ClientMap; // client id 对应的bufferevent int conectNumber = 0; int dataSize = 0; int lastTime = 0; int receiveNumber = 0; int sendNumber = 0; int main(int argc, char **argv) { cout << "Server begin running!" << endl; struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.S_un.S_addr = inet_addr(ip_address); sin.sin_port = htons(PORT); struct evconnlistener *listener; struct event_base *base = event_base_new(); if (!base) { cout << "Could not initialize libevent" << endl; ; return 1; } //默认情况下,链接监听器接收新套接字后,会将其设置为非阻塞的 listener = evconnlistener_new_bind(base, listener_cb, (void *)base, LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE, -1, (struct sockaddr *)&sin, sizeof(sin)); if (!listener) { cout << "Could not create a listener" << endl; return 1; } event_base_dispatch(base); evconnlistener_free(listener); event_base_free(base); return 0; } void listener_cb(struct evconnlistener *listener, evutil_socket_t fd, struct sockaddr *sa, int socklen, void *user_data) { cout << "Detect an connection" << endl; struct event_base *base = (struct event_base *)user_data; struct bufferevent *bev; // BEV_OPT_CLOSE_ON_FREE close the file descriptor when this bufferevent is freed bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE); if (!bev) { cout << "Could not create a bufferevent" << endl; event_base_loopbreak(base); return; } ClientMap[++conectNumber] = bev; // read write event bufferevent_setcb(bev, conn_readcb, NULL, conn_eventcb, NULL); bufferevent_enable(bev, EV_READ | EV_WRITE); // send a message to client when connect is succeeded string msg = "connedted"; Header header; header.sourceID = 0; header.targetID = conectNumber; header.length = msg.size(); write_buffer(msg, bev, header); } void conn_writecb(struct bufferevent *bev, void *user_data) { Sleep(2000); int len = 0; Header header; unsigned int toID = get_client_id(bev); string msg = "hello client " + inttostr(toID); header.targetID = toID; header.sourceID = 0; header.length = msg.size(); write_buffer(msg, bev, header); } void conn_readcb(struct bufferevent *bev, void *user_data) { struct evbuffer *input = bufferevent_get_input(bev); size_t sz = evbuffer_get_length(input); unsigned int sourceID = get_client_id(bev); while (sz >= MAX_PACKET_SIZE) { char msg[MAX_PACKET_SIZE] = {0}; char *ptr = msg; bufferevent_read(bev, ptr, HEADER_LENGTH); unsigned int len = ((Header *)ptr)->length; unsigned int targetID = ((Header *)ptr)->targetID; ((Header *)ptr)->sourceID = sourceID; ptr += HEADER_LENGTH; if (sz < len + HEADER_LENGTH) { break; } bufferevent_read(bev, ptr, len); receiveNumber++; dataSize += len + HEADER_LENGTH; if (ClientMap.find(targetID) != ClientMap.end()) { sendNumber++; bufferevent_write(ClientMap[targetID], msg, len + HEADER_LENGTH); } else { // can't find } sz = evbuffer_get_length(input); } // calculate the speed of data and packet clock_t nowtime = clock(); if (lastTime == 0) { lastTime = nowtime; } else { cout << "client number: " << ClientMap.size() << " "; cout << "data speed: " << (double)dataSize / (nowtime - lastTime) << "k/s "; cout << "packet speed: receive " << (double)receiveNumber / (nowtime - lastTime) << "k/s "; cout << "send " << (double)sendNumber / (nowtime - lastTime) << "k/s" << endl; if (nowtime - lastTime > TIME_INTERVAL) { dataSize = 0; lastTime = nowtime; receiveNumber = 0; sendNumber = 0; } } } void conn_eventcb(struct bufferevent *bev, short events, void *user_data) { if (events & BEV_EVENT_EOF) { cout << "Connection closed" << endl; } else if (events & BEV_EVENT_ERROR) { cout << "Got an error on the connection: " << strerror(errno) << endl; } bufferevent_free(bev); } unsigned int get_client_id(struct bufferevent *bev) { for (auto p = ClientMap.begin(); p != ClientMap.end(); p++) { if (p->second == bev) { return p->first; } } return 0; } void write_buffer(string &msg, struct bufferevent *bev, Header &header) { char send_msg[BUFFER_SIZE] = {0}; char *ptr = send_msg; int len = 0; memcpy(ptr, &header, sizeof(Header)); len += sizeof(Header); ptr += sizeof(Header); memcpy(ptr, msg.c_str(), msg.size()); len += msg.size(); bufferevent_write(bev, send_msg, len); } string inttostr(int num) { string result; bool neg = false; if (num < 0) { neg = true; num = -num; } if (num == 0) { result += '0'; } else { while (num > 0) { int rem = num % 10; result = (char)(rem + '0') + result; num /= 10; } } if (neg) { result = '-' + result; } return result; }
25.385321
116
0.644742
anancds
7e5799ca381a57dcd3ffbc7a25c21511d137171b
245
hpp
C++
include/member_thunk/error/region_not_empty.hpp
sylveon/member_thunk
1ac81a983e951678638be7785de2cce2d9f73151
[ "MIT" ]
9
2019-12-02T11:59:24.000Z
2022-02-28T06:34:59.000Z
include/member_thunk/error/region_not_empty.hpp
sylveon/member_thunk
1ac81a983e951678638be7785de2cce2d9f73151
[ "MIT" ]
29
2019-11-26T17:12:33.000Z
2020-10-06T04:58:53.000Z
include/member_thunk/error/region_not_empty.hpp
sylveon/member_thunk
1ac81a983e951678638be7785de2cce2d9f73151
[ "MIT" ]
null
null
null
#pragma once #include "./exception.hpp" namespace member_thunk { class region_not_empty final : public exception { public: constexpr region_not_empty() noexcept : exception("This region has been destroyed before being emptied.") { } }; }
20.416667
111
0.746939
sylveon
7e58b79975cc0b346c9a1625914694555b9d8901
4,173
cxx
C++
PWGJE/EMCALJetTasks/Tracks/AliAnalysisTaskEmcalOutliersGen.cxx
ilyafokin/AliPhysics
7a0021a9d7ad4f0a9e52e0a13f9d3ca3b74c63d4
[ "BSD-3-Clause" ]
1
2020-07-18T17:36:58.000Z
2020-07-18T17:36:58.000Z
PWGJE/EMCALJetTasks/Tracks/AliAnalysisTaskEmcalOutliersGen.cxx
ilyafokin/AliPhysics
7a0021a9d7ad4f0a9e52e0a13f9d3ca3b74c63d4
[ "BSD-3-Clause" ]
null
null
null
PWGJE/EMCALJetTasks/Tracks/AliAnalysisTaskEmcalOutliersGen.cxx
ilyafokin/AliPhysics
7a0021a9d7ad4f0a9e52e0a13f9d3ca3b74c63d4
[ "BSD-3-Clause" ]
1
2022-01-24T11:11:09.000Z
2022-01-24T11:11:09.000Z
#include <sstream> #include "AliAnalysisTaskEmcalOutliersGen.h" #include "AliAnalysisManager.h" #include "AliEmcalJet.h" #include "AliJetContainer.h" #include "AliMCEvent.h" #include "AliParticleContainer.h" #include "AliVParticle.h" ClassImp(PWGJE::EMCALJetTasks::AliAnalysisTaskEmcalOutliersGen) using namespace PWGJE::EMCALJetTasks; AliAnalysisTaskEmcalOutliersGen::AliAnalysisTaskEmcalOutliersGen(): AliAnalysisTaskEmcalJet(), fHistJetPt(nullptr) { } AliAnalysisTaskEmcalOutliersGen::AliAnalysisTaskEmcalOutliersGen(const char *name): AliAnalysisTaskEmcalJet(name, kTRUE), fHistJetPt(nullptr) { SetMakeGeneralHistograms(true); SetGetPtHardBinFromPath(kFALSE); SetIsPythia(true); } void AliAnalysisTaskEmcalOutliersGen::UserCreateOutputObjects() { AliAnalysisTaskEmcalJet::UserCreateOutputObjects(); fHistJetPt = new TH1F("fHistJetPt", "Jet pt", 1000, 0., 1000.); fOutput->Add(fHistJetPt); PostData(1, fOutput); } bool AliAnalysisTaskEmcalOutliersGen::Run() { auto particles = GetParticleContainer("mcparticlesSelected"); //auto particles = GetParticleContainer("mcparticles"); auto jets = GetJetContainer("partjets"); double partptmin[21] = {0., 20., 25., 30., 40., 50., 70., 80., 100., 120., 140., 180., 200., 250., 270., 300., 350., 380., 420., 450., 600.}; //std::cout << "Using pt-hard cut " << partptmin[fPtHardBin] << " for pt-hard bin " << fPtHardBin << std::endl; for(auto j : jets->accepted()){ fHistJetPt->Fill(j->Pt()); if(j->Pt() > partptmin[fPtHardBin]) { std::cout << "Outlier jet found, pt > " << j->Pt() << " GeV/c, NEF = " << j->NEF() << ", " << j->GetNumberOfTracks() << " / " << j->GetNumberOfClusters() << " constituents" << std::endl; for(int i = 0; i < j->GetNumberOfTracks(); i++){ auto part = j->TrackAt(i, particles->GetArray()); auto z = j->GetZ(part->Px(), part->Py(), part->Pz()); auto mother = part->GetMother() > -1 ? MCEvent()->GetTrack(part->GetMother()) : nullptr; std::cout << "Particle " << i << ": pt " << part->Pt() << " GeV/c, z " << z << ", pdg " << part->PdgCode(); if(mother) { std::cout << ", mother pdg " << mother->PdgCode() << ", mother pt " << mother->Pt(); auto grandmother = mother->GetMother() > -1 ? MCEvent()->GetTrack(mother->GetMother()) : nullptr; if(grandmother) { std::cout << ", grandmother pdg " << grandmother->PdgCode() << ", grandmother pt " << grandmother->Pt(); } else { std::cout << ", no grand mother"; } } else { std::cout << ", no mother"; } std::cout << std::endl; } } } return true; } AliAnalysisTaskEmcalOutliersGen *AliAnalysisTaskEmcalOutliersGen::AddTaskEmcalOutliersGen(const char *name) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if(!mgr){ ::Error("EmcalTriggerJets::AliAnalysisTaskEmcalJetEnergyScale::AddTaskJetEnergyScale", "No analysis manager available"); return nullptr; } auto task = new AliAnalysisTaskEmcalOutliersGen(name); mgr->AddTask(task); auto partcont = task->AddMCParticleContainer("mcparticlesSelected"); //auto partcont = task->AddMCParticleContainer("mcparticles"); partcont->SetMinPt(0.); auto contjet = task->AddJetContainer(AliJetContainer::kFullJet, AliJetContainer::antikt_algorithm, AliJetContainer::E_scheme, 0.2, AliJetContainer::kTPCfid, partcont, nullptr); contjet->SetName("partjets"); contjet->SetMaxTrackPt(1000.); std::stringstream outnamebuilder; outnamebuilder << mgr->GetCommonFileName() << ":Outliers"; mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, mgr->CreateContainer("OutlierHists", TList::Class(), AliAnalysisManager::kOutputContainer, outnamebuilder.str().data())); return task; }
40.514563
151
0.615385
ilyafokin
7e5a886dc544675b6477934205740aa2262e7048
4,568
cpp
C++
Source/MLApp/MLNetServiceHub.cpp
afofo/madronalib
14816a124c8d3a225540ffb408e602aa024fdb4b
[ "MIT" ]
null
null
null
Source/MLApp/MLNetServiceHub.cpp
afofo/madronalib
14816a124c8d3a225540ffb408e602aa024fdb4b
[ "MIT" ]
null
null
null
Source/MLApp/MLNetServiceHub.cpp
afofo/madronalib
14816a124c8d3a225540ffb408e602aa024fdb4b
[ "MIT" ]
null
null
null
// MadronaLib: a C++ framework for DSP applications. // Copyright (c) 2013 Madrona Labs LLC. http://www.madronalabs.com // Distributed under the MIT license: http://madrona-labs.mit-license.org/ /* Portions adapted from Oscbonjour: Copyright (c) 2005-2009 RÈmy Muller. 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. Any person wishing to distribute modifications to the Software is requested to send the modifications to the original developer so that they can be incorporated into the canonical version. 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 "MLPlatform.h" #if ML_WINDOWS // TODO #else #include "MLNetServiceHub.h" using namespace ZeroConf; //------------------------------------------------------------------------------------------------------------ MLNetServiceHub::MLNetServiceHub() : browser(0), resolver(0), service(0) { } MLNetServiceHub::~MLNetServiceHub() { if(browser) delete browser; if(resolver)delete resolver; if(service) delete service; } void MLNetServiceHub::Browse(const char *type, const char *domain) { if(browser) delete browser; browser = 0; browser = new NetServiceBrowser(); browser->setListener(this); browser->searchForServicesOfType(type, domain); } void MLNetServiceHub::Resolve(const char *name, const char *type, const char *domain) { if(resolver) delete resolver; resolver = 0; resolver = new NetService(domain,type,name); resolver->setListener(this); resolver->resolveWithTimeout(10.0, false); // ML temp } bool MLNetServiceHub::pollService(DNSServiceRef dnsServiceRef, double timeOutInSeconds, DNSServiceErrorType &err) { assert(dnsServiceRef); err = kDNSServiceErr_NoError; fd_set readfds; FD_ZERO(&readfds); int dns_sd_fd = DNSServiceRefSockFD(dnsServiceRef); int nfds = dns_sd_fd+1; FD_SET(dns_sd_fd, &readfds); struct timeval tv; tv.tv_sec = long(floor(timeOutInSeconds)); tv.tv_usec = long(1000000*(timeOutInSeconds - tv.tv_sec)); int result = select(nfds,&readfds,NULL,NULL,&tv); if(result>0 && FD_ISSET(dns_sd_fd, &readfds)) { err = DNSServiceProcessResult(dnsServiceRef); return true; } return false; } void MLNetServiceHub::PollNetServices() { if(resolver && resolver->getDNSServiceRef()) { printf("PollNetServices::polling...\n"); DNSServiceErrorType err = kDNSServiceErr_NoError; if(pollService(resolver->getDNSServiceRef(), 0.001, err)) { printf("PollNetServices::stop.\n"); resolver->stop(); } } } void MLNetServiceHub::publishUDPService(const char *name, int port) { if(service) delete service; service = 0; service = new NetService("local.", "_osc._udp", name, port); service->setListener(this); service->publish(false); } void MLNetServiceHub::didFindService(NetServiceBrowser* pNetServiceBrowser, NetService *pNetService, bool moreServicesComing) { veciterator it = std::find(services.begin(),services.end(), pNetService->getName()); if(it!=services.end()) return; // we already have it services.push_back(pNetService->getName()); } void MLNetServiceHub::didRemoveService(NetServiceBrowser *pNetServiceBrowser, NetService *pNetService, bool moreServicesComing) { veciterator it = std::find(services.begin(),services.end(), pNetService->getName()); if(it==services.end()) return; // we don't have it //long index = it-services.begin(); // store the position services.erase(it); } void MLNetServiceHub::didResolveAddress(NetService *pNetService) { // const std::string& hostName = pNetService->getHostName(); // int port = pNetService->getPort(); } void MLNetServiceHub::didPublish(NetService *pNetService) { } #endif // ML_WINDOWS
29.282051
127
0.734895
afofo
7e601575baaec490902abfffcded67583565afd8
11,044
cpp
C++
sources/leddevice/dev_net/ProviderUdpSSL.cpp
awawa-dev/hyperion.ng
459aa9b81fe04bfd7a259d761a0fdff94178e10d
[ "MIT-0", "Apache-2.0", "CC-BY-4.0", "MIT" ]
2
2020-08-24T10:02:51.000Z
2020-08-24T20:03:50.000Z
sources/leddevice/dev_net/ProviderUdpSSL.cpp
awawa-dev/hyperion.ng
459aa9b81fe04bfd7a259d761a0fdff94178e10d
[ "MIT-0", "Apache-2.0", "CC-BY-4.0", "MIT" ]
null
null
null
sources/leddevice/dev_net/ProviderUdpSSL.cpp
awawa-dev/hyperion.ng
459aa9b81fe04bfd7a259d761a0fdff94178e10d
[ "MIT-0", "Apache-2.0", "CC-BY-4.0", "MIT" ]
null
null
null
/* ProviderUdpSSL.cpp * * MIT License * * Copyright (c) 2021 awawa-dev * * Project homesite: https://github.com/awawa-dev/HyperHDR * * 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. */ // STL includes #include <cstdio> #include <exception> #include <algorithm> // Linux includes #include <fcntl.h> #ifndef _WIN32 #include <sys/ioctl.h> #endif #include <QUdpSocket> #include <QThread> // Local HyperHDR includes #include "ProviderUdpSSL.h" const int MAX_RETRY = 20; const ushort MAX_PORT_SSL = 65535; ProviderUdpSSL::ProviderUdpSSL(const QJsonObject& deviceConfig) : LedDevice(deviceConfig) , client_fd() , entropy() , ssl() , conf() , cacert() , ctr_drbg() , timer() , _transport_type("DTLS") , _custom("dtls_client") , _address("127.0.0.1") , _defaultHost("127.0.0.1") , _port(1) , _ssl_port(1) , _server_name() , _psk() , _psk_identity() , _handshake_attempts(5) , _retry_left(MAX_RETRY) , _streamReady(false) , _streamPaused(false) , _handshake_timeout_min(300) , _handshake_timeout_max(1000) { bool error = false; try { mbedtls_ctr_drbg_init(&ctr_drbg); error = !seedingRNG(); } catch (...) { error = true; } if (error) Error(_log, "Failed to initialize mbedtls seed"); } ProviderUdpSSL::~ProviderUdpSSL() { closeConnection(); mbedtls_ctr_drbg_free(&ctr_drbg); mbedtls_entropy_free(&entropy); } bool ProviderUdpSSL::init(const QJsonObject& deviceConfig) { bool isInitOK = false; // Initialise sub-class if (LedDevice::init(deviceConfig)) { //PSK Pre Shared Key _psk = deviceConfig["psk"].toString(); _psk_identity = deviceConfig["psk_identity"].toString(); _port = deviceConfig["sslport"].toInt(2100); _server_name = deviceConfig["servername"].toString(); if (deviceConfig.contains("transport_type")) _transport_type = deviceConfig["transport_type"].toString("DTLS"); if (deviceConfig.contains("seed_custom")) _custom = deviceConfig["seed_custom"].toString("dtls_client"); if (deviceConfig.contains("retry_left")) _retry_left = deviceConfig["retry_left"].toInt(MAX_RETRY); if (deviceConfig.contains("hs_attempts")) _handshake_attempts = deviceConfig["hs_attempts"].toInt(5); if (deviceConfig.contains("hs_timeout_min")) _handshake_timeout_min = deviceConfig["hs_timeout_min"].toInt(300); if (deviceConfig.contains("hs_timeout_max")) _handshake_timeout_max = deviceConfig["hs_timeout_max"].toInt(1000); QString host = deviceConfig["host"].toString(_defaultHost); if (_address.setAddress(host)) { Debug(_log, "Successfully parsed %s as an ip address.", QSTRING_CSTR(host)); } else { Debug(_log, "Failed to parse [%s] as an ip address.", QSTRING_CSTR(host)); QHostInfo info = QHostInfo::fromName(host); if (info.addresses().isEmpty()) { Debug(_log, "Failed to parse [%s] as a hostname.", QSTRING_CSTR(host)); QString errortext = QString("Invalid target address [%1]!").arg(host); this->setInError(errortext); isInitOK = false; } else { Debug(_log, "Successfully parsed %s as a hostname.", QSTRING_CSTR(host)); _address = info.addresses().first(); } } int config_port = deviceConfig["sslport"].toInt(_port); if (config_port <= 0 || config_port > MAX_PORT_SSL) { QString errortext = QString("Invalid target port [%1]!").arg(config_port); this->setInError(errortext); isInitOK = false; } else { _ssl_port = config_port; Debug(_log, "UDP SSL using %s:%u", QSTRING_CSTR(_address.toString()), _ssl_port); isInitOK = true; } } return isInitOK; } const int* ProviderUdpSSL::getCiphersuites() const { return mbedtls_ssl_list_ciphersuites(); } bool ProviderUdpSSL::initNetwork() { if ((!_isDeviceReady || _streamPaused) && _streamReady) closeConnection(); if (!initConnection()) return false; return true; } int ProviderUdpSSL::closeNetwork() { closeConnection(); return 0; } bool ProviderUdpSSL::initConnection() { if (_streamReady) return true; mbedtls_net_init(&client_fd); mbedtls_ssl_init(&ssl); mbedtls_ssl_config_init(&conf); mbedtls_x509_crt_init(&cacert); if (setupStructure()) { _streamReady = true; _streamPaused = false; _isDeviceReady = true; return true; } else return false; } void ProviderUdpSSL::closeConnection() { if (_streamReady) { closeSSLNotify(); freeSSLConnection(); _streamReady = false; } } bool ProviderUdpSSL::seedingRNG() { mbedtls_entropy_init(&entropy); QByteArray customDataArray = _custom.toLocal8Bit(); const char* customData = customDataArray.constData(); int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, reinterpret_cast<const unsigned char*>(customData), std::min(strlen(customData), (size_t)MBEDTLS_CTR_DRBG_MAX_SEED_INPUT)); if (ret != 0) { Error(_log, "%s", QSTRING_CSTR(QString("mbedtls_ctr_drbg_seed FAILED %1").arg(errorMsg(ret)))); return false; } return true; } bool ProviderUdpSSL::setupStructure() { int transport = (_transport_type == "DTLS") ? MBEDTLS_SSL_TRANSPORT_DATAGRAM : MBEDTLS_SSL_TRANSPORT_STREAM; int ret = mbedtls_ssl_config_defaults(&conf, MBEDTLS_SSL_IS_CLIENT, transport, MBEDTLS_SSL_PRESET_DEFAULT); if (ret != 0) { Error(_log, "%s", QSTRING_CSTR(QString("mbedtls_ssl_config_defaults FAILED %1").arg(errorMsg(ret)))); return false; } const int* ciphersuites = getCiphersuites(); mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_REQUIRED); mbedtls_ssl_conf_ca_chain(&conf, &cacert, NULL); mbedtls_ssl_conf_handshake_timeout(&conf, _handshake_timeout_min, _handshake_timeout_max); mbedtls_ssl_conf_ciphersuites(&conf, ciphersuites); mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg); if ((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0) { Error(_log, "%s", QSTRING_CSTR(QString("mbedtls_ssl_setup FAILED %1").arg(errorMsg(ret)))); return false; } return startUPDConnection(); } bool ProviderUdpSSL::startUPDConnection() { mbedtls_ssl_session_reset(&ssl); if (!setupPSK()) return false; int ret = mbedtls_net_connect(&client_fd, _address.toString().toUtf8(), std::to_string(_ssl_port).c_str(), MBEDTLS_NET_PROTO_UDP); if (ret != 0) { Error(_log, "%s", QSTRING_CSTR(QString("mbedtls_net_connect FAILED %1").arg(errorMsg(ret)))); return false; } mbedtls_ssl_set_bio(&ssl, &client_fd, mbedtls_net_send, mbedtls_net_recv, mbedtls_net_recv_timeout); mbedtls_ssl_set_timer_cb(&ssl, &timer, mbedtls_timing_set_delay, mbedtls_timing_get_delay); return startSSLHandshake(); } bool ProviderUdpSSL::setupPSK() { QByteArray pskRawArray = QByteArray::fromHex(_psk.toUtf8()); QByteArray pskIdRawArray = _psk_identity.toUtf8(); int ret = mbedtls_ssl_conf_psk(&conf, reinterpret_cast<const unsigned char*> (pskRawArray.constData()), pskRawArray.length(), reinterpret_cast<const unsigned char*> (pskIdRawArray.constData()), pskIdRawArray.length()); if (ret != 0) { Error(_log, "%s", QSTRING_CSTR(QString("mbedtls_ssl_conf_psk FAILED %1").arg(errorMsg(ret)))); return false; } return true; } bool ProviderUdpSSL::startSSLHandshake() { int ret = 0; for (unsigned int attempt = 1; attempt <= _handshake_attempts; ++attempt) { do { ret = mbedtls_ssl_handshake(&ssl); } while (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE); if (ret == 0) { break; } else { Warning(_log, "%s", QSTRING_CSTR(QString("mbedtls_ssl_handshake attempt %1/%2 FAILED. Reason: %3").arg(attempt).arg(_handshake_attempts).arg(errorMsg(ret)))); } QThread::msleep(200); } if (ret != 0) { Error(_log, "%s", QSTRING_CSTR(QString("mbedtls_ssl_handshake FAILED %1").arg(errorMsg(ret)))); return false; } else { if (mbedtls_ssl_get_verify_result(&ssl) != 0) { Error(_log, "SSL certificate verification failed!"); return false; } } return true; } void ProviderUdpSSL::freeSSLConnection() { try { Warning(_log, "Release mbedtls"); mbedtls_ssl_session_reset(&ssl); mbedtls_net_free(&client_fd); mbedtls_ssl_free(&ssl); mbedtls_ssl_config_free(&conf); mbedtls_x509_crt_free(&cacert); } catch (std::exception& e) { Error(_log, "%s", QSTRING_CSTR(QString("SSL Connection clean-up Error: %s").arg(e.what()))); } catch (...) { Error(_log, "SSL Connection clean-up Error: <unknown>"); } } void ProviderUdpSSL::writeBytes(unsigned int size, const uint8_t* data, bool flush) { if (!_streamReady || _streamPaused) return; if (!_streamReady || _streamPaused) return; _streamPaused = flush; int ret = 0; do { ret = mbedtls_ssl_write(&ssl, data, size); } while (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE); if (ret <= 0) { Error(_log, "Error while writing UDP SSL stream updates. mbedtls_ssl_write returned: %s", QSTRING_CSTR(errorMsg(ret))); if (_streamReady) { closeConnection(); // look for the host QUdpSocket socket; for (int i = 1; i <= _retry_left; i++) { Warning(_log, "Searching the host: %s (trial %i/%i)", QSTRING_CSTR(this->_address.toString()), i, _retry_left); socket.connectToHost(_address, _ssl_port); if (socket.waitForConnected(1000)) { Warning(_log, "Found host: %s", QSTRING_CSTR(this->_address.toString())); socket.close(); break; } else QThread::msleep(1000); } Warning(_log, "Hard restart of the LED device (host: %s).", QSTRING_CSTR(this->_address.toString())); // hard reset Warning(_log, "Disabling..."); this->disableDevice(false); Warning(_log, "Enabling..."); this->enableDevice(false); if (!_isOn) emit enableStateChanged(false); } } } QString ProviderUdpSSL::errorMsg(int ret) { char error_buf[1024]; mbedtls_strerror(ret, error_buf, 1024); return QString("Last error was: code = %1, description = %2").arg(ret).arg(error_buf); } void ProviderUdpSSL::closeSSLNotify() { /* No error checking, the connection might be closed already */ while (mbedtls_ssl_close_notify(&ssl) == MBEDTLS_ERR_SSL_WANT_WRITE); }
24.930023
161
0.711246
awawa-dev
7e6192e0b4144d477c15f9b0043c03b279b862d5
2,598
hh
C++
include/simlib/path.hh
varqox/simlib
7830472019f88aa0e35dbfa1119b62b5f9dd4b9d
[ "MIT" ]
null
null
null
include/simlib/path.hh
varqox/simlib
7830472019f88aa0e35dbfa1119b62b5f9dd4b9d
[ "MIT" ]
1
2017-01-05T17:50:32.000Z
2017-01-05T17:50:32.000Z
include/simlib/path.hh
varqox/simlib
7830472019f88aa0e35dbfa1119b62b5f9dd4b9d
[ "MIT" ]
1
2017-01-05T15:26:48.000Z
2017-01-05T15:26:48.000Z
#pragma once #include "simlib/string_view.hh" #include <optional> // Returns an absolute path that does not contain any . or .. components, // nor any repeated path separators (/). @p curr_dir can be empty. If path // begins with / then @p curr_dir is ignored. std::string path_absolute(StringView path, std::string curr_dir = "/"); /** * @brief Returns the filename (last non-directory component) of the @p path * @details Examples: * "/my/path/foo.bar" -> "foo.bar" * "/my/path/" -> "" * "/" -> "" * "/my/path/." -> "." * "/my/path/.." -> ".." * "foo" -> "foo" */ template <class T> constexpr auto path_filename(T&& path) noexcept { using RetType = std::conditional_t<std::is_convertible_v<T, CStringView>, CStringView, StringView>; RetType path_str(std::forward<T>(path)); auto pos = path_str.rfind('/'); return path_str.substr(pos == path_str.npos ? 0 : pos + 1); } // Returns extension (without dot) e.g. "foo.cc" -> "cc", "bar" -> "" template <class T> constexpr auto path_extension(T&& path) noexcept { using RetType = std::conditional_t<std::is_convertible_v<T, CStringView>, CStringView, StringView>; RetType path_str(std::forward<T>(path)); size_t start_pos = path_str.rfind('/'); if (start_pos == path_str.npos) { start_pos = 0; } else { ++start_pos; } size_t x = path_str.rfind('.', start_pos); if (x == path_str.npos) { return RetType{}; // No extension } return path_str.substr(x + 1); } /** * @brief Returns prefix of the @p path that is a dirpath of the @p path * @details Examples: * "/my/path/foo.bar" -> "/my/path/" * "/my/path/" -> "/my/path/" * "/" -> "/" * "/my/path/." -> "/my/path/" * "/my/path/.." -> "/my/path/" * "abc/efg" -> "abc/" * "foo" -> "" */ constexpr inline StringView path_dirpath(const StringView& path) noexcept { auto pos = path.rfind('/'); return path.substring(0, pos == StringView::npos ? 0 : pos + 1); } /** * @brief Checks every ancestor (parent) directory of @p path if it has @p * subpath and if true returns path of @p subpath in ancestor directory * @details Examples: * 1) @p path == "a/b/c/file", @p subpath == "/x/y/z", tried paths will be: * "a/b/c/x/y/z" * "a/b/x/y/z" * "a/x/y/z" * "x/y/z" * 2) @p path == "/a/b/c/", @p subpath == "x/y/", tried paths will be: * "/a/b/c/x/y/" * "/a/b/x/y/" * "/a/x/y/" * "/x/y/" */ std::optional<std::string> deepest_ancestor_dir_with_subpath( std::string path, StringView subpath);
30.209302
95
0.583911
varqox
7e69ada6af6c8ff3f214bc2c84d1c3af9121a2b3
1,148
hh
C++
src/NodeGenerators/generateCylDistributionFromRZ.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/NodeGenerators/generateCylDistributionFromRZ.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
41
2020-09-28T23:14:27.000Z
2022-03-28T17:01:33.000Z
src/NodeGenerators/generateCylDistributionFromRZ.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
//------------------------------------------------------------------------------ // Helper method for the GenerateCylindricalNodeDistribution3d node generator // to generate the spun node distribution. //------------------------------------------------------------------------------ #ifndef __Spheral_generateCylDistributionFromRZ__ #define __Spheral_generateCylDistributionFromRZ__ #include <vector> #include "Geometry/Dimension.hh" namespace Spheral { void generateCylDistributionFromRZ(std::vector<double>& x, std::vector<double>& y, std::vector<double>& z, std::vector<double>& m, std::vector<Dim<3>::SymTensor>& H, std::vector<int>& globalIDs, std::vector<std::vector<double> >& extraFields, const double nNodePerh, const double kernelExtent, const double phi, const int procID, const int nProcs); } #endif
37.032258
80
0.449477
jmikeowen
7e6cd2376953f623e471e461f5759b9392b8c312
624
cpp
C++
src/visual-scripting/processors/generators/counters/CounterProcessors.cpp
inexorgame/entity-system
230a6f116fb02caeace79bc9b32f17fe08687c36
[ "MIT" ]
19
2018-10-11T09:19:48.000Z
2020-04-19T16:36:58.000Z
src/visual-scripting/processors/generators/counters/CounterProcessors.cpp
inexorgame-obsolete/entity-system-inactive
230a6f116fb02caeace79bc9b32f17fe08687c36
[ "MIT" ]
132
2018-07-28T12:30:54.000Z
2020-04-25T23:05:33.000Z
src/visual-scripting/processors/generators/counters/CounterProcessors.cpp
inexorgame-obsolete/entity-system-inactive
230a6f116fb02caeace79bc9b32f17fe08687c36
[ "MIT" ]
3
2019-03-02T16:19:23.000Z
2020-02-18T05:15:29.000Z
#include "CounterProcessors.hpp" #include <utility> namespace inexor::visual_scripting { CounterProcessors::CounterProcessors(CounterIntProcessorPtr counter_int_processor, CounterFloatProcessorPtr counter_float_processor) : LifeCycleComponent(counter_int_processor, counter_float_processor) { this->counter_int_processor = std::move(counter_int_processor); this->counter_float_processor = std::move(counter_float_processor); } CounterProcessors::~CounterProcessors() = default; std::string CounterProcessors::get_component_name() { return "CounterProcessors"; } } // namespace inexor::visual_scripting
28.363636
132
0.8125
inexorgame
7e6ddfc364527a3c904016f6bb55ec7156a1d901
20,714
hpp
C++
Cxx11/stencil_rajaview.hpp
hattom/Kernels
dae34b73235ccbf150d9b0ed5fb480b924789383
[ "BSD-3-Clause" ]
346
2015-06-07T19:55:15.000Z
2022-03-18T07:55:10.000Z
Cxx11/stencil_rajaview.hpp
hattom/Kernels
dae34b73235ccbf150d9b0ed5fb480b924789383
[ "BSD-3-Clause" ]
202
2015-06-16T15:28:05.000Z
2022-01-06T18:26:13.000Z
Cxx11/stencil_rajaview.hpp
hattom/Kernels
dae34b73235ccbf150d9b0ed5fb480b924789383
[ "BSD-3-Clause" ]
101
2015-06-15T22:06:46.000Z
2022-01-13T02:56:02.000Z
using regular_policy = RAJA::KernelPolicy< RAJA::statement::For<0, thread_exec, RAJA::statement::For<1, RAJA::simd_exec, RAJA::statement::Lambda<0> > > >; void star1(const int n, const int t, matrix & in, matrix & out) { RAJA::RangeSegment inner1(1,n-1); auto inner2 = RAJA::make_tuple(inner1, inner1); RAJA::kernel<regular_policy>(inner2, [=](int i, int j) { out(i,j) += +in(i,j-1) * -0.5 +in(i-1,j) * -0.5 +in(i+1,j) * 0.5 +in(i,j+1) * 0.5; }); } void star2(const int n, const int t, matrix & in, matrix & out) { RAJA::RangeSegment inner1(2,n-2); auto inner2 = RAJA::make_tuple(inner1, inner1); RAJA::kernel<regular_policy>(inner2, [=](int i, int j) { out(i,j) += +in(i,j-2) * -0.125 +in(i,j-1) * -0.25 +in(i-2,j) * -0.125 +in(i-1,j) * -0.25 +in(i+1,j) * 0.25 +in(i+2,j) * 0.125 +in(i,j+1) * 0.25 +in(i,j+2) * 0.125; }); } void star3(const int n, const int t, matrix & in, matrix & out) { RAJA::RangeSegment inner1(3,n-3); auto inner2 = RAJA::make_tuple(inner1, inner1); RAJA::kernel<regular_policy>(inner2, [=](int i, int j) { out(i,j) += +in(i,j-3) * -0.05555555555555555 +in(i,j-2) * -0.08333333333333333 +in(i,j-1) * -0.16666666666666666 +in(i-3,j) * -0.05555555555555555 +in(i-2,j) * -0.08333333333333333 +in(i-1,j) * -0.16666666666666666 +in(i+1,j) * 0.16666666666666666 +in(i+2,j) * 0.08333333333333333 +in(i+3,j) * 0.05555555555555555 +in(i,j+1) * 0.16666666666666666 +in(i,j+2) * 0.08333333333333333 +in(i,j+3) * 0.05555555555555555; }); } void star4(const int n, const int t, matrix & in, matrix & out) { RAJA::RangeSegment inner1(4,n-4); auto inner2 = RAJA::make_tuple(inner1, inner1); RAJA::kernel<regular_policy>(inner2, [=](int i, int j) { out(i,j) += +in(i,j-4) * -0.03125 +in(i,j-3) * -0.041666666666666664 +in(i,j-2) * -0.0625 +in(i,j-1) * -0.125 +in(i-4,j) * -0.03125 +in(i-3,j) * -0.041666666666666664 +in(i-2,j) * -0.0625 +in(i-1,j) * -0.125 +in(i+1,j) * 0.125 +in(i+2,j) * 0.0625 +in(i+3,j) * 0.041666666666666664 +in(i+4,j) * 0.03125 +in(i,j+1) * 0.125 +in(i,j+2) * 0.0625 +in(i,j+3) * 0.041666666666666664 +in(i,j+4) * 0.03125; }); } void star5(const int n, const int t, matrix & in, matrix & out) { RAJA::RangeSegment inner1(5,n-5); auto inner2 = RAJA::make_tuple(inner1, inner1); RAJA::kernel<regular_policy>(inner2, [=](int i, int j) { out(i,j) += +in(i,j-5) * -0.02 +in(i,j-4) * -0.025 +in(i,j-3) * -0.03333333333333333 +in(i,j-2) * -0.05 +in(i,j-1) * -0.1 +in(i-5,j) * -0.02 +in(i-4,j) * -0.025 +in(i-3,j) * -0.03333333333333333 +in(i-2,j) * -0.05 +in(i-1,j) * -0.1 +in(i+1,j) * 0.1 +in(i+2,j) * 0.05 +in(i+3,j) * 0.03333333333333333 +in(i+4,j) * 0.025 +in(i+5,j) * 0.02 +in(i,j+1) * 0.1 +in(i,j+2) * 0.05 +in(i,j+3) * 0.03333333333333333 +in(i,j+4) * 0.025 +in(i,j+5) * 0.02; }); } void grid1(const int n, const int t, matrix & in, matrix & out) { RAJA::RangeSegment inner1(1,n-1); auto inner2 = RAJA::make_tuple(inner1, inner1); RAJA::kernel<regular_policy>(inner2, [=](int i, int j) { out(i,j) += +in(i-1,j-1) * -0.25 +in(i,j-1) * -0.25 +in(i-1,j) * -0.25 +in(i+1,j) * 0.25 +in(i,j+1) * 0.25 +in(i+1,j+1) * 0.25 ; }); } void grid2(const int n, const int t, matrix & in, matrix & out) { RAJA::RangeSegment inner1(2,n-2); auto inner2 = RAJA::make_tuple(inner1, inner1); RAJA::kernel<regular_policy>(inner2, [=](int i, int j) { out(i,j) += +in(i-2,j-2) * -0.0625 +in(i-1,j-2) * -0.020833333333333332 +in(i,j-2) * -0.020833333333333332 +in(i+1,j-2) * -0.020833333333333332 +in(i-2,j-1) * -0.020833333333333332 +in(i-1,j-1) * -0.125 +in(i,j-1) * -0.125 +in(i+2,j-1) * 0.020833333333333332 +in(i-2,j) * -0.020833333333333332 +in(i-1,j) * -0.125 +in(i+1,j) * 0.125 +in(i+2,j) * 0.020833333333333332 +in(i-2,j+1) * -0.020833333333333332 +in(i,j+1) * 0.125 +in(i+1,j+1) * 0.125 +in(i+2,j+1) * 0.020833333333333332 +in(i-1,j+2) * 0.020833333333333332 +in(i,j+2) * 0.020833333333333332 +in(i+1,j+2) * 0.020833333333333332 +in(i+2,j+2) * 0.0625 ; }); } void grid3(const int n, const int t, matrix & in, matrix & out) { RAJA::RangeSegment inner1(3,n-3); auto inner2 = RAJA::make_tuple(inner1, inner1); RAJA::kernel<regular_policy>(inner2, [=](int i, int j) { out(i,j) += +in(i-3,j-3) * -0.027777777777777776 +in(i-2,j-3) * -0.005555555555555556 +in(i-1,j-3) * -0.005555555555555556 +in(i,j-3) * -0.005555555555555556 +in(i+1,j-3) * -0.005555555555555556 +in(i+2,j-3) * -0.005555555555555556 +in(i-3,j-2) * -0.005555555555555556 +in(i-2,j-2) * -0.041666666666666664 +in(i-1,j-2) * -0.013888888888888888 +in(i,j-2) * -0.013888888888888888 +in(i+1,j-2) * -0.013888888888888888 +in(i+3,j-2) * 0.005555555555555556 +in(i-3,j-1) * -0.005555555555555556 +in(i-2,j-1) * -0.013888888888888888 +in(i-1,j-1) * -0.08333333333333333 +in(i,j-1) * -0.08333333333333333 +in(i+2,j-1) * 0.013888888888888888 +in(i+3,j-1) * 0.005555555555555556 +in(i-3,j) * -0.005555555555555556 +in(i-2,j) * -0.013888888888888888 +in(i-1,j) * -0.08333333333333333 +in(i+1,j) * 0.08333333333333333 +in(i+2,j) * 0.013888888888888888 +in(i+3,j) * 0.005555555555555556 +in(i-3,j+1) * -0.005555555555555556 +in(i-2,j+1) * -0.013888888888888888 +in(i,j+1) * 0.08333333333333333 +in(i+1,j+1) * 0.08333333333333333 +in(i+2,j+1) * 0.013888888888888888 +in(i+3,j+1) * 0.005555555555555556 +in(i-3,j+2) * -0.005555555555555556 +in(i-1,j+2) * 0.013888888888888888 +in(i,j+2) * 0.013888888888888888 +in(i+1,j+2) * 0.013888888888888888 +in(i+2,j+2) * 0.041666666666666664 +in(i+3,j+2) * 0.005555555555555556 +in(i-2,j+3) * 0.005555555555555556 +in(i-1,j+3) * 0.005555555555555556 +in(i,j+3) * 0.005555555555555556 +in(i+1,j+3) * 0.005555555555555556 +in(i+2,j+3) * 0.005555555555555556 +in(i+3,j+3) * 0.027777777777777776 ; }); } void grid4(const int n, const int t, matrix & in, matrix & out) { RAJA::RangeSegment inner1(4,n-4); auto inner2 = RAJA::make_tuple(inner1, inner1); RAJA::kernel<regular_policy>(inner2, [=](int i, int j) { out(i,j) += +in(i-4,j-4) * -0.015625 +in(i-3,j-4) * -0.002232142857142857 +in(i-2,j-4) * -0.002232142857142857 +in(i-1,j-4) * -0.002232142857142857 +in(i,j-4) * -0.002232142857142857 +in(i+1,j-4) * -0.002232142857142857 +in(i+2,j-4) * -0.002232142857142857 +in(i+3,j-4) * -0.002232142857142857 +in(i-4,j-3) * -0.002232142857142857 +in(i-3,j-3) * -0.020833333333333332 +in(i-2,j-3) * -0.004166666666666667 +in(i-1,j-3) * -0.004166666666666667 +in(i,j-3) * -0.004166666666666667 +in(i+1,j-3) * -0.004166666666666667 +in(i+2,j-3) * -0.004166666666666667 +in(i+4,j-3) * 0.002232142857142857 +in(i-4,j-2) * -0.002232142857142857 +in(i-3,j-2) * -0.004166666666666667 +in(i-2,j-2) * -0.03125 +in(i-1,j-2) * -0.010416666666666666 +in(i,j-2) * -0.010416666666666666 +in(i+1,j-2) * -0.010416666666666666 +in(i+3,j-2) * 0.004166666666666667 +in(i+4,j-2) * 0.002232142857142857 +in(i-4,j-1) * -0.002232142857142857 +in(i-3,j-1) * -0.004166666666666667 +in(i-2,j-1) * -0.010416666666666666 +in(i-1,j-1) * -0.0625 +in(i,j-1) * -0.0625 +in(i+2,j-1) * 0.010416666666666666 +in(i+3,j-1) * 0.004166666666666667 +in(i+4,j-1) * 0.002232142857142857 +in(i-4,j) * -0.002232142857142857 +in(i-3,j) * -0.004166666666666667 +in(i-2,j) * -0.010416666666666666 +in(i-1,j) * -0.0625 +in(i+1,j) * 0.0625 +in(i+2,j) * 0.010416666666666666 +in(i+3,j) * 0.004166666666666667 +in(i+4,j) * 0.002232142857142857 +in(i-4,j+1) * -0.002232142857142857 +in(i-3,j+1) * -0.004166666666666667 +in(i-2,j+1) * -0.010416666666666666 +in(i,j+1) * 0.0625 +in(i+1,j+1) * 0.0625 +in(i+2,j+1) * 0.010416666666666666 +in(i+3,j+1) * 0.004166666666666667 +in(i+4,j+1) * 0.002232142857142857 +in(i-4,j+2) * -0.002232142857142857 +in(i-3,j+2) * -0.004166666666666667 +in(i-1,j+2) * 0.010416666666666666 +in(i,j+2) * 0.010416666666666666 +in(i+1,j+2) * 0.010416666666666666 +in(i+2,j+2) * 0.03125 +in(i+3,j+2) * 0.004166666666666667 +in(i+4,j+2) * 0.002232142857142857 +in(i-4,j+3) * -0.002232142857142857 +in(i-2,j+3) * 0.004166666666666667 +in(i-1,j+3) * 0.004166666666666667 +in(i,j+3) * 0.004166666666666667 +in(i+1,j+3) * 0.004166666666666667 +in(i+2,j+3) * 0.004166666666666667 +in(i+3,j+3) * 0.020833333333333332 +in(i+4,j+3) * 0.002232142857142857 +in(i-3,j+4) * 0.002232142857142857 +in(i-2,j+4) * 0.002232142857142857 +in(i-1,j+4) * 0.002232142857142857 +in(i,j+4) * 0.002232142857142857 +in(i+1,j+4) * 0.002232142857142857 +in(i+2,j+4) * 0.002232142857142857 +in(i+3,j+4) * 0.002232142857142857 +in(i+4,j+4) * 0.015625 ; }); } void grid5(const int n, const int t, matrix & in, matrix & out) { RAJA::RangeSegment inner1(5,n-5); auto inner2 = RAJA::make_tuple(inner1, inner1); RAJA::kernel<regular_policy>(inner2, [=](int i, int j) { out(i,j) += +in(i-5,j-5) * -0.01 +in(i-4,j-5) * -0.0011111111111111111 +in(i-3,j-5) * -0.0011111111111111111 +in(i-2,j-5) * -0.0011111111111111111 +in(i-1,j-5) * -0.0011111111111111111 +in(i,j-5) * -0.0011111111111111111 +in(i+1,j-5) * -0.0011111111111111111 +in(i+2,j-5) * -0.0011111111111111111 +in(i+3,j-5) * -0.0011111111111111111 +in(i+4,j-5) * -0.0011111111111111111 +in(i-5,j-4) * -0.0011111111111111111 +in(i-4,j-4) * -0.0125 +in(i-3,j-4) * -0.0017857142857142857 +in(i-2,j-4) * -0.0017857142857142857 +in(i-1,j-4) * -0.0017857142857142857 +in(i,j-4) * -0.0017857142857142857 +in(i+1,j-4) * -0.0017857142857142857 +in(i+2,j-4) * -0.0017857142857142857 +in(i+3,j-4) * -0.0017857142857142857 +in(i+5,j-4) * 0.0011111111111111111 +in(i-5,j-3) * -0.0011111111111111111 +in(i-4,j-3) * -0.0017857142857142857 +in(i-3,j-3) * -0.016666666666666666 +in(i-2,j-3) * -0.0033333333333333335 +in(i-1,j-3) * -0.0033333333333333335 +in(i,j-3) * -0.0033333333333333335 +in(i+1,j-3) * -0.0033333333333333335 +in(i+2,j-3) * -0.0033333333333333335 +in(i+4,j-3) * 0.0017857142857142857 +in(i+5,j-3) * 0.0011111111111111111 +in(i-5,j-2) * -0.0011111111111111111 +in(i-4,j-2) * -0.0017857142857142857 +in(i-3,j-2) * -0.0033333333333333335 +in(i-2,j-2) * -0.025 +in(i-1,j-2) * -0.008333333333333333 +in(i,j-2) * -0.008333333333333333 +in(i+1,j-2) * -0.008333333333333333 +in(i+3,j-2) * 0.0033333333333333335 +in(i+4,j-2) * 0.0017857142857142857 +in(i+5,j-2) * 0.0011111111111111111 +in(i-5,j-1) * -0.0011111111111111111 +in(i-4,j-1) * -0.0017857142857142857 +in(i-3,j-1) * -0.0033333333333333335 +in(i-2,j-1) * -0.008333333333333333 +in(i-1,j-1) * -0.05 +in(i,j-1) * -0.05 +in(i+2,j-1) * 0.008333333333333333 +in(i+3,j-1) * 0.0033333333333333335 +in(i+4,j-1) * 0.0017857142857142857 +in(i+5,j-1) * 0.0011111111111111111 +in(i-5,j) * -0.0011111111111111111 +in(i-4,j) * -0.0017857142857142857 +in(i-3,j) * -0.0033333333333333335 +in(i-2,j) * -0.008333333333333333 +in(i-1,j) * -0.05 +in(i+1,j) * 0.05 +in(i+2,j) * 0.008333333333333333 +in(i+3,j) * 0.0033333333333333335 +in(i+4,j) * 0.0017857142857142857 +in(i+5,j) * 0.0011111111111111111 +in(i-5,j+1) * -0.0011111111111111111 +in(i-4,j+1) * -0.0017857142857142857 +in(i-3,j+1) * -0.0033333333333333335 +in(i-2,j+1) * -0.008333333333333333 +in(i,j+1) * 0.05 +in(i+1,j+1) * 0.05 +in(i+2,j+1) * 0.008333333333333333 +in(i+3,j+1) * 0.0033333333333333335 +in(i+4,j+1) * 0.0017857142857142857 +in(i+5,j+1) * 0.0011111111111111111 +in(i-5,j+2) * -0.0011111111111111111 +in(i-4,j+2) * -0.0017857142857142857 +in(i-3,j+2) * -0.0033333333333333335 +in(i-1,j+2) * 0.008333333333333333 +in(i,j+2) * 0.008333333333333333 +in(i+1,j+2) * 0.008333333333333333 +in(i+2,j+2) * 0.025 +in(i+3,j+2) * 0.0033333333333333335 +in(i+4,j+2) * 0.0017857142857142857 +in(i+5,j+2) * 0.0011111111111111111 +in(i-5,j+3) * -0.0011111111111111111 +in(i-4,j+3) * -0.0017857142857142857 +in(i-2,j+3) * 0.0033333333333333335 +in(i-1,j+3) * 0.0033333333333333335 +in(i,j+3) * 0.0033333333333333335 +in(i+1,j+3) * 0.0033333333333333335 +in(i+2,j+3) * 0.0033333333333333335 +in(i+3,j+3) * 0.016666666666666666 +in(i+4,j+3) * 0.0017857142857142857 +in(i+5,j+3) * 0.0011111111111111111 +in(i-5,j+4) * -0.0011111111111111111 +in(i-3,j+4) * 0.0017857142857142857 +in(i-2,j+4) * 0.0017857142857142857 +in(i-1,j+4) * 0.0017857142857142857 +in(i,j+4) * 0.0017857142857142857 +in(i+1,j+4) * 0.0017857142857142857 +in(i+2,j+4) * 0.0017857142857142857 +in(i+3,j+4) * 0.0017857142857142857 +in(i+4,j+4) * 0.0125 +in(i+5,j+4) * 0.0011111111111111111 +in(i-4,j+5) * 0.0011111111111111111 +in(i-3,j+5) * 0.0011111111111111111 +in(i-2,j+5) * 0.0011111111111111111 +in(i-1,j+5) * 0.0011111111111111111 +in(i,j+5) * 0.0011111111111111111 +in(i+1,j+5) * 0.0011111111111111111 +in(i+2,j+5) * 0.0011111111111111111 +in(i+3,j+5) * 0.0011111111111111111 +in(i+4,j+5) * 0.0011111111111111111 +in(i+5,j+5) * 0.01 ; }); }
53.112821
83
0.39273
hattom
7e6e5199750f9df713da118aa8b76ebef75f000e
3,832
hpp
C++
Rx/v2/src/rxcpp/operators/rx-multicast.hpp
guhwanbae/RxCpp
7f97aa901701343593869acad1ee5a02292f39cf
[ "Apache-2.0" ]
2
2022-02-09T19:01:00.000Z
2022-03-11T03:36:29.000Z
Rx/v2/src/rxcpp/operators/rx-multicast.hpp
ivan-cukic/wip-fork-rxcpp
483963939e4a2adf674450dcb829005d84be1d59
[ "Apache-2.0" ]
null
null
null
Rx/v2/src/rxcpp/operators/rx-multicast.hpp
ivan-cukic/wip-fork-rxcpp
483963939e4a2adf674450dcb829005d84be1d59
[ "Apache-2.0" ]
1
2022-02-09T12:00:05.000Z
2022-02-09T12:00:05.000Z
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. #pragma once /*! \file rx-multicast.hpp \brief allows connections to the source to be independent of subscriptions. \tparam Subject the subject to multicast the source Observable. \param sub the subject. */ #if !defined(RXCPP_OPERATORS_RX_MULTICAST_HPP) #define RXCPP_OPERATORS_RX_MULTICAST_HPP #include "../rx-includes.hpp" namespace rxcpp { namespace operators { namespace detail { template<class... AN> struct multicast_invalid_arguments {}; template<class... AN> struct multicast_invalid : public rxo::operator_base<multicast_invalid_arguments<AN...>> { using type = observable<multicast_invalid_arguments<AN...>, multicast_invalid<AN...>>; }; template<class... AN> using multicast_invalid_t = typename multicast_invalid<AN...>::type; template<class T, class Observable, class Subject> struct multicast : public operator_base<T> { using source_type = rxu::decay_t<Observable>; using subject_type = rxu::decay_t<Subject>; struct multicast_state : public std::enable_shared_from_this<multicast_state> { multicast_state(source_type o, subject_type sub) : source(std::move(o)) , subject_value(std::move(sub)) { } source_type source; subject_type subject_value; rxu::detail::maybe<typename composite_subscription::weak_subscription> connection; }; std::shared_ptr<multicast_state> state; multicast(source_type o, subject_type sub) : state(std::make_shared<multicast_state>(std::move(o), std::move(sub))) { } template<class Subscriber> void on_subscribe(Subscriber&& o) const { state->subject_value.get_observable().subscribe(std::forward<Subscriber>(o)); } void on_connect(composite_subscription cs) const { if (state->connection.empty()) { auto destination = state->subject_value.get_subscriber(); // the lifetime of each connect is nested in the subject lifetime state->connection.reset(destination.add(cs)); auto localState = state; // when the connection is finished it should shutdown the connection cs.add( [destination, localState](){ if (!localState->connection.empty()) { destination.remove(localState->connection.get()); localState->connection.reset(); } }); // use cs not destination for lifetime of subscribe. state->source.subscribe(cs, destination); } } }; } /*! @copydoc rx-multicast.hpp */ template<class... AN> auto multicast(AN&&... an) -> operator_factory<multicast_tag, AN...> { return operator_factory<multicast_tag, AN...>(std::make_tuple(std::forward<AN>(an)...)); } } template<> struct member_overload<multicast_tag> { template<class Observable, class Subject, class Enabled = rxu::enable_if_all_true_type_t< is_observable<Observable>>, class SourceValue = rxu::value_type_t<Observable>, class Multicast = rxo::detail::multicast<SourceValue, rxu::decay_t<Observable>, rxu::decay_t<Subject>>, class Value = rxu::value_type_t<Multicast>, class Result = connectable_observable<Value, Multicast>> static Result member(Observable&& o, Subject&& sub) { return Result(Multicast(std::forward<Observable>(o), std::forward<Subject>(sub))); } template<class... AN> static operators::detail::multicast_invalid_t<AN...> member(AN...) { std::terminate(); return {}; static_assert(sizeof...(AN) == 10000, "multicast takes (Subject)"); } }; } #endif
30.903226
132
0.658664
guhwanbae
7e781742def67dc40fe3b18ea2514984dcd8421b
1,013
hpp
C++
include/regrados.hpp
emanuelmoraes-dev/cpp-learn
4ca99f39e44016784619928cb61187be63586994
[ "MIT" ]
null
null
null
include/regrados.hpp
emanuelmoraes-dev/cpp-learn
4ca99f39e44016784619928cb61187be63586994
[ "MIT" ]
null
null
null
include/regrados.hpp
emanuelmoraes-dev/cpp-learn
4ca99f39e44016784619928cb61187be63586994
[ "MIT" ]
null
null
null
#ifndef REGRADOS_H_INCLUDED #define REGRADOS_H_INCLUDED #include <string> #include <vector> #include <memory> class Membro { public: std::string nome; }; class RegraDos3 { public: Membro membro; Membro* aloc1; Membro* aloc2; std::vector<Membro> membros; RegraDos3(); // Aplicando regra dos 3 RegraDos3(const RegraDos3&); // cópia ~RegraDos3(); // destrutor RegraDos3& operator=(const RegraDos3&); // cópia }; class RegraDos5 { public: Membro membro; Membro* aloc1; Membro* aloc2; std::vector<Membro> membros; RegraDos5(); // Aplicando regra dos 5 RegraDos5(const RegraDos5&); // cópia RegraDos5(RegraDos5&&); // mover ~RegraDos5(); // destrutor RegraDos5& operator=(const RegraDos5&); // cópia RegraDos5& operator=(RegraDos5&&); // mover }; class RegraDos0 { public: Membro membro; std::shared_ptr<Membro> aloc1; std::unique_ptr<Membro> aloc2; std::vector<Membro> membros; }; #endif // REGRADOS_H_INCLUDED
19.862745
52
0.660415
emanuelmoraes-dev
7e7da6a7d3209015d09bf16404f6138ea82c64ce
6,980
cpp
C++
AR_ColorSensor/src/AR_ColorSensor.cpp
fangchuan/AR_Library
c825bf26aa1f31b1537fdcaa382dc7b5b0de1afc
[ "MIT" ]
null
null
null
AR_ColorSensor/src/AR_ColorSensor.cpp
fangchuan/AR_Library
c825bf26aa1f31b1537fdcaa382dc7b5b0de1afc
[ "MIT" ]
null
null
null
AR_ColorSensor/src/AR_ColorSensor.cpp
fangchuan/AR_Library
c825bf26aa1f31b1537fdcaa382dc7b5b0de1afc
[ "MIT" ]
null
null
null
/* ********************************************************************************************************* * * 模块名称 : ColorSensor类库 * 文件名称 : AR_ColorSensor.cpp * 版 本 : V1.0 * 说 明 : * 修订记录 : 2017-3-13: 类内方法不可以被赋值给函数指针,必须将方法声明为static,但一旦将属性也改为static就失去了这个传感器类的意义 * 2017-3-14: 将数据属性全部public,主函数操作这些属性 * 每次扫描RGB都需要3次定时器溢出中断的过程 * 2017-3-16: 采用TC2做定时器,定时周期1ms,1s进行一次扫描,中断服务函数必须放在外部(全局可见) * 采用PCINT中断读取OUT引脚,中断服务函数也得放外部 * 2017-3-19: 颜色传感器读出的数值都差不多,这是为啥... * 2017-3-20: 颜色传感器四个灯换成白色LED,电阻47R * 白平衡结果参数0.01/0.01/0.01较合理 * 离传感器靠的越近区分效果越好 * * 2017-3-22: blue值始终偏高,不是程序问题,买的成品模块也是如此。可以把每次scann周期缩短到10ms,减小blue偏差 * * Copyright (C), 2015-2020, 阿波罗科技 www.apollorobot.cn * ********************************************************************************************************* */ #include <AR_ColorSensor.h> /* ********************************************************************************************************* * 函 数 名: AR_ColorSensor()构造函数 * 功能说明: * 形 参: * 返 回 值: 无 ********************************************************************************************************* */ AR_ColorSensor::AR_ColorSensor() { } /* ********************************************************************************************************* * 函 数 名: initialize * 功能说明: Initialize the pins color sensor used, and TC2 initialize * 形 参: s2: S2 pin * s3:S3 pin * out: OUT pin * 返 回 值: 无 ********************************************************************************************************* */ void AR_ColorSensor::initialize(uint8_t s2, uint8_t s3, uint8_t out) { s2_pin = s2; s3_pin = s3; out_pin = out; pinMode(s2_pin, OUTPUT); pinMode(s3_pin, OUTPUT); pinMode(out_pin, INPUT); initTime2(); initPCINT(); g_counts = 0; g_flag = 0; g_buffer[0] = 0; g_buffer[1] = 0; g_buffer[2] = 0; g_fac[0] = 0.01; g_fac[1] = 0.01; g_fac[2] = 0.01; } /* ********************************************************************************************************* * 函 数 名: initTime2 * 功能说明: 配置TC2寄存器,普通模式,64分频,定时器初值为6 1ms定时周期 * 1024分频,初值定为100 约10Ms定时周期 * 形 参: * 返 回 值: 无 ********************************************************************************************************* */ void AR_ColorSensor::initTime2() // { TCCR2A = 0; TIMSK2 = _BV(TOIE2); #if USE_1MS_INTERRUPT TCCR2B = _BV(CS22); TCNT2 = 6; #elif USE_10MS_INTERRUPT TCCR2B = _BV(CS22) | _BV(CS21) | _BV(CS20); //1024分频 TCNT2 = 100; //初值100 #endif sei(); } /* ********************************************************************************************************* * 函 数 名: initPCINT * 功能说明: 配置PCINT寄存器,ennable PCINT0/2 and PCINT pin 0/1/2/23 * PCINT0--8(Arduino) * PCINT1--9(Arduino) * PCINT2--10(Arduino) * PCINT23--7(Arduino) * 形 参: * 返 回 值: 无 ********************************************************************************************************* */ void AR_ColorSensor::initPCINT() { if (out_pin > 7){ PCICR = 1 << PCIE0; if(8 == out_pin) PCMSK0 = 1 << PCINT0; if(9 == out_pin) PCMSK0 = 1 << PCINT1; if(10 == out_pin) PCMSK0 = 1 << PCINT2; }else{ PCICR = 1 << PCIE2; PCMSK2 = 1 << PCINT23; } } /* ********************************************************************************************************* * 函 数 名: selectFilter * 功能说明: Select the filter color * 形 参: filter_index: 颜色滤波器 index * 返 回 值: 无 ********************************************************************************************************* */ void AR_ColorSensor::selectFilter(uint8_t filter_index) { switch(filter_index){ case RED_FILTER: digitalWrite(s2_pin, LOW); digitalWrite(s3_pin, LOW); break; case GREEN_FILTER: digitalWrite(s2_pin, HIGH); digitalWrite(s3_pin, HIGH); break; case BLUE_FILTER: digitalWrite(s2_pin, LOW); digitalWrite(s3_pin, HIGH); break; case NON_FILTER: digitalWrite(s2_pin, HIGH); digitalWrite(s3_pin, LOW); break; default:break; } //update the scann queue g_flag ++; if(g_flag > 2) g_flag = 0; } /* ********************************************************************************************************* * 函 数 名: scann * 功能说明: 扫描RGB值,每执行一次scann只能扫R/G/B,所以扫完一个物体要至少执行3次 * 形 参: filter_index: 颜色滤波器 index * 返 回 值: 无 ********************************************************************************************************* */ void AR_ColorSensor::scann() { switch(g_flag) { case RED_FILTER: #if USE_DEBUG Serial.print("->frequency B="); Serial.println(g_counts); #endif g_buffer[BLUE_INDEX] = g_counts; //store the previous filter out selectFilter(RED_FILTER); //filter red break; case GREEN_FILTER: #if USE_DEBUG Serial.print("->frequency R="); Serial.println(g_counts); #endif g_buffer[RED_INDEX] = g_counts; //store the previous filter out selectFilter(GREEN_FILTER); //filter green break; case BLUE_FILTER: #if USE_DEBUG Serial.print("->frequency G="); Serial.println(g_counts); #endif g_buffer[GREEN_INDEX] = g_counts; //store the previous filter out selectFilter(BLUE_FILTER); //filter blue break; default: break; } g_counts = 0; } /* ********************************************************************************************************* * 函 数 名: whiteBalance * 功能说明: white balance process * 形 参: 无 * 返 回 值: 无 ********************************************************************************************************* */ void AR_ColorSensor::whiteBalance() { if(g_buffer[0] != 0 && g_buffer[1] != 0 && g_buffer[2] != 0){ g_fac[0] = 255.0 / g_buffer[0]; g_fac[1] = 255.0 / g_buffer[1]; g_fac[2] = 255.0 / g_buffer[2]; #if USE_DEBUG Serial.print("R_Factor:"); Serial.println(g_fac[0]); Serial.print("G_Factor"); Serial.println(g_fac[1]); Serial.print("B_Factor"); Serial.println(g_fac[2]); #endif }else{ g_fac[0] = 0; g_fac[1] = 0; g_fac[2] = 0; } } /* ********************************************************************************************************* * 函 数 名: getResult * 功能说明: print the red/green/blue value * range: 0~255 * 形 参: 无 * 返 回 值: 无 ********************************************************************************************************* */ void AR_ColorSensor::getResult() { float red = g_buffer[RED_INDEX] * g_fac[RED_INDEX]; float green = g_buffer[GREEN_INDEX] * g_fac[GREEN_INDEX]; float blue = g_buffer[BLUE_INDEX] * g_fac[BLUE_INDEX]; #if USE_DEBUG Serial.print("red_result"); Serial.println(red); Serial.print("green_result"); Serial.println(green); Serial.print("blue_result"); Serial.println(blue); #endif } /***************************** 阿波罗科技 www.apollorobot.cn (END OF FILE) *********************************/
28.489796
105
0.440974
fangchuan
7e887fee2927fc5e7a30b76c39054a38c34fded0
445
cpp
C++
src/resources/terrain_library.cpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
[ "MIT" ]
null
null
null
src/resources/terrain_library.cpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
[ "MIT" ]
null
null
null
src/resources/terrain_library.cpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
[ "MIT" ]
null
null
null
/* * TS Elements * Copyright 2015-2018 M. Newhouse * Released under the MIT license. */ #include "terrain_library.hpp" #include <algorithm> namespace ts { namespace resources { void TerrainLibrary::define_terrain(const TerrainDefinition& terrain) { terrains_[terrain.id] = terrain; } const TerrainDefinition& TerrainLibrary::terrain(TerrainId terrain_id) const { return terrains_[terrain_id]; } } }
17.115385
80
0.696629
mnewhouse
7e89b9689048be6d81a61f59d446635923370799
1,041
hpp
C++
Nacro/SDK/FN_Bedroom_Dresser_02_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_Bedroom_Dresser_02_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_Bedroom_Dresser_02_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
#pragma once // Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function Bedroom_Dresser_02.Bedroom_Dresser_02_C.UserConstructionScript struct ABedroom_Dresser_02_C_UserConstructionScript_Params { }; // Function Bedroom_Dresser_02.Bedroom_Dresser_02_C.OnLootRepeat struct ABedroom_Dresser_02_C_OnLootRepeat_Params { }; // Function Bedroom_Dresser_02.Bedroom_Dresser_02_C.OnBeginSearch struct ABedroom_Dresser_02_C_OnBeginSearch_Params { }; // Function Bedroom_Dresser_02.Bedroom_Dresser_02_C.ExecuteUbergraph_Bedroom_Dresser_02 struct ABedroom_Dresser_02_C_ExecuteUbergraph_Bedroom_Dresser_02_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
24.209302
152
0.632085
Milxnor
7e89faa093f24847cdd82eb90b45385703c1210d
6,619
cpp
C++
source/AlgebraicMethods/Term.cpp
CoghettoR/gclc
b481b15d28ee66f995b73283e26c285ca8c4a821
[ "MIT" ]
21
2020-12-08T20:06:01.000Z
2022-02-13T22:52:02.000Z
source/AlgebraicMethods/Term.cpp
CoghettoR/gclc
b481b15d28ee66f995b73283e26c285ca8c4a821
[ "MIT" ]
9
2020-12-20T03:54:55.000Z
2022-03-31T19:30:04.000Z
source/AlgebraicMethods/Term.cpp
CoghettoR/gclc
b481b15d28ee66f995b73283e26c285ca8c4a821
[ "MIT" ]
5
2021-04-25T18:47:17.000Z
2022-01-23T02:37:30.000Z
#include "Term.h" #include "TermStorage.h" #include "TermStorageAvl.h" #include "TermStorageVector.h" #include "XTerm.h" Term::Term() { #if 0 static int cnt = 0; if (cnt == 12237) { int stop = 1; MyTerm = this; } cnt++; //Log::PrintLogF(0, "C:%d:%x\n", cnt++, this); #endif COSTR("term"); } Term::~Term() { #if 0 static int cnt = 0; //Log::PrintLogF(0, "D:%d:%x\n", cnt++, this); #endif for (int ii = 0, size = (int)_powers.size(); ii < size; ii++) { _powers[ii]->Dispose(); } DESTR("term"); } // // Compare two terms // Return values: // -1 : this < other // 0 : this = other // 1 : this > other // int Term::Compare(Term * /* other */) const { return -1; } // // Merge two equal terms // void Term::Merge(Term * /* other */) {} TermKeyType Term::Key() { return this; } TermStorage *Term::CreateTermStorage() { #if TERM_STORAGE_CLASS_VECTOR return new TermStorageVector(); #elif TERM_STORAGE_CLASS_AVL_TREE #ifdef AVLTREE_BANK return AvlTreeBank::AvlTreeFactory.AcquireAvlTree(); #else return new TermStorageAvlTree(); #endif #endif } // // Merge powers from other term. // Several usages: // 1. To add powers (multiplication) // 2. To remove powers (division) // 3. To remove powers (integer division, gcd) // void Term::MergePowers(Term *t, bool add) { uint cnt1 = (uint)_powers.size(); uint cnt2 = (uint)t->_powers.size(); uint ii = 0, jj = 0; int op = add ? 1 : -1; while (ii < cnt1 && jj < cnt2) { Power *w1 = _powers[ii]; Power *w2 = t->_powers[jj]; if (w1->GetIndex() == w2->GetIndex()) { // case 1, w1 == w2 // add/subtract degree int degree = w1->GetDegree() + op * w2->GetDegree(); // degree = max(0, degree); if (degree < 0) degree = 0; if (degree == 0) { // remove power w1->Dispose(); _powers.erase(_powers.begin() + ii); cnt1--; jj++; } else { w1->SetDegree(degree); ii++; jj++; } } else if (w1->GetIndex() < w2->GetIndex()) { // should not happen if add == false // correction - could happen, it means safe division! if (!add) { jj++; continue; // Log::PrintLogF(0, "Attempt to do rational division of powers!\n"); // throw -1; } // case 2, w1 < w2 // insert power and increase powers count _powers.insert(_powers.begin() + ii, w2->Clone()); cnt1++; ii++; jj++; } else { // case 3, w1 > w2 // move on with first iterator ii++; } } // ii < cnt2, nothing to do while (jj < cnt2) { // should not happen if add == false // correction - could happen, it means safe division! if (!add) { jj++; continue; // Log::PrintLogF(0, "Attempt to do rational division of powers!\n"); // throw -1; } // add remaining powers Power *w2 = t->_powers[jj]; _powers.push_back(w2->Clone()); jj++; } } // // Is this term divisible with other term // Check powers // bool Term::Divisible(Term *t) const { uint i1 = 0, i2 = 0; uint s1 = (uint)_powers.size(), s2 = (uint)t->_powers.size(); // constant is divisable only with constant bool divisible = (s1 > 0) || (s2 == 0); while (i1 < s1 && i2 < s2 && divisible) { // check current degree in t uint index2 = t->_powers[i2]->GetIndex(); // must match it in this term while (i1 < s1 && _powers[i1]->GetIndex() > index2) { i1++; } if (i1 >= s1 || _powers[i1]->GetIndex() != index2 || _powers[i1]->GetDegree() < t->_powers[i2]->GetDegree()) { divisible = false; } i2++; } return divisible; } uint Term::GetPowerCount() const { return (uint)_powers.size(); } Power *Term::GetPower(uint index) const { return _powers[index]; } // // degree of variable with given index // int Term::VariableDeg(int index, bool free) const { if (free == true && this->Type() == XTERM) { XTerm *xt = (XTerm *)this; Term *t = xt->GetUFraction()->GetNumerator()->LeadTerm(index, free); if (t) { return t->VariableDeg(index, free); } else { return 0; } } Power *pow = this->GetPowerByIndex(index); if (pow != NULL) { return pow->GetDegree(); } return 0; } // // Find and return power with given variable index // Power *Term::GetPowerByIndex(int index) const { int vecIndex = this->GetIndexOfIndex(index); return vecIndex >= 0 ? this->GetPower(vecIndex) : NULL; } // // Return index in array of power with given index // -1 if power doesn't exists // int Term::GetIndexOfIndex(int index) const { // search power using binary search int l = 0, r = this->GetPowerCount() - 1, m; while (l <= r) { m = (l + r) / 2; Power *pow = this->GetPower(m); if (pow->GetIndex() == (unsigned)index) { return m; } else if ((int)pow->GetIndex() < index) { // array is reversaly sorted r = m - 1; } else { l = m + 1; } } return -1; } // // Change degree of a power with given index // power doesn't have to exists // void Term::ChangePowerDegree(int index, int change) { if (change != 0) { int powIndex = this->GetIndexOfIndex(index); if (powIndex >= 0) { Power *pow = this->GetPower(powIndex); pow->SetDegree(pow->GetDegree() + change); if (pow->GetDegree() == 0) { this->RemovePower(powIndex); } } } } // // Remove power at index // void Term::RemovePower(uint index) { _powers[index]->Dispose(); _powers.erase(_powers.begin() + index); } // // this = GCD(this, t) // void Term::GCDWith(const Term *t) { uint j = 0; uint k, size1, size2; size1 = this->GetPowerCount(); size2 = t->GetPowerCount(); for (k = 0; k < size1; k++) { uint index1 = this->GetPower(k)->GetIndex(); while (j < size2 && index1 < t->GetPower(j)->GetIndex()) { j++; } if (j < size2 && index1 == t->GetPower(j)->GetIndex()) { uint d_k = this->GetPower(k)->GetDegree(); uint d_j = t->GetPower(j)->GetDegree(); uint d = (d_k < d_j ? d_k : d_j); this->GetPower(k)->SetDegree(d); if (this->GetPower(k)->GetDegree() == 0) { this->RemovePower(k); k--; size1--; } } else { this->RemovePower(k); k--; size1--; } } }
22.667808
78
0.536637
CoghettoR
7e8eba9f731da8d8b1c99ff78c14c779cfbb8111
7,991
cpp
C++
src/Client.cpp
nsentout/project-lambda-client
3b6f84e90ebf1319bbbfd6649b1e9e94b96f1469
[ "MIT" ]
null
null
null
src/Client.cpp
nsentout/project-lambda-client
3b6f84e90ebf1319bbbfd6649b1e9e94b96f1469
[ "MIT" ]
null
null
null
src/Client.cpp
nsentout/project-lambda-client
3b6f84e90ebf1319bbbfd6649b1e9e94b96f1469
[ "MIT" ]
null
null
null
#include <stdio.h> #include <string.h> #include "Client.hpp" #include "render/Renderer.hpp" #include <sstream> //#define CONNECTION_TIMEOUT 5000 #define CONNECTION_TIMEOUT 100000 #define NUMBER_CHANNELS 2 #define SPEED 25 Client::Client() : m_host(nullptr), m_server(nullptr) { createClient(); } Client::~Client() { this->disconnect(); delete m_server_address; } void printPacketDescription(const lambda::GameState *gamestate) { printf("\tPacket description:\n"); printf("\tNb players: %d\n", gamestate->nb_players()); for (int i = 0; i < gamestate->nb_players(); i++) { printf("\tPlayer %d: (%d,%d)\n", i + 1, gamestate->players_data(i).x(), gamestate->players_data(i).y()); } } int Client::createClient() { /* Creates a client */ m_host = enet_host_create(NULL /* create a client host */, 1 /* only allow 1 outgoing connection */, NUMBER_CHANNELS /* allow up 2 channels to be used, 0 and 1 */, 0 /* assume any amount of incoming bandwidth */, 0 /* assume any amount of outgoing bandwidth */); if (m_host == NULL) { fprintf(stderr, "An error occurred while trying to create an ENet client host.\n"); return -1; } return 1; } int Client::connectToServer(const char* server_ip, int server_port) { // Set server address m_server_address = new ENetAddress(); enet_address_set_host(m_server_address, server_ip); m_server_address->port = server_port; /* Initiate the connection, allocating the two channels 0 and 1. */ m_server = enet_host_connect(m_host, m_server_address, NUMBER_CHANNELS, 0); if (m_server == NULL) { fprintf(stderr, "No available peers for initiating an ENet connection.\n"); return -1; } /* Wait up to 5 seconds for the connection attempt to succeed. */ ENetEvent net_event; if (enet_host_service(m_host, &net_event, CONNECTION_TIMEOUT) > 0 && net_event.type == ENET_EVENT_TYPE_CONNECT) { printf("Attempt to connecting to %s:%d succeeded. Waiting for server response ...\n", server_ip, server_port); /* Store any relevant server information here. */ net_event.peer->data = (void *)"SERVER"; } else { /* Either the 5 seconds are up or a disconnect event was */ /* received. Reset the peer in the event the 5 seconds */ /* had run out without any significant event. */ enet_peer_reset(m_server); puts("Connection to the server failed."); return -1; } enet_host_flush(m_host); // Why does this have to be here for the server to receive the connection attempt ? //int response = enet_host_service(m_host, &event, 1000); int server_response = enet_host_service(m_host, &net_event, CONNECTION_TIMEOUT); // Server sent game state and the player's positions if (server_response > 0) { printf("Connection to %s:%d accepted.\n", server_ip, server_port); // Update the player's position lambda::GameState received_gamestate = getGamestateFromPacket(net_event.packet); int player_index = received_gamestate.nb_players() - 1; auto player_data = received_gamestate.players_data(player_index); m_id = player_data.id(); m_x = player_data.x(); m_y = player_data.y(); handlePacketReceipt(&net_event); } else { puts("Server did not respond... Good bye"); return -1; } return 1; } /** * Checks if a packet is in the waiting queue. */ void Client::checkPacketBox() { ENetEvent net_event; while (enet_host_service(m_host, &net_event, 0) > 0) { switch (net_event.type) { case ENET_EVENT_TYPE_CONNECT: { printf("Someone connected (why ?)\n"); break; } // The "peer" field contains the peer the packet was received from, "channelID" is the channel on // which the packet was sent, and "packet" is the packet that was sent. case ENET_EVENT_TYPE_RECEIVE: { handlePacketReceipt(&net_event); /* Clean up the packet now that we're done using it. */ enet_packet_destroy(net_event.packet); } } } } void Client::handlePacketReceipt(ENetEvent *net_event) { printf("A packet of length %lu was received from %d on channel %u.\n", net_event->packet->dataLength, net_event->peer->address.host, net_event->channelID); lambda::GameState received_gamestate = getGamestateFromPacket(net_event->packet); printPacketDescription(&received_gamestate); checkPacketFormat(&received_gamestate); updateRenderData(&received_gamestate); } void Client::updateRenderData(lambda::GameState *gamestate) const { if (gamestate->has_player_disconnected_id()) { Renderer::getInstance()->clearPlayer(gamestate->player_disconnected_id() - 1); // minus 1 because the server sends the index + 1 } // Retrieve players positions and send them to the renderer lambda::PlayersData player_data; int nb_players = gamestate->nb_players(); int player_index = -1; Position positions[nb_players]; for (int i = 0; i < nb_players; i++) { if (m_id == gamestate->players_data(i).id()) player_index = i; player_data = gamestate->players_data(i); positions[i] = {player_data.x(), player_data.y()}; } Renderer::getInstance()->updateRenderData(positions, nb_players, player_index); } void Client::disconnect() { ENetEvent net_event; enet_peer_disconnect(m_server, 0); /* Allow up to 3 seconds for the disconnect to succeed * and drop any received packets. */ while (enet_host_service(m_host, &net_event, 3000) > 0) { switch (net_event.type) { case ENET_EVENT_TYPE_RECEIVE: enet_packet_destroy(net_event.packet); break; case ENET_EVENT_TYPE_DISCONNECT: puts("Disconnection succeeded."); return; } } /* We've arrived here, so the disconnect attempt didn't */ /* succeed yet. Force the connection down. */ enet_peer_reset(m_server); enet_host_destroy(m_host); } void Client::moveUp() { m_y -= SPEED; sendPositionToServer(m_x, m_y); } void Client::moveDown() { m_y += SPEED; sendPositionToServer(m_x, m_y); } void Client::moveRight() { m_x += SPEED; sendPositionToServer(m_x, m_y); } void Client::moveLeft() { m_x -= SPEED; sendPositionToServer(m_x, m_y); } void Client::sendPositionToServer(int x, int y) const { lambda::PlayerAction playerAction; playerAction.set_new_x(x); playerAction.set_new_y(y); std::string packet_data = getStringFromPlayerAction(&playerAction); ENetPacket *packet = enet_packet_create(packet_data.data(), packet_data.size(), ENET_PACKET_FLAG_RELIABLE); // Send the packet to the peer over channel id 0. enet_peer_send(m_server, 0, packet); printf("Sending packet '(%d, %d)' to server.\n", playerAction.new_x(), playerAction.new_y()); } /** * Disconnect the client and close the window if the packet received is malformed */ void Client::checkPacketFormat(lambda::GameState *gamestate) { if (gamestate->nb_players() < 1) { printf("Received malformed packet.\n"); disconnect(); exit(-1); } } lambda::GameState Client::getGamestateFromPacket(ENetPacket *packet) const { lambda::GameState gamestate; gamestate.ParseFromArray(packet->data, packet->dataLength); return gamestate; } const std::string Client::getStringFromPlayerAction(lambda::PlayerAction *playeraction) const { std::string serialized_playeraction; playeraction->SerializeToString(&serialized_playeraction); return serialized_playeraction; }
29.058182
137
0.647228
nsentout
7e8f389f2ec72f9f4e69b6e67c0d432dcfd2686f
4,823
cpp
C++
sj_common.cpp
SJ-magic-youtube-VisualProgrammer/103_fft_Visualize__1_Artsin
4d5acdccae24364b173794793c9896c8420f55fb
[ "MIT" ]
null
null
null
sj_common.cpp
SJ-magic-youtube-VisualProgrammer/103_fft_Visualize__1_Artsin
4d5acdccae24364b173794793c9896c8420f55fb
[ "MIT" ]
null
null
null
sj_common.cpp
SJ-magic-youtube-VisualProgrammer/103_fft_Visualize__1_Artsin
4d5acdccae24364b173794793c9896c8420f55fb
[ "MIT" ]
null
null
null
/************************************************************ ************************************************************/ #include "sj_common.h" /************************************************************ ************************************************************/ /******************** ********************/ int GPIO_0 = 0; int GPIO_1 = 0; const float _PI = 3.1415; /******************** ********************/ GUI_GLOBAL* Gui_Global = NULL; FILE* fp_Log = nullptr; /************************************************************ func ************************************************************/ /****************************** ******************************/ double LPF(double LastVal, double CurrentVal, double Alpha_dt, double dt) { double Alpha; if((Alpha_dt <= 0) || (Alpha_dt < dt)) Alpha = 1; else Alpha = 1/Alpha_dt * dt; return CurrentVal * Alpha + LastVal * (1 - Alpha); } /****************************** ******************************/ double LPF(double LastVal, double CurrentVal, double Alpha) { if(Alpha < 0) Alpha = 0; else if(1 < Alpha) Alpha = 1; return CurrentVal * Alpha + LastVal * (1 - Alpha); } /****************************** ******************************/ double sj_max(double a, double b) { if(a < b) return b; else return a; } /****************************** ******************************/ bool checkIf_ContentsExist(char* ret, char* buf) { if( (ret == NULL) || (buf == NULL)) return false; string str_Line = buf; Align_StringOfData(str_Line); vector<string> str_vals = ofSplitString(str_Line, ","); if( (str_vals.size() == 0) || (str_vals[0] == "") ){ // no_data or exist text but it's",,,,,,,". return false; }else{ return true; } } /****************************** ******************************/ void Align_StringOfData(string& s) { size_t pos; while((pos = s.find_first_of("  \t\n\r")) != string::npos){ // 半角・全角space, \t 改行 削除 s.erase(pos, 1); } } /****************************** ******************************/ void print_separatoin() { printf("---------------------------------\n"); } /****************************** ******************************/ void ClearFbo(ofFbo& fbo) { fbo.begin(); ofClear(0, 0, 0, 255); fbo.end(); } /****************************** ******************************/ float toRad(float val){ return val * 3.1415 / 180.0; } /****************************** ******************************/ float toDeg(float val){ return val * 180.0 / 3.1415; } /****************************** ******************************/ float get_val_top_of_artsin_window(){ if(Gui_Global->ArtSin2D_BarHeight == 0) return 1e4; const float Window_H = 200.0; return 1.0 * Window_H / Gui_Global->ArtSin2D_BarHeight; } /************************************************************ class ************************************************************/ /****************************** ******************************/ void GUI_GLOBAL::setup(string GuiName, string FileName, float x, float y) { /******************** ********************/ gui.setup(GuiName.c_str(), FileName.c_str(), x, y); /******************** ********************/ Group_Audio.setup("Audio"); Group_Audio.add(b_Audio_Start.setup("Start", false)); Group_Audio.add(b_Audio_Stop.setup("Stop", false)); Group_Audio.add(b_Audio_Reset.setup("Reset", false)); gui.add(&Group_Audio); Group_FFT.setup("FFT"); Group_FFT.add(FFT__SoftGain.setup("FFT__SoftGain", 1.0, 1.0, 5.0)); Group_FFT.add(FFT__k_smooth.setup("FFT__k_smooth", 0.95, 0.8, 1.0)); Group_FFT.add(FFT__dt_smooth_2.setup("FFT__dt_smooth_2", 167, 10, 300)); Group_FFT.add(FFT__b_Window.setup("FFT__b_Window", true)); gui.add(&Group_FFT); Group_ArtSin.setup("ArtSin"); Group_ArtSin.add(ArtSin_Band_min.setup("ArtSin_Band_min", 1.0, 1.0, 255.0)); Group_ArtSin.add(ArtSin_Band_max.setup("ArtSin_Band_max", 1.0, 1.0, 255.0)); Group_ArtSin.add(ArtSin_PhaseMap_k.setup("ArtSin_PhaseMap_k", 1.0, 0.0, 2.0)); Group_ArtSin.add(b_ArtSin_abs.setup("b_ArtSin_abs", false)); Group_ArtSin.add(b_Window_artSin.setup("b_Window_artSin", false)); Group_ArtSin.add(Tukey_alpha.setup("Tukey_alpha", 0.3, 0.0, 1.0)); gui.add(&Group_ArtSin); Group_ArtSin2D.setup("ArtSin2D"); Group_ArtSin2D.add(b_Draw_ArtSin2D.setup("ArtSin2D:b_Draw", true)); Group_ArtSin2D.add(ArtSin2D_BarHeight.setup("ArtSin2D:BarHeight", 200, 0.0, 1000)); { ofColor initColor = ofColor(255, 255, 255, 140); ofColor minColor = ofColor(0, 0, 0, 0); ofColor maxColor = ofColor(255, 255, 255, 255); Group_ArtSin2D.add(col_ArtSin2D.setup("ArtSin2D:col", initColor, minColor, maxColor)); } gui.add(&Group_ArtSin2D); Group_img.setup("img"); Group_img.add(img_alpha.setup("img:alpha", 20, 0.0, 255.0)); gui.add(&Group_img); /******************** ********************/ gui.minimizeAll(); }
28.040698
97
0.477918
SJ-magic-youtube-VisualProgrammer
7e99bff8822e5d2d5f18f8c59410f9d2ce56cc5a
2,953
cpp
C++
Button/QCheckBox/mainwindow.cpp
Sakura1221/QtStudy
34d24affada2a10c901fb9571473a33c871201fa
[ "MIT" ]
4
2021-06-17T02:58:18.000Z
2021-11-09T11:40:37.000Z
Button/QCheckBox/mainwindow.cpp
Sakura1221/QtStudy
34d24affada2a10c901fb9571473a33c871201fa
[ "MIT" ]
null
null
null
Button/QCheckBox/mainwindow.cpp
Sakura1221/QtStudy
34d24affada2a10c901fb9571473a33c871201fa
[ "MIT" ]
1
2021-06-26T07:42:20.000Z
2021-06-26T07:42:20.000Z
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); //设置根结点的三态属性 ui->wives->setTristate(true); // 当父结点状态改变后,子结点也要相应改变(只有全选或全未选两种状态) // 为了避免信号冲突,捕获clicked信号 // 需要判断按钮是否被选中了,这里要传入clicked信号返回值 connect(ui->wives, &QCheckBox::clicked, this, [=] (bool st) { if (st) { ui->jianning->setChecked(true); ui->fangyi->setChecked(true); ui->longer->setChecked(true); ui->zengrou->setChecked(true); ui->mujianping->setChecked(true); ui->shuanger->setChecked(true); ui->ake->setChecked(true); } else { ui->jianning->setChecked(false); ui->fangyi->setChecked(false); ui->longer->setChecked(false); ui->zengrou->setChecked(false); ui->mujianping->setChecked(false); ui->shuanger->setChecked(false); ui->ake->setChecked(false); } }); // 信号与槽函数都相同,要使用统一函数,槽函数不能是匿名函数 connect(ui->jianning, &QCheckBox::stateChanged, this, &MainWindow::statusChanged); connect(ui->fangyi, &QCheckBox::stateChanged, this, &MainWindow::statusChanged); connect(ui->longer, &QCheckBox::stateChanged, this, &MainWindow::statusChanged); connect(ui->zengrou, &QCheckBox::stateChanged, this, &MainWindow::statusChanged); connect(ui->mujianping, &QCheckBox::stateChanged, this, &MainWindow::statusChanged); connect(ui->shuanger, &QCheckBox::stateChanged, this, &MainWindow::statusChanged); connect(ui->ake, &QCheckBox::stateChanged, this, &MainWindow::statusChanged); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_cpp_stateChanged(int arg1) { if (arg1 == Qt::Checked) { qDebug() << "我会C++"; } else { qDebug() << "我不会C++"; } } void MainWindow::on_go_stateChanged(int arg1) { // 选中时 if (arg1 == Qt::Checked) { qDebug() << "我会Go"; } // 取消时 else { qDebug() << "我不会Go"; } } void MainWindow::on_python_stateChanged(int arg1) { if (arg1 == Qt::Checked) { qDebug() << "我会Python"; } else { qDebug() << "我不会Python"; } } void MainWindow::on_java_stateChanged(int arg1) { if (arg1 == Qt::Checked) { qDebug() << "我会Java"; } else { qDebug() << "我不会Java"; } } void MainWindow::statusChanged(int state) { // 子结点状态修改计数器 if (state == Qt::Checked) { m_number ++; } else { m_number --; } // 根据计数器修改根结点状态 if (m_number == 7) { ui->wives->setCheckState(Qt::Checked); } else if (m_number == 0) { ui->wives->setCheckState(Qt::Unchecked); } else { ui->wives->setCheckState(Qt::PartiallyChecked); } }
22.203008
88
0.568236
Sakura1221
7e9f6cb6cf91773920d9c0461874a0d37d7b8345
1,177
cpp
C++
Actor/Characters/Enemy/E3/StateAI/StateMng_AI_EnemyE3.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
Actor/Characters/Enemy/E3/StateAI/StateMng_AI_EnemyE3.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
Actor/Characters/Enemy/E3/StateAI/StateMng_AI_EnemyE3.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "StateMng_AI_EnemyE3.h" #include "StateRoot_AI_EnemyE3.h" #include "../AIC_EnemyE3.h" UStateMng_AI_EnemyE3::UStateMng_AI_EnemyE3() { } UStateMng_AI_EnemyE3::~UStateMng_AI_EnemyE3() { } void UStateMng_AI_EnemyE3::Init(class AAIController* pRoot) { Super::Init(pRoot); m_pRootCharacter_Override = Cast<AAIC_EnemyE3>(pRoot); if (m_pRootCharacter_Override == nullptr) { ULOG(TEXT("m_pRootCharacter_Override is nullptr")); } m_pStateClass.Add(static_cast<int32>(E_StateAI_EnemyE3::E_Normal), NewObject<UStateAI_EnemyE3_Normal>()); m_pStateClass.Add(static_cast<int32>(E_StateAI_EnemyE3::E_Chase), NewObject<UState_AI_EnemyE3_Chase>()); m_pStateClass.Add(static_cast<int32>(E_StateAI_EnemyE3::E_Combat), NewObject<UStateAI_EnemyE3_Combat>()); m_pStateClass.Add(static_cast<int32>(E_StateAI_EnemyE3::E_Lost), NewObject<UStateAI_EnemyE3_Lost>()); for (TMap<int, class UStateRoot_AI*>::TIterator it = m_pStateClass.CreateIterator(); it; ++it) { it->Value->Init(this); } } void UStateMng_AI_EnemyE3::Destroy() { Super::Destroy(); m_pRootCharacter_Override = nullptr; }
26.75
106
0.7774
Bornsoul
7ea324a5d6413d9be9ad5ad01d8c1da842586b85
580
cpp
C++
example/iterable/at.cpp
rbock/hana
2b76377f91a5ebe037dea444e4eaabba6498d3a8
[ "BSL-1.0" ]
2
2015-05-07T14:29:13.000Z
2015-07-04T10:59:46.000Z
example/iterable/at.cpp
rbock/hana
2b76377f91a5ebe037dea444e4eaabba6498d3a8
[ "BSL-1.0" ]
null
null
null
example/iterable/at.cpp
rbock/hana
2b76377f91a5ebe037dea444e4eaabba6498d3a8
[ "BSL-1.0" ]
null
null
null
/* @copyright Louis Dionne 2014 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #include <boost/hana/detail/assert.hpp> #include <boost/hana/integral.hpp> #include <boost/hana/list/instance.hpp> using namespace boost::hana; int main() { //! [main] BOOST_HANA_CONSTEXPR_ASSERT(at(int_<0>, list(0, '1', 2.0)) == 0); BOOST_HANA_CONSTEXPR_ASSERT(at(int_<1>, list(0, '1', 2.0)) == '1'); BOOST_HANA_CONSTEXPR_ASSERT(at(int_<2>, list(0, '1', 2.0)) == 2.0); //! [main] }
29
78
0.674138
rbock
7ea3e4fa4f2f94bac0ff40745f8e800c0968fb86
50,109
cc
C++
bindings/v8_opengl_es2.cc
slightlyoff/bravo
450d13427a27ac4f276ecac5bc350b81de838a6b
[ "BSD-3-Clause" ]
5
2015-12-17T19:48:38.000Z
2021-05-07T15:45:15.000Z
bindings/v8_opengl_es2.cc
slightlyoff/bravo
450d13427a27ac4f276ecac5bc350b81de838a6b
[ "BSD-3-Clause" ]
null
null
null
bindings/v8_opengl_es2.cc
slightlyoff/bravo
450d13427a27ac4f276ecac5bc350b81de838a6b
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "bravo/bindings/v8_opengl_es2.h" #include "base/strings/stringprintf.h" #include "bravo/bindings/util.h" #include "bravo/plugin/instance.h" #include "bravo/plugin/ppb.h" #include "v8/include/v8.h" #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> // See also: // https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/core/html/canvas/WebGLRenderingContext.cpp namespace bravo { namespace { #define ARG_GLbitfield(arg) \ (arg)->Int32Value() #define ARG_GLenum(arg) \ (arg)->Int32Value() #define ARG_GLint(arg) \ (arg)->Int32Value() #define ARG_GLuint(arg) \ (arg)->Uint32Value() #define ARG_GLsizei(arg) \ (arg)->Uint32Value() #define ARG_GLfloat(arg) \ (arg)->NumberValue() #define ARG_GLclampf(arg) \ (arg)->NumberValue() #define ARG_GLboolean(arg) \ (arg)->BooleanValue() #define V8_BIND_0(interface, name) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ ppb.interface->name( \ GetPPResource(info)); \ } #define V8_BIND_1(interface, name, arg0) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 1) \ return; \ ppb.interface->name( \ GetPPResource(info), \ arg0(info[0])); \ } #define V8_BIND_2(interface, name, arg0, arg1) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 2) \ return; \ ppb.interface->name( \ GetPPResource(info), \ arg0(info[0]), \ arg1(info[1])); \ } #define V8_BIND_2_V(interface, name, arg0, arg1, type) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 2) \ return; \ type v = arg1(info[1]); \ ppb.interface->name( \ GetPPResource(info), \ arg0(info[0]), \ &v); \ } #define V8_BIND_3(interface, name, arg0, arg1, arg2) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 3) \ return; \ ppb.interface->name( \ GetPPResource(info), \ arg0(info[0]), \ arg1(info[1]), \ arg2(info[2])); \ } #define V8_BIND_4(interface, name, arg0, arg1, arg2, arg3) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 4) \ return; \ ppb.interface->name( \ GetPPResource(info), \ arg0(info[0]), \ arg1(info[1]), \ arg2(info[2]), \ arg3(info[3])); \ } #define V8_BIND_4_V(interface, name, arg0, arg1, arg2, arg3, type) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 4) \ return; \ type v = arg3(info[3]); \ ppb.interface->name( \ GetPPResource(info), \ arg0(info[0]), \ arg1(info[1]), \ arg2(info[2]), \ &v); \ } #define V8_BIND_5(interface, name, arg0, arg1, arg2, arg3, arg4) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 4) \ return; \ ppb.interface->name( \ GetPPResource(info), \ arg0(info[0]), \ arg1(info[1]), \ arg2(info[2]), \ arg3(info[3]), \ arg4(info[4])); \ } #define V8_BIND_8(interface, name, arg0, arg1, arg2, arg3, \ arg4, arg5, arg6, arg7) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 4) \ return; \ ppb.interface->name( \ GetPPResource(info), \ arg0(info[0]), \ arg1(info[1]), \ arg2(info[2]), \ arg3(info[3]), \ arg4(info[4]), \ arg5(info[5]), \ arg6(info[6]), \ arg7(info[7])); \ } #define V8_BIND_HANDLE_0(interface, name) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ info.GetReturnValue().Set(v8::Uint32::New( \ ppb.interface->name( \ GetPPResource(info) \ ))); \ } #define V8_BIND_HANDLE_1(interface, name, arg0) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 1) \ return; \ info.GetReturnValue().Set(v8::Uint32::New( \ ppb.interface->name( \ GetPPResource(info), \ arg0(info[0]) \ ))); \ } #define V8_BIND_HANDLE_BUFFER(interface, name, singular) \ void singular(const v8::FunctionCallbackInfo<v8::Value>& info) { \ GLuint buffer = 0; \ ppb.interface->name(GetPPResource(info), 1, &buffer); \ info.GetReturnValue().Set(v8::Uint32::New(buffer)); \ } #define V8_BIND_DELETE_BUFFER(interface, name, singular) \ void singular(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 1) \ return; \ GLuint buffer = info[0]->Uint32Value(); \ ppb.interface->name(GetPPResource(info), 1, &buffer); \ } #define V8_BIND_1_SHADER_STRING(interface, name, getter, type, arg0) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 1) \ return; \ \ GLsizei length = 0; \ ppb.interface->getter(GetPPResource(info), \ arg0(info[0]), \ type, \ &length); \ char buffer[length]; \ GLsizei returnedLength = 0; \ ppb.interface->name(GetPPResource(info), \ arg0(info[0]), \ length, \ &returnedLength, \ buffer); \ info.GetReturnValue().Set(v8::String::New(buffer, returnedLength)); \ } #define V8_BIND_VERTEX_V(interface, name, v8type, typeTest, glType) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 2) \ return; \ \ /* TODO: handle regular arrays like WebGL does */ \ if (!info[1]->typeTest()) \ return; \ \ GLint index = ARG_GLint(info[0]); \ v8::Handle<v8::v8type> arr = v8::Handle<v8::v8type>::Cast(info[1]); \ void * data = arr->Buffer()->Externalize().Data(); \ ppb.interface->name(GetPPResource(info), \ index, \ reinterpret_cast<const glType *>(data)); \ } #define V8_BIND_UNIFORM_V(interface, name, v8type, typeTest, glType) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 2) \ return; \ \ /* TODO: handle regular arrays like WebGL does */ \ if (!info[1]->typeTest()) \ return; \ \ GLint location = ARG_GLint(info[0]); \ v8::Handle<v8::v8type> arr = v8::Handle<v8::v8type>::Cast(info[1]); \ void * data = arr->Buffer()->Externalize().Data(); \ ppb.interface->name(GetPPResource(info), \ location, \ 1, \ reinterpret_cast<const glType *>(data)); \ } #define V8_BIND_UNIFORM_MATRIX(interface, name, v8type, typeTest, glType) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 3) \ return; \ \ /* TODO: handle regular arrays like WebGL does */ \ if (!info[2]->typeTest()) \ return; \ \ GLint location = ARG_GLint(info[0]); \ GLboolean transpose = ARG_GLboolean(info[1]); \ v8::Handle<v8::v8type> arr = v8::Handle<v8::v8type>::Cast(info[2]); \ void * data = arr->Buffer()->Externalize().Data(); \ ppb.interface->name(GetPPResource(info), \ location, \ 1, \ transpose, \ reinterpret_cast<const glType *>(data)); \ } V8_BIND_1(opengl_es2, ActiveTexture, ARG_GLenum) V8_BIND_2(opengl_es2, AttachShader, ARG_GLuint, ARG_GLuint) // void (*BindAttribLocation)( // PP_Resource context, GLuint program, GLuint index, const char* name); V8_BIND_2(opengl_es2, BindBuffer, ARG_GLenum, ARG_GLuint) V8_BIND_2(opengl_es2, BindFramebuffer, ARG_GLenum, ARG_GLuint) V8_BIND_2(opengl_es2, BindRenderbuffer, ARG_GLenum, ARG_GLuint) V8_BIND_2(opengl_es2, BindTexture, ARG_GLenum, ARG_GLuint) V8_BIND_4(opengl_es2, BlendColor, ARG_GLclampf, ARG_GLclampf, ARG_GLclampf, ARG_GLclampf) V8_BIND_1(opengl_es2, BlendEquation, ARG_GLenum) V8_BIND_2(opengl_es2, BlendEquationSeparate, ARG_GLenum, ARG_GLenum) V8_BIND_2(opengl_es2, BlendFunc, ARG_GLenum, ARG_GLenum) V8_BIND_4(opengl_es2, BlendFuncSeparate, ARG_GLenum, ARG_GLenum, ARG_GLenum, ARG_GLenum) void BufferData(const v8::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() < 3) return; GLenum target = info[0]->Int32Value(); GLenum usage = info[2]->Int32Value(); /* void bufferData(GLenum target, GLsizeiptr size, GLenum usage) (OpenGL ES 2.0 §2.9, man page) Set the size of the currently bound WebGLBuffer object for the passed target. The buffer is initialized to 0. */ if (info[1]->IsNumber()) { ppb.opengl_es2->BufferData(GetPPResource(info), target, info[1]->Int32Value(), 0, usage); return; } /* void bufferData(GLenum target, ArrayBufferView data, GLenum usage) */ if (info[1]->IsArrayBuffer()) { v8::Handle<v8::ArrayBuffer> buffer = v8::Handle<v8::ArrayBuffer>::Cast(info[1]); // (GLsizeiptr)buffer->ByteLength(), ppb.opengl_es2->BufferData(GetPPResource(info), target, buffer->ByteLength(), buffer->Externalize().Data(), usage); } /* void bufferData(GLenum target, ArrayBuffer? data, GLenum usage) (OpenGL ES 2.0 §2.9, man page) Set the size of the currently bound WebGLBuffer object for the passed target to the size of the passed data, then write the contents of data to the buffer object. */ if (info[1]->IsArrayBufferView()) { v8::Handle<v8::ArrayBufferView> view = v8::Handle<v8::ArrayBufferView>::Cast(info[1]); void * data = view->Buffer()->Externalize().Data(); ppb.opengl_es2->BufferData(GetPPResource(info), target, view->ByteLength(), data, usage); } /* TODO(slightlyoff): If the passed data is null then an INVALID_VALUE error is generated. */ } // void (*BufferSubData)( // PP_Resource context, GLenum target, GLintptr offset, GLsizeiptr size, // const void* data); V8_BIND_1(opengl_es2, CheckFramebufferStatus, ARG_GLenum) V8_BIND_1(opengl_es2, Clear, ARG_GLbitfield) V8_BIND_4(opengl_es2, ClearColor, ARG_GLclampf, ARG_GLclampf, ARG_GLclampf, ARG_GLclampf) V8_BIND_1(opengl_es2, ClearDepthf, ARG_GLclampf) V8_BIND_1(opengl_es2, ClearStencil, ARG_GLint) V8_BIND_4(opengl_es2, ColorMask, ARG_GLboolean, ARG_GLboolean, ARG_GLboolean, ARG_GLboolean) V8_BIND_1(opengl_es2, CompileShader, ARG_GLuint) // void (*CompressedTexImage2D)( // PP_Resource context, GLenum target, GLint level, GLenum internalformat, // GLsizei width, GLsizei height, GLint border, GLsizei imageSize, // const void* data); V8_BIND_8(opengl_es2, CopyTexImage2D, ARG_GLenum, ARG_GLint, ARG_GLenum, ARG_GLint, ARG_GLint, ARG_GLsizei, ARG_GLsizei, ARG_GLint) V8_BIND_8(opengl_es2, CopyTexSubImage2D, ARG_GLenum, ARG_GLint, ARG_GLint, ARG_GLint, ARG_GLint, ARG_GLint, ARG_GLsizei, ARG_GLsizei) V8_BIND_HANDLE_BUFFER(opengl_es2, GenBuffers, CreateBuffer) V8_BIND_HANDLE_BUFFER(opengl_es2, GenFramebuffers, CreateFramebuffer) V8_BIND_HANDLE_BUFFER(opengl_es2, GenRenderbuffers, CreateRenderbuffer) V8_BIND_HANDLE_BUFFER(opengl_es2, GenTextures, CreateTexture) V8_BIND_HANDLE_0(opengl_es2, CreateProgram) V8_BIND_HANDLE_1(opengl_es2, CreateShader, ARG_GLenum) V8_BIND_1(opengl_es2, CullFace, ARG_GLenum) V8_BIND_DELETE_BUFFER(opengl_es2, DeleteBuffers, DeleteBuffer) V8_BIND_DELETE_BUFFER(opengl_es2, DeleteFramebuffers, DeleteFramebuffer) V8_BIND_1(opengl_es2, DeleteProgram, ARG_GLuint) V8_BIND_DELETE_BUFFER(opengl_es2, DeleteRenderbuffers, DeleteRenderbuffer) V8_BIND_1(opengl_es2, DeleteShader, ARG_GLuint) V8_BIND_DELETE_BUFFER(opengl_es2, DeleteTextures, DeleteTexture) V8_BIND_1(opengl_es2, DepthFunc, ARG_GLenum) V8_BIND_1(opengl_es2, DepthMask, ARG_GLboolean) V8_BIND_2(opengl_es2, DepthRangef, ARG_GLclampf, ARG_GLclampf) V8_BIND_2(opengl_es2, DetachShader, ARG_GLuint, ARG_GLuint) V8_BIND_1(opengl_es2, Disable, ARG_GLenum) V8_BIND_1(opengl_es2, DisableVertexAttribArray, ARG_GLuint) V8_BIND_3(opengl_es2, DrawArrays, ARG_GLenum, ARG_GLint, ARG_GLsizei) void DrawElements(const v8::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() < 4) return; GLenum mode = ARG_GLenum(info[0]); GLsizei count = ARG_GLsizei(info[1]); GLenum elementType = ARG_GLenum(info[2]); GLint indices = ARG_GLint(info[3]); ppb.opengl_es2->DrawElements(GetPPResource(info), mode, count, elementType, reinterpret_cast<void *>(indices)); } V8_BIND_1(opengl_es2, Enable, ARG_GLenum) V8_BIND_1(opengl_es2, EnableVertexAttribArray, ARG_GLuint) V8_BIND_0(opengl_es2, Finish) V8_BIND_0(opengl_es2, Flush) V8_BIND_4(opengl_es2, FramebufferRenderbuffer, ARG_GLenum, ARG_GLenum, ARG_GLenum, ARG_GLuint) V8_BIND_5(opengl_es2, FramebufferTexture2D, ARG_GLenum, ARG_GLenum, ARG_GLenum, ARG_GLuint, ARG_GLint) V8_BIND_1(opengl_es2, FrontFace, ARG_GLenum) V8_BIND_1(opengl_es2, GenerateMipmap, ARG_GLenum) // void (*GetActiveAttrib)( // PP_Resource context, GLuint program, GLuint index, GLsizei bufsize, // GLsizei* length, GLint* size, GLenum* type, char* name); // void (*GetActiveUniform)( // PP_Resource context, GLuint program, GLuint index, GLsizei bufsize, // GLsizei* length, GLint* size, GLenum* type, char* name); // void (*GetAttachedShaders)( // PP_Resource context, GLuint program, GLsizei maxcount, GLsizei* count, // GLuint* shaders); void GetAttribLocation(const v8::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() < 2) return; if (!info[0]->IsNumber()) return; if (!info[1]->IsString()) return; v8::String::Utf8Value name(info[1]); const char* str = *name; GLint value = ppb.opengl_es2->GetAttribLocation(GetPPResource(info), ARG_GLint(info[0]), str); info.GetReturnValue().Set(v8::Uint32::New(value)); } // void (*GetBooleanv)(PP_Resource context, GLenum pname, GLboolean* params); // void (*GetBufferParameteriv)( // PP_Resource context, GLenum target, GLenum pname, GLint* params); V8_BIND_HANDLE_0(opengl_es2, GetError) // void (*GetFloatv)(PP_Resource context, GLenum pname, GLfloat* params); // void (*GetFramebufferAttachmentParameteriv)( // PP_Resource context, GLenum target, GLenum attachment, GLenum pname, // GLint* params); // void (*GetIntegerv)(PP_Resource context, GLenum pname, GLint* params); void GetProgramParameter(const v8::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() < 2) return; GLenum name = ARG_GLenum(info[1]); GLint value = 0; ppb.opengl_es2->GetProgramiv(GetPPResource(info), ARG_GLuint(info[0]), name, &value); if (name == GL_DELETE_STATUS || name == GL_LINK_STATUS || name == GL_VALIDATE_STATUS) { info.GetReturnValue().Set(v8::Boolean::New(value)); return; } if (name == GL_ATTACHED_SHADERS || name == GL_ACTIVE_ATTRIBUTES || name == GL_ACTIVE_UNIFORMS) { info.GetReturnValue().Set(v8::Uint32::New(value)); return; } info.GetReturnValue().Set(v8::Null()); } V8_BIND_1_SHADER_STRING(opengl_es2, GetProgramInfoLog, GetProgramiv, GL_INFO_LOG_LENGTH, ARG_GLuint) // void (*GetRenderbufferParameteriv)( // PP_Resource context, GLenum target, GLenum pname, GLint* params); // void (*GetShaderiv)( // PP_Resource context, GLuint shader, GLenum pname, GLint* params); void GetShaderParameter(const v8::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() < 2) return; GLint shader = ARG_GLuint(info[0]); GLenum name = ARG_GLenum(info[1]); GLint value = 0; ppb.opengl_es2->GetShaderiv(GetPPResource(info), shader, name, &value); if (name == GL_DELETE_STATUS || name == GL_COMPILE_STATUS) { info.GetReturnValue().Set(v8::Boolean::New(value)); return; } if (name == GL_SHADER_TYPE) { info.GetReturnValue().Set(v8::Uint32::New(value)); return; } info.GetReturnValue().Set(v8::Null()); } V8_BIND_1_SHADER_STRING(opengl_es2, GetShaderInfoLog, GetShaderiv, GL_INFO_LOG_LENGTH, ARG_GLuint) // void (*GetShaderPrecisionFormat)( // PP_Resource context, GLenum shadertype, GLenum precisiontype, // GLint* range, GLint* precision); V8_BIND_1_SHADER_STRING(opengl_es2, GetShaderSource, GetShaderiv, GL_SHADER_SOURCE_LENGTH, ARG_GLuint) // const GLubyte* (*GetString)(PP_Resource context, GLenum name); // void (*GetTexParameterfv)( // PP_Resource context, GLenum target, GLenum pname, GLfloat* params); // void (*GetTexParameteriv)( // PP_Resource context, GLenum target, GLenum pname, GLint* params); // void (*GetUniformfv)( // PP_Resource context, GLuint program, GLint location, GLfloat* params); // void (*GetUniformiv)( // PP_Resource context, GLuint program, GLint location, GLint* params); void GetUniformLocation(const v8::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() < 2) return; if (!info[0]->IsNumber()) return; if (!info[1]->IsString()) return; v8::String::Utf8Value name(info[1]); const char* str = *name; GLint value = ppb.opengl_es2->GetUniformLocation(GetPPResource(info), ARG_GLint(info[0]), str); info.GetReturnValue().Set(v8::Uint32::New(value)); } // void (*GetVertexAttribfv)( // PP_Resource context, GLuint index, GLenum pname, GLfloat* params); // void (*GetVertexAttribiv)( // PP_Resource context, GLuint index, GLenum pname, GLint* params); // void (*GetVertexAttribPointerv)( // PP_Resource context, GLuint index, GLenum pname, void** pointer); V8_BIND_2(opengl_es2, Hint, ARG_GLenum, ARG_GLenum) // GLboolean (*IsBuffer)(PP_Resource context, GLuint buffer); // GLboolean (*IsEnabled)(PP_Resource context, GLenum cap); // GLboolean (*IsFramebuffer)(PP_Resource context, GLuint framebuffer); // GLboolean (*IsProgram)(PP_Resource context, GLuint program); // GLboolean (*IsRenderbuffer)(PP_Resource context, GLuint renderbuffer); // GLboolean (*IsShader)(PP_Resource context, GLuint shader); // GLboolean (*IsTexture)(PP_Resource context, GLuint texture); V8_BIND_1(opengl_es2, LineWidth, ARG_GLfloat) V8_BIND_1(opengl_es2, LinkProgram, ARG_GLuint) V8_BIND_2(opengl_es2, PixelStorei, ARG_GLenum, ARG_GLint) V8_BIND_2(opengl_es2, PolygonOffset, ARG_GLfloat, ARG_GLfloat) // void (*ReadPixels)( // PP_Resource context, GLint x, GLint y, GLsizei width, GLsizei height, // GLenum format, GLenum type, void* pixels); V8_BIND_0(opengl_es2, ReleaseShaderCompiler) V8_BIND_4(opengl_es2, RenderbufferStorage, ARG_GLenum, ARG_GLenum, ARG_GLsizei, ARG_GLsizei) V8_BIND_2(opengl_es2, SampleCoverage, ARG_GLclampf, ARG_GLboolean) V8_BIND_4(opengl_es2, Scissor, ARG_GLint, ARG_GLint, ARG_GLsizei, ARG_GLsizei) // void (*ShaderBinary)( // PP_Resource context, GLsizei n, const GLuint* shaders, // GLenum binaryformat, const void* binary, GLsizei length); void ShaderSource(const v8::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() < 2) return; if (!info[1]->IsString()) return; v8::String::Utf8Value shaderSource(info[1]); const char* str = *shaderSource; int length = shaderSource.length(); ppb.opengl_es2->ShaderSource( GetPPResource(info), ARG_GLint(info[0]), 1, &str, // string &length); } V8_BIND_3(opengl_es2, StencilFunc, ARG_GLenum, ARG_GLint, ARG_GLuint) V8_BIND_4(opengl_es2, StencilFuncSeparate, ARG_GLenum, ARG_GLenum, ARG_GLint, ARG_GLuint) V8_BIND_1(opengl_es2, StencilMask, ARG_GLuint) V8_BIND_2(opengl_es2, StencilMaskSeparate, ARG_GLenum, ARG_GLuint) V8_BIND_3(opengl_es2, StencilOp, ARG_GLenum, ARG_GLenum, ARG_GLenum) V8_BIND_4(opengl_es2, StencilOpSeparate, ARG_GLenum, ARG_GLenum, ARG_GLenum, ARG_GLenum) /* void texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, ArrayBufferView? pixels); // void (*TexImage2D)( // PP_Resource context, GLenum target, GLint level, GLint internalformat, // GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, // const void* pixels); */ V8_BIND_3(opengl_es2, TexParameterf, ARG_GLenum, ARG_GLenum, ARG_GLfloat) // void (*TexParameterfv)( // PP_Resource context, GLenum target, GLenum pname, const GLfloat* params); V8_BIND_3(opengl_es2, TexParameteri, ARG_GLenum, ARG_GLenum, ARG_GLint) // void (*TexParameteriv)( // PP_Resource context, GLenum target, GLenum pname, const GLint* params); // void (*TexSubImage2D)( // PP_Resource context, GLenum target, GLint level, GLint xoffset, // GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, // const void* pixels); V8_BIND_2(opengl_es2, Uniform1f, ARG_GLint, ARG_GLfloat) V8_BIND_UNIFORM_V(opengl_es2, Uniform1fv, Float32Array, IsFloat32Array, GLfloat) V8_BIND_2(opengl_es2, Uniform1i, ARG_GLint, ARG_GLint) V8_BIND_UNIFORM_V(opengl_es2, Uniform1iv, Int32Array, IsInt32Array, GLint) V8_BIND_3(opengl_es2, Uniform2f, ARG_GLint, ARG_GLfloat, ARG_GLfloat) V8_BIND_UNIFORM_V(opengl_es2, Uniform2fv, Float32Array, IsFloat32Array, GLfloat) V8_BIND_3(opengl_es2, Uniform2i, ARG_GLint, ARG_GLint, ARG_GLint) V8_BIND_UNIFORM_V(opengl_es2, Uniform2iv, Int32Array, IsInt32Array, GLint) V8_BIND_4(opengl_es2, Uniform3f, ARG_GLint, ARG_GLfloat, ARG_GLfloat, ARG_GLfloat) V8_BIND_UNIFORM_V(opengl_es2, Uniform3fv, Float32Array, IsFloat32Array, GLfloat) V8_BIND_4(opengl_es2, Uniform3i, ARG_GLint, ARG_GLint, ARG_GLint, ARG_GLint) V8_BIND_UNIFORM_V(opengl_es2, Uniform3iv, Int32Array, IsInt32Array, GLint) V8_BIND_5(opengl_es2, Uniform4f, ARG_GLint, ARG_GLfloat, ARG_GLfloat, ARG_GLfloat, ARG_GLfloat) V8_BIND_UNIFORM_V(opengl_es2, Uniform4fv, Float32Array, IsFloat32Array, GLfloat) V8_BIND_5(opengl_es2, Uniform4i, ARG_GLint, ARG_GLint, ARG_GLint, ARG_GLint, ARG_GLint) V8_BIND_UNIFORM_V(opengl_es2, Uniform4iv, Int32Array, IsInt32Array, GLint) V8_BIND_UNIFORM_MATRIX(opengl_es2, UniformMatrix2fv, Float32Array, IsFloat32Array, GLfloat) V8_BIND_UNIFORM_MATRIX(opengl_es2, UniformMatrix3fv, Float32Array, IsFloat32Array, GLfloat) V8_BIND_UNIFORM_MATRIX(opengl_es2, UniformMatrix4fv, Float32Array, IsFloat32Array, GLfloat) V8_BIND_1(opengl_es2, UseProgram, ARG_GLuint) V8_BIND_1(opengl_es2, ValidateProgram, ARG_GLuint) V8_BIND_2(opengl_es2, VertexAttrib1f, ARG_GLuint, ARG_GLfloat) V8_BIND_VERTEX_V(opengl_es2, VertexAttrib1fv, Float32Array, IsFloat32Array, GLfloat) V8_BIND_3(opengl_es2, VertexAttrib2f, ARG_GLuint, ARG_GLfloat, ARG_GLfloat) V8_BIND_VERTEX_V(opengl_es2, VertexAttrib2fv, Float32Array, IsFloat32Array, GLfloat) V8_BIND_4(opengl_es2, VertexAttrib3f, ARG_GLuint, ARG_GLfloat, ARG_GLfloat, ARG_GLfloat) V8_BIND_VERTEX_V(opengl_es2, VertexAttrib3fv, Float32Array, IsFloat32Array, GLfloat) V8_BIND_5(opengl_es2, VertexAttrib4f, ARG_GLuint, ARG_GLfloat, ARG_GLfloat, ARG_GLfloat, ARG_GLfloat) V8_BIND_VERTEX_V(opengl_es2, VertexAttrib4fv, Float32Array, IsFloat32Array, GLfloat) void VertexAttribPointer(const v8::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() < 5) return; ppb.opengl_es2->VertexAttribPointer( GetPPResource(info), ARG_GLuint(info[0]), ARG_GLint(info[1]), ARG_GLenum(info[2]), ARG_GLboolean(info[3]), ARG_GLsizei(info[4]), reinterpret_cast<void*>(static_cast<intptr_t>(ARG_GLint(info[4])))); } V8_BIND_4(opengl_es2, Viewport, ARG_GLint, ARG_GLint, ARG_GLsizei, ARG_GLsizei) static const size_t kMethodCount = 107; static const MethodConfiguration g_methods[kMethodCount] = { { "activeTexture", ActiveTexture }, { "attachShader", AttachShader }, { "bindBuffer", BindBuffer }, { "bindFramebuffer", BindFramebuffer }, { "bindRenderbuffer", BindRenderbuffer }, { "bindTexture", BindTexture }, { "blendColor", BlendColor }, { "blendEquation", BlendEquation }, { "blendEquationSeparate", BlendEquationSeparate }, { "blendFunc", BlendFunc }, { "blendFuncSeparate", BlendFuncSeparate }, { "bufferData", BufferData }, { "checkFramebufferStatus", CheckFramebufferStatus }, { "clear", Clear }, { "clearColor", ClearColor }, { "clearDepth", ClearDepthf }, { "clearStencil", ClearStencil }, { "colorMask", ColorMask }, { "compileShader", CompileShader }, { "copyTexImage2D", CopyTexImage2D }, { "copyTexSubImage2D", CopyTexSubImage2D }, { "createBuffer", CreateBuffer }, { "createFramebuffer", CreateFramebuffer }, { "createProgram", CreateProgram }, { "createRenderbuffer", CreateRenderbuffer }, { "createShader", CreateShader }, { "createTexture", CreateTexture }, { "cullFace", CullFace }, { "deleteBuffer", DeleteBuffer }, { "deleteFramebuffer", DeleteFramebuffer }, { "deleteProgram", DeleteProgram }, { "deleteRenderbuffer", DeleteRenderbuffer }, { "deleteShader", DeleteShader }, { "deleteTexture", DeleteTexture }, { "depthFunc", DepthFunc }, { "depthMask", DepthMask }, { "depthRangef", DepthRangef }, { "detachShader", DetachShader }, { "disable", Disable }, { "disableVertexAttribArray", DisableVertexAttribArray }, { "drawArrays", DrawArrays }, { "drawElements", DrawElements }, { "enable", Enable }, { "enableVertexAttribArray", EnableVertexAttribArray }, { "finish", Finish }, { "flush", Flush }, { "framebufferRenderbuffer", FramebufferRenderbuffer }, { "framebufferTexture2D", FramebufferTexture2D }, { "frontFace", FrontFace }, { "generateMipmap", GenerateMipmap }, { "getAttribLocation", GetAttribLocation }, { "getError", GetError }, { "getProgramInfoLog", GetProgramInfoLog }, { "getProgramParameter", GetProgramParameter }, { "getShaderInfoLog", GetShaderInfoLog }, { "getShaderParameter", GetShaderParameter }, { "getShaderSource", GetShaderSource }, { "getUniformLocation", GetUniformLocation }, { "hint", Hint }, { "lineWidth", LineWidth }, { "linkProgram", LinkProgram }, { "pixelStorei", PixelStorei }, { "polygonOffset", PolygonOffset }, { "releaseShaderCompiler", ReleaseShaderCompiler }, { "renderbufferStorage", RenderbufferStorage }, { "sampleCoverage", SampleCoverage }, { "scissor", Scissor }, { "shaderSource", ShaderSource }, { "stencilFunc", StencilFunc }, { "stencilFuncSeparate", StencilFuncSeparate }, { "stencilMask", StencilMask }, { "stencilMaskSeparate", StencilMaskSeparate }, { "stencilOp", StencilOp }, { "stencilOpSeparate", StencilOpSeparate }, { "texParameterf", TexParameterf }, { "texParameteri", TexParameteri }, { "uniform1f", Uniform1f }, { "uniform1fv", Uniform1fv }, { "uniform1i", Uniform1i }, { "uniform1iv", Uniform1iv }, { "uniform2f", Uniform2f }, { "uniform2fv", Uniform2fv }, { "uniform2i", Uniform2i }, { "uniform2iv", Uniform2iv }, { "uniform3f", Uniform3f }, { "uniform3fv", Uniform3fv }, { "uniform3i", Uniform3i }, { "uniform3iv", Uniform3iv }, { "uniform4f", Uniform4f }, { "uniform4fv", Uniform4fv }, { "uniform4i", Uniform4i }, { "uniform4iv", Uniform4iv }, { "uniformMatrix2fv", UniformMatrix2fv }, { "uniformMatrix3fv", UniformMatrix3fv }, { "uniformMatrix4fv", UniformMatrix4fv }, { "useProgram", UseProgram }, { "validateProgram", ValidateProgram }, { "vertexAttrib1f", VertexAttrib1f }, { "vertexAttrib1fv", VertexAttrib1fv }, { "vertexAttrib2f", VertexAttrib2f }, { "vertexAttrib2fv", VertexAttrib2fv }, { "vertexAttrib3f", VertexAttrib3f }, { "vertexAttrib3fv", VertexAttrib3fv }, { "vertexAttrib4f", VertexAttrib4f }, { "vertexAttrib4fv", VertexAttrib4fv }, { "vertexAttribPointer", VertexAttribPointer }, { "viewport", Viewport }, }; static const size_t kConstantCount = 301; static const ConstantConfiguration g_constants[kConstantCount] = { { "DEPTH_BUFFER_BIT", GL_DEPTH_BUFFER_BIT }, { "STENCIL_BUFFER_BIT", GL_STENCIL_BUFFER_BIT }, { "COLOR_BUFFER_BIT", GL_COLOR_BUFFER_BIT }, { "FALSE", GL_FALSE }, { "TRUE", GL_TRUE }, { "POINTS", GL_POINTS }, { "LINES", GL_LINES }, { "LINE_LOOP", GL_LINE_LOOP }, { "LINE_STRIP", GL_LINE_STRIP }, { "TRIANGLES", GL_TRIANGLES }, { "TRIANGLE_STRIP", GL_TRIANGLE_STRIP }, { "TRIANGLE_FAN", GL_TRIANGLE_FAN }, { "ZERO", GL_ZERO }, { "ONE", GL_ONE }, { "SRC_COLOR", GL_SRC_COLOR }, { "ONE_MINUS_SRC_COLOR", GL_ONE_MINUS_SRC_COLOR }, { "SRC_ALPHA", GL_SRC_ALPHA }, { "ONE_MINUS_SRC_ALPHA", GL_ONE_MINUS_SRC_ALPHA }, { "DST_ALPHA", GL_DST_ALPHA }, { "ONE_MINUS_DST_ALPHA", GL_ONE_MINUS_DST_ALPHA }, { "DST_COLOR", GL_DST_COLOR }, { "ONE_MINUS_DST_COLOR", GL_ONE_MINUS_DST_COLOR }, { "SRC_ALPHA_SATURATE", GL_SRC_ALPHA_SATURATE }, { "FUNC_ADD", GL_FUNC_ADD }, { "BLEND_EQUATION", GL_BLEND_EQUATION }, { "BLEND_EQUATION_RGB", GL_BLEND_EQUATION_RGB }, { "BLEND_EQUATION_ALPHA", GL_BLEND_EQUATION_ALPHA }, { "FUNC_SUBTRACT", GL_FUNC_SUBTRACT }, { "FUNC_REVERSE_SUBTRACT", GL_FUNC_REVERSE_SUBTRACT }, { "BLEND_DST_RGB", GL_BLEND_DST_RGB }, { "BLEND_SRC_RGB", GL_BLEND_SRC_RGB }, { "BLEND_DST_ALPHA", GL_BLEND_DST_ALPHA }, { "BLEND_SRC_ALPHA", GL_BLEND_SRC_ALPHA }, { "CONSTANT_COLOR", GL_CONSTANT_COLOR }, { "ONE_MINUS_CONSTANT_COLOR", GL_ONE_MINUS_CONSTANT_COLOR }, { "CONSTANT_ALPHA", GL_CONSTANT_ALPHA }, { "ONE_MINUS_CONSTANT_ALPHA", GL_ONE_MINUS_CONSTANT_ALPHA }, { "BLEND_COLOR", GL_BLEND_COLOR }, { "ARRAY_BUFFER", GL_ARRAY_BUFFER }, { "ELEMENT_ARRAY_BUFFER", GL_ELEMENT_ARRAY_BUFFER }, { "ARRAY_BUFFER_BINDING", GL_ARRAY_BUFFER_BINDING }, { "ELEMENT_ARRAY_BUFFER_BINDING", GL_ELEMENT_ARRAY_BUFFER_BINDING }, { "STREAM_DRAW", GL_STREAM_DRAW }, { "STATIC_DRAW", GL_STATIC_DRAW }, { "DYNAMIC_DRAW", GL_DYNAMIC_DRAW }, { "BUFFER_SIZE", GL_BUFFER_SIZE }, { "BUFFER_USAGE", GL_BUFFER_USAGE }, { "CURRENT_VERTEX_ATTRIB", GL_CURRENT_VERTEX_ATTRIB }, { "FRONT", GL_FRONT }, { "BACK", GL_BACK }, { "FRONT_AND_BACK", GL_FRONT_AND_BACK }, { "TEXTURE_2D", GL_TEXTURE_2D }, { "CULL_FACE", GL_CULL_FACE }, { "BLEND", GL_BLEND }, { "DITHER", GL_DITHER }, { "STENCIL_TEST", GL_STENCIL_TEST }, { "DEPTH_TEST", GL_DEPTH_TEST }, { "SCISSOR_TEST", GL_SCISSOR_TEST }, { "POLYGON_OFFSET_FILL", GL_POLYGON_OFFSET_FILL }, { "SAMPLE_ALPHA_TO_COVERAGE", GL_SAMPLE_ALPHA_TO_COVERAGE }, { "SAMPLE_COVERAGE", GL_SAMPLE_COVERAGE }, { "NO_ERROR", GL_NO_ERROR }, { "INVALID_ENUM", GL_INVALID_ENUM }, { "INVALID_VALUE", GL_INVALID_VALUE }, { "INVALID_OPERATION", GL_INVALID_OPERATION }, { "OUT_OF_MEMORY", GL_OUT_OF_MEMORY }, { "CW", GL_CW }, { "CCW", GL_CCW }, { "LINE_WIDTH", GL_LINE_WIDTH }, { "ALIASED_POINT_SIZE_RANGE", GL_ALIASED_POINT_SIZE_RANGE }, { "ALIASED_LINE_WIDTH_RANGE", GL_ALIASED_LINE_WIDTH_RANGE }, { "CULL_FACE_MODE", GL_CULL_FACE_MODE }, { "FRONT_FACE", GL_FRONT_FACE }, { "DEPTH_RANGE", GL_DEPTH_RANGE }, { "DEPTH_WRITEMASK", GL_DEPTH_WRITEMASK }, { "DEPTH_CLEAR_VALUE", GL_DEPTH_CLEAR_VALUE }, { "DEPTH_FUNC", GL_DEPTH_FUNC }, { "STENCIL_CLEAR_VALUE", GL_STENCIL_CLEAR_VALUE }, { "STENCIL_FUNC", GL_STENCIL_FUNC }, { "STENCIL_FAIL", GL_STENCIL_FAIL }, { "STENCIL_PASS_DEPTH_FAIL", GL_STENCIL_PASS_DEPTH_FAIL }, { "STENCIL_PASS_DEPTH_PASS", GL_STENCIL_PASS_DEPTH_PASS }, { "STENCIL_REF", GL_STENCIL_REF }, { "STENCIL_VALUE_MASK", GL_STENCIL_VALUE_MASK }, { "STENCIL_WRITEMASK", GL_STENCIL_WRITEMASK }, { "STENCIL_BACK_FUNC", GL_STENCIL_BACK_FUNC }, { "STENCIL_BACK_FAIL", GL_STENCIL_BACK_FAIL }, { "STENCIL_BACK_PASS_DEPTH_FAIL", GL_STENCIL_BACK_PASS_DEPTH_FAIL }, { "STENCIL_BACK_PASS_DEPTH_PASS", GL_STENCIL_BACK_PASS_DEPTH_PASS }, { "STENCIL_BACK_REF", GL_STENCIL_BACK_REF }, { "STENCIL_BACK_VALUE_MASK", GL_STENCIL_BACK_VALUE_MASK }, { "STENCIL_BACK_WRITEMASK", GL_STENCIL_BACK_WRITEMASK }, { "VIEWPORT", GL_VIEWPORT }, { "SCISSOR_BOX", GL_SCISSOR_BOX }, { "COLOR_CLEAR_VALUE", GL_COLOR_CLEAR_VALUE }, { "COLOR_WRITEMASK", GL_COLOR_WRITEMASK }, { "UNPACK_ALIGNMENT", GL_UNPACK_ALIGNMENT }, { "PACK_ALIGNMENT", GL_PACK_ALIGNMENT }, { "MAX_TEXTURE_SIZE", GL_MAX_TEXTURE_SIZE }, { "MAX_VIEWPORT_DIMS", GL_MAX_VIEWPORT_DIMS }, { "SUBPIXEL_BITS", GL_SUBPIXEL_BITS }, { "RED_BITS", GL_RED_BITS }, { "GREEN_BITS", GL_GREEN_BITS }, { "BLUE_BITS", GL_BLUE_BITS }, { "ALPHA_BITS", GL_ALPHA_BITS }, { "DEPTH_BITS", GL_DEPTH_BITS }, { "STENCIL_BITS", GL_STENCIL_BITS }, { "POLYGON_OFFSET_UNITS", GL_POLYGON_OFFSET_UNITS }, { "POLYGON_OFFSET_FACTOR", GL_POLYGON_OFFSET_FACTOR }, { "TEXTURE_BINDING_2D", GL_TEXTURE_BINDING_2D }, { "SAMPLE_BUFFERS", GL_SAMPLE_BUFFERS }, { "SAMPLES", GL_SAMPLES }, { "SAMPLE_COVERAGE_VALUE", GL_SAMPLE_COVERAGE_VALUE }, { "SAMPLE_COVERAGE_INVERT", GL_SAMPLE_COVERAGE_INVERT }, { "NUM_COMPRESSED_TEXTURE_FORMATS", GL_NUM_COMPRESSED_TEXTURE_FORMATS }, { "COMPRESSED_TEXTURE_FORMATS", GL_COMPRESSED_TEXTURE_FORMATS }, { "DONT_CARE", GL_DONT_CARE }, { "FASTEST", GL_FASTEST }, { "NICEST", GL_NICEST }, { "GENERATE_MIPMAP_HINT", GL_GENERATE_MIPMAP_HINT }, { "BYTE", GL_BYTE }, { "UNSIGNED_BYTE", GL_UNSIGNED_BYTE }, { "SHORT", GL_SHORT }, { "UNSIGNED_SHORT", GL_UNSIGNED_SHORT }, { "INT", GL_INT }, { "UNSIGNED_INT", GL_UNSIGNED_INT }, { "FLOAT", GL_FLOAT }, { "FIXED", GL_FIXED }, { "DEPTH_COMPONENT", GL_DEPTH_COMPONENT }, { "ALPHA", GL_ALPHA }, { "RGB", GL_RGB }, { "RGBA", GL_RGBA }, { "LUMINANCE", GL_LUMINANCE }, { "LUMINANCE_ALPHA", GL_LUMINANCE_ALPHA }, { "UNSIGNED_SHORT_4_4_4_4", GL_UNSIGNED_SHORT_4_4_4_4 }, { "UNSIGNED_SHORT_5_5_5_1", GL_UNSIGNED_SHORT_5_5_5_1 }, { "UNSIGNED_SHORT_5_6_5", GL_UNSIGNED_SHORT_5_6_5 }, { "FRAGMENT_SHADER", GL_FRAGMENT_SHADER }, { "VERTEX_SHADER", GL_VERTEX_SHADER }, { "MAX_VERTEX_ATTRIBS", GL_MAX_VERTEX_ATTRIBS }, { "MAX_VERTEX_UNIFORM_VECTORS", GL_MAX_VERTEX_UNIFORM_VECTORS }, { "MAX_VARYING_VECTORS", GL_MAX_VARYING_VECTORS }, { "MAX_COMBINED_TEXTURE_IMAGE_UNITS", GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS }, { "MAX_VERTEX_TEXTURE_IMAGE_UNITS", GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS }, { "MAX_TEXTURE_IMAGE_UNITS", GL_MAX_TEXTURE_IMAGE_UNITS }, { "MAX_FRAGMENT_UNIFORM_VECTORS", GL_MAX_FRAGMENT_UNIFORM_VECTORS }, { "SHADER_TYPE", GL_SHADER_TYPE }, { "DELETE_STATUS", GL_DELETE_STATUS }, { "LINK_STATUS", GL_LINK_STATUS }, { "VALIDATE_STATUS", GL_VALIDATE_STATUS }, { "ATTACHED_SHADERS", GL_ATTACHED_SHADERS }, { "ACTIVE_UNIFORMS", GL_ACTIVE_UNIFORMS }, { "ACTIVE_UNIFORM_MAX_LENGTH", GL_ACTIVE_UNIFORM_MAX_LENGTH }, { "ACTIVE_ATTRIBUTES", GL_ACTIVE_ATTRIBUTES }, { "ACTIVE_ATTRIBUTE_MAX_LENGTH", GL_ACTIVE_ATTRIBUTE_MAX_LENGTH }, { "SHADING_LANGUAGE_VERSION", GL_SHADING_LANGUAGE_VERSION }, { "CURRENT_PROGRAM", GL_CURRENT_PROGRAM }, { "NEVER", GL_NEVER }, { "LESS", GL_LESS }, { "EQUAL", GL_EQUAL }, { "LEQUAL", GL_LEQUAL }, { "GREATER", GL_GREATER }, { "NOTEQUAL", GL_NOTEQUAL }, { "GEQUAL", GL_GEQUAL }, { "ALWAYS", GL_ALWAYS }, { "KEEP", GL_KEEP }, { "REPLACE", GL_REPLACE }, { "INCR", GL_INCR }, { "DECR", GL_DECR }, { "INVERT", GL_INVERT }, { "INCR_WRAP", GL_INCR_WRAP }, { "DECR_WRAP", GL_DECR_WRAP }, { "VENDOR", GL_VENDOR }, { "RENDERER", GL_RENDERER }, { "VERSION", GL_VERSION }, { "EXTENSIONS", GL_EXTENSIONS }, { "NEAREST", GL_NEAREST }, { "LINEAR", GL_LINEAR }, { "NEAREST_MIPMAP_NEAREST", GL_NEAREST_MIPMAP_NEAREST }, { "LINEAR_MIPMAP_NEAREST", GL_LINEAR_MIPMAP_NEAREST }, { "NEAREST_MIPMAP_LINEAR", GL_NEAREST_MIPMAP_LINEAR }, { "LINEAR_MIPMAP_LINEAR", GL_LINEAR_MIPMAP_LINEAR }, { "TEXTURE_MAG_FILTER", GL_TEXTURE_MAG_FILTER }, { "TEXTURE_MIN_FILTER", GL_TEXTURE_MIN_FILTER }, { "TEXTURE_WRAP_S", GL_TEXTURE_WRAP_S }, { "TEXTURE_WRAP_T", GL_TEXTURE_WRAP_T }, { "TEXTURE", GL_TEXTURE }, { "TEXTURE_CUBE_MAP", GL_TEXTURE_CUBE_MAP }, { "TEXTURE_BINDING_CUBE_MAP", GL_TEXTURE_BINDING_CUBE_MAP }, { "TEXTURE_CUBE_MAP_POSITIVE_X", GL_TEXTURE_CUBE_MAP_POSITIVE_X }, { "TEXTURE_CUBE_MAP_NEGATIVE_X", GL_TEXTURE_CUBE_MAP_NEGATIVE_X }, { "TEXTURE_CUBE_MAP_POSITIVE_Y", GL_TEXTURE_CUBE_MAP_POSITIVE_Y }, { "TEXTURE_CUBE_MAP_NEGATIVE_Y", GL_TEXTURE_CUBE_MAP_NEGATIVE_Y }, { "TEXTURE_CUBE_MAP_POSITIVE_Z", GL_TEXTURE_CUBE_MAP_POSITIVE_Z }, { "TEXTURE_CUBE_MAP_NEGATIVE_Z", GL_TEXTURE_CUBE_MAP_NEGATIVE_Z }, { "MAX_CUBE_MAP_TEXTURE_SIZE", GL_MAX_CUBE_MAP_TEXTURE_SIZE }, { "TEXTURE0", GL_TEXTURE0 }, { "TEXTURE1", GL_TEXTURE1 }, { "TEXTURE2", GL_TEXTURE2 }, { "TEXTURE3", GL_TEXTURE3 }, { "TEXTURE4", GL_TEXTURE4 }, { "TEXTURE5", GL_TEXTURE5 }, { "TEXTURE6", GL_TEXTURE6 }, { "TEXTURE7", GL_TEXTURE7 }, { "TEXTURE8", GL_TEXTURE8 }, { "TEXTURE9", GL_TEXTURE9 }, { "TEXTURE10", GL_TEXTURE10 }, { "TEXTURE11", GL_TEXTURE11 }, { "TEXTURE12", GL_TEXTURE12 }, { "TEXTURE13", GL_TEXTURE13 }, { "TEXTURE14", GL_TEXTURE14 }, { "TEXTURE15", GL_TEXTURE15 }, { "TEXTURE16", GL_TEXTURE16 }, { "TEXTURE17", GL_TEXTURE17 }, { "TEXTURE18", GL_TEXTURE18 }, { "TEXTURE19", GL_TEXTURE19 }, { "TEXTURE20", GL_TEXTURE20 }, { "TEXTURE21", GL_TEXTURE21 }, { "TEXTURE22", GL_TEXTURE22 }, { "TEXTURE23", GL_TEXTURE23 }, { "TEXTURE24", GL_TEXTURE24 }, { "TEXTURE25", GL_TEXTURE25 }, { "TEXTURE26", GL_TEXTURE26 }, { "TEXTURE27", GL_TEXTURE27 }, { "TEXTURE28", GL_TEXTURE28 }, { "TEXTURE29", GL_TEXTURE29 }, { "TEXTURE30", GL_TEXTURE30 }, { "TEXTURE31", GL_TEXTURE31 }, { "ACTIVE_TEXTURE", GL_ACTIVE_TEXTURE }, { "REPEAT", GL_REPEAT }, { "CLAMP_TO_EDGE", GL_CLAMP_TO_EDGE }, { "MIRRORED_REPEAT", GL_MIRRORED_REPEAT }, { "FLOAT_VEC2", GL_FLOAT_VEC2 }, { "FLOAT_VEC3", GL_FLOAT_VEC3 }, { "FLOAT_VEC4", GL_FLOAT_VEC4 }, { "INT_VEC2", GL_INT_VEC2 }, { "INT_VEC3", GL_INT_VEC3 }, { "INT_VEC4", GL_INT_VEC4 }, { "BOOL", GL_BOOL }, { "BOOL_VEC2", GL_BOOL_VEC2 }, { "BOOL_VEC3", GL_BOOL_VEC3 }, { "BOOL_VEC4", GL_BOOL_VEC4 }, { "FLOAT_MAT2", GL_FLOAT_MAT2 }, { "FLOAT_MAT3", GL_FLOAT_MAT3 }, { "FLOAT_MAT4", GL_FLOAT_MAT4 }, { "SAMPLER_2D", GL_SAMPLER_2D }, { "SAMPLER_CUBE", GL_SAMPLER_CUBE }, { "VERTEX_ATTRIB_ARRAY_ENABLED", GL_VERTEX_ATTRIB_ARRAY_ENABLED }, { "VERTEX_ATTRIB_ARRAY_SIZE", GL_VERTEX_ATTRIB_ARRAY_SIZE }, { "VERTEX_ATTRIB_ARRAY_STRIDE", GL_VERTEX_ATTRIB_ARRAY_STRIDE }, { "VERTEX_ATTRIB_ARRAY_TYPE", GL_VERTEX_ATTRIB_ARRAY_TYPE }, { "VERTEX_ATTRIB_ARRAY_NORMALIZED", GL_VERTEX_ATTRIB_ARRAY_NORMALIZED }, { "VERTEX_ATTRIB_ARRAY_POINTER", GL_VERTEX_ATTRIB_ARRAY_POINTER }, { "VERTEX_ATTRIB_ARRAY_BUFFER_BINDING", GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING }, { "IMPLEMENTATION_COLOR_READ_TYPE", GL_IMPLEMENTATION_COLOR_READ_TYPE }, { "IMPLEMENTATION_COLOR_READ_FORMAT", GL_IMPLEMENTATION_COLOR_READ_FORMAT }, { "COMPILE_STATUS", GL_COMPILE_STATUS }, { "INFO_LOG_LENGTH", GL_INFO_LOG_LENGTH }, { "SHADER_SOURCE_LENGTH", GL_SHADER_SOURCE_LENGTH }, { "SHADER_COMPILER", GL_SHADER_COMPILER }, { "SHADER_BINARY_FORMATS", GL_SHADER_BINARY_FORMATS }, { "NUM_SHADER_BINARY_FORMATS", GL_NUM_SHADER_BINARY_FORMATS }, { "LOW_FLOAT", GL_LOW_FLOAT }, { "MEDIUM_FLOAT", GL_MEDIUM_FLOAT }, { "HIGH_FLOAT", GL_HIGH_FLOAT }, { "LOW_INT", GL_LOW_INT }, { "MEDIUM_INT", GL_MEDIUM_INT }, { "HIGH_INT", GL_HIGH_INT }, { "FRAMEBUFFER", GL_FRAMEBUFFER }, { "RENDERBUFFER", GL_RENDERBUFFER }, { "RGBA4", GL_RGBA4 }, { "RGB5_A1", GL_RGB5_A1 }, { "RGB565", GL_RGB565 }, { "DEPTH_COMPONENT16", GL_DEPTH_COMPONENT16 }, { "STENCIL_INDEX8", GL_STENCIL_INDEX8 }, { "RENDERBUFFER_WIDTH", GL_RENDERBUFFER_WIDTH }, { "RENDERBUFFER_HEIGHT", GL_RENDERBUFFER_HEIGHT }, { "RENDERBUFFER_INTERNAL_FORMAT", GL_RENDERBUFFER_INTERNAL_FORMAT }, { "RENDERBUFFER_RED_SIZE", GL_RENDERBUFFER_RED_SIZE }, { "RENDERBUFFER_GREEN_SIZE", GL_RENDERBUFFER_GREEN_SIZE }, { "RENDERBUFFER_BLUE_SIZE", GL_RENDERBUFFER_BLUE_SIZE }, { "RENDERBUFFER_ALPHA_SIZE", GL_RENDERBUFFER_ALPHA_SIZE }, { "RENDERBUFFER_DEPTH_SIZE", GL_RENDERBUFFER_DEPTH_SIZE }, { "RENDERBUFFER_STENCIL_SIZE", GL_RENDERBUFFER_STENCIL_SIZE }, { "FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE", GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE }, { "FRAMEBUFFER_ATTACHMENT_OBJECT_NAME", GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME }, { "FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL", GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL }, { "FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE", GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE }, { "COLOR_ATTACHMENT0", GL_COLOR_ATTACHMENT0 }, { "DEPTH_ATTACHMENT", GL_DEPTH_ATTACHMENT }, { "STENCIL_ATTACHMENT", GL_STENCIL_ATTACHMENT }, { "NONE", GL_NONE }, { "FRAMEBUFFER_COMPLETE", GL_FRAMEBUFFER_COMPLETE }, { "FRAMEBUFFER_INCOMPLETE_ATTACHMENT", GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT }, { "FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT", GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT }, { "FRAMEBUFFER_INCOMPLETE_DIMENSIONS", GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS }, { "FRAMEBUFFER_UNSUPPORTED", GL_FRAMEBUFFER_UNSUPPORTED }, { "FRAMEBUFFER_BINDING", GL_FRAMEBUFFER_BINDING }, { "RENDERBUFFER_BINDING", GL_RENDERBUFFER_BINDING }, { "MAX_RENDERBUFFER_SIZE", GL_MAX_RENDERBUFFER_SIZE }, { "INVALID_FRAMEBUFFER_OPERATION", GL_INVALID_FRAMEBUFFER_OPERATION }, }; } v8::Handle<v8::FunctionTemplate> CreateWebGLBindings() { v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); v8::Handle<v8::FunctionTemplate> templ = v8::FunctionTemplate::New(); v8::Handle<v8::ObjectTemplate> proto = templ->PrototypeTemplate(); InstallConstants(proto, g_constants, kConstantCount); InstallMethods(proto, g_methods, kMethodCount); return handle_scope.Close(templ); } }
46.354302
166
0.585304
slightlyoff
7ea632659d78f66c799da5c115d5812060e893c0
2,942
hpp
C++
src/siili/kz/data_object_vector_list_impl.hpp
siilisolutions-pl/siili-kzutils
567e1f17160899911939d2402ee60550d6309e90
[ "Apache-2.0" ]
1
2019-10-07T15:58:29.000Z
2019-10-07T15:58:29.000Z
src/siili/kz/data_object_vector_list_impl.hpp
siilisolutions-pl/siili-kzutils
567e1f17160899911939d2402ee60550d6309e90
[ "Apache-2.0" ]
null
null
null
src/siili/kz/data_object_vector_list_impl.hpp
siilisolutions-pl/siili-kzutils
567e1f17160899911939d2402ee60550d6309e90
[ "Apache-2.0" ]
1
2019-10-07T16:38:37.000Z
2019-10-07T16:38:37.000Z
#ifndef SIILI__KZ__DATA_OBJECT_VECTOR_LIST_IMPL_HPP #define SIILI__KZ__DATA_OBJECT_VECTOR_LIST_IMPL_HPP #include <algorithm> #include <kanzi/core.ui/data/data_object.hpp> #include <kanzi/core.ui/data/data_object_list.hpp> #include <memory> #include <siili/kz/data_object_dynamic_list.hpp> #include <utility> #include <vector> namespace siili { namespace kz { namespace data_object_vector_list_impl { class DataObjectVectorList : public DataObjectDynamicList { public: DataObjectVectorList( kanzi::Domain *domain, kanzi::string_view name, kanzi::DataObjectSharedPtr itemTemplate); std::size_t itemCount() override; kanzi::DataObjectSharedPtr acquireItem(std::size_t index) override; void releaseItem(std::size_t index) override; kanzi::DataObjectSharedPtr getItemTemplate() override; void insertItems(std::size_t pos, const std::vector<kanzi::DataObjectSharedPtr> &items) override; void eraseItems(std::size_t beginPos, std::size_t endPos) override; private: std::vector<kanzi::DataObjectSharedPtr> mListItems; kanzi::DataObjectSharedPtr mItemTemplate; }; inline DataObjectVectorList::DataObjectVectorList( kanzi::Domain *domain, kanzi::string_view name, kanzi::DataObjectSharedPtr itemTemplate) : DataObjectDynamicList(domain, name), mListItems(), mItemTemplate(std::move(itemTemplate)) { } inline std::size_t DataObjectVectorList::itemCount() { return mListItems.size(); } inline kanzi::DataObjectSharedPtr DataObjectVectorList::acquireItem(std::size_t index) { return index < mListItems.size() ? mListItems[index] : std::make_shared<kanzi::DataObject>(getDomain(), ""); } inline void DataObjectVectorList::releaseItem(std::size_t) { } inline kanzi::DataObjectSharedPtr DataObjectVectorList::getItemTemplate() { return mItemTemplate ? mItemTemplate : acquireItem(0); } inline void DataObjectVectorList::insertItems(std::size_t pos, const std::vector<kanzi::DataObjectSharedPtr> &items) { const auto effPos = std::min(pos, mListItems.size()); if (!items.empty()) { mListItems.insert(mListItems.begin() + effPos, items.begin(), items.end()); notifyModified(); } } inline void DataObjectVectorList::eraseItems(std::size_t beginPos, std::size_t endPos) { if (endPos < beginPos) { return; } const auto effBeginPos = std::min(beginPos, mListItems.size()); const auto effEndPos = std::min(endPos, mListItems.size()); if (effBeginPos != effEndPos) { mListItems.erase(mListItems.begin() + effBeginPos, mListItems.begin() + effEndPos); notifyModified(); } } } inline std::shared_ptr<DataObjectDynamicList> makeDataObjectVectorList( kanzi::Domain *domain, kanzi::string_view name, kanzi::DataObjectSharedPtr itemTemplate) { using namespace data_object_vector_list_impl; return std::make_shared<DataObjectVectorList>(domain, name, itemTemplate); } } } #endif
25.807018
116
0.743372
siilisolutions-pl
7ea8ae9aaa21af63f1bcee21ef1be9fb2b852ebc
632
cpp
C++
src/Queue.cpp
dylsonowski/Producer_Consumers_Scheme
b784dc1f497f41c13d7ddee51c73e39a6daeb923
[ "Apache-2.0" ]
null
null
null
src/Queue.cpp
dylsonowski/Producer_Consumers_Scheme
b784dc1f497f41c13d7ddee51c73e39a6daeb923
[ "Apache-2.0" ]
null
null
null
src/Queue.cpp
dylsonowski/Producer_Consumers_Scheme
b784dc1f497f41c13d7ddee51c73e39a6daeb923
[ "Apache-2.0" ]
null
null
null
#include "Queue.h" std::mutex Queue::s_queueBlock; bool Queue::s_creationProcessFinished = false; void Queue::ChangeQueueStatus(bool canRead, bool canWrite) { _canRead = canRead; _canWrite = canWrite; } bool Queue::AddElement(std::array<int, 100000> newElement) { if (_canWrite) { s_queueBlock.lock(); _taskQueue.emplace_back(newElement); s_queueBlock.unlock(); return true; } else return false; } std::array<int, 100000> Queue::PopFirstElement() { if (_canRead) { s_queueBlock.lock(); std::array<int, 100000> temp = _taskQueue.front(); _taskQueue.pop_front(); s_queueBlock.unlock(); return temp; } }
20.387097
60
0.71519
dylsonowski
7ead7044df37b77e631c423666929b1980841d4c
12,726
cpp
C++
src/message_manager.cpp
klei1984/max
dc0f9108bbcfd4cb73ea101883d551c612097469
[ "MIT" ]
19
2020-02-06T17:41:39.000Z
2022-03-31T07:38:15.000Z
src/message_manager.cpp
klei1984/max
dc0f9108bbcfd4cb73ea101883d551c612097469
[ "MIT" ]
9
2020-02-14T15:46:46.000Z
2021-12-22T16:35:53.000Z
src/message_manager.cpp
klei1984/max
dc0f9108bbcfd4cb73ea101883d551c612097469
[ "MIT" ]
null
null
null
/* Copyright (c) 2021 M.A.X. Port Team * * 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 "message_manager.hpp" #include <algorithm> #include "dialogmenu.hpp" #include "gui.hpp" extern "C" { #include "gnw.h" } /// \todo Fix gwin includes extern "C" { WindowInfo* gwin_get_window(unsigned char id); } static_assert(sizeof(Point) == 4, "It is expected that Point is exactly 2+2 bytes long."); static_assert(sizeof(bool) == 1, "It is expected that bool is exactly 1 byte long."); #define MESSAGE_MANAGER_TEAM_COUNT 4 #define MESSAGE_MANAGER_MAX_COUNT 50 #define MESSAGE_MANAGER_MESSAGE_BUFFER_SIZE 800 #define MESSAGE_MANAGER_TEXT_BUFFER_SIZE 300 char MessageManager_MessageBuffer[MESSAGE_MANAGER_MESSAGE_BUFFER_SIZE]; char MessageManager_TextBuffer[MESSAGE_MANAGER_TEXT_BUFFER_SIZE]; short MessageManager_Buffer1_Length; short MessageManager_MessageBox_Width; short MessageManager_MessageBox_Height; char* MessageManager_MessageBox_BgColor; bool MessageManager_MessageBox_IsActive; /// \todo Implement correct LUT char** MessageManager_MessageBox_BgColorArray[] = {0, 0, 0}; SmartList<MessageLogEntry> MessageManager_TeamMessageLog[MESSAGE_MANAGER_TEAM_COUNT]; void MessageManager_WrapText(char* text, short width) { int position = 0; short row_width = 0; char* buffer = MessageManager_MessageBuffer; do { if (text[position] == '\n') { MessageManager_MessageBox_Width = std::max(row_width, MessageManager_MessageBox_Width); MessageManager_MessageBox_Height += 10; MessageManager_MessageBuffer[MessageManager_Buffer1_Length] = ' '; ++MessageManager_Buffer1_Length; MessageManager_MessageBuffer[MessageManager_Buffer1_Length] = '\0'; ++MessageManager_Buffer1_Length; row_width = 0; buffer = &MessageManager_MessageBuffer[MessageManager_Buffer1_Length]; } else { short char_width = text_char_width(text[position]); if ((row_width + char_width) > width) { char* line_buffer = &MessageManager_MessageBuffer[MessageManager_Buffer1_Length]; *line_buffer = '\0'; --line_buffer; while (*line_buffer != ' ') { --line_buffer; } *line_buffer = '\0'; row_width = text_width(buffer); MessageManager_MessageBox_Width = std::max(row_width, MessageManager_MessageBox_Width); buffer = line_buffer + 1; row_width = text_width(buffer); MessageManager_MessageBox_Height += 10; } row_width += char_width; SDL_assert(MessageManager_Buffer1_Length < sizeof(MessageManager_MessageBuffer)); MessageManager_MessageBuffer[MessageManager_Buffer1_Length] = text[position]; ++MessageManager_Buffer1_Length; } } while (text[position++] != '\0'); MessageManager_MessageBox_Width = std::max(row_width, MessageManager_MessageBox_Width); MessageManager_MessageBox_Height += 10; } void MessageManager_DrawMessageBoxText(unsigned char* buffer, int width, int left_margin, int top_margin, char* text, int color, bool monospace) { int flags; int offset; offset = 0; text_font(5); top_margin *= width; if (monospace) { flags = 0x40000; } else { flags = 0; } color += flags + 0x10000; do { text_to_buf(&buffer[left_margin + top_margin], &text[offset], width, width, color); top_margin += 10 * width; offset += strlen(&text[offset]) + 1; } while (text[offset] != '\0'); } void MessageManager_AddMessage(char* text, ResourceID id) { MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].PushBack( *dynamic_cast<MessageLogEntry*>(new (std::nothrow) MessageLogEntry(text, id))); if (MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].GetCount() > MESSAGE_MANAGER_MAX_COUNT) { MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].Remove( *MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].Begin()); } } void MessageManager_DrawMessage(char* text, char type, UnitInfo* unit, Point point) { if (text[0] != '\0') { MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].PushBack( *dynamic_cast<MessageLogEntry*>(new (std::nothrow) MessageLogEntry(text, unit, point))); if (MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].GetCount() > MESSAGE_MANAGER_MAX_COUNT) { MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].Remove( *MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].Begin()); } MessageManager_DrawMessage(text, type, 0); } } void MessageManager_DrawMessage(char* text, char type, int mode, bool flag1, bool save_to_log) { if (*text != '\0') { if (mode) { DialogMenu dialog(text, flag1); dialog.Run(); } else { WindowInfo* window_2; WindowInfo* window_38; int width; int offset_x; int offset_y; Rect bounds; if (MessageManager_MessageBox_IsActive) { MessageManager_ClearMessageBox(); } if (save_to_log) { MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].PushBack( *dynamic_cast<MessageLogEntry*>(new (std::nothrow) MessageLogEntry(text, I_CMPLX))); if (MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].GetCount() > MESSAGE_MANAGER_MAX_COUNT) { MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].Remove( *MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].Begin()); } } text_font(5); window_38 = gwin_get_window(38); width = window_38->window.lrx - window_38->window.ulx; MessageManager_MessageBox_Width = 0; MessageManager_Buffer1_Length = 0; MessageManager_MessageBox_Height = 20; MessageManager_WrapText(text, width - 20); MessageManager_MessageBuffer[MessageManager_Buffer1_Length] = '\0'; MessageManager_MessageBox_Width += 20; offset_x = 0; offset_y = 10; window_2 = gwin_get_window(2); window_2->window.ulx = window_38->window.ulx + offset_x; window_2->window.uly = window_38->window.uly + offset_y; window_2->window.lrx = window_2->window.ulx + MessageManager_MessageBox_Width; window_2->window.lry = window_2->window.uly + MessageManager_MessageBox_Height; window_2->buffer = &window_38->buffer[offset_x + 640 * offset_y]; MessageManager_MessageBox_BgColor = *MessageManager_MessageBox_BgColorArray[type]; MessageManager_MessageBox_IsActive = true; /// \todo Implement functions // sub_9A9FD(&bounds); // drawmap_add_dirty_zone(&bounds); } } } void MessageManager_DrawMessageBox() { WindowInfo* window; int height; int fullw; int row; window = gwin_get_window(2); for (height = MessageManager_MessageBox_Height, fullw = 0; height > 0; --height, fullw += 640) { for (row = 0; row < MessageManager_MessageBox_Width; ++row) { window->buffer[row + fullw] = MessageManager_MessageBox_BgColor[window->buffer[row + fullw]]; } } MessageManager_DrawMessageBoxText(window->buffer, 640, 10, 10, MessageManager_MessageBuffer, 0xFF, false); } void MessageManager_ClearMessageBox() { WindowInfo* window; Rect bounds; /// \todo Implement functions // sub_9A9FD(&bounds); // drawmap_add_dirty_zone(&bounds); window = gwin_get_window(2); window->window.ulx = -1; window->window.uly = -1; window->window.lrx = -1; window->window.lry = -1; MessageManager_MessageBox_IsActive = false; } void MessageManager_DrawTextMessage(WindowInfo* window, unsigned char* buffer, int width, int left_margin, int top_margin, char* text, int color, bool screen_refresh) { int text_position = 0; int buffer_position = 0; do { if (text[text_position] == '\n') { MessageManager_TextBuffer[buffer_position] = ' '; ++buffer_position; MessageManager_TextBuffer[buffer_position] = '\0'; ++buffer_position; } else { MessageManager_TextBuffer[buffer_position] = text[text_position]; ++buffer_position; } } while (text[text_position++] != '\0'); MessageManager_TextBuffer[buffer_position] = '\0'; MessageManager_DrawMessageBoxText(buffer, width, left_margin, top_margin, MessageManager_TextBuffer, color, false); if (screen_refresh) { win_draw_rect(window->id, &window->window); } } void MessageManager_LoadMessageLogs(SmartFileReader& file) { for (int i = 0; i < MESSAGE_MANAGER_TEAM_COUNT; + i) { MessageManager_TeamMessageLog[i].Clear(); for (int count = file.ReadObjectCount(); count > 0; --count) { MessageManager_TeamMessageLog[i].PushBack( *dynamic_cast<MessageLogEntry*>(new (std::nothrow) MessageLogEntry(file))); } } } void MessageManager_SaveMessageLogs(SmartFileWriter& file) { for (int i = 0; i < MESSAGE_MANAGER_TEAM_COUNT; + i) { file.WriteObjectCount(MessageManager_TeamMessageLog[i].GetCount()); for (SmartList<MessageLogEntry>::Iterator it = MessageManager_TeamMessageLog[i].Begin(); it != MessageManager_TeamMessageLog[i].End(); ++it) { (*it).FileSave(file); } } } void MessageManager_ClearMessageLogs() { for (int i = 0; i < MESSAGE_MANAGER_TEAM_COUNT; + i) { MessageManager_TeamMessageLog[i].Clear(); } } MessageLogEntry::MessageLogEntry(SmartFileReader& file) { unsigned short length; file.Read(length); text = new (std::nothrow) char[length]; file.Read(text, length); unit = dynamic_cast<UnitInfo*>(file.ReadObject()); file.Read(point); file.Read(field_20); file.Read(id); } MessageLogEntry::MessageLogEntry(char* text, ResourceID id) : id(id), text(strdup(text)), field_20(false) {} MessageLogEntry::MessageLogEntry(char* text, UnitInfo* unit, Point point) : text(strdup(text)), unit(unit), point(point), field_20(true), id(INVALID_ID) {} MessageLogEntry::~MessageLogEntry() { delete text; } void MessageLogEntry::FileSave(SmartFileWriter& file) { unsigned short length = strlen(text); file.Write(length); file.Write(text, length); file.WriteObject(&*unit); file.Write(point); file.Write(field_20); file.Write(id); } char* MessageLogEntry::GetCstr() const { return text; } void MessageLogEntry::MessageLogEntry_sub_B780B() { MessageManager_DrawMessage(text, 0, 0); if (field_20) { /// \todo Implement missing stuff if (unit != nullptr && unit->hits && unit->IsVisibleToTeam(GUI_PlayerTeamIndex)) { // sub_9F637(*unit); } else { // sub_A1620(1, point.x, point, y); } } }
35.747191
120
0.63995
klei1984
7ead720914b8f04b9d2f83f5db5bfd9789445a62
460
cpp
C++
Me.cpp
adityas129/ECE-150
0db483690ad2ce8fe1d5df4994c55bddc7a32569
[ "MIT" ]
null
null
null
Me.cpp
adityas129/ECE-150
0db483690ad2ce8fe1d5df4994c55bddc7a32569
[ "MIT" ]
null
null
null
Me.cpp
adityas129/ECE-150
0db483690ad2ce8fe1d5df4994c55bddc7a32569
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(){ cout << "My name is Aditya Sharma." << endl; cout << "My UserID is a273shar." << endl; cout << "I am in Electrical Engineering" << endl; cout << "I like programming because it is a very intellectually stimulating process. When you are solving a question, its like a big puzzle that has a bunch of pieces and the pieces need to match just perfectly for you to get the result." << endl; return 0; }
32.857143
248
0.708696
adityas129
7eae8153038ba986de7660142658879d2ae4ab80
2,676
cpp
C++
4/src/InterfaceFileSystem.cpp
AlinaNenasheva/operating-systems
9f04381945aa7870dff9616b45c6d07e96701bd7
[ "MIT" ]
null
null
null
4/src/InterfaceFileSystem.cpp
AlinaNenasheva/operating-systems
9f04381945aa7870dff9616b45c6d07e96701bd7
[ "MIT" ]
null
null
null
4/src/InterfaceFileSystem.cpp
AlinaNenasheva/operating-systems
9f04381945aa7870dff9616b45c6d07e96701bd7
[ "MIT" ]
null
null
null
#pragma once #include <map> #include "FileExistException.cpp" #include "FileNotFoundException.cpp" #include "OutOfMemoryException.cpp" #include "CustomFile.cpp" #define FILE_NOT_FOUND 0 #define DEFAULT_TOTAL_MEMORY 1024 using namespace std; class InterfaceFileSystem { private: map<string, CustomFile *> *nameToFile = new map<string, CustomFile *>(); unsigned long totalMemory; unsigned long capturedMemory = 0; public: InterfaceFileSystem() { InterfaceFileSystem(DEFAULT_TOTAL_MEMORY); } InterfaceFileSystem(unsigned long totalMemory) { this->totalMemory = totalMemory; } vector<CustomFile *> *findAll() { vector<CustomFile *> *files = new vector<CustomFile *>(); for (map<string, CustomFile *>::iterator it = nameToFile->begin(); it != nameToFile->end(); it++) { files->push_back(it->second); } return files; } CustomFile *findByName(const string &name) { if (nameToFile->count(name) > FILE_NOT_FOUND) { return nameToFile->find(name)->second; } else { throw FileNotFoundException(); } } CustomFile *save(const string &name, CustomFile *file) { if (nameToFile->count(name) == FILE_NOT_FOUND) { nameToFile->insert(pair<string, CustomFile *>(name, file)); decreaseFreeMemory(file->getSize()); return file; } else { throw FileIsExistException(); } } CustomFile *deleteFile(const string &name) { CustomFile *file = findByName(name); increaseFreeMemory(file->getSize()); nameToFile->erase(name); return file; } void updateFile(const string &name, CustomFile *file) { if (nameToFile->count(name) > FILE_NOT_FOUND) { const unsigned long previousSize = nameToFile->find(name)->second->getSize(); const unsigned long currentSize = file->getSize(); increaseFreeMemory(previousSize); if (currentSize <= getFreeMemory()) { nameToFile->insert(pair<string, CustomFile *>(name, file)); decreaseFreeMemory(currentSize); } else { decreaseFreeMemory(previousSize); throw OutOfMemoryException(); } } else { throw FileNotFoundException(); } } private: void increaseFreeMemory(unsigned long memory) { capturedMemory -= memory; } void decreaseFreeMemory(unsigned long memory) { capturedMemory += memory; } unsigned long getFreeMemory() { return totalMemory - capturedMemory; } };
28.168421
107
0.612855
AlinaNenasheva
9d176a9145ad7fbc6bbe4820ac5e59ab56825274
4,556
cpp
C++
Engine/source/forest/ts/tsForestCellBatch.cpp
jyaskus/Torque3D
fcac140405b2fbe7c54e7a2dc6e3b10b79c8983f
[ "Unlicense" ]
6
2015-06-01T15:44:43.000Z
2021-01-07T06:50:21.000Z
Engine/source/forest/ts/tsForestCellBatch.cpp
timmgt/Torque3D
ebc6c9cf3a2c7642b2cd30be3726810a302c3deb
[ "Unlicense" ]
null
null
null
Engine/source/forest/ts/tsForestCellBatch.cpp
timmgt/Torque3D
ebc6c9cf3a2c7642b2cd30be3726810a302c3deb
[ "Unlicense" ]
10
2015-01-05T15:58:31.000Z
2021-11-20T14:05:46.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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 "platform/platform.h" #include "forest/ts/tsForestCellBatch.h" #include "forest/ts/tsForestItemData.h" #include "scene/sceneManager.h" #include "ts/tsLastDetail.h" TSForestCellBatch::TSForestCellBatch( TSLastDetail *detail ) : mDetail( detail ) { } TSForestCellBatch::~TSForestCellBatch() { } bool TSForestCellBatch::_prepBatch( const ForestItem &item ) { // Make sure it's our item type! TSForestItemData* data = dynamic_cast<TSForestItemData*>( item.getData() ); if ( !data ) return false; // TODO: Eventually we should atlas multiple details into // a single combined texture map. Till then we have to // do one batch per-detail type. // If the detail type doesn't match then // we need to start a new batch. if ( data->getLastDetail() != mDetail ) return false; return true; } void TSForestCellBatch::_rebuildBatch() { // Clean up first. mVB = NULL; if ( mItems.empty() ) return; // How big do we need to make this? U32 verts = mItems.size() * 6; mVB.set( GFX, verts, GFXBufferTypeStatic ); if ( !mVB.isValid() ) { // If we failed it is probably because we requested // a size bigger than a VB can be. Warn the user. AssertWarn( false, "TSForestCellBatch::_rebuildBatch: Batch too big... try reducing the forest cell size!" ); return; } // Fill this puppy! ImposterState *vertPtr = mVB.lock(); Vector<ForestItem>::const_iterator item = mItems.begin(); const F32 radius = mDetail->getRadius(); ImposterState state; for ( ; item != mItems.end(); item++ ) { item->getWorldBox().getCenter( &state.center ); state.halfSize = radius * item->getScale(); state.alpha = 1.0f; item->getTransform().getColumn( 2, &state.upVec ); item->getTransform().getColumn( 0, &state.rightVec ); *vertPtr = state; vertPtr->corner = 0; ++vertPtr; *vertPtr = state; vertPtr->corner = 1; ++vertPtr; *vertPtr = state; vertPtr->corner = 2; ++vertPtr; *vertPtr = state; vertPtr->corner = 2; ++vertPtr; *vertPtr = state; vertPtr->corner = 3; ++vertPtr; *vertPtr = state; vertPtr->corner = 0; ++vertPtr; } mVB.unlock(); } void TSForestCellBatch::_render( const SceneRenderState *state ) { if ( !mVB.isValid() || ( state->isShadowPass() && !TSLastDetail::smCanShadow ) ) return; // Make sure we have a material to render with. BaseMatInstance *mat = state->getOverrideMaterial( mDetail->getMatInstance() ); if ( mat == NULL ) return; // We don't really render here... we submit it to // the render manager which collects all the batches // in the scene, sorts them by texture, sets up the // shader, and then renders them all at once. ImposterBatchRenderInst *inst = state->getRenderPass()->allocInst<ImposterBatchRenderInst>(); inst->mat = mat; inst->vertBuff = &mVB; // We sort by the imposter type first so that RIT_Imposter and // RIT_ImposterBatches do not get mixed together. // // We then sort by material. // inst->defaultKey = 0; inst->defaultKey2 = mat->getStateHint(); state->getRenderPass()->addInst( inst ); }
30.373333
115
0.645303
jyaskus
9d196c5aefd16eff10981d4fc13eb7160a19db1a
147
cpp
C++
Pong/src/Paddle.cpp
tbui468/pong
ff1ade4db34ac6b329ab1628e579550f4863968c
[ "MIT" ]
null
null
null
Pong/src/Paddle.cpp
tbui468/pong
ff1ade4db34ac6b329ab1628e579550f4863968c
[ "MIT" ]
null
null
null
Pong/src/Paddle.cpp
tbui468/pong
ff1ade4db34ac6b329ab1628e579550f4863968c
[ "MIT" ]
null
null
null
#include "Paddle.h" void Paddle::move(int key, unsigned int delta_time) { update_location(m_h_velocity * key, m_v_velocity * key, delta_time); }
24.5
69
0.748299
tbui468
9d19bf9f94485656e748eb749dc0a026a2342f57
1,332
cpp
C++
src/X-GSD/ComponentSprite.cpp
iPruch/X-GSD
1f0b294e27f5aee0fb0448207cd1091c9d42ae44
[ "Zlib" ]
2
2015-01-04T22:17:23.000Z
2017-04-28T14:19:56.000Z
src/X-GSD/ComponentSprite.cpp
iPruch/X-GSD
1f0b294e27f5aee0fb0448207cd1091c9d42ae44
[ "Zlib" ]
null
null
null
src/X-GSD/ComponentSprite.cpp
iPruch/X-GSD
1f0b294e27f5aee0fb0448207cd1091c9d42ae44
[ "Zlib" ]
null
null
null
#include <X-GSD/ComponentSprite.hpp> using namespace xgsd; ComponentSprite::ComponentSprite(const sf::Texture& texture) : mSprite(texture) { // Load resources here (RAII) // If this constructor is used and no texture rect is specified it will be as big as the texture } ComponentSprite::ComponentSprite(const sf::Texture& texture, sf::IntRect textureRect) : mSprite(texture) { // Load resources here (RAII) mSprite.setTextureRect(textureRect); } void ComponentSprite::draw(sf::RenderTarget& target, sf::RenderStates states) const { // Just draw the sprite on the render target target.draw(mSprite, states); } void ComponentSprite::setColor(sf::Color color) { mSprite.setColor(color); } void ComponentSprite::setTexture(sf::Texture &texture) { mSprite.setTexture(texture); } void ComponentSprite::setTextureRect(sf::IntRect textureRect) { mSprite.setTextureRect(textureRect); } sf::FloatRect ComponentSprite::getGlobalBounds() { return mSprite.getGlobalBounds(); } sf::Color ComponentSprite::getColor() { return mSprite.getColor(); } const sf::Texture& ComponentSprite::getTexture() { return *mSprite.getTexture(); } sf::IntRect ComponentSprite::getTextureRect() { return mSprite.getTextureRect(); } ComponentSprite::~ComponentSprite() { // Cleanup }
20.181818
104
0.726727
iPruch
9d23a9e6f4494c8b88e7306cdc073a67128bbefd
2,503
hpp
C++
src/managers/draw_manager.hpp
Romop5/holoinjector
db11922e6c57b4664beeec31199385a4877e1619
[ "MIT" ]
2
2021-04-12T06:09:57.000Z
2021-05-20T11:56:01.000Z
src/managers/draw_manager.hpp
Romop5/holoinjector
db11922e6c57b4664beeec31199385a4877e1619
[ "MIT" ]
null
null
null
src/managers/draw_manager.hpp
Romop5/holoinjector
db11922e6c57b4664beeec31199385a4877e1619
[ "MIT" ]
null
null
null
/***************************************************************************** * * PROJECT: HoloInjector - https://github.com/Romop5/holoinjector * LICENSE: See LICENSE in the top level directory * FILE: managers/draw_manager.hpp * *****************************************************************************/ #ifndef HI_DRAW_MANAGER_HPP #define HI_DRAW_MANAGER_HPP #include <functional> namespace hi { class Context; namespace pipeline { class PerspectiveProjectionParameters; } namespace managers { class DrawManager { public: void draw(Context& context, const std::function<void(void)>& code); void setInjectorDecodedProjection(Context& context, GLuint program, const hi::pipeline::PerspectiveProjectionParameters& projection); private: /// Decide if current draw call is dispached in suitable settings bool shouldSkipDrawCall(Context& context); /// Decide which draw methods should be used void drawGeneric(Context& context, const std::function<void(void)>& code); /// Draw without support of GS, or when shaderless fixed-pipeline is used void drawLegacy(Context& context, const std::function<void(void)>& code); /// Draw when Geometry Shader has been injected into program void drawWithGeometryShader(Context& context, const std::function<void(void)>& code); /// Draw without, just using Vertex Shader + repeating void drawWithVertexShader(Context& context, const std::function<void(void)>& code); std::string dumpDrawContext(Context& context) const; // TODO: Replace setters with separate class, devoted for intershader communication void setInjectorShift(Context& context, const glm::mat4& viewSpaceTransform, float projectionAdjust = 0.0); void resetInjectorShift(Context& context); void setInjectorIdentity(Context& context); void pushFixedPipelineProjection(Context& context, const glm::mat4& viewSpaceTransform, float projectionAdjust = 0.0); void popFixedPipelineProjection(Context& context); // Legacy OpenGL - Create single-view FBO from current FBO GLuint createSingleViewFBO(Context& contex, size_t layer); /* Context queries */ bool isSingleViewPossible(Context& context); bool isRepeatingSuitable(Context& context); void setInjectorUniforms(size_t shaderID, Context& context); }; } // namespace managers } // namespace hi #endif
37.924242
141
0.666001
Romop5
9d251642791f2f121d991d49d8b0c8a5e9a3d761
1,375
hpp
C++
hardware_interface_extensions/include/hardware_interface_extensions/sensor_state_interface.hpp
smilerobotics/ros_control_extensions
1eee21217708dcee80aa3d91b2c6415c1f4feffa
[ "MIT" ]
null
null
null
hardware_interface_extensions/include/hardware_interface_extensions/sensor_state_interface.hpp
smilerobotics/ros_control_extensions
1eee21217708dcee80aa3d91b2c6415c1f4feffa
[ "MIT" ]
null
null
null
hardware_interface_extensions/include/hardware_interface_extensions/sensor_state_interface.hpp
smilerobotics/ros_control_extensions
1eee21217708dcee80aa3d91b2c6415c1f4feffa
[ "MIT" ]
1
2021-10-14T06:37:36.000Z
2021-10-14T06:37:36.000Z
#ifndef HARDWARE_INTERFACE_EXTENSIONS_SENSOR_STATE_INTERFACE_HPP #define HARDWARE_INTERFACE_EXTENSIONS_SENSOR_STATE_INTERFACE_HPP #include <string> #include <hardware_interface/internal/hardware_resource_manager.h> #include <ros/common.h> // for ROS_ASSERT() #include <sensor_msgs/BatteryState.h> namespace hardware_interface_extensions { // // sensor state handles // template < typename DataT > class SensorStateHandle { public: typedef DataT Data; public: SensorStateHandle() : name_(), data_(NULL) {} SensorStateHandle(const std::string &name, const Data *const data) : name_(name), data_(data) {} virtual ~SensorStateHandle() {} std::string getName() const { return name_; } ros::Time getStamp() const { ROS_ASSERT(data_); return data_->header.stamp; } const Data &getData() const { ROS_ASSERT(data_); return *data_; } const Data *getDataPtr() const { return data_; } private: std::string name_; const Data *data_; }; typedef SensorStateHandle< sensor_msgs::BatteryState > BatteryStateHandle; // // sensor state interfaces // template < typename HandleT > class SensorStateInterface : public hardware_interface::HardwareResourceManager< HandleT > { public: typedef HandleT Handle; }; typedef SensorStateInterface< BatteryStateHandle > BatteryStateInterface; } // namespace hardware_interface_extensions #endif
22.177419
98
0.755636
smilerobotics
9d2d64a79f0feb23f8b0038cde54e2ddf8b476ba
520
tcc
C++
src/Arduino.tcc
lawyiu/2d-robot-simulator
864af5074a597c7505df29a5ab81aa4fe331f45c
[ "MIT" ]
1
2022-03-25T12:37:07.000Z
2022-03-25T12:37:07.000Z
src/Arduino.tcc
lawyiu/2d-robot-simulator
864af5074a597c7505df29a5ab81aa4fe331f45c
[ "MIT" ]
3
2021-09-20T20:52:03.000Z
2021-09-26T06:14:07.000Z
src/Arduino.tcc
lawyiu/2D-robot-simulator
864af5074a597c7505df29a5ab81aa4fe331f45c
[ "MIT" ]
null
null
null
template <typename T> std::string SerialPort::formatVal(T val, int type) { std::ostringstream os; switch (type) { case BIN: { std::bitset<8 * sizeof(val)> bits(val); os << bits; break; } case HEX: { os << std::hex << val; break; } case OCT: { os << std::oct << val; break; } default: { os << val; break; } } return os.str(); }
17.931034
74
0.388462
lawyiu
9d2ee29e2cdeeeb7cf4cc24a7a95dc7e7fb60797
14,264
cpp
C++
testapp/scenes/scenemanager.cpp
ColinGilbert/d-collide
8adb354d52e7ee49705ca2853d50a6a879f3cd49
[ "BSD-3-Clause" ]
6
2015-12-08T05:38:03.000Z
2021-04-09T13:45:59.000Z
testapp/scenes/scenemanager.cpp
ColinGilbert/d-collide
8adb354d52e7ee49705ca2853d50a6a879f3cd49
[ "BSD-3-Clause" ]
null
null
null
testapp/scenes/scenemanager.cpp
ColinGilbert/d-collide
8adb354d52e7ee49705ca2853d50a6a879f3cd49
[ "BSD-3-Clause" ]
null
null
null
/******************************************************************************* * Copyright (C) 2007 by the members of PG 510, University of Dortmund: * * d-collide-devel@lists.sourceforge.net * * * Andreas Beckermann, Christian Bode, Marcel Ens, Sebastian Ens, * * Martin Fassbach, Maximilian Hegele, Daniel Haus, Oliver Horst, * * Gregor Jochmann, Timo Loist, Marcel Nienhaus and Marc Schulz * * * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are met:* * - Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * - Neither the name of the PG510 nor the names of its contributors may be * * used to endorse or promote products derived from this software without * * specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE * *******************************************************************************/ #include "scenemanager.h" #include "dcollide-config_testapp.h" #include "deformable/deforming.h" #include "deformable/deformablescene.h" #include "deformable/deformablescenecollisions.h" #include "deformable/deformablescenespheres.h" #include "deformable/spherecloth.h" #include "general/collisionstopscene.h" #include "general/dcollidescene.h" #include "general/penetrationdepthscene.h" #include "general/specificationscene.h" #ifndef DCOLLIDE_BUILD_RELEASE_VERSION # include "general/devtest.h" #endif #include "physics/boxstackscene.h" #include "physics/clothbox.h" #include "physics/rotatingcloth.h" #include "physics/collisionresponse.h" #include "physics/rampscene.h" #include "physics/snookerscene.h" #include "physics/dominoday.h" #include "physics/wallscene.h" #include "physics/shakescene.h" #include "physics/marblerun.h" #include "physics/hangingclothscene.h" #include "rigid/manymovingboxes.h" #include "rigid/movingbunny.h" #include "rigid/tworigidhelicopters.h" #include "rigid/tworigidhelicoptersingrid.h" #include "benchmark/mixed.h" #include "benchmark/deformable.h" #include <d-collide/debug.h> #include <iostream> SceneManager* SceneManager::mSceneManager = 0; std::string SceneManager::mDefaultSceneId = "general"; SceneManager::SceneManager() { mSceneTitles.insert(std::make_pair("general", "General Testscene [general]")); mSceneTitles.insert(std::make_pair("surfacehierarchyply", "SurfaceHierarchy Demo (.ply model) [surfacehierarchyply]")); mSceneTitles.insert(std::make_pair("surfacehierarchycloth", "SurfaceHierarchy Demo (triangle grid) [surfacehierarchycloth]")); mSceneTitles.insert(std::make_pair("shcollisions", "SurfaceHierarchy CollisionTest [shcollisions]")); mSceneTitles.insert(std::make_pair("collisionstop", "Stop On Collision Scene [collisionstop]")); mSceneTitles.insert(std::make_pair("penetrationdepth", "Penetration depth for different shapes [penetrationdepth]")); mSceneTitles.insert(std::make_pair("copters", "Two Helicopters [copters]")); mSceneTitles.insert(std::make_pair("coptersgrid", "Two Helicopters in a grid of Boxes [coptersgrid]")); mSceneTitles.insert(std::make_pair("parallelboxes", "Moving Parallel Boxes [parallelboxes]")); mSceneTitles.insert(std::make_pair("spherecloth", "SpatialHash Demo [spherecloth]")); mSceneTitles.insert(std::make_pair("movingbunny", "Moving Bunny [movingbunny]")); mSceneTitles.insert(std::make_pair("snooker", "Physics Demo: Snooker Table [snooker]")); mSceneTitles.insert(std::make_pair("ramp", "Physics Demo: Rolling and Sliding on a Ramp [ramp]")); mSceneTitles.insert(std::make_pair("boxstack", "Physics Demo: [boxstack]")); mSceneTitles.insert(std::make_pair("response", "Physics Demo: All combinations of collisions in a physic scene [response]")); mSceneTitles.insert(std::make_pair("dominoday", "Physics Demo: Lots of fun with domino bricks [dominoday]")); mSceneTitles.insert(std::make_pair("clothbox", "Physics Demo: A cloth falling down onto a box [clothbox]")); mSceneTitles.insert(std::make_pair("rotatingcloth", "Physics Demo: A cloth falling down onto a rotating sphere [rotatingcloth]")); mSceneTitles.insert(std::make_pair("specification", "Exact specifications [specificationscene]")); mSceneTitles.insert(std::make_pair("wall", "Physics Demo: A wall of boxes and some cannonballs [wall]")); mSceneTitles.insert(std::make_pair("shake", "Physics Test: One body on two others [shake]")); mSceneTitles.insert(std::make_pair("marblerun", "Physics Demo: Marble in a maze [marblerun]")); mSceneTitles.insert(std::make_pair("hangingcloth", "Physics Demo: Cloth fixed at some points [hangingcloth]")); mSceneTitles.insert(std::make_pair("deforming", "Deforming objects [deforming]")); mSceneTitles.insert(std::make_pair("mixedbenchmark", "Benchmarking Scene (Mixed) [mixedbenchmark]")); mSceneTitles.insert(std::make_pair("deformablebenchmark", "Benchmarking Scene (Deformable) [deformablebenchmark]")); #ifndef DCOLLIDE_BUILD_RELEASE_VERSION mSceneTitles.insert(std::make_pair("devtest", "DEVELOPER SCENE [devtest]")); #endif } SceneManager::~SceneManager() { for (std::map<std::string, SceneBase*>::iterator it = mScenes.begin(); it != mScenes.end(); ++it) { delete (*it).second; } } /*! * Create the global scene manager object. This function must be called at most * once, multiple calls are not allowed (SceneManager is a singleton). */ void SceneManager::createSceneManager() { if (mSceneManager) { std::cerr << dc_funcinfo << "scenemanager already created" << std::endl; return; } mSceneManager = new SceneManager(); } /*! * \return The global SceneManager object or NULL if \ref createSceneManager was * not yet called. */ SceneManager* SceneManager::getSceneManager() { return mSceneManager; } /*! * Delete the global SceneManager object that was created by \ref * createSceneManager */ void SceneManager::deleteSceneManager() { delete mSceneManager; mSceneManager = 0; } /*! * Set the scene ID of the class that is used as "default scene", i.e. which is * created when the ID "default" is used in \ref createScene. * * This method is in particular meant to be used as a very early statment in the * main() function: you could easily create multiple test programs that are all * exactly equal (i.e. use exactly the same sources, except for main.cpp), * except for the default scene id that is used. */ void SceneManager::setDefaultSceneId(const std::string& id) { mDefaultSceneId = id; } /*! * \return The scene ID of the class that is created for the ID string * "default". See also \ref setDefaultSceneId */ const std::string& SceneManager::getDefaultSceneId() { return mDefaultSceneId; } /*! * Create a new scene as specified by \p id and returns a pointer to it. * * This class keeps ownership of the created scene and deletes it on * destruction. */ SceneBase* SceneManager::createScene(const std::string& id, Ogre::Root* root) { if (id == "default") { return createScene(getDefaultSceneId(), root); } if (mScenes.find(id) != mScenes.end()) { // no need to create a new scene, we already created one return (*mScenes.find(id)).second; } SceneBase* scene = 0; // note: also add new scenes to getAvailableSceneIds() ! if (id == "general") { scene = new DCollideScene(root); } else if (id == "surfacehierarchyply") { scene = new DeformableScene(root); } else if (id == "surfacehierarchycloth") { scene = new DeformableSceneSpheres(root); } else if (id == "shcollisions") { scene = new DeformableSceneCollisions(root); } else if (id == "collisionstop") { scene = new CollisionStopScene(root); } else if (id == "penetrationdepth") { scene = new PenetrationDepthScene(root); } else if (id == "copters") { scene = new TwoRigidHelicopters(root); } else if (id == "coptersgrid") { scene = new TwoRigidHelicoptersInGrid(root); } else if (id == "parallelboxes") { scene = new ManyMovingBoxes(root); } else if (id == "spherecloth") { scene = new SphereCloth(root); } else if (id == "movingbunny") { scene = new MovingBunny(root); } else if (id == "snooker") { scene = new SnookerScene(root); } else if (id == "ramp") { scene = new RampScene(root); } else if (id == "boxstack") { scene = new BoxstackScene(root); } else if (id == "response") { scene = new CollisionResponse(root); } else if (id == "dominoday") { scene = new DominoDay(root); } else if (id == "clothbox") { scene = new ClothBox(root); } else if (id == "rotatingcloth") { scene = new RotatingCloth(root); } else if (id == "specification") { scene = new SpecificationScene(root); } else if (id == "wall") { scene = new WallScene(root); } else if (id == "shake") { scene = new ShakeScene(root); } else if (id == "marblerun") { scene = new MarblerunScene(root); } else if (id == "deforming") { scene = new Deforming(root); } else if (id == "hangingcloth") { scene = new HangingClothScene(root); } else if (id == "mixedbenchmark") { scene = new MixedBenchmark(root); } else if (id == "deformablebenchmark") { scene = new DeformableBenchmark(root); } #ifndef DCOLLIDE_BUILD_RELEASE_VERSION else if (id == "devtest") { scene = new DevTestScene(root); } #endif if (!scene) { std::cerr << dc_funcinfo << "unknown identifier " << id << std::endl; return 0; } mScenes.insert(make_pair(id, scene)); return scene; } /*! * \brief scene titles * * these titles are displayed in the scene-chooser combobox * used format is [SceneID] short Title */ std::list<std::string> SceneManager::getAvailableSceneTitles() const { std::list<std::string> sceneTitles; for (std::map<std::string, std::string>::const_iterator iter = mSceneTitles.begin(); iter != mSceneTitles.end(); ++iter) { sceneTitles.push_back((*iter).second); } return sceneTitles; } std::list<std::string> SceneManager::getAvailableSceneIds() const { std::list<std::string> sceneIds; for (std::map<std::string, std::string>::const_iterator iter = mSceneTitles.begin(); iter != mSceneTitles.end(); ++iter) { sceneIds.push_back((*iter).first); } return sceneIds; } std::string SceneManager::getSceneTitle(const std::string& sceneId) const{ std::map<std::string, std::string>::const_iterator findIter = mSceneTitles.find(sceneId); if (findIter != mSceneTitles.end()) { return (*findIter).second; } return "n.A."; } /*! * Deletes the scene \p scene from the internal list, as well as the \p scene * object itself. */ void SceneManager::deleteScene(SceneBase* scene) { for (std::map<std::string, SceneBase*>::iterator it = mScenes.begin(); it != mScenes.end(); ++it) { if ((*it).second == scene) { delete scene; scene = 0; mScenes.erase(it); break; } } delete scene; // in case it was not in the map } /*! * \return The scene ID of a \p scene that was created using \ref createScene, * or an empty string if \p scene is not known to the SceneManager */ std::string SceneManager::getSceneId(SceneBase* scene) const { for (std::map<std::string, SceneBase*>::const_iterator it = mScenes.begin(); it != mScenes.end(); ++it) { if ((*it).second == scene) { return (*it).first; } } return ""; } /* * vim: et sw=4 ts=4 */
44.436137
161
0.609296
ColinGilbert
9d359e9a7e2c6b30b4f10d972a6ff2c0afe86528
20,386
cpp
C++
Source/ThirdParty/NewtonDynamics/include/packages/dContainers/dCRC.cpp
nigeyuk/HevEn
0dc970d6ecd0e5fd5512441562e2fdb4620214f0
[ "CC-BY-3.0" ]
15
2017-03-15T15:41:13.000Z
2022-01-11T01:15:12.000Z
Source/ThirdParty/NewtonDynamics/include/packages/dContainers/dCRC.cpp
nigeyuk/HevEn
0dc970d6ecd0e5fd5512441562e2fdb4620214f0
[ "CC-BY-3.0" ]
null
null
null
Source/ThirdParty/NewtonDynamics/include/packages/dContainers/dCRC.cpp
nigeyuk/HevEn
0dc970d6ecd0e5fd5512441562e2fdb4620214f0
[ "CC-BY-3.0" ]
3
2017-03-17T12:28:48.000Z
2020-03-19T19:32:02.000Z
/* Copyright (c) <2003-2016> <Newton Game Dynamics> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely */ #include "dContainersStdAfx.h" #include "dCRC.h" /* static dCRCTYPE randBits0[] = { 7266447313870364031ULL, 4946485549665804864ULL, 16945909448695747420ULL, 16394063075524226720ULL, 4873882236456199058ULL, 14877448043947020171ULL, 6740343660852211943ULL, 13857871200353263164ULL, 5249110015610582907ULL, 10205081126064480383ULL, 1235879089597390050ULL, 17320312680810499042ULL, 16489141110565194782ULL, 8942268601720066061ULL, 13520575722002588570ULL, 14226945236717732373ULL, 9383926873555417063ULL, 15690281668532552105ULL, 11510704754157191257ULL, 15864264574919463609ULL, 6489677788245343319ULL, 5112602299894754389ULL, 10828930062652518694ULL, 15942305434158995996ULL, 15445717675088218264ULL, 4764500002345775851ULL, 14673753115101942098ULL, 236502320419669032ULL, 13670483975188204088ULL, 14931360615268175698ULL, 8904234204977263924ULL, 12836915408046564963ULL, 12120302420213647524ULL, 15755110976537356441ULL, 5405758943702519480ULL, 10951858968426898805ULL, 17251681303478610375ULL, 4144140664012008120ULL, 18286145806977825275ULL, 13075804672185204371ULL, 10831805955733617705ULL, 6172975950399619139ULL, 12837097014497293886ULL, 12903857913610213846ULL, 560691676108914154ULL, 1074659097419704618ULL, 14266121283820281686ULL, 11696403736022963346ULL, 13383246710985227247ULL, 7132746073714321322ULL, 10608108217231874211ULL, 9027884570906061560ULL, 12893913769120703138ULL, 15675160838921962454ULL, 2511068401785704737ULL, 14483183001716371453ULL, 3774730664208216065ULL, 5083371700846102796ULL, 9583498264570933637ULL, 17119870085051257224ULL, 5217910858257235075ULL, 10612176809475689857ULL, 1924700483125896976ULL, 7171619684536160599ULL, 10949279256701751503ULL, 15596196964072664893ULL, 14097948002655599357ULL, 615821766635933047ULL, 5636498760852923045ULL, 17618792803942051220ULL, 580805356741162327ULL, 425267967796817241ULL, 8381470634608387938ULL, 13212228678420887626ULL, 16993060308636741960ULL, 957923366004347591ULL, 6210242862396777185ULL, 1012818702180800310ULL, 15299383925974515757ULL, 17501832009465945633ULL, 17453794942891241229ULL, 15807805462076484491ULL, 8407189590930420827ULL, 974125122787311712ULL, 1861591264068118966ULL, 997568339582634050ULL, 18046771844467391493ULL, 17981867688435687790ULL, 3809841506498447207ULL, 9460108917638135678ULL, 16172980638639374310ULL, 958022432077424298ULL, 4393365126459778813ULL, 13408683141069553686ULL, 13900005529547645957ULL, 15773550354402817866ULL, 16475327524349230602ULL, 6260298154874769264ULL, 12224576659776460914ULL, 6405294864092763507ULL, 7585484664713203306ULL, 5187641382818981381ULL, 12435998400285353380ULL, 13554353441017344755ULL, 646091557254529188ULL, 11393747116974949255ULL, 16797249248413342857ULL, 15713519023537495495ULL, 12823504709579858843ULL, 4738086532119935073ULL, 4429068783387643752ULL, 585582692562183870ULL, 1048280754023674130ULL, 6788940719869959076ULL, 11670856244972073775ULL, 2488756775360218862ULL, 2061695363573180185ULL, 6884655301895085032ULL, 3566345954323888697ULL, 12784319933059041817ULL, 4772468691551857254ULL, 6864898938209826895ULL, 7198730565322227090ULL, 2452224231472687253ULL, 13424792606032445807ULL, 10827695224855383989ULL, 11016608897122070904ULL, 14683280565151378358ULL, 7077866519618824360ULL, 17487079941198422333ULL, 3956319990205097495ULL, 5804870313319323478ULL, 8017203611194497730ULL, 3310931575584983808ULL, 5009341981771541845ULL, 11772020174577005930ULL, 3537640779967351792ULL, 6801855569284252424ULL, 17687268231192623388ULL, 12968358613633237218ULL, 1429775571144180123ULL, 10427377732172208413ULL, 12155566091986788996ULL, 16465954421598296115ULL, 12710429690464359999ULL, 9547226351541565595ULL, 12156624891403410342ULL, 2985938688676214686ULL, 18066917785985010959ULL, 5975570403614438776ULL, 11541343163022500560ULL, 11115388652389704592ULL, 9499328389494710074ULL, 9247163036769651820ULL, 3688303938005101774ULL, 2210483654336887556ULL, 15458161910089693228ULL, 6558785204455557683ULL, 1288373156735958118ULL, 18433986059948829624ULL, 3435082195390932486ULL, 16822351800343061990ULL, 3120532877336962310ULL, 16681785111062885568ULL, 7835551710041302304ULL, 2612798015018627203ULL, 15083279177152657491ULL, 6591467229462292195ULL, 10592706450534565444ULL, 7438147750787157163ULL, 323186165595851698ULL, 7444710627467609883ULL, 8473714411329896576ULL, 2782675857700189492ULL, 3383567662400128329ULL, 3200233909833521327ULL, 12897601280285604448ULL, 3612068790453735040ULL, 8324209243736219497ULL, 15789570356497723463ULL, 1083312926512215996ULL, 4797349136059339390ULL, 5556729349871544986ULL, 18266943104929747076ULL, 1620389818516182276ULL, 172225355691600141ULL, 3034352936522087096ULL, 1266779576738385285ULL, 3906668377244742888ULL, 6961783143042492788ULL, 17159706887321247572ULL, 4676208075243319061ULL, 10315634697142985816ULL, 13435140047933251189ULL, 716076639492622016ULL, 13847954035438697558ULL, 7195811275139178570ULL, 10815312636510328870ULL, 6214164734784158515ULL, 16412194511839921544ULL, 3862249798930641332ULL, 1005482699535576005ULL, 4644542796609371301ULL, 17600091057367987283ULL, 4209958422564632034ULL, 5419285945389823940ULL, 11453701547564354601ULL, 9951588026679380114ULL, 7425168333159839689ULL, 8436306210125134906ULL, 11216615872596820107ULL, 3681345096403933680ULL, 5770016989916553752ULL, 11102855936150871733ULL, 11187980892339693935ULL, 396336430216428875ULL, 6384853777489155236ULL, 7551613839184151117ULL, 16527062023276943109ULL, 13429850429024956898ULL, 9901753960477271766ULL, 9731501992702612259ULL, 5217575797614661659ULL, 10311708346636548706ULL, 15111747519735330483ULL, 4353415295139137513ULL, 1845293119018433391ULL, 11952006873430493561ULL, 3531972641585683893ULL, 16852246477648409827ULL, 15956854822143321380ULL, 12314609993579474774ULL, 16763911684844598963ULL, 16392145690385382634ULL, 1545507136970403756ULL, 17771199061862790062ULL, 12121348462972638971ULL, 12613068545148305776ULL, 954203144844315208ULL, 1257976447679270605ULL, 3664184785462160180ULL, 2747964788443845091ULL, 15895917007470512307ULL, 15552935765724302120ULL, 16366915862261682626ULL, 8385468783684865323ULL, 10745343827145102946ULL, 2485742734157099909ULL, 916246281077683950ULL, 15214206653637466707ULL, 12895483149474345798ULL, 1079510114301747843ULL, 10718876134480663664ULL, 1259990987526807294ULL, 8326303777037206221ULL, 14104661172014248293ULL, }; */ static dCRCTYPE randBits0[] = { static_cast<long long>(7266447313870364031ULL), static_cast<long long>(4946485549665804864ULL), static_cast<long long>(16945909448695747420ULL), static_cast<long long>(16394063075524226720ULL), static_cast<long long>(4873882236456199058ULL), static_cast<long long>(14877448043947020171ULL), static_cast<long long>(6740343660852211943ULL), static_cast<long long>(13857871200353263164ULL), static_cast<long long>(5249110015610582907ULL), static_cast<long long>(10205081126064480383ULL), static_cast<long long>(1235879089597390050ULL), static_cast<long long>(17320312680810499042ULL), static_cast<long long>(16489141110565194782ULL), static_cast<long long>(8942268601720066061ULL), static_cast<long long>(13520575722002588570ULL), static_cast<long long>(14226945236717732373ULL), static_cast<long long>(9383926873555417063ULL), static_cast<long long>(15690281668532552105ULL), static_cast<long long>(11510704754157191257ULL), static_cast<long long>(15864264574919463609ULL), static_cast<long long>(6489677788245343319ULL), static_cast<long long>(5112602299894754389ULL), static_cast<long long>(10828930062652518694ULL), static_cast<long long>(15942305434158995996ULL), static_cast<long long>(15445717675088218264ULL), static_cast<long long>(4764500002345775851ULL), static_cast<long long>(14673753115101942098ULL), static_cast<long long>(236502320419669032ULL), static_cast<long long>(13670483975188204088ULL), static_cast<long long>(14931360615268175698ULL), static_cast<long long>(8904234204977263924ULL), static_cast<long long>(12836915408046564963ULL), static_cast<long long>(12120302420213647524ULL), static_cast<long long>(15755110976537356441ULL), static_cast<long long>(5405758943702519480ULL), static_cast<long long>(10951858968426898805ULL), static_cast<long long>(17251681303478610375ULL), static_cast<long long>(4144140664012008120ULL), static_cast<long long>(18286145806977825275ULL), static_cast<long long>(13075804672185204371ULL), static_cast<long long>(10831805955733617705ULL), static_cast<long long>(6172975950399619139ULL), static_cast<long long>(12837097014497293886ULL), static_cast<long long>(12903857913610213846ULL), static_cast<long long>(560691676108914154ULL), static_cast<long long>(1074659097419704618ULL), static_cast<long long>(14266121283820281686ULL), static_cast<long long>(11696403736022963346ULL), static_cast<long long>(13383246710985227247ULL), static_cast<long long>(7132746073714321322ULL), static_cast<long long>(10608108217231874211ULL), static_cast<long long>(9027884570906061560ULL), static_cast<long long>(12893913769120703138ULL), static_cast<long long>(15675160838921962454ULL), static_cast<long long>(2511068401785704737ULL), static_cast<long long>(14483183001716371453ULL), static_cast<long long>(3774730664208216065ULL), static_cast<long long>(5083371700846102796ULL), static_cast<long long>(9583498264570933637ULL), static_cast<long long>(17119870085051257224ULL), static_cast<long long>(5217910858257235075ULL), static_cast<long long>(10612176809475689857ULL), static_cast<long long>(1924700483125896976ULL), static_cast<long long>(7171619684536160599ULL), static_cast<long long>(10949279256701751503ULL), static_cast<long long>(15596196964072664893ULL), static_cast<long long>(14097948002655599357ULL), static_cast<long long>(615821766635933047ULL), static_cast<long long>(5636498760852923045ULL), static_cast<long long>(17618792803942051220ULL), static_cast<long long>(580805356741162327ULL), static_cast<long long>(425267967796817241ULL), static_cast<long long>(8381470634608387938ULL), static_cast<long long>(13212228678420887626ULL), static_cast<long long>(16993060308636741960ULL), static_cast<long long>(957923366004347591ULL), static_cast<long long>(6210242862396777185ULL), static_cast<long long>(1012818702180800310ULL), static_cast<long long>(15299383925974515757ULL), static_cast<long long>(17501832009465945633ULL), static_cast<long long>(17453794942891241229ULL), static_cast<long long>(15807805462076484491ULL), static_cast<long long>(8407189590930420827ULL), static_cast<long long>(974125122787311712ULL), static_cast<long long>(1861591264068118966ULL), static_cast<long long>(997568339582634050ULL), static_cast<long long>(18046771844467391493ULL), static_cast<long long>(17981867688435687790ULL), static_cast<long long>(3809841506498447207ULL), static_cast<long long>(9460108917638135678ULL), static_cast<long long>(16172980638639374310ULL), static_cast<long long>(958022432077424298ULL), static_cast<long long>(4393365126459778813ULL), static_cast<long long>(13408683141069553686ULL), static_cast<long long>(13900005529547645957ULL), static_cast<long long>(15773550354402817866ULL), static_cast<long long>(16475327524349230602ULL), static_cast<long long>(6260298154874769264ULL), static_cast<long long>(12224576659776460914ULL), static_cast<long long>(6405294864092763507ULL), static_cast<long long>(7585484664713203306ULL), static_cast<long long>(5187641382818981381ULL), static_cast<long long>(12435998400285353380ULL), static_cast<long long>(13554353441017344755ULL), static_cast<long long>(646091557254529188ULL), static_cast<long long>(11393747116974949255ULL), static_cast<long long>(16797249248413342857ULL), static_cast<long long>(15713519023537495495ULL), static_cast<long long>(12823504709579858843ULL), static_cast<long long>(4738086532119935073ULL), static_cast<long long>(4429068783387643752ULL), static_cast<long long>(585582692562183870ULL), static_cast<long long>(1048280754023674130ULL), static_cast<long long>(6788940719869959076ULL), static_cast<long long>(11670856244972073775ULL), static_cast<long long>(2488756775360218862ULL), static_cast<long long>(2061695363573180185ULL), static_cast<long long>(6884655301895085032ULL), static_cast<long long>(3566345954323888697ULL), static_cast<long long>(12784319933059041817ULL), static_cast<long long>(4772468691551857254ULL), static_cast<long long>(6864898938209826895ULL), static_cast<long long>(7198730565322227090ULL), static_cast<long long>(2452224231472687253ULL), static_cast<long long>(13424792606032445807ULL), static_cast<long long>(10827695224855383989ULL), static_cast<long long>(11016608897122070904ULL), static_cast<long long>(14683280565151378358ULL), static_cast<long long>(7077866519618824360ULL), static_cast<long long>(17487079941198422333ULL), static_cast<long long>(3956319990205097495ULL), static_cast<long long>(5804870313319323478ULL), static_cast<long long>(8017203611194497730ULL), static_cast<long long>(3310931575584983808ULL), static_cast<long long>(5009341981771541845ULL), static_cast<long long>(11772020174577005930ULL), static_cast<long long>(3537640779967351792ULL), static_cast<long long>(6801855569284252424ULL), static_cast<long long>(17687268231192623388ULL), static_cast<long long>(12968358613633237218ULL), static_cast<long long>(1429775571144180123ULL), static_cast<long long>(10427377732172208413ULL), static_cast<long long>(12155566091986788996ULL), static_cast<long long>(16465954421598296115ULL), static_cast<long long>(12710429690464359999ULL), static_cast<long long>(9547226351541565595ULL), static_cast<long long>(12156624891403410342ULL), static_cast<long long>(2985938688676214686ULL), static_cast<long long>(18066917785985010959ULL), static_cast<long long>(5975570403614438776ULL), static_cast<long long>(11541343163022500560ULL), static_cast<long long>(11115388652389704592ULL), static_cast<long long>(9499328389494710074ULL), static_cast<long long>(9247163036769651820ULL), static_cast<long long>(3688303938005101774ULL), static_cast<long long>(2210483654336887556ULL), static_cast<long long>(15458161910089693228ULL), static_cast<long long>(6558785204455557683ULL), static_cast<long long>(1288373156735958118ULL), static_cast<long long>(18433986059948829624ULL), static_cast<long long>(3435082195390932486ULL), static_cast<long long>(16822351800343061990ULL), static_cast<long long>(3120532877336962310ULL), static_cast<long long>(16681785111062885568ULL), static_cast<long long>(7835551710041302304ULL), static_cast<long long>(2612798015018627203ULL), static_cast<long long>(15083279177152657491ULL), static_cast<long long>(6591467229462292195ULL), static_cast<long long>(10592706450534565444ULL), static_cast<long long>(7438147750787157163ULL), static_cast<long long>(323186165595851698ULL), static_cast<long long>(7444710627467609883ULL), static_cast<long long>(8473714411329896576ULL), static_cast<long long>(2782675857700189492ULL), static_cast<long long>(3383567662400128329ULL), static_cast<long long>(3200233909833521327ULL), static_cast<long long>(12897601280285604448ULL), static_cast<long long>(3612068790453735040ULL), static_cast<long long>(8324209243736219497ULL), static_cast<long long>(15789570356497723463ULL), static_cast<long long>(1083312926512215996ULL), static_cast<long long>(4797349136059339390ULL), static_cast<long long>(5556729349871544986ULL), static_cast<long long>(18266943104929747076ULL), static_cast<long long>(1620389818516182276ULL), static_cast<long long>(172225355691600141ULL), static_cast<long long>(3034352936522087096ULL), static_cast<long long>(1266779576738385285ULL), static_cast<long long>(3906668377244742888ULL), static_cast<long long>(6961783143042492788ULL), static_cast<long long>(17159706887321247572ULL), static_cast<long long>(4676208075243319061ULL), static_cast<long long>(10315634697142985816ULL), static_cast<long long>(13435140047933251189ULL), static_cast<long long>(716076639492622016ULL), static_cast<long long>(13847954035438697558ULL), static_cast<long long>(7195811275139178570ULL), static_cast<long long>(10815312636510328870ULL), static_cast<long long>(6214164734784158515ULL), static_cast<long long>(16412194511839921544ULL), static_cast<long long>(3862249798930641332ULL), static_cast<long long>(1005482699535576005ULL), static_cast<long long>(4644542796609371301ULL), static_cast<long long>(17600091057367987283ULL), static_cast<long long>(4209958422564632034ULL), static_cast<long long>(5419285945389823940ULL), static_cast<long long>(11453701547564354601ULL), static_cast<long long>(9951588026679380114ULL), static_cast<long long>(7425168333159839689ULL), static_cast<long long>(8436306210125134906ULL), static_cast<long long>(11216615872596820107ULL), static_cast<long long>(3681345096403933680ULL), static_cast<long long>(5770016989916553752ULL), static_cast<long long>(11102855936150871733ULL), static_cast<long long>(11187980892339693935ULL), static_cast<long long>(396336430216428875ULL), static_cast<long long>(6384853777489155236ULL), static_cast<long long>(7551613839184151117ULL), static_cast<long long>(16527062023276943109ULL), static_cast<long long>(13429850429024956898ULL), static_cast<long long>(9901753960477271766ULL), static_cast<long long>(9731501992702612259ULL), static_cast<long long>(5217575797614661659ULL), static_cast<long long>(10311708346636548706ULL), static_cast<long long>(15111747519735330483ULL), static_cast<long long>(4353415295139137513ULL), static_cast<long long>(1845293119018433391ULL), static_cast<long long>(11952006873430493561ULL), static_cast<long long>(3531972641585683893ULL), static_cast<long long>(16852246477648409827ULL), static_cast<long long>(15956854822143321380ULL), static_cast<long long>(12314609993579474774ULL), static_cast<long long>(16763911684844598963ULL), static_cast<long long>(16392145690385382634ULL), static_cast<long long>(1545507136970403756ULL), static_cast<long long>(17771199061862790062ULL), static_cast<long long>(12121348462972638971ULL), static_cast<long long>(12613068545148305776ULL), static_cast<long long>(954203144844315208ULL), static_cast<long long>(1257976447679270605ULL), static_cast<long long>(3664184785462160180ULL), static_cast<long long>(2747964788443845091ULL), static_cast<long long>(15895917007470512307ULL), static_cast<long long>(15552935765724302120ULL), static_cast<long long>(16366915862261682626ULL), static_cast<long long>(8385468783684865323ULL), static_cast<long long>(10745343827145102946ULL), static_cast<long long>(2485742734157099909ULL), static_cast<long long>(916246281077683950ULL), static_cast<long long>(15214206653637466707ULL), static_cast<long long>(12895483149474345798ULL), static_cast<long long>(1079510114301747843ULL), static_cast<long long>(10718876134480663664ULL), static_cast<long long>(1259990987526807294ULL), static_cast<long long>(8326303777037206221ULL), static_cast<long long>(14104661172014248293ULL), }; dCRCTYPE dCombineCRC (dCRCTYPE a, dCRCTYPE b) { return (a << 8) ^ b; } // calculate a 32 bit crc of a string dCRCTYPE dCRC64 (const char* const name, dCRCTYPE crcAcc) { if (name) { const int bitshift = (sizeof (dCRCTYPE)<<3) - 8; for (int i = 0; name[i]; i ++) { char c = name[i]; dCRCTYPE val = randBits0[((crcAcc >> bitshift) ^ c) & 0xff]; crcAcc = (crcAcc << 8) ^ val; } } return crcAcc; } dCRCTYPE dCRC64 (const void* const buffer, int size, dCRCTYPE crcAcc) { const unsigned char* const ptr = (unsigned char*)buffer; const int bitshift = (sizeof (dCRCTYPE)<<3) - 8; for (int i = 0; i < size; i ++) { char c = ptr[i]; dCRCTYPE val = randBits0[((crcAcc >> bitshift) ^ c) & 0xff]; crcAcc = (crcAcc << 8) ^ val; } return crcAcc; }
92.663636
199
0.842882
nigeyuk
9d37efdd720fdf2095dc30e105835c774a216a57
2,592
cpp
C++
source/GUI/GUIButton.cpp
badbrainz/pme
1c8e6f3d154cc59613f5ef3f2f8293f488c64b28
[ "WTFPL" ]
null
null
null
source/GUI/GUIButton.cpp
badbrainz/pme
1c8e6f3d154cc59613f5ef3f2f8293f488c64b28
[ "WTFPL" ]
null
null
null
source/GUI/GUIButton.cpp
badbrainz/pme
1c8e6f3d154cc59613f5ef3f2f8293f488c64b28
[ "WTFPL" ]
null
null
null
#include "GUIButton.h" #include "GUIAlphaElement.h" #include "GUIClippedRectangle.h" #include "../Tools/Logger.h" GUIButton::GUIButton(const char *cbs) : GUIAlphaElement(cbs), GUIClippedRectangle() { setBordersColor(0.0f, 0.0f, 0.0f); setDimensions(40, 22); setPosition(0.5, 0.5); setColor(100, 150, 190); widgetType = BUTTON; drawBackground = true; drawBounds = true; bounce = true; } bool GUIButton::loadXMLSettings(XMLElement *element) { if (!element || element->getName() != "Button") return Logger::writeErrorLog("Need a Button node in the xml file"); XMLElement *child = NULL; if (child = element->getChildByName("bounce")) enableBounce((child->getValue() == "true")); return GUIAlphaElement::loadXMLSettings(element) && GUIClippedRectangle::loadXMLClippedRectangleInfo(element); } void GUIButton::enableBounce(bool bounce_) { bounce = bounce_; } bool GUIButton::bounceEnabled() { return bounce; } void GUIButton::render(float clockTick) { if (!parent || !visible) return; modifyCurrentAlpha(clockTick); bgColor = color; Tuple3f tempColor = label.getColor(); float displacement = 2.0f*(pressed || clicked)*bounce; int xCenter = (windowBounds.x + windowBounds.z)/2, yCenter = (windowBounds.y + windowBounds.w)/2; glTranslatef(displacement, displacement, 0.0); renderClippedBounds(); label.printCenteredXY(xCenter, yCenter); glTranslatef(-displacement, -displacement, 0.0f); } const void GUIButton::computeWindowBounds() { if (parent && update) { GUIRectangle::computeWindowBounds(); label.computeDimensions(); int width = windowBounds.z - windowBounds.x, height = windowBounds.w - windowBounds.y; if (width <= label.getWidth() + 2*clipSize) { if (anchor == CENTER) { width = (label.getWidth() - width)/2 + clipSize + 2; windowBounds.x -=width; windowBounds.z +=width; } if ((anchor == CORNERLU) || (anchor == CORNERLD)) { width = (label.getWidth() - width)/2 + clipSize + 2; windowBounds.z +=2*width; } } if (height + 2*clipSize < label.getHeight()) { height = (label.getHeight() - height)/2 + clipSize + 2; windowBounds.y -= height; windowBounds.w += height; } computeClippedBounds(windowBounds); } }
26.44898
84
0.59375
badbrainz
9d39f3f0190f081772a317fb4aa185c5196469bb
3,669
cpp
C++
src/packet.cpp
caseycs/pinba2
931a820e12cbc41fd5c19e87bdbfd9811c7a969b
[ "BSD-3-Clause" ]
108
2018-11-02T08:41:11.000Z
2022-02-17T22:27:23.000Z
src/packet.cpp
caseycs/pinba2
931a820e12cbc41fd5c19e87bdbfd9811c7a969b
[ "BSD-3-Clause" ]
19
2018-11-02T06:54:37.000Z
2021-09-02T15:45:40.000Z
src/packet.cpp
caseycs/pinba2
931a820e12cbc41fd5c19e87bdbfd9811c7a969b
[ "BSD-3-Clause" ]
17
2018-11-08T14:14:31.000Z
2021-12-16T15:57:38.000Z
#include <cmath> #include "pinba/globals.h" #include "pinba/limits.h" #include "pinba/dictionary.h" #include "pinba/packet.h" #include "pinba/bloom.h" #include "proto/pinba.pb-c.h" //////////////////////////////////////////////////////////////////////////////////////////////// request_validate_result_t pinba_validate_request(Pinba__Request *r) { if (r->status >= PINBA_INTERNAL___STATUS_MAX) return request_validate_result::status_is_too_large; if (r->n_timer_value != r->n_timer_hit_count) // all timers have hit counts return request_validate_result::bad_hit_count; if (r->n_timer_value != r->n_timer_tag_count) // all timers have tag counts return request_validate_result::bad_tag_count; // NOTE(antoxa): some clients don't send rusage at all, let them // if (r->n_timer_value != r->n_timer_ru_utime) // return request_validate_result::bad_timer_ru_utime_count; // if (r->n_timer_value != r->n_timer_ru_stime) // return request_validate_result::bad_timer_ru_stime_count; // all timer hit counts are > 0 for (unsigned i = 0; i < r->n_timer_hit_count; i++) { if (r->timer_hit_count[i] <= 0) return request_validate_result::bad_timer_hit_count; } auto const total_tag_count = [&]() { size_t result = 0; for (unsigned i = 0; i < r->n_timer_tag_count; i++) { result += r->timer_tag_count[i]; } return result; }(); if (total_tag_count != r->n_timer_tag_name) // all tags have names return request_validate_result::not_enough_tag_names; if (total_tag_count != r->n_timer_tag_value) // all tags have values return request_validate_result::not_enough_tag_values; // request_time should be > 0, reset to 0 when < 0 { switch (std::fpclassify(r->request_time)) { case FP_ZERO: break; case FP_NORMAL: break; default: return request_validate_result::bad_float_request_time; } if (std::signbit(r->request_time)) r->request_time = 0; } // NOTE(antoxa): this should not happen, but happens A LOT // so just reset them to zero if negative { switch (std::fpclassify(r->ru_utime)) { case FP_ZERO: break; case FP_NORMAL: break; default: return request_validate_result::bad_float_ru_utime; } if (std::signbit(r->ru_utime)) r->ru_utime = 0; } { switch (std::fpclassify(r->ru_stime)) { case FP_ZERO: break; case FP_NORMAL: break; default: return request_validate_result::bad_float_ru_stime; } if (std::signbit(r->ru_stime)) r->ru_stime = 0; } // timer values must be >= 0 for (unsigned i = 0; i < r->n_timer_value; i++) { switch (std::fpclassify(r->timer_value[i])) { case FP_ZERO: break; case FP_NORMAL: break; default: return request_validate_result::bad_float_timer_value; } if (std::signbit(r->timer_value[i])) return request_validate_result::negative_float_timer_value; } // NOTE(antoxa): same as r->ru_utime, r->ru_stime // negative values happen, just make them zero for (unsigned i = 0; i < r->n_timer_ru_utime; i++) { switch (std::fpclassify(r->timer_ru_utime[i])) { case FP_ZERO: break; case FP_NORMAL: break; default: return request_validate_result::bad_float_timer_ru_utime; } if (std::signbit(r->timer_ru_utime[i])) r->timer_ru_utime[i] = 0; } for (unsigned i = 0; i < r->n_timer_ru_stime; i++) { switch (std::fpclassify(r->timer_ru_stime[i])) { case FP_ZERO: break; case FP_NORMAL: break; default: return request_validate_result::bad_float_timer_ru_stime; } if (std::signbit(r->timer_ru_stime[i])) r->timer_ru_stime[i] = 0; } return request_validate_result::okay; }
27.795455
96
0.668029
caseycs
9d3c414ae86ce3ada2ef92da5938d299d3d93a6e
1,218
cpp
C++
example.cpp
LTU-CEG/libserialpipe
0000e0466581b68c4674ac87cc358f27f430c872
[ "BSL-1.0" ]
null
null
null
example.cpp
LTU-CEG/libserialpipe
0000e0466581b68c4674ac87cc358f27f430c872
[ "BSL-1.0" ]
null
null
null
example.cpp
LTU-CEG/libserialpipe
0000e0466581b68c4674ac87cc358f27f430c872
[ "BSL-1.0" ]
null
null
null
// Copyright Emil Fresk 2015-2017. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <iostream> #include "serialpipe.hpp" using namespace std; void test(const std::vector<uint8_t> &data); int main() { /* Create serial pipe */ serialpipe::bridge sp("/dev/ttyUSB0", 57600, 10, true); /* serialpipe usage: * * serialpipe("port", * baudrate, * timeout (in ms), (optional, 1000 default) * string data (true / false) (optional, true default) * string termination); (optional, "\n" default) */ /* Register a callback */ sp.registerCallback(test); /* Open the serial port */ sp.openPort(); /* Transmit some data... */ sp.serialTransmit("test test test"); cin.get(); /* Close port */ sp.closePort(); return 0; } /* Print incoming data... */ void test(const std::vector<uint8_t> &data) { cout << "Data received: "; for (const uint8_t &ch : data) { cout << static_cast<char>( ch ); } cout << endl; }
21.75
72
0.560755
LTU-CEG
9d3ce8ce3c664643eac9a0d1abe018b8d79c7184
2,787
cpp
C++
TerrainApps/VTBuilder/PrefDlg.cpp
nakijun/vtp
7bd2b2abd3a3f778a32ba30be099cfba9b892922
[ "MIT" ]
4
2019-02-08T13:51:26.000Z
2021-12-07T13:11:06.000Z
TerrainApps/VTBuilder/PrefDlg.cpp
nakijun/vtp
7bd2b2abd3a3f778a32ba30be099cfba9b892922
[ "MIT" ]
null
null
null
TerrainApps/VTBuilder/PrefDlg.cpp
nakijun/vtp
7bd2b2abd3a3f778a32ba30be099cfba9b892922
[ "MIT" ]
7
2017-12-03T10:13:17.000Z
2022-03-29T09:51:18.000Z
// // Name: PrefDlg.cpp // // Copyright (c) 2007-2011 Virtual Terrain Project // Free for all uses, see license.txt for details. // // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #include "PrefDlg.h" #include "vtui/AutoDialog.h" // WDR: class implementations //---------------------------------------------------------------------------- // PrefDlg //---------------------------------------------------------------------------- // WDR: event table for PrefDlg BEGIN_EVENT_TABLE(PrefDlg, PrefDlgBase) EVT_INIT_DIALOG (PrefDlg::OnInitDialog) EVT_BUTTON( wxID_OK, PrefDlg::OnOK ) EVT_RADIOBUTTON( ID_RADIO1, PrefDlg::OnRadio ) EVT_RADIOBUTTON( ID_RADIO2, PrefDlg::OnRadio ) EVT_RADIOBUTTON( ID_RADIO3, PrefDlg::OnRadio ) EVT_RADIOBUTTON( ID_RADIO4, PrefDlg::OnRadio ) EVT_RADIOBUTTON( ID_RADIO5, PrefDlg::OnRadio ) EVT_RADIOBUTTON( ID_RADIO6, PrefDlg::OnRadio ) EVT_RADIOBUTTON( ID_RADIO7, PrefDlg::OnRadio ) EVT_RADIOBUTTON( ID_RADIO8, PrefDlg::OnRadio ) EVT_RADIOBUTTON( ID_RADIO9, PrefDlg::OnRadio ) EVT_RADIOBUTTON( ID_RADIO10, PrefDlg::OnRadio ) EVT_RADIOBUTTON( ID_RADIO11, PrefDlg::OnRadio ) EVT_CHECKBOX( ID_BLACK_TRANSP, PrefDlg::OnCheck ) EVT_CHECKBOX( ID_DEFLATE_TIFF, PrefDlg::OnCheck ) EVT_CHECKBOX( ID_DELAY_LOAD, PrefDlg::OnCheck ) END_EVENT_TABLE() PrefDlg::PrefDlg( wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style ) : PrefDlgBase( parent, id, title, position, size, style ) { AddValidator(this, ID_RADIO1, &b1); AddValidator(this, ID_RADIO2, &b2); AddValidator(this, ID_RADIO3, &b3); AddValidator(this, ID_RADIO4, &b4); AddValidator(this, ID_RADIO5, &b5); AddValidator(this, ID_RADIO6, &b6); AddValidator(this, ID_RADIO7, &b7); AddValidator(this, ID_RADIO8, &b8); AddValidator(this, ID_RADIO9, &b9); AddValidator(this, ID_RADIO10, &b10); AddValidator(this, ID_RADIO11, &b11); AddValidator(this, ID_BLACK_TRANSP, &b12); AddValidator(this, ID_DEFLATE_TIFF, &b13); AddValidator(this, ID_BT_GZIP, &b14); AddValidator(this, ID_DELAY_LOAD, &b15); AddNumValidator(this, ID_SAMPLING_N, &i1); AddNumValidator(this, ID_MAX_MEGAPIXELS, &i2); AddNumValidator(this, ID_ELEV_MAX_SIZE, &i3); AddNumValidator(this, ID_MAX_MEM_GRID, &i4); GetSizer()->SetSizeHints(this); } void PrefDlg::UpdateEnable() { FindWindow(ID_MAX_MEM_GRID)->Enable(b15); } // WDR: handler implementations for PrefDlg void PrefDlg::OnInitDialog(wxInitDialogEvent& event) { UpdateEnable(); } void PrefDlg::OnRadio( wxCommandEvent &event ) { TransferDataFromWindow(); } void PrefDlg::OnCheck( wxCommandEvent &event ) { TransferDataFromWindow(); UpdateEnable(); } void PrefDlg::OnOK( wxCommandEvent &event ) { TransferDataFromWindow(); event.Skip(); }
28.438776
78
0.712235
nakijun
9d46b3015fe4635e409aad8a16c738eebad683ba
1,222
cpp
C++
Effective Debugging: 66 Specific Ways to Debug Software and Systems/src/jenkins/JobButton.cpp
juliagoda/BookProjects
d2c2da993cc9fcbfead696b78d3bf98c66e3373c
[ "Unlicense" ]
null
null
null
Effective Debugging: 66 Specific Ways to Debug Software and Systems/src/jenkins/JobButton.cpp
juliagoda/BookProjects
d2c2da993cc9fcbfead696b78d3bf98c66e3373c
[ "Unlicense" ]
null
null
null
Effective Debugging: 66 Specific Ways to Debug Software and Systems/src/jenkins/JobButton.cpp
juliagoda/BookProjects
d2c2da993cc9fcbfead696b78d3bf98c66e3373c
[ "Unlicense" ]
null
null
null
#include "JobButton.h" #include <JenkinsJobInfo.h> #include <QLabel> #include <QIcon> #include <QHBoxLayout> #include <QMouseEvent> namespace Jenkins { JobButton::JobButton(const JenkinsJobInfo &job, QWidget *parent) : QFrame(parent) , mJob(job) { mJob.name.replace("%2F", "/"); mJob.color.remove("_anime"); if (mJob.color.contains("blue")) mJob.color = "green"; else if (mJob.color.contains("disabled") || mJob.color.contains("grey") || mJob.color.contains("notbuilt")) mJob.color = "grey"; else if (mJob.color.contains("aborted")) mJob.color = "dark_grey"; const auto icon = new QLabel(); icon->setPixmap(QIcon(QString(":/icons/%1").arg(mJob.color)).pixmap(22, 22)); const auto layout = new QHBoxLayout(this); layout->setContentsMargins(QMargins()); layout->setSpacing(20); layout->addWidget(icon); layout->addWidget(new QLabel(mJob.name)); layout->addStretch(); } void JobButton::mousePressEvent(QMouseEvent *e) { mPressed = rect().contains(e->pos()) && e->button() == Qt::LeftButton; } void JobButton::mouseReleaseEvent(QMouseEvent *e) { if (mPressed && rect().contains(e->pos()) && e->button() == Qt::LeftButton) emit clicked(); } }
24.938776
110
0.660393
juliagoda
9d4d418618a3f1156c0efca5b457aa54f5fcc3b0
556
cpp
C++
tests/unique_ptr_custom.cpp
IvayloTsankov/mempool
f34e7e3d3a51a09f4be6a961ab6fbf1f71d1edf5
[ "MIT" ]
null
null
null
tests/unique_ptr_custom.cpp
IvayloTsankov/mempool
f34e7e3d3a51a09f4be6a961ab6fbf1f71d1edf5
[ "MIT" ]
null
null
null
tests/unique_ptr_custom.cpp
IvayloTsankov/mempool
f34e7e3d3a51a09f4be6a961ab6fbf1f71d1edf5
[ "MIT" ]
null
null
null
#include <memory> #include <utility> #include <functional> struct Vector { float x, y, z; }; struct Del { void del(Vector*) { printf("Call Del::del\n"); } }; int main() { { std::unique_ptr<Vector, std::function<void(Vector*)>> v(new Vector{ 1, 1, 1 }, [](Vector* p) { printf("custom deleter called\n"); }); } { Del d; std::unique_ptr<Vector, std::function<void(Vector*)>> v(new Vector{ 2, 2, 2 }, std::bind(&Del::del, d, std::placeholders::_1)); } return 0; }
17.375
86
0.523381
IvayloTsankov
9d5cbaa7701c94ef7fc554b9526d20b8543f16f6
1,113
cpp
C++
ExodusImport/Source/ExodusImport/Private/JsonObjects/JsonRigidbody.cpp
AldeRoberge/ProjectExodus
74ecd6c8719e6365b51458c65954bff2910bc36e
[ "BSD-3-Clause" ]
288
2019-04-02T08:02:59.000Z
2022-03-28T23:53:28.000Z
ExodusImport/Source/ExodusImport/Private/JsonObjects/JsonRigidbody.cpp
adamgoodrich/ProjectExodus
29a9fa87f981ad41e3b323702dc2b0d4523889d8
[ "BSD-3-Clause" ]
54
2019-04-19T08:24:05.000Z
2022-03-28T19:44:42.000Z
ExodusImport/Source/ExodusImport/Private/JsonObjects/JsonRigidbody.cpp
adamgoodrich/ProjectExodus
29a9fa87f981ad41e3b323702dc2b0d4523889d8
[ "BSD-3-Clause" ]
56
2019-04-07T03:55:39.000Z
2022-03-20T04:54:57.000Z
#include "JsonImportPrivatePCH.h" #include "JsonRigidbody.h" #include "macros.h" using namespace JsonObjects; JsonRigidbody::JsonRigidbody(JsonObjPtr data){ load(data); } void JsonRigidbody::load(JsonObjPtr data){ /*I should probably get rid of those helper macros due to reduced error checking...*/ JSON_GET_VAR(data, angularDrag); JSON_GET_VAR(data, angularVelocity); JSON_GET_VAR(data, centerOfMass); JSON_GET_VAR(data, collisionDetectionMode); JSON_GET_VAR(data, constraints); JSON_GET_VAR(data, detectCollisions); JSON_GET_VAR(data, drag); JSON_GET_VAR(data, freezeRotation); JSON_GET_VAR(data, inertiaTensor); JSON_GET_VAR(data, interpolation); JSON_GET_VAR(data, isKinematic); JSON_GET_VAR(data, mass); JSON_GET_VAR(data, maxAngularVelocity); JSON_GET_VAR(data, maxDepenetrationVelocity); JSON_GET_VAR(data, position); JSON_GET_VAR(data, rotation); JSON_GET_VAR(data, sleepThreshold); JSON_GET_VAR(data, solverIterations); JSON_GET_VAR(data, solverVelocityIterations); JSON_GET_VAR(data, useGravity); JSON_GET_VAR(data, velocity); JSON_GET_VAR(data, worldCenterOfMass); }
25.883721
86
0.791554
AldeRoberge
9d5d30f769acc3c23f87e5c9875d59f3b69ce15f
17,404
cpp
C++
nau/src/nau/material/material.cpp
Khirion/nau
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
[ "MIT" ]
29
2015-09-16T22:28:30.000Z
2022-03-11T02:57:36.000Z
nau/src/nau/material/material.cpp
Khirion/nau
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
[ "MIT" ]
1
2017-03-29T13:32:58.000Z
2017-03-31T13:56:03.000Z
nau/src/nau/material/material.cpp
Khirion/nau
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
[ "MIT" ]
10
2015-10-15T14:20:15.000Z
2022-02-17T10:37:29.000Z
#include "nau/material/material.h" #include "nau.h" #include "nau/slogger.h" #include "nau/debug/profile.h" #include "nau/material/uniformBlockManager.h" using namespace nau::material; using namespace nau::render; using namespace nau::resource; Material::Material() : m_Color (), //m_Texmat (0), m_Shader (NULL), m_ProgramValues(), m_UniformValues(), m_Enabled (true), m_Name ("__Default"), m_State(NULL) { } Material::~Material() { while (!m_ImageTextures.empty()) { delete((*m_ImageTextures.begin()).second); m_ImageTextures.erase(m_ImageTextures.begin()); } while (!m_Textures.empty()) { delete((*m_Textures.begin()).second); m_Textures.erase(m_Textures.begin()); } while (!m_Buffers.empty()) { delete((*m_Buffers.begin()).second); m_Buffers.erase(m_Buffers.begin()); } } std::shared_ptr<Material> Material::clone() { // check clone Program Values Material *mat; mat = new Material(); mat->setName(m_Name); mat->m_Enabled = m_Enabled; mat->m_Shader = m_Shader; mat->m_ProgramValues = m_ProgramValues; mat->m_ProgramBlockValues = m_ProgramBlockValues; mat->m_Color = m_Color; mat->m_Buffers = m_Buffers; mat->m_Textures = m_Textures; for (auto &it : m_ImageTextures) { mat->attachImageTexture(it.second->getLabel(), it.second->getPropi(IImageTexture::UNIT), it.second->getPropui(IImageTexture::TEX_ID)); } for (auto &it : m_Textures) { mat->attachTexture(it.first, it.second->getTexture()); } mat->m_State = m_State; mat->m_ArrayOfTextures = m_ArrayOfTextures; //mat->m_ArrayOfImageTextures = new MaterialArrayOfTextures(m_ArrayOfImageTextures); return std::shared_ptr<Material>(mat); } bool Material::isShaderLinked() { return(m_Shader->isLinked()); } std::map<std::string, nau::material::ProgramValue>& Material::getProgramValues() { return m_ProgramValues; } std::map<std::string, nau::material::ProgramValue>& Material::getUniformValues() { return m_UniformValues; } std::map<std::pair<std::string, std::string>, nau::material::ProgramBlockValue>& Material::getProgramBlockValues() { return m_ProgramBlockValues; } void Material::setName (std::string name) { m_Name = name; } std::string& Material::getName () { return m_Name; } void Material::getValidProgramValueNames(std::vector<std::string> *names) { // valid program value names are program values that are not part of the uniforms map // this is because there may be a program value specified in the project file whose type // does not match the shader variable type std::map<std::string,ProgramValue>::iterator progValIter; progValIter = m_ProgramValues.begin(); for (; progValIter != m_ProgramValues.end(); progValIter++) { if (m_UniformValues.count(progValIter->first) == 0) names->push_back(progValIter->first); } } void Material::getUniformNames(std::vector<std::string> *names) { std::map<std::string,ProgramValue>::iterator progValIter; progValIter = m_UniformValues.begin(); for (; progValIter != m_UniformValues.end(); progValIter++) { names->push_back(progValIter->first); } } ProgramValue * Material::getProgramValue(std::string name) { if (m_ProgramValues.count(name) > 0) return &m_ProgramValues[name]; else return NULL; } void Material::getTextureNames(std::vector<std::string> *vs) { for (auto t : m_Textures) { vs->push_back(t.second->getTexture()->getLabel()); } } void Material::getTextureUnits(std::vector<unsigned int> *vi) { for (auto t : m_Textures) { vi->push_back(t.second->getPropi(MaterialTexture::UNIT)); } } void Material::setUniformValues() { { // explicit block for profiler PROFILE_GL("Set Uniforms"); std::map<std::string, ProgramValue>::iterator progValIter; progValIter = m_ProgramValues.begin(); for (; progValIter != m_ProgramValues.end(); ++progValIter) { void *v = progValIter->second.getValues(); m_Shader->setValueOfUniform(progValIter->first, v); } } int x = 3; } void Material::setUniformBlockValues() { { // explicit block for profiler PROFILE_GL("Set Blocks"); std::set<std::string> blocks; for (auto pbv : m_ProgramBlockValues) { void *v = pbv.second.getValues(); const std::string &block = pbv.first.first; std::string uniform = pbv.first.second; IUniformBlock *b = UNIFORMBLOCKMANAGER->getBlock(block); if (b) { b->setUniform(uniform, v); blocks.insert(block); } } m_Shader->prepareBlocks(); } } #include <algorithm> void Material::checkProgramValuesAndUniforms(std::string &result) { int loc; IUniform iu; std::string s,aux; std::vector<std::string> names, otherNames; m_Shader->getAttributeNames(&names); for (auto n : names) { if (VertexData::GetAttribIndex(n) == VertexData::MaxAttribs) { aux = "Material " + m_Name + ": attribute " + n + " - not valid"; result += aux + "\n"; SLOG("Material %s: attribute %s - not valid", m_Name.c_str(), n.c_str()); } } names.clear(); m_Shader->getUniformBlockNames(&names); // check if uniforms defined in the project are active in the shader std::string aName; for (auto bi : m_ProgramBlockValues) { aName = bi.first.first; if (std::any_of(names.begin(), names.end(), [aName](std::string i) {return i == aName; })) { IUniformBlock *b = UNIFORMBLOCKMANAGER->getBlock(aName); otherNames.clear(); b->getUniformNames(&otherNames); std::string uniName = bi.first.second; if (!std::any_of(otherNames.begin(), otherNames.end(), [uniName](std::string i) {return i == uniName; })) { aux = "Material " + m_Name + ": block: " + bi.first.first + " uniform: " + uniName + " - not active in shader"; result += aux + "\n"; SLOG("Material %s: block %s: uniform %s not active in shader", m_Name.c_str(), bi.first.first.c_str(), uniName.c_str()); } } else { SLOG("Material %s: block %s is not active in shader", m_Name.c_str(), bi.first.first.c_str()); aux = "Material " + m_Name + ": block: " + bi.first.first + " - not active in shader"; result += aux + "\n"; } } // check if uniforms used in the shader are defined in the project // for each block for (auto name : names) { IUniformBlock *b = UNIFORMBLOCKMANAGER->getBlock(name); otherNames.clear(); b->getUniformNames(&otherNames); // for each uniform in the block for (auto uni : otherNames) { if (uni.find(".") == std::string::npos && !std::any_of(m_ProgramBlockValues.begin(), m_ProgramBlockValues.end(), [&](std::pair<std::pair<std::string , std::string >, ProgramBlockValue> k) {return k.first == std::pair<std::string, std::string>(name, uni); })) { SLOG("Material %s: block %s: uniform %s is not defined in the material", m_Name.c_str(), name.c_str(), uni.c_str()); aux = "Material " + m_Name + ": shader block: " + name + " uniform: " + uni + " - not defined in the material"; result += aux + "\n"; } } } // get the location of the ProgramValue in the shader // loc == -1 means that ProgramValue is not an active uniform std::map<std::string, ProgramValue>::iterator progValIter; progValIter = m_ProgramValues.begin(); for (; progValIter != m_ProgramValues.end(); ++progValIter) { loc = m_Shader->getUniformLocation(progValIter->first); progValIter->second.setLoc(loc); if (loc == -1) { SLOG("Material %s: material uniform %s is not active in shader %s", m_Name.c_str(), progValIter->first.c_str(), m_Shader->getName().c_str()); aux = "Material: " + m_Name + " uniform: " + progValIter->first + " - not active in shader " + m_Shader->getName(); result += aux + "\n"; } } int k = m_Shader->getNumberOfUniforms(); for (int i = 0; i < k; ++i) { iu = m_Shader->getIUniform(i); s = iu.getName(); if (m_ProgramValues.count(s) == 0) { SLOG("Material %s: shader uniform %s from shader %s is not defined", m_Name.c_str(), s.c_str(), m_Shader->getName().c_str()); aux = "Material: " + m_Name + " shader : " + m_Shader->getName() + " + shader uniform: " + s + " - not defined in material"; result += aux + "\n"; } else if (! Enums::isCompatible(m_ProgramValues[s].getValueType(), iu.getSimpleType())) { aux = "Material: " + m_Name + " uniform: " + s + " - types are not compatible(" + iu.getStringSimpleType() + "," + Enums::DataTypeToString[m_ProgramValues[s].getValueType()] + ")"; result += aux + "\n"; SLOG("Material %s: uniform %s types are not compatiple (%s, %s)", m_Name.c_str(), s.c_str(), iu.getStringSimpleType().c_str(), Enums::DataTypeToString[m_ProgramValues[s].getValueType()].c_str()); } } } void Material::prepareNoShaders () { RENDERER->setState (getState()); m_Color.prepare(); for (auto t : m_Textures) t.second->bind(); if (APISupport->apiSupport(IAPISupport::APIFeatureSupport::IMAGE_TEXTURE)) { for (auto it : m_ImageTextures) it.second->prepare(); } for (auto b : m_Buffers) { b.second->bind(); } } void Material::prepare () { { PROFILE("Buffers"); for (auto &b : m_Buffers) { b.second->bind(); } } { PROFILE("State"); RENDERER->setState (getState()); } { PROFILE("Color"); m_Color.prepare(); } { PROFILE("Texture"); for (auto &t : m_Textures) { t.second->bind(); } } { PROFILE("Image Textures"); if (APISupport->apiSupport(IAPISupport::APIFeatureSupport::IMAGE_TEXTURE)) { for (auto &it : m_ImageTextures) it.second->prepare(); } } if (m_ArrayOfTextures.size()) { PROFILE("Array Of Textures"); for (auto &at : m_ArrayOfTextures) at.bind(); } if (m_ArrayOfImageTextures.size()) { PROFILE("Array Of Image Textures"); for (auto at : m_ArrayOfImageTextures) at->bind(); } { PROFILE("Shaders"); if (NULL != m_Shader) { bool prepared = m_Shader->prepare(); RENDERER->setShader(m_Shader); if (prepared) { setUniformValues(); setUniformBlockValues(); } } else RENDERER->setShader(NULL); } } void Material::restore() { //m_Color.restore(); //if (NULL != m_Shader && m_useShader) { // m_Shader->restore(); //} if (m_Shader) m_Shader->restore(); RENDERER->resetTextures(m_Textures); //for (auto t : m_Textures) // t.second->unbind(); for (auto b : m_Buffers) b.second->unbind(); if (APISupport->apiSupport(IAPISupport::APIFeatureSupport::IMAGE_TEXTURE)) { for (auto &b : m_ImageTextures) b.second->restore(); } for (auto &b: m_ArrayOfTextures) b.unbind(); } void Material::restoreNoShaders() { m_Color.restore(); for (auto t : m_Textures) t.second->unbind(); for (auto b : m_Buffers) b.second->unbind(); if (APISupport->apiSupport(IAPISupport::APIFeatureSupport::IMAGE_TEXTURE)) { for (auto b : m_ImageTextures) b.second->restore(); } } void Material::addArrayOfTextures(IArrayOfTextures *at, int unit) { size_t k = m_ArrayOfTextures.size(); m_ArrayOfTextures.resize(k+1); m_ArrayOfTextures[k].setArrayOfTextures(at); m_ArrayOfTextures[k].setPropi(MaterialArrayOfTextures::FIRST_UNIT, unit); // m_ArrayOfTextures.setArrayOfTextures(at); // m_ArrayOfTextures.setPropi(MaterialArrayOfTextures::FIRST_UNIT, unit); } MaterialArrayOfTextures * Material::getMaterialArrayOfTextures(int k) { if (k < m_ArrayOfTextures.size()) return &m_ArrayOfTextures[k]; else return NULL; }; void Material::addArrayOfImageTextures(MaterialArrayOfImageTextures *m) { m_ArrayOfImageTextures.push_back(m); } MaterialArrayOfImageTextures * Material::getArrayOfImageTextures(int id) { if (id < m_ArrayOfImageTextures.size()) return m_ArrayOfImageTextures[id]; else return NULL; } void Material::setState(IState *s) { m_State = s; } void Material::attachImageTexture(std::string label, unsigned int unit, unsigned int texID) { assert(APISupport->apiSupport(IAPISupport::APIFeatureSupport::IMAGE_TEXTURE) && "No image texture support"); IImageTexture *it = IImageTexture::Create(label, unit, texID); m_ImageTextures[unit] = it; } IImageTexture * Material::getImageTexture(unsigned int unit) { if (m_ImageTextures.count(unit)) return m_ImageTextures[unit]; else return NULL; } void Material::getImageTextureUnits(std::vector<unsigned int> *v) { for (auto i : m_ImageTextures) { v->push_back(i.first); } } void Material::getTextureIDs(std::vector<unsigned int>* v) { for (auto i : m_Textures) { v->push_back(i.second->getTexture()->getPropi(ITexture::ID)); } } void Material::attachBuffer(IMaterialBuffer *b) { int bp = b->getPropi(IMaterialBuffer::BINDING_POINT); m_Buffers[bp] = b; } IMaterialBuffer * Material::getMaterialBuffer(int id) { if (m_Buffers.count(id)) return m_Buffers[id]; else return NULL; } IBuffer * Material::getBuffer(int id) { if (m_Buffers.count(id)) return m_Buffers[id]->getBuffer(); else return NULL; } bool Material::hasBuffer(int id) { return 0 != m_Buffers.count(id); } void Material::getBufferBindings(std::vector<unsigned int> *vi) { for (auto t : m_Buffers) { vi->push_back(t.second->getPropi(IMaterialBuffer::BINDING_POINT)); } } bool Material::createTexture (int unit, std::string fn) { ITexture *tex = RESOURCEMANAGER->addTexture (fn); if (tex) { MaterialTexture *t = new MaterialTexture(unit); t->setTexture(tex); // t->setSampler(ITextureSampler::create(tex)); m_Textures[unit] = t; return(true); } else { SLOG("Texture not found: %s", fn.c_str()); return(false); } } void Material::unsetTexture(int unit) { m_Textures.erase(unit); } void Material::attachTexture (int unit, ITexture *tex) { MaterialTexture *t = new MaterialTexture(unit); t->setTexture(tex); // t->setSampler(ITextureSampler::create(tex)); m_Textures[unit] = t; } void Material::attachTexture (int unit, std::string label) { ITexture *tex = RESOURCEMANAGER->getTexture (label); assert(tex != NULL); MaterialTexture *t = new MaterialTexture(unit); t->setTexture(tex); // t->setSampler(ITextureSampler::create(tex)); m_Textures[unit] = t; } ITexture* Material::getTexture(int unit) { if (m_Textures.count(unit)) return m_Textures[unit]->getTexture() ; else return(NULL); } ITextureSampler* Material::getTextureSampler(unsigned int unit) { if (m_Textures.count(unit)) return m_Textures[unit]->getSampler(); else return(NULL); } MaterialTexture * Material::getMaterialTexture(int unit) { if (m_Textures.count(unit)) return m_Textures[unit]; else return(NULL); } void Material::attachProgram (std::string shaderName) { m_Shader = RESOURCEMANAGER->getProgram(shaderName); //m_ProgramValues.clear(); } void Material::cloneProgramFromMaterial(std::shared_ptr<Material> &mat) { m_Shader = mat->getProgram(); m_ProgramValues.clear(); m_ProgramBlockValues.clear(); m_UniformValues.clear(); std::map<std::string, nau::material::ProgramValue>::iterator iter; iter = mat->m_ProgramValues.begin(); for( ; iter != mat->m_ProgramValues.end(); ++iter) { m_ProgramValues[(*iter).first] = (*iter).second; } for (auto pbv : mat->m_ProgramBlockValues) { m_ProgramBlockValues[pbv.first] = pbv.second; } iter = mat->m_UniformValues.begin(); for( ; iter != mat->m_UniformValues.end(); ++iter) { m_UniformValues[(*iter).first] = (*iter).second; } } std::string Material::getProgramName() { if (m_Shader) return m_Shader->getName(); else return ""; } IProgram * Material::getProgram() { return m_Shader; } void Material::setValueOfUniform(std::string name, void *values) { if (m_ProgramValues.count(name)) m_ProgramValues[name].setValueOfUniform(values); } void Material::clearProgramValues() { m_ProgramValues.clear(); } void Material::addProgramValue (std::string name, nau::material::ProgramValue progVal) { // if specified in the material lib, add it to the program values if (progVal.isInSpecML()) m_ProgramValues[name] = progVal; else { // if the name is not part of m_ProgramValues or if it is but the type does not match if (m_ProgramValues.count(name) == 0 || !Enums::isCompatible(m_ProgramValues[name].getValueType(),progVal.getValueType())) { // if there is already a uniform with the same name, and a different type remove it if (m_UniformValues.count(name) || m_UniformValues[name].getValueType() != progVal.getValueType()) { m_UniformValues.erase(name); } // add it to the uniform values m_UniformValues[name] = progVal; } } } void Material::addProgramBlockValue (std::string block, std::string name, nau::material::ProgramBlockValue progVal) { m_ProgramBlockValues[std::pair<std::string, std::string>(block,name)] = progVal; } IState* Material::getState (void) { if (m_State == NULL) { m_State = RESOURCEMANAGER->createState(m_Name); } return m_State; } ColorMaterial& Material::getColor (void) { return m_Color; } //nau::material::TextureMat* //Material::getTextures (void) { // // return m_Texmat; //} //void //Material::clear() { // // m_Color.clear(); // m_Buffers.clear(); // m_Textures.clear(); // // m_ImageTextures.clear(); // // m_Shader = NULL; // m_ProgramValues.clear(); // m_Enabled = true; // //m_State->clear(); // m_State->setDefault(); // m_Name = "Default"; //} void Material::enable (void) { m_Enabled = true; } void Material::disable (void) { m_Enabled = false; } bool Material::isEnabled (void) { return m_Enabled; }
20.843114
127
0.675822
Khirion
9d5d32b2050f8f812e161fc6bbf624c6ea44dd9d
1,969
cpp
C++
src/core/correlationmatrix.cpp
mfayk/KINC
0f6565ce8e1102392382e4c716c128115b611f0c
[ "MIT" ]
10
2018-08-15T13:27:35.000Z
2020-12-10T17:20:40.000Z
src/core/correlationmatrix.cpp
mfayk/KINC
0f6565ce8e1102392382e4c716c128115b611f0c
[ "MIT" ]
182
2016-07-31T07:15:15.000Z
2022-01-30T01:25:41.000Z
src/core/correlationmatrix.cpp
mfayk/KINC
0f6565ce8e1102392382e4c716c128115b611f0c
[ "MIT" ]
7
2017-10-12T22:03:42.000Z
2020-02-26T00:01:18.000Z
#include "correlationmatrix.h" #include "correlationmatrix_model.h" #include "correlationmatrix_pair.h" /*! * Return a qt table model that represents this data object as a table. */ QAbstractTableModel* CorrelationMatrix::model() { EDEBUG_FUNC(this); if ( !_model ) { _model = new Model(this); } return _model; } /*! * Initialize this correlation matrix with a list of gene names, the max cluster * size, and a correlation name. * * @param geneNames * @param maxClusterSize * @param correlationName */ void CorrelationMatrix::initialize(const EMetaArray& geneNames, int maxClusterSize, const QString& correlationName) { EDEBUG_FUNC(this,&geneNames,maxClusterSize,&correlationName); // save correlation names to metadata EMetaObject metaObject {meta().toObject()}; metaObject.insert("correlation", correlationName); setMeta(metaObject); // initialize base class Matrix::initialize(geneNames, maxClusterSize, sizeof(float), SUBHEADER_SIZE); } /*! * Return the correlation name for this correlation matrix. */ QString CorrelationMatrix::correlationName() const { EDEBUG_FUNC(this); return meta().toObject().at("correlation").toString(); } /*! * Return a list of correlation pairs in raw form. */ std::vector<CorrelationMatrix::RawPair> CorrelationMatrix::dumpRawData() const { EDEBUG_FUNC(this); // create list of raw pairs std::vector<RawPair> pairs; pairs.reserve(size()); // iterate through all pairs Pair pair(this); while ( pair.hasNext() ) { // read in next pair pair.readNext(); // copy pair to raw list RawPair rawPair; rawPair.index = pair.index(); rawPair.correlations.resize(pair.clusterSize()); for ( int k = 0; k < pair.clusterSize(); ++k ) { rawPair.correlations[k] = pair.at(k); } pairs.push_back(rawPair); } return pairs; }
21.402174
115
0.663281
mfayk
9d5d48871ba785a309b1d82c63ed1dba6eda71a1
698
hpp
C++
src/camera.hpp
VeganPower/potato3d
4f0bacbd883f42be7c1acdf1f700045325512da2
[ "MIT" ]
null
null
null
src/camera.hpp
VeganPower/potato3d
4f0bacbd883f42be7c1acdf1f700045325512da2
[ "MIT" ]
1
2018-03-29T10:56:25.000Z
2018-03-29T11:00:57.000Z
src/camera.hpp
VeganPower/potato3d
4f0bacbd883f42be7c1acdf1f700045325512da2
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include "transformation.hpp" namespace potato { class Camera { public: typedef std::shared_ptr<Camera> ptr; Camera(); void transformation(Transformation const& p); Transformation const& transformation() const; f32 tan_half_fov() const; private: Transformation t_; f32 fov_; f32 tan_half_fov_; }; inline Camera::Camera() : t_(Transformation::identity) , fov_(90.f) , tan_half_fov_(tan(fov_/2.f)) { } inline Transformation const& Camera::transformation() const { return t_; } inline void Camera::transformation(Transformation const& p) { t_ = p; } inline f32 Camera::tan_half_fov() const { return tan_half_fov_; } }
14.541667
59
0.700573
VeganPower
9d66aba8e3c327d02da94421a58bb54b6bcaced1
285
cpp
C++
src/13000/13241.cpp
upple/BOJ
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
[ "MIT" ]
8
2018-04-12T15:54:09.000Z
2020-06-05T07:41:15.000Z
src/13000/13241.cpp
upple/BOJ
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
[ "MIT" ]
null
null
null
src/13000/13241.cpp
upple/BOJ
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
[ "MIT" ]
null
null
null
#include <cstdio> #include <algorithm> typedef long long ll; ll gcd(ll a, ll b) { if (a < b) std::swap(a, b); while (a) { ll tmp = b % a; b = a; a = tmp; } return b; } int main() { ll a, b, m; scanf("%lld %lld", &a, &b); m = gcd(a, b); printf("%lld", (a / m)*b); }
10.961538
28
0.487719
upple
9d6a0d980860b3cc519658461272b44e3ee633a5
814
hpp
C++
Gpx/Gpx/Window/GlfwWindow.hpp
DexterDreeeam/DxtSdk2021
2dd8807b4ebe1d65221095191eaa7938bc5e9e78
[ "MIT" ]
1
2021-11-18T03:57:54.000Z
2021-11-18T03:57:54.000Z
Gpx/Gpx/Window/GlfwWindow.hpp
DexterDreeeam/P9
2dd8807b4ebe1d65221095191eaa7938bc5e9e78
[ "MIT" ]
null
null
null
Gpx/Gpx/Window/GlfwWindow.hpp
DexterDreeeam/P9
2dd8807b4ebe1d65221095191eaa7938bc5e9e78
[ "MIT" ]
null
null
null
#pragma once #define GLFW_INCLUDE_VULKAN #include "../../External/Vulkan/Windows/Header/glfw3.h" #include "../Runtime/Interface.hpp" namespace gpx { class runtime; class glfw_window : public window { friend class vulkan_runtime; public: glfw_window(const window_desc& desc, obs<runtime> rt); virtual ~glfw_window() override; public: virtual string name() override; virtual boole start() override; virtual boole stop() override; // virtual boole present(s64 my_image) override; virtual boole poll_event() override; virtual boole is_running() override; private: static mutex _glfw_op_lock; static s64 _window_number; window_desc _desc; obs<runtime> _rt; GLFWwindow* _ctx; VkSurfaceKHR _surface; }; }
17.695652
58
0.673219
DexterDreeeam
9d6d802cee9fc387ad1a03df17cbb4fddc34eda4
5,713
hpp
C++
include/polynomial/polynomial.hpp
adityakadoo/CPPMatrixLib
de577017fcbbd3d7e960c71853b1fde65ec53dbb
[ "MIT" ]
null
null
null
include/polynomial/polynomial.hpp
adityakadoo/CPPMatrixLib
de577017fcbbd3d7e960c71853b1fde65ec53dbb
[ "MIT" ]
null
null
null
include/polynomial/polynomial.hpp
adityakadoo/CPPMatrixLib
de577017fcbbd3d7e960c71853b1fde65ec53dbb
[ "MIT" ]
null
null
null
#ifndef _POLYNOMIAL_H_ #define _POLYNOMIAL_H_ #include "../matrix/matrix.hpp" #include "../matrix/matrix_utility.hpp" template<typename T> class polynomial { public: // constructor with memory allocation polynomial(size_t d,T x=0) : D(d) { P.resize(d+1, 1, x); } // default constructor polynomial() : D(-1) {} // constructor from initializer list polynomial(const std::initializer_list<T> p) { D = p.size()-1; P.resize(D+1, 1); auto k = p.begin(); for(size_t i=0;i<D+1;i++) { P(i,0)+= *k; k++; } } // check if empty bool empty() const { return D == -1; } // access degree size_t degree() const { return D; } // resize polynomial void resize(size_t d,T x=0) { D = d; P.resize(d+1, 1, x); } // Algebraic Operations: // 1 polynomial(p), 1 scalar(a): -p, p*a, a*p // 2 polynomial(p, q): p+q, p-q, p*q, p==q, p!=q polynomial operator-() const { return polynomial(D) - *this; } polynomial operator*=(const T &rhs) { P *= rhs; return *this; } polynomial operator*(const T &rhs) const { return polynomial(*this) *= rhs; } friend polynomial<T> operator*(const T &lhs,const polynomial<T> &rhs) { return rhs * lhs; } polynomial operator+=(const polynomial &rhs) { if(D<rhs.D) { matrix<T> temp(rhs.D+1,1); for(size_t i=0;i<D+1;i++) { temp(i,0)+= P(i,0); } D=rhs.D; P.resize(D+1,1); P+=temp; } for(size_t i=0;i<rhs.D+1;i++) { P(i,0)+= rhs[i]; } return *this; } polynomial operator+(const polynomial &rhs) const { return polynomial(*this) += rhs; } polynomial operator-=(const polynomial &rhs) { if(D<rhs.D) { matrix<T> temp(rhs.D+1,1); for(size_t i=0;i<D+1;i++) { temp(i,0)+= P(i,0); } D=rhs.D; P.resize(D+1,1); P+=temp; } for(size_t i=0;i<rhs.D+1;i++) { P(i,0)-= rhs[i]; } return *this; } polynomial operator-(const polynomial &rhs) const { return polynomial(*this) -= rhs; } polynomial operator*(const polynomial &rhs) const { polynomial res(D+rhs.D); for(size_t i=0;i<D+1;i++) { for(size_t j=0;j<rhs.D+1;j++) { res[i+j] += P(i,0)*rhs[j]; } } return res; } polynomial operator*=(const polynomial &rhs) { (*this) = (*this)*rhs; return *this; } bool equality_floating_point(const polynomial &rhs) const { if( D<rhs.D ) { for(size_t i=D+1;i<=rhs.D;i++) { if( rhs[i]!=0 ) { return false; } } } else if( rhs.D<D ) { for(size_t i=rhs.D+1;i<=D;i++) { if( P(i,0)!=0 ) { return false; } } } double sum = 0; size_t min_deg = D<rhs.D ? D : rhs.D; for(size_t i=0;i<=min_deg;i++) { sum += (P(i,0) - rhs[i]) * (P(i,0) - rhs[i]); } sum /= min_deg+1; return sum < _MN_ERR; } bool equality_integral(const polynomial &rhs) const { if( D<rhs.D ) { for(size_t i=D+1;i<=rhs.D;i++) { if( rhs[i]!=0 ) { return false; } } } else if( rhs.D<D ) { for(size_t i=rhs.D+1;i<=D;i++) { if( P(i,0)!=0 ) { return false; } } } size_t min_deg = D<rhs.D ? D : rhs.D; for(size_t i=0;i<=min_deg;i++) { if( P(i,0)!=rhs[i] ) { return false; } } return true; } bool operator==(const polynomial &rhs) const { if (empty() || rhs.empty()) { return false; } if(std::is_floating_point<T>::value) { return this->equality_floating_point(rhs); } return this->equality_integral(rhs); } bool operator!=(const polynomial &rhs) const { return !((*this)==rhs); } // Element Numbering is based on power T& operator[](size_t i) { assert(0 <= i && i <= D); return P(i,0); } T operator[](size_t i) const { assert(0 <= i && i <= D); return P(i,0); } //Calculating value for given parameter T calculate(const T x) { assert(!empty()); T res=0; T fac=1; for(size_t i=0;i<=D;i++) { res += fac * P(i,0); fac *= x; } return res; } //First order derivative polynomial derivative() { assert(!empty()); if(D==0) { return polynomial(0); } matrix<T> derv_op(D,D+1); for(size_t i=0;i<D;i++) { derv_op(i,i+1)= i+1; } matrix<T> prod(derv_op*P); polynomial<T> res(D-1); for(size_t i=0;i<D;i++) { res[i]=prod[i]; } return res; } // Display polynomial friend std::ostream& operator<<(std::ostream &cout, polynomial<T> p) { size_t d = p.degree(); for(size_t i=0;i<d;i++) { cout<<"("<<p[i]<<")x^"<<i<<"+"; } if( !p.empty() ) { cout<<"("<<p[d]<<")x^"<<d; } return cout; } private: size_t D; matrix<T> P; }; #endif
25.057018
75
0.437598
adityakadoo
9d6dc6ab2d7223a691e31895c2ed17549977a850
864
cpp
C++
Chapter 05: Complete Search/Part1 : Generating Subsets/generatingsubsets_method2.cpp
pulkit1joshi/handbook_codes
4ddbd5eb53807cf93f8bae910e732e58af46d842
[ "MIT" ]
18
2020-11-26T02:26:33.000Z
2022-03-24T02:36:22.000Z
Chapter 05: Complete Search/Part1 : Generating Subsets/generatingsubsets_method2.cpp
abdullah-azab/handbook_codes
4ddbd5eb53807cf93f8bae910e732e58af46d842
[ "MIT" ]
1
2021-03-02T07:52:48.000Z
2021-03-02T07:52:48.000Z
Chapter 05: Complete Search/Part1 : Generating Subsets/generatingsubsets_method2.cpp
abdullah-azab/handbook_codes
4ddbd5eb53807cf93f8bae910e732e58af46d842
[ "MIT" ]
2
2020-11-26T02:26:35.000Z
2021-11-26T11:19:09.000Z
#include <bits/stdc++.h> using namespace std; /* Generating Subsets : Method 2 You are given a set of numbers : {0 , 1 , 2 , 3 , 4} You have to find all the subsets of this set. */ int n; int A[100]; void search() { // 1 << n means 2^n i.e this number of combinations are possible // Now 2^n will take n bits 101001... n // Each xth bit represets the presence of xth number in A[i] for(int i=0;i< (1<<n);i++) { for(int j=0;j<n;j++) { // 1<<j means setting jth bit as 1 and checking if it is set in i using && if((1<<j)&i) { cout << A[j] << " "; } } cout << endl; } } int main() { // The number of elements cin >> n; // Input the elements for(int i=0;i<n;i++) { cin >> A[i]; } search(); return 0; }
19.636364
86
0.493056
pulkit1joshi
9d6de54959618449bbb8c995ef787f1cbe1daa81
681
cpp
C++
owGameMap/Sky_Material.cpp
fan3750060/OpenWow
28925ebed1b3503d88014f6a3a7bd8adc777fdcc
[ "Apache-2.0" ]
null
null
null
owGameMap/Sky_Material.cpp
fan3750060/OpenWow
28925ebed1b3503d88014f6a3a7bd8adc777fdcc
[ "Apache-2.0" ]
null
null
null
owGameMap/Sky_Material.cpp
fan3750060/OpenWow
28925ebed1b3503d88014f6a3a7bd8adc777fdcc
[ "Apache-2.0" ]
1
2020-03-30T03:22:38.000Z
2020-03-30T03:22:38.000Z
#include "stdafx.h" // General #include "Sky_Material.h" Sky_Material::Sky_Material() : MaterialWrapper(_RenderDevice->CreateMaterial()) { std::shared_ptr<Shader> g_pVertexShader = _RenderDevice->CreateShader( Shader::VertexShader, "shaders_D3D/Sky.hlsl", Shader::ShaderMacros(), "VS_main", "latest" ); g_pVertexShader->LoadInputLayoutFromReflector(); std::shared_ptr<Shader> g_pPixelShader = _RenderDevice->CreateShader( Shader::PixelShader, "shaders_D3D/Sky.hlsl", Shader::ShaderMacros(), "PS_main", "latest" ); // Material SetShader(Shader::VertexShader, g_pVertexShader); SetShader(Shader::PixelShader, g_pPixelShader); } Sky_Material::~Sky_Material() { }
26.192308
91
0.754772
fan3750060
9d6e36e5cde619703fdf2cae129b1274e13a2192
460
cpp
C++
meshler/source/Interactors/CommandInteractor.cpp
timow-gh/FilApp
02ec78bf617fb78d872b2adceeb8a8351aa8f408
[ "Apache-2.0" ]
null
null
null
meshler/source/Interactors/CommandInteractor.cpp
timow-gh/FilApp
02ec78bf617fb78d872b2adceeb8a8351aa8f408
[ "Apache-2.0" ]
null
null
null
meshler/source/Interactors/CommandInteractor.cpp
timow-gh/FilApp
02ec78bf617fb78d872b2adceeb8a8351aa8f408
[ "Apache-2.0" ]
null
null
null
#include <Meshler/Interactors/CommandInteractor.hpp> #include <Meshler/MController.hpp> namespace Meshler { CommandInteractor::CommandInteractor(MController& controller) : m_controller(&controller) { } void CommandInteractor::onEvent(const Graphics::KeyEvent& keyEvent) { if (auto nextInteractorCommand = m_interactorKeyMap.nextInteractor(keyEvent.keyScancode)) m_controller->setNextInteractor(*nextInteractorCommand); } } // namespace Meshler
25.555556
93
0.797826
timow-gh
9d71cb630c4a2b418c9850d9b403295f5a74d91a
574
cpp
C++
c++/excel_sheet_column_title.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
c++/excel_sheet_column_title.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
c++/excel_sheet_column_title.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
/* Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB */ /* * */ #include "helper.h" class Solution { public: string convertToTitle(int n) { string res; while (n > 0) { n--; res += char('A' + n % 26); n /= 26; } reverse(res.begin(), res.end()); return res; } }; int main() { Solution s; cout << s.convertToTitle(28) << endl; return 0; }
14.35
92
0.468641
SongZhao
9d72e5973e0c77ec6d36e7a4797c223f5d28ed49
1,437
hpp
C++
pythran/pythonic/numpy/copy.hpp
Pikalchemist/Pythran
17d4108b56b3b365e089a4e1b01a09eb7e12942b
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/numpy/copy.hpp
Pikalchemist/Pythran
17d4108b56b3b365e089a4e1b01a09eb7e12942b
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/numpy/copy.hpp
Pikalchemist/Pythran
17d4108b56b3b365e089a4e1b01a09eb7e12942b
[ "BSD-3-Clause" ]
1
2017-03-12T20:32:36.000Z
2017-03-12T20:32:36.000Z
#ifndef PYTHONIC_NUMPY_COPY_HPP #define PYTHONIC_NUMPY_COPY_HPP #include "pythonic/utils/proxy.hpp" #include "pythonic/utils/numpy_conversion.hpp" #include "pythonic/types/ndarray.hpp" #include "pythonic/types/ndarray.hpp" namespace pythonic { namespace numpy { // list case template<class E> typename std::enable_if<!types::is_array<E>::value and !std::is_scalar<E>::value and !types::is_complex<E>::value, typename types::numpy_expr_to_ndarray<E>::type >::type copy(E const& v) { return typename types::numpy_expr_to_ndarray<E>::type{v}; } // scalar / complex case template<class E> auto copy(E const &v) -> typename std::enable_if<std::is_scalar<E>::value or types::is_complex<E>::value, E>::type { return v; } // No copy is required for numpy_expr template<class E> auto copy(E && v) -> typename std::enable_if<types::is_array<E>::value, decltype(std::forward<E>(v))>::type { return std::forward<E>(v); } // ndarray case template<class T, size_t N> types::ndarray<T,N> copy(types::ndarray<T,N> const& a) { return a.copy(); } PROXY(pythonic::numpy, copy); } } #endif
29.9375
126
0.544885
Pikalchemist
9d761c433f1ba80f04b598ab74fd262121d9c126
929
cpp
C++
src/utils/splitStrByDelimTest.cpp
lunalabsltd/fontbm
6db91d9d898ae8273d8676a5d2d71b2362466f23
[ "MIT" ]
148
2018-01-22T08:59:11.000Z
2022-03-29T05:12:49.000Z
src/utils/splitStrByDelimTest.cpp
lunalabsltd/fontbm
6db91d9d898ae8273d8676a5d2d71b2362466f23
[ "MIT" ]
18
2017-09-21T15:41:26.000Z
2022-03-10T12:08:39.000Z
src/utils/splitStrByDelimTest.cpp
lunalabsltd/fontbm
6db91d9d898ae8273d8676a5d2d71b2362466f23
[ "MIT" ]
21
2017-12-12T20:01:08.000Z
2022-02-17T20:56:51.000Z
#include "../external/catch.hpp" #include "splitStrByDelim.h" TEST_CASE("splitStrByDelim") { { std::vector<std::string> r = splitStrByDelim("1-2", '-'); REQUIRE(r.size() == 2); REQUIRE(r[0] == "1"); REQUIRE(r[1] == "2"); } { std::vector<std::string> r = splitStrByDelim("1", '-'); REQUIRE(r.size() == 1); REQUIRE(r[0] == "1"); } { std::vector<std::string> r = splitStrByDelim("a/b/z", '/'); REQUIRE(r.size() == 3); REQUIRE(r[0] == "a"); REQUIRE(r[1] == "b"); REQUIRE(r[2] == "z"); } { std::vector<std::string> r = splitStrByDelim("--1---2-", '-'); REQUIRE(r.size() == 7); REQUIRE(r[0] == ""); REQUIRE(r[1] == ""); REQUIRE(r[2] == "1"); REQUIRE(r[3] == ""); REQUIRE(r[4] == ""); REQUIRE(r[5] == "2"); REQUIRE(r[6] == ""); } }
23.820513
70
0.420883
lunalabsltd
9d8343e1fc243ad7e8bd42b8ccc33a1d8ef097a0
531
cpp
C++
CC/CF/Good Subarrays.cpp
MrRobo24/Codes
9513f42b61e898577123d5b996e43ba7a067a019
[ "MIT" ]
1
2020-10-12T08:03:20.000Z
2020-10-12T08:03:20.000Z
CC/CF/Good Subarrays.cpp
MrRobo24/Codes
9513f42b61e898577123d5b996e43ba7a067a019
[ "MIT" ]
null
null
null
CC/CF/Good Subarrays.cpp
MrRobo24/Codes
9513f42b61e898577123d5b996e43ba7a067a019
[ "MIT" ]
null
null
null
//TLE #include <bits/stdc++.h> #define LLI long long using namespace std; int main() { LLI t; cin >> t; while (t--) { LLI n; cin >> n; string s; cin >> s; vector<LLI> arr; for (LLI i=0;i<n;i++) { arr.push_back(s[i] - '0'); } LLI counter = 0; vector<LLI> pfx; LLI sum = 0; for (LLI i=0;i<n;i++) { sum += arr[i]; pfx.push_back(sum); } for (LLI i=0;i) } return 0; }
14.75
38
0.39548
MrRobo24
9d8cdcdc3f0c7bfb50b08797b36e7e3800833873
1,301
cpp
C++
2015/25/main.cpp
adrian-stanciu/adventofcode
47b3d12226b0c71fff485ef140cd7731c9a5d72f
[ "MIT" ]
null
null
null
2015/25/main.cpp
adrian-stanciu/adventofcode
47b3d12226b0c71fff485ef140cd7731c9a5d72f
[ "MIT" ]
null
null
null
2015/25/main.cpp
adrian-stanciu/adventofcode
47b3d12226b0c71fff485ef140cd7731c9a5d72f
[ "MIT" ]
null
null
null
#include <iostream> #include <regex> #include <string> auto read_position() { static const std::regex re{R"(\s+Enter the code at row ([1-9][0-9]*), column ([1-9][0-9]*).)"}; static const auto to_number = [] (const auto& s) { return strtol(s.data(), nullptr, 10); }; std::string line; getline(std::cin, line); auto msg = line.substr(line.find_first_of('.') + 1); std::smatch matched; regex_match(msg, matched, re); return std::make_pair(to_number(matched[1].str()), to_number(matched[2].str())); } auto next(long n) { return n * 252533 % 33554393; } auto next_after(long n, long iters) { while (iters--) n = next(n); return n; } auto sum_1_to_n(long n) { return n * (n + 1) / 2; } auto index_of_position(long row, long col) { // find on which row the diagonal containing this position begins auto diag_row = row + col - 1; // count how many numbers are above that diagonal // (use the fact that the i-th diagonal contains i numbers) auto numbers_above_diag = sum_1_to_n(diag_row - 1); return numbers_above_diag + col; } int main() { auto [row, col] = read_position(); auto index = index_of_position(row, col); std::cout << next_after(20151125, index - 1) << "\n"; return 0; }
20.015385
99
0.619523
adrian-stanciu
9d982be45559d04533ede9e5ea40e5e0b2806964
39,011
hh
C++
TswDps/Skills.hh
Philip-Trettner/tsw-optimal-dps
512ba96066b850d4a1bcdbaaac4718f95bbe7bd7
[ "MIT" ]
null
null
null
TswDps/Skills.hh
Philip-Trettner/tsw-optimal-dps
512ba96066b850d4a1bcdbaaac4718f95bbe7bd7
[ "MIT" ]
null
null
null
TswDps/Skills.hh
Philip-Trettner/tsw-optimal-dps
512ba96066b850d4a1bcdbaaac4718f95bbe7bd7
[ "MIT" ]
1
2021-12-16T20:53:51.000Z
2021-12-16T20:53:51.000Z
#pragma once #include "Skill.hh" /** * @brief Skill library * * For scalings see https://docs.google.com/spreadsheets/d/1z9b23xHPNQuqmZ5t51SeIMq2rlI6d8mPyWp9BmGNxjc/ */ struct Skills { public: private: template <Weapon weapon, DmgType dmgtype> struct Base { protected: Base() = delete; static Skill skill(std::string const& name, SkillType skilltype) { Skill s; s.name = name; s.weapon = weapon; s.dmgtype = dmgtype; s.skilltype = skilltype; return s; } }; static float scaling(std::string const& name); public: struct Pistol : private Base<Weapon::Pistol, DmgType::Ranged> { static Skill TheBusiness() { auto s = skill("The Business", SkillType::Builder); s.timeIn60th = 60; s.hits = 3; s.dmgScaling = scaling(s.name); return s; } static Skill GunFu() { auto s = skill("Gun-Fu", SkillType::None); s.timeIn60th = 60; s.passive.trigger = Trigger::FinishActivation; s.passive.effect = EffectSlot::GunFu; s.cooldownIn60th = 30 * 60; s.reduceWeaponConsumerCD = 4 * 60; s.slotForDmgAug = false; s.slotForSupportAug = true; return s; } static Skill Collaboration() { auto s = skill("Collaboration", SkillType::Builder); s.timeIn60th = 60; s.casttimeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); return s; } static Skill HairTrigger() { auto s = skill("Hair Trigger", SkillType::Builder); s.timeIn60th = 60; s.hits = 4; s.subtype = SubType::Focus; s.dmgScaling = scaling(s.name); s.channeling = true; return s; } static Skill Shootout() { auto s = skill("Shootout", SkillType::Consumer); s.timeIn60th = 150; s.cooldownIn60th = 60 * 4; s.hits = 5; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.channeling = true; s.subtype = SubType::Focus; return s; } static Skill Marked() { auto s = skill("Marked", SkillType::None); s.timeIn60th = 90; s.casttimeIn60th = 90; s.cooldownIn60th = 60 * 30; s.hits = 1; s.dmgScaling = scaling(s.name); s.slotForSupportAug = true; return s; } static Skill StartAndFinish() { auto s = skill("Start & Finish", SkillType::Consumer); s.timeIn60th = 60; s.cooldownIn60th = 60 * 4; s.hits = 2; s.dmgScalingA = scaling(s.name + " 1st"); s.specialHitsA = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.channeling = true; return s; } static Skill BondStrongBond() { auto s = skill("Bond, Strong Bond", SkillType::Consumer); s.timeIn60th = 3 * 60; s.hits = 10; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.cooldownIn60th = 60 * 4; s.channeling = true; return s; } static Skill Big45() { auto s = skill("Big Forty Five", SkillType::Consumer); s.casttimeIn60th = 90; // TODO: CD passive s.timeIn60th = 90; // TODO: CD passive s.cooldownIn60th = 60 * 4; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); return s; } static Skill DirtyTricks() { auto s = skill("Dirty Tricks", SkillType::Elite); s.cooldownIn60th = 25 * 60; s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.animaDeviation = true; s.slotForSupportAug = true; return s; } static Skill GunCrazy() { auto s = skill("Gun Crazy", SkillType::Elite); s.cooldownIn60th = 20 * 60; s.timeIn60th = 3 * 60; s.hits = 10; s.channeling = true; s.dmgScalingA = scaling(s.name + " 3xA"); s.dmgScalingB = scaling(s.name + " 3xB"); s.dmgScalingC = scaling(s.name + " 3xC"); s.dmgScaling = scaling(s.name + " Final"); s.specialHitsA = 3; s.specialHitsB = 3; s.specialHitsC = 3; s.appliesVulnerability = DmgType::Magic; s.slotForSupportAug = true; return s; } static Skill BulletBallet() { auto s = skill("Bullet Ballet", SkillType::Elite); s.consumesAnyways = true; s.cooldownIn60th = 20 * 60; s.timeIn60th = 2 * 60; s.hits = 10; s.channeling = true; s.specialHitsA = 9; s.dmgScalingA = scaling(s.name); s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.appliesVulnerability = DmgType::Melee; s.passive.trigger = Trigger::Hit; s.passive.effect = EffectSlot::CritRating; s.slotForSupportAug = true; return s; } }; struct Shotgun : private Base<Weapon::Shotgun, DmgType::Ranged> { static Skill Striker() { auto s = skill("Striker", SkillType::Builder); s.timeIn60th = 60; s.hits = 1; s.subtype = SubType::Strike; s.dmgScaling = scaling(s.name); return s; } static Skill SingleBarrel() { auto s = skill("Single Barrel", SkillType::Builder); s.timeIn60th = 60; s.casttimeIn60th = 30; s.hits = 1; s.dmgScaling = scaling(s.name); return s; } static Skill OutForAKill() { auto s = skill("Out for a Kill", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.cooldownIn60th = 60 * 4; return s; } static Skill SureShot() { auto s = skill("Sure Shot", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.cooldownIn60th = 60 * 4; return s; } static Skill Takedown() { auto s = skill("Takedown", SkillType::None); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.cooldownIn60th = 60 * 25; s.slotForSupportAug = true; return s; } /// Assumes close range static Skill RagingBullet() { auto s = skill("Raging Bullet", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.subtype = SubType::Strike; s.dmgScaling = scaling(s.name + " A @1"); s.dmgScaling5 = scaling(s.name + " A @5"); s.cooldownIn60th = 60 * 4; return s; } static Skill PointBlank() { auto s = skill("Point Blank", SkillType::Elite); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.cooldownIn60th = 60 * 25; s.animaDeviation = true; s.appliesVulnerability = DmgType::Melee; s.slotForSupportAug = true; return s; } static Skill Kneecapper() { auto s = skill("Kneecapper", SkillType::Elite); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.cooldownIn60th = 60 * 25; s.animaDeviation = true; s.slotForSupportAug = true; return s; } static Skill Bombardment() { auto s = skill("Bombardment", SkillType::Elite); s.timeIn60th = 60; s.cooldownIn60th = 60 * 30; s.passive.trigger = Trigger::StartActivation; s.passive.effect = EffectSlot::Bombardment; s.passive.effectStacks = 8; s.slotForSupportAug = true; return s; } static Skill LockStockBarrel() { auto s = skill("Lock, Stock & Barrel", SkillType::None); s.cooldownIn60th = 30 * 60; s.passive.effect = EffectSlot::LockStockBarrel; s.passive.trigger = Trigger::FinishActivation; s.slotForDmgAug = false; s.slotForSupportAug = true; return s; } static Skill ShotgunWedding() { auto s = skill("Shotgun Wedding", SkillType::Elite); s.timeIn60th = 2 * 60 + 30; s.hits = 5; s.dmgScaling = scaling(s.name); s.cooldownIn60th = 20 * 60; s.channeling = true; s.baseDmgIncPerHit = 0.25f; // 25% more dmg per hit s.appliesVulnerability = DmgType::Magic; s.slotForSupportAug = true; return s; } }; struct Rifle : private Base<Weapon::Rifle, DmgType::Ranged> { static Skill SafetyOff() { auto s = skill("Safety Off", SkillType::Builder); s.timeIn60th = 60; s.casttimeIn60th = 60; s.hits = 3; s.subtype = SubType::Burst; s.dmgScaling = scaling(s.name); return s; } static Skill LockAndLoad() { auto s = skill("Lock & Load", SkillType::None); s.passive.trigger = Trigger::FinishActivation; s.passive.effect = EffectSlot::LockAndLoad; s.cooldownIn60th = 25 * 60; s.reduceWeaponConsumerCD = 4 * 60; s.slotForDmgAug = false; s.slotForSupportAug = true; return s; } static Skill TriggerHappy() { auto s = skill("Trigger Happy", SkillType::Builder); s.timeIn60th = 60; s.casttimeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); return s; } static Skill Shellshocker() { auto s = skill("Shellshocker", SkillType::Elite); s.timeIn60th = 2 * 60; s.hits = 8; s.dmgScaling = scaling(s.name); s.cooldownIn60th = 25 * 60; s.channeling = true; s.animaDeviation = true; s.appliesVulnerability = DmgType::Melee; s.slotForSupportAug = true; return s; } static Skill RedMist() { auto s = skill("Red Mist", SkillType::Elite); s.timeIn60th = 2 * 60; s.casttimeIn60th = s.timeIn60th; s.hits = 1; s.dmgScaling = scaling(s.name); s.cooldownIn60th = 20 * 60; s.appliesVulnerability = DmgType::Magic; s.slotForSupportAug = true; return s; } static Skill ThreeRoundBurst() { auto s = skill("Three Round Burst", SkillType::Consumer); s.timeIn60th = 60; s.hits = 3; s.cooldownIn60th = 4 * 60; s.subtype = SubType::Burst; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); return s; } static Skill FireInTheHole() { auto s = skill("Fire in the Hole", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.cooldownIn60th = 4 * 60; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.passive.trigger = Trigger::Hit; s.passive.effect = EffectSlot::FireInTheHole; return s; } }; struct Chaos : private Base<Weapon::Chaos, DmgType::Magic> { static Skill RunRampant() { auto s = skill("Run Rampant", SkillType::Builder); s.timeIn60th = 60; s.hits = 3; s.subtype = SubType::Burst; s.dmgScaling = scaling(s.name); return s; } static Skill HandOfChange() { auto s = skill("Hand of Change", SkillType::Builder); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); return s; } static Skill FourHorsemen() { auto s = skill("Four Horsemen", SkillType::Consumer); s.timeIn60th = 60; s.hits = 4; s.subtype = SubType::Burst; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); /** Tooltip: 262 * * Hit 1: 263.12996941896 = 100% * Hit 2: 289.979719188768 = 110.20398772101% * Hit 3: 317.655963302752 = 120.722076624033% * Hit 4: 367.837606837607 = 139.793124914604% * * Tooltip: 365 (+39.5%) * Hit 1: 365.997957099081 = 100% * Hit 2: 393.580384226491 = 107.536224340166% * Hit 3: 420.548979591837 = 114.904734148007% * Hit 4: 472.626116071429 = 129.133539382976% */ // additive +10%, +20%, +30% s.baseDmgIncPerHit = 10 / 100.f; return s; } static Skill PullingTheStrings() { auto s = skill("Pulling the Strings", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); // TODO: minor hit chance return s; } static Skill SufferingAndSolace() { auto s = skill("Suffering and Solace", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); return s; } static Skill ChaoticPull() { auto s = skill("Chaotic Pull", SkillType::None); s.timeIn60th = 60; s.cooldownIn60th = 35 * 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.slotForSupportAug = true; return s; } static Skill Schism() { auto s = skill("Schism", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.dmgScalingLow = scaling(s.name + " @1 low"); s.dmgScaling5Low = scaling(s.name + " @5 low"); return s; } static Skill CallForEris() { auto s = skill("Call for Eris", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.extraHitPerResource = 1; s.fixedMultiHitPenalty = 0.70; // ?????? no fucking idea s.subtype = SubType::Burst; s.specialHitsA = 1; s.dmgScalingA = scaling(s.name + " 1st"); s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); return s; } static Skill AmorFati() { auto s = skill("Amor Fati", SkillType::None); s.cooldownIn60th = 60 * 60; s.passive.trigger = Trigger::FinishActivation; s.passive.effect = EffectSlot::AmorFati; s.slotForDmgAug = false; s.slotForSupportAug = true; return s; } static Skill DominoEffect() { auto s = skill("Domino Effect", SkillType::Elite); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.cooldownIn60th = 25 * 60; s.slotForSupportAug = true; return s; } static Skill PrisonerOfFate() { auto s = skill("Prisoner of Fate", SkillType::Elite); s.timeIn60th = 5 * 60; s.hits = 5; s.dmgScaling = scaling(s.name); s.dmgScalingLow = scaling(s.name + " low"); s.cooldownIn60th = 20 * 60; s.channeling = true; s.animaDeviation = true; s.appliesVulnerability = DmgType::Melee; s.slotForSupportAug = true; return s; } static Skill EyeOfPandemonium() { auto s = skill("Eye of Pandemonium", SkillType::Elite); s.timeIn60th = 60; s.cooldownIn60th = 25 * 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.passive.trigger = Trigger::FinishActivation; s.passive.effect = EffectSlot::EyeOfPandemonium; s.passive.effectStacks = 10; s.animaDeviation = true; s.slotForSupportAug = true; s.appliesVulnerability = DmgType::Ranged; return s; } static Skill GravitationalAnomaly() { auto s = skill("Gravitational Anomaly", SkillType::Elite); s.timeIn60th = 3 * 60; s.hits = 3; s.dmgScaling = scaling(s.name); s.cooldownIn60th = 25 * 60; s.channeling = true; s.slotForSupportAug = true; return s; } static Skill Paradox() { auto s = skill("Paradox", SkillType::None); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.cooldownIn60th = 10 * 60; return s; } }; struct Blood : private Base<Weapon::Blood, DmgType::Magic> { static Skill BoilingBlood() { auto s = skill("Boiling Blood", SkillType::Builder); s.timeIn60th = 60; s.casttimeIn60th = s.timeIn60th; s.hits = 1; s.dmgScaling = scaling(s.name); return s; } static Skill CardiacArrest() { auto s = skill("Cardiac Arrest", SkillType::Elite); s.timeIn60th = 60; s.casttimeIn60th = s.timeIn60th; s.cooldownIn60th = 25 * 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.animaDeviation = true; s.appliesVulnerability = DmgType::Melee; s.slotForSupportAug = true; return s; } static Skill Exsanguinate() { auto s = skill("Exsanguinate", SkillType::Consumer); s.timeIn60th = 150; s.hits = 5; s.fixedConsumerResources = 5; s.dmgScaling = scaling(s.name); s.channeling = true; s.subtype = SubType::Focus; return s; } static Skill Bloodline() { auto s = skill("Bloodline", SkillType::Builder); s.timeIn60th = 60; s.hits = 4; s.subtype = SubType::Focus; s.dmgScaling = scaling(s.name); s.channeling = true; return s; } static Skill Bloodshot() { auto s = skill("Bloodshot", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.fixedConsumerResources = 2; s.dmgScaling = scaling(s.name); return s; } static Skill Cannibalise() { auto s = skill("Cannibalise", SkillType::None); s.passive.trigger = Trigger::FinishActivation; s.passive.effect = EffectSlot::Cannibalise; s.cooldownIn60th = 25 * 60; s.slotForDmgAug = false; s.slotForSupportAug = true; return s; } static Skill Plague() { auto s = skill("Plague", SkillType::Elite); s.timeIn60th = 60 + 30; s.casttimeIn60th = s.timeIn60th; s.cooldownIn60th = 20 * 60; s.passive.trigger = Trigger::FinishActivation; s.passive.effect = EffectSlot::Plague; s.passive.effectStacks = 6; s.appliesVulnerability = DmgType::Ranged; return s; } static Skill LeftHandOfDarkness() { auto s = skill("Left Hand of Darkness", SkillType::Consumer); s.timeIn60th = 60; s.cooldownIn60th = 4 * 60; s.fixedConsumerResources = 3; s.passive.trigger = Trigger::StartActivation; s.passive.effect = EffectSlot::LeftHandOfDarkness; s.passive.effectStacks = 4; return s; } static Skill Contaminate() { auto s = skill("Contaminate", SkillType::None); s.timeIn60th = 60; s.casttimeIn60th = s.timeIn60th; s.cooldownIn60th = 40 * 60; s.fixedConsumerResources = 3; s.passive.trigger = Trigger::FinishActivation; s.passive.effect = EffectSlot::Contaminate; s.passive.effectStacks = 6; s.slotForSupportAug = true; return s; } }; struct Elemental : private Base<Weapon::Elemental, DmgType::Magic> { static Skill Shock() { auto s = skill("Shock", SkillType::Builder); s.timeIn60th = 60; s.casttimeIn60th = s.timeIn60th; s.hits = 1; s.dmgScaling = scaling(s.name); return s; } static Skill ElectricalBolt() { auto s = skill("Electrical Bolt", SkillType::Builder); s.timeIn60th = 60; s.casttimeIn60th = s.timeIn60th; s.hits = 1; s.dmgScaling = scaling(s.name); // TODO: 2 res if hindered return s; } static Skill Ignition() { auto s = skill("Ignition", SkillType::Builder); s.timeIn60th = 60; s.casttimeIn60th = 30; s.hits = 1; s.dmgScaling = scaling(s.name); s.subtype = SubType::Strike; return s; } static Skill Ignite() { auto s = skill("Ignite", SkillType::Builder); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.dmgScaling = scaling(s.name + " First"); return s; } static Skill Combust() { auto s = skill("Combust", SkillType::Consumer); s.timeIn60th = 60 + 30; // TODO: passive s.casttimeIn60th = s.timeIn60th; s.hits = 1; s.fixedConsumerResources = 2; // TODO: 1 if hindered s.dmgScaling = scaling(s.name); return s; } static Skill FlameStrike() { auto s = skill("Flame Strike", SkillType::Consumer); s.timeIn60th = 60; s.casttimeIn60th = s.timeIn60th; s.hits = 1; s.fixedConsumerResources = 2; s.dmgScaling = scaling(s.name); s.subtype = SubType::Strike; return s; } static Skill Blaze() { auto s = skill("Blaze", SkillType::Consumer); s.timeIn60th = 60 + 30; s.casttimeIn60th = s.timeIn60th; s.hits = 1; s.fixedConsumerResources = 3; s.dmgScaling = scaling(s.name); // TODO: Aidolon Passive return s; } static Skill MoltenEarth() { auto s = skill("Molten Earth", SkillType::Elite); s.timeIn60th = 60; s.cooldownIn60th = 25 * 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.animaDeviation = true; s.slotForSupportAug = true; return s; } static Skill ThorsHammer() { auto s = skill("Thor's Hammer", SkillType::Consumer); s.timeIn60th = 2 * 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.fixedConsumerResources = 5; s.subtype = SubType::Strike; return s; } static Skill HardReset() { auto s = skill("Hard Reset", SkillType::Elite); s.timeIn60th = 2 * 60; s.cooldownIn60th = 35 * 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.passive.bonusStats.addedCritChance = 1; // guaranteed crit s.animaDeviation = true; s.slotForSupportAug = true; return s; } static Skill Overload() { auto s = skill("Overload", SkillType::Elite); s.timeIn60th = 3 * 60; s.cooldownIn60th = 20 * 60; s.hits = 3; s.channeling = true; s.dmgScalingA = scaling(s.name); s.specialHitsA = 2; s.dmgScaling = scaling(s.name + " final"); s.appliesVulnerability = DmgType::Melee; s.slotForSupportAug = true; return s; } static Skill Whiteout() { auto s = skill("Whiteout", SkillType::Elite); s.timeIn60th = 60; s.casttimeIn60th = s.timeIn60th; s.cooldownIn60th = 25 * 60; s.passive.trigger = Trigger::FinishActivation; s.passive.effect = EffectSlot::Whiteout; s.passive.effectStacks = 16; s.animaDeviation = true; s.slotForSupportAug = true; return s; } static Skill PowerLine() { auto s = skill("Power Line", SkillType::Elite); s.timeIn60th = 60; s.cooldownIn60th = 20 * 60; s.passive.trigger = Trigger::StartActivation; s.passive.effect = EffectSlot::PowerLine; s.passive.effectStacks = 10; s.appliesVulnerability = DmgType::Ranged; s.slotForSupportAug = true; return s; } static Skill FireManifestation() { auto s = skill("Fire Manifestation", SkillType::Consumer); s.timeIn60th = 60; s.cooldownIn60th = 10 * 60; s.fixedConsumerResources = 2; s.passive.trigger = Trigger::StartActivation; s.passive.effect = EffectSlot::FireManifestation; s.passive.effectStacks = 4; s.slotForSupportAug = true; return s; } static Skill LightningManifestation() { auto s = skill("Lightning Manifestation", SkillType::Consumer); s.timeIn60th = 60; s.casttimeIn60th = s.timeIn60th; s.cooldownIn60th = 15 * 60; s.fixedConsumerResources = 2; s.passive.trigger = Trigger::StartActivation; s.passive.effect = EffectSlot::LightningManifestation; s.passive.effectStacks = 10; s.slotForSupportAug = true; return s; } static Skill AnimaCharge() { auto s = skill("Anima Charge", SkillType::None); s.passive.trigger = Trigger::FinishActivation; s.passive.effect = EffectSlot::AnimaCharge; s.cooldownIn60th = 30 * 60; s.slotForDmgAug = false; s.slotForSupportAug = true; // Casttime can be mitigated! return s; } }; struct Blade : private Base<Weapon::Blade, DmgType::Melee> { static Skill DelicateStrike() { auto s = skill("Delicate Strike", SkillType::Builder); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); return s; } static Skill GrassCutter() { auto s = skill("Grass Cutter", SkillType::Builder); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); return s; } static Skill SteelEcho() { auto s = skill("Steel Echo", SkillType::None); s.cooldownIn60th = 60 * 60; s.passive.trigger = Trigger::StartActivation; s.passive.effect = EffectSlot::SteelEcho; s.slotForSupportAug = true; s.slotForDmgAug = true; // TODO: Affects steel echo proc! // TODO: Can this proc more than once per sec? return s; } static Skill SlingBlade() { auto s = skill("Sling Blade", SkillType::None); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.cooldownIn60th = 35 * 60; s.slotForSupportAug = true; // TODO: afflict return s; } static Skill BalancedBlade() { auto s = skill("Balanced Blade", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); return s; } static Skill BindingWounds() { auto s = skill("Binding Wounds", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); return s; } static Skill DancingBlade() { auto s = skill("Dancing Blade", SkillType::Consumer); s.timeIn60th = 150; s.hits = 5; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.channeling = true; s.subtype = SubType::Focus; return s; } static Skill StunningSwirl() { auto s = skill("Stunning Swirl", SkillType::Elite); s.timeIn60th = 60; s.cooldownIn60th = 20 * 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.appliesVulnerability = DmgType::Ranged; s.slotForSupportAug = true; return s; } static Skill FourSeasons() { auto s = skill("Four Seasons", SkillType::Elite); s.timeIn60th = 150; s.hits = 5; s.cooldownIn60th = 20 * 60; s.passive.bonusStats.addedPenChance = 2.0; // guaranteed pen, even after penalty s.dmgScalingA = scaling(s.name); s.specialHitsA = 4; s.dmgScaling = scaling(s.name + " Final"); s.channeling = true; s.appliesVulnerability = DmgType::Magic; s.slotForSupportAug = true; return s; } }; struct Hammer : private Base<Weapon::Hammer, DmgType::Melee> { static Skill Smash() { auto s = skill("Smash", SkillType::Builder); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); return s; } static Skill FirstBlood() { auto s = skill("First Blood", SkillType::Builder); s.timeIn60th = 60; s.subtype = SubType::Strike; s.hits = 1; s.dmgScaling = scaling(s.name); s.dmgScaling0 = scaling(s.name + " First"); return s; } static Skill GrandSlam() { auto s = skill("Grand Slam", SkillType::Builder); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.passive.trigger = Trigger::Hit; s.passive.effect = EffectSlot::GrandSlam; return s; } static Skill Haymaker() { auto s = skill("Haymaker", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.subtype = SubType::Strike; return s; } static Skill StonesThrow() { auto s = skill("Stone's Throw", SkillType::None); s.timeIn60th = 60; s.hits = 1; s.cooldownIn60th = 15 * 60; s.dmgScaling = scaling(s.name); s.slotForSupportAug = true; return s; } static Skill Shockwave() { auto s = skill("Shockwave", SkillType::Elite); s.timeIn60th = 60; s.cooldownIn60th = 25 * 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.appliesVulnerability = DmgType::Magic; s.slotForSupportAug = true; return s; } static Skill Eruption() { auto s = skill("Eruption", SkillType::Elite); s.timeIn60th = 60; s.cooldownIn60th = 25 * 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.appliesVulnerability = DmgType::Ranged; s.slotForSupportAug = true; return s; } static Skill MoltenSteel() { auto s = skill("Molten Steel", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.passive.bonusStats.addedCritChance = 30 / 100.f; s.passive.bonusStats.addedCritPower = 15 / 100.f; return s; } static Skill BoneBreaker() { auto s = skill("Bone Breaker", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); return s; } static Skill FullMomentum() { auto s = skill("Full Momentum", SkillType::None); s.cooldownIn60th = 30 * 60; s.passive.effect = EffectSlot::FullMomentum; s.passive.trigger = Trigger::FinishActivation; s.slotForDmgAug = false; s.slotForSupportAug = true; return s; } }; struct Fist : private Base<Weapon::Fist, DmgType::Melee> { static Skill SeeRed() { auto s = skill("See Red", SkillType::Elite); s.timeIn60th = 4 * 60; s.hits = 20; s.dmgScaling = scaling(s.name); s.cooldownIn60th = 25 * 60; s.channeling = true; s.animaDeviation = true; s.appliesVulnerability = DmgType::Magic; s.slotForSupportAug = true; return s; } static Skill Reckless() { auto s = skill("Reckless", SkillType::None); s.cooldownIn60th = 40 * 60; s.passive.trigger = Trigger::FinishActivation; s.passive.effect = EffectSlot::Reckless; s.slotForDmgAug = false; s.slotForSupportAug = true; return s; } static Skill Claw() { auto s = skill("Claw", SkillType::Builder); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); return s; } static Skill PreyOnTheWeak() { auto s = skill("Prey on the Weak", SkillType::Builder); s.timeIn60th = 60; s.hits = 3; s.dmgScaling = scaling(s.name); s.subtype = SubType::Burst; return s; } static Skill WildAtHeart() { auto s = skill("Wild at Heart", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); return s; } static Skill TearEmUp() { auto s = skill("Tear Em Up", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.passive.trigger = Trigger::Hit; s.passive.effect = EffectSlot::TearEmUp; return s; } static Skill GoForTheThroat() { auto s = skill("Go for the Throat", SkillType::Elite); s.timeIn60th = 60; s.cooldownIn60th = 25 * 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.passive.trigger = Trigger::FinishActivation; s.passive.effect = EffectSlot::GoForTheThroat; s.passive.effectStacks = 10; s.animaDeviation = true; s.slotForSupportAug = true; return s; } static Skill OneTwo() { auto s = skill("One-Two", SkillType::Consumer); s.timeIn60th = 60; s.hits = 2; s.dmgScalingA = scaling(s.name + " 1st"); s.specialHitsA = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.subtype = SubType::Burst; return s; } }; struct Chainsaw : private Base<Weapon::Aux, DmgType::None> { static Skill Timber() { auto s = skill("Timber", SkillType::None); s.timeIn60th = 60; s.hits = 1; s.cooldownIn60th = 15 * 60; s.dmgScaling = scaling(s.name); s.chanceForScaleInc = 0.33f; s.scaleIncPerc = .45f; s.slotForDmgAug = false; return s; } }; struct Flamethrower : private Base<Weapon::Aux, DmgType::None> { static Skill ScorchedEarth() { auto s = skill("Scorched Earth", SkillType::None); s.timeIn60th = 60; s.casttimeIn60th = 30; s.cooldownIn60th = 20 * 60; // TODO: get real number with passive // TODO: continue assert(0 && "not impl"); s.slotForDmgAug = false; return s; } }; static Skill empty() { return Skill(); } static std::vector<Skill> all(); private: Skills() = delete; };
31.384553
104
0.488529
Philip-Trettner
9d9d5b7473894407a4608b205be216e53d7cc87b
839
hpp
C++
Core/src/Core/Texture/TextureGL.hpp
Zephilinox/Ricochet
9ace649ecb1ccc0fa6e8b8d35b449676452d0616
[ "Unlicense" ]
null
null
null
Core/src/Core/Texture/TextureGL.hpp
Zephilinox/Ricochet
9ace649ecb1ccc0fa6e8b8d35b449676452d0616
[ "Unlicense" ]
null
null
null
Core/src/Core/Texture/TextureGL.hpp
Zephilinox/Ricochet
9ace649ecb1ccc0fa6e8b8d35b449676452d0616
[ "Unlicense" ]
null
null
null
#pragma once //SELF //LIBS //STD #include <array> #include <vector> #include <functional> namespace core { struct Pixel { std::uint8_t r = 0; std::uint8_t g = 0; std::uint8_t b = 0; std::uint8_t a = 0; }; class TextureGL { public: TextureGL(); void load(std::vector<Pixel> pixels, unsigned int width, unsigned int height); const std::vector<Pixel>& getPixels() const; const Pixel& operator[](unsigned int index) const; void update(std::function<void(std::vector<Pixel>& pixels)> updater); unsigned int getOpenglTextureID() const; [[nodiscard]] unsigned int getWidth() const; [[nodiscard]] unsigned int getHeight() const; private: unsigned int width = 0; unsigned int height = 0; std::vector<Pixel> pixels; unsigned int opengl_texture_id = 0; }; } // namespace core
18.644444
82
0.66031
Zephilinox
9d9e74482cc40aa003ecdb937db3342304fe3021
275
cpp
C++
3rdparty/ImagingEngineLib/data/light.cpp
jia1000/DW_Client_CTA_Multi_Tab
3f69c8354dd37f3c8bbeaefc28a2e643bcdb1ee1
[ "MIT" ]
4
2021-05-17T19:33:22.000Z
2022-03-09T12:48:58.000Z
3rdparty/ImagingEngineLib/data/light.cpp
jia1000/DW_Client_CTA_Multi_Tab
3f69c8354dd37f3c8bbeaefc28a2e643bcdb1ee1
[ "MIT" ]
null
null
null
3rdparty/ImagingEngineLib/data/light.cpp
jia1000/DW_Client_CTA_Multi_Tab
3f69c8354dd37f3c8bbeaefc28a2e643bcdb1ee1
[ "MIT" ]
null
null
null
#pragma once #include "light.h" using namespace DW::IMAGE; using namespace std; Light::Light() { } Light::~Light() { } void Light::SetLight(vtkSmartPointer<vtkLight> light) { vtk_light_ = light; } vtkSmartPointer<vtkLight> Light::GetLight() { return vtk_light_; }
10.576923
54
0.701818
jia1000
9d9fe9e904353666f2eff93c607d1edb72acfe0b
43,319
cpp
C++
src/OBJECTS/Obj.cpp
Seideman-Group/chiML
9ace5dccdbc6c173e8383f6a31ff421b4fefffdf
[ "MIT" ]
1
2019-04-27T05:25:27.000Z
2019-04-27T05:25:27.000Z
src/OBJECTS/Obj.cpp
Seideman-Group/chiML
9ace5dccdbc6c173e8383f6a31ff421b4fefffdf
[ "MIT" ]
null
null
null
src/OBJECTS/Obj.cpp
Seideman-Group/chiML
9ace5dccdbc6c173e8383f6a31ff421b4fefffdf
[ "MIT" ]
2
2019-04-03T10:08:21.000Z
2019-09-30T22:40:28.000Z
/** @file OBJECTS/Obj.cpp * @brief Class that stores all object/material information * * A class that determines if a grid point is inside the object, stores the material parameters, and * finds the gradient to determine the surface normal vector. * * @author Thomas A. Purcell (tpurcell90) * @bug No known bugs. */ #include "Obj.hpp" std::array<double, 3> Obj::RealSpace2ObjectSpace(const std::array<double,3>& pt) { std::array<double,3> v_trans; std::array<double,3> v_cen; // Move origin to object's center std::transform(pt.begin(), pt.end(), location_.begin(), v_cen.begin(), std::minus<double>() ); // Convert x, y, z coordinates to coordinates along the object's unit axis dgemv_('T', v_cen.size(), v_cen.size(), 1.0, coordTransform_.data(), v_cen.size(), v_cen.data(), 1, 0.0, v_trans.data(), 1 ); return v_trans; } std::array<double, 3> Obj::ObjectSpace2RealSpace(const std::array<double,3>& pt) { std::array<double,3> realSpacePt; dgemv_('T', pt.size(), pt.size(), 1.0, invCoordTransform_.data(), pt.size(), pt.data(), 1, 0.0, realSpacePt.data(), 1 ); // Normalize the gradient vector if(std::accumulate(realSpacePt.begin(), realSpacePt.end(), 0.0, vecMagAdd<double>() ) < 1e-20) realSpacePt = {{ 0.0, 0.0, 0.0 }}; else normalize(realSpacePt); return realSpacePt; } Obj::Obj(const Obj &o) : ML_(o.ML_), useOrientedDipols_(o.useOrientedDipols_), eps_infty_(o.eps_infty_), mu_infty_(o.mu_infty_), tellegen_(o.tellegen_), unitVec_(o.unitVec_), dipOr_(o.dipOr_), magDipOr_(o.magDipOr_), geoParam_(o.geoParam_), geoParamML_(o.geoParamML_), location_(o.location_), alpha_(o.alpha_), xi_(o.xi_), gamma_(o.gamma_), magAlpha_(o.magAlpha_), magXi_(o.magXi_), magGamma_(o.magGamma_), chiAlpha_(o.chiAlpha_), chiXi_(o.chiXi_), chiGamma_(o.chiGamma_), chiGammaPrev_(o.chiGammaPrev_), dipE_(o.dipE_), dipM_(o.dipM_), pols_(o.pols_) {} Obj::Obj(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : ML_(ML), useOrientedDipols_(false), eps_infty_(eps_infty), mu_infty_(mu_infty), tellegen_(tellegen), unitVec_(unitVec), geoParam_(geo), geoParamML_(geo), location_(loc), pols_(pols) { for(int ii = 0; ii < 3; ++ii) { for(int jj = 0; jj < 3; ++jj) { std::array<double,3>cartCoord = {{ 0, 0, 0 }}; cartCoord[jj] = 1.0; coordTransform_[(ii)*3+jj] = ddot_(unitVec[ii].size(), unitVec[ii].data(), 1, cartCoord.data(), 1) / ( std::sqrt( std::accumulate(unitVec[ii].begin(),unitVec[ii].end(),0.0, vecMagAdd<double>() ) ) ); } } std::copy_n(coordTransform_.begin(), coordTransform_.size(), invCoordTransform_.begin()); std::vector<int>invIpiv(invCoordTransform_.size(), 0.0); std::vector<double>work(invCoordTransform_.size(), -1) ; int info; dgetrf_(3, 3, invCoordTransform_.data(), 3, invIpiv.data(), &info); if(info < 0) throw std::logic_error("The " + std::to_string(-1.0*info) + "th value of the coordTransform_ matrix is an illegal value."); else if(info > 0) throw std::logic_error("WARNING: The " + std::to_string(info) + "th diagonal element of u is 0. The invCoordTransform_ can't be calculated!"); dgetri_(3, invCoordTransform_.data(), 3, invIpiv.data(), work.data(), work.size(), &info); if(info < 0) throw std::logic_error("The " + std::to_string(-1.0*info) + "th value of the coordTransform_ matrix is an illegal value."); else if(info > 0) throw std::logic_error("WARNING: The " + std::to_string(info) + "th diagonal element of u is 0. The invCoordTransform_ can't be calculated!"); // for(int ii = 0; ii < 3; ++ii) // for(int jj = 0; jj < 3; ++jj) // invCoordTransform_[(jj)*3+ii] = coordTransform_[ ( (ii+1)%3 )*3 + ( (jj+1)%3 ) ]*coordTransform_[ ( (ii+2)%3 )*3 + ( (jj+2)%3 ) ] - coordTransform_[ ( (ii+2)%3 )*3 + ( (jj+1)%3 ) ]*coordTransform_[ ( (ii+1)%3 )*3 + ( (jj+2)%3 ) ]; // double detCoord = coordTransform_[0]*invCoordTransform_[0] + coordTransform_[3]*invCoordTransform_[1] + coordTransform_[6]*invCoordTransform_[2]; // if(std::abs(detCoord) < 1e-15) // throw std::logic_error("Determinant of the coordTransform_ matrix is 0, inverse is undefined."); // dscal_(invCoordTransform_.size(), 1.0/detCoord, invCoordTransform_.data(), 1); } sphere::sphere(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec) {} hemisphere::hemisphere(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec) {} cylinder::cylinder(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec) {} cone::cone(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec) {} ellipsoid::ellipsoid(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> axisCutNeg, std::array<double,3> axisCutPos, std::array<double,3> axisCutGlobal, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec), axisCutNeg_(axisCutNeg), axisCutPos_(axisCutPos), axisCutGlobal_(axisCutGlobal) {} hemiellipsoid::hemiellipsoid(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec) {} block::block(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec) {} rounded_block::rounded_block(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec) { double radCurv = geoParam_[geoParam_.size()-1]; curveCens_[0] = { geoParam_[0]/2.0 - radCurv, geoParam_[1]/2.0 - radCurv, geoParam_[2]/2.0 - radCurv}; curveCens_[1] = {-1.0*geoParam_[0]/2.0 + radCurv, geoParam_[1]/2.0 - radCurv, geoParam_[2]/2.0 - radCurv}; curveCens_[2] = { geoParam_[0]/2.0 - radCurv, -1.0*geoParam_[1]/2.0 + radCurv, geoParam_[2]/2.0 - radCurv}; curveCens_[3] = {-1.0*geoParam_[0]/2.0 + radCurv, -1.0*geoParam_[1]/2.0 + radCurv, geoParam_[2]/2.0 - radCurv}; curveCens_[4] = { geoParam_[0]/2.0 - radCurv, geoParam_[1]/2.0 - radCurv, -1.0*geoParam_[2]/2.0 + radCurv}; curveCens_[5] = {-1.0*geoParam_[0]/2.0 + radCurv, geoParam_[1]/2.0 - radCurv, -1.0*geoParam_[2]/2.0 + radCurv}; curveCens_[6] = { geoParam_[0]/2.0 - radCurv, -1.0*geoParam_[1]/2.0 + radCurv, -1.0*geoParam_[2]/2.0 + radCurv}; curveCens_[7] = {-1.0*geoParam_[0]/2.0 + radCurv, -1.0*geoParam_[1]/2.0 + radCurv, -1.0*geoParam_[2]/2.0 + radCurv}; } tri_prism::tri_prism(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec), invVertIpiv_(3, 0), invVertMat_(9,1.0) { vertLocs_[0] = {{ 0.5*geoParam_[0], -0.5*geoParam_[1] }}; vertLocs_[1] = {{ -0.5*geoParam_[0], -0.5*geoParam_[1] }}; vertLocs_[2] = {{ 0 , 0.5*geoParam_[1] }}; // For scaling recenter the object space geometry to the centroid std::array<double, 3> centroidLoc = {0.0,0.0,0.0}; for(int ii = 0; ii < 3; ++ii) std::transform(vertLocs_[ii].begin(), vertLocs_[ii].end(), centroidLoc.begin(), centroidLoc.begin(), [](double vert, double cent){return cent + vert/3.0;}); std::transform(location_.begin(), location_.end(), centroidLoc.begin(), location_.begin(), std::plus<double>() ); for(int ii = 0; ii < 3; ++ii) { std::transform(vertLocs_[ii].begin(), vertLocs_[ii].end(), centroidLoc.begin(), vertLocs_[ii].begin(), std::minus<double>() ); dcopy_(2, vertLocs_[ii].begin(), 1, &invVertMat_[ii], 3); } int info; dgetrf_(3, 3, invVertMat_.data(), 3, invVertIpiv_.data(), &info); d0_ = getLUFactMatDet(invVertMat_, invVertIpiv_, 3); if(d0_ == 0) throw std::logic_error("The triangular base is a line."); std::vector<double>work(9,0.0); dgetri_(3, invVertMat_.data(), 3, invVertIpiv_.data(), work.data(), work.size(), &info); geoParam_ = {{ 1.0, 1.0, 1.0, geoParam_[3] }}; } tri_prism::tri_prism(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<std::array<double, 2>, 3> vertLocs, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec), invVertIpiv_(3, 0), invVertMat_(9,1.0), vertLocs_(vertLocs) { // For scaling recenter the object space geometry to the centroid std::array<double, 3> centroidLoc = {0.0,0.0,0.0}; for(int ii = 0; ii < 3; ++ii) std::transform(vertLocs_[ii].begin(), vertLocs_[ii].end(), centroidLoc.begin(), centroidLoc.begin(), [](double vert, double cent){return cent + vert/3.0;}); std::transform(location_.begin(), location_.end(), centroidLoc.begin(), location_.begin(), std::plus<double>() ); for(int ii = 0; ii < 3; ++ii) { std::transform(vertLocs_[ii].begin(), vertLocs_[ii].end(), centroidLoc.begin(), vertLocs_[ii].begin(), std::minus<double>() ); dcopy_(2, vertLocs_[ii].begin(), 1, &invVertMat_[ii], 3); } int info; dgetrf_(3, 3, invVertMat_.data(), 3, invVertIpiv_.data(), &info); d0_ = getLUFactMatDet(invVertMat_, invVertIpiv_, 3); if(d0_ == 0) throw std::logic_error("The triangular base is a line."); std::vector<double>work(9,0.0); dgetri_(3, invVertMat_.data(), 3, invVertIpiv_.data(), work.data(), work.size(), &info); } ters_tip::ters_tip(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec) { radCen_ = {{ 0.0, 0.0, -1.0*geo[2]/2.0 + geo[0]/2.0 }}; } paraboloid::paraboloid(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec) {} torus::torus(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec) {} tetrahedron::tetrahedron(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec), invVertIpiv_(4, 0), invVertMat_(16,1.0) { std::vector<double> vert = {{ std::sqrt(8.0/9.0), 0, -1.0/3.0 }}; dgemv_('T', vert.size(), vert.size(), 1.0, coordTransform_.data(), vert.size(), vert.data(), 1, 0.0, vertLocs_[0].data(), 1 ); vert = {{-1.0*std::sqrt(2.0/9.0), std::sqrt(2.0/3.0), -1.0/3.0 }}; dgemv_('T', vert.size(), vert.size(), 1.0, coordTransform_.data(), vert.size(), vert.data(), 1, 0.0, vertLocs_[1].data(), 1 ); vert = {{-1.0*std::sqrt(2.0/9.0), -1.0*std::sqrt(2.0/3.0), -1.0/3.0 }}; dgemv_('T', vert.size(), vert.size(), 1.0, coordTransform_.data(), vert.size(), vert.data(), 1, 0.0, vertLocs_[2].data(), 1 ); vert = {{ 0, 0, 1}}; dgemv_('T', vert.size(), vert.size(), 1.0, coordTransform_.data(), vert.size(), vert.data(), 1, 0.0, vertLocs_[3].data(), 1 ); for(int ii = 0; ii < 4; ++ii) { dscal_(3, geoParam_[0]*std::sqrt(3.0/8.0), vertLocs_[ii].begin(), 1); daxpy_(3, 1.0, location_.begin(), 1, vertLocs_[ii].begin(), 1); } for(int ii = 0; ii < 4; ++ii) dcopy_(3, vertLocs_[ii].begin(), 1, &invVertMat_[ii], 4); int info; dgetrf_(4, 4, invVertMat_.data(), 4, invVertIpiv_.data(), &info); d0_ = getLUFactMatDet(invVertMat_, invVertIpiv_, 4); if(d0_ == 0) throw std::logic_error("The tetrahedron is planer."); std::vector<double>work(16,0.0); dgetri_(4, invVertMat_.data(), 4, invVertIpiv_.data(), work.data(), work.size(), &info); double heightRat = ( geoParam_[1]/( geoParam_[0]*sqrt(2.0/3.0) )*(5.0/4.0) ) - 1.0/4.0; std::array<double,3>v4(location_); daxpy_(3, heightRat, vertLocs_[3].begin(), 1, v4.data(), 1); std::array<double,4> v4Bary = cart2bary<double,4>(invVertMat_, v4, d0_); geoParam_ = {{ 1.0, 1.0, 1.0, v4Bary[3] }}; } tetrahedron::tetrahedron(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<std::array<double, 3>, 4> vertLocs, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec), invVertIpiv_(4, 0), invVertMat_(16,1.0), vertLocs_(vertLocs) { for(int ii = 0; ii < 4; ++ii) dcopy_(3, vertLocs_[ii].begin(), 1, &invVertMat_[ii], 4); int info; dgetrf_(4, 4, invVertMat_.data(), 4, invVertIpiv_.data(), &info); d0_ = getLUFactMatDet(invVertMat_, invVertIpiv_, 4); if(d0_ == 0) throw std::logic_error("The tetrahedron is planer."); std::vector<double>work(16,0.0); dgetri_(4, invVertMat_.data(), 4, invVertIpiv_.data(), work.data(), work.size(), &info); if(d0_ == 0) throw std::logic_error("The tetrahedron is planer."); } sphere::sphere(const sphere &o) : Obj(o) {} hemisphere::hemisphere(const hemisphere &o) : Obj(o) {} cone::cone(const cone &o) : Obj(o) {} cylinder::cylinder(const cylinder &o) : Obj(o) {} block::block(const block &o) : Obj(o) {} rounded_block::rounded_block(const rounded_block &o) : Obj(o), curveCens_(o.curveCens_) {} ellipsoid::ellipsoid(const ellipsoid &o) : Obj(o), axisCutNeg_(o.axisCutNeg_), axisCutPos_(o.axisCutPos_), axisCutGlobal_(o.axisCutGlobal_) {} hemiellipsoid::hemiellipsoid(const hemiellipsoid &o) : Obj(o) {} tri_prism::tri_prism(const tri_prism &o) : Obj(o) {} ters_tip::ters_tip(const ters_tip &o) : Obj(o), radCen_(o.radCen_) {} paraboloid::paraboloid(const paraboloid &o) : Obj(o) {} torus::torus(const torus &o) : Obj(o) {} void Obj::setUpConsts (double dt) { // Converts Lorentzian style functions into constants that can be used for time updates based on Taflove Chapter 9 for(auto& pol : pols_) { if(pol.dipOrE_ != MAT_DIP_ORIENTAITON::ISOTROPIC || pol.dipOrM_ != MAT_DIP_ORIENTAITON::ISOTROPIC) useOrientedDipols_ = true; double sigP = pol.sigP_; double sigM = pol.sigM_; double tau = pol.tau_; double gam = pol.gam_; double omg = pol.omg_; if(std::abs( sigP ) != 0.0) { dipOr_.push_back(pol.dipOrE_); dipE_.push_back(pol.uVecDipE_); dipNormCompE_.push_back(pol.normCompWeightE_); dipTanLatCompE_.push_back(pol.tangentLatCompWeightE_); dipTanLongCompE_.push_back(pol.tangentLongCompWeightE_); alpha_.push_back( ( (2-pow(omg*dt,2.0)) / (1+gam*dt) ) ); xi_.push_back( ( (gam*dt -1) / (1+gam*dt) ) ); gamma_.push_back( ( (sigP*pow(omg*dt,2.0)) / (1+gam*dt) ) ); } if(std::abs( sigM ) != 0.0) { magDipOr_.push_back(pol.dipOrM_); dipM_.push_back(pol.uVecDipM_); dipNormCompM_.push_back(pol.normCompWeightM_); dipTanLatCompM_.push_back(pol.tangentLatCompWeightM_); dipTanLongCompM_.push_back(pol.tangentLongCompWeightM_); magAlpha_.push_back( ( (2-pow(omg*dt,2.0)) / (1+gam*dt) ) ); magXi_.push_back( ( (gam*dt -1) / (1+gam*dt) ) ); magGamma_.push_back( ( (sigM*pow(omg*dt,2.0)) / (1+gam*dt) ) ); } if(std::abs( tau ) != 0.0) { chiEDipOr_.push_back(pol.dipOrE_); chiMDipOr_.push_back(pol.dipOrM_); dipChiE_.push_back(pol.uVecDipE_); dipChiM_.push_back(pol.uVecDipM_); dipNormCompChiE_.push_back(pol.normCompWeightE_); dipTanLatCompChiE_.push_back(pol.tangentLatCompWeightE_); dipTanLongCompChiE_.push_back(pol.tangentLongCompWeightE_); dipNormCompChiM_.push_back(pol.normCompWeightM_); dipTanLatCompChiM_.push_back(pol.tangentLatCompWeightM_); dipTanLongCompChiM_.push_back(pol.tangentLongCompWeightM_); chiAlpha_.push_back( ( (2-pow(omg*dt,2.0)) / (1+gam*dt) ) ); chiXi_.push_back( ( (gam*dt -1) / (1+gam*dt) ) ); chiGamma_.push_back( ( -1.0/dt ) * ( (tau*pow(omg*dt,2.0) ) / ( (1+gam*dt) ) ) ); //!< 1/dt for gamma is due to the time derivative needed for chiral interactions chiGammaPrev_.push_back( ( 1.0/dt ) * ( (tau*pow(omg*dt,2.0) ) / ( (1+gam*dt) ) ) ); //!< 1/dt for gamma is due to the time derivative needed for chiral interactions // chiGamma_.push_back( ( pol.molec_ ? gam/2.0 - 1.0/dt : -1.0/dt ) * ( (tau*pow(omg*dt,2.0) ) / ( (1+gam*dt) ) ) ); //!< 1/dt for gamma is due to the time derivative needed for chiral interactions // chiGammaPrev_.push_back( ( pol.molec_ ? gam/2.0 + 1.0/dt : 1.0/dt ) * ( (tau*pow(omg*dt,2.0) ) / ( (1+gam*dt) ) ) ); //!< 1/dt for gamma is due to the time derivative needed for chiral interactions } } alpha_.reserve( alpha_.size() ); xi_.reserve( xi_.size() ); gamma_.reserve( gamma_.size() ); magAlpha_.reserve( magAlpha_.size() ); magXi_.reserve( magXi_.size() ); magGamma_.reserve( magGamma_.size() ); chiAlpha_.reserve( chiAlpha_.size() ); chiXi_.reserve( chiXi_.size() ); chiGamma_.reserve( chiGamma_.size() ); chiGammaPrev_.reserve( chiGammaPrev_.size() ); } bool sphere::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { if(dist(v,location_) > geo[0] + dx/1.0e6) { return false; } return true; } bool hemisphere::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { if(dist(v,location_) > geo[0] + dx/1.0e6) { // Move origin to object's center return false; } // Convert x, y, z coordinates to coordinates along the object's unit axis std::array<double,3> v_trans; // Do geo checks based on the the object oriented coordinates std::array<double,3> v_cen; std::transform(v.begin(), v.end(), location_.begin(), v_cen.begin(), std::minus<double>() ); dgemv_('T', v_cen.size(), v_cen.size(), 1.0, coordTransform_.data(), v_cen.size(), v_cen.data(), 1, 0.0, v_trans.data(), 1 ); if(v_trans[0] > dx/1e6) return false; return true; } bool block::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { std::array<double,3> v_trans = RealSpace2ObjectSpace(v); // Do geo checks based on the the object oriented coordinates for(int ii = 0; ii < v.size(); ii++) { if((v_trans[ii] > geo[ii]/2.0 + dx/1.0e6) || (v_trans[ii] < -1.0*geo[ii]/2.0 - dx/1.0e6)) return false; } return true; } bool rounded_block::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { std::array<double,3> v_trans = RealSpace2ObjectSpace(v); // Do geo checks based on the the object oriented coordinates double radCurv = geo.back(); for(int ii = 0; ii < v.size(); ii++) { if((v_trans[ii] > geo[ii]/2.0 + dx/1.0e6) || (v_trans[ii] < -1.0*geo[ii]/2.0 - dx/1.0e6)) return false; } if( ( (v_trans[0] > geo[0]/2.0 - radCurv + dx/1.0e6) || (v_trans[0] < -1.0*geo[0]/2.0 + radCurv - dx/1.0e6) ) || ( (v_trans[1] > geo[1]/2.0 - radCurv + dx/1.0e6) || (v_trans[1] < -1.0*geo[1]/2.0 + radCurv - dx/1.0e6) ) || ( (v_trans[2] > geo[2]/2.0 - radCurv + dx/1.0e6) || (v_trans[2] < -1.0*geo[2]/2.0 + radCurv - dx/1.0e6) ) ) { for(int cc = 0; cc < curveCens_.size(); cc++) if( ( std::sqrt( std::pow(v_trans[0] - curveCens_[cc][0], 2.0) + std::pow(v_trans[1] - curveCens_[cc][1], 2.0) ) < radCurv + dx/1.0e6 ) || ( std::sqrt( std::pow(v_trans[2] - curveCens_[cc][2], 2.0) + std::pow(v_trans[1] - curveCens_[cc][1], 2.0) ) < radCurv + dx/1.0e6 ) || ( std::sqrt( std::pow(v_trans[0] - curveCens_[cc][0], 2.0) + std::pow(v_trans[2] - curveCens_[cc][2], 2.0) ) < radCurv + dx/1.0e6 ) ) return true; if( (v_trans[0] < geo[0]/2.0 - radCurv + dx/1.0e6) && (v_trans[0] > -1.0*geo[0]/2.0 + radCurv - dx/1.0e6) && (v_trans[1] < geo[1]/2.0 - radCurv + dx/1.0e6) && (v_trans[1] > -1.0*geo[1]/2.0 + radCurv - dx/1.0e6) || (v_trans[2] < geo[2]/2.0 - radCurv + dx/1.0e6) && (v_trans[2] > -1.0*geo[2]/2.0 + radCurv - dx/1.0e6) && (v_trans[1] < geo[1]/2.0 - radCurv + dx/1.0e6) && (v_trans[1] > -1.0*geo[1]/2.0 + radCurv - dx/1.0e6) || (v_trans[0] < geo[0]/2.0 - radCurv + dx/1.0e6) && (v_trans[0] > -1.0*geo[0]/2.0 + radCurv - dx/1.0e6) && (v_trans[2] < geo[2]/2.0 - radCurv + dx/1.0e6) && (v_trans[2] > -1.0*geo[2]/2.0 + radCurv - dx/1.0e6) ) return true; return false; } return true; } bool ellipsoid::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { std::array<double,3> v_trans = RealSpace2ObjectSpace(v); // Do geo checks based on the the object oriented coordinates double ptSum = 0.0; for( int ii = 0; ii < ( geo[2] != 0.0 ? v_trans.size() : 2 ); ++ii) ptSum += std::pow( (v_trans[ii]-dx/1.0e6) / (geo[ii]/2.0), 2.0 ); if(1.0 < ptSum ) return false; for(int ii = 0; ii < 3; ++ii) { if( (2.0*v_trans[ii]/geo[ii] < axisCutNeg_[ii]) || (2.0*v_trans[ii]/geo[ii] > axisCutPos_[ii]) ) return false; if( axisCutGlobal_[ii] >= 0.0 && (v_trans[ii] + geo[ii]/2.0) / geo[ii] >= axisCutGlobal_[ii]) return false; else if( axisCutGlobal_[ii] <= 0.0 && (v_trans[ii] - geo[ii]/2.0) / geo[ii] <= axisCutGlobal_[ii] ) return false; } return true; } bool hemiellipsoid::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { std::array<double,3> v_trans = RealSpace2ObjectSpace(v); // Do geo checks based on the the object oriented coordinates if(v_trans[0] > dx/1e6) return false; double ptSum = 0.0; for( int ii = 0; ii < ( geo[2] != 0.0 ? v_trans.size() : 2 ); ++ii) ptSum += std::pow( (v_trans[ii]-dx/1.0e6) / (geo[ii]/2.0), 2.0 ); if(1.0 < ptSum ) return false; return true; } bool tri_prism::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { std::array<double,3> v_trans = RealSpace2ObjectSpace(v); // If prism point is outside prism's length return false if( (v_trans[2] < -1.0*geo[3]/2.0 - dx*1e-6) || (v_trans[2] > geo[3]/2.0 + dx*1e-6) ) return false; // Is point within the triangle's cross-section? std::array<double,2> v_transTriFace = {v_trans[0], v_trans[1]}; std::array<double,3> baryCenCoords = cart2bary<double,3>(invVertMat_, v_transTriFace, d0_); // If Barycenteric coordinates are < 0 or > geoParam then they must be outside the cross-section for(int ii = 0; ii < 3; ++ii) if(baryCenCoords[ii] < -1e-13 || baryCenCoords[ii] > geo[ii]+1e-13) return false; // Sum barycenteric coords must = 1 if(std::abs( 1 - std::accumulate( baryCenCoords.begin(), baryCenCoords.end(), 0.0 ) ) > 1e-14 ) { std::cout << std::accumulate( baryCenCoords.begin(), baryCenCoords.end(), 0.0 ) << '\t' << d0_ << '\t' << v[0] << '\t' << v[1] << '\t' << v[2] << std::endl; throw std::logic_error("The sum of the boundary checks for a triangular base does not equal the determinant of the verticies, despite passing the checks. This is an error."); } return true; } bool tetrahedron::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { std::array<double, 4> baryCenCoords = cart2bary<double,4>(invVertMat_, v, d0_); // If Barycenteric coordinates are < 0 or > geoParam then they must be outside the cross-section for(int ii = 0; ii < 4; ++ii) if(baryCenCoords[ii] < -1e-6*dx|| (baryCenCoords[ii] + dx*1e-6) > geo[ii]) return false; // Sum barycenteric coords must = 1 if(std::abs( 1 - std::accumulate( baryCenCoords.begin(), baryCenCoords.end(), 0.0 ) ) > 1e-14 ) { std::cout << std::accumulate( baryCenCoords.begin(), baryCenCoords.end(), 0.0 ) << '\t' << d0_ << '\t' << v[0] << '\t' << v[1] << '\t' << v[2] << std::endl; throw std::logic_error("The sum of the boundary checks for a tetrahedron does not equal the determinant of the verticies, despite passing the checks. This is an error."); } return true; } bool cone::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { std::array<double,3> v_trans = RealSpace2ObjectSpace(v); // Do geo checks based on the the object oriented coordinates if( (v_trans[1] < -1.0*geo[1]/2.0 - dx*1e-6) || (v_trans[1] > geo[1]/2.0 + dx*1e-6) ) return false; else if( dist(std::array<double,3>( {{ v_trans[0], 0.0, v_trans[2] }} ), std::array<double,3>({{0,0,0}}) ) > std::pow(geo[0]/geo[2] * ( v_trans[2] - geo[1]/2.0 ), 2.0) ) return false; return true; } bool cylinder::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { std::array<double,3> v_trans = RealSpace2ObjectSpace(v); // Do geo checks based on the the object oriented coordinates if( (v_trans[1] < -1.0*geo[1]/2.0 - dx*1e-6) || (v_trans[1] > geo[1]/2.0 + dx*1e-6) ) return false; else if( dist(std::array<double,3>( {{ v_trans[0], 0.0, v_trans[2] }} ), std::array<double,3>({{0,0,0}}) ) > geo[0] + 1.0e-6*dx ) return false; return true; } bool ters_tip::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { std::array<double,3> v_trans = RealSpace2ObjectSpace(v); // Do geo checks based on the the object oriented coordinates if( dist(v_trans, radCen_) < geo[0]/2.0 ) return true; if( (v_trans[2] < geo[0] - geo[2]/2.0 - dx*1e-6) || (v_trans[2] > geo[1]/2.0 + dx*1e-6) ) return false; else if( ( std::pow( v_trans[0], 2.0 ) + std::pow( v_trans[1], 2.0 ) ) * std::pow( cos(geo[0]), 2.0 ) - std::pow( v_trans[2] * sin(geo[0]), 2.0) > dx*1e-6 ) return false; return true; } bool paraboloid::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { std::array<double,3> v_trans = RealSpace2ObjectSpace(v); // Do geo checks based on the the object oriented coordinates v_trans[1] += geo[2]/2.0; if(v_trans[1] > geo[2]) return false; else if( std::pow(v_trans[0]/geo[0], 2.0) + std::pow(v_trans[2]/geo[1], 2.0) > v_trans[1] ) return false; return true; } bool torus::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { std::array<double,3> v_trans = RealSpace2ObjectSpace(v); if( std::pow( std::sqrt( std::pow(v_trans[0], 2.0) + std::pow(v_trans[1], 2.0) ) - geo[0] , 2.0) > std::pow(geo[1],2.0) - std::pow(v_trans[2],2.0) ) return false; double phiPt = v_trans[0] !=0 ? std::atan(v_trans[1]/v_trans[0]) : v_trans[1]/std::abs(v_trans[1]) * M_PI / 2.0; if(v_trans[0] < 0) phiPt += M_PI; else if(v_trans[1] < 0) phiPt += 2.0*M_PI; if(phiPt < geo[2] || phiPt > geo[3]) return false; return true; } double Obj::dist(std::array<double,3> pt1, std::array<double,3> pt2) { double sum = 0; for(int cc = 0; cc < pt1.size(); cc ++) sum += std::pow((pt1[cc]-pt2[cc]),2); return sqrt(sum); } std::array<double, 3> sphere::findGradient(std::array<double,3> pt) { std::array<double,3> grad; // Move origin to object's center std::transform(pt.begin(), pt.end(), location_.begin(), grad.begin(), std::minus<double>() ); // Find the magnitude of the gradient vector (grad in this case since the radial and gradient vector are parallel) if(std::accumulate(grad.begin(), grad.end(), 0.0, vecMagAdd<double>() ) < 1e-20) grad = { 0.0, 0.0, 0.0 }; else normalize(grad); return grad; } std::array<double, 3> hemisphere::findGradient(std::array<double,3> pt) { std::array<double,3> grad; // Move origin to object's center std::transform(pt.begin(), pt.end(), location_.begin(), grad.begin(), std::minus<double>() ); // Find the magnitude of the gradient vector (grad in this case since the radial and gradient vector are parallel) if(std::accumulate(grad.begin(), grad.end(), 0.0, vecMagAdd<double>() ) < 1e-20) grad = { 0.0, 0.0, 0.0 }; else normalize(grad); return grad; } std::array<double, 3> ellipsoid::findGradient(std::array<double,3> pt) { std::array<double,3> grad = RealSpace2ObjectSpace(pt); // Find gradient by modifying the v_trans std::transform(grad.begin(), grad.end(), geoParam_.begin(), grad.begin(), [](double g, double geo){return g/std::pow(geo,2.0); } ); // Convert gradient back to real space return ObjectSpace2RealSpace(grad); } std::array<double, 3> hemiellipsoid::findGradient(std::array<double,3> pt) { std::array<double,3> grad = RealSpace2ObjectSpace(pt); // Find gradient by modifying the v_trans std::transform(grad.begin(), grad.end(), geoParam_.begin(), grad.begin(), [](double g, double geo){return g/std::pow(geo,2.0); } ); // Convert gradient back to real space return ObjectSpace2RealSpace(grad); } std::array<double, 3> cone::findGradient(std::array<double,3> pt) { std::array<double,3> v_trans = RealSpace2ObjectSpace(pt); // Find gradient by modifying the v_trans double z_prime = v_trans[2] + geoParam_[1]/2.0; double c = geoParam_[0]/geoParam_[2]; double z0 = z_prime * (1.0 + std::sqrt( (std::pow(v_trans[0],2.0) + std::pow(v_trans[1],2.0) ) / std::pow(c,2.0) ) ); std::array<double,3> grad = {{ 2.0*v_trans[0], 2.0*v_trans[1], -2.0*std::pow(c,2.0) * ( z_prime - z0 ) }}; if(std::abs(v_trans[2]) == std::abs(z0/2.0) ) grad = {{0, 0, -2.0*v_trans[2]/geoParam_[1] }}; // Convert gradient back to real space return ObjectSpace2RealSpace(grad); } std::array<double, 3> cylinder::findGradient(std::array<double,3> pt) { std::array<double,3> v_trans = RealSpace2ObjectSpace(pt); double r = std::sqrt( std::pow(v_trans[0], 2.0) + std::pow(v_trans[2], 2.0) ); double len = geoParam_[1] * (r / geoParam_[0] ); std::array<double,3> grad = {{ v_trans[0], 0.0, v_trans[2] }}; if(std::abs(v_trans[1]) >= len/2.0 ) grad = {{ 0.0, v_trans[1]/std::abs(v_trans[1]), 0.0 }}; return ObjectSpace2RealSpace(grad); } std::array<double, 3> block::findGradient(std::array<double,3> pt) { std::array<double,3> v_trans = RealSpace2ObjectSpace(pt); std::array<double,3> grad = {0.0,0.0,0.0}; std::array<double,3> ptRat; std::transform(v_trans.begin(), v_trans.end(), geoParam_.begin(), ptRat.begin(), std::divides<double>() ); int ptRatMax = idamax_(ptRat.size(), ptRat.data(), 1) - 1; for(int ii = 0; ii < 3; ++ii) if(ptRat[ii] == ptRat[ptRatMax]) grad[ ii ] = v_trans[ii] >=0 ? 1.0 : -1.0; return ObjectSpace2RealSpace(grad); } std::array<double, 3> rounded_block::findGradient(std::array<double,3> pt) { std::array<double,3> v_trans = RealSpace2ObjectSpace(pt); std::array<double,3> grad = {0.0,0.0,0.0}; std::array<double,3> ptRat; std::transform(v_trans.begin(), v_trans.end(), geoParam_.begin(), ptRat.begin(), std::divides<double>() ); int ptRatMax = idamax_(ptRat.size(), ptRat.data(), 1) - 1; double t = ptRat[ptRatMax]; bool atCorner = true; for(int ii = 0; ii < 3; ++ii) if(v_trans[ii] - t * (geoParam_[ii]-geoParam_[3]) <= 0) atCorner = false; if(atCorner) { std::array<double,3> absPt; std::transform(pt.begin(), pt.end(), absPt.begin(), [](double pt){return std::abs(pt);}); double cenPtDot = ddot_(3, absPt.data(), 1, curveCens_[0].data(), 1); double cenMag = std::accumulate(curveCens_[0].begin(), curveCens_[0].end(), 0.0, vecMagAdd<double>() ); double ptMag = std::accumulate(absPt.begin(), absPt.end(), 0.0, vecMagAdd<double>()); t = 1.0/ ( cenMag-std::pow(geoParam_[3],2.0) ) * ( std::pow(cenPtDot,2.0) - std::sqrt(std::pow(cenPtDot, 2.0) - ptMag*(cenMag-std::pow(geoParam_[3],2.0) ) ) ); std::transform(absPt.begin(), absPt.end(), curveCens_[0].begin(), grad.begin(), [=](double p, double cen){return p - t*cen;} ); std::transform(pt.begin(), pt.end(), grad.begin(), grad.begin(), [](double p, double grad){return grad*p/std::abs(p); } ); } else { for(int ii = 0; ii < 3; ++ii) if(ptRat[ii] == ptRat[ptRatMax]) grad[ ii ] = v_trans[ii] >=0 ? 1.0 : -1.0; } return ObjectSpace2RealSpace(grad); } std::array<double, 3> tri_prism::findGradient(std::array<double,3> pt) { std::array<double,3> v_trans = RealSpace2ObjectSpace(pt); std::array<double,2> v_transTriFace = {v_trans[0], v_trans[1]}; std::array<double,3> grad = {0.0,0.0,0.0}; double scalRat = std::abs(2*v_trans[2]/geoParam_[3]); if(scalRat > 0) { std::array<std::array<double, 2>, 3> scaledVertLocs_(vertLocs_); std::vector<double> invScalVertMat(9,1.0); for(int ii = 0; ii < 3; ++ii) { dscal_(2, scalRat, scaledVertLocs_[ii].begin(), 1); dcopy_(2, scaledVertLocs_[ii].begin(), 1, &invScalVertMat[ii], 3); } int info; std::vector<int>ivip(3, 0); dgetrf_(3, 3, invScalVertMat.data(), 3, ivip.data(), &info); double d0Scaled = getLUFactMatDet(invScalVertMat, ivip, 3); std::vector<double>work(9,0.0); dgetri_(3, invScalVertMat.data(), 3, ivip.data(), work.data(), work.size(), &info); std::array<double, 3> baryScaled = cart2bary<double,3>(invScalVertMat, v_transTriFace, d0Scaled); bool inTri = true; bool onEdge = false; for(int ii = 0; ii < 3; ++ii) { if( baryScaled[ii] < -1e-15 || baryScaled[ii] > geoParam_[ii]+1e-15 ) inTri = false; if( baryScaled[ii] == 0 || baryScaled[ii] == geoParam_[ii] ) onEdge = true; } // If the point is in the scaled triangle's cross section then it is on the cap face if(inTri) { grad = { 0.0, 0.0, (v_trans[2] >= 0 ? 1.0 : -1.0 ) } ; // If it's not on the edge then no need to calculate which triangle face is closest if(!onEdge) return ObjectSpace2RealSpace(grad); } } // Calculate the barycenteric coordinates std::array<double, 3> baryCenCoords = cart2bary<double,3>(invVertMat_, v_transTriFace, d0_); // Calculate the ratio from the base surface and truncated surace std::array<double, 3> baseRat; std::array<double, 3> truncRat; for(int ii = 0; ii < 3; ++ii) { baseRat[ii] = baryCenCoords[ii] / geoParam_[ii]; truncRat[ii] = ( geoParam_[ii] - baryCenCoords[ii] ) / geoParam_[ii]; } // Find the min distance to the base and truncated faces int indMinBaseRat = idamin_(baseRat.size(), baseRat.begin(), 1 ); int indMinTruncRat = idamin_(truncRat.size(), truncRat.begin(), 1 ); // Determine which of the two is closest and get it's distance int closestFace = ( truncRat[indMinTruncRat-1] < baseRat[indMinBaseRat-1] ) ? -1*indMinTruncRat : indMinBaseRat; double dist2ClosestFace = (closestFace < 0) ? truncRat[indMinTruncRat-1] : baseRat[indMinBaseRat-1]; // Collect all faces equidistant to the closest face std::vector<int> equiDistFaces; for(int ii = 0; ii < 3; ++ii) { // If both the truncated face and base face are equidistant give presidence to the base if(baseRat[ii] == dist2ClosestFace) equiDistFaces.push_back(ii+1); if(truncRat[ii] == dist2ClosestFace) equiDistFaces.push_back(-1*ii-1); } std::vector<std::vector<int>> activeVerts(equiDistFaces.size()); // Average over all faces for(int ff = 0; ff < equiDistFaces.size(); ++ff) { // Find the vertices needed to calculate the surface normal std::vector<int> activeVerts; for(int ii = 0; ii < 3; ++ii) { if( ii != std::abs(equiDistFaces[ff])-1 ) activeVerts.push_back(ii); } // Calculate the gradient for that face and add it to grad std::array<double, 3> tempGrad; double xSign = ( vertLocs_[ activeVerts[1] ][0]+vertLocs_[ activeVerts[0] ][0] )/2.0 - ( vertLocs_[ activeVerts[1] ][0]+vertLocs_[ activeVerts[0] ][0]+vertLocs_[closestFace][0] )/3.0; xSign /= -1.0*std::abs(xSign) * equiDistFaces[ff] / std::abs(equiDistFaces[ff]); double slopePerp = -1.0*(vertLocs_[ activeVerts[1] ][0]-vertLocs_[ activeVerts[0] ][0])/(vertLocs_[ activeVerts[1] ][1]-vertLocs_[ activeVerts[0] ][1]); if( std::abs(vertLocs_[ activeVerts[1] ][1]-vertLocs_[ activeVerts[0] ][1]) < 1e-14) tempGrad = { 0.0, xSign, 0.0 } ; else tempGrad = { xSign, xSign*slopePerp, 0.0 } ; normalize(tempGrad); std::transform(tempGrad.begin(), tempGrad.end(), grad.begin(), grad.begin(), std::plus<double>() ); } return ObjectSpace2RealSpace(grad); } std::array<double, 3> tetrahedron::findGradient(std::array<double,3> pt) { // Convert pt to barycentric coodrinates std::array<double, 4> baryCenCoords = cart2bary<double,4>(invVertMat_, pt, d0_); // Get the ratios from of face distance to the geo_params std::array<double, 4> truncRat; std::array<double, 4> baseRat; for(int ii = 0; ii < 4; ++ii) { baseRat[ii] = baryCenCoords[ii] / geoParam_[ii]; truncRat[ii] = ( geoParam_[ii] - baryCenCoords[ii] ) / geoParam_[ii]; } // Get the minimum distance to a base and truncated surface int indMinBaseDist = idamin_(4, baseRat.begin(), 1); int indMinTruncDist = idamin_(4, truncRat.begin(), 1 ); // Which is closer, and what is that distance int closestFace = ( truncRat[indMinTruncDist-1] < baseRat[indMinBaseDist-1] ) ? -1*indMinTruncDist : indMinBaseDist; double dist2ClosestFace = (closestFace < 0) ? truncRat[indMinTruncDist-1] : baseRat[indMinBaseDist-1]; // Find all faces equidistant to the closest face std::vector<int> equiDistFaces; for(int ii = 0; ii < 4; ++ii) { // If both the truncated face and base face are equidistant give presidence to the base if(baseRat[ii] == dist2ClosestFace) equiDistFaces.push_back(ii+1); if(truncRat[ii] == dist2ClosestFace) equiDistFaces.push_back(-1*ii-1); } std::array<double,3> grad = {0.0, 0.0, 0.0}; // Loop over all faces and add average their gradients for(int ff = 0; ff < equiDistFaces.size(); ++ff) { std::vector<int> activeVerts; // Find the vertices needed to calculate the surface normal in the correct order (https://math.stackexchange.com/questions/183030/given-a-tetrahedron-how-to-find-the-outward-surface-normals-for-each-side) for(int ii = 0; ii < 4; ++ii) { int index = ( static_cast<int>( std::pow( -1, std::abs(equiDistFaces[ff])-1 ) * ii) % 4 ) * static_cast<int>(equiDistFaces[ff] / std::abs(equiDistFaces[ff]) ); index += (index < 0) ? 4 : 0; if( index != std::abs(equiDistFaces[ff])-1 ) activeVerts.push_back(index); } // Calculate the gradient for that face and add it to grad std::array<double,3> v1; std::array<double,3> v2; std::transform(vertLocs_[activeVerts[1]].begin(), vertLocs_[activeVerts[1]].end(), vertLocs_[activeVerts[0]].begin(), v1.begin(), std::minus<double>()); std::transform(vertLocs_[activeVerts[2]].begin(), vertLocs_[activeVerts[2]].end(), vertLocs_[activeVerts[1]].begin(), v2.begin(), std::minus<double>()); std::array<double, 3> tempGrad = {{ v1[1]*v2[2]-v1[2]*v2[1], v1[2]*v2[0]-v1[0]*v2[2], v1[0]*v2[1]-v1[1]*v2[0] }}; normalize(tempGrad); std::transform(tempGrad.begin(), tempGrad.end(), grad.begin(), grad.begin(), std::plus<double>() ); } // If 0 return 0; otherwise normalize and return if( std::abs( std::accumulate(grad.begin(), grad.end(), 0.0, vecMagAdd<double>() ) ) < 1.0e-20 ) grad ={0.0, 0.0, 0.0}; else normalize(grad); return grad; } std::array<double, 3> ters_tip::findGradient(std::array<double,3> pt) { throw std::logic_error("Gradient is not defined for this object yet defined"); return std::array<double,3>({{0.0,0.0,0.0}}); } std::array<double, 3> paraboloid::findGradient(std::array<double,3> pt) { std::array<double,3> v_trans = RealSpace2ObjectSpace(pt); v_trans[1] += geoParam_[2]/2.0; std::array<double,3> grad = {2*v_trans[0]/std::pow(geoParam_[0],2.0), -1.0, 2.0*v_trans[2]/std::pow(geoParam_[2],2.0) }; normalize(grad); return grad; } std::array<double, 3> torus::findGradient(std::array<double,3> pt) { std::array<double,3> v_trans = RealSpace2ObjectSpace(pt); double radRing = std::sqrt( std::pow(v_trans[0], 2.0) + std::pow(v_trans[1], 2.0) ); double radRingTerm = (radRing - geoParam_[0]) / radRing; std::array<double,3> grad = { 2.0*v_trans[0] * radRingTerm, 2.0*v_trans[1] * radRingTerm, 2.0*v_trans[2]}; normalize(grad); return grad; }
49.394527
420
0.619266
Seideman-Group
9da3b09e1a93b0754c74478164e21ecc778a5ab5
3,174
cpp
C++
files/win32/MyProgram.cpp
keejelo/c_cpp_wrappers
d330999319effe88b6279fbc84de0db5a2da04fe
[ "MIT" ]
null
null
null
files/win32/MyProgram.cpp
keejelo/c_cpp_wrappers
d330999319effe88b6279fbc84de0db5a2da04fe
[ "MIT" ]
null
null
null
files/win32/MyProgram.cpp
keejelo/c_cpp_wrappers
d330999319effe88b6279fbc84de0db5a2da04fe
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------------------------- // ** MyProgram.cpp (template) //--------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------- // ** INCLUDE FILES //--------------------------------------------------------------------------------------------- #include "resource.h" #include "MyProgram.h" //--------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------- // ** VARIABLES //--------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------- // ** FUNCTIONS //--------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------- // ** OnCreate //--------------------------------------------------------------------------------------------- void OnCreate(HWND hWnd) { // ..add controls etc. }; //--------------------------------------------------------------------------------------------- // ** END: OnCreate //--------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------- // ** OnMouseButtonClick //--------------------------------------------------------------------------------------------- void OnMouseButtonClick(HWND hWnd, HWND hBtnCtrl) { // ** Check which button was clicked /* if (hBtnCtrl == hBtnOk) { // The OK button was clicked } else if (hBtnCtrl == hBtnCancel) { // The Cancel button was clicked } */ }; //--------------------------------------------------------------------------------------------- // ** END: OnMouseButtonClick //--------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------- // ** OnPaint //--------------------------------------------------------------------------------------------- void OnPaint(HWND hWnd) { }; //--------------------------------------------------------------------------------------------- // ** END: OnPaint //--------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------- // ** OnQuit //--------------------------------------------------------------------------------------------- void OnQuit() { }; //--------------------------------------------------------------------------------------------- // ** END: OnQuit //---------------------------------------------------------------------------------------------
37.341176
96
0.122873
keejelo
9da7e5986a644987832bbb833567d0a0ae347426
1,152
cpp
C++
Leetcode/String/sort-characters-by-frequency.cpp
susantabiswas/competitive_coding
49163ecdc81b68f5c1bd90988cc0dfac34ad5a31
[ "MIT" ]
2
2021-04-29T14:44:17.000Z
2021-10-01T17:33:22.000Z
Leetcode/String/sort-characters-by-frequency.cpp
adibyte95/competitive_coding
a6f084d71644606c21840875bad78d99f678a89d
[ "MIT" ]
null
null
null
Leetcode/String/sort-characters-by-frequency.cpp
adibyte95/competitive_coding
a6f084d71644606c21840875bad78d99f678a89d
[ "MIT" ]
1
2021-10-01T17:33:29.000Z
2021-10-01T17:33:29.000Z
/* https://leetcode.com/problems/sort-characters-by-frequency/ TC: O(N), SC: O(1) Sorting 256 chars is constant + linear traversal */ class Solution { public: string frequencySort(string s) { // (char, frequency) vector<pair<int, int>> char_freq(256); for(int i = 0; i < char_freq.size(); i++) { char_freq[i].first = i; char_freq[i].second = 0; } // for each char, store its frequency for(const char &c: s) char_freq[c].second += 1; // sort the chars based on their frequencies sort(char_freq.begin(), char_freq.end(), [](const pair<int, int>& a, const pair<int, int>& b) { return a.second > b.second; }); string result; for(int i = 0; i < char_freq.size(); i++) // if current char is present in string if(char_freq[i].second) { char c = char_freq[i].first; // add the chars while(char_freq[i].second--) result += c; } return result; } };
29.538462
67
0.493924
susantabiswas
9dabe1d4d4d94f67d267e0d54f58eb76c97c761c
536
cpp
C++
DecodeWays.cpp
yplusplus/LeetCode
122bd31b291af1e97ee4e9349a8e65bba6e04c96
[ "MIT" ]
3
2017-11-27T03:01:50.000Z
2021-03-13T08:14:00.000Z
DecodeWays.cpp
yplusplus/LeetCode
122bd31b291af1e97ee4e9349a8e65bba6e04c96
[ "MIT" ]
null
null
null
DecodeWays.cpp
yplusplus/LeetCode
122bd31b291af1e97ee4e9349a8e65bba6e04c96
[ "MIT" ]
null
null
null
class Solution { public: bool check(char a, char b) { if (a == '1') return true; if (a == '2' && b <= '6') return true; return false; } int numDecodings(string s) { if (s.length() == 0) return 0; vector<int> dp(s.length() + 1, 0); dp[0] = 1; for (int i = 1; i <= s.length(); i++) { if (s[i - 1] != '0') dp[i] += dp[i - 1]; if (i >= 2 && check(s[i - 2], s[i - 1])) dp[i] += dp[i - 2]; } return dp.back(); } };
28.210526
52
0.384328
yplusplus
9db771ef7a346888dc281b44f5ba4945dd06e884
410
hpp
C++
Oscillators/SinWave.hpp
jamestiller/Rain
1e55d90065be7ada9455029ad735dd285e7d2266
[ "Zlib" ]
1
2016-04-05T12:20:47.000Z
2016-04-05T12:20:47.000Z
Oscillators/SinWave.hpp
jamestiller/Rain
1e55d90065be7ada9455029ad735dd285e7d2266
[ "Zlib" ]
null
null
null
Oscillators/SinWave.hpp
jamestiller/Rain
1e55d90065be7ada9455029ad735dd285e7d2266
[ "Zlib" ]
null
null
null
// // SinWave.hpp // Rain // // Created by James Tiller on 2/25/16. // // #ifndef SinWave_hpp #define SinWave_hpp #include <stdio.h> #include "IWave.hpp" class SinWave : public IWave { public: friend class Oscillator; protected: SinWave() : IWave() { updateIncrement(); }; virtual void generate(double* buffer, int nFrames); virtual double nextSample(); }; #endif /* SinWave_hpp */
14.642857
55
0.656098
jamestiller
9dbc3fea2fb7076bf8259d701c1e6dfb5a07ef6a
1,816
cpp
C++
EditWidgets/CheckBox.cpp
sielicki/PothosFlow
61487651f3718fc75fd2da6ef36e90c8537c8dd3
[ "BSL-1.0" ]
null
null
null
EditWidgets/CheckBox.cpp
sielicki/PothosFlow
61487651f3718fc75fd2da6ef36e90c8537c8dd3
[ "BSL-1.0" ]
null
null
null
EditWidgets/CheckBox.cpp
sielicki/PothosFlow
61487651f3718fc75fd2da6ef36e90c8537c8dd3
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2017-2017 Josh Blum // SPDX-License-Identifier: BSL-1.0 #include <Pothos/Plugin.hpp> #include <QJsonObject> #include <QJsonArray> #include <QCheckBox> /*********************************************************************** * Check box with labels **********************************************************************/ class CheckBox : public QCheckBox { Q_OBJECT public: CheckBox(QWidget *parent, const QString &onText, const QString &offText): QCheckBox(parent), _onText(onText), _offText(offText) { connect(this, SIGNAL(toggled(bool)), this, SLOT(handleToggled(bool))); } public slots: QString value(void) const { return this->isChecked()?"true":"false"; } void setValue(const QString &s) { this->setChecked(s=="true"); this->updateText(s=="true"); } signals: void commitRequested(void); void widgetChanged(void); void entryChanged(void); private slots: void handleToggled(const bool checked) { this->updateText(checked); emit this->entryChanged(); } private: void updateText(const bool checked) { this->setText(checked?_onText:_offText); } const QString _onText; const QString _offText; }; /*********************************************************************** * Factory function and registration **********************************************************************/ static QWidget *makeCheckBox(const QJsonArray &, const QJsonObject &kwargs, QWidget *parent) { return new CheckBox(parent, kwargs["on"].toString(), kwargs["off"].toString()); } pothos_static_block(registerCheckBox) { Pothos::PluginRegistry::add("/flow/EntryWidgets/CheckBox", Pothos::Callable(&makeCheckBox)); } #include "CheckBox.moc"
25.222222
96
0.558921
sielicki
9dc3596075ad8409b242741de5bd33f0a24724ef
3,164
hpp
C++
myvector.hpp
mino2357/Hello_OpenSiv3D
c12cdc08da63d5d3d4ab377e8aa32d69167ed0eb
[ "MIT" ]
null
null
null
myvector.hpp
mino2357/Hello_OpenSiv3D
c12cdc08da63d5d3d4ab377e8aa32d69167ed0eb
[ "MIT" ]
1
2017-07-01T15:26:42.000Z
2018-04-23T08:25:49.000Z
myvector.hpp
mino2357/Hello_OpenSiv3D
c12cdc08da63d5d3d4ab377e8aa32d69167ed0eb
[ "MIT" ]
null
null
null
#include <iostream> #include <limits> #include <iomanip> #include <cmath> namespace mino2357{ template<typename T = double> class vector{ private: T componentX; T componentY; public: vector(T x, T y) noexcept : componentX(x), componentY(y) {} vector() noexcept : vector{T{}, T{}} {} inline void setComponetX(T) noexcept; inline void setComponetY(T) noexcept; inline T getComponentX() const noexcept; inline T getComponentY() const noexcept; inline vector& operator=( const vector<T>&) noexcept; inline vector& operator+=(const vector<T>&) noexcept; inline vector& operator-=(const vector<T>&) noexcept; inline T norm() noexcept; inline void printPosition() noexcept; }; template <typename T> inline void vector<T>::setComponetX(T x) noexcept { componentX = x; } template <typename T> inline void vector<T>::setComponetY(T y) noexcept { componentY = y; } template <typename T> inline T vector<T>::getComponentX() const noexcept { return this->componentX; } template <typename T> inline T vector<T>::getComponentY() const noexcept { return this->componentY; } template <typename T> inline void vector<T>::printPosition() noexcept{ std::cout << std::fixed << std::setprecision(std::numeric_limits<double>::digits10 + 1); std::cout << componentX << " " << componentY << std::endl; } template <typename T> inline vector<T>& vector<T>::operator=(const vector<T>& v) noexcept { this->componentX = v.getComponentX(); this->componentY = v.getComponentY(); return *this; } template <typename T> inline vector<T>& vector<T>::operator+=(const vector<T>& v) noexcept { this->componentX += v.getComponentX(); this->componentY += v.getComponentY(); return *this; } template <typename T> inline vector<T>& vector<T>::operator-=(const vector<T>& v) noexcept { this->componentX -= v.getComponentX(); this->componentY -= v.getComponentY(); return *this; } template <typename T> inline T vector<T>::norm() noexcept { return std::sqrt(componentX * componentX + componentY * componentY); } template <typename T> inline vector<T> operator+(const vector<T>& a, const vector<T>& b) noexcept { return vector<T>{ a.getComponentX() + b.getComponentX(), a.getComponentY() + b.getComponentY(), }; } template <typename T> inline vector<T> operator-(const vector<T>& a, const vector<T>& b) noexcept { return vector<T>{ a.getComponentX() - b.getComponentX(), a.getComponentY() - b.getComponentY(), }; } template <typename T> inline T operator*(const vector<T>& a, const vector<T>& b) noexcept { return a.getComponentX() * b.getComponentX() + a.getComponentY() * b.getComponentY(); } }
29.849057
96
0.581858
mino2357
9dc4bb85ccbfb05f0735589c059e53852a1be17a
6,901
hpp
C++
include/boost/cgi/cgi/request_service.hpp
Sil3ntStorm/libtelegram
a0c52ba4aac5519a3031dba506ad4a64cd8fca83
[ "MIT" ]
118
2016-10-02T10:49:02.000Z
2022-03-23T14:32:05.000Z
include/boost/cgi/cgi/request_service.hpp
Sil3ntStorm/libtelegram
a0c52ba4aac5519a3031dba506ad4a64cd8fca83
[ "MIT" ]
21
2017-04-21T13:34:36.000Z
2021-12-08T17:00:40.000Z
include/boost/cgi/cgi/request_service.hpp
Sil3ntStorm/libtelegram
a0c52ba4aac5519a3031dba506ad4a64cd8fca83
[ "MIT" ]
35
2016-06-08T15:31:03.000Z
2022-03-23T16:43:28.000Z
// -- cgi_service_impl.hpp -- // // Copyright (c) Darren Garvey 2007-2009. // 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 CGI_CGI_SERVICE_IMPL_HPP_INCLUDED__ #define CGI_CGI_SERVICE_IMPL_HPP_INCLUDED__ #include "boost/cgi/detail/push_options.hpp" #include "boost/cgi/common/tags.hpp" #include "boost/cgi/common/map.hpp" #include "boost/cgi/import/io_service.hpp" #include "boost/cgi/detail/service_base.hpp" #include "boost/cgi/detail/extract_params.hpp" #include "boost/cgi/connections/async_stdio.hpp" #include <boost/bind.hpp> #include <boost/assert.hpp> #include <boost/regex.hpp> #include <boost/tokenizer.hpp> #include <boost/lexical_cast.hpp> #include <boost/version.hpp> #include <boost/system/error_code.hpp> #include <boost/algorithm/string/find.hpp> /////////////////////////////////////////////////////////// #include "boost/cgi/common/map.hpp" #include "boost/cgi/basic_client.hpp" #include "boost/cgi/common/is_async.hpp" #include "boost/cgi/common/role_type.hpp" #include "boost/cgi/common/form_part.hpp" #include "boost/cgi/detail/throw_error.hpp" #include "boost/cgi/common/form_parser.hpp" #include "boost/cgi/common/request_base.hpp" #include "boost/cgi/common/parse_options.hpp" #include "boost/cgi/common/request_status.hpp" #include "boost/cgi/connections/async_stdio.hpp" #include "boost/cgi/detail/extract_params.hpp" #include "boost/cgi/detail/save_environment.hpp" BOOST_CGI_NAMESPACE_BEGIN class cgi_request_service : public common::request_base<common::tags::cgi> , public detail::service_base<cgi_request_service> { public: typedef common::tags::cgi protocol_type; typedef cgi_service protocol_service_type; typedef cgi_request_service self_type; struct implementation_type : base_type::impl_base { implementation_type() : stdin_data_read_(false) , stdin_bytes_left_(-1) { } protocol_service_type* service_; conn_ptr& connection() { return connection_; } bool stdin_data_read_; std::size_t stdin_bytes_left_; conn_ptr connection_; }; template<typename Service> struct callback_functor { callback_functor(implementation_type& impl, Service* service) : impl_(impl) , service_(service) { } std::size_t operator()(boost::system::error_code& ec) { return service_->read_some(impl_, ec); } private: implementation_type& impl_; Service* service_; }; cgi_request_service(common::io_context& ios) : detail::service_base<cgi_request_service>(ios) { } void construct(implementation_type& impl) { impl.client_.set_connection( connection_type::create(this->get_io_context()) ); } void shutdown_service() { } void clear(implementation_type& impl) { } int request_id(implementation_type& impl) { return 1; } /// Close the request. int close(implementation_type& impl, common::http::status_code http_s = http::ok , int program_status = 0) { int s(0); boost::system::error_code ec; s = close(impl, http_s, program_status, ec); detail::throw_error(ec); return s; } /// Close the request. int close(implementation_type& impl, common::http::status_code http_s , int program_status, boost::system::error_code& ec) { status(impl, common::closed); impl.http_status() = http_s; impl.all_done_ = true; return program_status; } /// Synchronously read/parse the request data boost::system::error_code& load(implementation_type& impl, common::parse_options parse_opts , boost::system::error_code& ec) { if (parse_opts & common::parse_env) { if (read_env_vars(impl, ec)) // returns an error_code return ec; } std::string const& cl = env_vars(impl.vars_)["CONTENT_LENGTH"]; impl.bytes_left_ = cl.empty() ? 0 : boost::lexical_cast<std::size_t>(cl); impl.client_.bytes_left() = impl.bytes_left_; std::string const& request_method = env_vars(impl.vars_)["REQUEST_METHOD"]; if ((request_method == "GET" || request_method == "HEAD") && parse_opts > common::parse_env && parse_opts & common::parse_get_only) { parse_get_vars(impl, ec); } else if ((request_method == "POST" || request_method == "PUT") && (parse_opts & common::parse_post_only)) { parse_post_vars(impl, ec); } if (ec) return ec; if (parse_opts & common::parse_cookie_only) { if (parse_cookie_vars(impl, "HTTP_COOKIE", ec)) // returns an error_code return ec; } status(impl, common::loaded); return ec; } /// CGI is always a responser. common::role_type role(implementation_type const& impl) const { return common::responder; } std::size_t read_some(implementation_type& impl, boost::system::error_code& ec) { return impl.client_.read_some(impl.prepare(64), ec); } protected: /// Read the environment variables into an internal map. template<typename RequestImpl> boost::system::error_code read_env_vars(RequestImpl& impl, boost::system::error_code& ec) { // Only call this once. if (!(status(impl) & common::env_read)) { detail::save_environment(env_vars(impl.vars_)); status(impl, (common::request_status)(status(impl) | common::env_read)); } return ec; } /// Read and parse the cgi POST meta variables (greedily) template<typename RequestImpl> boost::system::error_code parse_post_vars(RequestImpl& impl, boost::system::error_code& ec) { // **FIXME** use callback_functor<> in form_parser instead. std::size_t& bytes_left (impl.client_.bytes_left_); std::size_t bytes_read (0); do { bytes_read = read_some(impl, ec); bytes_left -= bytes_read; } while (!ec && bytes_left); // Return an error, except ignore EOF, as this is expected. if (ec) { if (ec == boost::cgi::common::error::eof) ec = boost::system::error_code(); else return ec; } return base_type::parse_post_vars( impl, callback_functor<self_type>(impl, this), ec ); } }; BOOST_CGI_NAMESPACE_END #include "boost/cgi/detail/pop_options.hpp" #endif // CGI_CGI_SERVICE_IMPL_HPP_INCLUDED__
28.167347
80
0.62759
Sil3ntStorm
e3853519478efa481dbaf3ad6adca8f24e6cb673
594
cpp
C++
#1077 Kuchiguse.cpp
ZachVec/PAT-Advanced
52ba5989c095ddbee3c297e82a4b3d0d2e0cd449
[ "MIT" ]
1
2021-12-26T08:34:47.000Z
2021-12-26T08:34:47.000Z
#1077 Kuchiguse.cpp
ZachVec/PAT-Advanced
52ba5989c095ddbee3c297e82a4b3d0d2e0cd449
[ "MIT" ]
null
null
null
#1077 Kuchiguse.cpp
ZachVec/PAT-Advanced
52ba5989c095ddbee3c297e82a4b3d0d2e0cd449
[ "MIT" ]
null
null
null
#include <iostream> #include <cstring> using namespace std; constexpr size_t MAX = 258; int main() { size_t n, orilen, len; char str[MAX], suffix[MAX]; if(!scanf("%zu\n", &n)) return 0; cin.getline(suffix, MAX); orilen = len = strlen(suffix); for(size_t i = 1, slen, j; i < n; ++i, len = j) { cin.getline(str, MAX); slen = strlen(str); for(j = 0; j < len && j < slen; ++j) { if(suffix[orilen - j - 1] != str[slen - j - 1]) break; } } if(len) printf("%s\n", suffix + orilen - len); else printf("nai\n"); return 0; }
25.826087
66
0.526936
ZachVec
e385465fd6aa11da88d1d249aa6dc3b258d41b69
2,145
hpp
C++
Habitat.hpp
ambotaku/Urknall-lite
79d812c0c895294699d9857415d3850f29f1b8a5
[ "MIT" ]
1
2022-03-07T20:33:13.000Z
2022-03-07T20:33:13.000Z
Habitat.hpp
ambotaku/Urknall-lite
79d812c0c895294699d9857415d3850f29f1b8a5
[ "MIT" ]
null
null
null
Habitat.hpp
ambotaku/Urknall-lite
79d812c0c895294699d9857415d3850f29f1b8a5
[ "MIT" ]
null
null
null
#ifndef _HABITAT_H_ #define _HABITAT_H_ #include "GFX.hpp" class Habitat : public GFX { public: /** * @brief create lifegame habitat (playfield) * * @param devAddr device i2c address. * @param size oled display size (W128xH64 or W128xH32) * @param i2c i2c instance */ Habitat(uint16_t const devAddr, Size size, i2c_inst_t * i2c); /* * @brief fill display with random pixels * @param seed seed for random generator * @param density divisor limiting start pixel count */ void randomFill(uint seed=12345, uint density=32); /** * @brief build next habitat generation */ void nextGen(); #ifdef EXPORT_GENERATION #include "base64.hpp" /* * export last rendered buffer as Base64 string */ std::basic_string<unsigned char> exportGeneration() { return base64::encode(readBuffer, bufferSize()); } #endif private: // return buffersize needed uint32_t bufferSize() { return width * height / 8; } // copy of current habitat for nondestructive analysis unsigned char * readBuffer; uint generation; // generation counter /* * @brief check pixel's neighborhood (2-3 pixels needed to survive) * param x horizontal pixel position * param y vertical pixel position * @return true if neighbor pixel is not set */ bool isEmptyPixel(int16_t x, int16_t y); /* * @brief align neighbor's horizontal offset (wrapping around) * pos horizontal position of test pixel * offset -1 for left, +1 for right neighbor * @return aligned x */ int8_t offsetWidth(int8_t pos, int8_t offset); /* * @brief calculate neighbor's vertical offset * pos vertical position of test pixel * offset -1 for upper, +1 for lower neighbor * @return aligned y */ int8_t offsetHeight(int8_t pos, int8_t offset); /* * @brief check pixel's complete neighborhood * @param x horizontal pixel position * @param y vertical pixel position * @return neighbor count */ uint8_t checkCell(uint8_t x, uint8_t y); }; #endif
25.843373
71
0.649883
ambotaku
e387ee6d08bbad2a7ed33e7add5b35dfb9ed8375
10,977
hpp
C++
filter/bloom_filter.hpp
yuchen1024/Kunlun
f1a4a6a1efcb81905df4f0c3ffe5e863fa0dfacf
[ "MIT" ]
33
2021-08-29T00:19:14.000Z
2022-03-30T02:40:36.000Z
filter/bloom_filter.hpp
yuchen1024/Kunlun
f1a4a6a1efcb81905df4f0c3ffe5e863fa0dfacf
[ "MIT" ]
null
null
null
filter/bloom_filter.hpp
yuchen1024/Kunlun
f1a4a6a1efcb81905df4f0c3ffe5e863fa0dfacf
[ "MIT" ]
3
2021-09-09T11:34:35.000Z
2022-01-12T11:10:05.000Z
/* ** Modified from https://github.com/ArashPartow/bloom ** (1) simplify the design ** (2) add serialize/deserialize interfaces */ #ifndef KUNLUN_BLOOM_FILTER_HPP #define KUNLUN_BLOOM_FILTER_HPP #include "../include/std.inc" #include "../crypto/ec_point.hpp" #include "../utility/murmurhash3.hpp" #include "../utility/print.hpp" //00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000 static const uint8_t bit_mask[8] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80}; // selection of keyed hash for bloom filter #define FastKeyedHash LiteMurmurHash // an alternative choice is MurmurHash3 /* Note:A distinct hash function need not be implementation-wise distinct. In the current implementation "seeding" a common hash function with different values seems to be adequate. */ std::vector<uint32_t> GenUniqueSaltVector(size_t hash_num, uint32_t random_seed){ const size_t predefined_salt_num = 128; static const uint32_t predefined_salt[predefined_salt_num] = { 0xAAAAAAAA, 0x55555555, 0x33333333, 0xCCCCCCCC, 0x66666666, 0x99999999, 0xB5B5B5B5, 0x4B4B4B4B, 0xAA55AA55, 0x55335533, 0x33CC33CC, 0xCC66CC66, 0x66996699, 0x99B599B5, 0xB54BB54B, 0x4BAA4BAA, 0xAA33AA33, 0x55CC55CC, 0x33663366, 0xCC99CC99, 0x66B566B5, 0x994B994B, 0xB5AAB5AA, 0xAAAAAA33, 0x555555CC, 0x33333366, 0xCCCCCC99, 0x666666B5, 0x9999994B, 0xB5B5B5AA, 0xFFFFFFFF, 0xFFFF0000, 0xB823D5EB, 0xC1191CDF, 0xF623AEB3, 0xDB58499F, 0xC8D42E70, 0xB173F616, 0xA91A5967, 0xDA427D63, 0xB1E8A2EA, 0xF6C0D155, 0x4909FEA3, 0xA68CC6A7, 0xC395E782, 0xA26057EB, 0x0CD5DA28, 0x467C5492, 0xF15E6982, 0x61C6FAD3, 0x9615E352, 0x6E9E355A, 0x689B563E, 0x0C9831A8, 0x6753C18B, 0xA622689B, 0x8CA63C47, 0x42CC2884, 0x8E89919B, 0x6EDBD7D3, 0x15B6796C, 0x1D6FDFE4, 0x63FF9092, 0xE7401432, 0xEFFE9412, 0xAEAEDF79, 0x9F245A31, 0x83C136FC, 0xC3DA4A8C, 0xA5112C8C, 0x5271F491, 0x9A948DAB, 0xCEE59A8D, 0xB5F525AB, 0x59D13217, 0x24E7C331, 0x697C2103, 0x84B0A460, 0x86156DA9, 0xAEF2AC68, 0x23243DA5, 0x3F649643, 0x5FA495A8, 0x67710DF8, 0x9A6C499E, 0xDCFB0227, 0x46A43433, 0x1832B07A, 0xC46AFF3C, 0xB9C8FFF0, 0xC9500467, 0x34431BDF, 0xB652432B, 0xE367F12B, 0x427F4C1B, 0x224C006E, 0x2E7E5A89, 0x96F99AA5, 0x0BEB452A, 0x2FD87C39, 0x74B2E1FB, 0x222EFD24, 0xF357F60C, 0x440FCB1E, 0x8BBE030F, 0x6704DC29, 0x1144D12F, 0x948B1355, 0x6D8FD7E9, 0x1C11A014, 0xADD1592F, 0xFB3C712E, 0xFC77642F, 0xF9C4CE8C, 0x31312FB9, 0x08B0DD79, 0x318FA6E7, 0xC040D23D, 0xC0589AA7, 0x0CA5C075, 0xF874B172, 0x0CF914D5, 0x784D3280, 0x4E8CFEBC, 0xC569F575, 0xCDB2A091, 0x2CC016B4, 0x5C5F4421}; std::vector<uint32_t> vec_salt; if (hash_num <= predefined_salt_num){ std::copy(predefined_salt, predefined_salt + hash_num, std::back_inserter(vec_salt)); // integrate the user defined random seed to allow for the generation of unique bloom filter instances. for (auto i = 0; i < hash_num; i++){ vec_salt[i] = vec_salt[i] * vec_salt[(i+3) % vec_salt.size()] + random_seed; } } else{ std::copy(predefined_salt, predefined_salt + predefined_salt_num, std::back_inserter(vec_salt)); srand(random_seed); while (vec_salt.size() < hash_num){ uint32_t current_salt = rand() * rand(); if (0 == current_salt) continue; if (vec_salt.end() == std::find(vec_salt.begin(), vec_salt.end(), current_salt)){ vec_salt.emplace_back(current_salt); } } } return vec_salt; } class BloomFilter{ public: uint32_t hash_num; // number of keyed hash functions std::vector<uint32_t> vec_salt; // to change it uint64_t, you should also modify the range of hash uint32_t table_size; // m std::vector<uint8_t> bit_table; size_t projected_element_num; // n uint32_t random_seed; //double desired_false_positive_probability; size_t inserted_element_num; /* find the number of hash functions and minimum amount of storage bits required to construct a bloom filter consistent with the user defined false positive probability and estimated element insertion num */ BloomFilter() {}; BloomFilter(size_t projected_element_num, double desired_false_positive_probability) { hash_num = static_cast<size_t>(-log2(desired_false_positive_probability)); random_seed = static_cast<uint32_t>(0xA5A5A5A55A5A5A5A * 0xA5A5A5A5 + 1); vec_salt = GenUniqueSaltVector(hash_num, random_seed); table_size = static_cast<uint32_t>(projected_element_num * (-1.44 * log2(desired_false_positive_probability))); bit_table.resize(table_size/8, static_cast<uint8_t>(0x00)); // naive implementation inserted_element_num = 0; } ~BloomFilter() {}; size_t ObjectSize() { // hash_num + random_seed + table_size + table_content return 3 * sizeof(uint32_t) + table_size/8; } inline void PlainInsert(const void* input, size_t LEN) { size_t bit_index = 0; for (auto i = 0; i < hash_num; i++){ bit_index = FastKeyedHash(vec_salt[i], input, LEN) % table_size; //bit_table[bit_index / 8] |= bit_mask[bit_index % 8]; // naive implementation bit_table[bit_index >> 3] |= bit_mask[bit_index & 0x07]; // more efficient implementation } inserted_element_num++; } template <typename ElementType> // Note: T must be a C++ POD type. inline void Insert(const ElementType& element) { PlainInsert(&element, sizeof(ElementType)); } inline void Insert(const std::string& str) { PlainInsert(str.data(), str.size()); } /* ** You can insert any custom-type data you like as below */ inline void Insert(const ECPoint &A) { unsigned char buffer[POINT_BYTE_LEN]; EC_POINT_point2oct(group, A.point_ptr, POINT_CONVERSION_COMPRESSED, buffer, POINT_BYTE_LEN, nullptr); PlainInsert(buffer, POINT_BYTE_LEN); } inline void Insert(const std::vector<ECPoint> &vec_A) { size_t num = vec_A.size(); unsigned char *buffer = new unsigned char[num*POINT_BYTE_LEN]; for(auto i = 0; i < num; i++){ EC_POINT_point2oct(group, vec_A[i].point_ptr, POINT_CONVERSION_COMPRESSED, buffer+i*POINT_BYTE_LEN, POINT_BYTE_LEN, nullptr); PlainInsert(buffer+i*POINT_BYTE_LEN, POINT_BYTE_LEN); } delete[] buffer; } template <typename InputIterator> inline void Insert(const InputIterator begin, const InputIterator end) { InputIterator itr = begin; while (end != itr) { Insert(*(itr++)); } } template <class T, class Allocator, template <class,class> class Container> inline void Insert(Container<T, Allocator>& container) { #ifdef OMP #pragma omp parallel for #endif for(auto i = 0; i < container.size(); i++) Insert(container[i]); } inline bool PlainContain(const void* input, size_t LEN) const { size_t bit_index = 0; size_t local_bit_index = 0; for(auto i = 0; i < vec_salt.size(); i++) { bit_index = FastKeyedHash(vec_salt[i], input, LEN) % table_size; local_bit_index = bit_index & 0x07; if ((bit_table[bit_index >> 3] & bit_mask[local_bit_index]) != bit_mask[local_bit_index]) return false; } return true; } template <typename ElementType> inline bool Contain(const ElementType& element) const { return PlainContain(&element, sizeof(ElementType)); } inline bool Contain(const std::string& str) const { return PlainContain(str.data(), str.size()); } inline bool Contain(const ECPoint& A) const { unsigned char buffer[POINT_BYTE_LEN]; EC_POINT_point2oct(group, A.point_ptr, POINT_CONVERSION_COMPRESSED, buffer, POINT_BYTE_LEN, nullptr); return PlainContain(buffer, POINT_BYTE_LEN); } inline void Clear() { std::fill(bit_table.begin(), bit_table.end(), static_cast<uint8_t>(0x00)); inserted_element_num = 0; } inline bool WriteObject(std::string file_name) { std::ofstream fout; fout.open(file_name, std::ios::binary); if(!fout){ std::cerr << file_name << " open error" << std::endl; return false; } fout.write(reinterpret_cast<char *>(&hash_num), 8); fout.write(reinterpret_cast<char *>(&random_seed), 8); fout.write(reinterpret_cast<char *>(&table_size), 8); fout.write(reinterpret_cast<char *>(bit_table.data()), table_size/8); fout.close(); #ifdef DEBUG std::cout << "'" <<file_name << "' size = " << ObjectSize() << " bytes" << std::endl; #endif return true; } inline bool ReadObject(std::string file_name) { std::ifstream fin; fin.open(file_name, std::ios::binary); if(!fin){ std::cerr << file_name << " open error" << std::endl; return false; } fin.read(reinterpret_cast<char *>(&hash_num), sizeof(hash_num)); fin.read(reinterpret_cast<char *>(&random_seed), sizeof(random_seed)); vec_salt = GenUniqueSaltVector(hash_num, random_seed); fin.read(reinterpret_cast<char *>(&table_size), sizeof(table_size)); bit_table.resize(table_size/8, static_cast<uint8_t>(0x00)); fin.read(reinterpret_cast<char *>(bit_table.data()), table_size/8); return true; } inline bool WriteObject(char* buffer) { if(buffer == nullptr){ std::cerr << "allocate memory for bloom filter fails" << std::endl; return false; } memcpy(buffer, &hash_num, sizeof(uint32_t)); memcpy(buffer+ sizeof(uint32_t), &random_seed, sizeof(uint32_t)); memcpy(buffer+2*sizeof(uint32_t), &table_size, sizeof(uint32_t)); memcpy(buffer+3*sizeof(uint32_t), bit_table.data(), table_size/8); return true; } inline bool ReadObject(char* buffer) { if(buffer == nullptr){ std::cerr << "allocate memory for bloom filter fails" << std::endl; return false; } memcpy(&hash_num, buffer, sizeof(uint32_t)); memcpy(&random_seed, buffer+sizeof(uint32_t), sizeof(uint32_t)); vec_salt = GenUniqueSaltVector(hash_num, random_seed); memcpy(&table_size, buffer+2*sizeof(uint32_t), sizeof(uint32_t)); bit_table.resize(table_size/8, static_cast<uint8_t>(0x00)); memcpy(bit_table.data(), buffer+3*sizeof(uint32_t), table_size/8); return true; } void PrintInfo() const{ PrintSplitLine('-'); std::cout << "BloomFilter Status:" << std::endl; std::cout << "inserted element num = " << inserted_element_num << std::endl; std::cout << "hashtable size = " << (bit_table.size() >> 10) << " KB\n" << std::endl; std::cout << "bits per element = " << double(bit_table.size()) * 8 / inserted_element_num << std::endl; PrintSplitLine('-'); } }; #endif
36.959596
117
0.67277
yuchen1024
e389ef611cb456374037d099a45ff7cbc55dea6f
9,590
cpp
C++
src/Lib/rfc3550/RtpSessionBase.cpp
miseri/rtp_plus_plus
244ddd86f40f15247dd39ae7f9283114c2ef03a2
[ "BSD-3-Clause" ]
1
2021-07-14T08:15:05.000Z
2021-07-14T08:15:05.000Z
src/Lib/rfc3550/RtpSessionBase.cpp
7956968/rtp_plus_plus
244ddd86f40f15247dd39ae7f9283114c2ef03a2
[ "BSD-3-Clause" ]
null
null
null
src/Lib/rfc3550/RtpSessionBase.cpp
7956968/rtp_plus_plus
244ddd86f40f15247dd39ae7f9283114c2ef03a2
[ "BSD-3-Clause" ]
2
2021-07-14T08:15:02.000Z
2021-07-14T08:56:10.000Z
#include "CorePch.h" #include <rtp++/rfc3550/RtpSessionBase.h> #include <boost/exception/all.hpp> #include <rtp++/rfc3550/RtcpPacketBase.h> #include <rtp++/util/ApplicationParameters.h> #ifndef EXIT_ON_TRUE #define EXIT_ON_TRUE(condition, log_message) if ((condition)){\ LOG(WARNING) << log_message;return false;} #endif namespace rfc3550 { RtpSessionBase::RtpSessionBase(const RtpSessionParameters& parameters, const GenericParameters& applicationParameters) :m_parameters(parameters), m_applicationParameters(applicationParameters), m_state(SS_STOPPED), m_uiByeSentCount(0) { } RtpSessionBase::~RtpSessionBase() { } bool RtpSessionBase::initialise() { try { m_state = SS_STOPPED; // create components m_vPayloadPacketisers = createPayloadPacketisers(m_parameters, m_applicationParameters); if (m_vPayloadPacketisers.empty()) { // create default packetiser LOG(WARNING) << "Unable to create suitable packetiser, creating default packetiser"; m_vPayloadPacketisers.push_back(PayloadPacketiserBase::create()); } m_vSessionDbs = createSessionDatabases(m_parameters); EXIT_ON_TRUE(m_vSessionDbs.empty(), "Failed to construct session database(s)"); m_vRtpInterfaces = createRtpNetworkInterfaces(m_parameters); EXIT_ON_TRUE(m_vRtpInterfaces.empty(), "Failed to create RTP network interfaces"); initialiseRtpNetworkInterfaces(m_parameters); // create playout buffer m_vReceiverBuffers = createRtpPlayoutBuffers(m_parameters); EXIT_ON_TRUE(m_vReceiverBuffers.empty(), "Failed to construct receiver buffers"); configureReceiverBuffers(m_parameters, m_applicationParameters); // TODO: abstract and define interface for receiver buffer // TODO: then move the following to RtpPlayoutBuffer implementation // set receiver buffer clock frequency so that we can adjust the jitter buffer #if 0 m_pPlayoutBuffer->setClockFrequency(m_parameters.getRtpTimestampFrequency()); // set buffer latency if configured in application parameters boost::optional<uint32_t> uiBufferLatency = m_applicationParameters.getUintParameter(ApplicationParameters::buf_lat); if (uiBufferLatency) m_pPlayoutBuffer->setPlayoutBufferLatency(*uiBufferLatency); #endif // RTCP inialisation MUST only occur after network interface initialisation // which is after the RTP network interfaces have been constructed m_vRtcpReportManagers = createRtcpReportManagers(m_parameters, m_applicationParameters, m_vSessionDbs); EXIT_ON_TRUE(m_vRtcpReportManagers.empty(), "Failed to construct RTCP report managers"); initialiseRtcp(); // RTP session state m_vRtpSessionStates = createRtpSessionStates(m_parameters); EXIT_ON_TRUE(m_vRtpSessionStates.empty(), "Failed to create RTP session states"); // RTP flows: linking up all the previously constructed objects m_vRtpFlows = createRtpFlows(m_parameters); EXIT_ON_TRUE(m_vRtpFlows.empty(), "Failed to create RTP flows"); return true; } catch (boost::exception& e) { LOG(ERROR) << "Exception: %1%" << boost::diagnostic_information(e); } catch (std::exception& e) { LOG(ERROR) << "Exception: %1%" << e.what(); } catch (...) { LOG(ERROR) << "Unknown exception!!!"; } return false; } boost::system::error_code RtpSessionBase::start() { if (m_state == SS_STOPPED) { if (initialise()) { boost::system::error_code ec = doStart(); if (!ec) { m_state = SS_STARTED; } return ec; } return boost::system::error_code(boost::system::errc::invalid_argument, boost::system::get_generic_category()); } else { return boost::system::error_code(boost::system::errc::invalid_argument, boost::system::get_generic_category()); } } boost::system::error_code RtpSessionBase::stop() { if (m_state == SS_STARTED) { VLOG(2) << "Shutting down RTP session"; m_state = SS_SHUTTING_DOWN; VLOG(2) << "Shutting down RTCP"; shutdownRtcp(); // let subclasses shutdown boost::system::error_code ec = doStop(); VLOG(2) << "Waiting for shutdown to complete"; // FIXME: this should only be reset once the shutdown is complete // i.e. all asynchronous handlers have been called // Commenting this out: for now the solution is to manually call reset // which will reset all session state // m_state = SS_STOPPED; return ec; } else { LOG(WARNING) << "Invalid state to call stop: " << m_state; return boost::system::error_code(boost::system::errc::invalid_argument, boost::system::get_generic_category()); } } boost::system::error_code RtpSessionBase::reset() { // reset state so that the session can be started again m_state = SS_STOPPED; // TODO: reinit all components return boost::system::error_code(); } void RtpSessionBase::sendSample(MediaSample::ptr pSample) { if (m_state == SS_STARTED) { doSendSample(pSample); } else if (m_state == SS_STOPPED) { LOG_FIRST_N(WARNING, 1) << "Session has not been started."; } else if (m_state == SS_SHUTTING_DOWN) { LOG_FIRST_N(INFO, 1) << "Shutting down, not sending any more samples."; } } void RtpSessionBase::sendSamples(const std::vector<MediaSample::ptr>& vMediaSamples) { if (m_state == SS_STARTED) { doSendSamples(vMediaSamples); } else if (m_state == SS_STOPPED) { LOG_FIRST_N(WARNING, 1) << "Session has not been started."; } else if (m_state == SS_SHUTTING_DOWN) { LOG_FIRST_N(INFO, 1) << "Shutting down, not sending any more samples."; } } void RtpSessionBase::doSendSamples(const std::vector<MediaSample::ptr>& vMediaSamples) { for (MediaSample::ptr pMediaSample: vMediaSamples) { doSendSample(pMediaSample); } } void RtpSessionBase::onIncomingRtp( const RtpPacket& rtpPacket, const EndPoint& ep ) { #ifdef DEBUG_INCOMING_RTP VLOG(10) << "Received RTP from " << ep.getAddress() << ":" << ep.getPort(); #endif // convert arrival time to RTP time uint32_t uiRtpTime = convertTimeToRtpTimestamp(rtpPacket.getArrivalTime(), m_parameters.getRtpTimestampFrequency(), m_parameters.getRtpTimestampBase()); RtpPacket& rPacket = const_cast<RtpPacket&>(rtpPacket); rPacket.setRtpArrivalTimestamp(uiRtpTime); if (m_incomingRtp) m_incomingRtp(rtpPacket, ep); doHandleIncomingRtp(rtpPacket, ep); } void RtpSessionBase::onOutgoingRtp( const RtpPacket& rtpPacket, const EndPoint& ep ) { doHandleOutgoingRtp(rtpPacket, ep); if (m_parameters.getRetransmissionTimeout() > 0) { storeRtpPacketForRetransmissionAndSchedulePacketRemoval(rtpPacket, ep, m_parameters.getRetransmissionTimeout()); } } void RtpSessionBase::onIncomingRtcp( const CompoundRtcpPacket& compoundRtcp, const EndPoint& ep ) { #ifdef DEBUG_INCOMING_RTP VLOG(10) << "Received RTCP from " << ep.getAddress() << ":" << ep.getPort(); #endif if (m_incomingRtcp) m_incomingRtcp(compoundRtcp, ep); doHandleIncomingRtcp(compoundRtcp, ep); } void RtpSessionBase::onOutgoingRtcp( const CompoundRtcpPacket& compoundRtcp, const EndPoint& ep ) { doHandleOutgoingRtcp(compoundRtcp, ep); // This code forms an integral part of the event loop: it assumes that each RtcpReportManager // must send a BYE at the end of the session and that each sent BYE results in this method being // called. // check if the outgoing packet contains an RTCP BYE: if so, shutdown the network interfaces // If all required BYEs have been sent, shutdown the network interfaces std::for_each(compoundRtcp.begin(), compoundRtcp.end(), [this](RtcpPacketBase::ptr pRtcpPacket) { if (pRtcpPacket->getPacketType() == PT_RTCP_BYE) { ++m_uiByeSentCount; } }); VLOG_IF(5, m_uiByeSentCount > 0) << m_uiByeSentCount << " RTCP BYE(s) sent. " << m_vRtcpReportManagers.size() << " report managers."; if (m_uiByeSentCount == m_vRtcpReportManagers.size()) { LOG(INFO) << "RTCP BYE(s) sent: shutting down RTP interface"; shutdownNetworkInterfaces(); } } void RtpSessionBase::initialiseRtpNetworkInterfaces(const RtpSessionParameters &rtpParameters) { std::for_each(m_vRtpInterfaces.begin(), m_vRtpInterfaces.end(), [this, &rtpParameters](std::unique_ptr<RtpNetworkInterface>& pRtpInterface) { configureNetworkInterface(pRtpInterface, rtpParameters); pRtpInterface->setIncomingRtpHandler(boost::bind(&RtpSessionBase::onIncomingRtp, this, _1, _2) ); pRtpInterface->setIncomingRtcpHandler(boost::bind(&RtpSessionBase::onIncomingRtcp, this, _1, _2) ); pRtpInterface->setOutgoingRtpHandler(boost::bind(&RtpSessionBase::onOutgoingRtp, this, _1, _2) ); pRtpInterface->setOutgoingRtcpHandler(boost::bind(&RtpSessionBase::onOutgoingRtcp, this, _1, _2) ); pRtpInterface->recv(); }); } void RtpSessionBase::shutdownNetworkInterfaces() { std::for_each(m_vRtpInterfaces.begin(), m_vRtpInterfaces.end(), [this](std::unique_ptr<RtpNetworkInterface>& pRtpInterface) { pRtpInterface->shutdown(); }); VLOG(10) << "RTP network interfaces shutdown"; } void RtpSessionBase::initialiseRtcp() { std::for_each(m_vRtcpReportManagers.begin(), m_vRtcpReportManagers.end(), [this](std::unique_ptr<rfc3550::RtcpReportManager>& pRtcpReportManager) { pRtcpReportManager->startReporting(); }); m_uiByeSentCount = 0; } void RtpSessionBase::shutdownRtcp() { std::for_each(m_vRtcpReportManagers.begin(), m_vRtcpReportManagers.end(), [this](std::unique_ptr<rfc3550::RtcpReportManager>& pRtcpReportManager) { pRtcpReportManager->scheduleFinalReportAndShutdown(); }); VLOG(10) << "RTCP report managers shutdown"; } }
32.730375
154
0.72951
miseri
e38a397590ea4d9e9eaa297ae75d2c15875804d7
3,122
cpp
C++
Queue/Circular_Queue.cpp
DeepthiTabithaBennet/Cpp_TheDataStructuresSurvivalKit
2819feeaabb6c65c1f89d592b89e25e2fca5261f
[ "BSD-3-Clause" ]
2
2021-05-21T17:15:10.000Z
2021-05-21T17:22:14.000Z
Queue/Circular_Queue.cpp
DeepthiTabithaBennet/Cpp_TheDataStructuresSurvivalKit
2819feeaabb6c65c1f89d592b89e25e2fca5261f
[ "BSD-3-Clause" ]
null
null
null
Queue/Circular_Queue.cpp
DeepthiTabithaBennet/Cpp_TheDataStructuresSurvivalKit
2819feeaabb6c65c1f89d592b89e25e2fca5261f
[ "BSD-3-Clause" ]
1
2022-01-11T07:52:42.000Z
2022-01-11T07:52:42.000Z
#include <iostream> using namespace std; /*---------------------------------------------------------------------------*/ class QUEUE{ private: int cqueue[5]; int front, rear, n; public: QUEUE(); //default constructor void insertCQ(int); void deleteCQ(); void displayCQ(); }; /*---------------------------------------------------------------------------*/ QUEUE :: QUEUE(){ front = -1; rear = -1; n = 5; } /*---------------------------------------------------------------------------*/ void QUEUE :: insertCQ(int val){ if (front == (rear + 1) % n){ cout << "Queue Overflow\n"; return; } if (front == -1){ front = 0; rear = 0; } else{ rear = (rear + 1) % n; } cqueue[rear] = val; } /*---------------------------------------------------------------------------*/ void QUEUE::deleteCQ(){ if(front == -1){ cout << "Queue Underflow\n"; return; } cout << "Element deleted from queue is " << cqueue[front] << endl; if (front == rear){ front = -1; rear = -1; } else{ front = (front + 1) % n; } } /*---------------------------------------------------------------------------*/ void QUEUE :: displayCQ(){ int f = front; int r = rear; if(f <= r){ while(f <= r){ cout << cqueue[f] << " "; f++; } } else{ while(f <= (n - 1)){ cout << cqueue[f] << " "; f++; } f = 0; while(f <= r){ cout << cqueue[f] << " "; f++; } } cout << endl; } /*---------------------------------------------------------------------------*/ // Objects QUEUE q1; QUEUE q2; /*---------------------------------------------------------------------------*/ int main(){ int ch, val; cout << "1 —————> Insert in Queue 1\n"; cout << "2 —————> Insert in Queue 2\n"; cout << "3 —————> Delete from Queue 1\n"; cout << "4 —————> Delete from Queue 2\n"; cout << "5 —————> Display Queue 1\n"; cout << "6 —————> Display Queue 2\n"; cout << "7 —————> Exit\n"; do{ cout << "\nEnter your choice : "; cin >> ch; switch(ch){ case (1): cout << "Enter the value to be inserted : "; cin >> val; q1.insertCQ(val); break; case (2): cout << "Enter the value to be inserted : "; cin >> val; q2.insertCQ(val); break; case (3): q1.deleteCQ(); break; case (4): q2.deleteCQ(); break; case (5): q1.displayCQ(); break; case (6): q2.displayCQ(); break; } }while(ch != 7); } /*---------------------------------------------------------------------------*/
22.955882
79
0.295324
DeepthiTabithaBennet
e3917d5cf12b3fc4abeac17e1870106c71260220
1,669
cpp
C++
src/test/middlewares/Volume/marshaller.cpp
kennymalac/tinyCDN
5227ce336e54fe8c74a9b4a5910e324f9ff913ac
[ "Apache-2.0" ]
16
2018-04-15T15:06:01.000Z
2020-06-04T08:54:01.000Z
src/test/middlewares/Volume/marshaller.cpp
kennymalac/tinyCDN
5227ce336e54fe8c74a9b4a5910e324f9ff913ac
[ "Apache-2.0" ]
2
2019-09-09T20:13:52.000Z
2019-09-17T23:52:54.000Z
src/test/middlewares/Volume/marshaller.cpp
kennymalac/tinyCDN
5227ce336e54fe8c74a9b4a5910e324f9ff913ac
[ "Apache-2.0" ]
2
2018-05-18T12:31:34.000Z
2019-09-15T18:38:08.000Z
#include "../../include/catch.hpp" #include <string> #include <iostream> #include "src/utility.hpp" #include "src/middlewares/Volume/volume.hpp" #include "src/middlewares/Volume/marshaller.hpp" using namespace TinyCDN; using namespace TinyCDN::Utility; using namespace TinyCDN::Middleware::Volume; TEST_CASE("VolumeParams") { VolumeParams params{VolumeId{"a32b8963a2084ba7"}, 1000_kB}; REQUIRE(params.id.str() == std::string{"a32b8963a2084ba7"}); REQUIRE(params.size == 1000_kB); } TEST_CASE("VirtualVolumeParams") { VirtualVolumeParams params{VolumeId{"a32b8963a2084ba7"}, fs::current_path(), fs::current_path() / "volumes.db", 1_gB, 4}; REQUIRE(params.id.str() == std::string{"a32b8963a2084ba7"}); REQUIRE(params.size == 4_gB); REQUIRE(params.location == fs::current_path()); REQUIRE(params.fbVolDbLocation == fs::current_path() / "volumes.db"); REQUIRE(params.defaultVolumeSize == 1_gB); REQUIRE(params.volumeLimit == 4); } // TEST_CASE("VolumeCSVMarshaller") {} TEST_CASE("VirtualVolumeMarshaller") { VirtualVolumeMarshaller marshaller{}; SECTION("getInstance returns unique_ptr of VirtualVolume") { VirtualVolumeParams params{VolumeId{"a32b8963a2084ba7"}, fs::current_path(), fs::current_path() / "volumes.db", 1_gB, 4}; auto volume = marshaller.getInstance(params); REQUIRE(typeid(volume) == typeid(std::unique_ptr<VirtualVolume>)); REQUIRE(volume->id.str() == std::string{"a32b8963a2084ba7"}); REQUIRE(volume->getSize() == 4_gB); REQUIRE(volume->location == fs::current_path()); // REQUIRE(volume->fbVolDbLocation == fs::current_path() / "volumes.db"); // REQUIRE(volume->volumeLimit == 4); } }
35.510638
125
0.717196
kennymalac
e392d203a40d6d5df2be7f0399e8b18e79f75ccb
4,679
cpp
C++
Tests/src/Log/Logger.cpp
BlockProject3D/Framework
1c27ef19d9a12d158a2b53f6bd28dd2d8e678912
[ "BSD-3-Clause" ]
2
2019-02-02T20:48:17.000Z
2019-02-22T09:59:40.000Z
Tests/src/Log/Logger.cpp
BlockProject3D/Framework
1c27ef19d9a12d158a2b53f6bd28dd2d8e678912
[ "BSD-3-Clause" ]
125
2020-01-14T18:26:38.000Z
2021-02-23T15:33:55.000Z
Tests/src/Log/Logger.cpp
BlockProject3D/Framework
1c27ef19d9a12d158a2b53f6bd28dd2d8e678912
[ "BSD-3-Clause" ]
1
2020-05-26T08:55:10.000Z
2020-05-26T08:55:10.000Z
// Copyright (c) 2020, BlockProject 3D // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of BlockProject 3D nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <Framework/Log/Logger.hpp> #include <Framework/Memory/Utility.hpp> #include <gtest/gtest.h> class MemoryLog final : public bpf::log::ILogAdapter { private: bpf::collection::List<bpf::String> &_log; public: explicit MemoryLog(bpf::collection::List<bpf::String> &log) : _log(log) { } void LogMessage(bpf::log::ELogLevel level, const bpf::String &category, const bpf::String &msg) final { _log.Add(bpf::String('[') + category + "] " + bpf::String::ValueOf((int)level) + ' ' + msg); } }; TEST(Logger, Basic) { bpf::collection::List<bpf::String> log; auto lg = bpf::log::Logger("UT"); lg.AddHandler(bpf::memory::MakeUnique<MemoryLog>(log)); lg.SetLevel(bpf::log::ELogLevel::DEBUG); lg.Debug("Test"); EXPECT_STREQ(*log.Last(), "[UT] 3 Test"); lg.Info("Test"); EXPECT_STREQ(*log.Last(), "[UT] 2 Test"); lg.Warning("Test"); EXPECT_STREQ(*log.Last(), "[UT] 1 Test"); lg.Error("Test"); EXPECT_STREQ(*log.Last(), "[UT] 0 Test"); } TEST(Logger, Move_1) { bpf::collection::List<bpf::String> log; auto lg = bpf::log::Logger("UT"); auto lg1 = bpf::log::Logger("UT1"); lg.AddHandler(bpf::memory::MakeUnique<MemoryLog>(log)); lg1.SetLevel(bpf::log::ELogLevel::DEBUG); lg1.AddHandler(bpf::memory::MakeUnique<MemoryLog>(log)); lg = std::move(lg1); lg.Debug("Test"); EXPECT_STREQ(*log.Last(), "[UT1] 3 Test"); lg.Info("Test"); EXPECT_STREQ(*log.Last(), "[UT1] 2 Test"); lg.Warning("Test"); EXPECT_STREQ(*log.Last(), "[UT1] 1 Test"); lg.Error("Test"); EXPECT_STREQ(*log.Last(), "[UT1] 0 Test"); } TEST(Logger, Move_2) { bpf::collection::List<bpf::String> log; auto lg1 = bpf::log::Logger("UT"); auto lg = std::move(lg1); lg.AddHandler(bpf::memory::MakeUnique<MemoryLog>(log)); lg.SetLevel(bpf::log::ELogLevel::DEBUG); lg.Debug("Test"); EXPECT_STREQ(*log.Last(), "[UT] 3 Test"); lg.Info("Test"); EXPECT_STREQ(*log.Last(), "[UT] 2 Test"); lg.Warning("Test"); EXPECT_STREQ(*log.Last(), "[UT] 1 Test"); lg.Error("Test"); EXPECT_STREQ(*log.Last(), "[UT] 0 Test"); } TEST(Logger, MinLevel_1) { bpf::collection::List<bpf::String> log; auto lg = bpf::log::Logger("UT"); lg.AddHandler(bpf::memory::MakeUnique<MemoryLog>(log)); lg.SetLevel(bpf::log::ELogLevel::ERROR); lg.Debug("Test"); EXPECT_EQ(log.Size(), 0u); lg.Info("Test"); EXPECT_EQ(log.Size(), 0u); lg.Warning("Test"); EXPECT_EQ(log.Size(), 0u); lg.Error("Test"); EXPECT_STREQ(*log.Last(), "[UT] 0 Test"); } TEST(Logger, MinLevel_2) { bpf::collection::List<bpf::String> log; auto lg = bpf::log::Logger("UT"); lg.AddHandler(bpf::memory::MakeUnique<MemoryLog>(log)); lg.SetLevel(bpf::log::ELogLevel::INFO); lg.Debug("Test"); EXPECT_EQ(log.Size(), 0u); lg.Info("Test"); EXPECT_STREQ(*log.Last(), "[UT] 2 Test"); lg.Warning("Test"); EXPECT_STREQ(*log.Last(), "[UT] 1 Test"); lg.Error("Test"); EXPECT_STREQ(*log.Last(), "[UT] 0 Test"); }
33.905797
105
0.6542
BlockProject3D
e3961a411be58af43857ea8e9c44b116cacb52f6
46
cpp
C++
source/Graphics/Color.cpp
Dante12129/Pancake
35282814e2f3b2d5e155a539ca5ddee32e240d3e
[ "Zlib" ]
null
null
null
source/Graphics/Color.cpp
Dante12129/Pancake
35282814e2f3b2d5e155a539ca5ddee32e240d3e
[ "Zlib" ]
null
null
null
source/Graphics/Color.cpp
Dante12129/Pancake
35282814e2f3b2d5e155a539ca5ddee32e240d3e
[ "Zlib" ]
null
null
null
#include "include/Pancake/Graphics/Color.hpp"
23
45
0.804348
Dante12129
e3971d733659d1e8c2f3b625207d207c7eb4be67
423
hpp
C++
ext/src/org/w3c/dom/NodeList.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/src/org/w3c/dom/NodeList.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/src/org/w3c/dom/NodeList.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar #pragma once #include <fwd-POI.hpp> #include <org/w3c/dom/fwd-POI.hpp> #include <java/lang/Object.hpp> struct org::w3c::dom::NodeList : public virtual ::java::lang::Object { virtual int32_t getLength() = 0; virtual Node* item(int32_t index) = 0; // Generated static ::java::lang::Class *class_(); };
22.263158
97
0.685579
pebble2015