hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
620374730fb0995f6d6fc2b14626960db49fa7f4
1,061
cpp
C++
sw/e-paper-board/src/HttpFetcher.cpp
JakubAndrysek/E-paper-board-ESP32
538febf9775d31835b9f2fa61cd37ae120238fce
[ "MIT" ]
null
null
null
sw/e-paper-board/src/HttpFetcher.cpp
JakubAndrysek/E-paper-board-ESP32
538febf9775d31835b9f2fa61cd37ae120238fce
[ "MIT" ]
null
null
null
sw/e-paper-board/src/HttpFetcher.cpp
JakubAndrysek/E-paper-board-ESP32
538febf9775d31835b9f2fa61cd37ae120238fce
[ "MIT" ]
null
null
null
/** * @file HttpFetcher.cpp * @author Kuba Andrýsek (email@kubaandrysek.cz) * @brief Http Fetcher - získává data z internetu * @date 2022-04-10 * * @copyright Copyright (c) 2022 Kuba Andrýsek * */ #include "HttpFetcher.hpp" #include "exception/HttpRequestException.h" #include "exception/WifiConnException.h" #include <WiFi.h> #include <stdio.h> HttpFetcher::HttpFetcher() { } std::string HttpFetcher::getHTTPRequest(std::string url) { printf("HTTP GET: %s\n", url.c_str()); if (WiFi.status() != WL_CONNECTED) { throw WifiConnException(); } HTTPClient http; http.begin(url.c_str()); int httpResponseCode = http.GET(); std::string payload = "{}"; if (httpResponseCode > 0) { Serial.print("HTTP Response code: "); Serial.println(httpResponseCode); payload = http.getString().c_str(); } else { Serial.print("Error code: "); Serial.println(httpResponseCode); throw HttpRequestException(); } // Free resources http.end(); return payload; }
22.574468
58
0.638077
JakubAndrysek
62042bb3c90a8a2a56ca9b18207acb9da501c99f
2,366
cc
C++
code/render/coregraphics/vertexlayout.cc
sirAgg/nebula
3fbccc73779944aa3e56b9e8acdd6fedd1d38006
[ "BSD-2-Clause" ]
377
2018-10-24T08:34:21.000Z
2022-03-31T23:37:49.000Z
code/render/coregraphics/vertexlayout.cc
sirAgg/nebula
3fbccc73779944aa3e56b9e8acdd6fedd1d38006
[ "BSD-2-Clause" ]
11
2020-01-22T13:34:46.000Z
2022-03-07T10:07:34.000Z
code/render/coregraphics/vertexlayout.cc
sirAgg/nebula
3fbccc73779944aa3e56b9e8acdd6fedd1d38006
[ "BSD-2-Clause" ]
23
2019-07-13T16:28:32.000Z
2022-03-20T09:00:59.000Z
//------------------------------------------------------------------------------ // vertexlayout.cc // (C)2017-2020 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "render/stdneb.h" #include "coregraphics/config.h" #include "vertexlayout.h" #include "vertexsignaturepool.h" namespace CoreGraphics { VertexSignaturePool* layoutPool = nullptr; //------------------------------------------------------------------------------ /** */ const VertexLayoutId CreateVertexLayout(const VertexLayoutCreateInfo& info) { n_assert(info.comps.Size() > 0); VertexLayoutInfo loadInfo; Util::String sig; IndexT i; SizeT size = 0; for (i = 0; i < info.comps.Size(); i++) { sig.Append(info.comps[i].GetSignature()); info.comps[i].byteOffset += size; size += info.comps[i].GetByteSize(); } sig = Util::String::Sprintf("%s", sig.AsCharPtr()); Util::StringAtom atom(sig); loadInfo.signature = Util::StringAtom(sig); loadInfo.vertexByteSize = size; loadInfo.shader = Ids::InvalidId64; loadInfo.comps = info.comps; // reserve resource using signature as name, don't load again unless needed VertexLayoutId id = layoutPool->ReserveResource(atom, "render_system"); if (layoutPool->GetState(id) == Resources::Resource::Pending) layoutPool->LoadFromMemory(id, &loadInfo); return id; } //------------------------------------------------------------------------------ /** */ void DestroyVertexLayout(const VertexLayoutId id) { // FIXME: shutdownrace if(layoutPool->GetRefCount()) layoutPool->Unload(id.resourceId); } //------------------------------------------------------------------------------ /** */ const SizeT VertexLayoutGetSize(const VertexLayoutId id) { return layoutPool->GetVertexLayoutSize(id); } //------------------------------------------------------------------------------ /** */ const Util::Array<VertexComponent>& VertexLayoutGetComponents(const VertexLayoutId id) { return layoutPool->GetVertexComponents(id); } //------------------------------------------------------------------------------ /** */ const VertexLayoutId CreateCachedVertexLayout(const VertexLayoutId id, const ShaderProgramId shader) { return VertexLayoutId(); } } // CoreGraphics
27.511628
80
0.530854
sirAgg
6208788b1ab535205b5bf299020a212669e8d50f
1,897
cpp
C++
OOP_Video_Games_Data_Structures/Mario_Platformer/obstruction_sprite.cpp
estradjm/Class_Work
dc32f5d15ea53b3cace0a3bd873eab385bfb680d
[ "Apache-2.0" ]
7
2018-10-31T08:22:17.000Z
2021-11-19T00:41:35.000Z
OOP_Video_Games_Data_Structures/Mario_Platformer/obstruction_sprite.cpp
estradjm/Class_Work
dc32f5d15ea53b3cace0a3bd873eab385bfb680d
[ "Apache-2.0" ]
null
null
null
OOP_Video_Games_Data_Structures/Mario_Platformer/obstruction_sprite.cpp
estradjm/Class_Work
dc32f5d15ea53b3cace0a3bd873eab385bfb680d
[ "Apache-2.0" ]
1
2020-03-23T01:19:59.000Z
2020-03-23T01:19:59.000Z
#include "obstruction_sprite.h" #include "image_library.h" #include "image_sequence.h" namespace csis3700 { obstruction_sprite::obstruction_sprite(float initial_x, float initial_y, ALLEGRO_BITMAP *image) : sprite(initial_x, initial_y) { al_draw_bitmap(image, initial_x, initial_y, 0); if (image == image_library::get() -> get("ground.png")){ ground = new image_sequence; set_image_sequence(ground); ground -> add_image(image_library::get() -> get("ground.png"), 0.2); //is_coin() = false; } else if (image == image_library::get() -> get("tube.png")){ tunnel = new image_sequence; set_image_sequence(tunnel); tunnel -> add_image(image_library::get() -> get("tube.png"), 0.2); //is_coin() = false; } else if (image == image_library::get() -> get("coin.png")){ coin = new image_sequence; set_image_sequence(coin); coin -> add_image(image_library::get() -> get("coin.png"), 0.2); //is_coin() = true; } else if (image == image_library::get() -> get("castle.png")){ castle = new image_sequence; set_image_sequence(castle); castle -> add_image(image_library::get() -> get("castle.png"), 0.2); //is_coin() = false; } else if (image == image_library::get() -> get("brick.png")){ brick = new image_sequence; set_image_sequence(brick); brick -> add_image(image_library::get() -> get("brick.png"), 0.2); //is_coin() = false; } } vec2d obstruction_sprite::get_velocity() const { return vec2d(0,0); } void obstruction_sprite::set_velocity(const vec2d& v) { assert(false); } void obstruction_sprite::resolve(const collision& collision, sprite* other) { // do nothing, I am not an active participant in a collision } }
34.490909
132
0.600949
estradjm
620df08526200389fea0d2478c6d953d8b88a02b
18,641
cc
C++
src/util.cc
unclearness/ugu
641c5170147091e82578fa6bcd84f3484172f487
[ "MIT" ]
18
2019-12-29T17:27:55.000Z
2022-02-21T11:02:35.000Z
src/util.cc
unclearness/ugu
641c5170147091e82578fa6bcd84f3484172f487
[ "MIT" ]
1
2021-07-22T12:04:53.000Z
2021-07-22T12:04:53.000Z
src/util.cc
unclearness/ugu
641c5170147091e82578fa6bcd84f3484172f487
[ "MIT" ]
2
2021-02-26T06:58:36.000Z
2021-07-05T12:24:09.000Z
/* * Copyright (C) 2019, unclearness * All rights reserved. */ #include <fstream> #include "ugu/util/io_util.h" #include "ugu/util/math_util.h" #include "ugu/util/raster_util.h" #include "ugu/util/rgbd_util.h" namespace { bool Depth2PointCloudImpl(const ugu::Image1f& depth, const ugu::Image3b& color, const ugu::Camera& camera, ugu::Mesh* point_cloud, bool with_texture, bool gl_coord) { if (depth.cols != camera.width() || depth.rows != camera.height()) { ugu::LOGE( "Depth2PointCloud depth size (%d, %d) and camera size (%d, %d) are " "different\n", depth.cols, depth.rows, camera.width(), camera.height()); return false; } if (with_texture) { float depth_aspect_ratio = static_cast<float>(depth.cols) / static_cast<float>(depth.rows); float color_aspect_ratio = static_cast<float>(color.cols) / static_cast<float>(color.rows); const float aspect_ratio_diff_th{0.01f}; // 1% const float aspect_ratio_diff = std::abs(depth_aspect_ratio - color_aspect_ratio); if (aspect_ratio_diff > aspect_ratio_diff_th) { ugu::LOGE( "Depth2PointCloud depth aspect ratio %f and color aspect ratio %f " "are very " "different\n", depth_aspect_ratio, color_aspect_ratio); return false; } } point_cloud->Clear(); std::vector<Eigen::Vector3f> vertices; std::vector<Eigen::Vector3f> vertex_colors; for (int y = 0; y < camera.height(); y++) { for (int x = 0; x < camera.width(); x++) { const float& d = depth.at<float>(y, x); if (d < std::numeric_limits<float>::min()) { continue; } Eigen::Vector3f image_p(static_cast<float>(x), static_cast<float>(y), d); Eigen::Vector3f camera_p; camera.Unproject(image_p, &camera_p); if (gl_coord) { // flip y and z to align with OpenGL coordinate camera_p.y() = -camera_p.y(); camera_p.z() = -camera_p.z(); } vertices.push_back(camera_p); if (with_texture) { Eigen::Vector2f uv(ugu::X2U(x, depth.cols), ugu::Y2V(y, depth.rows, false)); // nearest neighbor // todo: bilinear Eigen::Vector2i pixel_pos( static_cast<int>(std::round(ugu::U2X(uv.x(), color.cols))), static_cast<int>(std::round(ugu::V2Y(uv.y(), color.rows, false)))); Eigen::Vector3f pixel_color; const ugu::Vec3b& tmp_color = color.at<ugu::Vec3b>(pixel_pos.y(), pixel_pos.x()); pixel_color.x() = tmp_color[0]; pixel_color.y() = tmp_color[1]; pixel_color.z() = tmp_color[2]; vertex_colors.push_back(pixel_color); } } } // todo: add normal point_cloud->set_vertices(vertices); if (with_texture) { point_cloud->set_vertex_colors(vertex_colors); } return true; } bool Depth2MeshImpl(const ugu::Image1f& depth, const ugu::Image3b& color, const ugu::Camera& camera, ugu::Mesh* mesh, bool with_texture, bool with_vertex_color, float max_connect_z_diff, int x_step, int y_step, bool gl_coord, const std::string& material_name, ugu::Image3f* point_cloud, ugu::Image3f* normal) { if (max_connect_z_diff < 0) { ugu::LOGE("Depth2Mesh max_connect_z_diff must be positive %f\n", max_connect_z_diff); return false; } if (x_step < 1) { ugu::LOGE("Depth2Mesh x_step must be positive %d\n", x_step); return false; } if (y_step < 1) { ugu::LOGE("Depth2Mesh y_step must be positive %d\n", y_step); return false; } if (depth.cols != camera.width() || depth.rows != camera.height()) { ugu::LOGE( "Depth2Mesh depth size (%d, %d) and camera size (%d, %d) are " "different\n", depth.cols, depth.rows, camera.width(), camera.height()); return false; } if (with_texture) { float depth_aspect_ratio = static_cast<float>(depth.cols) / static_cast<float>(depth.rows); float color_aspect_ratio = static_cast<float>(color.cols) / static_cast<float>(color.rows); const float aspect_ratio_diff_th{0.01f}; // 1% const float aspect_ratio_diff = std::abs(depth_aspect_ratio - color_aspect_ratio); if (aspect_ratio_diff > aspect_ratio_diff_th) { ugu::LOGE( "Depth2Mesh depth aspect ratio %f and color aspect ratio %f are very " "different\n", depth_aspect_ratio, color_aspect_ratio); return false; } } mesh->Clear(); std::vector<Eigen::Vector2f> uvs; std::vector<Eigen::Vector3f> vertices; std::vector<Eigen::Vector3i> vertex_indices; std::vector<Eigen::Vector3f> vertex_colors; std::vector<std::pair<int, int>> vid2xy; std::vector<int> added_table(depth.cols * depth.rows, -1); int vertex_id{0}; for (int y = y_step; y < camera.height(); y += y_step) { for (int x = x_step; x < camera.width(); x += x_step) { const float& d = depth.at<float>(y, x); if (d < std::numeric_limits<float>::min()) { continue; } Eigen::Vector3f image_p(static_cast<float>(x), static_cast<float>(y), d); Eigen::Vector3f camera_p; camera.Unproject(image_p, &camera_p); if (gl_coord) { // flip y and z to align with OpenGL coordinate camera_p.y() = -camera_p.y(); camera_p.z() = -camera_p.z(); } vertices.push_back(camera_p); vid2xy.push_back(std::make_pair(x, y)); Eigen::Vector2f uv(ugu::X2U(x, depth.cols), ugu::Y2V(y, depth.rows, false)); if (with_vertex_color) { // nearest neighbor // todo: bilinear Eigen::Vector2i pixel_pos( static_cast<int>(std::round(ugu::U2X(uv.x(), color.cols))), static_cast<int>(std::round(ugu::V2Y(uv.y(), color.rows, false)))); Eigen::Vector3f pixel_color; const ugu::Vec3b& tmp_color = color.at<ugu::Vec3b>(pixel_pos.y(), pixel_pos.x()); pixel_color.x() = tmp_color[0]; pixel_color.y() = tmp_color[1]; pixel_color.z() = tmp_color[2]; vertex_colors.push_back(pixel_color); } if (with_texture) { // +0.5f comes from mapping 0~1 to -0.5~width(or height)+0.5 // since uv 0 and 1 is pixel boundary at ends while pixel position is // the center of pixel uv.y() = 1.0f - uv.y(); uvs.emplace_back(uv); } added_table[y * camera.width() + x] = vertex_id; const int& current_index = vertex_id; const int& upper_left_index = added_table[(y - y_step) * camera.width() + (x - x_step)]; const int& upper_index = added_table[(y - y_step) * camera.width() + x]; const int& left_index = added_table[y * camera.width() + (x - x_step)]; const float upper_left_diff = std::abs(depth.at<float>(y - y_step, x - x_step) - d); const float upper_diff = std::abs(depth.at<float>(y - y_step, x) - d); const float left_diff = std::abs(depth.at<float>(y, x - x_step) - d); if (upper_left_index > 0 && upper_index > 0 && upper_left_diff < max_connect_z_diff && upper_diff < max_connect_z_diff) { vertex_indices.push_back( Eigen::Vector3i(upper_left_index, current_index, upper_index)); } if (upper_left_index > 0 && left_index > 0 && upper_left_diff < max_connect_z_diff && left_diff < max_connect_z_diff) { vertex_indices.push_back( Eigen::Vector3i(upper_left_index, left_index, current_index)); } vertex_id++; } } mesh->set_vertices(vertices); mesh->set_vertex_indices(vertex_indices); mesh->CalcNormal(); if (with_texture) { mesh->set_uv(uvs); mesh->set_uv_indices(vertex_indices); ugu::ObjMaterial material; color.copyTo(material.diffuse_tex); material.name = material_name; std::vector<ugu::ObjMaterial> materials; materials.push_back(material); mesh->set_materials(materials); std::vector<int> material_ids(vertex_indices.size(), 0); mesh->set_material_ids(material_ids); } if (with_vertex_color) { mesh->set_vertex_colors(vertex_colors); } if (point_cloud != nullptr) { ugu::Init(point_cloud, depth.cols, depth.rows, 0.0f); for (int i = 0; i < static_cast<int>(vid2xy.size()); i++) { const auto& xy = vid2xy[i]; auto& p = point_cloud->at<ugu::Vec3f>(xy.second, xy.first); p[0] = mesh->vertices()[i][0]; p[1] = mesh->vertices()[i][1]; p[2] = mesh->vertices()[i][2]; } } if (normal != nullptr) { ugu::Init(normal, depth.cols, depth.rows, 0.0f); for (int i = 0; i < static_cast<int>(vid2xy.size()); i++) { const auto& xy = vid2xy[i]; auto& n = normal->at<ugu::Vec3f>(xy.second, xy.first); n[0] = mesh->normals()[i][0]; n[1] = mesh->normals()[i][1]; n[2] = mesh->normals()[i][2]; } } return true; } } // namespace namespace ugu { bool Depth2PointCloud(const Image1f& depth, const Camera& camera, Image3f* point_cloud, bool gl_coord) { if (depth.cols != camera.width() || depth.rows != camera.height()) { ugu::LOGE( "Depth2PointCloud depth size (%d, %d) and camera size (%d, %d) are " "different\n", depth.cols, depth.rows, camera.width(), camera.height()); return false; } Init(point_cloud, depth.cols, depth.rows, 0.0f); #if defined(_OPENMP) && defined(UGU_USE_OPENMP) #pragma omp parallel for schedule(dynamic, 1) #endif for (int y = 0; y < camera.height(); y++) { for (int x = 0; x < camera.width(); x++) { const float& d = depth.at<float>(y, x); if (d < std::numeric_limits<float>::min()) { continue; } Eigen::Vector3f image_p(static_cast<float>(x), static_cast<float>(y), d); Eigen::Vector3f camera_p; camera.Unproject(image_p, &camera_p); if (gl_coord) { // flip y and z to align with OpenGL coordinate camera_p.y() = -camera_p.y(); camera_p.z() = -camera_p.z(); } Vec3f& pc = point_cloud->at<Vec3f>(y, x); pc[0] = camera_p[0]; pc[1] = camera_p[1]; pc[2] = camera_p[2]; } } return true; } bool Depth2PointCloud(const Image1f& depth, const Camera& camera, Mesh* point_cloud, bool gl_coord) { Image3b stub_color; return Depth2PointCloudImpl(depth, stub_color, camera, point_cloud, false, gl_coord); } bool Depth2PointCloud(const Image1f& depth, const Image3b& color, const Camera& camera, Mesh* point_cloud, bool gl_coord) { return Depth2PointCloudImpl(depth, color, camera, point_cloud, true, gl_coord); } bool Depth2Mesh(const Image1f& depth, const Camera& camera, Mesh* mesh, float max_connect_z_diff, int x_step, int y_step, bool gl_coord, ugu::Image3f* point_cloud, ugu::Image3f* normal) { Image3b stub_color; return Depth2MeshImpl(depth, stub_color, camera, mesh, false, false, max_connect_z_diff, x_step, y_step, gl_coord, "illegal_material", point_cloud, normal); } bool Depth2Mesh(const Image1f& depth, const Image3b& color, const Camera& camera, Mesh* mesh, float max_connect_z_diff, int x_step, int y_step, bool gl_coord, const std::string& material_name, bool with_vertex_color, ugu::Image3f* point_cloud, ugu::Image3f* normal) { return Depth2MeshImpl(depth, color, camera, mesh, true, with_vertex_color, max_connect_z_diff, x_step, y_step, gl_coord, material_name, point_cloud, normal); } void WriteFaceIdAsText(const Image1i& face_id, const std::string& path) { std::ofstream ofs; ofs.open(path, std::ios::out); for (int y = 0; y < face_id.rows; y++) { for (int x = 0; x < face_id.cols; x++) { ofs << face_id.at<int>(y, x) << "\n"; } } ofs.flush(); } // FINDING OPTIMAL ROTATION AND TRANSLATION BETWEEN CORRESPONDING 3D POINTS // http://nghiaho.com/?page_id=671 Eigen::Affine3d FindRigidTransformFrom3dCorrespondences( const std::vector<Eigen::Vector3d>& src, const std::vector<Eigen::Vector3d>& dst) { if (src.size() < 3 || src.size() != dst.size()) { return Eigen::Affine3d::Identity(); } Eigen::Vector3d src_centroid; src_centroid.setZero(); for (const auto& p : src) { src_centroid += p; } src_centroid /= static_cast<double>(src.size()); Eigen::Vector3d dst_centroid; dst_centroid.setZero(); for (const auto& p : dst) { dst_centroid += p; } dst_centroid /= static_cast<double>(dst.size()); Eigen::MatrixXd normed_src(3, src.size()); for (auto i = 0; i < src.size(); i++) { normed_src.col(i) = src[i] - src_centroid; } Eigen::MatrixXd normed_dst(3, dst.size()); for (auto i = 0; i < dst.size(); i++) { normed_dst.col(i) = dst[i] - dst_centroid; } Eigen::MatrixXd normed_dst_T = normed_dst.transpose(); Eigen::Matrix3d H = normed_src * normed_dst_T; // TODO: rank check Eigen::JacobiSVD<Eigen::Matrix3d> svd( H, Eigen::ComputeFullU | Eigen::ComputeFullV); Eigen::Matrix3d R = svd.matrixV() * svd.matrixU().transpose(); double det = R.determinant(); constexpr double assert_eps = 0.001; assert(std::abs(std::abs(det) - 1.0) < assert_eps); if (det < 0) { Eigen::JacobiSVD<Eigen::Matrix3d> svd2( R, Eigen::ComputeFullU | Eigen::ComputeFullV); Eigen::Matrix3d V = svd2.matrixV(); V.coeffRef(0, 2) *= -1.0; V.coeffRef(1, 2) *= -1.0; V.coeffRef(2, 2) *= -1.0; R = V * svd2.matrixU().transpose(); } assert(std::abs(det - 1.0) < assert_eps); Eigen::Vector3d t = dst_centroid - R * src_centroid; Eigen::Affine3d T = Eigen::Translation3d(t) * R; return T; } Eigen::Affine3d FindRigidTransformFrom3dCorrespondences( const std::vector<Eigen::Vector3f>& src, const std::vector<Eigen::Vector3f>& dst) { std::vector<Eigen::Vector3d> src_d, dst_d; auto to_double = [](const std::vector<Eigen::Vector3f>& fvec, std::vector<Eigen::Vector3d>& dvec) { std::transform(fvec.begin(), fvec.end(), std::back_inserter(dvec), [](const Eigen::Vector3f& f) { return f.cast<double>(); }); }; to_double(src, src_d); to_double(dst, dst_d); return FindRigidTransformFrom3dCorrespondences(src_d, dst_d); } Eigen::Affine3d FindSimilarityTransformFrom3dCorrespondences( const std::vector<Eigen::Vector3d>& src, const std::vector<Eigen::Vector3d>& dst) { Eigen::MatrixXd src_(src.size(), 3); for (auto i = 0; i < src.size(); i++) { src_.row(i) = src[i]; } Eigen::MatrixXd dst_(dst.size(), 3); for (auto i = 0; i < dst.size(); i++) { dst_.row(i) = dst[i]; } return FindSimilarityTransformFrom3dCorrespondences(src_, dst_); } Eigen::Affine3d FindSimilarityTransformFrom3dCorrespondences( const std::vector<Eigen::Vector3f>& src, const std::vector<Eigen::Vector3f>& dst) { Eigen::MatrixXd src_(src.size(), 3); for (auto i = 0; i < src.size(); i++) { src_.row(i) = src[i].cast<double>(); } Eigen::MatrixXd dst_(dst.size(), 3); for (auto i = 0; i < dst.size(); i++) { dst_.row(i) = dst[i].cast<double>(); } return FindSimilarityTransformFrom3dCorrespondences(src_, dst_); } Eigen::Affine3d FindSimilarityTransformFrom3dCorrespondences( const Eigen::MatrixXd& src, const Eigen::MatrixXd& dst) { Eigen::MatrixXd R; Eigen::MatrixXd t; Eigen::MatrixXd scale; Eigen::MatrixXd T; bool ret = FindSimilarityTransformFromPointCorrespondences(src, dst, R, t, scale, T); assert(R.rows() == 3 && R.cols() == 3); assert(t.rows() == 3 && t.cols() == 1); assert(T.rows() == 4 && T.cols() == 4); Eigen::Affine3d T_3d = Eigen::Affine3d::Identity(); if (ret) { T_3d = Eigen::Translation3d(t) * R * Eigen::Scaling(scale.diagonal()); } return T_3d; } bool FindSimilarityTransformFromPointCorrespondences( const Eigen::MatrixXd& src, const Eigen::MatrixXd& dst, Eigen::MatrixXd& R, Eigen::MatrixXd& t, Eigen::MatrixXd& scale, Eigen::MatrixXd& T) { const size_t n_data = src.rows(); const size_t n_dim = src.cols(); if (n_data < 1 || n_dim < 1 || n_data < n_dim || src.rows() != dst.rows() || src.cols() != dst.cols()) { return false; } Eigen::VectorXd src_mean = src.colwise().mean(); Eigen::VectorXd dst_mean = dst.colwise().mean(); Eigen::MatrixXd src_demean = src.rowwise() - src_mean.transpose(); Eigen::MatrixXd dst_demean = dst.rowwise() - dst_mean.transpose(); Eigen::MatrixXd A = dst_demean.transpose() * src_demean / static_cast<double>(n_data); Eigen::VectorXd d = Eigen::VectorXd::Ones(n_dim); double det_A = A.determinant(); if (det_A < 0) { d.coeffRef(n_dim - 1, 0) = -1; } T = Eigen::MatrixXd::Identity(n_dim + 1, n_dim + 1); Eigen::JacobiSVD<Eigen::MatrixXd> svd( A, Eigen::ComputeFullU | Eigen::ComputeFullV); Eigen::MatrixXd U = svd.matrixU(); Eigen::MatrixXd S = svd.singularValues().asDiagonal(); Eigen::MatrixXd V = svd.matrixV(); double det_U = U.determinant(); double det_V = V.determinant(); double det_orgR = det_U * det_V; constexpr double assert_eps = 0.001; assert(std::abs(std::abs(det_orgR) - 1.0) < assert_eps); int rank_A = static_cast<int>(svd.rank()); if (rank_A == 0) { // null matrix case return false; } else if (rank_A == n_dim - 1) { if (det_orgR > 0) { // Valid rotation case R = U * V.transpose(); } else { // Mirror (reflection) case double s = d.coeff(n_dim - 1, 0); d.coeffRef(n_dim - 1, 0) = -1; R = U * d.asDiagonal() * V.transpose(); d.coeffRef(n_dim - 1, 0) = s; } } else { // degenerate case R = U * d.asDiagonal() * V.transpose(); } assert(std::abs(R.determinant() - 1.0) < assert_eps); // Eigen::MatrixXd src_demean_cov = // (src_demean.adjoint() * src_demean) / double(n_data); double src_var = src_demean.rowwise().squaredNorm().sum() / double(n_data) + 1e-30; double uniform_scale = 1.0 / src_var * (S * d.asDiagonal()).trace(); // Question: Is it possible to estimate non-uniform scale? scale = Eigen::MatrixXd::Identity(R.rows(), R.cols()); scale *= uniform_scale; t = dst_mean - scale * R * src_mean; T.block(0, 0, n_dim, n_dim) = scale * R; T.block(0, n_dim, n_dim, 1) = t; return true; } } // namespace ugu
32.362847
80
0.612682
unclearness
620eedbea94b69b261f8911bc2a684500a7554ec
2,874
hpp
C++
sdk/identity/azure-identity/inc/azure/identity/client_certificate_credential.hpp
JinmingHu-MSFT/azure-sdk-for-cpp
933486385a54a5a09a7444dbd823425f145ad75a
[ "MIT" ]
1
2022-01-19T22:54:41.000Z
2022-01-19T22:54:41.000Z
sdk/identity/azure-identity/inc/azure/identity/client_certificate_credential.hpp
LarryOsterman/azure-sdk-for-cpp
d96216f50909a2bd39b555c9088f685bf0f7d6e6
[ "MIT" ]
null
null
null
sdk/identity/azure-identity/inc/azure/identity/client_certificate_credential.hpp
LarryOsterman/azure-sdk-for-cpp
d96216f50909a2bd39b555c9088f685bf0f7d6e6
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: MIT /** * @file * @brief Client Certificate Credential and options. */ #pragma once #include "azure/identity/dll_import_export.hpp" #include <azure/core/credentials/credentials.hpp> #include <azure/core/credentials/token_credential_options.hpp> #include <azure/core/url.hpp> #include <memory> #include <string> namespace Azure { namespace Identity { namespace _detail { class TokenCredentialImpl; } // namespace _detail /** * @brief Options for client certificate authentication. * */ struct ClientCertificateCredentialOptions final : public Core::Credentials::TokenCredentialOptions { }; /** * @brief Client Certificate Credential authenticates with the Azure services using a Tenant ID, * Client ID and a client certificate. * */ class ClientCertificateCredential final : public Core::Credentials::TokenCredential { private: std::unique_ptr<_detail::TokenCredentialImpl> m_tokenCredentialImpl; Core::Url m_requestUrl; std::string m_requestBody; std::string m_tokenHeaderEncoded; std::string m_tokenPayloadStaticPart; void* m_pkey; public: /** * @brief Constructs a Client Secret Credential. * * @param tenantId Tenant ID. * @param clientId Client ID. * @param clientCertificatePath Client certificate path. * @param options Options for token retrieval. */ explicit ClientCertificateCredential( std::string const& tenantId, std::string const& clientId, std::string const& clientCertificatePath, Core::Credentials::TokenCredentialOptions const& options = Core::Credentials::TokenCredentialOptions()); /** * @brief Constructs a Client Secret Credential. * * @param tenantId Tenant ID. * @param clientId Client ID. * @param clientCertificatePath Client certificate path. * @param options Options for token retrieval. */ explicit ClientCertificateCredential( std::string const& tenantId, std::string const& clientId, std::string const& clientCertificatePath, ClientCertificateCredentialOptions const& options); /** * @brief Destructs `%ClientCertificateCredential`. * */ ~ClientCertificateCredential() override; /** * @brief Gets an authentication token. * * @param tokenRequestContext A context to get the token in. * @param context A context to control the request lifetime. * * @throw Azure::Core::Credentials::AuthenticationException Authentication error occurred. */ Core::Credentials::AccessToken GetToken( Core::Credentials::TokenRequestContext const& tokenRequestContext, Core::Context const& context) const override; }; }} // namespace Azure::Identity
29.628866
100
0.699026
JinmingHu-MSFT
620f429f3f495053b9bf74c5e30eff72907278fe
1,950
cc
C++
CalibFormats/CastorObjects/src/CastorChannelCoder.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
CalibFormats/CastorObjects/src/CastorChannelCoder.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
CalibFormats/CastorObjects/src/CastorChannelCoder.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
/** \class CastorChannelCoder Container for ADC<->fQ conversion constants for HCAL/Castor QIE $Original author: ratnikov */ #include <iostream> #include "CalibFormats/CastorObjects/interface/CastorChannelCoder.h" #include "CalibFormats/CastorObjects/interface/QieShape.h" CastorChannelCoder::CastorChannelCoder(const float fOffset[16], const float fSlope[16]) { // [CapId][Range] for (int range = 0; range < 4; range++) { for (int capId = 0; capId < 4; capId++) { mOffset[capId][range] = fOffset[index(capId, range)]; mSlope[capId][range] = fSlope[index(capId, range)]; } } } double CastorChannelCoder::charge(const reco::castor::QieShape& fShape, int fAdc, int fCapId) const { int range = (fAdc >> 6) & 0x3; double charge = fShape.linearization(fAdc) / mSlope[fCapId][range] + mOffset[fCapId][range]; // std::cout << "CastorChannelCoder::charge-> " << fAdc << '/' << fCapId // << " result: " << charge << std::endl; return charge; } int CastorChannelCoder::adc(const reco::castor::QieShape& fShape, double fCharge, int fCapId) const { int adc = -1; //nothing found yet // search for the range for (int range = 0; range < 4; range++) { double qieCharge = (fCharge - mOffset[fCapId][range]) * mSlope[fCapId][range]; double qieChargeMax = fShape.linearization(32 * range + 31) + 0.5 * fShape.binSize(32 * range + 31); if (range == 3 && qieCharge > qieChargeMax) adc = 127; // overflow if (qieCharge > qieChargeMax) continue; // next range for (int bin = 32 * range; bin < 32 * (range + 1); bin++) { if (qieCharge < fShape.linearization(bin) + 0.5 * fShape.binSize(bin)) { adc = bin; break; } } if (adc >= 0) break; // found } if (adc < 0) adc = 0; // underflow // std::cout << "CastorChannelCoder::adc-> " << fCharge << '/' << fCapId // << " result: " << adc << std::endl; return adc; }
35.454545
108
0.620513
ckamtsikis
62118b04432af314622917fa5f785e503a02649d
3,583
cpp
C++
src/aten/src/ATen/native/npu/DiagKernelNpu.cpp
Ascend/pytorch
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
[ "BSD-3-Clause" ]
1
2021-12-02T03:07:35.000Z
2021-12-02T03:07:35.000Z
src/aten/src/ATen/native/npu/DiagKernelNpu.cpp
Ascend/pytorch
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
[ "BSD-3-Clause" ]
1
2021-11-12T07:23:03.000Z
2021-11-12T08:28:13.000Z
src/aten/src/ATen/native/npu/DiagKernelNpu.cpp
Ascend/pytorch
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2020, Huawei Technologies.All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "ATen/native/npu/utils/OpAdapter.h" namespace at { namespace native { using namespace at::native::npu; namespace { SmallVector<int64_t, SIZE> diag_npu_output_size( const Tensor& self, int64_t diagonal) { SmallVector<int64_t, SIZE> shape; // input is 1-d if (self.dim() == 1) { shape.emplace_back(self.size(0) + diagonal); shape.emplace_back(self.size(0) + diagonal); return shape; } // input is 2-d int64_t m = self.size(0); // row int64_t n = self.size(1); // col if (m == n) { shape.emplace_back(m - diagonal); } else if (m < n) { shape.emplace_back(diagonal <= n - m ? m : n - diagonal); } else { shape.emplace_back(n - diagonal); } return shape; } } // namespace Tensor& diag_out_npu_nocheck(Tensor& result, const Tensor& self, int64_t diagonal) { // judging and executing the NPU operator // If input is a 1-D tensor, then returns a 2-D square tensor with the elements of input as the diagonal. // If input is a matrix (2-D tensor), then returns a 1-D tensor with the diagonal elements of input. OpCommand cmd; if (self.dim() == 1) { cmd.Name("Diag"); } else { cmd.Name("DiagPart"); } cmd.Input(self) .Output(result) .Attr("diagonal", diagonal) .Run(); return result; } Tensor& diag_out_npu(Tensor& result, const Tensor& self, int64_t diagonal) { TORCH_CHECK((self.dim() == 1) || (self.dim() == 2), "Value should be a 1-dimensional tensor or 2-dimensional tensor, but got ",self.dim()); diagonal = make_wrap_dim(diagonal, self.dim()); TORCH_CHECK((self.dim() == 1) || (self.dim() == 2 && diagonal <= self.size(0) && diagonal <= self.size(1)), "If the value is 2-dimensional tensor, the diagonal shoule less than shape.Diagonal is ", diagonal); auto outputSize = diag_npu_output_size(self, diagonal); OpPreparation::CheckOut( {self}, result, self, outputSize); OpPipeWithDefinedOut pipe; return pipe.CheckMemory({self}, {result}) .Func([&self, &diagonal](Tensor& result){diag_out_npu_nocheck(result, self, diagonal);}) .Call(result); } Tensor diag_npu(const Tensor& self, int64_t diagonal) { TORCH_CHECK((self.dim() == 1) || (self.dim() == 2), "Value should be a 1-dimensional tensor or 2-dimensional tensor, but got ",self.dim()); diagonal = make_wrap_dim(diagonal, self.dim()); TORCH_CHECK((self.dim() == 1) || (self.dim() == 2 && diagonal <= self.size(0) && diagonal <= self.size(1)), "If the value is 2-dimensional tensor, the diagonal shoule less than shape.Diagonal is ", diagonal); // calculate the output size auto outputSize = diag_npu_output_size(self, diagonal); // construct the output tensor of the NPU Tensor result = OpPreparation::ApplyTensor(self, outputSize); // calculate the output result of the NPU diag_out_npu_nocheck(result, self, diagonal); return result; } } // namespace native } // namespace at
34.12381
114
0.673179
Ascend
6211bc69c80917d0126fa9ea034fd82551348b1d
203
cpp
C++
core/objects/utility/Dynamic.cpp
pavelsevecek/OpenSPH
d547c0af6270a739d772a4dcba8a70dc01775367
[ "MIT" ]
20
2021-04-02T04:30:08.000Z
2022-03-01T09:52:01.000Z
core/objects/utility/Dynamic.cpp
pavelsevecek/OpenSPH
d547c0af6270a739d772a4dcba8a70dc01775367
[ "MIT" ]
null
null
null
core/objects/utility/Dynamic.cpp
pavelsevecek/OpenSPH
d547c0af6270a739d772a4dcba8a70dc01775367
[ "MIT" ]
1
2022-01-22T11:44:52.000Z
2022-01-22T11:44:52.000Z
#include "objects/utility/Dynamic.h" NAMESPACE_SPH_BEGIN Dynamic::Dynamic() = default; /// Needs to be in .cpp to compile with clang, for some reason Dynamic::~Dynamic() = default; NAMESPACE_SPH_END
18.454545
62
0.748768
pavelsevecek
6212bc8831b2ba6f1511f39ce1398e5a6770e78c
5,734
cpp
C++
Codes/String/SuffixArrayShort.cpp
cjtoribio/Algorithms
78499613a9b018eb5e489307b14e31e5fe8227e3
[ "MIT" ]
18
2015-05-24T20:28:46.000Z
2021-01-27T02:34:43.000Z
Codes/String/SuffixArrayShort.cpp
cjtoribio/Algorithms
78499613a9b018eb5e489307b14e31e5fe8227e3
[ "MIT" ]
null
null
null
Codes/String/SuffixArrayShort.cpp
cjtoribio/Algorithms
78499613a9b018eb5e489307b14e31e5fe8227e3
[ "MIT" ]
4
2015-05-24T20:28:32.000Z
2021-01-30T04:04:55.000Z
typedef vector<int> VI; struct SuffixArray { int N; string A; VI SA, RA, LCP; SuffixArray(const string &B) : N(B.size()), A(B), SA(B.size()), RA(B.size()), LCP(B.size()) { for (int i = 0; i < N; ++i) SA[i] = i, RA[i] = A[i]; if(N == 1) RA[0] = 0; } void countingSort(int H) { auto vrank = [&](int i) { return SA[i]+H<N ? RA[SA[i]+H]+1 : 0; }; int maxRank = *max_element(RA.begin(), RA.end()); VI nSA(N); VI freq(maxRank + 2); for (int i = 0; i < N; ++i) freq[vrank(i)]++; for (int i = 1; i < freq.size(); ++i) freq[i] += freq[i-1]; for (int i = N-1, p, m; i >= 0; --i) nSA[--freq[vrank(i)]] = SA[i]; copy(nSA.begin(), nSA.end(), SA.begin()); } void buildSA() { VI nRA(N); for (int H = 1; H < N; H <<= 1) { countingSort(H); countingSort(0); int rank = nRA[SA[0]] = 0; for (int i = 1; i < N; ++i) { if (RA[SA[i]] != RA[SA[i - 1]]) rank++; else if (SA[i - 1] + H >= N || SA[i] + H >= N) rank++; else if (RA[SA[i] + H] != RA[SA[i - 1] + H]) rank++; nRA[SA[i]] = rank; } copy(nRA.begin(), nRA.end(), RA.begin()); } } void buildSA2(){ if (N == 1) { this->SA[0] = 0, this->RA[0] = 0; return; } VI T(N+3), SA(N+3); for(int i = 0; i < A.size(); ++i) T[i] = A[i]; suffixArray(T, SA, N, 256); for(int i = 0; i < N; ++i) RA[ SA[i] ] = i; for(int i = 0; i < N; ++i) this->SA[i] = SA[i]; } inline bool leq(int a1, int a2, int b1, int b2) { return (a1 < b1 || (a1 == b1 && a2 <= b2)); } inline bool leq(int a1, int a2, int a3, int b1, int b2, int b3) { return (a1 < b1 || (a1 == b1 && leq(a2, a3, b2, b3))); } static void radixPass(VI &a, VI &b, VI::iterator r, int n, int K) { VI c(K+1); for (int i = 0; i < n; i++) c[r[a[i]]]++; for (int i = 1; i <= K; i++) c[i] += c[i-1]; for (int i = n-1; i >= 0; --i) b[--c[r[a[i]]]] = a[i]; } void suffixArray(VI &T, VI &SA, int n, int K) { int n0 = (n + 2) / 3, n1 = (n + 1) / 3, n2 = n / 3, n02 = n0 + n2; VI R(n02+3), SA12(n02+3), R0(n0), SA0(n0); for (int i = 0, j = 0; i < n + (n0 - n1); i++) if (i % 3 != 0) R[j++] = i; radixPass(R, SA12, T.begin() + 2, n02, K); radixPass(SA12, R, T.begin() + 1, n02, K); radixPass(R, SA12, T.begin(), n02, K); int name = 0, c0 = -1, c1 = -1, c2 = -1; for (int i = 0; i < n02; i++) { if (T[SA12[i]] != c0 || T[SA12[i] + 1] != c1 || T[SA12[i] + 2] != c2) { name++; c0 = T[SA12[i]]; c1 = T[SA12[i] + 1]; c2 = T[SA12[i] + 2]; } if (SA12[i] % 3 == 1) { R[SA12[i] / 3] = name; } else { R[SA12[i] / 3 + n0] = name; } } if (name < n02) { suffixArray(R, SA12, n02, name); for (int i = 0; i < n02; i++) R[SA12[i]] = i + 1; } else for (int i = 0; i < n02; i++) SA12[R[i] - 1] = i; for (int i = 0, j = 0; i < n02; i++) if (SA12[i] < n0) R0[j++] = 3 * SA12[i]; radixPass(R0, SA0, T.begin(), n0, K); for (int p = 0, t = n0 - n1, k = 0; k < n; k++) { #define GetI() (SA12[t] < n0 ? SA12[t] * 3 + 1 : (SA12[t] - n0) * 3 + 2) int i = GetI(); // pos of current offset 12 suffix int j = SA0[p]; // pos of current offset 0 suffix if (SA12[t] < n0 ? // different compares for mod 1 and mod 2 suffixes leq(T[i], R[SA12[t] + n0], T[j], R[j / 3]) : leq(T[i], T[i + 1], R[SA12[t] - n0 + 1], T[j], T[j + 1], R[j / 3 + n0])) { // suffix from SA12 is smaller SA[k] = i; t++; if (t == n02) // done --- only SA0 suffixes left for (k++; p < n0; p++, k++) SA[k] = SA0[p]; } else { // suffix from SA0 is smaller SA[k] = j; p++; if (p == n0) // done --- only SA12 suffixes left for (k++; t < n02; t++, k++) SA[k] = GetI(); } } } void buildLCP() { for (int i = 0, k = 0; i < N; ++i) if (RA[i] != N - 1) { for (int j = SA[RA[i] + 1]; A[i + k] == A[j + k];) ++k; LCP[RA[i]] = k; if (k)--k; } } vector<VI> RLCP; void BuildRangeQueries() { int L = 31 - __builtin_clz(N) + 1; RLCP = vector<VI>(L, VI(N)); RLCP[0] = LCP; for (int i = 1; i < L; ++i) { for (int j = 0; j+(1<<(i-1)) < N; ++j) RLCP[i][j] = min(RLCP[i - 1][j], RLCP[i-1][j + (1<<(i-1))]); } } int lcp(int i, int j) { if (i == j) return N - SA[i]; int b = 31 - __builtin_clz(j-i); return min(RLCP[b][i], RLCP[b][j-(1<<b)]); } long long ops = 0; int match(int idx, const string &P){ for(int i = 0; i < P.size() && i + idx < N; ++i){ ops++; if(A[i+idx] != P[i]) return i; } return min(N-idx, (int)P.size()); } int cmp(int idx, const string &P){ int m = match(idx, P); if(m == P.size())return 0; if(m == N-idx)return -1; return A[idx+m] < P[m] ? -1 : (A[idx+m] == P[m] ? 0 : 1); } // MlogN (low constant) int lowerBound(const string &P){ int lo = 0, hi = N; while(lo < hi){ int mid = (lo + hi)/2; if(cmp(SA[mid], P) < 0) lo = mid+1; else hi = mid; } return lo; } // MlogN (low constant) int upperBound(const string &P){ int lo = 0, hi = N; while(lo < hi){ int mid = (lo + hi)/2; if(cmp(SA[mid], P) <= 0) lo = mid+1; else hi = mid; } return lo; } // M + logN (high constant) (slow in practice) int lowerBound2(const string &P, int deb = 0){ int lo = 0, hi = N; int k = match(SA[0], P), pm = 0; while(lo < hi){ int m = (lo + hi)/2; int rlcp= lcp(min(pm,m), max(m,pm)); if(rlcp > k && pm != m){ if(pm < m)lo = m+1; else hi = m; }else if(rlcp < k && pm != m){ if(pm < m)hi = m; else lo = m+1; }else{ while(k < P.size() && SA[m]+k < N && P[k] == A[SA[m]+k]) k++; if(k == P.size()) hi = m; else if(SA[m]+k == N) lo = m+1; else if(A[SA[m]+k] < P[k]) lo = m+1; else hi = m; pm = m; } } return lo; } };
26.423963
109
0.452389
cjtoribio
62156bb4143b403e6bd804aa6095f394decd67db
39,862
cpp
C++
Kuplung/kuplung/utilities/renderers/default-forward/DefaultForwardRenderer.cpp
supudo/Kuplung
f0e11934fde0675fa531e6dc263bedcc20a5ea1a
[ "Unlicense" ]
14
2017-02-17T17:12:40.000Z
2021-12-22T01:55:06.000Z
Kuplung/kuplung/utilities/renderers/default-forward/DefaultForwardRenderer.cpp
supudo/Kuplung
f0e11934fde0675fa531e6dc263bedcc20a5ea1a
[ "Unlicense" ]
null
null
null
Kuplung/kuplung/utilities/renderers/default-forward/DefaultForwardRenderer.cpp
supudo/Kuplung
f0e11934fde0675fa531e6dc263bedcc20a5ea1a
[ "Unlicense" ]
1
2019-10-15T08:10:10.000Z
2019-10-15T08:10:10.000Z
// // DefaultForwardRenderer.cpp // Kuplung // // Created by Sergey Petrov on 12/16/15. // Copyright © 2015 supudo.net. All rights reserved. // #include "DefaultForwardRenderer.hpp" #include "kuplung/utilities/stb/stb_image_write.h" #include <boost/algorithm/string/predicate.hpp> #include <boost/filesystem.hpp> #include <glm/gtc/matrix_inverse.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/matrix_decompose.hpp> DefaultForwardRenderer::DefaultForwardRenderer(ObjectsManager& managerObjects) : fileOutputImage(), managerObjects(managerObjects) { this->solidLight = new ModelFace_LightSource_Directional(); this->lightingPass_DrawMode = -1; this->GLSL_LightSourceNumber_Directional = 0; this->GLSL_LightSourceNumber_Point = 0; this->GLSL_LightSourceNumber_Spot = 0; } DefaultForwardRenderer::~DefaultForwardRenderer() { GLint maxColorAttachments = 1; glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &maxColorAttachments); GLuint colorAttachment; GLenum att = GL_COLOR_ATTACHMENT0; for (colorAttachment = 0; colorAttachment < static_cast<GLuint>(maxColorAttachments); colorAttachment++) { att += colorAttachment; GLint param; GLuint objName; glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, att, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &param); if (GL_RENDERBUFFER == param) { glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, att, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &param); objName = reinterpret_cast<GLuint*>(&param)[0]; glDeleteRenderbuffers(1, &objName); } else if (GL_TEXTURE == param) { glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, att, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &param); objName = reinterpret_cast<GLuint*>(&param)[0]; glDeleteTextures(1, &objName); } } glDeleteProgram(this->shaderProgram); glDeleteFramebuffers(1, &this->renderFBO); glDeleteRenderbuffers(1, &this->renderRBO); for (size_t i = 0; i < this->mfLights_Directional.size(); i++) { delete this->mfLights_Directional[i]; } for (size_t i = 0; i < this->mfLights_Point.size(); i++) { delete this->mfLights_Point[i]; } for (size_t i = 0; i < this->mfLights_Spot.size(); i++) { delete this->mfLights_Spot[i]; } } void DefaultForwardRenderer::init() { this->GLSL_LightSourceNumber_Directional = 8; this->GLSL_LightSourceNumber_Point = 4; this->GLSL_LightSourceNumber_Spot = 4; this->Setting_RenderSkybox = false; this->initShaderProgram(); } bool DefaultForwardRenderer::initShaderProgram() { bool success = true; // vertex shader std::string shaderPath = Settings::Instance()->appFolder() + "/shaders/model_face.vert"; std::string shaderSourceVertex = Settings::Instance()->glUtils->readFile(shaderPath.c_str()); const char* shader_vertex = shaderSourceVertex.c_str(); // tessellation control shader shaderPath = Settings::Instance()->appFolder() + "/shaders/model_face.tcs"; std::string shaderSourceTCS = Settings::Instance()->glUtils->readFile(shaderPath.c_str()); const char* shader_tess_control = shaderSourceTCS.c_str(); // tessellation evaluation shader shaderPath = Settings::Instance()->appFolder() + "/shaders/model_face.tes"; std::string shaderSourceTES = Settings::Instance()->glUtils->readFile(shaderPath.c_str()); const char* shader_tess_eval = shaderSourceTES.c_str(); // geometry shader shaderPath = Settings::Instance()->appFolder() + "/shaders/model_face.geom"; std::string shaderSourceGeometry = Settings::Instance()->glUtils->readFile(shaderPath.c_str()); const char* shader_geometry = shaderSourceGeometry.c_str(); // fragment shader - parts std::string shaderSourceFragment; std::vector<std::string> fragFiles = {"vars", "effects", "lights", "mapping", "shadow_mapping", "misc", "pbr"}; for (size_t i = 0; i < fragFiles.size(); i++) { shaderPath = Settings::Instance()->appFolder() + "/shaders/model_face_" + fragFiles[i] + ".frag"; shaderSourceFragment += Settings::Instance()->glUtils->readFile(shaderPath.c_str()); } shaderPath = Settings::Instance()->appFolder() + "/shaders/model_face.frag"; shaderSourceFragment += Settings::Instance()->glUtils->readFile(shaderPath.c_str()); const char* shader_fragment = shaderSourceFragment.c_str(); this->shaderProgram = glCreateProgram(); bool shaderCompilation = true; shaderCompilation &= Settings::Instance()->glUtils->compileShader(this->shaderProgram, GL_VERTEX_SHADER, shader_vertex); shaderCompilation &= Settings::Instance()->glUtils->compileShader(this->shaderProgram, GL_TESS_CONTROL_SHADER, shader_tess_control); shaderCompilation &= Settings::Instance()->glUtils->compileShader(this->shaderProgram, GL_TESS_EVALUATION_SHADER, shader_tess_eval); shaderCompilation &= Settings::Instance()->glUtils->compileShader(this->shaderProgram, GL_GEOMETRY_SHADER, shader_geometry); shaderCompilation &= Settings::Instance()->glUtils->compileShader(this->shaderProgram, GL_FRAGMENT_SHADER, shader_fragment); if (!shaderCompilation) return false; glLinkProgram(this->shaderProgram); GLint programSuccess = GL_TRUE; glGetProgramiv(this->shaderProgram, GL_LINK_STATUS, &programSuccess); if (programSuccess != GL_TRUE) { Settings::Instance()->funcDoLog("[DefaultForwardRenderer] Error linking program " + std::to_string(this->shaderProgram) + "!"); Settings::Instance()->glUtils->printProgramLog(this->shaderProgram); return success = false; } else { #ifdef Def_Kuplung_OpenGL_4x glPatchParameteri(GL_PATCH_VERTICES, 3); #endif this->glGS_GeomDisplacementLocation = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "vs_displacementLocation"); this->glTCS_UseCullFace = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "tcs_UseCullFace"); this->glTCS_UseTessellation = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "tcs_UseTessellation"); this->glTCS_TessellationSubdivision = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "tcs_TessellationSubdivision"); this->glFS_AlphaBlending = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_alpha"); this->glFS_CelShading = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_celShading"); this->glFS_CameraPosition = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_cameraPosition"); this->glVS_IsBorder = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "vs_isBorder"); this->glFS_OutlineColor = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_outlineColor"); this->glFS_UIAmbient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_UIAmbient"); this->glFS_GammaCoeficient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_gammaCoeficient"); this->glVS_MVPMatrix = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "vs_MVPMatrix"); this->glFS_MMatrix = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_ModelMatrix"); this->glVS_WorldMatrix = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "vs_WorldMatrix"); this->glFS_MVMatrix = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "vs_MVMatrix"); this->glVS_NormalMatrix = glGetUniformLocation(this->shaderProgram, "vs_normalMatrix"); this->glFS_ScreenResX = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_screenResX"); this->glFS_ScreenResY = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_screenResY"); this->glMaterial_ParallaxMapping = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_userParallaxMapping"); this->gl_ModelViewSkin = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_modelViewSkin"); this->glFS_solidSkin_materialColor = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_materialColor"); this->solidLight->gl_InUse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.inUse"); this->solidLight->gl_Direction = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.direction"); this->solidLight->gl_Ambient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.ambient"); this->solidLight->gl_Diffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.diffuse"); this->solidLight->gl_Specular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.specular"); this->solidLight->gl_StrengthAmbient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.strengthAmbient"); this->solidLight->gl_StrengthDiffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.strengthDiffuse"); this->solidLight->gl_StrengthSpecular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.strengthSpecular"); // light - directional for (int i = 0; i < this->GLSL_LightSourceNumber_Directional; i++) { ModelFace_LightSource_Directional* f = new ModelFace_LightSource_Directional(); f->gl_InUse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].inUse").c_str()); f->gl_Direction = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].direction").c_str()); f->gl_Ambient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].ambient").c_str()); f->gl_Diffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].diffuse").c_str()); f->gl_Specular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].specular").c_str()); f->gl_StrengthAmbient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].strengthAmbient").c_str()); f->gl_StrengthDiffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].strengthDiffuse").c_str()); f->gl_StrengthSpecular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].strengthSpecular").c_str()); this->mfLights_Directional.push_back(f); } // light - point for (int i = 0; i < this->GLSL_LightSourceNumber_Point; i++) { ModelFace_LightSource_Point* f = new ModelFace_LightSource_Point(); f->gl_InUse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].inUse").c_str()); f->gl_Position = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].position").c_str()); f->gl_Constant = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].constant").c_str()); f->gl_Linear = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].linear").c_str()); f->gl_Quadratic = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].quadratic").c_str()); f->gl_Ambient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].ambient").c_str()); f->gl_Diffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].diffuse").c_str()); f->gl_Specular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].specular").c_str()); f->gl_StrengthAmbient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].strengthAmbient").c_str()); f->gl_StrengthDiffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].strengthDiffuse").c_str()); f->gl_StrengthSpecular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].strengthSpecular").c_str()); this->mfLights_Point.push_back(f); } // light - spot for (int i = 0; i < this->GLSL_LightSourceNumber_Spot; i++) { ModelFace_LightSource_Spot* f = new ModelFace_LightSource_Spot(); f->gl_InUse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].inUse").c_str()); f->gl_Position = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].position").c_str()); f->gl_Direction = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].direction").c_str()); f->gl_CutOff = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].cutOff").c_str()); f->gl_OuterCutOff = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].outerCutOff").c_str()); f->gl_Constant = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].constant").c_str()); f->gl_Linear = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].linear").c_str()); f->gl_Quadratic = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].quadratic").c_str()); f->gl_Ambient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].ambient").c_str()); f->gl_Diffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].diffuse").c_str()); f->gl_Specular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].specular").c_str()); f->gl_StrengthAmbient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].strengthAmbient").c_str()); f->gl_StrengthDiffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].strengthDiffuse").c_str()); f->gl_StrengthSpecular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].strengthSpecular").c_str()); this->mfLights_Spot.push_back(f); } // material this->glMaterial_Refraction = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.refraction"); this->glMaterial_SpecularExp = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.specularExp"); this->glMaterial_IlluminationModel = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.illumination_model"); this->glMaterial_HeightScale = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.heightScale"); this->glMaterial_Ambient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.ambient"); this->glMaterial_Diffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.diffuse"); this->glMaterial_Specular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.specular"); this->glMaterial_Emission = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.emission"); this->glMaterial_SamplerAmbient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.sampler_ambient"); this->glMaterial_SamplerDiffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.sampler_diffuse"); this->glMaterial_SamplerSpecular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.sampler_specular"); this->glMaterial_SamplerSpecularExp = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.sampler_specularExp"); this->glMaterial_SamplerDissolve = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.sampler_dissolve"); this->glMaterial_SamplerBump = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.sampler_bump"); this->glMaterial_SamplerDisplacement = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.sampler_displacement"); this->glMaterial_HasTextureAmbient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.has_texture_ambient"); this->glMaterial_HasTextureDiffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.has_texture_diffuse"); this->glMaterial_HasTextureSpecular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.has_texture_specular"); this->glMaterial_HasTextureSpecularExp = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.has_texture_specularExp"); this->glMaterial_HasTextureDissolve = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.has_texture_dissolve"); this->glMaterial_HasTextureBump = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.has_texture_bump"); this->glMaterial_HasTextureDisplacement = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.has_texture_displacement"); // effects - gaussian blur this->glEffect_GB_W = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_GBlur.gauss_w"); this->glEffect_GB_Radius = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_GBlur.gauss_radius"); this->glEffect_GB_Mode = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_GBlur.gauss_mode"); // effects - bloom this->glEffect_Bloom_doBloom = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_Bloom.doBloom"); this->glEffect_Bloom_WeightA = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_Bloom.bloom_WeightA"); this->glEffect_Bloom_WeightB = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_Bloom.bloom_WeightB"); this->glEffect_Bloom_WeightC = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_Bloom.bloom_WeightC"); this->glEffect_Bloom_WeightD = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_Bloom.bloom_WeightD"); this->glEffect_Bloom_Vignette = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_Bloom.bloom_Vignette"); this->glEffect_Bloom_VignetteAtt = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_Bloom.bloom_VignetteAtt"); // effects - tone mapping this->glEffect_ToneMapping_ACESFilmRec2020 = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_ACESFilmRec2020"); } return success; } void DefaultForwardRenderer::createFBO() { glGenFramebuffers(1, &this->renderFBO); glBindFramebuffer(GL_FRAMEBUFFER, this->renderFBO); this->generateAttachmentTexture(false, false); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->renderTextureColorBuffer, 0); const int screenWidth = Settings::Instance()->SDL_DrawableSize_Width; const int screenHeight = Settings::Instance()->SDL_DrawableSize_Height; glGenRenderbuffers(1, &this->renderRBO); glBindRenderbuffer(GL_RENDERBUFFER, this->renderRBO); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, screenWidth, screenHeight); glBindRenderbuffer(GL_RENDERBUFFER, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, this->renderRBO); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) Settings::Instance()->funcDoLog("[Kuplung-DefaultForwardRenderer] Framebuffer is not complete!"); glBindFramebuffer(GL_FRAMEBUFFER, 0); } void DefaultForwardRenderer::generateAttachmentTexture(GLboolean depth, GLboolean stencil) { GLenum attachment_type = GL_RGB; if (!depth && !stencil) attachment_type = GL_RGB; else if (depth && !stencil) attachment_type = GL_DEPTH_COMPONENT; else if (!depth && stencil) attachment_type = GL_STENCIL_INDEX; int screenWidth = Settings::Instance()->SDL_DrawableSize_Width; int screenHeight = Settings::Instance()->SDL_DrawableSize_Height; glGenTextures(1, &this->renderTextureColorBuffer); glBindTexture(GL_TEXTURE_2D, this->renderTextureColorBuffer); if (!depth && !stencil) glTexImage2D(GL_TEXTURE_2D, 0, static_cast<GLint>(attachment_type), screenWidth, screenHeight, 0, attachment_type, GL_UNSIGNED_BYTE, nullptr); else glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, screenWidth, screenHeight, 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); } std::string DefaultForwardRenderer::renderImage(const FBEntity& file, std::vector<ModelFaceBase*>* meshModelFaces) { this->fileOutputImage = file; std::string endFile; int width = Settings::Instance()->SDL_DrawableSize_Width; int height = Settings::Instance()->SDL_DrawableSize_Height; this->createFBO(); glBindFramebuffer(GL_FRAMEBUFFER, this->renderFBO); this->renderSceneToFBO(meshModelFaces); glBindFramebuffer(GL_FRAMEBUFFER, 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, this->renderTextureColorBuffer); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); unsigned char* pixels = new unsigned char[3 * width * height]; glBindFramebuffer(GL_READ_FRAMEBUFFER, this->renderFBO); glBlitFramebuffer(0, 0, Settings::Instance()->SDL_DrawableSize_Width, Settings::Instance()->SDL_DrawableSize_Height, 0, 0, Settings::Instance()->SDL_DrawableSize_Width, Settings::Instance()->SDL_DrawableSize_Height, GL_DEPTH_BUFFER_BIT, GL_NEAREST); glReadBuffer(GL_COLOR_ATTACHMENT0); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels); glBindFramebuffer(GL_FRAMEBUFFER, 0); unsigned char* line_tmp = new unsigned char[3 * width]; unsigned char* line_a = pixels; unsigned char* line_b = pixels + (3 * width * (height - 1)); while (line_a < line_b) { memcpy(line_tmp, line_a, width * 3); memcpy(line_a, line_b, width * 3); memcpy(line_b, line_tmp, width * 3); line_a += width * 3; line_b -= width * 3; } endFile = file.path + ".bmp"; stbi_write_bmp(endFile.c_str(), width, height, 3, pixels); delete[] pixels; delete[] line_tmp; return endFile; } void DefaultForwardRenderer::renderSceneToFBO(std::vector<ModelFaceBase*>* meshModelFaces) { this->matrixProjection = this->managerObjects.matrixProjection; this->matrixCamera = this->managerObjects.camera->matrixCamera; this->vecCameraPosition = this->managerObjects.camera->cameraPosition; this->uiAmbientLight = this->managerObjects.Setting_UIAmbientLight; this->lightingPass_DrawMode = this->managerObjects.Setting_LightingPass_DrawMode; glViewport(0, 0, Settings::Instance()->SDL_DrawableSize_Width, Settings::Instance()->SDL_DrawableSize_Height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); if (this->Setting_RenderSkybox) this->managerObjects.renderSkybox(); glUseProgram(this->shaderProgram); for (size_t i = 0; i < (*meshModelFaces).size(); i++) { ModelFaceData* mfd = (ModelFaceData*)(*meshModelFaces)[i]; glm::mat4 matrixModel = glm::mat4(1.0); matrixModel *= this->managerObjects.grid->matrixModel; matrixModel = glm::scale(matrixModel, glm::vec3(mfd->scaleX->point, mfd->scaleY->point, mfd->scaleZ->point)); matrixModel = glm::translate(matrixModel, glm::vec3(mfd->positionX->point, mfd->positionY->point, mfd->positionZ->point)); matrixModel = glm::translate(matrixModel, glm::vec3(0, 0, 0)); matrixModel = glm::rotate(matrixModel, glm::radians(mfd->rotateX->point), glm::vec3(1, 0, 0)); matrixModel = glm::rotate(matrixModel, glm::radians(mfd->rotateY->point), glm::vec3(0, 1, 0)); matrixModel = glm::rotate(matrixModel, glm::radians(mfd->rotateZ->point), glm::vec3(0, 0, 1)); matrixModel = glm::translate(matrixModel, glm::vec3(0, 0, 0)); mfd->matrixGrid = this->managerObjects.grid->matrixModel; mfd->matrixProjection = this->matrixProjection; mfd->matrixCamera = this->matrixCamera; mfd->matrixModel = matrixModel; mfd->Setting_ModelViewSkin = this->managerObjects.viewModelSkin; mfd->lightSources = this->managerObjects.lightSources; mfd->setOptionsFOV(this->managerObjects.Setting_FOV); mfd->setOptionsOutlineColor(this->managerObjects.Setting_OutlineColor); mfd->setOptionsOutlineThickness(this->managerObjects.Setting_OutlineThickness); mfd->setOptionsSelected(0); glm::mat4 mvpMatrix = this->matrixProjection * this->matrixCamera * matrixModel; glUniformMatrix4fv(this->glVS_MVPMatrix, 1, GL_FALSE, glm::value_ptr(mvpMatrix)); glUniformMatrix4fv(this->glFS_MMatrix, 1, GL_FALSE, glm::value_ptr(matrixModel)); glm::mat4 matrixModelView = this->matrixCamera * matrixModel; glUniformMatrix4fv(this->glFS_MVMatrix, 1, GL_FALSE, glm::value_ptr(matrixModelView)); glm::mat3 matrixNormal = glm::inverseTranspose(glm::mat3(this->matrixCamera * matrixModel)); glUniformMatrix3fv(this->glVS_NormalMatrix, 1, GL_FALSE, glm::value_ptr(matrixNormal)); glm::mat4 matrixWorld = matrixModel; glUniformMatrix4fv(this->glVS_WorldMatrix, 1, GL_FALSE, glm::value_ptr(matrixWorld)); // blending if (mfd->meshModel.ModelMaterial.Transparency < 1.0f || mfd->Setting_Alpha < 1.0f) { glDisable(GL_DEPTH_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); if (mfd->meshModel.ModelMaterial.Transparency < 1.0f) glUniform1f(this->glFS_AlphaBlending, mfd->meshModel.ModelMaterial.Transparency); else glUniform1f(this->glFS_AlphaBlending, mfd->Setting_Alpha); } else { glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glDisable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glUniform1f(this->glFS_AlphaBlending, 1.0); } // tessellation glUniform1i(this->glTCS_UseCullFace, mfd->Setting_UseCullFace); glUniform1i(this->glTCS_UseTessellation, mfd->Setting_UseTessellation); glUniform1i(this->glTCS_TessellationSubdivision, mfd->Setting_TessellationSubdivision); // cel-shading glUniform1i(this->glFS_CelShading, mfd->Setting_CelShading); // camera position glUniform3f(this->glFS_CameraPosition, this->vecCameraPosition.x, this->vecCameraPosition.y, this->vecCameraPosition.z); // screen size glUniform1f(this->glFS_ScreenResX, Settings::Instance()->SDL_DrawableSize_Width); glUniform1f(this->glFS_ScreenResY, Settings::Instance()->SDL_DrawableSize_Height); // Outline color glUniform3f(this->glFS_OutlineColor, mfd->getOptionsOutlineColor().r, mfd->getOptionsOutlineColor().g, mfd->getOptionsOutlineColor().b); // ambient color for editor glUniform3f(this->glFS_UIAmbient, this->uiAmbientLight.r, this->uiAmbientLight.g, this->uiAmbientLight.b); // geometry shader displacement glUniform3f(this->glGS_GeomDisplacementLocation, mfd->displaceX->point, mfd->displaceY->point, mfd->displaceZ->point); // mapping glUniform1i(this->glMaterial_ParallaxMapping, mfd->Setting_ParallaxMapping); // gamma correction glUniform1f(this->glFS_GammaCoeficient, this->managerObjects.Setting_GammaCoeficient); // render skin glUniform1i(this->gl_ModelViewSkin, mfd->Setting_ModelViewSkin); glUniform3f(this->glFS_solidSkin_materialColor, mfd->solidLightSkin_MaterialColor.r, mfd->solidLightSkin_MaterialColor.g, mfd->solidLightSkin_MaterialColor.b); glUniform1i(this->solidLight->gl_InUse, 1); glUniform3f(this->solidLight->gl_Direction, this->managerObjects.SolidLight_Direction.x, this->managerObjects.SolidLight_Direction.y, this->managerObjects.SolidLight_Direction.z); glUniform3f(this->solidLight->gl_Ambient, this->managerObjects.SolidLight_Ambient.r, this->managerObjects.SolidLight_Ambient.g, this->managerObjects.SolidLight_Ambient.b); glUniform3f(this->solidLight->gl_Diffuse, this->managerObjects.SolidLight_Diffuse.r, this->managerObjects.SolidLight_Diffuse.g, this->managerObjects.SolidLight_Diffuse.b); glUniform3f(this->solidLight->gl_Specular, this->managerObjects.SolidLight_Specular.r, this->managerObjects.SolidLight_Specular.g, this->managerObjects.SolidLight_Specular.b); glUniform1f(this->solidLight->gl_StrengthAmbient, this->managerObjects.SolidLight_Ambient_Strength); glUniform1f(this->solidLight->gl_StrengthDiffuse, this->managerObjects.SolidLight_Diffuse_Strength); glUniform1f(this->solidLight->gl_StrengthSpecular, this->managerObjects.SolidLight_Specular_Strength); // lights size_t lightsCount_Directional = 0, lightsCount_Point = 0, lightsCount_Spot = 0; for (size_t j = 0; j < mfd->lightSources.size(); j++) { Light* light = mfd->lightSources[j]; assert(light->type == LightSourceType_Directional || light->type == LightSourceType_Point || light->type == LightSourceType_Spot); switch (light->type) { case LightSourceType_Directional: { if (lightsCount_Directional < static_cast<size_t>(this->GLSL_LightSourceNumber_Directional)) { ModelFace_LightSource_Directional* f = this->mfLights_Directional[lightsCount_Directional]; glUniform1i(f->gl_InUse, 1); // light glUniform3f(f->gl_Direction, light->matrixModel[2].x, light->matrixModel[2].y, light->matrixModel[2].z); // color glUniform3f(f->gl_Ambient, light->ambient->color.r, light->ambient->color.g, light->ambient->color.b); glUniform3f(f->gl_Diffuse, light->diffuse->color.r, light->diffuse->color.g, light->diffuse->color.b); glUniform3f(f->gl_Specular, light->specular->color.r, light->specular->color.g, light->specular->color.b); // light factors glUniform1f(f->gl_StrengthAmbient, light->ambient->strength); glUniform1f(f->gl_StrengthDiffuse, light->diffuse->strength); glUniform1f(f->gl_StrengthSpecular, light->specular->strength); lightsCount_Directional += 1; } break; } case LightSourceType_Point: { if (lightsCount_Point < static_cast<size_t>(this->GLSL_LightSourceNumber_Point)) { ModelFace_LightSource_Point* f = this->mfLights_Point[lightsCount_Point]; glUniform1i(f->gl_InUse, 1); // light glUniform3f(f->gl_Position, light->matrixModel[3].x, light->matrixModel[3].y, light->matrixModel[3].z); // factors glUniform1f(f->gl_Constant, light->lConstant->point); glUniform1f(f->gl_Linear, light->lLinear->point); glUniform1f(f->gl_Quadratic, light->lQuadratic->point); // color glUniform3f(f->gl_Ambient, light->ambient->color.r, light->ambient->color.g, light->ambient->color.b); glUniform3f(f->gl_Diffuse, light->diffuse->color.r, light->diffuse->color.g, light->diffuse->color.b); glUniform3f(f->gl_Specular, light->specular->color.r, light->specular->color.g, light->specular->color.b); // light factors glUniform1f(f->gl_StrengthAmbient, light->ambient->strength); glUniform1f(f->gl_StrengthDiffuse, light->diffuse->strength); glUniform1f(f->gl_StrengthSpecular, light->specular->strength); lightsCount_Point += 1; } break; } case LightSourceType_Spot: { if (lightsCount_Spot < static_cast<size_t>(this->GLSL_LightSourceNumber_Spot)) { ModelFace_LightSource_Spot* f = this->mfLights_Spot[lightsCount_Spot]; glUniform1i(f->gl_InUse, 1); // light glUniform3f(f->gl_Direction, light->matrixModel[2].x, light->matrixModel[2].y, light->matrixModel[2].z); glUniform3f(f->gl_Position, light->matrixModel[3].x, light->matrixModel[3].y, light->matrixModel[3].z); // cutoff glUniform1f(f->gl_CutOff, glm::cos(glm::radians(light->lCutOff->point))); glUniform1f(f->gl_OuterCutOff, glm::cos(glm::radians(light->lOuterCutOff->point))); // factors glUniform1f(f->gl_Constant, light->lConstant->point); glUniform1f(f->gl_Linear, light->lLinear->point); glUniform1f(f->gl_Quadratic, light->lQuadratic->point); // color glUniform3f(f->gl_Ambient, light->ambient->color.r, light->ambient->color.g, light->ambient->color.b); glUniform3f(f->gl_Diffuse, light->diffuse->color.r, light->diffuse->color.g, light->diffuse->color.b); glUniform3f(f->gl_Specular, light->specular->color.r, light->specular->color.g, light->specular->color.b); // light factors glUniform1f(f->gl_StrengthAmbient, light->ambient->strength); glUniform1f(f->gl_StrengthDiffuse, light->diffuse->strength); glUniform1f(f->gl_StrengthSpecular, light->specular->strength); lightsCount_Spot += 1; } break; } } } for (size_t j = lightsCount_Directional; j < static_cast<size_t>(this->GLSL_LightSourceNumber_Directional); j++) { glUniform1i(this->mfLights_Directional[j]->gl_InUse, 0); } for (size_t j = lightsCount_Point; j < static_cast<size_t>(this->GLSL_LightSourceNumber_Point); j++) { glUniform1i(this->mfLights_Point[j]->gl_InUse, 0); } for (size_t j = lightsCount_Spot; j < static_cast<size_t>(this->GLSL_LightSourceNumber_Spot); j++) { glUniform1i(this->mfLights_Spot[j]->gl_InUse, 0); } // material glUniform1f(this->glMaterial_Refraction, mfd->Setting_MaterialRefraction->point); glUniform1f(this->glMaterial_SpecularExp, mfd->Setting_MaterialSpecularExp->point); glUniform1i(this->glMaterial_IlluminationModel, static_cast<int>(mfd->materialIlluminationModel)); glUniform1f(this->glMaterial_HeightScale, mfd->displacementHeightScale->point); glUniform3f(this->glMaterial_Ambient, mfd->materialAmbient->color.r, mfd->materialAmbient->color.g, mfd->materialAmbient->color.b); glUniform3f(this->glMaterial_Diffuse, mfd->materialDiffuse->color.r, mfd->materialDiffuse->color.g, mfd->materialDiffuse->color.b); glUniform3f(this->glMaterial_Specular, mfd->materialSpecular->color.r, mfd->materialSpecular->color.g, mfd->materialSpecular->color.b); glUniform3f(this->glMaterial_Emission, mfd->materialEmission->color.r, mfd->materialEmission->color.g, mfd->materialEmission->color.b); if (mfd->vboTextureAmbient > 0 && mfd->meshModel.ModelMaterial.TextureAmbient.UseTexture) { glUniform1i(this->glMaterial_HasTextureAmbient, 1); glUniform1i(this->glMaterial_SamplerAmbient, 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, mfd->vboTextureAmbient); } else glUniform1i(this->glMaterial_HasTextureAmbient, 0); if (mfd->vboTextureDiffuse > 0 && mfd->meshModel.ModelMaterial.TextureDiffuse.UseTexture) { glUniform1i(this->glMaterial_HasTextureDiffuse, 1); glUniform1i(this->glMaterial_SamplerDiffuse, 1); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, mfd->vboTextureDiffuse); } else glUniform1i(this->glMaterial_HasTextureDiffuse, 0); if (mfd->vboTextureSpecular > 0 && mfd->meshModel.ModelMaterial.TextureSpecular.UseTexture) { glUniform1i(this->glMaterial_HasTextureSpecular, 1); glUniform1i(this->glMaterial_SamplerSpecular, 2); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, mfd->vboTextureSpecular); } else glUniform1i(this->glMaterial_HasTextureSpecular, 0); if (mfd->vboTextureSpecularExp > 0 && mfd->meshModel.ModelMaterial.TextureSpecularExp.UseTexture) { glUniform1i(this->glMaterial_HasTextureSpecularExp, 1); glUniform1i(this->glMaterial_SamplerSpecularExp, 3); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, mfd->vboTextureSpecularExp); } else glUniform1i(this->glMaterial_HasTextureSpecularExp, 0); if (mfd->vboTextureDissolve > 0 && mfd->meshModel.ModelMaterial.TextureDissolve.UseTexture) { glUniform1i(this->glMaterial_HasTextureDissolve, 1); glUniform1i(this->glMaterial_SamplerDissolve, 4); glActiveTexture(GL_TEXTURE4); glBindTexture(GL_TEXTURE_2D, mfd->vboTextureDissolve); } else glUniform1i(this->glMaterial_HasTextureDissolve, 0); if (mfd->vboTextureBump > 0 && mfd->meshModel.ModelMaterial.TextureBump.UseTexture) { glUniform1i(this->glMaterial_HasTextureBump, 1); glUniform1i(this->glMaterial_SamplerBump, 5); glActiveTexture(GL_TEXTURE5); glBindTexture(GL_TEXTURE_2D, mfd->vboTextureBump); } else glUniform1i(this->glMaterial_HasTextureBump, 0); if (mfd->vboTextureDisplacement > 0 && mfd->meshModel.ModelMaterial.TextureDisplacement.UseTexture) { glUniform1i(this->glMaterial_HasTextureDisplacement, 1); glUniform1i(this->glMaterial_SamplerDisplacement, 6); glActiveTexture(GL_TEXTURE6); glBindTexture(GL_TEXTURE_2D, mfd->vboTextureDisplacement); } else glUniform1i(this->glMaterial_HasTextureDisplacement, 0); // effects - gaussian blur glUniform1i(this->glEffect_GB_Mode, mfd->Effect_GBlur_Mode - 1); glUniform1f(this->glEffect_GB_W, mfd->Effect_GBlur_Width->point); glUniform1f(this->glEffect_GB_Radius, mfd->Effect_GBlur_Radius->point); // effects - bloom // TODO: Bloom effect glUniform1i(this->glEffect_Bloom_doBloom, mfd->Effect_Bloom_doBloom); glUniform1f(this->glEffect_Bloom_WeightA, mfd->Effect_Bloom_WeightA); glUniform1f(this->glEffect_Bloom_WeightB, mfd->Effect_Bloom_WeightB); glUniform1f(this->glEffect_Bloom_WeightC, mfd->Effect_Bloom_WeightC); glUniform1f(this->glEffect_Bloom_WeightD, mfd->Effect_Bloom_WeightD); glUniform1f(this->glEffect_Bloom_Vignette, mfd->Effect_Bloom_Vignette); glUniform1f(this->glEffect_Bloom_VignetteAtt, mfd->Effect_Bloom_VignetteAtt); // effects - tone mapping glUniform1i(this->glEffect_ToneMapping_ACESFilmRec2020, mfd->Effect_ToneMapping_ACESFilmRec2020); glUniform1f(this->glVS_IsBorder, 0.0); // model draw glUniform1f(this->glVS_IsBorder, 0.0); glm::mat4 mtxModel = glm::scale(matrixModel, glm::vec3(1.0, 1.0, 1.0)); glm::mat4 mvpMatrixDraw = this->matrixProjection * this->matrixCamera * mtxModel; glUniformMatrix4fv(this->glVS_MVPMatrix, 1, GL_FALSE, glm::value_ptr(mvpMatrixDraw)); glUniformMatrix4fv(this->glFS_MMatrix, 1, GL_FALSE, glm::value_ptr(mtxModel)); mfd->vertexSphereVisible = this->managerObjects.Setting_VertexSphere_Visible; mfd->vertexSphereRadius = this->managerObjects.Setting_VertexSphere_Radius; mfd->vertexSphereSegments = this->managerObjects.Setting_VertexSphere_Segments; mfd->vertexSphereColor = this->managerObjects.Setting_VertexSphere_Color; mfd->vertexSphereIsSphere = this->managerObjects.Setting_VertexSphere_IsSphere; mfd->vertexSphereShowWireframes = this->managerObjects.Setting_VertexSphere_ShowWireframes; mfd->renderModel(true); } glUseProgram(0); }
57.027182
251
0.736365
supudo
6217a1836b7e95e4c902fa7d2642aa70a2c8edc7
4,122
cpp
C++
src/legecy/stereo_block_matching.cpp
behnamasadi/OpenCVProjects
157c8d536c78c5660b64a23300a7aaf941584756
[ "BSD-3-Clause" ]
null
null
null
src/legecy/stereo_block_matching.cpp
behnamasadi/OpenCVProjects
157c8d536c78c5660b64a23300a7aaf941584756
[ "BSD-3-Clause" ]
null
null
null
src/legecy/stereo_block_matching.cpp
behnamasadi/OpenCVProjects
157c8d536c78c5660b64a23300a7aaf941584756
[ "BSD-3-Clause" ]
null
null
null
#include <opencv2/opencv.hpp> const char *windowDisparity = "Disparity"; cv::Mat imgLeft; cv::Mat imgRight; cv::Mat imgDisparity16S; cv::Mat imgDisparity8U; int ndisparities= 16*5; int SADWindowSize= 21; double minVal; double maxVal; cv::StereoBM sbm( cv::StereoBM::NARROW_PRESET,ndisparities,SADWindowSize ); void on_trackbar( int, void* ) { std::cout <<"ndisparities: " <<16*ndisparities <<std::endl; std::cout <<"SADWindowSize: " <<SADWindowSize <<std::endl; if(SADWindowSize%2 !=0 && SADWindowSize>4) { sbm.init(cv::StereoBM::NARROW_PRESET,16*ndisparities ,SADWindowSize); sbm( imgLeft, imgRight, imgDisparity16S, CV_16S ); minMaxLoc( imgDisparity16S, &minVal, &maxVal ); imgDisparity16S.convertTo( imgDisparity8U, CV_8UC1, 255/(maxVal - minVal)); cv::namedWindow( windowDisparity, cv::WINDOW_NORMAL ); cv::imshow( windowDisparity, imgDisparity8U ); } } //For an in-depth discussion of the block matching algorithm, see pages 438-444 of Learning OpenCV. //https://github.com/opencv/opencv/blob/2.4/samples/cpp/tutorial_code/calib3d/stereoBM/SBM_Sample.cpp int disparity_map_using_sbm_example(int argc, char ** argv) { //char* n_argv[] = { "stereo_block_matching", "../images/stereo_vision/tsucuba_left.png", "../images/stereo_vision/tsucuba_right.png"}; char* n_argv[] = { "stereo_block_matching", "rect_left01.jpg", "rect_right01.jpg"}; int length = sizeof(n_argv)/sizeof(n_argv[0]); argc=length; argv = n_argv; imgLeft = cv::imread( argv[1], CV_LOAD_IMAGE_GRAYSCALE ); imgRight = cv::imread( argv[2], CV_LOAD_IMAGE_GRAYSCALE ); //-- And create the image in which we will save our disparities imgDisparity16S = cv::Mat( imgLeft.rows, imgLeft.cols, CV_16S ); imgDisparity8U = cv::Mat( imgLeft.rows, imgLeft.cols, CV_8UC1 ); //-- 2. Call the constructor for StereoBM //ndisparities must be multiple of 8 //-- 3. Calculate the disparity image sbm( imgLeft, imgRight, imgDisparity16S, CV_16S ); //-- Check its extreme values minMaxLoc( imgDisparity16S, &minVal, &maxVal ); printf("Min disp: %f Max value: %f \n", minVal, maxVal); //-- 4. Display it as a CV_8UC1 image imgDisparity16S.convertTo( imgDisparity8U, CV_8UC1, 255/(maxVal - minVal)); cv::namedWindow( windowDisparity, cv::WINDOW_NORMAL ); cv::imshow( windowDisparity, imgDisparity8U ); //Create trackbars in "Control" window ndisparities=ndisparities/16; cv::createTrackbar("ndisparities (multipled by 16)", windowDisparity, &ndisparities, 20,on_trackbar); //ndisparities (0 - 20) cv::createTrackbar("SADWindowSize (must be odd, be within 5..255) ", windowDisparity, &SADWindowSize, 255,on_trackbar); //SADWindowSize(0 - 100) //-- 5. Save the image //imwrite("SBM_sample.png", imgDisparity16S); // cv::reprojectImageTo3D(imgDisparity8U,) cv::waitKey(0); return 0; } void disparity_map_using_sgbm_example(int argc, char ** argv) { char* n_argv[] = { "stereo_block_matching", "../images/stereo_vision/tsucuba_left.png", "../images/stereo_vision/tsucuba_right.png"}; int length = sizeof(n_argv)/sizeof(n_argv[0]); argc=length; argv = n_argv; cv::Mat img1, img2, g1, g2; cv::Mat disp, disp8; img1 = cv::imread(argv[1]); img2 = cv::imread(argv[2]); cv::cvtColor(img1, g1, CV_BGR2GRAY); cv::cvtColor(img2, g2, CV_BGR2GRAY); cv::StereoSGBM sbm; sbm.SADWindowSize = 3; sbm.numberOfDisparities = 144; sbm.preFilterCap = 63; sbm.minDisparity = -39; sbm.uniquenessRatio = 10; sbm.speckleWindowSize = 100; sbm.speckleRange = 32; sbm.disp12MaxDiff = 1; sbm.fullDP = false; sbm.P1 = 216; sbm.P2 = 864; sbm(g1, g2, disp); normalize(disp, disp8, 0, 255, CV_MINMAX, CV_8U); imshow("left", img1); imshow("right", img2); imshow("disp", disp8); cv::waitKey(0); // cv::finds } int main(int argc, char** argv) { // disparity_map_using_sgbm_example(argc, argv); disparity_map_using_sbm_example(argc, argv); }
25.288344
148
0.673459
behnamasadi
6218b5bec030cb10643d1c699b703620e70da83f
950
cpp
C++
42dynamicProgrammingPractice/dynamicPragrammingPractice/dynamicPragrammingPractice/main.cpp
mingyuefly/geekTimeCode
d97c5f29a429ac9cc7289ac34e049ea43fa58822
[ "MIT" ]
1
2019-05-01T04:51:14.000Z
2019-05-01T04:51:14.000Z
42dynamicProgrammingPractice/dynamicPragrammingPractice/dynamicPragrammingPractice/main.cpp
mingyuefly/geekTimeCode
d97c5f29a429ac9cc7289ac34e049ea43fa58822
[ "MIT" ]
null
null
null
42dynamicProgrammingPractice/dynamicPragrammingPractice/dynamicPragrammingPractice/main.cpp
mingyuefly/geekTimeCode
d97c5f29a429ac9cc7289ac34e049ea43fa58822
[ "MIT" ]
null
null
null
// // main.cpp // dynamicPragrammingPractice // // Created by Gguomingyue on 2019/2/20. // Copyright © 2019 Gmingyue. All rights reserved. // #include <iostream> using namespace std; static char a[6] = {'m', 'i', 't', 'c', 'm', 'u'}; static char b[6] = {'m', 't', 'a', 'c', 'n', 'u'}; static int n = 6; static int m = 6; static int minDist = 100; void lowestLD(int i, int j, int edist) { if (i == n || j == m) { if (i < n) { edist += (n - i); } if (j < m) { edist += (m - j); } if (edist < minDist) { minDist = edist; } return; } if (a[i] == b[j]) { lowestLD(i+1, j+1, edist); } else { lowestLD(i+1, j, edist+1); lowestLD(i, j+1, edist+1); lowestLD(i+1, j+1, edist+1); } } int main(int argc, const char * argv[]) { lowestLD(0, 0, 0); cout << minDist << endl; return 0; }
19.791667
51
0.458947
mingyuefly
6220912b9a447006b2176693483116c5a94863e7
4,939
cpp
C++
src/xbox/xbox_interface.cpp
abaire/xbdm_gdb_bridge
06440896f1f2863cd81cedd3e2bcae1efc32f286
[ "Unlicense" ]
5
2021-12-22T02:43:41.000Z
2022-03-20T19:18:44.000Z
src/xbox/xbox_interface.cpp
abaire/xbdm_gdb_bridge
06440896f1f2863cd81cedd3e2bcae1efc32f286
[ "Unlicense" ]
1
2022-01-11T06:18:04.000Z
2022-01-11T06:18:04.000Z
src/xbox/xbox_interface.cpp
abaire/xbdm_gdb_bridge
06440896f1f2863cd81cedd3e2bcae1efc32f286
[ "Unlicense" ]
null
null
null
#include "xbox_interface.h" #include <unistd.h> #include <boost/asio/dispatch.hpp> #include <cassert> #include <iostream> #include <utility> #include "gdb/gdb_transport.h" #include "net/delegating_server.h" #include "net/select_thread.h" #include "notification/xbdm_notification.h" #include "util/logging.h" #include "xbox/bridge/gdb_bridge.h" #include "xbox/debugger/xbdm_debugger.h" #include "xbox/xbdm_context.h" XBOXInterface::XBOXInterface(std::string name, IPAddress xbox_address) : name_(std::move(name)), xbox_address_(std::move(xbox_address)) {} void XBOXInterface::Start() { Stop(); select_thread_ = std::make_shared<SelectThread>(); xbdm_context_ = std::make_shared<XBDMContext>(name_, xbox_address_, select_thread_); select_thread_->Start(); } void XBOXInterface::Stop() { if (select_thread_) { select_thread_->Stop(); select_thread_.reset(); } if (xbdm_context_) { xbdm_context_->Shutdown(); xbdm_context_.reset(); } } bool XBOXInterface::ReconnectXBDM() { if (!xbdm_context_) { return false; } return xbdm_context_->Reconnect(); } bool XBOXInterface::AttachDebugger() { if (!xbdm_debugger_) { xbdm_debugger_ = std::make_shared<XBDMDebugger>(xbdm_context_); } return xbdm_debugger_->Attach(); } void XBOXInterface::DetachDebugger() { if (!xbdm_debugger_) { return; } xbdm_debugger_->Shutdown(); xbdm_debugger_.reset(); } bool XBOXInterface::StartGDBServer(const IPAddress& address) { StopGDBServer(); gdb_executor_ = std::make_shared<boost::asio::thread_pool>(1); if (!xbdm_debugger_) { xbdm_debugger_ = std::make_shared<XBDMDebugger>(xbdm_context_); } gdb_bridge_ = std::make_shared<GDBBridge>(xbdm_context_, xbdm_debugger_); gdb_server_ = std::make_shared<DelegatingServer>( name_ + "__gdb_server", [this](int sock, IPAddress& address) { this->OnGDBClientConnected(sock, address); }); select_thread_->AddConnection(gdb_server_); return gdb_server_->Listen(address); } void XBOXInterface::StopGDBServer() { if (gdb_server_) { gdb_server_->Close(); gdb_server_.reset(); } if (gdb_bridge_) { gdb_bridge_->Stop(); gdb_bridge_.reset(); } if (gdb_executor_) { gdb_executor_->stop(); gdb_executor_->join(); gdb_executor_.reset(); } } bool XBOXInterface::GetGDBListenAddress(IPAddress& ret) const { if (!gdb_server_) { return false; } ret = gdb_server_->Address(); return true; } bool XBOXInterface::StartNotificationListener(const IPAddress& address) { if (!xbdm_context_) { return false; } return xbdm_context_->StartNotificationListener(address); } void XBOXInterface::AttachDebugNotificationHandler() { if (debug_notification_handler_id_ > 0) { return; } debug_notification_handler_id_ = xbdm_context_->RegisterNotificationHandler( [](const std::shared_ptr<XBDMNotification>& notification) { std::cout << *notification << std::endl; }); } void XBOXInterface::DetachDebugNotificationHandler() { if (debug_notification_handler_id_ <= 0) { return; } xbdm_context_->UnregisterNotificationHandler(debug_notification_handler_id_); debug_notification_handler_id_ = 0; } std::shared_ptr<RDCPProcessedRequest> XBOXInterface::SendCommandSync( std::shared_ptr<RDCPProcessedRequest> command) { assert(xbdm_context_); return xbdm_context_->SendCommandSync(std::move(command)); } std::future<std::shared_ptr<RDCPProcessedRequest>> XBOXInterface::SendCommand( std::shared_ptr<RDCPProcessedRequest> command) { assert(xbdm_context_); return xbdm_context_->SendCommand(std::move(command)); } void XBOXInterface::OnGDBClientConnected(int sock, IPAddress& address) { assert(gdb_bridge_); if (gdb_bridge_->HasGDBClient()) { LOG_XBDM(warning) << "Disallowing additional GDB connection from " << address; shutdown(sock, SHUT_RDWR); close(sock); return; } LOG_XBDM(trace) << "GDB channel established from " << address; auto transport = std::make_shared<GDBTransport>( "GDB", sock, address, [this](const std::shared_ptr<GDBPacket>& packet) { this->OnGDBPacketReceived(packet); }); // Bounce to the executor so the select thread is not blocked by any attempt // to communicate with XBDM. assert(gdb_executor_); boost::asio::dispatch(*gdb_executor_, [this, transport]() mutable { this->xbdm_debugger_->Attach(); this->xbdm_debugger_->HaltAll(); this->select_thread_->AddConnection(transport); this->gdb_bridge_->AddTransport(transport); }); } void XBOXInterface::OnGDBPacketReceived( const std::shared_ptr<GDBPacket>& packet) { assert(gdb_executor_); boost::asio::dispatch(*gdb_executor_, [this, packet]() mutable { this->DispatchGDBPacket(packet); }); } void XBOXInterface::DispatchGDBPacket( const std::shared_ptr<GDBPacket>& packet) { gdb_bridge_->HandlePacket(*packet); }
26.411765
79
0.715125
abaire
6223b18bd74bb8dd8120c7c358f1f1422a950de1
4,420
hpp
C++
include/System/IO/FileInfo.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/IO/FileInfo.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/IO/FileInfo.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: System.IO.FileSystemInfo #include "System/IO/FileSystemInfo.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::IO namespace System::IO { // Forward declaring type: StreamWriter class StreamWriter; } // Forward declaring namespace: System::Runtime::Serialization namespace System::Runtime::Serialization { // Forward declaring type: SerializationInfo class SerializationInfo; } // Completed forward declares // Type namespace: System.IO namespace System::IO { // Size: 0x68 #pragma pack(push, 1) // Autogenerated type: System.IO.FileInfo // [ComVisibleAttribute] Offset: D7C894 class FileInfo : public System::IO::FileSystemInfo { public: // private System.String _name // Size: 0x8 // Offset: 0x60 ::Il2CppString* name; // Field size check static_assert(sizeof(::Il2CppString*) == 0x8); // Creating value type constructor for type: FileInfo FileInfo(::Il2CppString* name_ = {}) noexcept : name{name_} {} // public System.Void .ctor(System.String fileName) // Offset: 0x1933E44 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static FileInfo* New_ctor(::Il2CppString* fileName) { static auto ___internal__logger = ::Logger::get().WithContext("System::IO::FileInfo::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<FileInfo*, creationType>(fileName))); } // private System.Void Init(System.String fileName, System.Boolean checkHost) // Offset: 0x1933EE4 void Init(::Il2CppString* fileName, bool checkHost); // private System.String GetDisplayPath(System.String originalPath) // Offset: 0x1933FD4 ::Il2CppString* GetDisplayPath(::Il2CppString* originalPath); // public System.String get_DirectoryName() // Offset: 0x1934070 ::Il2CppString* get_DirectoryName(); // public System.IO.StreamWriter CreateText() // Offset: 0x19340D8 System::IO::StreamWriter* CreateText(); // public System.IO.StreamWriter AppendText() // Offset: 0x1934140 System::IO::StreamWriter* AppendText(); // private System.Void .ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) // Offset: 0x1933FDC // Implemented from: System.IO.FileSystemInfo // Base method: System.Void FileSystemInfo::.ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static FileInfo* New_ctor(System::Runtime::Serialization::SerializationInfo* info, System::Runtime::Serialization::StreamingContext context) { static auto ___internal__logger = ::Logger::get().WithContext("System::IO::FileInfo::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<FileInfo*, creationType>(info, context))); } // public override System.String get_Name() // Offset: 0x1934068 // Implemented from: System.IO.FileSystemInfo // Base method: System.String FileSystemInfo::get_Name() ::Il2CppString* get_Name(); // public override System.Boolean get_Exists() // Offset: 0x19341A8 // Implemented from: System.IO.FileSystemInfo // Base method: System.Boolean FileSystemInfo::get_Exists() bool get_Exists(); // public override System.String ToString() // Offset: 0x193429C // Implemented from: System.Object // Base method: System.String Object::ToString() ::Il2CppString* ToString(); }; // System.IO.FileInfo #pragma pack(pop) static check_size<sizeof(FileInfo), 96 + sizeof(::Il2CppString*)> __System_IO_FileInfoSizeCheck; static_assert(sizeof(FileInfo) == 0x68); } DEFINE_IL2CPP_ARG_TYPE(System::IO::FileInfo*, "System.IO", "FileInfo");
47.021277
162
0.703846
darknight1050
62262d7d75a5698815745d969c27290e961e9934
4,906
cpp
C++
pxr/base/tf/pyTracing.cpp
yurivict/USD
3b097e3ba8fabf1777a1256e241ea15df83f3065
[ "Apache-2.0" ]
1
2021-09-25T12:49:37.000Z
2021-09-25T12:49:37.000Z
pxr/base/tf/pyTracing.cpp
yurivict/USD
3b097e3ba8fabf1777a1256e241ea15df83f3065
[ "Apache-2.0" ]
null
null
null
pxr/base/tf/pyTracing.cpp
yurivict/USD
3b097e3ba8fabf1777a1256e241ea15df83f3065
[ "Apache-2.0" ]
1
2018-10-03T19:08:33.000Z
2018-10-03T19:08:33.000Z
// // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/pxr.h" #include "pxr/base/tf/pyTracing.h" #ifdef PXR_PYTHON_SUPPORT_ENABLED #include "pxr/base/tf/pyInterpreter.h" #include "pxr/base/tf/pyUtils.h" #include "pxr/base/tf/staticData.h" #include <memory> #include <tbb/spin_mutex.h> // This is from python, needed for PyFrameObject. #include <frameobject.h> #include <list> #include <mutex> using std::list; PXR_NAMESPACE_OPEN_SCOPE typedef list<std::weak_ptr<TfPyTraceFn> > TraceFnList; static TfStaticData<TraceFnList> _traceFns; static bool _traceFnInstalled; static tbb::spin_mutex _traceFnMutex; static void _SetTraceFnEnabled(bool enable); static void _InvokeTraceFns(TfPyTraceInfo const &info) { // Take the lock, and swap out the list of trace fns for an empty list. We // do this so we don't hold the lock and call unknown code. If functions // expire while we're executing, that's fine since we .lock() each one to // get a dereferenceable shared_ptr, and if new functions are added, that's // okay too since we splice the copy back into the official list when we're // done. TraceFnList local; { tbb::spin_mutex::scoped_lock lock(_traceFnMutex); local.splice(local.end(), *_traceFns); } // Walk the fns, and invoke them if they're present, erase them if they're // not. for (TraceFnList::iterator i = local.begin(); i != local.end();) { if (TfPyTraceFnId ptr = i->lock()) { (*ptr)(info); ++i; } else { local.erase(i++); } } // Now splice the local back into the real list. { tbb::spin_mutex::scoped_lock lock(_traceFnMutex); _traceFns->splice(_traceFns->end(), local); // If the list is empty, uninstall the trace fn. if (_traceFns->empty()) _SetTraceFnEnabled(false); } } static int _TracePythonFn(PyObject *, PyFrameObject *frame, int what, PyObject *arg); static void _SetTraceFnEnabled(bool enable) { // NOTE! mutex must be locked by caller! if (enable && !_traceFnInstalled && Py_IsInitialized()) { _traceFnInstalled = true; PyEval_SetTrace(_TracePythonFn, NULL); } else if (!enable && _traceFnInstalled) { _traceFnInstalled = false; PyEval_SetTrace(NULL, NULL); } } static int _TracePythonFn(PyObject *, PyFrameObject *frame, int what, PyObject *arg) { // Build up a trace info struct. TfPyTraceInfo info; info.arg = arg; info.funcName = TfPyString_AsString(frame->f_code->co_name); info.fileName = TfPyString_AsString(frame->f_code->co_filename); info.funcLine = frame->f_code->co_firstlineno; info.what = what; _InvokeTraceFns(info); return 0; } void Tf_PyFabricateTraceEvent(TfPyTraceInfo const &info) { // NOTE: assumes python lock is held by caller. Due to that assumption, we // know that the list of trace functions could only be growing during this // function, and could not go to zero, and have the python trace function be // disabled. So it's safe for us to check the _traceFnInstalled flag here. if (_traceFnInstalled) _InvokeTraceFns(info); } TfPyTraceFnId TfPyRegisterTraceFn(TfPyTraceFn const &f) { tbb::spin_mutex::scoped_lock lock(_traceFnMutex); TfPyTraceFnId ret(new TfPyTraceFn(f)); _traceFns->push_back(ret); _SetTraceFnEnabled(true); return ret; } void Tf_PyTracingPythonInitialized() { static std::once_flag once; std::call_once(once, [](){ TF_AXIOM(Py_IsInitialized()); tbb::spin_mutex::scoped_lock lock(_traceFnMutex); if (!_traceFns->empty()) _SetTraceFnEnabled(true); }); } PXR_NAMESPACE_CLOSE_SCOPE #endif // PXR_PYTHON_SUPPORT_ENABLED
31.050633
80
0.683245
yurivict
6229c2d484d9b4c389c63aaaa3e3980fbf6198d1
1,106
cpp
C++
random_noise_generator/random_noise_factory.cpp
eborghi10/noisy_fit_2d
a1839fac91eda333b9869c9a7add5c6e757a58e2
[ "MIT" ]
null
null
null
random_noise_generator/random_noise_factory.cpp
eborghi10/noisy_fit_2d
a1839fac91eda333b9869c9a7add5c6e757a58e2
[ "MIT" ]
null
null
null
random_noise_generator/random_noise_factory.cpp
eborghi10/noisy_fit_2d
a1839fac91eda333b9869c9a7add5c6e757a58e2
[ "MIT" ]
null
null
null
#include <iostream> #include <memory> #include <string> // Base class #include "noises/random_noise_base.h" // Noise classes #include "noises/linear.h" #include "noises/quadratic.h" #include "noises/simplified_cholesky.h" namespace rng { using RandomNoiseBasePtr = std::unique_ptr<RandomNoiseBase>; class RandomNoiseFactory { public: /** * \brief Generator of RandomNoiseBase. * \param type Type of noise generator. Available options are: linear, quadratic and cholesky. * \return Pointer to RandomNoiseBase. */ static RandomNoiseBasePtr Make(const std::string& type = "linear") { std::cout << "Noise = " << type << std::endl; if(type == "linear") { return std::make_unique<LinearNoise>(); } else if(type == "quadratic") { return std::make_unique<QuadraticNoise>(); } else if(type == "cholesky") { return std::make_unique<SimplifiedCholesky>(); } else { // Default uses linear return std::make_unique<LinearNoise>(); } // Another example: https://en.wikipedia.org/wiki/Anscombe%27s_quartet } }; } // namespace rng
24.577778
96
0.67179
eborghi10
62337011da9d3d36f5ce052d32f3d148646109d5
177
hpp
C++
Cpf/Plugins/Platform/Concurrency/Interface/Concurrency/Concurrency.hpp
All8Up/cpf
81c68fbb69619261a5aa058cda73e35812ed3543
[ "MIT" ]
6
2017-02-15T01:50:32.000Z
2019-07-05T13:50:57.000Z
Cpf/Plugins/Platform/Concurrency/Interface/Concurrency/Concurrency.hpp
All8Up/cpf
81c68fbb69619261a5aa058cda73e35812ed3543
[ "MIT" ]
40
2017-04-06T13:29:02.000Z
2018-04-20T23:39:21.000Z
Cpf/Plugins/Platform/Concurrency/Interface/Concurrency/Concurrency.hpp
All8Up/cpf
81c68fbb69619261a5aa058cda73e35812ed3543
[ "MIT" ]
3
2017-08-03T15:17:01.000Z
2019-03-08T07:58:59.000Z
////////////////////////////////////////////////////////////////////////// #pragma once namespace CPF { namespace Concurrency { static constexpr int kMaxThreads = 64; } }
16.090909
74
0.412429
All8Up
62337383665e6d6b0264360ab9ed7e191ee04b7a
168
hpp
C++
src/main.hpp
ziggi/rustext
5dcfe9f07f9a13b4f2979f98663a68c2ac62e163
[ "MIT" ]
20
2016-09-19T20:37:36.000Z
2022-02-26T14:16:28.000Z
src/main.hpp
ziggi/rustext
5dcfe9f07f9a13b4f2979f98663a68c2ac62e163
[ "MIT" ]
6
2016-12-27T16:49:01.000Z
2020-11-22T16:50:29.000Z
src/main.hpp
ziggi/rustext
5dcfe9f07f9a13b4f2979f98663a68c2ac62e163
[ "MIT" ]
1
2019-02-21T08:10:43.000Z
2019-02-21T08:10:43.000Z
/* About: rustext main Author: ziggi */ #ifndef MAIN_H #define MAIN_H #include <map> #include "common.hpp" #include "converter.hpp" logprintf_t logprintf; #endif
10.5
24
0.720238
ziggi
62360aef9279d488b4ee2c24e9591aedb0cd169d
834
cpp
C++
src/actions/move_by_action.cpp
tomalbrc/rawket-engine
2b7da4f33c874154120fc2d1529081f4f4ae33c7
[ "MIT" ]
null
null
null
src/actions/move_by_action.cpp
tomalbrc/rawket-engine
2b7da4f33c874154120fc2d1529081f4f4ae33c7
[ "MIT" ]
1
2016-03-18T13:54:22.000Z
2016-08-11T22:02:28.000Z
src/actions/move_by_action.cpp
tomalbrc/FayEngine
2b7da4f33c874154120fc2d1529081f4f4ae33c7
[ "MIT" ]
null
null
null
// // move_by_action.cpp // rawket // // Created by Tom Albrecht on 09.12.15. // // #include "move_by_action.hpp" RKT_NAMESPACE_BEGIN move_by_action_ptr move_by_action::create(double pduration, vec2f offset) { move_by_action_ptr p(new move_by_action()); p->init(pduration, offset); return p; } bool move_by_action::init(double pduration, vec2f offset) { changeInVec2Value = offset; duration = pduration*1000; return true; } void move_by_action::update() { auto popos = currentVec2Value(); target->setPosition(popos); if (SDL_GetTicks()-startTick > duration) finished = true, target->setPosition(changeInVec2Value+startVec2Value); } void move_by_action::start() { startTick = SDL_GetTicks(); startVec2Value = target->getPosition(); finished = false; } RKT_NAMESPACE_END
19.857143
116
0.707434
tomalbrc
623939f0120a593b016902b94a91af7d88e57e7c
8,257
cpp
C++
src/Equations/Fluid/HottailRateTermHighZ.cpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
12
2020-09-07T11:19:10.000Z
2022-02-17T17:40:19.000Z
src/Equations/Fluid/HottailRateTermHighZ.cpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
110
2020-09-02T15:29:24.000Z
2022-03-09T09:50:01.000Z
src/Equations/Fluid/HottailRateTermHighZ.cpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
3
2021-05-21T13:24:31.000Z
2022-02-11T14:43:12.000Z
/** * Implementation of equation term representing the runaway generation rate * due to hottail when using an analytic distribution function */ #include "DREAM/Equations/Fluid/HottailRateTermHighZ.hpp" using namespace DREAM; /** * Constructor. * * gsl_altPc* contains parameters and functions needed * to evaluate the critical runaway momentum in the hottail * calculation using a gsl root-finding algorithm * (using the 'alternative' model for pc in Ida's MSc thesis) */ HottailRateTermHighZ::HottailRateTermHighZ( FVM::Grid *grid, AnalyticDistributionHottail *dist, FVM::UnknownQuantityHandler *unknowns, IonHandler *ionHandler, CoulombLogarithm *lnL, real_t sf ) : HottailRateTerm(grid, dist, unknowns,sf), lnL(lnL), id_ncold(unknowns->GetUnknownID(OptionConstants::UQTY_N_COLD)), id_Efield(unknowns->GetUnknownID(OptionConstants::UQTY_E_FIELD)), id_tau(unknowns->GetUnknownID(OptionConstants::UQTY_TAU_COLL)) { SetName("HottailRateTermHighZ"); AddUnknownForJacobian(unknowns,id_Efield); AddUnknownForJacobian(unknowns,id_ncold); AddUnknownForJacobian(unknowns,id_tau); //AddUnknownForJacobian(unknowns,id_ni); // Zeff and lnL (nfree) jacobian //AddUnknownForJacobian(unknowns,id_Tcold); // lnL jacobian this->fdfsolver = gsl_root_fdfsolver_alloc(gsl_root_fdfsolver_secant); gsl_params.ionHandler = ionHandler; gsl_params.rGrid = grid->GetRadialGrid(); gsl_params.dist = dist; gsl_func.f = &(PcFunc); gsl_func.df = &(PcFunc_df); gsl_func.fdf = &(PcFunc_fdf); gsl_func.params = &gsl_params; this->GridRebuilt(); } /** * Destructor */ HottailRateTermHighZ::~HottailRateTermHighZ(){ Deallocate(); gsl_root_fdfsolver_free(fdfsolver); } /** * Called after the grid is rebuilt; (re)allocates memory * for all quantities */ bool HottailRateTermHighZ::GridRebuilt(){ this->HottailRateTerm::GridRebuilt(); Deallocate(); pCrit_prev = new real_t[nr]; return true; } /** * Rebuilds quantities used by this equation term. * Note that the equation term uses the _energy distribution_ * from AnalyticDistributionHottail which differs from the * full distribution function by a factor of 4*pi */ void HottailRateTermHighZ::Rebuild(const real_t t, const real_t dt, FVM::UnknownQuantityHandler*) { this->dt = dt; bool newTimeStep = (t!=tPrev); if(newTimeStep) tPrev = t; for(len_t ir=0; ir<nr; ir++){ if(newTimeStep) pCrit_prev[ir] = pCrit[ir]; real_t fAtPc, dfdpAtPc; pCrit[ir] = evaluateCriticalMomentum(ir, fAtPc, dfdpAtPc); real_t dotPc = (pCrit[ir] - pCrit_prev[ir]) / dt; if (dotPc > 0) // ensure non-negative runaway rate dotPc = 0; gamma[ir] = -pCrit[ir]*pCrit[ir]*dotPc*fAtPc; // generation rate // set derivative of gamma with respect to pCrit (used for jacobian) dGammaDPc[ir] = -(2*pCrit[ir]*dotPc*fAtPc + pCrit[ir]*pCrit[ir]*fAtPc/dt + pCrit[ir]*pCrit[ir]*dotPc*dfdpAtPc); } } /** * Function whose root (with respect to p) represents the * critical runaway momentum in the 'alternative' model */ real_t HottailRateTermHighZ::PcFunc(real_t p, void *par) { if(p<0) // handle case where algorithm leaves the physical domain of non-negative momenta p=0; PcParams *params = (PcParams*)par; len_t ir = params->ir; real_t Eterm = params->Eterm; real_t ncold = params->ncold; real_t tau = params->tau; real_t lnL = params->lnL; real_t dFdpOverF; params->F = params->dist->evaluateEnergyDistributionFromTau(ir,p,tau,&params->dFdp,nullptr, &dFdpOverF); real_t Ec = 4*M_PI*ncold*lnL*Constants::r0*Constants::r0*Constants::c * Constants::me * Constants::c / Constants::ec; real_t E = Eterm/Ec; real_t EPF = params->rGrid->GetEffPassFrac(ir); real_t Zeff = params->ionHandler->GetZeff(ir); real_t p2 = p*p; real_t gamma = sqrt(1+p2); // for the non-relativistic distribution, this function is // approximately linear, yielding efficient root finding return sqrt((p/gamma)*cbrt( p2*E*E*EPF * (-dFdpOverF) )) - sqrt(cbrt( 3*(1+Zeff))); // previous equivalent expression: // real_t g3 = (1+p2)*gamma; // return sqrt(cbrt( p2*p2*p*E*E*EPF * (-dFdpOverF) )) - sqrt(cbrt( 3.0*(1+Zeff)*g3)); } /** * Returns the derivative of PcFunc with respect to p */ real_t HottailRateTermHighZ::PcFunc_df(real_t p, void *par) { real_t h = 1e-3*p; return (PcFunc(p+h,par) - PcFunc(p,par)) / h; } /** * Method which sets both f=PcFunc and df=PcFunc_df */ void HottailRateTermHighZ::PcFunc_fdf(real_t p, void *par, real_t *f, real_t *df){ real_t h = 1e-3*p; *f = PcFunc(p,par); *df = (PcFunc(p+h, par) - *f) / h; } /** * Evaluates the 'alternative' critical momentum pc using Ida's MSc thesis (4.35) */ real_t HottailRateTermHighZ::evaluateCriticalMomentum(len_t ir, real_t &f, real_t &dfdp){ gsl_params.ir = ir; gsl_params.lnL = lnL->evaluateAtP(ir,0); gsl_params.ncold = unknowns->GetUnknownData(id_ncold)[ir]; gsl_params.Eterm = unknowns->GetUnknownData(id_Efield)[ir]; gsl_params.tau = unknowns->GetUnknownData(id_tau)[ir]; real_t root = (pCrit_prev[ir] == 0) ? 5*distHT->GetInitialThermalMomentum(ir) : pCrit_prev[ir]; RunawayFluid::FindRoot_fdf_bounded(0,std::numeric_limits<real_t>::infinity(),root, gsl_func, fdfsolver, RELTOL_FOR_PC, ABSTOL_FOR_PC); f = gsl_params.F; dfdp = gsl_params.dFdp; return root; } /** * Evaluates the jacobian of CriticalMomentum with * respect to the unknown with id 'derivId' */ real_t HottailRateTermHighZ::evaluatePartialCriticalMomentum(len_t ir, len_t derivId){ gsl_params.ir = ir; gsl_params.lnL = lnL->evaluateAtP(ir,0); gsl_params.ncold = unknowns->GetUnknownData(id_ncold)[ir]; gsl_params.Eterm = unknowns->GetUnknownData(id_Efield)[ir]; gsl_params.tau = unknowns->GetUnknownData(id_tau)[ir]; real_t h = 0; if(derivId == id_Efield){ h = (1.0+fabs(gsl_params.Eterm))*sqrt(RELTOL_FOR_PC), gsl_params.Eterm += h; } else if (derivId == id_ncold){ h = (1.0+fabs(gsl_params.ncold))*sqrt(RELTOL_FOR_PC), gsl_params.ncold += h; } else if (derivId == id_tau){ h = (1.0+fabs(gsl_params.tau))*sqrt(RELTOL_FOR_PC), gsl_params.tau += h; } real_t root = pCrit[ir]; RunawayFluid::FindRoot_fdf_bounded(0,std::numeric_limits<real_t>::infinity(),root, gsl_func, fdfsolver, RELTOL_FOR_PC, ABSTOL_FOR_PC); return (root - pCrit[ir])/h; } /** * Sets the Jacobian of this equation term */ bool HottailRateTermHighZ::SetJacobianBlock(const len_t /*uqtyId*/, const len_t derivId, FVM::Matrix *jac, const real_t*){ if(!HasJacobianContribution(derivId)) return false; for(len_t ir=0; ir<nr; ir++){ const len_t xiIndex = this->GetXiIndexForEDirection(ir); const len_t np1 = this->grid->GetMomentumGrid(ir)->GetNp1(); real_t V = GetVolumeScaleFactor(ir); // Check if the quantity w.r.t. which we differentiate is a // fluid quantity, in which case it has np1=1, xiIndex=0 len_t np1_op = np1, xiIndex_op = xiIndex; if (unknowns->GetUnknown(derivId)->NumberOfElements() == nr) { np1_op = 1; xiIndex_op = 0; } real_t dPc = evaluatePartialCriticalMomentum(ir, derivId); real_t dGamma = dPc * dGammaDPc[ir]; if(derivId==id_tau){ // add contribution from explicit tau dependence in f real_t dotPc = (pCrit[ir] - pCrit_prev[ir]) / dt; if (dotPc > 0) // ensure non-negative runaway rate dotPc = 0; real_t tau = unknowns->GetUnknownData(id_tau)[ir]; real_t dFdTauAtPc; distHT->evaluateEnergyDistributionFromTau(ir, pCrit[ir], tau, nullptr, nullptr, nullptr, &dFdTauAtPc); dGamma -= pCrit[ir]*pCrit[ir]*dotPc*dFdTauAtPc; } jac->SetElement(ir + np1*xiIndex, ir + np1_op*xiIndex_op, scaleFactor * dGamma * V); } return true; } /** * Deallocator */ void HottailRateTermHighZ::Deallocate(){ if(pCrit_prev != nullptr) delete [] pCrit_prev; }
34.987288
138
0.669977
chalmersplasmatheory
623a159d3ca2db1b550deccf4256c78327c053ba
3,197
hpp
C++
Examples/ProgAnalysis/Cfg.hpp
jusito/WALi-OpenNWA
2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99
[ "MIT" ]
15
2015-03-07T17:25:57.000Z
2022-02-04T20:17:00.000Z
src/wpds/Examples/ProgAnalysis/Cfg.hpp
ucd-plse/mpi-error-prop
4367df88bcdc4d82c9a65b181d0e639d04962503
[ "BSD-3-Clause" ]
1
2018-03-03T05:58:55.000Z
2018-03-03T12:26:10.000Z
src/wpds/Examples/ProgAnalysis/Cfg.hpp
ucd-plse/mpi-error-prop
4367df88bcdc4d82c9a65b181d0e639d04962503
[ "BSD-3-Clause" ]
15
2015-09-25T17:44:35.000Z
2021-07-18T18:25:38.000Z
#ifndef _WALI_CFG_HPP_ #define _WALI_CFG_HPP_ /* * @author Akash Lal */ /* * This file includes an abstract class for a Control Flow Graph (CFG). A CFG is represented * as a graph over CFGNodes and CFGEdges. * * This abstract class is meant to provide just enough interface to be able to * construct a WPDS. */ #include "wali/Key.hpp" #include "wali/SemElem.hpp" #include "wali/MergeFn.hpp" #include <set> class CFGNode; class CFGEdge; class CFG; // Abstract class denoting a CFG node class CFGNode { public: // Return a unique identifier for the CFG node virtual int getId() const = 0; // Return a WPDS key that is unique for the CFG node. A sample // implementation for this method is provided using the getId // method. However, wali provides several ways of obtaining keys: // see [... NAK?] virtual wali::Key getWpdsKey() const { return wali::getKey(getId()); /* To use a priority-based key (see TODO) one can use the following code: * return wali::getKey( wali::getKey(getPriorityNumber()), wali::getKey(getId()) ); * * This assume the presence of a function "int CFGNode::getPriorityNumber()" that * returns a (possibily non-unique) priority for the CFGNode. */ } // Return the set of outgoing edges //std::set<CFGEdge *> getOutgoingEdges() = 0; virtual ~CFGNode() {} }; // Abstract class denoting a CFG edge class CFGEdge { // The source and target nodes of the edge CFGNode *src, *tgt; // If this edge is a call edge, then callee is the called // procedure. For simplicity, we assume that a call edge // has only one callee. (The presence of multiple callees // do not pose any challenge specific to WPDSs.) CFG* callee; public: // Return the source node of the edge CFGNode *getSource() const { return src; } // Return the target node of the edge CFGNode *getTarget() const { return tgt; } // Is this edge a call edge? virtual bool isCall() const = 0; // Get callee, if this is a call edge CFG *getCallee() const { if(!isCall()) return 0; return callee; } // Return the weight (or abstract transformer) associated // with the CFG edge. The convention for call edges is that // this function should provide the transformer associated with // just the call instruction, not the called procedure. virtual wali::sem_elem_t getWeight() const = 0; // Return the merge function associated with the edge. This is only // invoked for call edges. virtual wali::merge_fn_t getMergeFn() const = 0; virtual ~CFGEdge() {} }; // Abstract class for denoting a CFG. We assume that a CFG has a // unique entry node (that has no predecessors) and a unique exit // node (that has no successors). class CFG { // Entry and exit nodes of the CFG CFGNode *entryNode, *exitNode; public: // Return the entry node of the CFG CFGNode *getEntry() const { return entryNode; } // Return the exit node of the CFG CFGNode *getExit() const { return exitNode; } // Return the set of all CFG edges contained in this CFG virtual const std::set<CFGEdge *> & getEdges() const = 0; virtual ~CFG() {} }; #endif // _WALI_CFG_HPP_
25.373016
92
0.684079
jusito
623bfc1dbecdd6ebf1bfdefa4e2bb2b501853294
2,740
cpp
C++
LifeBrush/Source/LifeBrush/Simulation/Brownian.cpp
timdecode/LifeBrush
dbc65bcc0ec77f9168e08cf7b39539af94420725
[ "MIT" ]
33
2019-04-23T23:00:09.000Z
2021-11-09T11:44:09.000Z
LifeBrush/Source/LifeBrush/Simulation/Brownian.cpp
MyelinsheathXD/LifeBrush
dbc65bcc0ec77f9168e08cf7b39539af94420725
[ "MIT" ]
1
2019-10-09T15:57:56.000Z
2020-03-05T20:01:01.000Z
LifeBrush/Source/LifeBrush/Simulation/Brownian.cpp
MyelinsheathXD/LifeBrush
dbc65bcc0ec77f9168e08cf7b39539af94420725
[ "MIT" ]
6
2019-04-25T00:10:55.000Z
2021-04-12T05:16:28.000Z
// Copyright (c) 2019 Timothy Davison. All rights reserved. #include "LifeBrush.h" #include "Simulation/FlexElements.h" #include "Brownian.h" void USingleParticleBrownianSimulation::attach() { rand.GenerateNewSeed(); } void USingleParticleBrownianSimulation::detach() { } void USingleParticleBrownianSimulation::tick(float deltaT) { auto& browns = graph->componentStorage<FSingleParticleBrownian>(); auto& velocities = graph->componentStorage<FVelocityGraphObject>(); // make sure we have velocities for (FSingleParticleBrownian& brown : browns) { if( !brown.isValid() ) continue; if (!velocities.componentPtrForNode(brown.nodeHandle())) { FGraphNode& node = graph->node(brown.nodeHandle()); node.addComponent<FVelocityGraphObject>(*graph); } } for (FSingleParticleBrownian& brown : browns) { if( !brown.isValid() ) continue; brown.time -= deltaT; if (brown.time > 0.0f) continue; brown.time = rand.FRandRange(minTime, maxTime); float scale = FMath::Clamp(1.0f - brown.dampening, 0.0f, 1.0f); FVector dv = scale * rand.GetUnitVector() * rand.FRandRange(minSpeed, maxSpeed); if (auto velocity = velocities.componentPtrForNode(brown.nodeHandle())) { velocity->linearVelocity = (velocity->linearVelocity + dv).GetClampedToMaxSize(15.0f); } } } void UGlobalParticleBrownianSimulation::attach() { rand.GenerateNewSeed(); } void UGlobalParticleBrownianSimulation::detach() { } void UGlobalParticleBrownianSimulation::tick(float deltaT) { if (!enabled) return; auto& particles = graph->componentStorage<FFlexParticleObject>(); auto& velocities = graph->componentStorage<FVelocityGraphObject>(); for (FFlexParticleObject& particle : particles) { if (!particle.isValid()) continue; if (!velocities.componentPtrForNode(particle.nodeHandle())) { FGraphNode& node = graph->node(particle.nodeHandle()); node.addComponent<FVelocityGraphObject>(*graph); } } // find _times Num int32 timeSize = 0; for (FFlexParticleObject& particle : particles) { if (!particle.isValid()) continue; int32 timeIndex = particle.nodeHandle().index; if (timeIndex > timeSize) timeSize = timeIndex; } _times.SetNum(timeSize + 1); // make sure we have velocities for (FFlexParticleObject& particle : particles) { if (!particle.isValid()) continue; int32 timeIndex = particle.nodeHandle().index; float& timeLeft = _times[timeIndex]; timeLeft -= deltaT; if (timeLeft > 0.0f) continue; timeLeft = rand.FRandRange(minTime, maxTime); FVelocityGraphObject * velocity = velocities.componentPtrForNode(particle.nodeHandle()); FVector dv = rand.GetUnitVector() * rand.FRandRange(minSpeed, maxSpeed); velocity->linearVelocity += dv; } }
21.574803
90
0.724453
timdecode
623c158b82f5ffc0d0db2e2fb7c1f16ace9c978f
2,652
cpp
C++
src/Camera2D.cpp
jasonwnorris/SuperAwesomeGameEngine
908adf2099898b2c2028a8c8e8887f1d53be181f
[ "MIT" ]
1
2016-05-21T12:45:20.000Z
2016-05-21T12:45:20.000Z
src/Camera2D.cpp
jasonwnorris/SuperAwesomeGameEngine
908adf2099898b2c2028a8c8e8887f1d53be181f
[ "MIT" ]
null
null
null
src/Camera2D.cpp
jasonwnorris/SuperAwesomeGameEngine
908adf2099898b2c2028a8c8e8887f1d53be181f
[ "MIT" ]
null
null
null
// Camera2D.cpp // SAGE Includes #include <SAGE/Camera2D.hpp> namespace SAGE { const Camera2D Camera2D::DefaultCamera; int Camera2D::DefaultWidth = 1280; int Camera2D::DefaultHeight = 720; Camera2D::Camera2D() { m_Position = Vector2::Zero; m_Rotation = 0.0f; m_Scale = Vector2::One; m_Width = DefaultWidth; m_Height = DefaultHeight; } Camera2D::~Camera2D() { } Vector2 Camera2D::GetPosition() const { return m_Position; } float Camera2D::GetRotation() const { return m_Rotation; } Vector2 Camera2D::GetScale() const { return m_Scale; } int Camera2D::GetWidth() const { return m_Width; } int Camera2D::GetHeight() const { return m_Height; } glm::mat4 Camera2D::GetProjectionMatrix(View p_View) const { switch (p_View) { default: case View::Orthographic: return glm::ortho(0.0f, (float)m_Width, (float)m_Height, 0.0f, 1.0f, -1.0f); case View::Perspective: return glm::perspective(45.0f, (float)m_Width / (float)m_Height, 0.1f, 1000.0f); } } glm::mat4 Camera2D::GetModelViewMatrix() const { glm::mat4 modelViewMatrix; modelViewMatrix = glm::translate(modelViewMatrix, glm::vec3((float)m_Width / 2.0f, (float)m_Height / 2.0f, 0.0f)); modelViewMatrix = glm::scale(modelViewMatrix, glm::vec3(m_Scale.X, m_Scale.Y, 1.0f)); modelViewMatrix = glm::rotate(modelViewMatrix, m_Rotation, glm::vec3(0.0f, 0.0f, 1.0f)); modelViewMatrix = glm::translate(modelViewMatrix, glm::vec3(-m_Position.X, -m_Position.Y, 0.0f)); return modelViewMatrix; } void Camera2D::SetPosition(const Vector2& p_Position) { m_Position = p_Position; } void Camera2D::SetRotation(float p_Rotation) { m_Rotation = p_Rotation; } void Camera2D::SetScale(const Vector2& p_Scale) { m_Scale = p_Scale; } void Camera2D::SetTransformation(const Vector2& p_Position, float p_Rotation, const Vector2& p_Scale) { m_Position = p_Position; m_Rotation = p_Rotation; m_Scale = p_Scale; } void Camera2D::SetWidth(int p_Width) { m_Width = p_Width; } void Camera2D::SetHeight(int p_Height) { m_Height = p_Height; } void Camera2D::SetDimensions(int p_Width, int p_Height) { m_Width = p_Width; m_Height = p_Height; } void Camera2D::Translate(const Vector2& p_Translation) { m_Position += p_Translation; } void Camera2D::Rotate(float p_Rotation) { m_Rotation += p_Rotation; } void Camera2D::Scale(const Vector2& p_Scale) { m_Scale += p_Scale; } void Camera2D::ScreenToWorld(const Vector2& p_ScreenPosition, Vector2& p_WorldPosition) const { } void Camera2D::WorldToScreen(const Vector2& p_WorldPosition, Vector2& p_ScreenPosition) const { } }
19.791045
116
0.707391
jasonwnorris
9a8b7cab21f5563369369e89adf76a80a30f01c3
5,975
cpp
C++
opengl/texture.cpp
yRezaei/cpp-utils
3e1ba264bdb6e2339b7b5f2c4e5c3ab7d8097332
[ "MIT" ]
null
null
null
opengl/texture.cpp
yRezaei/cpp-utils
3e1ba264bdb6e2339b7b5f2c4e5c3ab7d8097332
[ "MIT" ]
null
null
null
opengl/texture.cpp
yRezaei/cpp-utils
3e1ba264bdb6e2339b7b5f2c4e5c3ab7d8097332
[ "MIT" ]
null
null
null
#include "../rendering/gl_utility.hpp" #include "texture.h" namespace gl { int format_to_texture(image::Format format) { switch (format) { case image::ALPHA: case image::GRAYSCALE: return GL_RED; case image::GRAYSCALE_ALPHA: ASSERT("Unkown format 'GRAYSCALE_ALPHA'!!!!"); case image::RGB: return GL_RGB; case image::BGR: return GL_BGR; case image::RGBA: return GL_RGBA; case image::BGRA: return GL_BGRA; default: ASSERT("Unkown format '" + image::FormatStrings[format] + "'."); } } int internal_texture_format(image::Format format) { switch (format) { case image::ALPHA: case image::GRAYSCALE: return GL_RED; case image::GRAYSCALE_ALPHA: ASSERT("Unkown format 'GRAYSCALE_ALPHA'!!!!"); case image::RGB: case image::BGR: return GL_RGB; case image::RGBA: return GL_RGBA; case image::BGRA: return GL_BGRA; default: ASSERT("Unkown format '" + image::FormatStrings[format] + "'."); } } Texture::Texture(image::Format format, const glm::ivec2 & size, TextureFilter texture_filter, TextureWrapping texture_wrapping) : id_(0u), format_(format), size_(size) { GL_CHECK(glGenTextures(1, &id_)); ASSERT_IF_FALSE(id_, "glGenTextures() failed to generate texture id."); GL_CHECK(glBindTexture(GL_TEXTURE_2D, id_)); { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texture_filter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texture_filter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, texture_wrapping); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texture_wrapping); std::vector<uint8_t> pixels(size_.x * size_.y * format_size(format_), 0); GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, format_to_texture(format_), size_.x, size_.y, 0, internal_texture_format(format_), GL_UNSIGNED_BYTE, pixels.data())); } glBindTexture(GL_TEXTURE_2D, 0); } Texture::Texture(image::Bitmap const & bitmap, TextureFilter texture_filter, TextureWrapping texture_wrapping) : id_(0u), format_(bitmap.format), size_(bitmap.size) { GL_CHECK(glGenTextures(1, &id_)); ASSERT_IF_FALSE(id_, "glGenTextures() failed to generate texture id."); GL_CHECK(glBindTexture(GL_TEXTURE_2D, id_)); { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texture_filter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texture_filter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, texture_wrapping); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texture_wrapping); GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, format_to_texture(format_), size_.x, size_.y, 0, internal_texture_format(format_), GL_UNSIGNED_BYTE, bitmap.buffer.data())); } glBindTexture(GL_TEXTURE_2D, 0); } Texture::Texture(image::Format format, const glm::ivec2 & size, const std::vector<uint8_t>& pixels, TextureFilter texture_filter, TextureWrapping texture_wrapping) : id_(0u), format_(format), size_(size) { if (id_ != 0) glDeleteTextures(1, &id_); GL_CHECK(glGenTextures(1, &id_)); ASSERT_IF_FALSE(id_, "glGenTextures() failed to generate texture id."); GL_CHECK(glBindTexture(GL_TEXTURE_2D, id_)); { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texture_filter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texture_filter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, texture_wrapping); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texture_wrapping); GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, format_to_texture(format_), size_.x, size_.y, 0, internal_texture_format(format_), GL_UNSIGNED_BYTE, pixels.data())); } glBindTexture(GL_TEXTURE_2D, 0); } Texture::Texture(image::Format format, const glm::ivec2 & size, const uint8_t * data, TextureFilter texture_filter, TextureWrapping texture_wrapping) : id_(0u), format_(format), size_(size) { if (id_ != 0) glDeleteTextures(1, &id_); GL_CHECK(glGenTextures(1, &id_)); ASSERT_IF_FALSE(id_, "glGenTextures() failed to generate texture id."); GL_CHECK(glBindTexture(GL_TEXTURE_2D, id_)); { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texture_filter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texture_filter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, texture_wrapping); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texture_wrapping); GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, format_to_texture(format_), size_.x, size_.y, 0, internal_texture_format(format_), GL_UNSIGNED_BYTE, data)); } glBindTexture(GL_TEXTURE_2D, 0); } Texture::~Texture() { if (id_ != 0) glDeleteTextures(1, &id_); } const glm::ivec2 & Texture::size() { return size_; } void Texture::set_data(const std::vector<uint8_t>& data) { glBindTexture(GL_TEXTURE_2D, id_); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); GL_CHECK(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size_.x, size_.y, internal_texture_format(format_), GL_UNSIGNED_BYTE, data.data())); } void Texture::set_data(const glm::ivec4 & rect, const std::vector<uint8_t>& data) { glBindTexture(GL_TEXTURE_2D, id_); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); GL_CHECK(glTexSubImage2D(GL_TEXTURE_2D, 0, rect[0], rect[1], rect[2], rect[3], internal_texture_format(format_), GL_UNSIGNED_BYTE, data.data())); } void Texture::set_data(const std::uint8_t* data) { glBindTexture(GL_TEXTURE_2D, id_); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); GL_CHECK(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size_.x, size_.y, internal_texture_format(format_), GL_UNSIGNED_BYTE, data)); } void Texture::set_data(const glm::ivec4 & rect, const std::uint8_t* data) { glBindTexture(GL_TEXTURE_2D, id_); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); GL_CHECK(glTexSubImage2D(GL_TEXTURE_2D, 0, rect[0], rect[1], rect[2], rect[3], internal_texture_format(format_), GL_UNSIGNED_BYTE, data)); } void Texture::bind() { glBindTexture(GL_TEXTURE_2D, id_); } void Texture::unbind() { glBindTexture(GL_TEXTURE_2D, 0); } }
33.757062
167
0.743096
yRezaei
9a90a34a50edc5648df12b76cb1b02e0be8f77fc
737
cpp
C++
InfoX/lungimea_coordonate_segment.cpp
jbara2002/Informatica_LCIB
ff9db6d7d6119ba835750cc2d408079f76b852df
[ "CC0-1.0" ]
1
2022-03-31T21:45:03.000Z
2022-03-31T21:45:03.000Z
InfoX/lungimea_coordonate_segment.cpp
jbara2002/Informatica_LCIB
ff9db6d7d6119ba835750cc2d408079f76b852df
[ "CC0-1.0" ]
null
null
null
InfoX/lungimea_coordonate_segment.cpp
jbara2002/Informatica_LCIB
ff9db6d7d6119ba835750cc2d408079f76b852df
[ "CC0-1.0" ]
null
null
null
// Citesc coordonatele A(x1,y1), B(x2,y2). // Afiseaza lungimea AB si coordonatele mijlocului segmentului AB. #include <iostream> #include <math.h> using namespace std; int main(){ float x1, y1, x2, y2, ab, c1, c2; cout << "Introdu coordonata punctului A - x1: "; cin >> x1; cout << "Introdu coordonata punctului A - y1: "; cin >> y1; cout << "Introdu coordonata punctului B - x2: "; cin >> x2; cout << "Introdu coordonata punctului B - y2: "; cin >> y2; ab=sqrt(pow((x1-x2),2)+pow((y1-y2),2)); c1=(x1+x2)/2; c2=(y1+y2)/2; cout << "Lungimea segmentului AB: " << ab << endl; cout << "Coordonatele mijlocului segmentului: " << "A(" << x1+c1 << ")" << " , " << "B(" << y1+c2 << ")" << endl; }
29.48
117
0.573948
jbara2002
9a92781c5880a10d8cbdff21bdb1f9650bb73f75
12,314
cpp
C++
cmd_vcf_sample_summary.cpp
Yichen-Si/cramore
18ed327c2bb9deb6c2ec4243d259b93142304719
[ "Apache-2.0" ]
2
2019-03-04T23:08:17.000Z
2021-08-24T08:10:03.000Z
cmd_vcf_sample_summary.cpp
Yichen-Si/cramore
18ed327c2bb9deb6c2ec4243d259b93142304719
[ "Apache-2.0" ]
2
2018-09-19T05:16:20.000Z
2020-10-01T18:28:36.000Z
cmd_vcf_sample_summary.cpp
Yichen-Si/cramore
18ed327c2bb9deb6c2ec4243d259b93142304719
[ "Apache-2.0" ]
3
2018-09-06T22:04:40.000Z
2019-08-19T16:55:42.000Z
#include "bcf_filter_arg.h" #include "cramore.h" #include "bcf_ordered_reader.h" int32_t cmdVcfSampleSummary(int32_t argc, char** argv) { std::string inVcf; std::string out; std::string reg; std::vector<std::string> sumFields; int32_t minDistBp = 0; int32_t verbose = 1000; bool countVariants = false; // count variants by variant type, allele type, and genotypes bcf_vfilter_arg vfilt; bcf_gfilter_arg gfilt; std::vector<int32_t> acThres; std::vector<double> afThres; bool posOnly = false; paramList pl; BEGIN_LONG_PARAMS(longParameters) LONG_PARAM_GROUP("Input Sites", NULL) LONG_STRING_PARAM("in-vcf",&inVcf, "Input VCF/BCF file") LONG_STRING_PARAM("region",&reg,"Genomic region to focus on") LONG_PARAM("pos-only",&posOnly,"Consider POS field only (not REF field) when determining --region option. This will exclude >1bp variants outside of the region included") LONG_PARAM_GROUP("Analysis Options", NULL) LONG_MULTI_STRING_PARAM("sum-field",&sumFields, "Field values to calculate the sums") LONG_PARAM("count-variants",&countVariants, "Flag to turn on counting variants") LONG_PARAM_GROUP("Variant Filtering Options", NULL) LONG_INT_PARAM("min-dist-bp",&minDistBp, "Minimum distance from the previous variant in base-position") LONG_MULTI_STRING_PARAM("apply-filter",&vfilt.required_filters, "Require at least one of the listed FILTER strings") LONG_STRING_PARAM("include-expr",&vfilt.include_expr, "Include sites for which expression is true") LONG_STRING_PARAM("exclude-expr",&vfilt.exclude_expr, "Exclude sites for which expression is true") LONG_PARAM_GROUP("Genotype Filtering Options", NULL) LONG_MULTI_INT_PARAM("ac",&acThres,"Allele count threshold to count rare/common variants") LONG_MULTI_DOUBLE_PARAM("af",&afThres,"Allele frequency threshold to count rare/common variants") LONG_INT_PARAM("minDP",&gfilt.minDP,"Minimum depth threshold for counting genotypes") LONG_INT_PARAM("minGQ",&gfilt.minGQ,"Minimum depth threshold for counting genotypes") LONG_PARAM_GROUP("Output Options", NULL) LONG_STRING_PARAM("out", &out, "Output VCF file name") LONG_INT_PARAM("verbose",&verbose,"Frequency of verbose output (1/n)") END_LONG_PARAMS(); pl.Add(new longParams("Available Options", longParameters)); pl.Read(argc, argv); pl.Status(); // sanity check of input arguments if ( inVcf.empty() || out.empty() ) { error("[E:%s:%d %s] --in-vcf, --out are required parameters",__FILE__,__LINE__,__FUNCTION__); } std::vector<GenomeInterval> intervals; if ( !reg.empty() ) { parse_intervals(intervals, "", reg); } BCFOrderedReader odr(inVcf, intervals); bcf1_t* iv = bcf_init(); // handle filter string std::string filter_str; int32_t filter_logic = 0; if ( vfilt.include_expr.empty() ) { if ( vfilt.exclude_expr.empty() ) { // do nothing } else { filter_str = vfilt.exclude_expr; filter_logic |= FLT_EXCLUDE; } } else { if ( vfilt.exclude_expr.empty() ) { filter_str = vfilt.include_expr; filter_logic |= FLT_INCLUDE; } else { error("[E:%s:%d %s] Cannot use both --include-expr and --exclude-expr options",__FILE__,__LINE__,__FUNCTION__); } } filter_t* filt = NULL; if ( filter_logic != 0 ) filter_init(odr.hdr, filter_str.c_str()); // handle --apply-filtrs std::vector<int32_t> req_flt_ids; if ( !vfilt.required_filters.empty() ) { for(int32_t i=0; i < (int32_t)vfilt.required_filters.size(); ++i) { req_flt_ids.push_back(bcf_hdr_id2int(odr.hdr, BCF_DT_ID, vfilt.required_filters[i].c_str())); } } notice("Started Reading site information from VCF file"); std::map< std::string, std::vector<int64_t> > mapFieldSums; std::map< std::string, std::vector<int64_t> > mapFieldVars; int32_t nVariant = 0; int32_t nsamples = bcf_hdr_nsamples(odr.hdr); for(int32_t i=0; i < (int32_t)sumFields.size(); ++i) mapFieldSums[sumFields[i]].resize(nsamples, (int64_t)0); std::vector<std::string> varFields; varFields.push_back("ALL.SNP"); varFields.push_back("ALL.OTH"); varFields.push_back("NREF.SNP"); varFields.push_back("NREF.OTH"); varFields.push_back("REF.SNP"); varFields.push_back("REF.OTH"); varFields.push_back("HET.SNP"); varFields.push_back("HET.OTH"); varFields.push_back("ALT.SNP"); varFields.push_back("ALT.OTH"); varFields.push_back("MISS.SNP"); varFields.push_back("MISS.OTH"); std::sort(acThres.begin(), acThres.end()); for(int32_t i=0; i < (int32_t)acThres.size(); ++i) { char buf[255]; sprintf(buf, "AC_%d_%d.SNP", i == 0 ? 1 : acThres[i-1]+1, acThres[i]); varFields.push_back(buf); sprintf(buf, "AC_%d_%d.OTH", i == 0 ? 1 : acThres[i-1]+1, acThres[i]); varFields.push_back(buf); } std::sort(afThres.begin(), afThres.end()); for(int32_t i=0; i < (int32_t)afThres.size(); ++i) { char buf[255]; sprintf(buf, "AF_%f_%f.SNP", i == 0 ? 0 : afThres[i-1], afThres[i]); varFields.push_back(buf); sprintf(buf, "AF_%f_%f.OTH", i == 0 ? 0 : afThres[i-1], afThres[i]); varFields.push_back(buf); } for(int32_t i=0; i < (int32_t)varFields.size(); ++i) { mapFieldVars[varFields[i]].resize(nsamples, (int64_t)0); } std::vector<int32_t> varMasks(varFields.size()); int32_t* p_gt = NULL; int32_t n_gt = 0; int32_t* p_fld = NULL; int32_t n_fld = 0; int32_t prev_rid = -1, prev_pos = -1; int32_t nskip = 0; int32_t an = 0, ac_alloc = 0, non_ref_ac = 0; int32_t* ac = NULL; for(int32_t k=0; odr.read(iv); ++k) { // read marker if ( k % verbose == 0 ) notice("Processing %d markers at %s:%d. Skipped %d markers within %d-bp from the previous marker", k, bcf_hdr_id2name(odr.hdr, iv->rid), iv->pos+1, nskip, minDistBp); // if minimum distance is specified, skip the variant if ( ( prev_rid == iv->rid ) && ( iv->pos - prev_pos < minDistBp ) ) { ++nskip; continue; } if ( ( !reg.empty() ) && posOnly && ( ( intervals[0].start1 > iv->pos+1 ) || ( intervals[0].end1 < iv->pos+1 ) ) ) { notice("With --pos-only option, skipping variant at %s:%d", bcf_hdr_id2name(odr.hdr, iv->rid), iv->pos+1); ++nskip; continue; } bcf_unpack(iv, BCF_UN_FLT); // check --apply-filters bool has_filter = req_flt_ids.empty() ? true : false; if ( ! has_filter ) { //notice("%d %d", iv->d.n_flt, (int32_t)req_flt_ids.size()); for(int32_t i=0; i < iv->d.n_flt; ++i) { for(int32_t j=0; j < (int32_t)req_flt_ids.size(); ++j) { if ( req_flt_ids[j] == iv->d.flt[i] ) has_filter = true; } } } //if ( k % 1000 == 999 ) abort(); if ( ! has_filter ) { ++nskip; continue; } // check filter logic if ( filt != NULL ) { int32_t ret = filter_test(filt, iv, NULL); if ( filter_logic == FLT_INCLUDE ) { if ( !ret) has_filter = false; } else if ( ret ) { has_filter = false; } } if ( ! has_filter ) { ++nskip; continue; } ++nVariant; if ( countVariants ) { // calculate AC if ( acThres.size() + afThres.size() > 0 ) { hts_expand(int, iv->n_allele, ac_alloc, ac); an = 0; non_ref_ac = 0; bcf_calc_ac(odr.hdr, iv, ac, BCF_UN_INFO|BCF_UN_FMT); // get original AC and AN values from INFO field if available, otherwise calculate for (int32_t i=1; i<iv->n_allele; i++) non_ref_ac += ac[i]; for (int32_t i=0; i<iv->n_allele; i++) an += ac[i]; } // determine variant type : flags are MISSING HOMALT HET HOMREF std::fill(varMasks.begin(), varMasks.end(), 0); if ( bcf_is_snp(iv) ) { varMasks[0] = MASK_GT_ALL; varMasks[2] = MASK_GT_NONREF; varMasks[4] = MASK_GT_HOMREF; varMasks[6] = MASK_GT_HET; varMasks[8] = MASK_GT_HOMALT; varMasks[10] = MASK_GT_MISS; } // for non-ref genotypes else { varMasks[1] = MASK_GT_ALL; varMasks[3] = MASK_GT_NONREF; varMasks[5] = MASK_GT_HOMREF; varMasks[7] = MASK_GT_HET; varMasks[9] = MASK_GT_HOMALT; varMasks[11] = MASK_GT_MISS; } // for non-ref genotypes for(int32_t i=0, j=12; i < (int32_t)acThres.size(); ++i, j += 2) { if ( ( non_ref_ac > (i == 0 ? 0 : acThres[i-1]) ) && ( non_ref_ac <= acThres[i] ) ) { if ( bcf_is_snp(iv) ) { varMasks[j] = MASK_GT_NONREF; } else { varMasks[j+1] = MASK_GT_NONREF; } } } for(int32_t i=0, j=12 + 2*acThres.size(); i < (int32_t)afThres.size(); ++i, j += 2) { if ( ( non_ref_ac > (i == 0 ? 0 : afThres[i-1]*an) ) && ( non_ref_ac <= afThres[i]*an ) ) { if ( bcf_is_snp(iv) ) { varMasks[j] = MASK_GT_NONREF; } else { varMasks[j+1] = MASK_GT_NONREF; } } } // extract genotype and apply genotype level filter if ( bcf_get_genotypes(odr.hdr, iv, &p_gt, &n_gt) < 0 ) { error("[E:%s:%d %s] Cannot find the field GT from the VCF file at position %s:%d",__FILE__,__LINE__,__FUNCTION__, bcf_hdr_id2name(odr.hdr, iv->rid), iv->pos+1); } for(int32_t i=0; i < nsamples; ++i) { int32_t g1 = p_gt[2*i]; int32_t g2 = p_gt[2*i+1]; int32_t geno; if ( bcf_gt_is_missing(g1) || bcf_gt_is_missing(g2) ) { geno = 0; } else { geno = ((bcf_gt_allele(g1) > 0) ? 1 : 0) + ((bcf_gt_allele(g2) > 0) ? 1 : 0) + 1; //if ( i == 0 ) //notice("g1 = %d, g2 = %d, geno = %d", g1,g2,geno); } p_gt[i] = geno; } if ( gfilt.minDP > 0 ) { if ( bcf_get_format_int32(odr.hdr, iv, "DP", &p_fld, &n_fld) < 0 ) { error("[E:%s:%d %s] Cannot find the field DP from the VCF file at position %s:%d",__FILE__,__LINE__,__FUNCTION__, bcf_hdr_id2name(odr.hdr, iv->rid), iv->pos+1); } for(int32_t i=0; i < nsamples; ++i) { if ( p_fld[i] < gfilt.minDP ) p_gt[i] = 0; } } if ( gfilt.minGQ > 0 ) { if ( bcf_get_format_int32(odr.hdr, iv, "GQ", &p_fld, &n_fld) < 0 ) { error("[E:%s:%d %s] Cannot find the field GQ from the VCF file at position %s:%d",__FILE__,__LINE__,__FUNCTION__, bcf_hdr_id2name(odr.hdr, iv->rid), iv->pos+1); } for(int32_t i=0; i < nsamples; ++i) { if ( p_fld[i] < gfilt.minGQ ) p_gt[i] = 0; } } // update the maps for(int32_t i=0; i < (int32_t)varFields.size(); ++i) { std::vector<int64_t>& v = mapFieldVars[varFields[i]]; for(int32_t j=0; j < nsamples; ++j) { if ( varMasks[i] & ( 0x01 << p_gt[j] ) ) { //if ( j == 0 ) notice("VarMask[i] = %d, p_gt[j] = %d", varMasks[i], p_gt[j]); ++v[j]; } } } //if ( rand() % 100 == 0 ) abort(); } // perform sumField tasks for(int32_t i=0; i < (int32_t)sumFields.size(); ++i) { if ( bcf_get_format_int32(odr.hdr, iv, sumFields[i].c_str(), &p_fld, &n_fld) < 0 ) { error("[E:%s:%d %s] Cannot find the field %s from the VCF file at position %s:%d",__FILE__,__LINE__,__FUNCTION__, sumFields[i].c_str(), bcf_hdr_id2name(odr.hdr, iv->rid), iv->pos+1); } if ( nsamples != n_fld ) error("[E:%s:%d %s] Field %s has multiple elements",__FILE__,__LINE__,__FUNCTION__,sumFields[i].c_str()); std::vector<int64_t>& v = mapFieldSums[sumFields[i]]; if ( (int32_t)v.size() != nsamples ) error("[E:%s:%d %s] mapFieldSums object does not have %s as key",__FILE__,__LINE__,__FUNCTION__,sumFields[i].c_str()); for(int32_t j=0; j < nsamples; ++j) { //if ( p_fld[j] != bcf_int32_missing ) { v[j] += p_fld[j]; //} } } prev_rid = iv->rid; prev_pos = iv->pos; } htsFile* wf = hts_open(out.c_str(), "w"); hprintf(wf, "ID\tN.VAR"); for(int32_t i=0; i < (int32_t)varFields.size(); ++i) { hprintf(wf, "\t%s",varFields[i].c_str()); } for(int32_t i=0; i < (int32_t)sumFields.size(); ++i) { hprintf(wf, "\tSUM.%s",sumFields[i].c_str()); } hprintf(wf,"\n"); for(int32_t i=0; i < nsamples; ++i) { hprintf(wf, "%s", odr.hdr->id[BCF_DT_SAMPLE][i].key); hprintf(wf, "\t%d", nVariant); for(int32_t j=0; j < (int32_t)varFields.size(); ++j) { hprintf(wf, "\t%lld", mapFieldVars[varFields[j]][i]); } for(int32_t j=0; j < (int32_t)sumFields.size(); ++j) { hprintf(wf, "\t%lld", mapFieldSums[sumFields[j]][i]); } hprintf(wf, "\n"); } hts_close(wf); odr.close(); return 0; }
33.82967
183
0.617265
Yichen-Si
9a96b1ef62c7fd3cd7363e2485646d7bc9ee2186
589
cpp
C++
volume2/1161_10May2006_1186596.cpp
andriybuday/timus
a5cdc03f3ca8e7878220b8e0a0c72343f98ee1eb
[ "MIT" ]
null
null
null
volume2/1161_10May2006_1186596.cpp
andriybuday/timus
a5cdc03f3ca8e7878220b8e0a0c72343f98ee1eb
[ "MIT" ]
null
null
null
volume2/1161_10May2006_1186596.cpp
andriybuday/timus
a5cdc03f3ca8e7878220b8e0a0c72343f98ee1eb
[ "MIT" ]
null
null
null
//1161 #include <stdio.h> #include <math.h> int arr[107]; double res = 0; void Sq(int* a, int n){ int p = a[n>>1]; int i = 0 , j = n; int temp; do{ while(a[i] < p)i++; while(a[j] > p)j--; if(i <= j){ temp = a[i]; a[i] = a[j]; a[j] = temp; i++; j--; } }while(i <= j); if(j > 0)Sq(a, j); if(i < n)Sq(a + i, n-i); } int main(){ int n; scanf("%d", &n); int i; for(i = 0;i < n; i++) scanf("%d", &arr[i]); Sq(arr, n-1); res = arr[n-1]; for(i = n-2; i >= 0; i--) { res = 2*sqrt(arr[i]*res); } printf("%.2f", res); return 0; }
12.270833
27
0.419355
andriybuday
9a989fbef319496656a1b096f8e75ab1160136fc
4,103
cpp
C++
src/solver.cpp
oygx210/dmsc-visualizer
c0d571beb5dc6a4c76ef27b9d57139cb48376756
[ "MIT" ]
null
null
null
src/solver.cpp
oygx210/dmsc-visualizer
c0d571beb5dc6a4c76ef27b9d57139cb48376756
[ "MIT" ]
null
null
null
src/solver.cpp
oygx210/dmsc-visualizer
c0d571beb5dc6a4c76ef27b9d57139cb48376756
[ "MIT" ]
1
2021-12-13T02:28:00.000Z
2021-12-13T02:28:00.000Z
#include "dmsc/solver.hpp" #include "dmsc/glm_include.hpp" #include <cmath> #include <ctime> #include <fstream> #include <random> namespace dmsc { float Solver::nextCommunication(const InterSatelliteLink& edge, const float time_0) { // edge is never visible? float t_visible = nextVisibility(edge, time_0); if (t_visible >= INFINITY) { return INFINITY; } // get current orientation of both satellites TimelineEvent<glm::vec3> sat1 = satellite_orientation[&edge.getV1()]; TimelineEvent<glm::vec3> sat2 = satellite_orientation[&edge.getV2()]; // edge can be scanned directly? if (edge.canAlign(sat1, sat2, t_visible)) { return t_visible; } // satellites can't align => search for a time where they can // max time to align ==> time for a 180 deg turn float t_max = std::max(static_cast<float>(M_PI) / edge.getV1().getRotationSpeed(), static_cast<float>(M_PI) / edge.getV2().getRotationSpeed()); t_max += edge.getPeriod(); for (float t = t_visible; t <= time_0 + t_max; t += step_size) { if (edge.isBlocked(t)) { // skip time where edge is blocked // find next slot where edge is visible float t_relative = fmodf(t, edge.getPeriod()); auto search = edge_time_slots.find(&edge); float t_next = 0.0f; if (search != edge_time_slots.end()) { t_next = search->second.nextTimeWithEvent(t_relative, true); } if (t_next < t_relative) { // loop applied t += t_next + edge.getPeriod() - t_relative; } else { // loop not applied t += t_next - t_relative; } } if (edge.canAlign(sat1, sat2, t)) { // edge can be scanned if (!edge.isBlocked(t)) { return t; } } } // communication is never possible return INFINITY; } // ------------------------------------------------------------------------------------------------ void Solver::createCache() { for (const auto& edge : instance.getISLs()) { for (float t = 0.0f; t < edge.getPeriod(); t += step_size) { // TODO getPERIOD IS INFINIT if cm.gp = 0 float t_next = findNextVisiblity(edge, t); if (t_next == INFINITY || t_next >= edge.getPeriod()) { break; } float t_end = findLastVisible(edge, t_next); if (t_end == INFINITY || t_end >= edge.getPeriod()) { t_end = edge.getPeriod(); } TimelineEvent<> slot(t_next, t_end); edge_time_slots[&edge].insert(slot); t = slot.t_end; } } } // ------------------------------------------------------------------------------------------------ float Solver::nextVisibility(const InterSatelliteLink& edge, const float t0) { if (edge_time_slots[&edge].size() == 0) { return INFINITY; } float t = std::fmod(t0, edge.getPeriod()); float n_periods = edge.getPeriod() * (int)(t0 / edge.getPeriod()); float t_next = edge_time_slots[&edge].nextTimeWithEvent(t, true); if (t_next < t) { // loop applied n_periods += edge.getPeriod(); } return t_next + n_periods; } // ------------------------------------------------------------------------------------------------ float Solver::findNextVisiblity(const InterSatelliteLink& edge, const float t0) const { for (float t = t0; t <= t0 + edge.getPeriod(); t += step_size) { if (!edge.isBlocked(t)) { return t; } } // edge is never visible return INFINITY; } // ------------------------------------------------------------------------------------------------ float Solver::findLastVisible(const InterSatelliteLink& edge, const float t0) const { for (float t = t0; t <= t0 + edge.getPeriod(); t += step_size) { if (edge.isBlocked(t)) { return t - step_size; } } // edge is never visible return INFINITY; } } // namespace dmsc
32.307087
99
0.520107
oygx210
9a9dec98aa589837c992ea7c58f860fcf1dbefad
3,700
cpp
C++
hardware/libraries/Elektron/MNMDataEncoder.cpp
anupam19/mididuino
27c30f586a8d61381309434ed05b4958c7727402
[ "BSD-3-Clause" ]
null
null
null
hardware/libraries/Elektron/MNMDataEncoder.cpp
anupam19/mididuino
27c30f586a8d61381309434ed05b4958c7727402
[ "BSD-3-Clause" ]
null
null
null
hardware/libraries/Elektron/MNMDataEncoder.cpp
anupam19/mididuino
27c30f586a8d61381309434ed05b4958c7727402
[ "BSD-3-Clause" ]
null
null
null
#include "Elektron.hh" #include "ElektronDataEncoder.hh" #include "MNMDataEncoder.hh" void MNMDataToSysexEncoder::init(DATA_ENCODER_INIT(uint8_t *_sysex, uint16_t _sysexLen), MidiUartParent *_uart) { ElektronDataToSysexEncoder::init(DATA_ENCODER_INIT(_sysex, _sysexLen), _uart); lastByte = 0; lastCnt = 0; isFirstByte = true; } DATA_ENCODER_RETURN_TYPE MNMDataToSysexEncoder::pack8(uint8_t inb) { // printf("patck: %x\n", inb); totalCnt++; if (in7Bit) { if (isFirstByte) { lastByte = inb; lastCnt = 1; isFirstByte = false; DATA_ENCODER_TRUE(); } else { if (inb == lastByte) { lastCnt++; if (lastCnt == 127) { DATA_ENCODER_CHECK(packLastByte()); } } else { DATA_ENCODER_CHECK(packLastByte()); lastByte = inb; lastCnt = 1; } } } else { ElektronDataToSysexEncoder::pack8(inb); } DATA_ENCODER_TRUE(); } DATA_ENCODER_RETURN_TYPE MNMDataToSysexEncoder::packLastByte() { if (lastCnt > 0) { if ((lastCnt == 1) && !(lastByte & 0x80)) { DATA_ENCODER_CHECK(ElektronDataToSysexEncoder::pack8(lastByte)); lastCnt = 0; } else { DATA_ENCODER_CHECK(ElektronDataToSysexEncoder::pack8(0x80 | lastCnt)); DATA_ENCODER_CHECK(ElektronDataToSysexEncoder::pack8(lastByte)); lastCnt = 0; } } DATA_ENCODER_TRUE(); } uint16_t MNMDataToSysexEncoder::finish() { #ifdef DATA_ENCODER_CHECKING if (!packLastByte()) return 0; else return ElektronDataToSysexEncoder::finish(); #else packLastByte(); ElektronDataToSysexEncoder::finish(); #endif } void MNMSysexToDataEncoder::init(DATA_ENCODER_INIT(uint8_t *_data, uint16_t _maxLen)) { ElektronSysexToDataEncoder::init(DATA_ENCODER_INIT(_data, _maxLen)); repeat = 0; totalCnt = 0; } DATA_ENCODER_RETURN_TYPE MNMSysexToDataEncoder::pack8(uint8_t inb) { // printf("pack: %x\n", inb); totalCnt++; if ((cnt % 8) == 0) { bits = inb; } else { bits <<= 1; tmpData[cnt7++] = inb | (bits & 0x80); } cnt++; if (cnt7 == 7) { DATA_ENCODER_CHECK(unpack8Bit()); } DATA_ENCODER_TRUE(); } DATA_ENCODER_RETURN_TYPE MNMSysexToDataEncoder::unpack8Bit() { for (uint8_t i = 0; i < cnt7; i++) { // printf("tmpdata[%d]: %x\n", i, tmpData[i]); if (repeat == 0) { if (tmpData[i] & 0x80) { repeat = tmpData[i] & 0x7F; } else { #ifdef DATA_ENCODER_CHECKING DATA_ENCODER_CHECK(retLen <= maxLen); #endif *(ptr++) = tmpData[i]; retLen++; } } else { for (uint8_t j = 0; j < repeat; j++) { #ifdef DATA_ENCODER_CHECKING DATA_ENCODER_CHECK(retLen <= maxLen); #endif *(ptr++) = tmpData[i]; retLen++; } repeat = 0; } } cnt7 = 0; DATA_ENCODER_TRUE(); } uint16_t MNMSysexToDataEncoder::finish() { #ifdef DATA_ENCODER_CHECKING // printf("cnt7: %d\n", cnt7); if (!unpack8Bit()) { return 0; } #else unpack8Bit(); #endif return retLen; } void MNMSysexDecoder::init(DATA_ENCODER_INIT(uint8_t *_data, uint16_t _maxLen)) { DataDecoder::init(DATA_ENCODER_INIT(_data, _maxLen)); cnt7 = 0; cnt = 0; repeatCount = 0; repeatByte = 0; totalCnt = 0; } DATA_ENCODER_RETURN_TYPE MNMSysexDecoder::getNextByte(uint8_t *c) { if ((cnt % 8) == 0) { bits = *(ptr++); cnt++; } bits <<= 1; *c = *(ptr++) | (bits & 0x80); cnt++; DATA_ENCODER_TRUE(); } DATA_ENCODER_RETURN_TYPE MNMSysexDecoder::get8(uint8_t *c) { uint8_t byte; totalCnt++; again: if (repeatCount > 0) { repeatCount--; *c = repeatByte; DATA_ENCODER_TRUE(); } DATA_ENCODER_CHECK(getNextByte(&byte)); if (IS_BIT_SET(byte, 7)) { repeatCount = byte & 0x7F; DATA_ENCODER_CHECK(getNextByte(&repeatByte)); goto again; } else { *c = byte; DATA_ENCODER_TRUE(); } }
20.786517
111
0.652703
anupam19
9a9ea4fd5b4657ee6f817ddef3d9c02f4b17b117
674
cpp
C++
solution.cpp
kylianlee/acmicpc_11000
df4fc833ee5aef7385250683d69405400557687e
[ "MIT" ]
null
null
null
solution.cpp
kylianlee/acmicpc_11000
df4fc833ee5aef7385250683d69405400557687e
[ "MIT" ]
null
null
null
solution.cpp
kylianlee/acmicpc_11000
df4fc833ee5aef7385250683d69405400557687e
[ "MIT" ]
null
null
null
// // Created by Kylian Lee on 2021/09/18. // #include <iostream> #include <vector> #include <queue> #include <utility> using namespace std; priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq; int main(){ int class_num; scanf("%d", &class_num); for (int i = 0; i < class_num; ++i) { int start, end; scanf("%d %d", &start, &end); pq.push({start, end}); } priority_queue<int, vector<int>, greater<>> answer; answer.push(pq.top().second); pq.pop(); while(!pq.empty()){ if(answer.top() <= pq.top().first) answer.pop(); answer.push(pq.top().second); pq.pop(); } cout << answer.size() << endl; return 0; }
19.823529
69
0.591988
kylianlee
9a9fffcd98f63cbc05284239b58ae4182f83c68b
3,301
cpp
C++
addons/ofxKinectForWindows2/example/src/ofApp.cpp
syeminpark/openFrame
2d117bf86ae58dbc2d5d0ddc6727f14e5627e6e6
[ "MIT" ]
null
null
null
addons/ofxKinectForWindows2/example/src/ofApp.cpp
syeminpark/openFrame
2d117bf86ae58dbc2d5d0ddc6727f14e5627e6e6
[ "MIT" ]
null
null
null
addons/ofxKinectForWindows2/example/src/ofApp.cpp
syeminpark/openFrame
2d117bf86ae58dbc2d5d0ddc6727f14e5627e6e6
[ "MIT" ]
null
null
null
#include "ofApp.h" int previewWidth = 512; int previewHeight = 424; //-------------------------------------------------------------- void ofApp::setup(){ kinect.open(); kinect.initDepthSource(); kinect.initColorSource(); kinect.initInfraredSource(); kinect.initBodySource(); kinect.initBodyIndexSource(); ofSetWindowShape(previewWidth * 2, previewHeight * 2); } //-------------------------------------------------------------- void ofApp::update(){ kinect.update(); //-- //Getting joint positions (skeleton tracking) //-- // { auto bodies = kinect.getBodySource()->getBodies(); for (auto body : bodies) { for (auto joint : body.joints) { //now do something with the joints } } } // //-- //-- //Getting bones (connected joints) //-- // { // Note that for this we need a reference of which joints are connected to each other. // We call this the 'boneAtlas', and you can ask for a reference to this atlas whenever you like auto bodies = kinect.getBodySource()->getBodies(); auto boneAtlas = ofxKinectForWindows2::Data::Body::getBonesAtlas(); for (auto body : bodies) { for (auto bone : boneAtlas) { auto firstJointInBone = body.joints[bone.first]; auto secondJointInBone = body.joints[bone.second]; //now do something with the joints } } } // //-- } //-------------------------------------------------------------- void ofApp::draw(){ kinect.getDepthSource()->draw(0, 0, previewWidth, previewHeight); // note that the depth texture is RAW so may appear dark // Color is at 1920x1080 instead of 512x424 so we should fix aspect ratio float colorHeight = previewWidth * (kinect.getColorSource()->getHeight() / kinect.getColorSource()->getWidth()); float colorTop = (previewHeight - colorHeight) / 2.0; kinect.getColorSource()->draw(previewWidth, 0 + colorTop, previewWidth, colorHeight); kinect.getBodySource()->drawProjected(previewWidth, 0 + colorTop, previewWidth, colorHeight); kinect.getInfraredSource()->draw(0, previewHeight, previewWidth, previewHeight); kinect.getBodyIndexSource()->draw(previewWidth, previewHeight, previewWidth, previewHeight); kinect.getBodySource()->drawProjected(previewWidth, previewHeight, previewWidth, previewHeight, ofxKFW2::ProjectionCoordinates::DepthCamera); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
27.057377
142
0.541351
syeminpark
9aa057125e59591d9eef384321180649580e4163
17,493
cpp
C++
application_sandbox/stencil_export/main.cpp
apazylbe/vulkan_test_applications
250bb3d371e3c587a8d1ceb5f9187a960b61d63f
[ "Apache-2.0" ]
null
null
null
application_sandbox/stencil_export/main.cpp
apazylbe/vulkan_test_applications
250bb3d371e3c587a8d1ceb5f9187a960b61d63f
[ "Apache-2.0" ]
null
null
null
application_sandbox/stencil_export/main.cpp
apazylbe/vulkan_test_applications
250bb3d371e3c587a8d1ceb5f9187a960b61d63f
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "application_sandbox/sample_application_framework/sample_application.h" #include "support/entry/entry.h" #include "vulkan_helpers/buffer_frame_data.h" #include "vulkan_helpers/helper_functions.h" #include "vulkan_helpers/vulkan_application.h" #include "vulkan_helpers/vulkan_model.h" #include <chrono> #include "mathfu/matrix.h" #include "mathfu/vector.h" using Mat44 = mathfu::Matrix<float, 4, 4>; using Vector4 = mathfu::Vector<float, 4>; namespace x_model { const struct { size_t num_vertices; float positions[24]; float uv[16]; float normals[24]; size_t num_indices; uint32_t indices[12]; } model = {8, /*positions*/ {1.5f, 1.5f, 0.0f, 1.5f, 1.5f, 0.0f, -1.5f, -1.5f, 0.0f, -1.5f, -1.5f, 0.0f, -1.5f, 1.5f, 0.0f, -1.5f, 1.5f, 0.0f, 1.5f, -1.5f, 0.0f, 1.5f, -1.5f, 0.0f}, /*texture_coords*/ {}, /*normals*/ {-1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, -1.0f}, 12, /*indices*/ {0, 2, 1, 1, 2, 3, 4, 5, 6, 6, 5, 7}}; } // namespace x_model const auto& x_cross_data = x_model::model; uint32_t line_vertex_shader[] = #include "line.vert.spv" ; uint32_t line_fragment_shader[] = #include "line.frag.spv" ; struct StencilExportFrameData { containers::unique_ptr<vulkan::VkCommandBuffer> command_buffer_; containers::unique_ptr<vulkan::VkFramebuffer> framebuffer_; containers::unique_ptr<vulkan::DescriptorSet> line_descriptor_set_; vulkan::ImagePointer stencil_; containers::unique_ptr<vulkan::VkImageView> stencil_view_; }; // This creates an application with 16MB of image memory, and defaults // for host, and device buffer sizes. class StencilExportSample : public sample_application::Sample<StencilExportFrameData> { public: StencilExportSample(const entry::EntryData* data) : data_(data), Sample<StencilExportFrameData>( data->allocator(), data, 1, 512, 1, 1, sample_application::SampleOptions().EnableMultisampling(), {}, {}, {VK_EXT_SHADER_STENCIL_EXPORT_EXTENSION_NAME}), x_cross_(data->allocator(), data->logger(), x_cross_data) {} virtual void InitializeApplicationData( vulkan::VkCommandBuffer* initialization_buffer, size_t num_swapchain_images) override { x_cross_.InitializeData(app(), initialization_buffer); line_descriptor_set_layouts_[0] = { 0, // binding VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // descriptorType 1, // descriptorCount VK_SHADER_STAGE_VERTEX_BIT, // stageFlags nullptr // pImmutableSamplers }; line_descriptor_set_layouts_[1] = { 1, // binding VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // descriptorType 1, // descriptorCount VK_SHADER_STAGE_VERTEX_BIT, // stageFlags nullptr // pImmutableSamplers }; pipeline_layout_ = containers::make_unique<vulkan::PipelineLayout>( data_->allocator(), app()->CreatePipelineLayout({{line_descriptor_set_layouts_[0], line_descriptor_set_layouts_[1]}})); VkAttachmentReference color_attachment = { 0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}; VkAttachmentReference stencil_attachment = { 1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL}; render_pass_ = containers::make_unique<vulkan::VkRenderPass>( data_->allocator(), app()->CreateRenderPass( {{ 0, // flags render_format(), // format num_samples(), // samples VK_ATTACHMENT_LOAD_OP_CLEAR, // loadOp VK_ATTACHMENT_STORE_OP_STORE, // storeOp VK_ATTACHMENT_LOAD_OP_DONT_CARE, // stenilLoadOp VK_ATTACHMENT_STORE_OP_DONT_CARE, // stenilStoreOp VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // initialLayout VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // finalLayout }, { 0, // flags VK_FORMAT_D24_UNORM_S8_UINT, // format num_samples(), // samples VK_ATTACHMENT_LOAD_OP_DONT_CARE, // loadOp VK_ATTACHMENT_STORE_OP_DONT_CARE, // storeOp VK_ATTACHMENT_LOAD_OP_CLEAR, // stenilLoadOp VK_ATTACHMENT_STORE_OP_DONT_CARE, // stenilStoreOp VK_IMAGE_LAYOUT_UNDEFINED, // initialLayout VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL // finalLayout }}, // AttachmentDescriptions {{ 0, // flags VK_PIPELINE_BIND_POINT_GRAPHICS, // pipelineBindPoint 0, // inputAttachmentCount nullptr, // pInputAttachments 1, // colorAttachmentCount &color_attachment, // colorAttachment nullptr, // pResolveAttachments &stencil_attachment, // pDepthStencilAttachment 0, // preserveAttachmentCount nullptr // pPreserveAttachments }}, // SubpassDescriptions {} // SubpassDependencies )); VkStencilOpState stencilOpState{VK_STENCIL_OP_KEEP, VK_STENCIL_OP_REPLACE, VK_STENCIL_OP_KEEP, VK_COMPARE_OP_GREATER, UINT32_MAX, UINT32_MAX, 0}; line_pipeline_ = containers::make_unique<vulkan::VulkanGraphicsPipeline>( data_->allocator(), app()->CreateGraphicsPipeline( pipeline_layout_.get(), render_pass_.get(), 0)); line_pipeline_->AddShader(VK_SHADER_STAGE_VERTEX_BIT, "main", line_vertex_shader); line_pipeline_->AddShader(VK_SHADER_STAGE_FRAGMENT_BIT, "main", line_fragment_shader); line_pipeline_->SetTopology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST); line_pipeline_->SetInputStreams(&x_cross_); line_pipeline_->SetViewport(viewport()); line_pipeline_->SetScissor(scissor()); line_pipeline_->SetSamples(num_samples()); line_pipeline_->AddAttachment(); line_pipeline_->DepthStencilState().depthTestEnable = false; line_pipeline_->DepthStencilState().stencilTestEnable = true; line_pipeline_->DepthStencilState().front = stencilOpState; line_pipeline_->Commit(); camera_data_ = containers::make_unique<vulkan::BufferFrameData<CameraData>>( data_->allocator(), app(), num_swapchain_images, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT); model_data_ = containers::make_unique<vulkan::BufferFrameData<ModelData>>( data_->allocator(), app(), num_swapchain_images, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT); float aspect = (float)app()->swapchain().width() / (float)app()->swapchain().height(); camera_data_->data().projection_matrix = Mat44::FromScaleVector(mathfu::Vector<float, 3>{1.0f, -1.0f, 1.0f}) * Mat44::Perspective(1.5708f, aspect, 0.1f, 100.0f); model_data_->data().transform = Mat44::FromTranslationVector( mathfu::Vector<float, 3>{0.0f, 0.0f, -3.0f}); } virtual void InitializeFrameData( StencilExportFrameData* frame_data, vulkan::VkCommandBuffer* initialization_buffer, size_t frame_index) override { frame_data->command_buffer_ = containers::make_unique<vulkan::VkCommandBuffer>( data_->allocator(), app()->GetCommandBuffer()); frame_data->line_descriptor_set_ = containers::make_unique<vulkan::DescriptorSet>( data_->allocator(), app()->AllocateDescriptorSet({line_descriptor_set_layouts_[0], line_descriptor_set_layouts_[1]})); VkDescriptorBufferInfo buffer_infos[2] = { { camera_data_->get_buffer(), // buffer camera_data_->get_offset_for_frame(frame_index), // offset camera_data_->size(), // range }, { model_data_->get_buffer(), // buffer model_data_->get_offset_for_frame(frame_index), // offset model_data_->size(), // range }}; VkWriteDescriptorSet write{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, // sType nullptr, // pNext *frame_data->line_descriptor_set_, // dstSet 0, // dstbinding 0, // dstArrayElement 2, // descriptorCount VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // descriptorType nullptr, // pImageInfo buffer_infos, // pBufferInfo nullptr, // pTexelBufferView }; app()->device()->vkUpdateDescriptorSets(app()->device(), 1, &write, 0, nullptr); VkImageCreateInfo image_create_info{ /* sType = */ VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, /* pNext = */ nullptr, /* flags = */ 0, /* imageType = */ VK_IMAGE_TYPE_2D, /* format = */ VK_FORMAT_D24_UNORM_S8_UINT, /* extent = */ { /* width = */ app()->swapchain().width(), /* height = */ app()->swapchain().height(), /* depth = */ app()->swapchain().depth(), }, /* mipLevels = */ 1, /* arrayLayers = */ 1, /* samples = */ num_samples(), /* tiling = */ VK_IMAGE_TILING_OPTIMAL, /* usage = */ VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, /* sharingMode = */ VK_SHARING_MODE_EXCLUSIVE, /* queueFamilyIndexCount = */ 0, /* pQueueFamilyIndices = */ nullptr, /* initialLayout = */ VK_IMAGE_LAYOUT_UNDEFINED, }; VkImageViewCreateInfo view_create_info = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, // sType nullptr, // pNext 0, // flags VK_NULL_HANDLE, // image VK_IMAGE_VIEW_TYPE_2D, // viewType VK_FORMAT_D24_UNORM_S8_UINT, // format {VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A}, {VK_IMAGE_ASPECT_STENCIL_BIT, 0, 1, 0, 1}}; ::VkImageView raw_views[2] = {color_view(frame_data), VK_NULL_HANDLE}; frame_data->stencil_ = app()->CreateAndBindImage(&image_create_info); view_create_info.image = *frame_data->stencil_; app()->device()->vkCreateImageView(app()->device(), &view_create_info, nullptr, &raw_views[1]); frame_data->stencil_view_ = containers::make_unique<vulkan::VkImageView>( data_->allocator(), vulkan::VkImageView(raw_views[1], nullptr, &app()->device())); // Create a framebuffer with depth and image attachments VkFramebufferCreateInfo framebuffer_create_info{ VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, // sType nullptr, // pNext 0, // flags *render_pass_, // renderPass 2, // attachmentCount raw_views, // attachments app()->swapchain().width(), // width app()->swapchain().height(), // height 1 // layers }; ::VkFramebuffer raw_framebuffer; app()->device()->vkCreateFramebuffer( app()->device(), &framebuffer_create_info, nullptr, &raw_framebuffer); frame_data->framebuffer_ = containers::make_unique<vulkan::VkFramebuffer>( data_->allocator(), vulkan::VkFramebuffer(raw_framebuffer, nullptr, &app()->device())); (*frame_data->command_buffer_) ->vkBeginCommandBuffer((*frame_data->command_buffer_), &sample_application::kBeginCommandBuffer); vulkan::VkCommandBuffer& cmdBuffer = (*frame_data->command_buffer_); VkClearValue clear[2]; vulkan::MemoryClear(&clear[0]); vulkan::MemoryClear(&clear[1]); VkRenderPassBeginInfo pass_begin = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, // sType nullptr, // pNext *render_pass_, // renderPass *frame_data->framebuffer_, // framebuffer {{0, 0}, {app()->swapchain().width(), app()->swapchain().height()}}, // renderArea 2, // clearValueCount clear // clears }; cmdBuffer->vkCmdBeginRenderPass(cmdBuffer, &pass_begin, VK_SUBPASS_CONTENTS_INLINE); cmdBuffer->vkCmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *line_pipeline_); cmdBuffer->vkCmdBindDescriptorSets( cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, ::VkPipelineLayout(*pipeline_layout_), 0, 1, &frame_data->line_descriptor_set_->raw_set(), 0, nullptr); x_cross_.Draw(&cmdBuffer); cmdBuffer->vkCmdEndRenderPass(cmdBuffer); (*frame_data->command_buffer_) ->vkEndCommandBuffer(*frame_data->command_buffer_); } virtual void Update(float time_since_last_render) override { model_data_->data().transform = model_data_->data().transform * Mat44::FromRotationMatrix(Mat44::RotationZ( 3.14f * time_since_last_render)); } virtual void Render(vulkan::VkQueue* queue, size_t frame_index, StencilExportFrameData* frame_data) override { // Update our uniform buffers. camera_data_->UpdateBuffer(queue, frame_index); model_data_->UpdateBuffer(queue, frame_index); VkSubmitInfo init_submit_info{ VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType nullptr, // pNext 0, // waitSemaphoreCount nullptr, // pWaitSemaphores nullptr, // pWaitDstStageMask, 1, // commandBufferCount &(frame_data->command_buffer_->get_command_buffer()), 0, // signalSemaphoreCount nullptr // pSignalSemaphores }; app()->render_queue()->vkQueueSubmit(app()->render_queue(), 1, &init_submit_info, static_cast<VkFence>(VK_NULL_HANDLE)); } private: struct CameraData { Mat44 projection_matrix; }; struct ModelData { Mat44 transform; }; const entry::EntryData* data_; containers::unique_ptr<vulkan::PipelineLayout> pipeline_layout_; containers::unique_ptr<vulkan::VulkanGraphicsPipeline> line_pipeline_; containers::unique_ptr<vulkan::VkRenderPass> render_pass_; VkDescriptorSetLayoutBinding line_descriptor_set_layouts_[2]; vulkan::VulkanModel x_cross_; containers::unique_ptr<vulkan::BufferFrameData<CameraData>> camera_data_; containers::unique_ptr<vulkan::BufferFrameData<ModelData>> model_data_; }; int main_entry(const entry::EntryData* data) { data->logger()->LogInfo("Application Startup"); StencilExportSample sample(data); sample.Initialize(); while (!sample.should_exit() && !data->WindowClosing()) { sample.ProcessFrame(); } sample.WaitIdle(); data->logger()->LogInfo("Application Shutdown"); return 0; }
42.980344
81
0.565998
apazylbe
9aa2275ec79a31055331c9a17e8e7e9cbf0301ed
8,865
cpp
C++
src/algorithms/AllMaximalIndependentSets.cpp
TheoryInPractice/MI-bicliques
ce5ca2cef979ef234dcc96bf089dca90d0268cad
[ "BSD-3-Clause" ]
null
null
null
src/algorithms/AllMaximalIndependentSets.cpp
TheoryInPractice/MI-bicliques
ce5ca2cef979ef234dcc96bf089dca90d0268cad
[ "BSD-3-Clause" ]
null
null
null
src/algorithms/AllMaximalIndependentSets.cpp
TheoryInPractice/MI-bicliques
ce5ca2cef979ef234dcc96bf089dca90d0268cad
[ "BSD-3-Clause" ]
1
2019-07-14T08:49:52.000Z
2019-07-14T08:49:52.000Z
/** * This implements the algorithm of Eppstein for enumerating all maximal * independent sets in a general graph, presented here: * * Eppstein, David. "Small maximal independent sets and faster exact graph * coloring." Workshop on Algorithms and Data Structures. Springer, Berlin, * Heidelberg, 2001. * * @authors Eric Horton, Kyle Kloster, Drew van der Poel * * This file is part of MI-bicliques, https://github.com/TheoryInPractice/MI-bicliques, * and is Copyright (C) North Carolina State University, 2018. * It is licensed under the three-clause BSD license; see LICENSE. */ #include "../graph/Graph.h" #include "../graph/OrderedVertexSet.h" #include "AllMaximalIndependentSets.h" /** * Check whether input node set "independent_set" can have any vertex in input * graph_ptr added to it (i.e. whether it is maximal as an independent set). */ bool check_is_maximal(std::shared_ptr<Graph> graph_ptr, OrderedVertexSet& independent_set){ // for each vertex outside the set, see if it can be added for (auto vertex = 0; vertex < graph_ptr->get_num_vertices(); vertex++){ // Skip vertices in the independent_set if (independent_set.has_vertex(vertex)) continue; // If we find a vertex that's independent from input, output not maximal if (graph_ptr->is_completely_independent_from(vertex,independent_set)) return false; } return true; } /** * Recursively branches on nodes in ed_graph that can be added to the * set independent_set. This is the main subroutine of the MIS enumeration * algorithm of Dias et al. */ void recursive_eppstein(std::shared_ptr<Graph> graph_ptr, std::vector<std::vector<size_t>>& list_of_MIS, EditableGraph& ed_graph, std::unordered_map<size_t,bool>& independent_set, size_t size_limit ) { // if S = 0 or size_limit = 0, check to add to the list of MISs if ( (ed_graph.size()==0) || (size_limit == 0) ){ // faster to check maximality using an OVS OrderedVertexSet IS(independent_set); // if it's maximal, add to the list if (check_is_maximal(graph_ptr,IS)) { list_of_MIS.push_back(IS.get_vertices()); } return; } // DEGREE 0: subgraph contains vertices of degree exactly 0 else if (ed_graph.degree_buckets[0].size() > 0) { // put all degree zero vertices into independent set auto temp_bucket = ed_graph.degree_buckets[0]; for (auto const & iter : temp_bucket) { size_t vertex = iter.first; ed_graph.delete_node(vertex); // delete vertex from subgraph independent_set[vertex] = true; // add v to independent set size_limit--; // decrement for each vertex deleted } recursive_eppstein(graph_ptr, list_of_MIS, ed_graph, independent_set, size_limit ); return; } // DEGREE 1: subset_of_graph contains a vertex of degree exactly 1 else if (ed_graph.degree_buckets[1].size() > 0) { // use the first vertex (v) we can find with degree 1 size_t vertex = ed_graph.degree_buckets[1].begin()->first; // get only neighbor (u) of vertex (v) size_t neighbor = ed_graph.get_neighbors(vertex).begin()->first; // FIRST recursive call: (S-N(v), I+v, k-1) // create subgraph minus the deleted vertex EditableGraph ed_graph_v = ed_graph; ed_graph_v.delete_neighbors(vertex); // copy independent set auto independent_set_copy = independent_set; independent_set_copy[vertex] = true; // make recursive call recursive_eppstein(graph_ptr, list_of_MIS, ed_graph_v, independent_set_copy, size_limit - 1 ); // SECOND recursive call: (S-N(u), I+u, k-1) // Delete N(u) from graph ed_graph.delete_neighbors(neighbor); // add neighbor to independent set independent_set[neighbor] = true; recursive_eppstein(graph_ptr, list_of_MIS, ed_graph, independent_set, size_limit - 1 ); return; } // DEGREE 3+: if subset_of_graph contains a vertex with induced degree >= 3 else if (ed_graph.degree_buckets[3].size() > 0) { // use the first vertex we can find with degree 3+ size_t vertex = ed_graph.degree_buckets[3].begin()->first; // FIRST recursive call: (S-v, I, k) // create subgraph minus the deleted vertex EditableGraph ed_graph_v = ed_graph; ed_graph_v.delete_node(vertex); // copy independent set auto independent_set_copy = independent_set; // make recursive call recursive_eppstein(graph_ptr, list_of_MIS, ed_graph_v, independent_set_copy, size_limit ); // SECOND recursive call: (S-N(v), I+v, k-1) // Delete N(v) from graph ed_graph.delete_neighbors(vertex); // add vertex to independent set independent_set[vertex] = true; recursive_eppstein(graph_ptr, list_of_MIS, ed_graph, independent_set, size_limit - 1 ); return; } // ALL VERTICES DEGREE 2 // FIRST recursive call: (S-N(v), I+v, k-1) // SECOND recursive call: (S-N(u), I+u, k-1) // THIRD recursive call: (S-N(w)-u, I+w, k-1) else { // use the first vertex (v) we can find with degree 2 size_t vertex = ed_graph.degree_buckets[2].begin()->first; std::vector<size_t> neighbors = {}; for (auto const & iter : ed_graph.get_neighbors(vertex)) neighbors.push_back(iter.first); size_t neighb_u = neighbors[0]; size_t neighb_w = neighbors[1]; // FIRST remove N(v) EditableGraph ed_graph_v = ed_graph; ed_graph_v.delete_neighbors(vertex); // copy independent set auto independent_set_copy = independent_set; independent_set_copy[vertex] = true; // make recursive call recursive_eppstein(graph_ptr, list_of_MIS, ed_graph_v, independent_set_copy, size_limit - 1 ); // SECOND remove N(u) EditableGraph ed_graph_u = ed_graph; ed_graph_u.delete_neighbors(neighb_u); // copy independent set auto independent_set_copy_u = independent_set; independent_set_copy_u[neighb_u] = true; // make recursive call recursive_eppstein(graph_ptr, list_of_MIS, ed_graph_u, independent_set_copy_u, size_limit - 1 ); // SECOND remove N(w) and u ed_graph.delete_neighbors(neighb_w); ed_graph.delete_node(neighb_u); // update independent set independent_set[neighb_w] = true; // make recursive call recursive_eppstein(graph_ptr, list_of_MIS, ed_graph, independent_set, size_limit - 1 ); return; } } /** * Wrapper for the maximal-independent-set enumeration algorithm. * Given input graph g, output a vector containing all maximal independent sets * in g. Each such independent set is stored as a vector containing node * indices in ascending order. */ std::vector<std::vector<size_t>> get_all_mis(Graph & g) { // Initializations // Get shared_ptr for graph auto graph_ptr = std::make_shared<Graph>(g); // Get editable graph EditableGraph ed_graph(g); // Output will be vector of MISs std::vector<std::vector<size_t>> list_of_MIS; // initialize full list of graph's vertices size_t num_vertices = g.get_num_vertices(); // initialize empty set std::unordered_map<size_t,bool> potential_MIS; recursive_eppstein(graph_ptr, list_of_MIS, ed_graph, potential_MIS, num_vertices ); return list_of_MIS; }
32.00361
97
0.570446
TheoryInPractice
9aa44ab013d4ea06a37dab5fec1871e02da1e5f3
2,639
hpp
C++
src/dwalker/include/PEManager.hpp
shmmsra/dwalker
4996adcec11bb92ad6d67a8d2e79bd5b022cb67f
[ "MIT" ]
null
null
null
src/dwalker/include/PEManager.hpp
shmmsra/dwalker
4996adcec11bb92ad6d67a8d2e79bd5b022cb67f
[ "MIT" ]
null
null
null
src/dwalker/include/PEManager.hpp
shmmsra/dwalker
4996adcec11bb92ad6d67a8d2e79bd5b022cb67f
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> #include <memory> #include <PHLib.hpp> #include <PE.hpp> #include <ApiSet.hpp> struct PeImport { unsigned short Hint; unsigned short Ordinal; std::string Name; std::string ModuleName; bool ImportByOrdinal; bool DelayImport; PeImport(const PPH_MAPPED_IMAGE_IMPORT_DLL importDll, size_t Index); PeImport(const PeImport& other); ~PeImport(); }; struct PeImportDll { public: long Flags; std::string Name; long NumberOfEntries; std::vector<PeImport> ImportList; // constructors PeImportDll(const PPH_MAPPED_IMAGE_IMPORTS& PvMappedImports, size_t ImportDllIndex); PeImportDll(const PeImportDll& other); // destructors ~PeImportDll(); // getters bool IsDelayLoad(); private: PPH_MAPPED_IMAGE_IMPORT_DLL ImportDll; }; struct PeProperties { short Machine; // DateTime^ Time; short Magic; long ImageBase; int SizeOfImage; long EntryPoint; int Checksum; bool CorrectChecksum; short Subsystem; std::pair<short, short>* SubsystemVersion; short Characteristics; short DllCharacteristics; unsigned long FileSize; }; class PEManager { public: PEManager(const std::wstring& filepath); ~PEManager(); // Mapped the PE in memory and init infos bool Load(); // Unmapped the PE from memory void Unload(); // Check if the PE is 32-bit bool IsWow64Dll(); // Return the ApiSetSchemaBase std::unique_ptr<ApiSetSchemaBase> GetApiSetSchema(); // Return the list of functions exported by the PE // List<PeExport ^>^ GetExports(); // Return the list of functions imported by the PE, bundled by Dll name std::vector<PeImportDll> GetImports(); // Retrieve the manifest embedded within the PE // Return an empty string if there is none. // NOTE: Currently only support reading normal string (not wstring) // because Xerces library doesn't seem to support that either std::string GetManifest(); // PE properties parsed from the NT header PeProperties* properties; // Check if the specified file has been successfully parsed as a PE file. bool loadSuccessful; // Path to PE file. std::wstring filepath; protected: // Initalize PeProperties struct once the PE has been loaded into memory bool InitProperties(); private: // C++ part interfacing with phlib PE* m_Impl; // local cache for imports and exports list std::vector<PeImportDll> m_Imports; // List<PeExport ^>^ m_Exports; bool m_ExportsInit; bool m_ImportsInit; };
22.176471
88
0.685866
shmmsra
9aaa32b8f7faa53eeb07eedcc6d0b0432185bd7b
1,027
cpp
C++
src/serializable.cpp
AperLambda/AperCommon
f35deee3784c2e3995fe8442c338aa2f7700142b
[ "MIT" ]
7
2017-08-14T10:40:19.000Z
2022-01-17T16:11:45.000Z
src/serializable.cpp
AperLambda/lambdacommon
f35deee3784c2e3995fe8442c338aa2f7700142b
[ "MIT" ]
null
null
null
src/serializable.cpp
AperLambda/lambdacommon
f35deee3784c2e3995fe8442c338aa2f7700142b
[ "MIT" ]
null
null
null
/* * Copyright © 2019 LambdAurora <aurora42lambda@gmail.com> * * This file is part of λcommon. * * Licensed under the MIT license. For more information, * see the LICENSE file. */ #include "../include/lambdacommon/serializable.h" namespace lambdacommon { namespace serializable { std::vector<std::string> LAMBDACOMMON_API tokenize(const std::string& _string, const std::string& delim) { std::string::size_type last_pos = 0; std::string::size_type pos = _string.find_first_of(delim, last_pos); std::vector<std::string> tokens; while (last_pos != std::string::npos) { if (pos != last_pos) tokens.push_back(_string.substr(last_pos, pos - last_pos)); last_pos = pos; if (last_pos == std::string::npos || last_pos + 1 == _string.length()) break; pos = _string.find_first_of(delim, ++last_pos); } return tokens; } } }
30.205882
114
0.57741
AperLambda
9aaa7871a9043ee5b33360e07308437e026f85f4
2,746
cpp
C++
openbr/plugins/gui/drawgridlines.cpp
gaatyin/openbr
a55fa7bd0038b323ade2340c69f109146f084218
[ "Apache-2.0" ]
1
2021-04-26T12:53:42.000Z
2021-04-26T12:53:42.000Z
openbr/plugins/gui/drawgridlines.cpp
William-New/openbr
326f9bbb84de35586e57b1b0449c220726571c6c
[ "Apache-2.0" ]
null
null
null
openbr/plugins/gui/drawgridlines.cpp
William-New/openbr
326f9bbb84de35586e57b1b0449c220726571c6c
[ "Apache-2.0" ]
null
null
null
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 The MITRE Corporation * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <openbr/plugins/openbr_internal.h> #include <opencv2/imgproc.hpp> using namespace cv; namespace br { /*! * \ingroup transforms * \brief Draws a grid on the image * \author Josh Klontz \cite jklontz */ class DrawGridLinesTransform : public UntrainableTransform { Q_OBJECT Q_PROPERTY(int rows READ get_rows WRITE set_rows RESET reset_rows STORED false) Q_PROPERTY(int columns READ get_columns WRITE set_columns RESET reset_columns STORED false) Q_PROPERTY(int r READ get_r WRITE set_r RESET reset_r STORED false) Q_PROPERTY(int g READ get_g WRITE set_g RESET reset_g STORED false) Q_PROPERTY(int b READ get_b WRITE set_b RESET reset_b STORED false) BR_PROPERTY(int, rows, 0) BR_PROPERTY(int, columns, 0) BR_PROPERTY(int, r, 196) BR_PROPERTY(int, g, 196) BR_PROPERTY(int, b, 196) void project(const Template &src, Template &dst) const { Mat m = src.m().clone(); float rowStep = 1.f * m.rows / (rows+1); float columnStep = 1.f * m.cols / (columns+1); int thickness = qMin(m.rows, m.cols) / 256; for (float row = rowStep/2; row < m.rows; row += rowStep) line(m, Point(0, row), Point(m.cols, row), Scalar(r, g, b), thickness, LINE_AA); for (float column = columnStep/2; column < m.cols; column += columnStep) line(m, Point(column, 0), Point(column, m.rows), Scalar(r, g, b), thickness, LINE_AA); dst = m; } }; BR_REGISTER(Transform, DrawGridLinesTransform) } // namespace br #include "gui/drawgridlines.moc"
42.90625
98
0.545157
gaatyin
9aab037399f466f54280363b00c770d0ac49434e
1,936
hh
C++
include/libbio/dispatch/dispatch_ptr.hh
tsnorri/libbio
6cd929ac5f7bcccc340be60a6aa0a4ca6c7cb761
[ "MIT" ]
2
2021-05-21T08:44:53.000Z
2021-12-24T16:22:56.000Z
include/libbio/dispatch/dispatch_ptr.hh
tsnorri/libbio
6cd929ac5f7bcccc340be60a6aa0a4ca6c7cb761
[ "MIT" ]
null
null
null
include/libbio/dispatch/dispatch_ptr.hh
tsnorri/libbio
6cd929ac5f7bcccc340be60a6aa0a4ca6c7cb761
[ "MIT" ]
null
null
null
/* * Copyright (c) 2016-2018 Tuukka Norri * This code is licensed under MIT license (see LICENSE for details). */ #ifndef LIBBIO_DISPATCH_DISPATCH_PTR_HH #define LIBBIO_DISPATCH_DISPATCH_PTR_HH #include <dispatch/dispatch.h> #include <utility> namespace libbio { template <typename t_dispatch> class dispatch_ptr { protected: t_dispatch m_ptr{}; public: dispatch_ptr() { } explicit dispatch_ptr(t_dispatch ptr, bool retain = false): m_ptr(ptr) { if (m_ptr && retain) dispatch_retain(m_ptr); } ~dispatch_ptr() { if (m_ptr) dispatch_release(m_ptr); } dispatch_ptr(dispatch_ptr const &other): dispatch_ptr(other.m_ptr, true) { } dispatch_ptr(dispatch_ptr &&other): m_ptr(other.m_ptr) { other.m_ptr = nullptr; } bool operator==(dispatch_ptr const &other) const { return m_ptr == other.m_ptr; } bool operator!=(dispatch_ptr const &other) const { return !(*this == other); } // std::unique_ptr has explicit operator bool, so we should probably too. explicit operator bool() const noexcept { return (m_ptr ? true : false); } dispatch_ptr &operator=(dispatch_ptr const &other) & { if (*this != other) { if (m_ptr) dispatch_release(m_ptr); m_ptr = other.m_ptr; dispatch_retain(m_ptr); } return *this; } dispatch_ptr &operator=(dispatch_ptr &&other) & { if (*this != other) { m_ptr = other.m_ptr; other.m_ptr = nullptr; } return *this; } t_dispatch operator*() { return m_ptr; } void reset(t_dispatch ptr = nullptr, bool retain = false) { if (m_ptr) dispatch_release(m_ptr); m_ptr = ptr; if (retain && m_ptr) dispatch_retain(m_ptr); } }; template <typename t_dispatch> void swap(dispatch_ptr <t_dispatch> &lhs, dispatch_ptr <t_dispatch> &rhs) { using std::swap; swap(lhs.m_ptr, rhs.m_ptr); } } #endif
17.285714
75
0.644112
tsnorri
9aae4ee0b7a4aa188f2e2316079f4f471f1c8a5a
3,416
cpp
C++
51nod/1037.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
3
2017-09-17T09:12:50.000Z
2018-04-06T01:18:17.000Z
51nod/1037.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
51nod/1037.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
#pragma GCC optimize 2 #include <bits/stdc++.h> #define N 100020 #define ll long long using namespace std; inline ll read(){ ll x=0,f=1;char ch=getchar(); while(ch>'9'||ch<'0')ch=='-'&&(f=0)||(ch=getchar()); while(ch<='9'&&ch>='0')x=(x<<3)+(x<<1)+ch-'0',ch=getchar(); return f?x:-x; } inline ll rand(ll mx) { return (ll) rand() * rand() % mx + 1; } inline ll safe_mul(ll x, ll y, ll p) { ll z = 0 % p; for (; y; y >>= 1, x = (x + x) % p) { if (y & 1) { z = (z + x) % p; } } return z; } inline ll fast_pow(ll x, ll y, ll p) { ll z = 1 % p; for (; y; y >>= 1, x = safe_mul(x, x, p)) { if (y & 1) { z = safe_mul(z, x, p); } } return z; } int primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37 }; bool isPrime(ll n) { if (n == 2) return true; if (n <= 1) return false; if (!(n & 1)) return false; ll m = n - 1, k = 0; while (!(m & 1)) { ++ k; m >>= 1; } for (int i = 0; i < 12; ++ i) { ll a = primes[i]; if (n == a) return true; ll x = fast_pow(a, m, n), y; for (int j = 1; j <= k; ++ j) { y = safe_mul(x, x, n); if (y == 1 && x != 1 && x != n - 1) { return false; } x = y; } if (y != 1) { return false; } } return true; } inline ll F(ll x, ll p) { return (safe_mul(x, x, p) + rand(p)) % p; } ll rho(ll n) { // printf("rho %lld\n", n); if (rand() % 3 != 0) { for (ll a = rand(n), d = 1, k = 1; d == 1; a = F(a, n), ++ k) { // printf("gcd(%lld, %lld)\n", a, n); d = __gcd(a, n); if (d > 1) { if (d == n) return rho(n); else return d; } if (k == 10) { k = 0; a = rand(n); } } } else { for (ll a = rand(n), d = 1, k = 1, s = 1; d == 1; a = F(a, n), ++ k) { // printf("gcd(%lld, %lld)\n", a, n); d = __gcd(a, n); if (d > 1) { if (d == n) return rho(n); else return d; } if (k == s) { a = rand(n); s <<= 1; } } } return 1; } vector<ll> ps, vs, cs; void resolve(ll n) { // printf("resolving %lld\n", n); if (n <= 1) return; if (isPrime(n)) { ps.push_back(n); return; } // printf("%lld is not prime\n", n); ll d = rho(n); resolve(d); resolve(n / d); } void decompose(ll n) { ps.clear(); vs.clear(); cs.clear(); resolve(n); sort(ps.begin(), ps.end()); for (size_t i = 0; i < ps.size(); ++ i) { if (!i || ps[i] != ps[i - 1]) { vs.push_back(ps[i]); cs.push_back(1); } else { ++ *cs.rbegin(); } } } vector<ll> ds; void dfs_ds(ll x, int d) { ds.push_back(x); if (d == vs.size()) return; for (int i = 0; i <= cs[d]; ++ i) { dfs_ds(x, d + 1); x *= vs[d]; } } bool check(ll n) { if (!isPrime(n)) return false; ll m = n - 1; decompose(m); dfs_ds(1, 0); sort(ds.begin(), ds.end()); for (ll d : ds) { // printf("enum %lld...\n", d); if (fast_pow(10, d, n) == 1) { return d == n - 1; } } return false; } int main(int argc, char const *argv[]) { // freopen("../tmp/.in", "r", stdin); for (ll n = read(); n; -- n) { if (n == 928098230207300044ll) return puts("928098230207299891"), 0; srand(n); if (check(n)) { return printf("%lld\n", n), 0; } else { // printf("%lld is not what i am fucking want.\n", n); } } // puts("zyy AK IOI 9102"); return 0; }
19.52
74
0.43589
swwind
9aae8cf1d38d195dab8f63a67a3e221bba43032a
4,484
cpp
C++
src/ProvisioningCipher.cpp
yorickdewid/Signalpp
c66d7455f46b883caf61cabd0dd01d3eb0839515
[ "BSD-3-Clause" ]
1
2017-07-08T12:36:01.000Z
2017-07-08T12:36:01.000Z
src/ProvisioningCipher.cpp
yorickdewid/Signalpp
c66d7455f46b883caf61cabd0dd01d3eb0839515
[ "BSD-3-Clause" ]
null
null
null
src/ProvisioningCipher.cpp
yorickdewid/Signalpp
c66d7455f46b883caf61cabd0dd01d3eb0839515
[ "BSD-3-Clause" ]
null
null
null
#include "Logger.h" #include "Helper.h" #include "Base64.h" #include "CryptoProvider.h" #include "ProvisioningCipher.h" #include "KeyHelper.h" #include "DeviceMessages.pb.h" #include <hkdf.h> using namespace signalpp; ProvisioningCipher::ProvisioningCipher() { signal_context_create(&context, 0);//TODO: move CryptoProvider::hook(context); } ProvisioningCipher::~ProvisioningCipher() { // SIGNAL_UNREF(key_pair); signal_context_destroy(context);//TODO: move } ec_public_key *ProvisioningCipher::getPublicKey() { int result = curve_generate_key_pair(context, &key_pair); if (result) { SIGNAL_LOG_ERROR << "curve_generate_key_pair() failed"; return nullptr; //TODO: throw } return ec_key_pair_get_public(key_pair); } ProvisionInfo ProvisioningCipher::decrypt(textsecure::ProvisionEnvelope& provisionEnvelope) { ProvisionInfo info; std::string masterEphemeral = provisionEnvelope.publickey(); std::string message = provisionEnvelope.body(); if (message[0] != 0x1) { SIGNAL_LOG_ERROR << "Bad version number on ProvisioningMessage"; return info; //TODO: throw } std::string iv = message.substr(1, 16); std::string mac = message.substr(message.size() - 32); std::string ivAndCiphertext = message.substr(0, message.size() - 32); std::string ciphertext = message.substr(16 + 1, message.size() - 32); SIGNAL_LOG_DEBUG << "mac: " << Base64::Encode(mac); SIGNAL_LOG_DEBUG << "ivAndCiphertext: " << Base64::Encode(ivAndCiphertext); SIGNAL_LOG_DEBUG << "ciphertext: " << Base64::Encode(ciphertext); SIGNAL_LOG_DEBUG << "iv: " << Base64::Encode(iv); /* Derive shared secret */ uint8_t *shared_secret = nullptr; ec_private_key *private_key = ec_key_pair_get_private(key_pair); ec_public_key *public_key = nullptr; int result = curve_decode_point(&public_key, (const uint8_t *)masterEphemeral.c_str(), masterEphemeral.size(), context); //TODO: c_str() to data() if (result) { SIGNAL_LOG_ERROR << "Cannot decode public key"; return info; //TODO: throw } result = curve_calculate_agreement(&shared_secret, public_key, private_key); if (result != 32) { SIGNAL_LOG_ERROR << "Agreement failed"; return info; //TODO: throw } /* Derive 3 keys */ hkdf_context *hkdf_context; uint8_t salt[32]; memset(salt, '\0', 32); char infoText[] = "TextSecure Provisioning Message"; result = hkdf_create(&hkdf_context, 3, context); if (result) { SIGNAL_LOG_ERROR << "Key derivation failed"; return info; //TODO: throw } uint8_t *derived_keys = nullptr; result = hkdf_derive_secrets(hkdf_context, &derived_keys, //TODO: use cryptoprovider shared_secret, 32, salt, 32, (uint8_t *)infoText, 31, 96); if (result != 96) { SIGNAL_LOG_ERROR << "Key derivation failed"; return info; //TODO: throw } std::string derivedKeys = std::string((char *)derived_keys, 96); std::string key0 = derivedKeys.substr(0, 32); std::string key1 = derivedKeys.substr(32, 32); std::string key2 = derivedKeys.substr(64, 32); SIGNAL_LOG_DEBUG << "key0: " << Base64::Encode(key0); SIGNAL_LOG_DEBUG << "key1: " << Base64::Encode(key1); SIGNAL_LOG_DEBUG << "key2: " << Base64::Encode(key2); /* Verify MAC and decrypt */ if (CryptoProvider::verifyMAC(ivAndCiphertext, key1, mac, 32)) { std::string plaintext = CryptoProvider::decrypt(key0, ciphertext, iv); textsecure::ProvisionMessage ProvisionMessage; ProvisionMessage.ParseFromString(plaintext); SIGNAL_LOG_DEBUG << "identityKeyPrivate size: " << ProvisionMessage.identitykeyprivate().size(); SIGNAL_LOG_DEBUG << "number: " << ProvisionMessage.number(); SIGNAL_LOG_DEBUG << "provisioningcode: " << ProvisionMessage.provisioningcode(); SIGNAL_LOG_DEBUG << "userAgent: " << ProvisionMessage.useragent(); ec_key_pair *_key_pair; ec_public_key *public_key = nullptr; ec_private_key *private_key = nullptr; result = curve_decode_private_point(&private_key, (const uint8_t *)ProvisionMessage.identitykeyprivate().data(), ProvisionMessage.identitykeyprivate().size(), context); result = curve_generate_public_key(&public_key, private_key); ec_key_pair_create(&_key_pair, public_key, private_key); info.identityKeyPair = _key_pair; info.number = ProvisionMessage.number(); info.provisioningCode = ProvisionMessage.provisioningcode(); info.userAgent = ProvisionMessage.useragent(); return info; } SIGNAL_LOG_ERROR << "Message verification failed"; // if (derived_keys) { // free(derived_keys); // } // SIGNAL_UNREF(hkdf_context); // return info; }
30.503401
170
0.730375
yorickdewid
9ab0b4500e62d18b299580808e4590dbe46695d2
547
cpp
C++
Basic Programs/CPP/binarysearch.cpp
PrajaktaSathe/HacktoberFest2020
e84fc7a513afe3dd75c7c28db1866d7f5e6a8147
[ "MIT" ]
null
null
null
Basic Programs/CPP/binarysearch.cpp
PrajaktaSathe/HacktoberFest2020
e84fc7a513afe3dd75c7c28db1866d7f5e6a8147
[ "MIT" ]
null
null
null
Basic Programs/CPP/binarysearch.cpp
PrajaktaSathe/HacktoberFest2020
e84fc7a513afe3dd75c7c28db1866d7f5e6a8147
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> using namespace std; //program to search an element in a sorted array using binary search int bin(int arr[], int start, int end, int k) { while (start<=end) { int mid = start + (end - start) / 2; if (arr[mid] == k) return mid; if (arr[mid] < k) start = mid + 1; else end = mid - 1; } return -1; } int main() { int n; cin>>n; int arr[n]; for(int i=0;i<=n;i++) { cin>>arr[i]; } int k ; cin>>k; int ans = bin(arr, 0, n - 1, k); (ans == -1) ? cout<< "-1": cout<<ans; return 0; } //Time Complexity:O(logn)
13.675
68
0.595978
PrajaktaSathe
9ab1177dc03c9f6f2a1d23f0cb4f5347d31e75e6
838
hpp
C++
include/Shared/SecureRandomGenerator.hpp
Praetonus/Erewhon-Game
0327efc5ea80e1084ffb78191818607e9678dcb3
[ "MIT" ]
1
2018-02-25T18:18:59.000Z
2018-02-25T18:18:59.000Z
include/Shared/SecureRandomGenerator.hpp
Praetonus/Erewhon-Game
0327efc5ea80e1084ffb78191818607e9678dcb3
[ "MIT" ]
null
null
null
include/Shared/SecureRandomGenerator.hpp
Praetonus/Erewhon-Game
0327efc5ea80e1084ffb78191818607e9678dcb3
[ "MIT" ]
null
null
null
// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Erewhon Shared" project // For conditions of distribution and use, see copyright notice in LICENSE #pragma once #ifndef EREWHON_SHARED_SECURE_RANDOM_GENERATOR_HPP #define EREWHON_SHARED_SECURE_RANDOM_GENERATOR_HPP #include <Nazara/Prerequisites.hpp> #include <Shared/RandomGenerator.hpp> #include <Shared/StdRandomGenerator.hpp> #include <memory> namespace ewn { class SecureRandomGenerator : public RandomGenerator { public: SecureRandomGenerator(); ~SecureRandomGenerator() = default; bool operator()(void* ptr, std::size_t length) override; private: std::unique_ptr<RandomGenerator> m_secureGenerator; StdRandomGenerator m_fallbackGenerator; }; } #include <Shared/RandomGenerator.inl> #endif // EREWHON_SHARED_SECURE_RANDOM_GENERATOR_HPP
24.647059
74
0.791169
Praetonus
9ab5a593606dbad340bc4e354322fc60326629f2
3,736
hpp
C++
src/nes/Bus.hpp
clubycoder/nes_emu
b4dac31dc1bd7ebb04ecb0a8593a636567440e97
[ "MIT" ]
null
null
null
src/nes/Bus.hpp
clubycoder/nes_emu
b4dac31dc1bd7ebb04ecb0a8593a636567440e97
[ "MIT" ]
null
null
null
src/nes/Bus.hpp
clubycoder/nes_emu
b4dac31dc1bd7ebb04ecb0a8593a636567440e97
[ "MIT" ]
null
null
null
/******************************************************************************* MIT License Copyright (c) 2020 Chris Luby 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. *******************************************************************************/ /******************************************************************************* Emulation of the bus for the Nintendo Entertainment System that connects all of the components *******************************************************************************/ #pragma once #include <cstdint> #include <memory> #include <chrono> #include <nes/Component.hpp> #include <nes/cpu/CPU2A03.hpp> #include <nes/ram/Ram.hpp> #include <nes/ppu/PPU2C02.hpp> #include <nes/apu/APURP2A03.hpp> #include <nes/controller/Controller.hpp> #include <nes/cart/Cart.hpp> namespace nes { class Bus : public Component { public: Bus( std::shared_ptr<nes::cpu::CPU2A03> cpu, std::shared_ptr<nes::ram::Ram> ram, std::shared_ptr<nes::ppu::PPU2C02> ppu, std::shared_ptr<nes::apu::APURP2A03> apu, std::shared_ptr<nes::controller::Controller> controller ) : m_cpu(cpu) , m_ram(ram) , m_ppu(ppu) , m_apu(apu) , m_controller(controller) { } void reset() override; void clock() override; void load_cart(std::shared_ptr<nes::cart::Cart> cart); const bool cpu_read(const uint16_t addr, uint8_t &data, const bool read_only = false) override; const bool cpu_write(const uint16_t addr, const uint8_t data) override; private: static const uint16_t ADDR_RAM_BEGIN = 0x0000; static const uint16_t ADDR_RAM_END = 0x1FFF; static const uint16_t ADDR_PPU_BEGIN = 0x2000; static const uint16_t ADDR_PPU_END = 0x3FFF; static const uint16_t ADDR_APU_BEGIN = 0x4000; static const uint16_t ADDR_APU_END = 0x4013; static const uint16_t ADDR_APU_STATUS = 0x4015; static const uint16_t ADDR_APU_FRAME_COUNTER = 0x4017; static const uint16_t ADDR_DMA = 0x4014; static const uint16_t ADDR_CONTROLLER_BEGIN = 0x4016; static const uint16_t ADDR_CONTROLLER_END = 0x4017; std::shared_ptr<nes::cpu::CPU2A03> m_cpu; std::shared_ptr<nes::ram::Ram> m_ram; std::shared_ptr<nes::ppu::PPU2C02> m_ppu; std::shared_ptr<nes::apu::APURP2A03> m_apu; std::shared_ptr<nes::controller::Controller> m_controller; std::shared_ptr<nes::cart::Cart> m_cart; static constexpr uint32_t CLOCK_CHECK_AFTER_COUNT = 341 * 262; // Check roughly every screen render static constexpr double CLOCK_CHECK_AFTER_EXPECTED = ((1.0 / 60.0) * 1000.0); // Roughly 60 fps or 21441960Hz uint32_t m_clock_check_count; std::chrono::time_point<std::chrono::high_resolution_clock> m_clock_check_last_timestamp; }; } // nes
40.172043
113
0.679069
clubycoder
9ab787a76aabe3939baecda3e75cc51ceb500c25
13,834
cpp
C++
src/commlib/zcelib/zce_os_adapt_file.cpp
sailzeng/zcelib
88e14ab436f1b40e8071e15ef6d9fae396efc3b4
[ "Apache-2.0" ]
72
2015-01-08T05:01:48.000Z
2021-12-28T06:13:03.000Z
src/commlib/zcelib/zce_os_adapt_file.cpp
sailzeng/zcelib
88e14ab436f1b40e8071e15ef6d9fae396efc3b4
[ "Apache-2.0" ]
4
2016-01-18T12:24:59.000Z
2019-10-12T07:19:15.000Z
src/commlib/zcelib/zce_os_adapt_file.cpp
sailzeng/zcelib
88e14ab436f1b40e8071e15ef6d9fae396efc3b4
[ "Apache-2.0" ]
40
2015-01-26T06:49:18.000Z
2021-07-20T08:11:48.000Z
#include "zce_predefine.h" #include "zce_log_logging.h" #include "zce_os_adapt_predefine.h" #include "zce_os_adapt_time.h" #include "zce_os_adapt_error.h" #include "zce_os_adapt_file.h" //读取文件 ssize_t zce::read(ZCE_HANDLE file_handle, void *buf, size_t count) { //WINDOWS下,长度无法突破32位的,参数限制了ReadFileEx也一样,大概WINDOWS认为没人这样读取文件 //位置当然你是可以调整的 #if defined (ZCE_OS_WINDOWS) DWORD ok_len; BOOL ret_bool = ::ReadFile (file_handle, buf, static_cast<DWORD> (count), &ok_len, NULL); if (ret_bool) { return (ssize_t) ok_len; } else { return -1; } #elif defined (ZCE_OS_LINUX) return ::read (file_handle, buf, count); #endif } //写如文件,WINDOWS下,长度无法突破32位的,当然有人需要写入4G数据吗? //Windows下尽量向POSIX 靠拢了 ssize_t zce::write(ZCE_HANDLE file_handle, const void *buf, size_t count) { #if defined (ZCE_OS_WINDOWS) DWORD ok_len; BOOL ret_bool = ::WriteFile (file_handle, buf, static_cast<DWORD> (count), &ok_len, NULL); if (ret_bool) { //注意zce Windows 下的write是有缓冲的,这个和Linux下的略有区别, //如果需要立即看到,可以用FlushFileBuffers,我暂时看不出一定要这样做的必要, //这个地方为了和POSIX统一,还是调用了这个函数 //另外一个方法是在CreateFile 时增加属性 FILE_FLAG_NO_BUFFERING and FILE_FLAG_WRITE_THROUGH ::FlushFileBuffers(file_handle); return (ssize_t) ok_len; } else { return -1; } #elif defined (ZCE_OS_LINUX) return ::write (file_handle, buf, count); #endif } //截断文件 int zce::truncate(const char *filename, size_t offset) { #if defined (ZCE_OS_WINDOWS) int ret = 0; //打开文件,并且截断,最后关闭 ZCE_HANDLE file_handle = zce::open(filename, (O_CREAT | O_RDWR)); if ( ZCE_INVALID_HANDLE == file_handle) { return -1; } ret = zce::ftruncate(file_handle, offset); if (0 != ret ) { return ret; } zce::close(file_handle); return 0; #endif #if defined (ZCE_OS_LINUX) return ::truncate (filename, static_cast<off_t>(offset)); #endif } //截断文件,倒霉的是WINDOWS下又TMD 没有,用BOOST的又非要遵守他的参数规范,我蛋疼 //其实可以变长,呵呵。 //注意这儿的fd是WIN32 API OpenFile得到的函数,不是你用ISO函数打开的那个fd, int zce::ftruncate(ZCE_HANDLE file_handle, size_t offset) { //Windows2000以前没有 SetFilePointerEx,我不是ACE,我不支持那么多屁事 #if defined (ZCE_OS_WINDOWS) LARGE_INTEGER loff; loff.QuadPart = offset; BOOL bret = ::SetFilePointerEx (file_handle, loff, 0, FILE_BEGIN); if (bret == FALSE) { return -1; } //linux ftruncate,后,吧指针放到了末尾 bret = ::SetEndOfFile (file_handle); if (bret == FALSE) { return -1; } return 0; // #elif defined (ZCE_OS_LINUX) return ::ftruncate (file_handle, static_cast<off_t>(offset)); #endif } //在文件内进行偏移 ssize_t zce::lseek(ZCE_HANDLE file_handle, ssize_t offset, int whence) { #if defined (ZCE_OS_WINDOWS) //WINDOWS的lseek是不支持64位的,所以直接用API,完成工作,(后来有了_lseeki64) DWORD dwmovemethod = FILE_BEGIN; if (whence == SEEK_SET) { dwmovemethod = FILE_BEGIN; } else if (whence == SEEK_CUR) { dwmovemethod = FILE_CURRENT; } else if (whence == SEEK_END) { dwmovemethod = FILE_END; } else { assert(false); } LARGE_INTEGER loff; loff.QuadPart = offset; LARGE_INTEGER new_pos; BOOL bret = ::SetFilePointerEx (file_handle, loff, &new_pos, dwmovemethod); if (bret == FALSE) { return -1; } return static_cast<ssize_t>(new_pos.QuadPart); #elif defined (ZCE_OS_LINUX) // return ::lseek(file_handle, static_cast<off_t> (offset), whence); #endif } //根据文件名称,判断文件的尺寸,如果文件不存在,打不开等,返回-1 int zce::filelen(const char *filename, size_t *file_size) { int ret = 0; ZCE_HANDLE file_handle = zce::open(filename, (O_RDONLY)); if ( ZCE_INVALID_HANDLE == file_handle) { return -1; } ret = zce::filesize (file_handle, file_size); zce::close (file_handle); return ret; } int zce::filesize (ZCE_HANDLE file_handle, size_t *file_size) { #if defined (ZCE_OS_WINDOWS) LARGE_INTEGER size; BOOL ret_bool = ::GetFileSizeEx (file_handle, &size); if (!ret_bool) { return -1; } //32位平台上可能丢长度,但是我就考虑64位系统,你才会突破4G把 *file_size = static_cast<size_t> (size.QuadPart); return 0; // #elif defined (ZCE_OS_LINUX) struct stat sb; int ret = ::fstat(file_handle, &sb); if (ret != 0 ) { return ret; } *file_size = sb.st_size; return 0; #endif } //我曾经很自以为是的认为ACE很土鳖,为什么不直接用open函数,然后用_get_osfhandle转换成HANDLE就可以了。 //关闭的时候用_open_osfhandle转换回来就OK了,但其实发现土鳖的是我, //我完全错误理解了_open_osfhandle函数,这也可能解释了原来pascal原来遇到的问题close触发断言的问题。 //一切都不是RP问题,还是写错了代码。感谢derrickhu和sasukeliu两位,一个隐藏的比较深刻的bug //为什么要提供这个API呢,因为WINDOWS平台大部分都是采用HANDLE处理的 ZCE_HANDLE zce::open (const char *filename, int open_mode, mode_t perms) { //Windows平台 #if defined (ZCE_OS_WINDOWS) //将各种LINUX的参数转换成Windows API的参数 DWORD access = GENERIC_READ; if (ZCE_BIT_IS_SET (open_mode, O_WRONLY)) { //如果仅仅只能写 access = GENERIC_WRITE; } else if (ZCE_BIT_IS_SET (open_mode, O_RDWR)) { access = GENERIC_READ | GENERIC_WRITE; } DWORD creation = OPEN_EXISTING; if ( ZCE_BIT_IS_SET (open_mode, O_CREAT) && ZCE_BIT_IS_SET (open_mode, O_EXCL)) { creation = CREATE_NEW; } else if ( ZCE_BIT_IS_SET (open_mode, O_CREAT) && ZCE_BIT_IS_SET (open_mode, O_TRUNC) ) { creation = CREATE_ALWAYS; } else if (ZCE_BIT_IS_SET (open_mode, O_CREAT)) { creation = OPEN_ALWAYS; } else if (ZCE_BIT_IS_SET (open_mode, O_TRUNC)) { creation = TRUNCATE_EXISTING; } DWORD shared_mode = 0; if ( ZCE_BIT_IS_SET(perms, S_IRGRP) || ZCE_BIT_IS_SET(perms, S_IROTH) || ZCE_BIT_IS_SET(perms, S_IWUSR)) { shared_mode |= FILE_SHARE_READ; } if ( ZCE_BIT_IS_SET(perms, S_IWGRP) || ZCE_BIT_IS_SET(perms, S_IWOTH) || ZCE_BIT_IS_SET(perms, S_IWUSR)) { shared_mode |= FILE_SHARE_WRITE; shared_mode |= FILE_SHARE_DELETE; } ZCE_HANDLE openfile_handle = ZCE_INVALID_HANDLE; //ACE的代码在这段用一个多线程的互斥保护, //因为CreateFileA并不能同时将文件的指针移动到末尾,所以(O_APPEND)这是一个两步操作(先CreateFileA,后SetFilePointerEx), //ACE担心有特殊情况?多线程创建还是?他的没有注释说明这个问题,我暂时不去做保护, //CRITICAL_SECTION fileopen_mutex; ////VISTAT后没有这个异常了 //__try //{ // ::InitializeCriticalSection (&fileopen_mutex); //} //__except (EXCEPTION_EXECUTE_HANDLER) //{ // errno = ENOMEM; // return ZCE_INVALID_HANDLE; //} openfile_handle = ::CreateFileA (filename, access, shared_mode, NULL, creation, FILE_ATTRIBUTE_NORMAL, 0); //如果打开的文件句柄是无效的 if (openfile_handle != ZCE_INVALID_HANDLE && ZCE_BIT_IS_SET (open_mode, O_APPEND)) { LARGE_INTEGER distance_to_move, new_file_pointer; distance_to_move.QuadPart = 0; new_file_pointer.QuadPart = 0; BOOL bret = ::SetFilePointerEx (openfile_handle, distance_to_move, &new_file_pointer, FILE_END); if (FALSE == bret) { ::CloseHandle(openfile_handle); openfile_handle = ZCE_INVALID_HANDLE; } } //对应上面的临界区保护 //::DeleteCriticalSection (&fileopen_mutex); return openfile_handle; #elif defined (ZCE_OS_LINUX) return ::open (filename, open_mode, perms); #endif } //关闭一个文件 int zce::close (ZCE_HANDLE handle) { // #if defined (ZCE_OS_WINDOWS) BOOL bret = ::CloseHandle(handle); if (bret == TRUE) { return 0; } else { return -1; } #elif defined (ZCE_OS_LINUX) return ::close (handle); #endif } //用模版名称建立并且打开一个临时文件, ZCE_HANDLE zce::mkstemp(char *template_name) { #if defined (ZCE_OS_WINDOWS) char *tmp_filename = _mktemp(template_name); return zce::open(tmp_filename, ZCE_DEFAULT_FILE_PERMS); #elif defined (ZCE_OS_LINUX) return ::mkstemp(template_name); #endif } //通过文件名称得到文件的stat信息,你可以认为zce_os_stat就是stat,只是在WINDOWS下stat64,主要是为了长文件考虑的 int zce::stat(const char *path, zce_os_stat *file_stat) { #if defined (ZCE_OS_WINDOWS) return ::_stat64(path, file_stat); #elif defined (ZCE_OS_LINUX) return ::stat(path, file_stat); #endif } //通过文件的句柄得到文件的stat信息 int zce::fstat(ZCE_HANDLE file_handle, zce_os_stat *file_stat) { #if defined (ZCE_OS_WINDOWS) //这个实现比较痛苦,但也没有办法,其他方法(比如用_open_osfhandle)都会偷鸡不成,反舍一把米 BOOL ret_bool = FALSE; BY_HANDLE_FILE_INFORMATION file_info; ret_bool = ::GetFileInformationByHandle(file_handle, &file_info); if (!ret_bool) { return -1; } //转换时间 timeval tv_ct_time = zce::make_timeval(&file_info.ftCreationTime); timeval tv_ac_time = zce::make_timeval(&file_info.ftLastAccessTime); timeval tv_wt_time = zce::make_timeval(&file_info.ftLastWriteTime); LARGE_INTEGER file_size; file_size.HighPart = file_info.nFileSizeHigh; file_size.LowPart = file_info.nFileSizeLow; //_S_IFDIR, memset(file_stat, 0, sizeof(zce_os_stat)); file_stat->st_uid = 0; file_stat->st_gid = 0; file_stat->st_size = file_size.QuadPart; //得到几个时间 //注意st_ctime这儿呀,这儿的LINUX下和Windows是有些不一样的,st_ctime在LINUX下是状态最后改变时间,而在WINDOWS下是创建时间 file_stat->st_ctime = tv_ct_time.tv_sec; file_stat->st_mtime = tv_wt_time.tv_sec; file_stat->st_atime = tv_ac_time.tv_sec; //检查是文件还是目录 file_stat->st_mode = 0; if (file_info.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE ) { file_stat->st_mode = S_IFREG; if (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { file_stat->st_mode = S_IFDIR; } } return 0; #elif defined (ZCE_OS_LINUX) return ::fstat(file_handle, file_stat); #endif } //路径是否是一个目录,如果是返回TRUE,如果不是返回FALSE bool zce::is_directory(const char *path_name) { int ret = 0; zce_os_stat file_stat; ret = zce::stat(path_name, &file_stat); if (0 != ret) { return false; } //如果有目录属性,则true if (file_stat.st_mode & S_IFDIR ) { return true; } else { return false; } } //删除文件 int zce::unlink(const char *filename ) { #if defined (ZCE_OS_WINDOWS) return ::_unlink(filename); #elif defined (ZCE_OS_LINUX) return ::unlink(filename); #endif } // mode_t zce::umask (mode_t cmask) { #if defined (ZCE_OS_WINDOWS) return ::_umask(cmask); #elif defined (ZCE_OS_LINUX) return ::umask(cmask); #endif } //检查文件是否OK,吼吼 //mode 两个平台都支持F_OK,R_OK,W_OK,R_OK|W_OK,X_OK参数LINUX支持,WIN不支持 int zce::access(const char *pathname, int mode) { #if defined (ZCE_OS_WINDOWS) return ::_access_s(pathname, mode); #elif defined (ZCE_OS_LINUX) return ::access(pathname, mode); #endif } //-------------------------------------------------------------------------------------------------- //非标准函数 //用只读方式读取一个文件的内容,返回的buffer最后填充'\0',buf_len >= 1 int zce::read_file_data(const char *filename, char *buffer, size_t buf_len, size_t *read_len, size_t offset) { //参数检查 ZCE_ASSERT(filename && buffer && buf_len >= 1); //打开文件 ZCE_HANDLE fd = zce::open(filename, O_RDONLY); if (ZCE_INVALID_HANDLE == fd) { ZCE_LOG(RS_ERROR, "open file [%s] fail ,error =%d", filename, zce::last_error()); return -1; } zce::lseek(fd,static_cast<ssize_t>(offset),SEEK_SET); //读取内容 ssize_t len = zce::read(fd, buffer, buf_len - 1); zce::close(fd); if (len < 0) { ZCE_LOG(RS_ERROR, "read file [%s] fail ,error =%d", filename, zce::last_error()); return -1; } buffer[len] = 0; *read_len = len; return 0; } //读取文件的全部数据, std::pair<int,std::shared_ptr<char>> zce::read_file_all(const char* filename, size_t* file_len, size_t offset) { int ret=-1; std::shared_ptr<char> null_ptr; //打开文件 ZCE_HANDLE fd=zce::open(filename,O_RDONLY); if(ZCE_INVALID_HANDLE==fd) { ZCE_LOG(RS_ERROR,"open file [%s] fail ,error =%d",filename,zce::last_error()); return std::make_pair(ret,null_ptr); } *file_len = zce::lseek(fd,0,SEEK_END); if(static_cast<size_t>(-1) == *file_len) { zce::close(fd); ZCE_LOG(RS_ERROR,"open file [%s] fail ,error =%d",filename,zce::last_error()); return std::make_pair(ret,null_ptr); } std::shared_ptr<char> ptr(new char [*file_len+1],std::default_delete<char []>()); *(ptr.get() +*file_len)='\0'; //调整偏移,读取内容 zce::lseek(fd,static_cast<ssize_t>(offset),SEEK_SET); ssize_t len=zce::read(fd,ptr.get(),*file_len); zce::close(fd); if(len<0) { ZCE_LOG(RS_ERROR,"read file [%s] fail ,error =%d",filename,zce::last_error()); return std::make_pair(ret,null_ptr); } ret=0; return std::make_pair(ret,ptr); }
23.851724
100
0.596791
sailzeng
9abbf4de82e06978301223619c9da0c8ce982546
26,856
cpp
C++
Universal-Physics-mod/src/PowderToySDL.cpp
AllSafeCyberSecur1ty/Nuclear-Engineering
302d6dcc7c0a85a9191098366b076cf9cb5a9f6e
[ "MIT" ]
1
2022-03-26T20:01:13.000Z
2022-03-26T20:01:13.000Z
Universal-Physics-mod/src/PowderToySDL.cpp
AllSafeCyberSecur1ty/Nuclear-Engineering
302d6dcc7c0a85a9191098366b076cf9cb5a9f6e
[ "MIT" ]
null
null
null
Universal-Physics-mod/src/PowderToySDL.cpp
AllSafeCyberSecur1ty/Nuclear-Engineering
302d6dcc7c0a85a9191098366b076cf9cb5a9f6e
[ "MIT" ]
1
2022-03-26T19:59:13.000Z
2022-03-26T19:59:13.000Z
#include "Config.h" #include "common/tpt-minmax.h" #include <map> #include <ctime> #include <climits> #ifdef WIN #include <direct.h> #endif #include "SDLCompat.h" #ifdef X86_SSE #include <xmmintrin.h> #endif #ifdef X86_SSE3 #include <pmmintrin.h> #endif #include <iostream> #include "Config.h" #if defined(LIN) #include "icon.h" #endif #include <csignal> #include <stdexcept> #ifndef WIN # include <unistd.h> #endif #ifdef MACOSX # ifdef DEBUG # undef DEBUG # define DEBUG 1 # endif # include <CoreServices/CoreServices.h> #endif #include <sys/stat.h> #include "Format.h" #include "Misc.h" #include "graphics/Graphics.h" #include "client/SaveInfo.h" #include "client/GameSave.h" #include "client/SaveFile.h" #include "client/Client.h" #include "gui/game/GameController.h" #include "gui/game/GameView.h" #include "gui/dialogues/ErrorMessage.h" #include "gui/dialogues/ConfirmPrompt.h" #include "gui/interface/Keys.h" #include "gui/Style.h" #include "gui/interface/Engine.h" #define INCLUDE_SYSWM #include "SDLCompat.h" int desktopWidth = 1280, desktopHeight = 1024; SDL_Window * sdl_window; SDL_Renderer * sdl_renderer; SDL_Texture * sdl_texture; int scale = 1; bool fullscreen = false; bool altFullscreen = false; bool forceIntegerScaling = true; bool resizable = false; bool momentumScroll = true; bool showAvatars = true; void StartTextInput() { SDL_StartTextInput(); } void StopTextInput() { SDL_StopTextInput(); } void SetTextInputRect(int x, int y, int w, int h) { SDL_Rect rect; rect.x = x; rect.y = y; rect.w = w; rect.h = h; SDL_SetTextInputRect(&rect); } void ClipboardPush(ByteString text) { SDL_SetClipboardText(text.c_str()); } ByteString ClipboardPull() { return ByteString(SDL_GetClipboardText()); } int GetModifiers() { return SDL_GetModState(); } void LoadWindowPosition() { int savedWindowX = Client::Ref().GetPrefInteger("WindowX", INT_MAX); int savedWindowY = Client::Ref().GetPrefInteger("WindowY", INT_MAX); int borderTop, borderLeft; SDL_GetWindowBordersSize(sdl_window, &borderTop, &borderLeft, nullptr, nullptr); // Sometimes (Windows), the border size may not be reported for 200+ frames // So just have a default of 5 to ensure the window doesn't get stuck where it can't be moved if (borderTop == 0) borderTop = 5; int numDisplays = SDL_GetNumVideoDisplays(); SDL_Rect displayBounds; bool ok = false; for (int i = 0; i < numDisplays; i++) { SDL_GetDisplayBounds(i, &displayBounds); if (savedWindowX + borderTop > displayBounds.x && savedWindowY + borderLeft > displayBounds.y && savedWindowX + borderTop < displayBounds.x + displayBounds.w && savedWindowY + borderLeft < displayBounds.y + displayBounds.h) { ok = true; break; } } if (ok) SDL_SetWindowPosition(sdl_window, savedWindowX + borderLeft, savedWindowY + borderTop); } void SaveWindowPosition() { int x, y; SDL_GetWindowPosition(sdl_window, &x, &y); int borderTop, borderLeft; SDL_GetWindowBordersSize(sdl_window, &borderTop, &borderLeft, nullptr, nullptr); Client::Ref().SetPref("WindowX", x - borderLeft); Client::Ref().SetPref("WindowY", y - borderTop); } void CalculateMousePosition(int *x, int *y) { int globalMx, globalMy; SDL_GetGlobalMouseState(&globalMx, &globalMy); int windowX, windowY; SDL_GetWindowPosition(sdl_window, &windowX, &windowY); if (x) *x = (globalMx - windowX) / scale; if (y) *y = (globalMy - windowY) / scale; } #ifdef OGLI void blit() { SDL_GL_SwapBuffers(); } #else void blit(pixel * vid) { SDL_UpdateTexture(sdl_texture, NULL, vid, WINDOWW * sizeof (Uint32)); // need to clear the renderer if there are black edges (fullscreen, or resizable window) if (fullscreen || resizable) SDL_RenderClear(sdl_renderer); SDL_RenderCopy(sdl_renderer, sdl_texture, NULL, NULL); SDL_RenderPresent(sdl_renderer); } #endif bool RecreateWindow(); void SDLOpen() { if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) { fprintf(stderr, "Initializing SDL (video subsystem): %s\n", SDL_GetError()); exit(-1); } if (!RecreateWindow()) { fprintf(stderr, "Creating SDL window: %s\n", SDL_GetError()); exit(-1); } int displayIndex = SDL_GetWindowDisplayIndex(sdl_window); if (displayIndex >= 0) { SDL_Rect rect; if (!SDL_GetDisplayUsableBounds(displayIndex, &rect)) { desktopWidth = rect.w; desktopHeight = rect.h; } if (Client::Ref().GetPrefBool("AutoDrawLimit", false)) { ui::Engine::Ref().AutoDrawingFrequencyLimit = true; SDL_DisplayMode displayMode; if (!SDL_GetCurrentDisplayMode(displayIndex, &displayMode) && displayMode.refresh_rate >= 60) { ui::Engine::Ref().SetDrawingFrequencyLimit(displayMode.refresh_rate); } } } #ifdef WIN SDL_SysWMinfo SysInfo; SDL_VERSION(&SysInfo.version); if(SDL_GetWindowWMInfo(sdl_window, &SysInfo) <= 0) { printf("%s : %p\n", SDL_GetError(), SysInfo.info.win.window); exit(-1); } HWND WindowHandle = SysInfo.info.win.window; // Use GetModuleHandle to get the Exe HMODULE/HINSTANCE HMODULE hModExe = GetModuleHandle(NULL); HICON hIconSmall = (HICON)LoadImage(hModExe, MAKEINTRESOURCE(101), IMAGE_ICON, 16, 16, LR_SHARED); HICON hIconBig = (HICON)LoadImage(hModExe, MAKEINTRESOURCE(101), IMAGE_ICON, 32, 32, LR_SHARED); SendMessage(WindowHandle, WM_SETICON, ICON_SMALL, (LPARAM)hIconSmall); SendMessage(WindowHandle, WM_SETICON, ICON_BIG, (LPARAM)hIconBig); #endif #ifdef LIN SDL_Surface *icon = SDL_CreateRGBSurfaceFrom((void*)app_icon, 128, 128, 32, 512, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000); SDL_SetWindowIcon(sdl_window, icon); SDL_FreeSurface(icon); #endif } void SDLSetScreen(int scale_, bool resizable_, bool fullscreen_, bool altFullscreen_, bool forceIntegerScaling_) { // bool changingScale = scale != scale_; bool changingFullscreen = fullscreen_ != fullscreen || (altFullscreen_ != altFullscreen && fullscreen); bool changingResizable = resizable != resizable_; scale = scale_; fullscreen = fullscreen_; altFullscreen = altFullscreen_; resizable = resizable_; forceIntegerScaling = forceIntegerScaling_; // Recreate the window when toggling fullscreen, due to occasional issues // Also recreate it when enabling resizable windows, to fix bugs on windows, // see https://github.com/jacob1/The-Powder-Toy/issues/24 if (changingFullscreen || (changingResizable && resizable && !fullscreen)) { RecreateWindow(); return; } if (changingResizable) SDL_RestoreWindow(sdl_window); SDL_SetWindowSize(sdl_window, WINDOWW * scale, WINDOWH * scale); SDL_RenderSetIntegerScale(sdl_renderer, forceIntegerScaling && fullscreen ? SDL_TRUE : SDL_FALSE); unsigned int flags = 0; if (fullscreen) flags = altFullscreen ? SDL_WINDOW_FULLSCREEN : SDL_WINDOW_FULLSCREEN_DESKTOP; SDL_SetWindowFullscreen(sdl_window, flags); if (fullscreen) SDL_RaiseWindow(sdl_window); SDL_SetWindowResizable(sdl_window, resizable ? SDL_TRUE : SDL_FALSE); } bool RecreateWindow() { unsigned int flags = 0; if (fullscreen) flags = altFullscreen ? SDL_WINDOW_FULLSCREEN : SDL_WINDOW_FULLSCREEN_DESKTOP; if (resizable && !fullscreen) flags |= SDL_WINDOW_RESIZABLE; if (sdl_texture) SDL_DestroyTexture(sdl_texture); if (sdl_renderer) SDL_DestroyRenderer(sdl_renderer); if (sdl_window) { SaveWindowPosition(); SDL_DestroyWindow(sdl_window); } sdl_window = SDL_CreateWindow("The Powder Toy", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOWW * scale, WINDOWH * scale, flags); sdl_renderer = SDL_CreateRenderer(sdl_window, -1, 0); if (!sdl_renderer) { fprintf(stderr, "SDL_CreateRenderer failed; available renderers:\n"); int num = SDL_GetNumRenderDrivers(); for (int i = 0; i < num; ++i) { SDL_RendererInfo info; SDL_GetRenderDriverInfo(i, &info); fprintf(stderr, " - %s\n", info.name); } return false; } SDL_RenderSetLogicalSize(sdl_renderer, WINDOWW, WINDOWH); if (forceIntegerScaling && fullscreen) SDL_RenderSetIntegerScale(sdl_renderer, SDL_TRUE); sdl_texture = SDL_CreateTexture(sdl_renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, WINDOWW, WINDOWH); SDL_RaiseWindow(sdl_window); //Uncomment this to enable resizing //SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear"); //SDL_SetWindowResizable(sdl_window, SDL_TRUE); if (!Client::Ref().IsFirstRun()) LoadWindowPosition(); return true; } unsigned int GetTicks() { return SDL_GetTicks(); } std::map<ByteString, ByteString> readArguments(int argc, char * argv[]) { std::map<ByteString, ByteString> arguments; //Defaults arguments["scale"] = ""; arguments["proxy"] = ""; arguments["nohud"] = "false"; //the nohud, sound, and scripts commands currently do nothing. arguments["sound"] = "false"; arguments["kiosk"] = "false"; arguments["redirect"] = "false"; arguments["scripts"] = "false"; arguments["open"] = ""; arguments["ddir"] = ""; arguments["ptsave"] = ""; arguments["font"] = ""; for (int i=1; i<argc; i++) { if (!strncmp(argv[i], "scale:", 6) && argv[i]+6) { arguments["scale"] = argv[i]+6; } if (!strncmp(argv[i], "font:", 5) && argv[i]+5) { arguments["font"] = argv[i]+5; } else if (!strncmp(argv[i], "proxy:", 6)) { if(argv[i]+6) arguments["proxy"] = argv[i]+6; else arguments["proxy"] = "false"; } else if (!strncmp(argv[i], "nohud", 5)) { arguments["nohud"] = "true"; } else if (!strncmp(argv[i], "kiosk", 5)) { arguments["kiosk"] = "true"; } else if (!strncmp(argv[i], "redirect", 8)) { arguments["redirect"] = "true"; } else if (!strncmp(argv[i], "sound", 5)) { arguments["sound"] = "true"; } else if (!strncmp(argv[i], "scripts", 8)) { arguments["scripts"] = "true"; } else if (!strncmp(argv[i], "open", 5) && i+1<argc) { arguments["open"] = argv[i+1]; i++; } else if (!strncmp(argv[i], "ddir", 5) && i+1<argc) { arguments["ddir"] = argv[i+1]; i++; } else if (!strncmp(argv[i], "ptsave", 7) && i+1<argc) { arguments["ptsave"] = argv[i+1]; i++; break; } else if (!strncmp(argv[i], "disable-network", 16)) { arguments["disable-network"] = "true"; } } return arguments; } int elapsedTime = 0, currentTime = 0, lastTime = 0, currentFrame = 0; unsigned int lastTick = 0; unsigned int lastFpsUpdate = 0; float fps = 0; ui::Engine * engine = NULL; bool showLargeScreenDialog = false; float currentWidth, currentHeight; int mousex = 0, mousey = 0; int mouseButton = 0; bool mouseDown = false; bool calculatedInitialMouse = false, delay = false; bool hasMouseMoved = false; void EventProcess(SDL_Event event) { switch (event.type) { case SDL_QUIT: if (engine->GetFastQuit() || engine->CloseWindow()) engine->Exit(); break; case SDL_KEYDOWN: if (SDL_GetModState() & KMOD_GUI) { break; } if (!event.key.repeat && event.key.keysym.sym == 'q' && (event.key.keysym.mod&KMOD_CTRL)) engine->ConfirmExit(); else engine->onKeyPress(event.key.keysym.sym, event.key.keysym.scancode, event.key.repeat, event.key.keysym.mod&KMOD_SHIFT, event.key.keysym.mod&KMOD_CTRL, event.key.keysym.mod&KMOD_ALT); break; case SDL_KEYUP: if (SDL_GetModState() & KMOD_GUI) { break; } engine->onKeyRelease(event.key.keysym.sym, event.key.keysym.scancode, event.key.repeat, event.key.keysym.mod&KMOD_SHIFT, event.key.keysym.mod&KMOD_CTRL, event.key.keysym.mod&KMOD_ALT); break; case SDL_TEXTINPUT: if (SDL_GetModState() & KMOD_GUI) { break; } engine->onTextInput(ByteString(event.text.text).FromUtf8()); break; case SDL_TEXTEDITING: if (SDL_GetModState() & KMOD_GUI) { break; } engine->onTextEditing(ByteString(event.edit.text).FromUtf8(), event.edit.start); break; case SDL_MOUSEWHEEL: { int x = event.wheel.x; int y = event.wheel.y; if (event.wheel.direction == SDL_MOUSEWHEEL_FLIPPED) { x *= -1; y *= -1; } engine->onMouseWheel(mousex, mousey, y); // TODO: pass x? break; } case SDL_MOUSEMOTION: mousex = event.motion.x; mousey = event.motion.y; engine->onMouseMove(mousex, mousey); hasMouseMoved = true; break; case SDL_DROPFILE: engine->onFileDrop(event.drop.file); SDL_free(event.drop.file); break; case SDL_MOUSEBUTTONDOWN: // if mouse hasn't moved yet, sdl will send 0,0. We don't want that if (hasMouseMoved) { mousex = event.button.x; mousey = event.button.y; } mouseButton = event.button.button; engine->onMouseClick(mousex, mousey, mouseButton); mouseDown = true; #if !defined(NDEBUG) && !defined(DEBUG) SDL_CaptureMouse(SDL_TRUE); #endif break; case SDL_MOUSEBUTTONUP: // if mouse hasn't moved yet, sdl will send 0,0. We don't want that if (hasMouseMoved) { mousex = event.button.x; mousey = event.button.y; } mouseButton = event.button.button; engine->onMouseUnclick(mousex, mousey, mouseButton); mouseDown = false; #if !defined(NDEBUG) && !defined(DEBUG) SDL_CaptureMouse(SDL_FALSE); #endif break; case SDL_WINDOWEVENT: { switch (event.window.event) { case SDL_WINDOWEVENT_SHOWN: if (!calculatedInitialMouse) { //initial mouse coords, sdl won't tell us this if mouse hasn't moved CalculateMousePosition(&mousex, &mousey); engine->initialMouse(mousex, mousey); engine->onMouseMove(mousex, mousey); calculatedInitialMouse = true; } break; // This event would be needed in certain glitchy cases of window resizing // But for all currently tested cases, it isn't needed /*case SDL_WINDOWEVENT_RESIZED: { float width = event.window.data1; float height = event.window.data2; currentWidth = width; currentHeight = height; // this "* scale" thing doesn't really work properly // currently there is a bug where input doesn't scale properly after resizing, only when double scale mode is active inputScaleH = (float)WINDOWW * scale / currentWidth; inputScaleV = (float)WINDOWH * scale / currentHeight; std::cout << "Changing input scale to " << inputScaleH << "x" << inputScaleV << std::endl; break; }*/ // This would send a mouse up event when focus is lost // Not even sdl itself will know when the mouse was released if it happens in another window // So it will ignore the next mouse down (after tpt is re-focused) and not send any events at all // This is more unintuitive than pretending the mouse is still down when it's not, so this code is commented out /*case SDL_WINDOWEVENT_FOCUS_LOST: if (mouseDown) { mouseDown = false; engine->onMouseUnclick(mousex, mousey, mouseButton); } break;*/ } break; } } } void LargeScreenDialog() { StringBuilder message; message << "Switching to " << scale << "x size mode since your screen was determined to be large enough: "; message << desktopWidth << "x" << desktopHeight << " detected, " << WINDOWW*scale << "x" << WINDOWH*scale << " required"; message << "\nTo undo this, hit Cancel. You can change this in settings at any time."; if (!ConfirmPrompt::Blocking("Large screen detected", message.Build())) { Client::Ref().SetPref("Scale", 1); engine->SetScale(1); } } void EngineProcess() { double frameTimeAvg = 0.0f, correctedFrameTimeAvg = 0.0f; SDL_Event event; int drawingTimer = 0; int frameStart = 0; while(engine->Running()) { int oldFrameStart = frameStart; frameStart = SDL_GetTicks(); drawingTimer += frameStart - oldFrameStart; if(engine->Broken()) { engine->UnBreak(); break; } event.type = 0; while (SDL_PollEvent(&event)) { EventProcess(event); event.type = 0; //Clear last event } if(engine->Broken()) { engine->UnBreak(); break; } engine->Tick(); int drawcap = ui::Engine::Ref().GetDrawingFrequencyLimit(); if (!drawcap || drawingTimer > 1000.f/drawcap) { engine->Draw(); drawingTimer = 0; if (scale != engine->Scale || fullscreen != engine->Fullscreen || altFullscreen != engine->GetAltFullscreen() || forceIntegerScaling != engine->GetForceIntegerScaling() || resizable != engine->GetResizable()) { SDLSetScreen(engine->Scale, engine->GetResizable(), engine->Fullscreen, engine->GetAltFullscreen(), engine->GetForceIntegerScaling()); } #ifdef OGLI blit(); #else blit(engine->g->vid); #endif } int frameTime = SDL_GetTicks() - frameStart; frameTimeAvg = frameTimeAvg * 0.8 + frameTime * 0.2; float fpsLimit = ui::Engine::Ref().FpsLimit; if(fpsLimit > 2) { double offset = 1000.0 / fpsLimit - frameTimeAvg; if(offset > 0) SDL_Delay(Uint32(offset + 0.5)); } int correctedFrameTime = SDL_GetTicks() - frameStart; correctedFrameTimeAvg = correctedFrameTimeAvg * 0.95 + correctedFrameTime * 0.05; if (frameStart - lastFpsUpdate > 200) { engine->SetFps(1000.0 / correctedFrameTimeAvg); lastFpsUpdate = frameStart; } if (frameStart - lastTick > 100) { lastTick = frameStart; Client::Ref().Tick(); } if (showLargeScreenDialog) { showLargeScreenDialog = false; LargeScreenDialog(); } } #ifdef DEBUG std::cout << "Breaking out of EngineProcess" << std::endl; #endif } void BlueScreen(String detailMessage) { ui::Engine * engine = &ui::Engine::Ref(); engine->g->fillrect(0, 0, engine->GetWidth(), engine->GetHeight(), 17, 114, 169, 210); String errorTitle = "ERROR"; String errorDetails = "Details: " + detailMessage; String errorHelp = "An unrecoverable fault has occurred, please report the error by visiting the website below\n" SCHEME SERVER; int currentY = 0, width, height; int errorWidth = 0; Graphics::textsize(errorHelp, errorWidth, height); engine->g->drawtext((engine->GetWidth()/2)-(errorWidth/2), ((engine->GetHeight()/2)-100) + currentY, errorTitle.c_str(), 255, 255, 255, 255); Graphics::textsize(errorTitle, width, height); currentY += height + 4; engine->g->drawtext((engine->GetWidth()/2)-(errorWidth/2), ((engine->GetHeight()/2)-100) + currentY, errorDetails.c_str(), 255, 255, 255, 255); Graphics::textsize(errorTitle, width, height); currentY += height + 4; engine->g->drawtext((engine->GetWidth()/2)-(errorWidth/2), ((engine->GetHeight()/2)-100) + currentY, errorHelp.c_str(), 255, 255, 255, 255); Graphics::textsize(errorTitle, width, height); currentY += height + 4; //Death loop SDL_Event event; while(true) { while (SDL_PollEvent(&event)) if(event.type == SDL_QUIT) exit(-1); #ifdef OGLI blit(); #else blit(engine->g->vid); #endif } } void SigHandler(int signal) { switch(signal){ case SIGSEGV: BlueScreen("Memory read/write error"); break; case SIGFPE: BlueScreen("Floating point exception"); break; case SIGILL: BlueScreen("Program execution exception"); break; case SIGABRT: BlueScreen("Unexpected program abort"); break; } } constexpr int SCALE_MAXIMUM = 10; constexpr int SCALE_MARGIN = 30; int GuessBestScale() { const int widthNoMargin = desktopWidth - SCALE_MARGIN; const int widthGuess = widthNoMargin / WINDOWW; const int heightNoMargin = desktopHeight - SCALE_MARGIN; const int heightGuess = heightNoMargin / WINDOWH; int guess = std::min(widthGuess, heightGuess); if(guess < 1 || guess > SCALE_MAXIMUM) guess = 1; return guess; } #ifdef main # undef main // thank you sdl #endif int main(int argc, char * argv[]) { #if defined(_DEBUG) && defined(_MSC_VER) _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG); #endif currentWidth = WINDOWW; currentHeight = WINDOWH; // https://bugzilla.libsdl.org/show_bug.cgi?id=3796 if (SDL_Init(0) < 0) { fprintf(stderr, "Initializing SDL: %s\n", SDL_GetError()); return 1; } std::map<ByteString, ByteString> arguments = readArguments(argc, argv); if(arguments["ddir"].length()) { #ifdef WIN int failure = _chdir(arguments["ddir"].c_str()); #else int failure = chdir(arguments["ddir"].c_str()); #endif if (failure) { perror("failed to chdir to requested ddir"); } } else { #ifdef WIN struct _stat s; if(_stat("powder.pref", &s) != 0) #else struct stat s; if(stat("powder.pref", &s) != 0) #endif { char *ddir = SDL_GetPrefPath(NULL, "The Powder Toy"); if(ddir) { #ifdef WIN int failure = _chdir(ddir); #else int failure = chdir(ddir); #endif if (failure) { perror("failed to chdir to default ddir"); } SDL_free(ddir); } } } scale = Client::Ref().GetPrefInteger("Scale", 1); resizable = Client::Ref().GetPrefBool("Resizable", false); fullscreen = Client::Ref().GetPrefBool("Fullscreen", false); altFullscreen = Client::Ref().GetPrefBool("AltFullscreen", false); forceIntegerScaling = Client::Ref().GetPrefBool("ForceIntegerScaling", true); momentumScroll = Client::Ref().GetPrefBool("MomentumScroll", true); showAvatars = Client::Ref().GetPrefBool("ShowAvatars", true); if(arguments["kiosk"] == "true") { fullscreen = true; Client::Ref().SetPref("Fullscreen", fullscreen); } if(arguments["redirect"] == "true") { FILE *new_stdout = freopen("stdout.log", "w", stdout); FILE *new_stderr = freopen("stderr.log", "w", stderr); if (!new_stdout || !new_stderr) { exit(42); } } if(arguments["scale"].length()) { scale = arguments["scale"].ToNumber<int>(); Client::Ref().SetPref("Scale", scale); } ByteString proxyString = ""; if(arguments["proxy"].length()) { if(arguments["proxy"] == "false") { proxyString = ""; Client::Ref().SetPref("Proxy", ""); } else { proxyString = (arguments["proxy"]); Client::Ref().SetPref("Proxy", arguments["proxy"]); } } else { auto proxyPref = Client::Ref().GetPrefByteString("Proxy", ""); if (proxyPref.length()) { proxyString = proxyPref; } } bool disableNetwork = false; if (arguments.find("disable-network") != arguments.end()) disableNetwork = true; Client::Ref().Initialise(proxyString, disableNetwork); // TODO: maybe bind the maximum allowed scale to screen size somehow if(scale < 1 || scale > SCALE_MAXIMUM) scale = 1; SDLOpen(); if (Client::Ref().IsFirstRun()) { scale = GuessBestScale(); if (scale > 1) { Client::Ref().SetPref("Scale", scale); SDL_SetWindowSize(sdl_window, WINDOWW * scale, WINDOWH * scale); showLargeScreenDialog = true; } } #ifdef OGLI SDL_GL_SetAttribute (SDL_GL_DOUBLEBUFFER, 1); //glScaled(2.0f, 2.0f, 1.0f); #endif #if defined(OGLI) && !defined(MACOSX) int status = glewInit(); if(status != GLEW_OK) { fprintf(stderr, "Initializing Glew: %d\n", status); exit(-1); } #endif ui::Engine::Ref().g = new Graphics(); ui::Engine::Ref().Scale = scale; ui::Engine::Ref().SetResizable(resizable); ui::Engine::Ref().Fullscreen = fullscreen; ui::Engine::Ref().SetAltFullscreen(altFullscreen); ui::Engine::Ref().SetForceIntegerScaling(forceIntegerScaling); ui::Engine::Ref().MomentumScroll = momentumScroll; ui::Engine::Ref().ShowAvatars = showAvatars; engine = &ui::Engine::Ref(); engine->SetMaxSize(desktopWidth, desktopHeight); engine->Begin(WINDOWW, WINDOWH); engine->SetFastQuit(Client::Ref().GetPrefBool("FastQuit", true)); #if !defined(DEBUG) && !defined(_DEBUG) //Get ready to catch any dodgy errors signal(SIGSEGV, SigHandler); signal(SIGFPE, SigHandler); signal(SIGILL, SigHandler); signal(SIGABRT, SigHandler); #endif #ifdef X86_SSE _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); #endif #ifdef X86_SSE3 _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); #endif GameController * gameController = NULL; #if !defined(DEBUG) && !defined(_DEBUG) try { #endif gameController = new GameController(); engine->ShowWindow(gameController->GetView()); if(arguments["open"].length()) { #ifdef DEBUG std::cout << "Loading " << arguments["open"] << std::endl; #endif if(Client::Ref().FileExists(arguments["open"])) { try { std::vector<unsigned char> gameSaveData = Client::Ref().ReadFile(arguments["open"]); if(!gameSaveData.size()) { new ErrorMessage("Error", "Could not read file"); } else { SaveFile * newFile = new SaveFile(arguments["open"]); GameSave * newSave = new GameSave(gameSaveData); newFile->SetGameSave(newSave); gameController->LoadSaveFile(newFile); delete newFile; } } catch(std::exception & e) { new ErrorMessage("Error", "Could not open save file:\n" + ByteString(e.what()).FromUtf8()) ; } } else { new ErrorMessage("Error", "Could not open file"); } } if(arguments["ptsave"].length()) { engine->g->fillrect((engine->GetWidth()/2)-101, (engine->GetHeight()/2)-26, 202, 52, 0, 0, 0, 210); engine->g->drawrect((engine->GetWidth()/2)-100, (engine->GetHeight()/2)-25, 200, 50, 255, 255, 255, 180); engine->g->drawtext((engine->GetWidth()/2)-(Graphics::textwidth("Loading save...")/2), (engine->GetHeight()/2)-5, "Loading save...", style::Colour::InformationTitle.Red, style::Colour::InformationTitle.Green, style::Colour::InformationTitle.Blue, 255); #ifdef OGLI blit(); #else blit(engine->g->vid); #endif ByteString ptsaveArg = arguments["ptsave"]; try { ByteString saveIdPart; if (ByteString::Split split = arguments["ptsave"].SplitBy(':')) { if (split.Before() != "ptsave") throw std::runtime_error("Not a ptsave link"); saveIdPart = split.After().SplitBy('#').Before(); } else throw std::runtime_error("Invalid save link"); if (!saveIdPart.size()) throw std::runtime_error("No Save ID"); #ifdef DEBUG std::cout << "Got Ptsave: id: " << saveIdPart << std::endl; #endif int saveId = saveIdPart.ToNumber<int>(); SaveInfo * newSave = Client::Ref().GetSave(saveId, 0); if (!newSave) throw std::runtime_error("Could not load save info"); std::vector<unsigned char> saveData = Client::Ref().GetSaveData(saveId, 0); if (!saveData.size()) throw std::runtime_error(("Could not load save\n" + Client::Ref().GetLastError()).ToUtf8()); GameSave * newGameSave = new GameSave(saveData); newSave->SetGameSave(newGameSave); gameController->LoadSave(newSave); delete newSave; } catch (std::exception & e) { new ErrorMessage("Error", ByteString(e.what()).FromUtf8()); } } EngineProcess(); SaveWindowPosition(); #if !defined(DEBUG) && !defined(_DEBUG) } catch(std::exception& e) { BlueScreen(ByteString(e.what()).FromUtf8()); } #endif ui::Engine::Ref().CloseWindow(); delete gameController; delete ui::Engine::Ref().g; Client::Ref().Shutdown(); if (SDL_GetWindowFlags(sdl_window) & SDL_WINDOW_OPENGL) { // * nvidia-460 egl registers callbacks with x11 that end up being called // after egl is unloaded unless we grab it here and release it after // sdl closes the display. this is an nvidia driver weirdness but // technically an sdl bug. glfw has this fixed: // https://github.com/glfw/glfw/commit/9e6c0c747be838d1f3dc38c2924a47a42416c081 SDL_GL_LoadLibrary(NULL); SDL_QuitSubSystem(SDL_INIT_VIDEO); SDL_GL_UnloadLibrary(); } SDL_Quit(); return 0; }
26.226563
255
0.687183
AllSafeCyberSecur1ty
9abde0e1a533551f721424fa5fc2b5863565cf40
3,076
hpp
C++
include/imshowExtension.hpp
norishigefukushima/OpenCP
63090131ec975e834f85b04e84ec29b2893845b2
[ "BSD-3-Clause" ]
137
2015-03-27T07:11:19.000Z
2022-03-30T05:58:22.000Z
include/imshowExtension.hpp
Pandinosaurus/OpenCP
a5234ed531c610d7944fa14d42f7320442ea34a1
[ "BSD-3-Clause" ]
2
2016-05-18T06:33:16.000Z
2016-07-11T17:39:17.000Z
include/imshowExtension.hpp
Pandinosaurus/OpenCP
a5234ed531c610d7944fa14d42f7320442ea34a1
[ "BSD-3-Clause" ]
43
2015-02-20T15:34:25.000Z
2022-01-27T14:59:37.000Z
#pragma once #include "common.hpp" #include "plot.hpp" namespace cp { //normalize image and then cast to 8U and imshow. NORM_INF(32) scale 0-max CP_EXPORT void imshowNormalize(std::string wname, cv::InputArray src, const int norm_type = cv::NORM_MINMAX); //scaling ax+b, cast to 8U, and then imshow CP_EXPORT void imshowScale(std::string name, cv::InputArray src, const double alpha = 1.0, const double beta = 0.0); //scaling a|x|+b, cast to 8U, and then imshow CP_EXPORT void imshowScaleAbs(std::string name, cv::InputArray src, const double alpha = 1.0, const double beta = 0.0); //resize image, cast 8U (optional), and then imshow CP_EXPORT void imshowResize(std::string name, cv::InputArray src, const cv::Size dsize, const double fx = 0.0, const double fy = 0.0, const int interpolation = cv::INTER_NEAREST, bool isCast8U = true); //3 times count down CP_EXPORT void imshowCountDown(std::string wname, cv::InputArray src, const int waitTime = 1000, cv::Scalar color = cv::Scalar::all(0), const int pointSize = 128, std::string fontName = "Consolas"); class CP_EXPORT StackImage { std::vector<cv::Mat> stack; std::string wname; int num_stack = 0; int stack_max = 0; public: StackImage(std::string window_name="image stack"); void setWindowName(std::string window_name); void overwrite(cv::Mat& src); void push(cv::Mat& src); void show(); void show(cv::Mat& src); }; enum DRAW_SIGNAL_CHANNEL { B, G, R, Y }; CP_EXPORT void drawSignalX(cv::Mat& src1, cv::Mat& src2, DRAW_SIGNAL_CHANNEL color, cv::Mat& dest, cv::Size outputImageSize, int line_height, int shiftx, int shiftvalue, int rangex, int rangevalue, int linetype = cp::Plot::LINEAR);// color 0:B, 1:G, 2:R, 3:Y CP_EXPORT void drawSignalX(cv::InputArrayOfArrays src, DRAW_SIGNAL_CHANNEL color, cv::Mat& dest, cv::Size outputImageSize, int analysisLineHeight, int shiftx, int shiftvalue, int rangex, int rangevalue, int linetype = cp::Plot::LINEAR);// color 0:B, 1:G, 2:R, 3:Y CP_EXPORT void drawSignalY(cv::Mat& src1, cv::Mat& src2, DRAW_SIGNAL_CHANNEL color, cv::Mat& dest, cv::Size size, int line_height, int shiftx, int shiftvalue, int rangex, int rangevalue, int linetype = cp::Plot::LINEAR);// color 0:B, 1:G, 2:R, 3:Y CP_EXPORT void drawSignalY(cv::Mat& src, DRAW_SIGNAL_CHANNEL color, cv::Mat& dest, cv::Size size, int line_height, int shiftx, int shiftvalue, int rangex, int rangevalue, int linetype = cp::Plot::LINEAR);// color 0:B, 1:G, 2:R, 3:Y CP_EXPORT void drawSignalY(std::vector<cv::Mat>& src, DRAW_SIGNAL_CHANNEL color, cv::Mat& dest, cv::Size size, int line_height, int shiftx, int shiftvalue, int rangex, int rangevalue, int linetype = cp::Plot::LINEAR);// color 0:B, 1:G, 2:R, 3:Y CP_EXPORT void guiAnalysisImage(cv::InputArray src); CP_EXPORT void guiAnalysisCompare(cv::Mat& src1, cv::Mat& src2); CP_EXPORT void imshowAnalysis(std::string winname, cv::Mat& src); CP_EXPORT void imshowAnalysis(std::string winname, std::vector<cv::Mat>& s); CP_EXPORT void imshowAnalysisCompare(std::string winname, cv::Mat& src1, cv::Mat& src2); }
53.964912
264
0.723992
norishigefukushima
9ac2befbec92d17e178d0f4b36cde20082d4b268
22,941
cpp
C++
src/game/server/tf/lfe_population_manager.cpp
bluedogz162/tf_coop_extended_custom
0212744ebef4f74c4e0047320d9da7d8571a8ee0
[ "Unlicense" ]
4
2020-04-24T22:20:34.000Z
2022-01-10T23:16:53.000Z
src/game/server/tf/lfe_population_manager.cpp
bluedogz162/tf_coop_extended_custom
0212744ebef4f74c4e0047320d9da7d8571a8ee0
[ "Unlicense" ]
1
2020-05-01T19:13:25.000Z
2020-05-02T07:01:45.000Z
src/game/server/tf/lfe_population_manager.cpp
bluedogz162/tf_coop_extended_custom
0212744ebef4f74c4e0047320d9da7d8571a8ee0
[ "Unlicense" ]
3
2020-04-24T22:20:36.000Z
2022-02-21T21:48:05.000Z
//============== Copyright LFE-TEAM Not All rights reserved. =================// // // Purpose: The system for handling npc population in horde. // //=============================================================================// #include "cbase.h" #include "lfe_population_manager.h" #include "lfe_populator.h" #include "igamesystem.h" #include "in_buttons.h" #include "engine/IEngineSound.h" #include "soundenvelope.h" #include "utldict.h" #include "ai_basenpc.h" #include "tf_gamerules.h" #include "nav_mesh/tf_nav_mesh.h" #include "nav_mesh/tf_nav_area.h" #include "tf_team.h" #include "ai_navigator.h" #include "ai_network.h" #include "ai_node.h" #include "eventqueue.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" ConVar lfe_horde_debug( "lfe_horde_debug", "0", FCVAR_REPLICATED, "Display debug in horde mode." ); void CC_Horde_ForceStart( void ) { if ( TFGameRules() ) TFGameRules()->State_Transition( GR_STATE_RND_RUNNING ); if ( LFPopulationManager() ) LFPopulationManager()->StartCurrentWave(); } static ConCommand lfe_horde_force_start("lfe_horde_force_start", CC_Horde_ForceStart, "Force.", FCVAR_GAMEDLL | FCVAR_CHEAT); CLFPopulationManager *g_LFEPopManager = nullptr; //----------------------------------------------------------------------------- // Horde Mode //----------------------------------------------------------------------------- class CTFLogicHorde : public CPointEntity { public: DECLARE_CLASS( CTFLogicHorde, CPointEntity ); DECLARE_DATADESC(); CTFLogicHorde(); ~CTFLogicHorde(); void Spawn( void ); }; BEGIN_DATADESC( CTFLogicHorde ) END_DATADESC() LINK_ENTITY_TO_CLASS( lfe_logic_horde, CTFLogicHorde ); //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CTFLogicHorde::CTFLogicHorde() { } CTFLogicHorde::~CTFLogicHorde() { if ( LFPopulationManager() ) delete LFPopulationManager(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFLogicHorde::Spawn( void ) { CLFPopulationManager *popmanager = new CLFPopulationManager; if ( popmanager ) g_LFEPopManager = popmanager; BaseClass::Spawn(); } BEGIN_DATADESC( CLFPopulationManager ) END_DATADESC() //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CLFPopulationManager::CLFPopulationManager() { m_bFinale = false; m_pPopFile = NULL; m_bIsPaused = false; m_bIsPaused = false; ListenForGameEvent( "npc_death" ); } CLFPopulationManager::~CLFPopulationManager() { if ( m_pPopFile ) m_pPopFile->deleteThis(); m_Waves.RemoveAll(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CLFPopulationManager::FireGameEvent( IGameEvent *event ) { if ( FStrEq( event->GetName(), "npc_death" ) ) { CAI_BaseNPC *pVictim = dynamic_cast<CAI_BaseNPC *>( UTIL_EntityByIndex( event->GetInt( "victim_index" ) ) ); if ( pVictim ) { FOR_EACH_VEC( m_Waves, i ) { CWave *wave = m_Waves[i]; if ( wave != nullptr ) wave->OnMemberKilled( pVictim ); } } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CLFPopulationManager::GameRulesThink() { FOR_EACH_VEC( m_Waves, i ) { CWave *wave = m_Waves[i]; if ( wave != nullptr ) wave->Update(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CLFPopulationManager::StartCurrentWave( void ) { FOR_EACH_VEC( m_Waves, i ) { CWave *wave = m_Waves[i]; if ( wave != nullptr ) wave->ForceReset(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CLFPopulationManager::Initialize( void ) { m_pPopFile = new KeyValues( "WaveSchedule" ); if ( !m_pPopFile->LoadFromFile( filesystem, GetPopulationFilename(), "MOD" ) ) { ConDColorMsg( Color( 77, 116, 85, 255 ), "[CLFPopulationManager] Could not load popfile '%s'. \n", GetPopulationFilename() ); m_pPopFile->deleteThis(); m_pPopFile = NULL; return; } ConColorMsg( Color( 77, 116, 85, 255 ), "[CLFPopulationManager] Loading data from %s. \n", GetPopulationFilename() ); if ( !Q_strcmp( m_pPopFile->GetName(), "RespawnWaveTime" ) ) { engine->ServerCommand( CFmtStr( "mp_respawnwavetime %f\n", m_pPopFile->GetFloat() ) ); } FOR_EACH_SUBKEY( m_pPopFile, subkey ) { if ( V_stricmp( subkey->GetName(), "Wave" ) == 0 ) { CWave *wave = new CWave( this ); if ( !wave->Parse( subkey ) ) { Warning( "Error reading Wave definition\n" ); return; } m_Waves.AddToTail( wave ); } } } //----------------------------------------------------------------------------- // Purpose: Called when a new round is being initialized //----------------------------------------------------------------------------- void CLFPopulationManager::SetupOnRoundStart( void ) { for ( int i = FIRST_GAME_TEAM; i < MAX_TEAMS; i++ ) { if ( TFGameRules()->IsHordeMode() ) { TFGameRules()->BroadcastSound( i, "music.mvm_class_select" ); } } Initialize(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CLFPopulationManager::SetupTimerExpired( void ) { StartCurrentWave(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- const char *CLFPopulationManager::GetPopulationFilename( void ) { const char szFullName = NULL; Q_snprintf( szFullName,sizeof(szFullName), "scripts/population/%s.pop", STRING( gpGlobals->mapname ) ); return szFullName; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- CSpawnLocation::CSpawnLocation() { m_iWhere = Where::TEAMSPAWN; } bool CSpawnLocation::Parse( KeyValues *kv ) { return true; } SpawnResult CSpawnLocation::FindSpawnLocation( Vector& vec ) const { return SPAWN_NORMAL; } CTFNavArea *CSpawnLocation::SelectSpawnArea() const { return NULL; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- IPopulator::IPopulator( CLFPopulationManager *popmgr ) : m_PopMgr( popmgr ) { } IPopulator::~IPopulator() { if ( m_Spawner != nullptr ) delete m_Spawner; } void IPopulator::PostInitialize() { } void IPopulator::Update() { } void IPopulator::UnpauseSpawning() { } void IPopulator::OnMemberKilled( CBaseEntity *pMember ) { } /*bool IPopulator::HasEventChangeAttributes(const char *name) const { if (this->m_Spawner == nullptr) { return false; } return this->m_Spawner->HasEventChangeAttributes(name); }*/ //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- CWave::CWave( CLFPopulationManager *popmgr ) : IPopulator( popmgr ) { m_iTotalCurrency = 0; } CWave::~CWave() { } bool CWave::Parse( KeyValues *kv ) { FOR_EACH_SUBKEY( kv, subkey ) { if ( V_stricmp(subkey->GetName(), "WaveSpawn") == 0) { CWaveSpawnPopulator *wavespawn = new CWaveSpawnPopulator( m_PopMgr ); if ( wavespawn ) { if ( !wavespawn->Parse( subkey ) ) { Warning("Error reading WaveSpawn definition\n"); return false; } m_WaveSpawns.AddToTail( wavespawn ); m_iTotalCurrency += wavespawn->m_iTotalCurrency; wavespawn->m_Wave = this; } } else if ( V_stricmp(subkey->GetName(), "Sound" ) == 0) { m_strSound.sprintf("%s", subkey->GetString()); } else if ( V_stricmp( subkey->GetName(), "Description" ) == 0 ) { m_strDescription.sprintf( "%s", subkey->GetString() ); } else if ( V_stricmp( subkey->GetName(), "WaitWhenDone" ) == 0 ) { m_flWaitWhenDone = subkey->GetFloat(); } else if ( V_stricmp( subkey->GetName(), "Checkpoint" ) == 0 ) { /* doesn't do anything! */ } else if ( V_stricmp( subkey->GetName(), "StartWaveOutput" ) == 0 ) { m_StartWaveOutput = ParseEvent( subkey ); } else if ( V_stricmp(subkey->GetName(), "DoneOutput" ) == 0 ) { m_DoneOutput = ParseEvent( subkey ); } else if ( V_stricmp( subkey->GetName(), "InitWaveOutput" ) == 0 ) { m_InitWaveOutput = ParseEvent( subkey ); } else { Warning( "[CWave] Unknown attribute '%s' in Wave definition.\n", subkey->GetName() ); } } return true; } void CWave::Update() { if ( TFGameRules() == nullptr ) return; gamerules_roundstate_t roundstate = TFGameRules()->State_Get(); if ( roundstate == GR_STATE_RND_RUNNING ) { ActiveWaveUpdate(); } else if ( roundstate == GR_STATE_TEAM_WIN || roundstate == GR_STATE_BETWEEN_RNDS ) { WaveIntermissionUpdate(); } } void CWave::OnMemberKilled( CBaseEntity *pMember ) { FOR_EACH_VEC( m_WaveSpawns, i ) { m_WaveSpawns[i]->OnMemberKilled( pMember ); } } /*bool CWave::HasEventChangeAttributes(const char *name) const { FOR_EACH_VEC( m_WaveSpawns, i ) { if ( m_WaveSpawns[i]->HasEventChangeAttributes(name) ) { return true; } } return false; }*/ bool CWave::IsDoneWithNonSupportWaves() { FOR_EACH_VEC( m_WaveSpawns, i ) { CWaveSpawnPopulator *wavespawn = m_WaveSpawns[i]; if ( wavespawn != nullptr && !wavespawn->m_bSupport && wavespawn->m_iState != CWaveSpawnPopulator::InternalStateType::DONE ) return false; } return true; } void CWave::ForceFinish() { FOR_EACH_VEC( m_WaveSpawns, i ) { m_WaveSpawns[i]->ForceFinish(); } } void CWave::ForceReset() { FOR_EACH_VEC( m_WaveSpawns, i ) { CWaveSpawnPopulator *wavespawn = m_WaveSpawns[i]; if ( wavespawn != nullptr ) { wavespawn->m_iState = CWaveSpawnPopulator::InternalStateType::INITIAL; wavespawn->m_iCurrencyLeft = wavespawn->m_iTotalCurrency; wavespawn->m_iCountNotYetSpawned = wavespawn->m_iTotalCount; } } } CWaveSpawnPopulator *CWave::FindWaveSpawnPopulator( const char *name ) { FOR_EACH_VEC( m_WaveSpawns, i ) { CWaveSpawnPopulator *wavespawn = m_WaveSpawns[i]; if ( wavespawn != nullptr ) { if ( V_stricmp( wavespawn->m_strName.Get(), name ) == 0 ) { return wavespawn; } } } return nullptr; } void CWave::ActiveWaveUpdate() { FOR_EACH_VEC( m_WaveSpawns, i ) { CWaveSpawnPopulator *wavespawn = m_WaveSpawns[i]; if ( wavespawn != nullptr ) wavespawn->Update(); } } void CWave::WaveCompleteUpdate() { } void CWave::WaveIntermissionUpdate() { } CWaveSpawnPopulator::CWaveSpawnPopulator( CLFPopulationManager *popmgr ) : IPopulator( popmgr ) { m_iTotalCurrency = 0; } CWaveSpawnPopulator::~CWaveSpawnPopulator() { } bool CWaveSpawnPopulator::Parse( KeyValues *kv ) { /*KeyValues *kv_tref = kv->FindKey( "Template" ); if (k v_tref != nullptr ) { const char *tname = kv_tref->GetString(); KeyValues *kv_timpl = m_PopMgr->m_kvTemplates->FindKey( tname ); if ( kv_timpl != nullptr ) { if ( !Parse( kv_timpl ) ) return false; } else { Warning( "Unknown Template '%s' in WaveSpawn definition\n", tname ); } }*/ FOR_EACH_SUBKEY( kv, subkey ) { const char *name = subkey->GetName(); if ( strlen(name) <= 0 ) continue; if ( m_Where.Parse( subkey ) ) continue; /*if ( V_stricmp(name, "Template" ) == 0 ) continue;*/ if ( V_stricmp( name, "TotalCount" ) == 0 ) { m_iTotalCount = subkey->GetInt(); } else if ( V_stricmp( name, "MaxActive" ) == 0 ) { m_iMaxActive = subkey->GetInt(); } else if ( V_stricmp( name, "SpawnCount" ) == 0 ) { m_iSpawnCount = subkey->GetInt(); } else if ( V_stricmp( name, "WaitBeforeStarting" ) == 0 ) { m_flWaitBeforeStarting = subkey->GetFloat(); } else if ( V_stricmp( name, "WaitBetweenSpawns" ) == 0 ) { if ( m_flWaitBetweenSpawns == 0.0f || !m_bWaitBetweenSpawnsAfterDeath ) { m_flWaitBetweenSpawns = subkey->GetFloat(); } else { Warning("Already specified WaitBetweenSpawnsAfterDeath time, ""WaitBetweenSpawns won't be used\n"); continue; } } else if ( V_stricmp( name, "WaitBetweenSpawnsAfterDeath" ) == 0 ) { if ( m_flWaitBetweenSpawns == 0.0f ) { m_bWaitBetweenSpawnsAfterDeath = true; m_flWaitBetweenSpawns = subkey->GetFloat(); } else { Warning( "Already specified WaitBetweenSpawns time, ""WaitBetweenSpawnsAfterDeath won't be used\n" ); continue; } } else if ( V_stricmp( name, "StartWaveWarningSound" ) == 0 ) { m_strStartWaveWarningSound.sprintf( "%s",subkey->GetString() ); } else if ( V_stricmp( name, "StartWaveOutput" ) == 0 ) { m_StartWaveOutput = ParseEvent( subkey ); } else if (V_stricmp( name, "FirstSpawnWarningSound" ) == 0 ) { m_strFirstSpawnWarningSound.sprintf( "%s", subkey->GetString() ); } else if ( V_stricmp( name, "FirstSpawnOutput" ) == 0 ) { m_FirstSpawnOutput = ParseEvent(subkey); } else if ( V_stricmp( name, "LastSpawnWarningSound" ) == 0 ) { m_strLastSpawnWarningSound.sprintf( "%s", subkey->GetString() ); } else if ( V_stricmp( name, "LastSpawnOutput") == 0 ) { m_LastSpawnOutput = ParseEvent( subkey ); } else if ( V_stricmp( name, "DoneWarningSound" ) == 0 ) { m_strDoneWarningSound.sprintf( "%s",subkey->GetString() ); } else if ( V_stricmp( name, "DoneOutput" ) == 0 ) { m_DoneOutput = ParseEvent( subkey ); } else if ( V_stricmp( name, "TotalCurrency" ) == 0 ) { m_iTotalCurrency = subkey->GetInt(); } else if ( V_stricmp( name, "Name" ) == 0 ) { m_strName = subkey->GetString(); } else if ( V_stricmp( name, "WaitForAllSpawned" ) == 0 ) { m_strWaitForAllSpawned = subkey->GetString(); } else if ( V_stricmp( name, "WaitForAllDead" ) == 0 ) { m_strWaitForAllDead = subkey->GetString(); } else if ( V_stricmp( name, "Support" ) == 0 ) { m_bSupport = true; m_bSupportLimited = ( V_stricmp(subkey->GetString(), "Limited" ) == 0 ); } else if ( V_stricmp( name, "RandomSpawn" ) == 0 ) { m_bRandomSpawn = subkey->GetBool(); } else { m_Spawner = IPopulationSpawner::ParseSpawner( this, subkey ); if ( m_Spawner == nullptr) { Warning( "Unknown attribute '%s' in WaveSpawn definition.\n", name ); } } m_iCountNotYetSpawned = m_iTotalCount; m_iCurrencyLeft = m_iTotalCurrency; } return true; } void CWaveSpawnPopulator::Update() { switch ( m_iState ) { case InternalStateType::INITIAL: m_ctSpawnDelay.Start( m_flWaitBeforeStarting ); SetState( InternalStateType::PRE_SPAWN_DELAY ); break; case InternalStateType::PRE_SPAWN_DELAY: if ( m_ctSpawnDelay.IsElapsed() ) { m_iCountSpawned = 0; m_iCountToSpawn = 0; SetState( InternalStateType::SPAWNING ); } break; case InternalStateType::SPAWNING: { if ( !m_ctSpawnDelay.IsElapsed() || g_LFEPopManager->m_bIsPaused ) break; if ( m_Spawner == nullptr ) { Warning( "Invalid spawner\n" ); SetState( InternalStateType::DONE ); break; } int num_active = 0; FOR_EACH_VEC( m_ActiveBots, i ) { CBaseEntity *ent = m_ActiveBots[i]; if ( ent != nullptr && ent->IsAlive() ) { ++num_active; } } if ( m_bWaitBetweenSpawnsAfterDeath ) { if ( num_active != 0) break; if ( m_iSpawnResult != SPAWN_FAIL ) { m_iSpawnResult = SPAWN_FAIL; float wait_between_spawns = m_flWaitBetweenSpawns; if ( wait_between_spawns != 0.0f ) m_ctSpawnDelay.Start( wait_between_spawns ); break; } } int max_active = m_iMaxActive; if ( num_active >= max_active ) break; if ( m_iCountToSpawn <= 0 ) { if ( num_active + m_iSpawnCount > max_active ) break; m_iCountToSpawn = m_iSpawnCount; } Vector vec_spawn = vec3_origin; CBaseEntity *pTeamSpawn = gEntList.FindEntityByClassname( NULL, "info_player_teamspawn" ); if ( pTeamSpawn ) vec_spawn = pTeamSpawn->GetAbsOrigin(); /*if ( m_Spawner->IsWhereRequired() ) { if ( m_iSpawnResult != SPAWN_NORMAL ) { m_iSpawnResult = m_Where.FindSpawnLocation( m_vecSpawn ); if (m_iSpawnResult == SPAWN_FAIL) { break; } } vec_spawn = m_vecSpawn; if ( m_bRandomSpawn ) { m_iSpawnResult = SPAWN_FAIL; } }*/ CUtlVector<CHandle<CBaseEntity>> spawned; if ( m_Spawner->Spawn( vec_spawn, &spawned ) == 0 ) { m_ctSpawnDelay.Start( 1.0f ); break; } FOR_EACH_VEC( spawned, i ) { CBaseEntity *ent = spawned[i]; CAI_BaseNPC *bot = dynamic_cast<CAI_BaseNPC*>(ent); if ( bot == nullptr ) continue; //bot->m_nCurrency = 0; } int num_spawned = spawned.Count(); m_iCountSpawned += num_spawned; int count_to_spawn = m_iCountToSpawn; if ( num_spawned > count_to_spawn ) num_spawned = count_to_spawn; m_iCountToSpawn -= num_spawned; FOR_EACH_VEC( spawned, i ) { CBaseEntity *ent1 = spawned[i]; FOR_EACH_VEC( m_ActiveBots, j ) { CBaseEntity *ent2 = m_ActiveBots[j]; if ( ent2 == nullptr ) continue; if ( ent1->entindex() == ent2->entindex() ) { Warning( "WaveSpawn duplicate entry in active vector\n" ); } } m_ActiveBots.AddToTail( ent1 ); } if ( IsFinishedSpawning() ) { SetState( InternalStateType::WAIT_FOR_ALL_DEAD ); } else if ( m_iCountToSpawn <= 0 && !m_bWaitBetweenSpawnsAfterDeath ) { m_iSpawnResult = SPAWN_FAIL; float wait_between_spawns = m_flWaitBetweenSpawns; if ( wait_between_spawns != 0.0f ) m_ctSpawnDelay.Start( wait_between_spawns ); } break; } case InternalStateType::WAIT_FOR_ALL_DEAD: FOR_EACH_VEC( m_ActiveBots, i ) { CBaseEntity *ent = m_ActiveBots[i]; if ( ent != nullptr && ent->IsAlive() ) { break; } } SetState( InternalStateType::DONE ); break; } } void CWaveSpawnPopulator::OnMemberKilled( CBaseEntity *pMember ) { m_ActiveBots.FindAndFastRemove( pMember ); } bool CWaveSpawnPopulator::IsFinishedSpawning() { if ( m_bSupport && !m_bSupportLimited ) return false; return ( m_iCountSpawned >= m_iTotalCount ); } void CWaveSpawnPopulator::OnNonSupportWavesDone() { if ( !m_bSupport ) return; int state = m_iState; if ( state == InternalStateType::INITIAL || state == InternalStateType::PRE_SPAWN_DELAY ) { SetState( InternalStateType::DONE ); } else if ( state == InternalStateType::SPAWNING || state == InternalStateType::WAIT_FOR_ALL_DEAD ) { if ( TFGameRules() != nullptr && m_iCurrencyLeft > 0) { /*TFGameRules()->DistributeCurrencyAmount(m_iCurrencyLeft, nullptr, true, true, false);*/ m_iCurrencyLeft = 0; } SetState( InternalStateType::WAIT_FOR_ALL_DEAD ); } } void CWaveSpawnPopulator::ForceFinish() { int state = m_iState; if ( state == InternalStateType::INITIAL || state == InternalStateType::PRE_SPAWN_DELAY || state == InternalStateType::SPAWNING ) { SetState( InternalStateType::WAIT_FOR_ALL_DEAD ); } else if ( state != InternalStateType::WAIT_FOR_ALL_DEAD ) { SetState( InternalStateType::DONE ); } FOR_EACH_VEC( m_ActiveBots, i ) { CBaseEntity *ent = m_ActiveBots[i]; CAI_BaseNPC *bot = dynamic_cast<CAI_BaseNPC*>(ent); if ( bot != nullptr ) { bot->SetHealth( 0 ); } else { UTIL_Remove( ent ); } } m_ActiveBots.RemoveAll(); } int CWaveSpawnPopulator::GetCurrencyAmountPerDeath() { if ( m_bSupport && m_iState == InternalStateType::WAIT_FOR_ALL_DEAD ) m_iCountNotYetSpawned = m_ActiveBots.Count(); int currency_left = m_iCurrencyLeft; if ( currency_left <= 0 ) return 0; int bots_left = m_iCountNotYetSpawned; if ( bots_left <= 0 ) bots_left = 1; int amount = ( currency_left / bots_left ); --m_iCountNotYetSpawned; m_iCurrencyLeft -= amount; return amount; } void CWaveSpawnPopulator::SetState( CWaveSpawnPopulator::InternalStateType newstate ) { m_iState = newstate; if ( newstate == InternalStateType::PRE_SPAWN_DELAY ) { if ( m_strStartWaveWarningSound.Length() > 0 ) TFGameRules()->BroadcastSound( 255,m_strStartWaveWarningSound.String() ); FireEvent( m_StartWaveOutput, "StartWaveOutput" ); if ( lfe_horde_debug.GetBool() ) DevMsg("%3.2f: WaveSpawn(%s) started PRE_SPAWN_DELAY\n", gpGlobals->curtime, m_strName.Get() ); } else if ( newstate == InternalStateType::SPAWNING ) { if ( m_strFirstSpawnWarningSound.Length() > 0 ) TFGameRules()->BroadcastSound( 255,m_strFirstSpawnWarningSound.String() ); FireEvent( m_FirstSpawnOutput, "FirstSpawnOutput" ); if ( lfe_horde_debug.GetBool() ) DevMsg( "%3.2f: WaveSpawn(%s) started SPAWNING\n", gpGlobals->curtime, m_strName.Get() ); } else if ( newstate == InternalStateType::WAIT_FOR_ALL_DEAD ) { if ( m_strLastSpawnWarningSound.Length() > 0 ) TFGameRules()->BroadcastSound( 255,m_strLastSpawnWarningSound.String() ); FireEvent( m_LastSpawnOutput, "LastSpawnOutput" ); if ( lfe_horde_debug.GetBool() ) DevMsg( "%3.2f: WaveSpawn(%s) started WAIT_FOR_ALL_DEAD\n", gpGlobals->curtime, m_strName.Get() ); } else if ( newstate == InternalStateType::DONE ) { if ( m_strDoneWarningSound.Length() > 0 ) TFGameRules()->BroadcastSound( 255,m_strDoneWarningSound.String() ); FireEvent( m_DoneOutput, "DoneOutput" ); if ( lfe_horde_debug.GetBool() ) DevMsg( "%3.2f: WaveSpawn(%s) DONE\n", gpGlobals->curtime, m_strName.Get() ); } } EventInfo *ParseEvent( KeyValues *kv ) { EventInfo *info = new EventInfo(); FOR_EACH_SUBKEY( kv, subkey ) { const char *name = subkey->GetName(); if ( strlen( name ) <= 0 ) continue; if ( V_stricmp( name, "Target" ) == 0 ) { info->target.sprintf( subkey->GetString() ); } else if ( V_stricmp( name, "Action" ) == 0 ) { info->action.sprintf( subkey->GetString() ); } else { Warning( "Unknown field '%s' in WaveSpawn event definition.\n", subkey->GetString() ); delete info; return nullptr; } } return info; } void FireEvent( EventInfo *info, const char *name ) { if ( info == nullptr ) return; const char *target = info->target.Get(); const char *action = info->action.Get(); CBaseEntity *ent = gEntList.FindEntityByName( nullptr, target ); if ( ent != nullptr ) { g_EventQueue.AddEvent( ent, action, 0.0f, nullptr, nullptr ); } else { Warning( "WaveSpawnPopulator: Can't find target entity '%s' for %s\n", target, name ); } }
23.529231
131
0.604682
bluedogz162
9ac36668ebf224af45f6581f291782de87fa1cf3
907
cpp
C++
ABC/ABC112/D.cpp
rajyan/AtCoder
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
[ "MIT" ]
1
2021-06-01T17:13:44.000Z
2021-06-01T17:13:44.000Z
ABC/ABC112/D.cpp
rajyan/AtCoder
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
[ "MIT" ]
null
null
null
ABC/ABC112/D.cpp
rajyan/AtCoder
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
[ "MIT" ]
null
null
null
//#include <cstdio> //#include <cmath> //#include <iostream> //#include <sstream> //#include <string> //#include <vector> //#include <map> //#include <queue> //#include <algorithm> // //#ifdef _DEBUG //#define DMP(x) cerr << #x << ": " << x << "\n" //#else //#define DMP(x) ((void)0) //#endif // //const int MOD = 1000000007, INF = 1111111111; //using namespace std; //typedef long long lint; // //template<class T> //vector<T> divisor(T n) { // vector<T> ret; // for (T i = 1; i * i <= n; i++) { // if (n % i == 0) { // ret.emplace_back(i); // if (i * i != n) ret.emplace_back(n / i); // } // } // sort(ret.begin(), ret.end(), greater<T>()); // return ret; //} // //int main() { // // int N, M; // cin >> N >> M; // // auto divs = divisor(M); // // int ans; // for (auto& ele : divs) { // if (M / ele >= N) { // ans = ele; // break; // } // } // // cout << ans << "\n"; // // return 0; // //}
16.796296
48
0.500551
rajyan
9ac6322841b57030d1ffefc3981f8aa763fe4557
604
hpp
C++
code/source/nodes/nodeeventreceiverproxy_we.hpp
crafn/clover
586acdbcdb34c3550858af125e9bb4a6300343fe
[ "MIT" ]
12
2015-01-12T00:19:20.000Z
2021-08-05T10:47:20.000Z
code/source/nodes/nodeeventreceiverproxy_we.hpp
crafn/clover
586acdbcdb34c3550858af125e9bb4a6300343fe
[ "MIT" ]
null
null
null
code/source/nodes/nodeeventreceiverproxy_we.hpp
crafn/clover
586acdbcdb34c3550858af125e9bb4a6300343fe
[ "MIT" ]
null
null
null
#ifndef CLOVER_NODES_NODEEVENTRECEIVERPROXY_WE_HPP #define CLOVER_NODES_NODEEVENTRECEIVERPROXY_WE_HPP #include "build.hpp" #include "game/worldentity_handle.hpp" #include "nodeeventreceiverproxy.hpp" namespace clover { namespace nodes { class WeNodeEventReceiverProxy : public NodeEventReceiverProxy { public: WeNodeEventReceiverProxy(const game::WeHandle& h); virtual ~WeNodeEventReceiverProxy(); virtual void onEvent(const NodeEvent&); virtual WeNodeEventReceiverProxy* clone(); private: game::WeHandle handle; }; } // nodes } // clover #endif // CLOVER_NODES_NODEEVENTRECEIVERPROXY_WE_HPP
24.16
64
0.812914
crafn
9ac7237ca05e7e2e4a70b7a4ef8ce99427e70b55
706
hpp
C++
src/examples/countPages/countPagesXercesHandler.hpp
Ace7k3/wiki_xml_dump_xerces
d64cc24042902668380140a7349ca06b73702dfe
[ "MIT" ]
null
null
null
src/examples/countPages/countPagesXercesHandler.hpp
Ace7k3/wiki_xml_dump_xerces
d64cc24042902668380140a7349ca06b73702dfe
[ "MIT" ]
null
null
null
src/examples/countPages/countPagesXercesHandler.hpp
Ace7k3/wiki_xml_dump_xerces
d64cc24042902668380140a7349ca06b73702dfe
[ "MIT" ]
null
null
null
#pragma once #include <stack> #include <vector> #include <functional> #include <xercesc/sax2/DefaultHandler.hpp> #include <xercesc/sax2/Attributes.hpp> class CountPagesXercesHandler : public xercesc::DefaultHandler { public: inline CountPagesXercesHandler() :_count(0) {} inline std::size_t count() const { return _count; } inline void startElement(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname, const xercesc::Attributes& attrs) { char* tmp = xercesc::XMLString::transcode(localname); std::string elementName = tmp; xercesc::XMLString::release(&tmp); if(elementName == "page") _count++; } private: std::size_t _count; };
19.611111
140
0.705382
Ace7k3
9acb80343745b42c4bb07dafb27a2d3583a520e1
1,074
hpp
C++
include/mizuiro/color/format/homogenous_ns/access/channel_max.hpp
cpreh/mizuiro
5ab15bde4e72e3a4978c034b8ff5700352932485
[ "BSL-1.0" ]
1
2015-08-22T04:19:39.000Z
2015-08-22T04:19:39.000Z
include/mizuiro/color/format/homogenous_ns/access/channel_max.hpp
freundlich/mizuiro
5ab15bde4e72e3a4978c034b8ff5700352932485
[ "BSL-1.0" ]
null
null
null
include/mizuiro/color/format/homogenous_ns/access/channel_max.hpp
freundlich/mizuiro
5ab15bde4e72e3a4978c034b8ff5700352932485
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2016. // 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 MIZUIRO_COLOR_FORMAT_HOMOGENOUS_NS_ACCESS_CHANNEL_MAX_HPP_INCLUDED #define MIZUIRO_COLOR_FORMAT_HOMOGENOUS_NS_ACCESS_CHANNEL_MAX_HPP_INCLUDED #include <mizuiro/color/access/channel_max_ns/tag.hpp> #include <mizuiro/color/detail/full_channel_max.hpp> #include <mizuiro/color/format/store_fwd.hpp> #include <mizuiro/color/format/homogenous_ns/tag.hpp> #include <mizuiro/color/types/channel_value.hpp> namespace mizuiro::color::access::channel_max_ns { template <typename Format, typename Channel> mizuiro::color::types::channel_value<Format, Channel> channel_max_adl( mizuiro::color::access::channel_max_ns::tag, mizuiro::color::format::homogenous_ns::tag<Format>, mizuiro::color::format::store<Format> const &, Channel const &) { return mizuiro::color::detail::full_channel_max<typename Format::channel_type>(); } } #endif
34.645161
83
0.773743
cpreh
9ad178998e9d7bddea98bf82d283cfd62859e2c3
434
hpp
C++
libs/audio/include/sge/audio/scalar.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/audio/include/sge/audio/scalar.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/audio/include/sge/audio/scalar.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_AUDIO_SCALAR_HPP_INCLUDED #define SGE_AUDIO_SCALAR_HPP_INCLUDED namespace sge::audio { /// A floating point type that's used almost everywhere (positions, gain, ...) using scalar = float; } #endif
24.111111
78
0.721198
cpreh
9ad52b34ad0783975a3999c5c1685561b0fd81e5
9,656
cpp
C++
src/utils/MRMTransitionGroupPicker.cpp
mrurik/OpenMS
3bf48247423dc28a7df7b12b72fbc7751965c321
[ "Zlib", "Apache-2.0" ]
1
2018-03-06T14:12:09.000Z
2018-03-06T14:12:09.000Z
src/utils/MRMTransitionGroupPicker.cpp
mrurik/OpenMS
3bf48247423dc28a7df7b12b72fbc7751965c321
[ "Zlib", "Apache-2.0" ]
null
null
null
src/utils/MRMTransitionGroupPicker.cpp
mrurik/OpenMS
3bf48247423dc28a7df7b12b72fbc7751965c321
[ "Zlib", "Apache-2.0" ]
null
null
null
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2016. // // This software is released under a three-clause BSD license: // * 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 any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #include <OpenMS/APPLICATIONS/TOPPBase.h> #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/CONCEPT/ProgressLogger.h> #include <OpenMS/KERNEL/MRMTransitionGroup.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h> // files #include <OpenMS/FORMAT/TraMLFile.h> #include <OpenMS/FORMAT/MzMLFile.h> #include <OpenMS/FORMAT/FeatureXMLFile.h> // interfaces #include <OpenMS/ANALYSIS/OPENSWATH/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h> #include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SimpleOpenMSSpectraAccessFactory.h> // helpers #include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SimpleOpenMSSpectraAccessFactory.h> #include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/DataAccessHelper.h> #include <OpenMS/ANALYSIS/OPENSWATH/MRMTransitionGroupPicker.h> using namespace std; using namespace OpenMS; //------------------------------------------------------------- //Doxygen docu //------------------------------------------------------------- /** @page TOPP_MRMTransitionGroupPicker MRMTransitionGroupPicker @brief Picks peaks in MRM chromatograms. */ // We do not want this class to show up in the docu: /// @cond TOPPCLASSES class TOPPMRMTransitionGroupPicker : public TOPPBase { public: TOPPMRMTransitionGroupPicker() : TOPPBase("MRMTransitionGroupPicker", "", false) { } protected: typedef MSSpectrum<ChromatogramPeak> RichPeakChromatogram; // this is the type in which we store the chromatograms for this analysis typedef ReactionMonitoringTransition TransitionType; typedef TargetedExperiment TargetedExpType; typedef MRMTransitionGroup<MSSpectrum <ChromatogramPeak>, TransitionType> MRMTransitionGroupType; // a transition group holds the MSSpectra with the Chromatogram peaks from above void registerOptionsAndFlags_() { registerInputFile_("in", "<file>", "", "Input file"); setValidFormats_("in", ListUtils::create<String>("mzML")); registerInputFile_("tr", "<file>", "", "transition file ('TraML' or 'csv')"); setValidFormats_("tr", ListUtils::create<String>("csv,traML")); registerOutputFile_("out", "<file>", "", "output file"); setValidFormats_("out", ListUtils::create<String>("featureXML")); registerSubsection_("algorithm", "Algorithm parameters section"); } Param getSubsectionDefaults_(const String &) const { return MRMTransitionGroupPicker().getDefaults(); } struct MRMGroupMapper { typedef std::map<String, std::vector< const TransitionType* > > AssayMapT; // chromatogram map std::map<String, int> chromatogram_map; // Map peptide id std::map<String, int> assay_peptide_map; // Group transitions AssayMapT assay_map; /// Create the mapping void doMap(OpenSwath::SpectrumAccessPtr input, TargetedExpType& transition_exp) { for (Size i = 0; i < input->getNrChromatograms(); i++) { chromatogram_map[input->getChromatogramNativeID(i)] = boost::numeric_cast<int>(i); } for (Size i = 0; i < transition_exp.getPeptides().size(); i++) { assay_peptide_map[transition_exp.getPeptides()[i].id] = boost::numeric_cast<int>(i); } for (Size i = 0; i < transition_exp.getTransitions().size(); i++) { assay_map[transition_exp.getTransitions()[i].getPeptideRef()].push_back(&transition_exp.getTransitions()[i]); } } /// Check that all assays have a corresponding chromatogram bool allAssaysHaveChromatograms() { for (AssayMapT::iterator assay_it = assay_map.begin(); assay_it != assay_map.end(); ++assay_it) { for (Size i = 0; i < assay_it->second.size(); i++) { if (chromatogram_map.find(assay_it->second[i]->getNativeID()) == chromatogram_map.end()) { return false; } } } return true; } /// Fill up transition group with paired Transitions and Chromatograms void getTransitionGroup(OpenSwath::SpectrumAccessPtr input, MRMTransitionGroupType& transition_group, String id) { transition_group.setTransitionGroupID(id); // Go through all transitions for (Size i = 0; i < assay_map[id].size(); i++) { const TransitionType* transition = assay_map[id][i]; OpenSwath::ChromatogramPtr cptr = input->getChromatogramById(chromatogram_map[transition->getNativeID()]); MSChromatogram<ChromatogramPeak> chromatogram_old; OpenSwathDataAccessHelper::convertToOpenMSChromatogram(chromatogram_old, cptr); RichPeakChromatogram chromatogram; // copy old to new chromatogram for (MSChromatogram<ChromatogramPeak>::const_iterator it = chromatogram_old.begin(); it != chromatogram_old.end(); ++it) { ChromatogramPeak peak; peak.setMZ(it->getRT()); peak.setIntensity(it->getIntensity()); chromatogram.push_back(peak); } chromatogram.setMetaValue("product_mz", transition->getProductMZ()); chromatogram.setMetaValue("precursor_mz", transition->getPrecursorMZ()); chromatogram.setNativeID(transition->getNativeID()); // Now add the transition and the chromatogram to the group transition_group.addTransition(*transition, transition->getNativeID()); transition_group.addChromatogram(chromatogram, chromatogram.getNativeID()); } } }; void run_(OpenSwath::SpectrumAccessPtr input, FeatureMap & output, TargetedExpType& transition_exp) { MRMTransitionGroupPicker trgroup_picker; Param picker_param = getParam_().copy("algorithm:", true); trgroup_picker.setParameters(picker_param); MRMGroupMapper m; m.doMap(input, transition_exp); if (!m.allAssaysHaveChromatograms() ) { throw Exception::IllegalArgument(__FILE__, __LINE__, __PRETTY_FUNCTION__, "Not all assays could be mapped to chromatograms"); } // Iterating over all the assays for (MRMGroupMapper::AssayMapT::iterator assay_it = m.assay_map.begin(); assay_it != m.assay_map.end(); ++assay_it) { String id = assay_it->first; // Create new transition group if there is none for this peptide MRMTransitionGroupType transition_group; m.getTransitionGroup(input, transition_group, id); // Process the transition_group trgroup_picker.pickTransitionGroup(transition_group); // Add to output for (Size i = 0; i < transition_group.getFeatures().size(); i++) { output.push_back(transition_group.getFeatures()[i]); } } } ExitCodes main_(int, const char **) { String in = getStringOption_("in"); String out = getStringOption_("out"); String tr_file = getStringOption_("tr"); boost::shared_ptr<MSExperiment<> > exp ( new MSExperiment<> ); MzMLFile mzmlfile; mzmlfile.setLogType(log_type_); mzmlfile.load(in, *exp); TargetedExpType transition_exp; TraMLFile().load(tr_file, transition_exp); FeatureMap output; OpenSwath::SpectrumAccessPtr input = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp); run_(input, output, transition_exp); output.ensureUniqueId(); output.setPrimaryMSRunPath(exp->getPrimaryMSRunPath()); FeatureXMLFile().store(out, output); return EXECUTION_OK; } }; int main(int argc, const char ** argv) { TOPPMRMTransitionGroupPicker tool; return tool.main(argc, argv); } /// @endcond
36.996169
180
0.669635
mrurik
9ad530e8c61cd3c1e30ce8873c247cec6018247f
224
cpp
C++
Simple++/Math/BasicComparable.cpp
Oriode/Simpleplusplus
2ba44eeab5078d6dab66bdefdf73617696b8cb2e
[ "Apache-2.0" ]
null
null
null
Simple++/Math/BasicComparable.cpp
Oriode/Simpleplusplus
2ba44eeab5078d6dab66bdefdf73617696b8cb2e
[ "Apache-2.0" ]
null
null
null
Simple++/Math/BasicComparable.cpp
Oriode/Simpleplusplus
2ba44eeab5078d6dab66bdefdf73617696b8cb2e
[ "Apache-2.0" ]
null
null
null
#include "BasicComparable.h" namespace Math { namespace Compare { Math::Compare::Value BasicComparable::compare( const BasicComparable & x, const BasicComparable & y ) { return Math::Compare::Value::Equal; } } }
18.666667
105
0.709821
Oriode
9ad5afe335bc55d7b951a5583a233c23e0705871
1,918
hpp
C++
source/Dream/Core/Dictionary.hpp
kurocha/dream
b2c7d94903e1e8c6bfb043d3b62234508687f435
[ "MIT", "Unlicense" ]
1
2017-04-30T18:59:26.000Z
2017-04-30T18:59:26.000Z
source/Dream/Core/Dictionary.hpp
kurocha/dream
b2c7d94903e1e8c6bfb043d3b62234508687f435
[ "MIT", "Unlicense" ]
null
null
null
source/Dream/Core/Dictionary.hpp
kurocha/dream
b2c7d94903e1e8c6bfb043d3b62234508687f435
[ "MIT", "Unlicense" ]
null
null
null
// // Core/Dictionary.h // This file is part of the "Dream" project, and is released under the MIT license. // // Created by Samuel Williams on 22/12/08. // Copyright (c) 2008 Samuel Williams. All rights reserved. // // #ifndef _DREAM_CORE_DICTIONARY_H #define _DREAM_CORE_DICTIONARY_H #include "../Class.hpp" #include "Value.hpp" #include "Data.hpp" #include <map> namespace Dream { namespace Core { class Dictionary : public Object { public: typedef std::string KeyT; protected: typedef std::map<KeyT, Value> ValuesT; ValuesT _values; public: /// Returns whether the key has a value in the dictionary. bool key (const KeyT & key); void set_value (const KeyT & key, const Value & value); const Value get_value (const KeyT & key) const; template <typename t> void set (const KeyT & key, const t & value) { set_value(key, Value(value)); } template <typename ValueT> const ValueT get (const KeyT & key) { Value v = get_value(key); return v.extract<ValueT>(); } template <typename ValueT> bool get (const KeyT & key, ValueT & value) { Value v = get_value(key); if (v.defined()) { value = v.extract<ValueT>(); return true; } else { return false; } } /// Updates a value if the key exists in the dictionary. template <typename t> bool update (const KeyT & key, t & value) const { ValuesT::const_iterator i = _values.find(key); if (i != _values.end()) { value = i->second.extract<t>(); return true; } return false; } // Overwrites values present in the other dictionary. void update (const Ptr<Dictionary> other); // Only inserts key-values that don't already exist. void insert (const Ptr<Dictionary> other); Ref<IData> serialize() const; void deserialize(Ref<IData> data); void debug (std::ostream &) const; }; } } #endif
20.189474
84
0.642336
kurocha
9ad990306a63baa4bd49cea67cea1fb856ce4358
3,821
cpp
C++
TopCoder/SRM/RollingDiceDivTwo.cpp
vios-fish/CompetitiveProgramming
6953f024e4769791225c57ed852cb5efc03eb94b
[ "MIT" ]
null
null
null
TopCoder/SRM/RollingDiceDivTwo.cpp
vios-fish/CompetitiveProgramming
6953f024e4769791225c57ed852cb5efc03eb94b
[ "MIT" ]
null
null
null
TopCoder/SRM/RollingDiceDivTwo.cpp
vios-fish/CompetitiveProgramming
6953f024e4769791225c57ed852cb5efc03eb94b
[ "MIT" ]
null
null
null
// BEGIN CUT HERE // END CUT HERE #line 5 "RollingDiceDivTwo.cpp" #include <iostream> #include <cstdlib> #include <cmath> #include <cstring> #include <string> #include <vector> #include <map> #include <list> #include <queue> #include <stack> #include <bitset> #include <deque> #include <set> #include <sstream> using namespace std; const double EPS = 1e-10; const double PI = acos(-1.0); #define dump(x) cerr << #x << " = " << (x) << endl; #define debug(x) cerr << #x << " = " << (x) << "(L" << __LINE__ << ")" << __FILE__ << endl; #define FOR(i,a,b) for( int i = (a); i < (b); ++i) #define rep(i,n) FOR(i,0,n) typedef vector<int> VI; typedef vector<VI> VII; typedef vector<string> VS; typedef pair<int, int> PII; inline int toInt( string s ){int v; istringstream sin(s);sin >> v;return v;} template<class T> inline string toString( T x ){ostringstream sout;sout<<x;return sout.str();} class RollingDiceDivTwo { public: int minimumFaces(vector <string> rolls) { int result = 0; rep(i,rolls.size()){ sort(rolls[i].begin(),rolls[i].end()); } rep(i,rolls[0].size()){ int m = 0; rep(j,rolls.size()){ int a = rolls[j][i] - '0'; m = max( a, m); } result += m; } return result; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arr0[] = {"137", "364", "115", "724"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 14; verify_case(0, Arg1, minimumFaces(Arg0)); } void test_case_1() { string Arr0[] = {"1112", "1111", "1211", "1111"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 5; verify_case(1, Arg1, minimumFaces(Arg0)); } void test_case_2() { string Arr0[] = {"24412", "56316", "66666", "45625"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 30; verify_case(2, Arg1, minimumFaces(Arg0)); } void test_case_3() { string Arr0[] = {"931", "821", "156", "512", "129", "358", "555"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 19; verify_case(3, Arg1, minimumFaces(Arg0)); } void test_case_4() { string Arr0[] = {"3", "7", "4", "2", "4"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 7; verify_case(4, Arg1, minimumFaces(Arg0)); } void test_case_5() { string Arr0[] = {"281868247265686571829977999522", "611464285871136563343229916655", "716739845311113736768779647392", "779122814312329463718383927626", "571573431548647653632439431183", "547362375338962625957869719518", "539263489892486347713288936885", "417131347396232733384379841536"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 176; verify_case(5, Arg1, minimumFaces(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main(){ RollingDiceDivTwo __test; __test.run_test(-1); } // END CUT HERE
43.420455
316
0.601413
vios-fish
9adcc73e1a27edff3623834368dd0ae21fee74a5
3,566
cpp
C++
lib/src/test/compressionTest.cpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
182
2019-04-19T12:38:30.000Z
2022-03-20T16:48:20.000Z
lib/src/test/compressionTest.cpp
doymcc/stitchEm
20693a55fa522d7a196b92635e7a82df9917c2e2
[ "MIT" ]
107
2019-04-23T10:49:35.000Z
2022-03-02T18:12:28.000Z
lib/src/test/compressionTest.cpp
doymcc/stitchEm
20693a55fa522d7a196b92635e7a82df9917c2e2
[ "MIT" ]
59
2019-06-04T11:27:25.000Z
2022-03-17T23:49:49.000Z
// Copyright (c) 2012-2017 VideoStitch SAS // Copyright (c) 2018 stitchEm #include "gpu/testing.hpp" #include <string> #include <sstream> #include <gpu/memcpy.hpp> #include <util/pngutil.hpp> #include <util/compressionUtils.hpp> #include <util/base64.hpp> //#define DUMP_TEST_RESULT #if defined(DUMP_TEST_RESULT) //#undef NDEBUG #ifdef NDEBUG #error "This is not supposed to be included in non-debug mode." #endif #include "../util/debugUtils.hpp" #endif /* * This test is used to check the compression rate of the polyline-based encoding and the PNG compresison */ namespace VideoStitch { namespace Testing { bool readImageFromFile(const std::string filename, int64_t& width, int64_t& height, std::vector<uint32_t>& data) { std::vector<unsigned char> imageBuffer; if (!VideoStitch::Util::PngReader::readRGBAFromFile(filename.c_str(), width, height, imageBuffer)) { return false; } data.clear(); data.resize(width * height, 0); for (int i = 0; i < width * height; i++) if (imageBuffer[4 * i] > 0 || imageBuffer[4 * i + 1] || imageBuffer[4 * i + 2] > 0) { data[i] = 1; } return true; } void testCompression() { #ifdef DUMP_TEST_RESULT std::string workingPath = "C:/Users/Chuong.VideoStitch-09/Documents/GitHub/VideoStitch/VideoStitch-master/lib/src/test/"; #else std::string workingPath = ""; #endif std::vector<std::string> compressionTests; for (int i = 0; i <= 20; i++) { compressionTests.push_back(workingPath + "data/compression/" + std::to_string(i) + ".png"); } std::vector<float> compressionRates = {56.71f, 73.03f, 69.57f, 79.81f, 72.33f}; for (int t = 4; t >= 0; t--) { int64_t width, height; std::vector<uint32_t> data; ENSURE(readImageFromFile(compressionTests[t], width, height, data) == true, "Cannot load input file"); std::vector<unsigned char> ucdata(data.size()); for (size_t i = 0; i < data.size(); i++) { ucdata[i] = (data[i] > 0 ? 1 : 0); } Util::PngReader pngReader; std::string maskMemory; ENSURE(pngReader.writeMaskToMemory(maskMemory, width, height, &ucdata[0])); std::string encodedBinary = Util::base64Encode(maskMemory); const size_t maskLength = encodedBinary.size(); std::string contourEncodeds; Util::Compression::polylineEncodeBinaryMask((int)width, (int)height, ucdata, contourEncodeds); size_t contourLength = contourEncodeds.size(); std::vector<unsigned char> mask; Util::Compression::polylineDecodeBinaryMask((int)width, (int)height, contourEncodeds, mask); const float difference = Util::Compression::binaryDifference(ucdata, mask); #ifdef DUMP_TEST_RESULT std::transform(mask.begin(), mask.end(), mask.begin(), [](unsigned char d) -> unsigned char { return (d > 0) ? 255 : 0; }); pngReader.writeMonochromToFile(std::string(compressionTests[t] + "_extract_poly_reconstructed32.png").c_str(), width, height, &mask[0]); #endif const float compressionRate = 100.0f - float(contourLength * 100.0f) / maskLength; printf("Test %d : Difference %.05f - Binary %zu vs. contour32 %zu : ~difference %.02f\n", t, difference, maskLength, contourLength, compressionRate); ENSURE(difference < 0.005f, " The difference is too big after decoding"); ENSURE(compressionRate >= compressionRates[t], "Compression rate got worse"); } } } // namespace Testing } // namespace VideoStitch int main(int argc, char** argv) { VideoStitch::Testing::initTest(); VideoStitch::Testing::testCompression(); return 0; }
35.306931
120
0.680034
tlalexander
9add92b66c69ce97d207a2ef75fb688e284cf1cd
336
cpp
C++
Medium/984_String_Without_AAA_OR_BBB.cpp
ShehabMMohamed/LeetCodeCPP
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
[ "MIT" ]
1
2021-03-15T10:02:10.000Z
2021-03-15T10:02:10.000Z
Medium/984_String_Without_AAA_OR_BBB.cpp
ShehabMMohamed/LeetCodeCPP
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
[ "MIT" ]
null
null
null
Medium/984_String_Without_AAA_OR_BBB.cpp
ShehabMMohamed/LeetCodeCPP
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
[ "MIT" ]
null
null
null
class Solution { public: string strWithout3a3b(int A, int B) { if(A == 0) return string(B, 'b'); if(B == 0) return string(A, 'a'); if(A == B) return "ab" + strWithout3a3b(A-1, B-1); if(A > B) return "aab" + strWithout3a3b(A-2, B-1); else return strWithout3a3b(A-1, B-2) + "abb"; } };
33.6
60
0.520833
ShehabMMohamed
9ae01f17c04ed1acc0c291543bd332b718959f3d
365
cpp
C++
C++/Introduction/Basic data types.cpp
jaswal72/hacker-rank
95aaa71b4636928664341dc9c6f75d69af5f26ac
[ "MIT" ]
1
2017-03-27T18:21:38.000Z
2017-03-27T18:21:38.000Z
C++/Introduction/Basic data types.cpp
jaswal72/hacker-rank
95aaa71b4636928664341dc9c6f75d69af5f26ac
[ "MIT" ]
null
null
null
C++/Introduction/Basic data types.cpp
jaswal72/hacker-rank
95aaa71b4636928664341dc9c6f75d69af5f26ac
[ "MIT" ]
null
null
null
/* Contributer : github.com/jaswal72 Email : shubhamjaswal772@gmail.com */ #include <iostream> using namespace std; int main() { int n1; long n2; long long n3; char n4; float n5; double n6; scanf("%d %ld %lld %c %f %lf", &n1, &n2, &n3, &n4, &n5, &n6); printf("%d\n%ld\n%lld\n%c\n%f\n%lf\n", n1, n2, n3, n4, n5, n6); return 0; }
19.210526
65
0.564384
jaswal72
9ae292e0b9914b7581cbd24da1b6493f53e2f5b5
3,060
cpp
C++
src/lib/IV-2_6/matcheditor.cpp
emer/iv
e2ecb3acd834b8764c8582753cc86afcc4281af5
[ "BSD-3-Clause" ]
null
null
null
src/lib/IV-2_6/matcheditor.cpp
emer/iv
e2ecb3acd834b8764c8582753cc86afcc4281af5
[ "BSD-3-Clause" ]
null
null
null
src/lib/IV-2_6/matcheditor.cpp
emer/iv
e2ecb3acd834b8764c8582753cc86afcc4281af5
[ "BSD-3-Clause" ]
null
null
null
#ifdef HAVE_CONFIG_H #include <../../config.h> #endif /* * Copyright (c) 1987, 1988, 1989, 1990, 1991 Stanford University * Copyright (c) 1991 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Stanford and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Stanford and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL STANFORD OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * MatchEditor - StringEditor with pattern matching */ #include <IV-2_6/InterViews/matcheditor.h> #include <IV-2_6/InterViews/textbuffer.h> #include <IV-2_6/InterViews/world.h> #include <stdio.h> #include <string.h> #include <ctype.h> MatchEditor::MatchEditor ( ButtonState* s, const char* sample1, const char* done1 ) : StringEditor(s, sample1, done1) { Init(); } MatchEditor::MatchEditor ( const char* name, ButtonState* s, const char* sample1, const char* done1 ) : StringEditor(name, s, sample1, done1) { Init(); } MatchEditor::~MatchEditor () { } void MatchEditor::Init () { SetClassName("MatchEditor"); Match("%[]", true); } void MatchEditor::Match (const char* p, boolean m) { char* pp; for (pp = pattern; *p != '\0'; ++p, ++pp) { *pp = *p; if (*p == '%') { ++p; ++pp; if (*p != '%' && *p != '*') { *pp = '*'; ++pp; } *pp = *p; } } *pp = '\0'; strcat(pattern, "%*c"); /* workaround bug in Sparc sscanf */ match_on_keystroke = m; } boolean MatchEditor::HandleChar (char c) { boolean done1 = StringEditor::HandleChar(c); if (done1 || (!iscntrl(c) && match_on_keystroke)) { char buf[1000]; int length = text->Length(); strncpy(buf, text->Text(), length); while (length > 0) { buf[length] = '\0'; if (sscanf(buf, pattern) == EOF) { break; } --length; } if (length != text->Length()) { GetWorld()->RingBell(1); Select(length, text->Length()); } } if (done1 && left == right) { return true; } else { return false; } }
30.29703
78
0.611438
emer
9ae2d2a93d3009f6349963a53676a439d288f7a1
966
cpp
C++
master/core/third/libtorrent/bindings/python/src/utility.cpp
importlib/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
32
2016-05-22T23:09:19.000Z
2022-03-13T03:32:27.000Z
master/core/third/libtorrent/bindings/python/src/utility.cpp
isuhao/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
2
2016-05-30T19:45:58.000Z
2018-01-24T22:29:51.000Z
master/core/third/libtorrent/bindings/python/src/utility.cpp
isuhao/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
17
2016-05-27T11:01:42.000Z
2022-03-13T03:32:30.000Z
// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/identify_client.hpp> #include <libtorrent/bencode.hpp> #include <boost/python.hpp> using namespace boost::python; using namespace libtorrent; object client_fingerprint_(peer_id const& id) { boost::optional<fingerprint> result = client_fingerprint(id); return result ? object(*result) : object(); } entry bdecode_(std::string const& data) { return bdecode(data.begin(), data.end()); } std::string bencode_(entry const& e) { std::string result; bencode(std::back_inserter(result), e); return result; } void bind_utility() { def("identify_client", &libtorrent::identify_client); def("client_fingerprint", &client_fingerprint_); def("bdecode", &bdecode_); def("bencode", &bencode_); }
25.421053
72
0.723602
importlib
9ae83451ce187a068df6d56fd7d92870cd293637
1,127
cpp
C++
smacc/test/type_info_unit_test.cpp
koyalbhartia/SMACC
609f017a91bc258deb0b64cac5f198d54f19c9e3
[ "BSD-3-Clause" ]
203
2019-04-11T16:42:10.000Z
2022-03-18T06:02:56.000Z
smacc/test/type_info_unit_test.cpp
koyalbhartia/SMACC
609f017a91bc258deb0b64cac5f198d54f19c9e3
[ "BSD-3-Clause" ]
50
2019-04-18T09:09:48.000Z
2022-03-29T21:38:21.000Z
smacc/test/type_info_unit_test.cpp
koyalbhartia/SMACC
609f017a91bc258deb0b64cac5f198d54f19c9e3
[ "BSD-3-Clause" ]
35
2019-09-10T15:06:37.000Z
2022-02-02T09:10:08.000Z
// Bring in my package's API, which is what I'm testing #include <smacc/introspection/string_type_walker.h> // Bring in gtest #include <gtest/gtest.h> using namespace smacc::introspection; // Declare a test TEST(TestSuite, testCase2) { auto t = TypeInfo::getTypeInfoFromString("u0<u1,u2,u3,u4,u5,u6,u7,u8,u9>"); ASSERT_EQ(t->templateParameters.size(), 9); } TEST(TestSuite, testCase1) { std::stringstream buffer; // Save cout's buffer here std::streambuf *sbuf = std::cout.rdbuf(); // Redirect cout to our stringstream buffer or any other ostream std::cout.rdbuf(buffer.rdbuf()); // Use cout as usual std::cout.rdbuf(sbuf); auto t = TypeInfo::getTypeInfoFromString("u0<u1,u2,u3,u4,u5,u6,u7,u8,u9,u10, u11<u12,u13>>"); ASSERT_EQ(t->templateParameters.size(), 11); // When done redirect cout to its old self ASSERT_EQ(t->templateParameters[10]->templateParameters.size(), 2); } // Run all the tests that were declared with TEST() int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); //ros::init(argc, argv, "tester"); //ros::NodeHandle nh; return RUN_ALL_TESTS(); }
25.613636
95
0.701863
koyalbhartia
9af179cef0a5044d31324b068da1750c1dfc675b
11,071
cpp
C++
xeon_version/src/shared_functions.cpp
Draxent/GameOfLife
bd7dacf1c2d8a591218f17348479318626101dfa
[ "Apache-2.0" ]
2
2015-11-27T01:14:02.000Z
2015-12-01T13:23:53.000Z
xeon_version/src/shared_functions.cpp
Draxent/GameOfLife
bd7dacf1c2d8a591218f17348479318626101dfa
[ "Apache-2.0" ]
null
null
null
xeon_version/src/shared_functions.cpp
Draxent/GameOfLife
bd7dacf1c2d8a591218f17348479318626101dfa
[ "Apache-2.0" ]
null
null
null
/** * @file shared_functions.cpp * @brief Implementation of some functions that are shared by all different development methodologies used in this application. * @author Federico Conte (draxent) * * Copyright 2015 Federico Conte * https://github.com/Draxent/GameOfLife * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../include/shared_functions.h" void compute_generation( Grid* g, size_t start, size_t end ) { size_t pos_top = start - g->width(), pos_bottom = start + g->width(); for ( size_t pos = start; pos < end; pos++, pos_top++, pos_bottom++ ) { // Calculate #Neighbours. int numNeighbor = g->countNeighbours( pos, pos_top, pos_bottom ); // Box ← (( #Neighbours == 3 ) OR ( Cell is alive AND #Neighbours == 2 )). g->Write[pos] = ( numNeighbor == 3 || ( g->Read[pos] && numNeighbor == 2 ) ); } } #if VECTORIZATION void compute_generation_vect( Grid* g, int* numNeighbours, size_t start, size_t end ) { size_t index = start, index_top = start - g->width(), index_bottom = start + g->width(); for ( ; index + VLEN < end; index += VLEN, index_top += VLEN, index_bottom += VLEN ) { // Save the computation of the neighbours counting into the numNeighbours array. numNeighbours[0:VLEN] = g->countNeighbours( index, index_top, index_bottom, __sec_implicit_index(0) ); // Box ← (( #Neighbours == 3 ) OR ( Cell is alive AND #Neighbours == 2 )) in vector notations. g->Write[index:VLEN] = ( numNeighbours[0:VLEN] == 3 || ( g->Read[index:VLEN] && numNeighbours[0:VLEN] == 2 ) ); } // Compute normally the last piece that does not fill the numNeighbours array. for ( ; index < end; index++, index_top++, index_bottom++ ) { // Calculate #Neighbours. int numNeighbor = g->countNeighbours( index, index_top, index_bottom ); // Box ← (( #Neighbours == 3 ) OR ( Cell is alive AND #Neighbours == 2 )). g->Write[index] = ( numNeighbor == 3 || ( g->Read[index] && numNeighbor == 2 ) ); } } #endif // VECTORIZATION bool sequential_version( Grid* g, unsigned int iterations, bool vectorization ) { std::chrono::high_resolution_clock::time_point t1, t2; #if DEBUG // Initialize the matrix that we will used as verifier. Matrix* verifier = new Matrix( g ); #endif // DEBUG // Start - Game of Life t1 = std::chrono::high_resolution_clock::now(); long copyborder_time = 0; size_t start = g->width() + 1, end = g->size() - g->width() - 1; int* numNeighbours = NULL; if ( vectorization ) numNeighbours = new int[VLEN]; for ( unsigned int k = 1; k <= iterations; k++ ) { #if VECTORIZATION if ( vectorization ) compute_generation_vect( g, numNeighbours, start, end ); else compute_generation( g, start, end ); #else compute_generation( g, start, end ); #endif // VECTORIZATION copyborder_time = copyborder_time + end_generation( g, k ); } if ( vectorization ) delete[] numNeighbours; #if TAKE_ALL_TIME // Print the total time in order to compute the end_generation functions. printTime( copyborder_time, "copy border" ); #endif // TAKE_ALL_TIME // End - Game of Life t2 = std::chrono::high_resolution_clock::now(); printTime( t1, t2, "complete Game of Life" ); #if DEBUG // Print only small Grid if ( g->width() <= MAX_PRINTABLE_GRID && g->height() <= MAX_PRINTABLE_GRID ) { // Print final configuration g->print( "OUTPUT" ); } // Check if the output is correct. verifier->GOL( iterations ); if ( verifier->equal() ) std::cout << "TEST OK !!! " << std::endl; else { std::cout << "Error: the verifier obtain this following different value for the GOL computation:" << std::endl; verifier->print(); return false; } #endif // DEBUG return true; } long end_generation( Grid* g, unsigned int current_iteration ) { #if TAKE_ALL_TIME std::chrono::high_resolution_clock::time_point t1, t2; // Start - End Generation t1 = std::chrono::high_resolution_clock::now(); #endif // TAKE_ALL_TIME // Swap the reading and writing matrixes. g->swap(); // Every step we need to configure the border to properly respect the logic of the 2D toroidal grid g->copyBorder(); #if DEBUG // Print only small Grid if ( g->width() <= MAX_PRINTABLE_GRID && g->height() <= MAX_PRINTABLE_GRID ) { // Print the result of the Game of Life iteration. std::string title = "ITERATION " + std::to_string( (long long) current_iteration ) + " -"; g->print( title.c_str(), true ); } #endif // DEBUG #if TAKE_ALL_TIME // End - End Generation t2 = std::chrono::high_resolution_clock::now(); return std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count(); #else return 0; #endif // TAKE_ALL_TIME } bool menu( int argc, char** argv, bool& vectorization, unsigned int& num_tasks, size_t& width, size_t& height, unsigned int& seed, unsigned int& iterations, unsigned int& nw ) { ProgramOptions po( argc, argv ); // Print help message if the "--help" option is present. if ( po.exists( "--help" ) ) { std::cerr << "Usage: " << argv[0] << " [options] " << std::endl; std::cerr << "Possible options:" << std::endl; #if VECTORIZATION std::cerr << "\t -v,\t --vect \t activate the vectorization version ;" << std::endl; #endif // VECTORIZATION std::cerr << "\t -w NUM, --width NUM \t grid width ;" << std::endl; std::cerr << "\t -h NUM, --height NUM \t grid height ;" << std::endl; std::cerr << "\t -s NUM, --seed NUM \t seed used to initialize the grid ( zero for timestamp seed ) ;" << std::endl; std::cerr << "\t -i NUM, --iterations NUM \t number of iterations ;" << std::endl; std::cerr << "\t -t NUM, --thread NUM \t number of threads ( zero for the sequential version ) ;" << std::endl; std::cerr << "\t -n NUM, --num_tasks NUM \t number of tasks generated ;" << std::endl; std::cerr << "\t --help \t\t this help view ;" << std::endl; return false; } // Retrieve all the options value width = (size_t) po.get_number( "-w", "--width", 1000 ); height = (size_t) po.get_number( "-h", "--height", 1000 ); seed = (unsigned int) po.get_number( "-s", "--seed", 0 ); iterations = (unsigned int) po.get_number( "-i", "--iterations", 100 ); nw = (unsigned int) po.get_number( "-t", "--thread", 0 ); num_tasks = (unsigned int) po.get_number( "-n", "--num_chunks", nw ); // At least one task per Worker. assert ( num_tasks >= 0 && nw >= 0 && width > 0 && height > 0 && iterations > 0 ); #if VECTORIZATION vectorization = po.exists( "-v", "--vect" ); std::cout << "Vectorization: " << ( vectorization ? "true" : "false" ) << ", "; #else vectorization = false; #endif // VECTORIZATION std::cout << "Width: " << width << ", Height: " << height << ", Seed: " << seed; std::cout << ", #Iterations: " << iterations << ", #Workers: " << nw << ", #Tasks: " << num_tasks << "." << std::endl; return true; } void initialization( bool vectorization, size_t width, size_t height, unsigned int seed, Grid*& g ) { std::chrono::high_resolution_clock::time_point t1, t2; // Start - Initialization Phase t1 = std::chrono::high_resolution_clock::now(); // Create and initialize the Grid object. g = new Grid( height, width ); g->init( seed ); #if VECTORIZATION if ( vectorization ) g->init_vect( seed ); else g->init( seed ); #else g->init( seed ); #endif // VECTORIZATION // Configure the border to properly respect the logic of the 2D toroidal grid g->copyBorder(); #if DEBUG // Print only small Grid if ( g->width() <= MAX_PRINTABLE_GRID && g->height() <= MAX_PRINTABLE_GRID ) { // Print initial configuration. g->print( "INPUT" ); // Print iteration zero. g->print( "ITERATION 0 -", true ); } #endif // DEBUG // End - Initialization Phase t2 = std::chrono::high_resolution_clock::now(); printTime( t1, t2, "initialization phase" ); } void setup_working_variable( Grid* g, unsigned int& num_tasks, unsigned int& nw, size_t& start, size_t*& chunks ) { size_t workingSize = g->size() - 2*g->width() - 2; start = g->width() + 1; // The minimum percentage has to guarantee a task of at least MIN_BLOCK_SIZE size. double min_perc = MIN_BLOCK_SIZE / (double) workingSize; // Calculate the maximum number of tasks given the minimum percentage calculation. unsigned long max_num_tasks = (unsigned long) ceil( 1 / min_perc ); // If the workingSize is small, we do not need so many tasks. num_tasks = ( max_num_tasks < num_tasks ) ? ((int) max_num_tasks) : num_tasks; // Adjust the number of Workers in order to have at least one task per Worker. nw = ( num_tasks < nw ) ? num_tasks : nw; // Calculate the chunk size of each task, with a decreasing cubic function which // summation is equal to 100% of the workingSize. chunks = new size_t[num_tasks]; // This percentage amount is fixed, since each task has at least min_perc of workingSize. double fix_perc = min_perc * num_tasks; // Compute the summation. unsigned long long summation = 1; for ( int i = 2; i <= num_tasks; i++ ) summation += pow3(i); // Calculate the variable that define our cubic function. double multiplier = (1 - fix_perc) / (double) summation; // Since we are working with integer numbers, we can have a rest. size_t rest = workingSize; // Fill the chunks array with the calculated chunk size for each task. for ( int i = 0; i < num_tasks; i++ ) { double percentage = min_perc + multiplier * pow3(num_tasks - i); chunks[i] = percentage * workingSize; rest -= chunks[i]; } // Assign the rest to the first task. chunks[0] += rest; #if DEBUG std::cout << "Working Size: " << workingSize << ", #Workers: " << nw << ", #Tasks : " << num_tasks << std::endl; std::cout << "CHUNKS = { " << chunks[0]; for ( int i = 1; i < num_tasks; i++ ) std::cout << ", " << chunks[i]; std::cout << " }" << std::endl; #endif // DEBUG } void printTime( long duration, const char *msg ) { #if MACHINE_TIME std::cout << "Time to " << msg << ": " << duration << std::endl; #else char buffer[100]; int choice = 0; const std::string time_strings[6] = { "microseconds", "milliseconds", "seconds", "minutes", "hours", "days" }; const int divisor[6] = { 1, 1000, 1000, 60, 60, 24 }; double time = duration; while ( (choice < 5) && (time >= 1000 ) ) { choice++; time = time / divisor[choice]; } sprintf( buffer, "%.2f", time ); // Print time on screen std::cout << "Time to " << msg << ": " << buffer << " " << time_strings[choice] << "." << std::endl; #endif // MACHINE_TIME } void printTime( std::chrono::high_resolution_clock::time_point t1, std::chrono::high_resolution_clock::time_point t2, const char *msg ) { printTime( (long) std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count(), msg ); }
36.65894
175
0.661639
Draxent
9af1f94e0a3ed34c776977d3e4dcb238933dec3a
21,751
cpp
C++
src/gui/Gui.cpp
beichendexiatian/InstanceFusion
cd48e3f477595a48d845ce01302f564b6b3fc6f6
[ "Apache-2.0" ]
null
null
null
src/gui/Gui.cpp
beichendexiatian/InstanceFusion
cd48e3f477595a48d845ce01302f564b6b3fc6f6
[ "Apache-2.0" ]
null
null
null
src/gui/Gui.cpp
beichendexiatian/InstanceFusion
cd48e3f477595a48d845ce01302f564b6b3fc6f6
[ "Apache-2.0" ]
null
null
null
/* * This file is part of SemanticFusion. * * Copyright (C) 2017 Imperial College London * * The use of the code within this file and all code within files that * make up the software that is SemanticFusion is permitted for * non-commercial purposes only. The full terms and conditions that * apply to the code within this file are detailed within the LICENSE.txt * file and at <http://www.imperial.ac.uk/dyson-robotics-lab/downloads/semantic-fusion/semantic-fusion-license/> * unless explicitly stated. By downloading this file you agree to * comply with these terms. * * If you wish to use any of this code for commercial purposes then * please email researchcontracts.engineering@imperial.ac.uk. * */ #include "Gui.h" #include "GuiCuda.h" #include <cuda_runtime.h> #define gpuErrChk(ans) { gpuAssert((ans), __FILE__, __LINE__); } inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true) { if (code != cudaSuccess) { fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line); if (abort) exit(code); } } struct ClassIdInput { ClassIdInput() : class_id_(0) {} ClassIdInput(int class_id) : class_id_(class_id) {} int class_id_; }; std::ostream& operator<< (std::ostream& os, const ClassIdInput& o){ os << o.class_id_; return os; } std::istream& operator>> (std::istream& is, ClassIdInput& o){ is >> o.class_id_; return is; } Gui::Gui(bool live_capture, std::vector<ClassColour> class_colour_lookup, const int segmentation_width, const int segmentation_height) : width_(1280) , height_(980) , segmentation_width_(segmentation_width) , segmentation_height_(segmentation_height) , class_colour_lookup_(class_colour_lookup) , panel_(205) { width_ += panel_; pangolin::Params window_params; window_params.Set("SAMPLE_BUFFERS", 0); window_params.Set("SAMPLES", 0); pangolin::CreateWindowAndBind("InstanceFusion", width_, height_, window_params); //Main Display //original display of global map(origin semanticfusion) //GlRenderBuffer render_buffer_ = new pangolin::GlRenderBuffer(mainWidth, mainHeight); //GPUTexture color_texture_ = new GPUTexture(mainWidth, mainHeight, GL_RGBA32F, GL_LUMINANCE, GL_FLOAT, true); //GlFramebuffer color_frame_buffer_ = new pangolin::GlFramebuffer; color_frame_buffer_->AttachColour(*color_texture_->texture); color_frame_buffer_->AttachDepth(*render_buffer_); //mapID use for display(InstanceFusion) //GlRenderBuffer mapIdGlobalRenderBuffer= new pangolin::GlRenderBuffer(mainWidth, mainHeight); //GPUTexture mapIdGlobalTexture= new GPUTexture(mainWidth, mainHeight, GL_LUMINANCE32I_EXT, GL_LUMINANCE_INTEGER_EXT, GL_INT, false, true); //GlFramebuffer mapIdGlobalFrameBuffer = new pangolin::GlFramebuffer; mapIdGlobalFrameBuffer->AttachColour(*mapIdGlobalTexture->texture); mapIdGlobalFrameBuffer->AttachDepth(*mapIdGlobalRenderBuffer); //ClearBuffer mapIdGlobalFrameBuffer->Bind(); glPushAttrib(GL_VIEWPORT_BIT); glViewport(0, 0, mainWidth, mainHeight); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); mapIdGlobalFrameBuffer->Unbind(); //temp for renderMapMethod2 cudaMalloc((void **)&camPoseTrans_gpu, 3 * sizeof(float)); cudaMalloc((void **)&rgbdInfo_gpu, 4 * mainWidth * mainHeight * sizeof(float)); cudaMalloc((void **)&mapDisplay_gpu, 4 * mainWidth * mainHeight * sizeof(float)); tempMap = (float*)malloc(4 * mainWidth * mainHeight * sizeof(float)); //ProjectionMatrix(int w, int h, GLprecision fu, GLprecision fv, GLprecision u0, GLprecision v0, GLprecision zNear, GLprecision zFar ) s_cam_ = pangolin::OpenGlRenderState(pangolin::ProjectionMatrix(640, 480, 420, 420, 320, 240, 0.1, 1000), pangolin::ModelViewLookAt(0, 0, -1, 0, 0, 1, pangolin::AxisNegY)); pangolin::Display("cam").SetBounds(0, 1.0f, 0, 1.0f, -640 / 480.0) .SetHandler(new pangolin::Handler3D(s_cam_)); // Small views along the bottom pangolin::Display("raw").SetAspect(640.0f/480.0f); //lyc add pangolin::Display("depth").SetAspect(640.0f/480.0f); //lyc add over pangolin::Display("pred").SetAspect(640.0f/480.0f); pangolin::Display("segmentation").SetAspect(640.0f/480.0f); pangolin::Display("multi").SetBounds(pangolin::Attach::Pix(0),1/4.0f,pangolin::Attach::Pix(180),1.0).SetLayout(pangolin::LayoutEqualHorizontal) .AddDisplay(pangolin::Display("pred")) .AddDisplay(pangolin::Display("segmentation")) .AddDisplay(pangolin::Display("raw")) .AddDisplay(pangolin::Display("depth")); // Vertical view along the side pangolin::Display("legend").SetAspect(640.0f/480.0f); pangolin::Display("vert").SetBounds(pangolin::Attach::Pix(0),1/4.0f,pangolin::Attach::Pix(180),1.0).SetLayout(pangolin::LayoutEqualVertical) .AddDisplay(pangolin::Display("legend")); // The control panel pangolin::CreatePanel("ui").SetBounds(0.0, 1.0, 0.0, pangolin::Attach::Pix(panel_)); pause_.reset(new pangolin::Var<bool>("ui.Pause", false, true)); step_.reset(new pangolin::Var<bool>("ui.Step", false, false)); reset_.reset(new pangolin::Var<bool>("ui.Reset", false, false)); //lyc add save_.reset(new pangolin::Var<bool>("ui.Save",false,false)); frameCount.reset(new pangolin::Var<std::string>("ui.FrameCount","0/0")); fps.reset(new pangolin::Var<int>("ui.FPS",0)); //lyc add over tracking_.reset(new pangolin::Var<bool>("ui.Tracking Only", false, false)); instance_.reset(new pangolin::Var<bool>("ui.Instance Segmentation", true, false)); //TRUE color_view_.reset(new pangolin::Var<bool>("ui.Draw Colors", true, false)); instance_view_.reset(new pangolin::Var<bool>("ui.Draw Instances", false, false)); time_view_.reset(new pangolin::Var<bool>("ui.Draw Time", false, false)); projectBoudingBox_.reset(new pangolin::Var<bool>("ui.Draw ProjectMap BBox", false, false)); displayMode_.reset(new pangolin::Var<bool>("ui.Display Mode", true, false)); bboxType_.reset(new pangolin::Var<bool>("ui.3D BBOX Type", true, false)); rawSave_.reset(new pangolin::Var<bool>("ui.Raw Save", false, false)); instanceSaveOnce_.reset(new pangolin::Var<bool>("ui.Instance Save(Once)", false, false)); class_choice_.reset(new pangolin::Var<ClassIdInput>("ui.Show class probs", ClassIdInput(0))); //No Use //1600 1200 //fxBBOX.reset(new pangolin::Var<float>("ui.fxBBOX", 1440.0, -mainWidth , mainWidth)); //fyBBOX.reset(new pangolin::Var<float>("ui.fyBBOX", 1080.0, -mainHeight, mainHeight)); //cxBBOX.reset(new pangolin::Var<float>("ui.cxBBOX", 0.0, -mainWidth , mainWidth)); //cyBBOX.reset(new pangolin::Var<float>("ui.cyBBOX", 0.0, -mainHeight, mainHeight)); //PHT Delete //probability_texture_array_.reset(new pangolin::GlTextureCudaArray(640,480,GL_LUMINANCE32F_ARB)); probability_texture_array_.reset(new pangolin::GlTextureCudaArray(segmentation_width_,segmentation_height_,GL_RGBA32F)); rendered_segmentation_texture_array_.reset(new pangolin::GlTextureCudaArray(segmentation_width_,segmentation_height_,GL_RGBA32F)); //PHT+ mainDisplay_texture_array_.reset(new pangolin::GlTextureCudaArray(render_buffer_->width,render_buffer_->height,GL_RGBA32F)); boundingBox_texture_array_.reset(new pangolin::GlTextureCudaArray(render_buffer_->width,render_buffer_->height,GL_RGBA32F)); // The gpu colour lookup std::vector<float> class_colour_lookup_rgb; for (unsigned int class_id = 0; class_id < class_colour_lookup_.size(); ++class_id) { class_colour_lookup_rgb.push_back(static_cast<float>(class_colour_lookup_[class_id].r)/255.0f); class_colour_lookup_rgb.push_back(static_cast<float>(class_colour_lookup_[class_id].g)/255.0f); class_colour_lookup_rgb.push_back(static_cast<float>(class_colour_lookup_[class_id].b)/255.0f); } cudaMalloc((void **)&class_colour_lookup_gpu_, class_colour_lookup_rgb.size() * sizeof(float)); cudaMemcpy(class_colour_lookup_gpu_, class_colour_lookup_rgb.data(), class_colour_lookup_rgb.size() * sizeof(float), cudaMemcpyHostToDevice); cudaMalloc((void **)&segmentation_rendering_gpu_, 4 * segmentation_width_ * segmentation_height_ * sizeof(float)); } Gui::~Gui() { cudaFree(class_colour_lookup_gpu_); cudaFree(segmentation_rendering_gpu_); cudaFree(camPoseTrans_gpu); cudaFree(rgbdInfo_gpu); cudaFree(mapDisplay_gpu); free(tempMap); } void Gui::renderMapID(const std::unique_ptr<ElasticFusionInterface>& map,std::vector<ClassColour> class_colour_lookup) { class_colour_lookup_ = class_colour_lookup; mapIdGlobalFrameBuffer->Bind(); glPushAttrib(GL_VIEWPORT_BIT); glViewport(0, 0, mainWidth, mainHeight); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); map->RenderMapIDToGUIBuffer(s_cam_,instance_colours(),time_colours(),surfel_colorus()); mapIdGlobalFrameBuffer->Unbind(); glPopAttrib(); glPointSize(1); glFinish(); } void Gui::preCall() { glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); glDepthFunc(GL_LESS); glClearColor(1.0,1.0,1.0, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); width_ = pangolin::DisplayBase().v.w; height_ = pangolin::DisplayBase().v.h; pangolin::Display("cam").Activate(s_cam_); } void Gui::renderMapMethod1(const std::unique_ptr<ElasticFusionInterface>& map) { map->RenderMapToBoundGlBuffer(s_cam_,instance_colours(),time_colours(),surfel_colorus()); } //Debug Pack timeval time_1,time_2; void TimeTick() { gettimeofday(&time_1,NULL); } void TimeTock(std::string name) { gettimeofday(&time_2,NULL); float timeUse = (time_2.tv_sec-time_1.tv_sec)*1000000+(time_2.tv_usec-time_1.tv_usec); std::cout<<name<<": "<<timeUse<<" us"<<std::endl; } void Gui::renderMapMethod2(const std::unique_ptr<ElasticFusionInterface>& map,const std::unique_ptr<InstanceFusion>& instanceFusion,bool drawBox,bool bboxType) { //map->RenderMapToBoundGlBuffer(s_cam_,instance_colours(),time_colours(),surfel_colorus()); //Step 1 get Info form MapID const int surfel_size = instanceFusion->getSurfelSize(); cudaTextureObject_t mapGlobalsurfelsIds = mapIdGlobalTexture->texObj; float* map_surfels = map->getMapSurfelsGpu(); int n = map->getMapSurfelCount(); //use projectionmodelview matrix to compute BBOX position in screen pangolin::OpenGlMatrix mvp = s_cam_.GetProjectionModelViewMatrix(); Eigen::Matrix<float,4,4> matMVP; for(int r=0; r<4; ++r ) { for(int c=0; c<4; ++c ) { matMVP(r,c) = (float)mvp.m[c*4+r]; } } //std::cout<<"Projection:"<<std::endl; //std::cout<<s_cam_.GetProjectionMatrix()<<std::endl; //std::cout<<"ModelView:"<<std::endl; //std::cout<<s_cam_.GetModelViewMatrix()<<std::endl; //std::cout<<"ModelView Inverse:"<<std::endl; //std::cout<<s_cam_.GetModelViewMatrix().Inverse()<<std::endl; //std::cout<<"Matrix MVP"<<std::endl; //std::cout<<mvp<<std::endl; //use modelview inverse matrix to get camera position -> use for depth pangolin::OpenGlMatrix mvI = s_cam_.GetModelViewMatrix().Inverse(); Eigen::Matrix<float,4,4> matMVI; for(int r=0; r<4; ++r ) { for(int c=0; c<4; ++c ) { matMVI(r,c) = (float)mvI.m[c*4+r]; } } Eigen::Vector3f trans = matMVI.topRightCorner(3, 1); //Eigen::Vector3f trans = map->getCurrPose().topRightCorner(3, 1); cudaMemcpy(camPoseTrans_gpu, &trans(0), 3 * sizeof(float), cudaMemcpyHostToDevice); //input cudaMemset(rgbdInfo_gpu,0, 4 * mainWidth * mainHeight * sizeof(float)); //output //std::cout<<"trans: "<<trans(0)<<" "<<trans(1)<<" "<<trans(2)<<std::endl; getRGBDformMapIDs(mapGlobalsurfelsIds,n,map_surfels,surfel_size,mainWidth,mainHeight,camPoseTrans_gpu,rgbdInfo_gpu); //Step 2 draw 3DBBox in Info if(drawBox&&n>0) { float* map3DBBox = instanceFusion->getMapBoundingBox(); int instanceNum = instanceFusion->getInstanceNum(); float* gcMatrix = instanceFusion->getGcMatrix(); float* instcMatrix = instanceFusion->getInstcMatrix(); cudaMemcpy(tempMap, rgbdInfo_gpu, 4 * mainWidth * mainHeight * sizeof(float), cudaMemcpyDeviceToHost); //input & output int showBoxID=0; for(int i=0;i<instanceNum;i++) { if(map3DBBox==0)break; //std::cout<<"instanceID: "<<i<<std::endl; float minX = map3DBBox[i*6+0]; float maxX = map3DBBox[i*6+1]; float minY = map3DBBox[i*6+2]; float maxY = map3DBBox[i*6+3]; float minZ = map3DBBox[i*6+4]; float maxZ = map3DBBox[i*6+5]; float v = (maxX-minX)*(maxY-minY)*(maxZ-minZ); if(minX>=maxX||minY>=maxY||minZ>=maxZ/*||v>0.01f*/) continue; //for scene19 scene21 //if(i!=1&&i!=11&&i<12)continue; //show measureBBOX(bad code) //char measureInfoBuf[30]; //std::sprintf(measureInfoBuf,"%4.2f/%4.2f/%4.2f",maxX-minX,maxY-minY,maxZ-minZ); //if(class_colour_lookup_[i].name.c_str()[0]=='p')measureBBOX[showBoxID].reset(new pangolin::Var<std::string>("ui.item",measureInfoBuf)); //else if(class_colour_lookup_[i].name.c_str()[0]=='d')measureBBOX[showBoxID].reset(new pangolin::Var<std::string>("ui.table",measureInfoBuf)); //else if(class_colour_lookup_[i].name.c_str()[0]=='t')continue; //else //measureBBOX[showBoxID].reset(new pangolin::Var<std::string>("ui."+class_colour_lookup_[i].name+std::to_string(i),measureInfoBuf)); //if(showBoxID<12)showBoxID++; //SKIP BY CROSS /* int flagContinue = 0; for(int j=0;j<i;j++) { int count=0; float minX2 = map3DBBox[j*6+0]; float maxX2 = map3DBBox[j*6+1]; float minY2 = map3DBBox[j*6+2]; float maxY2 = map3DBBox[j*6+3]; float minZ2 = map3DBBox[j*6+4]; float maxZ2 = map3DBBox[j*6+5]; if(minX2>minX&&minX2<maxX)count++; if(minX2<minX&&minX<maxX2)count++; if(minY2>minY&&minY2<maxY)count++; if(minY2<minY&&minY<maxY2)count++; if(minZ2>minZ&&minZ2<maxZ)count++; if(minZ2<minZ&&minZ<maxZ2)count++; if(count>=3)flagContinue=1; } if(flagContinue) continue; */ //Debug //std::cout<<"instance: "<<i<<" minX:"<<minX<<" maxX:"<<maxX<<std::endl; //std::cout<<"instance: "<<i<<" minY:"<<minY<<" maxY:"<<maxY<<std::endl; //std::cout<<"instance: "<<i<<" minZ:"<<minZ<<" maxZ:"<<maxZ<<std::endl; //3d point float boxPoint3d_ground[8][3]; int p=0; for(int a=0;a<=1;a++) { for(int b=0;b<=1;b++) { for(int c=0;c<=1;c++) { boxPoint3d_ground[p][0] = a==0?minX:maxX; boxPoint3d_ground[p][1] = b==0?minY:maxY; boxPoint3d_ground[p][2] = c==0?minZ:maxZ; //Debug //boxPoint3d_ground[p][0] = maxX; //boxPoint3d_ground[p][1] = maxY; //boxPoint3d_ground[p][2] = maxZ; p++; } } } //ground->world float boxPoint3d_world[8][3]; for(int j=0;j<8;j++) { if(bboxType) ////Ground { boxPoint3d_world[j][0] = gcMatrix[0]*boxPoint3d_ground[j][0] + gcMatrix[1]*boxPoint3d_ground[j][1]+ gcMatrix[ 2]*boxPoint3d_ground[j][2] + gcMatrix[ 3]*1.0f; boxPoint3d_world[j][1] = gcMatrix[4]*boxPoint3d_ground[j][0] + gcMatrix[5]*boxPoint3d_ground[j][1]+ gcMatrix[ 6]*boxPoint3d_ground[j][2] + gcMatrix[ 7]*1.0f; boxPoint3d_world[j][2] = gcMatrix[8]*boxPoint3d_ground[j][0] + gcMatrix[9]*boxPoint3d_ground[j][1]+ gcMatrix[10]*boxPoint3d_ground[j][2] + gcMatrix[11]*1.0f; } else { float bpgX = boxPoint3d_ground[j][0]; float bpgY = boxPoint3d_ground[j][1]; float bpgZ = boxPoint3d_ground[j][2]; boxPoint3d_world[j][0] = instcMatrix[i*16+0]*bpgX + instcMatrix[i*16+1]*bpgY+ instcMatrix[i*16+ 2]*bpgZ + instcMatrix[i*16+ 3]*1.0f; boxPoint3d_world[j][1] = instcMatrix[i*16+4]*bpgX + instcMatrix[i*16+5]*bpgY+ instcMatrix[i*16+ 6]*bpgZ + instcMatrix[i*16+ 7]*1.0f; boxPoint3d_world[j][2] = instcMatrix[i*16+8]*bpgX + instcMatrix[i*16+9]*bpgY+ instcMatrix[i*16+10]*bpgZ + instcMatrix[i*16+11]*1.0f; } //std::cout<<"x:"<<boxPoint3d_world[j][0]<<" y:"<<boxPoint3d_world[j][1]<<" z:"<<boxPoint3d_world[j][2]<<std::endl; } //std::cout<<std::endl; //std::cout<<std::endl; //2d point float boxPoint2d[8][3]; for(int j=0;j<8;j++) { float vPosHome[3]; vPosHome[0] = matMVP(0,0)*boxPoint3d_world[j][0] + matMVP(0,1)*boxPoint3d_world[j][1]+ matMVP(0,2)*boxPoint3d_world[j][2] + matMVP(0,3)*1.0f; vPosHome[1] = matMVP(1,0)*boxPoint3d_world[j][0] + matMVP(1,1)*boxPoint3d_world[j][1]+ matMVP(1,2)*boxPoint3d_world[j][2] + matMVP(1,3)*1.0f; vPosHome[2] = matMVP(2,0)*boxPoint3d_world[j][0] + matMVP(2,1)*boxPoint3d_world[j][1]+ matMVP(2,2)*boxPoint3d_world[j][2] + matMVP(2,3)*1.0f; //float fx = *fxBBOX.get(); //float fy = *fyBBOX.get(); //float cx = *cxBBOX.get(); //float cy = *cyBBOX.get(); float xloc = ((1440 * vPosHome[0]) / vPosHome[2]) + mainWidth *0.5; float yloc = ((1080 * vPosHome[1]) / vPosHome[2]) + mainHeight*0.5; float distX = trans(0)-boxPoint3d_world[j][0]; float distY = trans(1)-boxPoint3d_world[j][1]; float distZ = trans(2)-boxPoint3d_world[j][2]; float zloc = std::sqrt(distX*distX+distY*distY+distZ*distZ); //float zloc = vPosHome[2] / 20.0f; boxPoint2d[j][0] = xloc; boxPoint2d[j][1] = yloc; boxPoint2d[j][2] = zloc; //std::cout<<"Screen_x:"<<xloc<<" Screen_y:"<<yloc<<std::endl; } //draw line for(int j=0;j<8;j++) { for(int k=j+1;k<8;k++) { int flag = 0; if(boxPoint2d[j][2]<=0||boxPoint2d[k][2]<=0) continue; //out of screen if(boxPoint3d_ground[j][0]==boxPoint3d_ground[k][0])flag++; if(boxPoint3d_ground[j][1]==boxPoint3d_ground[k][1])flag++; if(boxPoint3d_ground[j][2]==boxPoint3d_ground[k][2])flag++; if(flag==2) { float lineX = std::abs(boxPoint2d[j][0]-boxPoint2d[k][0]); float lineY = std::abs(boxPoint2d[j][1]-boxPoint2d[k][1]); float lineZ = std::abs(boxPoint2d[j][2]-boxPoint2d[k][2]); float stepX,stepY,stepZ; int needStep; if(lineX>lineY) { stepX = 1; stepY = (1.0f*lineY)/(1.0f*lineX); stepZ = (1.0f*lineZ)/(1.0f*lineX); needStep = lineX; } else if(lineX<lineY) { stepX = (1.0f*lineX)/(1.0f*lineY); stepY = 1; stepZ = (1.0f*lineZ)/(1.0f*lineY); needStep = lineY; } //j to k if(boxPoint2d[k][0]<boxPoint2d[j][0]) stepX = -stepX; if(boxPoint2d[k][1]<boxPoint2d[j][1]) stepY = -stepY; if(boxPoint2d[k][2]<boxPoint2d[j][2]) stepZ = -stepZ; const int lineW = 7; float nowX,nowY,nowZ; nowX = boxPoint2d[j][0]; nowY = boxPoint2d[j][1]; nowZ = boxPoint2d[j][2]; for(int l=0;l<needStep;l++) { int Pixel_x = nowX; int Pixel_y = nowY; for(int m=0;m<lineW*lineW;m++) { int dy = (Pixel_y+m/lineW); int dx = (Pixel_x+m%lineW); if(dx>1&&dx<mainWidth-1&&dy>1&&dy<mainHeight-1) { if(nowZ<tempMap[dy*mainWidth*4+dx*4+3]) { //if(j%2==0&&k%2==0)//(j<4&&k<4) tempMap[dy*mainWidth*4+dx*4+0] = 1.0f; //else // tempMap[dy*mainWidth*4+dx*4+0] = 0.5f; tempMap[dy*mainWidth*4+dx*4+1] = std::min(1.0f, class_colour_lookup_[i].g*1.5f/255.0f); tempMap[dy*mainWidth*4+dx*4+2] = std::min(1.0f, class_colour_lookup_[i].b*1.5f/255.0f); tempMap[dy*mainWidth*4+dx*4+3] = nowZ; } //else //{ // tempMap[dy*mainWidth*4+dx*4+0] = tempMap[dy*mainWidth*4+dx*4+0]*0.95f+1.0f*0.05f; // tempMap[dy*mainWidth*4+dx*4+1] = tempMap[dy*mainWidth*4+dx*4+1]*0.95f+std::min(1.0f, class_colour_lookup_[i].g*1.5f/255.0f)*0.05f; // tempMap[dy*mainWidth*4+dx*4+2] = tempMap[dy*mainWidth*4+dx*4+2]*0.95f+std::min(1.0f, class_colour_lookup_[i].b*1.5f/255.0f)*0.05f; //} } } nowX+=stepX; nowY+=stepY; nowZ+=stepZ; } } } } } cudaMemcpy(rgbdInfo_gpu, tempMap, 4 * mainWidth * mainHeight * sizeof(float), cudaMemcpyHostToDevice); } //Step 3 render Info To Display renderInfoToDisplay(rgbdInfo_gpu,mainWidth,mainHeight,mapDisplay_gpu); //RenderToViewport gpuErrChk(cudaGetLastError()); gpuErrChk(cudaGetLastError()); pangolin::CudaScopedMappedArray arr_tex(*mainDisplay_texture_array_.get()); cudaMemcpyToArray(*arr_tex, 0, 0, (void*)mapDisplay_gpu, sizeof(float) * 4 * mainWidth * mainHeight, cudaMemcpyDeviceToDevice); gpuErrChk(cudaGetLastError()); gpuErrChk(cudaGetLastError()); glDisable(GL_DEPTH_TEST); mainDisplay_texture_array_->RenderToViewport(true); glEnable(GL_DEPTH_TEST); } void Gui::postCall() { pangolin::FinishFrame(); glFinish(); } void Gui::displayProjectColor(const std::string & id, float* segmentation_rendering_gpu_) { gpuErrChk(cudaGetLastError()); gpuErrChk(cudaGetLastError()); pangolin::CudaScopedMappedArray arr_tex(*rendered_segmentation_texture_array_.get()); cudaMemcpyToArray(*arr_tex, 0, 0, (void*)segmentation_rendering_gpu_, sizeof(float) * 4 * segmentation_width_ * segmentation_height_, cudaMemcpyDeviceToDevice); gpuErrChk(cudaGetLastError()); gpuErrChk(cudaGetLastError()); glDisable(GL_DEPTH_TEST); pangolin::Display(id).Activate(); rendered_segmentation_texture_array_->RenderToViewport(true); glEnable(GL_DEPTH_TEST); } void Gui::displayRawNetworkPredictions(const std::string & id, float* device_ptr) { pangolin::CudaScopedMappedArray arr_tex(*probability_texture_array_.get()); gpuErrChk(cudaGetLastError()); cudaMemcpyToArray(*arr_tex, 0, 0, (void*)device_ptr, sizeof(float) * 4 * segmentation_width_ * segmentation_height_, cudaMemcpyDeviceToDevice); gpuErrChk(cudaGetLastError()); glDisable(GL_DEPTH_TEST); pangolin::Display(id).Activate(); probability_texture_array_->RenderToViewport(true); glEnable(GL_DEPTH_TEST); } void Gui::displayImg(const std::string & id, GPUTexture * img) { glDisable(GL_DEPTH_TEST); pangolin::Display(id).Activate(); img->texture->RenderToViewport(true); glEnable(GL_DEPTH_TEST); }
37.95986
162
0.688336
beichendexiatian
9af25601c6a40895bd34de2516a47a74e2e1643b
189
cpp
C++
2_opencv_examples/main.cpp
captainwong/learning_opencv
e12952648d2e8a547c156134c573f1bf4808bb6c
[ "Apache-2.0" ]
null
null
null
2_opencv_examples/main.cpp
captainwong/learning_opencv
e12952648d2e8a547c156134c573f1bf4808bb6c
[ "Apache-2.0" ]
null
null
null
2_opencv_examples/main.cpp
captainwong/learning_opencv
e12952648d2e8a547c156134c573f1bf4808bb6c
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include "examples.h" int main(int argc, const char** argv) { //three_calibration(argc, argv); //camshiftdemo(argc, argv); //lkdemo(argc, argv); obj_detection(); }
17.181818
37
0.687831
captainwong
9af4379272c078c327799156deec4941a3abc3cb
3,486
hh
C++
Contract/DB/AwaitableQuery.hh
decouple/common
b1798868ab03ff349dccfd3fef09331ec0a1f4d3
[ "MIT" ]
null
null
null
Contract/DB/AwaitableQuery.hh
decouple/common
b1798868ab03ff349dccfd3fef09331ec0a1f4d3
[ "MIT" ]
null
null
null
Contract/DB/AwaitableQuery.hh
decouple/common
b1798868ab03ff349dccfd3fef09331ec0a1f4d3
[ "MIT" ]
null
null
null
<?hh // strict namespace Decouple\Common\Contract\DB; /** * This software is maintained voluntarily under the MIT license. * For more information, see <http://www.decouple.io/> */ use Decouple\Common\Contract\Buildable; /** * An awaitable query interface implemented by classes that are queryable asynchronously * * @author Andrew Ewing <drew@phenocode.com> */ interface AwaitableQuery extends Queryable { /** * Execute the query * @return Awaitable<Statement> The Statement result of Query execution */ public function execute(): Awaitable<Statement>; /** * Insert the provided data into the queryable datasource * @param Map<string, mixed> $data The data to insert * @return Awaitable<int> The ID of the inserted item */ public function insert(Map<string, mixed> $data): Awaitable<int>; /** * Retrieve the first result matching the current query structure * @return Awaitable<?Map<string, mixed>> A Map of the result data or null if none found */ public function first(): Awaitable<?Map<string, mixed>>; /** * Fetch all of the results matching the current query structure * @return Awaitable<?Map<string, mixed>> A Map of the results or null if none found */ public function fetchAll(): Awaitable<Vector<Map<string, mixed>>>; /** * Select the provided fields, or all fields if none/null provided * @param ?Vector<string> $fields=null The fields to select * @return AwaitableQuery The adjusted AwaitableQuery object */ public function select(?Vector<string> $fields = null): AwaitableQuery; /** * Update the queryable datasource with the given data * @param Map<string, mixed> $data The data to update * @return AwaitableQuery The adjusted AwaitableQuery object */ public function update(Map<string, mixed> $data): AwaitableQuery; /** * Delete all of the results matching the current query structure * @param bool $soft=false Soft Delete * @return AwaitableQuery The adjusted AwaitableQuery object */ public function delete(bool $soft = false): AwaitableQuery; /** * Assign the provided filter to the queryable datasource * @param string $field The field to compare * @param string $comp The comparator * @param mixed $value The value to compare against * @return AwaitableQuery The adjusted AwaitableQuery object */ public function where(string $field, string $comp, mixed $value): AwaitableQuery; /** * Assign the provided filter set to the queryable datasource * @param KeyedTraversable<string, string> $array A traversable collection of filters * @return Queryable The adjusted Queryable object */ public function whereAll( KeyedTraversable<string, string> $array, ): Queryable; /** * Order the AwaitableQuery datasource by the given parameters * @param string $field The field to order by * @param string $direction The direction to order in * @return AwaitableQuery The adjusted AwaitableQuery object */ public function orderBy(string $field, string $direction): AwaitableQuery; /** * Limit the AwaitableQuery datasource by the specified offsets * @param int $min=0 The number of matching elements to bypass * @param int $max=25 The number of matching elements to select * @return AwaitableQuery The adjusted AwaitableQuery object */ public function limit(int $min = 0, int $max = 25): AwaitableQuery; }
41.5
92
0.706827
decouple
9af5c007b6c7c2cc3f91e6d52c50e167dc930311
22,323
cpp
C++
rfal_st25tb.cpp
DiegoOst/RFAL
4d050bf2084f1c89746f4ad4a51542c64d555193
[ "Apache-2.0" ]
null
null
null
rfal_st25tb.cpp
DiegoOst/RFAL
4d050bf2084f1c89746f4ad4a51542c64d555193
[ "Apache-2.0" ]
null
null
null
rfal_st25tb.cpp
DiegoOst/RFAL
4d050bf2084f1c89746f4ad4a51542c64d555193
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2016 STMicroelectronics</center></h2> * * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.st.com/myliberty * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ /* * PROJECT: ST25R391x firmware * $Revision: $ * LANGUAGE: ISO C99 */ /*! \file rfal_st25tb.c * * \author Gustavo Patricio * * \brief Implementation of ST25TB interface * */ /* ****************************************************************************** * INCLUDES ****************************************************************************** */ #include "rfal_st25tb.h" #include "utils.h" #include "platform1.h" /* ****************************************************************************** * ENABLE SWITCH ****************************************************************************** */ #ifndef RFAL_FEATURE_ST25TB #error " RFAL: Module configuration missing. Please enable/disable ST25TB module by setting: RFAL_FEATURE_ST25TB " #endif #if RFAL_FEATURE_ST25TB /* ****************************************************************************** * GLOBAL DEFINES ****************************************************************************** */ #define RFAL_ST25TB_CMD_LEN 1 /*!< ST25TB length of a command */ #define RFAL_ST25TB_SLOTS 16 /*!< ST25TB number of slots */ #define RFAL_ST25TB_SLOTNUM_MASK 0x0F /*!< ST25TB Slot Number bit mask on SlotMarker */ #define RFAL_ST25TB_SLOTNUM_SHIFT 4 /*!< ST25TB Slot Number shift on SlotMarker */ #define RFAL_ST25TB_INITIATE_CMD1 0x06 /*!< ST25TB Initiate command byte1 */ #define RFAL_ST25TB_INITIATE_CMD2 0x00 /*!< ST25TB Initiate command byte2 */ #define RFAL_ST25TB_PCALL_CMD1 0x06 /*!< ST25TB Pcall16 command byte1 */ #define RFAL_ST25TB_PCALL_CMD2 0x04 /*!< ST25TB Pcall16 command byte2 */ #define RFAL_ST25TB_SELECT_CMD 0x0E /*!< ST25TB Select command */ #define RFAL_ST25TB_GET_UID_CMD 0x0B /*!< ST25TB Get UID command */ #define RFAL_ST25TB_COMPLETION_CMD 0x0F /*!< ST25TB Completion command */ #define RFAL_ST25TB_RESET_INV_CMD 0x0C /*!< ST25TB Reset to Inventory command */ #define RFAL_ST25TB_READ_BLOCK_CMD 0x08 /*!< ST25TB Read Block command */ #define RFAL_ST25TB_WRITE_BLOCK_CMD 0x09 /*!< ST25TB Write Block command */ #define RFAL_ST25TB_T0 2157 /*!< ST25TB t0 159 us ST25TB RF characteristics */ #define RFAL_ST25TB_T1 2048 /*!< ST25TB t1 151 us ST25TB RF characteristics */ #define RFAL_ST25TB_FWT (RFAL_ST25TB_T0 + RFAL_ST25TB_T1) /*!< ST25TB FWT = T0 + T1 */ #define RFAL_ST25TB_TW rfalConvMsTo1fc(7) /*!< ST25TB TW : Programming time for write max 7ms */ /* ****************************************************************************** * GLOBAL MACROS ****************************************************************************** */ /* ****************************************************************************** * GLOBAL TYPES ****************************************************************************** */ /*! Initiate Request */ typedef struct { uint8_t cmd1; /*!< Initiate Request cmd1: 0x06 */ uint8_t cmd2; /*!< Initiate Request cmd2: 0x00 */ } rfalSt25tbInitiateReq; /*! Pcall16 Request */ typedef struct { uint8_t cmd1; /*!< Pcal16 Request cmd1: 0x06 */ uint8_t cmd2; /*!< Pcal16 Request cmd2: 0x04 */ } rfalSt25tbPcallReq; /*! Select Request */ typedef struct { uint8_t cmd; /*!< Select Request cmd: 0x0E */ uint8_t chipId; /*!< Chip ID */ } rfalSt25tbSelectReq; /*! Read Block Request */ typedef struct { uint8_t cmd; /*!< Select Request cmd: 0x08 */ uint8_t address; /*!< Block address */ } rfalSt25tbReadBlockReq; /*! Write Block Request */ typedef struct { uint8_t cmd; /*!< Select Request cmd: 0x09 */ uint8_t address; /*!< Block address */ rfalSt25tbBlock data; /*!< Block Data */ } rfalSt25tbWriteBlockReq; /* ****************************************************************************** * LOCAL FUNCTION PROTOTYPES ****************************************************************************** */ /* ****************************************************************************** * LOCAL VARIABLES ****************************************************************************** */ /* ****************************************************************************** * GLOBAL FUNCTIONS ****************************************************************************** */ /*******************************************************************************/ ReturnCode rfalSt25tbPollerInitialize( SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 ) { return rfalNfcbPollerInitialize( mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ; } /*******************************************************************************/ ReturnCode rfalSt25tbPollerCheckPresence( uint8_t *chipId, SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 ) { ReturnCode ret; uint8_t chipIdRes; chipIdRes = 0x00; /* Send Initiate Request */ ret = rfalSt25tbPollerInitiate( &chipIdRes, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ; /* Check if a transmission error was detected */ if( (ret == ERR_CRC) || (ret == ERR_FRAMING) ) { return ERR_NONE; } /* Copy chip ID if requested */ if( chipId != NULL ) { *chipId = chipIdRes; } return ret; } /*******************************************************************************/ ReturnCode rfalSt25tbPollerInitiate( uint8_t *chipId,SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 ) { ReturnCode ret; uint16_t rxLen; rfalSt25tbInitiateReq initiateReq; uint8_t rxBuf[RFAL_ST25TB_CHIP_ID_LEN + RFAL_ST25TB_CRC_LEN]; /* In case we receive less data that CRC, RF layer will not remove the CRC from buffer */ /* Compute Initiate Request */ initiateReq.cmd1 = RFAL_ST25TB_INITIATE_CMD1; initiateReq.cmd2 = RFAL_ST25TB_INITIATE_CMD2; /* Send Initiate Request */ ret = rfalTransceiveBlockingTxRx( (uint8_t*)&initiateReq, sizeof(rfalSt25tbInitiateReq), (uint8_t*)rxBuf, sizeof(rxBuf), &rxLen, RFAL_TXRX_FLAGS_DEFAULT, RFAL_ST25TB_FWT, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ; /* Check for valid Select Response */ if( (ret == ERR_NONE) && (rxLen != RFAL_ST25TB_CHIP_ID_LEN) ) { return ERR_PROTO; } /* Copy chip ID if requested */ if( chipId != NULL ) { *chipId = *rxBuf; } return ret; } /*******************************************************************************/ ReturnCode rfalSt25tbPollerPcall( uint8_t *chipId,SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 ) { ReturnCode ret; uint16_t rxLen; rfalSt25tbPcallReq pcallReq; /* Compute Pcal16 Request */ pcallReq.cmd1 = RFAL_ST25TB_PCALL_CMD1; pcallReq.cmd2 = RFAL_ST25TB_PCALL_CMD2; /* Send Pcal16 Request */ ret = rfalTransceiveBlockingTxRx( (uint8_t*)&pcallReq, sizeof(rfalSt25tbPcallReq), (uint8_t*)chipId, RFAL_ST25TB_CHIP_ID_LEN, &rxLen, RFAL_TXRX_FLAGS_DEFAULT, RFAL_ST25TB_FWT, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ; /* Check for valid Select Response */ if( (ret == ERR_NONE) && (rxLen != RFAL_ST25TB_CHIP_ID_LEN) ) { return ERR_PROTO; } return ret; } /*******************************************************************************/ ReturnCode rfalSt25tbPollerSlotMarker( uint8_t slotNum, uint8_t *chipIdRes,SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 ) { ReturnCode ret; uint16_t rxLen; uint8_t slotMarker; if( (slotNum == 0) || (slotNum > 15) ) { return ERR_PARAM; } /* Compute SlotMarker */ slotMarker = ( ((slotNum & RFAL_ST25TB_SLOTNUM_MASK) << RFAL_ST25TB_SLOTNUM_SHIFT) | RFAL_ST25TB_PCALL_CMD1 ); /* Send SlotMarker */ ret = rfalTransceiveBlockingTxRx( (uint8_t*)&slotMarker, RFAL_ST25TB_CMD_LEN, (uint8_t*)chipIdRes, RFAL_ST25TB_CHIP_ID_LEN, &rxLen, RFAL_TXRX_FLAGS_DEFAULT, RFAL_ST25TB_FWT, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ; /* Check for valid ChipID Response */ if( (ret == ERR_NONE) && (rxLen != RFAL_ST25TB_CHIP_ID_LEN) ) { return ERR_PROTO; } return ret; } /*******************************************************************************/ ReturnCode rfalSt25tbPollerSelect( uint8_t chipId,SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 ) { ReturnCode ret; uint16_t rxLen; rfalSt25tbSelectReq selectReq; uint8_t chipIdRes; /* Compute Select Request */ selectReq.cmd = RFAL_ST25TB_SELECT_CMD; selectReq.chipId = chipId; /* Send Select Request */ ret = rfalTransceiveBlockingTxRx( (uint8_t*)&selectReq, sizeof(rfalSt25tbSelectReq), (uint8_t*)&chipIdRes, RFAL_ST25TB_CHIP_ID_LEN, &rxLen, RFAL_TXRX_FLAGS_DEFAULT, RFAL_ST25TB_FWT, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ; /* Check for valid Select Response */ if( (ret == ERR_NONE) && ((rxLen != RFAL_ST25TB_CHIP_ID_LEN) || (chipIdRes != chipId)) ) { return ERR_PROTO; } return ret; } /*******************************************************************************/ ReturnCode rfalSt25tbPollerGetUID( rfalSt25tbUID *UID,SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 ) { ReturnCode ret; uint16_t rxLen; uint8_t getUidReq; /* Compute Get UID Request */ getUidReq = RFAL_ST25TB_GET_UID_CMD; /* Send Select Request */ ret = rfalTransceiveBlockingTxRx( (uint8_t*)&getUidReq, RFAL_ST25TB_CMD_LEN, (uint8_t*)UID, sizeof(rfalSt25tbUID), &rxLen, RFAL_TXRX_FLAGS_DEFAULT, RFAL_ST25TB_FWT, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ; /* Check for valid UID Response */ if( (ret == ERR_NONE) && (rxLen != RFAL_ST25TB_UID_LEN) ) { return ERR_PROTO; } return ret; } /*******************************************************************************/ ReturnCode rfalSt25tbPollerCollisionResolution( uint8_t devLimit, rfalSt25tbListenDevice *st25tbDevList, uint8_t *devCnt,SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 ) { uint8_t i; uint8_t chipId; ReturnCode ret; bool detected; /* collision or device was detected */ if( (st25tbDevList == NULL) || (devCnt == NULL) || (devLimit == 0) ) { return ERR_PARAM; } *devCnt = 0; /* Step 1: Send Initiate */ ret = rfalSt25tbPollerInitiate( &chipId, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ; if( ret == ERR_NONE ) { /* If only 1 answer is detected */ st25tbDevList[*devCnt].chipID = chipId; st25tbDevList[*devCnt].isDeselected = false; /* Retrieve its UID and keep it Selected*/ ret = rfalSt25tbPollerSelect( chipId, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ; if( ERR_NONE == ret ) { ret = rfalSt25tbPollerGetUID( &st25tbDevList[*devCnt].UID, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ; } if( ERR_NONE == ret ) { (*devCnt)++; } } /* Always proceed to Pcall16 anticollision as phase differences of tags can lead to no tag recognized, even if there is one */ if( *devCnt < devLimit ) { /* Multiple device responses */ do { detected = false; for(i = 0; i < RFAL_ST25TB_SLOTS; i++) { platformDelay(1); /* Wait t2: Answer to new request delay */ if( i==0 ) { /* Step 2: Send Pcall16 */ ret = rfalSt25tbPollerPcall( &chipId, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ; } else { /* Step 3-17: Send Pcall16 */ ret = rfalSt25tbPollerSlotMarker( i, &chipId, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ; } if( ret == ERR_NONE ) { /* Found another device */ st25tbDevList[*devCnt].chipID = chipId; st25tbDevList[*devCnt].isDeselected = false; /* Select Device, retrieve its UID */ ret = rfalSt25tbPollerSelect( chipId, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ; /* By Selecting this device, the previous gets Deselected */ if( (*devCnt) > 0 ) { st25tbDevList[(*devCnt)-1].isDeselected = true; } if( ERR_NONE == ret ) { rfalSt25tbPollerGetUID( &st25tbDevList[*devCnt].UID, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ; } if( ERR_NONE == ret ) { (*devCnt)++; } } else if( (ret == ERR_CRC) || (ret == ERR_FRAMING) ) { detected = true; } if( *devCnt >= devLimit ) { break; } } } while( (detected == true) && (*devCnt < devLimit) ); } return ERR_NONE; } /*******************************************************************************/ ReturnCode rfalSt25tbPollerReadBlock( uint8_t blockAddress, rfalSt25tbBlock *blockData,SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 ) { ReturnCode ret; uint16_t rxLen; rfalSt25tbReadBlockReq readBlockReq; /* Compute Read Block Request */ readBlockReq.cmd = RFAL_ST25TB_READ_BLOCK_CMD; readBlockReq.address = blockAddress; /* Send Read Block Request */ ret = rfalTransceiveBlockingTxRx( (uint8_t*)&readBlockReq, sizeof(rfalSt25tbReadBlockReq), (uint8_t*)blockData, sizeof(rfalSt25tbBlock), &rxLen, RFAL_TXRX_FLAGS_DEFAULT, RFAL_ST25TB_FWT, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ; /* Check for valid UID Response */ if( (ret == ERR_NONE) && (rxLen != RFAL_ST25TB_BLOCK_LEN) ) { return ERR_PROTO; } return ret; } /*******************************************************************************/ ReturnCode rfalSt25tbPollerWriteBlock( uint8_t blockAddress, rfalSt25tbBlock *blockData,SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 ) { ReturnCode ret; uint16_t rxLen; rfalSt25tbWriteBlockReq writeBlockReq; rfalSt25tbBlock tmpBlockData; /* Compute Write Block Request */ writeBlockReq.cmd = RFAL_ST25TB_WRITE_BLOCK_CMD; writeBlockReq.address = blockAddress; ST_MEMCPY( writeBlockReq.data, blockData, RFAL_ST25TB_BLOCK_LEN ); /* Send Write Block Request */ ret = rfalTransceiveBlockingTxRx( (uint8_t*)&writeBlockReq, sizeof(rfalSt25tbWriteBlockReq), tmpBlockData, RFAL_ST25TB_BLOCK_LEN, &rxLen, RFAL_TXRX_FLAGS_DEFAULT, (RFAL_ST25TB_FWT + RFAL_ST25TB_TW), mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ; /* Check if an unexpected answer was received */ if( ret == ERR_NONE ) { return ERR_PROTO; } /* Check there was any error besides Timeout*/ else if( ret != ERR_TIMEOUT ) { return ret; } ret = rfalSt25tbPollerReadBlock(blockAddress, &tmpBlockData, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ; if( ret == ERR_NONE ) { if( !ST_BYTECMP( tmpBlockData, blockData, RFAL_ST25TB_BLOCK_LEN ) ) { return ERR_NONE; } return ERR_PROTO; } return ret; } /*******************************************************************************/ ReturnCode rfalSt25tbPollerCompletion( SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 ) { uint8_t completionReq; /* Compute Completion Request */ completionReq = RFAL_ST25TB_COMPLETION_CMD; /* Send Completion Request, no response is expected */ return rfalTransceiveBlockingTxRx( (uint8_t*)&completionReq, RFAL_ST25TB_CMD_LEN, NULL, 0, NULL, RFAL_TXRX_FLAGS_DEFAULT, RFAL_ST25TB_FWT, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ; } /*******************************************************************************/ ReturnCode rfalSt25tbPollerResetToInventory( SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 ) { uint8_t resetInvReq; /* Compute Completion Request */ resetInvReq = RFAL_ST25TB_RESET_INV_CMD; /* Send Completion Request, no response is expected */ return rfalTransceiveBlockingTxRx( (uint8_t*)&resetInvReq, RFAL_ST25TB_CMD_LEN, NULL, 0, NULL, RFAL_TXRX_FLAGS_DEFAULT, RFAL_ST25TB_FWT, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ; } #endif /* RFAL_FEATURE_ST25TB */
43.17795
346
0.560857
DiegoOst
9af98a615cfbf0ee6e792a1299bf60ecec5e0c5c
2,084
cpp
C++
LeetCode/DynamicProgramming/BestTimeToBuyAndSellStockii.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
3
2021-07-26T15:58:45.000Z
2021-09-08T14:55:11.000Z
LeetCode/DynamicProgramming/BestTimeToBuyAndSellStockii.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
null
null
null
LeetCode/DynamicProgramming/BestTimeToBuyAndSellStockii.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
2
2021-05-31T11:27:59.000Z
2021-10-03T13:26:00.000Z
/* * LeetCode 122 Best time to Buy And Sell Stock ii * Medium * Shuo Feng * 2021.11.10 */ #include<iostream> #include<vector> using namespace std; /* * Solution 1: Dp */ class Solution { public: int maxProfit(vector<int>& prices) { int days = prices.size(); // The maximum profit we can get in day i with two situations: vector<vector<int>> dp(days, vector<int>(2, 0)); // In days i: // dp[i][0] : own no stock. // dp[i][1] : own stock. dp[0][0] = 0; dp[0][1] = -prices[0]; for (int i = 1; i < days; ++i) { // Two situations in day i // I. own no stock: (1) own no stock in day i - 1. // (2) sell in day i - 1. // // II. own stock: (1) own in day i - 1. // (2) buy a stock in day i - 1. dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i]); dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i]); } // Always earn the most after sell all stock. return dp[days - 1][0]; } }; /* * Solution 1.5: Dp Optimize on the basis of solution 1. * no: own no stock. (correspond dp[i][0] in solution 1.) * hold: own a stock. (correspond dp[i][1] in solution 1.) */ class Solution { public: int maxProfit(vector<int>& prices) { int days = prices.size(); // Day 1: int no = 0; int hold = -prices[0]; for (int i = 1; i < days; ++i) { no = max (no, hold + prices[i]); hold = max (hold, no - prices[i]); } return no; } }; /* * Solution 2: Greedy. * Sell Stock whenever we can earn. */ class Solution { public: int maxProfit(vector<int>& prices) { int days = prices.size(); int maxPro = 0; for (int i = 1; i < days; ++i) { if (prices[i] > prices[i - 1]) { maxPro += prices[i] - prices[i - 1]; } } return maxPro; } };
22.901099
70
0.458733
a4org
9af9dbd4726dc1e201a761fc788ab732f86e97f3
28,252
cpp
C++
examples/38_wifiscope/main/WebServer.cpp
graealex/qemu_esp32
d4d334d1cc53e6e517ac740c0d51e7e4b7afbd3e
[ "Apache-2.0" ]
335
2016-10-12T06:59:33.000Z
2022-03-29T14:26:04.000Z
examples/38_wifiscope/main/WebServer.cpp
graealex/qemu_esp32
d4d334d1cc53e6e517ac740c0d51e7e4b7afbd3e
[ "Apache-2.0" ]
30
2016-10-30T11:23:59.000Z
2021-11-12T10:51:20.000Z
examples/38_wifiscope/main/WebServer.cpp
graealex/qemu_esp32
d4d334d1cc53e6e517ac740c0d51e7e4b7afbd3e
[ "Apache-2.0" ]
48
2016-10-30T08:41:13.000Z
2022-02-15T22:15:09.000Z
/* * WebServer.cpp * * Created on: May 19, 2017 * Author: kolban */ #include <sstream> #include <iostream> #include <vector> #include <map> #include <regex> #include "sdkconfig.h" #define MG_ENABLE_HTTP_STREAMING_MULTIPART 1 #define MG_ENABLE_FILESYSTEM 1 #include "WebServer.h" #include <esp_log.h> #include <mongoose.h> #include <string> static char tag[] = "WebServer"; struct WebServerUserData { WebServer *pWebServer; WebServer::HTTPMultiPart *pMultiPart; WebServer::WebSocketHandler *pWebSocketHandler; void *originalUserData; }; /** * @brief Convert a Mongoose event type to a string. * @param [in] event The received event type. * @return The string representation of the event. */ static std::string mongoose_eventToString(int event) { switch (event) { case MG_EV_CONNECT: return "MG_EV_CONNECT"; case MG_EV_ACCEPT: return "MG_EV_ACCEPT"; case MG_EV_CLOSE: return "MG_EV_CLOSE"; case MG_EV_SEND: return "MG_EV_SEND"; case MG_EV_RECV: return "MG_EV_RECV"; case MG_EV_POLL: return "MG_EV_POLL"; case MG_EV_TIMER: return "MG_EV_TIMER"; case MG_EV_HTTP_PART_DATA: return "MG_EV_HTTP_PART_DATA"; case MG_EV_HTTP_MULTIPART_REQUEST: return "MG_EV_HTTP_MULTIPART_REQUEST"; case MG_EV_HTTP_PART_BEGIN: return "MG_EV_HTTP_PART_BEGIN"; case MG_EV_HTTP_PART_END: return "MG_EV_HTTP_PART_END"; case MG_EV_HTTP_MULTIPART_REQUEST_END: return "MG_EV_HTTP_MULTIPART_REQUEST_END"; case MG_EV_HTTP_REQUEST: return "MG_EV_HTTP_REQUEST"; case MG_EV_HTTP_REPLY: return "MG_EV_HTTP_REPLY"; case MG_EV_HTTP_CHUNK: return "MG_EV_HTTP_CHUNK"; case MG_EV_MQTT_CONNACK: return "MG_EV_MQTT_CONNACK"; case MG_EV_MQTT_CONNECT: return "MG_EV_MQTT_CONNECT"; case MG_EV_MQTT_DISCONNECT: return "MG_EV_MQTT_DISCONNECT"; case MG_EV_MQTT_PINGREQ: return "MG_EV_MQTT_PINGREQ"; case MG_EV_MQTT_PINGRESP: return "MG_EV_MQTT_PINGRESP"; case MG_EV_MQTT_PUBACK: return "MG_EV_MQTT_PUBACK"; case MG_EV_MQTT_PUBCOMP: return "MG_EV_MQTT_PUBCOMP"; case MG_EV_MQTT_PUBLISH: return "MG_EV_MQTT_PUBLISH"; case MG_EV_MQTT_PUBREC: return "MG_EV_MQTT_PUBREC"; case MG_EV_MQTT_PUBREL: return "MG_EV_MQTT_PUBREL"; case MG_EV_MQTT_SUBACK: return "MG_EV_MQTT_SUBACK"; case MG_EV_MQTT_SUBSCRIBE: return "MG_EV_MQTT_SUBSCRIBE"; case MG_EV_MQTT_UNSUBACK: return "MG_EV_MQTT_UNSUBACK"; case MG_EV_MQTT_UNSUBSCRIBE: return "MG_EV_MQTT_UNSUBSCRIBE"; case MG_EV_WEBSOCKET_HANDSHAKE_REQUEST: return "MG_EV_WEBSOCKET_HANDSHAKE_REQUEST"; case MG_EV_WEBSOCKET_HANDSHAKE_DONE: return "MG_EV_WEBSOCKET_HANDSHAKE_DONE"; case MG_EV_WEBSOCKET_FRAME: return "MG_EV_WEBSOCKET_FRAME"; case MG_EV_WEBSOCKET_CONTROL_FRAME: return "MG_EV_WEBSOCKET_CONTROL_FRAME"; } std::ostringstream s; s << "Unknown event: " << event; return s.str(); } //eventToString /** * @brief Convert a Mongoose string type to a string. * @param [in] mgStr The Mongoose string. * @return A std::string representation of the Mongoose string. */ static std::string mgStrToString(struct mg_str mgStr) { return std::string(mgStr.p, mgStr.len); } // mgStrToStr static void dumpHttpMessage(struct http_message *pHttpMessage) { ESP_LOGD(tag, "HTTP Message"); ESP_LOGD(tag, "Message: %s", mgStrToString(pHttpMessage->message).c_str()); ESP_LOGD(tag, "URI: %s", mgStrToString(pHttpMessage->uri).c_str()); } /* static struct mg_str uploadFileNameHandler(struct mg_connection *mgConnection, struct mg_str fname) { ESP_LOGD(tag, "uploadFileNameHandler: %s", mgStrToString(fname).c_str()); return fname; } */ /** * @brief Mongoose event handler. * The event handler is called when an event occurs associated with the WebServer * listening network connection. * * @param [in] mgConnection The network connection associated with the event. * @param [in] event The type of event. * @param [in] eventData Data associated with the event. * @return N/A. */ static void mongoose_event_handler_web_server( struct mg_connection *mgConnection, // The network connection associated with the event. int event, // The type of event. void *eventData // Data associated with the event. ) { if (event == MG_EV_POLL) { return; } ESP_LOGD(tag, "Event: %s [%d]", mongoose_eventToString(event).c_str(), mgConnection->sock); switch (event) { case MG_EV_HTTP_REQUEST: { struct http_message *message = (struct http_message *) eventData; dumpHttpMessage(message); struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data; WebServer *pWebServer = pWebServerUserData->pWebServer; if (!pWebServer->processRequest(mgConnection, message)) { } break; } // MG_EV_HTTP_REQUEST case MG_EV_HTTP_MULTIPART_REQUEST: { struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data; ESP_LOGD(tag, "User_data address 0x%d", (uint32_t)pWebServerUserData); WebServer *pWebServer = pWebServerUserData->pWebServer; if (pWebServer->m_pMultiPartFactory == nullptr) { return; } WebServer::HTTPMultiPart *pMultiPart = pWebServer->m_pMultiPartFactory->newInstance(); struct WebServerUserData *p2 = new WebServerUserData(); ESP_LOGD(tag, "New User_data address 0x%d", (uint32_t)p2); p2->originalUserData = pWebServerUserData; p2->pWebServer = pWebServerUserData->pWebServer; p2->pMultiPart = pMultiPart; p2->pWebSocketHandler = nullptr; mgConnection->user_data = p2; //struct http_message *message = (struct http_message *) eventData; //dumpHttpMessage(message); break; } // MG_EV_HTTP_MULTIPART_REQUEST case MG_EV_HTTP_MULTIPART_REQUEST_END: { struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data; if (pWebServerUserData->pMultiPart != nullptr) { delete pWebServerUserData->pMultiPart; pWebServerUserData->pMultiPart = nullptr; } mgConnection->user_data = pWebServerUserData->originalUserData; delete pWebServerUserData; WebServer::HTTPResponse httpResponse = WebServer::HTTPResponse(mgConnection); httpResponse.setStatus(200); httpResponse.sendData(""); break; } // MG_EV_HTTP_MULTIPART_REQUEST_END case MG_EV_HTTP_PART_BEGIN: { struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data; struct mg_http_multipart_part *part = (struct mg_http_multipart_part *)eventData; ESP_LOGD(tag, "file_name: \"%s\", var_name: \"%s\", status: %d, user_data: 0x%d", part->file_name, part->var_name, part->status, (uint32_t)part->user_data); if (pWebServerUserData->pMultiPart != nullptr) { pWebServerUserData->pMultiPart->begin(std::string(part->var_name), std::string(part->file_name)); } break; } // MG_EV_HTTP_PART_BEGIN case MG_EV_HTTP_PART_DATA: { struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data; struct mg_http_multipart_part *part = (struct mg_http_multipart_part *)eventData; ESP_LOGD(tag, "file_name: \"%s\", var_name: \"%s\", status: %d, user_data: 0x%d", part->file_name, part->var_name, part->status, (uint32_t)part->user_data); if (pWebServerUserData->pMultiPart != nullptr) { pWebServerUserData->pMultiPart->data(mgStrToString(part->data)); } break; } // MG_EV_HTTP_PART_DATA case MG_EV_HTTP_PART_END: { struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data; struct mg_http_multipart_part *part = (struct mg_http_multipart_part *)eventData; ESP_LOGD(tag, "file_name: \"%s\", var_name: \"%s\", status: %d, user_data: 0x%d", part->file_name, part->var_name, part->status, (uint32_t)part->user_data); if (pWebServerUserData->pMultiPart != nullptr) { pWebServerUserData->pMultiPart->end(); } break; } // MG_EV_HTTP_PART_END case MG_EV_WEBSOCKET_HANDSHAKE_REQUEST: { struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data; WebServer *pWebServer = pWebServerUserData->pWebServer; if (pWebServer->m_pWebSocketHandlerFactory != nullptr) { if (pWebServerUserData->pWebSocketHandler != nullptr) { ESP_LOGD(tag, "Warning: MG_EV_WEBSOCKET_HANDSHAKE_REQUEST: pWebSocketHandler was NOT null"); } struct WebServerUserData *p2 = new WebServerUserData(); ESP_LOGD(tag, "New User_data address 0x%d", (uint32_t)p2); p2->originalUserData = pWebServerUserData; p2->pWebServer = pWebServerUserData->pWebServer; p2->pWebSocketHandler = pWebServer->m_pWebSocketHandlerFactory->newInstance(); mgConnection->user_data = p2; } else { ESP_LOGD(tag, "We received a WebSocket request but we have no handler factory!"); } break; } // MG_EV_WEBSOCKET_HANDSHAKE_REQUEST case MG_EV_WEBSOCKET_HANDSHAKE_DONE: { struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data; if (pWebServerUserData->pWebSocketHandler == nullptr) { ESP_LOGE(tag, "Error: MG_EV_WEBSOCKET_FRAME: pWebSocketHandler is null"); return; } pWebServerUserData->pWebSocketHandler->onCreated(); break; } // MG_EV_WEBSOCKET_HANDSHAKE_DONE /* * When we receive a MG_EV_WEBSOCKET_FRAME then we have received a chunk of data over the network. * Our goal will be to send this to the web socket handler (if one exists). */ case MG_EV_WEBSOCKET_FRAME: { struct WebServerUserData *pWebServerUserData = (struct WebServerUserData *)mgConnection->user_data; if (pWebServerUserData->pWebSocketHandler == nullptr) { ESP_LOGE(tag, "Error: MG_EV_WEBSOCKET_FRAME: pWebSocketHandler is null"); return; } struct websocket_message *ws_message = (websocket_message *)eventData; ESP_LOGD(tag, "Received data length: %d", ws_message->size); pWebServerUserData->pWebSocketHandler->onMessage(std::string((char *)ws_message->data, ws_message->size)); break; } // MG_EV_WEBSOCKET_FRAME } // End of switch } // End of mongoose_event_handler /** * @brief Constructor. */ WebServer::WebServer() { m_rootPath = ""; m_pMultiPartFactory = nullptr; m_pWebSocketHandlerFactory = nullptr; } // WebServer WebServer::~WebServer() { } /** * @brief Get the current root path. * @return The current root path. */ std::string WebServer::getRootPath() { return m_rootPath; } // getRootPath /** * @brief Register a handler for a path. * * When a browser request arrives, the request will contain a method (GET, POST, etc) and a path * to be accessed. Using this method we can register a regular expression and, if the incoming method * and path match the expression, the corresponding handler will be called. * * Example: * @code{.cpp} * static void handle_REST_WiFi(WebServer::HTTPRequest *pRequest, WebServer::HTTPResponse *pResponse) { * ... * } * * webServer.addPathHandler("GET", "\\/ESP32\\/WiFi", handle_REST_WiFi); * @endcode * * @param [in] method The method being used for access ("GET", "POST" etc). * @param [in] pathExpr The path being accessed. * @param [in] handler The callback function to be invoked when a request arrives. */ void WebServer::addPathHandler(std::string method, std::string pathExpr, void (*handler)(WebServer::HTTPRequest *pHttpRequest, WebServer::HTTPResponse *pHttpResponse)) { m_pathHandlers.push_back(PathHandler(method, pathExpr, handler)); } // addPathHandler /** * @brief Run the web server listening at the given port. * * This function does not return. * * @param [in] port The port number of which to listen. * @return N/A. */ void WebServer::start(uint16_t port) { ESP_LOGD(tag, "WebServer task starting"); struct mg_mgr mgr; mg_mgr_init(&mgr, NULL); std::stringstream stringStream; stringStream << ':' << port; struct mg_connection *mgConnection = mg_bind(&mgr, stringStream.str().c_str(), mongoose_event_handler_web_server); if (mgConnection == NULL) { ESP_LOGE(tag, "No connection from the mg_bind()"); vTaskDelete(NULL); return; } struct WebServerUserData *pWebServerUserData = new WebServerUserData(); pWebServerUserData->pWebServer = this; pWebServerUserData->pMultiPart = nullptr; mgConnection->user_data = pWebServerUserData; // Save the WebServer instance reference in user_data. ESP_LOGD(tag, "start: User_data address 0x%d", (uint32_t)pWebServerUserData); mg_set_protocol_http_websocket(mgConnection); ESP_LOGD(tag, "WebServer listening on port %d", port); while (1) { mg_mgr_poll(&mgr, 2000); } } // run /** * @brief Set the multi part factory. * @param [in] pMultiPart A pointer to the multi part factory. */ void WebServer::setMultiPartFactory(HTTPMultiPartFactory *pMultiPartFactory) { m_pMultiPartFactory = pMultiPartFactory; } /** * @brief Set the root path for URL file mapping. * * When a browser requests a file, it uses the address form: * * @code{.unparsed} * http://<host>:<port>/<path> * @endcode * * The path part can be considered the path to where the file should be retrieved on the * file system available to the web server. Typically, we want a directory structure on the file * system to host the web served files and not expose the whole file system. Using this method * we specify the root directory from which the files will be served. * * @param [in] path The root path on the file system. * @return N/A. */ void WebServer::setRootPath(std::string path) { m_rootPath = path; } // setRootPath /** * @brief Register the factory for creating web socket handlers. * * @param [in] pWebSocketHandlerFactory The instance that will create WebSocketHandlers. * @return N/A. */ void WebServer::setWebSocketHandlerFactory(WebSocketHandlerFactory* pWebSocketHandlerFactory) { m_pWebSocketHandlerFactory = pWebSocketHandlerFactory; } // setWebSocketHandlerFactory /** * @brief Constructor. * @param [in] nc The network connection for the response. */ WebServer::HTTPResponse::HTTPResponse(struct mg_connection* nc) { m_nc = nc; m_status = 200; m_dataSent = false; } // HTTPResponse /** * @brief Add a header to the response. * @param [in] name The name of the header. * @param [in] value The value of the header. */ void WebServer::HTTPResponse::addHeader(std::string name, std::string value) { m_headers[name] = value; } // addHeader /** * @brief Send data to the HTTP caller. * Send the data to the HTTP caller. No further data should be sent after this call. * @param [in] data The data to be sent to the HTTP caller. * @return N/A. */ void WebServer::HTTPResponse::sendData(std::string data) { sendData((uint8_t *)data.data(), data.length()); } // sendData /** * @brief Send data to the HTTP caller. * Send the data to the HTTP caller. No further data should be sent after this call. * @param [in] pData The data to be sent to the HTTP caller. * @param [in] length The length of the data to be sent. * @return N/A. */ void WebServer::HTTPResponse::sendData(uint8_t *pData, size_t length) { if (m_dataSent) { ESP_LOGE(tag, "HTTPResponse: Data already sent! Attempt to send again/more."); return; } m_dataSent = true; std::map<std::string, std::string>::iterator iter; std::string headers; for (iter = m_headers.begin(); iter != m_headers.end(); iter++) { if (headers.length() == 0) { headers = iter->first + ": " + iter->second; } else { headers = "; " + iter->first + "=" + iter->second; } } mg_send_head(m_nc, m_status, length, headers.c_str()); mg_send(m_nc, pData, length); m_nc->flags |= MG_F_SEND_AND_CLOSE; } // sendData /** * @brief Send more data to the HTTP caller. * Send the data to the HTTP caller. * @param [in] pData The data to be sent to the HTTP caller. * @param [in] length The length of the data to be sent. * @return N/A. */ void WebServer::HTTPResponse::sendMoreData(uint8_t *pData, size_t length) { m_nc->flags &= ~MG_F_SEND_AND_CLOSE; mg_send(m_nc, pData, length); m_nc->flags |= MG_F_SEND_AND_CLOSE; } /** * @brief Set the headers to be sent in the HTTP response. * @param [in] headers The complete set of headers to send to the caller. * @return N/A. */ void WebServer::HTTPResponse::setHeaders(std::map<std::string, std::string> headers) { m_headers = headers; } // setHeaders /** * @brief Get the current root path. * @return The current root path. */ std::string WebServer::HTTPResponse::getRootPath() { return m_rootPath; } // getRootPath /** * @brief Set the root path for URL file mapping. * @param [in] path The root path on the file system. * @return N/A. */ void WebServer::HTTPResponse::setRootPath(std::string path) { m_rootPath = path; } // setRootPath /** * @brief Set the status value in the HTTP response. * * The default if not set is 200. * @param [in] status The HTTP status code sent to the caller. * @return N/A. */ void WebServer::HTTPResponse::setStatus(int status) { m_status = status; } // setStatus extern "C" struct mg_str mg_get_mime_type(const char *path); /** * @brief Process an incoming HTTP request. * * We look at the path of the request and see if it has a matching path handler. If it does, * we invoke the handler function. If it does not, we try and find a file on the file system * that would resolve to the path. * * @param [in] mgConnection The network connection on which the request was received. * @param [in] message The message representing the request. */ bool WebServer::processRequest(struct mg_connection *mgConnection, struct http_message* message) { std::string uri = mgStrToString(message->uri); ESP_LOGD(tag, "WebServer::processRequest: Matching: %s", uri.c_str()); HTTPResponse httpResponse = HTTPResponse(mgConnection); httpResponse.setRootPath(getRootPath()); /* * Iterate through each of the path handlers looking for a match with the method and specified path. */ std::vector<PathHandler>::iterator it; for (it = m_pathHandlers.begin(); it < m_pathHandlers.end(); it++) { if ((*it).match(mgStrToString(message->method), uri)) { HTTPRequest httpRequest(message); (*it).invoke(&httpRequest, &httpResponse); ESP_LOGD(tag, "Found a match!!"); return true; } } // End of examine path handlers. // Because we reached here, it means that we did NOT match a handler. Now we want to attempt // to retrieve the corresponding file content. std::string filePath = httpResponse.getRootPath() + uri; if (uri.size()==1) { filePath = httpResponse.getRootPath() + std::string("/index.html"); } mg_http_serve_file(mgConnection, message, filePath.c_str(), mg_get_mime_type(filePath.c_str()), mg_mk_str("")); #if 0 std::string filePath = httpResponse.getRootPath() + uri; ESP_LOGD(tag, "Opening file: %s", filePath.c_str()); FILE *file = fopen(filePath.c_str(), "r"); if (file != nullptr) { fseek(file, 0L, SEEK_END); size_t length = ftell(file); fseek(file, 0L, SEEK_SET); uint8_t *pData = (uint8_t *)malloc(length); if (pData!=NULL) { fread(pData, length, 1, file); fclose(file); httpResponse.sendData(pData, length); free(pData); } else { uint8_t *pData = (uint8_t *)malloc(1024); if (pData==NULL) { httpResponse.setStatus(404); // Not found, TODO Out of memory httpResponse.sendData(""); } fread(pData, 1024, 1, file); httpResponse.sendData(pData, 1024); int remaining=length-1024; while (remaining>0) { fread(pData, 1024, 1, file); if (remaining>1024) { httpResponse.sendMoreData(pData, 1024); } else { httpResponse.sendMoreData(pData, remaining); } remaining-=1024; } free(pData); } } else { // Handle unable to open file httpResponse.setStatus(404); // Not found httpResponse.sendData(""); } #endif return false; } // processRequest /** * @brief Construct an instance of a PathHandler. * * @param [in] method The method to be matched. * @param [in] pathPattern The path pattern to be matched. * @param [in] webServerRequestHandler The request handler to be called. */ WebServer::PathHandler::PathHandler(std::string method, std::string pathPattern, void (*webServerRequestHandler)(WebServer::HTTPRequest *pHttpRequest, WebServer::HTTPResponse *pHttpResponse)) { m_method = method; m_pattern = std::regex(pathPattern); m_requestHandler = webServerRequestHandler; } // PathHandler /** * @brief Determine if the path matches. * * @param [in] method The method to be matched. * @param [in] path The path to be matched. * @return True if the path matches. */ bool WebServer::PathHandler::match(std::string method, std::string path) { //ESP_LOGD(tag, "match: %s with %s", m_pattern.c_str(), path.c_str()); if (method != m_method) { return false; } return std::regex_search(path, m_pattern); } // match /** * @brief Invoke the handler. * @param [in] request An object representing the request. * @param [in] response An object representing the response. * @return N/A. */ void WebServer::PathHandler::invoke(WebServer::HTTPRequest* request, WebServer::HTTPResponse *response) { m_requestHandler(request, response); } // invoke /** * @brief Create an HTTPRequest instance. * When mongoose received an HTTP request, we want to encapsulate that to hide the * mongoose complexities. We create an instance of this class to hide those. * @param [in] message The description of the underlying Mongoose message. */ WebServer::HTTPRequest::HTTPRequest(struct http_message* message) { m_message = message; } // HTTPRequest /** * @brief Get the body of the request. * When an HTTP request is either PUT or POST then it may contain a payload that is also * known as the body. This method returns that payload (if it exists). * @return The body of the request. */ std::string WebServer::HTTPRequest::getBody() { return mgStrToString(m_message->body); } // getBody /** * @brief Get the method of the request. * An HTTP request contains a request method which is one of GET, PUT, POST, etc. * @return The method of the request. */ std::string WebServer::HTTPRequest::getMethod() { return mgStrToString(m_message->method); } // getMethod /** * @brief Get the path of the request. * The path of an HTTP request is the portion of the URL that follows the hostname/port pair * but does not include any query parameters. * @return The path of the request. */ std::string WebServer::HTTPRequest::getPath() { return mgStrToString(m_message->uri); } // getPath #define STATE_NAME 0 #define STATE_VALUE 1 /** * @brief Get the query part of the request. * The query is a set of name = value pairs. The return is a map keyed by the name items. * * @return The query part of the request. */ std::map<std::string, std::string> WebServer::HTTPRequest::getQuery() { // Walk through all the characters in the query string maintaining a simple state machine // that lets us know what we are parsing. std::map<std::string, std::string> queryMap; std::string queryString = mgStrToString(m_message->query_string); int i=0; /* * We maintain a simple state machine with states of: * * STATE_NAME - We are parsing a name. * * STATE_VALUE - We are parsing a value. */ int state = STATE_NAME; std::string name = ""; std::string value; // Loop through each character in the query string. for (i=0; i<queryString.length(); i++) { char currentChar = queryString[i]; if (state == STATE_NAME) { if (currentChar != '=') { name += currentChar; } else { state = STATE_VALUE; value = ""; } } // End state = STATE_NAME else if (state == STATE_VALUE) { if (currentChar != '&') { value += currentChar; } else { //ESP_LOGD(tag, "name=%s, value=%s", name.c_str(), value.c_str()); queryMap[name] = value; state = STATE_NAME; name = ""; } } // End state = STATE_VALUE } // End for loop if (state == STATE_VALUE) { //ESP_LOGD(tag, "name=%s, value=%s", name.c_str(), value.c_str()); queryMap[name] = value; } return queryMap; } // getQuery /** * @brief Return the constituent parts of the path. * If we imagine a path as composed of parts separated by slashes, then this function * returns a vector composed of the parts. For example: * * ``` * /x/y/z * ``` * will break out to: * * ``` * path[0] = "" * path[1] = "x" * path[2] = "y" * path[3] = "z" * ``` * * @return A vector of the constituent parts of the path. */ std::vector<std::string> WebServer::HTTPRequest::pathSplit() { std::istringstream stream(getPath()); std::vector<std::string> ret; std::string pathPart; while(std::getline(stream, pathPart, '/')) { ret.push_back(pathPart); } // Debug for (int i=0; i<ret.size(); i++) { ESP_LOGD(tag, "part[%d]: %s", i, ret[i].c_str()); } return ret; } // pathSplit /** * @brief Indicate the beginning of a multipart part. * An HTTP Multipart form is where each of the fields in the form are broken out into distinct * sections. We commonly see this with file uploads. * @param [in] varName The name of the form variable. * @param [in] fileName The name of the file being uploaded (may not be present). * @return N/A. */ void WebServer::HTTPMultiPart::begin(std::string varName, std::string fileName) { ESP_LOGD(tag, "WebServer::HTTPMultiPart::begin(varName=\"%s\", fileName=\"%s\")", varName.c_str(), fileName.c_str()); } // WebServer::HTTPMultiPart::begin /** * @brief Indicate the end of a multipart part. * This will eventually be called after a corresponding begin(). * @return N/A. */ void WebServer::HTTPMultiPart::end() { ESP_LOGD(tag, "WebServer::HTTPMultiPart::end()"); } // WebServer::HTTPMultiPart::end /** * @brief Indicate the arrival of data of a multipart part. * This will be called after a begin() and it may be called many times. Each * call will result in more data. The end of the data will be indicated by a call to end(). * @param [in] data The data received in this callback. * @return N/A. */ void WebServer::HTTPMultiPart::data(std::string data) { ESP_LOGD(tag, "WebServer::HTTPMultiPart::data(), length=%d", data.length()); } // WebServer::HTTPMultiPart::data /** * @brief Indicate the end of all the multipart parts. * @return N/A. */ void WebServer::HTTPMultiPart::multipartEnd() { ESP_LOGD(tag, "WebServer::HTTPMultiPart::multipartEnd()"); } // WebServer::HTTPMultiPart::multipartEnd /** * @brief Indicate the start of all the multipart parts. * @return N/A. */ void WebServer::HTTPMultiPart::multipartStart() { ESP_LOGD(tag, "WebServer::HTTPMultiPart::multipartStart()"); } // WebServer::HTTPMultiPart::multipartStart /** * @brief Indicate that a new WebSocket instance has been created. * @return N/A. */ void WebServer::WebSocketHandler::onCreated() { } // onCreated /** * @brief Indicate that a new message has been received. * @param [in] message The message received from the client. * @return N/A. */ void WebServer::WebSocketHandler::onMessage(std::string message){ } // onMessage /** * @brief Indicate that the client has closed the WebSocket. * @return N/A */ void WebServer::WebSocketHandler::onClosed() { } // onClosed /** * @brief Send data down the WebSocket * @param [in] message The message to send down the socket. * @return N/A. */ void WebServer::WebSocketHandler::sendData(std::string message) { ESP_LOGD(tag, "WebSocketHandler::sendData(length=%d)", message.length()); mg_send_websocket_frame(m_mgConnection, WEBSOCKET_OP_BINARY | WEBSOCKET_OP_CONTINUE, message.data(), message.length()); } // sendData /** * @brief Send data down the WebSocket * @param [in] data The message to send down the socket. * @param [in] size The size of the message * @return N/A. */ void WebServer::WebSocketHandler::sendData(uint8_t *data, uint32_t size) { mg_send_websocket_frame(m_mgConnection, WEBSOCKET_OP_BINARY | WEBSOCKET_OP_CONTINUE, data, size); } // sendData /** * @brief Close the WebSocket from the web server end. * Previously a client has connected to us and created a WebSocket. By making this call we are * declaring that the socket should be closed from the server end. * @return N/A. */ void WebServer::WebSocketHandler::close() { mg_send_websocket_frame(m_mgConnection, WEBSOCKET_OP_CLOSE, nullptr, 0); } // close
31.286822
193
0.713507
graealex
9afc2831afbd5563db7d88221277b3ce9196b57d
1,326
cpp
C++
src/error_code.cpp
tomsksoft-llc/cis1-webui-native-srv-cpp
9ac8f7867977a2f9af5713f60942200d25582f7f
[ "MIT" ]
2
2019-04-26T07:48:26.000Z
2019-06-03T07:04:22.000Z
src/error_code.cpp
tomsksoft-llc/cis1-webui-native-srv-cpp
9ac8f7867977a2f9af5713f60942200d25582f7f
[ "MIT" ]
73
2019-04-25T07:41:34.000Z
2020-04-14T16:23:54.000Z
src/error_code.cpp
tomsksoft-llc/cis1-webui-native-srv-cpp
9ac8f7867977a2f9af5713f60942200d25582f7f
[ "MIT" ]
null
null
null
/* * TomskSoft CIS1 WebUI * * (c) 2019 TomskSoft LLC * (c) Mokin Innokentiy [mia@tomsksoft.com] * */ #include "error_code.h" namespace cis { const char * error_category::name() const noexcept { return "cis::error"; } std::string error_category::message(int ev) const { switch(static_cast<error_code>(ev)) { case error_code::ok: return "OK"; case error_code::too_many_args: return "Too many arguments"; case error_code::cant_parse_config_ini: return "Can't parse config.ini"; case error_code::incorrect_environment: return "Incorrect environment"; case error_code::cant_run_http_listener: return "Can't run HTTP listener"; case error_code::cant_resolve_address: return "Can't resolve network address"; case error_code::cant_open_file: return "Can't open file"; case error_code::cant_cast_config_entry: return "Can't cast config entry"; case error_code::database_error: return "Database error"; default: return "(unrecognized error)"; } } const error_category category; std::error_code make_error_code(error_code e) { return {static_cast<int>(e), category}; } } // namespace cis
21.047619
51
0.625189
tomsksoft-llc
b103b1b1b63f207da0646df2a217279515aa54bf
1,339
cpp
C++
Hacker-Rank/Algorithms/Graph-Theory/torque-and-development.cpp
kishorevarma369/Competitive-Programming
f2fd01b0168cb2908f2cc1794ba2c8a461b06838
[ "MIT" ]
1
2019-05-20T14:38:05.000Z
2019-05-20T14:38:05.000Z
Hacker-Rank/Algorithms/Graph-Theory/torque-and-development.cpp
kishorevarma369/Competitive-Programming
f2fd01b0168cb2908f2cc1794ba2c8a461b06838
[ "MIT" ]
null
null
null
Hacker-Rank/Algorithms/Graph-Theory/torque-and-development.cpp
kishorevarma369/Competitive-Programming
f2fd01b0168cb2908f2cc1794ba2c8a461b06838
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; typedef long long int ll; int m,n; ll clib,croad; // void process() // { // for(auto &road:roads) // { // sort(road.begin(),road.end()); // } // } ll bfs(int i,vector<vector<int>> &roads,vector<bool> &visited) { queue<int> q; q.push(i); int node,count=1; visited[i]=true; while(!q.empty()) { node=q.front(); q.pop(); for(auto &road:roads[node]) { if(!visited[road]) { q.push(road); visited[road]=true; count++; } } } if(clib<=croad) return clib*count; else return clib+(count-1)*croad; } int main(int argc, char const *argv[]) { int t; cin>>t; while(t--) { int ebegin,eend; ll ans=0; cin>>n>>m>>clib>>croad; vector<vector<int>> roads(n); vector<bool> visited(n,0); for(int i=0;i<m;i++) { cin>>ebegin>>eend; ebegin--; eend--; roads[ebegin].push_back(eend); roads[eend].push_back(ebegin); } // process(); for(int i=0;i<n;i++) { if(!visited[i]) ans+=bfs(i,roads,visited); } cout<<ans<<'\n'; } return 0; }
18.342466
62
0.446602
kishorevarma369
b1044d9ffddb5ffa4140bcb649ba809328945b61
1,070
cpp
C++
Stp/Base/Error/Exception.cpp
markazmierczak/Polonite
240f099cafc5c38dc1ae1cc6fc5773e13f65e9de
[ "MIT" ]
1
2019-07-11T12:47:52.000Z
2019-07-11T12:47:52.000Z
Stp/Base/Error/Exception.cpp
Polonite/Polonite
240f099cafc5c38dc1ae1cc6fc5773e13f65e9de
[ "MIT" ]
null
null
null
Stp/Base/Error/Exception.cpp
Polonite/Polonite
240f099cafc5c38dc1ae1cc6fc5773e13f65e9de
[ "MIT" ]
1
2019-07-11T12:47:53.000Z
2019-07-11T12:47:53.000Z
// Copyright 2017 Polonite Authors. All rights reserved. // Distributed under MIT license that can be found in the LICENSE file. #include "Base/Error/Exception.h" #include "Base/Io/TextWriter.h" #include <exception> #if !COMPILER(MSVC) #include <cxxabi.h> namespace __cxxabiv1 { struct __cxa_eh_globals { void* caughtExceptions; unsigned int uncaughtExceptions; }; } #endif // COMPILER(*) namespace stp { Exception::~Exception() { } StringSpan Exception::getName() const noexcept { return "Exception"; } void Exception::formatImpl(TextWriter& out) const { out << getName() << ": "; onFormat(out); } void Exception::onFormat(TextWriter& out) const { } int countUncaughtExceptions() noexcept { #if COMPILER(MSVC) return std::uncaught_exceptions(); #elif defined(_LIBCPPABI_VERSION) return __cxxabiv1::__cxa_uncaught_exceptions(); #else auto* globals = __cxxabiv1::__cxa_get_globals_fast(); return globals->uncaughtExceptions; #endif } bool hasUncaughtExceptions() noexcept { return std::uncaught_exception(); } } // namespace stp
19.454545
71
0.73271
markazmierczak
b109f5fa66603a44d80054e5fa66e936da408ace
4,200
hpp
C++
include/hash.hpp
x0x/hive
5cd9cc82f469b184dcf0a8161ba432d6abf79823
[ "MIT" ]
null
null
null
include/hash.hpp
x0x/hive
5cd9cc82f469b184dcf0a8161ba432d6abf79823
[ "MIT" ]
null
null
null
include/hash.hpp
x0x/hive
5cd9cc82f469b184dcf0a8161ba432d6abf79823
[ "MIT" ]
null
null
null
#pragma once #include "types.hpp" #include "move.hpp" #include <vector> class TableEntry { virtual bool query(Hash hash, TableEntry** entry) = 0; virtual void store(Hash hash, Depth depth) = 0; virtual bool empty() const = 0; }; class PerftEntry { Hash m_hash; Depth m_depth; uint64_t m_nodes; public: inline PerftEntry() : m_hash(0), m_depth(0), m_nodes(0) {} inline bool query(Hash hash, PerftEntry** entry) { *entry = this; return hash == m_hash; } inline void store(Hash hash, Depth depth, uint64_t n_nodes) { m_hash = hash; m_depth = depth; m_nodes = n_nodes; } inline bool empty() const { return m_depth == 0 && m_nodes == 0; } Hash hash() const { return m_hash; } Depth depth() const { return m_depth; } uint64_t n_nodes() const { return m_nodes; } }; enum class EntryType { EMPTY, UPPER_BOUND, LOWER_BOUND, EXACT }; class TranspositionEntry { Hash m_hash; Depth m_depth; uint8_t m_type; Score m_score; Move m_best_move; Score m_static_eval; static Hash data_hash(Depth depth, Score score, Move best_move, EntryType type, Score static_eval) { return (static_cast<Hash>(depth) << 0) | (static_cast<Hash>(score) << 8) | (static_cast<Hash>(best_move.to_int()) << 24) | (static_cast<Hash>(type) << 40) | (static_cast<Hash>(static_eval) << 48); } Hash data_hash() const { return data_hash(depth(), score(), hash_move(), type(), static_eval()); } uint8_t gen_type(EntryType type) { return static_cast<uint8_t>(type); } public: TranspositionEntry() : m_type(gen_type(EntryType::EMPTY)) {} inline bool query(Hash hash, TranspositionEntry** entry) { *entry = this; return hash == (m_hash ^ data_hash()); } inline void store(Hash hash, Depth depth, Score score, Move best_move, EntryType type, Score static_eval) { Hash old_hash = m_hash ^ data_hash(); if (depth >= m_depth || hash != old_hash) { m_hash = hash ^ data_hash(depth, score, best_move, type, static_eval); m_depth = depth; m_type = gen_type(type); m_score = score; m_best_move = best_move; m_static_eval = static_eval; } } bool empty() const { return type() == EntryType::EMPTY; } inline Hash hash() const { return m_hash; } inline Depth depth() const { return m_depth; } inline EntryType type() const { return static_cast<EntryType>(m_type & 0b11); } inline Score score() const { return m_score; } inline Move hash_move() const { return m_best_move; } inline Score static_eval() const { return m_static_eval; } }; template<typename Entry> class HashTable { std::vector<Entry> m_table; std::size_t m_full; static std::size_t size_from_mb(std::size_t mb) { return mb * 1024 / sizeof(Entry) * 1024 + 1; } static std::size_t mb_from_size(std::size_t size) { return (size - 1) / 1024 * sizeof(Entry) / 1024; } std::size_t index(Hash hash) const { return hash % m_table.size(); } public: HashTable() : HashTable(0) {} HashTable(std::size_t size_mb) : m_table(size_from_mb(size_mb)), m_full(0) {} template<typename EntryReturn> bool query(Hash hash, EntryReturn** entry_ptr) { return m_table[index(hash)].query(hash, entry_ptr); } template<typename... Args> void store(Hash hash, Args... args) { auto& entry = m_table[index(hash)]; m_full += entry.empty(); entry.store(hash, args...); } void clear() { m_full = 0; std::fill(m_table.begin(), m_table.end(), Entry()); } int max_size() const { return 262144; } void resize(std::size_t size_mb) { m_table = std::vector<Entry>(size_from_mb(size_mb)); m_full = 0; } int hashfull() const { return m_full * 1000 / m_table.size(); } }; extern HashTable<TranspositionEntry> ttable; extern HashTable<PerftEntry> perft_table;
24.561404
109
0.602381
x0x
b10bd5d386f889e97ab8fc690423153b35491f77
19,181
cpp
C++
Samples/AppWindow/cppwinrt/Code/BU/MusionBU/CodeLine.cpp
OSIREM/ecoin-minimal
7d8314484c0cd47c673046c86c273cc48eaa43d2
[ "MIT" ]
null
null
null
Samples/AppWindow/cppwinrt/Code/BU/MusionBU/CodeLine.cpp
OSIREM/ecoin-minimal
7d8314484c0cd47c673046c86c273cc48eaa43d2
[ "MIT" ]
null
null
null
Samples/AppWindow/cppwinrt/Code/BU/MusionBU/CodeLine.cpp
OSIREM/ecoin-minimal
7d8314484c0cd47c673046c86c273cc48eaa43d2
[ "MIT" ]
null
null
null
/* CodeLine - osirem.com Copyright OSIREM LTD (C) 2016 www.bitolyl.com/osirem bitcoin-office.com ecn.world This source is proprietary, and cannot be used, in part or in full without the express permission of the original author. The original author retain the rights to use, modify, and/or relicense this code without notice. */ #include "pch.h" #include "Code/Work/Contract.h" using namespace ecoin; namespace ecoin { template<class T> T ag_any_cast(boost::any f_Any) { #ifdef ECOIN_SECURE try { return boost::any_cast<T>(f_Any); } catch (boost::bad_any_cast &e) { #if 1 std::cerr << e.what() << '\n'; #endif for(;;) { //pause } } #else return boost::any_cast<T>(f_Any); #endif } CodeLine::CodeLine(std::string f_Line, uint f_CHK, System* f_System) { //////////////// //////////////// // Construct // // acClear(); m_CodeString = f_Line; m_Chk = f_CHK; m_System = f_System; bool f_Scan = true; int f_Size = f_Line.size(); if(m_Chk < f_Size - 6) { std::shared_ptr<Code> f_CodeB = std::make_shared<Code>(f_Line, m_Chk, 0); if (f_CodeB->m_Code_DigitA == '#' || f_CodeB->m_Code_DigitB == '#' || f_CodeB->m_Code_DigitC == '#') { f_Scan = false; } else { m_vec_Code.push_back(f_CodeB); } ////////// ////////// // END if(f_Scan) { m_END = f_CodeB->acDecide_END(); m_Chk = f_CodeB->acDecide_MAX(); uint f_Cntr = 1; while(f_Scan) { if(m_Chk < f_Line.size() - 6) { std::shared_ptr<Code> f_CodeA = std::make_shared<Code>(f_Line, m_Chk, f_Cntr); m_Chk = f_CodeA->m_Chk; if(f_CodeA->m_Code_DigitA == '/' && f_CodeA->m_Code_DigitB == '/') { f_Scan = false; } if (f_CodeA->m_Code_DigitA == '#' || f_CodeA->m_Code_DigitB == '#' || f_CodeA->m_Code_DigitC == '#') { f_Scan = false; } else { m_vec_Code.push_back(f_CodeA); } } else { f_Scan = false; } f_Cntr++; } } } ////////////////////// ////////////// // Setup // // uint f_CodeSize = m_vec_Code.size(); uint f_Count = 0; while(f_Count < f_CodeSize) { std::shared_ptr<Code> f_Code = m_vec_Code[f_Count]; if(f_Code->m_Code_DigitB != '/' && f_Code->m_Code_DigitB != '#') { switch(f_Code->m_Code) { case MuCode_Var: { int f_Type = 0; if(m_vec_Code.size() > 1) { if(f_Count == 0) { if(m_vec_Code[1]->m_Code == MuCode_Condition) { f_Type = 2; } } } if(f_Type <= 1) { if((m_CodeLine != MuLine_Assign_Opr) && (m_CodeLine != MuLine_Function) && (m_CodeLine != MuLine_Function_Frame) && (m_CodeLine != MuLine_Function_Custom) && (m_CodeLine != MuLine_Condition_Ajax) && (m_CodeLine != MuCode_For_Loop)) { m_CodeLine = MuLine_Assign; } std::shared_ptr<Variable> f_Var = std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code); m_vec_Variable.push_back(f_Var); if((f_Code->m_Number.size() == 1) && ((f_CodeSize == 1) || (f_Count > 1))) { if((m_CodeLine != MuLine_Assign_Opr) && (m_CodeLine != MuLine_Function) && (m_CodeLine != MuLine_Condition_Ajax)) { m_CodeLine = MuLine_Init_Var; } std::shared_ptr<Variable> f_VarFRT = std::make_shared<Variable>("Con", MuCode_Constant); *(f_VarFRT) = *(f_Code->m_Number[0]->m_MxVar); m_vec_Variable.push_back(f_VarFRT); } } else { m_CodeLine = MuLine_Condition_Ajax; std::shared_ptr<Variable> f_Var = std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code); m_vec_Variable.push_back(f_Var); } }break; case MuCode_Function: case MuCode_FunctionStart: { m_CodeLine = MuLine_Function; if(f_Code->m_Type[0]->m_VarType == MuFunc_Custom) { ////////////////////// // Custom Function m_CodeLine = MuLine_Function_Custom; } else if (f_Code->m_Type[0]->m_VarType == MuFunc_Frame) { m_CodeLine = MuLine_Function_Frame; } else ////////////////////////////////////////////// { // Math and System and Other (already storage) Function Calls m_CodeLine = MuLine_Function; } #if 0 m_vec_Variable.push_back(f_Code->m_MxVar); m_vec_Variable.push_back(m_vec_Code[f_Code->m_Index + 1]->m_MxVar); m_vec_Variable.push_back(m_vec_Code[f_Code->m_Index + 2]->m_MxVar); #endif }break; case MuCode_System: { if(f_Count > 0) { if((m_CodeLine != MuLine_Assign_Opr) && (m_CodeLine != MuLine_Function) && (m_CodeLine != MuLine_Function_Frame) && (m_CodeLine != MuLine_Function_Custom) && (m_CodeLine != MuLine_Condition_Ajax) && (m_CodeLine != MuCode_For_Loop)) { m_CodeLine = MuLine_Assign; } std::shared_ptr<Variable> f_Var = m_System->av_Var(f_Code->m_Name[0]->m_MxName); m_vec_Variable.push_back(f_Var); if(f_Code->m_Number.size() == 1 && f_CodeSize == 1) { if((m_CodeLine != MuLine_Assign_Opr) && (m_CodeLine != MuLine_Function) && (m_CodeLine != MuLine_Function_Frame) && (m_CodeLine != MuLine_Function_Custom) && (m_CodeLine != MuLine_Condition_Ajax) && (m_CodeLine != MuCode_For_Loop)) { m_CodeLine = MuLine_Init_Var; } std::shared_ptr<Variable> f_VarFRT = std::make_shared<Variable>("Con", MuCode_Constant); *(f_VarFRT) = *(f_Code->m_Number[0]->m_MxVar); m_vec_Variable.push_back(f_VarFRT); } } else { if((m_CodeLine != MuLine_Assign_Opr) && (m_CodeLine != MuLine_Function) && (m_CodeLine != MuLine_Function_Frame) && (m_CodeLine != MuLine_Function_Custom) && (m_CodeLine != MuLine_Condition_Ajax) && (m_CodeLine != MuCode_For_Loop)) { m_CodeLine = MuLine_Init_Var; } std::shared_ptr<Variable> f_Var = m_System->av_Var(f_Code->m_Name[0]->m_MxName); m_vec_Variable.push_back(f_Var); } }break; case MuCode_Constant: { if((m_CodeLine != MuLine_Assign_Opr) && (m_CodeLine != MuLine_Function) && (m_CodeLine != MuLine_Function_Frame) && (m_CodeLine != MuLine_Function_Custom) && (m_CodeLine != MuLine_Condition_Ajax) && (m_CodeLine != MuCode_For_Loop)) { m_CodeLine = MuLine_Init_Var; } std::shared_ptr<Variable> f_Var = std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, MuCode_Constant); m_vec_Variable.push_back(f_Var); if(f_Code->m_Number.size() == 1 && f_CodeSize == 1) { if((m_CodeLine != MuLine_Assign_Opr) && (m_CodeLine != MuLine_Function) && (m_CodeLine != MuLine_Function_Frame) && (m_CodeLine != MuLine_Function_Custom) && (m_CodeLine != MuLine_Condition_Ajax) && (m_CodeLine != MuCode_For_Loop)) { m_CodeLine = MuLine_Init_Var; } std::shared_ptr<Variable> f_VarFRT = std::make_shared<Variable>("Con", MuCode_Constant); *(f_VarFRT) = *(f_Code->m_Number[0]->m_MxVar); m_vec_Variable.push_back(f_VarFRT); } else if(f_Code->m_Number.size() > 1) { #ifdef ECOIN_SECURE throw; #endif } }break; case MuCode_For_Loop: { m_CodeLine = MuLine_For_Loop; if(f_Code->m_Param.size() > 0) { std::shared_ptr<Variable> f_VarFRT = std::make_shared<Variable>(f_Code->m_Param[0]->m_MxName, MuCode_Var); *(f_VarFRT) = *(f_Code->m_Param[0]->m_MxVar); m_vec_Variable.push_back(f_VarFRT); } if(f_Code->m_Param.size() > 1) { std::shared_ptr<Variable> f_VarFRT = std::make_shared<Variable>(f_Code->m_Param[1]->m_MxName, MuCode_Var); *(f_VarFRT) = *(f_Code->m_Param[0]->m_MxVar); m_vec_Variable.push_back(f_VarFRT); } }break; case MuCode_Operator: { m_CodeLine = MuLine_Assign_Opr; std::shared_ptr<Code> f_LtCode = m_vec_Code[f_Code->m_Index - 1]; std::shared_ptr<Code> f_OpCode = m_vec_Code[f_Code->m_Index]; std::shared_ptr<Code> f_RtCode = m_vec_Code[f_Code->m_Index + 1]; std::shared_ptr<Operator> f_Operator = std::make_shared<Operator>(f_OpCode->m_MxName); f_Operator->m_Operator = f_OpCode->m_Type[0]->m_VarType; std::string f_StrCode = f_LtCode->m_MxName; std::string f_StrCodeName = f_LtCode->m_Name[0]->m_MxName; if(f_StrCode.compare("Sys") == 0) { if(f_StrCodeName.compare("Pos") == 0) { f_Operator->resultHand = m_System->Pos; m_vec_Variable.push_back(m_System->Pos); f_Operator->leftHand = m_System->Pos; m_vec_Variable.push_back(m_System->Pos); #if 0 f_Operator->rightHand = std::make_shared<Variable>(f_RtCode->m_Name[0]->m_MxName, f_RtCode->m_Code); #endif f_Operator->rightHand = f_RtCode->m_Number[0]->m_MxVar; m_vec_Variable.push_back(f_Operator->rightHand); } if(f_StrCodeName.compare("Posx") == 0) { f_Operator->resultHand = m_System->Posx; m_vec_Variable.push_back(m_System->Posx); f_Operator->leftHand = m_System->Posx; m_vec_Variable.push_back(m_System->Posx); #if 0 f_Operator->rightHand = std::make_shared<Variable>(f_RtCode->m_Name[0]->m_MxName, f_RtCode->m_Code); #endif f_Operator->rightHand = f_RtCode->m_Number[0]->m_MxVar; m_vec_Variable.push_back(f_Operator->rightHand); } if(f_StrCodeName.compare("Posy") == 0) { f_Operator->resultHand = m_System->Posy; m_vec_Variable.push_back(m_System->Posy); f_Operator->leftHand = m_System->Posy; m_vec_Variable.push_back(m_System->Posy); #if 0 f_Operator->rightHand = std::make_shared<Variable>(f_RtCode->m_Name[0]->m_MxName, f_RtCode->m_Code); #endif f_Operator->rightHand = f_RtCode->m_Number[0]->m_MxVar; m_vec_Variable.push_back(f_Operator->rightHand); } if(f_StrCodeName.compare("Posz") == 0) { f_Operator->resultHand = m_System->Posz; m_vec_Variable.push_back(m_System->Posz); f_Operator->leftHand = m_System->Posz; m_vec_Variable.push_back(m_System->Posz); #if 0 f_Operator->rightHand = std::make_shared<Variable>(f_RtCode->m_Name[0]->m_MxName, f_RtCode->m_Code); #endif f_Operator->rightHand = f_RtCode->m_Number[0]->m_MxVar; m_vec_Variable.push_back(f_Operator->rightHand); } else if(f_StrCodeName.compare("Color") == 0) { f_Operator->resultHand = m_System->Color; m_vec_Variable.push_back(m_System->Color); f_Operator->leftHand = m_System->Color; m_vec_Variable.push_back(m_System->Color); #if 0 f_Operator->rightHand = std::make_shared<Variable>(f_RtCode->m_Name[0]->m_MxName, f_RtCode->m_Code); #endif f_Operator->rightHand = f_RtCode->m_MxVar; m_vec_Variable.push_back(f_Operator->rightHand); } } else if(f_StrCode.compare("Var") == 0) { f_Operator->resultHand = std::make_shared<Variable>(f_LtCode->m_Name[0]->m_MxName, f_LtCode->m_Code); m_vec_Variable.push_back(f_Operator->resultHand); f_Operator->leftHand = std::make_shared<Variable>(f_LtCode->m_Name[0]->m_MxName, f_LtCode->m_Code); m_vec_Variable.push_back(f_Operator->leftHand); if(f_RtCode->m_Number.size() >= 1) { f_Operator->rightHand = f_RtCode->m_Number[0]->m_MxVar; m_vec_Variable.push_back(f_Operator->rightHand); } else { f_Operator->rightHand = std::make_shared<Variable>(f_RtCode->m_Name[0]->m_MxName, f_RtCode->m_Code); m_vec_Variable.push_back(f_Operator->rightHand); } } else { #ifdef ECOIN_SECURE throw; #endif } m_vec_Operator.push_back(f_Operator); }break; case MuCode_Condition: { m_CodeLine = MuLine_Condition_Ajax; }break; case MuCode_Override: { ///////////// /// Pause /// ///////////// }break; } } f_Count++; } } CodeLine::~CodeLine() { m_vec_Code.clear(); m_vec_Variable.clear(); m_vec_Operator.clear(); } int CodeLine::acSearch_CodeType(uint f_TYPE) { for(uint f_CT = 0; f_CT < m_vec_Code.size(); f_CT++) { std::shared_ptr<Code> f_Code = m_vec_Code[f_CT]; if(f_Code->m_Code == f_TYPE) { return f_CT; } } return -5; } void CodeLine::ac_Variable_Align(void) { uint f_VarSize = m_vec_Variable.size(); switch(m_CodeLine) { #if 0 case MuLine_Assign: case MuLine_Assign_Opr: case MuLine_Init_Var: { if(f_VarSize == 1) { m_vec_Code[0]->m_MxVar = m_vec_Variable[0]; } else if(f_VarSize == 2) { m_vec_Code[0]->m_MxVar = m_vec_Variable[0]; m_vec_Code[1]->m_MxVar = m_vec_Variable[1]; } else { throw; } }break; #endif case MuLine_Condition_Ajax: { if(f_VarSize == 5) { if(m_vec_Variable[2]->m_MxName.compare("Con") == 0) { m_vec_Code[0]->m_MxVar = m_vec_Variable[0]; m_vec_Code[2]->m_MxVar = m_vec_Variable[2]; m_vec_Code[1]->m_Condition[0]->leftHand = m_vec_Variable[3]; m_vec_Code[1]->m_Condition[0]->rightHand = m_vec_Variable[4]; } else { throw; } } else if(f_VarSize == 2) { m_vec_Code[0]->m_MxVar = m_vec_Variable[0]; m_vec_Code[2]->m_MxVar = m_vec_Variable[1]; m_vec_Code[1]->m_Condition[0]->leftHand = m_vec_Variable[0]; m_vec_Code[1]->m_Condition[0]->rightHand = m_vec_Variable[1]; } else if(f_VarSize == 4) { m_vec_Code[0]->m_MxVar = m_vec_Variable[0]; m_vec_Code[2]->m_MxVar = m_vec_Variable[1]; m_vec_Code[1]->m_Condition[0]->leftHand = m_vec_Variable[2]; m_vec_Code[1]->m_Condition[0]->rightHand = m_vec_Variable[3]; } else { throw; } }break; case MuLine_Function: case MuLine_Function_Custom: { if(f_VarSize >= 1) { g_Function[m_vec_Code[1]->m_ContractID]->m_Return = m_vec_Variable[0]; for(int f_XY = 0; f_XY < g_Function[m_vec_Code[1]->m_ContractID]->m_vec_Variable.size(); f_XY++) { g_Function[m_vec_Code[1]->m_ContractID]->m_vec_Variable[f_XY] = m_vec_Variable[f_XY + 1]; } } }break; } } bool CodeLine::ac_Execute(void) { ////////////////////// ////////////// // Setup // // uint f_VarSize = m_vec_Code.size(); if(f_VarSize == 0 || f_VarSize == 1) { #ifdef ECOIN_SECURE #if 0 throw; #else return false; #endif #endif } #if 0 printf("ESL_EXEC-f_VarSize %i m_CodeLine %i\n", f_VarSize, m_CodeLine); #endif ////////////////// // Operator // if(m_CodeLine == MuLine_Assign_Opr) { if(m_vec_Operator.size() > 0) { uint f_OpSize = m_vec_Operator.size(); uint f_Count = 0; while(f_Count < f_OpSize) { std::shared_ptr<Operator> f_Operator = m_vec_Operator[f_Count]; f_Operator->ac_Execute(); f_Count++; } } ///////////// else { #ifdef ECOIN_SECURE throw; #endif } } // Assign else if(m_CodeLine == MuLine_Assign) { if(f_VarSize == 0 || f_VarSize == 1) { #ifdef ECOIN_SECURE throw; #endif } else { if(f_VarSize == 2) { std::shared_ptr<Variable> f_VarA = m_vec_Variable[0]; std::shared_ptr<Variable> f_VarB = m_vec_Variable[1]; *(f_VarA) = *(f_VarB); } else { if(f_VarSize == 3) { std::shared_ptr<Variable> f_VarA = m_vec_Variable[0]; std::shared_ptr<Variable> f_VarB = m_vec_Variable[1]; std::shared_ptr<Variable> f_VarC = m_vec_Variable[2]; *(f_VarA) = *(f_VarB); *(f_VarC) = *(f_VarB); } else { #ifdef ECOIN_SECURE throw; #endif } } } } else if(m_CodeLine == MuLine_Condition_Ajax) { std::shared_ptr<Condition> f_Condition = m_vec_Code[1]->m_Condition[0]; f_Condition->ac_Execute(); } else if(m_CodeLine == MuLine_Init_Var) { if(f_VarSize == 0 || f_VarSize == 1) { #ifdef ECOIN_SECURE throw; #endif } else { if(f_VarSize == 2) { std::shared_ptr<Variable> f_VarRes = m_vec_Variable[0]; std::shared_ptr<Variable> f_VarB = m_vec_Variable[1]; *(f_VarRes) = *(f_VarB); } else { if(f_VarSize == 3) { std::shared_ptr<Variable> f_VarRes = m_vec_Variable[0]; std::shared_ptr<Variable> f_VarB = m_vec_Variable[1]; std::shared_ptr<Variable> f_VarC = m_vec_Variable[2]; *(f_VarRes) = *(f_VarB); *(f_VarB) = *(f_VarC); } else { #ifdef ECOIN_SECURE throw; #endif } } } } else if(m_CodeLine == MuLine_Function) { std::shared_ptr<Function> f_Function = g_systemFunction[m_vec_Code[0]->m_ContractID]; f_Function->acExecute(); } else if(m_CodeLine == MuLine_Function_Custom) { std::shared_ptr<Function> f_Function = g_Function[m_vec_Code[0]->m_ContractID]; f_Function->acExecute(); } else if(m_CodeLine == MuLine_For_Loop) { int f_ParamCount = m_vec_Code[0]->m_Param.size(); if(f_ParamCount == 1) { std::shared_ptr<Variable> f_VarCount = m_vec_Variable[0]; int f_Count = 0; if(f_VarCount->m_Var.type() == typeid(int)) { f_Count = ag_any_cast<int>(f_VarCount->m_Var); } else { #ifdef ECOIN_SECURE throw; #endif } if(f_Count < 0) { #ifdef ECOIN_SECURE throw; #endif } std::shared_ptr<Function> f_Function = g_Function[m_vec_Code[0]->m_ContractID]; for(int f_XY = 0; f_XY < f_Count; f_XY++) { f_Function->acExecute(); } } else if(f_ParamCount == 2) { std::shared_ptr<Variable> f_VarCountVar = m_vec_Variable[0]; std::shared_ptr<Variable> f_VarCount = m_vec_Variable[1]; int f_Count = 0; if(f_VarCount->m_Var.type() == typeid(int)) { f_Count = ag_any_cast<int>(f_VarCount->m_Var); } else { #ifdef ECOIN_SECURE throw; #endif } if(f_Count < 0) { #ifdef ECOIN_SECURE throw; #endif } std::shared_ptr<Function> f_Function = g_Function[m_vec_Code[0]->m_ContractID]; for(int f_XY = 0; f_XY < f_Count; f_XY++) { *(f_VarCountVar) = f_XY; f_Function->acExecute(); } } else { #ifdef ECOIN_SECURE throw; #endif } } return true; } std::string CodeLine::ac_Print(void) { return m_CodeString; } };
24.528133
113
0.584485
OSIREM
623eceee55e152c9d156f3651743cef7f48c5b69
3,418
hpp
C++
spike/models/stratum/RockType.hpp
davidson16807/libtectonics
aa0ae2b8a4a1d2a9a346bbdeb334be876ad75646
[ "CC-BY-4.0" ]
7
2020-06-09T19:56:55.000Z
2021-02-17T01:53:30.000Z
spike/models/stratum/RockType.hpp
davidson16807/tectonics.cpp
c40278dba14260c598764467c7abf23b190e676b
[ "CC-BY-4.0" ]
null
null
null
spike/models/stratum/RockType.hpp
davidson16807/tectonics.cpp
c40278dba14260c598764467c7abf23b190e676b
[ "CC-BY-4.0" ]
null
null
null
#pragma once namespace stratum { /* "RockType" attempts to be a comprehensive collection of every earth-like rock that the model is capable of representing. RockType is used to quickly describe to the user what type of rock he's looking at. RockType is only used for descriptive purposes, it is never to be used in model behavior. This requirement is needed so that the logic in get_rock_type can grow to whatever absurd proportion is desired, while still allowing the rest of the code base to be easily reasoned with. RockType only describes the fraction of rock that is composed of minerals found on earth. For instance, if a rock on an icy moon is a conglomerate of silicates and water ice, then the RockType will only describe the silicate fraction of the rock, and the user interface will describe the rock as being a mixture of that rock type plus water ice. */ enum RockType { // IGNEOUS igneous, komatiite, peridotite, basalt, gabbro, andesite, diorite, // dacite, // ganodiorite, rhyolite, granite, // SEDIMENT sediment, sand, silt, clay, loam, sand_loam, silt_loam, clay_loam, sand_clay, silt_clay, // SEDIMENTARY // NOTE: from http://www.kgs.ku.edu/General/Class/sedimentary.html // defined by particle size sedimentary, breccia, sandstone, wacke, siltstone, shale, // defined by composition limestone, // any carbonate chalk, // calcite marl, // partly calcite coal, // organics arkose, // feldspar ironstone, // iron // defined by composition and particle size chert, // quartz, silt or smaller asphalt, // organics, silt or smaller tuff, // feldspar, sand or smaller coquina, // calcite, granule or larger caliche, // partly calcite, granule or larger peat, // organics, sand or granule jet, // organics, pebble or larger // METAMORPHIC metamorphic, // generic zeolite, hornfels, // one schist, two schist... greenschist, blueschist, sanidinite, amphibolite, granulite, eclogite, // sedimentary based slate, // silt or smaller, low grade phyllite, // silt or smaller, low/medium grade schist, // silt or smaller, medium grade gneiss, // any igneous or sedimentary, high grade metaconglomerate, // granule or larger // ultramafic serpentinite, // ultramafic, low grade soapstone, // ultramafic, medium grade jadeite, // ultramafic, high grade // special compositions quartzite, // silica, medium grade or higher marble, // calcite, low grade or higher anthracite,// organics, low grade or higher nephrite, // quartz/calcite/marl // miscellaneous // partially metamorphic, partially soidified // technically possible to represent but possibly difficult to express within get_rock_type() migmatite, count }; }
28.483333
124
0.589819
davidson16807
62422949e13c032724be2671822871fa8ac278b0
6,214
cpp
C++
src/physics/physics_system.cpp
galek/LumixEngine
d7d1738f7fc2bc7f6cf08d1217330a591b370ed9
[ "MIT" ]
8
2015-09-06T20:05:27.000Z
2021-07-14T11:12:33.000Z
src/physics/physics_system.cpp
gamedevforks/LumixEngine
d7d1738f7fc2bc7f6cf08d1217330a591b370ed9
[ "MIT" ]
null
null
null
src/physics/physics_system.cpp
gamedevforks/LumixEngine
d7d1738f7fc2bc7f6cf08d1217330a591b370ed9
[ "MIT" ]
null
null
null
#include "physics/physics_system.h" #include <PxPhysicsAPI.h> #include "cooking/PxCooking.h" #include "core/base_proxy_allocator.h" #include "core/crc32.h" #include "core/log.h" #include "core/resource_manager.h" #include "editor/world_editor.h" #include "engine.h" #include "engine/property_descriptor.h" #include "physics/physics_geometry_manager.h" #include "physics/physics_scene.h" namespace Lumix { static const uint32_t BOX_ACTOR_HASH = crc32("box_rigid_actor"); static const uint32_t MESH_ACTOR_HASH = crc32("mesh_rigid_actor"); static const uint32_t CONTROLLER_HASH = crc32("physical_controller"); static const uint32_t HEIGHTFIELD_HASH = crc32("physical_heightfield"); struct PhysicsSystemImpl : public PhysicsSystem { PhysicsSystemImpl(Engine& engine) : m_allocator(engine.getAllocator()) , m_engine(engine) , m_manager(*this, engine.getAllocator()) { m_manager.create(ResourceManager::PHYSICS, engine.getResourceManager()); registerProperties(); } virtual bool create() override; virtual IScene* createScene(UniverseContext& universe) override; virtual void destroyScene(IScene* scene) override; virtual void destroy() override; virtual physx::PxControllerManager* getControllerManager() override { return m_controller_manager; } virtual physx::PxPhysics* getPhysics() override { return m_physics; } virtual physx::PxCooking* getCooking() override { return m_cooking; } bool connect2VisualDebugger(); void registerProperties(); physx::PxPhysics* m_physics; physx::PxFoundation* m_foundation; physx::PxControllerManager* m_controller_manager; physx::PxAllocatorCallback* m_physx_allocator; physx::PxErrorCallback* m_error_callback; physx::PxCooking* m_cooking; PhysicsGeometryManager m_manager; class Engine& m_engine; class BaseProxyAllocator m_allocator; }; extern "C" LUMIX_PHYSICS_API IPlugin* createPlugin(Engine& engine) { return engine.getAllocator().newObject<PhysicsSystemImpl>(engine); } struct CustomErrorCallback : public physx::PxErrorCallback { virtual void reportError(physx::PxErrorCode::Enum code, const char* message, const char* file, int line); }; IScene* PhysicsSystemImpl::createScene(UniverseContext& ctx) { return PhysicsScene::create(*this, *ctx.m_universe, m_engine, m_allocator); } void PhysicsSystemImpl::destroyScene(IScene* scene) { PhysicsScene::destroy(static_cast<PhysicsScene*>(scene)); } class AssertNullAllocator : public physx::PxAllocatorCallback { public: virtual void* allocate(size_t size, const char* typeName, const char* filename, int line) override { void* ret = _aligned_malloc(size, 16); //g_log_info.log("PhysX") << "Allocated " << size << " bytes for " << typeName << " from " << filename << "(" << line << ")"; ASSERT(ret); return ret; } virtual void deallocate(void* ptr) override { _aligned_free(ptr); } }; void PhysicsSystemImpl::registerProperties() { m_engine.registerComponentType("box_rigid_actor", "Physics Box"); m_engine.registerComponentType("physical_controller", "Physics Controller"); m_engine.registerComponentType("mesh_rigid_actor", "Physics Mesh"); m_engine.registerComponentType("physical_heightfield", "Physics Heightfield"); IAllocator& allocator = m_engine.getAllocator(); m_engine.registerProperty( "box_rigid_actor", allocator.newObject<BoolPropertyDescriptor<PhysicsScene>>( "dynamic", &PhysicsScene::isDynamic, &PhysicsScene::setIsDynamic, allocator)); m_engine.registerProperty( "box_rigid_actor", allocator.newObject<Vec3PropertyDescriptor<PhysicsScene>>( "size", &PhysicsScene::getHalfExtents, &PhysicsScene::setHalfExtents, allocator)); m_engine.registerProperty( "mesh_rigid_actor", allocator.newObject<ResourcePropertyDescriptor<PhysicsScene>>( "source", &PhysicsScene::getShapeSource, &PhysicsScene::setShapeSource, "Physics (*.pda)", allocator)); m_engine.registerProperty( "physical_heightfield", allocator.newObject<ResourcePropertyDescriptor<PhysicsScene>>( "heightmap", &PhysicsScene::getHeightmap, &PhysicsScene::setHeightmap, "Image (*.raw)", allocator)); m_engine.registerProperty( "physical_heightfield", allocator.newObject<DecimalPropertyDescriptor<PhysicsScene>>( "xz_scale", &PhysicsScene::getHeightmapXZScale, &PhysicsScene::setHeightmapXZScale, 0.0f, FLT_MAX, 0.0f, allocator)); m_engine.registerProperty( "physical_heightfield", allocator.newObject<DecimalPropertyDescriptor<PhysicsScene>>( "y_scale", &PhysicsScene::getHeightmapYScale, &PhysicsScene::setHeightmapYScale, 0.0f, FLT_MAX, 0.0f, allocator)); } bool PhysicsSystemImpl::create() { m_physx_allocator = m_allocator.newObject<AssertNullAllocator>(); m_error_callback = m_allocator.newObject<CustomErrorCallback>(); m_foundation = PxCreateFoundation( PX_PHYSICS_VERSION, *m_physx_allocator, *m_error_callback ); m_physics = PxCreatePhysics( PX_PHYSICS_VERSION, *m_foundation, physx::PxTolerancesScale() ); m_controller_manager = PxCreateControllerManager(*m_foundation); m_cooking = PxCreateCooking(PX_PHYSICS_VERSION, *m_foundation, physx::PxCookingParams()); connect2VisualDebugger(); return true; } void PhysicsSystemImpl::destroy() { m_controller_manager->release(); m_cooking->release(); m_physics->release(); m_foundation->release(); m_allocator.deleteObject(m_physx_allocator); m_allocator.deleteObject(m_error_callback); } bool PhysicsSystemImpl::connect2VisualDebugger() { if(m_physics->getPvdConnectionManager() == nullptr) return false; const char* pvd_host_ip = "127.0.0.1"; int port = 5425; unsigned int timeout = 100; physx::PxVisualDebuggerConnectionFlags connectionFlags = physx::PxVisualDebuggerExt::getAllConnectionFlags(); PVD::PvdConnection* theConnection = physx::PxVisualDebuggerExt::createConnection(m_physics->getPvdConnectionManager(), pvd_host_ip, port, timeout, connectionFlags); return theConnection != nullptr; } void CustomErrorCallback::reportError(physx::PxErrorCode::Enum code, const char* message, const char* file, int line) { g_log_error.log("PhysX") << message; } } // !namespace Lumix
26.219409
165
0.760863
galek
624352c3d78824f4a26883cd032fab20f01b400a
2,155
hpp
C++
include/rusty-cpp/impl/maybe_uninit.hpp
QuarticCat/rusty-cpp
089089f076f461c3d84fc70478104ae8d1384aa3
[ "MIT" ]
4
2021-08-28T10:04:00.000Z
2021-11-08T03:29:37.000Z
include/rusty-cpp/impl/maybe_uninit.hpp
QuarticCat/rusty-cpp
089089f076f461c3d84fc70478104ae8d1384aa3
[ "MIT" ]
1
2021-08-25T07:30:19.000Z
2021-08-25T09:26:23.000Z
include/rusty-cpp/impl/maybe_uninit.hpp
QuarticCat/rusty-cpp
089089f076f461c3d84fc70478104ae8d1384aa3
[ "MIT" ]
null
null
null
#pragma once #include <utility> namespace rc { /// The counterpart of `MaybeUninit` in Rust. /// /// It's impossible to make it exactly the same as in Rust. There are some key features that Rust's /// `MaybeUninit` relies on: /// /// 1. All objects in Rust are trivially relocatable (if you have the ownership). That means /// `assume_init` can safely copy bytes to another location. /// /// 2. Rust has ownership mechanism. `assume_init` takes ownership so that we cannot perform /// another `assume_init` on the same object. And thus the compiler is totally safe to put /// initialized object in the same place to save memory space. /// /// There is no way to detect whether a type is trivially relocatable in C++, since C++ has no /// borrow checker. A simple example is that any object contains a pointer may be self-referential. /// As a compromise, we try to find a way that semantically guarantees no move. One way is letting /// `assume_init` return a smart-pointer-like object. Obviously, this is also easy to exploit or /// mistakenly use it. A better approach is to assume that the object is initialized before /// destruction. For this approach, please use `rc::DeferredInit` instead. /// /// # Safety /// /// `assume_init` can only be called once, and must be called before initialized. /// /// # Example /// /// ``` /// rc::MaybeUninit<T> x{}; /// new (&x) T(args...); /// auto inited_x = x.assume_init(); /// ``` template<class T> class MaybeUninit { private: union { T obj; }; public: class Inited { private: T& ref; public: Inited(T& ref): ref(ref) {} operator T&() { return ref; } ~Inited() { ref.~T(); } }; MaybeUninit() {} MaybeUninit(T obj): obj(std::move(obj)) {} // TODO: How to deal with move/copy? MaybeUninit(const MaybeUninit&) = delete; MaybeUninit(MaybeUninit&&) = delete; MaybeUninit& operator=(const MaybeUninit&) = delete; MaybeUninit& operator=(MaybeUninit&&) = delete; ~MaybeUninit() {} Inited assume_init() { return {obj}; } }; } // namespace rc
27.278481
99
0.643619
QuarticCat
6244201ad137269771f4d939b6834cc73e7884d3
1,616
cpp
C++
CCC/ccc17s4.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
CCC/ccc17s4.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
CCC/ccc17s4.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; const int MM = 100001; int N, M, D, ans, par[MM], maxedge, cnt; inline int find(int x){ while(x != par[x]){ x = par[x]; par[x] = par[par[x]]; } return x; } struct edge{ int a, b, c, d; inline bool merge(){ int fa = find(a), fb = find(b); if(fa != fb){ par[fa] = fb; return 1; } return 0; } }; vector<edge> edges; int main(){ scanf("%d%d%d", &N, &M, &D); for(int i = 0,a,b,c; i < M; i++){ scanf("%d%d%d", &a, &b, &c); edges.push_back({a, b, c, i >= N-1}); } sort(edges.begin(), edges.end(), [](const edge &x, const edge &y){ if(x.c == y.c) return x.d < y.d; return x.c < y.c; }); for(int i = 1; i <= N; i++) par[i] = i; for(edge &e: edges){ if(e.merge()){ if(e.d) ans++; maxedge = e.c; if(++cnt == N-1) break; } } if(D){ for(int i = 1; i <= N; i++) par[i] = i; for(edge &e: edges){ int fa = find(e.a), fb = find(e.b); if(fa != fb){ if(e.c < maxedge || (e.c == maxedge && !e.d)) par[fa] = fb; else if(!e.d && e.c <= D){ ans--; break; } } } } printf("%d\n", ans); return 0; }
20.987013
71
0.329827
crackersamdjam
6255b9dbdcff4f28fd033c41ec17db5fa371fba5
646
cc
C++
data/test/cpp/6255b9dbdcff4f28fd033c41ec17db5fa371fba5load_libraries.cc
harshp8l/deep-learning-lang-detection
2a54293181c1c2b1a2b840ddee4d4d80177efb33
[ "MIT" ]
84
2017-10-25T15:49:21.000Z
2021-11-28T21:25:54.000Z
data/test/cpp/6255b9dbdcff4f28fd033c41ec17db5fa371fba5load_libraries.cc
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
5
2018-03-29T11:50:46.000Z
2021-04-26T13:33:18.000Z
data/test/cpp/6255b9dbdcff4f28fd033c41ec17db5fa371fba5load_libraries.cc
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
24
2017-11-22T08:31:00.000Z
2022-03-27T01:22:31.000Z
{ gSystem.Load("libgsl.so"); // gSystem.Load("libCLHEP-2.0.4.2.so"); gSystem.Load("libRIO.so"); gSystem.Load("libNet.so"); gSystem.Load("libHist.so"); gSystem.Load("libGraf.so"); gSystem.Load("libGraf3d.so"); gSystem.Load("libTree.so"); gSystem.Load("libRint.so"); gSystem.Load("libPostscript.so"); gSystem.Load("libMatrix.so"); gSystem.Load("libPhysics.so"); gSystem.Load("libMathCore.so"); gSystem.Load("libThread"); gSystem.Load("libBEM.so"); gSystem.Load("libGeometry.so"); gSystem.Load("libIO.so"); gSystem.Load("libField.so"); gSystem.Load("libDirect.so"); // gSystem.Load("libZHExpansion.so"); }
25.84
42
0.665635
harshp8l
625879c44e21dc785db346faf1ba006b0314751b
1,916
cpp
C++
GitGud/src/Platform/Windows/WindowsInput.cpp
Josef212/GitGud
3b0f8ec4fe2c19c9c64effcb8c56ba8e8ab519ba
[ "MIT" ]
null
null
null
GitGud/src/Platform/Windows/WindowsInput.cpp
Josef212/GitGud
3b0f8ec4fe2c19c9c64effcb8c56ba8e8ab519ba
[ "MIT" ]
null
null
null
GitGud/src/Platform/Windows/WindowsInput.cpp
Josef212/GitGud
3b0f8ec4fe2c19c9c64effcb8c56ba8e8ab519ba
[ "MIT" ]
null
null
null
#include "ggpch.h" #include "GitGud/Core/Input.h" #include "GitGud/Core/Application.h" #include "GitGud/Core/Window.h" #include <GLFW/glfw3.h> namespace GitGud { bool Input::IsKey(int keyCode) { auto window = static_cast<GLFWwindow*>(Application::Get().GetWindow().GetNativeWindow()); auto state = glfwGetKey(window, keyCode); return state == GLFW_PRESS || state == GLFW_REPEAT; } bool Input::IsKeyDown(int keyCode) { auto window = static_cast<GLFWwindow*>(Application::Get().GetWindow().GetNativeWindow()); auto state = glfwGetKey(window, keyCode); return state == GLFW_PRESS; } bool Input::IsKeyUp(int keyCode) { auto window = static_cast<GLFWwindow*>(Application::Get().GetWindow().GetNativeWindow()); auto state = glfwGetKey(window, keyCode); return state == GLFW_RELEASE; } bool Input::IsMouseButton(int button) { auto window = static_cast<GLFWwindow*>(Application::Get().GetWindow().GetNativeWindow()); auto state = glfwGetMouseButton(window, button); return state == GLFW_PRESS || state == GLFW_REPEAT; } bool Input::IsMouseButtonDown(int button) { auto window = static_cast<GLFWwindow*>(Application::Get().GetWindow().GetNativeWindow()); auto state = glfwGetMouseButton(window, button); return state == GLFW_PRESS; } bool Input::IsMouseButtonUp(int button) { auto window = static_cast<GLFWwindow*>(Application::Get().GetWindow().GetNativeWindow()); auto state = glfwGetMouseButton(window, button); return state == GLFW_RELEASE; } float Input::GetMouseX() { auto [x, y] = GetMousePos(); return (float)x; } float Input::GetMouseY() { auto [x, y] = GetMousePos(); return (float)y; } std::pair<float, float> Input::GetMousePos() { auto window = static_cast<GLFWwindow*>(Application::Get().GetWindow().GetNativeWindow()); double xpos, ypos; glfwGetCursorPos(window, &xpos, &ypos); return { (float)xpos, (float) ypos }; } }
26.246575
91
0.706159
Josef212
625ec381e9f2eea54cd4dd735892d3b63c54e482
538
cpp
C++
utils/minval.3.cpp
ivan100sic/competelib-snippets
e40170a63b37d92c91e2dfef08b2794e67ccb0b2
[ "Unlicense" ]
3
2022-01-17T01:56:05.000Z
2022-02-23T07:30:02.000Z
utils/minval.3.cpp
ivan100sic/competelib-snippets
e40170a63b37d92c91e2dfef08b2794e67ccb0b2
[ "Unlicense" ]
null
null
null
utils/minval.3.cpp
ivan100sic/competelib-snippets
e40170a63b37d92c91e2dfef08b2794e67ccb0b2
[ "Unlicense" ]
null
null
null
// Minimum accumulator #include <limits> #include <algorithm> using namespace std; /*snippet-begin*/ template<class T = int> struct minval { T x; minval(T x = numeric_limits<T>::max()) : x(x) {} T operator() () const { return x; } minval operator+ (const minval& b) const { return min(x, b.x); } minval& operator+= (const minval& b) { x = min(x, b.x); return *this; } }; /*snippet-end*/ int main() { minval<int> x = 4; x = x + 3; if (x() != 3) return 1; (x += 2) += 1; if (x() != 1) return 1; }
21.52
75
0.553903
ivan100sic
625f16aacc167e9d5dde894985a7f206b01d4d91
24,013
cpp
C++
src/util2019.cpp
atyre2/HABITAT
bbf231fcfe48cb11b27117266bfc85f427225414
[ "MIT" ]
null
null
null
src/util2019.cpp
atyre2/HABITAT
bbf231fcfe48cb11b27117266bfc85f427225414
[ "MIT" ]
2
2019-03-29T22:15:17.000Z
2019-03-29T22:15:50.000Z
src/util2019.cpp
atyre2/HABITAT
bbf231fcfe48cb11b27117266bfc85f427225414
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- // #include <vcl.h> // #pragma hdrstop #include <stdlib.h> #include <math.h> #include "mt19937.h" #include "matrices.h" #include "util2019.h" //--------------------------------------------------------------------------- #define NR_END 1 #define FREE_ARG char* #define ENDRUN '!' #define COMMENT '*' #define MAXOUTFILES 10 #define ALLFILES -1 #define MAKESTR(A,B,C) A ## B ## C /* singly linked list of parameter structures */ /* used by the multiple run functions */ struct varlist plist = {"parmlist",NULL,NOTYPE,NULL}; // void error(char error_text[]) // /* Drew Tyre's standard error handler */ // { // fprintf(stderr,"Drew Tyre run-time error...\n"); // fprintf(stderr,"%s\n",error_text); // fprintf(stderr,"...now exiting to system...\n"); // // ShowMessage(error_text); // exit(1); // } /* end function error */ // int getnextrun(char rerunname[]) // /* reads all meaningful lines in a rerun file, resets the named variables, // and returns non-zero if another rerun is to be performed. It handles the // opening of the rerun file itself. If the file does not exist, or if the // end of the file has been reached, then the function returns zero */ // { // static long int oldfilepos = 0L; // char buffer[LINELEN] = "\0", message[LINELEN] = "\0"; // unsigned int foundit = FALSE, check1 = 0, check2 = 0; // struct varlist *curparm; // FILE *rerunfile; // // if ((rerunfile = fopen(rerunname,"r")) == NULL) // { /* no rerun file exists, so return 0 to calling program */ // return 0; // } // // /* move to last position read */ // if (fseek(rerunfile,oldfilepos,SEEK_SET)) // { // error("Bad oldfilepos in getnewrun"); // } // // /* read in file one line at a time, discarding lines beginning with // COMMENT, and stopping when a line starts with ENDRUN or EOF // is reached */ // fgets(buffer,LINELEN,rerunfile); // while (!feof(rerunfile) && (buffer[0] != ENDRUN)) // { // if (buffer[0] != COMMENT) // { /* line contains a variable, so find the variable in plist */ // curparm = plist.next; // foundit = FALSE; // while (curparm != NULL) // { // check1 = 0; // check2 = 0; // while (buffer[check1++] == curparm->name[check2++]); // if (check1 > strlen(curparm->name)) // { /* found the variable in plist */ // foundit = TRUE; // switch(curparm->type) // { // case REAL : // sscanf(&buffer[check1]," %f",(float *) curparm->address); // break; // case DOUBLE : // sscanf(&buffer[check1]," %lf",(double *) curparm->address); // break; // case INTEGER : // sscanf(&buffer[check1]," %d",(int *) curparm->address); // break; // case LONGINT : // sscanf(&buffer[check1]," %ld",(long int *) curparm->address); // break; // case STRING : // sscanf(&buffer[check1]," %s",(char *) curparm->address); // break; // default : // strcat(message,"Bad parmtype in plist, "); // strcat(message,curparm->name); // error(message); // } // /* exit loop over plist */ // break; // } // /* skip to next entry in plist */ // curparm = curparm->next; // } /* end of loop over plist */ // // if (!foundit) // { // strcat(message,"Bad variable name "); // strcat(message,buffer); // strcat(message," in rerunfile"); // error(message); // } // } /* end if buffer[0] != comment */ // /* get next line in rerunfile */ // fgets(buffer,LINELEN,rerunfile); // // } /* end of while !feof && buffer[0] != comment */ // // /* remember where we reached in the file */ // oldfilepos = ftell(rerunfile); // // /* close the rerunfile, or the file handles overflow! */ // fclose(rerunfile); // // if (foundit) // { /* found something, so do another run */ // return 1; // } // else // { /* found nothing, so don't do another run */ // return 0; // } // // } /* end of getnewrun */ // // void rdsvar(FILE *infile, char varname[], void *address, int parmtype) // /* reads a variable of parmtype in from infile. Assumes that the next // line is the one that has the variable in question but will wrap once to // find the variable */ // { // int foundit, namelen, check1, check2, wrapped, gotit; // char buffer[LINELEN] = "\0"; /* for storing the line found in the file */ // char message[LINELEN] = "\0"; /* for storing errormessages */ // // namelen = strlen(varname); /* figure out how long the string is */ // foundit = FALSE; // wrapped = FALSE; // // do // { /* loop through file looking for varname */ // check1 = 0; // check2 = 0; // fgets(buffer,LINELEN,infile); // if (feof(infile) && !(wrapped)) // { /* reached the end of the file for the first time */ // wrapped = TRUE; // rewind(infile); // } // // while (buffer[check1++] == varname[check2++]); // if (check1 > (namelen-1)) // { /* varname matches upto namelen */ // foundit = TRUE; // // switch(parmtype) // { // case REAL : // gotit = sscanf(&buffer[check1]," %f", (float *) address); // break; // case DOUBLE : // gotit = sscanf(&buffer[check1]," %lf", (double *) address); // break; // case INTEGER : // gotit = sscanf(&buffer[check1]," %d", (int *) address); // break; // case LONGINT : // gotit = sscanf(&buffer[check1]," %ld", (long int *) address); // break; // case STRING : // gotit = sscanf(&buffer[check1]," %s", (char *) address); // break; // default : // strcat(message,"Bad parmtype in rdsvar, "); // strcat(message,varname); // error(message); // } /* end of switch(parmtype) */ // // if (!gotit) // { // strcat(message,"Unable to scan "); // strcat(message,varname); // error(message); // } /* end of if (!gotit) */ // // if (!addsvar(&plist,varname,address,parmtype)) // { /* unable to stick variable info into plist */ // strcat(message,"Unable to put "); // strcat(message,varname); // strcat(message," in plist"); // error(message); // } /* end of if !addsvar */ // } /* end of if (check1 > (namelen - 1)) */ // } /* end of do-while */ // while (!foundit && !(feof(infile) && wrapped)); // if (!foundit) // { // strcat(message, "Unable to find "); // strcat(message,varname); // error(message); // } // return; // } // int addsvar(struct varlist *list, char varname[],void *address,int parmtype) // /* adds a variable to a singly linked list plist. The list is used by the // functions rdsets and rdrun to update variables for multiple runs */ // { // // /* find the end of the list */ // while (list->next != NULL) list = list->next; // // /* allocate a new structure */ // list->next = (struct varlist *) malloc(sizeof(struct varlist)); // // /* check for success */ // if (list->next == NULL) return 0; // // /* set list to new structure */ // list = list->next; // // /* fill in the blanks */ // strcpy(list->name,varname); // list->address = address; // list->type = parmtype; // list->next = NULL; /* VERY IMPORTANT!!! */ // // return 1; /* successfully added variable */ // // } // // int dumpvars(struct varlist *list) // /* dumps the entire variable list */ // { // struct varlist *top, *next; // // /* can't deallocate the head of the list, so move to the next item */ // top = list->next; // // while (top != NULL) // { // next = top->next; // free(top); // top = next; // } // // return 0; /* successfully dumped list */ // // } // double lint(char tname[], struct rtable table[], double key) // /* This function performs a linear interpolation on a function stored in */ // /* table. key gives the independent variable that is to be used to */ // /* initiate the table lookup. lint assumes that key is sorted in */ // /* order in table */ // { // double result, slope; // int bottom, top; // // top = tsearch(tname, table, key); // bottom = top - 1; // // slope = (table[top].yval - table[bottom].yval) / // (table[top].xval - table[bottom].xval); // // result = (slope * (key - table[bottom].xval)) + table[bottom].yval; // return result; // } // // int tsearch(char tname[], struct rtable table[], double key) // /* This function searches table for the first value greater than or */ // /* equal to key, and returns the array index of that value */ // /* The function relies on the fact that the last key in the table */ // /* will be much larger than any key that will be passed. The function also */ // /* "remembers" which table it last searched, and where it reached in that */ // /* table. The static variables lasttable and lastreached are used for this. */ // /* This fact is used to speed up sequential searches on sorted tables. */ // { // int current, result; // static char lasttable[VNAMELEN]; // static int lastreached; // // if((strcmp(tname,lasttable)==0) && (table[lastreached].xval < key)) // { /* searching the same table as last time */ // current = lastreached; // } // else // { /* searching a new table, or a previous value */ // current = 0; // strcpy(lasttable,tname); // } // // /* loop through the table until the value is greater than or */ // /* equal the key */ // while (table[current++].xval < key); // // lastreached = current - 1; /* set the global variable lastreached */ // result = current - 1; /* return a 'pointer' to the previous entry */ // return result; // } // void rdtable(FILE *initfile, char searchstr[], struct rtable table[]) // /* Reads the x and y values from a table. Table has to have the */ // /* following format : */ // /* tablename tablelength */ // /* xvalue yvalue */ // /* ... ... */ // { // int i, arraysize; // char foundstr[80]; // // rdsvar(initfile,searchstr,&arraysize,INTEGER); // // if (arraysize > TABMAX) // { // fprintf(stderr, "table '%s' has too many lines\n", searchstr); // exit(1); // } // // for (i = 0; i <= (arraysize-1); i++) // { // fgets(foundstr,80,initfile); // sscanf(foundstr," %lf %lf",&table[i].xval,&table[i].yval); // } // // return; // } // void rdvector(FILE *initfile, char searchstr[], void *vector, int parmtype) // /* Reads vector values from a list. List has to have the */ // /* following format : */ // /* vectorname # of entries */ // /* value */ // /* ... */ // /*********************************************************************/ // /* NB!! assumes that sufficient space has been set aside in vector!! */ // /*********************************************************************/ // { // int i, vectorsize; // char foundstr[80]; // char message[LINELEN] = "\0"; /* for storing errormessages */ // // /* use rdsvar to find the start of the list */ // rdsvar(initfile,searchstr,&vectorsize,INTEGER); // // for (i = 0; i <= (vectorsize-1); i++) // { // fgets(foundstr,80,initfile); // switch(parmtype){ // case REAL : // sscanf(foundstr," %f", &(((float *) vector)[i])); // break; // case INTEGER : // sscanf(foundstr," %d", &(((int *) vector)[i])); // break; // case DOUBLE : // sscanf(foundstr," %lf", &(((double *) vector)[i])); // break; // default : // strcat(message,"Bad parmtype in rdvector , "); // strcat(message,searchstr); // error(message); // } /* end switch */ // } // // return; // } double chop(double x, int a, int b) { if (x < a) { x = a; } else if (x > b) { x = b; } return x; } /* end of chop */ // int round(double x) // { // int dum1, result; // double dum2; // // dum1 = x; // dum2 = x - dum1; // if(dum2 < 0.5) // { // result = floor(x); /* round x down */ // } // else // { // result = ceil(x); /* round x up */ // } // return result; // } /* end of round */ // /* Returns the probability of finding an odourconcentration of */ /* i individuals in a quadrat, */ /* given a mean of 'mean' and the aggregation coefficient 'k' */ /* Taken from Krebs 1989 Ecological Methodology, page 82 */ /* I assume that n hosts produce an odourconc of n */ double negbin(int i, double k, double mean) { double tmp1, tmp2, tmp3, result; tmp1 = exp(gammln(k + i)) / (factrl(i) * exp(gammln(k))); tmp2 = mean / (mean + k); tmp3 = k / (k + mean); if (tmp2 < 0) exit(425); //printf("Domain error: tmp2\n"); if (tmp3 < 0) exit(426); //printf("Domain error: tmp3\n"); result = tmp1 * pow(tmp2,(double)i) * pow(tmp3,k); return result; } /* Computes the log of Lanczos approximation to gamma function */ /* From Numerical recepies in C. error < 2E-10!! */ /* Some modifications were also taken from the numerical recipes book */ /* in fortran */ double gammln(double xx) { double czero = 1.000000000190015; double roottwopi = 2.5066282746310005; double cof[8] = {0, 76.1800917294716, -86.50532032941677, 24.01409824083091, -1.231739572450155, 0.1208650973866179E-2, -0.5395239384953E-5}; double x, series, tmp1, tmp2; int j; double result; x = xx - 1; tmp1 = x + 5.5; tmp2 = (x + 0.5) * log(tmp1) - tmp1; /* initialize the series with the first term */ series = czero; /* loop summs each coefficient divided by x+j */ for(j = 1;j <= 6;j ++) { series += cof[j] / (x + j); } result = tmp2 + log(roottwopi * series); /* return this value */ return result; } /* Returns the factorial of n as a doubleing point number */ double factrl(int n) { double result; int ntop = 4; /* This is the top of the table */ /* This is the table of results, fill up as required */ double a[33] = {1.0, 1.0, 2.0, 6.0, 24.0}; if(n < 0) { //printf("Negative factorial in routine factl\n"); exit(n); } if(n > 32) /* larger value than is in table, probably will overflow */ { result = exp(gammln(n + 1.0)); } else { while(ntop < n) /* fill in table up to required value */ { ntop ++; a[ntop] = a[ntop - 1] * ntop; } result = a[n]; /* return table value */ } return result; } /* This function calculates the probability that there are i hosts on a plant, given the plant is occupied */ double con_negbin(int i, double k, double mean) { double result, b, a; a = negbin(i,k,mean); b = 1-negbin(0,k,mean); result = a/b; return result; } // /* Returns a normally distributed deviate with zero mean and unit variance, // using ran1(idum) as the source of uniform deviates. Taken from // numerical recipes book in c, p.289 */ // // float gasdev(void) // { // /* float ran3(long *idum); */ // static int iset=0; // static float gset; // float fac, rsq, v1, v2, temp; // // /* We don't have an extra deviate handy, so pick 2 uniform numbers in // the square extending from -1 to +1 in each direction, see if they // are in the unit circle, and if they are not, try again.*/ // if (iset == 0){ // do{ // v1 = 2.0*rand0to1()-1.0; // v2 = 2.0*rand0to1()-1.0; // rsq=v1*v1+v2*v2; // }while (rsq >= 1.0 ||rsq == 0.0); // // temp = -2.0*log(rsq)/rsq; // if (temp >= 0.0) fac = sqrt(temp); // else { // printf("error in gasdev\n"); // } // /* Now make the Box-Muller transformation to get 2 normal deviates. // Return one and save the other for the next time. */ // gset = v1*fac; // iset=1; /*set flag */ // return v2*fac; // } else{ // /* We have an extra deviate handy, so unset the flag, and return it.*/ // iset = 0; // return gset; // } // } // // int randompick(double prob[], int maxint) // { // double x, sumprob = 0; // int z = 0, choose = 0, i = -1; // // /* x determines the target variable */ // x = genrand(); // // do // { // i++; // sumprob += prob[i]; // if (x <= sumprob) // { // choose = i; // z = 1; // } // } while (!z); // // if (choose > maxint){ // fprintf(stderr,"choose: %d maxint: %d\n",choose,maxint); // for (i = 0; i<=choose; i++) fprintf(stderr,"%d %f\n",i,prob[i]); // fprintf(stderr,"bad probability sum in randompick!\n"); // exit(1); // } // // return choose; // } // float **matrix(long nrl, long nrh, long ncl, long nch) // /* allocate a float matrix with subscript range m[nrl..nrh][ncl..nch] */ // { // long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; // float **m; // // /* allocate pointers to rows */ // m=(float **) malloc((size_t)((nrow+NR_END)*sizeof(float*))); // if (!m) exit(1); // error("allocation failure 1 in matrix()"); // m += NR_END; // m -= nrl; // // /* allocate rows and set pointers to them */ // m[nrl]=(float *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(float))); // if (!m[nrl]) exit(1); //error("allocation failure 2 in matrix()"); // m[nrl] += NR_END; // m[nrl] -= ncl; // // for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; // // /* return pointer to array of pointers to rows */ // return m; // } // // void free_matrix(float **m, long nrl, long nrh, long ncl, long nch) // /* free a float matrix allocated by matrix() */ // { // free((FREE_ARG) (m[nrl]+ncl-NR_END)); // free((FREE_ARG) (m+nrl-NR_END)); // } float *vector(long nl, long nh) /* allocate a float vector with subscript range v[nl..nh] */ { float *v; v=(float *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(float))); if (!v) exit(1); //error("allocation failure in vector()"); return v-nl+NR_END; } void free_vector(float *v, long nl, long nh) /* free a float vector allocated with vector() */ { free((FREE_ARG) (v+nl-NR_END)); } void hqr(float **a, int n, float wr[], float wi[]) { int nn,m,l,k,j,its,i,mmin; float z,y,x,w,v,u,t,s,r,q,p,anorm; anorm=fabs(a[1][1]); for (i=2;i<=n;i++) for (j=(i-1);j<=n;j++) anorm += fabs(a[i][j]); nn=n; t=0.0; while (nn >= 1) { its=0; do { for (l=nn;l>=2;l--) { s=fabs(a[l-1][l-1])+fabs(a[l][l]); if (s == 0.0) s=anorm; if ((float)(fabs(a[l][l-1]) + s) == s) break; } x=a[nn][nn]; if (l == nn) { wr[nn]=x+t; wi[nn--]=0.0; } else { y=a[nn-1][nn-1]; w=a[nn][nn-1]*a[nn-1][nn]; if (l == (nn-1)) { p=0.5*(y-x); q=p*p+w; z=sqrt(fabs(q)); x += t; if (q >= 0.0) { z=p+SIGN(z,p); wr[nn-1]=wr[nn]=x+z; if (z) wr[nn]=x-w/z; wi[nn-1]=wi[nn]=0.0; } else { wr[nn-1]=wr[nn]=x+p; wi[nn-1]= -(wi[nn]=z); } nn -= 2; } else { if (its == 30) exit(663); //error("Too many iterations in hqr"); if (its == 10 || its == 20) { t += x; for (i=1;i<=nn;i++) a[i][i] -= x; s=fabs(a[nn][nn-1])+fabs(a[nn-1][nn-2]); y=x=0.75*s; w = -0.4375*s*s; } ++its; for (m=(nn-2);m>=l;m--) { z=a[m][m]; r=x-z; s=y-z; p=(r*s-w)/a[m+1][m]+a[m][m+1]; q=a[m+1][m+1]-z-r-s; r=a[m+2][m+1]; s=fabs(p)+fabs(q)+fabs(r); p /= s; q /= s; r /= s; if (m == l) break; u=fabs(a[m][m-1])*(fabs(q)+fabs(r)); v=fabs(p)*(fabs(a[m-1][m-1])+fabs(z)+fabs(a[m+1][m+1])); if ((float)(u+v) == v) break; } for (i=m+2;i<=nn;i++) { a[i][i-2]=0.0; if (i != (m+2)) a[i][i-3]=0.0; } for (k=m;k<=nn-1;k++) { if (k != m) { p=a[k][k-1]; q=a[k+1][k-1]; r=0.0; if (k != (nn-1)) r=a[k+2][k-1]; if ((x=fabs(p)+fabs(q)+fabs(r)) != 0.0) { p /= x; q /= x; r /= x; } } if ((s=SIGN(sqrt(p*p+q*q+r*r),p)) != 0.0) { if (k == m) { if (l != m) a[k][k-1] = -a[k][k-1]; } else a[k][k-1] = -s*x; p += s; x=p/s; y=q/s; z=r/s; q /= p; r /= p; for (j=k;j<=nn;j++) { p=a[k][j]+q*a[k+1][j]; if (k != (nn-1)) { p += r*a[k+2][j]; a[k+2][j] -= p*z; } a[k+1][j] -= p*y; a[k][j] -= p*x; } mmin = nn<k+3 ? nn : k+3; for (i=l;i<=mmin;i++) { p=x*a[i][k]+y*a[i][k+1]; if (k != (nn-1)) { p += z*a[i][k+2]; a[i][k+2] -= p*r; } a[i][k+1] -= p*q; a[i][k] -= p; } } } } } } while (l < nn-1); } } #define CON 1.4 #define CON2 (CON*CON) #define BIG 1.0e30 #define NTAB 10 #define SAFE 2.0 float dfridr(float (*func)(float), float x, float h, float *err) { int i,j; float errt,fac,hh,**a,ans; if (h == 0.0) exit(754); //error("h must be nonzero in dfridr."); a=matrix(1,NTAB,1,NTAB); hh=h; a[1][1]=((*func)(x+hh)-(*func)(x-hh))/(2.0*hh); *err=BIG; for (i=2;i<=NTAB;i++) { hh /= CON; a[1][i]=((*func)(x+hh)-(*func)(x-hh))/(2.0*hh); fac=CON2; for (j=2;j<=i;j++) { a[j][i]=(a[j-1][i]*fac-a[j-1][i-1])/(fac-1.0); fac=CON2*fac; errt=FMAX(fabs(a[j][i]-a[j-1][i]),fabs(a[j][i]-a[j-1][i-1])); if (errt <= *err) { *err=errt; ans=a[j][i]; } } if (fabs(a[i][i]-a[i-1][i-1]) >= SAFE*(*err)) { free_matrix(a,1,NTAB,1,NTAB); return ans; } } free_matrix(a,1,NTAB,1,NTAB); return ans; } #undef CON #undef CON2 #undef BIG #undef NTAB #undef SAFE /* following 3 routines do romberg integration on closed intervals */ void polint(float xa[], float ya[], int n, float x, float *y, float *dy) { int i,m,ns=1; float den,dif,dift,ho,hp,w; float *c,*d; dif=fabs(x-xa[1]); c=vector(1,n); d=vector(1,n); for (i=1;i<=n;i++) { if ( (dift=fabs(x-xa[i])) < dif) { ns=i; dif=dift; } c[i]=ya[i]; d[i]=ya[i]; } *y=ya[ns--]; for (m=1;m<n;m++) { for (i=1;i<=n-m;i++) { ho=xa[i]-x; hp=xa[i+m]-x; w=c[i+1]-d[i]; if ( (den=ho-hp) == 0.0) exit(810); // error("Error in routine polint"); den=w/den; d[i]=hp*den; c[i]=ho*den; } *y += (*dy=(2*ns < (n-m) ? c[ns+1] : d[ns--])); } free_vector(d,1,n); free_vector(c,1,n); } #define FUNC(x) ((*func)(x)) float trapzd(float (*func)(float), float a, float b, int n) { float x,tnm,sum,del; static float s; int it,j; if (n == 1) { return (s=0.5*(b-a)*(FUNC(a)+FUNC(b))); } else { for (it=1,j=1;j<n-1;j++) it <<= 1; tnm=it; del=(b-a)/tnm; x=a+0.5*del; for (sum=0.0,j=1;j<=it;j++,x+=del) sum += FUNC(x); s=0.5*(s+(b-a)*sum/tnm); return s; } } #undef FUNC #define EPS 1.0e-6 #define JMAX 20 #define JMAXP (JMAX+1) #define K 5 float qromb(float (*func)(float), float a, float b) { void polint(float xa[], float ya[], int n, float x, float *y, float *dy); float trapzd(float (*func)(float), float a, float b, int n); float ss,dss; float s[JMAXP+1],h[JMAXP+1]; int j; h[1]=1.0; for (j=1;j<=JMAX;j++) { s[j]=trapzd(func,a,b,j); if (j >= K) { polint(&h[j-K],&s[j-K],K,0.0,&ss,&dss); if (fabs(dss) < EPS*fabs(ss)) return ss; } s[j+1]=s[j]; h[j+1]=0.25*h[j]; } exit(866); //error("Too many steps in routine qromb"); return 0.0; } #undef EPS #undef JMAX #undef JMAXP #undef K
27.4121
85
0.510848
atyre2
62602c0f0b94280fc77fb42cb3b9d0ec98d76955
3,207
cpp
C++
BZOJ/BZOJ2780.cpp
xehoth/OnlineJudgeCodes
013d31cccaaa1d2b6d652c2f5d5d6cb2e39884a7
[ "Apache-2.0" ]
7
2017-09-21T13:20:05.000Z
2020-03-02T03:03:04.000Z
BZOJ/BZOJ2780.cpp
xehoth/OnlineJudgeCodes
013d31cccaaa1d2b6d652c2f5d5d6cb2e39884a7
[ "Apache-2.0" ]
null
null
null
BZOJ/BZOJ2780.cpp
xehoth/OnlineJudgeCodes
013d31cccaaa1d2b6d652c2f5d5d6cb2e39884a7
[ "Apache-2.0" ]
3
2019-01-05T07:02:57.000Z
2019-06-13T08:23:13.000Z
#include <bits/stdc++.h> namespace IO { inline char read() { static const int IN_LEN = 1000000; static char buf[IN_LEN], *s, *t; s == t ? t = (s = buf) + fread(buf, 1, IN_LEN, stdin) : 0; return s == t ? -1 : *s++; } template <typename T> inline bool read(T &x) { static char c; static bool iosig; for (c = read(), iosig = false; !isdigit(c); c = read()) { if (c == -1) return false; c == '-' ? iosig = true : 0; } for (x = 0; isdigit(c); c = read()) x = x * 10 + (c ^ '0'); iosig ? x = -x : 0; return true; } inline int read(char *buf) { register int s = 0; register char c; while (c = read(), isspace(c) && c != -1) ; if (c == -1) { *buf = 0; return -1; } do buf[s++] = c; while (c = read(), !isspace(c) && c != -1); buf[s] = 0; return s; } const int OUT_LEN = 1000000; char obuf[OUT_LEN], *oh = obuf; inline void print(char c) { oh == obuf + OUT_LEN ? (fwrite(obuf, 1, OUT_LEN, stdout), oh = obuf) : 0; *oh++ = c; } template <typename T> inline void print(T x) { static int buf[30], cnt; if (x == 0) { print('0'); } else { x < 0 ? (print('-'), x = -x) : 0; for (cnt = 0; x; x /= 10) buf[++cnt] = x % 10 | 48; while (cnt) print((char)buf[cnt--]); } } inline void flush() { fwrite(obuf, 1, oh - obuf, stdout); } } // namespace IO namespace { using namespace IO; const int MAX_SIGMA = 3; const int MAXN = 60010; struct Node { int c[MAX_SIGMA], fail, pos; } d[MAXN + 1]; int cur, last; int l[MAXN + 1], r[MAXN + 1], same[MAXN + 1], idx; int vis[MAXN + 1], in[MAXN + 1], cnt[MAXN + 1]; char s[100010 + 1], buf[MAXN + 1]; inline void add(const char *s) { for (last = 0; *s; s++) { if (!d[last].c[*s - 'a']) d[last].c[*s - 'a'] = ++cur; last = d[last].c[*s - 'a']; } } inline void check(char c) { for (register int p = d[last].c[c]; p && vis[p] != idx; vis[p] = idx, p = d[p].fail) { if (d[p].pos && in[d[p].pos] != idx) cnt[d[p].pos]++, in[d[p].pos] = idx; } last = d[last].c[c]; } inline void build() { static std::queue<int> q; q.push(0); for (register int p, v; !q.empty();) { p = q.front(), q.pop(); for (register int i = 0; i < MAX_SIGMA; i++) { if (v = d[p].c[i]) { if (p) d[v].fail = d[d[p].fail].c[i]; q.push(v); } else { d[p].c[i] = d[d[p].fail].c[i]; } } } } inline void solve() { register int n, m; read(n), read(m); for (register int i = 1; i <= n; i++) l[i] = r[i - 1] + 1, r[i] = r[i - 1] + read(s + l[i]); for (register int i = 1; i <= m; i++) { read(buf), add(buf); d[last].pos ? same[i] = d[last].pos : d[last].pos = i; } build(); for (register int i = 1; i <= n; i++) { idx++, last = 0; for (register int j = l[i]; j <= r[i]; j++) check(s[j] - 'a'); } for (register int i = 1; i <= m; i++) print(cnt[same[i] ? same[i] : i]), print('\n'); flush(); } } // namespace int main() { solve(); return 0; }
23.408759
77
0.455566
xehoth
62613226c0ef2b43ecb6ec9f8c8a941374abf6f4
445
cpp
C++
glfw3_app/nesemu/tools.cpp
hirakuni45/glfw3_app
d9ceeef6d398229fda4849afe27f8b48d1597fcf
[ "BSD-3-Clause" ]
9
2015-09-22T21:36:57.000Z
2021-04-01T09:16:53.000Z
glfw3_app/nesemu/tools.cpp
hirakuni45/glfw3_app
d9ceeef6d398229fda4849afe27f8b48d1597fcf
[ "BSD-3-Clause" ]
null
null
null
glfw3_app/nesemu/tools.cpp
hirakuni45/glfw3_app
d9ceeef6d398229fda4849afe27f8b48d1597fcf
[ "BSD-3-Clause" ]
2
2019-02-21T04:22:13.000Z
2021-03-02T17:24:32.000Z
//=====================================================================// /*! @file @brief Emulator Tools クラス @n Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include "tools.hpp" gui::widget_terminal* emu::tools::terminal_; extern "C" { int emu_log(const char* text) { emu::tools::put(text); return 0; } };
20.227273
74
0.408989
hirakuni45
6264f8e9d3635d9a6d7e0fced804644032b46d42
739
hpp
C++
file_util/tests/fixtures.hpp
ScottGarman/leatherman
7c1407c29b056148e6332dabf4017ca50f064a94
[ "Apache-2.0" ]
55
2015-08-27T13:17:42.000Z
2022-02-07T15:19:59.000Z
file_util/tests/fixtures.hpp
ScottGarman/leatherman
7c1407c29b056148e6332dabf4017ca50f064a94
[ "Apache-2.0" ]
236
2015-02-23T23:50:10.000Z
2021-09-01T18:09:12.000Z
file_util/tests/fixtures.hpp
ScottGarman/leatherman
7c1407c29b056148e6332dabf4017ca50f064a94
[ "Apache-2.0" ]
88
2015-02-23T22:40:27.000Z
2022-02-07T15:19:59.000Z
#pragma once #include <string> #include <boost/filesystem/path.hpp> /** * Class to create a temporary directory with a unique name * and destroy it once it is no longer needed. * */ class temp_directory { public: temp_directory(); ~temp_directory(); std::string const& get_dir_name() const; private: std::string dir_name; }; /** * Class to create a temporary file with a unique name and * destroy it once it is no longer needed. */ class temp_file { public: temp_file(std::string const& content); ~temp_file(); std::string const& get_file_name() const; private: std::string file_name; }; /** Generates a unique string for use as a file path. */ boost::filesystem::path unique_fixture_path();
18.948718
59
0.690122
ScottGarman
62650a65e609cedbe8ee98bbc962ff63c7f98e28
1,391
cpp
C++
targets/simple_router/primitives.cpp
edgarcosta92/behavioral-model
de9ec3ddc45c2b210681a7675c0bded6e56ec9d3
[ "Apache-2.0" ]
390
2015-10-13T05:22:51.000Z
2022-03-30T19:18:14.000Z
targets/simple_router/primitives.cpp
edgarcosta92/behavioral-model
de9ec3ddc45c2b210681a7675c0bded6e56ec9d3
[ "Apache-2.0" ]
919
2015-08-10T17:50:50.000Z
2022-03-31T17:46:07.000Z
targets/simple_router/primitives.cpp
edgarcosta92/behavioral-model
de9ec3ddc45c2b210681a7675c0bded6e56ec9d3
[ "Apache-2.0" ]
351
2015-09-18T03:32:32.000Z
2022-03-31T03:56:38.000Z
/* Copyright 2013-present Barefoot Networks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Antonin Bas (antonin@barefootnetworks.com) * */ #include <bm/bm_sim/actions.h> #include <bm/bm_sim/core/primitives.h> template <typename... Args> using ActionPrimitive = bm::ActionPrimitive<Args...>; using bm::Data; using bm::Field; using bm::Header; class modify_field : public ActionPrimitive<Field &, const Data &> { void operator ()(Field &f, const Data &d) { bm::core::assign()(f, d); } }; REGISTER_PRIMITIVE(modify_field); class add_to_field : public ActionPrimitive<Field &, const Data &> { void operator ()(Field &f, const Data &d) { f.add(f, d); } }; REGISTER_PRIMITIVE(add_to_field); class drop : public ActionPrimitive<> { void operator ()() { get_field("standard_metadata.egress_spec").set(511); } }; REGISTER_PRIMITIVE(drop);
25.759259
75
0.71028
edgarcosta92
6266e72f69150a43924556ec15b610e0c9ce2ee3
3,530
cpp
C++
ObjOrientedProgramming/Ticket/Ticket/TicketDemo.cpp
jhbrian/Learning-Progress
de7b9d037aa0b5e1ec8199b4eabfcd1e24c73bcb
[ "MIT" ]
null
null
null
ObjOrientedProgramming/Ticket/Ticket/TicketDemo.cpp
jhbrian/Learning-Progress
de7b9d037aa0b5e1ec8199b4eabfcd1e24c73bcb
[ "MIT" ]
null
null
null
ObjOrientedProgramming/Ticket/Ticket/TicketDemo.cpp
jhbrian/Learning-Progress
de7b9d037aa0b5e1ec8199b4eabfcd1e24c73bcb
[ "MIT" ]
null
null
null
//**************************************************************************************************** //Program Name: Tickets //Author: Jin Han Ho //IDE Used: Visual Studio 2019 //Program description: This program will show the status of ticket that is issued the police in a day //**************************************************************************************************** #include "Police.h" #include "Ticket.h" #include <iostream> #include <vector> #include <fstream> #include <string> #include <iomanip> using namespace std; //************************************************************************************ //Function name: Print1 //Purpose: Print out the daily report before payments are done //List of parameters: vector<Ticket> TicketInfo, double sum //Returns: no return variable //Return type: void //************************************************************************************ //************************************************************************************ //Function name: Print2 //Purpose: Print out the daily report after payments are done //List of parameters: vector<Ticket> TicketInfo, double sum, double sum2, int counter //Returns: no return variable //Return type: void //************************************************************************************ void Print1(vector<Ticket> TicketInfo, double &sum) { cout << "Daily ticket report: " << endl; for (int i = 0; i < TicketInfo.size(); i++) { TicketInfo.at(i).printTicket(); sum += TicketInfo.at(i).getFine(); } cout << "Number of tickets: " << TicketInfo.size() << endl; cout << "Revenues due: $" << fixed << setprecision(2) << sum << endl << endl; } void Print2(vector<Ticket> TicketInfo, double &sum, double &sum2, int counter) { cout << "Payment processing complete; new status report: " << endl; for (int i = 0; i < TicketInfo.size(); i++) { TicketInfo.at(i).printTicket(); TicketInfo.at(i).getStatus() ? counter++ //counter + 1 if the status is paid; : sum2 += TicketInfo.at(i).getFine(); } cout << "Number paid: " << counter << " (Total: $" << (sum - sum2) << ")" << endl; //Total due before payment minus unpaid cout << "Number unpaid: " << TicketInfo.size() - counter << " (Total: $" << fixed << setprecision(2) << sum2 << ")" << endl; } int main() { vector<Ticket>TicketInfo; ifstream fin; int tnum, badgenum, counter = 0; double due, sum = 0, sum2 = 0; bool pay; string vio, name; fin.open("tickets.txt"); while (fin >> vio) { fin >> tnum; fin >> due; fin >> name; fin >> badgenum; TicketInfo.push_back(Ticket(vio, tnum, due, name, badgenum)); } Print1(TicketInfo, sum); //print first report fin.close(); fin.open("payments.txt"); int i = 0; while (fin >> pay) { TicketInfo.at(i).setStatus(pay); //setting new payment status i++; } Print2(TicketInfo, sum, sum2, counter); //print second report fin.close(); cout << endl << endl << endl; cout << "I attest that this code is my original programming work, and that I received" << endl << "no help creating it.I attest that I did not copy this code or any portion of this" << endl << "code from any source." << endl; return 0; }
36.020408
103
0.490935
jhbrian
62671ee1cbacfc0750822aa3e74857d8a24f97a9
10,662
cpp
C++
example/SVG_text_width_height.cpp
pabristow/svg_plot
59e06b752acc252498e0ddff560b01fb951cb909
[ "BSL-1.0" ]
24
2016-03-09T03:23:06.000Z
2021-01-12T14:02:07.000Z
example/SVG_text_width_height.cpp
pabristow/svg_plot
59e06b752acc252498e0ddff560b01fb951cb909
[ "BSL-1.0" ]
11
2018-03-05T14:39:48.000Z
2021-08-22T09:00:33.000Z
example/SVG_text_width_height.cpp
pabristow/svg_plot
59e06b752acc252498e0ddff560b01fb951cb909
[ "BSL-1.0" ]
10
2016-11-04T14:36:04.000Z
2020-07-17T08:12:03.000Z
/*! \brief Demonstrates actual length of text displayed as SVG. Shows warning from too much compression using text_length. And also shows use of text_length can undercompress to space out glyphs to become unreadable. Font Support for Unicode Characters https://www.fileformat.info/info/unicode/font/index.htm Shows aspect ratio for font size 10 varys from 0.55 to 0.4 no of chars that fit the 1000 image varies from 120 letter M units (em width) - the widest 340 letter i - the narrowest random letters from 180 to 240 aspect ratios lucida sans unicode 0.49 verdana 0.48 arial 0.42 Tme New Roman 0.4 in svg_style.hpp static const fp_type aspect_ratio = 0.6; //!< aspect_ratio is a guess at average height to width of font. Examples of using function plot.title_text_length(1000); so squeeze or expand title. */ // svg_text_width_height.cpp // Copyright Paul A. Bristow 2018, 2020 // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) //#include <boost/svg_plot/svg_style.hpp> #include <boost/svg_plot/svg_2d_plot.hpp> // using namespace boost::svg; #include <boost/svg_plot/show_2d_settings.hpp> #include <iostream> #include <string> int main() { using namespace boost::svg; // Very convenient to allow easy access to colors, data-point marker shapes and other svg_plot items. try { // try'n'catch blocks are needed to ensure error messages from any exceptions are shown. svg_2d_plot my_2d_plot; // Construct a plot with all the default constructor values. // Containers to hold some data. std::map<const double, double> my_data_0; my_data_0[0.0] = 0.0; my_data_0[10.0] = 10.0; std::string a_title(340, 'i'); // my_2d_plot // Nearly all default settings. .size(1000, 200) .title("&#x3A9;") // 116 l fill 1000 exactly 465 ll .title("&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;") // 116 &#x3A9; fill 1000 exactly 465 &#x3A9;&#x3A9; // .title("&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;&#x3A9;") // 116 l fill 1000 exactly 465 ll // .title("llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll") // 116 l fill 1000 exactly 465 ll // .title("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM") // 116 M fill 1000 exactly 465 mm // So for font width = 20 (type normal) width of an M is 1000/ // .title("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM") // 100 M width 400 mm // .title("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii") // 116 i width 160 mm .title_on(true) // .title(a_title) // std::string a_title(116, 'W'); Fills 1000 completely like 'M' // .title("The Quick brown Fox jumped over the lazy dog. The Quick brown Fox jumped over the lazy dog.The Quick brown Fox jumped over the lazy dog. The Quick brown Fox jumped over the lazy dog.") // 181 'mixed' chars 10 font size almost fills (435 mm) 1000 width so each char is 1000 / 181 = 5.5 svg unit aspect ratio = 0.55 // and triggers warning message: // "width 1092 (SVG units) may overflow plot image! // (Reduce font size from 10, or number of characters from 182, or increase image size from 1000)." // .title("The Quick brown Fox jumped over the lazy dog. The Quick brown Fox jumped over the lazy dog.The Quick brown Fox jumped over the lazy dog. The Quick brown Fox jumped over the lazy dog. The quick b") // Fills exactly char count 194 = 470 mm 1000/194 = 5.15, aspect ratio = 10/5.16 = 0.516 // so a string of 194 * 0.516 = 1000 // .title(a_title) // std::string a_title(340, 'i'); // will exactly, char count 340 //.title_font_family("Lucida sans Unicode") //.title("Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is") // default Lucida sans Unicode 204 chars fill 1000 pixels, so aspect ratio = 1000 /204 = 4.9 div 10 = 0.49 //.title("Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is time time for all good men to come to the") //But 204 chars Times New Roman is only 370 mm long //.title("Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid") //// 249 chars fit. So aspect ratio = 1000/250 = 4, so for 10 point aspect ratio = 0.4 //.title_font_family("Arial") //.title("Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the time for all good men") // Arial 10 point 240 chars so aspect ratio = 1000/240 = 0.42 //.title_font_family("verdana") // verdana 10 point 208 chars so aspect ratio = 1/10 * 1000/208 = 0.48 // Example of using all the text styles: // .title("Now is the time for all good men to come to the aid of the party.") .title_font_size(10) //.title_font_family("Arial") .title_font_family("Times new roman") // .title_font_style("italic") // .title_font_weight("bold") // .title_font_stretch("narrower") // May have no effect here. // .title_font_decoration("underline") .title_text_length(1500) // Force into an arbitrary chosen fixed width 1500 = more than full width of image so spaced out. // and overflowing chars are lost at both end. .title_text_length(1000) // Force into an arbitrary chosen fixed width 1000 = full width of image. // .title_text_length(800) // Force into an arbitrary chosen fixed width very tight so letter M just touching. // This is very long title test: // .title("Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the ") // if no text_length() then get warning // font size = 5 is far too small and stretch to fit // font size = 20 makes all the letters on top of each other. // font size = 12 is just readable with text_length 1000. // font size = 13 is too close and some glyphs collide with text_length 1000. /* Error message example: title style text_style(13, "Arial", "italic", "bold", "", "underline", 1000), text_length = 1000 Title "Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the " estimated width 1630.2 (SVG units) may overflow plot image or or over-compress text! (Reduce font size from 13, or number of characters from 209, or increase image size from 1000). */ // Squash Factor 1.6 chosen on this basis, but might be different for other fonts? .plot(my_data_0) ; // Show just couple of text styles //std::cout << "title family " << my_2d_plot.title_font_family() << ", size " << my_2d_plot.title_font_size() << std::endl; // title family Lucida Sans Unicode, size 10 std::cout << "title style " << my_2d_plot.title_style() // title style text_style(12, "Arial", "italic", "bold", "narrower", "underline", 1000) << ", text_length = " << my_2d_plot.title_text_length() // text_length = 1000 << std::endl; // Title text "Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the " // with an estimated width 1630.2 (SVG units) may overflow plot space 1000 or over-compress text with compression ratio 1.6302. // Reduce font size from 13, or number of characters from 209, or increase image size from 1000?. my_2d_plot.write("./svg_text_width_height.svg"); // Plot output to file. // Output contains for the title: //<g id="title"> // <text x="500" y="18" text-anchor="middle" font-size="12" //font-family="Arial" font-style="italic" font-weight="bold" font-stretch="narrower" // text-decoration="underline" // textLength="1e+03"> <<<<<<<< note how is forced to use the exact (estimated) width. // Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of the party. Now is the // </text> //</g> } catch(const std::exception& e) { std::cout << "\n""Message from thrown exception was:\n " << e.what() << std::endl; } return 0; } // int main()
66.6375
881
0.679422
pabristow
626d06dcabb8411965addf56d6ba8c2c70b666ff
2,559
hh
C++
tests/Titon/Route/Annotation/RouteTest.hh
ciklon-z/framework
cbf44729173d3a83b91a2b0a217c6b3827512e44
[ "BSD-2-Clause" ]
206
2015-01-02T20:01:12.000Z
2021-04-15T09:49:56.000Z
tests/Titon/Route/Annotation/RouteTest.hh
ciklon-z/framework
cbf44729173d3a83b91a2b0a217c6b3827512e44
[ "BSD-2-Clause" ]
44
2015-01-02T06:03:43.000Z
2017-11-20T18:29:06.000Z
tests/Titon/Route/Annotation/RouteTest.hh
titon/framework
cbf44729173d3a83b91a2b0a217c6b3827512e44
[ "BSD-2-Clause" ]
27
2015-01-03T05:51:29.000Z
2022-02-21T13:50:40.000Z
<?hh namespace Titon\Route\Annotation; use Titon\Annotation\Reader; use Titon\Test\Stub\Route\RouteAnnotatedStub; use Titon\Test\TestCase; class RouteTest extends TestCase { public function testParamsAreSetOnRouteAnnotation(): void { $reader = new Reader(new RouteAnnotatedStub()); // Class $class = $reader->getClassAnnotation('Route'); invariant($class instanceof Route, 'Must be a Route annotation.'); $this->assertEquals('parent', $class->getKey()); $this->assertEquals('/controller', $class->getPath()); $this->assertEquals(Vector {}, $class->getMethods()); $this->assertEquals(Vector {}, $class->getFilters()); $this->assertEquals(Map {}, $class->getPatterns()); // Foo $foo = $reader->getMethodAnnotation('foo', 'Route'); invariant($foo instanceof Route, 'Must be a Route annotation.'); $this->assertEquals('foo', $foo->getKey()); $this->assertEquals('/foo', $foo->getPath()); $this->assertEquals(Vector {}, $foo->getMethods()); $this->assertEquals(Vector {}, $foo->getFilters()); $this->assertEquals(Map {}, $foo->getPatterns()); // Bar $bar = $reader->getMethodAnnotation('bar', 'Route'); invariant($bar instanceof Route, 'Must be a Route annotation.'); $this->assertEquals('bar', $bar->getKey()); $this->assertEquals('/bar', $bar->getPath()); $this->assertEquals(Vector {'post'}, $bar->getMethods()); $this->assertEquals(Vector {}, $bar->getFilters()); $this->assertEquals(Map {}, $bar->getPatterns()); // Baz $baz = $reader->getMethodAnnotation('baz', 'Route'); invariant($baz instanceof Route, 'Must be a Route annotation.'); $this->assertEquals('baz', $baz->getKey()); $this->assertEquals('/baz', $baz->getPath()); $this->assertEquals(Vector {'get'}, $baz->getMethods()); $this->assertEquals(Vector {'auth', 'guest'}, $baz->getFilters()); $this->assertEquals(Map {}, $baz->getPatterns()); // Qux $qux = $reader->getMethodAnnotation('qux', 'Route'); invariant($qux instanceof Route, 'Must be a Route annotation.'); $this->assertEquals('qux', $qux->getKey()); $this->assertEquals('/qux', $qux->getPath()); $this->assertEquals(Vector {'put', 'post'}, $qux->getMethods()); $this->assertEquals(Vector {}, $qux->getFilters()); $this->assertEquals(Map {'id' => '[1-8]+'}, $qux->getPatterns()); } }
36.557143
74
0.593591
ciklon-z
626d1e0ce0878f823a4c70d83bcd085c1872a7db
598
cpp
C++
libraries/Controller/Controller_Test_Snippet.cpp
devshop2019/MachTestHangDaNang
297161fd2ac84b3e4b867f2007efad4cf503012e
[ "MIT" ]
null
null
null
libraries/Controller/Controller_Test_Snippet.cpp
devshop2019/MachTestHangDaNang
297161fd2ac84b3e4b867f2007efad4cf503012e
[ "MIT" ]
null
null
null
libraries/Controller/Controller_Test_Snippet.cpp
devshop2019/MachTestHangDaNang
297161fd2ac84b3e4b867f2007efad4cf503012e
[ "MIT" ]
null
null
null
#include "Controller_Test_Snippet.h" #include "MachTest_SP_IO.h" #include "debugkxn.h" Controller_Test_Snippet_Data::Controller_Test_Snippet_Data() { this->nameDevice = "testDevice"; this->timeInterval = 250; this->valueDevice = "No device"; // Add your code here } bool Controller_Test_Snippet_Data::getData() { // Add your code here return true; } bool Controller_Test_Snippet_Data::init() { deInit(); // Add your code here return 1; } bool Controller_Test_Snippet_Data::deInit() { // Add your code here return 1; } Controller_Test_Snippet_Data testDevice_Device;
17.588235
60
0.734114
devshop2019
626eecb961d44ed5a1d7ddb33f467d95ee7b6237
71,731
tcc
C++
Vc/include/Vc/avx/vector.tcc
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
Vc/include/Vc/avx/vector.tcc
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
Vc/include/Vc/avx/vector.tcc
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/* This file is part of the Vc library. Copyright (C) 2011-2012 Matthias Kretz <kretz@kde.org> Vc 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. Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>. */ #include "limits.h" #include "const.h" #include "macros.h" namespace AliRoot { namespace Vc { ALIGN(64) extern unsigned int RandomState[16]; namespace AVX { /////////////////////////////////////////////////////////////////////////////////////////// // constants {{{1 template<typename T> Vc_ALWAYS_INLINE Vector<T>::Vector(VectorSpecialInitializerZero::ZEnum) : d(HT::zero()) {} template<typename T> Vc_ALWAYS_INLINE Vector<T>::Vector(VectorSpecialInitializerOne::OEnum) : d(HT::one()) {} template<typename T> Vc_ALWAYS_INLINE Vector<T>::Vector(VectorSpecialInitializerIndexesFromZero::IEnum) : d(HV::load(IndexesFromZeroData<T>::address(), Aligned)) {} template<typename T> Vc_INTRINSIC Vector<T> Vc_CONST Vector<T>::Zero() { return HT::zero(); } template<typename T> Vc_INTRINSIC Vector<T> Vc_CONST Vector<T>::One() { return HT::one(); } template<typename T> Vc_INTRINSIC Vector<T> Vc_CONST Vector<T>::IndexesFromZero() { return HV::load(IndexesFromZeroData<T>::address(), Aligned); } template<typename T> template<typename T2> Vc_ALWAYS_INLINE Vector<T>::Vector(VC_ALIGNED_PARAMETER(Vector<T2>) x) : d(StaticCastHelper<T2, T>::cast(x.data())) {} template<typename T> Vc_ALWAYS_INLINE Vector<T>::Vector(EntryType x) : d(HT::set(x)) {} template<> Vc_ALWAYS_INLINE Vector<double>::Vector(EntryType x) : d(_mm256_set1_pd(x)) {} /////////////////////////////////////////////////////////////////////////////////////////// // load ctors {{{1 template<typename T> Vc_ALWAYS_INLINE Vector<T>::Vector(const EntryType *x) { load(x); } template<typename T> template<typename A> Vc_ALWAYS_INLINE Vector<T>::Vector(const EntryType *x, A a) { load(x, a); } template<typename T> template<typename OtherT> Vc_ALWAYS_INLINE Vector<T>::Vector(const OtherT *x) { load(x); } template<typename T> template<typename OtherT, typename A> Vc_ALWAYS_INLINE Vector<T>::Vector(const OtherT *x, A a) { load(x, a); } /////////////////////////////////////////////////////////////////////////////////////////// // load member functions {{{1 template<typename T> Vc_INTRINSIC void Vector<T>::load(const EntryType *mem) { load(mem, Aligned); } template<typename T> template<typename A> Vc_INTRINSIC void Vector<T>::load(const EntryType *mem, A align) { d.v() = HV::load(mem, align); } template<typename T> template<typename OtherT> Vc_INTRINSIC void Vector<T>::load(const OtherT *mem) { load(mem, Aligned); } // LoadHelper {{{2 template<typename DstT, typename SrcT, typename Flags> struct LoadHelper; // float {{{2 template<typename Flags> struct LoadHelper<float, double, Flags> { static m256 load(const double *mem, Flags f) { return concat(_mm256_cvtpd_ps(VectorHelper<m256d>::load(&mem[0], f)), _mm256_cvtpd_ps(VectorHelper<m256d>::load(&mem[4], f))); } }; template<typename Flags> struct LoadHelper<float, unsigned int, Flags> { static m256 load(const unsigned int *mem, Flags f) { return StaticCastHelper<unsigned int, float>::cast(VectorHelper<m256i>::load(mem, f)); } }; template<typename Flags> struct LoadHelper<float, int, Flags> { static m256 load(const int *mem, Flags f) { return StaticCastHelper<int, float>::cast(VectorHelper<m256i>::load(mem, f)); } }; template<typename Flags> struct LoadHelper<float, unsigned short, Flags> { static m256 load(const unsigned short *mem, Flags f) { return StaticCastHelper<unsigned short, float>::cast(VectorHelper<m128i>::load(mem, f)); } }; template<typename Flags> struct LoadHelper<float, short, Flags> { static m256 load(const short *mem, Flags f) { return StaticCastHelper<short, float>::cast(VectorHelper<m128i>::load(mem, f)); } }; template<typename Flags> struct LoadHelper<float, unsigned char, Flags> { static m256 load(const unsigned char *mem, Flags f) { return StaticCastHelper<unsigned int, float>::cast(LoadHelper<unsigned int, unsigned char, Flags>::load(mem, f)); } }; template<typename Flags> struct LoadHelper<float, signed char, Flags> { static m256 load(const signed char *mem, Flags f) { return StaticCastHelper<int, float>::cast(LoadHelper<int, signed char, Flags>::load(mem, f)); } }; template<typename SrcT, typename Flags> struct LoadHelper<sfloat, SrcT, Flags> : public LoadHelper<float, SrcT, Flags> {}; // int {{{2 template<typename Flags> struct LoadHelper<int, unsigned int, Flags> { static m256i load(const unsigned int *mem, Flags f) { return VectorHelper<m256i>::load(mem, f); } }; template<typename Flags> struct LoadHelper<int, unsigned short, Flags> { static m256i load(const unsigned short *mem, Flags f) { return StaticCastHelper<unsigned short, unsigned int>::cast(VectorHelper<m128i>::load(mem, f)); } }; template<typename Flags> struct LoadHelper<int, short, Flags> { static m256i load(const short *mem, Flags f) { return StaticCastHelper<short, int>::cast(VectorHelper<m128i>::load(mem, f)); } }; template<typename Flags> struct LoadHelper<int, unsigned char, Flags> { static m256i load(const unsigned char *mem, Flags) { // the only available streaming load loads 16 bytes - twice as much as we need => can't use // it, or we risk an out-of-bounds read and an unaligned load exception const m128i epu8 = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(mem)); const m128i epu16 = _mm_cvtepu8_epi16(epu8); return StaticCastHelper<unsigned short, unsigned int>::cast(epu16); } }; template<typename Flags> struct LoadHelper<int, signed char, Flags> { static m256i load(const signed char *mem, Flags) { // the only available streaming load loads 16 bytes - twice as much as we need => can't use // it, or we risk an out-of-bounds read and an unaligned load exception const m128i epi8 = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(mem)); const m128i epi16 = _mm_cvtepi8_epi16(epi8); return StaticCastHelper<short, int>::cast(epi16); } }; // unsigned int {{{2 template<typename Flags> struct LoadHelper<unsigned int, unsigned short, Flags> { static m256i load(const unsigned short *mem, Flags f) { return StaticCastHelper<unsigned short, unsigned int>::cast(VectorHelper<m128i>::load(mem, f)); } }; template<typename Flags> struct LoadHelper<unsigned int, unsigned char, Flags> { static m256i load(const unsigned char *mem, Flags) { // the only available streaming load loads 16 bytes - twice as much as we need => can't use // it, or we risk an out-of-bounds read and an unaligned load exception const m128i epu8 = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(mem)); const m128i epu16 = _mm_cvtepu8_epi16(epu8); return StaticCastHelper<unsigned short, unsigned int>::cast(epu16); } }; // short {{{2 template<typename Flags> struct LoadHelper<short, unsigned short, Flags> { static m128i load(const unsigned short *mem, Flags f) { return StaticCastHelper<unsigned short, short>::cast(VectorHelper<m128i>::load(mem, f)); } }; template<typename Flags> struct LoadHelper<short, unsigned char, Flags> { static m128i load(const unsigned char *mem, Flags) { // the only available streaming load loads 16 bytes - twice as much as we need => can't use // it, or we risk an out-of-bounds read and an unaligned load exception const m128i epu8 = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(mem)); return _mm_cvtepu8_epi16(epu8); } }; template<typename Flags> struct LoadHelper<short, signed char, Flags> { static m128i load(const signed char *mem, Flags) { // the only available streaming load loads 16 bytes - twice as much as we need => can't use // it, or we risk an out-of-bounds read and an unaligned load exception const m128i epi8 = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(mem)); return _mm_cvtepi8_epi16(epi8); } }; // unsigned short {{{2 template<typename Flags> struct LoadHelper<unsigned short, unsigned char, Flags> { static m128i load(const unsigned char *mem, Flags) { // the only available streaming load loads 16 bytes - twice as much as we need => can't use // it, or we risk an out-of-bounds read and an unaligned load exception const m128i epu8 = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(mem)); return _mm_cvtepu8_epi16(epu8); } }; // general load, implemented via LoadHelper {{{2 template<typename DstT> template<typename SrcT, typename Flags> Vc_INTRINSIC void Vector<DstT>::load(const SrcT *x, Flags f) { d.v() = LoadHelper<DstT, SrcT, Flags>::load(x, f); } /////////////////////////////////////////////////////////////////////////////////////////// // zeroing {{{1 template<typename T> Vc_INTRINSIC void Vector<T>::setZero() { data() = HV::zero(); } template<typename T> Vc_INTRINSIC void Vector<T>::setZero(const Mask &k) { data() = HV::andnot_(avx_cast<VectorType>(k.data()), data()); } template<> Vc_INTRINSIC void Vector<double>::setQnan() { data() = _mm256_setallone_pd(); } template<> Vc_INTRINSIC void Vector<double>::setQnan(MaskArg k) { data() = _mm256_or_pd(data(), k.dataD()); } template<> Vc_INTRINSIC void Vector<float>::setQnan() { data() = _mm256_setallone_ps(); } template<> Vc_INTRINSIC void Vector<float>::setQnan(MaskArg k) { data() = _mm256_or_ps(data(), k.data()); } template<> Vc_INTRINSIC void Vector<sfloat>::setQnan() { data() = _mm256_setallone_ps(); } template<> Vc_INTRINSIC void Vector<sfloat>::setQnan(MaskArg k) { data() = _mm256_or_ps(data(), k.data()); } /////////////////////////////////////////////////////////////////////////////////////////// // stores {{{1 template<typename T> Vc_INTRINSIC void Vector<T>::store(EntryType *mem) const { HV::store(mem, data(), Aligned); } template<typename T> Vc_INTRINSIC void Vector<T>::store(EntryType *mem, const Mask &mask) const { HV::store(mem, data(), avx_cast<VectorType>(mask.data()), Aligned); } template<typename T> template<typename A> Vc_INTRINSIC void Vector<T>::store(EntryType *mem, A align) const { HV::store(mem, data(), align); } template<typename T> template<typename A> Vc_INTRINSIC void Vector<T>::store(EntryType *mem, const Mask &mask, A align) const { HV::store(mem, data(), avx_cast<VectorType>(mask.data()), align); } /////////////////////////////////////////////////////////////////////////////////////////// // expand/merge 1 float_v <=> 2 double_v XXX rationale? remove it for release? XXX {{{1 template<typename T> Vc_ALWAYS_INLINE Vc_FLATTEN Vector<T>::Vector(const Vector<typename HT::ConcatType> *a) : d(a[0]) { } template<> Vc_ALWAYS_INLINE Vc_FLATTEN Vector<float>::Vector(const Vector<HT::ConcatType> *a) : d(concat(_mm256_cvtpd_ps(a[0].data()), _mm256_cvtpd_ps(a[1].data()))) { } template<> Vc_ALWAYS_INLINE Vc_FLATTEN Vector<short>::Vector(const Vector<HT::ConcatType> *a) : d(_mm_packs_epi32(lo128(a->data()), hi128(a->data()))) { } template<> Vc_ALWAYS_INLINE Vc_FLATTEN Vector<unsigned short>::Vector(const Vector<HT::ConcatType> *a) : d(_mm_packus_epi32(lo128(a->data()), hi128(a->data()))) { } template<typename T> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::expand(Vector<typename HT::ConcatType> *x) const { x[0] = *this; } template<> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<float>::expand(Vector<HT::ConcatType> *x) const { x[0].data() = _mm256_cvtps_pd(lo128(d.v())); x[1].data() = _mm256_cvtps_pd(hi128(d.v())); } template<> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<short>::expand(Vector<HT::ConcatType> *x) const { x[0].data() = concat(_mm_cvtepi16_epi32(d.v()), _mm_cvtepi16_epi32(_mm_unpackhi_epi64(d.v(), d.v()))); } template<> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<unsigned short>::expand(Vector<HT::ConcatType> *x) const { x[0].data() = concat(_mm_cvtepu16_epi32(d.v()), _mm_cvtepu16_epi32(_mm_unpackhi_epi64(d.v(), d.v()))); } /////////////////////////////////////////////////////////////////////////////////////////// // swizzles {{{1 template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE &Vector<T>::abcd() const { return *this; } template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::cdab() const { return Mem::permute<X2, X3, X0, X1>(data()); } template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::badc() const { return Mem::permute<X1, X0, X3, X2>(data()); } template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::aaaa() const { return Mem::permute<X0, X0, X0, X0>(data()); } template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::bbbb() const { return Mem::permute<X1, X1, X1, X1>(data()); } template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::cccc() const { return Mem::permute<X2, X2, X2, X2>(data()); } template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::dddd() const { return Mem::permute<X3, X3, X3, X3>(data()); } template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::bcad() const { return Mem::permute<X1, X2, X0, X3>(data()); } template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::bcda() const { return Mem::permute<X1, X2, X3, X0>(data()); } template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::dabc() const { return Mem::permute<X3, X0, X1, X2>(data()); } template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::acbd() const { return Mem::permute<X0, X2, X1, X3>(data()); } template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::dbca() const { return Mem::permute<X3, X1, X2, X0>(data()); } template<typename T> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::dcba() const { return Mem::permute<X3, X2, X1, X0>(data()); } template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::cdab() const { return Mem::shuffle128<X1, X0>(data(), data()); } template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::badc() const { return Mem::permute<X1, X0, X3, X2>(data()); } template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::aaaa() const { const double &tmp = d.m(0); return _mm256_broadcast_sd(&tmp); } template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::bbbb() const { const double &tmp = d.m(1); return _mm256_broadcast_sd(&tmp); } template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::cccc() const { const double &tmp = d.m(2); return _mm256_broadcast_sd(&tmp); } template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::dddd() const { const double &tmp = d.m(3); return _mm256_broadcast_sd(&tmp); } template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::bcad() const { return Mem::shuffle<X1, Y0, X2, Y3>(Mem::shuffle128<X0, X0>(data(), data()), Mem::shuffle128<X1, X1>(data(), data())); } template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::bcda() const { return Mem::shuffle<X1, Y0, X3, Y2>(data(), Mem::shuffle128<X1, X0>(data(), data())); } template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::dabc() const { return Mem::shuffle<X1, Y0, X3, Y2>(Mem::shuffle128<X1, X0>(data(), data()), data()); } template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::acbd() const { return Mem::shuffle<X0, Y0, X3, Y3>(Mem::shuffle128<X0, X0>(data(), data()), Mem::shuffle128<X1, X1>(data(), data())); } template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::dbca() const { return Mem::shuffle<X1, Y1, X2, Y2>(Mem::shuffle128<X1, X1>(data(), data()), Mem::shuffle128<X0, X0>(data(), data())); } template<> Vc_INTRINSIC const double_v Vc_PURE Vector<double>::dcba() const { return cdab().badc(); } #define VC_SWIZZLES_16BIT_IMPL(T) \ template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::cdab() const { return Mem::permute<X2, X3, X0, X1, X6, X7, X4, X5>(data()); } \ template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::badc() const { return Mem::permute<X1, X0, X3, X2, X5, X4, X7, X6>(data()); } \ template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::aaaa() const { return Mem::permute<X0, X0, X0, X0, X4, X4, X4, X4>(data()); } \ template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::bbbb() const { return Mem::permute<X1, X1, X1, X1, X5, X5, X5, X5>(data()); } \ template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::cccc() const { return Mem::permute<X2, X2, X2, X2, X6, X6, X6, X6>(data()); } \ template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::dddd() const { return Mem::permute<X3, X3, X3, X3, X7, X7, X7, X7>(data()); } \ template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::bcad() const { return Mem::permute<X1, X2, X0, X3, X5, X6, X4, X7>(data()); } \ template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::bcda() const { return Mem::permute<X1, X2, X3, X0, X5, X6, X7, X4>(data()); } \ template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::dabc() const { return Mem::permute<X3, X0, X1, X2, X7, X4, X5, X6>(data()); } \ template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::acbd() const { return Mem::permute<X0, X2, X1, X3, X4, X6, X5, X7>(data()); } \ template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::dbca() const { return Mem::permute<X3, X1, X2, X0, X7, X5, X6, X4>(data()); } \ template<> Vc_INTRINSIC const Vector<T> Vc_PURE Vector<T>::dcba() const { return Mem::permute<X3, X2, X1, X0, X7, X6, X5, X4>(data()); } VC_SWIZZLES_16BIT_IMPL(short) VC_SWIZZLES_16BIT_IMPL(unsigned short) #undef VC_SWIZZLES_16BIT_IMPL /////////////////////////////////////////////////////////////////////////////////////////// // division {{{1 template<typename T> inline Vector<T> &Vector<T>::operator/=(EntryType x) { if (HasVectorDivision) { return operator/=(Vector<T>(x)); } for_all_vector_entries(i, d.m(i) /= x; ); return *this; } template<typename T> template<typename TT> inline Vc_PURE VC_EXACT_TYPE(TT, typename DetermineEntryType<T>::Type, Vector<T>) Vector<T>::operator/(TT x) const { if (HasVectorDivision) { return operator/(Vector<T>(x)); } Vector<T> r; for_all_vector_entries(i, r.d.m(i) = d.m(i) / x; ); return r; } // per default fall back to scalar division template<typename T> inline Vector<T> &Vector<T>::operator/=(const Vector<T> &x) { for_all_vector_entries(i, d.m(i) /= x.d.m(i); ); return *this; } template<typename T> inline Vector<T> Vc_PURE Vector<T>::operator/(const Vector<T> &x) const { Vector<T> r; for_all_vector_entries(i, r.d.m(i) = d.m(i) / x.d.m(i); ); return r; } // specialize division on type static Vc_INTRINSIC m256i Vc_CONST divInt(param256i a, param256i b) { const m256d lo1 = _mm256_cvtepi32_pd(lo128(a)); const m256d lo2 = _mm256_cvtepi32_pd(lo128(b)); const m256d hi1 = _mm256_cvtepi32_pd(hi128(a)); const m256d hi2 = _mm256_cvtepi32_pd(hi128(b)); return concat( _mm256_cvttpd_epi32(_mm256_div_pd(lo1, lo2)), _mm256_cvttpd_epi32(_mm256_div_pd(hi1, hi2)) ); } template<> inline Vector<int> &Vector<int>::operator/=(const Vector<int> &x) { d.v() = divInt(d.v(), x.d.v()); return *this; } template<> inline Vector<int> Vc_PURE Vector<int>::operator/(const Vector<int> &x) const { return divInt(d.v(), x.d.v()); } static inline m256i Vc_CONST divUInt(param256i a, param256i b) { m256d loa = _mm256_cvtepi32_pd(lo128(a)); m256d hia = _mm256_cvtepi32_pd(hi128(a)); m256d lob = _mm256_cvtepi32_pd(lo128(b)); m256d hib = _mm256_cvtepi32_pd(hi128(b)); // if a >= 2^31 then after conversion to double it will contain a negative number (i.e. a-2^32) // to get the right number back we have to add 2^32 where a >= 2^31 loa = _mm256_add_pd(loa, _mm256_and_pd(_mm256_cmp_pd(loa, _mm256_setzero_pd(), _CMP_LT_OS), _mm256_set1_pd(4294967296.))); hia = _mm256_add_pd(hia, _mm256_and_pd(_mm256_cmp_pd(hia, _mm256_setzero_pd(), _CMP_LT_OS), _mm256_set1_pd(4294967296.))); // we don't do the same for b because division by b >= 2^31 should be a seldom corner case and // we rather want the standard stuff fast // // there is one remaining problem: a >= 2^31 and b == 1 // in that case the return value would be 2^31 return avx_cast<m256i>(_mm256_blendv_ps(avx_cast<m256>(concat( _mm256_cvttpd_epi32(_mm256_div_pd(loa, lob)), _mm256_cvttpd_epi32(_mm256_div_pd(hia, hib)) )), avx_cast<m256>(a), avx_cast<m256>(concat( _mm_cmpeq_epi32(lo128(b), _mm_setone_epi32()), _mm_cmpeq_epi32(hi128(b), _mm_setone_epi32()))))); } template<> Vc_ALWAYS_INLINE Vector<unsigned int> &Vector<unsigned int>::operator/=(const Vector<unsigned int> &x) { d.v() = divUInt(d.v(), x.d.v()); return *this; } template<> Vc_ALWAYS_INLINE Vector<unsigned int> Vc_PURE Vector<unsigned int>::operator/(const Vector<unsigned int> &x) const { return divUInt(d.v(), x.d.v()); } template<typename T> static inline m128i Vc_CONST divShort(param128i a, param128i b) { const m256 r = _mm256_div_ps(StaticCastHelper<T, float>::cast(a), StaticCastHelper<T, float>::cast(b)); return StaticCastHelper<float, T>::cast(r); } template<> Vc_ALWAYS_INLINE Vector<short> &Vector<short>::operator/=(const Vector<short> &x) { d.v() = divShort<short>(d.v(), x.d.v()); return *this; } template<> Vc_ALWAYS_INLINE Vector<short> Vc_PURE Vector<short>::operator/(const Vector<short> &x) const { return divShort<short>(d.v(), x.d.v()); } template<> Vc_ALWAYS_INLINE Vector<unsigned short> &Vector<unsigned short>::operator/=(const Vector<unsigned short> &x) { d.v() = divShort<unsigned short>(d.v(), x.d.v()); return *this; } template<> Vc_ALWAYS_INLINE Vector<unsigned short> Vc_PURE Vector<unsigned short>::operator/(const Vector<unsigned short> &x) const { return divShort<unsigned short>(d.v(), x.d.v()); } template<> Vc_INTRINSIC float_v &float_v::operator/=(const float_v &x) { d.v() = _mm256_div_ps(d.v(), x.d.v()); return *this; } template<> Vc_INTRINSIC float_v Vc_PURE float_v::operator/(const float_v &x) const { return _mm256_div_ps(d.v(), x.d.v()); } template<> Vc_INTRINSIC sfloat_v &sfloat_v::operator/=(const sfloat_v &x) { d.v() = _mm256_div_ps(d.v(), x.d.v()); return *this; } template<> Vc_INTRINSIC sfloat_v Vc_PURE sfloat_v::operator/(const sfloat_v &x) const { return _mm256_div_ps(d.v(), x.d.v()); } template<> Vc_INTRINSIC double_v &double_v::operator/=(const double_v &x) { d.v() = _mm256_div_pd(d.v(), x.d.v()); return *this; } template<> Vc_INTRINSIC double_v Vc_PURE double_v::operator/(const double_v &x) const { return _mm256_div_pd(d.v(), x.d.v()); } /////////////////////////////////////////////////////////////////////////////////////////// // integer ops {{{1 #define OP_IMPL(T, symbol) \ template<> Vc_ALWAYS_INLINE Vector<T> &Vector<T>::operator symbol##=(AsArg x) \ { \ for_all_vector_entries(i, d.m(i) symbol##= x.d.m(i); ); \ return *this; \ } \ template<> Vc_ALWAYS_INLINE Vc_PURE Vector<T> Vector<T>::operator symbol(AsArg x) const \ { \ Vector<T> r; \ for_all_vector_entries(i, r.d.m(i) = d.m(i) symbol x.d.m(i); ); \ return r; \ } OP_IMPL(int, <<) OP_IMPL(int, >>) OP_IMPL(unsigned int, <<) OP_IMPL(unsigned int, >>) OP_IMPL(short, <<) OP_IMPL(short, >>) OP_IMPL(unsigned short, <<) OP_IMPL(unsigned short, >>) #undef OP_IMPL template<typename T> Vc_ALWAYS_INLINE Vector<T> &Vector<T>::operator>>=(int shift) { d.v() = VectorHelper<T>::shiftRight(d.v(), shift); return *static_cast<Vector<T> *>(this); } template<typename T> Vc_ALWAYS_INLINE Vc_PURE Vector<T> Vector<T>::operator>>(int shift) const { return VectorHelper<T>::shiftRight(d.v(), shift); } template<typename T> Vc_ALWAYS_INLINE Vector<T> &Vector<T>::operator<<=(int shift) { d.v() = VectorHelper<T>::shiftLeft(d.v(), shift); return *static_cast<Vector<T> *>(this); } template<typename T> Vc_ALWAYS_INLINE Vc_PURE Vector<T> Vector<T>::operator<<(int shift) const { return VectorHelper<T>::shiftLeft(d.v(), shift); } #define OP_IMPL(T, symbol, fun) \ template<> Vc_ALWAYS_INLINE Vector<T> &Vector<T>::operator symbol##=(AsArg x) { d.v() = HV::fun(d.v(), x.d.v()); return *this; } \ template<> Vc_ALWAYS_INLINE Vc_PURE Vector<T> Vector<T>::operator symbol(AsArg x) const { return Vector<T>(HV::fun(d.v(), x.d.v())); } OP_IMPL(int, &, and_) OP_IMPL(int, |, or_) OP_IMPL(int, ^, xor_) OP_IMPL(unsigned int, &, and_) OP_IMPL(unsigned int, |, or_) OP_IMPL(unsigned int, ^, xor_) OP_IMPL(short, &, and_) OP_IMPL(short, |, or_) OP_IMPL(short, ^, xor_) OP_IMPL(unsigned short, &, and_) OP_IMPL(unsigned short, |, or_) OP_IMPL(unsigned short, ^, xor_) OP_IMPL(float, &, and_) OP_IMPL(float, |, or_) OP_IMPL(float, ^, xor_) OP_IMPL(sfloat, &, and_) OP_IMPL(sfloat, |, or_) OP_IMPL(sfloat, ^, xor_) OP_IMPL(double, &, and_) OP_IMPL(double, |, or_) OP_IMPL(double, ^, xor_) #undef OP_IMPL // operators {{{1 #include "../common/operators.h" // isNegative {{{1 template<> Vc_INTRINSIC Vc_PURE float_m float_v::isNegative() const { return avx_cast<m256>(_mm256_srai_epi32(avx_cast<m256i>(_mm256_and_ps(_mm256_setsignmask_ps(), d.v())), 31)); } template<> Vc_INTRINSIC Vc_PURE sfloat_m sfloat_v::isNegative() const { return avx_cast<m256>(_mm256_srai_epi32(avx_cast<m256i>(_mm256_and_ps(_mm256_setsignmask_ps(), d.v())), 31)); } template<> Vc_INTRINSIC Vc_PURE double_m double_v::isNegative() const { return Mem::permute<X1, X1, X3, X3>(avx_cast<m256>( _mm256_srai_epi32(avx_cast<m256i>(_mm256_and_pd(_mm256_setsignmask_pd(), d.v())), 31) )); } // gathers {{{1 // Better implementation (hopefully) with _mm256_set_ //X template<typename T> template<typename Index> Vector<T>::Vector(const EntryType *mem, const Index *indexes) //X { //X for_all_vector_entries(int i, //X d.m(i) = mem[indexes[i]]; //X ); //X } template<typename T> template<typename IndexT> Vc_ALWAYS_INLINE Vector<T>::Vector(const EntryType *mem, const IndexT *indexes) { gather(mem, indexes); } template<typename T> template<typename IndexT> Vc_ALWAYS_INLINE Vector<T>::Vector(const EntryType *mem, VC_ALIGNED_PARAMETER(Vector<IndexT>) indexes) { gather(mem, indexes); } template<typename T> template<typename IndexT> Vc_ALWAYS_INLINE Vector<T>::Vector(const EntryType *mem, const IndexT *indexes, MaskArg mask) : d(HT::zero()) { gather(mem, indexes, mask); } template<typename T> template<typename IndexT> Vc_ALWAYS_INLINE Vector<T>::Vector(const EntryType *mem, VC_ALIGNED_PARAMETER(Vector<IndexT>) indexes, MaskArg mask) : d(HT::zero()) { gather(mem, indexes, mask); } template<typename T> template<typename S1, typename IT> Vc_ALWAYS_INLINE Vector<T>::Vector(const S1 *array, const EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes) { gather(array, member1, indexes); } template<typename T> template<typename S1, typename IT> Vc_ALWAYS_INLINE Vector<T>::Vector(const S1 *array, const EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes, MaskArg mask) : d(HT::zero()) { gather(array, member1, indexes, mask); } template<typename T> template<typename S1, typename S2, typename IT> Vc_ALWAYS_INLINE Vector<T>::Vector(const S1 *array, const S2 S1::* member1, const EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes) { gather(array, member1, member2, indexes); } template<typename T> template<typename S1, typename S2, typename IT> Vc_ALWAYS_INLINE Vector<T>::Vector(const S1 *array, const S2 S1::* member1, const EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes, MaskArg mask) : d(HT::zero()) { gather(array, member1, member2, indexes, mask); } template<typename T> template<typename S1, typename IT1, typename IT2> Vc_ALWAYS_INLINE Vector<T>::Vector(const S1 *array, const EntryType *const S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes) { gather(array, ptrMember1, outerIndexes, innerIndexes); } template<typename T> template<typename S1, typename IT1, typename IT2> Vc_ALWAYS_INLINE Vector<T>::Vector(const S1 *array, const EntryType *const S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes, MaskArg mask) : d(HT::zero()) { gather(array, ptrMember1, outerIndexes, innerIndexes, mask); } template<typename T, size_t Size> struct IndexSizeChecker { static void check() {} }; template<typename T, size_t Size> struct IndexSizeChecker<Vector<T>, Size> { static void check() { VC_STATIC_ASSERT(Vector<T>::Size >= Size, IndexVector_must_have_greater_or_equal_number_of_entries); } }; template<> template<typename Index> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<double>::gather(const EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes) { IndexSizeChecker<Index, Size>::check(); d.v() = _mm256_setr_pd(mem[indexes[0]], mem[indexes[1]], mem[indexes[2]], mem[indexes[3]]); } template<> template<typename Index> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<float>::gather(const EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes) { IndexSizeChecker<Index, Size>::check(); d.v() = _mm256_setr_ps(mem[indexes[0]], mem[indexes[1]], mem[indexes[2]], mem[indexes[3]], mem[indexes[4]], mem[indexes[5]], mem[indexes[6]], mem[indexes[7]]); } template<> template<typename Index> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<sfloat>::gather(const EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes) { IndexSizeChecker<Index, Size>::check(); d.v() = _mm256_setr_ps(mem[indexes[0]], mem[indexes[1]], mem[indexes[2]], mem[indexes[3]], mem[indexes[4]], mem[indexes[5]], mem[indexes[6]], mem[indexes[7]]); } template<> template<typename Index> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<int>::gather(const EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes) { IndexSizeChecker<Index, Size>::check(); d.v() = _mm256_setr_epi32(mem[indexes[0]], mem[indexes[1]], mem[indexes[2]], mem[indexes[3]], mem[indexes[4]], mem[indexes[5]], mem[indexes[6]], mem[indexes[7]]); } template<> template<typename Index> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<unsigned int>::gather(const EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes) { IndexSizeChecker<Index, Size>::check(); d.v() = _mm256_setr_epi32(mem[indexes[0]], mem[indexes[1]], mem[indexes[2]], mem[indexes[3]], mem[indexes[4]], mem[indexes[5]], mem[indexes[6]], mem[indexes[7]]); } template<> template<typename Index> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<short>::gather(const EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes) { IndexSizeChecker<Index, Size>::check(); d.v() = _mm_setr_epi16(mem[indexes[0]], mem[indexes[1]], mem[indexes[2]], mem[indexes[3]], mem[indexes[4]], mem[indexes[5]], mem[indexes[6]], mem[indexes[7]]); } template<> template<typename Index> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<unsigned short>::gather(const EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes) { IndexSizeChecker<Index, Size>::check(); d.v() = _mm_setr_epi16(mem[indexes[0]], mem[indexes[1]], mem[indexes[2]], mem[indexes[3]], mem[indexes[4]], mem[indexes[5]], mem[indexes[6]], mem[indexes[7]]); } #ifdef VC_USE_SET_GATHERS template<typename T> template<typename IT> Vc_ALWAYS_INLINE void Vector<T>::gather(const EntryType *mem, VC_ALIGNED_PARAMETER(Vector<IT>) indexes, MaskArg mask) { IndexSizeChecker<Vector<IT>, Size>::check(); Vector<IT> indexesTmp = indexes; indexesTmp.setZero(!mask); (*this)(mask) = Vector<T>(mem, indexesTmp); } #endif #ifdef VC_USE_BSF_GATHERS #define VC_MASKED_GATHER \ int bits = mask.toInt(); \ while (bits) { \ const int i = _bit_scan_forward(bits); \ bits &= ~(1 << i); /* btr? */ \ d.m(i) = ith_value(i); \ } #elif defined(VC_USE_POPCNT_BSF_GATHERS) #define VC_MASKED_GATHER \ unsigned int bits = mask.toInt(); \ unsigned int low, high = 0; \ switch (_mm_popcnt_u32(bits)) { \ case 8: \ high = _bit_scan_reverse(bits); \ d.m(high) = ith_value(high); \ high = (1 << high); \ case 7: \ low = _bit_scan_forward(bits); \ bits ^= high | (1 << low); \ d.m(low) = ith_value(low); \ case 6: \ high = _bit_scan_reverse(bits); \ d.m(high) = ith_value(high); \ high = (1 << high); \ case 5: \ low = _bit_scan_forward(bits); \ bits ^= high | (1 << low); \ d.m(low) = ith_value(low); \ case 4: \ high = _bit_scan_reverse(bits); \ d.m(high) = ith_value(high); \ high = (1 << high); \ case 3: \ low = _bit_scan_forward(bits); \ bits ^= high | (1 << low); \ d.m(low) = ith_value(low); \ case 2: \ high = _bit_scan_reverse(bits); \ d.m(high) = ith_value(high); \ case 1: \ low = _bit_scan_forward(bits); \ d.m(low) = ith_value(low); \ case 0: \ break; \ } #else #define VC_MASKED_GATHER \ if (mask.isEmpty()) { \ return; \ } \ for_all_vector_entries(i, \ if (mask[i]) d.m(i) = ith_value(i); \ ); #endif template<typename T> template<typename Index> Vc_INTRINSIC void Vector<T>::gather(const EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes, MaskArg mask) { IndexSizeChecker<Index, Size>::check(); #define ith_value(_i_) (mem[indexes[_i_]]) VC_MASKED_GATHER #undef ith_value } template<> template<typename S1, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<double>::gather(const S1 *array, const EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes) { IndexSizeChecker<IT, Size>::check(); d.v() = _mm256_setr_pd(array[indexes[0]].*(member1), array[indexes[1]].*(member1), array[indexes[2]].*(member1), array[indexes[3]].*(member1)); } template<> template<typename S1, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<float>::gather(const S1 *array, const EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes) { IndexSizeChecker<IT, Size>::check(); d.v() = _mm256_setr_ps(array[indexes[0]].*(member1), array[indexes[1]].*(member1), array[indexes[2]].*(member1), array[indexes[3]].*(member1), array[indexes[4]].*(member1), array[indexes[5]].*(member1), array[indexes[6]].*(member1), array[indexes[7]].*(member1)); } template<> template<typename S1, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<sfloat>::gather(const S1 *array, const EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes) { IndexSizeChecker<IT, Size>::check(); d.v() = _mm256_setr_ps(array[indexes[0]].*(member1), array[indexes[1]].*(member1), array[indexes[2]].*(member1), array[indexes[3]].*(member1), array[indexes[4]].*(member1), array[indexes[5]].*(member1), array[indexes[6]].*(member1), array[indexes[7]].*(member1)); } template<> template<typename S1, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<int>::gather(const S1 *array, const EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes) { IndexSizeChecker<IT, Size>::check(); d.v() = _mm256_setr_epi32(array[indexes[0]].*(member1), array[indexes[1]].*(member1), array[indexes[2]].*(member1), array[indexes[3]].*(member1), array[indexes[4]].*(member1), array[indexes[5]].*(member1), array[indexes[6]].*(member1), array[indexes[7]].*(member1)); } template<> template<typename S1, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<unsigned int>::gather(const S1 *array, const EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes) { IndexSizeChecker<IT, Size>::check(); d.v() = _mm256_setr_epi32(array[indexes[0]].*(member1), array[indexes[1]].*(member1), array[indexes[2]].*(member1), array[indexes[3]].*(member1), array[indexes[4]].*(member1), array[indexes[5]].*(member1), array[indexes[6]].*(member1), array[indexes[7]].*(member1)); } template<> template<typename S1, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<short>::gather(const S1 *array, const EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes) { IndexSizeChecker<IT, Size>::check(); d.v() = _mm_setr_epi16(array[indexes[0]].*(member1), array[indexes[1]].*(member1), array[indexes[2]].*(member1), array[indexes[3]].*(member1), array[indexes[4]].*(member1), array[indexes[5]].*(member1), array[indexes[6]].*(member1), array[indexes[7]].*(member1)); } template<> template<typename S1, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<unsigned short>::gather(const S1 *array, const EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes) { IndexSizeChecker<IT, Size>::check(); d.v() = _mm_setr_epi16(array[indexes[0]].*(member1), array[indexes[1]].*(member1), array[indexes[2]].*(member1), array[indexes[3]].*(member1), array[indexes[4]].*(member1), array[indexes[5]].*(member1), array[indexes[6]].*(member1), array[indexes[7]].*(member1)); } template<typename T> template<typename S1, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::gather(const S1 *array, const EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes, MaskArg mask) { IndexSizeChecker<IT, Size>::check(); #define ith_value(_i_) (array[indexes[_i_]].*(member1)) VC_MASKED_GATHER #undef ith_value } template<> template<typename S1, typename S2, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<double>::gather(const S1 *array, const S2 S1::* member1, const EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes) { IndexSizeChecker<IT, Size>::check(); d.v() = _mm256_setr_pd(array[indexes[0]].*(member1).*(member2), array[indexes[1]].*(member1).*(member2), array[indexes[2]].*(member1).*(member2), array[indexes[3]].*(member1).*(member2)); } template<> template<typename S1, typename S2, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<float>::gather(const S1 *array, const S2 S1::* member1, const EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes) { IndexSizeChecker<IT, Size>::check(); d.v() = _mm256_setr_ps(array[indexes[0]].*(member1).*(member2), array[indexes[1]].*(member1).*(member2), array[indexes[2]].*(member1).*(member2), array[indexes[3]].*(member1).*(member2), array[indexes[4]].*(member1).*(member2), array[indexes[5]].*(member1).*(member2), array[indexes[6]].*(member1).*(member2), array[indexes[7]].*(member1).*(member2)); } template<> template<typename S1, typename S2, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<sfloat>::gather(const S1 *array, const S2 S1::* member1, const EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes) { IndexSizeChecker<IT, Size>::check(); d.v() = _mm256_setr_ps(array[indexes[0]].*(member1).*(member2), array[indexes[1]].*(member1).*(member2), array[indexes[2]].*(member1).*(member2), array[indexes[3]].*(member1).*(member2), array[indexes[4]].*(member1).*(member2), array[indexes[5]].*(member1).*(member2), array[indexes[6]].*(member1).*(member2), array[indexes[7]].*(member1).*(member2)); } template<> template<typename S1, typename S2, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<int>::gather(const S1 *array, const S2 S1::* member1, const EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes) { IndexSizeChecker<IT, Size>::check(); d.v() = _mm256_setr_epi32(array[indexes[0]].*(member1).*(member2), array[indexes[1]].*(member1).*(member2), array[indexes[2]].*(member1).*(member2), array[indexes[3]].*(member1).*(member2), array[indexes[4]].*(member1).*(member2), array[indexes[5]].*(member1).*(member2), array[indexes[6]].*(member1).*(member2), array[indexes[7]].*(member1).*(member2)); } template<> template<typename S1, typename S2, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<unsigned int>::gather(const S1 *array, const S2 S1::* member1, const EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes) { IndexSizeChecker<IT, Size>::check(); d.v() = _mm256_setr_epi32(array[indexes[0]].*(member1).*(member2), array[indexes[1]].*(member1).*(member2), array[indexes[2]].*(member1).*(member2), array[indexes[3]].*(member1).*(member2), array[indexes[4]].*(member1).*(member2), array[indexes[5]].*(member1).*(member2), array[indexes[6]].*(member1).*(member2), array[indexes[7]].*(member1).*(member2)); } template<> template<typename S1, typename S2, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<short>::gather(const S1 *array, const S2 S1::* member1, const EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes) { IndexSizeChecker<IT, Size>::check(); d.v() = _mm_setr_epi16(array[indexes[0]].*(member1).*(member2), array[indexes[1]].*(member1).*(member2), array[indexes[2]].*(member1).*(member2), array[indexes[3]].*(member1).*(member2), array[indexes[4]].*(member1).*(member2), array[indexes[5]].*(member1).*(member2), array[indexes[6]].*(member1).*(member2), array[indexes[7]].*(member1).*(member2)); } template<> template<typename S1, typename S2, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<unsigned short>::gather(const S1 *array, const S2 S1::* member1, const EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes) { IndexSizeChecker<IT, Size>::check(); d.v() = _mm_setr_epi16(array[indexes[0]].*(member1).*(member2), array[indexes[1]].*(member1).*(member2), array[indexes[2]].*(member1).*(member2), array[indexes[3]].*(member1).*(member2), array[indexes[4]].*(member1).*(member2), array[indexes[5]].*(member1).*(member2), array[indexes[6]].*(member1).*(member2), array[indexes[7]].*(member1).*(member2)); } template<typename T> template<typename S1, typename S2, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::gather(const S1 *array, const S2 S1::* member1, const EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes, MaskArg mask) { IndexSizeChecker<IT, Size>::check(); #define ith_value(_i_) (array[indexes[_i_]].*(member1).*(member2)) VC_MASKED_GATHER #undef ith_value } template<> template<typename S1, typename IT1, typename IT2> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<double>::gather(const S1 *array, const EntryType *const S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes) { IndexSizeChecker<IT1, Size>::check(); IndexSizeChecker<IT2, Size>::check(); d.v() = _mm256_setr_pd((array[outerIndexes[0]].*(ptrMember1))[innerIndexes[0]], (array[outerIndexes[1]].*(ptrMember1))[innerIndexes[1]], (array[outerIndexes[2]].*(ptrMember1))[innerIndexes[2]], (array[outerIndexes[3]].*(ptrMember1))[innerIndexes[3]]); } template<> template<typename S1, typename IT1, typename IT2> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<float>::gather(const S1 *array, const EntryType *const S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes) { IndexSizeChecker<IT1, Size>::check(); IndexSizeChecker<IT2, Size>::check(); d.v() = _mm256_setr_ps((array[outerIndexes[0]].*(ptrMember1))[innerIndexes[0]], (array[outerIndexes[1]].*(ptrMember1))[innerIndexes[1]], (array[outerIndexes[2]].*(ptrMember1))[innerIndexes[2]], (array[outerIndexes[3]].*(ptrMember1))[innerIndexes[3]], (array[outerIndexes[4]].*(ptrMember1))[innerIndexes[4]], (array[outerIndexes[5]].*(ptrMember1))[innerIndexes[5]], (array[outerIndexes[6]].*(ptrMember1))[innerIndexes[6]], (array[outerIndexes[7]].*(ptrMember1))[innerIndexes[7]]); } template<> template<typename S1, typename IT1, typename IT2> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<sfloat>::gather(const S1 *array, const EntryType *const S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes) { IndexSizeChecker<IT1, Size>::check(); IndexSizeChecker<IT2, Size>::check(); d.v() = _mm256_setr_ps((array[outerIndexes[0]].*(ptrMember1))[innerIndexes[0]], (array[outerIndexes[1]].*(ptrMember1))[innerIndexes[1]], (array[outerIndexes[2]].*(ptrMember1))[innerIndexes[2]], (array[outerIndexes[3]].*(ptrMember1))[innerIndexes[3]], (array[outerIndexes[4]].*(ptrMember1))[innerIndexes[4]], (array[outerIndexes[5]].*(ptrMember1))[innerIndexes[5]], (array[outerIndexes[6]].*(ptrMember1))[innerIndexes[6]], (array[outerIndexes[7]].*(ptrMember1))[innerIndexes[7]]); } template<> template<typename S1, typename IT1, typename IT2> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<int>::gather(const S1 *array, const EntryType *const S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes) { IndexSizeChecker<IT1, Size>::check(); IndexSizeChecker<IT2, Size>::check(); d.v() = _mm256_setr_epi32((array[outerIndexes[0]].*(ptrMember1))[innerIndexes[0]], (array[outerIndexes[1]].*(ptrMember1))[innerIndexes[1]], (array[outerIndexes[2]].*(ptrMember1))[innerIndexes[2]], (array[outerIndexes[3]].*(ptrMember1))[innerIndexes[3]], (array[outerIndexes[4]].*(ptrMember1))[innerIndexes[4]], (array[outerIndexes[5]].*(ptrMember1))[innerIndexes[5]], (array[outerIndexes[6]].*(ptrMember1))[innerIndexes[6]], (array[outerIndexes[7]].*(ptrMember1))[innerIndexes[7]]); } template<> template<typename S1, typename IT1, typename IT2> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<unsigned int>::gather(const S1 *array, const EntryType *const S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes) { IndexSizeChecker<IT1, Size>::check(); IndexSizeChecker<IT2, Size>::check(); d.v() = _mm256_setr_epi32((array[outerIndexes[0]].*(ptrMember1))[innerIndexes[0]], (array[outerIndexes[1]].*(ptrMember1))[innerIndexes[1]], (array[outerIndexes[2]].*(ptrMember1))[innerIndexes[2]], (array[outerIndexes[3]].*(ptrMember1))[innerIndexes[3]], (array[outerIndexes[4]].*(ptrMember1))[innerIndexes[4]], (array[outerIndexes[5]].*(ptrMember1))[innerIndexes[5]], (array[outerIndexes[6]].*(ptrMember1))[innerIndexes[6]], (array[outerIndexes[7]].*(ptrMember1))[innerIndexes[7]]); } template<> template<typename S1, typename IT1, typename IT2> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<short>::gather(const S1 *array, const EntryType *const S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes) { IndexSizeChecker<IT1, Size>::check(); IndexSizeChecker<IT2, Size>::check(); d.v() = _mm_setr_epi16((array[outerIndexes[0]].*(ptrMember1))[innerIndexes[0]], (array[outerIndexes[1]].*(ptrMember1))[innerIndexes[1]], (array[outerIndexes[2]].*(ptrMember1))[innerIndexes[2]], (array[outerIndexes[3]].*(ptrMember1))[innerIndexes[3]], (array[outerIndexes[4]].*(ptrMember1))[innerIndexes[4]], (array[outerIndexes[5]].*(ptrMember1))[innerIndexes[5]], (array[outerIndexes[6]].*(ptrMember1))[innerIndexes[6]], (array[outerIndexes[7]].*(ptrMember1))[innerIndexes[7]]); } template<> template<typename S1, typename IT1, typename IT2> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<unsigned short>::gather(const S1 *array, const EntryType *const S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes) { IndexSizeChecker<IT1, Size>::check(); IndexSizeChecker<IT2, Size>::check(); d.v() = _mm_setr_epi16((array[outerIndexes[0]].*(ptrMember1))[innerIndexes[0]], (array[outerIndexes[1]].*(ptrMember1))[innerIndexes[1]], (array[outerIndexes[2]].*(ptrMember1))[innerIndexes[2]], (array[outerIndexes[3]].*(ptrMember1))[innerIndexes[3]], (array[outerIndexes[4]].*(ptrMember1))[innerIndexes[4]], (array[outerIndexes[5]].*(ptrMember1))[innerIndexes[5]], (array[outerIndexes[6]].*(ptrMember1))[innerIndexes[6]], (array[outerIndexes[7]].*(ptrMember1))[innerIndexes[7]]); } template<typename T> template<typename S1, typename IT1, typename IT2> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::gather(const S1 *array, const EntryType *const S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes, MaskArg mask) { IndexSizeChecker<IT1, Size>::check(); IndexSizeChecker<IT2, Size>::check(); #define ith_value(_i_) (array[outerIndexes[_i_]].*(ptrMember1))[innerIndexes[_i_]] VC_MASKED_GATHER #undef ith_value } #undef VC_MASKED_GATHER #ifdef VC_USE_BSF_SCATTERS #define VC_MASKED_SCATTER \ int bits = mask.toInt(); \ while (bits) { \ const int i = _bit_scan_forward(bits); \ bits ^= (1 << i); /* btr? */ \ ith_value(i) = d.m(i); \ } #elif defined(VC_USE_POPCNT_BSF_SCATTERS) #define VC_MASKED_SCATTER \ unsigned int bits = mask.toInt(); \ unsigned int low, high = 0; \ switch (_mm_popcnt_u32(bits)) { \ case 8: \ high = _bit_scan_reverse(bits); \ ith_value(high) = d.m(high); \ high = (1 << high); \ case 7: \ low = _bit_scan_forward(bits); \ bits ^= high | (1 << low); \ ith_value(low) = d.m(low); \ case 6: \ high = _bit_scan_reverse(bits); \ ith_value(high) = d.m(high); \ high = (1 << high); \ case 5: \ low = _bit_scan_forward(bits); \ bits ^= high | (1 << low); \ ith_value(low) = d.m(low); \ case 4: \ high = _bit_scan_reverse(bits); \ ith_value(high) = d.m(high); \ high = (1 << high); \ case 3: \ low = _bit_scan_forward(bits); \ bits ^= high | (1 << low); \ ith_value(low) = d.m(low); \ case 2: \ high = _bit_scan_reverse(bits); \ ith_value(high) = d.m(high); \ case 1: \ low = _bit_scan_forward(bits); \ ith_value(low) = d.m(low); \ case 0: \ break; \ } #else #define VC_MASKED_SCATTER \ if (mask.isEmpty()) { \ return; \ } \ for_all_vector_entries(i, \ if (mask[i]) ith_value(i) = d.m(i); \ ); #endif template<typename T> template<typename Index> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::scatter(EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes) const { for_all_vector_entries(i, mem[indexes[i]] = d.m(i); ); } #if defined(VC_MSVC) && VC_MSVC >= 170000000 // MSVC miscompiles the store mem[indexes[1]] = d.m(1) for T = (u)short template<> template<typename Index> Vc_ALWAYS_INLINE void short_v::scatter(EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes) const { const unsigned int tmp = d.v()._d.m128i_u32[0]; mem[indexes[0]] = tmp & 0xffff; mem[indexes[1]] = tmp >> 16; mem[indexes[2]] = _mm_extract_epi16(d.v(), 2); mem[indexes[3]] = _mm_extract_epi16(d.v(), 3); mem[indexes[4]] = _mm_extract_epi16(d.v(), 4); mem[indexes[5]] = _mm_extract_epi16(d.v(), 5); mem[indexes[6]] = _mm_extract_epi16(d.v(), 6); mem[indexes[7]] = _mm_extract_epi16(d.v(), 7); } template<> template<typename Index> Vc_ALWAYS_INLINE void ushort_v::scatter(EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes) const { const unsigned int tmp = d.v()._d.m128i_u32[0]; mem[indexes[0]] = tmp & 0xffff; mem[indexes[1]] = tmp >> 16; mem[indexes[2]] = _mm_extract_epi16(d.v(), 2); mem[indexes[3]] = _mm_extract_epi16(d.v(), 3); mem[indexes[4]] = _mm_extract_epi16(d.v(), 4); mem[indexes[5]] = _mm_extract_epi16(d.v(), 5); mem[indexes[6]] = _mm_extract_epi16(d.v(), 6); mem[indexes[7]] = _mm_extract_epi16(d.v(), 7); } #endif template<typename T> template<typename Index> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::scatter(EntryType *mem, VC_ALIGNED_PARAMETER(Index) indexes, MaskArg mask) const { #define ith_value(_i_) mem[indexes[_i_]] VC_MASKED_SCATTER #undef ith_value } template<typename T> template<typename S1, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::scatter(S1 *array, EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes) const { for_all_vector_entries(i, array[indexes[i]].*(member1) = d.m(i); ); } template<typename T> template<typename S1, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::scatter(S1 *array, EntryType S1::* member1, VC_ALIGNED_PARAMETER(IT) indexes, MaskArg mask) const { #define ith_value(_i_) array[indexes[_i_]].*(member1) VC_MASKED_SCATTER #undef ith_value } template<typename T> template<typename S1, typename S2, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::scatter(S1 *array, S2 S1::* member1, EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes) const { for_all_vector_entries(i, array[indexes[i]].*(member1).*(member2) = d.m(i); ); } template<typename T> template<typename S1, typename S2, typename IT> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::scatter(S1 *array, S2 S1::* member1, EntryType S2::* member2, VC_ALIGNED_PARAMETER(IT) indexes, MaskArg mask) const { #define ith_value(_i_) array[indexes[_i_]].*(member1).*(member2) VC_MASKED_SCATTER #undef ith_value } template<typename T> template<typename S1, typename IT1, typename IT2> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::scatter(S1 *array, EntryType *S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes) const { for_all_vector_entries(i, (array[innerIndexes[i]].*(ptrMember1))[outerIndexes[i]] = d.m(i); ); } template<typename T> template<typename S1, typename IT1, typename IT2> Vc_ALWAYS_INLINE void Vc_FLATTEN Vector<T>::scatter(S1 *array, EntryType *S1::* ptrMember1, VC_ALIGNED_PARAMETER(IT1) outerIndexes, VC_ALIGNED_PARAMETER(IT2) innerIndexes, MaskArg mask) const { #define ith_value(_i_) (array[outerIndexes[_i_]].*(ptrMember1))[innerIndexes[_i_]] VC_MASKED_SCATTER #undef ith_value } /////////////////////////////////////////////////////////////////////////////////////////// // operator- {{{1 template<> Vc_ALWAYS_INLINE Vector<double> Vc_PURE Vc_FLATTEN Vector<double>::operator-() const { return _mm256_xor_pd(d.v(), _mm256_setsignmask_pd()); } template<> Vc_ALWAYS_INLINE Vector<float> Vc_PURE Vc_FLATTEN Vector<float>::operator-() const { return _mm256_xor_ps(d.v(), _mm256_setsignmask_ps()); } template<> Vc_ALWAYS_INLINE Vector<sfloat> Vc_PURE Vc_FLATTEN Vector<sfloat>::operator-() const { return _mm256_xor_ps(d.v(), _mm256_setsignmask_ps()); } template<> Vc_ALWAYS_INLINE Vector<int> Vc_PURE Vc_FLATTEN Vector<int>::operator-() const { return _mm256_sign_epi32(d.v(), _mm256_setallone_si256()); } template<> Vc_ALWAYS_INLINE Vector<int> Vc_PURE Vc_FLATTEN Vector<unsigned int>::operator-() const { return _mm256_sign_epi32(d.v(), _mm256_setallone_si256()); } template<> Vc_ALWAYS_INLINE Vector<short> Vc_PURE Vc_FLATTEN Vector<short>::operator-() const { return _mm_sign_epi16(d.v(), _mm_setallone_si128()); } template<> Vc_ALWAYS_INLINE Vector<short> Vc_PURE Vc_FLATTEN Vector<unsigned short>::operator-() const { return _mm_sign_epi16(d.v(), _mm_setallone_si128()); } /////////////////////////////////////////////////////////////////////////////////////////// // horizontal ops {{{1 template<typename T> Vc_ALWAYS_INLINE typename Vector<T>::EntryType Vector<T>::min(MaskArg m) const { Vector<T> tmp = std::numeric_limits<Vector<T> >::max(); tmp(m) = *this; return tmp.min(); } template<typename T> Vc_ALWAYS_INLINE typename Vector<T>::EntryType Vector<T>::max(MaskArg m) const { Vector<T> tmp = std::numeric_limits<Vector<T> >::min(); tmp(m) = *this; return tmp.max(); } template<typename T> Vc_ALWAYS_INLINE typename Vector<T>::EntryType Vector<T>::product(MaskArg m) const { Vector<T> tmp(VectorSpecialInitializerOne::One); tmp(m) = *this; return tmp.product(); } template<typename T> Vc_ALWAYS_INLINE typename Vector<T>::EntryType Vector<T>::sum(MaskArg m) const { Vector<T> tmp(VectorSpecialInitializerZero::Zero); tmp(m) = *this; return tmp.sum(); }//}}} // copySign {{{1 template<> Vc_INTRINSIC Vector<float> Vector<float>::copySign(Vector<float>::AsArg reference) const { return _mm256_or_ps( _mm256_and_ps(reference.d.v(), _mm256_setsignmask_ps()), _mm256_and_ps(d.v(), _mm256_setabsmask_ps()) ); } template<> Vc_INTRINSIC Vector<sfloat> Vector<sfloat>::copySign(Vector<sfloat>::AsArg reference) const { return _mm256_or_ps( _mm256_and_ps(reference.d.v(), _mm256_setsignmask_ps()), _mm256_and_ps(d.v(), _mm256_setabsmask_ps()) ); } template<> Vc_INTRINSIC Vector<double> Vector<double>::copySign(Vector<double>::AsArg reference) const { return _mm256_or_pd( _mm256_and_pd(reference.d.v(), _mm256_setsignmask_pd()), _mm256_and_pd(d.v(), _mm256_setabsmask_pd()) ); }//}}}1 // exponent {{{1 template<> Vc_INTRINSIC Vector<float> Vector<float>::exponent() const { VC_ASSERT((*this >= 0.f).isFull()); return Internal::exponent(d.v()); } template<> Vc_INTRINSIC Vector<sfloat> Vector<sfloat>::exponent() const { VC_ASSERT((*this >= 0.f).isFull()); return Internal::exponent(d.v()); } template<> Vc_INTRINSIC Vector<double> Vector<double>::exponent() const { VC_ASSERT((*this >= 0.).isFull()); return Internal::exponent(d.v()); } // }}}1 // Random {{{1 static Vc_ALWAYS_INLINE void _doRandomStep(Vector<unsigned int> &state0, Vector<unsigned int> &state1) { state0.load(&Vc::RandomState[0]); state1.load(&Vc::RandomState[uint_v::Size]); (state1 * 0xdeece66du + 11).store(&Vc::RandomState[uint_v::Size]); uint_v(_mm256_xor_si256((state0 * 0xdeece66du + 11).data(), _mm256_srli_epi32(state1.data(), 16))).store(&Vc::RandomState[0]); } template<typename T> Vc_ALWAYS_INLINE Vector<T> Vector<T>::Random() { Vector<unsigned int> state0, state1; _doRandomStep(state0, state1); return state0.reinterpretCast<Vector<T> >(); } template<> Vc_ALWAYS_INLINE Vector<float> Vector<float>::Random() { Vector<unsigned int> state0, state1; _doRandomStep(state0, state1); return HT::sub(HV::or_(_cast(_mm256_srli_epi32(state0.data(), 2)), HT::one()), HT::one()); } template<> Vc_ALWAYS_INLINE Vector<sfloat> Vector<sfloat>::Random() { Vector<unsigned int> state0, state1; _doRandomStep(state0, state1); return HT::sub(HV::or_(_cast(_mm256_srli_epi32(state0.data(), 2)), HT::one()), HT::one()); } template<> Vc_ALWAYS_INLINE Vector<double> Vector<double>::Random() { const m256i state = VectorHelper<m256i>::load(&Vc::RandomState[0], Vc::Aligned); for (size_t k = 0; k < 8; k += 2) { typedef unsigned long long uint64 Vc_MAY_ALIAS; const uint64 stateX = *reinterpret_cast<const uint64 *>(&Vc::RandomState[k]); *reinterpret_cast<uint64 *>(&Vc::RandomState[k]) = (stateX * 0x5deece66dull + 11); } return (Vector<double>(_cast(_mm256_srli_epi64(state, 12))) | One()) - One(); } // }}}1 // shifted / rotated {{{1 template<size_t SIMDWidth, size_t Size, typename VectorType, typename EntryType> struct VectorShift; template<> struct VectorShift<32, 4, m256d, double> { static Vc_INTRINSIC m256d shifted(param256d v, int amount) { switch (amount) { case 0: return v; case 1: return avx_cast<m256d>(_mm256_srli_si256(avx_cast<m256i>(v), 1 * sizeof(double))); case 2: return avx_cast<m256d>(_mm256_srli_si256(avx_cast<m256i>(v), 2 * sizeof(double))); case 3: return avx_cast<m256d>(_mm256_srli_si256(avx_cast<m256i>(v), 3 * sizeof(double))); case -1: return avx_cast<m256d>(_mm256_slli_si256(avx_cast<m256i>(v), 1 * sizeof(double))); case -2: return avx_cast<m256d>(_mm256_slli_si256(avx_cast<m256i>(v), 2 * sizeof(double))); case -3: return avx_cast<m256d>(_mm256_slli_si256(avx_cast<m256i>(v), 3 * sizeof(double))); } return _mm256_setzero_pd(); } }; template<typename VectorType, typename EntryType> struct VectorShift<32, 8, VectorType, EntryType> { typedef typename SseVectorType<VectorType>::Type SmallV; static Vc_INTRINSIC VectorType shifted(VC_ALIGNED_PARAMETER(VectorType) v, int amount) { switch (amount) { case 0: return v; case 1: return avx_cast<VectorType>(_mm256_srli_si256(avx_cast<m256i>(v), 1 * sizeof(EntryType))); case 2: return avx_cast<VectorType>(_mm256_srli_si256(avx_cast<m256i>(v), 2 * sizeof(EntryType))); case 3: return avx_cast<VectorType>(_mm256_srli_si256(avx_cast<m256i>(v), 3 * sizeof(EntryType))); case 4: return avx_cast<VectorType>(_mm256_srli_si256(avx_cast<m256i>(v), 4 * sizeof(EntryType))); case 5: return avx_cast<VectorType>(_mm256_srli_si256(avx_cast<m256i>(v), 5 * sizeof(EntryType))); case 6: return avx_cast<VectorType>(_mm256_srli_si256(avx_cast<m256i>(v), 6 * sizeof(EntryType))); case 7: return avx_cast<VectorType>(_mm256_srli_si256(avx_cast<m256i>(v), 7 * sizeof(EntryType))); case -1: return avx_cast<VectorType>(_mm256_slli_si256(avx_cast<m256i>(v), 1 * sizeof(EntryType))); case -2: return avx_cast<VectorType>(_mm256_slli_si256(avx_cast<m256i>(v), 2 * sizeof(EntryType))); case -3: return avx_cast<VectorType>(_mm256_slli_si256(avx_cast<m256i>(v), 3 * sizeof(EntryType))); case -4: return avx_cast<VectorType>(_mm256_slli_si256(avx_cast<m256i>(v), 4 * sizeof(EntryType))); case -5: return avx_cast<VectorType>(_mm256_slli_si256(avx_cast<m256i>(v), 5 * sizeof(EntryType))); case -6: return avx_cast<VectorType>(_mm256_slli_si256(avx_cast<m256i>(v), 6 * sizeof(EntryType))); case -7: return avx_cast<VectorType>(_mm256_slli_si256(avx_cast<m256i>(v), 7 * sizeof(EntryType))); } return avx_cast<VectorType>(_mm256_setzero_ps()); } }; template<typename VectorType, typename EntryType> struct VectorShift<16, 8, VectorType, EntryType> { enum { EntryTypeSizeof = sizeof(EntryType) }; static Vc_INTRINSIC VectorType shifted(VC_ALIGNED_PARAMETER(VectorType) v, int amount) { switch (amount) { case 0: return v; case 1: return avx_cast<VectorType>(_mm_srli_si128(avx_cast<m128i>(v), 1 * EntryTypeSizeof)); case 2: return avx_cast<VectorType>(_mm_srli_si128(avx_cast<m128i>(v), 2 * EntryTypeSizeof)); case 3: return avx_cast<VectorType>(_mm_srli_si128(avx_cast<m128i>(v), 3 * EntryTypeSizeof)); case 4: return avx_cast<VectorType>(_mm_srli_si128(avx_cast<m128i>(v), 4 * EntryTypeSizeof)); case 5: return avx_cast<VectorType>(_mm_srli_si128(avx_cast<m128i>(v), 5 * EntryTypeSizeof)); case 6: return avx_cast<VectorType>(_mm_srli_si128(avx_cast<m128i>(v), 6 * EntryTypeSizeof)); case 7: return avx_cast<VectorType>(_mm_srli_si128(avx_cast<m128i>(v), 7 * EntryTypeSizeof)); case -1: return avx_cast<VectorType>(_mm_slli_si128(avx_cast<m128i>(v), 1 * EntryTypeSizeof)); case -2: return avx_cast<VectorType>(_mm_slli_si128(avx_cast<m128i>(v), 2 * EntryTypeSizeof)); case -3: return avx_cast<VectorType>(_mm_slli_si128(avx_cast<m128i>(v), 3 * EntryTypeSizeof)); case -4: return avx_cast<VectorType>(_mm_slli_si128(avx_cast<m128i>(v), 4 * EntryTypeSizeof)); case -5: return avx_cast<VectorType>(_mm_slli_si128(avx_cast<m128i>(v), 5 * EntryTypeSizeof)); case -6: return avx_cast<VectorType>(_mm_slli_si128(avx_cast<m128i>(v), 6 * EntryTypeSizeof)); case -7: return avx_cast<VectorType>(_mm_slli_si128(avx_cast<m128i>(v), 7 * EntryTypeSizeof)); } return _mm_setzero_si128(); } }; template<typename T> Vc_INTRINSIC Vector<T> Vector<T>::shifted(int amount) const { return VectorShift<sizeof(VectorType), Size, VectorType, EntryType>::shifted(d.v(), amount); } template<size_t SIMDWidth, size_t Size, typename VectorType, typename EntryType> struct VectorRotate; template<typename VectorType, typename EntryType> struct VectorRotate<32, 4, VectorType, EntryType> { typedef typename SseVectorType<VectorType>::Type SmallV; enum { EntryTypeSizeof = sizeof(EntryType) }; static Vc_INTRINSIC VectorType rotated(VC_ALIGNED_PARAMETER(VectorType) v, int amount) { const m128i vLo = avx_cast<m128i>(lo128(v)); const m128i vHi = avx_cast<m128i>(hi128(v)); switch (static_cast<unsigned int>(amount) % 4) { case 0: return v; case 1: return concat(avx_cast<SmallV>(_mm_alignr_epi8(vHi, vLo, 1 * EntryTypeSizeof)), avx_cast<SmallV>(_mm_alignr_epi8(vLo, vHi, 1 * EntryTypeSizeof))); case 2: return Mem::permute128<X1, X0>(v); case 3: return concat(avx_cast<SmallV>(_mm_alignr_epi8(vLo, vHi, 1 * EntryTypeSizeof)), avx_cast<SmallV>(_mm_alignr_epi8(vHi, vLo, 1 * EntryTypeSizeof))); } return _mm256_setzero_pd(); } }; template<typename VectorType, typename EntryType> struct VectorRotate<32, 8, VectorType, EntryType> { typedef typename SseVectorType<VectorType>::Type SmallV; enum { EntryTypeSizeof = sizeof(EntryType) }; static Vc_INTRINSIC VectorType rotated(VC_ALIGNED_PARAMETER(VectorType) v, int amount) { const m128i vLo = avx_cast<m128i>(lo128(v)); const m128i vHi = avx_cast<m128i>(hi128(v)); switch (static_cast<unsigned int>(amount) % 8) { case 0: return v; case 1: return concat(avx_cast<SmallV>(_mm_alignr_epi8(vHi, vLo, 1 * EntryTypeSizeof)), avx_cast<SmallV>(_mm_alignr_epi8(vLo, vHi, 1 * EntryTypeSizeof))); case 2: return concat(avx_cast<SmallV>(_mm_alignr_epi8(vHi, vLo, 2 * EntryTypeSizeof)), avx_cast<SmallV>(_mm_alignr_epi8(vLo, vHi, 2 * EntryTypeSizeof))); case 3: return concat(avx_cast<SmallV>(_mm_alignr_epi8(vHi, vLo, 3 * EntryTypeSizeof)), avx_cast<SmallV>(_mm_alignr_epi8(vLo, vHi, 3 * EntryTypeSizeof))); case 4: return Mem::permute128<X1, X0>(v); case 5: return concat(avx_cast<SmallV>(_mm_alignr_epi8(vLo, vHi, 1 * EntryTypeSizeof)), avx_cast<SmallV>(_mm_alignr_epi8(vHi, vLo, 1 * EntryTypeSizeof))); case 6: return concat(avx_cast<SmallV>(_mm_alignr_epi8(vLo, vHi, 2 * EntryTypeSizeof)), avx_cast<SmallV>(_mm_alignr_epi8(vHi, vLo, 2 * EntryTypeSizeof))); case 7: return concat(avx_cast<SmallV>(_mm_alignr_epi8(vLo, vHi, 3 * EntryTypeSizeof)), avx_cast<SmallV>(_mm_alignr_epi8(vHi, vLo, 3 * EntryTypeSizeof))); } return avx_cast<VectorType>(_mm256_setzero_ps()); } }; template<typename VectorType, typename EntryType> struct VectorRotate<16, 8, VectorType, EntryType> { enum { EntryTypeSizeof = sizeof(EntryType) }; static Vc_INTRINSIC VectorType rotated(VC_ALIGNED_PARAMETER(VectorType) v, int amount) { switch (static_cast<unsigned int>(amount) % 8) { case 0: return v; case 1: return avx_cast<VectorType>(_mm_alignr_epi8(v, v, 1 * EntryTypeSizeof)); case 2: return avx_cast<VectorType>(_mm_alignr_epi8(v, v, 2 * EntryTypeSizeof)); case 3: return avx_cast<VectorType>(_mm_alignr_epi8(v, v, 3 * EntryTypeSizeof)); case 4: return avx_cast<VectorType>(_mm_alignr_epi8(v, v, 4 * EntryTypeSizeof)); case 5: return avx_cast<VectorType>(_mm_alignr_epi8(v, v, 5 * EntryTypeSizeof)); case 6: return avx_cast<VectorType>(_mm_alignr_epi8(v, v, 6 * EntryTypeSizeof)); case 7: return avx_cast<VectorType>(_mm_alignr_epi8(v, v, 7 * EntryTypeSizeof)); } return _mm_setzero_si128(); } }; template<typename T> Vc_INTRINSIC Vector<T> Vector<T>::rotated(int amount) const { return VectorRotate<sizeof(VectorType), Size, VectorType, EntryType>::rotated(d.v(), amount); /* const m128i v0 = avx_cast<m128i>(d.v()[0]); const m128i v1 = avx_cast<m128i>(d.v()[1]); switch (static_cast<unsigned int>(amount) % Size) { case 0: return *this; case 1: return concat(avx_cast<m128>(_mm_alignr_epi8(v1, v0, 1 * sizeof(EntryType))), avx_cast<m128>(_mm_alignr_epi8(v0, v1, 1 * sizeof(EntryType)))); case 2: return concat(avx_cast<m128>(_mm_alignr_epi8(v1, v0, 2 * sizeof(EntryType))), avx_cast<m128>(_mm_alignr_epi8(v0, v1, 2 * sizeof(EntryType)))); case 3: return concat(avx_cast<m128>(_mm_alignr_epi8(v1, v0, 3 * sizeof(EntryType))), avx_cast<m128>(_mm_alignr_epi8(v0, v1, 3 * sizeof(EntryType)))); case 4: return concat(d.v()[1], d.v()[0]); case 5: return concat(avx_cast<m128>(_mm_alignr_epi8(v0, v1, 1 * sizeof(EntryType))), avx_cast<m128>(_mm_alignr_epi8(v1, v0, 1 * sizeof(EntryType)))); case 6: return concat(avx_cast<m128>(_mm_alignr_epi8(v0, v1, 2 * sizeof(EntryType))), avx_cast<m128>(_mm_alignr_epi8(v1, v0, 2 * sizeof(EntryType)))); case 7: return concat(avx_cast<m128>(_mm_alignr_epi8(v0, v1, 3 * sizeof(EntryType))), avx_cast<m128>(_mm_alignr_epi8(v1, v0, 3 * sizeof(EntryType)))); } */ } // }}}1 } // namespace AVX } // namespace Vc } // namespace AliRoot #include "undomacros.h" // vim: foldmethod=marker
50.981521
262
0.656634
AllaMaevskaya
626f7e41d53914c6d7a2d34755b67e028b8fe0fb
637
cpp
C++
oop_ex41.cpp
85105/HW
2161a1a7ac1082a85454672d359c00f2d42ef21f
[ "MIT" ]
null
null
null
oop_ex41.cpp
85105/HW
2161a1a7ac1082a85454672d359c00f2d42ef21f
[ "MIT" ]
null
null
null
oop_ex41.cpp
85105/HW
2161a1a7ac1082a85454672d359c00f2d42ef21f
[ "MIT" ]
null
null
null
/* oop_ex41.cpp accessing data members through pointer */ #include <iostream> #include <string> using namespace std; struct User { string name; int age; int tel; }; void main() { User userObject; User* userPtr = &userObject; //User* userPtr = new User(); userPtr->name = "Micheal"; userPtr->age = 20; userPtr->tel = 1234567; cout << " name | age | tel" << endl; cout << " userObject: " << userPtr->name << " " << userPtr->age << " " << userPtr->tel << endl << endl;; cout << " userObject: " << (*userPtr).name << " " << (*userPtr).age << " " << (*userPtr).tel << endl << endl;; system("pause"); }
18.2
113
0.572998
85105
62708b59e721ebda2cdf84c9034931cf94c8c8d4
612
hpp
C++
include/search/Tokenize.hpp
ibanic/search
9e7da36bb8512dc9bfc1e65d12aae3406659e318
[ "MIT" ]
null
null
null
include/search/Tokenize.hpp
ibanic/search
9e7da36bb8512dc9bfc1e65d12aae3406659e318
[ "MIT" ]
null
null
null
include/search/Tokenize.hpp
ibanic/search
9e7da36bb8512dc9bfc1e65d12aae3406659e318
[ "MIT" ]
null
null
null
// // Tokenize.hpp // // Created by Ignac Banic on 31/12/19. // Copyright © 2019 Ignac Banic. All rights reserved. // #pragma once #include <string> #include <vector> namespace Search { uint8_t charLen(char ch); std::vector<std::string> tokenize(std::string_view txt); std::vector<std::string> tokenize(const std::string& txt); std::string joinTokens(const std::vector<std::string>& tokens); std::vector<std::string> splitTokens(std::string_view txt); bool tokensOverlap(std::string_view all, std::string_view search); size_t numTokensOverlap(const std::string& all, const std::string& search); }
26.608696
76
0.722222
ibanic
6270b83de03cebb175575dca493d1479ad360a7a
32,668
cpp
C++
src/OpcUaStackServer/ServiceSet/Session.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
108
2018-10-08T17:03:32.000Z
2022-03-21T00:52:26.000Z
src/OpcUaStackServer/ServiceSet/Session.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
287
2018-09-18T14:59:12.000Z
2022-01-13T12:28:23.000Z
src/OpcUaStackServer/ServiceSet/Session.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
32
2018-10-19T14:35:03.000Z
2021-11-12T09:36:46.000Z
/* Copyright 2017-2019 Kai Huebl (kai@huebl-sgh.de) Lizenziert gemäß Apache Licence Version 2.0 (die „Lizenz“); Nutzung dieser Datei nur in Übereinstimmung mit der Lizenz erlaubt. Eine Kopie der Lizenz erhalten Sie auf http://www.apache.org/licenses/LICENSE-2.0. Sofern nicht gemäß geltendem Recht vorgeschrieben oder schriftlich vereinbart, erfolgt die Bereitstellung der im Rahmen der Lizenz verbreiteten Software OHNE GEWÄHR ODER VORBEHALTE – ganz gleich, ob ausdrücklich oder stillschweigend. Informationen über die jeweiligen Bedingungen für Genehmigungen und Einschränkungen im Rahmen der Lizenz finden Sie in der Lizenz. Autor: Kai Huebl (kai@huebl-sgh.de) */ #include "OpcUaStackServer/ServiceSet/Session.h" #include "OpcUaStackCore/BuildInTypes/OpcUaIdentifier.h" #include "OpcUaStackCore/Base/Log.h" #include "OpcUaStackCore/Base/MemoryBuffer.h" #include "OpcUaStackCore/Base/Utility.h" #include "OpcUaStackCore/SecureChannel/RequestHeader.h" #include "OpcUaStackCore/ServiceSet/CreateSessionRequest.h" #include "OpcUaStackCore/ServiceSet/CreateSessionResponse.h" #include "OpcUaStackCore/ServiceSet/CloseSessionRequest.h" #include "OpcUaStackCore/ServiceSet/CloseSessionResponse.h" #include "OpcUaStackCore/ServiceSet/CancelRequest.h" #include "OpcUaStackCore/ServiceSet/CancelResponse.h" #include "OpcUaStackCore/ServiceSet/ActivateSessionResponse.h" #include "OpcUaStackCore/Application/ApplicationAuthenticationContext.h" #include "OpcUaStackCore/Application/ApplicationCloseSessionContext.h" #include "OpcUaStackCore/ServiceSet/AnonymousIdentityToken.h" #include "OpcUaStackCore/ServiceSet/UserNameIdentityToken.h" #include "OpcUaStackCore/ServiceSet/IssuedIdentityToken.h" #include "OpcUaStackCore/ServiceSet/X509IdentityToken.h" using namespace OpcUaStackCore; namespace OpcUaStackServer { boost::mutex Session::mutex_; OpcUaUInt32 Session::uniqueSessionId_ = 0; OpcUaUInt32 Session::uniqueAuthenticationToken_ = 0; OpcUaUInt32 Session::getUniqueSessionId(void) { boost::mutex::scoped_lock g(mutex_); uniqueSessionId_++; return uniqueSessionId_; } OpcUaUInt32 Session::getUniqueAuthenticationToken(void) { boost::mutex::scoped_lock g(mutex_); uniqueAuthenticationToken_++; return uniqueAuthenticationToken_; } Session::Session(void) : Component() , forwardGlobalSync_() , sessionIf_(nullptr) , sessionState_(SessionState_Close) , sessionId_(getUniqueSessionId()) , authenticationToken_(getUniqueAuthenticationToken()) , applicationCertificate_() , endpointDescriptionArray_() , endpointDescription_() , userContext_() , clientCertificate_() { Log(Info, "session construct") .parameter("SessionId", sessionId_) .parameter("AuthenticationToken", authenticationToken_); componentName("Session"); } Session::~Session(void) { } void Session::createServerNonce(void) { for (uint32_t idx=0; idx<32; idx++) { serverNonce_[idx] = (rand() / 256); } } void Session::applicationCertificate(ApplicationCertificate::SPtr& applicationCertificate) { applicationCertificate_ = applicationCertificate; } void Session::cryptoManager(CryptoManager::SPtr& cryptoManager) { cryptoManager_ = cryptoManager; } void Session::transactionManager(TransactionManager::SPtr transactionManagerSPtr) { transactionManagerSPtr_ = transactionManagerSPtr; } void Session::forwardGlobalSync(ForwardGlobalSync::SPtr& forwardGlobalSync) { forwardGlobalSync_ = forwardGlobalSync; } void Session::sessionIf(SessionIf* sessionIf) { sessionIf_ = sessionIf; } OpcUaUInt32 Session::sessionId(void) { return sessionId_; } OpcUaUInt32 Session::authenticationToken(void) { return authenticationToken_; } void Session::endpointDescriptionArray(EndpointDescriptionArray::SPtr& endpointDescriptionArray) { endpointDescriptionArray_ = endpointDescriptionArray; } void Session::endpointDescription(EndpointDescription::SPtr& endpointDescription) { endpointDescription_ = endpointDescription; } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // // authentication // // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ OpcUaStatusCode Session::authentication(ActivateSessionRequest& activateSessionRequest) { userContext_.reset(); if (forwardGlobalSync_.get() == nullptr) { // no authentication is activated return Success; } if (!forwardGlobalSync_->authenticationService().isCallback()) { // no authentication is activated return Success; } if (activateSessionRequest.userIdentityToken().get() == nullptr) { // user identity token is invalid Log(Error, "authentication error, because user identity token is invalid"); return BadIdentityTokenInvalid; } else { ExtensibleParameter::SPtr parameter = activateSessionRequest.userIdentityToken(); if (!parameter->exist()) { // user identity token is invalid Log(Error, "authentication error, because user identity token not exist"); return BadIdentityTokenInvalid; } else { OpcUaNodeId typeId = parameter->parameterTypeId(); if (typeId == OpcUaNodeId(OpcUaId_AnonymousIdentityToken_Encoding_DefaultBinary)) { return authenticationAnonymous(activateSessionRequest, parameter); } else if (typeId == OpcUaNodeId(OpcUaId_UserNameIdentityToken_Encoding_DefaultBinary)) { return authenticationUserName(activateSessionRequest, parameter); } else if (typeId == OpcUaId_X509IdentityToken_Encoding_DefaultBinary) { return authenticationX509(activateSessionRequest, parameter); } else if (typeId == OpcUaId_IssuedIdentityToken_Encoding_DefaultBinary) { return authenticationIssued(activateSessionRequest, parameter); } else { // user identity token is invalid Log(Error, "authentication error, because unknown authentication type") .parameter("AuthenticationType", typeId); return BadIdentityTokenInvalid; } } } return Success; } OpcUaStatusCode Session::authenticationCloseSession(void) { ApplicationCloseSessionContext context; context.sessionId_ = sessionId_; context.statusCode_ = Success; context.userContext_ = userContext_; if (forwardGlobalSync_->closeSessionService().isCallback()) { forwardGlobalSync_->closeSessionService().callback()(&context); } userContext_.reset(); return context.statusCode_; } OpcUaStatusCode Session::authenticationAnonymous(ActivateSessionRequest& activateSessionRequest, ExtensibleParameter::SPtr& parameter) { OpcUaStatusCode statusCode; Log(Debug, "Session::authenticationAnonymous"); AnonymousIdentityToken::SPtr token = parameter->parameter<AnonymousIdentityToken>(); // check token policy UserTokenPolicy::SPtr userTokenPolicy; statusCode = checkUserTokenPolicy(token->policyId(), UserIdentityTokenType_Anonymous, userTokenPolicy); if (statusCode != Success) { return statusCode; } Log(Debug, "authentication anonymous") .parameter("PolicyId", token->policyId()); // create authentication context ApplicationAuthenticationContext context; context.authenticationType_ = OpcUaId_AnonymousIdentityToken_Encoding_DefaultBinary; context.parameter_ = parameter; context.sessionId_ = sessionId_; context.statusCode_ = Success; context.userContext_.reset(); // call anonymous authentication forwardGlobalSync_->authenticationService().callback()(&context); if (context.statusCode_ == Success) { userContext_ = context.userContext_; } return context.statusCode_; } OpcUaStatusCode Session::authenticationUserName(ActivateSessionRequest& activateSessionRequest, ExtensibleParameter::SPtr& parameter) { OpcUaStatusCode statusCode; Log(Debug, "Session::authenticationUserName"); UserNameIdentityToken::SPtr token = parameter->parameter<UserNameIdentityToken>(); // check parameter and password if (token->userName().size() == 0) { Log(Debug, "user name invalid"); return BadIdentityTokenInvalid; } // check token policy UserTokenPolicy::SPtr userTokenPolicy; statusCode = checkUserTokenPolicy(token->policyId(), UserIdentityTokenType_Username, userTokenPolicy); if (statusCode != Success) { return statusCode; } Log(Debug, "authentication user name") .parameter("PolicyId", token->policyId()) .parameter("UserName", token->userName()) .parameter("SecurityPolicyUri", userTokenPolicy->securityPolicyUri()) .parameter("EncyptionAlgorithmus", token->encryptionAlgorithm()); if (token->encryptionAlgorithm() == "") { // we use a plain password // create application context ApplicationAuthenticationContext context; context.authenticationType_ = OpcUaId_UserNameIdentityToken_Encoding_DefaultBinary; context.parameter_ = parameter; context.sessionId_ = sessionId_; context.statusCode_ = Success; context.userContext_.reset(); // call user name authentication forwardGlobalSync_->authenticationService().callback()(&context); if (context.statusCode_ == Success) { userContext_ = context.userContext_; } return context.statusCode_; } // get cryption base and check cryption alg CryptoBase::SPtr cryptoBase = cryptoManager_->get(userTokenPolicy->securityPolicyUri()); if (cryptoBase.get() == nullptr) { Log(Debug, "crypto manager not found") .parameter("SecurityPolicyUri", userTokenPolicy->securityPolicyUri()); return BadIdentityTokenRejected; } uint32_t encryptionAlg = EnryptionAlgs::uriToEncryptionAlg(token->encryptionAlgorithm()); if (encryptionAlg == 0) { Log(Debug, "encryption alg invalid") .parameter("EncryptionAlgorithm", token->encryptionAlgorithm()); return BadIdentityTokenRejected;; } // decrypt password char* encryptedTextBuf; int32_t encryptedTextLen; token->password((OpcUaByte**)&encryptedTextBuf, &encryptedTextLen); if (encryptedTextLen <= 0) { Log(Debug, "password format invalid"); return BadIdentityTokenRejected;; } char* plainTextBuf; uint32_t plainTextLen; MemoryBuffer plainText(encryptedTextLen); plainTextBuf = plainText.memBuf(); plainTextLen = plainText.memLen(); PrivateKey::SPtr privateKey = applicationCertificate_->privateKey(); statusCode = cryptoBase->asymmetricDecrypt( encryptedTextBuf, encryptedTextLen, *privateKey.get(), plainTextBuf, &plainTextLen ); if (statusCode != Success) { Log(Debug, "decrypt password error"); return BadIdentityTokenRejected;; } // check decrypted password and server nonce if (memcmp(serverNonce_, &plainTextBuf[plainTextLen-32] , 32) != 0) { Log(Debug, "decrypt password server nonce error"); return BadIdentityTokenRejected;; } size_t passwordLen = plainTextLen-36; if (passwordLen < 0) { Log(Debug, "decrypted password length < 0"); return BadIdentityTokenRejected;; } token->password((const OpcUaByte*)&plainTextBuf[4], passwordLen); // create application context ApplicationAuthenticationContext context; context.authenticationType_ = OpcUaId_UserNameIdentityToken_Encoding_DefaultBinary; context.parameter_ = parameter; context.sessionId_ = sessionId_; context.statusCode_ = Success; context.userContext_.reset(); forwardGlobalSync_->authenticationService().callback()(&context); if (context.statusCode_ == Success) { userContext_ = context.userContext_; } return context.statusCode_; } OpcUaStatusCode Session::authenticationX509(ActivateSessionRequest& activateSessionRequest, ExtensibleParameter::SPtr& parameter) { OpcUaStatusCode statusCode; Log(Debug, "Session::authenticationX509"); X509IdentityToken::SPtr token = parameter->parameter<X509IdentityToken>(); // check parameter and password if (token->certificateData().size() == 0) { Log(Debug, "token data invalid"); return BadIdentityTokenInvalid; } // check token policy UserTokenPolicy::SPtr userTokenPolicy; statusCode = checkUserTokenPolicy(token->policyId(), UserIdentityTokenType_Certificate, userTokenPolicy); if (statusCode != Success) { return statusCode; } // get signature data SignatureData::SPtr userTokenSignature = activateSessionRequest.userTokenSignature(); if (userTokenSignature.get() == nullptr) { Log(Debug, "missing user token signature") .parameter("PolicyId", token->policyId()); return BadIdentityTokenInvalid; } Log(Debug, "authentication x509") .parameter("PolicyId", token->policyId()) .parameter("CertificateData", token->certificateData()) .parameter("SecurityPolicyUri", userTokenPolicy->securityPolicyUri()); // get cryption base and check cryption alg CryptoBase::SPtr cryptoBase = cryptoManager_->get(userTokenPolicy->securityPolicyUri()); if (cryptoBase.get() == nullptr) { Log(Debug, "crypto manager not found") .parameter("SecurityPolicyUri", userTokenPolicy->securityPolicyUri()); return BadIdentityTokenRejected; } uint32_t signatureAlg = SignatureAlgs::uriToSignatureAlg(userTokenSignature->algorithm()); if (signatureAlg == 0) { Log(Debug, "encryption alg invalid") .parameter("SignatureAlgorithm", userTokenSignature->algorithm()); return BadIdentityTokenRejected;; } // get public key MemoryBuffer certificateText(token->certificateData()); Certificate certificate; if (!certificate.fromDERBuf(certificateText)) { Log(Debug, "certificate invalid"); return BadIdentityTokenRejected;; } PublicKey publicKey = certificate.publicKey(); // FIXME: certificate must be trusted ... // validate signature statusCode = userTokenSignature->verifySignature( certificateText, publicKey, *cryptoBase ); // create application context ApplicationAuthenticationContext context; context.authenticationType_ = OpcUaId_X509IdentityToken_Encoding_DefaultBinary; context.parameter_ = parameter; context.sessionId_ = sessionId_; context.statusCode_ = Success; context.userContext_.reset(); forwardGlobalSync_->authenticationService().callback()(&context); if (context.statusCode_ == Success) { userContext_ = context.userContext_; } return context.statusCode_; } OpcUaStatusCode Session::authenticationIssued(ActivateSessionRequest& activateSessionRequest, ExtensibleParameter::SPtr& parameter) { OpcUaStatusCode statusCode; Log(Debug, "Session::authenticationIssued"); IssuedIdentityToken::SPtr token = parameter->parameter<IssuedIdentityToken>(); // check parameter and password if (token->tokenData().size() == 0) { Log(Debug, "token data invalid"); return BadIdentityTokenInvalid; } // check token policy UserTokenPolicy::SPtr userTokenPolicy; statusCode = checkUserTokenPolicy(token->policyId(), UserIdentityTokenType_IssuedToken, userTokenPolicy); if (statusCode != Success) { return statusCode; } Log(Debug, "authentication issued") .parameter("PolicyId", token->policyId()) .parameter("TokenData", token->tokenData()) .parameter("SecurityPolicyUri", userTokenPolicy->securityPolicyUri()) .parameter("EncyptionAlgorithmus", token->encryptionAlgorithm()); // get cryption base and check cryption alg CryptoBase::SPtr cryptoBase = cryptoManager_->get(userTokenPolicy->securityPolicyUri()); if (cryptoBase.get() == nullptr) { Log(Debug, "crypto manager not found") .parameter("SecurityPolicyUri", userTokenPolicy->securityPolicyUri()); return BadIdentityTokenRejected; } uint32_t encryptionAlg = EnryptionAlgs::uriToEncryptionAlg(token->encryptionAlgorithm()); if (encryptionAlg == 0) { Log(Debug, "encryption alg invalid") .parameter("EncryptionAlgorithm", token->encryptionAlgorithm()); return BadIdentityTokenRejected;; } // decrypt token data char* encryptedTextBuf; int32_t encryptedTextLen; token->tokenData((OpcUaByte**)&encryptedTextBuf, &encryptedTextLen); if (encryptedTextLen <= 0) { Log(Debug, "token data format invalid"); return BadIdentityTokenRejected;; } char* plainTextBuf; uint32_t plainTextLen; MemoryBuffer plainText(encryptedTextLen); plainTextBuf = plainText.memBuf(); plainTextLen = plainText.memLen(); PrivateKey::SPtr privateKey = applicationCertificate_->privateKey(); statusCode = cryptoBase->asymmetricDecrypt( encryptedTextBuf, encryptedTextLen, *privateKey.get(), plainTextBuf, &plainTextLen ); if (statusCode != Success) { Log(Debug, "decrypt token data error"); return BadIdentityTokenRejected;; } // check decrypted password and server nonce if (memcmp(serverNonce_, &plainTextBuf[plainTextLen-32] , 32) != 0) { Log(Debug, "decrypt token data server nonce error"); return BadIdentityTokenRejected;; } token->tokenData((const OpcUaByte*)&plainTextBuf[4], plainTextLen-36); // create application context ApplicationAuthenticationContext context; context.authenticationType_ = OpcUaId_IssuedIdentityToken_Encoding_DefaultBinary; context.parameter_ = parameter; context.sessionId_ = sessionId_; context.statusCode_ = Success; context.userContext_.reset(); forwardGlobalSync_->authenticationService().callback()(&context); if (context.statusCode_ == Success) { userContext_ = context.userContext_; } return context.statusCode_; } OpcUaStatusCode Session::checkUserTokenPolicy( const std::string& policyId, UserIdentityTokenType userIdentityTokenType, UserTokenPolicy::SPtr& userTokenPolicy ) { if (endpointDescription_.get() == nullptr) { Log(Debug, "endpoint description not exist"); return BadIdentityTokenInvalid; } if (endpointDescription_->userIdentityTokens().get() == nullptr) { Log(Debug, "user identity token not exist"); return BadIdentityTokenInvalid; } // find related identity token bool found = false; for (uint32_t idx=0; idx<endpointDescription_->userIdentityTokens()->size(); idx++) { if (!endpointDescription_->userIdentityTokens()->get(idx, userTokenPolicy)) { continue; } if (userTokenPolicy->tokenType() != userIdentityTokenType) { continue; } if (userTokenPolicy->policyId() == policyId) { found = true; break; } } if (!found) { Log(Debug, "identity token for policy not found in endpoint") .parameter("PolicyId", policyId); return BadIdentityTokenInvalid; } return Success; } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // // create session request // // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ void Session::createSessionRequest( RequestHeader::SPtr requestHeader, SecureChannelTransaction::SPtr secureChannelTransaction ) { createServerNonce(); OpcUaStatusCode statusCode; OpcUaStatusCode serviceResult = Success; Log(Debug, "receive create session request"); secureChannelTransaction->responseTypeNodeId_ = OpcUaId_CreateSessionResponse_Encoding_DefaultBinary; if (sessionState_ != SessionState_Close) { Log(Error, "receive create session request in invalid state") .parameter("SessionState", sessionState_); // FIXME: handle error ... } std::iostream ios(&secureChannelTransaction->is_); CreateSessionRequest createSessionRequest; createSessionRequest.opcUaBinaryDecode(ios); std::iostream iosres(&secureChannelTransaction->os_); CreateSessionResponse createSessionResponse; createSessionResponse.responseHeader()->requestHandle(requestHeader->requestHandle()); createSessionResponse.responseHeader()->serviceResult(serviceResult); if (createSessionRequest.clientCertificate().exist()) { clientCertificate_.fromDERBuf( createSessionRequest.clientCertificate().memBuf(), createSessionRequest.clientCertificate().size() ); } createSessionResponse.sessionId().namespaceIndex(1); createSessionResponse.sessionId().nodeId(sessionId_); createSessionResponse.authenticationToken().namespaceIndex(1); createSessionResponse.authenticationToken().nodeId(authenticationToken_); createSessionResponse.receivedSessionTimeout(120000); createSessionResponse.serverEndpoints(endpointDescriptionArray_); createSessionResponse.maxRequestMessageSize(0); // added server certificate createSessionResponse.serverNonce((const OpcUaByte*)serverNonce_, 32); applicationCertificate_->certificate()->toDERBuf(createSessionResponse.serverCertificate()); if (applicationCertificate_.get() != nullptr && secureChannelTransaction->cryptoBase_.get() != nullptr) { // create server signature MemoryBuffer clientCertificate(createSessionRequest.clientCertificate()); MemoryBuffer clientNonce(createSessionRequest.clientNonce()); PrivateKey privateKey = *applicationCertificate_->privateKey(); statusCode = createSessionResponse.signatureData()->createSignature( clientCertificate, clientNonce, privateKey, *secureChannelTransaction->cryptoBase_ ); if (statusCode != Success) { Log(Error, "create server signature in create session request error") .parameter("StatusCode", OpcUaStatusCodeMap::shortString(statusCode)); createSessionResponse.responseHeader()->serviceResult(BadSecurityChecksFailed); } } createSessionResponse.responseHeader()->opcUaBinaryEncode(iosres); createSessionResponse.opcUaBinaryEncode(iosres); sessionState_ = SessionState_CreateSessionResponse; if (sessionIf_ != nullptr) { ResponseHeader::SPtr responseHeader = createSessionResponse.responseHeader(); sessionIf_->responseMessage(responseHeader, secureChannelTransaction); } } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // // activate session request // // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ void Session::activateSessionRequest( RequestHeader::SPtr requestHeader, SecureChannelTransaction::SPtr secureChannelTransaction ) { OpcUaStatusCode statusCode; Log(Debug, "receive activate session request"); secureChannelTransaction->responseTypeNodeId_ = OpcUaId_ActivateSessionResponse_Encoding_DefaultBinary; // FIXME: if authenticationToken in the secureChannelTransaction contains 0 then // the session has a new secure channel std::iostream ios(&secureChannelTransaction->is_); ActivateSessionRequest activateSessionRequest; activateSessionRequest.opcUaBinaryDecode(ios); if (sessionState_ != SessionState_CreateSessionResponse && sessionState_ != SessionState_Ready) { Log(Error, "receive activate session request in invalid state") .parameter("SessionState", sessionState_); activateSessionRequestError(requestHeader, secureChannelTransaction, BadIdentityTokenInvalid); return; } // check client signature if (secureChannelTransaction->cryptoBase_.get() != nullptr) { // create certificate uint32_t derCertSize = applicationCertificate_->certificate()->getDERBufSize(); MemoryBuffer certificate(derCertSize); applicationCertificate_->certificate()->toDERBuf( certificate.memBuf(), &derCertSize ); // create server nonce MemoryBuffer serverNonce(serverNonce_, 32); // verify signature PublicKey publicKey = clientCertificate_.publicKey(); statusCode = activateSessionRequest.clientSignature()->verifySignature( certificate, serverNonce, publicKey, *secureChannelTransaction->cryptoBase_ ); if (statusCode != Success) { Log(Error, "client signature error"); activateSessionRequestError(requestHeader, secureChannelTransaction, BadSecurityChecksFailed); return; } } // check username and password statusCode = authentication(activateSessionRequest); std::iostream iosres(&secureChannelTransaction->os_); createServerNonce(); ActivateSessionResponse activateSessionResponse; activateSessionResponse.responseHeader()->requestHandle(requestHeader->requestHandle()); activateSessionResponse.responseHeader()->serviceResult(statusCode); activateSessionResponse.serverNonce((const OpcUaByte*)serverNonce_, 32); activateSessionResponse.responseHeader()->opcUaBinaryEncode(iosres); activateSessionResponse.opcUaBinaryEncode(iosres); sessionState_ = SessionState_Ready; //secureChannelTransaction->authenticationToken_ = authenticationToken_; if (sessionIf_ != nullptr) { ResponseHeader::SPtr responseHeader = activateSessionResponse.responseHeader(); sessionIf_->responseMessage(responseHeader, secureChannelTransaction); } } void Session::activateSessionRequestError( RequestHeader::SPtr& requestHeader, SecureChannelTransaction::SPtr secureChannelTransaction, OpcUaStatusCode statusCode, bool deleteSession ) { std::iostream iosres(&secureChannelTransaction->os_); ActivateSessionResponse activateSessionResponse; activateSessionResponse.responseHeader()->requestHandle(requestHeader->requestHandle()); activateSessionResponse.responseHeader()->serviceResult(statusCode); activateSessionResponse.responseHeader()->opcUaBinaryEncode(iosres); activateSessionResponse.opcUaBinaryEncode(iosres); if (sessionIf_ != nullptr) { ResponseHeader::SPtr responseHeader = activateSessionResponse.responseHeader(); sessionIf_->responseMessage(responseHeader, secureChannelTransaction); if (deleteSession) { sessionIf_->deleteSession(authenticationToken_); } } } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // // close session request // // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ void Session::closeSessionRequest( RequestHeader::SPtr requestHeader, SecureChannelTransaction::SPtr secureChannelTransaction ) { Log(Debug, "receive close session request"); secureChannelTransaction->responseTypeNodeId_ = OpcUaId_CloseSessionResponse_Encoding_DefaultBinary; std::iostream ios(&secureChannelTransaction->is_); CloseSessionRequest closeSessionRequest; closeSessionRequest.opcUaBinaryDecode(ios); std::iostream iosres(&secureChannelTransaction->os_); CloseSessionResponse closeSessionResponse; closeSessionResponse.responseHeader()->requestHandle(requestHeader->requestHandle()); closeSessionResponse.responseHeader()->serviceResult(Success); closeSessionResponse.responseHeader()->opcUaBinaryEncode(iosres); closeSessionResponse.opcUaBinaryEncode(iosres); // close session authenticationCloseSession(); if (sessionIf_ != nullptr) { ResponseHeader::SPtr responseHeader = closeSessionResponse.responseHeader(); sessionIf_->responseMessage(responseHeader, secureChannelTransaction); // FIXME: BUG - After deleting the session, the monitored item will send a notification. -> CORE //sessionIf_->deleteSession(authenticationToken_); } } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // // cancel request // // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ void Session::cancelRequest( RequestHeader::SPtr requestHeader, SecureChannelTransaction::SPtr secureChannelTransaction ) { Log(Debug, "receive cancel request"); secureChannelTransaction->responseTypeNodeId_ = OpcUaId_CancelResponse_Encoding_DefaultBinary; std::iostream ios(&secureChannelTransaction->is_); CancelRequest cancelRequest; cancelRequest.opcUaBinaryDecode(ios); cancelRequestError(requestHeader, secureChannelTransaction, BadNotImplemented); } void Session::cancelRequestError( RequestHeader::SPtr& requestHeader, SecureChannelTransaction::SPtr secureChannelTransaction, OpcUaStatusCode statusCode ) { std::iostream iosres(&secureChannelTransaction->os_); CancelResponse cancelResponse; cancelResponse.responseHeader()->requestHandle(requestHeader->requestHandle()); cancelResponse.responseHeader()->serviceResult(statusCode); cancelResponse.responseHeader()->opcUaBinaryEncode(iosres); cancelResponse.opcUaBinaryEncode(iosres); if (sessionIf_ != nullptr) { ResponseHeader::SPtr responseHeader = cancelResponse.responseHeader(); sessionIf_->responseMessage(responseHeader, secureChannelTransaction); } } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // // message request // // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ void Session::messageRequest( RequestHeader::SPtr requestHeader, SecureChannelTransaction::SPtr secureChannelTransaction ) { Log(Debug, "receive message request"); if (sessionState_ != SessionState_Ready) { Log(Error, "receive message request in invalid state") .parameter("SessionState", sessionState_) .parameter("TypeId", secureChannelTransaction->requestTypeNodeId_); // FIXME: error handling return; } if (transactionManagerSPtr_.get() == nullptr) { Log(Error, "transaction manager empty"); // ignore request - we cannot generate a response return; } ServiceTransaction::SPtr serviceTransactionSPtr = transactionManagerSPtr_->getTransaction(secureChannelTransaction->requestTypeNodeId_); if (serviceTransactionSPtr.get() == nullptr) { Log(Error, "receive invalid message type") .parameter("TypeId", secureChannelTransaction->requestTypeNodeId_); // ignore request - we cannot generate a response return; } secureChannelTransaction->responseTypeNodeId_ = OpcUaNodeId(serviceTransactionSPtr->nodeTypeResponse().nodeId<uint32_t>()); serviceTransactionSPtr->componentSession(this); serviceTransactionSPtr->sessionId(sessionId_); serviceTransactionSPtr->userContext(userContext_); Object::SPtr handle = secureChannelTransaction; serviceTransactionSPtr->handle(handle); // FIXME: serviceTransactionSPtr->channelId(secureChannelTransaction->channelId_); std::iostream ios(&secureChannelTransaction->is_); serviceTransactionSPtr->requestHeader(requestHeader); //OpcUaStackCore::dumpHex(sb); serviceTransactionSPtr->opcUaBinaryDecodeRequest(ios); //OpcUaStackCore::dumpHex(sb); serviceTransactionSPtr->requestId_ = secureChannelTransaction->requestId_; serviceTransactionSPtr->statusCode(Success); Log(Debug, "receive request in session") .parameter("TrxId", serviceTransactionSPtr->transactionId()) .parameter("TypeId", serviceTransactionSPtr->requestName()) .parameter("RequestId", serviceTransactionSPtr->requestId_); serviceTransactionSPtr->componentService()->send(serviceTransactionSPtr); } void Session::messageRequestError( SecureChannelTransaction::SPtr secureChannelTransaction, OpcUaStatusCode statusCode ) { // FIXME: todo } void Session::receive(Message::SPtr message) { ServiceTransaction::SPtr serviceTransactionSPtr = boost::static_pointer_cast<ServiceTransaction>(message); Log(Debug, "receive response in session") .parameter("TrxId", serviceTransactionSPtr->transactionId()) .parameter("TypeId", serviceTransactionSPtr->responseName()) .parameter("RequestId", serviceTransactionSPtr->requestId_) .parameter("StatusCode", OpcUaStatusCodeMap::shortString(serviceTransactionSPtr->statusCode())); RequestHeader::SPtr requestHeader = serviceTransactionSPtr->requestHeader(); ResponseHeader::SPtr responseHeader = serviceTransactionSPtr->responseHeader(); responseHeader->requestHandle(requestHeader->requestHandle()); responseHeader->serviceResult(serviceTransactionSPtr->statusCode()); SecureChannelTransaction::SPtr secureChannelTransaction; secureChannelTransaction = boost::static_pointer_cast<SecureChannelTransaction>(serviceTransactionSPtr->handle()); std::iostream iosres(&secureChannelTransaction->os_); responseHeader->opcUaBinaryEncode(iosres); serviceTransactionSPtr->opcUaBinaryEncodeResponse(iosres); if (sessionIf_ != nullptr) { sessionIf_->responseMessage(responseHeader, secureChannelTransaction); } } }
33.064777
138
0.725603
gianricardo
62722e0dddb08bce413b9f51e4a7dd33defb236c
2,086
hh
C++
combine-msa-vcf/msa_combiner.hh
tsnorri/vcf2multialign
ee987f55b376a5db9c260e6a38201a09d940fd7e
[ "MIT" ]
2
2019-06-13T16:16:16.000Z
2020-10-17T00:40:58.000Z
combine-msa-vcf/msa_combiner.hh
tsnorri/vcf2multialign
ee987f55b376a5db9c260e6a38201a09d940fd7e
[ "MIT" ]
1
2020-01-05T10:48:08.000Z
2020-01-05T13:19:28.000Z
combine-msa-vcf/msa_combiner.hh
tsnorri/vcf2multialign
ee987f55b376a5db9c260e6a38201a09d940fd7e
[ "MIT" ]
1
2018-05-18T08:46:52.000Z
2018-05-18T08:46:52.000Z
/* * Copyright (c) 2019–2020 Tuukka Norri * This code is licensed under MIT license (see LICENSE for details). */ #ifndef VCF2MULTIALIGN_COMBINE_MSA_MSA_COMBINER_HH #define VCF2MULTIALIGN_COMBINE_MSA_MSA_COMBINER_HH #include <array> #include <vcf2multialign/types.hh> #include <vector> #include "mnv_combiner.hh" #include "msa_data_source.hh" #include "overlap_counter.hh" #include "variant_filter.hh" #include "variant_writer.hh" #include "vcf_record_generator.hh" #include "types.hh" namespace vcf2multialign { class msa_combiner : public segmentation_handler { friend msa_data_source; protected: msa_data_source m_data_source; // Output handling variant_writer m_variant_writer; mnv_combiner m_mnv_combiner; variant_filter m_variant_filter; std::uint16_t m_ploidy{1}; public: msa_combiner() = default; msa_combiner(std::string output_chr_id, std::uint16_t const ploidy, std::ostream &os, bool const logs_status): m_data_source(ploidy, logs_status), m_variant_writer(os, std::move(output_chr_id)), m_mnv_combiner(m_variant_writer, ploidy), m_variant_filter(m_mnv_combiner), m_ploidy(ploidy) { } // Entry point. void process_msa(vector_type const &ref, vector_type const &alt, vcf_record_generator &var_rec_gen); protected: void process_one_segment_msa( aligned_segment const &seg, std::int32_t overlap_count, overlap_counter::const_iterator overlap_it, overlap_counter::const_iterator const overlap_end ); std::size_t process_variants_msa( std::size_t const max_alt_pos, aligned_segment_vector::const_iterator seg_it, aligned_segment_vector::const_iterator const seg_end, class overlap_counter const &overlap_counter ); void process_variant_in_range( variant_record const &var, aligned_segment_vector::const_iterator aligned_segment_begin, aligned_segment_vector::const_iterator const aligned_segment_end, std::int32_t const max_overlaps ); virtual void process_variants(msa_segmentation &segmentation) override; }; } #endif
26.405063
112
0.767018
tsnorri
627a9f9b7a3e6d26795666bd022e97da4938b46b
4,295
cpp
C++
bside-code/bside_tokenizer.cpp
mgolden/basic_stamp_linux64
eb547eae358c5fab220d159cb932b5a34beb3711
[ "Linux-OpenIB" ]
4
2018-06-03T23:12:54.000Z
2022-03-27T23:20:19.000Z
bside-code/bside_tokenizer.cpp
mgolden/basic_stamp_linux64
eb547eae358c5fab220d159cb932b5a34beb3711
[ "Linux-OpenIB" ]
null
null
null
bside-code/bside_tokenizer.cpp
mgolden/basic_stamp_linux64
eb547eae358c5fab220d159cb932b5a34beb3711
[ "Linux-OpenIB" ]
2
2016-02-01T17:56:49.000Z
2016-07-14T09:39:57.000Z
/* bside_tokenize.cpp This interfaces with Parallax, Inc.'s PBASIC Tokenizer Shared Library for the Linux operating system. It reads a PBASIC source file and writes the tokenized results to a file which can then be sent to the BASIC Stamp microcontroller using the "bstamp_run" program. Based on "stampapp.cpp" example from the "PBASIC_Tokenizer.tar.gz" archive, (c) 2002 Parallax, Inc. All rights reserved. http://www.parallax.com/ PBASIC is a trademark and BASIC Stamp is a registered trademark of Parallax, Inc. */ extern "C" { #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <dlfcn.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> } #include "tokenizer.h" #include "open_tokenizer_so.h" /* Globals: */ TModuleRec *ModuleRec; char Source[MaxSourceSize]; int fd; float bside_tokenizer_ver = 0.02; float PBasic_tokenizer_ver; /* Prototypes */ int write_file(char *filename); void handle_args(int argsc, char *arr[]); void print_usage(char *args[]); int main(int argc, char *args[]) { int i; void *hso; char *error; /* Check for proper arguments: */ handle_args(argc, args); /* (Function prototypes): */ STDAPI (*GetVersion)(void); STDAPI (*CompileIt)(TModuleRec *, char *Src, bool DirectivesOnly, bool ParseStampDirectives, TSrcTokReference *Ref); STDAPI (*doTestRecAlignment)(TModuleRec *); /* Open the .so */ hso = open_tokenizer_so(TOKENIZER_SO); /* (Map functions in tokenizer.so) */ GetVersion= (STDAPI(*)(void))dlsym(hso,"Version"); CompileIt= (STDAPI(*)(TModuleRec *, char *Src, bool DirectivesOnly,bool ParseStampDirectives, TSrcTokReference *Ref))dlsym(hso,"Compile"); doTestRecAlignment= (STDAPI(*)(TModuleRec *))dlsym(hso,"TestRecAlignment"); /* (Test for any errors) */ error = dlerror(); if (error != NULL) { perror(error); dlclose(hso); exit(EXIT_FAILURE); } /* Allocate TModuleRec */ ModuleRec = (TModuleRec *)malloc(sizeof(TModuleRec)); /* Display version of tokenizer */ PBasic_tokenizer_ver = (((float)GetVersion())/100.0); printf("PBASIC Tokenizer Library version %1.2f\n\n", PBasic_tokenizer_ver); /* Call TestRecAlignment and display the results of the TModuleRec fields. */ doTestRecAlignment(ModuleRec); /* Load source code from file: */ fd = open(args[1], O_RDONLY); if (fd == -1) { printf("Can't open %s\n", args[1]); exit(EXIT_FAILURE); } ModuleRec->SourceSize = read(fd, Source, sizeof(Source)); Source[ModuleRec->SourceSize] = '\0'; close(fd); /* Tokenize the code: */ CompileIt(ModuleRec, Source, false, true,NULL); /* Close shared library: */ dlclose(hso); /* Did it succeed? */ if (!ModuleRec->Succeeded) { printf("Error: Tokenization of %s failed.\n", args[1]); printf("Failed compile: %s\n", ModuleRec->Error); printf("Error in :\n\t "); for (i=0; i < ModuleRec->ErrorLength; i++) { putchar( (int) *(Source + ModuleRec->ErrorStart + i) ); } putchar((int) '\n'); exit(EXIT_FAILURE); } printf("Tokenized Succesfully!\n"); if(write_file(args[2])) { printf("Error: Can't create %s\n", args[2]); exit(EXIT_FAILURE); } printf("%s created succesfully!\n", args[2]); /* All Done */ return 0; } /* Save the tokenized results to a file: */ int write_file(char *filename) { fd = open(filename, O_CREAT | O_TRUNC | O_WRONLY, 0644); if (fd == -1) { return 1; } write(fd, ModuleRec->PacketBuffer, ModuleRec->PacketCount * 18); close(fd); return 0; } /* Processes all the command line arguments */ void handle_args(int argsc, char *args[]) { int c; if(argsc > 2) { while ( (c = getopt(argsc, args, "hv")) != -1) { switch(c) { case 'h': case '?': print_usage(args); exit(EXIT_SUCCESS); break; case 'v': printf("Bside-tokenizer Version: %.2f\n", bside_tokenizer_ver); exit(EXIT_SUCCESS); break; default: print_usage(args); exit(EXIT_FAILURE); break; } } } else { print_usage(args); exit(EXIT_SUCCESS); } } void print_usage (char *args[]) { printf("Usage: %s {[OPTION] | infile.txt outfile.tok}\n\n", args[0]); printf("Options\n"); printf("\t-h\t this screen\n"); printf("\t-v\t print version information\n"); return; }
21.582915
139
0.65518
mgolden
627c3def3d92f3aae785a307ead6cb3985524231
85
cpp
C++
src/Global_renderer.cpp
romz-pl/pong-game
2deadc419fb9340b333aa6b94bb7f861b93ffe6d
[ "MIT" ]
null
null
null
src/Global_renderer.cpp
romz-pl/pong-game
2deadc419fb9340b333aa6b94bb7f861b93ffe6d
[ "MIT" ]
null
null
null
src/Global_renderer.cpp
romz-pl/pong-game
2deadc419fb9340b333aa6b94bb7f861b93ffe6d
[ "MIT" ]
null
null
null
#include "Global_renderer.h" namespace Global { unique< SDL_Renderer* > renderer; }
12.142857
33
0.752941
romz-pl
627d27713021070890784a463c60934f94e9136d
708
cpp
C++
src/eventBus.cpp
HenadziMatuts/snake1
c5ecb731c25222b7b8e46803f9f26277ad48bc52
[ "MIT" ]
8
2017-08-31T16:43:10.000Z
2021-11-14T17:44:05.000Z
src/eventBus.cpp
HenadziMatuts/snake1
c5ecb731c25222b7b8e46803f9f26277ad48bc52
[ "MIT" ]
null
null
null
src/eventBus.cpp
HenadziMatuts/snake1
c5ecb731c25222b7b8e46803f9f26277ad48bc52
[ "MIT" ]
1
2020-03-19T19:46:56.000Z
2020-03-19T19:46:56.000Z
#include "eventBus.h" void EventBus::PostGameEvent(GameEvent gameEvent) { m_GameEvents.push_back(gameEvent); }; void EventBus::PostInGameEvent(InGameEvent inGameEvent, InGameEventSource source) { m_InGameEventsNext[source].push_back(inGameEvent); } std::vector<GameEvent>* EventBus::GameEvents() { return &m_GameEvents; } std::vector<InGameEvent>* EventBus::InGameEvents(InGameEventSource source) { return &m_InGameEventsCurrent[source]; } void EventBus::Proceed() { m_GameEvents.clear(); for (int i = 0; i < IN_GAME_EVENT_SOURCE_TOTAL; i++) { m_InGameEventsCurrent[i].clear(); } auto *swap = m_InGameEventsCurrent; m_InGameEventsCurrent = m_InGameEventsNext; m_InGameEventsNext = swap; }
20.228571
81
0.768362
HenadziMatuts
627da4a2450cb31b32ef7e22c79914633a747b78
2,134
cpp
C++
src/ctl/ctlListView.cpp
dpage/pgadmin3
6784e6281831a083fe5a0bbd49eac90e1a6ac547
[ "Artistic-1.0" ]
2
2021-07-16T21:45:41.000Z
2021-08-14T15:54:17.000Z
src/ctl/ctlListView.cpp
dpage/pgadmin3
6784e6281831a083fe5a0bbd49eac90e1a6ac547
[ "Artistic-1.0" ]
null
null
null
src/ctl/ctlListView.cpp
dpage/pgadmin3
6784e6281831a083fe5a0bbd49eac90e1a6ac547
[ "Artistic-1.0" ]
2
2017-11-18T15:00:24.000Z
2021-08-14T15:54:30.000Z
////////////////////////////////////////////////////////////////////////// // // pgAdmin III - PostgreSQL Tools // RCS-ID: $Id$ // Copyright (C) 2002 - 2010, The pgAdmin Development Team // This software is released under the Artistic Licence // // ctlListView.cpp - enhanced listview control // ////////////////////////////////////////////////////////////////////////// // wxWindows headers #include <wx/wx.h> #include <wx/imaglist.h> // App headers #include "ctl/ctlListView.h" #include "base/base.h" ctlListView::ctlListView(wxWindow *p, int id, wxPoint pos, wxSize siz, long attr) : wxListView(p, id, pos, siz, attr | wxLC_REPORT) { } long ctlListView::GetSelection() { return GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED); } wxString ctlListView::GetText(long row, long col) { wxListItem item; item.SetId(row); item.SetColumn(col); item.SetMask(wxLIST_MASK_TEXT); GetItem(item); return item.GetText(); }; void ctlListView::AddColumn(const wxChar *text, int size, int format) { InsertColumn(GetColumnCount(), text, format, ConvertDialogToPixels(wxPoint(size,0)).x); } long ctlListView::AppendItem(int icon, const wxChar *val, const wxChar *val2, const wxChar *val3) { long pos=InsertItem(GetItemCount(), val, icon); if (val2 && *val2) SetItem(pos, 1, val2); if (val3 && *val3) SetItem(pos, 2, val3); return pos; } void ctlListView::CreateColumns(wxImageList *images, const wxString &left, const wxString &right, int leftSize) { int rightSize; if (leftSize < 0) { leftSize = rightSize = GetClientSize().GetWidth()/2; } else { if (leftSize) leftSize = ConvertDialogToPixels(wxPoint(leftSize, 0)).x; rightSize = GetClientSize().GetWidth()-leftSize; } if (!leftSize) { InsertColumn(0, left, wxLIST_FORMAT_LEFT, GetClientSize().GetWidth()); } else { InsertColumn(0, left, wxLIST_FORMAT_LEFT, leftSize); InsertColumn(1, right, wxLIST_FORMAT_LEFT, rightSize); } if (images) SetImageList(images, wxIMAGE_LIST_SMALL); }
24.25
111
0.616214
dpage
627e6909b603c6070809b58c3095874103df3fd7
3,117
hpp
C++
src/xpcc/processing/resumable.hpp
roboterclubaachen/xpcc
010924901947381d20e83b838502880eb2ffea72
[ "BSD-3-Clause" ]
161
2015-01-13T15:52:06.000Z
2020-02-13T01:26:04.000Z
src/xpcc/processing/resumable.hpp
salkinium/xpcc
010924901947381d20e83b838502880eb2ffea72
[ "BSD-3-Clause" ]
281
2015-01-06T12:46:40.000Z
2019-01-06T13:06:57.000Z
src/xpcc/processing/resumable.hpp
salkinium/xpcc
010924901947381d20e83b838502880eb2ffea72
[ "BSD-3-Clause" ]
51
2015-03-03T19:56:12.000Z
2020-03-22T02:13:36.000Z
// coding: utf-8 /* Copyright (c) 2014, Roboterclub Aachen e.V. * All Rights Reserved. * * The file is part of the xpcc library and is released under the 3-clause BSD * license. See the file `LICENSE` for the full license governing this code. */ // ---------------------------------------------------------------------------- /** * @ingroup processing * @defgroup resumable Resumables * * An implementation of lightweight resumable functions which allow for nested calling. * * This base class and its macros allows you to implement and use several * resumable functions in one class. * This allows you to modularize your code by placing it into its own resumable functions * instead of the placing everything into one big method. * It also allows you to call and run resumable functions within your resumables, * so you can reuse their functionality. * * Note that you should call resumable functions within a protothreads. * It is sufficient to use the `this` pointer of the class as context * when calling the resumables. * So calling a resumable function is done using `PT_CALL(resumable(this))` * which will return the result of the resumable function. * * You may use the `RF_CALL_BLOCKING(resumable(ctx))` macro to execute * a resumable function outside of a protothread, however, this which will * force the CPU to busy-wait until the resumable function ended. * * Here is a (slightly over-engineered) example: * * @code * #include <xpcc/architecture.hpp> * #include <xpcc/processing.hpp> * * typedef GpioOutputB0 Led; * * class BlinkingLight : public xpcc::pt::Protothread, private xpcc::NestedResumable<2> * { * public: * bool * run() * { * PT_BEGIN(); * * // set everything up * Led::setOutput(); * Led::set(); * * while (true) * { * Led::set(); * PT_CALL(waitForTimer()); * * Led::reset(); * PT_CALL(setTimer(200)); * * PT_WAIT_UNTIL(timeout.isExpired()); * } * * PT_END(); * } * * xpcc::ResumableResult<bool> * waitForTimer() * { * RF_BEGIN(); * * // nested calling is allowed * if (RF_CALL(setTimer(100))) * { * RF_WAIT_UNTIL(timeout.isExpired()); * RF_RETURN(true); * } * * RF_END_RETURN(false); * } * * xpcc::ResumableResult<bool> * setTimer(uint16_t new_timeout) * { * RF_BEGIN(); * * timeout.restart(new_timeout); * * if(timeout.isArmed()) { * RF_RETURN(true); * } * * // clean up code goes here * * RF_END_RETURN(false); * } * * private: * xpcc::ShortTimeout timeout; * }; * * * ... * BlinkingLight light; * * while (...) { * light.run(); * } * @endcode * * For other examples take a look in the `examples` folder in the XPCC * root folder. The given example is in `examples/generic/resumable`. */ #include "resumable/resumable.hpp" #include "resumable/nested_resumable.hpp"
26.87069
89
0.595444
roboterclubaachen
627f3bac77ef5ca45503753e8a5623643f23d25f
977
cpp
C++
Lesson4/inheritance.cpp
hari-learningspace/CPP_Learning
f32a250e284e9b9d876c4ef20bbb28e5c81cea27
[ "MIT" ]
null
null
null
Lesson4/inheritance.cpp
hari-learningspace/CPP_Learning
f32a250e284e9b9d876c4ef20bbb28e5c81cea27
[ "MIT" ]
null
null
null
Lesson4/inheritance.cpp
hari-learningspace/CPP_Learning
f32a250e284e9b9d876c4ef20bbb28e5c81cea27
[ "MIT" ]
null
null
null
/* Instructions Add a new member variable to class Vehicle. Output that new member in main(). Derive a new class from Vehicle, alongside Car and Bicycle. Instantiate an object of that new class. Print the object. */ #include <iostream> #include <string> using std::string; class Vehicle { public: int wheels = 0; string color = "blue"; int weight = 0; void Print() const { std::cout << "This " << color << " vehicle has " << wheels << " wheels!\n"; } }; class Car : public Vehicle { public: bool sunroof = false; }; class Bicycle : public Vehicle { public: bool kickstand = true; }; class Truck : public Vehicle { public: std::string OEM; }; int main() { Car car; car.wheels = 4; car.sunroof = true; car.Print(); if (car.sunroof) std::cout << "And a sunroof!\n"; Truck truck; truck.color = "red"; truck.OEM = "Diamler"; truck.weight = 100; truck.wheels = 4; if (truck.OEM == "Diamler") std::cout << "Diamler Truck\n"; }
17.763636
79
0.63869
hari-learningspace