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
float64
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
float64
1
77k
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
float64
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
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
8f9885bbeab0b33acc49b50e04af084143c267e1
5,572
cxx
C++
painty/renderer/src/TextureBrushDictionary.cxx
lindemeier/painty
792cac6655b3707805ffc68d902f0e675a7770b8
[ "MIT" ]
15
2020-04-22T15:18:28.000Z
2022-03-24T07:48:28.000Z
painty/renderer/src/TextureBrushDictionary.cxx
lindemeier/painty
792cac6655b3707805ffc68d902f0e675a7770b8
[ "MIT" ]
25
2020-04-18T18:55:50.000Z
2021-05-30T21:26:39.000Z
painty/renderer/src/TextureBrushDictionary.cxx
lindemeier/painty
792cac6655b3707805ffc68d902f0e675a7770b8
[ "MIT" ]
2
2020-09-16T05:55:54.000Z
2021-01-09T12:09:43.000Z
/** * @file TextureBrushDictionary.cxx * @author Thomas Lindemeier * @brief * @date 2020-09-29 * */ #include "painty/renderer/TextureBrushDictionary.hxx" #include <filesystem> #include <fstream> #include <iostream> #include <map> #include <random> // #include "opencv2/highgui/highgui.hpp" #include "painty/io/ImageIO.hxx" namespace painty { TextureBrushDictionary::TextureBrushDictionary() { createBrushTexturesFromFolder("data/textures"); } auto TextureBrushDictionary::lookup(const std::vector<vec2>& path, const double brushSize) const -> Entry { auto length = 0.0; for (auto i = 0U; i < (path.size() - 1U); i++) { length += (path[i] - path[i + 1U]).norm(); } uint32_t i0 = 0; uint32_t i1 = 1; // find best fitting size double mr = _avgSizes[0U]; for (uint32_t i = 0U; i < _avgSizes.size(); i++) { double d = std::abs(_avgSizes[i] - brushSize); if (d < mr) { mr = d; i0 = i; } } // find best fitting length double ml = _avgTexLength[i0][0]; for (uint32_t i = 0U; i < _avgSizes.size(); i++) { double d = abs(_avgTexLength[i0][i] - length); if (d < ml) { ml = d; i1 = i; } } const auto& candidates = _brushTexturesBySizeByLength[i0][i1]; if (candidates.empty()) { throw std::runtime_error("no candidate found"); } static std::random_device rd; static std::mt19937 gen(rd()); std::uniform_int_distribution<std::size_t> dis( static_cast<std::size_t>(0UL), candidates.size() - static_cast<std::size_t>(1UL)); const auto index = dis(gen); return candidates[index]; } auto TextureBrushDictionary::loadHeightMap(const std::string& file) const -> Mat1d { Mat1d gray; io::imRead(file, gray, false); cv::normalize(gray, gray, 0.0, 1.0, cv::NORM_MINMAX); return gray; } void TextureBrushDictionary::createBrushTexturesFromFolder( const std::string& folder) { auto split = [](const std::string& input, const char delim) { std::vector<std::string> elems; std::stringstream ss(input); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; }; std::map<uint32_t, std::map<uint32_t, std::vector<Entry>>> textureMap; for (const auto& p : std::filesystem::directory_iterator(folder)) { const auto filepath = p.path(); // std::cout << filepath << std::endl; const std::string filename = split(split(filepath, '.').front(), '/').back(); std::vector<std::string> tokens = split(filename, '_'); const auto radius = static_cast<uint32_t>(std::stoi(tokens[0])); const auto length = static_cast<uint32_t>(std::stoi(tokens[1])); Entry entry; entry.texHost = loadHeightMap(filepath); Mat1f fImage = {}; { Mat1f copy = {}; cv::normalize(entry.texHost, copy, 0.0, 1.0, cv::NORM_MINMAX); cv::flip(copy, copy, 0); copy.convertTo(fImage, CV_32FC1, 1.0); } // cv::imshow("brush_tex", byteImage); // cv::waitKey(100); entry.texGpu = prgl::Texture2d::Create( fImage.cols, fImage.rows, prgl::TextureFormatInternal::R32F, prgl::TextureFormat::Red, prgl::DataType::Float); entry.texGpu->upload(fImage.data); textureMap[radius][length].push_back(entry); } _brushTexturesBySizeByLength.clear(); for (const auto& e : textureMap) { _brushTexturesBySizeByLength.push_back(std::vector<std::vector<Entry>>()); for (const auto& a : e.second) { _brushTexturesBySizeByLength.back().push_back(std::vector<Entry>()); for (const auto& tex : a.second) { _brushTexturesBySizeByLength.back().back().push_back(tex); } } } _avgSizes.resize(_brushTexturesBySizeByLength.size()); for (auto& e : _avgSizes) { e = 0.0; } std::vector<uint32_t> brushSizesCounters(_brushTexturesBySizeByLength.size(), 0U); for (auto i = 0U; i < _brushTexturesBySizeByLength.size(); i++) { for (auto j = 0U; j < _brushTexturesBySizeByLength[i].size(); j++) { for (const auto& texture : _brushTexturesBySizeByLength[i][j]) { _avgSizes[i] += static_cast<double>(texture.texHost.rows); brushSizesCounters[i]++; } } } for (auto i = 0U; i < _avgSizes.size(); i++) { _avgSizes[i] *= (1.0 / static_cast<double>(brushSizesCounters[i])); } _avgTexLength.resize(_brushTexturesBySizeByLength.size()); std::vector<std::vector<uint32_t>> brushLengthCounters( _brushTexturesBySizeByLength.size()); for (auto i = 0U; i < _brushTexturesBySizeByLength.size(); i++) { _avgTexLength[i] = std::vector<double>(_brushTexturesBySizeByLength[i].size(), 0.0); brushLengthCounters[i] = std::vector<uint32_t>(_brushTexturesBySizeByLength[i].size(), 0U); } for (auto i = 0U; i < _brushTexturesBySizeByLength.size(); i++) { for (auto j = 0U; j < _brushTexturesBySizeByLength[i].size(); j++) { for (const auto& texture : _brushTexturesBySizeByLength[i][j]) { _avgTexLength[i][j] += static_cast<double>(texture.texHost.cols); brushLengthCounters[i][j]++; } } } for (auto i = 0U; i < _avgTexLength.size(); i++) { for (auto j = 0U; j < _avgTexLength[i].size(); j++) { _avgTexLength[i][j] *= (1.0 / static_cast<double>(brushLengthCounters[i][j])); } } } } // namespace painty
30.448087
80
0.611271
8f9c2b9a39f8f684797d7cfbfa8c3831a742d24d
3,477
cpp
C++
Source/ComponentProgressBar.cpp
Project-3-UPC-DDV-BCN/Project3
3fb345ce49485ccbc7d03fb320623df6114b210c
[ "MIT" ]
10
2018-01-16T16:18:42.000Z
2019-02-19T19:51:45.000Z
Source/ComponentProgressBar.cpp
Project-3-UPC-DDV-BCN/Project3
3fb345ce49485ccbc7d03fb320623df6114b210c
[ "MIT" ]
136
2018-05-10T08:47:58.000Z
2018-06-15T09:38:10.000Z
Source/ComponentProgressBar.cpp
Project-3-UPC-DDV-BCN/Project3
3fb345ce49485ccbc7d03fb320623df6114b210c
[ "MIT" ]
1
2018-06-04T17:18:40.000Z
2018-06-04T17:18:40.000Z
#include "ComponentProgressBar.h" #include "GameObject.h" #include "ComponentCanvas.h" #include "ComponentRectTransform.h" #include "Texture.h" #include "Application.h" #include "ModuleResources.h" ComponentProgressBar::ComponentProgressBar(GameObject * attached_gameobject) { SetActive(true); SetName("ProgressBar"); SetType(ComponentType::CompProgressBar); SetGameObject(attached_gameobject); c_rect_trans = GetRectTrans(); c_rect_trans->SetSize(float2(100, 30)); progress_percentage = 50.0f; base_colour = float4(1.0f, 1.0f, 1.0f, 1.0f); progress_colour = float4(0.5f, 0.5f, 0.5f, 1.0f); } ComponentProgressBar::~ComponentProgressBar() { } bool ComponentProgressBar::Update() { BROFILER_CATEGORY("Component - ProgressBar - Update", Profiler::Color::Beige); bool ret = true; ComponentCanvas* canvas = GetCanvas(); if (canvas != nullptr) { CanvasDrawElement base(canvas, this); base.SetTransform(c_rect_trans->GetMatrix()); base.SetOrtoTransform(c_rect_trans->GetOrtoMatrix()); base.SetSize(c_rect_trans->GetScaledSize()); base.SetColour(base_colour); canvas->AddDrawElement(base); CanvasDrawElement progres(canvas, this); float2 pos = float2::zero; pos.x = -(c_rect_trans->GetScaledSize().x / 2); pos.x += (GetProgesSize() / 2); progres.SetTransform(c_rect_trans->GetMatrix()); progres.SetOrtoTransform(c_rect_trans->GetOrtoMatrix()); progres.SetPosition(pos); progres.SetSize(float2(GetProgesSize(), c_rect_trans->GetScaledSize().y)); progres.SetColour(progress_colour); if(progress_percentage != 0.0f) canvas->AddDrawElement(progres); } return ret; } void ComponentProgressBar::SetBaseColour(const float4 & colour) { base_colour = colour; } float4 ComponentProgressBar::GetBaseColour() const { return base_colour; } void ComponentProgressBar::SetProgressColour(const float4 & colour) { progress_colour = colour; } float4 ComponentProgressBar::GetProgressColour() const { return progress_colour; } void ComponentProgressBar::SetProgressPercentage(float progres) { progress_percentage = progres; if (progress_percentage < 0) progress_percentage = 0.0f; if (progress_percentage > 100) progress_percentage = 100.0f; } float ComponentProgressBar::GetProgressPercentage() const { return progress_percentage; } void ComponentProgressBar::Save(Data & data) const { data.AddInt("Type", GetType()); data.AddBool("Active", IsActive()); data.AddUInt("UUID", GetUID()); data.AddFloat("progress_percentage", progress_percentage); data.AddVector4("base_colour", base_colour); data.AddVector4("progress_colour", progress_colour); } void ComponentProgressBar::Load(Data & data) { SetActive(data.GetBool("Active")); SetUID(data.GetUInt("UUID")); SetProgressPercentage(data.GetFloat("progress_percentage")); SetBaseColour(data.GetVector4("base_colour")); SetProgressColour(data.GetVector4("progress_colour")); } ComponentCanvas * ComponentProgressBar::GetCanvas() { ComponentCanvas* ret = nullptr; bool go_is_canvas; ret = GetRectTrans()->GetCanvas(go_is_canvas); return ret; } ComponentRectTransform * ComponentProgressBar::GetRectTrans() { ComponentRectTransform* ret = nullptr; ret = (ComponentRectTransform*)GetGameObject()->GetComponent(Component::CompRectTransform); return ret; } float ComponentProgressBar::GetProgesSize() { float ret = 0.0f; float2 scaled_size = c_rect_trans->GetScaledSize(); ret = (scaled_size.x / 100) * progress_percentage; return ret; }
22.875
92
0.757262
8f9d7d06b8752e0af1ccf1127dcdcc3e33712842
10,043
cc
C++
streetlearn/engine/pano_projection.cc
turningpoint1988/streetlearn
dd348cb811064582a77abe855b9ac15799e4a1ef
[ "Apache-2.0" ]
256
2019-01-09T18:00:45.000Z
2022-03-29T12:56:46.000Z
streetlearn/engine/pano_projection.cc
windstrip/DeepMind-StreetLearn
35ffa07e053278b4dd88a2a9da9c72f23d1fff58
[ "Apache-2.0" ]
11
2019-02-05T20:12:18.000Z
2021-05-24T11:20:13.000Z
streetlearn/engine/pano_projection.cc
windstrip/DeepMind-StreetLearn
35ffa07e053278b4dd88a2a9da9c72f23d1fff58
[ "Apache-2.0" ]
60
2019-01-09T18:13:14.000Z
2022-02-24T07:39:47.000Z
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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 "streetlearn/engine/pano_projection.h" #include <cmath> #include <cstdint> #include <cstring> #include <iostream> #include <vector> #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "absl/memory/memory.h" #include "streetlearn/engine/math_util.h" namespace { // Radius used in calculations of the X, Y, Z point cloud. static constexpr double PANO_RADIUS = 120.0; } // namespace namespace streetlearn { namespace { // Conversion from Image to OpenCV Mat. void ImageToOpenCV(const Image3_b& input, cv::Mat* output) { const int width = input.width(); const int height = input.height(); output->create(height, width, CV_8UC3); const auto image_data = input.data(); std::copy(image_data.begin(), image_data.end(), output->data); } } // namespace struct PanoProjection::Impl { Impl(double fov_deg, int proj_width, int proj_height) : fov_deg_(0), proj_width_(0), proj_height_(0) { // Update the projection size and pre-compute the centered XYZ point cloud. UpdateProjectionSize(fov_deg, proj_width, proj_height); } void Project(const cv::Mat& input, double yaw_deg, double pitch_deg, cv::Mat* output); // Prepares the centered XYZ point cloud for a specified field of view and // projection image width and height. cv::Mat PrepareXYZPointCloud(); // Rotates a centered XYZ point cloud to given yaw and pitch angles. cv::Mat RotateXYZPointCloud(double yaw_deg, double pitch_deg); // Projects an XYZ point cloud to latitude and longitude maps, given panorama // image and projected image widths and heights. void ProjectXYZPointCloud(const cv::Mat& xyz, int pano_width, int pano_height, cv::Mat* map_lon, cv::Mat* map_lat); // Decodes the image. void Decode(int image_width, int image_height, int image_depth, int compressed_size, const char* compressed_image, std::vector<uint8_t>* output); // Updates the projected image size and field of view, and if there are // changes then recomputes the centered XYZ point cloud. void UpdateProjectionSize(double fov_deg, int proj_width, int proj_height); // Degrees of horizontal field of view. double fov_deg_; // Projected image size. int proj_width_; int proj_height_; // Point cloud of projected image coordinates, with zero yaw and pitch. cv::Mat xyz_centered_; }; cv::Mat PanoProjection::Impl::PrepareXYZPointCloud() { // Vertical and horizontal fields of view. double fov_width_deg = fov_deg_; double fov_height_deg = fov_deg_ * proj_height_ / proj_width_; // Scale of the Y and Z grid. double half_fov_width_rad = math::DegreesToRadians(fov_width_deg / 2.0); double half_afov_width_rad = math::DegreesToRadians((180.0 - fov_width_deg) / 2.0); double half_fov_height_rad = math::DegreesToRadians(fov_height_deg / 2.0); double half_afov_height_rad = math::DegreesToRadians((180.0 - fov_height_deg) / 2.0); double ratio_width = std::sin(half_fov_width_rad) / std::sin(half_afov_width_rad); double scale_width = 2.0 * PANO_RADIUS * ratio_width / (proj_width_ - 1); double ratio_height = std::sin(half_fov_height_rad) / std::sin(half_afov_height_rad); double scale_height = 2.0 * PANO_RADIUS * ratio_height / (proj_height_ - 1); // Image centres for the projection. double c_x = (proj_width_ - 1.0) / 2.0; double c_y = (proj_height_ - 1.0) / 2.0; // Create the 3D point cloud for X, Y, Z coordinates of the image projected // on a sphere. cv::Mat xyz_centered; xyz_centered.create(3, proj_height_ * proj_width_, CV_32FC1); for (int i = 0, k = 0; i < proj_height_; i++) { for (int j = 0; j < proj_width_; j++, k++) { double x_ij = PANO_RADIUS; double y_ij = (j - c_x) * scale_width; double z_ij = -(i - c_y) * scale_height; double d_ij = std::sqrt(x_ij * x_ij + y_ij * y_ij + z_ij * z_ij); double coeff = PANO_RADIUS / d_ij; xyz_centered.at<float>(0, k) = coeff * x_ij; xyz_centered.at<float>(1, k) = coeff * y_ij; xyz_centered.at<float>(2, k) = coeff * z_ij; } } return xyz_centered; } cv::Mat PanoProjection::Impl::RotateXYZPointCloud(double yaw_deg, double pitch_deg) { // Rotation matrix for yaw. float z_axis_data[3] = {0.0, 0.0, 1.0}; cv::Mat z_axis(3, 1, CV_32FC1, z_axis_data); cv::Mat z_rotation_vec = z_axis * math::DegreesToRadians(yaw_deg); cv::Mat z_rotation_mat(3, 3, CV_32FC1); cv::Rodrigues(z_rotation_vec, z_rotation_mat); // Rotation matrix for pitch. float y_axis_data[3] = {0.0, 1.0, 0.0}; cv::Mat y_axis(3, 1, CV_32FC1, y_axis_data); cv::Mat y_rotation_vec = z_rotation_mat * y_axis * math::DegreesToRadians(-pitch_deg); cv::Mat y_rotation_mat(3, 3, CV_32FC1); cv::Rodrigues(y_rotation_vec, y_rotation_mat); // Apply yaw and pitch rotation to the point cloud. cv::Mat xyz_rotated = y_rotation_mat * (z_rotation_mat * xyz_centered_); return xyz_rotated; } void PanoProjection::Impl::ProjectXYZPointCloud(const cv::Mat& xyz, int pano_width, int pano_height, cv::Mat* map_lon, cv::Mat* map_lat) { // Image centres for the panorama. double pano_c_x = (pano_width - 1.0) / 2.0; double pano_c_y = (pano_height - 1.0) / 2.0; map_lat->create(proj_height_, proj_width_, CV_32FC1); map_lon->create(proj_height_, proj_width_, CV_32FC1); for (int i = 0, k = 0; i < proj_height_; i++) { for (int j = 0; j < proj_width_; j++, k++) { // Project the Z coordinate into latitude. double z_ij = xyz.at<float>(2, k); double sin_lat_ij = z_ij / PANO_RADIUS; double lat_ij = std::asin(sin_lat_ij); map_lat->at<float>(i, j) = -lat_ij / CV_PI * 2.0 * pano_c_y + pano_c_y; // Project the X and Y coordinates into longitude. double x_ij = xyz.at<float>(0, k); double y_ij = xyz.at<float>(1, k); double tan_theta_ij = y_ij / x_ij; double theta_ij = std::atan(tan_theta_ij); double lon_ij; if (x_ij > 0) { lon_ij = theta_ij; } else { if (y_ij > 0) { lon_ij = theta_ij + CV_PI; } else { lon_ij = theta_ij - CV_PI; } } map_lon->at<float>(i, j) = lon_ij / CV_PI * pano_c_x + pano_c_x; } } } void PanoProjection::Impl::UpdateProjectionSize(double fov_deg, int proj_width, int proj_height) { // Update only if there is a change. if ((proj_width_ != proj_width) || (proj_height_ != proj_height) || (fov_deg != fov_deg_)) { fov_deg_ = fov_deg; proj_width_ = proj_width; proj_height_ = proj_height; // If updated the projected image or field of view parameters, // recompute the centered XYZ point cloud. xyz_centered_ = PrepareXYZPointCloud(); } } void PanoProjection::Impl::Decode(int image_width, int image_height, int image_depth, int compressed_size, const char* compressed_image, std::vector<uint8_t>* output) { std::vector<uint8_t> input(compressed_image, compressed_image + compressed_size); cv::Mat mat = cv::imdecode(cv::Mat(input), CV_LOAD_IMAGE_ANYDEPTH); output->resize(image_width * image_height * image_depth); output->assign(mat.datastart, mat.dataend); } void PanoProjection::Impl::Project(const cv::Mat& input, double yaw_deg, double pitch_deg, cv::Mat* output) { // Assuming that the field of view has not changed, check for updates of // the projected image size, and optionally recompute the centered XYZ // point cloud. int proj_width = output->cols; int proj_height = output->rows; UpdateProjectionSize(fov_deg_, proj_width, proj_height); // Rotate the XYZ point cloud by given yaw and pitch. cv::Mat xyz = RotateXYZPointCloud(yaw_deg, pitch_deg); // Project the rotated XYZ point cloud to latitude and longitude maps. int pano_width = input.cols; int pano_height = input.rows; cv::Mat map_lon; cv::Mat map_lat; ProjectXYZPointCloud(xyz, pano_width, pano_height, &map_lon, &map_lat); // Remap from input to output given the latitude and longitude maps. cv::remap(input, *output, map_lon, map_lat, CV_INTER_CUBIC, cv::BORDER_WRAP); } PanoProjection::PanoProjection(double fov_deg, int proj_width, int proj_height) : impl_(absl::make_unique<PanoProjection::Impl>(fov_deg, proj_width, proj_height)) {} PanoProjection::~PanoProjection() {} void PanoProjection::Project(const Image3_b& input, double yaw_deg, double pitch_deg, Image3_b* output) { cv::Mat input_cv; ImageToOpenCV(input, &input_cv); cv::Mat output_cv; output_cv.create(impl_->proj_height_, impl_->proj_width_, CV_8UC3); impl_->Project(input_cv, yaw_deg, pitch_deg, &output_cv); std::memcpy(output->pixel(0, 0), output_cv.data, impl_->proj_width_ * impl_->proj_height_ * 3); } void PanoProjection::ChangeFOV(double fov_deg) { impl_->UpdateProjectionSize(fov_deg, impl_->proj_width_, impl_->proj_height_); } } // namespace streetlearn
37.898113
80
0.666534
8f9dbb4b41187c40fce56bcdbaefce1a97b42079
3,944
cpp
C++
bangtal1.cpp
jingwangjjang/Bangtal_week2
e64bd3e44cfb3d727eb5de964335d361ae25362f
[ "MIT" ]
null
null
null
bangtal1.cpp
jingwangjjang/Bangtal_week2
e64bd3e44cfb3d727eb5de964335d361ae25362f
[ "MIT" ]
null
null
null
bangtal1.cpp
jingwangjjang/Bangtal_week2
e64bd3e44cfb3d727eb5de964335d361ae25362f
[ "MIT" ]
null
null
null
#include <bangtal.h> using namespace bangtal; int main() { SoundPtr sound = Sound::create("Sound/bgm.mp3"); sound->play(); ScenePtr scene1 = Scene::create("첫번째 방", "RoomEscape/배경-1.png"); ScenePtr scene2 = Scene::create("두번째 방", "RoomEscape/배경-2.png"); auto crush = Object::create("RoomEscape/균열1.png", scene1, 800, 500); auto hammer = Object::create("RoomEscape/망치.png", scene1, 200, 100); auto seulgi = Object::create("RoomEscape/슬기.jpg", scene1, 150, 400); seulgi->setScale(0.5f); hammer->setScale(0.4f); int crush_touch = 1; bool hammer_handed = false; crush->setOnMouseCallback([&](ObjectPtr object, int x, int y, MouseAction action)->bool { if (crush_touch == 1 && hammer_handed == true) { crush->setImage("RoomEscape/균열2.png"); showMessage("콰직!"); crush_touch++; } else if (crush_touch == 2 && hammer_handed == true) { crush->setImage("RoomEscape/균열3.png"); showMessage("콰지직!"); crush_touch++; } else if (crush_touch == 3 && hammer_handed == true) { crush->setImage("RoomEscape/구멍.png"); showMessage("쿵!!!"); crush_touch++; } else if (crush_touch == 4) { scene2->enter(); } else { showMessage("망치로 부셔질 것 같은 벽이다."); } return true; }); hammer->setOnMouseCallback([&](ObjectPtr object, int x, int y, MouseAction action)->bool { hammer->pick(); hammer_handed = true; showMessage("망치를 획득했다."); return true; }); auto hole = Object::create("RoomEscape/구멍.png", scene2, 100, 300); auto drawer = Object::create("RoomEscape/서랍.png", scene2, 450, 240); auto door = Object::create("RoomEscape/문-오른쪽-닫힘.png", scene2, 910, 270); auto halfkey1 = Object::create("RoomEscape/열쇠1.png", scene2, 100, 100, false); auto halfkey2 = Object::create("RoomEscape/열쇠2.png", scene2, 1150, 200); auto plant = Object::create("RoomEscape/화분.png", scene2, 1100, 200); auto key = Object::create("RoomEscape/열쇠.png", scene2, 100, 100, false); bool key_handed = false; bool door_open = false; bool drawer_open = false; drawer->setScale(0.25f); halfkey2->setScale(0.08f); hole->setOnMouseCallback([&](ObjectPtr object, int x, int y, MouseAction action)->bool { scene1->enter(); return true; }); drawer->setOnMouseCallback([&](ObjectPtr object, int x, int y, MouseAction action)->bool { showKeypad("200210", drawer); return true; }); door->setOnMouseCallback([&](ObjectPtr object, int x, int y, MouseAction action)->bool { if (key_handed && door_open == false) { door->setImage("RoomEscape/문-오른쪽-열림.png"); door_open = true; } else if (door_open) { endGame(); } else { showMessage("문이 잠겨있다."); } return true; }); halfkey2->setOnMouseCallback([&](ObjectPtr object, int x, int y, MouseAction action)->bool { halfkey2->pick(); showMessage("열쇠조각2을 획득했다."); return true; }); drawer->setOnKeypadCallback([&](ObjectPtr object)->bool { if (drawer_open == false) { drawer->setImage("RoomEscape/열린서랍.png"); halfkey1->pick(); showMessage("열쇠조각1을 획득했다."); drawer_open = true; } return true; }); plant->setOnMouseCallback([&](ObjectPtr object, int x, int y, MouseAction action)->bool { if (action == MouseAction::MOUSE_DRAG_RIGHT) { plant->locate(scene2, 1200, 200); } return true; }); key->defineCombination(halfkey1, halfkey2); key->setOnCombineCallback([&](ObjectPtr object)->bool { key_handed = true; return true; }); startGame(scene1); return 0; }
32.065041
96
0.573529
8f9fa97caf1fc74fb3694c47316be88e0157ee4c
676
cpp
C++
learncpp.com/9.14.Q1/main.cpp
kaubu/cpp-projects
3f2b1de662c275e1aae7ccced669412b628c3bfb
[ "MIT" ]
null
null
null
learncpp.com/9.14.Q1/main.cpp
kaubu/cpp-projects
3f2b1de662c275e1aae7ccced669412b628c3bfb
[ "MIT" ]
null
null
null
learncpp.com/9.14.Q1/main.cpp
kaubu/cpp-projects
3f2b1de662c275e1aae7ccced669412b628c3bfb
[ "MIT" ]
1
2021-04-09T13:45:49.000Z
2021-04-09T13:45:49.000Z
#include <algorithm> #include <iostream> #include <string> int main() { std::cout << "How many names do you wish to enter? "; std::size_t namesAmount{}; std::cin >> namesAmount; std::string *namesArray{ new std::string[namesAmount]{} }; for (size_t i{ 0 }; i <= namesAmount; ++i) { std::cout << "Enter name #" << i + 1 << ": "; std::string name{}; std::getline(std::cin, name); namesArray[i] = name; } std::sort(std::begin(*namesArray), std::end(*namesArray)); std::cout << "Here is your sorted list:\n"; for (size_t i{ 0 }; i < namesAmount; ++i) { std::cout << "Name #" << i << ": " << namesArray[i] << '\n'; } delete[] namesArray; return 0; }
20.484848
62
0.58432
8fa2445ef2545e28995155af0ae4b2b25ed6097f
597
cc
C++
crypto/internal.cc
chronos-tachyon/mojo
8d268932dd927a24a2b5de167d63869484e1433a
[ "MIT" ]
3
2017-04-24T07:00:59.000Z
2020-04-13T04:53:06.000Z
crypto/internal.cc
chronos-tachyon/mojo
8d268932dd927a24a2b5de167d63869484e1433a
[ "MIT" ]
1
2017-01-10T04:23:55.000Z
2017-01-10T04:23:55.000Z
crypto/internal.cc
chronos-tachyon/mojo
8d268932dd927a24a2b5de167d63869484e1433a
[ "MIT" ]
1
2020-04-13T04:53:07.000Z
2020-04-13T04:53:07.000Z
// Copyright © 2017 by Donald King <chronos@chronos-tachyon.net> // Available under the MIT License. See LICENSE for details. #include "crypto/internal.h" namespace crypto { namespace internal { std::string canonical_name(base::StringPiece in) { std::string out; out.reserve(in.size()); for (char ch : in) { if (ch >= '0' && ch <= '9') { out.push_back(ch); } else if (ch >= 'a' && ch <= 'z') { out.push_back(ch); } else if (ch >= 'A' && ch <= 'Z') { out.push_back(ch + ('a' - 'A')); } } return out; } } // namespace internal } // namespace crypto
22.961538
64
0.579564
8fa4f728c6b428132adeb9e748c6380f25761b13
5,642
cpp
C++
src/org/apache/poi/ss/usermodel/DataConsolidateFunction.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/usermodel/DataConsolidateFunction.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/usermodel/DataConsolidateFunction.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/ss/usermodel/DataConsolidateFunction.java #include <org/apache/poi/ss/usermodel/DataConsolidateFunction.hpp> #include <java/io/Serializable.hpp> #include <java/lang/ArrayStoreException.hpp> #include <java/lang/Comparable.hpp> #include <java/lang/Enum.hpp> #include <java/lang/IllegalArgumentException.hpp> #include <java/lang/String.hpp> #include <SubArray.hpp> #include <ObjectArray.hpp> template<typename ComponentType, typename... Bases> struct SubArray; namespace java { namespace io { typedef ::SubArray< ::java::io::Serializable, ::java::lang::ObjectArray > SerializableArray; } // io namespace lang { typedef ::SubArray< ::java::lang::Comparable, ObjectArray > ComparableArray; typedef ::SubArray< ::java::lang::Enum, ObjectArray, ComparableArray, ::java::io::SerializableArray > EnumArray; } // lang } // java namespace poi { namespace ss { namespace usermodel { typedef ::SubArray< ::poi::ss::usermodel::DataConsolidateFunction, ::java::lang::EnumArray > DataConsolidateFunctionArray; } // usermodel } // ss } // poi poi::ss::usermodel::DataConsolidateFunction::DataConsolidateFunction(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::ss::usermodel::DataConsolidateFunction::DataConsolidateFunction(::java::lang::String* name, int ordinal, int32_t value, ::java::lang::String* name1) : DataConsolidateFunction(*static_cast< ::default_init_tag* >(0)) { ctor(name, ordinal, value,name1); } poi::ss::usermodel::DataConsolidateFunction* poi::ss::usermodel::DataConsolidateFunction::AVERAGE = new ::poi::ss::usermodel::DataConsolidateFunction(u"AVERAGE"_j, 0, int32_t(1), u"Average"_j); poi::ss::usermodel::DataConsolidateFunction* poi::ss::usermodel::DataConsolidateFunction::COUNT = new ::poi::ss::usermodel::DataConsolidateFunction(u"COUNT"_j, 1, int32_t(2), u"Count"_j); poi::ss::usermodel::DataConsolidateFunction* poi::ss::usermodel::DataConsolidateFunction::COUNT_NUMS = new ::poi::ss::usermodel::DataConsolidateFunction(u"COUNT_NUMS"_j, 2, int32_t(3), u"Count"_j); poi::ss::usermodel::DataConsolidateFunction* poi::ss::usermodel::DataConsolidateFunction::MAX = new ::poi::ss::usermodel::DataConsolidateFunction(u"MAX"_j, 3, int32_t(4), u"Max"_j); poi::ss::usermodel::DataConsolidateFunction* poi::ss::usermodel::DataConsolidateFunction::MIN = new ::poi::ss::usermodel::DataConsolidateFunction(u"MIN"_j, 4, int32_t(5), u"Min"_j); poi::ss::usermodel::DataConsolidateFunction* poi::ss::usermodel::DataConsolidateFunction::PRODUCT = new ::poi::ss::usermodel::DataConsolidateFunction(u"PRODUCT"_j, 5, int32_t(6), u"Product"_j); poi::ss::usermodel::DataConsolidateFunction* poi::ss::usermodel::DataConsolidateFunction::STD_DEV = new ::poi::ss::usermodel::DataConsolidateFunction(u"STD_DEV"_j, 6, int32_t(7), u"StdDev"_j); poi::ss::usermodel::DataConsolidateFunction* poi::ss::usermodel::DataConsolidateFunction::STD_DEVP = new ::poi::ss::usermodel::DataConsolidateFunction(u"STD_DEVP"_j, 7, int32_t(8), u"StdDevp"_j); poi::ss::usermodel::DataConsolidateFunction* poi::ss::usermodel::DataConsolidateFunction::SUM = new ::poi::ss::usermodel::DataConsolidateFunction(u"SUM"_j, 8, int32_t(9), u"Sum"_j); poi::ss::usermodel::DataConsolidateFunction* poi::ss::usermodel::DataConsolidateFunction::VAR = new ::poi::ss::usermodel::DataConsolidateFunction(u"VAR"_j, 9, int32_t(10), u"Var"_j); poi::ss::usermodel::DataConsolidateFunction* poi::ss::usermodel::DataConsolidateFunction::VARP = new ::poi::ss::usermodel::DataConsolidateFunction(u"VARP"_j, 10, int32_t(11), u"Varp"_j); void poi::ss::usermodel::DataConsolidateFunction::ctor(::java::lang::String* name, int ordinal, int32_t value, ::java::lang::String* name1) { super::ctor(name, ordinal); this->value = value; this->name_ = name; } java::lang::String* poi::ss::usermodel::DataConsolidateFunction::getName() { return this->name_; } int32_t poi::ss::usermodel::DataConsolidateFunction::getValue() { return this->value; } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::ss::usermodel::DataConsolidateFunction::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.ss.usermodel.DataConsolidateFunction", 51); return c; } poi::ss::usermodel::DataConsolidateFunction* poi::ss::usermodel::DataConsolidateFunction::valueOf(::java::lang::String* a0) { if(AVERAGE->toString()->equals(a0)) return AVERAGE; if(COUNT->toString()->equals(a0)) return COUNT; if(COUNT_NUMS->toString()->equals(a0)) return COUNT_NUMS; if(MAX->toString()->equals(a0)) return MAX; if(MIN->toString()->equals(a0)) return MIN; if(PRODUCT->toString()->equals(a0)) return PRODUCT; if(STD_DEV->toString()->equals(a0)) return STD_DEV; if(STD_DEVP->toString()->equals(a0)) return STD_DEVP; if(SUM->toString()->equals(a0)) return SUM; if(VAR->toString()->equals(a0)) return VAR; if(VARP->toString()->equals(a0)) return VARP; throw new ::java::lang::IllegalArgumentException(a0); } poi::ss::usermodel::DataConsolidateFunctionArray* poi::ss::usermodel::DataConsolidateFunction::values() { return new poi::ss::usermodel::DataConsolidateFunctionArray({ AVERAGE, COUNT, COUNT_NUMS, MAX, MIN, PRODUCT, STD_DEV, STD_DEVP, SUM, VAR, VARP, }); } java::lang::Class* poi::ss::usermodel::DataConsolidateFunction::getClass0() { return class_(); }
41.485294
197
0.706487
8fa5ecfa889230b20409cec510e61b6d1c6e17f7
3,353
cpp
C++
lib/djvAV/TIFFFunc.cpp
pafri/DJV
9db15673b6b03ad3743f57119118261b1fbe8810
[ "BSD-3-Clause" ]
null
null
null
lib/djvAV/TIFFFunc.cpp
pafri/DJV
9db15673b6b03ad3743f57119118261b1fbe8810
[ "BSD-3-Clause" ]
null
null
null
lib/djvAV/TIFFFunc.cpp
pafri/DJV
9db15673b6b03ad3743f57119118261b1fbe8810
[ "BSD-3-Clause" ]
null
null
null
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2020 Darby Johnston // All rights reserved. #include <djvAV/TIFFFunc.h> #include <array> using namespace djv::Core; namespace djv { namespace AV { namespace IO { namespace TIFF { void readPalette( uint8_t * in, int size, int bytes, uint16_t * red, uint16_t * green, uint16_t * blue) { switch (bytes) { case 1: { const uint8_t * inP = in + size - 1; uint8_t * outP = in + (size_t(size) - 1) * 3; for (int x = 0; x < size; ++x, outP -= 3) { const uint8_t index = *inP--; outP[0] = static_cast<uint8_t>(red[index]); outP[1] = static_cast<uint8_t>(green[index]); outP[2] = static_cast<uint8_t>(blue[index]); } } break; case 2: { const uint16_t * inP = reinterpret_cast<const uint16_t *>(in) + size - 1; uint16_t * outP = reinterpret_cast<uint16_t *>(in) + (size_t(size) - 1) * 3; for (int x = 0; x < size; ++x, outP -= 3) { const uint16_t index = *inP--; outP[0] = red [index]; outP[1] = green[index]; outP[2] = blue [index]; } } break; } } DJV_ENUM_HELPERS_IMPLEMENTATION(Compression); } // namespace TIFF } // namespace IO } // namespace AV rapidjson::Value toJSON(const AV::IO::TIFF::Options& value, rapidjson::Document::AllocatorType& allocator) { rapidjson::Value out(rapidjson::kObjectType); { std::stringstream ss; ss << value.compression; const std::string& s = ss.str(); out.AddMember("Compression", rapidjson::Value(s.c_str(), s.size(), allocator), allocator); } return out; } void fromJSON(const rapidjson::Value& value, AV::IO::TIFF::Options& out) { if (value.IsObject()) { for (const auto& i : value.GetObject()) { if (0 == strcmp("Compression", i.name.GetString()) && i.value.IsString()) { std::stringstream ss(i.value.GetString()); ss >> out.compression; } } } else { //! \todo How can we translate this? throw std::invalid_argument(DJV_TEXT("error_cannot_parse_the_value")); } } DJV_ENUM_SERIALIZE_HELPERS_IMPLEMENTATION( AV::IO::TIFF, Compression, DJV_TEXT("tiff_compression_none"), DJV_TEXT("tiff_compression_rle"), DJV_TEXT("tiff_compression_lzw")); } // namespace djv
31.933333
110
0.421712
8fa68f10b64065a1e43f7291036da4b7943b8745
3,005
cpp
C++
IotHttpServer/tests/TestUriParser.cpp
saarbastler/IotHttpServer
f55896950510e7a6403d19ce2f425adae4761b2d
[ "BSD-2-Clause" ]
1
2018-08-26T11:37:31.000Z
2018-08-26T11:37:31.000Z
IotHttpServer/tests/TestUriParser.cpp
saarbastler/IotHttpServer
f55896950510e7a6403d19ce2f425adae4761b2d
[ "BSD-2-Clause" ]
null
null
null
IotHttpServer/tests/TestUriParser.cpp
saarbastler/IotHttpServer
f55896950510e7a6403d19ce2f425adae4761b2d
[ "BSD-2-Clause" ]
null
null
null
#ifdef IOT_HTTP_SERVER_TESTS #include <iostream> #include "../UriParser.h" //#define BOOST_TEST_MODULE UriParserTest #include <boost/test/unit_test.hpp> using namespace saba::web; BOOST_AUTO_TEST_CASE(UriParserTest_path1) { UriParser uriParser("/"); BOOST_CHECK_EQUAL(uriParser.getPath(), "/"); BOOST_CHECK(uriParser.getFragment().empty()); BOOST_CHECK_EQUAL(uriParser.params().size(), 0); } BOOST_AUTO_TEST_CASE(UriParserTest_path2) { UriParser uriParser("/abc/def"); BOOST_CHECK_EQUAL(uriParser.getPath(), "/abc/def"); BOOST_CHECK(uriParser.getFragment().empty()); BOOST_CHECK_EQUAL(uriParser.params().size(), 0); } BOOST_AUTO_TEST_CASE(UriParserTest_fragment) { UriParser uriParser("/url#test"); BOOST_CHECK_EQUAL(uriParser.getPath(), "/url"); BOOST_CHECK_EQUAL(uriParser.getFragment(), "test"); BOOST_CHECK_EQUAL(uriParser.params().size(), 0); } BOOST_AUTO_TEST_CASE(UriParserTest_params1) { UriParser uriParser("/abc/def?a=b"); BOOST_CHECK_EQUAL(uriParser.getPath(), "/abc/def"); BOOST_CHECK(uriParser.getFragment().empty()); BOOST_CHECK_EQUAL(uriParser.params().size(), 1); auto it = uriParser.params().find("a"); BOOST_REQUIRE(it != uriParser.params().end()); BOOST_CHECK_EQUAL(it->second, "b"); } BOOST_AUTO_TEST_CASE(UriParserTest_params2) { UriParser uriParser("/?name=value&name2=1234"); BOOST_CHECK_EQUAL(uriParser.getPath(), "/"); BOOST_CHECK(uriParser.getFragment().empty()); BOOST_CHECK_EQUAL(uriParser.params().size(), 2); auto it = uriParser.params().find("name"); BOOST_REQUIRE(it != uriParser.params().end()); BOOST_CHECK_EQUAL(it->second, "value"); it = uriParser.params().find("name2"); BOOST_REQUIRE(it != uriParser.params().end()); BOOST_CHECK_EQUAL(it->second, "1234"); } BOOST_AUTO_TEST_CASE(UriParserTest_params_fragment) { UriParser uriParser("/my/uri/?arg1=value1&arg2=xyz#qwertz"); BOOST_CHECK_EQUAL(uriParser.getPath(), "/my/uri/"); BOOST_CHECK_EQUAL(uriParser.getFragment(),"qwertz"); BOOST_CHECK_EQUAL(uriParser.params().size(), 2); auto it = uriParser.params().find("arg1"); BOOST_REQUIRE(it != uriParser.params().end()); BOOST_CHECK_EQUAL(it->second, "value1"); it = uriParser.params().find("arg2"); BOOST_REQUIRE(it != uriParser.params().end()); BOOST_CHECK_EQUAL(it->second, "xyz"); } BOOST_AUTO_TEST_CASE(UriParserTest_decode) { UriParser uriParser("/my/uri/?arg1=hello%20world&arg2=%5c%26%3D#q%3Bw%3Ae%2A%23"); BOOST_CHECK_EQUAL(uriParser.getPath(), "/my/uri/"); BOOST_CHECK_EQUAL(uriParser.getFragment(), "q;w:e*#"); BOOST_CHECK_EQUAL(uriParser.params().size(), 2); auto it = uriParser.params().find("arg1"); BOOST_REQUIRE(it != uriParser.params().end()); BOOST_CHECK_EQUAL(it->second, "hello world"); it = uriParser.params().find("arg2"); BOOST_REQUIRE(it != uriParser.params().end()); BOOST_CHECK_EQUAL(it->second, "\\&="); } #endif
28.349057
85
0.692512
8fa829cf09caf4185924822def95ead5d454d5d3
5,300
cpp
C++
common/Util.cpp
enjiushi/VulkanLearn
29fb429a3fb526f8de7406404a983685a7e87117
[ "MIT" ]
272
2019-06-27T12:21:49.000Z
2022-03-23T07:18:33.000Z
common/Util.cpp
enjiushi/VulkanLearn
29fb429a3fb526f8de7406404a983685a7e87117
[ "MIT" ]
9
2019-08-11T13:07:01.000Z
2022-01-26T12:30:24.000Z
common/Util.cpp
enjiushi/VulkanLearn
29fb429a3fb526f8de7406404a983685a7e87117
[ "MIT" ]
16
2019-09-29T01:41:02.000Z
2022-03-29T15:51:35.000Z
#include "Util.h" #include "Enums.h" #include "../common/Macros.h" Axis CubeFaceAxisMapping[(uint32_t)CubeFace::COUNT][(uint32_t)NormCoordAxis::COUNT] = { { Axis::Y, Axis::Z, Axis::X }, { Axis::Y, Axis::Z, Axis::X }, { Axis::Z, Axis::X, Axis::Y }, { Axis::Z, Axis::X, Axis::Y }, { Axis::X, Axis::Y, Axis::Z }, { Axis::X, Axis::Y, Axis::Z } }; uint64_t AcquireBinaryCoord(double normCoord) { // Prepare uint64_t *pBinaryCoord; pBinaryCoord = (uint64_t*)&normCoord; // Step7: Acquire binary position of the intersection // 1. (*pU) & fractionMask: Acquire only fraction bits // 2. (1) + extraOne: Acquire actual fraction bits by adding an invisible bit // 3. (*pU) & exponentMask: Acquire only exponent bits // 4. (3) >> fractionBits: Acquire readable exponent by shifting it right of 52 bits // 5. zeroExponent - (3): We need to right shift fraction part using exponent value, to make same levels pair with same bits(floating format trait) // 6. (2) >> (5): Right shift return (((*pBinaryCoord) & fractionMask) + extraOne) >> (zeroExponent - (((*pBinaryCoord) & exponentMask) >> fractionBits)); } uint32_t GetVertexBytes(uint32_t vertexFormat) { uint32_t vertexByte = 0; if (vertexFormat & (1 << VAFPosition)) { vertexByte += 3 * sizeof(float); } if (vertexFormat & (1 << VAFNormal)) { vertexByte += 3 * sizeof(float); } if (vertexFormat & (1 << VAFColor)) { vertexByte += 4 * sizeof(float); } if (vertexFormat & (1 << VAFTexCoord)) { vertexByte += 2 * sizeof(float); } if (vertexFormat & (1 << VAFTangent)) { vertexByte += 3 * sizeof(float); } if (vertexFormat & (1 << VAFBone)) { vertexByte += 5 * sizeof(float); } return vertexByte; } uint32_t GetIndexBytes(VkIndexType indexType) { switch (indexType) { case VK_INDEX_TYPE_UINT16: return 2; case VK_INDEX_TYPE_UINT32: return 4; default: ASSERTION(false); } return 0; } VkVertexInputBindingDescription GenerateReservedVBBindingDesc(uint32_t vertexFormat) { VkVertexInputBindingDescription bindingDesc = {}; bindingDesc.binding = ReservedVBBindingSlot_MeshData; bindingDesc.stride = GetVertexBytes(vertexFormat); bindingDesc.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; return bindingDesc; } std::vector<VkVertexInputAttributeDescription> GenerateReservedVBAttribDesc(uint32_t vertexFormat, uint32_t vertexFormatInMem) { // Do assert all bits of vertex format must exist in vertex format in memory ASSERTION((vertexFormat & vertexFormatInMem) == vertexFormat); std::vector<VkVertexInputAttributeDescription> attribDesc; uint32_t offset = 0; if (vertexFormat & (1 << VAFPosition)) { VkVertexInputAttributeDescription attrib = {}; attrib.binding = ReservedVBBindingSlot_MeshData; attrib.format = VK_FORMAT_R32G32B32_SFLOAT; attrib.location = VAFPosition; attrib.offset = offset; attribDesc.push_back(attrib); } if (vertexFormatInMem & (1 << VAFPosition)) offset += sizeof(float) * 3; if (vertexFormat & (1 << VAFNormal)) { VkVertexInputAttributeDescription attrib = {}; attrib.binding = ReservedVBBindingSlot_MeshData; attrib.format = VK_FORMAT_R32G32B32_SFLOAT; attrib.location = VAFNormal; attrib.offset = offset; attribDesc.push_back(attrib); } if (vertexFormatInMem & (1 << VAFNormal)) offset += sizeof(float) * 3; if (vertexFormat & (1 << VAFColor)) { VkVertexInputAttributeDescription attrib = {}; attrib.binding = ReservedVBBindingSlot_MeshData; attrib.format = VK_FORMAT_R32G32B32A32_SFLOAT; attrib.location = VAFColor; attrib.offset = offset; attribDesc.push_back(attrib); } if (vertexFormatInMem & (1 << VAFColor)) offset += sizeof(float) * 4; if (vertexFormat & (1 << VAFTexCoord)) { VkVertexInputAttributeDescription attrib = {}; attrib.binding = ReservedVBBindingSlot_MeshData; attrib.format = VK_FORMAT_R32G32_SFLOAT; attrib.location = VAFTexCoord; attrib.offset = offset; attribDesc.push_back(attrib); } if (vertexFormatInMem & (1 << VAFTexCoord)) offset += sizeof(float) * 2; if (vertexFormat & (1 << VAFTangent)) { VkVertexInputAttributeDescription attrib = {}; attrib.binding = ReservedVBBindingSlot_MeshData; attrib.format = VK_FORMAT_R32G32B32_SFLOAT; attrib.location = VAFTangent; attrib.offset = offset; attribDesc.push_back(attrib); } if (vertexFormatInMem & (1 << VAFTangent)) offset += sizeof(float) * 3; if (vertexFormat & (1 << VAFBone)) { // Bone weight VkVertexInputAttributeDescription attrib = {}; attrib.binding = ReservedVBBindingSlot_MeshData; attrib.format = VK_FORMAT_R32G32B32A32_SFLOAT; attrib.location = VAFBone; attrib.offset = offset; attribDesc.push_back(attrib); // Bone index (4 bytes, 1 per index from 0 - 255) attrib = {}; attrib.binding = ReservedVBBindingSlot_MeshData; attrib.format = VK_FORMAT_R32_UINT; attrib.location = VAFBone + 1; attrib.offset = offset + sizeof(float) * 4; attribDesc.push_back(attrib); } if (vertexFormatInMem & (1 << VAFBone)) offset += sizeof(float) * 5; return attribDesc; } void TransferBytesToVector(std::vector<uint8_t>& vec, const void* pData, uint32_t offset, uint32_t numBytes) { if (offset + numBytes > (uint32_t)vec.size()) { vec.resize(offset + numBytes); } for (uint32_t i = 0; i < numBytes; i++) { vec[offset + i] = *((uint8_t*)(pData) + i); } }
28.648649
148
0.712264
8fa9b96a70ccdf8a7096913e6a93b7d357d817ef
8,987
cpp
C++
src/main.cpp
otakot/CarND-PID-Control
692e3fd482bb711bfac78684b2e2bd04672b6913
[ "MIT" ]
null
null
null
src/main.cpp
otakot/CarND-PID-Control
692e3fd482bb711bfac78684b2e2bd04672b6913
[ "MIT" ]
null
null
null
src/main.cpp
otakot/CarND-PID-Control
692e3fd482bb711bfac78684b2e2bd04672b6913
[ "MIT" ]
null
null
null
#include <uWS/uWS.h> #include <iostream> #include "json.hpp" #include "PID.h" #include <math.h> #include <limits> // for convenience using json = nlohmann::json; // best tau values (manually selected, based on comfort feeling) double K_P = 0.12; double K_I = 0.0015; double K_D = 5.0; // calibrated tau values, based on criteria of minimal mean squared error: [0.245, 0.0008949, 8.74359] constexpr double MAX_CALIBRATION_STEPS = 2000; constexpr double MIN_SPEED = 5.0; constexpr double ANTI_ROLLBACK_THROTTLE = 0.1; // calibration variables double delta_tau_tolerance = 0.0; double delta_tau = 0.0; double squared_eror_sum = 0.0; // sum of suared errors int calibration_steps_counter = 0; double best_mse = std::numeric_limits<double>::max(); double current_param_value = K_P; double best_param_value = 0.0; // Checks if the SocketIO event has JSON data. // If there is data the JSON object in string format will be returned, // else the empty string "" will be returned. std::string hasData(std::string s) { auto found_null = s.find("null"); auto b1 = s.find_first_of("["); auto b2 = s.find_last_of("]"); if (found_null != std::string::npos) { return ""; } else if (b1 != std::string::npos && b2 != std::string::npos) { return s.substr(b1, b2 - b1 + 1); } return ""; } void ResetSimulator(uWS::WebSocket<uWS::SERVER> ws) { std::string reset_msg = "42[\"reset\",{}]"; ws.send(reset_msg.data(), reset_msg.length(), uWS::OpCode::TEXT); calibration_steps_counter = 0; squared_eror_sum = 0.0; // mean squared error } void CalibrateParam(const double mse, double& param_value, double& delta, bool& reset_flag){ if(delta > delta_tau_tolerance) { if (reset_flag) { // param value was not yet updated current_param_value = param_value; param_value+=delta; std::cout << "Param increased from : " << current_param_value << " to " << param_value << std::endl; reset_flag = false; } else { if (mse < best_mse) { best_mse = mse; best_param_value = param_value; // store best value of parameter as a workaround for 'local optimum' issue delta*=1.1; std::cout << "Delta increased by 1.1" << " to " << delta << std::endl; reset_flag = true; CalibrateParam(mse, param_value, delta_tau, reset_flag); } else { if (current_param_value < param_value) { //param value was increased by d_param during previous calibration step but this was not efficent current_param_value = param_value; param_value-= 2.0 * delta; // decrease to previous value and try by d_param less std::cout << "Param decreased from : " << current_param_value << " to " << param_value << std::endl; reset_flag = false; } else { // seems like param value was decreased in previous step and this was not efficient current_param_value = param_value; param_value+= delta_tau; // restore param value to initial state delta*= 0.9; // decrease d_param reset_flag = true; std::cout << "Delta decreased by 0.9" << " to " << delta << std::endl; std::cout << "Param restored to " << param_value << std::endl; } } } } else { std::cout << "Calibration finished!: Best MSE: " << best_mse << " with PID parameter value " << best_param_value << std::endl; exit(0); } } int main(int argC, char** argV) { bool in_caliration_mode = false; bool calibration_reset = true; double* calibration_param = nullptr; PID pid; // check if PID controller has to run in calibration mode to find best values for tau parameters if (argC > 2) { std::string mode = argV[1]; if (mode.compare("calibrate") == 0) { in_caliration_mode = true; } std::string calibration_param_name = argV[2]; if (calibration_param_name.compare("P")==0) { calibration_param = &pid.Kp_; // calibration process settings K_P = 0.05; delta_tau_tolerance = 0.005; delta_tau = 0.01; } else if (calibration_param_name.compare("I")==0){ calibration_param = &pid.Ki_; // calibration process settings K_I = 0.0005; delta_tau_tolerance = 0.00005; delta_tau = 0.0001; } else if (calibration_param_name.compare("D")==0) { K_D = 3.0; calibration_param = &pid.Kd_; // calibration process settings K_D = 3.0; delta_tau_tolerance = 0.2; delta_tau = 0.5; } else { std::cerr << "Unsupported PID param name " << calibration_param << std::endl; return -1; } } uWS::Hub h; // Initialize the PID controller with default tau values pid.Init(K_P, K_I, K_D); h.onMessage([&pid, &in_caliration_mode, &calibration_reset, &calibration_param](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) { // "42" at the start of the message means there's a websocket message event. // The 4 signifies a websocket message // The 2 signifies a websocket event if (length && length > 2 && data[0] == '4' && data[1] == '2') { auto s = hasData(std::string(data).substr(0, length)); if (s != "") { auto j = json::parse(s); std::string event = j[0].get<std::string>(); if (event == "telemetry") { // j[1] is the data JSON object double cte = std::stod(j[1]["cte"].get<std::string>()); double speed = std::stod(j[1]["speed"].get<std::string>()); double angle = std::stod(j[1]["steering_angle"].get<std::string>()); double steer_value; /* * Calcuate steering value in range [-1, 1]. * NOTE: Feel free to play around with the throttle and speed. Maybe use * another PID controller to control the speed! */ // Update error values with new cte pid.UpdateError(cte); // Calculate value for steer controller within allowed range [-1, 1] steer_value = std::min(1.0, std::max(-1.0, pid.TotalError())); // DEBUG if (in_caliration_mode) { calibration_steps_counter++; if (calibration_steps_counter > MAX_CALIBRATION_STEPS) { // we gathered enough data for calibration, so can calibrate now const double mse = squared_eror_sum / (calibration_steps_counter-1); std::cout << " Best MSE: " << best_mse << " Current MSE: " << mse << " with PID params: " << pid.Kp_ << ": " << pid.Ki_ << " : " << pid.Kd_ << std::endl; CalibrateParam(mse, *calibration_param, delta_tau, calibration_reset); ResetSimulator(ws); return; } else { // update mean squared error squared_eror_sum+= pow(cte, 2); } } else { std::cout << " Steering Angle: " << angle << ", CTE: " << cte << ", Calculated steer Value: " << steer_value << std::endl; } json msgJson; msgJson["steering_angle"] = steer_value; // Throttle value must correlate with steering angle. // means the bigger the steering angle is in both left and right direction in range [0:1], // smaller the throttle must be (even lowering to negative value for slight braking). double throttle = 0.7 - std::abs(cte)/4 - std::abs(steer_value); if(speed < MIN_SPEED && throttle < 0) { throttle = ANTI_ROLLBACK_THROTTLE; } msgJson["throttle"] = throttle; auto msg = "42[\"steer\"," + msgJson.dump() + "]"; //std::cout << msg << std::endl; ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT); } } else { // Manual driving std::string msg = "42[\"manual\",{}]"; ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT); } } }); // We don't need this since we're not using HTTP but if it's removed the program // doesn't compile :-( h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data, size_t, size_t) { const std::string s = "<h1>Hello world!</h1>"; if (req.getUrl().valueLength == 1) { res->end(s.data(), s.length()); } else { // i guess this should be done more gracefully? res->end(nullptr, 0); } }); h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) { std::cout << "Connected!!!" << std::endl; }); h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char *message, size_t length) { ws.close(); std::cout << "Disconnected" << std::endl; }); int port = 4567; if (h.listen(port)) { std::cout << "Listening to port " << port << std::endl; } else { std::cerr << "Failed to listen to port" << std::endl; return -1; } h.run(); }
35.804781
172
0.592745
8faccddc8c15d5eca8f759aee1b8a865cb6aade4
14,212
inl
C++
include/ion/math/matrix.inl
dvdbrink/ion
a5fe2aba7927b7a90e913cbf72325a04172fc494
[ "MIT" ]
null
null
null
include/ion/math/matrix.inl
dvdbrink/ion
a5fe2aba7927b7a90e913cbf72325a04172fc494
[ "MIT" ]
null
null
null
include/ion/math/matrix.inl
dvdbrink/ion
a5fe2aba7927b7a90e913cbf72325a04172fc494
[ "MIT" ]
null
null
null
template<typename T, std::size_t R, std::size_t C> inline Matrix<T, R, C>::Matrix() { for (unsigned int i = 0; i < R; i++) { for (unsigned int j = 0; j < C; j++) { m[i][j] = (T)((i == j) ? 1 : 0); } } } template<typename T, std::size_t R, std::size_t C> inline Matrix<T, R, C>::Matrix(std::initializer_list<T> list) { assert(list.size() == R*C); auto iterator = begin(list); for (unsigned int i = 0; i < R; i++) { for (unsigned int j = 0; j < C; j++) { m[i][j] = *(iterator++); } } } template<typename T, std::size_t R, std::size_t C> inline Matrix<T, R, C>::Matrix(const Matrix<T, R, C>& rhs) { if (this != &rhs) { m = rhs.m; } } template<typename T, std::size_t R, std::size_t C> inline Matrix<T, R, C>::Matrix(Matrix<T, R, C>&& rhs) { if (this != &rhs) { m = std::move(rhs.m); } } template<typename T, std::size_t R, std::size_t C> inline Matrix<T, R, C>& Matrix<T, R, C>::operator=(const Matrix<T, R, C>& rhs) { if (this != &rhs) { m = rhs.m; } return *this; } template<typename T, std::size_t R, std::size_t C> inline Matrix<T, R, C>& Matrix<T, R, C>::operator=(Matrix<T, R, C>&& rhs) { if (this != &rhs) { m = std::move(rhs.m); } return *this; } template<typename T, std::size_t R, std::size_t C> inline Matrix<T, R, C>& Matrix<T, R, C>::operator+=(const Matrix<T, R, C>& rhs) { for (unsigned int r = 0; r < R; r++) { for (unsigned int c = 0; c < C; c++) { m[r][c] += rhs[r][c]; } } return *this; } template<typename T, std::size_t R, std::size_t C> inline Matrix<T, R, C>& Matrix<T, R, C>::operator-=(const Matrix<T, R, C>& rhs) { for (unsigned int r = 0; r < R; r++) { for (unsigned int c = 0; c < C; c++) { m[r][c] -= rhs[r][c]; } } return *this; } template<typename T, std::size_t R, std::size_t C> inline Matrix<T, R, C>& Matrix<T, R, C>::operator*=(const Matrix<T, R, C>& rhs) { assert(R == C); Matrix<T, R, C> out; for (unsigned int i = 0; i < R; i++) { for (unsigned int j = 0; j < C; j++) { out[i][j] = (T) 0; for (unsigned int k = 0; k < C; k++) { out[i][j] += m[i][k] * rhs[k][j]; } } } *this = out; return *this; } template<typename T, std::size_t R, std::size_t C> inline Matrix<T, R, C>& Matrix<T, R, C>::operator*=(const T rhs) { for (unsigned int i = 0; i < R; i++) { for (unsigned int j = 0; j < C; j++) { m[i][j] *= rhs; } } return *this; } template<typename T, std::size_t R, std::size_t C> inline std::array<T, C>& Matrix<T, R, C>::operator[](const unsigned int i) { return m[i]; } template<typename T, std::size_t R, std::size_t C> inline const std::array<T, C>& Matrix<T, R, C>::operator[](const unsigned int i) const { return m[i]; } template<typename T, std::size_t R, std::size_t C> inline Matrix<T, R, C> operator+(const Matrix<T, R, C>& lhs, const Matrix<T, R, C>& rhs) { return Matrix<T, R, C>(lhs) += rhs; } template<typename T, std::size_t R, std::size_t C> inline Matrix<T, R, C> operator-(const Matrix<T, R, C>& lhs, const Matrix<T, R, C>& rhs) { return Matrix<T, R, C>(lhs) -= rhs; } template<typename T, size_t R, size_t C> inline Matrix<T, R, C> operator*(const Matrix<T, R, C>& lhs, const Matrix<T, R, C>& rhs) { return Matrix<T, R, C>(lhs) *= rhs; } template<typename T, size_t R, size_t C> inline Matrix<T, R, C> operator*(const Matrix<T, R, C>& lhs, const T rhs) { return Matrix<T, R, C>(lhs) *= rhs; } template<typename T, size_t R, size_t C, size_t N> inline Vector3<T> operator*(const Matrix<T, R, C>& lhs, const Vector3<T>& rhs) { return Matrix<T, R, C>(lhs) *= rhs; } template<typename T, size_t R, size_t C> inline bool operator==(const Matrix<T, R, C>& lhs, const Matrix<T, R, C>& rhs) { for (unsigned int r = 0; r < R; r++) { for (unsigned int c = 0; c < C; c++) { if (lhs[r][c] != rhs[r][c]) { return false; } } } return true; } template<typename T, size_t R, size_t C> inline bool operator!=(const Matrix<T, R, C>& lhs, const Matrix<T, R, C>& rhs) { for (unsigned int r = 0; r < R; r++) { for (unsigned int c = 0; c < C; c++) { if (lhs[r][c] == rhs[r][c]) { return false; } } } return true; } template<typename T, size_t R, size_t C> inline std::ostream& operator<<(std::ostream& out, const Matrix<T, R, C>& rhs) { for (unsigned int i = 0; i < R; i++) { for (unsigned int j = 0; j < C; j++) { out << rhs[i][j]; if (j < C-1) { out << ", "; } } if (i < R-1) { out << "\n"; } } return out; } template<typename T, size_t R, size_t C> inline Matrix<T, R, C> transpose(const Matrix<T, R, C>& in) { assert(R == C); Matrix<T, R, C> out; for (unsigned int i = 0; i < R; i++) { for (unsigned int j = 0; j < C; j++) { out[j][i] = in[i][j]; } } return out; } template<typename T> inline T determinant(const Matrix<T, 2, 2>& in) { return in[0][0] * in[1][1] - in[0][1] * in[1][0]; } template<typename T> inline T determinant(const Matrix<T, 3, 3>& in) { return in[0][0] * (in[1][1] * in[2][2] - in[2][1] * in[1][2]) + in[0][1] * (in[2][0] * in[1][2] - in[1][0] * in[2][2]) + in[0][2] * (in[1][0] * in[2][1] - in[2][0] * in[1][1]); } template<typename T> inline T determinant(const Matrix<T, 4, 4>& in) { return in[3][0]*in[2][1]*in[1][2]*in[0][3] - in[2][0]*in[3][1]*in[1][2]*in[0][3] - in[3][0]*in[1][1]*in[2][2]*in[0][3] + in[1][0]*in[3][1]*in[2][2]*in[0][3] + in[2][0]*in[1][1]*in[3][2]*in[0][3] - in[1][0]*in[2][1]*in[3][2]*in[0][3] - in[3][0]*in[2][1]*in[0][2]*in[1][3] + in[2][0]*in[3][1]*in[0][2]*in[1][3] + in[3][0]*in[0][1]*in[2][2]*in[1][3] - in[0][0]*in[3][1]*in[2][2]*in[1][3] - in[2][0]*in[0][1]*in[3][2]*in[1][3] + in[0][0]*in[2][1]*in[3][2]*in[1][3] + in[3][0]*in[1][1]*in[0][2]*in[2][3] - in[1][0]*in[3][1]*in[0][2]*in[2][3] - in[3][0]*in[0][1]*in[1][2]*in[2][3] + in[0][0]*in[3][1]*in[1][2]*in[2][3] + in[1][0]*in[0][1]*in[3][2]*in[2][3] - in[0][0]*in[1][1]*in[3][2]*in[2][3] - in[2][0]*in[1][1]*in[0][2]*in[3][3] + in[1][0]*in[2][1]*in[0][2]*in[3][3] + in[2][0]*in[0][1]*in[1][2]*in[3][3] - in[0][0]*in[2][1]*in[1][2]*in[3][3] - in[1][0]*in[0][1]*in[2][2]*in[3][3] + in[0][0]*in[1][1]*in[2][2]*in[3][3]; } template<typename T> inline Matrix<T, 2, 2> adjugate(const Matrix<T, 2, 2>& in) { return {in[1][1], -in[0][1], -in[1][0], in[0][0]}; } template<typename T> inline Matrix<T, 3, 3> adjugate(const Matrix<T, 3, 3>& in) { Matrix<T, 3, 3> out; out[0][0] = in[1][1] * in[2][2] - in[1][2] * in[2][1]; out[1][0] = in[0][2] * in[2][1] - in[0][1] * in[2][2]; out[2][0] = in[0][1] * in[1][2] - in[0][2] * in[1][1]; out[0][1] = in[1][2] * in[2][0] - in[1][0] * in[2][2]; out[1][1] = in[0][0] * in[2][2] - in[0][2] * in[2][0]; out[2][1] = in[0][2] * in[1][0] - in[0][0] * in[1][2]; out[0][2] = in[1][0] * in[2][1] - in[1][1] * in[2][0]; out[1][2] = in[0][1] * in[2][0] - in[0][0] * in[2][1]; out[2][2] = in[0][0] * in[1][1] - in[0][1] * in[1][0]; return out; } template<typename T> inline Matrix<T, 4, 4> adjugate(const Matrix<T, 4, 4>& in) { Matrix<T, 4, 4> out; out[0][0] = in[1][1]*in[2][2]*in[3][3] + in[2][1]*in[3][2]*in[1][3] + in[3][1]*in[1][2]*in[2][3] - in[1][1]*in[3][2]*in[2][3] - in[2][1]*in[1][2]*in[3][3] - in[3][1]*in[2][2]*in[1][3]; out[1][0] = in[0][1]*in[3][2]*in[2][3] + in[2][1]*in[0][2]*in[3][3] + in[3][1]*in[2][2]*in[0][3] - in[0][1]*in[2][2]*in[3][3] - in[2][1]*in[3][2]*in[0][3] - in[3][1]*in[0][2]*in[2][3]; out[2][0] = in[0][1]*in[1][2]*in[3][3] + in[1][1]*in[3][2]*in[0][3] + in[3][1]*in[0][2]*in[1][3] - in[0][1]*in[3][2]*in[1][3] - in[1][1]*in[0][2]*in[3][3] - in[3][1]*in[1][2]*in[0][3]; out[3][0] = in[0][1]*in[2][2]*in[1][3] + in[1][1]*in[0][2]*in[2][3] + in[2][1]*in[1][2]*in[0][3] - in[0][1]*in[1][2]*in[2][3] - in[1][1]*in[2][2]*in[0][3] - in[2][1]*in[0][2]*in[1][3]; out[0][1] = in[1][0]*in[3][2]*in[2][3] + in[2][0]*in[1][2]*in[3][3] + in[3][0]*in[2][2]*in[1][3] - in[1][0]*in[2][2]*in[3][3] - in[2][0]*in[3][2]*in[1][3] - in[3][0]*in[1][2]*in[2][3]; out[1][1] = in[0][0]*in[2][2]*in[3][3] + in[2][0]*in[3][2]*in[0][3] + in[3][0]*in[0][2]*in[2][3] - in[0][0]*in[3][2]*in[2][3] - in[2][0]*in[0][2]*in[3][3] - in[3][0]*in[2][2]*in[0][3]; out[2][1] = in[0][0]*in[3][2]*in[1][3] + in[1][0]*in[0][2]*in[3][3] + in[3][0]*in[1][2]*in[0][3] - in[0][0]*in[1][2]*in[3][3] - in[1][0]*in[3][2]*in[0][3] - in[3][0]*in[0][2]*in[1][3]; out[3][1] = in[0][0]*in[1][2]*in[2][3] + in[1][0]*in[2][2]*in[0][3] + in[2][0]*in[0][2]*in[1][3] - in[0][0]*in[2][2]*in[1][3] - in[1][0]*in[0][2]*in[2][3] - in[2][0]*in[1][2]*in[0][3]; out[0][2] = in[1][0]*in[2][1]*in[3][3] + in[2][0]*in[3][1]*in[1][3] + in[3][0]*in[1][1]*in[2][3] - in[1][0]*in[3][1]*in[2][3] - in[2][0]*in[1][1]*in[3][3] - in[3][0]*in[2][1]*in[1][3]; out[1][2] = in[0][0]*in[3][1]*in[2][3] + in[2][0]*in[0][1]*in[3][3] + in[3][0]*in[2][1]*in[0][3] - in[0][0]*in[2][1]*in[3][3] - in[2][0]*in[3][1]*in[0][3] - in[3][0]*in[0][1]*in[2][3]; out[2][2] = in[0][0]*in[1][1]*in[3][3] + in[1][0]*in[3][1]*in[0][3] + in[3][0]*in[0][1]*in[1][3] - in[0][0]*in[3][1]*in[1][3] - in[1][0]*in[0][1]*in[3][3] - in[3][0]*in[1][1]*in[0][3]; out[3][2] = in[0][0]*in[2][1]*in[1][3] + in[1][0]*in[0][1]*in[2][3] + in[2][0]*in[1][1]*in[0][3] - in[0][0]*in[1][1]*in[2][3] - in[1][0]*in[2][1]*in[0][3] - in[2][0]*in[0][1]*in[1][3]; out[0][3] = in[1][0]*in[3][1]*in[2][2] + in[2][0]*in[1][1]*in[3][2] + in[3][0]*in[2][1]*in[1][2] - in[1][0]*in[2][1]*in[3][2] - in[2][0]*in[3][1]*in[1][2] - in[3][0]*in[1][1]*in[2][2]; out[1][3] = in[0][0]*in[2][1]*in[3][2] + in[2][0]*in[3][1]*in[0][2] + in[3][0]*in[0][1]*in[2][2] - in[0][0]*in[3][1]*in[2][2] - in[2][0]*in[0][1]*in[3][2] - in[3][0]*in[2][1]*in[0][2]; out[2][3] = in[0][0]*in[3][1]*in[1][2] + in[1][0]*in[0][1]*in[3][2] + in[3][0]*in[1][1]*in[0][2] - in[0][0]*in[1][1]*in[3][2] - in[1][0]*in[3][1]*in[0][2] - in[3][0]*in[0][1]*in[1][2]; out[3][3] = in[0][0]*in[1][1]*in[2][2] + in[1][0]*in[2][1]*in[0][2] + in[2][0]*in[0][1]*in[1][2] - in[0][0]*in[2][1]*in[1][2] - in[1][0]*in[0][1]*in[2][2] - in[2][0]*in[1][1]*in[0][2]; return out; } template<typename T, size_t R, size_t C> inline Matrix<T, R, C> inverse(const Matrix<T, R, C>& in) { assert(R == C); float d = determinant(in); assert(d != 0); return adjugate(in) * (1.0f / d); } template<typename T> inline Matrix<T, 4, 4> translate(const Matrix<T, 4, 4>& in, const Vector3<T>& translation) { Matrix<T, 4, 4> out(in); out[3][0] = translation.x; out[3][1] = translation.y; out[3][2] = translation.z; return out; } template<typename T> inline Matrix<T, 4, 4> scale(const Matrix<T, 4, 4>& in, const Vector3<T>& scalar) { Matrix<T, 4, 4> out(in); out[0][0] *= scalar.x; out[1][1] *= scalar.y; out[2][2] *= scalar.z; return out; } template<typename T, typename U> inline Vector3<T> project(const Vector3<T>& point, const Matrix<T, 4, 4>& projection, const Matrix<T, 4, 4>& view, const Vector4<U>& viewport) { Vector4<T> tmp = Vector4<T>{point.x, point.y, point.z, T(1)}; tmp = view * tmp; tmp = projection * tmp; tmp /= tmp.w; tmp = tmp * T(0.5) + T(0.5); tmp.x = tmp.x * T(viewport.z) + T(viewport.x); tmp.y = tmp.y * T(viewport.w) + T(viewport.y); return Vector3<T>{tmp.x, tmp.y, tmp.z}; } template<typename T, typename U> inline Vector3<T> unproject(const Vector3<T>& point, const Matrix<T, 4, 4>& projection, const Matrix<T, 4, 4>& view, const Vector4<U>& viewport) { Matrix<T, 4, 4> inverse = inverse(projection * view); Vector4<T> tmp = Vector4<T>{point.x, point.y, point.z, T(1)}; tmp[0] = (tmp[0] - T(viewport.x) / T(viewport.z)); tmp[1] = (tmp[1] - T(viewport.y) / T(viewport.w)); tmp = tmp * T(2) - T(1); Vector4<T> obj = inverse * tmp; obj /= obj.w; return Vector3<T>{obj.x, obj.y, obj.z}; } template<typename T> inline Matrix<T, 4, 4> perspective(const T fieldOfView, const T aspectRatio, const T nearPlane, const T farPlane) { T yScale = (T)(1.0f / std::tan((fieldOfView / 2.0f) * (3.14159265f / 180.0f))); T xScale = yScale / aspectRatio; T frustumLength = farPlane - nearPlane; Matrix<T, 4, 4> out; out[0][0] = xScale; out[1][1] = yScale; out[2][2] = -((farPlane + nearPlane) / frustumLength); out[2][3] = -1; out[3][2] = -((2 * nearPlane * farPlane) / frustumLength); return out; } template<typename T> inline Matrix<T, 4, 4> ortho(const T left, const T right, const T bottom, const T top, const T zNear, const T zFar) { Matrix<T, 4, 4> out; out[0][0] = T(2) / (right - left); out[1][1] = T(2) / (top - bottom); out[2][2] = -T(2) / (zFar - zNear); out[3][0] = -(right + left) / (right - left); out[3][1] = -(top + bottom) / (top - bottom); out[3][2] = -(zFar + zNear) / (zFar - zNear); return out; } template<typename T> inline Matrix<T, 4, 4> look_at(const Vector3<T>& position, const Vector3<T>& target, const Vector3<T>& up) { Vector3<T> zAxis = normal(position - target); Vector3<T> xAxis = normal(cross(up, zAxis)); Vector3<T> yAxis = cross(zAxis, xAxis); Matrix<T, 4, 4> out; out[0][0] = xAxis.x; out[1][0] = xAxis.y; out[2][0] = xAxis.z; out[0][1] = yAxis.x; out[1][1] = yAxis.y; out[2][1] = yAxis.z; out[0][2] = zAxis.x; out[1][2] = zAxis.y; out[2][2] = zAxis.z; out[3][0] = -dot(xAxis, position); out[3][1] = -dot(yAxis, position); out[3][2] = -dot(zAxis, position); return out; }
32.822171
188
0.485787
8fb27bdb97fb335445a8ee19d6b85273db44cc1a
150
cpp
C++
examples/llvm-hello_world/target/branching2.cpp
flix-/phasar
85b30c329be1766136c8cbc6f925cb4fd1bafd27
[ "BSL-1.0" ]
581
2018-06-10T10:37:55.000Z
2022-03-30T14:56:53.000Z
examples/llvm-hello_world/target/branching2.cpp
flix-/phasar
85b30c329be1766136c8cbc6f925cb4fd1bafd27
[ "BSL-1.0" ]
172
2018-06-13T12:33:26.000Z
2022-03-26T07:21:41.000Z
examples/llvm-hello_world/target/branching2.cpp
flix-/phasar
85b30c329be1766136c8cbc6f925cb4fd1bafd27
[ "BSL-1.0" ]
137
2018-06-10T10:31:14.000Z
2022-03-06T11:53:56.000Z
int main(int argc, char **argv) { int a = 10; int b = 100; if (argc - 1) { a = 20; } else { a = 30; b = 300; } return a + b; }
13.636364
33
0.426667
8fb84ea0e291d10742fddeab683b67fcb9cbaef5
8,286
cpp
C++
SurfaceCtrl/MagicCamera.cpp
Xemuth/SurfaceCtrl
07167935a0950c22f06fdf2ba2bff7bb3f2dee05
[ "BSD-2-Clause" ]
2
2020-07-12T21:06:23.000Z
2021-02-17T11:39:37.000Z
SurfaceCtrl/MagicCamera.cpp
Xemuth/SurfaceCtrl
07167935a0950c22f06fdf2ba2bff7bb3f2dee05
[ "BSD-2-Clause" ]
4
2021-02-17T11:38:45.000Z
2021-03-20T20:27:49.000Z
SurfaceCtrl/MagicCamera.cpp
Xemuth/SurfaceCtrl
07167935a0950c22f06fdf2ba2bff7bb3f2dee05
[ "BSD-2-Clause" ]
null
null
null
#include "MagicCamera.h" namespace Upp{ glm::mat4 MagicCamera::GetProjectionMatrix()const noexcept{ if(type == CameraType::PERSPECTIVE){ return glm::perspective(glm::radians(GetFOV()),float( ScreenSize.cx / ScreenSize.cy),GetDrawDistanceMin(),GetDrawDisanceMax());//We calculate Projection here since multiple camera can have different FOV }else if(type == CameraType::ORTHOGRAPHIC){ float distance = glm::distance(glm::vec3(0,0,0),transform.GetPosition())* float(ScreenSize.cx/ScreenSize.cy); float distanceY = glm::distance(glm::vec3(0,0,0),transform.GetPosition()); return glm::ortho(-distance ,distance ,-distanceY ,distanceY, 0.00001f, 10000.0f); // return glm::mat4(); }else{ LOG("Swaping to Camera Perspective (cause of unknow type)"); return glm::perspective(glm::radians(GetFOV()),(float)( ScreenSize.cx / ScreenSize.cy),(-GetDrawDisanceMax())*10.0f,(GetDrawDisanceMax())*10.0f);//We calculate Projection here since multiple camera can have different FOV } } glm::mat4 MagicCamera::GetViewMatrix()const noexcept{ return glm::lookAt( transform.GetPosition() , transform.GetPosition() + transform.GetFront() , transform.GetUp()); } glm::vec3 MagicCamera::UnProject2(float winX, float winY,float winZ)const noexcept{ glm::mat4 View = GetViewMatrix() * glm::mat4(1.0f); glm::mat4 projection = GetProjectionMatrix(); glm::mat4 viewProjInv = glm::inverse(projection * View); winY = float(ScreenSize.cy) - winY; glm::vec4 clickedPointOnSreen; clickedPointOnSreen.x = ((winX - 0.0f) / float(ScreenSize.cx)) *2.0f -1.0f; clickedPointOnSreen.y = ((winY - 0.0f) / float(ScreenSize.cy)) * 2.0f -1.0f; clickedPointOnSreen.z = 2.0f*winZ-1.0f; clickedPointOnSreen.w = 1.0f; glm::vec4 clickedPointOrigin = viewProjInv * clickedPointOnSreen; return glm::vec3(clickedPointOrigin.x / clickedPointOrigin.w,clickedPointOrigin.y / clickedPointOrigin.w,clickedPointOrigin.z / clickedPointOrigin.w); } MagicCamera& MagicCamera::MouseWheelMouvement(float xoffset,float yoffset)noexcept{ xoffset *= MouseSensitivity; yoffset *= MouseSensitivity; float a1 = xoffset * -1.0f; float a2 = yoffset * -1.0f; glm::vec3 pos = focus - transform.GetPosition(); float angle = glm::dot(glm::normalize(transform.GetFront()),glm::normalize(pos)); glm::vec3 between; if(type == CameraType::ORTHOGRAPHIC){ between = transform.GetPosition(); focus = glm::vec3(0.0f,0.0f,0.0f); }else{ if(angle < 0.90f){ if (angle < 0){ focus = glm::vec3(0.0f,0.0f,0.0f); } focus = transform.GetPosition() + (transform.GetFront()*10.0f); } between = transform.GetPosition() - focus; } glm::quat upRotation = Transform::GetQuaterion(a1,transform.GetWorldUp()); glm::quat rightRotation = Transform::GetQuaterion(a2, transform.GetRight()); between = glm::rotate(upRotation, between); between = glm::rotate(rightRotation, between); transform.SetPosition(focus + between); transform.Rotate(glm::inverse(upRotation * rightRotation)); return *this; } MagicCamera& MagicCamera::ProcessMouseScroll(float zdelta, float multiplier)noexcept{ //Must call DetermineRotationPoint before float xoffset = (lastPress.x - (float(ScreenSize.cx)/2.0f)) * 0.05f; float yoffset = (lastPress.y) * 0.05f * -1.0f; float Upoffset = (lastPress.y - (float(ScreenSize.cy)/2.0f)) * 0.05f; glm::vec3 scaling = (0.1f * (transform.GetPosition() - focus))* multiplier; if(zdelta == - 120){ if(!OnObject){ transform.SetPosition(transform.GetPosition() - ((transform.GetRight() * xoffset)* multiplier)); transform.SetPosition(transform.GetPosition() + ((transform.GetFront() * yoffset)* multiplier)); transform.SetPosition(transform.GetPosition() + ((transform.GetUp() * Upoffset)* multiplier)); }else{ transform.SetPosition(transform.GetPosition() + scaling); } }else{ if(!OnObject){ transform.SetPosition(transform.GetPosition() + ((transform.GetRight() * xoffset)* multiplier)); transform.SetPosition(transform.GetPosition() - ((transform.GetFront() * yoffset)* multiplier)); transform.SetPosition(transform.GetPosition() - ((transform.GetUp() * Upoffset)* multiplier)); }else{ float length = glm::length(GetTransform().GetPosition() - focus); if(length > 2.0f) transform.SetPosition(transform.GetPosition() - (scaling)); } } return *this; } MagicCamera& MagicCamera::ProcessMouseWheelTranslation(float xoffset,float yoffset){ yoffset *= 0.05f * -1.0f; xoffset *= 0.05f; float Absx = sqrt(pow(xoffset,2)); float Absy = sqrt(pow(yoffset,2)); if(Absx > Absy){ transform.Move(transform.GetRight() * xoffset); }else{ transform.Move(transform.GetUp() * yoffset); } return *this; } int MagicCamera::Pick(float x, float y,const Upp::Vector<Object3D>& allObjects)const noexcept{ int intersect = -1; double distance = 100000.0f; glm::vec3 start = UnProject2(x,y,0.0f); glm::vec3 end = UnProject2(x,y,1.0f); for (const Object3D& obj : allObjects){ if (obj.TestLineIntersection(start,end)){ double dis = glm::length(transform.GetPosition() - obj.GetTransform().GetPosition()); if( dis < distance){ distance = dis; intersect =obj.GetID(); } } } return intersect; } bool MagicCamera::PickFocus(float x, float y){ glm::vec3 start = UnProject2(x,y,0.0f); glm::vec3 end = UnProject2(x,y,1.0f); glm::vec3 focusMin = focus - 0.5f; glm::vec3 focusMax = focus + 0.5f; glm::vec3 center = (focusMin + focusMax) * 0.5f; glm::vec3 extents = focusMax - focus; glm::vec3 lineDir = 0.5f * (end - start); glm::vec3 lineCenter = start + lineDir; glm::vec3 dir = lineCenter - center; float ld0 = abs(lineDir.x); if (abs(dir.x) > (extents.x + ld0)) return false; float ld1 = abs(lineDir.y); if (abs(dir.y) > (extents.y + ld1)) return false; float ld2 = abs(lineDir.z); if (abs(dir.z) > (extents.z + ld2)) return false; glm::vec3 vCross = glm::cross(lineDir, dir); if (abs(vCross.x) > (extents.y * ld2 + extents.z * ld1)) return false; if (abs(vCross.y) > (extents.x * ld2 + extents.y * ld0)) return false; if (abs(vCross.z) > (extents.x * ld1 + extents.y * ld0)) return false; return true; } MagicCamera& MagicCamera::DetermineRotationPoint(Point& p,const Upp::Vector<Object3D>& allObjects, const Upp::Vector<int>& allSelecteds)noexcept{ if(allSelecteds.GetCount() == 0){ int obj = Pick(float(p.x),float(p.y),allObjects); if(obj != -1){ for(const Object3D& o : allObjects){ if(o.GetID() == obj){ focus = o.GetBoundingBoxTransformed().GetCenter(); OnObject = true; } } }else{ if(PickFocus(float(p.x),float(p.y))){ OnObject = true; }else{ OnObject = false; glm::vec3 pos = focus - transform.GetPosition(); float angle = glm::dot(glm::normalize(transform.GetFront()),glm::normalize(pos)); if(angle > 0.95f){ focus = glm::vec3(0.0f,0.0f,0.0f); } } } }else{ OnObject = true; } return *this; } MagicCamera& MagicCamera::LookAt(const glm::vec3& lookat)noexcept{ glm::vec3 direction = glm::normalize( lookat - transform.GetPosition()); if(!(glm::length(direction) > 0.0001)){ // Check if the direction is valid; Also deals with NaN transform.SetRotation(glm::quat(1, 0, 0, 0)); return *this; } //Check if We must use relative Up glm::vec3 upToUse = transform.GetWorldUp(); if(glm::abs(glm::dot(direction, transform.GetWorldUp())) > .9999f) upToUse = transform.GetUp(); //Check if parallel if(glm::vec3(0.0f) == glm::cross(transform.GetUp(),direction) ) direction = glm::normalize(lookat - (transform.GetPosition() + glm::vec3(0.001f,0.0f,0.001f))); //Change position and recalculate direction //Calcul new quaternion transform.SetRotation(glm::inverse(glm::quatLookAt(direction, upToUse))); return *this; } void MagicCamera::ViewFromAxe(bool AxeX, bool AxeY, bool AxeZ, bool Inverse)noexcept{ // Will set camera on axe selected axe float length = glm::length(transform.GetPosition() - focus); if(Inverse) length *= -1.0f; glm::vec3 pos = focus; if(AxeX){ pos.x += length; }if(AxeY){ pos.y += length; }if(AxeZ){ pos.z += length; } transform.SetPosition(pos); LookAt(focus); } }
35.715517
222
0.678132
8fba64c948f55005b98a0ad4969760169ec7934f
3,633
cpp
C++
src/common/mathematica_graphics_test.cpp
wkrzemien/j-pet-mlem
4ed746f3fe79890e4141158cd49d1869938105de
[ "Apache-2.0" ]
null
null
null
src/common/mathematica_graphics_test.cpp
wkrzemien/j-pet-mlem
4ed746f3fe79890e4141158cd49d1869938105de
[ "Apache-2.0" ]
5
2018-08-08T08:26:04.000Z
2020-05-13T13:33:39.000Z
src/common/mathematica_graphics_test.cpp
wkrzemien/j-pet-mlem
4ed746f3fe79890e4141158cd49d1869938105de
[ "Apache-2.0" ]
5
2018-06-04T21:04:29.000Z
2021-07-03T14:19:39.000Z
#include <sstream> #include "util/test.h" #include "mathematica_graphics.h" #include "2d/barrel/square_detector.h" #include "2d/barrel/scanner_builder.h" #include "2d/geometry/line_segment.h" #include "2d/geometry/pixel_grid.h" #include "2d/barrel/options.h" #include "common/types.h" using LOR = PET2D::Barrel::LOR<S>; using Detector = PET2D::Barrel::SquareDetector<F>; using Scanner = PET2D::Barrel::GenericScanner<Detector, S>; using ScannerBuilder = PET2D::Barrel::ScannerBuilder<Scanner>; using MathematicaGraphics = Common::MathematicaGraphics<F>; static Scanner make_barrel() { return ScannerBuilder::build_multiple_rings( { F(M_SQRT2), F(2) }, { F(0), F(0.5) }, { S(24), S(32) }, F(0.2), F(0.3)); } TEST("common/mathematica_graphics/detector") { std::stringstream out; Detector detector(0.007, 0.019, 0); { MathematicaGraphics graphics(out); graphics.add(detector); } REQUIRE(out.str() == "{\n" "{Polygon[{\n" " {0.00350000010803, 0.00949999969453},\n" " {0.00350000010803, -0.00949999969453},\n" " {-0.00350000010803, -0.00949999969453},\n" " {-0.00350000010803, 0.00949999969453}}]}}\n"); } #define TEST_LINE(out, line, text) \ std::getline(out, line); \ REQUIRE(line == text); TEST("common/mathematica_graphics/big_barrel") { std::stringstream out; auto scanner = make_barrel(); { MathematicaGraphics graphics(out); graphics.add(scanner); } std::string line; TEST_LINE(out, line, "{"); TEST_LINE(out, line, "{{Polygon[{"); TEST_LINE(out, line, " {1.71421349049, -0.100000075996},"); } TEST("common/mathematica_graphics/big_barrel/lor") { std::stringstream out; auto scanner = make_barrel(); { MathematicaGraphics graphics(out); graphics.add(scanner); graphics.add(scanner, LOR(10, 0)); } std::string line; TEST_LINE(out, line, "{"); TEST_LINE(out, line, "{{Polygon[{"); TEST_LINE(out, line, " {1.71421349049, -0.100000075996},"); } TEST("common/mathematica_graphics/big_barrel/segment") { std::stringstream out; auto scanner = make_barrel(); using Point = PET2D::Point<F>; { MathematicaGraphics graphics(out); graphics.add(scanner); PET2D::LineSegment<F> segment(Point(-0.400, 0), Point(0, 0.400)); graphics.add(segment); } std::string line; TEST_LINE(out, line, "{"); TEST_LINE(out, line, "{{Polygon[{"); TEST_LINE(out, line, " {1.71421349049, -0.100000075996},"); } TEST("common/mathematica_graphics/big_barrel/circle") { std::stringstream out; auto scanner = make_barrel(); { MathematicaGraphics graphics(out); graphics.add(scanner); graphics.add_circle(0.400); for (auto& d : scanner) { auto center = d.center(); graphics.add_circle(center, 0.015); } } std::string line; TEST_LINE(out, line, "{"); TEST_LINE(out, line, "{{Polygon[{"); TEST_LINE(out, line, " {1.71421349049, -0.100000075996},"); } TEST("common/mathematica_graphics/big_barrel/pixel") { std::stringstream out; auto scanner = make_barrel(); using Point = PET2D::Point<F>; { MathematicaGraphics graphics(out); graphics.add(scanner); const int n_columns = 20; const int n_rows = 20; PET2D::PixelGrid<F, S> grid(n_columns, n_rows, 0.01, Point(-0.1, -0.1)); for (int ix = 0; ix < n_columns; ++ix) { for (int iy = 0; iy < n_rows; ++iy) { graphics.add_pixel(grid, PET2D::Pixel<S>(ix, iy)); } } } std::string line; TEST_LINE(out, line, "{"); TEST_LINE(out, line, "{{Polygon[{"); TEST_LINE(out, line, " {1.71421349049, -0.100000075996},"); }
28.382813
80
0.646573
2631c73522cd8cea585b3cb74ac9e79fc190587e
8,309
cpp
C++
generator/Patch.cpp
jessicalemos/Solar-System
679b757b18bc5fe4d3c757de271b4639c8e1500d
[ "MIT" ]
null
null
null
generator/Patch.cpp
jessicalemos/Solar-System
679b757b18bc5fe4d3c757de271b4639c8e1500d
[ "MIT" ]
null
null
null
generator/Patch.cpp
jessicalemos/Solar-System
679b757b18bc5fe4d3c757de271b4639c8e1500d
[ "MIT" ]
null
null
null
#include "headers/Patch.h" Patch::Patch(){ } Patch::Patch(vector<Point> p){ controlPoints = p; } void Patch::multMatrixVector(float *m, float *v, float *res){ for (int j = 0; j < 4; ++j){ res[j] = 0; for (int k = 0; k < 4; ++k) res[j] += v[k] * m[j * 4 + k]; } } Patch::Patch(int tess, string filename){ tessellation = tess; parserPatchFile(filename); } void Patch::geradorModeloBezier(vector<Point> *vert, vector<Point> *normal, vector<float> *text) { for(int i=0; i < nPatchs; i++) getPatchPoints(i,vert,text,normal); } void Patch::parserPatchFile(string filename){ string line, x,y,z; string fileDir = "../../files/" + filename; ifstream file(fileDir); if (file.is_open()) { getline(file,line); nPatchs = stoi(line); //parsing dos indexes for(int i = 0; i < nPatchs; i++) { vector<int> patchIndex; if(getline(file,line)) { char* str = strdup(line.c_str()); char* token = strtok(str, " ,"); while (token != NULL) { patchIndex.push_back(atoi(token)); token = strtok(NULL, " ,"); } patchs[i] = patchIndex; free(str); } else cout << "Cannot get all patchIndex!" << endl; } getline(file,line); nPoints = stoi(line); //parsing das coordenadas dos pontos for(int i = 0; i < nPoints; i++) { if(getline(file,line)) { char* str = strdup(line.c_str()); char* token = strtok(str, " ,"); float x = atof(token); token = strtok(NULL, " ,"); float y = atof(token); token = strtok(NULL, " ,"); float z = atof(token); Point *p = new Point(x,y,z); controlPoints.push_back(*p); free(str); } else cout << "Cannot get all patchIndex!" << endl; } file.close(); } else cout << "Unable to open file: " << filename << "." << endl; } Point* Patch::getPoint(float ta, float tb, float coordenadasX[4][4], float coordenadasY[4][4], float coordenadasZ[4][4]){ float x = 0.0f, y = 0.0f, z = 0.0f; float a[4] = { ta*ta*ta, ta*ta, ta, 1.0f}; float b[4] = { tb*tb*tb, tb*tb, tb, 1.0f}; float am[4]; multMatrixVector(*m,a,am); float bm[4]; multMatrixVector(*m,b,bm); float amCoordenadaX[4], amCoordenadaY[4], amCoordenadaZ[4]; multMatrixVector(*coordenadasX,am,amCoordenadaX); multMatrixVector(*coordenadasY,am,amCoordenadaY); multMatrixVector(*coordenadasZ,am,amCoordenadaZ); // for (int i = 0; i < 4; i++) { x += amCoordenadaX[i] * bm[i]; y += amCoordenadaY[i] * bm[i]; z += amCoordenadaZ[i] * bm[i]; } Point *p = new Point(x,y,z); return p; } float* Patch::getTangent(float tu, float tv, float mX[4][4], float mY[4][4], float mZ[4][4], int type){ float u[4], v[4]; if(type == 0) { u[0] = 3.0f * tu * tu; u[1] = 2.0f * tu; u[2] = 1.0f; u[3] = 0.0f; v[0] = tv * tv * tv; v[1] = tv * tv; v[2] = tv; v[3] = 1.0f; } else { u[0] = tu * tu * tu; u[1] = tu * tu; u[2] = tu; u[3] = 1.0f; v[0] = 3.0f * tv * tv; v[1] = 2.0f * tv; v[2] = 1.0f; v[3] = 0.0f; } float uM[4]; multMatrixVector(*m,u,uM); float Mv[4]; multMatrixVector(*m,v,Mv); float matX[4], matY[4], matZ[4]; multMatrixVector(*mX,uM,matX); multMatrixVector(*mY,uM,matY); multMatrixVector(*mZ,uM,matZ); float *tang = (float *) calloc(3, sizeof(float)); for (int i = 0; i < 4; i++) { tang[0] += matX[i] * Mv[i]; tang[1] += matY[i] * Mv[i]; tang[2] += matZ[i] * Mv[i]; } return tang; } //normalizar vetor void Patch::normalize(float *a) { float n = sqrt(a[0]*a[0] + a[1] * a[1] + a[2] * a[2]); a[0] = a[0]/n; a[1] = a[1]/n; a[2] = a[2]/n; } void Patch::cross(float *a, float *b, float *res) { res[0] = a[1]*b[2] - a[2]*b[1]; res[1] = a[2]*b[0] - a[0]*b[2]; res[2] = a[0]*b[1] - a[1]*b[0]; } void Patch::getPatchPoints(int patch, vector<Point>* points, vector<float>* textureList, vector<Point>* normalList){ vector<int> indexesControlPoints = patchs.at(patch); float coordenadasX[4][4], coordenadasY[4][4], coordenadasZ[4][4]; float u,v,uu,vv; float t = 1.0f /tessellation; int pos = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { Point controlPoint = controlPoints[indexesControlPoints[pos]]; coordenadasX[i][j] = controlPoint.getX(); coordenadasY[i][j] = controlPoint.getY(); coordenadasZ[i][j] = controlPoint.getZ(); pos++; } } for(int i = 0; i < tessellation; i++) { for (int j = 0; j < tessellation; j++) { u = i*t; v = j*t; uu = (i+1)*t; vv = (j+1)*t; Point *p0,*p1,*p2,*p3; Point *n0,*n1,*n2,*n3; float *tangenteU,*tangenteV,res[3]; p0 = getPoint(u, v, coordenadasX, coordenadasY, coordenadasZ); tangenteU = getTangent(u,v,coordenadasX,coordenadasY,coordenadasZ,0); tangenteV = getTangent(u,v,coordenadasX,coordenadasY,coordenadasZ,1); cross(tangenteU,tangenteV,res); normalize(res); n0 = new Point(res[0],res[1],res[2]); p1 = getPoint(u, vv, coordenadasX, coordenadasY, coordenadasZ); tangenteU = getTangent(u,vv,coordenadasX,coordenadasY,coordenadasZ,0); tangenteV = getTangent(u,vv,coordenadasX,coordenadasY,coordenadasZ,1); cross(tangenteU,tangenteV,res); normalize(res); n1 = new Point(res[0],res[1],res[2]); p2 = getPoint(uu, v, coordenadasX, coordenadasY, coordenadasZ); tangenteU = getTangent(uu,v,coordenadasX,coordenadasY,coordenadasZ,0); tangenteV = getTangent(uu,v,coordenadasX,coordenadasY,coordenadasZ,1); cross(tangenteU,tangenteV,res); normalize(res); n2 = new Point(res[0],res[1],res[2]); p3 = getPoint(uu, vv, coordenadasX, coordenadasY, coordenadasZ); tangenteU = getTangent(uu,vv,coordenadasX,coordenadasY,coordenadasZ,0); tangenteV = getTangent(uu,vv,coordenadasX,coordenadasY,coordenadasZ,1); cross(tangenteU,tangenteV,res); normalize(res); n3 = new Point(res[0],res[1],res[2]); points->push_back(*p0); points->push_back(*p2); points->push_back(*p1); points->push_back(*p1); points->push_back(*p2); points->push_back(*p3); normalList->push_back(*n0); normalList->push_back(*n2); normalList->push_back(*n1); normalList->push_back(*n1); normalList->push_back(*n2); normalList->push_back(*n3); textureList->push_back(1-u); textureList->push_back(1-v); textureList->push_back(1-uu); textureList->push_back(1-v); textureList->push_back(1-u); textureList->push_back(1-vv); textureList->push_back(1-u); textureList->push_back(1-vv); textureList->push_back(1-uu); textureList->push_back(1-v); textureList->push_back(1-uu); textureList->push_back(1-vv); } } }
32.081081
121
0.479841
26336d63dd840996ce7ce02b9a6a9e6f278e4d1a
63,888
cpp
C++
src/lib/foundations/globals/numerics.cpp
abetten/orbiter
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
[ "RSA-MD" ]
15
2016-10-27T15:18:28.000Z
2022-02-09T11:13:07.000Z
src/lib/foundations/globals/numerics.cpp
abetten/orbiter
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
[ "RSA-MD" ]
4
2019-12-09T11:49:11.000Z
2020-07-30T17:34:45.000Z
src/lib/foundations/globals/numerics.cpp
abetten/orbiter
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
[ "RSA-MD" ]
15
2016-06-10T20:05:30.000Z
2020-12-18T04:59:19.000Z
// numerics.cpp // // Anton Betten // // started: February 11, 2018 #include "foundations.h" using namespace std; #define EPSILON 0.01 namespace orbiter { namespace foundations { numerics::numerics() { } numerics::~numerics() { } void numerics::vec_print(double *a, int len) { int i; cout << "("; for (i = 0; i < len; i++) { cout << a[i]; if (i < len - 1) { cout << ", "; } } cout << ")"; } void numerics::vec_linear_combination1(double c1, double *v1, double *w, int len) { int i; for (i = 0; i < len; i++) { w[i] = c1 * v1[i]; } } void numerics::vec_linear_combination(double c1, double *v1, double c2, double *v2, double *v3, int len) { int i; for (i = 0; i < len; i++) { v3[i] = c1 * v1[i] + c2 * v2[i]; } } void numerics::vec_linear_combination3( double c1, double *v1, double c2, double *v2, double c3, double *v3, double *w, int len) { int i; for (i = 0; i < len; i++) { w[i] = c1 * v1[i] + c2 * v2[i] + c3 * v3[i]; } } void numerics::vec_add(double *a, double *b, double *c, int len) { int i; for (i = 0; i < len; i++) { c[i] = a[i] + b[i]; } } void numerics::vec_subtract(double *a, double *b, double *c, int len) { int i; for (i = 0; i < len; i++) { c[i] = a[i] - b[i]; } } void numerics::vec_scalar_multiple(double *a, double lambda, int len) { int i; for (i = 0; i < len; i++) { a[i] *= lambda; } } int numerics::Gauss_elimination(double *A, int m, int n, int *base_cols, int f_complete, int verbose_level) { int f_v = (verbose_level >= 1); int f_vv = (verbose_level >= 2); int i, j, k, jj, rank; double a, b, c, f, z; double pivot, pivot_inv; if (f_v) { cout << "Gauss_elimination" << endl; } if (f_vv) { print_system(A, m, n); } i = 0; for (j = 0; j < n; j++) { if (f_vv) { cout << "j=" << j << endl; } /* search for pivot element: */ for (k = i; k < m; k++) { if (ABS(A[k * n + j]) > EPSILON) { if (f_vv) { cout << "i=" << i << " pivot found in " << k << "," << j << endl; } // pivot element found: if (k != i) { for (jj = j; jj < n; jj++) { a = A[i * n + jj]; A[i * n + jj] = A[k * n + jj]; A[k * n + jj] = a; } } break; } // if != 0 } // next k if (k == m) { // no pivot found if (f_vv) { cout << "no pivot found" << endl; } continue; // increase j, leave i constant } if (f_vv) { cout << "row " << i << " pivot in row " << k << " colum " << j << endl; } base_cols[i] = j; //if (FALSE) { // cout << "."; cout.flush(); // } pivot = A[i * n + j]; if (f_vv) { cout << "pivot=" << pivot << endl; } pivot_inv = 1. / pivot; if (f_vv) { cout << "pivot=" << pivot << " pivot_inv=" << pivot_inv << endl; } // make pivot to 1: for (jj = j; jj < n; jj++) { A[i * n + jj] *= pivot_inv; } if (f_vv) { cout << "pivot=" << pivot << " pivot_inv=" << pivot_inv << " made to one: " << A[i * n + j] << endl; } // do the gaussian elimination: if (f_vv) { cout << "doing elimination in column " << j << " from row " << i + 1 << " to row " << m - 1 << ":" << endl; } for (k = i + 1; k < m; k++) { if (f_vv) { cout << "k=" << k << endl; } z = A[k * n + j]; if (ABS(z) < 0.00000001) { continue; } f = z; f = -1. * f; A[k * n + j] = 0; if (f_vv) { cout << "eliminating row " << k << endl; } for (jj = j + 1; jj < n; jj++) { a = A[i * n + jj]; b = A[k * n + jj]; // c := b + f * a // = b - z * a if !f_special // b - z * pivot_inv * a if f_special c = f * a; c += b; A[k * n + jj] = c; if (f_vv) { cout << A[k * n + jj] << " "; } } if (f_vv) { print_system(A, m, n); } } i++; } // next j rank = i; if (f_vv) { print_system(A, m, n); } if (f_complete) { if (f_v) { cout << "completing" << endl; } //if (FALSE) { // cout << ";"; cout.flush(); // } for (i = rank - 1; i >= 0; i--) { j = base_cols[i]; a = A[i * n + j]; // do the gaussian elimination in the upper part: for (k = i - 1; k >= 0; k--) { z = A[k * n + j]; if (z == 0) { continue; } A[k * n + j] = 0; for (jj = j + 1; jj < n; jj++) { a = A[i * n + jj]; b = A[k * n + jj]; c = z * a; c = -1. * c; c += b; A[k * n + jj] = c; } } // next k if (f_vv) { print_system(A, m, n); } } // next i } return rank; } void numerics::print_system(double *A, int m, int n) { int i, j; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { cout << A[i * n + j] << "\t"; } cout << endl; } } void numerics::get_kernel(double *M, int m, int n, int *base_cols, int nb_base_cols, int &kernel_m, int &kernel_n, double *kernel) // kernel must point to the appropriate amount of memory! // (at least n * (n - nb_base_cols) doubles) // m is not used! { int r, k, i, j, ii, iii, a, b; int *kcol; double m_one; if (kernel == NULL) { cout << "get_kernel kernel == NULL" << endl; exit(1); } m_one = -1.; r = nb_base_cols; k = n - r; kernel_m = n; kernel_n = k; kcol = NEW_int(k); ii = 0; j = 0; if (j < r) { b = base_cols[j]; } else { b = -1; } for (i = 0; i < n; i++) { if (i == b) { j++; if (j < r) { b = base_cols[j]; } else { b = -1; } } else { kcol[ii] = i; ii++; } } if (ii != k) { cout << "get_kernel ii != k" << endl; exit(1); } //cout << "kcol = " << kcol << endl; ii = 0; j = 0; if (j < r) { b = base_cols[j]; } else { b = -1; } for (i = 0; i < n; i++) { if (i == b) { for (iii = 0; iii < k; iii++) { a = kcol[iii]; kernel[i * kernel_n + iii] = M[j * n + a]; } j++; if (j < r) { b = base_cols[j]; } else { b = -1; } } else { for (iii = 0; iii < k; iii++) { if (iii == ii) { kernel[i * kernel_n + iii] = m_one; } else { kernel[i * kernel_n + iii] = 0.; } } ii++; } } FREE_int(kcol); } int numerics::Null_space(double *M, int m, int n, double *K, int verbose_level) // K will be k x n // where k is the return value. { int f_v = (verbose_level >= 1); int *base_cols; int rk, i, j; int kernel_m, kernel_n; double *Ker; if (f_v) { cout << "Null_space" << endl; } Ker = new double [n * n]; base_cols = NEW_int(n); rk = Gauss_elimination(M, m, n, base_cols, TRUE /* f_complete */, 0 /* verbose_level */); get_kernel(M, m, n, base_cols, rk /* nb_base_cols */, kernel_m, kernel_n, Ker); if (kernel_m != n) { cout << "kernel_m != n" << endl; exit(1); } for (i = 0; i < kernel_n; i++) { for (j = 0; j < kernel_m; j++) { K[i * n + j] = Ker[j * kernel_n + i]; } } FREE_int(base_cols); delete [] Ker; if (f_v) { cout << "Null_space done" << endl; } return kernel_n; } void numerics::vec_normalize_from_back(double *v, int len) { int i, j; double av; for (i = len - 1; i >= 0; i--) { if (ABS(v[i]) > 0.01) { break; } } if (i < 0) { cout << "numerics::vec_normalize_from_back i < 0" << endl; exit(1); } av = 1. / v[i]; for (j = 0; j <= i; j++) { v[j] = v[j] * av; } } void numerics::vec_normalize_to_minus_one_from_back(double *v, int len) { int i, j; double av; for (i = len - 1; i >= 0; i--) { if (ABS(v[i]) > 0.01) { break; } } if (i < 0) { cout << "numerics::vec_normalize_to_minus_one_from_back i < 0" << endl; exit(1); } av = -1. / v[i]; for (j = 0; j <= i; j++) { v[j] = v[j] * av; } } #define EPS 0.001 int numerics::triangular_prism(double *P1, double *P2, double *P3, double *abc3, double *angles3, double *T3, int verbose_level) { int f_v = (verbose_level >= 1); int f_vv = (verbose_level >= 2); int i; double P4[3]; double P5[3]; double P6[3]; double P7[3]; double P8[3]; double P9[3]; double T[3]; // translation vector double phi; double Rz[9]; double psi; double Ry[9]; double chi; double Rx[9]; if (f_v) { cout << "numerics::triangular_prism" << endl; } if (f_vv) { cout << "P1="; vec_print(cout, P1, 3); cout << endl; cout << "P2="; vec_print(cout, P2, 3); cout << endl; cout << "P3="; vec_print(cout, P3, 3); cout << endl; } vec_copy(P1, T, 3); for (i = 0; i < 3; i++) { P2[i] -= T[i]; } for (i = 0; i < 3; i++) { P3[i] -= T[i]; } if (f_vv) { cout << "after translation:" << endl; cout << "P2="; vec_print(cout, P2, 3); cout << endl; cout << "P3="; vec_print(cout, P3, 3); cout << endl; } if (f_vv) { cout << "next, we make the y-coordinate of the first point " "disappear by turning around the z-axis:" << endl; } phi = atan_xy(P2[0], P2[1]); // (x, y) if (f_vv) { cout << "phi=" << rad2deg(phi) << endl; } make_Rz(Rz, -1 * phi); if (f_vv) { cout << "Rz=" << endl; print_matrix(Rz); } mult_matrix(P2, Rz, P4); mult_matrix(P3, Rz, P5); if (f_vv) { cout << "after rotation Rz by an angle of -1 * " << rad2deg(phi) << ":" << endl; cout << "P4="; vec_print(cout, P4, 3); cout << endl; cout << "P5="; vec_print(cout, P5, 3); cout << endl; } if (ABS(P4[1]) > EPS) { cout << "something is wrong in step 1, " "the y-coordinate is too big" << endl; return FALSE; } if (f_vv) { cout << "next, we make the z-coordinate of the " "first point disappear by turning around the y-axis:" << endl; } psi = atan_xy(P4[0], P4[2]); // (x,z) if (f_vv) { cout << "psi=" << rad2deg(psi) << endl; } make_Ry(Ry, psi); if (f_vv) { cout << "Ry=" << endl; print_matrix(Ry); } mult_matrix(P4, Ry, P6); mult_matrix(P5, Ry, P7); if (f_vv) { cout << "after rotation Ry by an angle of " << rad2deg(psi) << ":" << endl; cout << "P6="; vec_print(cout, P6, 3); cout << endl; cout << "P7="; vec_print(cout, P7, 3); cout << endl; } if (ABS(P6[2]) > EPS) { cout << "something is wrong in step 2, " "the z-coordinate is too big" << endl; return FALSE; } if (f_vv) { cout << "next, we move the plane determined by the second " "point into the xz plane by turning around the x-axis:" << endl; } chi = atan_xy(P7[2], P7[1]); // (z,y) if (f_vv) { cout << "chi=" << rad2deg(chi) << endl; } make_Rx(Rx, chi); if (f_vv) { cout << "Rx=" << endl; print_matrix(Rx); } mult_matrix(P6, Rx, P8); mult_matrix(P7, Rx, P9); if (f_vv) { cout << "after rotation Rx by an angle of " << rad2deg(chi) << ":" << endl; cout << "P8="; vec_print(cout, P8, 3); cout << endl; cout << "P9="; vec_print(cout, P9, 3); cout << endl; } if (ABS(P9[1]) > EPS) { cout << "something is wrong in step 3, " "the y-coordinate is too big" << endl; return FALSE; } for (i = 0; i < 3; i++) { T3[i] = T[i]; } angles3[0] = -chi; angles3[1] = -psi; angles3[2] = phi; abc3[0] = P8[0]; abc3[1] = P9[0]; abc3[2] = P9[2]; if (f_v) { cout << "numerics::triangular_prism done" << endl; } return TRUE; } int numerics::general_prism(double *Pts, int nb_pts, double *Pts_xy, double *abc3, double *angles3, double *T3, int verbose_level) { int f_v = (verbose_level >= 1); int f_vv = (verbose_level >= 2); int i, h; double *Moved_pts1; double *Moved_pts2; double *Moved_pts3; double *Moved_pts4; double *P1, *P2, *P3; double P4[3]; double P5[3]; double P6[3]; double P7[3]; double P8[3]; double P9[3]; double T[3]; // translation vector double phi; double Rz[9]; double psi; double Ry[9]; double chi; double Rx[9]; if (f_v) { cout << "general_prism" << endl; } P1 = Pts; P2 = Pts + 3; P3 = Pts + 6; Moved_pts1 = new double[nb_pts * 3]; Moved_pts2 = new double[nb_pts * 3]; Moved_pts3 = new double[nb_pts * 3]; Moved_pts4 = new double[nb_pts * 3]; if (f_vv) { cout << "P1="; vec_print(cout, P1, 3); cout << endl; cout << "P2="; vec_print(cout, P2, 3); cout << endl; cout << "P3="; vec_print(cout, P3, 3); cout << endl; } vec_copy(P1, T, 3); for (h = 0; h < nb_pts; h++) { for (i = 0; i < 3; i++) { Moved_pts1[h * 3 + i] = Pts[h * 3 + i] - T[i]; } } // this must come after: for (i = 0; i < 3; i++) { P2[i] -= T[i]; } for (i = 0; i < 3; i++) { P3[i] -= T[i]; } if (f_vv) { cout << "after translation:" << endl; cout << "P2="; vec_print(cout, P2, 3); cout << endl; cout << "P3="; vec_print(cout, P3, 3); cout << endl; } if (f_vv) { cout << "next, we make the y-coordinate of the first point " "disappear by turning around the z-axis:" << endl; } phi = atan_xy(P2[0], P2[1]); // (x, y) if (f_vv) { cout << "phi=" << rad2deg(phi) << endl; } make_Rz(Rz, -1 * phi); if (f_vv) { cout << "Rz=" << endl; print_matrix(Rz); } mult_matrix(P2, Rz, P4); mult_matrix(P3, Rz, P5); for (h = 0; h < nb_pts; h++) { mult_matrix(Moved_pts1 + h * 3, Rz, Moved_pts2 + h * 3); } if (f_vv) { cout << "after rotation Rz by an angle of -1 * " << rad2deg(phi) << ":" << endl; cout << "P4="; vec_print(cout, P4, 3); cout << endl; cout << "P5="; vec_print(cout, P5, 3); cout << endl; } if (ABS(P4[1]) > EPS) { cout << "something is wrong in step 1, the y-coordinate " "is too big" << endl; return FALSE; } if (f_vv) { cout << "next, we make the z-coordinate of the first " "point disappear by turning around the y-axis:" << endl; } psi = atan_xy(P4[0], P4[2]); // (x,z) if (f_vv) { cout << "psi=" << rad2deg(psi) << endl; } make_Ry(Ry, psi); if (f_vv) { cout << "Ry=" << endl; print_matrix(Ry); } mult_matrix(P4, Ry, P6); mult_matrix(P5, Ry, P7); for (h = 0; h < nb_pts; h++) { mult_matrix(Moved_pts2 + h * 3, Ry, Moved_pts3 + h * 3); } if (f_vv) { cout << "after rotation Ry by an angle of " << rad2deg(psi) << ":" << endl; cout << "P6="; vec_print(cout, P6, 3); cout << endl; cout << "P7="; vec_print(cout, P7, 3); cout << endl; } if (ABS(P6[2]) > EPS) { cout << "something is wrong in step 2, the z-coordinate " "is too big" << endl; return FALSE; } if (f_vv) { cout << "next, we move the plane determined by the second " "point into the xz plane by turning around the x-axis:" << endl; } chi = atan_xy(P7[2], P7[1]); // (z,y) if (f_vv) { cout << "chi=" << rad2deg(chi) << endl; } make_Rx(Rx, chi); if (f_vv) { cout << "Rx=" << endl; print_matrix(Rx); } mult_matrix(P6, Rx, P8); mult_matrix(P7, Rx, P9); for (h = 0; h < nb_pts; h++) { mult_matrix(Moved_pts3 + h * 3, Rx, Moved_pts4 + h * 3); } if (f_vv) { cout << "after rotation Rx by an angle of " << rad2deg(chi) << ":" << endl; cout << "P8="; vec_print(cout, P8, 3); cout << endl; cout << "P9="; vec_print(cout, P9, 3); cout << endl; } if (ABS(P9[1]) > EPS) { cout << "something is wrong in step 3, the y-coordinate " "is too big" << endl; return FALSE; } for (i = 0; i < 3; i++) { T3[i] = T[i]; } angles3[0] = -chi; angles3[1] = -psi; angles3[2] = phi; abc3[0] = P8[0]; abc3[1] = P9[0]; abc3[2] = P9[2]; for (h = 0; h < nb_pts; h++) { Pts_xy[2 * h + 0] = Moved_pts4[h * 3 + 0]; Pts_xy[2 * h + 1] = Moved_pts4[h * 3 + 2]; } delete [] Moved_pts1; delete [] Moved_pts2; delete [] Moved_pts3; delete [] Moved_pts4; if (f_v) { cout << "numerics::general_prism done" << endl; } return TRUE; } void numerics::mult_matrix(double *v, double *R, double *vR) { int i, j; double c; for (j = 0; j < 3; j++) { c = 0; for (i = 0; i < 3; i++) { c += v[i] * R[i * 3 + j]; } vR[j] = c; } } void numerics::mult_matrix_matrix( double *A, double *B, double *C, int m, int n, int o) // A is m x n, B is n x o, C is m x o { int i, j, h; double c; for (i = 0; i < m; i++) { for (j = 0; j < o; j++) { c = 0; for (h = 0; h < n; h++) { c += A[i * n + h] * B[h * o + j]; } C[i * o + j] = c; } } } void numerics::print_matrix(double *R) { int i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { cout << R[i * 3 + j] << " "; } cout << endl; } } void numerics::make_Rz(double *R, double phi) { double c, s; int i; c = cos(phi); s = sin(phi); for (i = 0; i < 9; i++) { R[i] = 0.; } R[2 * 3 + 2] = 1.; R[0 * 3 + 0] = c; R[0 * 3 + 1] = s; R[1 * 3 + 0] = -1. * s; R[1 * 3 + 1] = c; } void numerics::make_Ry(double *R, double psi) { double c, s; int i; c = cos(psi); s = sin(psi); for (i = 0; i < 9; i++) { R[i] = 0.; } R[1 * 3 + 1] = 1; R[0 * 3 + 0] = c; R[0 * 3 + 2] = -1 * s; R[2 * 3 + 0] = s; R[2 * 3 + 2] = c; } void numerics::make_Rx(double *R, double chi) { double c, s; int i; c = cos(chi); s = sin(chi); for (i = 0; i < 9; i++) { R[i] = 0.; } R[0 * 3 + 0] = 1; R[1 * 3 + 1] = c; R[1 * 3 + 2] = s; R[2 * 3 + 1] = -1 * s; R[2 * 3 + 2] = c; } double numerics::atan_xy(double x, double y) { double phi; //cout << "atan x=" << x << " y=" << y << endl; if (ABS(x) < 0.00001) { if (y > 0) { phi = M_PI * 0.5; } else { phi = M_PI * -0.5; } } else { if (x < 0) { x = -x; y = -y; phi = atan(y / x) + M_PI; } else { phi = atan(y / x); } } //cout << "angle = " << rad2deg(phi) << " degrees" << endl; return phi; } double numerics::dot_product(double *u, double *v, int len) { double d; int i; d = 0; for (i = 0; i < len; i++) { d += u[i] * v[i]; } return d; } void numerics::cross_product(double *u, double *v, double *n) { n[0] = u[1] * v[2] - v[1] * u[2]; n[1] = u[2] * v[0] - u[0] * v[2]; n[2] = u[0] * v[1] - u[1] * v[0]; } double numerics::distance_euclidean(double *x, double *y, int len) { double d, a; int i; d = 0; for (i = 0; i < len; i++) { a = y[i] - x[i]; d += a * a; } d = sqrt(d); return d; } double numerics::distance_from_origin(double x1, double x2, double x3) { double d; d = sqrt(x1 * x1 + x2 * x2 + x3 * x3); return d; } double numerics::distance_from_origin(double *x, int len) { double d; int i; d = 0; for (i = 0; i < len; i++) { d += x[i] * x[i]; } d = sqrt(d); return d; } void numerics::make_unit_vector(double *v, int len) { double d, dv; d = distance_from_origin(v, len); if (ABS(d) < 0.00001) { cout << "make_unit_vector ABS(d) < 0.00001" << endl; exit(1); } dv = 1. / d; vec_scalar_multiple(v, dv, len); } void numerics::center_of_mass(double *Pts, int len, int *Pt_idx, int nb_pts, double *c) { int i, h, idx; double a; for (i = 0; i < len; i++) { c[i] = 0.; } for (h = 0; h < nb_pts; h++) { idx = Pt_idx[h]; for (i = 0; i < len; i++) { c[i] += Pts[idx * len + i]; } } a = 1. / nb_pts; vec_scalar_multiple(c, a, len); } void numerics::plane_through_three_points( double *p1, double *p2, double *p3, double *n, double &d) { int i; double a, b; double u[3]; double v[3]; vec_subtract(p2, p1, u, 3); // u = p2 - p1 vec_subtract(p3, p1, v, 3); // v = p3 - p1 #if 0 cout << "u=" << endl; print_system(u, 1, 3); cout << endl; cout << "v=" << endl; print_system(v, 1, 3); cout << endl; #endif cross_product(u, v, n); #if 0 cout << "n=" << endl; print_system(n, 1, 3); cout << endl; #endif a = distance_from_origin(n[0], n[1], n[2]); if (ABS(a) < 0.00001) { cout << "plane_through_three_points ABS(a) < 0.00001" << endl; exit(1); } b = 1. / a; for (i = 0; i < 3; i++) { n[i] *= b; } #if 0 cout << "n unit=" << endl; print_system(n, 1, 3); cout << endl; #endif d = dot_product(p1, n, 3); } void numerics::orthogonal_transformation_from_point_to_basis_vector( double *from, double *A, double *Av, int verbose_level) { int f_v = (verbose_level >= 1); int i, i0, i1, j; double d, a; if (f_v) { cout << "numerics::orthogonal_transformation_from_point_" "to_basis_vector" << endl; } vec_copy(from, Av, 3); a = 0.; i0 = -1; for (i = 0; i < 3; i++) { if (ABS(Av[i]) > a) { i0 = i; a = ABS(Av[i]); } } if (i0 == -1) { cout << "i0 == -1" << endl; exit(1); } if (i0 == 0) { i1 = 1; } else if (i0 == 1) { i1 = 2; } else { i1 = 0; } for (i = 0; i < 3; i++) { Av[3 + i] = 0.; } Av[3 + i1] = -Av[i0]; Av[3 + i0] = Av[i1]; // now the dot product of the first row and // the secon row is zero. d = dot_product(Av, Av + 3, 3); if (ABS(d) > 0.01) { cout << "dot product between first and second " "row of Av is not zero" << endl; exit(1); } cross_product(Av, Av + 3, Av + 6); d = dot_product(Av, Av + 6, 3); if (ABS(d) > 0.01) { cout << "dot product between first and third " "row of Av is not zero" << endl; exit(1); } d = dot_product(Av + 3, Av + 6, 3); if (ABS(d) > 0.01) { cout << "dot product between second and third " "row of Av is not zero" << endl; exit(1); } make_unit_vector(Av, 3); make_unit_vector(Av + 3, 3); make_unit_vector(Av + 6, 3); // make A the transpose of Av. // for orthonormal matrices, the inverse is the transpose. for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { A[j * 3 + i] = Av[i * 3 + j]; } } if (f_v) { cout << "numerics::orthogonal_transformation_from_point_" "to_basis_vector done" << endl; } } void numerics::output_double(double a, ostream &ost) { if (ABS(a) < 0.0001) { ost << 0; } else { ost << a; } } void numerics::mult_matrix_4x4(double *v, double *R, double *vR) { int i, j; double c; for (j = 0; j < 4; j++) { c = 0; for (i = 0; i < 4; i++) { c += v[i] * R[i * 4 + j]; } vR[j] = c; } } void numerics::transpose_matrix_4x4(double *A, double *At) { int i, j; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { At[i * 4 + j] = A[j * 4 + i]; } } } void numerics::transpose_matrix_nxn(double *A, double *At, int n) { int i, j; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { At[i * n + j] = A[j * n + i]; } } } void numerics::substitute_quadric_linear( double *coeff_in, double *coeff_out, double *A4_inv, int verbose_level) // uses povray ordering of monomials // 1: x^2 // 2: xy // 3: xz // 4: x // 5: y^2 // 6: yz // 7: y // 8: z^2 // 9: z // 10: 1 { int f_v = (verbose_level >= 1); int Variables[] = { 0,0, 0,1, 0,2, 0,3, 1,1, 1,2, 1,3, 2,2, 2,3, 3,3 }; int Affine_to_monomial[16]; int *V; int nb_monomials = 10; int degree = 2; int n = 4; double coeff2[10]; double coeff3[10]; double b, c; int h, i, j, a, nb_affine, idx; int A[2]; int v[4]; number_theory_domain NT; geometry_global Gg; if (f_v) { cout << "substitute_quadric_linear" << endl; } nb_affine = NT.i_power_j(n, degree); for (i = 0; i < nb_affine; i++) { Gg.AG_element_unrank(n /* q */, A, 1, degree, i); Orbiter->Int_vec.zero(v, n); for (j = 0; j < degree; j++) { a = A[j]; v[a]++; } for (idx = 0; idx < 10; idx++) { if (int_vec_compare(v, Variables + idx * 2, 2) == 0) { break; } } if (idx == 10) { cout << "could not determine Affine_to_monomial" << endl; exit(1); } Affine_to_monomial[i] = idx; } for (i = 0; i < nb_monomials; i++) { coeff3[i] = 0.; } for (h = 0; h < nb_monomials; h++) { c = coeff_in[h]; if (c == 0) { continue; } V = Variables + h * degree; // a list of the indices of the variables // which appear in the monomial // (possibly with repeats) // Example: the monomial x_0^3 becomes 0,0,0 for (i = 0; i < nb_monomials; i++) { coeff2[i] = 0.; } for (a = 0; a < nb_affine; a++) { Gg.AG_element_unrank(n /* q */, A, 1, degree, a); // sequence of length degree // over the alphabet 0,...,n-1. b = 1.; for (j = 0; j < degree; j++) { //factors[j] = Mtx_inv[V[j] * n + A[j]]; b *= A4_inv[A[j] * n + V[j]]; } idx = Affine_to_monomial[a]; coeff2[idx] += b; } for (j = 0; j < nb_monomials; j++) { coeff2[j] *= c; } for (j = 0; j < nb_monomials; j++) { coeff3[j] += coeff2[j]; } } for (j = 0; j < nb_monomials; j++) { coeff_out[j] = coeff3[j]; } if (f_v) { cout << "substitute_quadric_linear done" << endl; } } void numerics::substitute_cubic_linear_using_povray_ordering( double *coeff_in, double *coeff_out, double *A4_inv, int verbose_level) // uses povray ordering of monomials // http://www.povray.org/documentation/view/3.6.1/298/ // 1: x^3 // 2: x^2y // 3: x^2z // 4: x^2 // 5: xy^2 // 6: xyz // 7: xy // 8: xz^2 // 9: xz // 10: x // 11: y^3 // 12: y^2z // 13: y^2 // 14: yz^2 // 15: yz // 16: y // 17: z^3 // 18: z^2 // 19: z // 20: 1 { int f_v = (verbose_level >= 1); int Variables[] = { 0,0,0, 0,0,1, 0,0,2, 0,0,3, 0,1,1, 0,1,2, 0,1,3, 0,2,2, 0,2,3, 0,3,3, 1,1,1, 1,1,2, 1,1,3, 1,2,2, 1,2,3, 1,3,3, 2,2,2, 2,2,3, 2,3,3, 3,3,3, }; int *Monomials; int Affine_to_monomial[64]; // n^degree int *V; int nb_monomials = 20; int degree = 3; int n = 4; // number of variables double coeff2[20]; double coeff3[20]; double b, c; int h, i, j, a, nb_affine, idx; int A[3]; int v[4]; number_theory_domain NT; geometry_global Gg; if (f_v) { cout << "numerics::substitute_cubic_linear_using_povray_ordering" << endl; } nb_affine = NT.i_power_j(n, degree); if (FALSE) { cout << "Variables:" << endl; Orbiter->Int_vec.matrix_print(Variables, 20, 3); } Monomials = NEW_int(nb_monomials * n); Orbiter->Int_vec.zero(Monomials, nb_monomials * n); for (i = 0; i < nb_monomials; i++) { for (j = 0; j < degree; j++) { a = Variables[i * degree + j]; Monomials[i * n + a]++; } } if (FALSE) { cout << "Monomials:" << endl; Orbiter->Int_vec.matrix_print(Monomials, nb_monomials, n); } for (i = 0; i < nb_affine; i++) { Gg.AG_element_unrank(n /* q */, A, 1, degree, i); Orbiter->Int_vec.zero(v, n); for (j = 0; j < degree; j++) { a = A[j]; v[a]++; } for (idx = 0; idx < nb_monomials; idx++) { if (int_vec_compare(v, Monomials + idx * n, n) == 0) { break; } } if (idx == nb_monomials) { cout << "could not determine Affine_to_monomial" << endl; cout << "Monomials:" << endl; Orbiter->Int_vec.matrix_print(Monomials, nb_monomials, n); cout << "v="; Orbiter->Int_vec.print(cout, v, n); exit(1); } Affine_to_monomial[i] = idx; } if (FALSE) { cout << "Affine_to_monomial:"; Orbiter->Int_vec.print(cout, Affine_to_monomial, nb_affine); cout << endl; } for (i = 0; i < nb_monomials; i++) { coeff3[i] = 0.; } for (h = 0; h < nb_monomials; h++) { c = coeff_in[h]; if (c == 0) { continue; } V = Variables + h * degree; // a list of the indices of the variables // which appear in the monomial // (possibly with repeats) // Example: the monomial x_0^3 becomes 0,0,0 for (i = 0; i < nb_monomials; i++) { coeff2[i] = 0.; } for (a = 0; a < nb_affine; a++) { Gg.AG_element_unrank(n /* q */, A, 1, degree, a); // sequence of length degree // over the alphabet 0,...,n-1. b = 1.; for (j = 0; j < degree; j++) { //factors[j] = Mtx_inv[V[j] * n + A[j]]; b *= A4_inv[A[j] * n + V[j]]; } idx = Affine_to_monomial[a]; coeff2[idx] += b; } for (j = 0; j < nb_monomials; j++) { coeff2[j] *= c; } for (j = 0; j < nb_monomials; j++) { coeff3[j] += coeff2[j]; } } for (j = 0; j < nb_monomials; j++) { coeff_out[j] = coeff3[j]; } FREE_int(Monomials); if (f_v) { cout << "numerics::substitute_cubic_linear_using_povray_ordering done" << endl; } } void numerics::substitute_quartic_linear_using_povray_ordering( double *coeff_in, double *coeff_out, double *A4_inv, int verbose_level) // uses povray ordering of monomials // http://www.povray.org/documentation/view/3.6.1/298/ // 1: x^4 // 2: x^3y // 3: x^3z // 4: x^3 // 5: x^2y^2 // 6: x^2yz // 7: x^2y // 8: x^2z^2 // 9: x^2z // 10: x^2 // 11: xy^3 // 12: xy^2z // 13: xy^2 // 14: xyz^2 // 15: xyz // 16: xy // 17: xz^3 // 18: xz^2 // 19: xz // 20: x // 21: y^4 // 22: y^3z // 23: y^3 // 24: y^2z^2 // 25: y^2z // 26: y^2 // 27: yz^3 // 28: yz^2 // 29: yz // 30: y // 31: z^4 // 32: z^3 // 33: z^2 // 34: z // 35: 1 { int f_v = (verbose_level >= 1); int Variables[] = { // 1: 0,0,0,0, 0,0,0,1, 0,0,0,2, 0,0,0,3, 0,0,1,1, 0,0,1,2, 0,0,1,3, 0,0,2,2, 0,0,2,3, 0,0,3,3, //11: 0,1,1,1, 0,1,1,2, 0,1,1,3, 0,1,2,2, 0,1,2,3, 0,1,3,3, 0,2,2,2, 0,2,2,3, 0,2,3,3, 0,3,3,3, // 21: 1,1,1,1, 1,1,1,2, 1,1,1,3, 1,1,2,2, 1,1,2,3, 1,1,3,3, 1,2,2,2, 1,2,2,3, 1,2,3,3, 1,3,3,3, // 31: 2,2,2,2, 2,2,2,3, 2,2,3,3, 2,3,3,3, 3,3,3,3, }; int *Monomials; // [nb_monomials * n] int Affine_to_monomial[256]; // 4^4 int *V; int nb_monomials = 35; int degree = 4; int n = 4; double coeff2[35]; double coeff3[35]; double b, c; int h, i, j, a, nb_affine, idx; int A[4]; int v[4]; number_theory_domain NT; geometry_global Gg; if (f_v) { cout << "numerics::substitute_quartic_linear_using_povray_ordering" << endl; } nb_affine = NT.i_power_j(n, degree); if (FALSE) { cout << "Variables:" << endl; Orbiter->Int_vec.matrix_print(Variables, 35, 4); } Monomials = NEW_int(nb_monomials * n); Orbiter->Int_vec.zero(Monomials, nb_monomials * n); for (i = 0; i < nb_monomials; i++) { for (j = 0; j < degree; j++) { a = Variables[i * degree + j]; Monomials[i * n + a]++; } } if (FALSE) { cout << "Monomials:" << endl; Orbiter->Int_vec.matrix_print(Monomials, nb_monomials, n); } for (i = 0; i < nb_affine; i++) { Gg.AG_element_unrank(n /* q */, A, 1, degree, i); Orbiter->Int_vec.zero(v, n); for (j = 0; j < degree; j++) { a = A[j]; v[a]++; } for (idx = 0; idx < nb_monomials; idx++) { if (int_vec_compare(v, Monomials + idx * n, n) == 0) { break; } } if (idx == nb_monomials) { cout << "could not determine Affine_to_monomial" << endl; cout << "Monomials:" << endl; Orbiter->Int_vec.matrix_print(Monomials, nb_monomials, n); cout << "v="; Orbiter->Int_vec.print(cout, v, n); exit(1); } Affine_to_monomial[i] = idx; } if (FALSE) { cout << "Affine_to_monomial:"; Orbiter->Int_vec.print(cout, Affine_to_monomial, nb_affine); cout << endl; } for (i = 0; i < nb_monomials; i++) { coeff3[i] = 0.; } for (h = 0; h < nb_monomials; h++) { c = coeff_in[h]; if (c == 0) { continue; } V = Variables + h * degree; // a list of the indices of the variables // which appear in the monomial // (possibly with repeats) // Example: the monomial x_0^3 becomes 0,0,0 for (i = 0; i < nb_monomials; i++) { coeff2[i] = 0.; } for (a = 0; a < nb_affine; a++) { Gg.AG_element_unrank(n /* q */, A, 1, degree, a); // sequence of length degree // over the alphabet 0,...,n-1. b = 1.; for (j = 0; j < degree; j++) { //factors[j] = Mtx_inv[V[j] * n + A[j]]; b *= A4_inv[A[j] * n + V[j]]; } idx = Affine_to_monomial[a]; coeff2[idx] += b; } for (j = 0; j < nb_monomials; j++) { coeff2[j] *= c; } for (j = 0; j < nb_monomials; j++) { coeff3[j] += coeff2[j]; } } for (j = 0; j < nb_monomials; j++) { coeff_out[j] = coeff3[j]; } FREE_int(Monomials); if (f_v) { cout << "numerics::substitute_quartic_linear_using_povray_ordering done" << endl; } } void numerics::make_transform_t_varphi_u_double(int n, double *varphi, double *u, double *A, double *Av, int verbose_level) // varphi are the dual coordinates of a plane. // u is a vector such that varphi(u) \neq -1. // A = I + varphi * u. { int f_v = (verbose_level >= 1); int i, j; if (f_v) { cout << "make_transform_t_varphi_u_double" << endl; } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { if (i == j) { A[i * n + j] = 1. + varphi[i] * u[j]; } else { A[i * n + j] = varphi[i] * u[j]; } } } matrix_double_inverse(A, Av, n, 0 /* verbose_level */); if (f_v) { cout << "make_transform_t_varphi_u_double done" << endl; } } void numerics::matrix_double_inverse(double *A, double *Av, int n, int verbose_level) { int f_v = (verbose_level >= 1); double *M; int *base_cols; int i, j, two_n, rk; if (f_v) { cout << "matrix_double_inverse" << endl; } two_n = n * 2; M = new double [n * n * 2]; base_cols = NEW_int(two_n); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { M[i * two_n + j] = A[i * n + j]; if (i == j) { M[i * two_n + n + j] = 1.; } else { M[i * two_n + n + j] = 0.; } } } rk = Gauss_elimination(M, n, two_n, base_cols, TRUE /* f_complete */, 0 /* verbose_level */); if (rk < n) { cout << "matrix_double_inverse the matrix " "is not invertible" << endl; exit(1); } if (base_cols[n - 1] != n - 1) { cout << "matrix_double_inverse the matrix " "is not invertible" << endl; exit(1); } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { Av[i * n + j] = M[i * two_n + n + j]; } } delete [] M; FREE_int(base_cols); if (f_v) { cout << "matrix_double_inverse done" << endl; } } int numerics::line_centered(double *pt1_in, double *pt2_in, double *pt1_out, double *pt2_out, double r, int verbose_level) { int f_v = TRUE; //(verbose_level >= 1); double v[3]; double x1, x2, x3, y1, y2, y3; double a, b, c, av, d, e; double lambda1, lambda2; if (f_v) { cout << "numerics::line_centered" << endl; cout << "r=" << r << endl; cout << "pt1_in="; vec_print(pt1_in, 3); cout << endl; cout << "pt2_in="; vec_print(pt2_in, 3); cout << endl; } x1 = pt1_in[0]; x2 = pt1_in[1]; x3 = pt1_in[2]; y1 = pt2_in[0]; y2 = pt2_in[1]; y3 = pt2_in[2]; v[0] = y1 - x1; v[1] = y2 - x2; v[2] = y3 - x3; if (f_v) { cout << "v="; vec_print(v, 3); cout << endl; } // solve // (x1+\lambda*v[0])^2 + (x2+\lambda*v[1])^2 + (x3+\lambda*v[2])^2 = r^2 // which gives the quadratic // (v[0]^2+v[1]^2+v[2]^2) * \lambda^2 // + (2*x1*v[0] + 2*x2*v[1] + 2*x3*v[2]) * \lambda // + x1^2 + x2^2 + x3^2 - r^2 // = 0 a = v[0] * v[0] + v[1] * v[1] + v[2] * v[2]; b = 2. * (x1 * v[0] + x2 * v[1] + x3 * v[2]); c = x1 * x1 + x2 * x2 + x3 * x3 - r * r; if (f_v) { cout << "a=" << a << " b=" << b << " c=" << c << endl; } av = 1. / a; b = b * av; c = c * av; d = b * b * 0.25 - c; if (f_v) { cout << "a=" << a << " b=" << b << " c=" << c << " d=" << d << endl; } if (d < 0) { cout << "line_centered d < 0" << endl; cout << "r=" << r << endl; cout << "d=" << d << endl; cout << "a=" << a << endl; cout << "b=" << b << endl; cout << "c=" << c << endl; cout << "pt1_in="; vec_print(pt1_in, 3); cout << endl; cout << "pt2_in="; vec_print(pt2_in, 3); cout << endl; cout << "v="; vec_print(v, 3); cout << endl; exit(1); //return FALSE; //d = 0; } e = sqrt(d); lambda1 = -b * 0.5 + e; lambda2 = -b * 0.5 - e; pt1_out[0] = x1 + lambda1 * v[0]; pt1_out[1] = x2 + lambda1 * v[1]; pt1_out[2] = x3 + lambda1 * v[2]; pt2_out[0] = x1 + lambda2 * v[0]; pt2_out[1] = x2 + lambda2 * v[1]; pt2_out[2] = x3 + lambda2 * v[2]; if (f_v) { cout << "numerics::line_centered done" << endl; } return TRUE; } int numerics::line_centered_tolerant(double *pt1_in, double *pt2_in, double *pt1_out, double *pt2_out, double r, int verbose_level) { int f_v = (verbose_level >= 1); double v[3]; double x1, x2, x3, y1, y2, y3; double a, b, c, av, d, e; double lambda1, lambda2; if (f_v) { cout << "numerics::line_centered_tolerant" << endl; cout << "r=" << r << endl; cout << "pt1_in="; vec_print(pt1_in, 3); cout << endl; cout << "pt2_in="; vec_print(pt2_in, 3); cout << endl; } x1 = pt1_in[0]; x2 = pt1_in[1]; x3 = pt1_in[2]; y1 = pt2_in[0]; y2 = pt2_in[1]; y3 = pt2_in[2]; v[0] = y1 - x1; v[1] = y2 - x2; v[2] = y3 - x3; if (f_v) { cout << "v="; vec_print(v, 3); cout << endl; } // solve // (x1+\lambda*v[0])^2 + (x2+\lambda*v[1])^2 + (x3+\lambda*v[2])^2 = r^2 // which gives the quadratic // (v[0]^2+v[1]^2+v[2]^2) * \lambda^2 // + (2*x1*v[0] + 2*x2*v[1] + 2*x3*v[2]) * \lambda // + x1^2 + x2^2 + x3^2 - r^2 // = 0 a = v[0] * v[0] + v[1] * v[1] + v[2] * v[2]; b = 2. * (x1 * v[0] + x2 * v[1] + x3 * v[2]); c = x1 * x1 + x2 * x2 + x3 * x3 - r * r; if (f_v) { cout << "a=" << a << " b=" << b << " c=" << c << endl; } av = 1. / a; b = b * av; c = c * av; d = b * b * 0.25 - c; if (f_v) { cout << "a=" << a << " b=" << b << " c=" << c << " d=" << d << endl; } if (d < 0) { cout << "line_centered d < 0" << endl; cout << "r=" << r << endl; cout << "d=" << d << endl; cout << "a=" << a << endl; cout << "b=" << b << endl; cout << "c=" << c << endl; cout << "pt1_in="; vec_print(pt1_in, 3); cout << endl; cout << "pt2_in="; vec_print(pt2_in, 3); cout << endl; cout << "v="; vec_print(v, 3); cout << endl; //exit(1); return FALSE; } e = sqrt(d); lambda1 = -b * 0.5 + e; lambda2 = -b * 0.5 - e; pt1_out[0] = x1 + lambda1 * v[0]; pt1_out[1] = x2 + lambda1 * v[1]; pt1_out[2] = x3 + lambda1 * v[2]; pt2_out[0] = x1 + lambda2 * v[0]; pt2_out[1] = x2 + lambda2 * v[1]; pt2_out[2] = x3 + lambda2 * v[2]; if (f_v) { cout << "numerics::line_centered_tolerant done" << endl; } return TRUE; } int numerics::sign_of(double a) { if (a < 0) { return -1; } else if (a > 0) { return 1; } else { return 0; } } void numerics::eigenvalues(double *A, int n, double *lambda, int verbose_level) { int f_v = (verbose_level >= 1); int i, j; if (f_v) { cout << "eigenvalues" << endl; } polynomial_double_domain Poly; polynomial_double *P; polynomial_double *det; Poly.init(n); P = NEW_OBJECTS(polynomial_double, n * n); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { P[i * n + j].init(n + 1); if (i == j) { P[i * n + j].coeff[0] = A[i * n + j]; P[i * n + j].coeff[1] = -1.; P[i * n + j].degree = 1; } else { P[i * n + j].coeff[0] = A[i * n + j]; P[i * n + j].degree = 0; } } } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { P[i * n + j].print(cout); cout << "; "; } cout << endl; } det = NEW_OBJECT(polynomial_double); det->init(n + 1); Poly.determinant_over_polynomial_ring( P, det, n, 0 /*verbose_level*/); cout << "characteristic polynomial "; det->print(cout); cout << endl; //double *lambda; //lambda = new double[n]; Poly.find_all_roots(det, lambda, verbose_level); // bubble sort: for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if (lambda[i] > lambda[j]) { double a; a = lambda[i]; lambda[i] = lambda[j]; lambda[j] = a; } } } cout << "The eigenvalues are: "; for (i = 0; i < n; i++) { cout << lambda[i]; if (i < n - 1) { cout << ", "; } } cout << endl; if (f_v) { cout << "eigenvalues done" << endl; } } void numerics::eigenvectors(double *A, double *Basis, int n, double *lambda, int verbose_level) { int f_v = (verbose_level >= 1); int i, j; if (f_v) { cout << "eigenvectors" << endl; } cout << "The eigenvalues are: "; for (i = 0; i < n; i++) { cout << lambda[i]; if (i < n - 1) { cout << ", "; } } cout << endl; double *B, *K; int u, v, h, k; double uv, vv, s; B = new double[n * n]; K = new double[n * n]; for (h = 0; h < n; ) { cout << "eigenvector " << h << " / " << n << " is " << lambda[h] << ":" << endl; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { if (i == j) { B[i * n + j] = A[i * n + j] - lambda[h]; } else { B[i * n + j] = A[i * n + j]; } } } k = Null_space(B, n, n, K, verbose_level); // K will be k x n // where k is the return value. cout << "the eigenvalue has multiplicity " << k << endl; for (u = 0; u < k; u++) { for (j = 0; j < n; j++) { Basis[j * n + h + u] = K[u * n + j]; } if (u) { // perform Gram-Schmidt: for (v = 0; v < u; v++) { uv = 0; for (i = 0; i < n; i++) { uv += Basis[i * n + h + u] * Basis[i * n + h + v]; } vv = 0; for (i = 0; i < n; i++) { vv += Basis[i * n + h + v] * Basis[i * n + h + v]; } s = uv / vv; for (i = 0; i < n; i++) { Basis[i * n + h + u] -= s * Basis[i * n + h + v]; } } // next v } // if (u) } // perform normalization: for (v = 0; v < k; v++) { vv = 0; for (i = 0; i < n; i++) { vv += Basis[i * n + h + v] * Basis[i * n + h + v]; } s = 1 / sqrt(vv); for (i = 0; i < n; i++) { Basis[i * n + h + v] *= s; } } h += k; } // next h cout << "The orthonormal Basis is: " << endl; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { cout << Basis[i * n + j] << "\t"; } cout << endl; } if (f_v) { cout << "eigenvectors done" << endl; } } double numerics::rad2deg(double phi) { return phi * 180. / M_PI; } void numerics::vec_copy(double *from, double *to, int len) { int i; double *p, *q; for (p = from, q = to, i = 0; i < len; p++, q++, i++) { *q = *p; } } void numerics::vec_swap(double *from, double *to, int len) { int i; double *p, *q; double a; for (p = from, q = to, i = 0; i < len; p++, q++, i++) { a = *q; *q = *p; *p = a; } } void numerics::vec_print(ostream &ost, double *v, int len) { int i; ost << "( "; for (i = 0; i < len; i++) { ost << v[i]; if (i < len - 1) ost << ", "; } ost << " )"; } void numerics::vec_scan(const char *s, double *&v, int &len) { istringstream ins(s); vec_scan_from_stream(ins, v, len); } void numerics::vec_scan(std::string &s, double *&v, int &len) { istringstream ins(s); vec_scan_from_stream(ins, v, len); } void numerics::vec_scan_from_stream(istream & is, double *&v, int &len) { int verbose_level = 0; int f_v = (verbose_level >= 1); double a; char s[10000], c; int l, h; len = 20; v = new double [len]; h = 0; l = 0; while (TRUE) { if (!is) { len = h; return; } l = 0; if (is.eof()) { //cout << "breaking off because of eof" << endl; len = h; return; } is >> c; //c = get_character(is, verbose_level - 2); if (c == 0) { len = h; return; } while (TRUE) { while (c != 0) { if (f_v) { cout << "character \"" << c << "\", ascii=" << (int)c << endl; } if (c == '-') { //cout << "c='" << c << "'" << endl; if (is.eof()) { //cout << "breaking off because of eof" << endl; break; } s[l++] = c; is >> c; //c = get_character(is, verbose_level - 2); } else if ((c >= '0' && c <= '9') || c == '.') { //cout << "c='" << c << "'" << endl; if (is.eof()) { //cout << "breaking off because of eof" << endl; break; } s[l++] = c; is >> c; //c = get_character(is, verbose_level - 2); } else { //cout << "breaking off because c='" << c << "'" << endl; break; } if (c == 0) { break; } //cout << "int_vec_scan_from_stream inside loop: \"" //<< c << "\", ascii=" << (int)c << endl; } s[l] = 0; sscanf(s, "%lf", &a); //a = atoi(s); if (FALSE) { cout << "digit as string: " << s << ", numeric: " << a << endl; } if (h == len) { len += 20; double *v2; v2 = new double [len]; vec_copy(v, v2, h); delete [] v; v = v2; } v[h++] = a; l = 0; if (!is) { len = h; return; } if (c == 0) { len = h; return; } if (is.eof()) { //cout << "breaking off because of eof" << endl; len = h; return; } is >> c; //c = get_character(is, verbose_level - 2); if (c == 0) { len = h; return; } } } } #include <math.h> double numerics::cos_grad(double phi) { double x; x = (phi * M_PI) / 180.; return cos(x); } double numerics::sin_grad(double phi) { double x; x = (phi * M_PI) / 180.; return sin(x); } double numerics::tan_grad(double phi) { double x; x = (phi * M_PI) / 180.; return tan(x); } double numerics::atan_grad(double x) { double y, phi; y = atan(x); phi = (y * 180.) / M_PI; return phi; } void numerics::adjust_coordinates_double( double *Px, double *Py, int *Qx, int *Qy, int N, double xmin, double ymin, double xmax, double ymax, int verbose_level) { int f_v = (verbose_level >= 1); int f_vv = (verbose_level >= 2); double in[4], out[4]; double x_min, x_max; double y_min, y_max; int i; double x, y; x_min = x_max = Px[0]; y_min = y_max = Py[0]; for (i = 1; i < N; i++) { x_min = MINIMUM(x_min, Px[i]); x_max = MAXIMUM(x_max, Px[i]); y_min = MINIMUM(y_min, Py[i]); y_max = MAXIMUM(y_max, Py[i]); } if (f_v) { cout << "numerics::adjust_coordinates_double: x_min=" << x_min << "x_max=" << x_max << "y_min=" << y_min << "y_max=" << y_max << endl; cout << "adjust_coordinates_double: "; cout << "xmin=" << xmin << " xmax=" << xmax << " ymin=" << ymin << " ymax=" << ymax << endl; } in[0] = x_min; in[1] = y_min; in[2] = x_max; in[3] = y_max; out[0] = xmin; out[1] = ymin; out[2] = xmax; out[3] = ymax; for (i = 0; i < N; i++) { x = Px[i]; y = Py[i]; if (f_vv) { cout << "In:" << x << "," << y << " : "; } transform_llur_double(in, out, x, y); Qx[i] = (int)x; Qy[i] = (int)y; if (f_vv) { cout << " Out: " << Qx[i] << "," << Qy[i] << endl; } } } void numerics::Intersection_of_lines(double *X, double *Y, double *a, double *b, double *c, int l1, int l2, int pt) { intersection_of_lines( a[l1], b[l1], c[l1], a[l2], b[l2], c[l2], X[pt], Y[pt]); } void numerics::intersection_of_lines( double a1, double b1, double c1, double a2, double b2, double c2, double &x, double &y) { double d; d = a1 * b2 - a2 * b1; d = 1. / d; x = d * (b2 * -c1 + -b1 * -c2); y = d * (-a2 * -c1 + a1 * -c2); } void numerics::Line_through_points(double *X, double *Y, double *a, double *b, double *c, int pt1, int pt2, int line_idx) { line_through_points(X[pt1], Y[pt1], X[pt2], Y[pt2], a[line_idx], b[line_idx], c[line_idx]); } void numerics::line_through_points(double pt1_x, double pt1_y, double pt2_x, double pt2_y, double &a, double &b, double &c) { double s, off; const double MY_EPS = 0.01; if (ABS(pt2_x - pt1_x) > MY_EPS) { s = (pt2_y - pt1_y) / (pt2_x - pt1_x); off = pt1_y - s * pt1_x; a = s; b = -1; c = off; } else { s = (pt2_x - pt1_x) / (pt2_y - pt1_y); off = pt1_x - s * pt1_y; a = 1; b = -s; c = -off; } } void numerics::intersect_circle_line_through(double rad, double x0, double y0, double pt1_x, double pt1_y, double pt2_x, double pt2_y, double &x1, double &y1, double &x2, double &y2) { double a, b, c; line_through_points(pt1_x, pt1_y, pt2_x, pt2_y, a, b, c); //cout << "intersect_circle_line_through pt1_x=" << pt1_x //<< " pt1_y=" << pt1_y << " pt2_x=" << pt2_x //<< " pt2_y=" << pt2_y << endl; //cout << "intersect_circle_line_through a=" << a << " b=" << b //<< " c=" << c << endl; intersect_circle_line(rad, x0, y0, a, b, c, x1, y1, x2, y2); //cout << "intersect_circle_line_through x1=" << x1 << " y1=" << y1 // << " x2=" << x2 << " y2=" << y2 << endl << endl; } void numerics::intersect_circle_line(double rad, double x0, double y0, double a, double b, double c, double &x1, double &y1, double &x2, double &y2) { double A, B, C; double a2 = a * a; double b2 = b * b; double c2 = c * c; double x02 = x0 * x0; double y02 = y0 * y0; double r2 = rad * rad; double p, q, u, disc, d; cout << "a=" << a << " b=" << b << " c=" << c << endl; A = 1 + a2 / b2; B = 2 * a * c / b2 - 2 * x0 + 2 * a * y0 / b; C = c2 / b2 + 2 * c * y0 / b + x02 + y02 - r2; cout << "A=" << A << " B=" << B << " C=" << C << endl; p = B / A; q = C / A; u = -p / 2; disc = u * u - q; d = sqrt(disc); x1 = u + d; x2 = u - d; y1 = (-a * x1 - c) / b; y2 = (-a * x2 - c) / b; } void numerics::affine_combination(double *X, double *Y, int pt0, int pt1, int pt2, double alpha, int new_pt) //X[new_pt] = X[pt0] + alpha * (X[pt2] - X[pt1]); //Y[new_pt] = Y[pt0] + alpha * (Y[pt2] - Y[pt1]); { X[new_pt] = X[pt0] + alpha * (X[pt2] - X[pt1]); Y[new_pt] = Y[pt0] + alpha * (Y[pt2] - Y[pt1]); } void numerics::on_circle_double(double *Px, double *Py, int idx, double angle_in_degree, double rad) { Px[idx] = cos_grad(angle_in_degree) * rad; Py[idx] = sin_grad(angle_in_degree) * rad; } void numerics::affine_pt1(int *Px, int *Py, int p0, int p1, int p2, double f1, int p3) { int x = Px[p0] + (int)(f1 * (double)(Px[p2] - Px[p1])); int y = Py[p0] + (int)(f1 * (double)(Py[p2] - Py[p1])); Px[p3] = x; Py[p3] = y; } void numerics::affine_pt2(int *Px, int *Py, int p0, int p1, int p1b, double f1, int p2, int p2b, double f2, int p3) { int x = Px[p0] + (int)(f1 * (double)(Px[p1b] - Px[p1])) + (int)(f2 * (double)(Px[p2b] - Px[p2])); int y = Py[p0] + (int)(f1 * (double)(Py[p1b] - Py[p1])) + (int)(f2 * (double)(Py[p2b] - Py[p2])); Px[p3] = x; Py[p3] = y; } double numerics::norm_of_vector_2D(int x1, int x2, int y1, int y2) { return sqrt((double)(x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); } #undef DEBUG_TRANSFORM_LLUR void numerics::transform_llur(int *in, int *out, int &x, int &y) { int dx, dy; //, rad; double a, b; //, f; #ifdef DEBUG_TRANSFORM_LLUR cout << "transform_llur: "; cout << "In=" << in[0] << "," << in[1] << "," << in[2] << "," << in[3] << endl; cout << "Out=" << out[0] << "," << out[1] << "," << out[2] << "," << out[3] << endl; #endif dx = x - in[0]; dy = y - in[1]; //rad = MIN(out[2] - out[0], out[3] - out[1]); a = (double) dx / (double)(in[2] - in[0]); b = (double) dy / (double)(in[3] - in[1]); //a = a / 300000.; //b = b / 300000.; #ifdef DEBUG_TRANSFORM_LLUR cout << "transform_llur: (x,y)=(" << x << "," << y << ") in[2] - in[0]=" << in[2] - in[0] << " in[3] - in[1]=" << in[3] - in[1] << " (a,b)=(" << a << "," << b << ") -> "; #endif // projection on a disc of radius 1: //f = 300000 / sqrt(1. + a * a + b * b); #ifdef DEBUG_TRANSFORM_LLUR cout << "f=" << f << endl; #endif //a = f * a; //b = f * b; //dx = (int)(a * f); //dy = (int)(b * f); dx = (int)(a * (double)(out[2] - out[0])); dy = (int)(b * (double)(out[3] - out[1])); x = dx + out[0]; y = dy + out[1]; #ifdef DEBUG_TRANSFORM_LLUR cout << x << "," << y << " a=" << a << " b=" << b << endl; #endif } void numerics::transform_dist(int *in, int *out, int &x, int &y) { int dx, dy; double a, b; a = (double) x / (double)(in[2] - in[0]); b = (double) y / (double)(in[3] - in[1]); dx = (int)(a * (double) (out[2] - out[0])); dy = (int)(b * (double) (out[3] - out[1])); x = dx; y = dy; } void numerics::transform_dist_x(int *in, int *out, int &x) { int dx; double a; a = (double) x / (double)(in[2] - in[0]); dx = (int)(a * (double) (out[2] - out[0])); x = dx; } void numerics::transform_dist_y(int *in, int *out, int &y) { int dy; double b; b = (double) y / (double)(in[3] - in[1]); dy = (int)(b * (double) (out[3] - out[1])); y = dy; } void numerics::transform_llur_double(double *in, double *out, double &x, double &y) { double dx, dy; double a, b; #ifdef DEBUG_TRANSFORM_LLUR cout << "transform_llur_double: " << x << "," << y << " -> "; #endif dx = x - in[0]; dy = y - in[1]; a = dx / (in[2] - in[0]); b = dy / (in[3] - in[1]); dx = a * (out[2] - out[0]); dy = b * (out[3] - out[1]); x = dx + out[0]; y = dy + out[1]; #ifdef DEBUG_TRANSFORM_LLUR cout << x << "," << y << endl; #endif } void numerics::on_circle_int(int *Px, int *Py, int idx, int angle_in_degree, int rad) { Px[idx] = (int)(cos_grad(angle_in_degree) * (double) rad); Py[idx] = (int)(sin_grad(angle_in_degree) * (double) rad); } double numerics::power_of(double x, int n) { double b, c; b = x; c = 1.; while (n) { if (n % 2) { //cout << "numerics::power_of mult(" << b << "," << c << ")="; c = b * c; //cout << c << endl; } b = b * b; n >>= 1; //cout << "numerics::power_of " << b << "^" //<< n << " * " << c << endl; } return c; } double numerics::bernoulli(double p, int n, int k) { double q, P, Q, PQ, c; int nCk; combinatorics_domain Combi; q = 1. - p; P = power_of(p, k); Q = power_of(q, n - k); PQ = P * Q; nCk = Combi.int_n_choose_k(n, k); c = (double) nCk * PQ; return c; } void numerics::local_coordinates_wrt_triangle(double *pt, double *triangle_points, double &x, double &y, int verbose_level) { int f_v = (verbose_level >= 1); double b1[3]; double b2[3]; if (f_v) { cout << "numerics::local_coordinates_wrt_triangle" << endl; } vec_linear_combination(1., triangle_points + 1 * 3, -1, triangle_points + 0 * 3, b1, 3); vec_linear_combination(1., triangle_points + 2 * 3, -1, triangle_points + 0 * 3, b2, 3); if (f_v) { cout << "numerics::local_coordinates_wrt_triangle b1:" << endl; print_system(b1, 1, 3); cout << endl; cout << "numerics::local_coordinates_wrt_triangle b2:" << endl; print_system(b2, 1, 3); cout << endl; } double system[9]; double system_transposed[9]; double K[3]; int rk; vec_copy(b1, system, 3); vec_copy(b2, system + 3, 3); vec_linear_combination(1., pt, -1, triangle_points + 0 * 3, system + 6, 3); transpose_matrix_nxn(system, system_transposed, 3); if (f_v) { cout << "system (transposed):" << endl; print_system(system_transposed, 3, 3); cout << endl; } rk = Null_space(system_transposed, 3, 3, K, 0 /* verbose_level */); if (f_v) { cout << "system transposed in RREF" << endl; print_system(system_transposed, 3, 3); cout << endl; cout << "K=" << endl; print_system(K, 1, 3); cout << endl; } // K will be rk x n if (rk != 1) { cout << "numerics::local_coordinates_wrt_triangle rk != 1" << endl; exit(1); } if (ABS(K[2]) < EPSILON) { cout << "numerics::local_coordinates_wrt_triangle ABS(K[2]) < EPSILON" << endl; //exit(1); x = 0; y = 0; } else { double c, cv; c = K[2]; cv = -1. / c; // make the last coefficient -1 // so we get the equation // x * b1 + y * b2 = v // where v is the point that we consider K[0] *= cv; K[1] *= cv; x = K[0]; y = K[1]; } if (f_v) { cout << "numerics::local_coordinates_wrt_triangle done" << endl; } } int numerics::intersect_line_and_line( double *line1_pt1_coords, double *line1_pt2_coords, double *line2_pt1_coords, double *line2_pt2_coords, double &lambda, double *pt_coords, int verbose_level) { int f_v = (verbose_level >= 1); int f_vv = FALSE; // (verbose_level >= 2); //double B[3]; double M[9]; int i; double v[3]; numerics N; if (f_v) { cout << "numerics::intersect_line_and_line" << endl; } // equation of the form: // P_0 + \lambda * v = Q_0 + \mu * u // where P_0 is a point on the line, // Q_0 is a point on the plane, // v is a direction vector of line 1 // u is a direction vector of line 2 // M is the matrix whose columns are // v, -u, -P_0 + Q_0 // point on line 1, brought over on the other side, hence the minus: // -P_0 M[0 * 3 + 2] = -1. * line1_pt1_coords[0]; //Line_coords[line1_idx * 6 + 0]; M[1 * 3 + 2] = -1. * line1_pt1_coords[1]; //Line_coords[line1_idx * 6 + 1]; M[2 * 3 + 2] = -1. * line1_pt1_coords[2]; //Line_coords[line1_idx * 6 + 2]; // +P_1 M[0 * 3 + 2] += line2_pt1_coords[0]; //Line_coords[line2_idx * 6 + 0]; M[1 * 3 + 2] += line2_pt1_coords[1]; //Line_coords[line2_idx * 6 + 1]; M[2 * 3 + 2] += line2_pt1_coords[2]; //Line_coords[line2_idx * 6 + 2]; // v = direction vector of line 1: for (i = 0; i < 3; i++) { v[i] = line1_pt2_coords[i] - line1_pt1_coords[i]; } // we will need v[] later, hence we store this vector for (i = 0; i < 3; i++) { //v[i] = line1_pt2_coords[i] - line1_pt1_coords[i]; //v[i] = Line_coords[line1_idx * 6 + 3 + i] - // Line_coords[line1_idx * 6 + i]; M[i * 3 + 0] = v[i]; } // negative direction vector of line 2: for (i = 0; i < 3; i++) { M[i * 3 + 1] = -1. * (line2_pt2_coords[i] - line2_pt1_coords[i]); //M[i * 3 + 1] = -1. * (Line_coords[line2_idx * 6 + 3 + i] - // Line_coords[line2_idx * 6 + i]); } // solve M: int rk; int base_cols[3]; if (f_vv) { cout << "numerics::intersect_line_and_line " "before Gauss elimination:" << endl; N.print_system(M, 3, 3); } rk = N.Gauss_elimination(M, 3, 3, base_cols, TRUE /* f_complete */, 0 /* verbose_level */); if (f_vv) { cout << "numerics::intersect_line_and_line " "after Gauss elimination:" << endl; N.print_system(M, 3, 3); } if (rk < 2) { cout << "numerics::intersect_line_and_line " "the matrix M does not have full rank" << endl; return FALSE; } lambda = M[0 * 3 + 2]; for (i = 0; i < 3; i++) { pt_coords[i] = line1_pt1_coords[i] + lambda * v[i]; //B[i] = Line_coords[line1_idx * 6 + i] + lambda * v[i]; } if (f_vv) { cout << "numerics::intersect_line_and_line " "The intersection point is " << pt_coords[0] << ", " << pt_coords[1] << ", " << pt_coords[2] << endl; } //point(B[0], B[1], B[2]); if (f_v) { cout << "numerics::intersect_line_and_line done" << endl; } return TRUE; } void numerics::clebsch_map_up( double *line1_pt1_coords, double *line1_pt2_coords, double *line2_pt1_coords, double *line2_pt2_coords, double *pt_in, double *pt_out, double *Cubic_coords_povray_ordering, int line1_idx, int line2_idx, int verbose_level) { int f_v = (verbose_level >= 1); int i; int rk; numerics Num; double M[16]; double L[16]; double Pts[16]; double N[16]; double C[20]; if (f_v) { cout << "numerics::clebsch_map_up " "line1_idx=" << line1_idx << " line2_idx=" << line2_idx << endl; } if (line1_idx == line2_idx) { cout << "numerics::clebsch_map_up " "line1_idx == line2_idx, line1_idx=" << line1_idx << endl; exit(1); } Num.vec_copy(line1_pt1_coords, M, 3); M[3] = 1.; Num.vec_copy(line1_pt2_coords, M + 4, 3); M[7] = 1.; Num.vec_copy(pt_in, M + 8, 3); M[11] = 1.; if (f_v) { cout << "numerics::clebsch_map_up " "system for plane 1=" << endl; Num.print_system(M, 3, 4); } rk = Num.Null_space(M, 3, 4, L, 0 /* verbose_level */); if (rk != 1) { cout << "numerics::clebsch_map_up " "system for plane 1 does not have nullity 1" << endl; cout << "numerics::clebsch_map_up " "nullity=" << rk << endl; exit(1); } if (f_v) { cout << "numerics::clebsch_map_up " "perp for plane 1=" << endl; Num.print_system(L, 1, 4); } Num.vec_copy(line2_pt1_coords, M, 3); M[3] = 1.; Num.vec_copy(line2_pt2_coords, M + 4, 3); M[7] = 1.; Num.vec_copy(pt_in, M + 8, 3); M[11] = 1.; if (f_v) { cout << "numerics::clebsch_map_up " "system for plane 2=" << endl; Num.print_system(M, 3, 4); } rk = Num.Null_space(M, 3, 4, L + 4, 0 /* verbose_level */); if (rk != 1) { cout << "numerics::clebsch_map_up " "system for plane 2 does not have nullity 1" << endl; cout << "numerics::clebsch_map_up " "nullity=" << rk << endl; exit(1); } if (f_v) { cout << "numerics::clebsch_map_up " "perp for plane 2=" << endl; Num.print_system(L + 4, 1, 4); } if (f_v) { cout << "numerics::clebsch_map_up " "system for line=" << endl; Num.print_system(L, 2, 4); } rk = Num.Null_space(L, 2, 4, L + 8, 0 /* verbose_level */); if (rk != 2) { cout << "numerics::clebsch_map_up " "system for line does not have nullity 2" << endl; cout << "numerics::clebsch_map_up " "nullity=" << rk << endl; exit(1); } if (f_v) { cout << "numerics::clebsch_map_up " "perp for Line=" << endl; Num.print_system(L + 8, 2, 4); } Num.vec_normalize_from_back(L + 8, 4); Num.vec_normalize_from_back(L + 12, 4); if (f_v) { cout << "numerics::clebsch_map_up " "perp for Line normalized=" << endl; Num.print_system(L + 8, 2, 4); } if (ABS(L[11]) < 0.0001) { Num.vec_copy(L + 12, Pts, 4); Num.vec_add(L + 8, L + 12, Pts + 4, 4); if (f_v) { cout << "numerics::clebsch_map_up " "two affine points on the line=" << endl; Num.print_system(Pts, 2, 4); } } else { cout << "numerics::clebsch_map_up " "something is wrong with the line" << endl; exit(1); } Num.line_centered(Pts, Pts + 4, N, N + 4, 10, verbose_level - 1); N[3] = 1.; N[7] = 0.; if (f_v) { cout << "numerics::clebsch_map_up " "line centered=" << endl; Num.print_system(N, 2, 4); } //int l_idx; double line3_pt1_coords[3]; double line3_pt2_coords[3]; // create a line: //l_idx = S->line(N[0], N[1], N[2], N[4], N[5], N[6]); //Line_idx[nb_line_idx++] = S->nb_lines - 1; for (i = 0; i < 3; i++) { line3_pt1_coords[i] = N[i]; } for (i = 0; i < 3; i++) { line3_pt2_coords[i] = N[4 + i]; } for (i = 0; i < 3; i++) { N[4 + i] = N[4 + i] - N[i]; } for (i = 8; i < 16; i++) { N[i] = 0.; } if (f_v) { cout << "N=" << endl; Num.print_system(N, 4, 4); } Num.substitute_cubic_linear_using_povray_ordering(Cubic_coords_povray_ordering, C, N, 0 /* verbose_level */); if (f_v) { cout << "numerics::clebsch_map_up " "transformed cubic=" << endl; Num.print_system(C, 1, 20); } double a, b, c, d, tr, t1, t2, t3; a = C[10]; b = C[4]; c = C[1]; d = C[0]; tr = -1 * b / a; if (f_v) { cout << "numerics::clebsch_map_up " "a=" << a << " b=" << b << " c=" << c << " d=" << d << endl; cout << "clebsch_scene::create_point_up " "tr = " << tr << endl; } double pt1_coords[3]; double pt2_coords[3]; // creates a point: if (!intersect_line_and_line( line3_pt1_coords, line3_pt2_coords, line1_pt1_coords, line1_pt2_coords, t1 /* lambda */, pt1_coords, 0 /*verbose_level*/)) { cout << "numerics::clebsch_map_up " "problem computing intersection with line 1" << endl; exit(1); } double P1[3]; for (i = 0; i < 3; i++) { P1[i] = N[i] + t1 * (N[4 + i] - N[i]); } if (f_v) { cout << "numerics::clebsch_map_up t1=" << t1 << endl; cout << "numerics::clebsch_map_up P1="; Num.print_system(P1, 1, 3); cout << "numerics::clebsch_map_up point: "; Num.print_system(pt1_coords, 1, 3); } double eval_t1; eval_t1 = (((a * t1 + b) * t1) + c) * t1 + d; if (f_v) { cout << "numerics::clebsch_map_up " "eval_t1=" << eval_t1 << endl; } // creates a point: if (!intersect_line_and_line( line3_pt1_coords, line3_pt2_coords, line1_pt2_coords, line2_pt2_coords, t2 /* lambda */, pt2_coords, 0 /*verbose_level*/)) { cout << "numerics::clebsch_map_up " "problem computing intersection with line 2" << endl; exit(1); } double P2[3]; for (i = 0; i < 3; i++) { P2[i] = N[i] + t2 * (N[4 + i] - N[i]); } if (f_v) { cout << "numerics::clebsch_map_up t2=" << t2 << endl; cout << "numerics::clebsch_map_up P2="; Num.print_system(P2, 1, 3); cout << "numerics::clebsch_map_up point: "; Num.print_system(pt2_coords, 1, 3); } double eval_t2; eval_t2 = (((a * t2 + b) * t2) + c) * t2 + d; if (f_v) { cout << "numerics::clebsch_map_up " "eval_t2=" << eval_t2 << endl; } t3 = tr - t1 - t2; double eval_t3; eval_t3 = (((a * t3 + b) * t3) + c) * t3 + d; if (f_v) { cout << "numerics::clebsch_map_up " "eval_t3=" << eval_t3 << endl; } if (f_v) { cout << "numerics::clebsch_map_up " "tr=" << tr << " t1=" << t1 << " t2=" << t2 << " t3=" << t3 << endl; } double Q[3]; for (i = 0; i < 3; i++) { Q[i] = N[i] + t3 * N[4 + i]; } if (f_v) { cout << "numerics::clebsch_map_up Q="; Num.print_system(Q, 1, 3); } // delete two points: //S->nb_points -= 2; Num.vec_copy(Q, pt_out, 3); if (f_v) { cout << "numerics::clebsch_map_up done" << endl; } } void numerics::project_to_disc(int f_projection_on, int f_transition, int step, int nb_steps, double rad, double height, double x, double y, double &xp, double &yp) { double f; if (f_transition) { double x1, y1, d0, d1; f = rad / sqrt(height * height + x * x + y * y); x1 = x * f; y1 = y * f; d1 = (double) step / (double) nb_steps; d0 = 1. - d1; xp = x * d0 + x1 * d1; yp = y * d0 + y1 * d1; } else if (f_projection_on) { f = rad / sqrt(height * height + x * x + y * y); xp = x * f; yp = y * f; } else { xp = x; yp = y; } } }}
19.633682
171
0.519487
263370c98e163baafdad40ec75d1366c1c1d7de5
259
cpp
C++
Cpp_Program/File Handling/writelinebyine.cpp
ajaypp123/DataStructure_Competative_Programing
6d2cbac3498b31655de50cf4dc3f564d52608780
[ "MIT" ]
null
null
null
Cpp_Program/File Handling/writelinebyine.cpp
ajaypp123/DataStructure_Competative_Programing
6d2cbac3498b31655de50cf4dc3f564d52608780
[ "MIT" ]
null
null
null
Cpp_Program/File Handling/writelinebyine.cpp
ajaypp123/DataStructure_Competative_Programing
6d2cbac3498b31655de50cf4dc3f564d52608780
[ "MIT" ]
null
null
null
#include<iostream> #include<fstream> using namespace std; int main() { fstream file; file.open("file.txt"); string line; while(line != "end") { getline(cin, line); file << line << endl; } file.close(); return 0; }
16.1875
29
0.552124
26352650d1252dd1882ab8b5ba4dd7d98247b782
861
cpp
C++
SelfProject/DrawAndDrop/mainwindow.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
3
2018-12-24T19:35:52.000Z
2022-02-04T14:45:59.000Z
SelfProject/DrawAndDrop/mainwindow.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
null
null
null
SelfProject/DrawAndDrop/mainwindow.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
1
2019-05-09T02:42:40.000Z
2019-05-09T02:42:40.000Z
#include <QDragEnterEvent> #include <QDropEvent> #include <QMimeData> #include <QTextEdit> #include "mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { textEdit = new QTextEdit; setCentralWidget(textEdit); textEdit->setAcceptDrops(false); setAcceptDrops(true); setWindowTitle(tr("Text Editor")); } MainWindow::~MainWindow() { } void MainWindow::dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasFormat("text/uri-list")) { event->acceptProposedAction(); } } void MainWindow::dropEvent(QDropEvent *event) { QList<QUrl> urls = event->mimeData()->urls(); if (urls.isEmpty()) { return; } QString fileName = urls.first().toLocalFile(); if (fileName.isEmpty()) { return; } if (readFile(fileName)) { setWindowTitle(tr("%1 - %2").arg(fileName).arg(tr("Drag file"))); } }
20.5
69
0.681765
26355530e1518b72c5f6e917ab4dd61156635581
53,079
cc
C++
chrome/browser/extensions/process_manager_browsertest.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
chrome/browser/extensions/process_manager_browsertest.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
chrome/browser/extensions/process_manager_browsertest.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stddef.h> #include <memory> #include <utility> #include "base/callback.h" #include "base/macros.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/test/histogram_tester.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/extensions/browser_action_test_util.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/test_extension_dir.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension_process_policy.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/guest_view/browser/test_guest_view_manager.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" #include "content/public/common/browser_side_navigation_policy.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_navigation_observer.h" #include "content/public/test/test_utils.h" #include "extensions/browser/app_window/app_window.h" #include "extensions/browser/app_window/app_window_registry.h" #include "extensions/browser/process_manager.h" #include "extensions/common/permissions/permissions_data.h" #include "extensions/common/value_builder.h" #include "extensions/test/background_page_watcher.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" namespace extensions { namespace { void AddFrameToSet(std::set<content::RenderFrameHost*>* frames, content::RenderFrameHost* rfh) { if (rfh->IsRenderFrameLive()) frames->insert(rfh); } GURL CreateBlobURL(content::RenderFrameHost* frame, const std::string& content) { std::string blob_url_string; EXPECT_TRUE(ExecuteScriptAndExtractString( frame, "var blob = new Blob(['<html><body>" + content + "</body></html>'],\n" " {type: 'text/html'});\n" "domAutomationController.send(URL.createObjectURL(blob));\n", &blob_url_string)); GURL blob_url(blob_url_string); EXPECT_TRUE(blob_url.is_valid()); EXPECT_TRUE(blob_url.SchemeIsBlob()); return blob_url; } GURL CreateFileSystemURL(content::RenderFrameHost* frame, const std::string& content) { std::string filesystem_url_string; EXPECT_TRUE(ExecuteScriptAndExtractString( frame, "var blob = new Blob(['<html><body>" + content + "</body></html>'],\n" " {type: 'text/html'});\n" "window.webkitRequestFileSystem(TEMPORARY, blob.size, fs => {\n" " fs.root.getFile('foo.html', {create: true}, file => {\n" " file.createWriter(writer => {\n" " writer.write(blob);\n" " writer.onwriteend = () => {\n" " domAutomationController.send(file.toURL());\n" " }\n" " });\n" " });\n" "});\n", &filesystem_url_string)); GURL filesystem_url(filesystem_url_string); EXPECT_TRUE(filesystem_url.is_valid()); EXPECT_TRUE(filesystem_url.SchemeIsFileSystem()); return filesystem_url; } std::string GetTextContent(content::RenderFrameHost* frame) { std::string result; EXPECT_TRUE(ExecuteScriptAndExtractString( frame, "domAutomationController.send(document.body.innerText)", &result)); return result; } // Helper to send a postMessage from |sender| to |opener| via window.opener, // wait for a reply, and verify the response. Defines its own message event // handlers. void VerifyPostMessageToOpener(content::RenderFrameHost* sender, content::RenderFrameHost* opener) { EXPECT_TRUE( ExecuteScript(opener, "window.addEventListener('message', function(event) {\n" " event.source.postMessage(event.data, '*');\n" "});")); EXPECT_TRUE( ExecuteScript(sender, "window.addEventListener('message', function(event) {\n" " window.domAutomationController.send(event.data);\n" "});")); std::string result; EXPECT_TRUE(ExecuteScriptAndExtractString( sender, "opener.postMessage('foo', '*');", &result)); EXPECT_EQ("foo", result); } } // namespace // Takes a snapshot of all frames upon construction. When Wait() is called, a // MessageLoop is created and Quit when all previously recorded frames are // either present in the tab, or deleted. If a navigation happens between the // construction and the Wait() call, then this logic ensures that all obsolete // RenderFrameHosts have been destructed when Wait() returns. // See also the comment at ProcessManagerBrowserTest::NavigateToURL. class NavigationCompletedObserver : public content::WebContentsObserver { public: explicit NavigationCompletedObserver(content::WebContents* web_contents) : content::WebContentsObserver(web_contents), message_loop_runner_(new content::MessageLoopRunner) { web_contents->ForEachFrame( base::Bind(&AddFrameToSet, base::Unretained(&frames_))); } void Wait() { if (!AreAllFramesInTab()) message_loop_runner_->Run(); } void RenderFrameDeleted(content::RenderFrameHost* rfh) override { if (frames_.erase(rfh) != 0 && message_loop_runner_->loop_running() && AreAllFramesInTab()) message_loop_runner_->Quit(); } private: // Check whether all frames that were recorded at the construction of this // class are still part of the tab. bool AreAllFramesInTab() { std::set<content::RenderFrameHost*> current_frames; web_contents()->ForEachFrame( base::Bind(&AddFrameToSet, base::Unretained(&current_frames))); for (content::RenderFrameHost* frame : frames_) { if (current_frames.find(frame) == current_frames.end()) return false; } return true; } std::set<content::RenderFrameHost*> frames_; scoped_refptr<content::MessageLoopRunner> message_loop_runner_; DISALLOW_COPY_AND_ASSIGN(NavigationCompletedObserver); }; // Exists as a browser test because ExtensionHosts are hard to create without // a real browser. class ProcessManagerBrowserTest : public ExtensionBrowserTest { public: ProcessManagerBrowserTest() { guest_view::GuestViewManager::set_factory_for_testing(&factory_); } // Create an extension with web-accessible frames and an optional background // page. const Extension* CreateExtension(const std::string& name, bool has_background_process) { std::unique_ptr<TestExtensionDir> dir(new TestExtensionDir()); DictionaryBuilder manifest; manifest.Set("name", name) .Set("version", "1") .Set("manifest_version", 2) // To allow ExecuteScript* to work. .Set("content_security_policy", "script-src 'self' 'unsafe-eval'; object-src 'self'") .Set("sandbox", DictionaryBuilder() .Set("pages", ListBuilder().Append("sandboxed.html").Build()) .Build()) .Set("web_accessible_resources", ListBuilder().Append("*").Build()); if (has_background_process) { manifest.Set("background", DictionaryBuilder().Set("page", "bg.html").Build()); dir->WriteFile(FILE_PATH_LITERAL("bg.html"), "<iframe id='bgframe' src='empty.html'></iframe>"); } dir->WriteFile(FILE_PATH_LITERAL("blank_iframe.html"), "<iframe id='frame0' src='about:blank'></iframe>"); dir->WriteFile(FILE_PATH_LITERAL("srcdoc_iframe.html"), "<iframe id='frame0' srcdoc='Hello world'></iframe>"); dir->WriteFile(FILE_PATH_LITERAL("two_iframes.html"), "<iframe id='frame1' src='empty.html'></iframe>" "<iframe id='frame2' src='empty.html'></iframe>"); dir->WriteFile(FILE_PATH_LITERAL("sandboxed.html"), "Some sandboxed page"); dir->WriteFile(FILE_PATH_LITERAL("empty.html"), ""); dir->WriteManifest(manifest.ToJSON()); const Extension* extension = LoadExtension(dir->UnpackedPath()); EXPECT_TRUE(extension); temp_dirs_.push_back(std::move(dir)); return extension; } // ui_test_utils::NavigateToURL sometimes returns too early: It returns as // soon as the StopLoading notification has been triggered. This does not // imply that RenderFrameDeleted was called, so the test may continue too // early and fail when ProcessManager::GetAllFrames() returns too many frames // (namely frames that are in the process of being deleted). To work around // this problem, we also wait until all previous frames have been deleted. void NavigateToURL(const GURL& url) { NavigationCompletedObserver observer( browser()->tab_strip_model()->GetActiveWebContents()); ui_test_utils::NavigateToURL(browser(), url); // Wait until the last RenderFrameHosts are deleted. This wait doesn't take // long. observer.Wait(); } size_t IfExtensionsIsolated(size_t if_enabled, size_t if_disabled) { return content::AreAllSitesIsolatedForTesting() || IsIsolateExtensionsEnabled() ? if_enabled : if_disabled; } content::WebContents* OpenPopup(content::RenderFrameHost* opener, const GURL& url) { content::WindowedNotificationObserver popup_observer( chrome::NOTIFICATION_TAB_ADDED, content::NotificationService::AllSources()); EXPECT_TRUE(ExecuteScript( opener, "window.popup = window.open('" + url.spec() + "')")); popup_observer.Wait(); content::WebContents* popup = browser()->tab_strip_model()->GetActiveWebContents(); WaitForLoadStop(popup); EXPECT_EQ(url, popup->GetMainFrame()->GetLastCommittedURL()); return popup; } private: guest_view::TestGuestViewManagerFactory factory_; std::vector<std::unique_ptr<TestExtensionDir>> temp_dirs_; }; // Test that basic extension loading creates the appropriate ExtensionHosts // and background pages. IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest, ExtensionHostCreation) { ProcessManager* pm = ProcessManager::Get(profile()); // We start with no background hosts. ASSERT_EQ(0u, pm->background_hosts().size()); ASSERT_EQ(0u, pm->GetAllFrames().size()); // Load an extension with a background page. scoped_refptr<const Extension> extension = LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("browser_action") .AppendASCII("none")); ASSERT_TRUE(extension.get()); // Process manager gains a background host. EXPECT_EQ(1u, pm->background_hosts().size()); EXPECT_EQ(1u, pm->GetAllFrames().size()); EXPECT_TRUE(pm->GetBackgroundHostForExtension(extension->id())); EXPECT_TRUE(pm->GetSiteInstanceForURL(extension->url())); EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension->id()).size()); EXPECT_FALSE(pm->IsBackgroundHostClosing(extension->id())); EXPECT_EQ(0, pm->GetLazyKeepaliveCount(extension.get())); // Unload the extension. UnloadExtension(extension->id()); // Background host disappears. EXPECT_EQ(0u, pm->background_hosts().size()); EXPECT_EQ(0u, pm->GetAllFrames().size()); EXPECT_FALSE(pm->GetBackgroundHostForExtension(extension->id())); EXPECT_TRUE(pm->GetSiteInstanceForURL(extension->url())); EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension->id()).size()); EXPECT_FALSE(pm->IsBackgroundHostClosing(extension->id())); EXPECT_EQ(0, pm->GetLazyKeepaliveCount(extension.get())); } // Test that loading an extension with a browser action does not create a // background page and that clicking on the action creates the appropriate // ExtensionHost. // Disabled due to flake, see http://crbug.com/315242 IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest, DISABLED_PopupHostCreation) { ProcessManager* pm = ProcessManager::Get(profile()); // Load an extension with the ability to open a popup but no background // page. scoped_refptr<const Extension> popup = LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("browser_action") .AppendASCII("popup")); ASSERT_TRUE(popup.get()); // No background host was added. EXPECT_EQ(0u, pm->background_hosts().size()); EXPECT_EQ(0u, pm->GetAllFrames().size()); EXPECT_FALSE(pm->GetBackgroundHostForExtension(popup->id())); EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(popup->id()).size()); EXPECT_TRUE(pm->GetSiteInstanceForURL(popup->url())); EXPECT_FALSE(pm->IsBackgroundHostClosing(popup->id())); EXPECT_EQ(0, pm->GetLazyKeepaliveCount(popup.get())); // Simulate clicking on the action to open a popup. BrowserActionTestUtil test_util(browser()); content::WindowedNotificationObserver frame_observer( content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); // Open popup in the first extension. test_util.Press(0); frame_observer.Wait(); ASSERT_TRUE(test_util.HasPopup()); // We now have a view, but still no background hosts. EXPECT_EQ(0u, pm->background_hosts().size()); EXPECT_EQ(1u, pm->GetAllFrames().size()); EXPECT_FALSE(pm->GetBackgroundHostForExtension(popup->id())); EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(popup->id()).size()); EXPECT_TRUE(pm->GetSiteInstanceForURL(popup->url())); EXPECT_FALSE(pm->IsBackgroundHostClosing(popup->id())); EXPECT_EQ(0, pm->GetLazyKeepaliveCount(popup.get())); } // Content loaded from http://hlogonemlfkgpejgnedahbkiabcdhnnn should not // interact with an installed extension with that ID. Regression test // for bug 357382. IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest, HttpHostMatchingExtensionId) { ProcessManager* pm = ProcessManager::Get(profile()); // We start with no background hosts. ASSERT_EQ(0u, pm->background_hosts().size()); ASSERT_EQ(0u, pm->GetAllFrames().size()); // Load an extension with a background page. scoped_refptr<const Extension> extension = LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("browser_action") .AppendASCII("none")); // Set up a test server running at http://[extension-id] ASSERT_TRUE(extension.get()); const std::string& aliased_host = extension->id(); host_resolver()->AddRule(aliased_host, "127.0.0.1"); ASSERT_TRUE(embedded_test_server()->Start()); GURL url = embedded_test_server()->GetURL("/extensions/test_file_with_body.html"); GURL::Replacements replace_host; replace_host.SetHostStr(aliased_host); url = url.ReplaceComponents(replace_host); // Load a page from the test host in a new tab. ui_test_utils::NavigateToURLWithDisposition( browser(), url, WindowOpenDisposition::NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); // Sanity check that there's no bleeding between the extension and the tab. content::WebContents* tab_web_contents = browser()->tab_strip_model()->GetActiveWebContents(); EXPECT_EQ(url, tab_web_contents->GetVisibleURL()); EXPECT_FALSE(pm->GetExtensionForWebContents(tab_web_contents)) << "Non-extension content must not have an associated extension"; ASSERT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension->id()).size()); content::WebContents* extension_web_contents = content::WebContents::FromRenderFrameHost( *pm->GetRenderFrameHostsForExtension(extension->id()).begin()); EXPECT_TRUE(extension_web_contents->GetSiteInstance() != tab_web_contents->GetSiteInstance()); EXPECT_TRUE(pm->GetSiteInstanceForURL(extension->url()) != tab_web_contents->GetSiteInstance()); EXPECT_TRUE(pm->GetBackgroundHostForExtension(extension->id())); } IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest, NoBackgroundPage) { ASSERT_TRUE(embedded_test_server()->Start()); ProcessManager* pm = ProcessManager::Get(profile()); const Extension* extension = LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("messaging") .AppendASCII("connect_nobackground")); ASSERT_TRUE(extension); // The extension has no background page. EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension->id()).size()); // Start in a non-extension process, then navigate to an extension process. NavigateToURL(embedded_test_server()->GetURL("/empty.html")); EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension->id()).size()); const GURL extension_url = extension->url().Resolve("manifest.json"); NavigateToURL(extension_url); EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension->id()).size()); NavigateToURL(GURL("about:blank")); EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension->id()).size()); ui_test_utils::NavigateToURLWithDisposition( browser(), extension_url, WindowOpenDisposition::NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension->id()).size()); } // Tests whether frames are correctly classified. Non-extension frames should // never appear in the list. Top-level extension frames should always appear. // Child extension frames should only appear if it is hosted in an extension // process (i.e. if the top-level frame is an extension page, or if OOP frames // are enabled for extensions). IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest, FrameClassification) { const Extension* extension1 = CreateExtension("Extension 1", false); const Extension* extension2 = CreateExtension("Extension 2", true); embedded_test_server()->ServeFilesFromDirectory(extension1->path()); ASSERT_TRUE(embedded_test_server()->Start()); const GURL kExt1TwoFramesUrl(extension1->url().Resolve("two_iframes.html")); const GURL kExt1EmptyUrl(extension1->url().Resolve("empty.html")); const GURL kExt2TwoFramesUrl(extension2->url().Resolve("two_iframes.html")); const GURL kExt2EmptyUrl(extension2->url().Resolve("empty.html")); ProcessManager* pm = ProcessManager::Get(profile()); // 1 background page + 1 frame in background page from Extension 2. BackgroundPageWatcher(pm, extension2).WaitForOpen(); EXPECT_EQ(2u, pm->GetAllFrames().size()); EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension1->id()).size()); EXPECT_EQ(2u, pm->GetRenderFrameHostsForExtension(extension2->id()).size()); ExecuteScriptInBackgroundPageNoWait(extension2->id(), "setTimeout(window.close, 0)"); BackgroundPageWatcher(pm, extension2).WaitForClose(); EXPECT_EQ(0u, pm->GetAllFrames().size()); EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension2->id()).size()); NavigateToURL(embedded_test_server()->GetURL("/two_iframes.html")); EXPECT_EQ(0u, pm->GetAllFrames().size()); content::WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); // Tests extension frames in non-extension page. EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame1", kExt1EmptyUrl)); EXPECT_EQ(IfExtensionsIsolated(1, 0), pm->GetRenderFrameHostsForExtension(extension1->id()).size()); EXPECT_EQ(IfExtensionsIsolated(1, 0), pm->GetAllFrames().size()); EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame2", kExt2EmptyUrl)); EXPECT_EQ(IfExtensionsIsolated(1, 0), pm->GetRenderFrameHostsForExtension(extension2->id()).size()); EXPECT_EQ(IfExtensionsIsolated(2, 0), pm->GetAllFrames().size()); // Tests non-extension page in extension frame. NavigateToURL(kExt1TwoFramesUrl); // 1 top-level + 2 child frames from Extension 1. EXPECT_EQ(3u, pm->GetAllFrames().size()); EXPECT_EQ(3u, pm->GetRenderFrameHostsForExtension(extension1->id()).size()); EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension2->id()).size()); EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame1", embedded_test_server() ->GetURL("/empty.html"))); // 1 top-level + 1 child frame from Extension 1. EXPECT_EQ(2u, pm->GetRenderFrameHostsForExtension(extension1->id()).size()); EXPECT_EQ(2u, pm->GetAllFrames().size()); EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame1", kExt1EmptyUrl)); // 1 top-level + 2 child frames from Extension 1. EXPECT_EQ(3u, pm->GetAllFrames().size()); EXPECT_EQ(3u, pm->GetRenderFrameHostsForExtension(extension1->id()).size()); // Load a frame from another extension. EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame1", kExt2EmptyUrl)); // 1 top-level + 1 child frame from Extension 1, // 1 child frame from Extension 2. EXPECT_EQ(IfExtensionsIsolated(3, 2), pm->GetAllFrames().size()); EXPECT_EQ(2u, pm->GetRenderFrameHostsForExtension(extension1->id()).size()); EXPECT_EQ(IfExtensionsIsolated(1, 0), pm->GetRenderFrameHostsForExtension(extension2->id()).size()); // Destroy all existing frames by navigating to another extension. NavigateToURL(extension2->url().Resolve("empty.html")); EXPECT_EQ(1u, pm->GetAllFrames().size()); EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension1->id()).size()); EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension2->id()).size()); // Test about:blank and about:srcdoc child frames. NavigateToURL(extension2->url().Resolve("srcdoc_iframe.html")); // 1 top-level frame + 1 child frame from Extension 2. EXPECT_EQ(2u, pm->GetAllFrames().size()); EXPECT_EQ(2u, pm->GetRenderFrameHostsForExtension(extension2->id()).size()); NavigateToURL(extension2->url().Resolve("blank_iframe.html")); // 1 top-level frame + 1 child frame from Extension 2. EXPECT_EQ(2u, pm->GetAllFrames().size()); EXPECT_EQ(2u, pm->GetRenderFrameHostsForExtension(extension2->id()).size()); // Sandboxed frames are not viewed as extension frames. EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame0", extension2->url() .Resolve("sandboxed.html"))); // 1 top-level frame from Extension 2. EXPECT_EQ(1u, pm->GetAllFrames().size()); EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension2->id()).size()); NavigateToURL(extension2->url().Resolve("sandboxed.html")); EXPECT_EQ(0u, pm->GetAllFrames().size()); EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension2->id()).size()); // Test nested frames (same extension). NavigateToURL(kExt2TwoFramesUrl); // 1 top-level + 2 child frames from Extension 2. EXPECT_EQ(3u, pm->GetAllFrames().size()); EXPECT_EQ(3u, pm->GetRenderFrameHostsForExtension(extension2->id()).size()); EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame1", kExt2TwoFramesUrl)); // 1 top-level + 2 child frames from Extension 1, // 2 child frames in frame1 from Extension 2. EXPECT_EQ(5u, pm->GetAllFrames().size()); EXPECT_EQ(5u, pm->GetRenderFrameHostsForExtension(extension2->id()).size()); // The extension frame from the other extension should not be classified as an // extension (unless out-of-process frames are enabled). EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame1", kExt1EmptyUrl)); // 1 top-level + 1 child frames from Extension 2, // 1 child frame from Extension 1. EXPECT_EQ(IfExtensionsIsolated(3, 2), pm->GetAllFrames().size()); EXPECT_EQ(IfExtensionsIsolated(1, 0), pm->GetRenderFrameHostsForExtension(extension1->id()).size()); EXPECT_EQ(2u, pm->GetRenderFrameHostsForExtension(extension2->id()).size()); EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame2", kExt1TwoFramesUrl)); // 1 top-level + 1 child frames from Extension 2, // 1 child frame + 2 child frames in frame2 from Extension 1. EXPECT_EQ(IfExtensionsIsolated(5, 1), pm->GetAllFrames().size()); EXPECT_EQ(IfExtensionsIsolated(4, 0), pm->GetRenderFrameHostsForExtension(extension1->id()).size()); EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension2->id()).size()); // Crash tab where the top-level frame is an extension frame. content::CrashTab(tab); EXPECT_EQ(0u, pm->GetAllFrames().size()); EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension1->id()).size()); EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension2->id()).size()); // Now load an extension page and a non-extension page... ui_test_utils::NavigateToURLWithDisposition( browser(), kExt1EmptyUrl, WindowOpenDisposition::NEW_BACKGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); NavigateToURL(embedded_test_server()->GetURL("/two_iframes.html")); EXPECT_EQ(1u, pm->GetAllFrames().size()); // ... load an extension frame in the non-extension process EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame1", kExt1EmptyUrl)); EXPECT_EQ(IfExtensionsIsolated(2, 1), pm->GetRenderFrameHostsForExtension(extension1->id()).size()); // ... and take down the tab. The extension process is not part of the tab, // so it should be kept alive (minus the frames that died). content::CrashTab(tab); EXPECT_EQ(1u, pm->GetAllFrames().size()); EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension1->id()).size()); } // Verify correct keepalive count behavior on network request events. // Regression test for http://crbug.com/535716. IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest, KeepaliveOnNetworkRequest) { // Load an extension with a lazy background page. scoped_refptr<const Extension> extension = LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("lazy_background_page") .AppendASCII("broadcast_event")); ASSERT_TRUE(extension.get()); ProcessManager* pm = ProcessManager::Get(profile()); ProcessManager::FrameSet frames = pm->GetRenderFrameHostsForExtension(extension->id()); ASSERT_EQ(1u, frames.size()); // Keepalive count at this point is unpredictable as there may be an // outstanding event dispatch. We use the current keepalive count as a // reliable baseline for future expectations. int baseline_keepalive = pm->GetLazyKeepaliveCount(extension.get()); // Simulate some network events. This test assumes no other network requests // are pending, i.e., that there are no conflicts with the fake request IDs // we're using. This should be a safe assumption because LoadExtension should // wait for loads to complete, and we don't run the message loop otherwise. content::RenderFrameHost* frame_host = *frames.begin(); pm->OnNetworkRequestStarted(frame_host, 1); EXPECT_EQ(baseline_keepalive + 1, pm->GetLazyKeepaliveCount(extension.get())); pm->OnNetworkRequestDone(frame_host, 1); EXPECT_EQ(baseline_keepalive, pm->GetLazyKeepaliveCount(extension.get())); // Simulate only a request completion for this ID and ensure it doesn't result // in keepalive decrement. pm->OnNetworkRequestDone(frame_host, 2); EXPECT_EQ(baseline_keepalive, pm->GetLazyKeepaliveCount(extension.get())); } IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest, ExtensionProcessReuse) { const size_t kNumExtensions = 3; content::RenderProcessHost::SetMaxRendererProcessCount(kNumExtensions - 1); ProcessManager* pm = ProcessManager::Get(profile()); std::set<int> processes; std::set<const Extension*> installed_extensions; // Create 3 extensions, which is more than the process limit. for (int i = 1; i <= static_cast<int>(kNumExtensions); ++i) { const Extension* extension = CreateExtension(base::StringPrintf("Extension %d", i), true); installed_extensions.insert(extension); ExtensionHost* extension_host = pm->GetBackgroundHostForExtension(extension->id()); EXPECT_EQ(extension->url(), extension_host->host_contents()->GetSiteInstance()->GetSiteURL()); processes.insert(extension_host->render_process_host()->GetID()); } EXPECT_EQ(kNumExtensions, installed_extensions.size()); if (content::AreAllSitesIsolatedForTesting()) { EXPECT_EQ(kNumExtensions, processes.size()) << "Extension process reuse is " "expected to be disabled in " "--site-per-process."; } else { EXPECT_LT(processes.size(), kNumExtensions) << "Expected extension process reuse, but none happened."; } // Interact with each extension background page by setting and reading back // the cookie. This would fail for one of the two extensions in a shared // process, if that process is locked to a single origin. This is a regression // test for http://crbug.com/600441. for (const Extension* extension : installed_extensions) { content::DOMMessageQueue queue; ExecuteScriptInBackgroundPageNoWait( extension->id(), "document.cookie = 'extension_cookie';" "window.domAutomationController.send(document.cookie);"); std::string message; ASSERT_TRUE(queue.WaitForMessage(&message)); EXPECT_EQ(message, "\"extension_cookie\""); } } // Test that navigations to blob: and filesystem: URLs with extension origins // are disallowed when initiated from non-extension processes. See // https://crbug.com/645028 and https://crbug.com/644426. IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest, NestedURLNavigationsToExtensionBlocked) { // Disabling web security is necessary to test the browser enforcement; // without it, the loads in this test would be blocked by // SecurityOrigin::canDisplay() as invalid local resource loads. PrefService* prefs = browser()->profile()->GetPrefs(); prefs->SetBoolean(prefs::kWebKitWebSecurityEnabled, false); // Create a simple extension without a background page. const Extension* extension = CreateExtension("Extension", false); embedded_test_server()->ServeFilesFromDirectory(extension->path()); ASSERT_TRUE(embedded_test_server()->Start()); // Navigate main tab to a web page with two web iframes. There should be no // extension frames yet. NavigateToURL(embedded_test_server()->GetURL("/two_iframes.html")); ProcessManager* pm = ProcessManager::Get(profile()); EXPECT_EQ(0u, pm->GetAllFrames().size()); EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension->id()).size()); content::WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); // Navigate first subframe to an extension URL. With --isolate-extensions, // this will go into a new extension process. const GURL extension_url(extension->url().Resolve("empty.html")); EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame1", extension_url)); EXPECT_EQ(IfExtensionsIsolated(1, 0), pm->GetRenderFrameHostsForExtension(extension->id()).size()); EXPECT_EQ(IfExtensionsIsolated(1, 0), pm->GetAllFrames().size()); content::RenderFrameHost* main_frame = tab->GetMainFrame(); content::RenderFrameHost* extension_frame = ChildFrameAt(main_frame, 0); // Validate that permissions have been granted for the extension scheme // to the process of the extension iframe. content::ChildProcessSecurityPolicy* policy = content::ChildProcessSecurityPolicy::GetInstance(); EXPECT_TRUE(policy->CanRequestURL( extension_frame->GetProcess()->GetID(), GURL("blob:chrome-extension://some-extension-id/some-guid"))); EXPECT_TRUE(policy->CanRequestURL( main_frame->GetProcess()->GetID(), GURL("blob:chrome-extension://some-extension-id/some-guid"))); EXPECT_TRUE(policy->CanRequestURL( extension_frame->GetProcess()->GetID(), GURL("filesystem:chrome-extension://some-extension-id/some-path"))); EXPECT_TRUE(policy->CanRequestURL( main_frame->GetProcess()->GetID(), GURL("filesystem:chrome-extension://some-extension-id/some-path"))); EXPECT_TRUE(policy->CanRequestURL( extension_frame->GetProcess()->GetID(), GURL("chrome-extension://some-extension-id/resource.html"))); EXPECT_TRUE(policy->CanRequestURL( main_frame->GetProcess()->GetID(), GURL("chrome-extension://some-extension-id/resource.html"))); if (IsIsolateExtensionsEnabled()) { EXPECT_TRUE(policy->CanCommitURL( extension_frame->GetProcess()->GetID(), GURL("blob:chrome-extension://some-extension-id/some-guid"))); EXPECT_FALSE(policy->CanCommitURL( main_frame->GetProcess()->GetID(), GURL("blob:chrome-extension://some-extension-id/some-guid"))); EXPECT_TRUE(policy->CanCommitURL( extension_frame->GetProcess()->GetID(), GURL("chrome-extension://some-extension-id/resource.html"))); EXPECT_FALSE(policy->CanCommitURL( main_frame->GetProcess()->GetID(), GURL("chrome-extension://some-extension-id/resource.html"))); EXPECT_TRUE(policy->CanCommitURL( extension_frame->GetProcess()->GetID(), GURL("filesystem:chrome-extension://some-extension-id/some-path"))); EXPECT_FALSE(policy->CanCommitURL( main_frame->GetProcess()->GetID(), GURL("filesystem:chrome-extension://some-extension-id/some-path"))); } // Open a new about:blank popup from main frame. This should stay in the web // process. content::WebContents* popup = OpenPopup(main_frame, GURL(url::kAboutBlankURL)); EXPECT_NE(popup, tab); ASSERT_EQ(2, browser()->tab_strip_model()->count()); EXPECT_EQ(IfExtensionsIsolated(1, 0), pm->GetRenderFrameHostsForExtension(extension->id()).size()); EXPECT_EQ(IfExtensionsIsolated(1, 0), pm->GetAllFrames().size()); // Create valid blob and filesystem URLs in the extension's origin. url::Origin extension_origin(extension_frame->GetLastCommittedOrigin()); GURL blob_url(CreateBlobURL(extension_frame, "foo")); EXPECT_EQ(extension_origin, url::Origin(blob_url)); GURL filesystem_url(CreateFileSystemURL(extension_frame, "foo")); EXPECT_EQ(extension_origin, url::Origin(filesystem_url)); // Navigate the popup to each nested URL with extension origin. GURL nested_urls[] = {blob_url, filesystem_url}; for (size_t i = 0; i < arraysize(nested_urls); i++) { content::TestNavigationObserver observer(popup); EXPECT_TRUE(ExecuteScript( popup, "location.href = '" + nested_urls[i].spec() + "';")); observer.Wait(); // This is a top-level navigation that should be blocked since it // originates from a non-extension process. Ensure that the error page // doesn't commit an extension URL or origin. EXPECT_NE(nested_urls[i], popup->GetLastCommittedURL()); EXPECT_FALSE(extension_origin.IsSameOriginWith( popup->GetMainFrame()->GetLastCommittedOrigin())); EXPECT_NE("foo", GetTextContent(popup->GetMainFrame())); EXPECT_EQ(IfExtensionsIsolated(1, 0), pm->GetRenderFrameHostsForExtension(extension->id()).size()); EXPECT_EQ(IfExtensionsIsolated(1, 0), pm->GetAllFrames().size()); } // Navigate second subframe to each nested URL from the main frame (i.e., // from non-extension process). This should be blocked in // --isolate-extensions, but allowed without --isolate-extensions due to // unblessed extension frames. // // TODO(alexmos): This is also temporarily allowed under PlzNavigate, because // currently this particular blocking happens in // ChromeContentBrowserClientExtensionsPart::ShouldAllowOpenURL, which isn't // triggered below under PlzNavigate (since there'll be no transfer). Once // the blob/filesystem URL checks in ExtensionNavigationThrottle are updated // to apply to all frames and not just main frames, the PlzNavigate exception // below can be removed. See https://crbug.com/661324. for (size_t i = 0; i < arraysize(nested_urls); i++) { EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame2", nested_urls[i])); content::RenderFrameHost* second_frame = ChildFrameAt(main_frame, 1); if (IsIsolateExtensionsEnabled() && !content::IsBrowserSideNavigationEnabled()) { EXPECT_NE(nested_urls[i], second_frame->GetLastCommittedURL()); EXPECT_FALSE(extension_origin.IsSameOriginWith( second_frame->GetLastCommittedOrigin())); EXPECT_NE("foo", GetTextContent(second_frame)); EXPECT_EQ(IfExtensionsIsolated(1, 0), pm->GetRenderFrameHostsForExtension(extension->id()).size()); EXPECT_EQ(IfExtensionsIsolated(1, 0), pm->GetAllFrames().size()); } else { EXPECT_EQ(nested_urls[i], second_frame->GetLastCommittedURL()); EXPECT_EQ(extension_origin, second_frame->GetLastCommittedOrigin()); EXPECT_EQ("foo", GetTextContent(second_frame)); EXPECT_EQ(IfExtensionsIsolated(2, 0), pm->GetRenderFrameHostsForExtension(extension->id()).size()); EXPECT_EQ(IfExtensionsIsolated(2, 0), pm->GetAllFrames().size()); } EXPECT_TRUE( content::NavigateIframeToURL(tab, "frame2", GURL(url::kAboutBlankURL))); } } // Test that navigations to blob: and filesystem: URLs with extension origins // are allowed when initiated from extension processes. See // https://crbug.com/645028 and https://crbug.com/644426. IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest, NestedURLNavigationsToExtensionAllowed) { // Create a simple extension without a background page. const Extension* extension = CreateExtension("Extension", false); embedded_test_server()->ServeFilesFromDirectory(extension->path()); ASSERT_TRUE(embedded_test_server()->Start()); // Navigate main tab to an extension URL with a blank subframe. const GURL extension_url(extension->url().Resolve("blank_iframe.html")); NavigateToURL(extension_url); ProcessManager* pm = ProcessManager::Get(profile()); EXPECT_EQ(2u, pm->GetAllFrames().size()); EXPECT_EQ(2u, pm->GetRenderFrameHostsForExtension(extension->id()).size()); content::WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); content::RenderFrameHost* main_frame = tab->GetMainFrame(); // Create blob and filesystem URLs in the extension's origin. url::Origin extension_origin(main_frame->GetLastCommittedOrigin()); GURL blob_url(CreateBlobURL(main_frame, "foo")); EXPECT_EQ(extension_origin, url::Origin(blob_url)); GURL filesystem_url(CreateFileSystemURL(main_frame, "foo")); EXPECT_EQ(extension_origin, url::Origin(filesystem_url)); // From the main frame, navigate its subframe to each nested URL. This // should be allowed and should stay in the extension process. GURL nested_urls[] = {blob_url, filesystem_url}; for (size_t i = 0; i < arraysize(nested_urls); i++) { EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame0", nested_urls[i])); content::RenderFrameHost* child = ChildFrameAt(main_frame, 0); EXPECT_EQ(nested_urls[i], child->GetLastCommittedURL()); EXPECT_EQ(extension_origin, child->GetLastCommittedOrigin()); EXPECT_EQ("foo", GetTextContent(child)); EXPECT_EQ(2u, pm->GetRenderFrameHostsForExtension(extension->id()).size()); EXPECT_EQ(2u, pm->GetAllFrames().size()); } // From the main frame, create a blank popup and navigate it to each nested // URL. This should also be allowed, since the navigation originated from an // extension process. for (size_t i = 0; i < arraysize(nested_urls); i++) { content::WebContents* popup = OpenPopup(main_frame, GURL(url::kAboutBlankURL)); EXPECT_NE(popup, tab); content::TestNavigationObserver observer(popup); EXPECT_TRUE(ExecuteScript( popup, "location.href = '" + nested_urls[i].spec() + "';")); observer.Wait(); EXPECT_EQ(nested_urls[i], popup->GetLastCommittedURL()); EXPECT_EQ(extension_origin, popup->GetMainFrame()->GetLastCommittedOrigin()); EXPECT_EQ("foo", GetTextContent(popup->GetMainFrame())); EXPECT_EQ(3 + i, pm->GetRenderFrameHostsForExtension(extension->id()).size()); EXPECT_EQ(3 + i, pm->GetAllFrames().size()); } } // Test that navigations to blob: and filesystem: URLs with extension origins // are disallowed in an unprivileged, non-guest web process when the extension // origin corresponds to a Chrome app with the "webview" permission. See // https://crbug.com/656752. These requests should still be allowed inside // actual <webview> guest processes created by a Chrome app; this is checked in // WebViewTest.Shim_TestBlobURL. IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest, NestedURLNavigationsToAppBlocked) { // TODO(alexmos): Re-enable this test for PlzNavigate after tightening // nested URL blocking for apps with the "webview" permission in // ExtensionNavigationThrottle and removing the corresponding check from // ChromeExtensionsNetworkDelegate. The latter is incompatible with // PlzNavigate. if (content::IsBrowserSideNavigationEnabled()) return; // Disabling web security is necessary to test the browser enforcement; // without it, the loads in this test would be blocked by // SecurityOrigin::canDisplay() as invalid local resource loads. PrefService* prefs = browser()->profile()->GetPrefs(); prefs->SetBoolean(prefs::kWebKitWebSecurityEnabled, false); // Load a simple app that has the "webview" permission. The app will also // open a <webview> when it's loaded. ASSERT_TRUE(embedded_test_server()->Start()); base::FilePath dir; PathService::Get(chrome::DIR_TEST_DATA, &dir); dir = dir.AppendASCII("extensions") .AppendASCII("platform_apps") .AppendASCII("web_view") .AppendASCII("simple"); const Extension* app = LoadAndLaunchApp(dir); EXPECT_TRUE(app->permissions_data()->HasAPIPermission( extensions::APIPermission::kWebView)); auto app_windows = AppWindowRegistry::Get(browser()->profile()) ->GetAppWindowsForApp(app->id()); EXPECT_EQ(1u, app_windows.size()); content::WebContents* app_tab = (*app_windows.begin())->web_contents(); content::RenderFrameHost* app_rfh = app_tab->GetMainFrame(); url::Origin app_origin(app_rfh->GetLastCommittedOrigin()); EXPECT_EQ(url::Origin(app->url()), app_rfh->GetLastCommittedOrigin()); // Wait for the app's guest WebContents to load. guest_view::TestGuestViewManager* guest_manager = static_cast<guest_view::TestGuestViewManager*>( guest_view::TestGuestViewManager::FromBrowserContext( browser()->profile())); content::WebContents* guest = guest_manager->WaitForSingleGuestCreated(); // There should be two extension frames in ProcessManager: the app's main // page and the background page. ProcessManager* pm = ProcessManager::Get(profile()); EXPECT_EQ(2u, pm->GetAllFrames().size()); EXPECT_EQ(2u, pm->GetRenderFrameHostsForExtension(app->id()).size()); // Create valid blob and filesystem URLs in the app's origin. GURL blob_url(CreateBlobURL(app_rfh, "foo")); EXPECT_EQ(app_origin, url::Origin(blob_url)); GURL filesystem_url(CreateFileSystemURL(app_rfh, "foo")); EXPECT_EQ(app_origin, url::Origin(filesystem_url)); // Create a new tab, unrelated to the app, and navigate it to a web URL. chrome::NewTab(browser()); content::WebContents* web_tab = browser()->tab_strip_model()->GetActiveWebContents(); GURL web_url(embedded_test_server()->GetURL("/title1.html")); ui_test_utils::NavigateToURL(browser(), web_url); EXPECT_NE(web_tab, app_tab); EXPECT_NE(web_tab->GetMainFrame()->GetProcess(), app_rfh->GetProcess()); // The web process shouldn't have permission to request URLs in the app's // origin, but the guest process should. content::ChildProcessSecurityPolicy* policy = content::ChildProcessSecurityPolicy::GetInstance(); EXPECT_FALSE(policy->HasSpecificPermissionForOrigin( web_tab->GetRenderProcessHost()->GetID(), app_origin)); EXPECT_TRUE(policy->HasSpecificPermissionForOrigin( guest->GetRenderProcessHost()->GetID(), app_origin)); // Try navigating the web tab to each nested URL with the app's origin. This // should be blocked. GURL nested_urls[] = {blob_url, filesystem_url}; for (size_t i = 0; i < arraysize(nested_urls); i++) { content::TestNavigationObserver observer(web_tab); EXPECT_TRUE(ExecuteScript( web_tab, "location.href = '" + nested_urls[i].spec() + "';")); observer.Wait(); EXPECT_NE(nested_urls[i], web_tab->GetLastCommittedURL()); EXPECT_FALSE(app_origin.IsSameOriginWith( web_tab->GetMainFrame()->GetLastCommittedOrigin())); EXPECT_NE("foo", GetTextContent(web_tab->GetMainFrame())); EXPECT_NE(web_tab->GetMainFrame()->GetProcess(), app_rfh->GetProcess()); EXPECT_EQ(2u, pm->GetAllFrames().size()); EXPECT_EQ(2u, pm->GetRenderFrameHostsForExtension(app->id()).size()); } } // Test that a web frame can't navigate a proxy for an extension frame to a // blob/filesystem extension URL. See https://crbug.com/656752. IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest, NestedURLNavigationsViaProxyBlocked) { base::HistogramTester uma; // Create a simple extension without a background page. const Extension* extension = CreateExtension("Extension", false); embedded_test_server()->ServeFilesFromDirectory(extension->path()); ASSERT_TRUE(embedded_test_server()->Start()); // Navigate main tab to an empty web page. There should be no extension // frames yet. NavigateToURL(embedded_test_server()->GetURL("/empty.html")); ProcessManager* pm = ProcessManager::Get(profile()); EXPECT_EQ(0u, pm->GetAllFrames().size()); EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension->id()).size()); content::WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); content::RenderFrameHost* main_frame = tab->GetMainFrame(); // Open a new about:blank popup from main frame. This should stay in the web // process. content::WebContents* popup = OpenPopup(main_frame, GURL(url::kAboutBlankURL)); EXPECT_NE(popup, tab); ASSERT_EQ(2, browser()->tab_strip_model()->count()); EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension->id()).size()); EXPECT_EQ(0u, pm->GetAllFrames().size()); // Navigate popup to an extension page. const GURL extension_url(extension->url().Resolve("empty.html")); content::TestNavigationObserver observer(popup); EXPECT_TRUE( ExecuteScript(popup, "location.href = '" + extension_url.spec() + "';")); observer.Wait(); EXPECT_EQ(1u, pm->GetAllFrames().size()); EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension->id()).size()); content::RenderFrameHost* extension_frame = popup->GetMainFrame(); // Create valid blob and filesystem URLs in the extension's origin. url::Origin extension_origin(extension_frame->GetLastCommittedOrigin()); GURL blob_url(CreateBlobURL(extension_frame, "foo")); EXPECT_EQ(extension_origin, url::Origin(blob_url)); GURL filesystem_url(CreateFileSystemURL(extension_frame, "foo")); EXPECT_EQ(extension_origin, url::Origin(filesystem_url)); // Have the web page navigate the popup to each nested URL with extension // origin via the window reference it obtained earlier from window.open. GURL nested_urls[] = {blob_url, filesystem_url}; for (size_t i = 0; i < arraysize(nested_urls); i++) { EXPECT_TRUE(ExecuteScript( tab, "window.popup.location.href = '" + nested_urls[i].spec() + "';")); WaitForLoadStop(popup); // This is a top-level navigation that should be blocked since it // originates from a non-extension process. Ensure that the popup stays at // the original page and doesn't navigate to the nested URL. EXPECT_NE(nested_urls[i], popup->GetLastCommittedURL()); EXPECT_NE("foo", GetTextContent(popup->GetMainFrame())); EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension->id()).size()); EXPECT_EQ(1u, pm->GetAllFrames().size()); } // Verify that the blocking was recorded correctly in UMA. uma.ExpectTotalCount("Extensions.ShouldAllowOpenURL.Failure", 2); uma.ExpectBucketCount("Extensions.ShouldAllowOpenURL.Failure", 0 /* FAILURE_FILE_SYSTEM_URL */, 1); uma.ExpectBucketCount("Extensions.ShouldAllowOpenURL.Failure", 1 /* FAILURE_BLOB_URL */, 1); } // Verify that a web popup created via window.open from an extension page can // communicate with the extension page via window.opener. See // https://crbug.com/590068. IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest, WebPopupFromExtensionMainFrameHasValidOpener) { // Create a simple extension without a background page. const Extension* extension = CreateExtension("Extension", false); embedded_test_server()->ServeFilesFromDirectory(extension->path()); ASSERT_TRUE(embedded_test_server()->Start()); // Navigate main tab to an extension page. NavigateToURL(extension->GetResourceURL("empty.html")); ProcessManager* pm = ProcessManager::Get(profile()); EXPECT_EQ(1u, pm->GetAllFrames().size()); EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension->id()).size()); content::WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); content::RenderFrameHost* main_frame = tab->GetMainFrame(); // Open a new web popup from the extension tab. The popup should go into a // new process. GURL popup_url(embedded_test_server()->GetURL("/empty.html")); content::WebContents* popup = OpenPopup(main_frame, popup_url); EXPECT_NE(popup, tab); ASSERT_EQ(2, browser()->tab_strip_model()->count()); EXPECT_NE(popup->GetRenderProcessHost(), main_frame->GetProcess()); // Ensure the popup's window.opener is defined. bool is_opener_defined = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( popup, "window.domAutomationController.send(!!window.opener)", &is_opener_defined)); EXPECT_TRUE(is_opener_defined); // Verify that postMessage to window.opener works. VerifyPostMessageToOpener(popup->GetMainFrame(), main_frame); } // Verify that a web popup created via window.open from an extension subframe // can communicate with the extension page via window.opener. Similar to the // test above, but for subframes. See https://crbug.com/590068. IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest, WebPopupFromExtensionSubframeHasValidOpener) { // This test only makes sense if OOPIFs are enabled for extension subframes. if (!IsIsolateExtensionsEnabled()) return; // Create a simple extension without a background page. const Extension* extension = CreateExtension("Extension", false); embedded_test_server()->ServeFilesFromDirectory(extension->path()); ASSERT_TRUE(embedded_test_server()->Start()); // Navigate main tab to a web page with a blank iframe. There should be no // extension frames yet. NavigateToURL(embedded_test_server()->GetURL("/blank_iframe.html")); ProcessManager* pm = ProcessManager::Get(profile()); EXPECT_EQ(0u, pm->GetAllFrames().size()); EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension->id()).size()); content::WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); // Navigate first subframe to an extension URL. const GURL extension_url(extension->GetResourceURL("empty.html")); EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame0", extension_url)); EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension->id()).size()); EXPECT_EQ(1u, pm->GetAllFrames().size()); content::RenderFrameHost* main_frame = tab->GetMainFrame(); content::RenderFrameHost* extension_frame = ChildFrameAt(main_frame, 0); // Open a new web popup from extension frame. The popup should go into main // frame's web process. GURL popup_url(embedded_test_server()->GetURL("/empty.html")); content::WebContents* popup = OpenPopup(extension_frame, popup_url); EXPECT_NE(popup, tab); ASSERT_EQ(2, browser()->tab_strip_model()->count()); EXPECT_NE(popup->GetRenderProcessHost(), extension_frame->GetProcess()); EXPECT_EQ(popup->GetRenderProcessHost(), main_frame->GetProcess()); // Ensure the popup's window.opener is defined. bool is_opener_defined = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( popup, "window.domAutomationController.send(!!window.opener)", &is_opener_defined)); EXPECT_TRUE(is_opener_defined); // Verify that postMessage to window.opener works. VerifyPostMessageToOpener(popup->GetMainFrame(), extension_frame); } } // namespace extensions
45.522298
80
0.715273
26362cf965b782026e910ea37ae72d445615cf61
227
hpp
C++
all.hpp
cslauritsen/MyThermostat
a0c888a75c1368c9949e1de8cfc6d75c1d8e735c
[ "Apache-2.0" ]
null
null
null
all.hpp
cslauritsen/MyThermostat
a0c888a75c1368c9949e1de8cfc6d75c1d8e735c
[ "Apache-2.0" ]
null
null
null
all.hpp
cslauritsen/MyThermostat
a0c888a75c1368c9949e1de8cfc6d75c1d8e735c
[ "Apache-2.0" ]
null
null
null
#include "MyThermostat.hpp" #if defined(__APPLE__) || defined(__linux) #include <fstream> #include <iostream> #include <ostream> #endif #if defined(__linux) || defined(ARDUINO) #include <stdint.h> #include <string.h> #endif
16.214286
42
0.726872
26367fe60b048fc01d1f38111277b3133f7ce0ca
1,541
cpp
C++
src/kudu/rest/test/Tests.cpp
khazarmammadli/kudu
ab574903430fafd0a536ee2e185b19e57ed9e39f
[ "Apache-2.0" ]
null
null
null
src/kudu/rest/test/Tests.cpp
khazarmammadli/kudu
ab574903430fafd0a536ee2e185b19e57ed9e39f
[ "Apache-2.0" ]
null
null
null
src/kudu/rest/test/Tests.cpp
khazarmammadli/kudu
ab574903430fafd0a536ee2e185b19e57ed9e39f
[ "Apache-2.0" ]
null
null
null
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 "MyControllerTest.h" #include <iostream> void runTests() { OATPP_RUN_TEST(MyControllerTest); } int main() { oatpp::base::Environment::init(); runTests(); /* Print how much objects were created during app running, and what have left-probably leaked */ /* Disable object counting for release builds using '-D OATPP_DISABLE_ENV_OBJECT_COUNTERS' flag for better performance */ std::cout << "\nEnvironment:\n"; std::cout << "objectsCount = " << oatpp::base::Environment::getObjectsCount() << "\n"; std::cout << "objectsCreated = " << oatpp::base::Environment::getObjectsCreated() << "\n\n"; OATPP_ASSERT(oatpp::base::Environment::getObjectsCount() == 0); oatpp::base::Environment::destroy(); return 0; }
35.022727
123
0.726152
263699fa55fc119416ee683d5055f8412dd30d02
1,219
hpp
C++
D01/ex08/Human.hpp
amoinier/piscine-cpp
43d4806d993eb712f49a32e54646d8c058a569ea
[ "MIT" ]
null
null
null
D01/ex08/Human.hpp
amoinier/piscine-cpp
43d4806d993eb712f49a32e54646d8c058a569ea
[ "MIT" ]
null
null
null
D01/ex08/Human.hpp
amoinier/piscine-cpp
43d4806d993eb712f49a32e54646d8c058a569ea
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Human.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: amoinier <amoinier@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/10/03 16:26:56 by amoinier #+# #+# */ /* Updated: 2017/10/03 17:20:37 by amoinier ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef HUMAN_HPP # define HUMAN_HPP # include <iostream> class Human { private: void meleeAttack(std::string const & target); void rangedAttack(std::string const & target); void intimidatingShout(std::string const & target); public: void action(std::string const & action_name, std::string const & target); }; #endif
39.322581
80
0.279737
26392813434506c75d8fc68707a06bcadc556151
410
hh
C++
src/Zynga/Framework/ShardedDatabase/V3/Test/UserSharded/Config/Mock/Base/NoPassword.hh
ssintzz/zynga-hacklang-framework
9e165068f16f224edf2ee5bf5e25855714792d54
[ "MIT" ]
19
2018-04-23T09:30:48.000Z
2022-03-06T21:35:18.000Z
src/Zynga/Framework/ShardedDatabase/V3/Test/UserSharded/Config/Mock/Base/NoPassword.hh
ssintzz/zynga-hacklang-framework
9e165068f16f224edf2ee5bf5e25855714792d54
[ "MIT" ]
22
2017-11-27T23:39:25.000Z
2019-08-09T08:56:57.000Z
src/Zynga/Framework/ShardedDatabase/V3/Test/UserSharded/Config/Mock/Base/NoPassword.hh
ssintzz/zynga-hacklang-framework
9e165068f16f224edf2ee5bf5e25855714792d54
[ "MIT" ]
28
2017-11-16T20:53:56.000Z
2021-01-04T11:13:17.000Z
<?hh // strict namespace Zynga\Framework\ShardedDatabase\V3\Test\UserSharded\Config\Mock\Base; use Zynga\Framework\ShardedDatabase\V3\Config\Mock\Base as ConfigBase ; use Zynga\Framework\ShardedDatabase\V3\ConnectionDetails; class NoPassword extends ConfigBase { public function shardsInit(): bool { $this->addServer(new ConnectionDetails('someusername', '', 'locahost', 0)); return true; } }
25.625
79
0.760976
2639ce8bd22d52aa9a2ac8021a704d0eae2e64ee
3,758
cc
C++
frontend/lex/numbers.cc
asoffer/icarus
5c9af79d1a39e14d95da1adacbdd7392908eedc5
[ "Apache-2.0" ]
10
2015-10-28T18:54:41.000Z
2021-12-29T16:48:31.000Z
frontend/lex/numbers.cc
asoffer/icarus
5c9af79d1a39e14d95da1adacbdd7392908eedc5
[ "Apache-2.0" ]
95
2020-02-27T22:34:02.000Z
2022-03-06T19:45:24.000Z
frontend/lex/numbers.cc
asoffer/icarus
5c9af79d1a39e14d95da1adacbdd7392908eedc5
[ "Apache-2.0" ]
2
2019-02-01T23:16:04.000Z
2020-02-27T16:06:02.000Z
#include "frontend/lex/numbers.h" #include <string> #include <string_view> #include <variant> namespace frontend { namespace { template <int Base> int64_t DigitInBase(char c) { if constexpr (Base == 10) { return ('0' <= c and c <= '9') ? (c - '0') : -1; } else if constexpr (Base == 2) { return ((c | 1) == '1') ? (c - '0') : -1; } else if constexpr (Base == 8) { return ((c | 7) == '7') ? (c - '0') : -1; } else if constexpr (Base == 16) { int digit = DigitInBase<10>(c); if (digit != -1) { return digit; } if ('A' <= c and c <= 'F') { return c - 'A' + 10; } if ('a' <= c and c <= 'f') { return c - 'a' + 10; } return -1; } } template <int Base> bool IntRepresentableInBase(std::string_view s) { if constexpr (Base == 10) { // TODO this is specific to 64-bit integers. return s.size() < 19 or (s.size() == 19 and s <= "9223372036854775807"); } else if constexpr (Base == 2) { return s.size() < kMaxIntBytes * 8; } else if constexpr (Base == 8) { constexpr const char kFirstCharLimit[] = "371"; return (s.size() < (kMaxIntBytes * 8 / 3)) or (s.size() == kMaxIntBytes and s[0] <= kFirstCharLimit[kMaxIntBytes % 3]); } else if constexpr (Base == 16) { return (s.size() < kMaxIntBytes) or (s.size() == kMaxIntBytes and s[0] <= '7'); } } template <int Base> std::variant<ir::Integer, double, NumberParsingError> ParseIntInBase( std::string_view s) { if (not IntRepresentableInBase<Base>(s)) { return NumberParsingError::kTooLarge; } ir::Integer result = 0; for (char c : s) { int64_t digit = DigitInBase<Base>(c); if (digit == -1) { return NumberParsingError::kInvalidDigit; } result = result * Base + digit; } return result; } template <int Base> std::variant<ir::Integer, double, NumberParsingError> ParseRealInBase( std::string_view s, int dot) { int64_t int_part = 0; for (int i = 0; i < dot; ++i) { int64_t digit = DigitInBase<Base>(s[i]); if (digit == -1) { return NumberParsingError::kInvalidDigit; } int_part = int_part * Base + digit; } int64_t frac_part = 0; int64_t exp = 1; for (size_t i = dot + 1; i < s.size(); ++i) { int64_t digit = DigitInBase<Base>(s[i]); if (digit == -1) { return NumberParsingError::kInvalidDigit; } exp *= Base; frac_part = frac_part * Base + digit; } return int_part + static_cast<double>(frac_part) / exp; } template <int Base> std::variant<ir::Integer, double, NumberParsingError> ParseNumberInBase( std::string_view sv) { std::string copy; for (char c : sv) { if (c != '_') { copy.push_back(c); } } int first_dot = -1; size_t num_dots = 0; for (size_t i = 0; i < copy.size(); ++i) { if (copy[i] != '.') { continue; } if (num_dots++ == 0) { first_dot = i; } } if (num_dots == copy.size()) { // TODO better error message here return NumberParsingError::kNoDigits; } switch (num_dots) { case 0: return ParseIntInBase<Base>(copy); case 1: return ParseRealInBase<Base>(copy, first_dot); default: return NumberParsingError::kTooManyDots; } } } // namespace std::variant<ir::Integer, double, NumberParsingError> ParseNumber( std::string_view sv) { if (sv.size() > 1 and sv[0] == '0') { if (sv[1] == '.') { return ParseNumberInBase<10>(sv); } char base = sv[1]; sv.remove_prefix(2); switch (base) { case 'b': return ParseNumberInBase<2>(sv); case 'o': return ParseNumberInBase<8>(sv); case 'd': return ParseNumberInBase<10>(sv); case 'x': return ParseNumberInBase<16>(sv); default: return NumberParsingError::kUnknownBase; } } else { return ParseNumberInBase<10>(sv); } } } // namespace frontend
29.825397
76
0.598457
264181320de5d2983bce174e8145ccfaa5602aef
3,961
cpp
C++
poprithms/tests/tests/schedule/shift/graph_hash.cpp
graphcore/poprithms
9975a6a343891e3c5f8968a9507261c1185029ed
[ "MIT" ]
24
2020-07-06T17:11:30.000Z
2022-01-01T07:39:12.000Z
poprithms/tests/tests/schedule/shift/graph_hash.cpp
graphcore/poprithms
9975a6a343891e3c5f8968a9507261c1185029ed
[ "MIT" ]
null
null
null
poprithms/tests/tests/schedule/shift/graph_hash.cpp
graphcore/poprithms
9975a6a343891e3c5f8968a9507261c1185029ed
[ "MIT" ]
2
2020-07-15T12:33:22.000Z
2021-07-27T06:07:16.000Z
// Copyright (c) 2021 Graphcore Ltd. All rights reserved. #include <iostream> #include <string> #include <poprithms/error/error.hpp> #include <poprithms/schedule/shift/graph.hpp> namespace { using namespace poprithms::schedule::shift; void test0() { Graph g0; /* * * A B (allocs) * : : * : : * a --> b (ops) * | * v * c ==> d (ops) * * */ auto a = g0.insertOp("a"); auto b = g0.insertOp("b"); auto c = g0.insertOp("c"); auto d = g0.insertOp("d"); g0.insertConstraint(a, b); g0.insertConstraint(a, c); g0.insertLink(c, d); auto A = g0.insertAlloc(100.); auto B = g0.insertAlloc(200.); g0.insertOpAlloc(a, A); g0.insertOpAlloc(b, B); // Exact copy: { const auto g1 = g0; if (g0.hash(true) != g1.hash(true)) { throw poprithms::test::error( "g0 == g1 but g0.hash(true) != g1.hash(true)"); } if (g0.hash(false) != g1.hash(false)) { throw poprithms::test::error( "g0 == g1 but g0.hash(false) != g1.hash(false)"); } } // Extra constraint: { auto g1 = g0; g1.insertConstraint(b, d); if (g0.hash(true) == g1.hash(true)) { throw poprithms::test::error( "g1 has an extra constraint, but g0.hash(true) == g1.hash(true)"); } if (g0.hash(false) == g1.hash(false)) { throw poprithms::test::error( "g1 has an extra constraint, but g0.hash(false) == g1.hash(false)"); } } // Extra op: { auto g1 = g0; g1.insertOp("extra"); if (g0.hash(true) == g1.hash(true)) { throw poprithms::test::error( "g1 has an extra op, but g0.hash(true) == g1.hash(true)"); } if (g0.hash(false) == g1.hash(false)) { throw poprithms::test::error( "g1 has an extra op, but g0.hash(false) == g1.hash(false)"); } } // Extra link: { auto g1 = g0; g1.insertLink(a, b); if (g0.hash(true) == g1.hash(true)) { throw poprithms::test::error( "g1 has an extra link, but g0.hash(true) == g1.hash(true)"); } if (g0.hash(false) == g1.hash(false)) { throw poprithms::test::error( "g1 has an extra link, but g0.hash(false) == g1.hash(false)"); } } // Names differ on 1 op: { auto g1 = g0; g1.insertOp("foo"); auto g2 = g0; g2.insertOp("bar"); if (g1.hash(true) == g2.hash(true)) { throw poprithms::test::error( "g1 and g2 use different names, but g1.hash(true) == " "g2.hash(true)"); } if (g1.hash(false) != g2.hash(false)) { throw poprithms::test::error( "g1 and g2 use different names only, but g1.hash(false) != " "g2.hash(false)"); } } // alloc values differ on 1 alloc { auto g1 = g0; g1.insertAlloc(5); auto g2 = g0; g2.insertAlloc(6); if (g1.hash(true) == g2.hash(true)) { throw poprithms::test::error( "g1 and g2 do not have the same allocs, but g1.hash(true) " "== g2.hash(true)"); } if (g1.hash(false) == g2.hash(false)) { throw poprithms::test::error( "g1 and g2 do not have the same allocs, but g1.hash(false) " "== g2.hash(false)"); } } // allocs assigned to different ops { auto g1 = g0; { auto C = g1.insertAlloc(5); g1.insertOpAlloc(c, C); } auto g2 = g0; { auto D = g2.insertAlloc(5); g2.insertOpAlloc(d, D); } if (g1.hash(true) == g2.hash(true)) { throw poprithms::test::error( "The 2 Graphs are not the same, the final alloc is " "assigned to different Ops, but g1.hash(true) == g2.hash(true)"); } if (g1.hash(false) == g2.hash(false)) { throw poprithms::test::error( "The 2 Graphs are not the same, the final alloc is " "assigned to different Ops, but g1.hash(false) == g2.hash(false)"); } } } } // namespace int main() { test0(); return 0; }
23.718563
78
0.537743
2642b315fe73e455b2c5d384f3fc2e63eff319e5
26,959
cc
C++
tensorstore/driver/neuroglancer_precomputed/driver.cc
google/tensorstore
8df16a67553debaec098698ceaa5404eaf79634a
[ "BSD-2-Clause" ]
106
2020-04-02T20:00:18.000Z
2022-03-23T20:27:31.000Z
tensorstore/driver/neuroglancer_precomputed/driver.cc
0xgpapad/tensorstore
dfc2972e54588a7b745afea8b9322b57b26b657a
[ "BSD-2-Clause" ]
28
2020-04-12T02:04:47.000Z
2022-03-23T20:27:03.000Z
tensorstore/driver/neuroglancer_precomputed/driver.cc
0xgpapad/tensorstore
dfc2972e54588a7b745afea8b9322b57b26b657a
[ "BSD-2-Clause" ]
18
2020-04-08T06:41:30.000Z
2022-02-18T03:05:49.000Z
// Copyright 2020 The TensorStore Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "tensorstore/driver/driver.h" #include "absl/strings/str_cat.h" #include "tensorstore/context.h" #include "tensorstore/data_type.h" #include "tensorstore/driver/kvs_backed_chunk_driver.h" #include "tensorstore/driver/neuroglancer_precomputed/chunk_encoding.h" #include "tensorstore/driver/neuroglancer_precomputed/metadata.h" #include "tensorstore/driver/neuroglancer_precomputed/uint64_sharded_key_value_store.h" #include "tensorstore/driver/registry.h" #include "tensorstore/index.h" #include "tensorstore/index_space/index_transform_builder.h" #include "tensorstore/internal/cache/cache_key.h" #include "tensorstore/internal/cache/chunk_cache.h" #include "tensorstore/internal/json.h" #include "tensorstore/internal/path.h" #include "tensorstore/kvstore/kvstore.h" #include "tensorstore/tensorstore.h" #include "tensorstore/util/constant_vector.h" #include "tensorstore/util/division.h" #include "tensorstore/util/future.h" namespace tensorstore { namespace internal_neuroglancer_precomputed { namespace { namespace jb = tensorstore::internal_json_binding; using internal_kvs_backed_chunk_driver::KvsDriverSpec; class NeuroglancerPrecomputedDriverSpec : public internal::RegisteredDriverSpec<NeuroglancerPrecomputedDriverSpec, KvsDriverSpec> { public: using Base = internal::RegisteredDriverSpec<NeuroglancerPrecomputedDriverSpec, KvsDriverSpec>; constexpr static char id[] = "neuroglancer_precomputed"; OpenConstraints open_constraints; constexpr static auto ApplyMembers = [](auto& x, auto f) { return f(internal::BaseCast<KvsDriverSpec>(x), x.open_constraints); }; static inline const auto default_json_binder = jb::Sequence( internal_kvs_backed_chunk_driver::SpecJsonBinder, [](auto is_loading, auto options, auto* obj, auto* j) { options.Set(obj->schema.dtype()); return jb::DefaultBinder<>(is_loading, options, &obj->open_constraints, j); }, jb::Initialize([](auto* obj) { TENSORSTORE_RETURN_IF_ERROR(obj->schema.Set(RankConstraint{4})); TENSORSTORE_RETURN_IF_ERROR( obj->schema.Set(obj->open_constraints.multiscale.dtype)); return absl::OkStatus(); })); absl::Status ApplyOptions(SpecOptions&& options) override { if (options.minimal_spec) { open_constraints.scale = ScaleMetadataConstraints{}; open_constraints.multiscale = MultiscaleMetadataConstraints{}; } return Base::ApplyOptions(std::move(options)); } Result<IndexDomain<>> GetDomain() const override { return GetEffectiveDomain(/*existing_metadata=*/nullptr, open_constraints, schema); } Result<CodecSpec::Ptr> GetCodec() const override { TENSORSTORE_ASSIGN_OR_RETURN(auto codec, GetEffectiveCodec(open_constraints, schema)); return CodecSpec::Ptr(std::move(codec)); } Result<ChunkLayout> GetChunkLayout() const override { TENSORSTORE_ASSIGN_OR_RETURN( auto domain_and_chunk_layout, GetEffectiveDomainAndChunkLayout(/*existing_metadata=*/nullptr, open_constraints, schema)); return domain_and_chunk_layout.second; } Result<SharedArray<const void>> GetFillValue( IndexTransformView<> transform) const override { return {std::in_place}; } Result<DimensionUnitsVector> GetDimensionUnits() const override { return GetEffectiveDimensionUnits(open_constraints, schema); } Future<internal::Driver::Handle> Open( internal::OpenTransactionPtr transaction, ReadWriteMode read_write_mode) const override; }; Result<std::shared_ptr<const MultiscaleMetadata>> ParseEncodedMetadata( std::string_view encoded_value) { nlohmann::json raw_data = nlohmann::json::parse(encoded_value, nullptr, /*allow_exceptions=*/false); if (raw_data.is_discarded()) { return absl::FailedPreconditionError("Invalid JSON"); } TENSORSTORE_ASSIGN_OR_RETURN(auto metadata, MultiscaleMetadata::FromJson(raw_data)); return std::make_shared<MultiscaleMetadata>(std::move(metadata)); } class MetadataCache : public internal_kvs_backed_chunk_driver::MetadataCache { using Base = internal_kvs_backed_chunk_driver::MetadataCache; public: using Base::Base; std::string GetMetadataStorageKey(std::string_view entry_key) override { return tensorstore::StrCat(entry_key, kMetadataKey); } Result<MetadataPtr> DecodeMetadata(std::string_view entry_key, absl::Cord encoded_metadata) override { return ParseEncodedMetadata(encoded_metadata.Flatten()); } Result<absl::Cord> EncodeMetadata(std::string_view entry_key, const void* metadata) override { return absl::Cord( ::nlohmann::json(*static_cast<const MultiscaleMetadata*>(metadata)) .dump()); } }; /// Defines common DataCache behavior for the Neuroglancer precomputed driver /// for both the unsharded and sharded formats. /// /// In the metadata `"size"` and `"chunk_sizes"` fields, dimensions are listed /// in `(x, y, z)` order, and in the chunk keys, dimensions are also listed in /// `(x, y, z)` order. Within encoded chunks, data is stored in /// `(x, y, z, channel)` Fortran order. For consistency, the default dimension /// order exposed to users is also `(x, y, z, channel)`. Because the chunk /// cache always stores each chunk component in C order, we use the reversed /// `(channel, z, y, x)` order for the component, and then permute the /// dimensions in `{Ex,In}ternalizeTransform`. class DataCacheBase : public internal_kvs_backed_chunk_driver::DataCache { using Base = internal_kvs_backed_chunk_driver::DataCache; public: explicit DataCacheBase(Initializer initializer, std::string_view key_prefix, const MultiscaleMetadata& metadata, std::size_t scale_index, std::array<Index, 3> chunk_size_xyz) : Base(std::move(initializer), GetChunkGridSpecification(metadata, scale_index, chunk_size_xyz)), key_prefix_(key_prefix), scale_index_(scale_index) { chunk_layout_czyx_.shape()[0] = metadata.num_channels; for (int i = 0; i < 3; ++i) { chunk_layout_czyx_.shape()[1 + i] = chunk_size_xyz[2 - i]; } ComputeStrides(c_order, metadata.dtype.size(), chunk_layout_czyx_.shape(), chunk_layout_czyx_.byte_strides()); } /// Returns the chunk size in the external (xyz) order. std::array<Index, 3> chunk_size_xyz() const { return {{ chunk_layout_czyx_.shape()[3], chunk_layout_czyx_.shape()[2], chunk_layout_czyx_.shape()[1], }}; } Status ValidateMetadataCompatibility(const void* existing_metadata_ptr, const void* new_metadata_ptr) override { const auto& existing_metadata = *static_cast<const MultiscaleMetadata*>(existing_metadata_ptr); const auto& new_metadata = *static_cast<const MultiscaleMetadata*>(new_metadata_ptr); return internal_neuroglancer_precomputed::ValidateMetadataCompatibility( existing_metadata, new_metadata, scale_index_, chunk_size_xyz()); } void GetChunkGridBounds( const void* metadata_ptr, MutableBoxView<> bounds, BitSpan<std::uint64_t> implicit_lower_bounds, BitSpan<std::uint64_t> implicit_upper_bounds) override { // Chunk grid dimension order is `[x, y, z]`. const auto& metadata = *static_cast<const MultiscaleMetadata*>(metadata_ptr); assert(3 == bounds.rank()); assert(3 == implicit_lower_bounds.size()); assert(3 == implicit_upper_bounds.size()); std::fill(bounds.origin().begin(), bounds.origin().end(), Index(0)); const auto& scale_metadata = metadata.scales[scale_index_]; absl::c_copy(scale_metadata.box.shape(), bounds.shape().begin()); implicit_lower_bounds.fill(false); implicit_upper_bounds.fill(false); } Result<std::shared_ptr<const void>> GetResizedMetadata( const void* existing_metadata, span<const Index> new_inclusive_min, span<const Index> new_exclusive_max) override { return absl::UnimplementedError(""); } static internal::ChunkGridSpecification GetChunkGridSpecification( const MultiscaleMetadata& metadata, size_t scale_index, span<Index, 3> chunk_size_xyz) { std::array<Index, 4> chunk_shape_czyx; chunk_shape_czyx[0] = metadata.num_channels; for (DimensionIndex i = 0; i < 3; ++i) { chunk_shape_czyx[3 - i] = chunk_size_xyz[i]; } // Component dimension order is `[channel, z, y, x]`. SharedArray<const void> fill_value( internal::AllocateAndConstructSharedElements(1, value_init, metadata.dtype), StridedLayout<>(chunk_shape_czyx, GetConstantVector<Index, 0, 4>())); // Resizing is not supported. Specifying the `component_bounds` permits // partial chunks at the upper bounds to be written unconditionally (which // may be more efficient) if fully overwritten. Box<> component_bounds_czyx(4); component_bounds_czyx.origin()[0] = 0; component_bounds_czyx.shape()[0] = metadata.num_channels; const auto& box_xyz = metadata.scales[scale_index].box; for (DimensionIndex i = 0; i < 3; ++i) { // The `ChunkCache` always translates the origin to `0`. component_bounds_czyx[3 - i] = IndexInterval::UncheckedSized(0, box_xyz[i].size()); } return internal::ChunkGridSpecification( {internal::ChunkGridSpecification::Component( std::move(fill_value), std::move(component_bounds_czyx), {3, 2, 1})}); } Result<absl::InlinedVector<SharedArrayView<const void>, 1>> DecodeChunk( const void* metadata, span<const Index> chunk_indices, absl::Cord data) override { if (auto result = internal_neuroglancer_precomputed::DecodeChunk( chunk_indices, *static_cast<const MultiscaleMetadata*>(metadata), scale_index_, chunk_layout_czyx_, std::move(data))) { return absl::InlinedVector<SharedArrayView<const void>, 1>{ std::move(*result)}; } else { return absl::FailedPreconditionError(result.status().message()); } } Result<absl::Cord> EncodeChunk( const void* metadata, span<const Index> chunk_indices, span<const ArrayView<const void>> component_arrays) override { assert(component_arrays.size() == 1); return internal_neuroglancer_precomputed::EncodeChunk( chunk_indices, *static_cast<const MultiscaleMetadata*>(metadata), scale_index_, component_arrays[0]); } Result<IndexTransform<>> GetExternalToInternalTransform( const void* metadata_ptr, std::size_t component_index) override { assert(component_index == 0); const auto& metadata = *static_cast<const MultiscaleMetadata*>(metadata_ptr); const auto& scale = metadata.scales[scale_index_]; const auto& box = scale.box; auto builder = IndexTransformBuilder<>(4, 4); auto input_origin = builder.input_origin(); std::copy(box.origin().begin(), box.origin().end(), input_origin.begin()); input_origin[3] = 0; auto input_shape = builder.input_shape(); std::copy(box.shape().begin(), box.shape().end(), input_shape.begin()); input_shape[3] = metadata.num_channels; builder.input_labels({"x", "y", "z", "channel"}); builder.output_single_input_dimension(0, 3); for (int i = 0; i < 3; ++i) { builder.output_single_input_dimension(3 - i, -box.origin()[i], 1, i); } return builder.Finalize(); } absl::Status GetBoundSpecData( KvsDriverSpec& spec_base, const void* metadata_ptr, [[maybe_unused]] std::size_t component_index) override { assert(component_index == 0); auto& spec = static_cast<NeuroglancerPrecomputedDriverSpec&>(spec_base); const auto& metadata = *static_cast<const MultiscaleMetadata*>(metadata_ptr); const auto& scale = metadata.scales[scale_index_]; spec.open_constraints.scale_index = scale_index_; auto& scale_constraints = spec.open_constraints.scale; scale_constraints.chunk_size = chunk_size_xyz(); scale_constraints.key = scale.key; scale_constraints.resolution = scale.resolution; scale_constraints.box = scale.box; scale_constraints.encoding = scale.encoding; if (scale.encoding == ScaleMetadata::Encoding::compressed_segmentation) { scale_constraints.compressed_segmentation_block_size = scale.compressed_segmentation_block_size; } scale_constraints.sharding = scale.sharding; auto& multiscale_constraints = spec.open_constraints.multiscale; multiscale_constraints.num_channels = metadata.num_channels; multiscale_constraints.type = metadata.type; return absl::OkStatus(); } Result<ChunkLayout> GetBaseChunkLayout(const MultiscaleMetadata& metadata, ChunkLayout::Usage base_usage) { ChunkLayout layout; // Leave origin set at zero; origin is accounted for by the index transform. TENSORSTORE_RETURN_IF_ERROR( layout.Set(ChunkLayout::GridOrigin(GetConstantVector<Index, 0>(4)))); const auto& scale = metadata.scales[scale_index_]; { DimensionIndex inner_order[4]; SetPermutation(c_order, inner_order); TENSORSTORE_RETURN_IF_ERROR( layout.Set(ChunkLayout::InnerOrder(inner_order))); } TENSORSTORE_RETURN_IF_ERROR(layout.Set(ChunkLayout::Chunk( ChunkLayout::ChunkShape(chunk_layout_czyx_.shape()), base_usage))); if (scale.encoding == ScaleMetadata::Encoding::compressed_segmentation) { TENSORSTORE_RETURN_IF_ERROR(layout.Set(ChunkLayout::CodecChunkShape( {1, scale.compressed_segmentation_block_size[2], scale.compressed_segmentation_block_size[1], scale.compressed_segmentation_block_size[0]}))); } return layout; } Result<CodecSpec::Ptr> GetCodec(const void* metadata_ptr, std::size_t component_index) override { return GetCodecFromMetadata( *static_cast<const MultiscaleMetadata*>(metadata_ptr), scale_index_); } std::string GetBaseKvstorePath() override { return key_prefix_; } std::string key_prefix_; std::size_t scale_index_; // channel, z, y, x StridedLayout<4> chunk_layout_czyx_; }; class UnshardedDataCache : public DataCacheBase { public: explicit UnshardedDataCache(Initializer initializer, std::string_view key_prefix, const MultiscaleMetadata& metadata, std::size_t scale_index, std::array<Index, 3> chunk_size_xyz) : DataCacheBase(std::move(initializer), key_prefix, metadata, scale_index, chunk_size_xyz) { const auto& scale = metadata.scales[scale_index]; scale_key_prefix_ = ResolveScaleKey(key_prefix, scale.key); } std::string GetChunkStorageKey(const void* metadata_ptr, span<const Index> cell_indices) override { const auto& metadata = *static_cast<const MultiscaleMetadata*>(metadata_ptr); std::string key = scale_key_prefix_; if (!key.empty()) key += '/'; const auto& scale = metadata.scales[scale_index_]; for (int i = 0; i < 3; ++i) { const Index chunk_size = chunk_layout_czyx_.shape()[3 - i]; if (i != 0) key += '_'; absl::StrAppend( &key, scale.box.origin()[i] + chunk_size * cell_indices[i], "-", scale.box.origin()[i] + std::min(chunk_size * (cell_indices[i] + 1), scale.box.shape()[i])); } return key; } Result<ChunkLayout> GetChunkLayout(const void* metadata_ptr, std::size_t component_index) override { const auto& metadata = *static_cast<const MultiscaleMetadata*>(metadata_ptr); TENSORSTORE_ASSIGN_OR_RETURN( auto layout, GetBaseChunkLayout(metadata, ChunkLayout::kWrite)); TENSORSTORE_RETURN_IF_ERROR(layout.Finalize()); return layout; } private: /// Resolved key prefix for the scale. std::string scale_key_prefix_; }; class ShardedDataCache : public DataCacheBase { public: explicit ShardedDataCache(Initializer initializer, std::string_view key_prefix, const MultiscaleMetadata& metadata, std::size_t scale_index, std::array<Index, 3> chunk_size_xyz) : DataCacheBase(std::move(initializer), key_prefix, metadata, scale_index, chunk_size_xyz) { const auto& scale = metadata.scales[scale_index]; compressed_z_index_bits_ = GetCompressedZIndexBits(scale.box.shape(), chunk_size_xyz); } std::string GetChunkStorageKey(const void* metadata_ptr, span<const Index> cell_indices) override { assert(cell_indices.size() == 3); const std::uint64_t chunk_key = EncodeCompressedZIndex( {cell_indices.data(), 3}, compressed_z_index_bits_); return neuroglancer_uint64_sharded::ChunkIdToKey({chunk_key}); } Result<ChunkLayout> GetChunkLayout(const void* metadata_ptr, std::size_t component_index) override { const auto& metadata = *static_cast<const MultiscaleMetadata*>(metadata_ptr); const auto& scale = metadata.scales[scale_index_]; const auto& sharding = *std::get_if<ShardingSpec>(&scale.sharding); TENSORSTORE_ASSIGN_OR_RETURN( auto layout, GetBaseChunkLayout(metadata, ChunkLayout::kRead)); if (ShardChunkHierarchy hierarchy; GetShardChunkHierarchy( sharding, scale.box.shape(), scale.chunk_sizes[0], hierarchy)) { // Each shard corresponds to a rectangular region. Index write_chunk_shape[4]; write_chunk_shape[0] = metadata.num_channels; for (int dim = 0; dim < 3; ++dim) { const Index chunk_size = scale.chunk_sizes[0][dim]; const Index volume_size = scale.box.shape()[dim]; write_chunk_shape[3 - dim] = RoundUpTo( std::min(hierarchy.shard_shape_in_chunks[dim] * chunk_size, volume_size), chunk_size); } TENSORSTORE_RETURN_IF_ERROR( layout.Set(ChunkLayout::WriteChunkShape(write_chunk_shape))); } else { // Each shard does not correspond to a rectangular region. The write // chunk shape is equal to the full domain. Index write_chunk_shape[4]; write_chunk_shape[0] = metadata.num_channels; for (int dim = 0; dim < 3; ++dim) { write_chunk_shape[3 - dim] = RoundUpTo(scale.box.shape()[dim], scale.chunk_sizes[0][dim]); } TENSORSTORE_RETURN_IF_ERROR( layout.Set(ChunkLayout::WriteChunkShape(write_chunk_shape))); } TENSORSTORE_RETURN_IF_ERROR(layout.Finalize()); return layout; } std::array<int, 3> compressed_z_index_bits_; }; class NeuroglancerPrecomputedDriver : public internal_kvs_backed_chunk_driver::RegisteredKvsDriver< NeuroglancerPrecomputedDriver, NeuroglancerPrecomputedDriverSpec> { using Base = internal_kvs_backed_chunk_driver::RegisteredKvsDriver< NeuroglancerPrecomputedDriver, NeuroglancerPrecomputedDriverSpec>; public: using Base::Base; class OpenState; Result<DimensionUnitsVector> GetDimensionUnits() override { auto* cache = static_cast<DataCacheBase*>(this->cache()); const auto& metadata = *static_cast<const MultiscaleMetadata*>(cache->initial_metadata_.get()); const auto& scale = metadata.scales[cache->scale_index_]; DimensionUnitsVector units(4); for (int i = 0; i < 3; ++i) { units[3 - i] = Unit(scale.resolution[i], "nm"); } return units; } }; class NeuroglancerPrecomputedDriver::OpenState : public NeuroglancerPrecomputedDriver::OpenStateBase { public: using NeuroglancerPrecomputedDriver::OpenStateBase::OpenStateBase; std::string GetPrefixForDeleteExisting() override { // TODO(jbms): Possibly change behavior in the future to allow deleting // just a single scale. return spec().store.path; } std::string GetMetadataCacheEntryKey() override { return spec().store.path; } std::unique_ptr<internal_kvs_backed_chunk_driver::MetadataCache> GetMetadataCache(MetadataCache::Initializer initializer) override { return std::make_unique<MetadataCache>(std::move(initializer)); } std::string GetDataCacheKey(const void* metadata) override { std::string result; const auto& spec = this->spec(); internal::EncodeCacheKey( &result, spec.store.path, GetMetadataCompatibilityKey( *static_cast<const MultiscaleMetadata*>(metadata), scale_index_ ? *scale_index_ : *spec.open_constraints.scale_index, chunk_size_xyz_)); return result; } internal_kvs_backed_chunk_driver::AtomicUpdateConstraint GetCreateConstraint() override { // `Create` can modify an existing `info` file, but can also create a new // `info` file if one does not already exist. return internal_kvs_backed_chunk_driver::AtomicUpdateConstraint::kNone; } Result<std::shared_ptr<const void>> Create( const void* existing_metadata) override { const auto* metadata = static_cast<const MultiscaleMetadata*>(existing_metadata); if (auto result = CreateScale(metadata, spec().open_constraints, spec().schema)) { scale_index_ = result->second; return result->first; } else { scale_index_ = std::nullopt; return std::move(result).status(); } } std::unique_ptr<internal_kvs_backed_chunk_driver::DataCache> GetDataCache( internal_kvs_backed_chunk_driver::DataCache::Initializer initializer) override { const auto& metadata = *static_cast<const MultiscaleMetadata*>(initializer.metadata.get()); assert(scale_index_); const auto& scale = metadata.scales[scale_index_.value()]; if (std::holds_alternative<ShardingSpec>(scale.sharding)) { return std::make_unique<ShardedDataCache>( std::move(initializer), spec().store.path, metadata, scale_index_.value(), chunk_size_xyz_); } else { return std::make_unique<UnshardedDataCache>( std::move(initializer), spec().store.path, metadata, scale_index_.value(), chunk_size_xyz_); } } Result<std::size_t> GetComponentIndex(const void* metadata_ptr, OpenMode open_mode) override { const auto& metadata = *static_cast<const MultiscaleMetadata*>(metadata_ptr); // FIXME: avoid copy by changing OpenScale to take separate arguments auto open_constraints = spec().open_constraints; if (scale_index_) { if (spec().open_constraints.scale_index) { assert(*spec().open_constraints.scale_index == *scale_index_); } else { open_constraints.scale_index = *scale_index_; } } TENSORSTORE_ASSIGN_OR_RETURN( size_t scale_index, OpenScale(metadata, open_constraints, spec().schema)); const auto& scale = metadata.scales[scale_index]; if (spec().open_constraints.scale.chunk_size && absl::c_linear_search(scale.chunk_sizes, *spec().open_constraints.scale.chunk_size)) { // Use the specified chunk size. chunk_size_xyz_ = *spec().open_constraints.scale.chunk_size; } else { // Chunk size was unspecified. assert(!spec().open_constraints.scale.chunk_size); chunk_size_xyz_ = scale.chunk_sizes[0]; } TENSORSTORE_RETURN_IF_ERROR(ValidateMetadataSchema( metadata, scale_index, chunk_size_xyz_, spec().schema)); scale_index_ = scale_index; // Component index is always 0. return 0; } Result<kvstore::DriverPtr> GetDataKeyValueStore( kvstore::DriverPtr base_kv_store, const void* metadata_ptr) override { const auto& metadata = *static_cast<const MultiscaleMetadata*>(metadata_ptr); assert(scale_index_); const auto& scale = metadata.scales[*scale_index_]; if (auto* sharding_spec = std::get_if<ShardingSpec>(&scale.sharding)) { assert(scale.chunk_sizes.size() == 1); return neuroglancer_uint64_sharded::GetShardedKeyValueStore( std::move(base_kv_store), executor(), ResolveScaleKey(spec().store.path, scale.key), *sharding_spec, *cache_pool(), GetChunksPerVolumeShardFunction(*sharding_spec, scale.box.shape(), scale.chunk_sizes[0])); } return base_kv_store; } // Set by `Create` or `GetComponentIndex` to indicate the scale index that // has been determined. std::optional<std::size_t> scale_index_; // Set by `GetComponentIndex` to indicate the chunk size that has been // determined. std::array<Index, 3> chunk_size_xyz_; }; Future<internal::Driver::Handle> NeuroglancerPrecomputedDriverSpec::Open( internal::OpenTransactionPtr transaction, ReadWriteMode read_write_mode) const { return NeuroglancerPrecomputedDriver::Open(std::move(transaction), this, read_write_mode); } } // namespace } // namespace internal_neuroglancer_precomputed } // namespace tensorstore TENSORSTORE_DECLARE_GARBAGE_COLLECTION_SPECIALIZATION( tensorstore::internal_neuroglancer_precomputed:: NeuroglancerPrecomputedDriver) // Use default garbage collection implementation provided by // kvs_backed_chunk_driver (just handles the kvstore) TENSORSTORE_DEFINE_GARBAGE_COLLECTION_SPECIALIZATION( tensorstore::internal_neuroglancer_precomputed:: NeuroglancerPrecomputedDriver, tensorstore::internal_neuroglancer_precomputed:: NeuroglancerPrecomputedDriver::GarbageCollectionBase) namespace { const tensorstore::internal::DriverRegistration< tensorstore::internal_neuroglancer_precomputed:: NeuroglancerPrecomputedDriverSpec> registration; } // namespace
41.221713
87
0.687451
2649aa1d585ddcda57f5cbb4c1ac6e2a042e75a9
4,575
cpp
C++
test/PHControlTest.cpp
IDzyre/TankController
60ccdd6d4023be7a0e0155b508e8b067603bf8b2
[ "MIT" ]
null
null
null
test/PHControlTest.cpp
IDzyre/TankController
60ccdd6d4023be7a0e0155b508e8b067603bf8b2
[ "MIT" ]
null
null
null
test/PHControlTest.cpp
IDzyre/TankController
60ccdd6d4023be7a0e0155b508e8b067603bf8b2
[ "MIT" ]
null
null
null
#include <Arduino.h> #include <ArduinoUnitTests.h> #include <ci/ObservableDataStream.h> #include "Devices/DateTime_TC.h" #include "MainMenu.h" #include "PHCalibrationMid.h" #include "PHControl.h" #include "TankControllerLib.h" const uint16_t PIN = 49; /** * cycle the control through to a point of being off */ void reset() { PHControl* singleton = PHControl::instance(); singleton->enablePID(false); singleton->setTargetPh(7.00); singleton->updateControl(7.00); delay(10000); singleton->updateControl(7.00); TankControllerLib* tc = TankControllerLib::instance(); tc->setNextState(new MainMenu(tc), true); } unittest_setup() { reset(); } unittest_teardown() { reset(); } // updateControl function unittest(beforeTenSeconds) { GodmodeState* state = GODMODE(); PHControl* controlSolenoid = PHControl::instance(); TankControllerLib::instance()->loop(); state->resetClock(); DateTime_TC january(2021, 1, 15, 1, 48, 24); january.setAsCurrent(); delay(1000); state->serialPort[0].dataOut = ""; // the history of data written assertEqual(TURN_SOLENOID_OFF, state->digitalPin[PIN]); controlSolenoid->setTargetPh(7.00); controlSolenoid->updateControl(8.00); assertEqual(TURN_SOLENOID_ON, state->digitalPin[PIN]); assertEqual("2021-01-15 01:48:25\r\nCO2 bubbler turned on after 1000 ms\r\n", state->serialPort[0].dataOut); delay(9500); controlSolenoid->updateControl(8.00); assertEqual(TURN_SOLENOID_ON, state->digitalPin[PIN]); } unittest(afterTenSecondsButPhStillHigher) { GodmodeState* state = GODMODE(); PHControl* controlSolenoid = PHControl::instance(); assertEqual(TURN_SOLENOID_OFF, state->digitalPin[PIN]); controlSolenoid->setTargetPh(7.00); controlSolenoid->updateControl(8.00); assertEqual(TURN_SOLENOID_ON, state->digitalPin[PIN]); delay(9500); controlSolenoid->updateControl(8.00); assertEqual(TURN_SOLENOID_ON, state->digitalPin[PIN]); delay(1000); controlSolenoid->updateControl(7.25); assertEqual(TURN_SOLENOID_ON, state->digitalPin[PIN]); } unittest(afterTenSecondsAndPhIsLower) { GodmodeState* state = GODMODE(); PHControl* controlSolenoid = PHControl::instance(); state->serialPort[0].dataOut = ""; // the history of data written assertEqual(TURN_SOLENOID_OFF, state->digitalPin[PIN]); controlSolenoid->setTargetPh(7.00); controlSolenoid->updateControl(8.00); assertEqual(TURN_SOLENOID_ON, state->digitalPin[PIN]); assertEqual("2021-01-15 01:49:25\r\nCO2 bubbler turned on after 20014 ms\r\n", state->serialPort[0].dataOut); state->serialPort[0].dataOut = ""; // the history of data written delay(9500); controlSolenoid->updateControl(8.00); assertEqual(TURN_SOLENOID_ON, state->digitalPin[PIN]); delay(1000); controlSolenoid->updateControl(6.75); assertEqual(TURN_SOLENOID_OFF, state->digitalPin[PIN]); assertEqual("2021-01-15 01:49:35\r\nCO2 bubbler turned off after 10500 ms\r\n", state->serialPort[0].dataOut); } /** * Test that CO2 b is turned on when needed * \see unittest(disableDuringCalibration) */ unittest(beforeTenSecondsButPhIsLower) { GodmodeState* state = GODMODE(); PHControl* controlSolenoid = PHControl::instance(); // device is initially off but turns on when needed assertEqual(TURN_SOLENOID_OFF, state->digitalPin[PIN]); controlSolenoid->setTargetPh(7.00); controlSolenoid->updateControl(8.00); assertEqual(TURN_SOLENOID_ON, state->digitalPin[PIN]); delay(7500); controlSolenoid->updateControl(6.75); assertEqual(TURN_SOLENOID_OFF, state->digitalPin[PIN]); } unittest(PhEvenWithTarget) { GodmodeState* state = GODMODE(); PHControl* controlSolenoid = PHControl::instance(); assertEqual(TURN_SOLENOID_OFF, state->digitalPin[PIN]); controlSolenoid->setTargetPh(7.00); controlSolenoid->updateControl(7.00); assertEqual(TURN_SOLENOID_OFF, state->digitalPin[PIN]); } /** * Test that CO2 bubbler is turned on when needed * \see unittest(beforeTenSecondsButPhIsLower) */ unittest(disableDuringCalibration) { TankControllerLib* tc = TankControllerLib::instance(); assertFalse(tc->isInCalibration()); PHCalibrationMid* test = new PHCalibrationMid(tc); tc->setNextState(test, true); assertTrue(tc->isInCalibration()); GodmodeState* state = GODMODE(); PHControl* controlSolenoid = PHControl::instance(); // device is initially off and stays off due to calibration assertEqual(TURN_SOLENOID_OFF, state->digitalPin[PIN]); controlSolenoid->setTargetPh(7.00); controlSolenoid->updateControl(8.00); assertEqual(TURN_SOLENOID_OFF, state->digitalPin[PIN]); } unittest_main()
33.888889
112
0.74623
264e7319da810019e64f74b064a4d2b4949c2fd3
261
cpp
C++
test/test_get_memory_info.cpp
xcjusuih/Memtracker
93db5fe1cfbdb3755b952c608d34cb5a12a702ef
[ "MIT" ]
null
null
null
test/test_get_memory_info.cpp
xcjusuih/Memtracker
93db5fe1cfbdb3755b952c608d34cb5a12a702ef
[ "MIT" ]
null
null
null
test/test_get_memory_info.cpp
xcjusuih/Memtracker
93db5fe1cfbdb3755b952c608d34cb5a12a702ef
[ "MIT" ]
1
2021-04-30T11:45:36.000Z
2021-04-30T11:45:36.000Z
#include <cstdio> #include "process.hpp" int main() { memory* mem = get_memory_info(); printf("%u\t%u\t%u\t%u\t%u\n", mem->memTotal, mem->memFree, mem->MemAvailable, mem->Buffers, mem->Cached); delete(mem); }
20.076923
36
0.54023
2650d87f48eb1b74a9a280537059de5dc71df5cb
38
hpp
C++
src/boost_fusion_algorithm.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_fusion_algorithm.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_fusion_algorithm.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/fusion/algorithm.hpp>
19
37
0.789474
26514c2bffae327a7b38b275f04db707c695e211
8,401
cc
C++
ja2/Build/Editor/EditorMapInfo.cc
gtrafimenkov/ja2-vanilla-cp
961076add8175afa845cbd6c33dbf9cd78f61a0c
[ "BSD-Source-Code" ]
null
null
null
ja2/Build/Editor/EditorMapInfo.cc
gtrafimenkov/ja2-vanilla-cp
961076add8175afa845cbd6c33dbf9cd78f61a0c
[ "BSD-Source-Code" ]
null
null
null
ja2/Build/Editor/EditorMapInfo.cc
gtrafimenkov/ja2-vanilla-cp
961076add8175afa845cbd6c33dbf9cd78f61a0c
[ "BSD-Source-Code" ]
null
null
null
#include "Editor/EditorMapInfo.h" #include "Editor/EditScreen.h" #include "Editor/EditSys.h" #include "Editor/EditorDefines.h" #include "Editor/EditorItems.h" #include "Editor/EditorMercs.h" #include "Editor/EditorTaskbarUtils.h" #include "Editor/EditorTerrain.h" //for access to TerrainTileDrawMode #include "Editor/EditorUndo.h" #include "Editor/ItemStatistics.h" #include "Editor/SelectWin.h" #include "SGP/Font.h" #include "SGP/Input.h" #include "SGP/Line.h" #include "SGP/MouseSystem.h" #include "SGP/Random.h" #include "Strategic/StrategicMap.h" #include "Tactical/AnimationData.h" #include "Tactical/InterfaceItems.h" #include "Tactical/MapInformation.h" #include "Tactical/SoldierAdd.h" #include "Tactical/SoldierControl.h" #include "Tactical/SoldierCreate.h" //The stuff that connects the editor generated information #include "Tactical/SoldierInitList.h" #include "Tactical/SoldierProfile.h" #include "Tactical/SoldierProfileType.h" #include "Tactical/WorldItems.h" #include "TileEngine/Environment.h" #include "TileEngine/ExitGrids.h" #include "TileEngine/Lighting.h" #include "TileEngine/SimpleRenderUtils.h" #include "TileEngine/SysUtil.h" #include "Utils/FontControl.h" #include "Utils/TextInput.h" INT8 gbDefaultLightType = PRIMETIME_LIGHT; SGPPaletteEntry gEditorLightColor; BOOLEAN gfEditorForceShadeTableRebuild = FALSE; void SetupTextInputForMapInfo() { wchar_t str[10]; InitTextInputModeWithScheme(DEFAULT_SCHEME); AddUserInputField(NULL); // just so we can use short cut keys while not // typing. // light rgb fields swprintf(str, lengthof(str), L"%d", gEditorLightColor.r); AddTextInputField(10, 394, 25, 18, MSYS_PRIORITY_NORMAL, str, 3, INPUTTYPE_NUMERICSTRICT); swprintf(str, lengthof(str), L"%d", gEditorLightColor.g); AddTextInputField(10, 414, 25, 18, MSYS_PRIORITY_NORMAL, str, 3, INPUTTYPE_NUMERICSTRICT); swprintf(str, lengthof(str), L"%d", gEditorLightColor.b); AddTextInputField(10, 434, 25, 18, MSYS_PRIORITY_NORMAL, str, 3, INPUTTYPE_NUMERICSTRICT); swprintf(str, lengthof(str), L"%d", gsLightRadius); AddTextInputField(120, 394, 25, 18, MSYS_PRIORITY_NORMAL, str, 3, INPUTTYPE_NUMERICSTRICT); swprintf(str, lengthof(str), L"%d", gusLightLevel); AddTextInputField(120, 414, 25, 18, MSYS_PRIORITY_NORMAL, str, 2, INPUTTYPE_NUMERICSTRICT); // Scroll restriction ID swprintf(str, lengthof(str), L"%.d", gMapInformation.ubRestrictedScrollID); AddTextInputField(210, 420, 30, 20, MSYS_PRIORITY_NORMAL, str, 2, INPUTTYPE_NUMERICSTRICT); // exit grid input fields swprintf(str, lengthof(str), L"%c%d", gExitGrid.ubGotoSectorY + 'A' - 1, gExitGrid.ubGotoSectorX); AddTextInputField(338, 363, 30, 18, MSYS_PRIORITY_NORMAL, str, 3, INPUTTYPE_COORDINATE); swprintf(str, lengthof(str), L"%d", gExitGrid.ubGotoSectorZ); AddTextInputField(338, 383, 30, 18, MSYS_PRIORITY_NORMAL, str, 1, INPUTTYPE_NUMERICSTRICT); swprintf(str, lengthof(str), L"%d", gExitGrid.usGridNo); AddTextInputField(338, 403, 40, 18, MSYS_PRIORITY_NORMAL, str, 5, INPUTTYPE_NUMERICSTRICT); } void UpdateMapInfo() { SetFont(FONT10ARIAL); SetFontShadow(FONT_NEARBLACK); SetFontForeground(FONT_RED); MPrint(38, 399, L"R"); SetFontForeground(FONT_GREEN); MPrint(38, 419, L"G"); SetFontForeground(FONT_DKBLUE); MPrint(38, 439, L"B"); SetFontForeground(FONT_YELLOW); MPrint(65, 369, L"Prime"); MPrint(65, 382, L"Night"); MPrint(65, 397, L"24Hrs"); SetFontForeground(FONT_YELLOW); MPrint(148, 399, L"Radius"); if (!gfBasement && !gfCaves) SetFontForeground(FONT_DKYELLOW); MPrint(148, 414, L"Underground"); MPrint(148, 423, L"Light Level"); SetFontForeground(FONT_YELLOW); MPrint(230, 369, L"Outdoors"); MPrint(230, 384, L"Basement"); MPrint(230, 399, L"Caves"); SetFontForeground(FONT_ORANGE); MPrint(250, 420, L"Restricted"); MPrint(250, 430, L"Scroll ID"); SetFontForeground(FONT_YELLOW); MPrint(368, 363, L"Destination"); MPrint(368, 372, L"Sector"); MPrint(368, 383, L"Destination"); MPrint(368, 392, L"Bsmt. Level"); MPrint(378, 403, L"Dest."); MPrint(378, 412, L"GridNo"); } void UpdateMapInfoFields() { wchar_t str[10]; // Update the text fields to reflect the validated values. // light rgb fields swprintf(str, lengthof(str), L"%d", gEditorLightColor.r); SetInputFieldStringWith16BitString(1, str); swprintf(str, lengthof(str), L"%d", gEditorLightColor.g); SetInputFieldStringWith16BitString(2, str); swprintf(str, lengthof(str), L"%d", gEditorLightColor.b); SetInputFieldStringWith16BitString(3, str); swprintf(str, lengthof(str), L"%d", gsLightRadius); SetInputFieldStringWith16BitString(4, str); swprintf(str, lengthof(str), L"%d", gusLightLevel); SetInputFieldStringWith16BitString(5, str); swprintf(str, lengthof(str), L"%.d", gMapInformation.ubRestrictedScrollID); SetInputFieldStringWith16BitString(6, str); ApplyNewExitGridValuesToTextFields(); } void ExtractAndUpdateMapInfo() { INT32 temp; BOOLEAN fUpdateLight1 = FALSE; // extract light1 colors temp = MIN(GetNumericStrictValueFromField(1), 255); if (temp != -1 && temp != gEditorLightColor.r) { fUpdateLight1 = TRUE; gEditorLightColor.r = (UINT8)temp; } temp = MIN(GetNumericStrictValueFromField(2), 255); if (temp != -1 && temp != gEditorLightColor.g) { fUpdateLight1 = TRUE; gEditorLightColor.g = (UINT8)temp; } temp = MIN(GetNumericStrictValueFromField(3), 255); if (temp != -1 && temp != gEditorLightColor.b) { fUpdateLight1 = TRUE; gEditorLightColor.b = (UINT8)temp; } if (fUpdateLight1) { gfEditorForceShadeTableRebuild = TRUE; LightSetColor(&gEditorLightColor); gfEditorForceShadeTableRebuild = FALSE; } // extract radius temp = MAX(MIN(GetNumericStrictValueFromField(4), 8), 1); if (temp != -1) gsLightRadius = (INT16)temp; temp = MAX(MIN(GetNumericStrictValueFromField(5), 15), 1); if (temp != -1 && temp != gusLightLevel) { gusLightLevel = (UINT16)temp; gfRenderWorld = TRUE; ubAmbientLightLevel = (UINT8)(EDITOR_LIGHT_MAX - gusLightLevel); LightSetBaseLevel(ubAmbientLightLevel); LightSpriteRenderAll(); } temp = (INT8)GetNumericStrictValueFromField(6); gMapInformation.ubRestrictedScrollID = temp != -1 ? temp : 0; // set up fields for exitgrid information wchar_t const *const str = GetStringFromField(7); wchar_t row = str[0]; if ('a' <= row && row <= 'z') row -= 32; // uppercase it! if ('A' <= row && row <= 'Z' && '0' <= str[1] && str[1] <= '9') { // only update, if coordinate is valid. gExitGrid.ubGotoSectorY = (UINT8)(row - 'A' + 1); gExitGrid.ubGotoSectorX = (UINT8)(str[1] - '0'); if (str[2] >= '0' && str[2] <= '9') gExitGrid.ubGotoSectorX = (UINT8)(gExitGrid.ubGotoSectorX * 10 + str[2] - '0'); gExitGrid.ubGotoSectorX = (UINT8)MAX(MIN(gExitGrid.ubGotoSectorX, 16), 1); gExitGrid.ubGotoSectorY = (UINT8)MAX(MIN(gExitGrid.ubGotoSectorY, 16), 1); } gExitGrid.ubGotoSectorZ = (UINT8)MAX(MIN(GetNumericStrictValueFromField(8), 3), 0); gExitGrid.usGridNo = (UINT16)MAX(MIN(GetNumericStrictValueFromField(9), 25600), 0); UpdateMapInfoFields(); } BOOLEAN ApplyNewExitGridValuesToTextFields() { wchar_t str[10]; // exit grid input fields if (iCurrentTaskbar != TASK_MAPINFO) return FALSE; swprintf(str, lengthof(str), L"%c%d", gExitGrid.ubGotoSectorY + 'A' - 1, gExitGrid.ubGotoSectorX); SetInputFieldStringWith16BitString(7, str); swprintf(str, lengthof(str), L"%d", gExitGrid.ubGotoSectorZ); SetInputFieldStringWith16BitString(8, str); swprintf(str, lengthof(str), L"%d", gExitGrid.usGridNo); SetInputFieldStringWith16BitString(9, str); SetActiveField(0); return TRUE; } void LocateNextExitGrid() { static UINT16 usCurrentExitGridNo = 0; EXITGRID ExitGrid; UINT16 i; for (i = usCurrentExitGridNo + 1; i < WORLD_MAX; i++) { if (GetExitGrid(i, &ExitGrid)) { usCurrentExitGridNo = i; CenterScreenAtMapIndex(i); return; } } for (i = 0; i < usCurrentExitGridNo; i++) { if (GetExitGrid(i, &ExitGrid)) { usCurrentExitGridNo = i; CenterScreenAtMapIndex(i); return; } } } void ChangeLightDefault(INT8 bLightType) { UnclickEditorButton(MAPINFO_PRIMETIME_LIGHT + gbDefaultLightType); gbDefaultLightType = bLightType; ClickEditorButton(MAPINFO_PRIMETIME_LIGHT + gbDefaultLightType); }
35.150628
100
0.717296
26550220b122d5d69e5a93bdd574de699eb1315a
5,812
cc
C++
src/operators/test/operator_mini1D.cc
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
37
2017-04-26T16:27:07.000Z
2022-03-01T07:38:57.000Z
src/operators/test/operator_mini1D.cc
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
494
2016-09-14T02:31:13.000Z
2022-03-13T18:57:05.000Z
src/operators/test/operator_mini1D.cc
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
43
2016-09-26T17:58:40.000Z
2022-03-25T02:29:59.000Z
/* Operators Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL. Amanzi is released under the three-clause BSD License. The terms of use and "as is" disclaimer for this license are provided in the top-level COPYRIGHT file. Author: Konstantin Lipnikov (lipnikov@lanl.gov) */ #include <cstdlib> #include <cmath> #include <iostream> #include <string> #include <vector> // TPLs #include "Teuchos_ParameterList.hpp" #include "UnitTest++.h" // Operators #include "OperatorDefs.hh" #include "Mini_Diffusion1D.hh" /* ***************************************************************** * This test diffusion solver one dimension: u(x) = x^3, K = 2. * **************************************************************** */ void MiniDiffusion1D_Constant(double bcl, int type_l, double bcr, int type_r) { using namespace Amanzi; using namespace Amanzi::Operators; std::cout << "\nTest: 1D elliptic solver: constant coefficient" << std::endl; double pl2_err[2], ph1_err[2]; for (int loop = 0; loop < 2; ++loop) { int ncells = (loop + 1) * 30; double length(1.0); auto mesh = std::make_shared<WhetStone::DenseVector>(WhetStone::DenseVector(ncells + 1)); // make a non-uniform mesh double h = length / ncells; for (int i = 0; i < ncells + 1; ++i) (*mesh)(i) = h * i; for (int i = 1; i < ncells; ++i) (*mesh)(i) += h * std::sin(3 * h * i) / 4; // initialize diffusion operator with constant coefficient Mini_Diffusion1D op; op.Init(mesh); if (loop == 0) { double K(2.0); op.Setup(K); } else { auto K = std::make_shared<WhetStone::DenseVector>(WhetStone::DenseVector(ncells)); for (int i = 0; i < ncells; ++i) (*K)(i) = 2.0; op.Setup(K, NULL, NULL); } op.UpdateMatrices(); // create right-hand side WhetStone::DenseVector& rhs = op.rhs(); for (int i = 0; i < ncells; ++i) { double xc = op.mesh_cell_centroid(i); double hc = op.mesh_cell_volume(i); rhs(i) = -12.0 * xc * hc; } // apply boundary condition op.ApplyBCs(bcl, type_l, bcr, type_r); // solve the problem WhetStone::DenseVector sol(rhs); op.ApplyInverse(rhs, sol); // compute error double hc, xc, err, pnorm(1.0), hnorm(1.0); pl2_err[loop] = 0.0; ph1_err[loop] = 0.0; for (int i = 0; i < ncells; ++i) { hc = op.mesh_cell_volume(i); xc = op.mesh_cell_centroid(i); err = xc * xc * xc - sol(i); pl2_err[loop] += err * err * hc; pnorm += xc * xc * xc * hc; } pl2_err[loop] = std::pow(pl2_err[loop] / pnorm, 0.5); ph1_err[loop] = std::pow(ph1_err[loop] / hnorm, 0.5); printf("BCs:%2d%2d L2(p)=%9.6f H1(p)=%9.6f\n", type_l, type_r, pl2_err[loop], ph1_err[loop]); CHECK(pl2_err[loop] < 1e-3 / (loop + 1) && ph1_err[loop] < 1e-4 / (loop + 1)); } CHECK(pl2_err[0] / pl2_err[1] > 3.7); } TEST(OPERATOR_MINI_DIFFUSION_CONSTANT) { int dir = Amanzi::Operators::OPERATOR_BC_DIRICHLET; int neu = Amanzi::Operators::OPERATOR_BC_NEUMANN; MiniDiffusion1D_Constant(0.0, dir, 1.0, dir); MiniDiffusion1D_Constant(0.0, dir, -6.0, neu); MiniDiffusion1D_Constant(0.0, neu, 1.0, dir); } /* ***************************************************************** * This test diffusion solver one dimension: u(x) = x^2, K(x) = x+1 * **************************************************************** */ void MiniDiffusion1D_Variable(double bcl, int type_l, double bcr, int type_r) { using namespace Amanzi; using namespace Amanzi::Operators; std::cout << "\nTest: 1D elliptic solver: variable coefficient" << std::endl; double pl2_err[2], ph1_err[2]; for (int loop = 0; loop < 2; ++loop) { int ncells = (loop + 1) * 30; double length(1.0); auto mesh = std::make_shared<WhetStone::DenseVector>(WhetStone::DenseVector(ncells + 1)); // make a non-uniform mesh double h = length / ncells; for (int i = 0; i < ncells + 1; ++i) (*mesh)(i) = h * i; for (int i = 1; i < ncells; ++i) (*mesh)(i) += h * std::sin(3 * h * i) / 4; // initialize diffusion operator with constant coefficient Mini_Diffusion1D op; op.Init(mesh); auto K = std::make_shared<WhetStone::DenseVector>(WhetStone::DenseVector(ncells)); for (int i = 0; i < ncells; ++i) { double xc = op.mesh_cell_centroid(i); (*K)(i) = xc + 1.0; } op.Setup(K, NULL, NULL); op.UpdateMatrices(); // create right-hand side WhetStone::DenseVector& rhs = op.rhs(); for (int i = 0; i < ncells; ++i) { double xc = op.mesh_cell_centroid(i); double hc = op.mesh_cell_volume(i); rhs(i) = -(4 * xc + 2.0) * hc; } // apply boundary condition op.ApplyBCs(bcl, type_l, bcr, type_r); // solve the problem WhetStone::DenseVector sol(rhs); op.ApplyInverse(rhs, sol); // compute error double hc, xc, err, pnorm(1.0), hnorm(1.0); pl2_err[loop] = 0.0; ph1_err[loop] = 0.0; for (int i = 0; i < ncells; ++i) { hc = op.mesh_cell_volume(i); xc = op.mesh_cell_centroid(i); err = xc * xc - sol(i); pl2_err[loop] += err * err * hc; pnorm += xc * xc * hc; } pl2_err[loop] = std::pow(pl2_err[loop] / pnorm, 0.5); ph1_err[loop] = std::pow(ph1_err[loop] / hnorm, 0.5); printf("BCs:%2d%2d L2(p)=%9.6f H1(p)=%9.6f\n", type_l, type_r, pl2_err[loop], ph1_err[loop]); CHECK(pl2_err[loop] < 1e-3 / (loop + 1) && ph1_err[loop] < 1e-4 / (loop + 1)); } CHECK(pl2_err[0] / pl2_err[1] > 3.7); } TEST(OPERATOR_MINI_DIFFUSION_VARIABLE) { int dir = Amanzi::Operators::OPERATOR_BC_DIRICHLET; int neu = Amanzi::Operators::OPERATOR_BC_NEUMANN; MiniDiffusion1D_Variable(0.0, dir, 1.0, dir); MiniDiffusion1D_Variable(0.0, dir, -4.0, neu); MiniDiffusion1D_Variable(0.0, neu, 1.0, dir); }
30.914894
98
0.582072
2657531345a1be7c95f5c8fdf80852b4c7419e44
190
hpp
C++
include/crucible/PointLight.hpp
pianoman373/crucible
fa03ca471fef56cf2def029a14bcc6a467996dfa
[ "MIT" ]
2
2019-02-17T02:55:38.000Z
2019-04-19T04:57:39.000Z
include/crucible/PointLight.hpp
pianoman373/crucible
fa03ca471fef56cf2def029a14bcc6a467996dfa
[ "MIT" ]
null
null
null
include/crucible/PointLight.hpp
pianoman373/crucible
fa03ca471fef56cf2def029a14bcc6a467996dfa
[ "MIT" ]
1
2018-12-03T22:39:44.000Z
2018-12-03T22:39:44.000Z
#pragma once #include <crucible/Math.hpp> class PointLight { public: vec3 m_position; vec3 m_color; float m_radius; PointLight(vec3 position, vec3 color, float radius); };
15.833333
56
0.7
2657fae70315ea802aa34bdf029df3baf77cbe83
275
cpp
C++
programmers/source/2-3.cpp
tdm1223/Algorithm
994149afffa21a81e38b822afcfc01f677d9e430
[ "MIT" ]
7
2019-06-26T07:03:32.000Z
2020-11-21T16:12:51.000Z
programmers/source/2-3.cpp
tdm1223/Algorithm
994149afffa21a81e38b822afcfc01f677d9e430
[ "MIT" ]
null
null
null
programmers/source/2-3.cpp
tdm1223/Algorithm
994149afffa21a81e38b822afcfc01f677d9e430
[ "MIT" ]
9
2019-02-28T03:34:54.000Z
2020-12-18T03:02:40.000Z
// JadenCase 문자열 만들기 // 2019.06.28 #include<string> using namespace std; string solution(string s) { s[0] = toupper(s[0]); for (int i = 1; i<s.size(); i++) { if (s[i - 1] == ' ') { s[i] = toupper(s[i]); } else { s[i] = tolower(s[i]); } } return s; }
11.956522
33
0.501818
26592a5e44863f17480bc4cb343850030f328d0b
3,361
cpp
C++
app/src/main/cpp/UI/Scoreboard/ScoreboardWindow.cpp
ArnisLielturks/Urho3D-Project-Template
998d12e2470ec8a43ec552a1c2182eecfed63ca1
[ "MIT" ]
48
2019-01-06T02:17:44.000Z
2021-09-28T15:10:30.000Z
app/src/main/cpp/UI/Scoreboard/ScoreboardWindow.cpp
urnenfeld/Urho3D-Project-Template
efd45e4edcffb232753010a3ee623d6cf9bc1c26
[ "MIT" ]
17
2019-01-22T17:48:58.000Z
2021-04-04T17:52:56.000Z
app/src/main/cpp/UI/Scoreboard/ScoreboardWindow.cpp
ArnisLielturks/Urho3D-Project-Template
998d12e2470ec8a43ec552a1c2182eecfed63ca1
[ "MIT" ]
18
2019-02-18T13:55:41.000Z
2021-04-02T14:28:00.000Z
#include <Urho3D/UI/UI.h> #include <Urho3D/Resource/ResourceCache.h> #include <Urho3D/UI/Text.h> #include <Urho3D/UI/Font.h> #include "ScoreboardWindow.h" #include "../../Player/PlayerEvents.h" #include "../../Globals/GUIDefines.h" ScoreboardWindow::ScoreboardWindow(Context* context) : BaseWindow(context) { } ScoreboardWindow::~ScoreboardWindow() { baseWindow_->Remove(); } void ScoreboardWindow::Init() { Create(); SubscribeToEvents(); } void ScoreboardWindow::Create() { baseWindow_ = GetSubsystem<UI>()->GetRoot()->CreateChild<Window>(); baseWindow_->SetStyleAuto(); baseWindow_->SetAlignment(HA_CENTER, VA_CENTER); baseWindow_->SetSize(300, 300); baseWindow_->BringToFront(); baseWindow_->SetLayout(LayoutMode::LM_VERTICAL, 20, IntRect(20, 20, 20, 20)); CreatePlayerScores(); //URHO3D_LOGINFO("Player scores " + String(GetGlobalVar("PlayerScores").Get)); } void ScoreboardWindow::SubscribeToEvents() { SubscribeToEvent(PlayerEvents::E_PLAYER_SCORES_UPDATED, URHO3D_HANDLER(ScoreboardWindow, HandleScoresUpdated)); } void ScoreboardWindow::HandleScoresUpdated(StringHash eventType, VariantMap& eventData) { CreatePlayerScores(); } void ScoreboardWindow::CreatePlayerScores() { baseWindow_->RemoveAllChildren(); { auto container = baseWindow_->CreateChild<UIElement>(); container->SetAlignment(HA_LEFT, VA_TOP); container->SetLayout(LM_HORIZONTAL, 20); auto *cache = GetSubsystem<ResourceCache>(); auto* font = cache->GetResource<Font>(APPLICATION_FONT); // Create log element to view latest logs from the system auto name = container->CreateChild<Text>(); name->SetFont(font, 16); name->SetText("Player"); name->SetFixedWidth(200); name->SetColor(Color::GRAY); name->SetTextEffect(TextEffect::TE_SHADOW); // Create log element to view latest logs from the system auto score = container->CreateChild<Text>(); score->SetFont(font, 16); score->SetText("Score"); score->SetFixedWidth(100); score->SetColor(Color::GRAY); score->SetTextEffect(TextEffect::TE_SHADOW); } VariantMap players = GetGlobalVar("Players").GetVariantMap(); for (auto it = players.Begin(); it != players.End(); ++it) { VariantMap playerData = (*it).second_.GetVariantMap(); auto container = baseWindow_->CreateChild<UIElement>(); container->SetAlignment(HA_LEFT, VA_TOP); container->SetLayout(LM_HORIZONTAL, 20); auto *cache = GetSubsystem<ResourceCache>(); auto* font = cache->GetResource<Font>(APPLICATION_FONT); // Create log element to view latest logs from the system auto name = container->CreateChild<Text>(); name->SetFont(font, 14); name->SetText(playerData["Name"].GetString()); name->SetFixedWidth(200); name->SetColor(Color::GREEN); name->SetTextEffect(TextEffect::TE_SHADOW); // Create log element to view latest logs from the system auto score = container->CreateChild<Text>(); score->SetFont(font, 14); score->SetText(String(playerData["Score"].GetInt())); score->SetFixedWidth(100); score->SetColor(Color::GREEN); score->SetTextEffect(TextEffect::TE_SHADOW); } }
31.707547
115
0.670336
265e73379723ba9280c8780994d45196cc6eb362
3,376
cpp
C++
tests/functions.cpp
ulikoehler/aquila
d5e3bde3c8d07678a95f225b657a7bb23d0c4730
[ "MIT" ]
361
2015-01-06T20:12:35.000Z
2022-03-29T01:58:49.000Z
tests/functions.cpp
ulikoehler/aquila
d5e3bde3c8d07678a95f225b657a7bb23d0c4730
[ "MIT" ]
30
2015-01-13T12:17:13.000Z
2021-06-03T14:12:10.000Z
tests/functions.cpp
ulikoehler/aquila
d5e3bde3c8d07678a95f225b657a7bb23d0c4730
[ "MIT" ]
112
2015-01-14T12:01:00.000Z
2022-03-29T06:42:00.000Z
#include "aquila/global.h" #include "aquila/functions.h" #include "UnitTest++/UnitTest++.h" #include <vector> SUITE(Functions) { const std::size_t SIZE = 3; double arr1[SIZE] = {0, 1, 2}; std::vector<double> v1(arr1, arr1 + SIZE); double arr2[SIZE] = {1, 2, 3}; std::vector<double> v2(arr2, arr2 + SIZE); TEST(DecibelConversion) { double decibel = Aquila::dB(10.0); CHECK_CLOSE(20.0, decibel, 0.000001); } TEST(ComplexDecibelConversion) { double decibel = Aquila::dB(Aquila::ComplexType(0.0, 10.0)); CHECK_CLOSE(20.0, decibel, 0.000001); } TEST(ReferenceDecibelConversion) { double decibel = Aquila::dB(1000.0, 10.0); CHECK_CLOSE(40.0, decibel, 0.000001); } TEST(ClampToMax) { double value = Aquila::clamp(5.0, 9.0, 6.0); CHECK_CLOSE(6.0, value, 0.000001); } TEST(ClampToMin) { double value = Aquila::clamp(5.0, 1.0, 6.0); CHECK_CLOSE(5.0, value, 0.000001); } TEST(ClampUnchanged) { double value = Aquila::clamp(5.0, 5.5, 6.0); CHECK_CLOSE(5.5, value, 0.000001); } TEST(RandomRange) { for (std::size_t i = 0; i < 1000; ++i) { int x = Aquila::random(1, 2); CHECK_EQUAL(1, x); } } TEST(RandomDoubleRange) { for (std::size_t i = 0; i < 1000; ++i) { double x = Aquila::randomDouble(); CHECK(x < 1.0); } } TEST(IsPowerOf2ForNonPowers) { CHECK(!Aquila::isPowerOf2(0)); CHECK(!Aquila::isPowerOf2(3)); CHECK(!Aquila::isPowerOf2(15)); CHECK(!Aquila::isPowerOf2(247)); CHECK(!Aquila::isPowerOf2(32769)); } TEST(IsPowerOf2ForPowers) { CHECK(Aquila::isPowerOf2(1)); CHECK(Aquila::isPowerOf2(2)); CHECK(Aquila::isPowerOf2(16)); CHECK(Aquila::isPowerOf2(1024)); CHECK(Aquila::isPowerOf2(32768)); CHECK(Aquila::isPowerOf2(1152921504606846976ul)); } TEST(NextPowerOf2) { CHECK_EQUAL(2, Aquila::nextPowerOf2(1)); CHECK_EQUAL(4, Aquila::nextPowerOf2(3)); CHECK_EQUAL(1024, Aquila::nextPowerOf2(513)); CHECK_EQUAL(16384, Aquila::nextPowerOf2(10000)); CHECK_EQUAL(65536, Aquila::nextPowerOf2(44100)); CHECK_EQUAL(1152921504606846976ul, Aquila::nextPowerOf2(576460752303423489ul)); } TEST(EuclideanDistanceToItself) { double distance = Aquila::euclideanDistance(v1, v1); CHECK_CLOSE(0.0, distance, 0.000001); } TEST(EuclideanDistance) { double distance = Aquila::euclideanDistance(v1, v2); CHECK_CLOSE(1.732051, distance, 0.000001); } TEST(ManhattanDistanceToItself) { double distance = Aquila::manhattanDistance(v1, v1); CHECK_CLOSE(0.0, distance, 0.000001); } TEST(ManhattanDistance) { double distance = Aquila::manhattanDistance(v1, v2); CHECK_CLOSE(3.0, distance, 0.000001); } TEST(ChebyshevDistanceToItself) { double distance = Aquila::chebyshevDistance(v1, v1); CHECK_CLOSE(0.0, distance, 0.000001); } TEST(ChebyshevDistance) { double distance = Aquila::chebyshevDistance(v1, v2); CHECK_CLOSE(1.0, distance, 0.000001); } }
25.007407
87
0.582346
265eb7e3d7bb380c5091c946648d17cc17b2acd0
17,977
cpp
C++
trunk/suicore/src/System/Render/Skia/SkiaDrawContext.cpp
OhmPopy/MPFUI
eac88d66aeb88d342f16866a8d54858afe3b6909
[ "MIT" ]
59
2017-08-27T13:27:55.000Z
2022-01-21T13:24:05.000Z
src/suicore/System/Render/Skia/SkiaDrawContext.cpp
BigPig0/MPFUI
7042e0a5527ab323e16d2106d715db4f8ee93275
[ "MIT" ]
5
2017-11-26T05:40:23.000Z
2019-04-02T08:58:21.000Z
src/suicore/System/Render/Skia/SkiaDrawContext.cpp
BigPig0/MPFUI
7042e0a5527ab323e16d2106d715db4f8ee93275
[ "MIT" ]
49
2017-08-24T08:00:50.000Z
2021-11-07T01:24:41.000Z
#include "skiadrawing.h" #include <System/Types/Const.h> #include <System/Types/Structure.h> #include <System/Graphics/SkiaPaint.h> #include <System/Interop/System.h> #include "SkTextOp.h" #include <Skia/effects/SkGradientShader.h> #include <Skia/core/SkTypeface.h> namespace suic { SkiaDrawing::SkiaDrawing(Handle h, bool layeredMode) { _bmp = NULL; _handle = h; _layered.Resize(16); _layered.Add(layeredMode); } SkiaDrawing::~SkiaDrawing() { } void SkiaDrawing::SetOffset(const fPoint& pt) { SkMatrix matrix; _offset.x += pt.x; _offset.y += pt.y; matrix.setTranslate(pt.x, pt.y); GetCanvas()->concat(matrix); } void SkiaDrawing::SetBitmap(Bitmap* dib) { SkBitmap* bmp = reinterpret_cast<SkBitmap*>(static_cast<LONG_PTR>(dib->GetData())); GetCanvas()->SetBitmap(*bmp); _bmp = dib; } Handle SkiaDrawing::GetHandle() { return _handle; } Bitmap* SkiaDrawing::GetBitmap() { return _bmp; } void* SkiaDrawing::GetCanvas(int type) { return &_canvas; } int SkiaDrawing::Save() { _layered.Add(_layered[_layered.Length() - 1]); return GetCanvas()->save(); } int SkiaDrawing::SaveLayerAlpha(const fRect* rect, Byte alpha) { _layered.Add(true); if (NULL == rect) { return GetCanvas()->saveLayerAlpha(NULL, alpha); } else { SkRect srect = ToSkRect(rect); return GetCanvas()->saveLayerAlpha(&srect, alpha); } } int SkiaDrawing::SaveLayer(const fRect* rect, DrawInfo* drawInfo) { SkPaint& paint = DrawInfoToSkia(drawInfo); _layered.Add(true); paint.setFilterBitmap(true); if (NULL == rect) { return GetCanvas()->saveLayer(NULL, &paint); } else { SkRect srect = ToSkRect(rect); return GetCanvas()->saveLayer(&srect, &paint); } } void SkiaDrawing::Restore() { GetCanvas()->restore(); _layered.RemoveAt(_layered.Length() - 1); } int SkiaDrawing::GetSaveCount() { return GetCanvas()->getSaveCount(); } void SkiaDrawing::ResotreToCount(int count) { GetCanvas()->restoreToCount(count); } Rect SkiaDrawing::GetClipBound() { SkIRect rect; GetCanvas()->getClipDeviceBounds(&rect); return Rect(rect.left(), rect.top(), rect.width(), rect.height()); } bool SkiaDrawing::ContainsClip(fRect* clip) { return true; } bool SkiaDrawing::ContainsClip(fRRect* clip) { return true; } bool SkiaDrawing::ContainsClip(Geometry* clip) { return true; } bool SkiaDrawing::ClipRect(const fRect* clip, ClipOp op, bool anti) { SkRect rect = ToSkRect(clip); GetCanvas()->clipRect(rect, SkRegion::Op(op), anti); return !GetCanvas()->quickReject(rect); } bool SkiaDrawing::ClipRound(const fRRect* clip, ClipOp op, bool anti) { SkRRect rrect; SkVector raddi[4]; memcpy(&raddi[0], &clip->radii[0], sizeof(clip->radii)); rrect.setRectRadii(ToSkRect(&clip->rect), raddi); GetCanvas()->clipRRect(rrect, SkRegion::Op(op), anti); return true; } bool SkiaDrawing::ClipPath(OPath* rgn, ClipOp op, bool anti) { SkPath* path = (SkPath*)rgn->GetData(); GetCanvas()->clipPath(*path, SkRegion::Op(op), anti); return true; } bool SkiaDrawing::ClipRegion(Geometry* gmt, ClipOp op, bool anti) { SkPath dst; SkRegion* region = (SkRegion*)gmt->GetData(); region->getBoundaryPath(&dst); GetCanvas()->clipPath(dst, SkRegion::Op(op), anti); return true; } void SkiaDrawing::SetPixel(Int32 x, Int32 y, Color clr) { _bmp->SetColor(x, y, clr); } Color SkiaDrawing::GetPixel(Int32 x, Int32 y) { return _bmp->GetColor(x, y); } void SkiaDrawing::ReadPixels(Bitmap* dest, Point offset) { SkBitmap* bmp = reinterpret_cast<SkBitmap*>(static_cast<LONG_PTR>(dest->GetData())); GetCanvas()->readPixels(bmp, offset.x, offset.y); } void SkiaDrawing::WritePixels(const Bitmap* dest, Point casOff) { const SkBitmap* bmp = reinterpret_cast<const SkBitmap*>(static_cast<LONG_PTR>(dest->GetData())); GetCanvas()->writePixels(*bmp, casOff.x, casOff.y); } void SkiaDrawing::SetMatrix(const Matrix& m, bool bSet) { SkMatrix skm; skm.readFromMemory(m.GetBuffer(), 9 * sizeof(float)); if (bSet) { GetCanvas()->setMatrix(skm); } else { GetCanvas()->concat(skm); } } void SkiaDrawing::EraseColor(Color color) { GetCanvas()->drawColor(color); } void SkiaDrawing::EraseRect(const fRect* rc, Color color) { SkPaint paint; paint.setColor(color); GetCanvas()->drawIRect(ToSkIRect(rc), paint); } void SkiaDrawing::DrawImageBrush(ImageBrush* brush, const fRect* lprc) { Bitmap* pImage = brush->GetImage(); if (pImage) { SkRect rcImg(ToSkRect(brush->GetViewBox().TofRect())); SkRect drawRect(ToSkRect(*lprc)); SkBitmap* skbmp = reinterpret_cast<SkBitmap*>(static_cast<LONG_PTR>(pImage->GetData())); SkPaint paint; paint.setAlpha(brush->GetOpacity()); paint.setAntiAlias(true); if (brush->GetGrey()) { pImage->Backup(); pImage->EraseGray(); } if (brush->GetStretch() == Stretch::UniformToFill) { if (TileMode::Tile == brush->GetTileMode()) { for (int y = lprc->top; y < lprc->bottom;) { for (int x = lprc->left; x < lprc->right;) { SkRect rect; rect.setXYWH(x, y, rcImg.width(), rcImg.height()); GetCanvas()->drawBitmapRect(*skbmp, &rect, rcImg, &paint); x += rcImg.width(); } y += rcImg.height(); } } else { DeflatSkRect(rcImg, brush->GetCornerBox()); if (rcImg.width() > lprc->Width() && rcImg.height() > lprc->Height()) { rcImg.right = rcImg.left + lprc->Width(); rcImg.bottom = rcImg.top + lprc->Height(); } GetCanvas()->drawBitmapRect(*skbmp, &drawRect, rcImg, &paint); } } else if (brush->GetStretch() == Stretch::Uniform) { DeflatSkRect(rcImg, brush->GetCornerBox()); drawRect.right = drawRect.left + rcImg.width(); drawRect.bottom = drawRect.top + rcImg.height(); GetCanvas()->drawBitmapRect(*skbmp, &drawRect, rcImg, &paint); } else { //SkRect rcCorner(ToSkRect(brush->GetCornerBox().TofRect())); //GetCanvas()->drawBitmapNine(); } if (brush->GetGrey() > 0) { pImage->Restore(); pImage->ResetBackup(); } } } void SkiaDrawing::DrawLine(Pen* pen, fPoint pt0, fPoint pt1) { SkPaint paint; paint.setAntiAlias(true); InitPenIntoSkiaPaint(paint, pen); GetCanvas()->drawLine(pt0.x, pt0.y, pt1.x , pt1.y, paint); } void SkiaDrawing::InitBrushIntoSkPaint(SkPaint& paint, Brush* brush) { if (brush->GetRTTIType() == ImageBrush::RTTIType()) { ImageBrush* imBrush = (ImageBrush*)brush; SkBitmap* skbmp = reinterpret_cast<SkBitmap*>(static_cast<LONG_PTR>(imBrush->GetImage()->GetData())); SkShader* shader = SkShader::CreateBitmapShader(*skbmp, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode); paint.setShader(shader); shader->unref(); } else if (brush->GetRTTIType() == SolidColorBrush::RTTIType()) { paint.setColor(brush->ToColor()); } } void SkiaDrawing::InitPenIntoSkiaPaint(SkPaint& paint, Pen* pen) { if (pen != NULL) { paint.setStrokeWidth(pen->GetThickness()); paint.setStrokeCap((SkPaint::Cap)pen->GetDashCap()); paint.setStrokeJoin((SkPaint::Join)pen->GetLineJoin()); if (pen->GetBrush()) { paint.setColor(pen->GetBrush()->ToColor()); } if (pen->GetDashStyle()->dashes.Length() > 0) { ; } } } void SkiaDrawing::DrawRect(Brush* brush, Pen* pen, const fRect* rc) { SkRect rect = ToSkRect(rc); if (brush != NULL) { if (brush->GetRTTIType() == ImageBrush::RTTIType()) { DrawImageBrush(RTTICast<ImageBrush>(brush), &rect); } else { SkPaint paint; paint.setColor(brush->ToColor()); paint.setStyle(SkPaint::Style::kFill_Style); GetCanvas()->drawRect(rect, paint); } } if (pen != NULL) { SkPaint paint; paint.setStyle(SkPaint::Style::kStroke_Style); InitPenIntoSkiaPaint(paint, pen); GetCanvas()->drawRect(rect, paint); } } void SkiaDrawing::DrawRRect(Brush* brush, Pen* pen, const fRRect* rc) { SkRRect rrect; SkVector raddi[4]; memcpy(&raddi[0], &rc->radii[0], sizeof(rc->radii)); rrect.setRectRadii(ToSkRect(&rc->rect), raddi); if (brush != NULL) { if (brush->GetRTTIType() == ImageBrush::RTTIType()) { DrawImageBrush(RTTICast<ImageBrush>(brush), &rc->rect); } else { SkPaint paint; paint.setColor(brush->ToColor()); paint.setAntiAlias(true); paint.setStyle(SkPaint::Style::kFill_Style); GetCanvas()->drawRRect(rrect, paint); } } if (pen != NULL) { SkPaint paint; paint.setStyle(SkPaint::Style::kStroke_Style); InitPenIntoSkiaPaint(paint, pen); GetCanvas()->drawRRect(rrect, paint); } } void SkiaDrawing::DrawRoundRect(Brush* brush, Pen* pen, const fRect* rc, Float radiusX, Float radiusY) { SkRect rect = ToSkRect(rc); if (brush != NULL) { if (brush->GetRTTIType() == ImageBrush::RTTIType()) { DrawImageBrush(RTTICast<ImageBrush>(brush), &rect); } else { SkPaint paint; paint.setColor(brush->ToColor()); paint.setAntiAlias(true); paint.setStyle(SkPaint::Style::kFill_Style); GetCanvas()->drawRoundRect(rect, radiusX, radiusY, paint); } } if (pen != NULL) { SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::Style::kStroke_Style); InitPenIntoSkiaPaint(paint, pen); GetCanvas()->drawRoundRect(ToSkRect(rc), radiusX, radiusY, paint); } } void SkiaDrawing::DrawCircle(Brush* brush, Pen* pen, fPoint center, Float radius) { if (brush != NULL) { if (brush->GetRTTIType() == ImageBrush::RTTIType()) { fRect rect(center.x - radius, center.y - radius, center.x + radius, center.y + radius); DrawImageBrush(RTTICast<ImageBrush>(brush), &rect); } else { SkPaint paint; paint.setColor(brush->ToColor()); paint.setAntiAlias(true); paint.setStyle(SkPaint::Style::kFill_Style); GetCanvas()->drawCircle(center.x, center.y, radius, paint); } } if (pen != NULL) { SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::Style::kStroke_Style); InitPenIntoSkiaPaint(paint, pen); GetCanvas()->drawCircle(center.x, center.y, radius, paint); } } void SkiaDrawing::DrawEllipse(Brush* brush, Pen* pen, const fRect* rc) { SkRect rect = ToSkRect(rc); if (brush != NULL) { if (brush->GetRTTIType() == ImageBrush::RTTIType()) { DrawImageBrush(RTTICast<ImageBrush>(brush), &rect); } else { SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::Style::kFill_Style); InitBrushIntoSkPaint(paint, brush); GetCanvas()->drawOval(rect, paint); } } if (pen != NULL) { SkPaint paint; paint.setColor(brush->ToColor()); paint.setAntiAlias(true); paint.setStyle(SkPaint::Style::kStroke_Style); GetCanvas()->drawOval(rect, paint); } } void SkiaDrawing::DrawPath(Brush* brush, Pen* pen, OPath* opath) { SkPath* path = (SkPath*)opath->GetData(); if (brush != NULL) { SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::Style::kFill_Style); InitBrushIntoSkPaint(paint, brush); GetCanvas()->drawPath(*path, paint); } if (pen != NULL) { SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::Style::kStroke_Style); InitPenIntoSkiaPaint(paint, pen); GetCanvas()->drawPath(*path, paint); } } void SkiaDrawing::DrawRegion(Brush* brush, Pen* pen, Geometry* regm) { SkPath path; SkRegion* region = (SkRegion*)regm->GetData(); region->getBoundaryPath(&path); } void SkiaDrawing::DrawArc(Brush* brush, Pen* pen, fRect* oval, Float starta, Float sweepa, bool usecenter) { SkRect rect = ToSkRect(oval); if (brush != NULL) { SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::Style::kFill_Style); InitBrushIntoSkPaint(paint, brush); GetCanvas()->drawArc(rect, starta, sweepa, usecenter, paint); } if (pen != NULL) { SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::Style::kStroke_Style); InitPenIntoSkiaPaint(paint, pen); GetCanvas()->drawArc(rect, starta, sweepa, usecenter, paint); } } void SkiaDrawing::DrawImage(Bitmap* bmp, const fRect* rcdc, const fRect* rcimg, Byte alpha) { SkBitmap* skbmp = reinterpret_cast<SkBitmap*>(static_cast<LONG_PTR>(bmp->GetData())); SkIRect irc = SkIRect::MakeLTRB(rcimg->left, rcimg->top, rcimg->right, rcimg->bottom); SkPaint paint; if (alpha < 255) { paint.setAlpha(alpha); } GetCanvas()->drawBitmapRect(*skbmp, &irc, ToSkRect(rcdc), &paint); } void SkiaDrawing::DrawImage(Bitmap* bmp, const fRect* rcdc, const fRect* rcimg, Byte alpha, Color trans) { SkBitmap* skbmp = reinterpret_cast<SkBitmap*>(static_cast<LONG_PTR>(bmp->GetData())); SkPaint paint; SkIRect irc = SkIRect::MakeLTRB(rcimg->left, rcimg->top, rcimg->right, rcimg->bottom); paint.setAlpha(alpha); paint.setAntiAlias(true); GetCanvas()->drawBitmapRect(*skbmp, &irc, ToSkRect(rcdc), &paint); } void SkiaDrawing::DrawString(FormattedText* formattedText, const Char* text, int size, const fRect* rc) { SkRect skrc = ToSkRect(rc); SkPaint paint; SkTypeface* skface = SkTypeface::CreateFromName(formattedText->GetFontFamily().c_str(), SkTypeface::Style::kNormal); paint.setTypeface(skface); paint.setTextEncoding(SkPaint::kUTF16_TextEncoding); paint.setAntiAlias(true); paint.setAutohinted(true); paint.setLCDRenderText(true); paint.setEmbeddedBitmapText(true); if (skface->isItalic()) { paint.setTextSkewX((SkScalar)0.4); } int iFmt = 0; if (formattedText->GetSingleLine()) { iFmt |= SkTextOp::TextFormat::tSingleLine; SkTextOp::DrawSingleText(GetCanvas(), paint, skrc, text, size, iFmt); } else { iFmt |= SkTextOp::TextFormat::tWrapText; SkTextOp::DrawText(GetCanvas(), paint, skrc, text, size, iFmt); } } void SkiaDrawing::MeasureString(TmParam& tm, FormattedText* formattedText, const Char* text, int size) { } fSize SkiaDrawing::MeasureString(DrawInfo* tp, Float w, const Char* text, int size, bool bFlag) { fSize sz; int iFmt = 0; SkPaint::FontMetrics fm; SkPaint& paint = DrawInfoToSkia(tp); SkTypeface* skface = paint.getTypeface(); if (NULL == skface) { skface = SkTypeface::CreateFromName("Tahoma", SkTypeface::Style::kNormal); paint.setTypeface(skface); } paint.setTextEncoding(SkPaint::kUTF16_TextEncoding); paint.getFontMetrics(&fm); SkScalar lineSpace = CalcLineSpace(fm); if (!tp->GetSingleLine()) { SkScalar outLen = 0; int iLines = SkTextOp::ComputeWrapTextLineCount(paint, outLen, w, text, size); sz.cy = iLines * lineSpace; if (iLines == 1) { sz.cx = paint.measureText(text, size * 2); } else { sz.cx = outLen; } } else { sz.cx = paint.measureText(text, size * 2); sz.cy = lineSpace; } return sz; } Size SkDrawMeta::MeasureText(Float w, const Char* text, int size) { Size sz; int iFmt = 0; SkPaint::FontMetrics fm; SkPaint& paint = Paint(); SkTypeface* skface = paint.getTypeface(); if (NULL == skface) { skface = SkTypeface::CreateFromName("Tahoma", SkTypeface::Style::kNormal); paint.setTypeface(skface); } paint.setTextEncoding(SkPaint::kUTF16_TextEncoding); paint.getFontMetrics(&fm); SkScalar outLen = 0; int iLines = SkTextOp::ComputeWrapTextLineCount(paint, outLen, w, text, size); SkScalar lineSpace = CalcLineSpace(fm); sz.cy = iLines * lineSpace; if (iLines == 1) { sz.cx = paint.measureText(text, size * 2); } else { sz.cx = outLen; } return sz; } Size SkDrawMeta::MeasureText(Float w, const Char* text, int size, int& realCount) { Size measureSize; SkScalar outLen = 0; SkPaint::FontMetrics fm; SkPaint& paint = Paint(); SkTypeface* skface = paint.getTypeface(); if (NULL == skface) { skface = SkTypeface::CreateFromName("Tahoma", SkTypeface::Style::kNormal); paint.setTypeface(skface); } paint.setTextEncoding(SkPaint::kUTF16_TextEncoding); paint.getFontMetrics(&fm); realCount = SkTextOp::ComputeTextLines(paint, outLen, w, text, size); measureSize.cy = (LONG)CalcLineSpace(fm); measureSize.cx = (LONG)outLen; return measureSize; } }
24.659808
120
0.600156
2660dee65773eb47d544cdbf61d9424c09bfb4e2
622
cpp
C++
demo.cpp
asgs/cache
d1d31eaa51e1433546f94080908a2596d98826f4
[ "Unlicense" ]
null
null
null
demo.cpp
asgs/cache
d1d31eaa51e1433546f94080908a2596d98826f4
[ "Unlicense" ]
null
null
null
demo.cpp
asgs/cache
d1d31eaa51e1433546f94080908a2596d98826f4
[ "Unlicense" ]
null
null
null
#include <iostream> #include <map> #include <chrono> #include <thread> #include "cache.h" #include "datetime_utils.h" int main() { SimpleCache<std::string, std::string> cache; std::string value1 = "1"; std::string key1 = "a"; cache.put(key1, value1, current_time() + 3); std::string value2 = "2"; std::string key2 = "b"; cache.put(key2, value2, current_time() + 11); cache.print(); std::this_thread::sleep_for(std::chrono::seconds(5)); cache.print(); //std::cout << "value of key " << key1 << " is " << cache.get(key1); //std::cout << std::endl << "value of key " << key2 << " is " << cache.get(key2); }
23.037037
82
0.622186
2662f0342aea17a0c7cd36fc6c8edfda4fcaa9c2
2,445
cpp
C++
source/example.cpp
Nicola20/programmiersprachen-aufgabenblatt-3
3d213c3a5c46cfac04670bd9720334e9fd1fcf61
[ "MIT" ]
null
null
null
source/example.cpp
Nicola20/programmiersprachen-aufgabenblatt-3
3d213c3a5c46cfac04670bd9720334e9fd1fcf61
[ "MIT" ]
null
null
null
source/example.cpp
Nicola20/programmiersprachen-aufgabenblatt-3
3d213c3a5c46cfac04670bd9720334e9fd1fcf61
[ "MIT" ]
null
null
null
#include "window.hpp" #include "Circle.hpp" //#include "Rectangle.hpp" //#include "Vec2.hpp" #include <GLFW/glfw3.h> #include <utility> #include <cmath> #include <set> #include <iostream> #include <vector> #include <string> int main(int argc, char* argv[]) { Window win{std::make_pair(800,800)}; std::cout<<"Please enter a name of the circle you are searching for. \n"; string input; std::cin >> input; double first_timestamp = win.get_time(); Circle c1{200.0f, Vec2{300.0f,100.0f}, Color{0.0f}, "karl"}; Circle c2{100.0f, Vec2{250.0f,150.0f}, Color{0.0f}, "judith"}; std::vector<Circle> vec; vec.push_back(c1); vec.push_back(c2); while (!win.should_close()) { if (win.get_key(GLFW_KEY_ESCAPE) == GLFW_PRESS) { win.close(); } bool left_pressed = win.get_mouse_button(GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS; auto t = win.get_time(); float x1{400 + 380 * std::sin(t)}; float y1{400 + 380 * std::cos(t)}; float x2{400 + 380 * std::sin(2.0f*t)}; float y2{400 + 380 * std::cos(2.0f*t)}; float x3{400 + 380 * std::sin(t-10.f)}; float y3{400 + 380 * std::cos(t-10.f)}; win.draw_point(x1, y1, 1.0f, 0.0f, 0.0f); win.draw_point(x2, y2, 0.0f, 1.0f, 0.0f); win.draw_point(x3, y3, 0.0f, 0.0f, 1.0f); auto m = win.mouse_position(); if (left_pressed) { win.draw_line(30, 30, // from m.first, m.second, // to 1.0,0.0,0.0); } /*Ergänzungen zu Aufgabe 3.4*/ for (int i = 0; i < vec.size(); ++i) { if(vec[i].getName() == input) { double second_timestamp = win.get_time(); //std::cout << second_timestamp - first_timestamp << std::endl; if ((second_timestamp - first_timestamp) < 11) { vec[i].setColor(Color{1.0f, 0.0f, 0.0f}); } } vec[i].draw(win, vec[i].getColor()); } win.draw_line(0, m.second, 10, m.second, 0.0, 0.0, 0.0); win.draw_line(win.window_size().second - 10, m.second, win.window_size().second, m.second, 0.0, 0.0, 0.0); win.draw_line(m.first, 0, m.first, 10, 0.0, 0.0, 0.0); win.draw_line(m.first, win.window_size().second - 10, m.first, win.window_size().second, 0.0, 0.0, 0.0); std::string text = "mouse position: (" + std::to_string(m.first) + ", " + std::to_string(m.second) + ")"; win.draw_text(10, 5, 35.0f, text); win.update(); } return 0; }
26.010638
110
0.577096
26671dd7edc3c49d10e07e9e2dbabdb863ebba71
637
hpp
C++
include/lol/def/LolChatPlayerPreferences.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
1
2020-07-22T11:14:55.000Z
2020-07-22T11:14:55.000Z
include/lol/def/LolChatPlayerPreferences.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
null
null
null
include/lol/def/LolChatPlayerPreferences.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
4
2018-12-01T22:48:21.000Z
2020-07-22T11:14:56.000Z
#pragma once #include "../base_def.hpp" namespace lol { struct LolChatPlayerPreferences { std::string data; std::string hash; std::string type; uint64_t modified; }; inline void to_json(json& j, const LolChatPlayerPreferences& v) { j["data"] = v.data; j["hash"] = v.hash; j["type"] = v.type; j["modified"] = v.modified; } inline void from_json(const json& j, LolChatPlayerPreferences& v) { v.data = j.at("data").get<std::string>(); v.hash = j.at("hash").get<std::string>(); v.type = j.at("type").get<std::string>(); v.modified = j.at("modified").get<uint64_t>(); } }
28.954545
69
0.599686
266a1f110a44dfe36bb5da7c8969135b31ac459b
2,173
cpp
C++
src/certificate/ObjectIdentifier.cpp
LabSEC/libcryptosec
e53030ec32b52b6abeaa973a9f0bfba0eb2c2440
[ "BSD-3-Clause" ]
22
2015-08-26T16:40:59.000Z
2022-02-22T19:52:55.000Z
src/certificate/ObjectIdentifier.cpp
LabSEC/Libcryptosec
e53030ec32b52b6abeaa973a9f0bfba0eb2c2440
[ "BSD-3-Clause" ]
14
2015-09-01T00:39:22.000Z
2018-12-17T16:24:28.000Z
src/certificate/ObjectIdentifier.cpp
LabSEC/Libcryptosec
e53030ec32b52b6abeaa973a9f0bfba0eb2c2440
[ "BSD-3-Clause" ]
22
2015-08-31T19:17:37.000Z
2021-01-04T13:38:35.000Z
#include <libcryptosec/certificate/ObjectIdentifier.h> ObjectIdentifier::ObjectIdentifier() { this->asn1Object = ASN1_OBJECT_new(); // printf("New OID: nid: %d - length: %d\n", this->asn1Object->nid, this->asn1Object->length); } ObjectIdentifier::ObjectIdentifier(ASN1_OBJECT *asn1Object) { this->asn1Object = asn1Object; // printf("Set OID: nid: %d - length: %d\n", this->asn1Object->nid, this->asn1Object->length); } ObjectIdentifier::ObjectIdentifier(const ObjectIdentifier& objectIdentifier) { this->asn1Object = OBJ_dup(objectIdentifier.getObjectIdentifier()); } ObjectIdentifier::~ObjectIdentifier() { ASN1_OBJECT_free(this->asn1Object); } std::string ObjectIdentifier::getXmlEncoded() { return this->getXmlEncoded(""); } std::string ObjectIdentifier::getXmlEncoded(std::string tab) { std::string ret, oid; try { oid = this->getOid(); } catch (...) { oid = ""; } ret = tab + "<oid>" + oid + "</oid>\n"; return ret; } std::string ObjectIdentifier::getOid() throw (CertificationException) { char data[30]; if (!this->asn1Object->data) { throw CertificationException(CertificationException::SET_NO_VALUE, "ObjectIdentifier::getOid"); } OBJ_obj2txt(data, 30, this->asn1Object, 1); return std::string(data); } int ObjectIdentifier::getNid() const { return OBJ_obj2nid(this->asn1Object); } std::string ObjectIdentifier::getName() { const char *data; std::string ret; if (!this->asn1Object->data) { return "undefined"; } if (this->asn1Object->nid) { data = OBJ_nid2sn(this->asn1Object->nid); ret = data; } else if ((this->asn1Object->nid = OBJ_obj2nid(this->asn1Object)) != NID_undef) { data = OBJ_nid2sn(this->asn1Object->nid); ret = data; } else { ret = this->getOid(); } return ret; } ASN1_OBJECT* ObjectIdentifier::getObjectIdentifier() const { return this->asn1Object; } ObjectIdentifier& ObjectIdentifier::operator =(const ObjectIdentifier& value) { if (this->asn1Object) { ASN1_OBJECT_free(this->asn1Object); } if (value.getObjectIdentifier()->length > 0) { this->asn1Object = OBJ_dup(value.getObjectIdentifier()); } else { this->asn1Object = ASN1_OBJECT_new(); } return (*this); }
20.12037
97
0.702255
266b1ad7c6660c1a355af6b7563e09eb81b04022
235
cpp
C++
1st-course/AlgSD/lab_1/B.cpp
astappev/NURE
9c148c3212993471953781dec16c9c0205daab9a
[ "MIT" ]
null
null
null
1st-course/AlgSD/lab_1/B.cpp
astappev/NURE
9c148c3212993471953781dec16c9c0205daab9a
[ "MIT" ]
null
null
null
1st-course/AlgSD/lab_1/B.cpp
astappev/NURE
9c148c3212993471953781dec16c9c0205daab9a
[ "MIT" ]
null
null
null
#include <iostream> #include <math.h> using namespace std; int main() { int a,b,c,d; cin>>a; cin>>b; cin>>c; cin>>d; if (a==0 && b==0) cout<<"INF"; else if ( a==0 || b%a!=0 || c*(-b/a)+d==0) cout<<"NO"; else cout<<-(b/a); }
14.6875
56
0.506383
266b71ec36a696e07ffe79b3426a70709a9ac0c8
864
cpp
C++
IO/IO.cpp
STEMLab/IndoorData_Conversion
cb22b0cc0088a17a5ce2a89e3c3d5a8cb2551314
[ "MIT" ]
null
null
null
IO/IO.cpp
STEMLab/IndoorData_Conversion
cb22b0cc0088a17a5ce2a89e3c3d5a8cb2551314
[ "MIT" ]
null
null
null
IO/IO.cpp
STEMLab/IndoorData_Conversion
cb22b0cc0088a17a5ce2a89e3c3d5a8cb2551314
[ "MIT" ]
null
null
null
// // Created by byeonggon on 2018-11-12. // #include "IO.h" #include "TRANSFORM/Transform.h" #include <stdio.h> #include <ctype.h> #include <iostream> int CellSpace_ID=1; int CellSpaceBoundary_ID=1; int State_id=1; int Transition_id=1; int OSM_NODE_ID=-1; int OSM_WAY_ID=-30000; int OSM_RELATION_ID=-60000; namespace IO{ char * lowercase(char *input){ int i=0; char c; while(input[i]){ c=input[i]; input[i]=tolower(c); i++; } return input; } bool ISNOT_INDOORGML(char **input){ bool output=false; if (strcmp(lowercase(input[1]),"indoorgml")==0||strcmp(lowercase(input[2]),"indoorgml")==0) output=true; return output; } void ISNOT_INDORGML_MESSAGE(){ std::cout<<"INDOORGML FILE is not included among INPUT values."; } }
23.351351
99
0.603009
266daa49cd3e4f526a836bcde3a66b8eab32b4ae
12,976
cpp
C++
a3d/src/d3d12/a3dDescriptorSetLayout.cpp
ProjectAsura/asura-SDK
e823129856185b023b164415b7aec2de0ba9c338
[ "MIT" ]
42
2016-11-11T13:27:48.000Z
2021-07-27T17:53:43.000Z
a3d/src/d3d12/a3dDescriptorSetLayout.cpp
ProjectAsura/asura-SDK
e823129856185b023b164415b7aec2de0ba9c338
[ "MIT" ]
null
null
null
a3d/src/d3d12/a3dDescriptorSetLayout.cpp
ProjectAsura/asura-SDK
e823129856185b023b164415b7aec2de0ba9c338
[ "MIT" ]
2
2017-03-26T08:25:29.000Z
2018-10-24T06:10:29.000Z
//------------------------------------------------------------------------------------------------- // File : a3dDescriptorSetLayout.cpp // Desc : Descriptor Set Layout Implementation. // Copyright(c) Project Asura. All right reserved. //------------------------------------------------------------------------------------------------- namespace /* anonymous */ { //------------------------------------------------------------------------------------------------- // ネイティブ形式に変換します. //------------------------------------------------------------------------------------------------- D3D12_SHADER_VISIBILITY ToNativeShaderVisibility( uint32_t mask ) { if ( mask == a3d::SHADER_MASK_VERTEX ) { return D3D12_SHADER_VISIBILITY_VERTEX; } else if ( mask == a3d::SHADER_MASK_DOMAIN ) { return D3D12_SHADER_VISIBILITY_DOMAIN; } else if ( mask == a3d::SHADER_MASK_HULL ) { return D3D12_SHADER_VISIBILITY_HULL; } else if ( mask == a3d::SHADER_MASK_GEOMETRY ) { return D3D12_SHADER_VISIBILITY_GEOMETRY; } else if ( mask == a3d::SHADER_MASK_PIXEL ) { return D3D12_SHADER_VISIBILITY_PIXEL; } else if ( mask == a3d::SHADER_MASK_AMPLIFICATION) { return D3D12_SHADER_VISIBILITY_AMPLIFICATION; } else if ( mask == a3d::SHADER_MASK_MESH ) { return D3D12_SHADER_VISIBILITY_MESH; } return D3D12_SHADER_VISIBILITY_ALL; } //------------------------------------------------------------------------------------------------- // ネイティブのディスクリプタレンジに変換します. //------------------------------------------------------------------------------------------------ void ToNativeDescriptorRange( const a3d::DescriptorEntry& entry, D3D12_DESCRIPTOR_RANGE& result ) { switch(entry.Type) { case a3d::DESCRIPTOR_TYPE_CBV: result.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_CBV; break; case a3d::DESCRIPTOR_TYPE_UAV: result.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV; break; case a3d::DESCRIPTOR_TYPE_SRV: result.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; break; case a3d::DESCRIPTOR_TYPE_SMP: result.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER; break; } result.NumDescriptors = 1; result.BaseShaderRegister = entry.ShaderRegister; result.RegisterSpace = 0; result.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; } } // namespace /* anonymous */ namespace a3d { /////////////////////////////////////////////////////////////////////////////////////////////////// // DescriptorSetLayout class /////////////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------------- // コンストラクタです. //------------------------------------------------------------------------------------------------- DescriptorSetLayout::DescriptorSetLayout() : m_RefCount (1) , m_pDevice (nullptr) , m_pRootSignature (nullptr) , m_Type (PIPELINE_GRAPHICS) { memset( &m_Desc, 0, sizeof(m_Desc) ); } //------------------------------------------------------------------------------------------------- // デストラクタです. //------------------------------------------------------------------------------------------------- DescriptorSetLayout::~DescriptorSetLayout() { Term(); } //------------------------------------------------------------------------------------------------- // 初期化処理を行います. //------------------------------------------------------------------------------------------------- bool DescriptorSetLayout::Init(IDevice* pDevice, const DescriptorSetLayoutDesc* pDesc) { if (pDevice == nullptr || pDesc == nullptr) { return false; } Term(); m_pDevice = static_cast<Device*>(pDevice); m_pDevice->AddRef(); auto pNativeDevice = m_pDevice->GetD3D12Device(); A3D_ASSERT(pNativeDevice); memcpy( &m_Desc, pDesc, sizeof(m_Desc) ); bool isCompute = false; for(auto i=0u; i<pDesc->EntryCount; ++i) { if ((pDesc->Entries[i].ShaderMask & SHADER_MASK_COMPUTE) == SHADER_MASK_COMPUTE) { m_Type = PIPELINE_COMPUTE; isCompute = true; } if ((pDesc->Entries[i].ShaderMask & SHADER_MASK_VERTEX) == SHADER_MASK_VERTEX) { m_Type = PIPELINE_GRAPHICS; if (isCompute) { return false; } } if (((pDesc->Entries[i].ShaderMask & SHADER_MASK_AMPLIFICATION) == SHADER_MASK_AMPLIFICATION) || ((pDesc->Entries[i].ShaderMask & SHADER_MASK_MESH) == SHADER_MASK_MESH)) { m_Type = PIPELINE_GEOMETRY; if (isCompute) { return false; } } } { auto pEntries = new D3D12_DESCRIPTOR_RANGE [pDesc->EntryCount]; A3D_ASSERT(pEntries); auto pParams = new D3D12_ROOT_PARAMETER [pDesc->EntryCount]; A3D_ASSERT(pParams); auto mask = 0; for(auto i=0u; i<pDesc->EntryCount; ++i) { ToNativeDescriptorRange(pDesc->Entries[i], pEntries[i]); pParams[i].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; pParams[i].DescriptorTable.NumDescriptorRanges = 1; pParams[i].DescriptorTable.pDescriptorRanges = &pEntries[i]; pParams[i].ShaderVisibility = ToNativeShaderVisibility( pDesc->Entries[i].ShaderMask ); mask |= pDesc->Entries[i].ShaderMask; } bool shaders[5] = {}; if (m_Type == PIPELINE_GEOMETRY) { if ( mask & SHADER_MASK_AMPLIFICATION ) { shaders[0] = true; } if ( mask & SHADER_MASK_MESH ) { shaders[1] = true; } if ( mask & SHADER_MASK_PIXEL ) { shaders[2] = true; } } else { if ( mask & SHADER_MASK_VERTEX ) { shaders[0] = true; } if ( mask & SHADER_MASK_HULL ) { shaders[1] = true; } if ( mask & SHADER_MASK_DOMAIN ) { shaders[2] = true; } if ( mask & SHADER_MASK_GEOMETRY ) { shaders[3] = true; } if ( mask & SHADER_MASK_PIXEL ) { shaders[4] = true; } } D3D12_ROOT_SIGNATURE_DESC desc = {}; desc.NumParameters = pDesc->EntryCount; desc.pParameters = pParams; desc.NumStaticSamplers = 0; desc.pStaticSamplers = nullptr; desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; if (pDesc->EntryCount >= 0) { if (m_Type == PIPELINE_GEOMETRY) { desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; if (shaders[0] == false) { desc.Flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS; } if (shaders[1] == false) { desc.Flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS; } if (shaders[2] == false) { desc.Flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS; } } else { if (shaders[0] == false) { desc.Flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS; } if (shaders[1] == false) { desc.Flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS; } if (shaders[2] == false) { desc.Flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS; } if (shaders[3] == false) { desc.Flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS; } if (shaders[4] == false) { desc.Flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS; } } } ID3DBlob* pSignatureBlob = nullptr; ID3DBlob* pErrorBlob = nullptr; auto hr = D3D12SerializeRootSignature( &desc, D3D_ROOT_SIGNATURE_VERSION_1, &pSignatureBlob, &pErrorBlob); delete [] pParams; delete [] pEntries; if ( FAILED(hr) ) { SafeRelease(pSignatureBlob); SafeRelease(pErrorBlob); return false; } hr = pNativeDevice->CreateRootSignature( 0, pSignatureBlob->GetBufferPointer(), pSignatureBlob->GetBufferSize(), IID_PPV_ARGS(&m_pRootSignature)); SafeRelease(pSignatureBlob); SafeRelease(pErrorBlob); if ( FAILED(hr) ) { return false; } } return true; } //------------------------------------------------------------------------------------------------- // 終了処理を行います. //------------------------------------------------------------------------------------------------- void DescriptorSetLayout::Term() { SafeRelease(m_pRootSignature); SafeRelease(m_pDevice); memset( &m_Desc, 0, sizeof(m_Desc) ); } //------------------------------------------------------------------------------------------------- // 参照カウントを増やします. //------------------------------------------------------------------------------------------------- void DescriptorSetLayout::AddRef() { m_RefCount++; } //------------------------------------------------------------------------------------------------- // 解放処理を行います. //------------------------------------------------------------------------------------------------- void DescriptorSetLayout::Release() { m_RefCount--; if (m_RefCount == 0) { delete this; } } //------------------------------------------------------------------------------------------------- // 参照カウントを取得します. //------------------------------------------------------------------------------------------------- uint32_t DescriptorSetLayout::GetCount() const { return m_RefCount; } //------------------------------------------------------------------------------------------------- // デバイスを取得します. //------------------------------------------------------------------------------------------------- void DescriptorSetLayout::GetDevice(IDevice** ppDevice) { *ppDevice = m_pDevice; if (m_pDevice != nullptr) { m_pDevice->AddRef(); } } //------------------------------------------------------------------------------------------------- // ディスクリプタセットを割り当てます. //------------------------------------------------------------------------------------------------- bool DescriptorSetLayout::CreateDescriptorSet(IDescriptorSet** ppDesctiproSet) { if (ppDesctiproSet == nullptr) { return false; } auto pWrapDevice = reinterpret_cast<Device*>(m_pDevice); A3D_ASSERT(pWrapDevice != nullptr); if (!DescriptorSet::Create(m_pDevice, this, ppDesctiproSet)) { return false; } return true; } //------------------------------------------------------------------------------------------------- // ルートシグニチャを取得します. //------------------------------------------------------------------------------------------------- ID3D12RootSignature* DescriptorSetLayout::GetD3D12RootSignature() const { return m_pRootSignature; } //------------------------------------------------------------------------------------------------- // パイプラインタイプを取得します. //------------------------------------------------------------------------------------------------- uint8_t DescriptorSetLayout::GetType() const { return m_Type; } //------------------------------------------------------------------------------------------------- // 構成設定を取得します. //------------------------------------------------------------------------------------------------- const DescriptorSetLayoutDesc& DescriptorSetLayout::GetDesc() const { return m_Desc; } //------------------------------------------------------------------------------------------------- // 生成処理を行います. //------------------------------------------------------------------------------------------------- bool DescriptorSetLayout::Create ( IDevice* pDevice, const DescriptorSetLayoutDesc* pDesc, IDescriptorSetLayout** ppLayout ) { if (pDevice == nullptr || pDesc == nullptr || ppLayout == nullptr) { return false; } auto instance = new DescriptorSetLayout; if (instance == nullptr) { return false; } if (!instance->Init(pDevice, pDesc)) { instance->Release(); return false; } *ppLayout = instance; return true; } } // namespace a3d
36.655367
116
0.433955
266db602595f4fddce7894fe25ad418c77987836
9,726
cpp
C++
modules/asset/src/scene.cpp
lenamueller/glpp
f7d29e5924537fd405a5bb409d67e65efdde8d9e
[ "MIT" ]
16
2019-12-10T19:44:17.000Z
2022-01-04T03:16:19.000Z
modules/asset/src/scene.cpp
lenamueller/glpp
f7d29e5924537fd405a5bb409d67e65efdde8d9e
[ "MIT" ]
null
null
null
modules/asset/src/scene.cpp
lenamueller/glpp
f7d29e5924537fd405a5bb409d67e65efdde8d9e
[ "MIT" ]
3
2021-06-04T21:56:55.000Z
2022-03-03T06:47:56.000Z
#include "glpp/asset/scene.hpp" #include <assimp/scene.h> #include <assimp/postprocess.h> #include <assimp/Importer.hpp> namespace glpp::asset { void traverse_scene_graph( const aiScene* scene, const aiNode* node, glm::mat4 old, std::vector<mesh_t>& meshes ); struct light_cast_t { const aiScene* scene; const aiLight* light; template <class T> bool has_type() const; template <class T> T cast() const; private: template <class T> void check_type() const; }; struct parse_texture_stack_t { const aiMaterial* material; scene_t& scene; using texture_stack_description_t = std::pair<aiTextureType , texture_stack_t material_t::*>; glpp::asset::op_t convert(aiTextureOp op) const; void operator()(const texture_stack_description_t channel_desc); }; aiMatrix4x4 get_transformation(const aiNode* node); scene_t::scene_t(const char* file_name) { Assimp::Importer importer; auto scene = importer.ReadFile(file_name, aiProcess_Triangulate); if(!scene) { throw std::runtime_error(std::string("Could not open ")+file_name+"."); } materials.reserve(scene->mNumMaterials); std::for_each_n( scene->mMaterials, scene->mNumMaterials, [&](const aiMaterial* material) { aiString name; const auto success = material->Get(AI_MATKEY_NAME, name); if(aiReturn_SUCCESS == success) { aiColor3D diffuse, specular, ambient, emissive; material->Get(AI_MATKEY_COLOR_DIFFUSE, diffuse); material->Get(AI_MATKEY_COLOR_SPECULAR, specular); material->Get(AI_MATKEY_COLOR_AMBIENT, ambient); material->Get(AI_MATKEY_COLOR_EMISSIVE, emissive); float shininess; material->Get(AI_MATKEY_SHININESS, shininess); materials.emplace_back(material_t{ name.C_Str(), glm::vec3(diffuse.r, diffuse.g, diffuse.b), {}, glm::vec3(emissive.r, emissive.g, emissive.b), {}, glm::vec3(ambient.r, ambient.g, ambient.b), {}, glm::vec3(specular.r, specular.g, specular.b), {}, shininess }); constexpr std::array channels { std::make_pair(aiTextureType_DIFFUSE, &material_t::diffuse_textures), std::make_pair(aiTextureType_EMISSIVE, &material_t::emissive_textures), std::make_pair(aiTextureType_AMBIENT, &material_t::ambient_textures), std::make_pair(aiTextureType_SPECULAR, &material_t::specular_textures) }; std::for_each(channels.begin(), channels.end(), parse_texture_stack_t{ material, *this}); } } ); traverse_scene_graph(scene, scene->mRootNode, glm::mat4(1.0f), meshes); std::for_each_n(scene->mLights, scene->mNumLights, [this, scene](const aiLight* light) { light_cast_t light_cast{ scene, light }; if(light_cast.has_type<ambient_light_t>()) { ambient_lights.emplace_back(light_cast.cast<ambient_light_t>()); } else if(light_cast.has_type<directional_light_t>()) { directional_lights.emplace_back(light_cast.cast<directional_light_t>()); } else if(light_cast.has_type<spot_light_t>()) { spot_lights.emplace_back(light_cast.cast<spot_light_t>()); } else if(light_cast.has_type<point_light_t>()) { point_lights.emplace_back(light_cast.cast<point_light_t>()); } }); cameras.reserve(scene->mNumCameras); std::transform(scene->mCameras, scene->mCameras+scene->mNumCameras, std::back_inserter(cameras), [&](const aiCamera* cam){ aiMatrix4x4 transform = get_transformation(scene->mRootNode->FindNode(cam->mName)); auto aiPos = transform*cam->mPosition; const glm::vec3 position { aiPos.x, aiPos.y, aiPos.z }; auto aiLookAt = transform*cam->mLookAt; const glm::vec3 look_at { aiLookAt.x, aiLookAt.y, aiLookAt.z }; auto aiUp = transform*cam->mUp; const glm::vec3 up { aiUp.x, aiUp.y, aiUp.z }; return core::render::camera_t( position, look_at, up, glm::degrees(cam->mHorizontalFOV), cam->mClipPlaneNear, cam->mClipPlaneFar, cam->mAspect ); }); } mesh_t mesh_from_assimp(const aiMesh* aiMesh, const glm::mat4& model_matrix) { mesh_t mesh; using vertex_description_t = mesh_t::vertex_description_t; for(auto i = 0u; i < aiMesh->mNumVertices; ++i) { const auto pos = aiMesh->mVertices[i]; const auto normal = aiMesh->mNormals[i]; aiVector3D tex; if(aiMesh->GetNumUVChannels() > 0) { tex = aiMesh->mTextureCoords[0][i]; } mesh.model.verticies.emplace_back(vertex_description_t{ glm::vec3{ pos.x, pos.y, pos.z }, glm::vec3{ normal.x, normal.y, normal.z }, glm::vec2{ tex.x, tex.y }, }); } std::for_each_n( aiMesh->mFaces, aiMesh->mNumFaces, [&](const aiFace& face){ std::copy_n(face.mIndices, face.mNumIndices, std::back_inserter(mesh.model.indicies)); } ); mesh.model_matrix = model_matrix; mesh.material_index = aiMesh->mMaterialIndex; return mesh; } void traverse_scene_graph( const aiScene* scene, const aiNode* node, glm::mat4 old, std::vector<mesh_t>& meshes ) { glm::mat4 transformation = glm::transpose(glm::make_mat4(&(node->mTransformation.a1)))*old; std::for_each_n(node->mMeshes, node->mNumMeshes, [&](unsigned int meshId){ const auto* mesh = scene->mMeshes[meshId]; meshes.emplace_back( mesh_from_assimp(mesh, transformation) ); }); std::for_each_n(node->mChildren, node->mNumChildren, [&](const aiNode* next) { traverse_scene_graph(scene, next, transformation, meshes); }); } aiMatrix4x4 get_transformation(const aiNode* node) { aiMatrix4x4 transform; do { const auto node_transform = node->mTransformation; transform = transform*node_transform; node = node->mParent; } while(node); return transform; } template <class T> bool light_cast_t::has_type() const { if constexpr(std::is_same_v<T, ambient_light_t>) { return light->mType == aiLightSourceType::aiLightSource_AMBIENT; } if constexpr(std::is_same_v<T, directional_light_t>) { return light->mType == aiLightSourceType::aiLightSource_DIRECTIONAL; } if constexpr(std::is_same_v<T, point_light_t>) { return light->mType == aiLightSourceType::aiLightSource_POINT; } if constexpr(std::is_same_v<T, spot_light_t>) { return light->mType == aiLightSourceType::aiLightSource_SPOT; } return false; } template <class T> T light_cast_t::cast() const { check_type<T>(); const glm::vec3 ambient { light->mColorAmbient.r, light->mColorAmbient.g, light->mColorAmbient.b }; const glm::vec3 diffuse { light->mColorDiffuse.r, light->mColorDiffuse.g, light->mColorDiffuse.b }; const glm::vec3 specular { light->mColorSpecular.r, light->mColorSpecular.g, light->mColorSpecular.b }; if constexpr(std::is_same_v<T, ambient_light_t>) { return ambient_light_t{ ambient, diffuse, specular }; } const glm::vec3 direction { light->mDirection.x, light->mDirection.y, light->mDirection.z }; if constexpr(std::is_same_v<T, directional_light_t>) { return directional_light_t { direction, ambient, diffuse, specular }; } const auto transform = get_transformation(scene->mRootNode->FindNode(light->mName)); const auto ai_position = transform*light->mPosition; const glm::vec3 position { ai_position.x, ai_position.y, ai_position.z }; const float attenuation_constant = light->mAttenuationConstant; const float attenuation_linear = light->mAttenuationLinear; const float attenuation_quadratic = light->mAttenuationQuadratic; if constexpr(std::is_same_v<T, point_light_t>) { return point_light_t { position, ambient, diffuse, specular, attenuation_constant, attenuation_linear, attenuation_quadratic }; } float inner_cone = light->mAngleInnerCone; float outer_cone = light->mAngleOuterCone; if constexpr(std::is_same_v<T, spot_light_t>) { return spot_light_t { position, direction, ambient, diffuse, specular, inner_cone, outer_cone, attenuation_constant, attenuation_linear, attenuation_quadratic }; } } template <class T> void light_cast_t::check_type() const { if(!has_type<T>()) { throw std::runtime_error("Light type missmatch"); } } glpp::asset::op_t parse_texture_stack_t::convert(aiTextureOp op) const { switch(op) { case aiTextureOp::aiTextureOp_Add: return glpp::asset::op_t::addition; case aiTextureOp::aiTextureOp_Divide: return glpp::asset::op_t::division; case aiTextureOp::aiTextureOp_Multiply: return glpp::asset::op_t::multiplication; case aiTextureOp::aiTextureOp_SignedAdd: return glpp::asset::op_t::signed_addition; case aiTextureOp::aiTextureOp_SmoothAdd: return glpp::asset::op_t::smooth_addition; case aiTextureOp::aiTextureOp_Subtract: return glpp::asset::op_t::addition; default: throw std::runtime_error("Could not convert texture op"); } } void parse_texture_stack_t::operator()(const texture_stack_description_t channel_desc) { auto [channel, corresponding_texture_stack] = channel_desc; const auto stack_size = material->GetTextureCount(aiTextureType_DIFFUSE); for(auto i = 0u; i < stack_size; ++i) { float strength = 1.0f; aiString path; aiTextureOp op = aiTextureOp_Add; material->GetTexture(channel, i, &path, nullptr, nullptr, &strength, &op, nullptr); std::string std_path{ path.C_Str() }; const auto it = std::find(scene.textures.begin(), scene.textures.end(), std_path); const size_t key = std::distance(scene.textures.begin(), it); if(it == scene.textures.end()) { scene.textures.emplace_back(std::move(std_path)); } const auto glpp_op = convert(op); if(op == aiTextureOp_Subtract) { strength *= -1.0; } (scene.materials.back().*corresponding_texture_stack).emplace_back( texture_stack_entry_t{ key, strength, glpp_op } ); } } }
30.778481
123
0.707177
267f44b12c7e1a6ce6e5ba457f0e28d4d3cfe4bd
2,992
cc
C++
components/previews/core/previews_data_savings.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
components/previews/core/previews_data_savings.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
components/previews/core/previews_data_savings.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/previews/core/previews_data_savings.h" #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "components/data_reduction_proxy/core/common/data_savings_recorder.h" namespace previews { PreviewsDataSavings::PreviewsDataSavings( data_reduction_proxy::DataSavingsRecorder* data_savings_recorder) : data_savings_recorder_(data_savings_recorder) { DCHECK(data_savings_recorder); } PreviewsDataSavings::~PreviewsDataSavings() { DCHECK(thread_checker_.CalledOnValidThread()); } void PreviewsDataSavings::RecordDataSavings( const std::string& fully_qualified_domain_name, int64_t data_used, int64_t original_size) { DCHECK(thread_checker_.CalledOnValidThread()); // Only record savings when data saver is enabled. if (!data_savings_recorder_->UpdateDataSavings(fully_qualified_domain_name, data_used, original_size)) { // Record metrics in KB for previews with data saver disabled. UMA_HISTOGRAM_COUNTS("Previews.OriginalContentLength.DataSaverDisabled", original_size >> 10); UMA_HISTOGRAM_COUNTS("Previews.ContentLength.DataSaverDisabled", data_used >> 10); if (original_size >= data_used) { UMA_HISTOGRAM_COUNTS("Previews.DataSavings.DataSaverDisabled", (original_size - data_used) >> 10); UMA_HISTOGRAM_PERCENTAGE( "Previews.DataSavingsPercent.DataSaverDisabled", (original_size - data_used) * 100 / original_size); } else { UMA_HISTOGRAM_COUNTS("Previews.DataInflation.DataSaverDisabled", (data_used - original_size) >> 10); UMA_HISTOGRAM_PERCENTAGE( "Previews.DataInflationPercent.DataSaverDisabled", (data_used - original_size) * 100 / data_used); } return; } // Record metrics in KB for previews with data saver enabled. UMA_HISTOGRAM_COUNTS("Previews.OriginalContentLength.DataSaverEnabled", original_size >> 10); UMA_HISTOGRAM_COUNTS("Previews.ContentLength.DataSaverEnabled", data_used >> 10); if (original_size >= data_used) { UMA_HISTOGRAM_COUNTS("Previews.DataSavings.DataSaverEnabled", (original_size - data_used) >> 10); UMA_HISTOGRAM_PERCENTAGE("Previews.DataSavingsPercent.DataSaverEnabled", (original_size - data_used) * 100 / original_size); } else { UMA_HISTOGRAM_COUNTS("Previews.DataInflation.DataSaverEnabled", (data_used - original_size) >> 10); UMA_HISTOGRAM_PERCENTAGE("Previews.DataInflationPercent.DataSaverEnabled", (data_used - original_size) * 100 / data_used); } } } // namespace previews
41.555556
80
0.687834
2681f01f49362550d596e64e01dd9c88d2b11557
580
hpp
C++
src/sn_Exception/source_location_extend.hpp
Airtnp/SuperNaiveCppLib
0745aa79dc5060cd0f7025658164374b991c698e
[ "MIT" ]
4
2017-04-01T08:09:09.000Z
2017-05-20T11:35:58.000Z
src/sn_Exception/source_location_extend.hpp
Airtnp/ACppLib
0745aa79dc5060cd0f7025658164374b991c698e
[ "MIT" ]
null
null
null
src/sn_Exception/source_location_extend.hpp
Airtnp/ACppLib
0745aa79dc5060cd0f7025658164374b991c698e
[ "MIT" ]
null
null
null
// // Created by Airtnp on 10/18/2019. // #ifndef ACPPLIB_SOURCE_LOCATION_EXTEND_HPP #define ACPPLIB_SOURCE_LOCATION_EXTEND_HPP #include <utility> namespace sn_Exception { namespace source_location { /// For `std::source_location` after variadic template argumentss template <typename ...Ts> struct vdebug { vdebug(Ts&&... ts, const std::source_location& loc = std::source_location::current()); }; template <typename ...Ts> vdebug(Ts&&...) -> vdebug<Ts...>; } } #endif //ACPPLIB_SOURCE_LOCATION_EXTEND_HPP
23.2
98
0.655172
2682206794cdbd6f5715731c73a0cbaf0a403230
20,518
hxx
C++
include/vigra/multi_opencl.hxx
burgerdev/vigra
f9f8d0b3224f3dc89bc7d0caf1126d49f6d4a3ca
[ "MIT" ]
316
2015-01-01T02:06:53.000Z
2022-03-28T08:37:28.000Z
include/vigra/multi_opencl.hxx
burgerdev/vigra
f9f8d0b3224f3dc89bc7d0caf1126d49f6d4a3ca
[ "MIT" ]
232
2015-01-06T23:51:07.000Z
2022-03-18T13:14:02.000Z
include/vigra/multi_opencl.hxx
burgerdev/vigra
f9f8d0b3224f3dc89bc7d0caf1126d49f6d4a3ca
[ "MIT" ]
150
2015-01-05T02:11:18.000Z
2022-03-16T09:44:14.000Z
/************************************************************************/ /* */ /* Copyright 1998-2004 by Ullrich Koethe */ /* Copyright 2011-2011 by Michael Tesch */ /* */ /* This file is part of the VIGRA computer vision library. */ /* The VIGRA Website is */ /* http://hci.iwr.uni-heidelberg.de/vigra/ */ /* Please direct questions, bug reports, and contributions to */ /* ullrich.koethe@iwr.uni-heidelberg.de or */ /* vigra@informatik.uni-hamburg.de */ /* */ /* Permission is hereby granted, free of charge, to any person */ /* obtaining a copy of this software and associated documentation */ /* files (the "Software"), to deal in the Software without */ /* restriction, including without limitation the rights to use, */ /* copy, modify, merge, publish, distribute, sublicense, and/or */ /* sell copies of the Software, and to permit persons to whom the */ /* Software is furnished to do so, subject to the following */ /* conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the */ /* Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */ /* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */ /* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */ /* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */ /* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */ /* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */ /* OTHER DEALINGS IN THE SOFTWARE. */ /* */ /************************************************************************/ #ifndef VIGRA_OPENCL_HXX #define VIGRA_OPENCL_HXX #include "numerictraits.hxx" #ifdef __APPLE__ #include <OpenCL/opencl.h> #else #include <CL/opencl.h> #endif namespace vigra { /********************************************************/ /* */ /* NumericTraits */ /* */ /********************************************************/ #ifndef NO_PARTIAL_TEMPLATE_SPECIALIZATION #define VIGRA_OPENCL_VECTYPEN_INTEGER_TRAITS(basetype, n) \ template<> \ struct NumericTraits< basetype##n > \ { \ typedef basetype##n Type; \ typedef Type Promote; \ typedef Type UnsignedPromote; \ typedef Type RealPromote; \ typedef std::complex<Type> ComplexPromote; \ typedef basetype ValueType; \ \ typedef VigraFalseType isIntegral; \ typedef VigraFalseType isScalar; \ typedef typename NumericTraits<ValueType>::isSigned isSigned; \ typedef VigraFalseType isOrdered; \ typedef typename NumericTraits<ValueType>::isComplex isComplex; \ \ static Type zero() { Type x; bzero(&x, sizeof(x)); return x; } \ static Type one() { Type x = {{1}}; return x; } \ static Type nonZero() { return one(); } \ \ static Promote toPromote(Type const & v) { return v; } \ static Type fromPromote(Promote const & v) { return v; } \ static Type fromRealPromote(RealPromote v) { return v; } \ } #define VIGRA_OPENCL_VECTYPEN_REAL_TRAITS(basetype, n) \ template<> \ struct NumericTraits< basetype##n > \ { \ typedef basetype##n Type; \ typedef Type Promote; \ typedef Type UnsignedPromote; \ typedef Type RealPromote; \ typedef std::complex<Type> ComplexPromote; \ typedef basetype ValueType; \ \ typedef VigraFalseType isIntegral; \ typedef VigraFalseType isScalar; \ typedef typename NumericTraits<ValueType>::isSigned isSigned; \ typedef VigraFalseType isOrdered; \ typedef typename NumericTraits<ValueType>::isComplex isComplex; \ \ static Type zero() { Type x; bzero(&x, sizeof(x)); return x; } \ static Type one() { Type x = {{1}}; return x; } \ static Type nonZero() { return one(); } \ static Type epsilon() { Type x; x.x = NumericTraits<ValueType>::epsilon(); return x; } \ static Type smallestPositive() { Type x; x.x = NumericTraits<ValueType>::smallestPositive(); return x; } \ \ static Promote toPromote(Type const & v) { return v; } \ static Type fromPromote(Promote const & v) { return v; } \ static Type fromRealPromote(RealPromote v) { return v; } \ } /// \todo - fix one() - maybe with .hi and .lo accessors? #define VIGRA_OPENCL_VECN_TRAITS(n) \ VIGRA_OPENCL_VECTYPEN_INTEGER_TRAITS(cl_char, n); \ VIGRA_OPENCL_VECTYPEN_INTEGER_TRAITS(cl_uchar, n); \ VIGRA_OPENCL_VECTYPEN_INTEGER_TRAITS(cl_short, n); \ VIGRA_OPENCL_VECTYPEN_INTEGER_TRAITS(cl_ushort, n); \ VIGRA_OPENCL_VECTYPEN_INTEGER_TRAITS(cl_int, n); \ VIGRA_OPENCL_VECTYPEN_INTEGER_TRAITS(cl_uint, n); \ VIGRA_OPENCL_VECTYPEN_INTEGER_TRAITS(cl_long, n); \ VIGRA_OPENCL_VECTYPEN_INTEGER_TRAITS(cl_ulong, n); \ VIGRA_OPENCL_VECTYPEN_REAL_TRAITS(cl_float, n); \ VIGRA_OPENCL_VECTYPEN_REAL_TRAITS(cl_double, n); VIGRA_OPENCL_VECN_TRAITS(2); VIGRA_OPENCL_VECN_TRAITS(3); //VIGRA_OPENCL_VECN_TRAITS(4); // cl_type4 is the same as cl_type3 VIGRA_OPENCL_VECN_TRAITS(8); VIGRA_OPENCL_VECN_TRAITS(16); #undef VIGRA_OPENCL_VECTYPEN_INTEGER_TRAITS #undef VIGRA_OPENCL_VECTYPEN_REAL_TRAITS #undef VIGRA_OPENCL_VECN_TRAITS /** \todo looks like the windows CL/cl_platform.h does signed/unsigned * strangely, so that the signed properties may not have the right * NumericalTraits::isSigned -- not sure if there's a reason for that. */ #endif // NO_PARTIAL_TEMPLATE_SPECIALIZATION /********************************************************/ /* */ /* SquareRootTraits */ /* */ /********************************************************/ /********************************************************/ /* */ /* NormTraits */ /* */ /********************************************************/ #if 0 template<> struct NormTraits<fftw_complex> { typedef fftw_complex Type; typedef fftw_real SquaredNormType; typedef fftw_real NormType; }; template<class Real> struct NormTraits<FFTWComplex<Real> > { typedef FFTWComplex<Real> Type; typedef typename Type::SquaredNormType SquaredNormType; typedef typename Type::NormType NormType; }; #endif /********************************************************/ /* */ /* PromoteTraits */ /* */ /********************************************************/ #if 0 template<class T> struct CanSkipInitialization<std::complex<T> > { typedef typename CanSkipInitialization<T>::type type; static const bool value = type::asBool; }; #endif /********************************************************/ /* */ /* multi_math */ /* */ /********************************************************/ namespace multi_math { /// \todo ! /** OpenCL 1.1 [6.2] - Convert operators */ /** OpenCL 1.1 [6.3] - Scalar/vector math operators */ /** OpenCL 1.1 [6.11.2] - Math Built-in Functions */ /** OpenCL 1.1 [6.11.3] - Integer Built-in Functions */ /** OpenCL 1.1 [6.11.4] - Common Built-in Functions */ /** OpenCL 1.1 [6.11.5] - Geometric Built-in Functions */ /** OpenCL 1.1 [6.11.6] - Relational Built-in Functions */ /** OpenCL 1.1 [6.11.7] - Vector Data Load/Store Built-in Functions */ /** OpenCL 1.1 [6.11.12] - Misc Vector Built-in Functions */ /** OpenCL 1.1 [6.11.12] - Image Read and Write Built-in Functions */ } // namespace multi_math /********************************************************/ /* */ /* Channel Accessors */ /* */ /********************************************************/ /** \addtogroup DataAccessors */ //@{ /** \defgroup OpenCL-Accessors Accessors for OpenCL types Encapsulate access to members of OpenCL vector types. <b>\#include</b> \<vigra/multi_opencl.hxx\> OpenCL 1.1 [6.1.7] - Vector Components - cl_TYPE2Accessor_x - cl_TYPE2Accessor_y - cl_TYPE2Accessor_s0 - cl_TYPE2Accessor_s1 - cl_TYPE2WriteAccessor_x - cl_TYPE2WriteAccessor_y - cl_TYPE2WriteAccessor_s0 - cl_TYPE2WriteAccessor_s1 - cl_TYPE3Accessor_x - cl_TYPE3Accessor_y - cl_TYPE3Accessor_z - cl_TYPE3Accessor_s0 - cl_TYPE3Accessor_s1 - cl_TYPE3Accessor_s2 - cl_TYPE3WriteAccessor_x - cl_TYPE3WriteAccessor_y - cl_TYPE3WriteAccessor_z - cl_TYPE3WriteAccessor_s0 - cl_TYPE3WriteAccessor_s1 - ... where TYPE is one of {char, uchar, short, ushort, int, uint, long, ulong, float, double } For example: \code #include <vigra/multi_opencl.hxx> MultiArrayView<2, cl_double3 > dataView = ...; vigra::FindMinMax<double> minmax; vigra::inspectMultiArray(srcMultiArrayRange(dataView, cl_double3Accessor_z()), minmax); std::cout << "range of .z: " << minmax.min << " - " << minmax.max; \endcode */ //@{ /** \class cl_charNAccessor_COMP access the first component. \class cl_TYPE3WriteAccessor_s1 access the second component. \class cl_TYPE3WriteAccessor_s2 access the third component. */ //@} //@} #define VIGRA_OPENCL_TYPE_ACCESSOR(basetype, n, NTH) \ class basetype##n##Accessor_##NTH \ { \ public: \ /** The accessor's value type. */ \ typedef NumericTraits< basetype##n >::ValueType value_type; \ \ /** Read component at iterator position. */ \ template <class ITERATOR> \ value_type operator()(ITERATOR const & i) const { \ return (*i).NTH; \ } \ \ /** Read component at offset from iterator position. */ \ template <class ITERATOR, class DIFFERENCE> \ value_type operator()(ITERATOR const & i, DIFFERENCE d) const { \ return i[d].NTH; \ } \ \ /** Write component at iterator position from a scalar. */ \ template <class ITERATOR> \ void set(value_type const & v, ITERATOR const & i) const { \ (*i).NTH = v; \ } \ \ /** Write component at offset from iterator position from a scalar. */ \ template <class ITERATOR, class DIFFERENCE> \ void set(value_type const & v, ITERATOR const & i, DIFFERENCE d) const { \ i[d].NTH = v; \ } \ \ /** Write component at iterator position into a scalar. */ \ template <class R, class ITERATOR> \ void set(FFTWComplex<R> const & v, ITERATOR const & i) const { \ *i = v.NTH; \ } \ \ /** Write component at offset from iterator position into a scalar. */ \ template <class R, class ITERATOR, class DIFFERENCE> \ void set(FFTWComplex<R> const & v, ITERATOR const & i, DIFFERENCE d) const { \ i[d] = v.NTH; \ } \ }; \ class basetype##n##WriteAccessor_##NTH \ : public basetype##n##Accessor_##NTH \ { \ public: \ /** The accessor's value type. */ \ typedef NumericTraits< basetype##n >::ValueType value_type; \ \ /** Write component at iterator position. */ \ template <class ITERATOR> \ void set(value_type const & v, ITERATOR const & i) const { \ (*i).NTH = v; \ } \ \ /** Write component at offset from iterator position. */ \ template <class ITERATOR, class DIFFERENCE> \ void set(value_type const & v, ITERATOR const & i, DIFFERENCE d) const { \ i[d].NTH = v; \ } \ } #define VIGRA_OPENCL_TYPE2_ACCESSORS(basetype) \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 2, s0); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 2, s1); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 2, x); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 2, y); #define VIGRA_OPENCL_TYPE3_ACCESSORS(basetype) \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 3, s0); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 3, s1); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 3, s2); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 3, x); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 3, y); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 3, z); #define VIGRA_OPENCL_TYPE4_ACCESSORS(basetype) \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 4, s0); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 4, s1); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 4, s2); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 4, s3); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 4, x); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 4, y); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 4, z); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 4, w); #define VIGRA_OPENCL_TYPE8_ACCESSORS(basetype) \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 8, s0); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 8, s1); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 8, s2); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 8, s3); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 8, s4); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 8, s5); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 8, s6); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 8, s7); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 8, s8); #define VIGRA_OPENCL_TYPE16_ACCESSORS(basetype) \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, s0); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, s1); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, s2); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, s3); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, s4); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, s5); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, s6); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, s7); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, s8); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, sa); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, sb); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, sc); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, sd); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, se); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, sf); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, sA); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, sB); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, sC); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, sD); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, sE); \ VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, sF); /// \todo figure out half (.hi .lo, .even .odd) and other odd-sized accessors #define VIGRA_OPENCL_ACCESSORS(basetype) \ VIGRA_OPENCL_TYPE2_ACCESSORS(basetype); \ VIGRA_OPENCL_TYPE3_ACCESSORS(basetype); \ VIGRA_OPENCL_TYPE4_ACCESSORS(basetype); \ VIGRA_OPENCL_TYPE8_ACCESSORS(basetype); \ VIGRA_OPENCL_TYPE16_ACCESSORS(basetype); VIGRA_OPENCL_ACCESSORS(cl_char); VIGRA_OPENCL_ACCESSORS(cl_uchar); VIGRA_OPENCL_ACCESSORS(cl_short); VIGRA_OPENCL_ACCESSORS(cl_ushort); VIGRA_OPENCL_ACCESSORS(cl_int); VIGRA_OPENCL_ACCESSORS(cl_uint); VIGRA_OPENCL_ACCESSORS(cl_long); VIGRA_OPENCL_ACCESSORS(cl_ulong); VIGRA_OPENCL_ACCESSORS(cl_float); VIGRA_OPENCL_ACCESSORS(cl_double); #undef VIGRA_OPENCL_TYPE_ACCESSOR #undef VIGRA_OPENCL_TYPE2_ACCESSORS #undef VIGRA_OPENCL_TYPE3_ACCESSORS #undef VIGRA_OPENCL_TYPE4_ACCESSORS #undef VIGRA_OPENCL_TYPE8_ACCESSORS #undef VIGRA_OPENCL_TYPE16_ACCESSORS #undef VIGRA_OPENCL_ACCESSORS } // namespace vigra #endif // VIGRA_OPENCL_HXX
46.211712
110
0.471391
268324cc8e0071ff6f7753ada142d5a8a5006a36
1,004
hpp
C++
include/Config.hpp
ShimmerFairy/z64fe
e680f009814ee5f625422837a1744ad02b7d8f08
[ "ClArtistic" ]
4
2016-05-04T07:03:11.000Z
2022-02-25T18:55:15.000Z
include/Config.hpp
ShimmerFairy/z64fe
e680f009814ee5f625422837a1744ad02b7d8f08
[ "ClArtistic" ]
null
null
null
include/Config.hpp
ShimmerFairy/z64fe
e680f009814ee5f625422837a1744ad02b7d8f08
[ "ClArtistic" ]
null
null
null
/** \file Config.hpp * * \brief Declares various constant maps and such for rom-specific info. May * well be in external files someday, but this works for now. * */ #pragma once #include <map> #include <string> namespace Config { enum class Region { UNKNOWN, NTSC, PAL, US, JP, EU, }; enum class Game { UNKNOWN, Ocarina, Majora, }; enum class Version { UNKNOWN, OOT_NTSC_1_0, OOT_NTSC_1_1, OOT_NTSC_1_2, OOT_PAL_1_0, OOT_PAL_1_1, OOT_MQ_DEBUG, MM_JP_1_0, MM_JP_1_1, MM_US, MM_EU_1_0, MM_EU_1_1, MM_DEBUG, }; std::string vDisplayStr(Version v); std::string vFileStr(Version v); Game getGame(Version v); Region getRegion(Version v); enum class Language { JP, EN, DE, FR, ES, }; std::string langString(Language L); }
16.733333
77
0.5249
2685a4500cf6be8acd15b8f171c210227adf6153
1,267
cpp
C++
aws-cpp-sdk-rekognition/source/model/S3Destination.cpp
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-rekognition/source/model/S3Destination.cpp
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-rekognition/source/model/S3Destination.cpp
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
1
2021-11-09T12:02:58.000Z
2021-11-09T12:02:58.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/rekognition/model/S3Destination.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Rekognition { namespace Model { S3Destination::S3Destination() : m_bucketHasBeenSet(false), m_keyPrefixHasBeenSet(false) { } S3Destination::S3Destination(JsonView jsonValue) : m_bucketHasBeenSet(false), m_keyPrefixHasBeenSet(false) { *this = jsonValue; } S3Destination& S3Destination::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("Bucket")) { m_bucket = jsonValue.GetString("Bucket"); m_bucketHasBeenSet = true; } if(jsonValue.ValueExists("KeyPrefix")) { m_keyPrefix = jsonValue.GetString("KeyPrefix"); m_keyPrefixHasBeenSet = true; } return *this; } JsonValue S3Destination::Jsonize() const { JsonValue payload; if(m_bucketHasBeenSet) { payload.WithString("Bucket", m_bucket); } if(m_keyPrefixHasBeenSet) { payload.WithString("KeyPrefix", m_keyPrefix); } return payload; } } // namespace Model } // namespace Rekognition } // namespace Aws
16.893333
69
0.714286
2685a4686c01fb7cd7e7de44f972cbef3a02f9be
4,790
hh
C++
neb/inc/com/centreon/engine/configuration/hostescalation.hh
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
neb/inc/com/centreon/engine/configuration/hostescalation.hh
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
neb/inc/com/centreon/engine/configuration/hostescalation.hh
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
/* ** Copyright 2011-2013,2017 Centreon ** ** This file is part of Centreon Engine. ** ** Centreon Engine is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Engine is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Centreon Engine. If not, see ** <http://www.gnu.org/licenses/>. */ #ifndef CCE_CONFIGURATION_HOSTESCALATION_HH # define CCE_CONFIGURATION_HOSTESCALATION_HH # include <memory> # include <set> # include "com/centreon/engine/configuration/group.hh" # include "com/centreon/engine/configuration/object.hh" # include "com/centreon/engine/opt.hh" # include "com/centreon/engine/namespace.hh" # include "com/centreon/engine/shared.hh" CCE_BEGIN() namespace configuration { class hostescalation : public object { public: enum action_on { none = 0, down = (1 << 0), unreachable = (1 << 1), recovery = (1 << 2) }; typedef hostescalation key_type; hostescalation(); hostescalation(hostescalation const& right); ~hostescalation() throw () override; hostescalation& operator=(hostescalation const& right); bool operator==( hostescalation const& right) const throw (); bool operator!=( hostescalation const& right) const throw (); bool operator<( hostescalation const& right) const; void check_validity() const override; key_type const& key() const throw (); void merge(object const& obj) override; bool parse(char const* key, char const* value) override; set_string& contactgroups() throw (); set_string const& contactgroups() const throw (); bool contactgroups_defined() const throw (); void escalation_options( unsigned short options) throw (); unsigned short escalation_options() const throw (); void escalation_period(std::string const& period); std::string const& escalation_period() const throw (); bool escalation_period_defined() const throw (); void first_notification(unsigned int n) throw (); uint32_t first_notification() const throw (); set_string& hostgroups() throw (); set_string const& hostgroups() const throw (); set_string& hosts() throw (); set_string const& hosts() const throw (); void last_notification(unsigned int n) throw (); unsigned int last_notification() const throw (); void notification_interval(unsigned int interval); unsigned int notification_interval() const throw (); bool notification_interval_defined() const throw (); Uuid const& uuid() const; private: typedef bool (*setter_func)(hostescalation&, char const*); bool _set_contactgroups(std::string const& value); bool _set_escalation_options(std::string const& value); bool _set_escalation_period(std::string const& value); bool _set_first_notification(unsigned int value); bool _set_hostgroups(std::string const& value); bool _set_hosts(std::string const& value); bool _set_last_notification(unsigned int value); bool _set_notification_interval(unsigned int value); group<set_string> _contactgroups; opt<unsigned short> _escalation_options; opt<std::string> _escalation_period; opt<unsigned int> _first_notification; group<set_string> _hostgroups; group<set_string> _hosts; opt<unsigned int> _last_notification; opt<unsigned int> _notification_interval; static std::unordered_map<std::string, setter_func> const _setters; Uuid _uuid; }; typedef std::shared_ptr<hostescalation> hostescalation_ptr; typedef std::set<hostescalation> set_hostescalation; } CCE_END() #endif // !CCE_CONFIGURATION_HOSTESCALATION_HH
42.767857
78
0.602088
268612881e134b8543e320a3a65b6bc505944e36
407
cpp
C++
mine/49-group_anagrams.cpp
Junlin-Yin/myLeetCode
8a33605d3d0de9faa82b5092a8e9f56b342c463f
[ "MIT" ]
null
null
null
mine/49-group_anagrams.cpp
Junlin-Yin/myLeetCode
8a33605d3d0de9faa82b5092a8e9f56b342c463f
[ "MIT" ]
null
null
null
mine/49-group_anagrams.cpp
Junlin-Yin/myLeetCode
8a33605d3d0de9faa82b5092a8e9f56b342c463f
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<vector<string>> ans; map<string, vector<string>> m; for(auto s: strs){ string key = s; sort(key.begin(), key.end()); m[key].push_back(s); } for(auto v: m) ans.push_back(v.second); return ans; } };
27.133333
65
0.4914
26870717ca42ee947e4d83fb9bb16c4aa5d0ffed
4,489
cpp
C++
tests/shared/src/MovingPercentileTests.cpp
ey6es/hifi
23f9c799dde439e4627eef45341fb0d53feff80b
[ "Apache-2.0" ]
1
2015-03-11T19:49:20.000Z
2015-03-11T19:49:20.000Z
tests/shared/src/MovingPercentileTests.cpp
ey6es/hifi
23f9c799dde439e4627eef45341fb0d53feff80b
[ "Apache-2.0" ]
null
null
null
tests/shared/src/MovingPercentileTests.cpp
ey6es/hifi
23f9c799dde439e4627eef45341fb0d53feff80b
[ "Apache-2.0" ]
null
null
null
// // MovingPercentileTests.cpp // tests/shared/src // // Created by Yixin Wang on 6/4/2014 // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "MovingPercentileTests.h" #include "SharedUtil.h" #include "MovingPercentile.h" #include <qqueue.h> float MovingPercentileTests::random() { return rand() / (float)RAND_MAX; } void MovingPercentileTests::runAllTests() { QVector<int> valuesForN; valuesForN.append(1); valuesForN.append(2); valuesForN.append(3); valuesForN.append(4); valuesForN.append(5); valuesForN.append(10); valuesForN.append(100); QQueue<float> lastNSamples; for (int i=0; i<valuesForN.size(); i++) { int N = valuesForN.at(i); qDebug() << "testing moving percentile with N =" << N << "..."; { bool fail = false; qDebug() << "\t testing running min..."; lastNSamples.clear(); MovingPercentile movingMin(N, 0.0f); for (int s = 0; s < 3*N; s++) { float sample = random(); lastNSamples.push_back(sample); if (lastNSamples.size() > N) { lastNSamples.pop_front(); } movingMin.updatePercentile(sample); float experimentMin = movingMin.getValueAtPercentile(); float actualMin = lastNSamples[0]; for (int j = 0; j < lastNSamples.size(); j++) { if (lastNSamples.at(j) < actualMin) { actualMin = lastNSamples.at(j); } } if (experimentMin != actualMin) { qDebug() << "\t\t FAIL at sample" << s; fail = true; break; } } if (!fail) { qDebug() << "\t\t PASS"; } } { bool fail = false; qDebug() << "\t testing running max..."; lastNSamples.clear(); MovingPercentile movingMax(N, 1.0f); for (int s = 0; s < 10000; s++) { float sample = random(); lastNSamples.push_back(sample); if (lastNSamples.size() > N) { lastNSamples.pop_front(); } movingMax.updatePercentile(sample); float experimentMax = movingMax.getValueAtPercentile(); float actualMax = lastNSamples[0]; for (int j = 0; j < lastNSamples.size(); j++) { if (lastNSamples.at(j) > actualMax) { actualMax = lastNSamples.at(j); } } if (experimentMax != actualMax) { qDebug() << "\t\t FAIL at sample" << s; fail = true; break; } } if (!fail) { qDebug() << "\t\t PASS"; } } { bool fail = false; qDebug() << "\t testing running median..."; lastNSamples.clear(); MovingPercentile movingMedian(N, 0.5f); for (int s = 0; s < 10000; s++) { float sample = random(); lastNSamples.push_back(sample); if (lastNSamples.size() > N) { lastNSamples.pop_front(); } movingMedian.updatePercentile(sample); float experimentMedian = movingMedian.getValueAtPercentile(); int samplesLessThan = 0; int samplesMoreThan = 0; for (int j=0; j<lastNSamples.size(); j++) { if (lastNSamples.at(j) < experimentMedian) { samplesLessThan++; } else if (lastNSamples.at(j) > experimentMedian) { samplesMoreThan++; } } if (!(samplesLessThan <= N/2 && samplesMoreThan <= N-1/2)) { qDebug() << "\t\t FAIL at sample" << s; fail = true; break; } } if (!fail) { qDebug() << "\t\t PASS"; } } } }
26.405882
88
0.450212
268758411a17323da5bed5c00840b7125d087d0b
3,269
hpp
C++
examples/mantevo/miniFE-1.1/optional/stk_util/parallel/Parallel.hpp
sdressler/objekt
30ee938f5cb06193871f802be0bbdae6ecd26a33
[ "BSD-3-Clause" ]
1
2019-11-26T22:24:12.000Z
2019-11-26T22:24:12.000Z
examples/mantevo/miniFE-1.1/optional/stk_util/parallel/Parallel.hpp
sdressler/objekt
30ee938f5cb06193871f802be0bbdae6ecd26a33
[ "BSD-3-Clause" ]
null
null
null
examples/mantevo/miniFE-1.1/optional/stk_util/parallel/Parallel.hpp
sdressler/objekt
30ee938f5cb06193871f802be0bbdae6ecd26a33
[ "BSD-3-Clause" ]
null
null
null
/*------------------------------------------------------------------------*/ /* Copyright 2010 Sandia Corporation. */ /* Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive */ /* license for use of this work by or on behalf of the U.S. Government. */ /* Export of this program may require a license from the */ /* United States Government. */ /*------------------------------------------------------------------------*/ #ifndef stk_util_parallel_Parallel_hpp #define stk_util_parallel_Parallel_hpp // stk_config.h resides in the build directory and contains the // complete set of #define macros for build-dependent features. #include <stk_util/stk_config.h> //---------------------------------------------------------------------- // Parallel machine #if defined( STK_HAS_MPI ) #include <mpi.h> namespace stk { /** \addtogroup parallel_module * @{ */ /// \todo REFACTOR: Figure out a better way to typedef for non-MPI builds typedef MPI_Comm ParallelMachine ; /// \todo REFACTOR: Figure out a better way to typedef for non-MPI builds typedef MPI_Datatype ParallelDatatype ; /** * @brief <b>parallel_machine_null</b> returns MPI_COMM_NULL if MPI is enabled. * * @return a <b>ParallelMachine</b> ... */ inline ParallelMachine parallel_machine_null() { return MPI_COMM_NULL ; } /** * @brief <b>parallel_machine_init</b> calls MPI_Init. * * @param argc * * @param argv * * @return <b>ParallelMachine</b> (MPI_COMM_WORLD) */ inline ParallelMachine parallel_machine_init( int * argc , char *** argv ) { MPI_Init( argc , argv ); return MPI_COMM_WORLD ; } /** * @brief <b>parallel_machine_finalize</b> calls MPI_Finalize. * */ inline void parallel_machine_finalize() { MPI_Finalize(); } /** \} */ } //---------------------------------------- // Other parallel communication machines go here // as '#elif defined( STK_HAS_<name> )' //---------------------------------------- // Stub for non-parallel #else // Some needed stubs #define MPI_Comm int #define MPI_COMM_WORLD 0 #define MPI_COMM_SELF 0 #define MPI_Barrier( a ) (void)a namespace stk { typedef int ParallelMachine ; typedef int ParallelDatatype ; inline ParallelMachine parallel_machine_null() { return 0 ; } inline ParallelMachine parallel_machine_init( int * , char *** ) { return 0 ; } inline void parallel_machine_finalize() {} } #endif //---------------------------------------------------------------------- // Common parallel machine needs. namespace stk { /** * @brief Member function <b>parallel_machine_size</b> ... * * @param m a <b>ParallelMachine</b> ... * * @return an <b>unsigned int</b> ... */ unsigned parallel_machine_size( ParallelMachine parallel_machine ); /** * @brief Member function <b>parallel_machine_rank</b> ... * * @param m a <b>ParallelMachine</b> ... * * @return an <b>unsigned int</b> ... */ unsigned parallel_machine_rank( ParallelMachine parallel_machine ); /** * @brief Member function <b>parallel_machine_barrier</b> ... * */ void parallel_machine_barrier( ParallelMachine parallel_machine); } //---------------------------------------------------------------------- #endif
23.517986
79
0.588559
268f36cb1993f70b9db72c578a7a6409eab31ac5
193,857
cpp
C++
game.cpp
umer-mukhtar/LudoGame
0687e45ff20af82ea6c24417dcd0dcb1819705fc
[ "MIT" ]
null
null
null
game.cpp
umer-mukhtar/LudoGame
0687e45ff20af82ea6c24417dcd0dcb1819705fc
[ "MIT" ]
null
null
null
game.cpp
umer-mukhtar/LudoGame
0687e45ff20af82ea6c24417dcd0dcb1819705fc
[ "MIT" ]
null
null
null
#ifndef CENTIPEDE_CPP_ #define CENTIPEDE_CPP_ //#include "Board.h" #include "util.h" #include <iostream> #include<string> #include<cmath> #include<fstream> using namespace std; int players; // global variable to record number of players string playerNames[4]={}; // string array to store player names int playerColors[4]={-1,-1,-1,-1}; //int array to store player colors.0 for yellow, 1 for blue, 2 for red, 3 for green, -1 for disabled int window=1; // starts from 1st window.actually these are displays on the same window(not seperate windows) int choice=0; // choice of assignment of colors(window3) int spacePressed=0; // global variable to record if space is pressed char keyPressed; // global variable to record if a printable key is pressed int piece[4][4]={}; // initializing all pieces to zero (zero means locked) int turn=0; //0:yellow 1:blue 2:red 3:green int dice; // global variable for dice which is rolled int dices[3]={}; // initilializing dice array to zero int squares[124][2]; // to set positions of pieces int killCount[4]={}; // initializing kill count of all 4 players to zero int score[4]={}; // initializing score of all 4 players to zero int block[52]={}; // if block forms on any of the 52 squares(initialized to zero) int status[4]={-1,-1,-1,-1}; // status of all 4 players. (0 for playing. -1 for disabled. 1 for winners) int teamMode=0; // 0 for disabled, 1 for enabled int partnersRoll[4]={}; // TeamMode: 0 if partner is in play, if partner has all 4 pieces in home triangle and throws a six, it is =1 void initializingPieceArray() // this function runs only once to initialize piece[4][4] array's all values to -1 { static int countForInitializingPieceArrayFunc = 0; // counter variable for initializingPieceArray function if(countForInitializingPieceArrayFunc == 0) { for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { piece[i][j]=-1; } } countForInitializingPieceArrayFunc++; } } void assignValuesToSquares() // this function is being used to fill squars[52][2] with all central points of each square so later a circle can be made in place { // considering 0th square to be the one directly on the safe spot of yellow and 51th square at the one below safe spot of yellow squares[0][0]=468; // x squares[0][1]=168; // y squares[1][0]=468; squares[1][1]=168+32; squares[2][0]=468; squares[2][1]=168+(2*32); squares[3][0]=468; squares[3][1]=168+(3*32); squares[4][0]=468; squares[4][1]=168+(4*32); squares[5][0]=468-32; squares[5][1]=168+(5*32); squares[6][0]=468-(2*32); squares[6][1]=168+(5*32); squares[7][0]=468-(3*32); squares[7][1]=168+(5*32); squares[8][0]=468-(4*32); squares[8][1]=168+(5*32); squares[9][0]=468-(5*32); squares[9][1]=168+(5*32); squares[10][0]=468-(6*32); squares[10][1]=168+(5*32); squares[11][0]=468-(6*32); squares[11][1]=168+(6*32); squares[12][0]=468-(6*32); squares[12][1]=168+(7*32); squares[13][0]=468-(5*32); squares[13][1]=168+(7*32); squares[14][0]=468-(4*32); squares[14][1]=168+(7*32); squares[15][0]=468-(3*32); squares[15][1]=168+(7*32); squares[16][0]=468-(2*32); squares[16][1]=168+(7*32); squares[17][0]=468-(1*32); squares[17][1]=168+(7*32); squares[18][0]=468-(0*32); squares[18][1]=168+(8*32); squares[19][0]=468-(0*32); squares[19][1]=168+(9*32); squares[20][0]=468-(0*32); squares[20][1]=168+(10*32); squares[21][0]=468-(0*32); squares[21][1]=168+(11*32); squares[22][0]=468-(0*32); squares[22][1]=168+(12*32); squares[23][0]=468-(0*32); squares[23][1]=168+(13*32); squares[24][0]=468+(1*32); squares[24][1]=168+(13*32); squares[25][0]=468+(2*32); squares[25][1]=168+(13*32); squares[26][0]=468+(2*32); squares[26][1]=168+(12*32); squares[27][0]=468+(2*32); squares[27][1]=168+(11*32); squares[28][0]=468+(2*32); squares[28][1]=168+(10*32); squares[29][0]=468+(2*32); squares[29][1]=168+(9*32); squares[30][0]=468+(2*32); squares[30][1]=168+(8*32); squares[31][0]=468+(3*32); squares[31][1]=168+(7*32); squares[32][0]=468+(4*32); squares[32][1]=168+(7*32); squares[33][0]=468+(5*32); squares[33][1]=168+(7*32); squares[34][0]=468+(6*32); squares[34][1]=168+(7*32); squares[35][0]=468+(7*32); squares[35][1]=168+(7*32); squares[36][0]=468+(8*32); squares[36][1]=168+(7*32); squares[37][0]=468+(8*32); squares[37][1]=168+(6*32); squares[38][0]=468+(8*32); squares[38][1]=168+(5*32); squares[39][0]=468+(7*32); squares[39][1]=168+(5*32); squares[40][0]=468+(6*32); squares[40][1]=168+(5*32); squares[41][0]=468+(5*32); squares[41][1]=168+(5*32); squares[42][0]=468+(4*32); squares[42][1]=168+(5*32); squares[43][0]=468+(3*32); squares[43][1]=168+(5*32); squares[44][0]=468+(2*32); squares[44][1]=168+(4*32); squares[45][0]=468+(2*32); squares[45][1]=168+(3*32); squares[46][0]=468+(2*32); squares[46][1]=168+(2*32); squares[47][0]=468+(2*32); squares[47][1]=168+(1*32); squares[48][0]=468+(2*32); squares[48][1]=168+(0*32); squares[49][0]=468+(2*32); squares[49][1]=168-(1*32); squares[50][0]=468+(1*32); squares[50][1]=168-(1*32); squares[51][0]=468+(0*32); squares[51][1]=168-(1*32); // now assigning squares of home column squares[100][0]=240+20+16+(7*32); squares[100][1]=100+20+16+(1*32); squares[101][0]=240+20+16+(7*32); squares[101][1]=100+20+16+(2*32); squares[102][0]=240+20+16+(7*32); squares[102][1]=100+20+16+(3*32); squares[103][0]=240+20+16+(7*32); squares[103][1]=100+20+16+(4*32); squares[104][0]=240+20+16+(7*32); squares[104][1]=100+20+16+(5*32); //squares[105][0]=240+20+16+(7*32); //squares[105][1]=100+20+16+(6*32); squares[106][0]=240+20+16+(1*32); squares[106][1]=100+20+16+(7*32); squares[107][0]=240+20+16+(2*32); squares[107][1]=100+20+16+(7*32); squares[108][0]=240+20+16+(3*32); squares[108][1]=100+20+16+(7*32); squares[109][0]=240+20+16+(4*32); squares[109][1]=100+20+16+(7*32); squares[110][0]=240+20+16+(5*32); squares[110][1]=100+20+16+(7*32); //squares[111][0]=240+20+16+(6*32); //squares[111][1]=100+20+16+(7*32); squares[112][0]=240+20+16+(7*32); squares[112][1]=100+20+16+(13*32); squares[113][0]=240+20+16+(7*32); squares[113][1]=100+20+16+(12*32); squares[114][0]=240+20+16+(7*32); squares[114][1]=100+20+16+(11*32); squares[115][0]=240+20+16+(7*32); squares[115][1]=100+20+16+(10*32); squares[116][0]=240+20+16+(7*32); squares[116][1]=100+20+16+(9*32); //squares[117][0]=240+20+16+(7*32); //squares[117][1]=100+20+16+(8*32); squares[118][0]=240+20+16+(13*32); squares[118][1]=100+20+16+(7*32); squares[119][0]=240+20+16+(12*32); squares[119][1]=100+20+16+(7*32); squares[120][0]=240+20+16+(11*32); squares[120][1]=100+20+16+(7*32); squares[121][0]=240+20+16+(10*32); squares[121][1]=100+20+16+(7*32); squares[122][0]=240+20+16+(9*32); squares[122][1]=100+20+16+(7*32); //squares[123][0]=240+20+16+(8*32); //squares[123][1]=100+20+16+(7*32); } void SetCanvasSize(int width, int height) { // this function sets the screen to the width and height of 720p resolution(my laptop) glMatrixMode (GL_PROJECTION); glLoadIdentity(); glOrtho(0, width, 0, height, -1, 1); // set the screen size to given width and height. glMatrixMode (GL_MODELVIEW); glLoadIdentity(); } void PrintableKeys(unsigned char key, int x, int y) { // this function automatically runs when a printable key is pressed if (key == 27/* Escape key ASCII*/) { if(window==1) { exit(1); // exits the program when escape key is pressed in window 1 } else { window=1; // returns to main menu } } if(window==1) //main menu { if(key==49) // ASCII for '1' { window=2; // enter names window } if(key==50) // ASCII for '2' { window=6; // Leaderboard window } if(key==51) //ASCII for '3' { window=4; // rules window } if(key==52) //ASCII for '4' { window=5;// instructions window } } if(window==2) //player's names input { static int x=0; while(x==0) { // this loop is made so that the number of players are only entered once if(key>=50 && key<=52) { players=key-48; x++; // this causes the loop to never run again } else { break; // the loop breaks if no key is being pressed } } while(x==1) { static int y=0; if((key>=65 && key<=90) || (key>=97 && key<=122)) // ASCII for capital and small alphabets { keyPressed=key; break; } else if(key==13)//ASCII for enter { y++; keyPressed=13; if(y==players) { if(players==4) // then they are able to play in teams if willing { window=13; // go to 13th window } else // they are not able to play in teams { window=3; // go to 3rd window } } break; } else { break; // breaks the loop if no key is pressed } } } if(window==3) //choice of assignment of colors { if(key==49) //ASCII for 1 { choice=1; } if(key==50) //ASCII for 2 { choice=2; window=11; } } if(window==13) // choice of teammode { if(key==49) //yes { teamMode=1; window=3; } if(key==50) // no { teamMode=0; window=3; } } if(window==12) // display randomely assigned colors { if(key==13) { window=7; } } if(window==11) //color by choice { if(key==97) { keyPressed='a'; } if(key==98) { keyPressed='b'; } if(key==99) { keyPressed='c'; } if(key==100) { keyPressed='d'; } } if(window==4) //rules { // does not react to user inputs except Esc } if(window==5) // instructions { // does not react to user inputs except Esc } if(window==6) // leaderboard { // does not react to user inputs except Esc } if(window==7) // highest roll { if(key==32) { dice=GetRandInRange(1,7); } } if(window==8) // game board { if (key == 32) //Key for rolling dice { /*if(turn == 4) { turn=0; }*/ spacePressed=1; dice = GetRandInRange(1,7); } if( key==97) { keyPressed='a'; } if(key==98) { keyPressed='b'; } if(key==99) { keyPressed='c'; } if(key==100) { keyPressed='d'; } if(key == 110) // if no possible moves { turn++; // next turn dice = GetRandInRange(1,7); // new dice number for(int x=0;x<3;x++) { dices[x]=0; } } } if(window==9) // end window { if(key==13) { window=6; // it says press enter to view leaderboard } } glutPostRedisplay(); } void window1() // this function is used to display main menu { DrawStringHead(610,500,"LUDO",colors[BLACK]); DrawStringHead(610-40,500-27,"MAIN MENU",colors[BLACK]); DrawString(570,400,"1) Play Game",colors[BLACK]); DrawString(570,400-20,"2) Leaderboard",colors[BLACK]); DrawString(570,400-40,"3) Rules",colors[BLACK]); DrawString(570,400-60,"4) Instructions",colors[BLACK]); DrawStringSmall(570,400-100,"Press the respective numeric key",colors[BLACK]); //select option by presing the respective number key //DrawString(610-200,500-37,,colors[BLACK]); //DrawStringHead(520,480,"MAIN MENU",colors[BLACK]); glutPostRedisplay(); } void window2() // this function is used to take player's names input from the user { DrawString(510,500,"Please enter the number of players",colors[BLACK]); string playersString; // to display the number of players on screen using DrawString function playersString = players + 48; // e.g if players are 2, then int of 2 is ASCII 2+48 which is '2' in string if(players==0) { DrawString(630,480,"___",colors[BLACK]); // Dash as a replacement for numbers beforehand } else { DrawString(635,470,playersString,colors[BLACK]); DrawString(440,410,"Please enter your names one by one (by pressing the enter)",colors[BLACK]); /*DrawString(440,390,playerNames[0],colors[BLACK]); DrawString(440,380,playerNames[1],colors[BLACK]); DrawString(440,370,playerNames[2],colors[BLACK]); DrawString(440,360,playerNames[3],colors[BLACK]);*/ static int i=0; if(i<players) { if(keyPressed==0) // NULL { // do nothing } else if(keyPressed==13) { i++; } else if(keyPressed!=13) // when some alphabet keys are pressed { playerNames[i]+=keyPressed; }// when this for loop breaks, the window should move on to the next one DrawString(620,380,playerNames[0],colors[BLACK]); // prints name of player 0 DrawString(620,360,playerNames[1],colors[BLACK]);// prints name of player 1 DrawString(620,340,playerNames[2],colors[BLACK]);// prints name of player 2 DrawString(620,320,playerNames[3],colors[BLACK]);//prints name of player 3 keyPressed=0; } } glutPostRedisplay(); } void window12() // displays the randomely assigned colors { /*test data players=2; playerNames[0]="ABC"; playerNames[1]="DEF"; playerColors[0]=1; playerColors[1]=2;*/ for(int i=0;i<players;i++) { DrawString(400,500,"These colors were randomely assigned to you",colors[BLACK]); if(i==0) // player 0 { DrawString(400,460,playerNames[i],colors[BLACK]); if(playerColors[i]==0) { DrawString(500,460,"Yellow",colors[OLIVE]); } if(playerColors[i]==1) { DrawString(500,460,"Blue",colors[BLUE]); } if(playerColors[i]==2) { DrawString(500,460,"Red",colors[RED]); } if(playerColors[i]==3) { DrawString(500,460,"Green", colors[LIME]); } } if(i==1) // player 1 { DrawString(400,430,playerNames[i],colors[BLACK]); if(playerColors[i]==0) { DrawString(500,430,"Yellow",colors[OLIVE]); } if(playerColors[i]==1) { DrawString(500,430,"Blue",colors[BLUE]); } if(playerColors[i]==2) { DrawString(500,430,"Red",colors[RED]); } if(playerColors[i]==3) { DrawString(500,430,"Green", colors[LIME]); } } if(i==2) // player 2 { DrawString(400,400,playerNames[i],colors[BLACK]); if(playerColors[i]==0) { DrawString(500,400,"Yellow",colors[OLIVE]); } if(playerColors[i]==1) { DrawString(500,400,"Blue",colors[BLUE]); } if(playerColors[i]==2) { DrawString(500,400,"Red",colors[RED]); } if(playerColors[i]==3) { DrawString(500,400,"Green", colors[LIME]); } } if(i==3) // player 3 { DrawString(400,370,playerNames[i],colors[BLACK]); if(playerColors[i]==0) { DrawString(500,370,"Yellow",colors[OLIVE]); } if(playerColors[i]==1) { DrawString(500,370,"Blue",colors[BLUE]); } if(playerColors[i]==2) { DrawString(500,370,"Red",colors[RED]); } if(playerColors[i]==3) { DrawString(500,370,"Green", colors[LIME]); } } //DrawString(100,100,playerNames[i],colors[BLACK]); DrawString(400,340,"Press Enter to conitnue",colors[BLACK]); } glutPostRedisplay(); } void window3() // this function is used to ask for choice of colors from user { DrawString(380,500,"How do you want to be assigned colors?",colors[BLACK]); DrawString(380,470,"1) Randomly" ,colors[BLACK]); DrawString(380,450,"2) Based on choice",colors[BLACK]); DrawStringSmall(380,430,"Press the respective numeric key",colors[BLACK]); if(choice == 1) { if(players==2) // 2 players can only have opposite colors { playerColors[0] = GetRandInRange(0, 4); if(playerColors[0]<=1) { playerColors[1] = playerColors[0]+2; // if playerColors[0] is 0 then other will get 2. if it is 1, then other will get 3 } else { playerColors[1] = playerColors[0]-2; // if playercolors[0] is 2 then other will get 0, if it is 3 then other will get 1 } } else // if players are 3 or 4, they will get any random color { playerColors[0] = GetRandInRange(0, 4); if(players==3) { do{ playerColors[1] = GetRandInRange(0, 4); }while(playerColors[1]==playerColors[0]); // does not allow same colors do{ playerColors[2] = GetRandInRange(0, 4); }while(playerColors[2] == playerColors[0] || playerColors[2]==playerColors[1]); // doesnt allow same colors } if(players==4) { do{ playerColors[1] = GetRandInRange(0, 4); }while(playerColors[1]==playerColors[0]) ;// does not allow same colors do{ playerColors[2] = GetRandInRange(0, 4); }while(playerColors[2] == playerColors[0] || playerColors[2]==playerColors[1]) ;// doesnt allow same colors do{ playerColors[3] = GetRandInRange(0, 4); }while(playerColors[3] == playerColors[0] || playerColors[3]==playerColors[1] || playerColors[3]==playerColors[2]); // doesnt allow same colors } } window=12; } else; // change of window is in PrintableKeys function glutPostRedisplay(); } void window13() // this function asks the players if they want to play in teams { DrawString(400,500,"Do you want to play in teams? (Opposite colors will be of the same team)",colors[BLACK]); DrawString(400,470,"1) Yes",colors[BLACK]); DrawString(400,450,"2) No",colors[BLACK]); DrawStringSmall(400,430,"Press the respective numeric key",colors[BLACK]); } void window11() // this function lets user pick color by choice { static int x=0; DrawStringHead(490,650-50,"Pick a color",colors[BLACK]); DrawRectangle(450, 550-30-50-100, 100, 100, colors[OLIVE]); DrawRectangle(450, 550-30-50, 100, 100, colors[BLUE]); DrawRectangle(450+100, 550-30-50, 100, 100, colors[RED]); DrawRectangle(450+100, 550-30-50-100, 100, 100, colors[LIME]); DrawString(450+50, 550-30-50-100+50, "a", colors[BLACK]); DrawString(450+50, 550-30-50+50, "b", colors[BLACK]); DrawString(450+100+50, 550-30-50+50,"c", colors[BLACK]); DrawString(450+100+50, 550-30-50-100+50,"d", colors[BLACK]); DrawString(450+50, 550-30-50-150, playerNames[x], colors[BLACK]); if(players==2) // in case of 2 players, they can only have opposing colors { if(keyPressed>=97 && keyPressed<=100) { playerColors[0]=keyPressed-97; if(keyPressed<=98) // a and b { playerColors[1]=keyPressed-97+2; // if 0 chooses a then 1 gets c. if 0 chooses b then 1 gets d keyPressed=0; window=7; } else if(keyPressed>=99) // c and d { playerColors[1]=keyPressed-97-2; // if 0 chooses c then 1 gets a. if 0 chooses d then 1 gets b keyPressed=0; window=7; } } } else { if(x<players) { if(keyPressed>=97 && keyPressed<=100) { if(x==0) { playerColors[0]=keyPressed-97; x++; keyPressed=0; } else if(x==1) { if(playerColors[0]!=keyPressed-97) { playerColors[1]=keyPressed-97; x++; keyPressed=0; } } else if(x==2) { if(playerColors[0]!=keyPressed-97 && playerColors[1]!=keyPressed-97) { playerColors[2]=keyPressed-97; x++; keyPressed=0; } } else if(x==3) { for(int j=0;j<4;j++) { if(playerColors[0]!=j && playerColors[1]!=j && playerColors[2]!=j) { playerColors[3]=j; x++; } } keyPressed=0; } else { keyPressed=0; } } } else // if x==players move on to the next window { window=7; } } glutPostRedisplay(); } void window4() // this function is used to display the rules of the game { DrawStringHead(550,600,"RULES",colors[BLACK]); DrawString(200,570,"1) Each player will have 4 Ludo pieces of that color placed in the corresponding starting square.",colors[BLACK]); DrawString(200,550-5,"2) A player must throw a 6 to move a piece from the starting square onto the first square on the track.",colors[BLACK]); DrawString(200,530-10,"3) A player will keep on throwing the dice if Six comes.",colors[BLACK]); DrawString(200,510-15,"4) Three consecutive sixes will result in loss of turn and all his numbers in that turn will be discarded.",colors[BLACK]); DrawString(200,490-20,"5) A piece moves in a clockwise direction around the track given by the number thrown.",colors[BLACK]); DrawString(200,470-25,"6) If a piece lands on a piece of a different color, the piece jumped upon is returned to its starting circle.",colors[BLACK]); DrawString(200,450-30,"7) An extra turn is given to the player that removes the opponent's piece",colors[BLACK]); DrawString(200,430-35,"8) If a piece lands upon a piece of the same color, this forms a block.",colors[BLACK]); DrawString(220,410-40,"This block cannot be passed or landed on by any opposing piece.",colors[BLACK]); DrawString(200,390-45,"9) When a piece has circumnavigated the board, it proceeds up the home column.",colors[BLACK]); DrawString(200,370-50,"10) A player is not be allowed to enter into his Home column until he has removed at least one opposing piece.",colors[BLACK]); DrawString(200,350-55,"11) A piece can only be moved onto the home triangle by an exact throw.",colors[BLACK]); DrawString(200,330-60,"12) An extra turn is given to the player whose piece makes it to the home triangle.",colors[BLACK]); DrawString(200,310-65,"13) The first person to move all 4 pieces into the home triangle wins.",colors[BLACK]); DrawString(200,290-70,"14) Scoring criteria:",colors[BLACK]); DrawString(250,270-75,"a) A player receives 1 point for each square crossed.",colors[BLACK]); DrawString(250,250-80,"b) A player receives 2 points for creating a block.",colors[BLACK]); DrawString(250,230-85,"c) A player receives 10 points if removes an opponent's piece.",colors[BLACK]); DrawString(250,210-90,"d) A player receives 15 points if moves a piece into the home column.",colors[BLACK]); glutPostRedisplay(); } void window5() // this function is used to display the instructions on how to play the game { DrawStringHead(550,600,"INSTRUCTIONS",colors[BLACK]); DrawString(200,570,"1) Each player will roll the dice by using the spacebar key",colors[BLACK]); DrawString(200,550-5,"2) If dice rolls 6, the player will be given an extra roll which will also be done using the spacebar key.",colors[BLACK]); DrawString(200,530-10,"3) A player will select the piece to be moved based on its character using 'a', 'b', 'c', or 'd' keys.",colors[BLACK]); DrawString(200,510-15,"4) If there is no possible move, the player may press 'n' to move the turn to the next player",colors[BLACK]); DrawString(200,490-20,"5) Press Esc to return to the main menu",colors[BLACK]); glutPostRedisplay(); } void updateLeaderboardArraysFromFile(string leaderboardNames[],string leaderboardScores[]) // updates the arrays from the file highscore.txt { ifstream leaderboard; leaderboard.open("highscores.txt"); for(int i=0;i<10;i++) { leaderboard >> leaderboardNames[i] >> leaderboardScores[i]; } /*for(int x=0;x<10;x++) { cout<<leaderboardNames[x]<<" "<<leaderboardScores[x]<<endl; }*/ leaderboard.close(); } void window6() // this function displays the leaderboard { string leaderboardNames[10]; // stores leaderboardnames in string array string leaderboardScores[10]; // stores leaderboardscores in string array updateLeaderboardArraysFromFile(leaderboardNames,leaderboardScores); DrawStringHead(350+200,500,"LEADERBOARD",colors[BLACK]); for(int i=0;i<10;i++) { DrawString(350+200,460-(i*30),leaderboardNames[i],colors[BLACK]); DrawString(480+200,460-(i*30),leaderboardScores[i],colors[BLACK]); } glutPostRedisplay(); } void drawDiceForFirstRolls(int diceNum, int index) // draws dices for first rolls { if(index==0) { // DrawString(250+(0*200),250,playerNames[0],colors[BLACK]); DrawRoundRect(1120-870, 600-230, 44, 44, colors[SANDY_BROWN], 10); if(diceNum==1) { DrawCircle(1120+22-870, 600+22-230, 5, colors[BLACK]); } else if(diceNum==2) { DrawCircle(1120+10-5+22-870, 600+10-5+22-230, 5, colors[BLACK]); DrawCircle(1120-10+5+22-870, 600-10+5+22-230, 5, colors[BLACK]); } else if(diceNum==3) { DrawCircle(1120+22-870, 600+22-230, 5, colors[BLACK]); DrawCircle(1120+10+22-870, 600+10+22-230, 5, colors[BLACK]); DrawCircle(1120-10+22-870, 600-10+22-230, 5, colors[BLACK]); } else if(diceNum==4) { DrawCircle(1120+10-3+22-870, 600+10-3+22-230, 5, colors[BLACK]); DrawCircle(1120-10+3+22-870, 600-10+3+22-230, 5, colors[BLACK]); DrawCircle(1120+10-3+22-15-870, 600+10-3+22-230, 5, colors[BLACK]); DrawCircle(1120-10+3+22+15-870, 600-10+3+22-230, 5, colors[BLACK]); } else if(diceNum==5) { DrawCircle(1120+22-870, 600+22-230, 5, colors[BLACK]); DrawCircle(1120+10+22-870, 600+10+22-230, 5, colors[BLACK]); DrawCircle(1120-10+22-870, 600-10+22-230, 5, colors[BLACK]); DrawCircle(1120-10+22-870, 600+10+22-230, 5, colors[BLACK]); DrawCircle(1120+10+22-870, 600-10+22-230, 5, colors[BLACK]); } else //if diceNum==6 { DrawCircle(1120+10-3+22-15-1-870, 600+10-3+22+5-230, 5, colors[BLACK]); // top left DrawCircle(1120+10-3+22+1-870, 600+10-3+22+5-230, 5, colors[BLACK]); // top right DrawCircle(1120-10+3+22-1-870, 600-10+5+22+5-230, 5, colors[BLACK]); // middle left DrawCircle(1120-10+3+22+15+1-870, 600-10+5+22+5-230, 5, colors[BLACK]); // middle right DrawCircle(1120-10+3+22-1-870, 600-10+3+22-5-230, 5, colors[BLACK]); // bottom left DrawCircle(1120-10+3+22+15+1-870, 600-10+3+22-5-230, 5, colors[BLACK]); // bottom right } } if(index==1) { DrawRoundRect(1120-670, 600-230, 44, 44, colors[SANDY_BROWN], 10); if(diceNum==1) { DrawCircle(1120+22-670, 600+22-230, 5, colors[BLACK]); } else if(diceNum==2) { DrawCircle(1120+10-5+22-670, 600+10-5+22-230, 5, colors[BLACK]); DrawCircle(1120-10+5+22-670, 600-10+5+22-230, 5, colors[BLACK]); } else if(diceNum==3) { DrawCircle(1120+22-670, 600+22-230, 5, colors[BLACK]); DrawCircle(1120+10+22-670, 600+10+22-230, 5, colors[BLACK]); DrawCircle(1120-10+22-670, 600-10+22-230, 5, colors[BLACK]); } else if(diceNum==4) { DrawCircle(1120+10-3+22-670, 600+10-3+22-230, 5, colors[BLACK]); DrawCircle(1120-10+3+22-670, 600-10+3+22-230, 5, colors[BLACK]); DrawCircle(1120+10-3+22-15-670, 600+10-3+22-230, 5, colors[BLACK]); DrawCircle(1120-10+3+22+15-670, 600-10+3+22-230, 5, colors[BLACK]); } else if(diceNum==5) { DrawCircle(1120+22-670, 600+22-230, 5, colors[BLACK]); DrawCircle(1120+10+22-670, 600+10+22-230, 5, colors[BLACK]); DrawCircle(1120-10+22-670, 600-10+22-230, 5, colors[BLACK]); DrawCircle(1120-10+22-670, 600+10+22-230, 5, colors[BLACK]); DrawCircle(1120+10+22-670, 600-10+22-230, 5, colors[BLACK]); } else //if diceNum==6 { DrawCircle(1120+10-3+22-15-1-670, 600+10-3+22+5-230, 5, colors[BLACK]); // top left DrawCircle(1120+10-3+22+1-670, 600+10-3+22+5-230, 5, colors[BLACK]); // top right DrawCircle(1120-10+3+22-1-670, 600-10+5+22+5-230, 5, colors[BLACK]); // middle left DrawCircle(1120-10+3+22+15+1-670, 600-10+5+22+5-230, 5, colors[BLACK]); // middle right DrawCircle(1120-10+3+22-1-670, 600-10+3+22-5-230, 5, colors[BLACK]); // bottom left DrawCircle(1120-10+3+22+15+1-670, 600-10+3+22-5-230, 5, colors[BLACK]); // bottom right } } if(index==2) { DrawRoundRect(1120-470, 600-230, 44, 44, colors[SANDY_BROWN], 10); if(diceNum==1) { DrawCircle(1120+22-470, 600+22-230, 5, colors[BLACK]); } else if(diceNum==2) { DrawCircle(1120+10-5+22-470, 600+10-5+22-230, 5, colors[BLACK]); DrawCircle(1120-10+5+22-470, 600-10+5+22-230, 5, colors[BLACK]); } else if(diceNum==3) { DrawCircle(1120+22-470, 600+22-230, 5, colors[BLACK]); DrawCircle(1120+10+22-470, 600+10+22-230, 5, colors[BLACK]); DrawCircle(1120-10+22-470, 600-10+22-230, 5, colors[BLACK]); } else if(diceNum==4) { DrawCircle(1120+10-3+22-470, 600+10-3+22-230, 5, colors[BLACK]); DrawCircle(1120-10+3+22-470, 600-10+3+22-230, 5, colors[BLACK]); DrawCircle(1120+10-3+22-15-470, 600+10-3+22-230, 5, colors[BLACK]); DrawCircle(1120-10+3+22+15-470, 600-10+3+22-230, 5, colors[BLACK]); } else if(diceNum==5) { DrawCircle(1120+22-470, 600+22-230, 5, colors[BLACK]); DrawCircle(1120+10+22-470, 600+10+22-230, 5, colors[BLACK]); DrawCircle(1120-10+22-470, 600-10+22-230, 5, colors[BLACK]); DrawCircle(1120-10+22-470, 600+10+22-230, 5, colors[BLACK]); DrawCircle(1120+10+22-470, 600-10+22-230, 5, colors[BLACK]); } else //if diceNum==6 { DrawCircle(1120+10-3+22-15-1-470, 600+10-3+22+5-230, 5, colors[BLACK]); // top left DrawCircle(1120+10-3+22+1-470, 600+10-3+22+5-230, 5, colors[BLACK]); // top right DrawCircle(1120-10+3+22-1-470, 600-10+5+22+5-230, 5, colors[BLACK]); // middle left DrawCircle(1120-10+3+22+15+1-470, 600-10+5+22+5-230, 5, colors[BLACK]); // middle right DrawCircle(1120-10+3+22-1-470, 600-10+3+22-5-230, 5, colors[BLACK]); // bottom left DrawCircle(1120-10+3+22+15+1-470, 600-10+3+22-5-230, 5, colors[BLACK]); // bottom right } } if(index==3) { DrawRoundRect(1120-270, 600-230, 44, 44, colors[SANDY_BROWN], 10); if(diceNum==1) { DrawCircle(1120+22-270, 600+22-230, 5, colors[BLACK]); } else if(diceNum==2) { DrawCircle(1120+10-5+22-270, 600+10-5+22-230, 5, colors[BLACK]); DrawCircle(1120-10+5+22-270, 600-10+5+22-230, 5, colors[BLACK]); } else if(diceNum==3) { DrawCircle(1120+22-270, 600+22-230, 5, colors[BLACK]); DrawCircle(1120+10+22-270, 600+10+22-230, 5, colors[BLACK]); DrawCircle(1120-10+22-270, 600-10+22-230, 5, colors[BLACK]); } else if(diceNum==4) { DrawCircle(1120+10-3+22-270, 600+10-3+22-230, 5, colors[BLACK]); DrawCircle(1120-10+3+22-270, 600-10+3+22-230, 5, colors[BLACK]); DrawCircle(1120+10-3+22-15-270, 600+10-3+22-230, 5, colors[BLACK]); DrawCircle(1120-10+3+22+15-270, 600-10+3+22-230, 5, colors[BLACK]); } else if(diceNum==5) { DrawCircle(1120+22-270, 600+22-230, 5, colors[BLACK]); DrawCircle(1120+10+22-270, 600+10+22-230, 5, colors[BLACK]); DrawCircle(1120-10+22-270, 600-10+22-230, 5, colors[BLACK]); DrawCircle(1120-10+22-270, 600+10+22-230, 5, colors[BLACK]); DrawCircle(1120+10+22-270, 600-10+22-230, 5, colors[BLACK]); } else //if diceNum==6 { DrawCircle(1120+10-3+22-15-1-270, 600+10-3+22+5-230, 5, colors[BLACK]); // top left DrawCircle(1120+10-3+22+1-270, 600+10-3+22+5-230, 5, colors[BLACK]); // top right DrawCircle(1120-10+3+22-1-270, 600-10+5+22+5-230, 5, colors[BLACK]); // middle left DrawCircle(1120-10+3+22+15+1-270, 600-10+5+22+5-230, 5, colors[BLACK]); // middle right DrawCircle(1120-10+3+22-1-270, 600-10+3+22-5-230, 5, colors[BLACK]); // bottom left DrawCircle(1120-10+3+22+15+1-270, 600-10+3+22-5-230, 5, colors[BLACK]); // bottom right } } //DrawSquare( 1140-20 , 620-20 , 40, colors[SANDY_BROWN]); /*DrawRoundRect(1120, 600-230, 44, 44, colors[SANDY_BROWN], 10); if(diceNum==1) { DrawCircle(1120+22, 600+22-230, 5, colors[BLACK]); } else if(diceNum==2) { DrawCircle(1120+10-5+22, 600+10-5+22-230, 5, colors[BLACK]); DrawCircle(1120-10+5+22, 600-10+5+22-230, 5, colors[BLACK]); } else if(diceNum==3) { DrawCircle(1120+22, 600+22-230, 5, colors[BLACK]); DrawCircle(1120+10+22, 600+10+22-230, 5, colors[BLACK]); DrawCircle(1120-10+22, 600-10+22-230, 5, colors[BLACK]); } else if(diceNum==4) { DrawCircle(1120+10-3+22, 600+10-3+22-230, 5, colors[BLACK]); DrawCircle(1120-10+3+22, 600-10+3+22-230, 5, colors[BLACK]); DrawCircle(1120+10-3+22-15, 600+10-3+22-230, 5, colors[BLACK]); DrawCircle(1120-10+3+22+15, 600-10+3+22-230, 5, colors[BLACK]); } else if(diceNum==5) { DrawCircle(1120+22, 600+22-230, 5, colors[BLACK]); DrawCircle(1120+10+22, 600+10+22-230, 5, colors[BLACK]); DrawCircle(1120-10+22, 600-10+22-230, 5, colors[BLACK]); DrawCircle(1120-10+22, 600+10+22-230, 5, colors[BLACK]); DrawCircle(1120+10+22, 600-10+22-230, 5, colors[BLACK]); } else //if diceNum==6 { DrawCircle(1120+10-3+22-15-1, 600+10-3+22+5-230, 5, colors[BLACK]); // top left DrawCircle(1120+10-3+22+1, 600+10-3+22+5-230, 5, colors[BLACK]); // top right DrawCircle(1120-10+3+22-1, 600-10+5+22+5-230, 5, colors[BLACK]); // middle left DrawCircle(1120-10+3+22+15+1, 600-10+5+22+5-230, 5, colors[BLACK]); // middle right DrawCircle(1120-10+3+22-1, 600-10+3+22-5-230, 5, colors[BLACK]); // bottom left DrawCircle(1120-10+3+22+15+1, 600-10+3+22-5-230, 5, colors[BLACK]); // bottom right }*/ glutPostRedisplay(); } void window7() //this is to assign turn with respect to the highest roll { /* test data players=2; playerNames[0]="ABC"; playerNames[1]="CED"; playerColors[0]=2; playerColors[1]=3; */ static int firstRolls[4]={}; DrawString(400,650,"The player with the highest roll will get the first turn",colors[BLACK]); DrawString(550,620,"Roll dice one by one",colors[BLACK]); static int i=0; static int rollAgain=0; // will be used to show roll again message if more than one highest rolls occur if(rollAgain==1) { DrawString(580,590,"Roll again",colors[BLACK]); } DrawString(250+(0*200),250,playerNames[0],colors[BLACK]); // printing player names that exist DrawString(250+(1*200),250,playerNames[1],colors[BLACK]); DrawString(250+(2*200),250,playerNames[2],colors[BLACK]); DrawString(250+(3*200),250,playerNames[3],colors[BLACK]); if(firstRolls[0]!=0) // printing dices that are rolled ONLY { drawDiceForFirstRolls(firstRolls[0], 0); } if(firstRolls[1]!=0) { drawDiceForFirstRolls(firstRolls[1], 1); } if(firstRolls[2]!=0) { drawDiceForFirstRolls(firstRolls[2], 2); } if(firstRolls[3]!=0) { drawDiceForFirstRolls(firstRolls[3], 3); } if(i<players) { if(dice!=0) { firstRolls[i]=dice; // to record first rolls dice=0; i++; } } else // i==players now { // now finding the highest roll static int counter=0; /// to find the number of players who rolled the highest number static int highestRoll=0; static int index; // to keep track of the color which rolls highest for(int i=0;i<players;i++) { if(firstRolls[i]>highestRoll) { highestRoll=firstRolls[i]; index=i; } } for(int j=0;j<players;j++) { if(highestRoll==firstRolls[j]) { counter++; } } if(counter==1) // there was only one highest roll { turn=playerColors[index]; // first turn goes to the player who rolled highest window=8; } else // more than 1 highest rolls occured. the players should now roll again { rollAgain=1; counter=0; highestRoll=0; i=0; for(int x=0;x<players;x++) { firstRolls[x]=0; // they will have to roll again } } } glutPostRedisplay(); } // window8 is inside GameDisplay function void updateLeaderboard() // updates the leaderboard if any one beats the highscores { /*test data playerNames[1]="ABC"; playerColors[1]=3; score[3]=500;*/ string leaderboardNames[10]; // stores leaderboardnames in string array int leaderboardScores[10]; // stores leaderboardscores in INT array ifstream leaderboard; leaderboard.open("highscores.txt"); for(int i=0;i<10;i++) { leaderboard >> leaderboardNames[i] >> leaderboardScores[i]; } leaderboard.close(); // now the data has been stored in the arrays int lowestScore=leaderboardScores[0]; int index=0;; // index of the lowest score for(static int j=0;j<4;j++) { for(int i=0;i<10;i++) { if(leaderboardScores[i]<lowestScore) // this finds lowest score in the array of scores { lowestScore=leaderboardScores[i]; index=i; } } // this loop should run to check for every player's score(e.g if player 2 scores more than player 1 and player 1 is at lowest, then it should be updated with player 2) if(score[j]>lowestScore) { for(int x=0;x<4;x++) { if(playerColors[x]==j) { leaderboardNames[index]=playerNames[x]; // replaces the index of name array with lowest score leaderboardScores[index]=score[j]; // replaces the index of score array with lowest score } } index=0; lowestScore=leaderboardScores[0]; } } // now the arrays have been updated. ofstream leaderboardUpdate; leaderboardUpdate.open("highscores.txt"); for(int k=0;k<10;k++) { leaderboardUpdate << leaderboardNames[k] << " " << leaderboardScores[k] << endl; // updates the highscore.txt file } leaderboardUpdate.close(); } string intToString(int intVal) // this function converts int numbers to string { string stringVal; int tempNum=intVal; int digits=0; do{ tempNum/=10; digits++; }while(tempNum!=0); int m=0; do{ tempNum=(intVal/pow(10,digits-1))-(10*static_cast<int>(intVal/pow(10,digits))); stringVal+=tempNum+48; digits--; m++; }while(digits!=0); // no comments as all this logic was created using the help of pen and paper // should just know that it converts any int value to string return stringVal; } void window9() // this function displays the end game (GAME OVER) window { /*test data players=2; playerNames[0]="ABC"; playerNames[1]="DEF"; playerColors[0]=0; playerColors[1]=3; score[0]=300; score[3]=19;*/ DrawStringHead(550,500,"GAME OVER",colors[BLACK]); for(int i=0;i<players;i++) { string tempScore; // a temporary variable to store scores to display them in string form if(playerColors[i]==0) // yellow { DrawString(550,460,playerNames[i],colors[BLACK]); tempScore=intToString(score[0]); DrawString(650,460,tempScore,colors[BLACK]); } if(playerColors[i]==1) //blue { DrawString(550,430,playerNames[i],colors[BLACK]); tempScore=intToString(score[1]); DrawString(650,430,tempScore,colors[BLACK]); //DrawString(650,460,score[1],colors[BLACK]); } if(playerColors[i]==2) // red { DrawString(550,400,playerNames[i],colors[BLACK]); tempScore=intToString(score[2]); DrawString(650,400,tempScore,colors[BLACK]); //DrawString(650,460,score[2],colors[BLACK]); } if(playerColors[i]==3) // green { DrawString(550,370,playerNames[i],colors[BLACK]); tempScore=intToString(score[3]); DrawString(650,370,tempScore,colors[BLACK]); //DrawString(650,460,score[3],colors[BLACK]); } } DrawString(550,340,"Press Enter to view leaderboard",colors[BLACK]); glutPostRedisplay(); } void writeTurn() // this function writes the colour whose turn it is { if(turn==0) { DrawString( 1085, 450, "Yellow's Turn", colors[BLACK]); } else if(turn==1) { DrawString( 1093, 450, "Blue's Turn", colors[BLACK]); } else if(turn==2) { DrawString( 1098, 450, "Red's Turn", colors[BLACK]); } else //turn==3 { DrawString( 1090, 450, "Green's Turn", colors[BLACK]); } glutPostRedisplay(); } void drawPieces(); //prototype void drawBoard() // this function draws the board { DrawLine( 1000 , 0 , 1000 , 720-1 , 10 , colors[BLACK] ); // seperation line DrawRoundRect(241-0, 101-0, 520, 520, colors[SANDY_BROWN], 20); //outer board DrawRectangle(240-1+20-2, 100-1+20-2, 520-40+4, 520-40+4, colors[BLACK]); // line DrawRectangle(240-1+20, 100-1+20, 520-40, 520-40, colors[BURLY_WOOD]); // inner board // THROUGHOUT THE DISPLAY, 32x32 IS THE SIZE OF A SINGLE BLOCK ON WHICH A PIECE MOVES for(int i=0;i<15;i++) { for(int j=0;j<3;j++) { DrawSquare( 432+20+(j*32)+1 , 100+20+(i*32)+1 ,32,colors[BLACK]); DrawSquare( 432+20+(j*32)+1 , 100+20+(i*32)+1 ,30,colors[WHITE]); } }//vertical line of boxes for(int i=0;i<15;i++) { for(int j=0;j<3;j++) { DrawSquare( 240+20+(i*32)+1 , 292+20+(j*32)+1 ,32,colors[BLACK]); DrawSquare( 240+20+(i*32)+1 , 292+20+(j*32)+1 ,30,colors[WHITE]); } }//horizontal line of boxes //horizontal line DrawLine(240 + 20, 292 + 20, 240 + 20 + 480, 292 + 20, 2, colors[BLACK]); //vertical lines DrawLine(240 + 20+192, 100 + 20-1, 240 + 20+192, 100 + 20+480, 2, colors[BLACK]); //drawing homes and their pieces /*DrawCircle(240+20+96, 100+20+96, 65, colors[OLIVE]); // actually yellow DrawCircle(240+20+96-24, 100+20+96-24, 12, colors[DARK_GOLDEN_ROD]); // darker yellow shade one can say DrawCircle(240+20+96-24, 100+20+96+24, 12, colors[DARK_GOLDEN_ROD]); DrawCircle(240+20+96+24, 100+20+96+24, 12, colors[DARK_GOLDEN_ROD]); DrawCircle(240+20+96+24, 100+20+96-24, 12, colors[DARK_GOLDEN_ROD]); DrawCircle(240+20+96+292, 100+20+96, 65, colors[LIME]); // lighter green shade DrawCircle(240+20+96+292-24, 100+20+96-24, 12, colors[GREEN]); DrawCircle(240+20+96+292-24, 100+20+96+24, 12, colors[GREEN]); DrawCircle(240+20+96+292+24, 100+20+96+24, 12, colors[GREEN]); DrawCircle(240+20+96+292+24, 100+20+96-24, 12, colors[GREEN]); DrawCircle(240+20+96, 100+20+96+292, 65, colors[BLUE]); // lighter blue shade DrawCircle(240+20+96-24, 100+20+96+292-24, 12, colors[DARK_BLUE]); DrawCircle(240+20+96-24, 100+20+96+292+24, 12, colors[DARK_BLUE]); DrawCircle(240+20+96+24, 100+20+96+292+24, 12, colors[DARK_BLUE]); DrawCircle(240+20+96+24, 100+20+96+292-24, 12, colors[DARK_BLUE]); DrawCircle(240+20+96+292, 100+20+96+292, 65, colors[RED]); DrawCircle(240+20+96+292-24, 100+20+96+292-24, 12, colors[FIREBRICK]);// darker red shade DrawCircle(240+20+96+292-24, 100+20+96+292+24, 12, colors[FIREBRICK]); DrawCircle(240+20+96+292+24, 100+20+96+292+24, 12, colors[FIREBRICK]); DrawCircle(240+20+96+292+24, 100+20+96+292-24, 12, colors[FIREBRICK]);*/ DrawCircle(240+20+96, 100+20+96, 65, colors[OLIVE]); // actually yellow DrawCircle(240+20+96-24, 100+20+96-24, 12, colors[MISTY_ROSE]); // white( if the piece has left the starting circle) DrawCircle(240+20+96-24, 100+20+96+24, 12, colors[MISTY_ROSE]); DrawCircle(240+20+96+24, 100+20+96+24, 12, colors[MISTY_ROSE]); DrawCircle(240+20+96+24, 100+20+96-24, 12, colors[MISTY_ROSE]); DrawCircle(240+20+96+292, 100+20+96, 65, colors[LIME]); DrawCircle(240+20+96+292-24, 100+20+96-24, 12, colors[MISTY_ROSE]); DrawCircle(240+20+96+292-24, 100+20+96+24, 12, colors[MISTY_ROSE]); DrawCircle(240+20+96+292+24, 100+20+96+24, 12, colors[MISTY_ROSE]); DrawCircle(240+20+96+292+24, 100+20+96-24, 12, colors[MISTY_ROSE]); DrawCircle(240+20+96, 100+20+96+292, 65, colors[BLUE]); DrawCircle(240+20+96-24, 100+20+96+292-24, 12, colors[MISTY_ROSE]); DrawCircle(240+20+96-24, 100+20+96+292+24, 12, colors[MISTY_ROSE]); DrawCircle(240+20+96+24, 100+20+96+292+24, 12, colors[MISTY_ROSE]); DrawCircle(240+20+96+24, 100+20+96+292-24, 12, colors[MISTY_ROSE]); DrawCircle(240+20+96+292, 100+20+96+292, 65, colors[RED]); DrawCircle(240+20+96+292-24, 100+20+96+292-24, 12, colors[MISTY_ROSE]); DrawCircle(240+20+96+292-24, 100+20+96+292+24, 12, colors[MISTY_ROSE]); DrawCircle(240+20+96+292+24, 100+20+96+292+24, 12, colors[MISTY_ROSE]); DrawCircle(240+20+96+292+24, 100+20+96+292-24, 12, colors[MISTY_ROSE]); // now drawing yellow boxes DrawSquare( 240+20+192+1 , 100+20+32 ,30,colors[OLIVE]); for(int i=1;i<6;i++) { DrawSquare( 240+20+32+192+1 , 100+20+(32*i) ,30,colors[OLIVE]); } // now drawing green boxes DrawSquare( 240+20+192+1+(7*32) , 100+20+(6*32) ,30,colors[LIME]); for(int i=7;i>2;i--) { DrawSquare( 240+20+192+1+(i*32) , 100+20+(7*32) ,30,colors[LIME]); } // now drawing red boxes DrawSquare(240+20+(8*32),100+20+(13*32),31,colors[RED]); for(int i=13;i>8;i--) { DrawSquare(240+20+(7*32),100+20+(i*32),31,colors[RED]); } // now drawing blue boxes DrawSquare(240+20+32,100+20+(8*32),31,colors[BLUE]); for(int i=1;i<6;i++) { DrawSquare(240+20+(i*32),100+20+(7*32),31,colors[BLUE]); } // now drawing central triangles DrawTriangle(240+20+(32*6), 100+20+(32*6), 240+20+(32*9), 100+20+(32*6), 240+20+(32*7.5), 100+20+(32*7.5), colors[OLIVE]); DrawTriangle(240+20+(32*9), 100+20+(32*6), 240+20+(32*9), 100+20+(32*9), 240+20+(32*7.5), 100+20+(32*7.5), colors[LIME]); DrawTriangle(240+20+(32*6), 100+20+(32*9), 240+20+(32*9), 100+20+(32*9), 240+20+(32*7.5), 100+20+(32*7.5), colors[RED]); DrawTriangle(240+20+(32*6), 100+20+(32*6), 240+20+(32*6), 100+20+(32*9), 240+20+(32*7.5), 100+20+(32*7.5), colors[BLUE]); // now drawing additional safe spots(other than coloured ones) DrawSquare(240+20+(32*8),100+20+(2*32),31,colors[DIM_GRAY]);//yellow DrawSquare(240+20+(32*6),100+20+(12*32),31,colors[DIM_GRAY]);//red DrawSquare(240+20+(32*2),100+20+(6*32),31,colors[DIM_GRAY]);//blue DrawSquare(240+20+(32*12),100+20+(8*32),31,colors[DIM_GRAY]);//green drawPieces(); glutPostRedisplay(); } void drawPiecesStart() // this function draws the pieces ONLY when they are in the starting circle { for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { if(i==0) // 1st player { if(piece[i][j]==-1) // i is the player, j is the piece number, -1 means the piece is locked { if(j==0) // 1st piece { DrawCircle(240+20+96-24, 100+20+96-24, 12, colors[DARK_GOLDEN_ROD]); // darker yellow shade one can say DrawString(240+20+96-24-5,100+20+96-24-5 , "a", colors[BLACK]); } else if(j==1) // 2nd piece { DrawCircle(240+20+96-24, 100+20+96+24, 12, colors[DARK_GOLDEN_ROD]); DrawString(240+20+96-24-5,100+20+96+24-5 , "b", colors[BLACK]); } else if(j==2) // 3rd piece { DrawCircle(240+20+96+24, 100+20+96+24, 12, colors[DARK_GOLDEN_ROD]); DrawString(240+20+96+24-5,100+20+96+24-5 , "c", colors[BLACK]); } else { DrawCircle(240+20+96+24, 100+20+96-24, 12, colors[DARK_GOLDEN_ROD]); DrawString(240+20+96+24-5,100+20+96-24-5 , "d", colors[BLACK]); } } } else if(i==1) // blue { if(piece[i][j]==-1) { if(j==0) { //DrawCircle(240+20+96+292-24, 100+20+96-24, 12, colors[DARK_BLUE]); //DrawString(240+20+96+292-24-5,100+20+96-24-5 , "a", colors[BLACK]); DrawCircle(240+20+96-24, 100+20+96+292-24, 12, colors[DARK_BLUE]);// darker red shade DrawString(240+20+96-24-5,100+20+96+292-24-5 , "a", colors[BLACK]); } else if(j==1) { //DrawCircle(240+20+96+292-24, 100+20+96+24, 12, colors[DARK_BLUE]); //DrawString(240+20+96+292-24-5,100+20+96+24-5 , "b", colors[BLACK]); DrawCircle(240+20+96-24, 100+20+96+292+24, 12, colors[DARK_BLUE]); DrawString(240+20+96-24-5,100+20+96+292+24-5 , "b", colors[BLACK]); } else if(j==2) { //DrawCircle(240+20+96+292+24, 100+20+96+24, 12, colors[DARK_BLUE]); //DrawString(240+20+96+292+24-5,100+20+96+24-5 , "c", colors[BLACK]); DrawCircle(240+20+96+24, 100+20+96+292+24, 12, colors[DARK_BLUE]); DrawString(240+20+96+24-5,100+20+96+292+24-5 , "c", colors[BLACK]); } else { //DrawCircle(240+20+96+292+24, 100+20+96-24, 12, colors[DARK_BLUE]); //DrawString(240+20+96+292+24-5,100+20+96-24-5 , "d", colors[BLACK]); DrawCircle(240+20+96+24, 100+20+96+292-24, 12, colors[DARK_BLUE]); DrawString(240+20+96+24-5,100+20+96+292-24-5 , "d", colors[BLACK]); } } } else if(i==2) //red { if(piece[i][j]==-1) { if(j==0) { DrawCircle(240+20+96+292-24, 100+20+96+292-24, 12, colors[FIREBRICK]);// darker red shade DrawString(240+20+96+292-24-5,100+20+96+292-24-5 , "a", colors[BLACK]); //DrawCircle(240+20+96-24, 100+20+96+292-24, 12, colors[FIREBRICK]); //DrawString(240+20+96-24-5,100+20+96+292-24-5 , "a", colors[BLACK]); } else if(j==1) { DrawCircle(240+20+96+292-24, 100+20+96+292+24, 12, colors[FIREBRICK]); DrawString(240+20+96+292-24-5,100+20+96+292+24-5 , "b", colors[BLACK]); //DrawCircle(240+20+96-24, 100+20+96+292+24, 12, colors[FIREBRICK]); //DrawString(240+20+96-24-5,100+20+96+292+24-5 , "b", colors[BLACK]); } else if(j==2) { //DrawCircle(240+20+96+24, 100+20+96+292+24, 12, colors[FIREBRICK]); //DrawString(240+20+96+24-5,100+20+96+292+24-5 , "c", colors[BLACK]); DrawCircle(240+20+96+292+24, 100+20+96+292+24, 12, colors[FIREBRICK]); DrawString(240+20+96+292+24-5,100+20+96+292+24-5 , "c", colors[BLACK]); } else { DrawCircle(240+20+96+292+24, 100+20+96+292-24, 12, colors[FIREBRICK]); DrawString(240+20+96+292+24-5,100+20+96+292-24-5 , "d", colors[BLACK]); //DrawCircle(240+20+96+24, 100+20+96+292-24, 12, colors[FIREBRICK]); //DrawString(240+20+96+24-5,100+20+96+292-24-5 , "d", colors[BLACK]); } } } else //green { if(piece[i][j]==-1) { if(j==0) { DrawCircle(240+20+96+292-24, 100+20+96-24, 12, colors[GREEN]); DrawString(240+20+96+292-24-5,100+20+96-24-5 , "a", colors[BLACK]); //DrawCircle(240+20+96-24, 100+20+96+292-24, 12, colors[FIREBRICK]); //DrawString(240+20+96-24-5,100+20+96+292-24-5 , "a", colors[BLACK]); } else if(j==1) { DrawCircle(240+20+96+292-24, 100+20+96+24, 12, colors[GREEN]); DrawString(240+20+96+292-24-5,100+20+96+24-5 , "b", colors[BLACK]); //DrawCircle(240+20+96-24, 100+20+96+292+24, 12, colors[FIREBRICK]); //DrawString(240+20+96-24-5,100+20+96+292+24-5 , "b", colors[BLACK]); } else if(j==2) { //DrawCircle(240+20+96+24, 100+20+96+292+24, 12, colors[FIREBRICK]); //DrawString(240+20+96+24-5,100+20+96+292+24-5 , "c", colors[BLACK]); DrawCircle(240+20+96+292+24, 100+20+96+24, 12, colors[GREEN]); DrawString(240+20+96+292+24-5,100+20+96+24-5 , "c", colors[BLACK]); } else { DrawCircle(240+20+96+292+24, 100+20+96-24, 12, colors[GREEN]); DrawString(240+20+96+292+24-5,100+20+96-24-5 , "d", colors[BLACK]); //DrawCircle(240+20+96+24, 100+20+96+292-24, 12, colors[FIREBRICK]); //DrawString(240+20+96+24-5,100+20+96+292-24-5 , "d", colors[BLACK]); } } } } } glutPostRedisplay(); } void drawPieces() // this function draws the pieces ONLY when they are NOT in the starting circle { //drawing position of pieces for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { if(piece[i][j]!=-1 && piece[i][j]!=-2) { if(i==0) { DrawCircle(squares[piece[i][j]][0], squares[piece[i][j]][1],12, colors[DARK_GOLDEN_ROD]); if(j==0) { DrawString(squares[piece[i][j]][0]-5, squares[piece[i][j]][1]-5, "a", colors[BLACK]); } else if(j==1) { DrawString(squares[piece[i][j]][0]-5, squares[piece[i][j]][1]-5, "b", colors[BLACK]); } else if(j==2) { DrawString(squares[piece[i][j]][0]-5, squares[piece[i][j]][1]-5, "c", colors[BLACK]); } else { DrawString(squares[piece[i][j]][0]-5, squares[piece[i][j]][1]-5, "d", colors[BLACK]); } } else if(i==1) { DrawCircle(squares[piece[i][j]][0], squares[piece[i][j]][1],12, colors[DARK_BLUE]); if(j==0) { DrawString(squares[piece[i][j]][0]-5, squares[piece[i][j]][1]-5, "a", colors[BLACK]); } else if(j==1) { DrawString(squares[piece[i][j]][0]-5, squares[piece[i][j]][1]-5, "b", colors[BLACK]); } else if(j==2) { DrawString(squares[piece[i][j]][0]-5, squares[piece[i][j]][1]-5, "c", colors[BLACK]); } else { DrawString(squares[piece[i][j]][0]-5, squares[piece[i][j]][1]-5, "d", colors[BLACK]); } } else if(i==2) { DrawCircle(squares[piece[i][j]][0], squares[piece[i][j]][1],12, colors[FIREBRICK]); if(j==0) { DrawString(squares[piece[i][j]][0]-5, squares[piece[i][j]][1]-5, "a", colors[BLACK]); } else if(j==1) { DrawString(squares[piece[i][j]][0]-5, squares[piece[i][j]][1]-5, "b", colors[BLACK]); } else if(j==2) { DrawString(squares[piece[i][j]][0]-5, squares[piece[i][j]][1]-5, "c", colors[BLACK]); } else { DrawString(squares[piece[i][j]][0]-5, squares[piece[i][j]][1]-5, "d", colors[BLACK]); } } else //i==3 { DrawCircle(squares[piece[i][j]][0], squares[piece[i][j]][1],12, colors[GREEN]); if(j==0) { DrawString(squares[piece[i][j]][0]-5, squares[piece[i][j]][1]-5, "a", colors[BLACK]); } else if(j==1) { DrawString(squares[piece[i][j]][0]-5, squares[piece[i][j]][1]-5, "b", colors[BLACK]); } else if(j==2) { DrawString(squares[piece[i][j]][0]-5, squares[piece[i][j]][1]-5, "c", colors[BLACK]); } else { DrawString(squares[piece[i][j]][0]-5, squares[piece[i][j]][1]-5, "d", colors[BLACK]); } } } } } glutPostRedisplay(); } void drawPiecesHomeTriangle() // this function draws only those pieces which are in home triangle { //pieces are difficult to be seen visually when overlapping so in home triangle every piece has its unique place where it goes for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { if(piece[i][j]==-2) //piece is in home triangle { if(i==0) // yellow { if(j==0) { DrawCircle(240+20+(32*7)+16, 100+20+(32*7), 12, colors[DARK_GOLDEN_ROD]); DrawString(240+20+(32*7)+16-5, 100+20+(32*7)-5, "a", colors[BLACK]); } else if(j==1) { DrawCircle(240+20+(32*6)+16+12, 100+20+(32*6)+12, 12, colors[DARK_GOLDEN_ROD]); DrawString(240+20+(32*6)+16+12-5, 100+20+(32*6)+12-5, "b", colors[BLACK]); } else if(j==2) { DrawCircle(240+20+(32*6)+16+12+20, 100+20+(32*6)+12, 12, colors[DARK_GOLDEN_ROD]); DrawString(240+20+(32*6)+16+12-5+20, 100+20+(32*6)+12-5, "c", colors[BLACK]); } else //if j==3 { DrawCircle(240+20+(32*6)+16+12+40, 100+20+(32*6)+12, 12, colors[DARK_GOLDEN_ROD]); DrawString(240+20+(32*6)+16+12-5+40, 100+20+(32*6)+12-5, "d", colors[BLACK]); } } else if(i==1) //BLUE { if(j==0) { DrawCircle(240+20+(32*6)+16+13, 100+20+(32*6)+12+38, 12, colors[DARK_BLUE]); DrawString(240+20+(32*6)+16+13-5, 100+20+(32*6)+12+38-5, "a", colors[BLACK]); } else if(j==1) { DrawCircle(240+20+(32*6)+13, 100+20+(32*6)+12+38+20, 12, colors[DARK_BLUE]); DrawString(240+20+(32*6)+13-5, 100+20+(32*6)+12+38-5+20, "b", colors[BLACK]); } else if(j==2) { DrawCircle(240+20+(32*6)+13, 100+20+(32*6)+12+38, 12, colors[DARK_BLUE]); DrawString(240+20+(32*6)+13-5, 100+20+(32*6)+12+38-5, "c", colors[BLACK]); } else //if j==3 { DrawCircle(240+20+(32*6)+13, 100+20+(32*6)+12+38-20, 12, colors[DARK_BLUE]); DrawString(240+20+(32*6)+13-5, 100+20+(32*6)+12+38-5-20, "d", colors[BLACK]); } } else if(i==2)//red { if(j==0) { DrawCircle(240+20+(32*7)+16, 100+20+(32*8), 12, colors[FIREBRICK]); DrawString(240+20+(32*7)+16-5, 100+20+(32*8)-5, "a", colors[BLACK]); } else if(j==1) { DrawCircle(240+20+(32*6)+16+12, 100+20+(32*8)+12+10, 12, colors[FIREBRICK]); DrawString(240+20+(32*6)+16+12-5, 100+20+(32*8)+12-5+10, "b", colors[BLACK]); } else if(j==2) { DrawCircle(240+20+(32*6)+16+12+20, 100+20+(32*8)+12+10, 12, colors[FIREBRICK]); DrawString(240+20+(32*6)+16+12-5+20, 100+20+(32*8)+12+10-5, "c", colors[BLACK]); } else //if j==3 { DrawCircle(240+20+(32*6)+16+12+40, 100+20+(32*8)+12+10, 12, colors[FIREBRICK]); DrawString(240+20+(32*6)+16+12-5+40, 100+20+(32*8)+12+10-5, "d", colors[BLACK]); } } else //i==3 green { if(j==0) { DrawCircle(240+20+(32*6)+16+13+37, 100+20+(32*6)+12+38, 12, colors[GREEN]); DrawString(240+20+(32*6)+16+13-5+37, 100+20+(32*6)+12+38-5, "a", colors[BLACK]); } else if(j==1) { DrawCircle(240+20+(32*7)+13+40, 100+20+(32*6)+12+38+20, 12, colors[GREEN]); DrawString(240+20+(32*7)+13-5+40, 100+20+(32*6)+12+38-5+20, "b", colors[BLACK]); } else if(j==2) { DrawCircle(240+20+(32*7)+13+40, 100+20+(32*6)+12+38, 12, colors[GREEN]); DrawString(240+20+(32*7)+13-5+40, 100+20+(32*6)+12+38-5, "c", colors[BLACK]); } else //if j==3 { DrawCircle(240+20+(32*7)+13+40, 100+20+(32*6)+12+38-20, 12, colors[GREEN]); DrawString(240+20+(32*7)+13-5+40, 100+20+(32*6)+12+38-5-20, "d", colors[BLACK]); } } } } } glutPostRedisplay(); } void drawDice(int diceNum) // this function creates the animated dice using the argument of the dice number passed to it { //DrawSquare( 1140-20 , 620-20 , 40, colors[SANDY_BROWN]); DrawRoundRect(1120, 600-230, 44, 44, colors[SANDY_BROWN], 10); if(diceNum==1) { DrawCircle(1120+22, 600+22-230, 5, colors[BLACK]); } else if(diceNum==2) { DrawCircle(1120+10-5+22, 600+10-5+22-230, 5, colors[BLACK]); DrawCircle(1120-10+5+22, 600-10+5+22-230, 5, colors[BLACK]); } else if(diceNum==3) { DrawCircle(1120+22, 600+22-230, 5, colors[BLACK]); DrawCircle(1120+10+22, 600+10+22-230, 5, colors[BLACK]); DrawCircle(1120-10+22, 600-10+22-230, 5, colors[BLACK]); } else if(diceNum==4) { DrawCircle(1120+10-3+22, 600+10-3+22-230, 5, colors[BLACK]); DrawCircle(1120-10+3+22, 600-10+3+22-230, 5, colors[BLACK]); DrawCircle(1120+10-3+22-15, 600+10-3+22-230, 5, colors[BLACK]); DrawCircle(1120-10+3+22+15, 600-10+3+22-230, 5, colors[BLACK]); } else if(diceNum==5) { DrawCircle(1120+22, 600+22-230, 5, colors[BLACK]); DrawCircle(1120+10+22, 600+10+22-230, 5, colors[BLACK]); DrawCircle(1120-10+22, 600-10+22-230, 5, colors[BLACK]); DrawCircle(1120-10+22, 600+10+22-230, 5, colors[BLACK]); DrawCircle(1120+10+22, 600-10+22-230, 5, colors[BLACK]); } else //if diceNum==6 { DrawCircle(1120+10-3+22-15-1, 600+10-3+22+5-230, 5, colors[BLACK]); // top left DrawCircle(1120+10-3+22+1, 600+10-3+22+5-230, 5, colors[BLACK]); // top right DrawCircle(1120-10+3+22-1, 600-10+5+22+5-230, 5, colors[BLACK]); // middle left DrawCircle(1120-10+3+22+15+1, 600-10+5+22+5-230, 5, colors[BLACK]); // middle right DrawCircle(1120-10+3+22-1, 600-10+3+22-5-230, 5, colors[BLACK]); // bottom left DrawCircle(1120-10+3+22+15+1, 600-10+3+22-5-230, 5, colors[BLACK]); // bottom right } glutPostRedisplay(); } void writeNames() // this function writes names of players who are playing next to their color { for(int i=0;i<players;i++) { if(playerColors[i]==0) // yellow { for(int x=0;playerNames[i][x]!='\0';x++) // divides playerNames[i] single string to characters . {// '\0' refers to the NULL character. It is present at the end of string so it lets know that the string has ended string playerNamesStringArray[15]; // this string is being used as a character array to store characters of playerNames[i] string 1 by 1 playerNamesStringArray[x]=playerNames[i][x]; DrawString(450+(x*18),50,playerNamesStringArray[x],colors[BLACK]); // this function then displays those characters 1 by 1 as the for loop runs } //DrawString(450,50,playerNames[i],colors[BLACK]); } if(playerColors[i]==1) //blue { for(int x=0;playerNames[i][x]!='\0';x++) { string playerNamesStringArray[15]; playerNamesStringArray[x]=playerNames[i][x]; DrawString(120,100+520-220-(x*18),playerNamesStringArray[x],colors[BLACK]); } } if(playerColors[i]==2) // red { for(int x=0;playerNames[i][x]!='\0';x++) { string playerNamesStringArray[15]; playerNamesStringArray[x]=playerNames[i][x]; DrawString(450+(x*18),100+520+50,playerNamesStringArray[x],colors[BLACK]); } //DrawString(450,100+520+50,playerNames[i],colors[BLACK]); } if(playerColors[i]==3) // green { for(int x=0;playerNames[i][x]!='\0';x++) { string playerNamesStringArray[15]; playerNamesStringArray[x]=playerNames[i][x]; DrawString(240+520+120,100+520-220-(x*18),playerNamesStringArray[x],colors[BLACK]); } } } glutPostRedisplay(); } void homeColumnStatus() // this function displays a cross on home columns if they are closed { for(int i=0;i<4;i++) { if(status[i]!=-1) // either playing or won { if(killCount[i]==0) { //DrawLine(int x1, int y1, int x2, int y2, int lwidth, float *color) //DrawLine( 550 , 50 , 550 , 480 , 10 , colors[MISTY_ROSE] ); if(i==0) { DrawCircle(484+16,152+16,10,colors[SANDY_BROWN]); DrawCircle(484+16,152+16,7,colors[OLIVE]); } if(i==1) { DrawCircle(308,360,10,colors[SANDY_BROWN]); DrawCircle(308,360,7,colors[BLUE]); } if(i==2) { DrawCircle(484+16,552,10,colors[SANDY_BROWN]); DrawCircle(484+16,552,7,colors[RED]); } if(i==3) { DrawCircle(692,360,10,colors[SANDY_BROWN]); DrawCircle(692,360,7,colors[LIME]); } } else { // display nothing } } } } int checkForHomeColumn(int diceNum) //check if the piece is eligible and also can move to home triangle { if(turn==0 && killCount[turn]>0) // if kills are zero then the piece will move along the board instead of going in the home column { if(piece[turn][keyPressed-97]+dices[diceNum]>50) { piece[turn][keyPressed-97]+=49+dices[diceNum]; // this logic was created with the help of pen and paper return 1; } } else if(turn==1 && killCount[turn]>0) { if(piece[turn][keyPressed-97]+dices[diceNum]>11 && piece[turn][keyPressed-97]<=11) { piece[turn][keyPressed-97]+=94+dices[diceNum]; // this logic was created with the help of pen and paper return 1; } } else if(turn==2 && killCount[turn]>0) { if(piece[turn][keyPressed-97]+dices[diceNum]>24 && piece[turn][keyPressed-97]<=24) { piece[turn][keyPressed-97]+=87+dices[diceNum]; // this logic was created with the help of pen and paper return 1; } } else if(turn==3 && killCount[turn]>0) { if(piece[turn][keyPressed-97]+dices[diceNum]>37 && piece[turn][keyPressed-97]<=37) { piece[turn][keyPressed-97]+=80+dices[diceNum]; // this logic was created with the help of pen and paper return 1; } } else { return 0; } } void checkForKill() // check if a piece is killing another piece { //piece[turn][keyPressed-97] if(teamMode==0) { for(int i=0;i<4;i++) // colours { if(turn!=i) // not the same colors { for(int j=0;j<4;j++) // pieces { if((piece[turn][keyPressed-97]==piece[i][j]) && piece[i][j]!=-1 && piece[i][j]!=-2 && piece[i][j]!=0 && piece[i][j]!=8 && piece[i][j]!=13 && piece[i][j]!=21 && piece[i][j]!=26 && piece[i][j]!=34 && piece[i][j]!=39 && piece[i][j]!=47 && piece[i][j]<52) // all these are safe spots where a piece cannot be removed {// one piece kills another killCount[turn]++; score[turn]+=10; piece[i][j]=-1; // move back to the starting circle turn--; // gives the player another turn } } } } } if(teamMode==1) // teammates are unable to remove each other's pieces from the board { for(int i=0;i<4;i++) // colours { if(turn<=1) { if(turn!=i && i!=turn+2) // not the same colors or same teams { for(int j=0;j<4;j++) // pieces { if((piece[turn][keyPressed-97]==piece[i][j]) && piece[i][j]!=-1 && piece[i][j]!=-2 && piece[i][j]!=0 && piece[i][j]!=8 && piece[i][j]!=13 && piece[i][j]!=21 && piece[i][j]!=26 && piece[i][j]!=34 && piece[i][j]!=39 && piece[i][j]!=47 && piece[i][j]<52) // all these are safe spots where a piece cannot be removed {// one piece kills another killCount[turn]++; score[turn]+=10; piece[i][j]=-1; // move back to the starting circle turn--; // gives the player another turn } } } } if(turn>=2) { if(turn!=i && i!=turn-2) // not the same colors or same teams { for(int j=0;j<4;j++) // pieces { if((piece[turn][keyPressed-97]==piece[i][j]) && piece[i][j]!=-1 && piece[i][j]!=-2 && piece[i][j]!=0 && piece[i][j]!=8 && piece[i][j]!=13 && piece[i][j]!=21 && piece[i][j]!=26 && piece[i][j]!=34 && piece[i][j]!=39 && piece[i][j]!=47 && piece[i][j]<52) // all these are safe spots where a piece cannot be removed {// one piece kills another killCount[turn]++; score[turn]+=10; piece[i][j]=-1; // move back to the starting circle turn--; // gives the player another turn } } } } } } } void blocksFormed() // checks if a block is formed and displays it { if(teamMode==0) { for(int i=0;i<4;i++) //turns { for(int j=0;j<4;j++) { for(int k=0;k<4;k++) { if((piece[i][j]==piece[i][k] && j!=k) && piece[i][j]!=-1 && piece[i][j]!=-2 && piece[i][j]!=0 && piece[i][j]!=8 && piece[i][j]!=13 && piece[i][j]!=21 && piece[i][j]!=26 && piece[i][j]!=34 && piece[i][j]!=39 && piece[i][j]!=47 && piece[i][j]<100) // other pieces { if(i==0) { DrawSquare(squares[piece[i][j]][0]-13,squares[piece[i][j]][1]-13,26,colors[DARK_GOLDEN_ROD]); if (j==0) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "a", colors[BLACK]); } else if(j==1) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "b", colors[BLACK]); } else if(j==2) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "c", colors[BLACK]); } else //if j==3 { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "d", colors[BLACK]); } if(k==0) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "a", colors[BLACK]); } else if(k==1) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "b", colors[BLACK]); } else if(k==2) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "c", colors[BLACK]); } else // if k==3 { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "d", colors[BLACK]); } } else if(i==1) { DrawSquare(squares[piece[i][j]][0]-13,squares[piece[i][j]][1]-13,26,colors[DARK_BLUE]); if (j==0) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "a", colors[BLACK]); } else if(j==1) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "b", colors[BLACK]); } else if(j==2) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "c", colors[BLACK]); } else //if j==3 { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "d", colors[BLACK]); } if(k==0) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "a", colors[BLACK]); } else if(k==1) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "b", colors[BLACK]); } else if(k==2) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "c", colors[BLACK]); } else // if k==3 { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "d", colors[BLACK]); } } else if(i==2) { DrawSquare(squares[piece[i][j]][0]-13,squares[piece[i][j]][1]-13,26,colors[FIREBRICK]); if (j==0) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "a", colors[BLACK]); } else if(j==1) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "b", colors[BLACK]); } else if(j==2) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "c", colors[BLACK]); } else //if j==3 { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "d", colors[BLACK]); } if(k==0) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "a", colors[BLACK]); } else if(k==1) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "b", colors[BLACK]); } else if(k==2) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "c", colors[BLACK]); } else // if k==3 { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "d", colors[BLACK]); } } else //if i==4 { DrawSquare(squares[piece[i][j]][0]-13,squares[piece[i][j]][1]-13,26,colors[GREEN]); if (j==0) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "a", colors[BLACK]); } else if(j==1) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "b", colors[BLACK]); } else if(j==2) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "c", colors[BLACK]); } else //if j==3 { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "d", colors[BLACK]); } if(k==0) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "a", colors[BLACK]); } else if(k==1) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "b", colors[BLACK]); } else if(k==2) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "c", colors[BLACK]); } else // if k==3 { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "d", colors[BLACK]); } } /*if (j==0) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "a", colors[BLACK]); } else if(j==1) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "b", colors[BLACK]); } else if(j==2) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "c", colors[BLACK]); } else //if j==3 { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "d", colors[BLACK]); } if(k==0) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "a", colors[BLACK]); } else if(k==1) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "b", colors[BLACK]); } else if(k==2) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "c", colors[BLACK]); } else // if k==3 { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "d", colors[BLACK]); }*/ block[piece[i][j]]=1; } } } } } if(teamMode==1) { for(int i=0;i<4;i++) // this for loop is for same colored block { for(int j=0;j<4;j++) { for(int k=0;k<4;k++) { if((piece[i][j]==piece[i][k] && j!=k) && piece[i][j]!=-1 && piece[i][j]!=-2 && piece[i][j]!=0 && piece[i][j]!=8 && piece[i][j]!=13 && piece[i][j]!=21 && piece[i][j]!=26 && piece[i][j]!=34 && piece[i][j]!=39 && piece[i][j]!=47 && piece[i][j]<100) // other pieces { if(i==0) { DrawSquare(squares[piece[i][j]][0]-13,squares[piece[i][j]][1]-13,26,colors[DARK_GOLDEN_ROD]); if (j==0) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "a", colors[BLACK]); } else if(j==1) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "b", colors[BLACK]); } else if(j==2) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "c", colors[BLACK]); } else //if j==3 { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "d", colors[BLACK]); } if(k==0) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "a", colors[BLACK]); } else if(k==1) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "b", colors[BLACK]); } else if(k==2) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "c", colors[BLACK]); } else // if k==3 { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "d", colors[BLACK]); } } else if(i==1) { DrawSquare(squares[piece[i][j]][0]-13,squares[piece[i][j]][1]-13,26,colors[DARK_BLUE]); if (j==0) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "a", colors[BLACK]); } else if(j==1) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "b", colors[BLACK]); } else if(j==2) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "c", colors[BLACK]); } else //if j==3 { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "d", colors[BLACK]); } if(k==0) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "a", colors[BLACK]); } else if(k==1) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "b", colors[BLACK]); } else if(k==2) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "c", colors[BLACK]); } else // if k==3 { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "d", colors[BLACK]); } } else if(i==2) { DrawSquare(squares[piece[i][j]][0]-13,squares[piece[i][j]][1]-13,26,colors[FIREBRICK]); if (j==0) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "a", colors[BLACK]); } else if(j==1) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "b", colors[BLACK]); } else if(j==2) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "c", colors[BLACK]); } else //if j==3 { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "d", colors[BLACK]); } if(k==0) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "a", colors[BLACK]); } else if(k==1) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "b", colors[BLACK]); } else if(k==2) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "c", colors[BLACK]); } else // if k==3 { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "d", colors[BLACK]); } } else //if i==4 { DrawSquare(squares[piece[i][j]][0]-13,squares[piece[i][j]][1]-13,26,colors[GREEN]); if (j==0) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "a", colors[BLACK]); } else if(j==1) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "b", colors[BLACK]); } else if(j==2) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "c", colors[BLACK]); } else //if j==3 { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "d", colors[BLACK]); } if(k==0) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "a", colors[BLACK]); } else if(k==1) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "b", colors[BLACK]); } else if(k==2) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "c", colors[BLACK]); } else // if k==3 { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "d", colors[BLACK]); } } block[piece[i][j]]=1; } } } } for(int i=0;i<4;i++) // this for loop is for different coloured blocks { for(int j=0;j<4;j++) { for(int k=0;k<4;k++) { if(i<=1) { if((piece[i][j]==piece[i+2][k]) && piece[i][j]!=-1 && piece[i][j]!=-2 && piece[i][j]!=0 && piece[i][j]!=8 && piece[i][j]!=13 && piece[i][j]!=21 && piece[i][j]!=26 && piece[i][j]!=34 && piece[i][j]!=39 && piece[i][j]!=47 && piece[i][j]<100) // other pieces { if(i==0) { DrawSquare(squares[piece[i][j]][0]-13,squares[piece[i][j]][1]-13,26,colors[FIREBRICK]); DrawRectangle(squares[piece[i][j]][0]-13,squares[piece[i][j]][1]-13,26/2,26,colors[DARK_GOLDEN_ROD]); // tested this logic. if you overlap a half rectangle on a square, it looks like there are 2 half rectangles if (j==0) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "a", colors[BLACK]); } else if(j==1) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "b", colors[BLACK]); } else if(j==2) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "c", colors[BLACK]); } else //if j==3 { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "d", colors[BLACK]); } if(k==0) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "a", colors[BLACK]); } else if(k==1) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "b", colors[BLACK]); } else if(k==2) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "c", colors[BLACK]); } else // if k==3 { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "d", colors[BLACK]); } } else if(i==1) { DrawSquare(squares[piece[i][j]][0]-13,squares[piece[i][j]][1]-13,26,colors[GREEN]); DrawRectangle(squares[piece[i][j]][0]-13,squares[piece[i][j]][1]-13,26/2,26,colors[DARK_BLUE]); //DrawSquare(squares[piece[i][j]][0]-13,squares[piece[i][j]][1]-13,26,colors[DARK_BLUE]); if (j==0) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "a", colors[BLACK]); } else if(j==1) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "b", colors[BLACK]); } else if(j==2) { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "c", colors[BLACK]); } else //if j==3 { DrawString(squares[piece[i][j]][0]-12,squares[piece[i][j]][1]-13+5 , "d", colors[BLACK]); } if(k==0) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "a", colors[BLACK]); } else if(k==1) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "b", colors[BLACK]); } else if(k==2) { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "c", colors[BLACK]); } else // if k==3 { DrawString(squares[piece[i][j]][0]+1,squares[piece[i][j]][1]-13+5 , "d", colors[BLACK]); } } block[piece[i][j]]=1; } } } } } } glutPostRedisplay(); } void moveFromBlock(int diceNum) // if a piece moves from the block, this function breaks the block { if(piece[turn][keyPressed-97]-dices[diceNum]<0) // the block was before the 0th position { if(block[52+piece[turn][keyPressed-97]-dices[diceNum]]==1) // this logic was created with the help of pen and paper { block[52+piece[turn][keyPressed-97]-dices[diceNum]]=0; score[turn]+=2; } } else if(piece[turn][keyPressed-97]-dices[diceNum]>=0) // the block was after 0th position(i.e. yellow's starting square) { if(block[piece[turn][keyPressed-97]-dices[diceNum]]==1) { block[piece[turn][keyPressed-97]-dices[diceNum]]=0; score[turn]+=2; } } } int colorAtBlock(int x) // returns the number of color at the block(0,1,2,3) { for(int a=0;a<4;a++) { for(int b=0;b<4;b++) { if(piece[a][b]==x) { return a; } } } } int checkForBlock(int diceNum) // checks whether a block exists in the path of the piece { // returns 0 if the pathway is open. returns 1 if the pathway is closed by a block int blockCounter=0; if(teamMode==0) { if(piece[turn][keyPressed-97]+dices[diceNum]<52) { for(int i=piece[turn][keyPressed-97]+1;i<=(piece[turn][keyPressed-97]+dices[diceNum]);i++) { if(block[i]==1 && colorAtBlock(i)!=turn) // colorAtBlock(i)!=turn allows only the same color to cross the block { blockCounter++; } } } else if((piece[turn][keyPressed-97]+dices[diceNum])>=52 && (piece[turn][keyPressed-97]+dices[diceNum])<100) { for(int i=piece[turn][keyPressed-97]+1;i<=(piece[turn][keyPressed-97]+dices[diceNum]);i++) { if(i<52) { if(block[i]==1 && colorAtBlock(i)!=turn) // colorAtBlock(i)!=turn allows only the same color to cross the block { blockCounter++; } } if(i>=52) { if(block[i-52]==1 && colorAtBlock(i-52)!=turn) // colorAtBlock(i-52)!=turn allows only the same color to cross the block { blockCounter++; } } } // this function started creating issues when pieces crossed yellow's home cirlcle. so all this logic was created to remove those issues } } if(teamMode==1) { if(turn<=1) { if(piece[turn][keyPressed-97]+dices[diceNum]<52) { for(int i=piece[turn][keyPressed-97]+1;i<=(piece[turn][keyPressed-97]+dices[diceNum]);i++) { if(block[i]==1 && colorAtBlock(i)!=turn && colorAtBlock(i)!=(turn+2)) // colorAtBlock(i)!=turn allows only the same color to cross the block { blockCounter++; } } } else if((piece[turn][keyPressed-97]+dices[diceNum])>=52 && (piece[turn][keyPressed-97]+dices[diceNum])<100) { for(int i=piece[turn][keyPressed-97]+1;i<=(piece[turn][keyPressed-97]+dices[diceNum]);i++) { if(i<52) { if(block[i]==1 && colorAtBlock(i)!=turn && colorAtBlock(i)!=(turn+2)) // colorAtBlock(i)!=turn allows only the same color to cross the block { blockCounter++; } } if(i>=52) { if(block[i-52]==1 && colorAtBlock(i-52)!=turn && colorAtBlock(i-52)!=(turn+2)) // colorAtBlock(i-52)!=turn allows only the same color to cross the block { blockCounter++; } } } // this function started creating issues when pieces crossed yellow's home cirlcle. so all this logic was created to remove those issues } } if(turn>=2) { if(piece[turn][keyPressed-97]+dices[diceNum]<52) { for(int i=piece[turn][keyPressed-97]+1;i<=(piece[turn][keyPressed-97]+dices[diceNum]);i++) { if(block[i]==1 && colorAtBlock(i)!=turn && colorAtBlock(i)!=(turn-2)) // colorAtBlock(i)!=turn allows only the same color to cross the block { blockCounter++; } } } else if((piece[turn][keyPressed-97]+dices[diceNum])>=52 && (piece[turn][keyPressed-97]+dices[diceNum])<100) { for(int i=piece[turn][keyPressed-97]+1;i<=(piece[turn][keyPressed-97]+dices[diceNum]);i++) { if(i<52) { if(block[i]==1 && colorAtBlock(i)!=(turn-2) && colorAtBlock(i)!=(turn-2)) // colorAtBlock(i)!=turn allows only the same color to cross the block { blockCounter++; } } if(i>=52) { if(block[i-52]==1 && colorAtBlock(i-52)!=(turn-2) && colorAtBlock(i-52)!=(turn-2)) // colorAtBlock(i-52)!=turn allows only the same color to cross the block { blockCounter++; } } } // this function started creating issues when pieces crossed yellow's home cirlcle. so all this logic was created to remove those issues } } } if(blockCounter>0) { return 1; } else { return 0; } } int checkForHomeTriangle_Six() //this function puts the piece in home triangle ONLY when the piece is out of the home column on the first block before it. As then the piece needs a 6 to move to home triangle { if(turn == 0 && killCount[turn]>0 && piece[turn][keyPressed-97]==50 ) { return 1; } if(turn == 1 && killCount[turn]>0 && piece[turn][keyPressed-97]==11 ) { return 1; } if(turn == 2 && killCount[turn]>0 && piece[turn][keyPressed-97]==24 ) { return 1; } if(turn == 3 && killCount[turn]>0 && piece[turn][keyPressed-97]==37 ) { return 1; } return 0; // did not move to home triangle( actually it will move along the board agiain) } void limitHomeThrow(int diceNum) // a piece enters home triangle only on exact throw { if(turn ==0) { if(piece[turn][keyPressed-97]+dices[diceNum]==105) { piece[turn][keyPressed-97]=-2; score[turn]+=dices[diceNum]; turn--; // gives an extra turn } else if(piece[turn][keyPressed-97]+dices[diceNum]<105) { piece[turn][keyPressed-97]+=dices[diceNum]; score[turn]+=dices[diceNum]; } else { // do nothing } } else if(turn == 1) { if(piece[turn][keyPressed-97]+dices[diceNum]==111) { piece[turn][keyPressed-97]=-2; score[turn]+=dices[diceNum]; turn--; // gives an extra turn } else if(piece[turn][keyPressed-97]+dices[diceNum]<111) { piece[turn][keyPressed-97]+=dices[diceNum]; score[turn]+=dices[diceNum]; } else { // do nothing } } else if(turn == 2) { if(piece[turn][keyPressed-97]+dices[diceNum]==117) { piece[turn][keyPressed-97]=-2; score[turn]+=dices[diceNum]; turn--; // gives an extra turn } else if(piece[turn][keyPressed-97]+dices[diceNum]<117) { piece[turn][keyPressed-97]+=dices[diceNum]; score[turn]+=dices[diceNum]; } else { // do nothing } } else if(turn == 3) { if(piece[turn][keyPressed-97]+dices[diceNum]==123) { piece[turn][keyPressed-97]=-2; score[turn]+=dices[diceNum]; turn--; // gives an extra turn } else if(piece[turn][keyPressed-97]+dices[diceNum]<123) { piece[turn][keyPressed-97]+=dices[diceNum]; score[turn]+=dices[diceNum]; } else { // do nothing } } } void checkForWinners() // checks if there are any winners after the last turn and gives winner status=1; { for(int i=0;i<4;i++) { int count=0; for(int j=0;j<4;j++) { if(piece[i][j]==-2) // in home triangle { count++; } } if(count==4) // all 4 pieces in home triangle { status[i]=1; // the COLOR i has won } } } void setStatus() // this function only runs once to set the status of playing colors to zero { static int i=0; if(i==0) { for(int x=0;x<4;x++) { if(playerColors[x]>=0) { status[playerColors[x]]=0; // in play } } i++; } } void nextTurn() // this function selects which color is getting the next turn { for(;;) { if(turn >= 4) // there is no 4th player. turn statrts from zero again { turn=0; } if (status[turn]==1 || status[turn]==-1) // turn++ if a color is disabled or has won { turn++; continue; } else { break; } } } //TeamMode functions are created starting from here /// FOR TURN+2(This means when 0th and 1st players gives theur turn to 2nd and 3rd player respectively) // therefore all these functions are named TeamPlus int checkForHomeColumnTeamPlus(int diceNum) //check if the piece is eligible and also can move to home triangle { if(turn+2==0 && killCount[turn+2]>0) // if kills are zero then the piece will move along the board instead of going in the home column { if(piece[turn+2][keyPressed-97]+dices[diceNum]>50) { piece[turn+2][keyPressed-97]+=49+dices[diceNum]; // this logic was created with the help of pen and paper return 1; } } else if(turn+2==1 && killCount[turn+2]>0) { if(piece[turn+2][keyPressed-97]+dices[diceNum]>11 && piece[turn+2][keyPressed-97]<=11) { piece[turn+2][keyPressed-97]+=94+dices[diceNum]; // this logic was created with the help of pen and paper return 1; } } else if(turn+2==2 && killCount[turn+2]>0) { if(piece[turn+2][keyPressed-97]+dices[diceNum]>24 && piece[turn+2][keyPressed-97]<=24) { piece[turn+2][keyPressed-97]+=87+dices[diceNum]; // this logic was created with the help of pen and paper return 1; } } else if(turn+2==3 && killCount[turn+2]>0) { if(piece[turn+2][keyPressed-97]+dices[diceNum]>37 && piece[turn+2][keyPressed-97]<=37) { piece[turn+2][keyPressed-97]+=80+dices[diceNum]; // this logic was created with the help of pen and paper return 1; } } else { return 0; } } void checkForKillTeamPlus() // check if a piece is killing another piece { //piece[turn][keyPressed-97] for(int i=0;i<4;i++) // colours { if(turn+2<=1) { if(turn+2!=i && i!=turn+2+2) // not the same colors or same teams { for(int j=0;j<4;j++) // pieces { if((piece[turn+2][keyPressed-97]==piece[i][j]) && piece[i][j]!=-1 && piece[i][j]!=-2 && piece[i][j]!=0 && piece[i][j]!=8 && piece[i][j]!=13 && piece[i][j]!=21 && piece[i][j]!=26 && piece[i][j]!=34 && piece[i][j]!=39 && piece[i][j]!=47 && piece[i][j]<52) // all these are safe spots where a piece cannot be removed {// one piece kills another killCount[turn+2]++; score[turn+2]+=10; piece[i][j]=-1; // move back to the starting circle turn--; // gives the player another turn } } } } if(turn+2>=2) { if(turn+2!=i && i!=turn+2-2) // not the same colors or same teams { for(int j=0;j<4;j++) // pieces { if((piece[turn+2][keyPressed-97]==piece[i][j]) && piece[i][j]!=-1 && piece[i][j]!=-2 && piece[i][j]!=0 && piece[i][j]!=8 && piece[i][j]!=13 && piece[i][j]!=21 && piece[i][j]!=26 && piece[i][j]!=34 && piece[i][j]!=39 && piece[i][j]!=47 && piece[i][j]<52) // all these are safe spots where a piece cannot be removed {// one piece kills another killCount[turn+2]++; score[turn+2]+=10; piece[i][j]=-1; // move back to the starting circle turn--; // gives the player another turn } } } } } } void moveFromBlockTeamPlus(int diceNum) // if a piece moves from the block, this function breaks the block { if(piece[turn+2][keyPressed-97]-dices[diceNum]<0) // the block was before the 0th position { if(block[52+piece[turn+2][keyPressed-97]-dices[diceNum]]==1) // this logic was created with the help of pen and paper { block[52+piece[turn+2][keyPressed-97]-dices[diceNum]]=0; score[turn+2]+=2; } } else if(piece[turn+2][keyPressed-97]-dices[diceNum]>=0) // the block was after 0th position(i.e. yellow's starting square) { if(block[piece[turn+2][keyPressed-97]-dices[diceNum]]==1) { block[piece[turn+2][keyPressed-97]-dices[diceNum]]=0; score[turn+2]+=2; } } } int checkForBlockTeamPlus(int diceNum) // checks whether a block exists in the path of the piece { // returns 0 if the pathway is open. returns 1 if the pathway is closed by a block int blockCounter=0; if(turn+2<=1) { if(piece[turn+2][keyPressed-97]+dices[diceNum]<52) { for(int i=piece[turn+2][keyPressed-97]+1;i<=(piece[turn+2][keyPressed-97]+dices[diceNum]);i++) { if(block[i]==1 && colorAtBlock(i)!=turn+2 && colorAtBlock(i)!=(turn+2+2)) // colorAtBlock(i)!=turn allows only the same color to cross the block { blockCounter++; } } } else if((piece[turn+2][keyPressed-97]+dices[diceNum])>=52 && (piece[turn+2][keyPressed-97]+dices[diceNum])<100) { for(int i=piece[turn+2][keyPressed-97]+1;i<=(piece[turn+2][keyPressed-97]+dices[diceNum]);i++) { if(i<52) { if(block[i]==1 && colorAtBlock(i)!=turn+2 && colorAtBlock(i)!=(turn+2+2)) // colorAtBlock(i)!=turn+2 allows only the same color to cross the block { blockCounter++; } } if(i>=52) { if(block[i-52]==1 && colorAtBlock(i-52)!=turn+2 && colorAtBlock(i-52)!=(turn+2+2)) // colorAtBlock(i-52)!=turn+2 allows only the same color to cross the block { blockCounter++; } } } // this function started creating issues when pieces crossed yellow's home cirlcle. so all this logic was created to remove those issues } } if(turn+2>=2) { if(piece[turn+2][keyPressed-97]+dices[diceNum]<52) { for(int i=piece[turn+2][keyPressed-97]+1;i<=(piece[turn+2][keyPressed-97]+dices[diceNum]);i++) { if(block[i]==1 && colorAtBlock(i)!=turn+2 && colorAtBlock(i)!=(turn+2-2)) // colorAtBlock(i)!=turn+2 allows only the same color to cross the block { blockCounter++; } } } else if((piece[turn+2][keyPressed-97]+dices[diceNum])>=52 && (piece[turn+2][keyPressed-97]+dices[diceNum])<100) { for(int i=piece[turn+2][keyPressed-97]+1;i<=(piece[turn+2][keyPressed-97]+dices[diceNum]);i++) { if(i<52) { if(block[i]==1 && colorAtBlock(i)!=(turn+2-2) && colorAtBlock(i)!=(turn+2-2)) // colorAtBlock(i)!=turn+2 allows only the same color to cross the block { blockCounter++; } } if(i>=52) { if(block[i-52]==1 && colorAtBlock(i-52)!=(turn+2-2) && colorAtBlock(i-52)!=(turn+2-2)) // colorAtBlock(i-52)!=turn+2 allows only the same color to cross the block { blockCounter++; } } } // this function started creating issues when pieces crossed yellow's home cirlcle. so all this logic was created to remove those issues } } if(blockCounter>0) { return 1; } else { return 0; } } int checkForHomeTriangle_SixTeamPlus() //this function puts the piece in home triangle ONLY when the piece is out of the home column on the first block before it. As then the piece needs a 6 to move to home triangle { if(turn+2 == 0 && killCount[turn+2]>0 && piece[turn+2][keyPressed-97]==50 ) { return 1; } if(turn+2 == 1 && killCount[turn+2]>0 && piece[turn+2][keyPressed-97]==11 ) { return 1; } if(turn+2 == 2 && killCount[turn+2]>0 && piece[turn+2][keyPressed-97]==24 ) { return 1; } if(turn+2 == 3 && killCount[turn+2]>0 && piece[turn+2][keyPressed-97]==37 ) { return 1; } return 0; // did not move to home triangle( actually it will move along the board agiain) } void limitHomeThrowTeamPlus(int diceNum) // a piece enters home triangle only on exact throw { if(turn+2 ==0) { if(piece[turn+2][keyPressed-97]+dices[diceNum]==105) { piece[turn+2][keyPressed-97]=-2; score[turn+2]+=dices[diceNum]; turn--; // gives an extra turn } else if(piece[turn+2][keyPressed-97]+dices[diceNum]<105) { piece[turn+2][keyPressed-97]+=dices[diceNum]; score[turn+2]+=dices[diceNum]; } else { // do nothing } } else if(turn+2 == 1) { if(piece[turn+2][keyPressed-97]+dices[diceNum]==111) { piece[turn+2][keyPressed-97]=-2; score[turn+2]+=dices[diceNum]; turn--; // gives an extra turn } else if(piece[turn+2][keyPressed-97]+dices[diceNum]<111) { piece[turn+2][keyPressed-97]+=dices[diceNum]; score[turn+2]+=dices[diceNum]; } else { // do nothing } } else if(turn+2 == 2) { if(piece[turn+2][keyPressed-97]+dices[diceNum]==117) { piece[turn+2][keyPressed-97]=-2; score[turn+2]+=dices[diceNum]; turn--; // gives an extra turn } else if(piece[turn+2][keyPressed-97]+dices[diceNum]<117) { piece[turn+2][keyPressed-97]+=dices[diceNum]; score[turn+2]+=dices[diceNum]; } else { // do nothing } } else if(turn+2 == 3) { if(piece[turn+2][keyPressed-97]+dices[diceNum]==123) { piece[turn+2][keyPressed-97]=-2; score[turn+2]+=dices[diceNum]; turn--; // gives an extra turn } else if(piece[turn+2][keyPressed-97]+dices[diceNum]<123) { piece[turn+2][keyPressed-97]+=dices[diceNum]; score[turn+2]+=dices[diceNum]; } else { // do nothing } } } //////////////////////////////////////////////// // FOR TURN-2 (This means when 2nd and 3rd players gives theur turn to 0th and 1st players respectively) // therefore all these functions are named TeamMinus int checkForHomeColumnTeamMinus(int diceNum) //check if the piece is eligible and also can move to home triangle { if(turn-2==0 && killCount[turn-2]>0) // if kills are zero then the piece will move along the board instead of going in the home column { if(piece[turn-2][keyPressed-97]+dices[diceNum]>50) { piece[turn-2][keyPressed-97]+=49+dices[diceNum]; // this logic was created with the help of pen and paper return 1; } } else if(turn-2==1 && killCount[turn-2]>0) { if(piece[turn-2][keyPressed-97]+dices[diceNum]>11 && piece[turn-2][keyPressed-97]<=11) { piece[turn-2][keyPressed-97]+=94+dices[diceNum]; // this logic was created with the help of pen and paper return 1; } } else if(turn-2==2 && killCount[turn-2]>0) { if(piece[turn-2][keyPressed-97]+dices[diceNum]>24 && piece[turn-2][keyPressed-97]<=24) { piece[turn-2][keyPressed-97]+=87+dices[diceNum]; // this logic was created with the help of pen and paper return 1; } } else if(turn-2==3 && killCount[turn-2]>0) { if(piece[turn-2][keyPressed-97]+dices[diceNum]>37 && piece[turn-2][keyPressed-97]<=37) { piece[turn-2][keyPressed-97]+=80+dices[diceNum]; // this logic was created with the help of pen and paper return 1; } } else { return 0; } } void checkForKillTeamMinus() // check if a piece is killing another piece { //piece[turn][keyPressed-97] for(int i=0;i<4;i++) // colours { if(turn-2<=1) { if(turn-2!=i && i!=turn-2+2) // not the same colors or same teams { for(int j=0;j<4;j++) // pieces { if((piece[turn-2][keyPressed-97]==piece[i][j]) && piece[i][j]!=-1 && piece[i][j]!=-2 && piece[i][j]!=0 && piece[i][j]!=8 && piece[i][j]!=13 && piece[i][j]!=21 && piece[i][j]!=26 && piece[i][j]!=34 && piece[i][j]!=39 && piece[i][j]!=47 && piece[i][j]<52) // all these are safe spots where a piece cannot be removed {// one piece kills another killCount[turn-2]++; score[turn-2]+=10; piece[i][j]=-1; // move back to the starting circle turn--; // gives the player another turn } } } } if(turn-2>=2) { if(turn-2!=i && i!=turn-2-2) // not the same colors or same teams { for(int j=0;j<4;j++) // pieces { if((piece[turn-2][keyPressed-97]==piece[i][j]) && piece[i][j]!=-1 && piece[i][j]!=-2 && piece[i][j]!=0 && piece[i][j]!=8 && piece[i][j]!=13 && piece[i][j]!=21 && piece[i][j]!=26 && piece[i][j]!=34 && piece[i][j]!=39 && piece[i][j]!=47 && piece[i][j]<52) // all these are safe spots where a piece cannot be removed {// one piece kills another killCount[turn-2]++; score[turn-2]+=10; piece[i][j]=-1; // move back to the starting circle turn--; // gives the player another turn } } } } } } void moveFromBlockTeamMinus(int diceNum) // if a piece moves from the block, this function breaks the block { if(piece[turn-2][keyPressed-97]-dices[diceNum]<0) // the block was before the 0th position { if(block[52+piece[turn-2][keyPressed-97]-dices[diceNum]]==1) // this logic was created with the help of pen and paper { block[52+piece[turn-2][keyPressed-97]-dices[diceNum]]=0; score[turn-2]+=2; } } else if(piece[turn-2][keyPressed-97]-dices[diceNum]>=0) // the block was after 0th position(i.e. yellow's starting square) { if(block[piece[turn-2][keyPressed-97]-dices[diceNum]]==1) { block[piece[turn-2][keyPressed-97]-dices[diceNum]]=0; score[turn-2]+=2; } } } int checkForBlockTeamMinus(int diceNum) // checks whether a block exists in the path of the piece { // returns 0 if the pathway is open. returns 1 if the pathway is closed by a block int blockCounter=0; if(turn-2<=1) { if(piece[turn-2][keyPressed-97]+dices[diceNum]<52) { for(int i=piece[turn-2][keyPressed-97]+1;i<=(piece[turn-2][keyPressed-97]+dices[diceNum]);i++) { if(block[i]==1 && colorAtBlock(i)!=turn-2 && colorAtBlock(i)!=(turn-2+2)) // colorAtBlock(i)!=turn allows only the same color to cross the block { blockCounter++; } } } else if((piece[turn-2][keyPressed-97]+dices[diceNum])>=52 && (piece[turn-2][keyPressed-97]+dices[diceNum])<100) { for(int i=piece[turn-2][keyPressed-97]+1;i<=(piece[turn-2][keyPressed-97]+dices[diceNum]);i++) { if(i<52) { if(block[i]==1 && colorAtBlock(i)!=turn-2 && colorAtBlock(i)!=(turn-2+2)) // colorAtBlock(i)!=turn-2 allows only the same color to cross the block { blockCounter++; } } if(i>=52) { if(block[i-52]==1 && colorAtBlock(i-52)!=turn-2 && colorAtBlock(i-52)!=(turn-2+2)) // colorAtBlock(i-52)!=turn-2 allows only the same color to cross the block { blockCounter++; } } } // this function started creating issues when pieces crossed yellow's home cirlcle. so all this logic was created to remove those issues } } if(turn-2>=2) { if(piece[turn-2][keyPressed-97]+dices[diceNum]<52) { for(int i=piece[turn-2][keyPressed-97]+1;i<=(piece[turn-2][keyPressed-97]+dices[diceNum]);i++) { if(block[i]==1 && colorAtBlock(i)!=turn-2 && colorAtBlock(i)!=(turn-2-2)) // colorAtBlock(i)!=turn-2 allows only the same color to cross the block { blockCounter++; } } } else if((piece[turn-2][keyPressed-97]+dices[diceNum])>=52 && (piece[turn-2][keyPressed-97]+dices[diceNum])<100) { for(int i=piece[turn-2][keyPressed-97]+1;i<=(piece[turn-2][keyPressed-97]+dices[diceNum]);i++) { if(i<52) { if(block[i]==1 && colorAtBlock(i)!=(turn-2-2) && colorAtBlock(i)!=(turn-2-2)) // colorAtBlock(i)!=turn-2 allows only the same color to cross the block { blockCounter++; } } if(i>=52) { if(block[i-52]==1 && colorAtBlock(i-52)!=(turn-2-2) && colorAtBlock(i-52)!=(turn-2-2)) // colorAtBlock(i-52)!=turn-2 allows only the same color to cross the block { blockCounter++; } } } // this function started creating issues when pieces crossed yellow's home cirlcle. so all this logic was created to remove those issues } } if(blockCounter>0) { return 1; } else { return 0; } } int checkForHomeTriangle_SixTeamMinus() //this function puts the piece in home triangle ONLY when the piece is out of the home column on the first block before it. As then the piece needs a 6 to move to home triangle { if(turn-2 == 0 && killCount[turn-2]>0 && piece[turn-2][keyPressed-97]==50 ) { return 1; } if(turn-2 == 1 && killCount[turn-2]>0 && piece[turn-2][keyPressed-97]==11 ) { return 1; } if(turn-2 == 2 && killCount[turn-2]>0 && piece[turn-2][keyPressed-97]==24 ) { return 1; } if(turn-2 == 3 && killCount[turn-2]>0 && piece[turn-2][keyPressed-97]==37 ) { return 1; } return 0; // did not move to home triangle( actually it will move along the board agiain) } void limitHomeThrowTeamMinus(int diceNum) // a piece enters home triangle only on exact throw { if(turn-2 ==0) { if(piece[turn-2][keyPressed-97]+dices[diceNum]==105) { piece[turn-2][keyPressed-97]=-2; score[turn-2]+=dices[diceNum]; turn--; // gives an extra turn } else if(piece[turn-2][keyPressed-97]+dices[diceNum]<105) { piece[turn-2][keyPressed-97]+=dices[diceNum]; score[turn-2]+=dices[diceNum]; } else { // do nothing } } else if(turn-2 == 1) { if(piece[turn-2][keyPressed-97]+dices[diceNum]==111) { piece[turn-2][keyPressed-97]=-2; score[turn-2]+=dices[diceNum]; turn--; // gives an extra turn } else if(piece[turn-2][keyPressed-97]+dices[diceNum]<111) { piece[turn-2][keyPressed-97]+=dices[diceNum]; score[turn-2]+=dices[diceNum]; } else { // do nothing } } else if(turn-2 == 2) { if(piece[turn-2][keyPressed-97]+dices[diceNum]==117) { piece[turn-2][keyPressed-97]=-2; score[turn-2]+=dices[diceNum]; turn--; // gives an extra turn } else if(piece[turn-2][keyPressed-97]+dices[diceNum]<117) { piece[turn-2][keyPressed-97]+=dices[diceNum]; score[turn-2]+=dices[diceNum]; } else { // do nothing } } else if(turn-2 == 3) { if(piece[turn-2][keyPressed-97]+dices[diceNum]==123) { piece[turn-2][keyPressed-97]=-2; score[turn-2]+=dices[diceNum]; turn--; // gives an extra turn } else if(piece[turn-2][keyPressed-97]+dices[diceNum]<123) { piece[turn-2][keyPressed-97]+=dices[diceNum]; score[turn-2]+=dices[diceNum]; } else { // do nothing } } } ///////////////////////////////////////////////// // End of teamMode functions void GameDisplay() { // main game display function. All other functions are called through it glClearColor(255.0/255/*Red Component*/, 255.0/255 /*Green Component*/, 254.0/255/*Blue Component*/, 1.0 /*Alpha component*/); // background colour glClear (GL_COLOR_BUFFER_BIT); //Update the colors if(window!=1) { DrawStringSmall( 1055, 20, "Press Esc to return to main menu", colors[BLACK]); } else { DrawStringSmall( 1095, 20, "Press Esc to exit", colors[BLACK]); } if(window==1) // all window functions are linked to this GameDisplay function for seperate displays { window1(); } if(window==2) { window2(); } if(window==3) { window3(); } if(window==13) { window13(); } if(window==12) { window12(); } if(window==11) { window11(); } if(window==4) { window4(); } if(window==5) { window5(); } if (window==6) { window6(); } if(window==7) { window7(); } if(window==8) { if(teamMode==0) // this runs when there is no teammode { setStatus(); // sets status of the 4 colors drawBoard(); // draws the wooden board drawPiecesStart();// draws pieces in starting circle drawPiecesHomeTriangle(); // draws pieces only in home triangle writeTurn(); // writes whos turn it is in the right column writeNames(); // writes names of the players playing the game blocksFormed(); // draws any block if they are formed homeColumnStatus(); // draws status of home columns DrawCircle(0, 0, 14, colors[MISTY_ROSE]); // to cover up when home-triangle pieces jump to corner(co-ordinates for 105,111,117 and 123 are (0,0)) if (spacePressed==1) // dice got rolled { static int sixCount=0; static int x=0; //string diceNum; // to display the number of dice on screen using DrawString function //diceNum = dice + 48; // e.g if dice gives 2, then int of 2 is ASCII 2+48 which is '2' in string drawDice(dice); if(dice==6) { sixCount++; dices[x]=6; x++; if(sixCount==3) { for(int z=0;z<3;z++) { dices[z]=0; } x=0; sixCount=0; turn++; // turn gets skipped on 3 consecutive sixes } spacePressed=0; } else { if(sixCount==0) // this if statement will only run when a person gets a single roll meaning only a single numeric less than 6 { static int y=0; dices[y]=dice; //dices[0] as y=0 int count=0; for(int i=0;i<4;i++) { if(piece[turn][i]==-1 || piece[turn][i]==-2) { count++; } } if(count==4) { spacePressed=0; // turn gets skipped if all pieces are in starting circle turn++; for(int z=0;z<3;z++) { dices[z]=0; // assigning all dices back to zero } } else { DrawString( 1055, 330, "Select piece to move", colors[BLACK]); } if(keyPressed==0) { // do nothing } else if(piece[turn][keyPressed-97]!=-1 && piece[turn][keyPressed-97]!=-2 && checkForBlock(y)==0) //&&keyPressed !=0 { if(piece[turn][keyPressed-97]>=100) // it is already in home column { limitHomeThrow(y); } else if(checkForHomeColumn(y)==1) { //the function will return 1 if the piece is eligible and is going to home column // it will return 0 otherwise score[turn]+=dices[y]; score[turn]+=15; } else if(piece[turn][keyPressed-97]+dices[y]>51) // our MAIN board is being ranged from 0-51 { piece[turn][keyPressed-97]=piece[turn][keyPressed-97]+dices[y]-52; // this logic was created with help of pen and paper for example subtracting 52 from 52 will give 0 score[turn]+=dices[y]; } // it will start it back again from position[0][0] else { piece[turn][keyPressed-97]+=dices[y]; score[turn]+=dices[y]; //MOVEMENT DONE HERE } //checkForHomeColumn(y); moveFromBlock(y); checkForKill(); for(int z=0;z<3;z++) { dices[z]=0; // assigning all dices back to zero } spacePressed=0; turn++; y=0; } else if(piece[turn][keyPressed-97]==-1 && count!=4) // the key user pressed was not moveable { //DrawString( 900, 200, "AGAIN!", colors[BLACK]); spacePressed=1; // turn != ++ } }// end if statement of (if there were no sixes) else // this statement will run when there are sixes too to be moved { dices[x]=dice; static int y=0; DrawString( 1055, 330, "Select piece to move", colors[BLACK]); if(dices[y]==0) // assuming if the 2nd roll was !=6 so the 3rd roll was 0. so it should move to the next turn { turn++; sixCount=0; x=0; for(int z=0;z<3;z++) { dices[z]=0; // assigning all dices back to zero } spacePressed=0; y=0; } if(keyPressed==0) { // do nothing } else if(dices[y]==6 && piece[turn][keyPressed-97]!=-2 && checkForBlock(y)==0)// && some key is pressed { if(piece[turn][keyPressed-97]==-1) // 97 is the ASCII for 'a', so if a user enters a, it directs towards 0th piece i.e. 'a' piece { if(turn==0) //movement also done here but on safe spots { piece[turn][keyPressed-97]=0;//starting position of yellow } else if(turn==1) { piece[turn][keyPressed-97]=13; // starting position of blue } else if(turn==2) { piece[turn][keyPressed-97]=26;//starting position of red } else { piece[turn][keyPressed-97]=39;//starting position of green } //turn++; y++; } else // piece is on the board squares { if(checkForHomeTriangle_Six()==1) { // the function will return true when the piece is eligible and is going to home triangle // otherwise it will return false piece[turn][keyPressed-97]=-2; score[turn]+=dices[y]; score[turn]+=15; // because actually, the piece crossed the home column to get into home triangle } else if(checkForHomeColumn(y)==1) { //the function will return 1 if the piece is eligible and is going to home column // it will return 0 otherwise score[turn]+=15; score[turn]+=dices[y]; } else if(piece[turn][keyPressed-97]+dices[y]>51) // our board is being ranged from 0-51 { piece[turn][keyPressed-97]=piece[turn][keyPressed-97]+dices[y]-52; // this logic was created with help of pen and paper score[turn]+=dices[y]; } // it will start it back again from position[0][0] else { piece[turn][keyPressed-97]+=dices[y]; //MOVEMENT DONE HERE score[turn]+=dices[y]; } //checkForHomeColumn(y); moveFromBlock(y); checkForKill(); //turn++; y++; } } else if(dices[y]!=6 && dices[y]!=0 && piece[turn][keyPressed-97]!=-1 && piece[turn][keyPressed-97]!=-2 && checkForBlock(y)==0) // if dices[y]!=6 (1-5) && some key is pressed { if(piece[turn][keyPressed-97]>=100) // it is already in home column { limitHomeThrow(y); } else if(checkForHomeColumn(y)==1) { //the function will return 1 if the piece is eligible and is going to home column // it will return 0 otherwise score[turn]+=15; score[turn]+=dices[y]; } else if(piece[turn][keyPressed-97]+dices[y]>51) // our board is being ranged from 0-51 { piece[turn][keyPressed-97]=piece[turn][keyPressed-97]+dices[y]-52; // this logic was created with help of pen and paper score[turn]+=dices[y]; } // it will start it back again from position[0][0] else { piece[turn][keyPressed-97]+=dices[y]; //MOVEMENT DONE HERE score[turn]+=dices[y]; } //checkForHomeColumn(y); moveFromBlock(y); checkForKill(); turn++; sixCount=0; x=0; for(int z=0;z<3;z++) { dices[z]=0; // assigning all dices back to zero } spacePressed=0; y=0; } } } /*if(turn == 4) { turn=0; }*/ checkForWinners(); // checks if someone has won and makes their status 1 if they have won int count=0; for(int i=0;i<4;i++) { if(status[i]==1 || status[i]==-1) { count++; } } if(count==3) // only 1 player has been left { updateLeaderboard(); window=9; // end game window } /* test data piece[2][0]=-2; piece[2][1]=-2; piece[2][2]=-2; piece[2][3]=-2; */ nextTurn(); /*if(turn==1) { turn++; } if(turn==3) { turn=0; }*/ keyPressed=0; } } if(teamMode==1) // this runs when there is teammode { setStatus(); // sets status of the 4 colors to zero drawBoard(); // draws the wooden board drawPiecesStart();// draws pieces in starting circle drawPiecesHomeTriangle(); // draws pieces only in home triangle writeTurn(); // writes whos turn it is in the right column writeNames(); // writes names of the players playing the game blocksFormed(); // draws any block if they are formed homeColumnStatus(); // draws status of home columns DrawCircle(0, 0, 14, colors[MISTY_ROSE]); // to cover up when home-triangle pieces jump to corner(co-ordinates for 105,111,117 and 123 are (0,0)) if (spacePressed==1) // dice got rolled { static int sixCount=0; static int x=0; drawDice(dice); if(status[turn]==0) // player is in play { if(dice==6) { sixCount++; dices[x]=6; x++; if(sixCount==3) { for(int z=0;z<3;z++) { dices[z]=0; } x=0; sixCount=0; turn++; // turn gets skipped on 3 consecutive sixes } spacePressed=0; } else { if(sixCount==0) // this if statement will only run when a person gets a single roll meaning only a single numeric less than 6 { static int y=0; dices[y]=dice; //dices[0] as y=0 int count=0; for(int i=0;i<4;i++) { if(piece[turn][i]==-1 || piece[turn][i]==-2) { count++; } } if(count==4) { spacePressed=0; // turn gets skipped if all pieces are in starting circle turn++; for(int z=0;z<3;z++) { dices[z]=0; // assigning all dices back to zero } } else { DrawString( 1055, 330, "Select piece to move", colors[BLACK]); } if(keyPressed==0) { // do nothing } else if(piece[turn][keyPressed-97]!=-1 && piece[turn][keyPressed-97]!=-2 && checkForBlock(y)==0) //&&keyPressed !=0 { if(piece[turn][keyPressed-97]>=100) // it is already in home column { limitHomeThrow(y); } else if(checkForHomeColumn(y)==1) { //the function will return 1 if the piece is eligible and is going to home column // it will return 0 otherwise score[turn]+=dices[y]; score[turn]+=15; } else if(piece[turn][keyPressed-97]+dices[y]>51) // our MAIN board is being ranged from 0-51 { piece[turn][keyPressed-97]=piece[turn][keyPressed-97]+dices[y]-52; // this logic was created with help of pen and paper for example subtracting 52 from 52 will give 0 score[turn]+=dices[y]; } // it will start it back again from position[0][0] else { piece[turn][keyPressed-97]+=dices[y]; score[turn]+=dices[y]; //MOVEMENT DONE HERE } //checkForHomeColumn(y); moveFromBlock(y); checkForKill(); for(int z=0;z<3;z++) { dices[z]=0; // assigning all dices back to zero } spacePressed=0; turn++; y=0; } else if(piece[turn][keyPressed-97]==-1 && count!=4) // the key user pressed was not moveable { //DrawString( 900, 200, "AGAIN!", colors[BLACK]); spacePressed=1; // turn != ++ } }// end if statement of (if there were no sixes) else // this statement will run when there are sixes too to be moved { dices[x]=dice; static int y=0; DrawString( 1055, 330, "Select piece to move", colors[BLACK]); if(dices[y]==0) // assuming if the 2nd roll was !=6 so the 3rd roll was 0. so it should move to the next turn { turn++; sixCount=0; x=0; for(int z=0;z<3;z++) { dices[z]=0; // assigning all dices back to zero } spacePressed=0; y=0; } if(keyPressed==0) { // do nothing } else if(dices[y]==6 && piece[turn][keyPressed-97]!=-2 && checkForBlock(y)==0)// && some key is pressed { if(piece[turn][keyPressed-97]==-1) // 97 is the ASCII for 'a', so if a user enters a, it directs towards 0th piece i.e. 'a' piece { if(turn==0) //movement also done here but on safe spots { piece[turn][keyPressed-97]=0;//starting position of yellow } else if(turn==1) { piece[turn][keyPressed-97]=13; // starting position of blue } else if(turn==2) { piece[turn][keyPressed-97]=26;//starting position of red } else { piece[turn][keyPressed-97]=39;//starting position of green } //turn++; y++; } else // piece is on the board squares { if(checkForHomeTriangle_Six()==1) { // the function will return true when the piece is eligible and is going to home triangle // otherwise it will return false piece[turn][keyPressed-97]=-2; score[turn]+=dices[y]; score[turn]+=15; // because actually, the piece crossed the home column to get into home triangle } else if(checkForHomeColumn(y)==1) { //the function will return 1 if the piece is eligible and is going to home column // it will return 0 otherwise score[turn]+=15; score[turn]+=dices[y]; } else if(piece[turn][keyPressed-97]+dices[y]>51) // our board is being ranged from 0-51 { piece[turn][keyPressed-97]=piece[turn][keyPressed-97]+dices[y]-52; // this logic was created with help of pen and paper score[turn]+=dices[y]; } // it will start it back again from position[0][0] else { piece[turn][keyPressed-97]+=dices[y]; //MOVEMENT DONE HERE score[turn]+=dices[y]; } //checkForHomeColumn(y); moveFromBlock(y); checkForKill(); //turn++; y++; } } else if(dices[y]!=6 && dices[y]!=0 && piece[turn][keyPressed-97]!=-1 && piece[turn][keyPressed-97]!=-2 && checkForBlock(y)==0) // if dices[y]!=6 (1-5) && some key is pressed { if(piece[turn][keyPressed-97]>=100) // it is already in home column { limitHomeThrow(y); } else if(checkForHomeColumn(y)==1) { //the function will return 1 if the piece is eligible and is going to home column // it will return 0 otherwise score[turn]+=15; score[turn]+=dices[y]; } else if(piece[turn][keyPressed-97]+dices[y]>51) // our board is being ranged from 0-51 { piece[turn][keyPressed-97]=piece[turn][keyPressed-97]+dices[y]-52; // this logic was created with help of pen and paper score[turn]+=dices[y]; } // it will start it back again from position[0][0] else { piece[turn][keyPressed-97]+=dices[y]; //MOVEMENT DONE HERE score[turn]+=dices[y]; } //checkForHomeColumn(y); moveFromBlock(y); checkForKill(); turn++; sixCount=0; x=0; for(int z=0;z<3;z++) { dices[z]=0; // assigning all dices back to zero } spacePressed=0; y=0; } } } } else if(status[turn]==1) // player has all 4 pieces in home triangle { if(partnersRoll[turn]==0) { if(dice==6) { partnersRoll[turn]=1; dice=0; spacePressed=0; } else { //partnersRoll[turn] will remain zero dice=0; spacePressed=0; } turn++; } else // if partnersRoll[turn]==1 { if(turn<=1) { if(dice==6) { sixCount++; dices[x]=6; x++; if(sixCount==3) { for(int z=0;z<3;z++) { dices[z]=0; } x=0; sixCount=0; turn++; // turn gets skipped on 3 consecutive sixes } spacePressed=0; } else { if(sixCount==0) // this if statement will only run when a person gets a single roll meaning only a single numeric less than 6 { static int y=0; dices[y]=dice; //dices[0] as y=0 int count=0; for(int i=0;i<4;i++) { if(piece[turn+2][i]==-1 || piece[turn+2][i]==-2) { count++; } } if(count==4) { spacePressed=0; // turn gets skipped if all pieces are in starting circle turn++; for(int z=0;z<3;z++) { dices[z]=0; // assigning all dices back to zero } } else { DrawString( 1055, 330, "Select piece to move", colors[BLACK]); } if(keyPressed==0) { // do nothing } else if(piece[turn+2][keyPressed-97]!=-1 && piece[turn+2][keyPressed-97]!=-2 && checkForBlockTeamPlus(y)==0) //&&keyPressed !=0 { if(piece[turn+2][keyPressed-97]>=100) // it is already in home column { limitHomeThrowTeamPlus(y); } else if(checkForHomeColumnTeamPlus(y)==1) { //the function will return 1 if the piece is eligible and is going to home column // it will return 0 otherwise score[turn+2]+=dices[y]; score[turn+2]+=15; } else if(piece[turn+2][keyPressed-97]+dices[y]>51) // our MAIN board is being ranged from 0-51 { piece[turn+2][keyPressed-97]=piece[turn+2][keyPressed-97]+dices[y]-52; // this logic was created with help of pen and paper for example subtracting 52 from 52 will give 0 score[turn+2]+=dices[y]; } // it will start it back again from position[0][0] else { piece[turn+2][keyPressed-97]+=dices[y]; score[turn+2]+=dices[y]; //MOVEMENT DONE HERE } //checkForHomeColumn(y); moveFromBlockTeamPlus(y); checkForKillTeamPlus(); for(int z=0;z<3;z++) { dices[z]=0; // assigning all dices back to zero } spacePressed=0; turn++; y=0; } else if(piece[turn+2][keyPressed-97]==-1 && count!=4) // the key user pressed was not moveable { //DrawString( 900, 200, "AGAIN!", colors[BLACK]); spacePressed=1; // turn != ++ } }// end if statement of (if there were no sixes) else // this statement will run when there are sixes too to be moved { dices[x]=dice; static int y=0; DrawString( 1055, 330, "Select piece to move", colors[BLACK]); if(dices[y]==0) // assuming if the 2nd roll was !=6 so the 3rd roll was 0. so it should move to the next turn { turn++; sixCount=0; x=0; for(int z=0;z<3;z++) { dices[z]=0; // assigning all dices back to zero } spacePressed=0; y=0; } if(keyPressed==0) { // do nothing } else if(dices[y]==6 && piece[turn+2][keyPressed-97]!=-2 && checkForBlockTeamPlus(y)==0)// && some key is pressed { if(piece[turn+2][keyPressed-97]==-1) // 97 is the ASCII for 'a', so if a user enters a, it directs towards 0th piece i.e. 'a' piece { if(turn+2==0) //movement also done here but on safe spots { piece[turn+2][keyPressed-97]=0;//starting position of yellow } else if(turn+2==1) { piece[turn+2][keyPressed-97]=13; // starting position of blue } else if(turn+2==2) { piece[turn+2][keyPressed-97]=26;//starting position of red } else { piece[turn+2][keyPressed-97]=39;//starting position of green } //turn++; y++; } else // piece is on the board squares { if(checkForHomeTriangle_SixTeamPlus()==1) { // the function will return true when the piece is eligible and is going to home triangle // otherwise it will return false piece[turn+2][keyPressed-97]=-2; score[turn+2]+=dices[y]; score[turn+2]+=15; // because actually, the piece crossed the home column to get into home triangle } else if(checkForHomeColumnTeamPlus(y)==1) { //the function will return 1 if the piece is eligible and is going to home column // it will return 0 otherwise score[turn+2]+=15; score[turn+2]+=dices[y]; } else if(piece[turn+2][keyPressed-97]+dices[y]>51) // our board is being ranged from 0-51 { piece[turn+2][keyPressed-97]=piece[turn+2][keyPressed-97]+dices[y]-52; // this logic was created with help of pen and paper score[turn+2]+=dices[y]; } // it will start it back again from position[0][0] else { piece[turn+2][keyPressed-97]+=dices[y]; //MOVEMENT DONE HERE score[turn+2]+=dices[y]; } //checkForHomeColumn(y); moveFromBlockTeamPlus(y); checkForKillTeamPlus(); //turn++; y++; } } else if(dices[y]!=6 && dices[y]!=0 && piece[turn+2][keyPressed-97]!=-1 && piece[turn+2][keyPressed-97]!=-2 && checkForBlockTeamPlus(y)==0) // if dices[y]!=6 (1-5) && some key is pressed { if(piece[turn+2][keyPressed-97]>=100) // it is already in home column { limitHomeThrowTeamPlus(y); } else if(checkForHomeColumnTeamPlus(y)==1) { //the function will return 1 if the piece is eligible and is going to home column // it will return 0 otherwise score[turn+2]+=15; score[turn+2]+=dices[y]; } else if(piece[turn+2][keyPressed-97]+dices[y]>51) // our board is being ranged from 0-51 { piece[turn+2][keyPressed-97]=piece[turn+2][keyPressed-97]+dices[y]-52; // this logic was created with help of pen and paper score[turn+2]+=dices[y]; } // it will start it back again from position[0][0] else { piece[turn+2][keyPressed-97]+=dices[y]; //MOVEMENT DONE HERE score[turn+2]+=dices[y]; } //checkForHomeColumn(y); moveFromBlockTeamPlus(y); checkForKillTeamPlus(); turn++; sixCount=0; x=0; for(int z=0;z<3;z++) { dices[z]=0; // assigning all dices back to zero } spacePressed=0; y=0; } } } } if(turn>=2) { if(dice==6) { sixCount++; dices[x]=6; x++; if(sixCount==3) { for(int z=0;z<3;z++) { dices[z]=0; } x=0; sixCount=0; turn++; // turn gets skipped on 3 consecutive sixes } spacePressed=0; } else { if(sixCount==0) // this if statement will only run when a person gets a single roll meaning only a single numeric less than 6 { static int y=0; dices[y]=dice; //dices[0] as y=0 int count=0; for(int i=0;i<4;i++) { if(piece[turn-2][i]==-1 || piece[turn-2][i]==-2) { count++; } } if(count==4) { spacePressed=0; // turn gets skipped if all pieces are in starting circle turn++; for(int z=0;z<3;z++) { dices[z]=0; // assigning all dices back to zero } } else { DrawString( 1055, 330, "Select piece to move", colors[BLACK]); } if(keyPressed==0) { // do nothing } else if(piece[turn-2][keyPressed-97]!=-1 && piece[turn-2][keyPressed-97]!=-2 && checkForBlockTeamMinus(y)==0) //&&keyPressed !=0 { if(piece[turn-2][keyPressed-97]>=100) // it is already in home column { limitHomeThrowTeamMinus(y); } else if(checkForHomeColumnTeamMinus(y)==1) { //the function will return 1 if the piece is eligible and is going to home column // it will return 0 otherwise score[turn-2]+=dices[y]; score[turn-2]+=15; } else if(piece[turn-2][keyPressed-97]+dices[y]>51) // our MAIN board is being ranged from 0-51 { piece[turn-2][keyPressed-97]=piece[turn-2][keyPressed-97]+dices[y]-52; // this logic was created with help of pen and paper for example subtracting 52 from 52 will give 0 score[turn-2]+=dices[y]; } // it will start it back again from position[0][0] else { piece[turn-2][keyPressed-97]+=dices[y]; score[turn-2]+=dices[y]; //MOVEMENT DONE HERE } //checkForHomeColumn(y); moveFromBlockTeamMinus(y); checkForKillTeamMinus(); for(int z=0;z<3;z++) { dices[z]=0; // assigning all dices back to zero } spacePressed=0; turn++; y=0; } else if(piece[turn-2][keyPressed-97]==-1 && count!=4) // the key user pressed was not moveable { //DrawString( 900, 200, "AGAIN!", colors[BLACK]); spacePressed=1; // turn != ++ } }// end if statement of (if there were no sixes) else // this statement will run when there are sixes too to be moved { dices[x]=dice; static int y=0; DrawString( 1055, 330, "Select piece to move", colors[BLACK]); if(dices[y]==0) // assuming if the 2nd roll was !=6 so the 3rd roll was 0. so it should move to the next turn { turn++; sixCount=0; x=0; for(int z=0;z<3;z++) { dices[z]=0; // assigning all dices back to zero } spacePressed=0; y=0; } if(keyPressed==0) { // do nothing } else if(dices[y]==6 && piece[turn-2][keyPressed-97]!=-2 && checkForBlockTeamMinus(y)==0)// && some key is pressed { if(piece[turn-2][keyPressed-97]==-1) // 97 is the ASCII for 'a', so if a user enters a, it directs towards 0th piece i.e. 'a' piece { if(turn-2==0) //movement also done here but on safe spots { piece[turn-2][keyPressed-97]=0;//starting position of yellow } else if(turn-2==1) { piece[turn-2][keyPressed-97]=13; // starting position of blue } else if(turn-2==2) { piece[turn-2][keyPressed-97]=26;//starting position of red } else { piece[turn-2][keyPressed-97]=39;//starting position of green } //turn++; y++; } else // piece is on the board squares { if(checkForHomeTriangle_SixTeamMinus()==1) { // the function will return true when the piece is eligible and is going to home triangle // otherwise it will return false piece[turn-2][keyPressed-97]=-2; score[turn-2]+=dices[y]; score[turn-2]+=15; // because actually, the piece crossed the home column to get into home triangle } else if(checkForHomeColumnTeamMinus(y)==1) { //the function will return 1 if the piece is eligible and is going to home column // it will return 0 otherwise score[turn-2]+=15; score[turn-2]+=dices[y]; } else if(piece[turn-2][keyPressed-97]+dices[y]>51) // our board is being ranged from 0-51 { piece[turn-2][keyPressed-97]=piece[turn-2][keyPressed-97]+dices[y]-52; // this logic was created with help of pen and paper score[turn-2]+=dices[y]; } // it will start it back again from position[0][0] else { piece[turn-2][keyPressed-97]+=dices[y]; //MOVEMENT DONE HERE score[turn-2]+=dices[y]; } //checkForHomeColumn(y); moveFromBlockTeamMinus(y); checkForKillTeamMinus(); //turn++; y++; } } else if(dices[y]!=6 && dices[y]!=0 && piece[turn-2][keyPressed-97]!=-1 && piece[turn-2][keyPressed-97]!=-2 && checkForBlockTeamMinus(y)==0) // if dices[y]!=6 (1-5) && some key is pressed { if(piece[turn-2][keyPressed-97]>=100) // it is already in home column { limitHomeThrowTeamMinus(y); } else if(checkForHomeColumnTeamMinus(y)==1) { //the function will return 1 if the piece is eligible and is going to home column // it will return 0 otherwise score[turn-2]+=15; score[turn-2]+=dices[y]; } else if(piece[turn-2][keyPressed-97]+dices[y]>51) // our board is being ranged from 0-51 { piece[turn-2][keyPressed-97]=piece[turn-2][keyPressed-97]+dices[y]-52; // this logic was created with help of pen and paper score[turn-2]+=dices[y]; } // it will start it back again from position[0][0] else { piece[turn-2][keyPressed-97]+=dices[y]; //MOVEMENT DONE HERE score[turn-2]+=dices[y]; } //checkForHomeColumn(y); moveFromBlockTeamMinus(y); checkForKillTeamMinus(); turn++; sixCount=0; x=0; for(int z=0;z<3;z++) { dices[z]=0; // assigning all dices back to zero } spacePressed=0; y=0; } } } } } } checkForWinners(); // checks if someone has won and makes their status 1 if they have won int count=0; if(status[0]==1 && status[2]==1) { count++; } if(status[1]==1 && status[3]==1) { count++; } if(count==1) // 1 team has won { updateLeaderboard(); window=9; // end game window } if(turn==4) // next turn function for team mode { turn=0; } // no nextTurn() because in teammode, all 4 players keep rolling the dice until the game ends keyPressed=0; } } } if(window==9) { window9(); } glutSwapBuffers(); // do not modify this line.. } void Timer(int m) { glutTimerFunc(1000.0, Timer, 0); glutPostRedisplay(); } int main(int argc, char*argv[]) { initializingPieceArray(); assignValuesToSquares(); int width = 1280, height = 720; // i have set my window in accordance with my laptop i.e. 720p InitRandomizer(); // seed the random number generator (util) glutInit(&argc, argv); // initialize the graphics library glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); // we will be using color display mode glutInitWindowPosition(50, 50); // set the initial position of our window glutInitWindowSize(width, height); // set the size of our window glutCreateWindow("LUDO"); // set the title of our game window SetCanvasSize(width, height); // set the number of pixels... glutDisplayFunc(GameDisplay); // tell library which function to call for drawing Canvas. glutKeyboardFunc(PrintableKeys); // tell library which function to call for printable ASCII characters glutTimerFunc(1000.0, Timer, 0); glutMainLoop(); return 1; } #endif /* Old code to run some tests int start(string names[]) { int players; cout<<"How many players want to play? "; for(;;) { cin>>players; if(players<=1 || players>4) { cout<<"Invalid input. Please try again: "; } else { break; } } cin.ignore(20,'\n'); cout<<"Please enter your respective names: "; for(int i=0;i<players;i++) { getline(cin,names[i]); } return players; } Old codes if(dice==6) { DrawString( 900, 400, "Select piece to move(a,b,c,d)", colors[BLACK]); if(keyPressed==0) { // do nothing } else { if(piece[turn][keyPressed-97]==-1) // 97 is the ASCII for 'a', so if a user enters a, it directs towards 0th piece i.e. 'a' piece { if(turn==0) { piece[turn][keyPressed-97]=0;//starting position of yellow } else if(turn==1) { piece[turn][keyPressed-97]=13; // starting position of blue } else if(turn==2) { piece[turn][keyPressed-97]=26;//starting position of red } else { piece[turn][keyPressed-97]=39;//starting position of green } turn++; } else { piece[turn][keyPressed-97]+=dice; turn++; } spacePressed=0; } } else // if dice == 1-5 { int count=0; for(int i=0;i<4;i++) { if(piece[turn][i]==-1) { count++; } } if(count==4) { spacePressed=0; turn++; } DrawString( 900, 400, "Select piece to\n move(a,b,c,d)", colors[BLACK]); if(keyPressed==0) { // do nothing } else if(piece[turn][keyPressed-97]!=-1) //&&keyPressed !=0 { piece[turn][keyPressed-97]+=dice; spacePressed=0; turn++; } else if(piece[turn][keyPressed-97]==-1 && count!=4) // the key user pressed was not moveable { DrawString( 900, 200, "AGAIN!", colors[BLACK]); spacePressed=1; // turn != ++ } }*/
44.36087
338
0.417457
2692fdc36bf8a34a62e4f1893e5404eb0ec811f3
70,302
cpp
C++
sdktools/debuggers/minidump/gen.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
sdktools/debuggers/minidump/gen.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
sdktools/debuggers/minidump/gen.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1999-2002 Microsoft Corporation Module Name: gen.c Abstract: Generic routines for minidump that work on both NT and Win9x. Author: Matthew D Hendel (math) 10-Sep-1999 Revision History: --*/ #include "pch.cpp" #include <limits.h> // // For FPO frames on x86 we access bytes outside of the ESP - StackBase range. // This variable determines how many extra bytes we need to add for this // case. // #define X86_STACK_FRAME_EXTRA_FPO_BYTES 4 #define REASONABLE_NB11_RECORD_SIZE (10 * KBYTE) #define REASONABLE_MISC_RECORD_SIZE (10 * KBYTE) class GenMiniDumpProviderCallbacks : public MiniDumpProviderCallbacks { public: GenMiniDumpProviderCallbacks( IN PMINIDUMP_STATE Dump, IN PINTERNAL_PROCESS Process ) { m_Dump = Dump; m_Process = Process; m_MemType = MEMBLOCK_OTHER; m_SaveMemType = MEMBLOCK_OTHER; } virtual HRESULT EnumMemory(ULONG64 Offset, ULONG Size) { return GenAddMemoryBlock(m_Dump, m_Process, m_MemType, Offset, Size); } void PushMemType(MEMBLOCK_TYPE Type) { m_SaveMemType = m_MemType; m_MemType = Type; } void PopMemType(void) { m_MemType = m_SaveMemType; } PMINIDUMP_STATE m_Dump; PINTERNAL_PROCESS m_Process; MEMBLOCK_TYPE m_MemType, m_SaveMemType; }; LPVOID AllocMemory( IN PMINIDUMP_STATE Dump, IN ULONG Size ) { LPVOID Mem = Dump->AllocProv->Alloc(Size); if (!Mem) { // Handle marking the no-memory state for all allocations. GenAccumulateStatus(Dump, MDSTATUS_OUT_OF_MEMORY); } return Mem; } VOID FreeMemory( IN PMINIDUMP_STATE Dump, IN LPVOID Memory ) { Dump->AllocProv->Free(Memory); } PVOID ReAllocMemory( IN PMINIDUMP_STATE Dump, IN LPVOID Memory, IN ULONG Size ) { LPVOID Mem = Dump->AllocProv->Realloc(Memory, Size); if (!Mem) { // Handle marking the no-memory state for all allocations. GenAccumulateStatus(Dump, MDSTATUS_OUT_OF_MEMORY); } return Mem; } void GenAccumulateStatus( IN PMINIDUMP_STATE Dump, IN ULONG Status ) { // This is a function to make it easy to debug failures // by setting a breakpoint here. Dump->AccumStatus |= Status; } VOID GenGetDefaultWriteFlags( IN PMINIDUMP_STATE Dump, OUT PULONG ModuleWriteFlags, OUT PULONG ThreadWriteFlags ) { *ModuleWriteFlags = ModuleWriteModule | ModuleWriteMiscRecord | ModuleWriteCvRecord; if (Dump->DumpType & MiniDumpWithDataSegs) { *ModuleWriteFlags |= ModuleWriteDataSeg; } *ThreadWriteFlags = ThreadWriteThread | ThreadWriteContext; if (!(Dump->DumpType & MiniDumpWithFullMemory)) { *ThreadWriteFlags |= ThreadWriteStack | ThreadWriteInstructionWindow; if (Dump->BackingStore) { *ThreadWriteFlags |= ThreadWriteBackingStore; } } if (Dump->DumpType & MiniDumpWithProcessThreadData) { *ThreadWriteFlags |= ThreadWriteThreadData; } } BOOL GenExecuteIncludeThreadCallback( IN PMINIDUMP_STATE Dump, IN ULONG ThreadId, OUT PULONG WriteFlags ) { BOOL Succ; MINIDUMP_CALLBACK_INPUT CallbackInput; MINIDUMP_CALLBACK_OUTPUT CallbackOutput; // Initialize the default write flags. GenGetDefaultWriteFlags(Dump, &CallbackOutput.ModuleWriteFlags, WriteFlags); // // If there are no callbacks to call, then we are done. // if ( Dump->CallbackRoutine == NULL ) { return TRUE; } CallbackInput.ProcessHandle = Dump->ProcessHandle; CallbackInput.ProcessId = Dump->ProcessId; CallbackInput.CallbackType = IncludeThreadCallback; CallbackInput.IncludeThread.ThreadId = ThreadId; CallbackOutput.ThreadWriteFlags = *WriteFlags; Succ = Dump->CallbackRoutine (Dump->CallbackParam, &CallbackInput, &CallbackOutput); // // If the callback returned FALSE, quit now. // if ( !Succ ) { return FALSE; } // Limit the flags that can be added. *WriteFlags &= CallbackOutput.ThreadWriteFlags; return TRUE; } BOOL GenExecuteIncludeModuleCallback( IN PMINIDUMP_STATE Dump, IN ULONG64 BaseOfImage, OUT PULONG WriteFlags ) { BOOL Succ; MINIDUMP_CALLBACK_INPUT CallbackInput; MINIDUMP_CALLBACK_OUTPUT CallbackOutput; // Initialize the default write flags. GenGetDefaultWriteFlags(Dump, WriteFlags, &CallbackOutput.ThreadWriteFlags); // // If there are no callbacks to call, then we are done. // if ( Dump->CallbackRoutine == NULL ) { return TRUE; } CallbackInput.ProcessHandle = Dump->ProcessHandle; CallbackInput.ProcessId = Dump->ProcessId; CallbackInput.CallbackType = IncludeModuleCallback; CallbackInput.IncludeModule.BaseOfImage = BaseOfImage; CallbackOutput.ModuleWriteFlags = *WriteFlags; Succ = Dump->CallbackRoutine (Dump->CallbackParam, &CallbackInput, &CallbackOutput); // // If the callback returned FALSE, quit now. // if ( !Succ ) { return FALSE; } // Limit the flags that can be added. *WriteFlags = (*WriteFlags | ModuleReferencedByMemory) & CallbackOutput.ModuleWriteFlags; return TRUE; } HRESULT GenGetDebugRecord( IN PMINIDUMP_STATE Dump, IN PVOID Base, IN ULONG MappedSize, IN ULONG DebugRecordType, IN ULONG DebugRecordMaxSize, OUT PVOID * DebugInfo, OUT ULONG * SizeOfDebugInfo ) { ULONG i; ULONG Size; ULONG NumberOfDebugDirectories; IMAGE_DEBUG_DIRECTORY UNALIGNED* DebugDirectories; Size = 0; // // Find the debug directory and copy the memory into the buffer. // Assumes the call to this function is wrapped in a try/except. // DebugDirectories = (IMAGE_DEBUG_DIRECTORY UNALIGNED *) GenImageDirectoryEntryToData (Base, FALSE, IMAGE_DIRECTORY_ENTRY_DEBUG, &Size); // // Check that we got a valid record. // if (DebugDirectories && ((Size % sizeof (IMAGE_DEBUG_DIRECTORY)) == 0) && (ULONG_PTR)DebugDirectories - (ULONG_PTR)Base + Size <= MappedSize) { NumberOfDebugDirectories = Size / sizeof (IMAGE_DEBUG_DIRECTORY); for (i = 0 ; i < NumberOfDebugDirectories; i++) { // // We should check if it's a NB10 or something record. // if ((DebugDirectories[ i ].Type == DebugRecordType) && (DebugDirectories[ i ].SizeOfData < DebugRecordMaxSize)) { if (DebugDirectories[i].PointerToRawData + DebugDirectories[i].SizeOfData > MappedSize) { return E_INVALIDARG; } Size = DebugDirectories [ i ].SizeOfData; PVOID NewInfo = AllocMemory(Dump, Size); if (!NewInfo) { return E_OUTOFMEMORY; } CopyMemory(NewInfo, ((PBYTE) Base) + DebugDirectories [ i ].PointerToRawData, Size); *DebugInfo = NewInfo; *SizeOfDebugInfo = Size; return S_OK; } } } return E_INVALIDARG; } HRESULT GenAddDataSection(IN PMINIDUMP_STATE Dump, IN PINTERNAL_PROCESS Process, IN PINTERNAL_MODULE Module, IN PIMAGE_SECTION_HEADER Section) { HRESULT Status = S_OK; if ( (Section->Characteristics & IMAGE_SCN_MEM_WRITE) && (Section->Characteristics & IMAGE_SCN_MEM_READ) && ( (Section->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) || (Section->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) )) { Status = GenAddMemoryBlock(Dump, Process, MEMBLOCK_DATA_SEG, Section->VirtualAddress + Module->BaseOfImage, Section->Misc.VirtualSize); #if 0 if (Status == S_OK) { printf ("Section: %8.8s Addr: %0I64x Size: %08x Raw Size: %08x\n", Section->Name, Section->VirtualAddress + Module->BaseOfImage, Section->Misc.VirtualSize, Section->SizeOfRawData); } #endif } return Status; } HRESULT GenGetDataContributors( IN PMINIDUMP_STATE Dump, IN OUT PINTERNAL_PROCESS Process, IN PINTERNAL_MODULE Module ) { ULONG i; PIMAGE_SECTION_HEADER NtSection; HRESULT Status; PVOID MappedBase; PIMAGE_NT_HEADERS NtHeaders; ULONG MappedSize; UCHAR HeaderBuffer[512]; PVOID HeaderBase; GenMiniDumpProviderCallbacks Callbacks(Dump, Process); // See if the provider wants to handle this. Callbacks.PushMemType(MEMBLOCK_DATA_SEG); if (Dump->SysProv-> EnumImageDataSections(Process->ProcessHandle, Module->FullPath, Module->BaseOfImage, &Callbacks) == S_OK) { // Provider did everything. return S_OK; } if ((Status = Dump->SysProv-> OpenMapping(Module->FullPath, &MappedSize, NULL, 0, &MappedBase)) != S_OK) { MappedBase = NULL; // If we can't map the file try and read the image // data from the process. if ((Status = Dump->SysProv-> ReadAllVirtual(Dump->ProcessHandle, Module->BaseOfImage, HeaderBuffer, sizeof(HeaderBuffer))) != S_OK) { GenAccumulateStatus(Dump, MDSTATUS_UNABLE_TO_READ_MEMORY); return Status; } HeaderBase = HeaderBuffer; } else { HeaderBase = MappedBase; } NtHeaders = GenImageNtHeader(HeaderBase, NULL); if (!NtHeaders) { Status = HRESULT_FROM_WIN32(ERROR_INVALID_DLL); } else { HRESULT OneStatus; Status = S_OK; NtSection = IMAGE_FIRST_SECTION ( NtHeaders ); if (MappedBase) { __try { for (i = 0; i < NtHeaders->FileHeader.NumberOfSections; i++) { if ((OneStatus = GenAddDataSection(Dump, Process, Module, &NtSection[i])) != S_OK) { Status = OneStatus; } } } __except(EXCEPTION_EXECUTE_HANDLER) { Status = HRESULT_FROM_NT(GetExceptionCode()); } } else { ULONG64 SectionOffs; IMAGE_SECTION_HEADER SectionBuffer; SectionOffs = Module->BaseOfImage + ((ULONG_PTR)NtSection - (ULONG_PTR)HeaderBase); for (i = 0; i < NtHeaders->FileHeader.NumberOfSections; i++) { if ((OneStatus = Dump->SysProv-> ReadAllVirtual(Dump->ProcessHandle, SectionOffs, &SectionBuffer, sizeof(SectionBuffer))) != S_OK) { Status = OneStatus; } else if ((OneStatus = GenAddDataSection(Dump, Process, Module, &SectionBuffer)) != S_OK) { Status = OneStatus; } SectionOffs += sizeof(SectionBuffer); } } } if (MappedBase) { Dump->SysProv->CloseMapping(MappedBase); } return Status; } HRESULT GenAllocateThreadObject( IN PMINIDUMP_STATE Dump, IN struct _INTERNAL_PROCESS* Process, IN ULONG ThreadId, IN ULONG WriteFlags, PINTERNAL_THREAD* ThreadRet ) /*++ Routine Description: Allocate and initialize an INTERNAL_THREAD structure. Return Values: S_OK on success. S_FALSE if the thread can't be opened. Errors on failure. --*/ { HRESULT Status; PINTERNAL_THREAD Thread; ULONG64 StackEnd; ULONG64 StackLimit; ULONG64 StoreLimit; ULONG64 StoreCurrent; Thread = (PINTERNAL_THREAD) AllocMemory ( Dump, sizeof (INTERNAL_THREAD) + Dump->ContextSize ); if (Thread == NULL) { return E_OUTOFMEMORY; } *ThreadRet = Thread; Thread->ThreadId = ThreadId; Status = Dump->SysProv-> OpenThread(THREAD_ALL_ACCESS, FALSE, Thread->ThreadId, &Thread->ThreadHandle); if (Status != S_OK) { // The thread may have exited before we got around // to trying to open it. If the open fails with // a not-found code return an alternate success to // indicate that it's not a critical failure. if (Status == HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER) || Status == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) || Status == HRESULT_FROM_NT(STATUS_INVALID_CID)) { Status = S_FALSE; } else if (SUCCEEDED(Status)) { Status = E_FAIL; } if (FAILED(Status)) { GenAccumulateStatus(Dump, MDSTATUS_CALL_FAILED); } goto Exit; } // If the current thread is dumping itself we can't // suspend. We can also assume the suspend count must // be zero since the thread is running. if (Thread->ThreadId == Dump->SysProv->GetCurrentThreadId()) { Thread->SuspendCount = 0; } else { Thread->SuspendCount = Dump->SysProv-> SuspendThread ( Thread->ThreadHandle ); } Thread->WriteFlags = WriteFlags; // // Add this if we ever need it // Thread->PriorityClass = 0; Thread->Priority = 0; // // Initialize the thread context. // Thread->ContextBuffer = Thread + 1; Status = Dump->SysProv-> GetThreadContext (Thread->ThreadHandle, Thread->ContextBuffer, Dump->ContextSize, &Thread->CurrentPc, &StackEnd, &StoreCurrent); if ( Status != S_OK ) { GenAccumulateStatus(Dump, MDSTATUS_CALL_FAILED); goto Exit; } if (Dump->CpuType == IMAGE_FILE_MACHINE_I386) { // // Note: for FPO frames on x86 we access bytes outside of the // ESP - StackBase range. Add a couple of bytes extra here so we // don't fail these cases. // StackEnd -= X86_STACK_FRAME_EXTRA_FPO_BYTES; } if ((Status = Dump->SysProv-> GetThreadInfo(Dump->ProcessHandle, Thread->ThreadHandle, &Thread->Teb, &Thread->SizeOfTeb, &Thread->StackBase, &StackLimit, &Thread->BackingStoreBase, &StoreLimit)) != S_OK) { goto Exit; } // // If the stack pointer (SP) is within the range of the stack // region (as allocated by the OS), only take memory from // the stack region up to the SP. Otherwise, assume the program // has blown it's SP -- purposefully, or not -- and copy // the entire stack as known by the OS. // if (Dump->BackingStore) { Thread->BackingStoreSize = (ULONG)(StoreCurrent - Thread->BackingStoreBase); } else { Thread->BackingStoreSize = 0; } if (StackLimit <= StackEnd && StackEnd < Thread->StackBase) { Thread->StackEnd = StackEnd; } else { Thread->StackEnd = StackLimit; } if ((ULONG)(Thread->StackBase - Thread->StackEnd) > Process->MaxStackOrStoreSize) { Process->MaxStackOrStoreSize = (ULONG)(Thread->StackBase - Thread->StackEnd); } if (Thread->BackingStoreSize > Process->MaxStackOrStoreSize) { Process->MaxStackOrStoreSize = Thread->BackingStoreSize; } Exit: if ( Status != S_OK ) { FreeMemory ( Dump, Thread ); } return Status; } VOID GenFreeThreadObject( IN PMINIDUMP_STATE Dump, IN PINTERNAL_THREAD Thread ) { if (Thread->SuspendCount != -1 && Thread->ThreadId != Dump->SysProv->GetCurrentThreadId()) { Dump->SysProv->ResumeThread (Thread->ThreadHandle); Thread->SuspendCount = -1; } Dump->SysProv->CloseThread(Thread->ThreadHandle); Thread->ThreadHandle = NULL; FreeMemory ( Dump, Thread ); Thread = NULL; } HRESULT GenGetThreadInstructionWindow( IN PMINIDUMP_STATE Dump, IN PINTERNAL_PROCESS Process, IN PINTERNAL_THREAD Thread ) { PVOID MemBuf; ULONG64 InstrStart; ULONG InstrSize; ULONG BytesRead; HRESULT Status = E_FAIL; if (!Dump->InstructionWindowSize) { return S_OK; } // // Store a window of the instruction stream around // the current program counter. This allows some // instruction context to be given even when images // can't be mapped. It also allows instruction // context to be given for generated code where // no image contains the necessary instructions. // InstrStart = Thread->CurrentPc - Dump->InstructionWindowSize / 2; InstrSize = Dump->InstructionWindowSize; MemBuf = AllocMemory(Dump, InstrSize); if (!MemBuf) { return E_OUTOFMEMORY; } for (;;) { // If we can read the instructions through the // current program counter we'll say that's // good enough. if (Dump->SysProv-> ReadVirtual(Dump->ProcessHandle, InstrStart, MemBuf, InstrSize, &BytesRead) == S_OK && InstrStart + BytesRead > Thread->CurrentPc) { Status = GenAddMemoryBlock(Dump, Process, MEMBLOCK_INSTR_WINDOW, InstrStart, BytesRead); break; } // We couldn't read up to the program counter. // If the start address is on the previous page // move it up to the same page. if ((InstrStart & ~((ULONG64)Dump->PageSize - 1)) != (Thread->CurrentPc & ~((ULONG64)Dump->PageSize - 1))) { ULONG Fraction = Dump->PageSize - (ULONG)InstrStart & (Dump->PageSize - 1); InstrSize -= Fraction; InstrStart += Fraction; } else { // The start and PC were on the same page so // we just can't read memory. There may have been // a jump to a bad address or something, so this // doesn't constitute an unexpected failure. break; } } FreeMemory(Dump, MemBuf); return Status; } PWSTR GenGetPathTail( IN PWSTR Path ) { PWSTR Scan = Path + GenStrLengthW(Path); while (Scan > Path) { Scan--; if (*Scan == '\\' || *Scan == '/' || *Scan == ':') { return Scan + 1; } } return Path; } HRESULT GenAllocateModuleObject( IN PMINIDUMP_STATE Dump, IN PINTERNAL_PROCESS Process, IN PWSTR FullPathW, IN ULONG64 BaseOfModule, IN ULONG WriteFlags, OUT PINTERNAL_MODULE* ModuleRet ) /*++ Routine Description: Given the full-path to the module and the base of the module, create and initialize an INTERNAL_MODULE object, and return it. --*/ { HRESULT Status; PVOID MappedBase; ULONG MappedSize; PIMAGE_NT_HEADERS NtHeaders; PINTERNAL_MODULE Module; ULONG Chars; ASSERT (FullPathW); ASSERT (BaseOfModule); Module = (PINTERNAL_MODULE) AllocMemory ( Dump, sizeof (INTERNAL_MODULE) ); if (Module == NULL) { return E_OUTOFMEMORY; } // // Get the version information for the module. // if ((Status = Dump->SysProv-> GetImageVersionInfo(Dump->ProcessHandle, FullPathW, BaseOfModule, &Module->VersionInfo)) != S_OK) { ZeroMemory(&Module->VersionInfo, sizeof(Module->VersionInfo)); } if ((Status = Dump->SysProv-> OpenMapping(FullPathW, &MappedSize, Module->FullPath, ARRAY_COUNT(Module->FullPath), &MappedBase)) != S_OK) { MappedBase = NULL; // Some providers can't map but still have image // information. Try that. if ((Status = Dump->SysProv-> GetImageHeaderInfo(Dump->ProcessHandle, FullPathW, BaseOfModule, &Module->SizeOfImage, &Module->CheckSum, &Module->TimeDateStamp)) != S_OK) { GenAccumulateStatus(Dump, MDSTATUS_CALL_FAILED); FreeMemory(Dump, Module); return Status; } // No long path name is available so just use // the incoming path. GenStrCopyNW(Module->FullPath, FullPathW, ARRAY_COUNT(Module->FullPath)); } if (IsFlagSet(Dump->DumpType, MiniDumpFilterModulePaths)) { Module->SavePath = GenGetPathTail(Module->FullPath); } else { Module->SavePath = Module->FullPath; } Module->BaseOfImage = BaseOfModule; Module->WriteFlags = WriteFlags; Module->CvRecord = NULL; Module->SizeOfCvRecord = 0; Module->MiscRecord = NULL; Module->SizeOfMiscRecord = 0; if (MappedBase) { IMAGE_NT_HEADERS64 Hdr64; NtHeaders = GenImageNtHeader ( MappedBase, &Hdr64 ); if (!NtHeaders) { GenAccumulateStatus(Dump, MDSTATUS_CALL_FAILED); FreeMemory(Dump, Module); return HRESULT_FROM_WIN32(ERROR_INVALID_DLL); } __try { // // Cull information from the image header. // Module->SizeOfImage = Hdr64.OptionalHeader.SizeOfImage; Module->CheckSum = Hdr64.OptionalHeader.CheckSum; Module->TimeDateStamp = Hdr64.FileHeader.TimeDateStamp; // // Get the CV record from the debug directory. // if (IsFlagSet(Module->WriteFlags, ModuleWriteCvRecord)) { GenGetDebugRecord(Dump, MappedBase, MappedSize, IMAGE_DEBUG_TYPE_CODEVIEW, REASONABLE_NB11_RECORD_SIZE, &Module->CvRecord, &Module->SizeOfCvRecord); } // // Get the MISC record from the debug directory. // if (IsFlagSet(Module->WriteFlags, ModuleWriteMiscRecord)) { GenGetDebugRecord(Dump, MappedBase, MappedSize, IMAGE_DEBUG_TYPE_MISC, REASONABLE_MISC_RECORD_SIZE, &Module->MiscRecord, &Module->SizeOfMiscRecord); } Status = S_OK; } __except(EXCEPTION_EXECUTE_HANDLER) { Status = HRESULT_FROM_NT(GetExceptionCode()); } Dump->SysProv->CloseMapping(MappedBase); if (Status != S_OK) { GenAccumulateStatus(Dump, MDSTATUS_CALL_FAILED); FreeMemory(Dump, Module); return Status; } } else { ULONG RecordLen; // // See if the provider can retrieve debug records. // RecordLen = 0; if (IsFlagSet(Module->WriteFlags, ModuleWriteCvRecord) && Dump->SysProv-> GetImageDebugRecord(Process->ProcessHandle, Module->FullPath, Module->BaseOfImage, IMAGE_DEBUG_TYPE_CODEVIEW, NULL, &RecordLen) == S_OK && RecordLen <= REASONABLE_NB11_RECORD_SIZE && (Module->CvRecord = AllocMemory(Dump, RecordLen))) { Module->SizeOfCvRecord = RecordLen; if (Dump->SysProv-> GetImageDebugRecord(Process->ProcessHandle, Module->FullPath, Module->BaseOfImage, IMAGE_DEBUG_TYPE_CODEVIEW, Module->CvRecord, &Module->SizeOfCvRecord) != S_OK) { FreeMemory(Dump, Module->CvRecord); Module->CvRecord = NULL; Module->SizeOfCvRecord = 0; } } RecordLen = 0; if (IsFlagSet(Module->WriteFlags, ModuleWriteMiscRecord) && Dump->SysProv-> GetImageDebugRecord(Process->ProcessHandle, Module->FullPath, Module->BaseOfImage, IMAGE_DEBUG_TYPE_CODEVIEW, NULL, &RecordLen) == S_OK && RecordLen <= REASONABLE_MISC_RECORD_SIZE && (Module->MiscRecord = AllocMemory(Dump, RecordLen))) { Module->SizeOfMiscRecord = RecordLen; if (Dump->SysProv-> GetImageDebugRecord(Process->ProcessHandle, Module->FullPath, Module->BaseOfImage, IMAGE_DEBUG_TYPE_MISC, Module->MiscRecord, &Module->SizeOfMiscRecord) != S_OK) { FreeMemory(Dump, Module->MiscRecord); Module->MiscRecord = NULL; Module->SizeOfMiscRecord = 0; } } } *ModuleRet = Module; return S_OK; } VOID GenFreeModuleObject( IN PMINIDUMP_STATE Dump, IN PINTERNAL_MODULE Module ) { FreeMemory ( Dump, Module->CvRecord ); Module->CvRecord = NULL; FreeMemory ( Dump, Module->MiscRecord ); Module->MiscRecord = NULL; FreeMemory ( Dump, Module ); Module = NULL; } HRESULT GenAllocateUnloadedModuleObject( IN PMINIDUMP_STATE Dump, IN PWSTR Path, IN ULONG64 BaseOfModule, IN ULONG SizeOfModule, IN ULONG CheckSum, IN ULONG TimeDateStamp, OUT PINTERNAL_UNLOADED_MODULE* ModuleRet ) { PINTERNAL_UNLOADED_MODULE Module; Module = (PINTERNAL_UNLOADED_MODULE) AllocMemory ( Dump, sizeof (*Module) ); if (Module == NULL) { return E_OUTOFMEMORY; } GenStrCopyNW(Module->Path, Path, ARRAY_COUNT(Module->Path)); Module->BaseOfImage = BaseOfModule; Module->SizeOfImage = SizeOfModule; Module->CheckSum = CheckSum; Module->TimeDateStamp = TimeDateStamp; *ModuleRet = Module; return S_OK; } VOID GenFreeUnloadedModuleObject( IN PMINIDUMP_STATE Dump, IN PINTERNAL_UNLOADED_MODULE Module ) { FreeMemory ( Dump, Module ); Module = NULL; } HRESULT GenAllocateFunctionTableObject( IN PMINIDUMP_STATE Dump, IN ULONG64 MinAddress, IN ULONG64 MaxAddress, IN ULONG64 BaseAddress, IN ULONG EntryCount, IN PVOID RawTable, OUT PINTERNAL_FUNCTION_TABLE* TableRet ) { PINTERNAL_FUNCTION_TABLE Table; Table = (PINTERNAL_FUNCTION_TABLE) AllocMemory(Dump, sizeof(INTERNAL_FUNCTION_TABLE) + Dump->FuncTableSize); if (!Table) { return E_OUTOFMEMORY; } Table->RawEntries = AllocMemory(Dump, Dump->FuncTableEntrySize * EntryCount); if (!Table->RawEntries) { FreeMemory(Dump, Table); return E_OUTOFMEMORY; } Table->MinimumAddress = MinAddress; Table->MaximumAddress = MaxAddress; Table->BaseAddress = BaseAddress; Table->EntryCount = EntryCount; Table->RawTable = (Table + 1); memcpy(Table->RawTable, RawTable, Dump->FuncTableSize); *TableRet = Table; return S_OK; } VOID GenFreeFunctionTableObject( IN PMINIDUMP_STATE Dump, IN struct _INTERNAL_FUNCTION_TABLE* Table ) { if (Table->RawEntries) { FreeMemory(Dump, Table->RawEntries); } FreeMemory(Dump, Table); } HRESULT GenAllocateProcessObject( IN PMINIDUMP_STATE Dump, OUT PINTERNAL_PROCESS* ProcessRet ) { HRESULT Status; PINTERNAL_PROCESS Process; FILETIME Create, Exit, User, Kernel; Process = (PINTERNAL_PROCESS) AllocMemory ( Dump, sizeof (INTERNAL_PROCESS) ); if (!Process) { return E_OUTOFMEMORY; } Process->ProcessId = Dump->ProcessId; Process->ProcessHandle = Dump->ProcessHandle; Process->NumberOfThreads = 0; Process->NumberOfModules = 0; Process->NumberOfFunctionTables = 0; InitializeListHead (&Process->ThreadList); InitializeListHead (&Process->ModuleList); InitializeListHead (&Process->UnloadedModuleList); InitializeListHead (&Process->FunctionTableList); InitializeListHead (&Process->MemoryBlocks); if ((Status = Dump->SysProv-> GetPeb(Dump->ProcessHandle, &Process->Peb, &Process->SizeOfPeb)) != S_OK) { // Failure is only critical if the dump needs // to include PEB memory. if (Dump->DumpType & MiniDumpWithProcessThreadData) { FreeMemory(Dump, Process); return Status; } else { Process->Peb = 0; Process->SizeOfPeb = 0; } } // Win9x doesn't support GetProcessTimes so failures // here are possible. if (Dump->SysProv-> GetProcessTimes(Dump->ProcessHandle, &Create, &User, &Kernel) == S_OK) { Process->TimesValid = TRUE; Process->CreateTime = FileTimeToTimeDate(&Create); Process->UserTime = FileTimeToSeconds(&User); Process->KernelTime = FileTimeToSeconds(&Kernel); } *ProcessRet = Process; return S_OK; } VOID GenFreeProcessObject( IN PMINIDUMP_STATE Dump, IN PINTERNAL_PROCESS Process ) { PINTERNAL_MODULE Module; PINTERNAL_UNLOADED_MODULE UnlModule; PINTERNAL_THREAD Thread; PINTERNAL_FUNCTION_TABLE Table; PVA_RANGE Range; PLIST_ENTRY Entry; Thread = NULL; Module = NULL; Entry = Process->ModuleList.Flink; while ( Entry != &Process->ModuleList ) { Module = CONTAINING_RECORD (Entry, INTERNAL_MODULE, ModulesLink); Entry = Entry->Flink; GenFreeModuleObject ( Dump, Module ); } Entry = Process->UnloadedModuleList.Flink; while ( Entry != &Process->UnloadedModuleList ) { UnlModule = CONTAINING_RECORD (Entry, INTERNAL_UNLOADED_MODULE, ModulesLink); Entry = Entry->Flink; GenFreeUnloadedModuleObject ( Dump, UnlModule ); } Entry = Process->ThreadList.Flink; while ( Entry != &Process->ThreadList ) { Thread = CONTAINING_RECORD (Entry, INTERNAL_THREAD, ThreadsLink); Entry = Entry->Flink; GenFreeThreadObject ( Dump, Thread ); } Entry = Process->FunctionTableList.Flink; while ( Entry != &Process->FunctionTableList ) { Table = CONTAINING_RECORD (Entry, INTERNAL_FUNCTION_TABLE, TableLink); Entry = Entry->Flink; GenFreeFunctionTableObject ( Dump, Table ); } Entry = Process->MemoryBlocks.Flink; while (Entry != &Process->MemoryBlocks) { Range = CONTAINING_RECORD(Entry, VA_RANGE, NextLink); Entry = Entry->Flink; FreeMemory(Dump, Range); } FreeMemory ( Dump, Process ); Process = NULL; } HRESULT GenIncludeUnwindInfoMemory( IN PMINIDUMP_STATE Dump, IN PINTERNAL_PROCESS Process, IN PINTERNAL_FUNCTION_TABLE Table ) { HRESULT Status; ULONG i; if (Dump->DumpType & MiniDumpWithFullMemory) { // Memory will be included by default. return S_OK; } for (i = 0; i < Table->EntryCount; i++) { ULONG64 Start; ULONG Size; if ((Status = Dump->SysProv-> EnumFunctionTableEntryMemory(Table->BaseAddress, Table->RawEntries, i, &Start, &Size)) != S_OK) { return Status; } if ((Status = GenAddMemoryBlock(Dump, Process, MEMBLOCK_UNWIND_INFO, Start, Size)) != S_OK) { return Status; } } return S_OK; } void GenRemoveMemoryBlock( IN PINTERNAL_PROCESS Process, IN PVA_RANGE Block ) { RemoveEntryList(&Block->NextLink); Process->NumberOfMemoryBlocks--; Process->SizeOfMemoryBlocks -= Block->Size; } HRESULT GenAddMemoryBlock( IN PMINIDUMP_STATE Dump, IN PINTERNAL_PROCESS Process, IN MEMBLOCK_TYPE Type, IN ULONG64 Start, IN ULONG Size ) { ULONG64 End; PLIST_ENTRY ScanEntry; PVA_RANGE Scan; ULONG64 ScanEnd; PVA_RANGE New = NULL; SIZE_T Done; UCHAR Byte; // Do not use Size after this to avoid ULONG overflows. End = Start + Size; if (End < Start) { End = (ULONG64)-1; } if (Start == End) { // Nothing to add. return S_OK; } if ((End - Start) > ULONG_MAX - Process->SizeOfMemoryBlocks) { // Overflow. GenAccumulateStatus(Dump, MDSTATUS_INTERNAL_ERROR); return E_INVALIDARG; } // // First trim the range down to memory that can actually // be accessed. // while (Start < End) { if (Dump->SysProv-> ReadAllVirtual(Dump->ProcessHandle, Start, &Byte, sizeof(Byte)) == S_OK) { break; } // Move up to the next page. Start = (Start + Dump->PageSize) & ~((ULONG64)Dump->PageSize - 1); if (!Start) { // Wrapped around. return S_OK; } } if (Start >= End) { // No valid memory. return S_OK; } ScanEnd = (Start + Dump->PageSize) & ~((ULONG64)Dump->PageSize - 1); for (;;) { if (ScanEnd >= End) { break; } if (Dump->SysProv-> ReadAllVirtual(Dump->ProcessHandle, ScanEnd, &Byte, sizeof(Byte)) != S_OK) { End = ScanEnd; break; } // Move up to the next page. ScanEnd = (ScanEnd + Dump->PageSize) & ~((ULONG64)Dump->PageSize - 1); if (!ScanEnd) { ScanEnd--; break; } } // // When adding memory to the list of memory to be saved // we want to avoid overlaps and also coalesce adjacent regions // so that the list has the largest possible non-adjacent // blocks. In order to accomplish this we make a pass over // the list and merge all listed blocks that overlap or abut the // incoming range with the incoming range, then remove the // merged entries from the list. After this pass we have // a region which is guaranteed not to overlap or abut anything in // the list. // ScanEntry = Process->MemoryBlocks.Flink; while (ScanEntry != &Process->MemoryBlocks) { Scan = CONTAINING_RECORD(ScanEntry, VA_RANGE, NextLink); ScanEnd = Scan->Start + Scan->Size; ScanEntry = Scan->NextLink.Flink; if (Scan->Start > End || ScanEnd < Start) { // No overlap or adjacency. continue; } // // Compute the union of the incoming range and // the scan block, then remove the scan block. // if (Scan->Start < Start) { Start = Scan->Start; } if (ScanEnd > End) { End = ScanEnd; } // We've lost the specific type. This is not a problem // right now but if specific types must be preserved // all the way through in the future it will be necessary // to avoid merging. Type = MEMBLOCK_MERGED; GenRemoveMemoryBlock(Process, Scan); if (!New) { // Save memory for reuse. New = Scan; } else { FreeMemory(Dump, Scan); } } if (!New) { New = (PVA_RANGE)AllocMemory(Dump, sizeof(*New)); if (!New) { return E_OUTOFMEMORY; } } New->Start = Start; // Overflow is extremely unlikely, so don't do anything // fancy to handle it. if (End - Start > ULONG_MAX) { New->Size = ULONG_MAX; } else { New->Size = (ULONG)(End - Start); } New->Type = Type; InsertTailList(&Process->MemoryBlocks, &New->NextLink); Process->NumberOfMemoryBlocks++; Process->SizeOfMemoryBlocks += New->Size; return S_OK; } void GenRemoveMemoryRange( IN PMINIDUMP_STATE Dump, IN PINTERNAL_PROCESS Process, IN ULONG64 Start, IN ULONG Size ) { ULONG64 End = Start + Size; PLIST_ENTRY ScanEntry; PVA_RANGE Scan; ULONG64 ScanEnd; Restart: ScanEntry = Process->MemoryBlocks.Flink; while (ScanEntry != &Process->MemoryBlocks) { Scan = CONTAINING_RECORD(ScanEntry, VA_RANGE, NextLink); ScanEnd = Scan->Start + Scan->Size; ScanEntry = Scan->NextLink.Flink; if (Scan->Start >= End || ScanEnd <= Start) { // No overlap. continue; } if (Scan->Start < Start) { // Trim block to non-overlapping pre-Start section. Scan->Size = (ULONG)(Start - Scan->Start); if (ScanEnd > End) { // There's also a non-overlapping section post-End. // We need to add a new block. GenAddMemoryBlock(Dump, Process, Scan->Type, End, (ULONG)(ScanEnd - End)); // The list has changed so restart. goto Restart; } } else if (ScanEnd > End) { // Trim block to non-overlapping post-End section. Scan->Start = End; Scan->Size = (ULONG)(ScanEnd - End); } else { // Scan is completely contained. GenRemoveMemoryBlock(Process, Scan); FreeMemory(Dump, Scan); } } } HRESULT GenAddPebMemory( IN PMINIDUMP_STATE Dump, IN PINTERNAL_PROCESS Process ) { HRESULT Status = S_OK, Check; GenMiniDumpProviderCallbacks Callbacks(Dump, Process); Callbacks.PushMemType(MEMBLOCK_PEB); // Accumulate error status but do not stop processing // for errors. if ((Check = GenAddMemoryBlock(Dump, Process, MEMBLOCK_PEB, Process->Peb, Process->SizeOfPeb)) != S_OK) { Status = Check; } if (!(Dump->DumpType & MiniDumpWithoutOptionalData) && (Check = Dump->SysProv-> EnumPebMemory(Process->ProcessHandle, Process->Peb, Process->SizeOfPeb, &Callbacks)) != S_OK) { Status = Check; } Callbacks.PopMemType(); return Status; } HRESULT GenAddTebMemory( IN PMINIDUMP_STATE Dump, IN PINTERNAL_PROCESS Process, IN PINTERNAL_THREAD Thread ) { HRESULT Status = S_OK, Check; GenMiniDumpProviderCallbacks Callbacks(Dump, Process); Callbacks.PushMemType(MEMBLOCK_TEB); // Accumulate error status but do not stop processing // for errors. if ((Check = GenAddMemoryBlock(Dump, Process, MEMBLOCK_TEB, Thread->Teb, Thread->SizeOfTeb)) != S_OK) { Status = Check; } if (!(Dump->DumpType & MiniDumpWithoutOptionalData) && (Check = Dump->SysProv-> EnumTebMemory(Process->ProcessHandle, Thread->ThreadHandle, Thread->Teb, Thread->SizeOfTeb, &Callbacks)) != S_OK) { Status = Check; } Callbacks.PopMemType(); return Status; } HRESULT GenScanAddressSpace( IN PMINIDUMP_STATE Dump, IN PINTERNAL_PROCESS Process ) { HRESULT Status; ULONG ProtectMask = 0, TypeMask = 0; ULONG64 Offset, Size; ULONG Protect, State, Type; if (Dump->DumpType & MiniDumpWithPrivateReadWriteMemory) { ProtectMask |= PAGE_READWRITE; TypeMask |= MEM_PRIVATE; } if (!ProtectMask || !TypeMask) { // Nothing to scan for. return S_OK; } Status = S_OK; Offset = 0; for (;;) { if (Dump->SysProv-> QueryVirtual(Dump->ProcessHandle, Offset, &Offset, &Size, &Protect, &State, &Type) != S_OK) { break; } ULONG64 ScanOffset = Offset; Offset += Size; if (State == MEM_COMMIT && (Protect & ProtectMask) && (Type & TypeMask)) { while (Size > 0) { ULONG BlockSize; HRESULT OneStatus; if (Size > ULONG_MAX / 2) { BlockSize = ULONG_MAX / 2; } else { BlockSize = (ULONG)Size; } if ((OneStatus = GenAddMemoryBlock(Dump, Process, MEMBLOCK_PRIVATE_RW, ScanOffset, BlockSize)) != S_OK) { Status = OneStatus; } ScanOffset += BlockSize; Size -= BlockSize; } } } return Status; } BOOL GenAppendStrW( IN OUT PWSTR* Str, IN OUT PULONG Chars, IN PCWSTR Append ) { if (!Append) { return FALSE; } while (*Chars > 1 && *Append) { **Str = *Append++; (*Str)++; (*Chars)--; } if (!*Chars) { return FALSE; } **Str = 0; return TRUE; } PWSTR GenIToAW( IN ULONG Val, IN ULONG FieldChars, IN WCHAR FillChar, IN PWSTR Buf, IN ULONG BufChars ) { PWSTR Store = Buf + (BufChars - 1); *Store-- = 0; if (Val == 0) { *Store-- = L'0'; } else { while (Val) { if (Store < Buf) { return NULL; } *Store-- = (WCHAR)(Val % 10) + L'0'; Val /= 10; } } PWSTR FieldStart = Buf + (BufChars - 1) - FieldChars; while (Store >= FieldStart) { *Store-- = FillChar; } return Store + 1; } class GenCorDataAccessServices : public ICorDataAccessServices { public: GenCorDataAccessServices(IN PMINIDUMP_STATE Dump, IN PINTERNAL_PROCESS Process) { m_Dump = Dump; m_Process = Process; } // IUnknown. STDMETHOD(QueryInterface)( THIS_ IN REFIID InterfaceId, OUT PVOID* Interface ) { *Interface = NULL; return E_NOINTERFACE; } STDMETHOD_(ULONG, AddRef)( THIS ) { return 1; } STDMETHOD_(ULONG, Release)( THIS ) { return 0; } // ICorDataAccessServices. virtual HRESULT STDMETHODCALLTYPE GetMachineType( /* [out] */ ULONG32 *machine); virtual HRESULT STDMETHODCALLTYPE GetPointerSize( /* [out] */ ULONG32 *size); virtual HRESULT STDMETHODCALLTYPE GetImageBase( /* [string][in] */ LPCWSTR name, /* [out] */ CORDATA_ADDRESS *base); virtual HRESULT STDMETHODCALLTYPE ReadVirtual( /* [in] */ CORDATA_ADDRESS address, /* [length_is][size_is][out] */ PBYTE buffer, /* [in] */ ULONG32 request, /* [optional][out] */ ULONG32 *done); virtual HRESULT STDMETHODCALLTYPE WriteVirtual( /* [in] */ CORDATA_ADDRESS address, /* [size_is][in] */ PBYTE buffer, /* [in] */ ULONG32 request, /* [optional][out] */ ULONG32 *done); virtual HRESULT STDMETHODCALLTYPE GetTlsValue( /* [in] */ ULONG32 index, /* [out] */ CORDATA_ADDRESS* value); virtual HRESULT STDMETHODCALLTYPE SetTlsValue( /* [in] */ ULONG32 index, /* [in] */ CORDATA_ADDRESS value); virtual HRESULT STDMETHODCALLTYPE GetCurrentThreadId( /* [out] */ ULONG32* threadId); virtual HRESULT STDMETHODCALLTYPE GetThreadContext( /* [in] */ ULONG32 threadId, /* [in] */ ULONG32 contextFlags, /* [in] */ ULONG32 contextSize, /* [out, size_is(contextSize)] */ PBYTE context); virtual HRESULT STDMETHODCALLTYPE SetThreadContext( /* [in] */ ULONG32 threadId, /* [in] */ ULONG32 contextSize, /* [in, size_is(contextSize)] */ PBYTE context); PMINIDUMP_STATE m_Dump; PINTERNAL_PROCESS m_Process; }; HRESULT STDMETHODCALLTYPE GenCorDataAccessServices::GetMachineType( /* [out] */ ULONG32 *machine ) { *machine = m_Dump->CpuType; return S_OK; } HRESULT STDMETHODCALLTYPE GenCorDataAccessServices::GetPointerSize( /* [out] */ ULONG32 *size ) { *size = m_Dump->PtrSize; return S_OK; } HRESULT STDMETHODCALLTYPE GenCorDataAccessServices::GetImageBase( /* [string][in] */ LPCWSTR name, /* [out] */ CORDATA_ADDRESS *base ) { if ((!GenStrCompareW(name, L"mscoree.dll") && !GenStrCompareW(m_Process->CorDllType, L"ee")) || (!GenStrCompareW(name, L"mscorwks.dll") && !GenStrCompareW(m_Process->CorDllType, L"wks")) || (!GenStrCompareW(name, L"mscorsvr.dll") && !GenStrCompareW(m_Process->CorDllType, L"svr"))) { *base = m_Process->CorDllBase; return S_OK; } return E_NOINTERFACE; } HRESULT STDMETHODCALLTYPE GenCorDataAccessServices::ReadVirtual( /* [in] */ CORDATA_ADDRESS address, /* [length_is][size_is][out] */ PBYTE buffer, /* [in] */ ULONG32 request, /* [optional][out] */ ULONG32 *done ) { return m_Dump->SysProv-> ReadVirtual(m_Process->ProcessHandle, address, buffer, request, (PULONG)done); } HRESULT STDMETHODCALLTYPE GenCorDataAccessServices::WriteVirtual( /* [in] */ CORDATA_ADDRESS address, /* [size_is][in] */ PBYTE buffer, /* [in] */ ULONG32 request, /* [optional][out] */ ULONG32 *done) { // No modification supported. return E_UNEXPECTED; } HRESULT STDMETHODCALLTYPE GenCorDataAccessServices::GetTlsValue( /* [in] */ ULONG32 index, /* [out] */ CORDATA_ADDRESS* value ) { // Not needed for minidump. return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE GenCorDataAccessServices::SetTlsValue( /* [in] */ ULONG32 index, /* [in] */ CORDATA_ADDRESS value) { // No modification supported. return E_UNEXPECTED; } HRESULT STDMETHODCALLTYPE GenCorDataAccessServices::GetCurrentThreadId( /* [out] */ ULONG32* threadId) { // Not needed for minidump. return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE GenCorDataAccessServices::GetThreadContext( /* [in] */ ULONG32 threadId, /* [in] */ ULONG32 contextFlags, /* [in] */ ULONG32 contextSize, /* [out, size_is(contextSize)] */ PBYTE context ) { PINTERNAL_THREAD Thread; PLIST_ENTRY Entry; Entry = m_Process->ThreadList.Flink; while (Entry != &m_Process->ThreadList) { Thread = CONTAINING_RECORD(Entry, INTERNAL_THREAD, ThreadsLink); Entry = Entry->Flink; if (Thread->ThreadId == threadId) { ULONG64 Ignored; return m_Dump->SysProv-> GetThreadContext(Thread->ThreadHandle, context, contextSize, &Ignored, &Ignored, &Ignored); } } return E_NOINTERFACE; } HRESULT STDMETHODCALLTYPE GenCorDataAccessServices::SetThreadContext( /* [in] */ ULONG32 threadId, /* [in] */ ULONG32 contextSize, /* [in, size_is(contextSize)] */ PBYTE context) { // No modification supported. return E_UNEXPECTED; } class GenCorDataEnumMemoryRegions : public ICorDataEnumMemoryRegions { public: GenCorDataEnumMemoryRegions(IN PMINIDUMP_STATE Dump, IN PINTERNAL_PROCESS Process) { m_Dump = Dump; m_Process = Process; } // IUnknown. STDMETHOD(QueryInterface)( THIS_ IN REFIID InterfaceId, OUT PVOID* Interface ) { *Interface = NULL; return E_NOINTERFACE; } STDMETHOD_(ULONG, AddRef)( THIS ) { return 1; } STDMETHOD_(ULONG, Release)( THIS ) { return 0; } // ICorDataEnumMemoryRegions. HRESULT STDMETHODCALLTYPE EnumMemoryRegion( /* [in] */ CORDATA_ADDRESS address, /* [in] */ ULONG32 size ) { return GenAddMemoryBlock(m_Dump, m_Process, MEMBLOCK_COR, address, size); } private: PMINIDUMP_STATE m_Dump; PINTERNAL_PROCESS m_Process; }; HRESULT GenTryGetCorMemory( IN PMINIDUMP_STATE Dump, IN PINTERNAL_PROCESS Process, IN PWSTR CorDebugDllPath, OUT PBOOL Loaded ) { HRESULT Status; GenCorDataAccessServices Services(Dump, Process); GenCorDataEnumMemoryRegions EnumMem(Dump, Process); ICorDataAccess* Access; *Loaded = FALSE; if ((Status = Dump->SysProv-> GetCorDataAccess(CorDebugDllPath, &Services, &Access)) != S_OK) { return Status; } *Loaded = TRUE; Status = Access->EnumMemoryRegions(&EnumMem, DAC_ENUM_MEM_DEFAULT); Dump->SysProv->ReleaseCorDataAccess(Access); return Status; } HRESULT GenGetCorMemory( IN PMINIDUMP_STATE Dump, IN PINTERNAL_PROCESS Process ) { HRESULT Status; // Do not enable COR memory gathering for .NET Server // as it's not stable yet. #ifdef GET_COR_MEMORY if (!Process->CorDllType) { // COR is not loaded. return S_OK; } if (Dump->DumpType & (MiniDumpWithFullMemory | MiniDumpWithPrivateReadWriteMemory)) { // All COR memory should already be included. return S_OK; } WCHAR CorDebugDllPath[MAX_PATH + 1]; WCHAR NumStr[16]; PWSTR DllPathEnd, End; ULONG Chars; BOOL Loaded; GenStrCopyNW(CorDebugDllPath, Process->CorDllPath, ARRAY_COUNT(CorDebugDllPath)); DllPathEnd = GenGetPathTail(CorDebugDllPath); // // First try to load with the basic name. // End = DllPathEnd; *End = 0; Chars = (ULONG)(ARRAY_COUNT(CorDebugDllPath) - (End - CorDebugDllPath)); if (!GenAppendStrW(&End, &Chars, L"mscordacwks.dll")) { return E_INVALIDARG; } if ((Status = GenTryGetCorMemory(Dump, Process, CorDebugDllPath, &Loaded)) == S_OK || Loaded) { return Status; } // // That didn't work, so try with the full name. // #if defined(_X86_) PWSTR HostCpu = L"x86"; #elif defined(_IA64_) PWSTR HostCpu = L"IA64"; #elif defined(_AMD64_) PWSTR HostCpu = L"AMD64"; #elif defined(_ARM_) PWSTR HostCpu = L"ARM"; #else #error Unknown processor. #endif if (!GenAppendStrW(&End, &Chars, L"mscordac") || !GenAppendStrW(&End, &Chars, Process->CorDllType) || !GenAppendStrW(&End, &Chars, L"_") || !GenAppendStrW(&End, &Chars, HostCpu) || !GenAppendStrW(&End, &Chars, L"_") || !GenAppendStrW(&End, &Chars, Dump->CpuTypeName) || !GenAppendStrW(&End, &Chars, L"_") || !GenAppendStrW(&End, &Chars, GenIToAW(Process->CorDllVer.dwFileVersionMS >> 16, 0, 0, NumStr, ARRAY_COUNT(NumStr))) || !GenAppendStrW(&End, &Chars, L".") || !GenAppendStrW(&End, &Chars, GenIToAW(Process->CorDllVer.dwFileVersionMS & 0xffff, 0, 0, NumStr, ARRAY_COUNT(NumStr))) || !GenAppendStrW(&End, &Chars, L".") || !GenAppendStrW(&End, &Chars, GenIToAW(Process->CorDllVer.dwFileVersionLS >> 16, 0, 0, NumStr, ARRAY_COUNT(NumStr))) || !GenAppendStrW(&End, &Chars, L".") || !GenAppendStrW(&End, &Chars, GenIToAW(Process->CorDllVer.dwFileVersionLS & 0xffff, 2, L'0', NumStr, ARRAY_COUNT(NumStr))) || ((Process->CorDllVer.dwFileFlags & VS_FF_DEBUG) && !GenAppendStrW(&End, &Chars, (Process->CorDllVer.dwFileFlags & VS_FF_SPECIALBUILD) ? L".dbg" : L".chk")) || !GenAppendStrW(&End, &Chars, L".dll")) { return E_INVALIDARG; } return GenTryGetCorMemory(Dump, Process, CorDebugDllPath, &Loaded); #else return S_OK; #endif } HRESULT GenGetProcessInfo( IN PMINIDUMP_STATE Dump, OUT PINTERNAL_PROCESS * ProcessRet ) { HRESULT Status; BOOL EnumStarted = FALSE; PINTERNAL_PROCESS Process; WCHAR UnicodePath[MAX_PATH + 10]; if ((Status = GenAllocateProcessObject(Dump, &Process)) != S_OK) { return Status; } if ((Status = Dump->SysProv->StartProcessEnum(Dump->ProcessHandle, Dump->ProcessId)) != S_OK) { goto Exit; } EnumStarted = TRUE; // // Walk thread list, suspending all threads and getting thread info. // for (;;) { PINTERNAL_THREAD Thread; ULONG ThreadId; Status = Dump->SysProv->EnumThreads(&ThreadId); if (Status == S_FALSE) { break; } else if (Status != S_OK) { goto Exit; } ULONG WriteFlags; if (!GenExecuteIncludeThreadCallback(Dump, ThreadId, &WriteFlags) || IsFlagClear(WriteFlags, ThreadWriteThread)) { continue; } Status = GenAllocateThreadObject(Dump, Process, ThreadId, WriteFlags, &Thread); if (FAILED(Status)) { goto Exit; } // If Status is S_FALSE it means that the thread // couldn't be opened and probably exited before // we got to it. Just continue on. if (Status == S_OK) { Process->NumberOfThreads++; InsertTailList(&Process->ThreadList, &Thread->ThreadsLink); } } // // Walk module list, getting module information. // for (;;) { PINTERNAL_MODULE Module; ULONG64 ModuleBase; Status = Dump->SysProv->EnumModules(&ModuleBase, UnicodePath, ARRAY_COUNT(UnicodePath)); if (Status == S_FALSE) { break; } else if (Status != S_OK) { goto Exit; } PWSTR ModPathTail; BOOL IsCor = FALSE; ModPathTail = GenGetPathTail(UnicodePath); if (!GenStrCompareW(ModPathTail, L"mscoree.dll") && !Process->CorDllType) { IsCor = TRUE; Process->CorDllType = L"ee"; } else if (!GenStrCompareW(ModPathTail, L"mscorwks.dll")) { IsCor = TRUE; Process->CorDllType = L"wks"; } else if (!GenStrCompareW(ModPathTail, L"mscorsvr.dll")) { IsCor = TRUE; Process->CorDllType = L"svr"; } if (IsCor) { Process->CorDllBase = ModuleBase; GenStrCopyNW(Process->CorDllPath, UnicodePath, ARRAY_COUNT(Process->CorDllPath)); } ULONG WriteFlags; if (!GenExecuteIncludeModuleCallback(Dump, ModuleBase, &WriteFlags) || IsFlagClear(WriteFlags, ModuleWriteModule)) { // If this is the COR DLL module we need to get // its version information for later use. The // callback has dropped it from the enumeration // so do it right now before the module is forgotten. if (IsCor && (Status = Dump->SysProv-> GetImageVersionInfo(Dump->ProcessHandle, UnicodePath, ModuleBase, &Process->CorDllVer)) != S_OK) { // If we can't get the version just forget // that this process has the COR loaded. // The dump will probably be useless but // there's a tiny chance it won't. Process->CorDllType = NULL; } continue; } if ((Status = GenAllocateModuleObject(Dump, Process, UnicodePath, ModuleBase, WriteFlags, &Module)) != S_OK) { goto Exit; } if (IsCor) { Process->CorDllVer = Module->VersionInfo; } Process->NumberOfModules++; InsertTailList (&Process->ModuleList, &Module->ModulesLink); } // // Walk function table list. The function table list // is important but not absolutely critical so failures // here are not fatal. // for (;;) { PINTERNAL_FUNCTION_TABLE Table; ULONG64 MinAddr, MaxAddr, BaseAddr; ULONG EntryCount; ULONG64 RawTable[(MAX_DYNAMIC_FUNCTION_TABLE + sizeof(ULONG64) - 1) / sizeof(ULONG64)]; PVOID RawEntryHandle; Status = Dump->SysProv-> EnumFunctionTables(&MinAddr, &MaxAddr, &BaseAddr, &EntryCount, RawTable, Dump->FuncTableSize, &RawEntryHandle); if (Status != S_OK) { break; } if (GenAllocateFunctionTableObject(Dump, MinAddr, MaxAddr, BaseAddr, EntryCount, RawTable, &Table) == S_OK) { if (Dump->SysProv-> EnumFunctionTableEntries(RawTable, Dump->FuncTableSize, RawEntryHandle, Table->RawEntries, EntryCount * Dump->FuncTableEntrySize) != S_OK) { GenFreeFunctionTableObject(Dump, Table); } else { GenIncludeUnwindInfoMemory(Dump, Process, Table); Process->NumberOfFunctionTables++; InsertTailList(&Process->FunctionTableList, &Table->TableLink); } } } // // Walk unloaded module list. The unloaded module // list is not critical information so failures here // are not fatal. // if (Dump->DumpType & MiniDumpWithUnloadedModules) { PINTERNAL_UNLOADED_MODULE UnlModule; ULONG64 ModuleBase; ULONG Size; ULONG CheckSum; ULONG TimeDateStamp; while (Dump->SysProv-> EnumUnloadedModules(UnicodePath, ARRAY_COUNT(UnicodePath), &ModuleBase, &Size, &CheckSum, &TimeDateStamp) == S_OK) { if (GenAllocateUnloadedModuleObject(Dump, UnicodePath, ModuleBase, Size, CheckSum, TimeDateStamp, &UnlModule) == S_OK) { Process->NumberOfUnloadedModules++; InsertHeadList(&Process->UnloadedModuleList, &UnlModule->ModulesLink); } else { break; } } } Status = S_OK; Exit: if (EnumStarted) { Dump->SysProv->FinishProcessEnum(); } if (Status == S_OK) { // We don't consider a failure here to be a critical // failure. The dump won't contain all of the // requested information but it'll still have // the basic thread information, which could be // valuable on its own. GenScanAddressSpace(Dump, Process); GenGetCorMemory(Dump, Process); } else { GenFreeProcessObject(Dump, Process); Process = NULL; } *ProcessRet = Process; return Status; } HRESULT GenWriteHandleData( IN PMINIDUMP_STATE Dump, IN PMINIDUMP_STREAM_INFO StreamInfo ) { HRESULT Status; ULONG HandleCount; ULONG Hits; WCHAR TypeName[64]; WCHAR ObjectName[MAX_PATH]; PMINIDUMP_HANDLE_DESCRIPTOR Descs, Desc; ULONG32 Len; MINIDUMP_HANDLE_DATA_STREAM DataStream; RVA Rva = StreamInfo->RvaOfHandleData; if ((Status = Dump->SysProv-> StartHandleEnum(Dump->ProcessHandle, Dump->ProcessId, &HandleCount)) != S_OK) { return Status; } if (!HandleCount) { Dump->SysProv->FinishHandleEnum(); return S_OK; } Descs = (PMINIDUMP_HANDLE_DESCRIPTOR) AllocMemory(Dump, HandleCount * sizeof(*Desc)); if (Descs == NULL) { Dump->SysProv->FinishHandleEnum(); return E_OUTOFMEMORY; } Hits = 0; Desc = Descs; while (Hits < HandleCount && Dump->SysProv-> EnumHandles(&Desc->Handle, (PULONG)&Desc->Attributes, (PULONG)&Desc->GrantedAccess, (PULONG)&Desc->HandleCount, (PULONG)&Desc->PointerCount, TypeName, ARRAY_COUNT(TypeName), ObjectName, ARRAY_COUNT(ObjectName)) == S_OK) { // Successfully got a handle, so consider this a hit. Hits++; Desc->TypeNameRva = Rva; Len = GenStrLengthW(TypeName) * sizeof(WCHAR); if ((Status = Dump->OutProv-> WriteAll(&Len, sizeof(Len))) != S_OK) { goto Exit; } Len += sizeof(WCHAR); if ((Status = Dump->OutProv-> WriteAll(TypeName, Len)) != S_OK) { goto Exit; } Rva += Len + sizeof(Len); if (ObjectName[0]) { Desc->ObjectNameRva = Rva; Len = GenStrLengthW(ObjectName) * sizeof(WCHAR); if ((Status = Dump->OutProv-> WriteAll(&Len, sizeof(Len))) != S_OK) { goto Exit; } Len += sizeof(WCHAR); if ((Status = Dump->OutProv-> WriteAll(ObjectName, Len)) != S_OK) { goto Exit; } Rva += Len + sizeof(Len); } else { Desc->ObjectNameRva = 0; } Desc++; } DataStream.SizeOfHeader = sizeof(DataStream); DataStream.SizeOfDescriptor = sizeof(*Descs); DataStream.NumberOfDescriptors = (ULONG)(Desc - Descs); DataStream.Reserved = 0; StreamInfo->RvaOfHandleData = Rva; StreamInfo->SizeOfHandleData = sizeof(DataStream) + DataStream.NumberOfDescriptors * sizeof(*Descs); if ((Status = Dump->OutProv-> WriteAll(&DataStream, sizeof(DataStream))) == S_OK) { Status = Dump->OutProv-> WriteAll(Descs, DataStream.NumberOfDescriptors * sizeof(*Descs)); } Exit: FreeMemory(Dump, Descs); Dump->SysProv->FinishHandleEnum(); return Status; } ULONG GenProcArchToImageMachine(ULONG ProcArch) { switch(ProcArch) { case PROCESSOR_ARCHITECTURE_INTEL: return IMAGE_FILE_MACHINE_I386; case PROCESSOR_ARCHITECTURE_IA64: return IMAGE_FILE_MACHINE_IA64; case PROCESSOR_ARCHITECTURE_AMD64: return IMAGE_FILE_MACHINE_AMD64; case PROCESSOR_ARCHITECTURE_ARM: return IMAGE_FILE_MACHINE_ARM; case PROCESSOR_ARCHITECTURE_ALPHA: return IMAGE_FILE_MACHINE_ALPHA; case PROCESSOR_ARCHITECTURE_ALPHA64: return IMAGE_FILE_MACHINE_AXP64; default: return IMAGE_FILE_MACHINE_UNKNOWN; } } LPWSTR GenStrCopyNW( OUT LPWSTR lpString1, IN LPCWSTR lpString2, IN int iMaxLength ) { wchar_t * cp = lpString1; if (iMaxLength > 0) { while( iMaxLength > 1 && (*cp++ = *lpString2++) ) iMaxLength--; /* Copy src over dst */ if (cp > lpString1 && cp[-1]) { *cp = 0; } } return( lpString1 ); } size_t GenStrLengthW( const wchar_t * wcs ) { const wchar_t *eos = wcs; while( *eos++ ) ; return( (size_t)(eos - wcs - 1) ); } int GenStrCompareW( IN LPCWSTR String1, IN LPCWSTR String2 ) { while (*String1) { if (*String1 < *String2) { return -1; } else if (*String1 > *String2) { return 1; } String1++; String2++; } return *String2 ? 1 : 0; } C_ASSERT(sizeof(EXCEPTION_RECORD64) == sizeof(MINIDUMP_EXCEPTION)); void GenExRecord32ToMd(PEXCEPTION_RECORD32 Rec32, PMINIDUMP_EXCEPTION RecMd) { ULONG i; RecMd->ExceptionCode = Rec32->ExceptionCode; RecMd->ExceptionFlags = Rec32->ExceptionFlags; RecMd->ExceptionRecord = (LONG)Rec32->ExceptionRecord; RecMd->ExceptionAddress = (LONG)Rec32->ExceptionAddress; RecMd->NumberParameters = Rec32->NumberParameters; for (i = 0; i < EXCEPTION_MAXIMUM_PARAMETERS; i++) { RecMd->ExceptionInformation[i] = (LONG)Rec32->ExceptionInformation[i]; } }
28.508516
80
0.526884
26945ad97669474146a61832833e9516173e6d14
268
cpp
C++
robot_driver/src/robot_driver_node.cpp
robomechanics/quad-software
89154df18e98162249f38301b669df27ee595220
[ "MIT" ]
20
2021-12-05T03:40:28.000Z
2022-03-30T02:53:56.000Z
robot_driver/src/robot_driver_node.cpp
robomechanics/rml-spirit-firmware
89154df18e98162249f38301b669df27ee595220
[ "MIT" ]
45
2021-12-06T12:45:05.000Z
2022-03-31T22:15:47.000Z
robot_driver/src/robot_driver_node.cpp
robomechanics/rml-spirit-firmware
89154df18e98162249f38301b669df27ee595220
[ "MIT" ]
2
2021-12-06T03:20:15.000Z
2022-02-20T04:19:41.000Z
#include <ros/ros.h> #include <iostream> #include "robot_driver/robot_driver.h" int main(int argc, char** argv) { ros::init(argc, argv, "robot_driver_node"); ros::NodeHandle nh; RobotDriver robot_driver(nh, argc, argv); robot_driver.spin(); return 0; }
16.75
45
0.69403
2696661cdfcc1cdd32850db86f3aa38a27bdf078
52,915
cpp
C++
libraries/ble/nRF51822/nordic/ble/ble_bondmngr.cpp
hakehuang/mbed
04b488dcc418f0317cdee1781b27a59295909c77
[ "Apache-2.0" ]
null
null
null
libraries/ble/nRF51822/nordic/ble/ble_bondmngr.cpp
hakehuang/mbed
04b488dcc418f0317cdee1781b27a59295909c77
[ "Apache-2.0" ]
null
null
null
libraries/ble/nRF51822/nordic/ble/ble_bondmngr.cpp
hakehuang/mbed
04b488dcc418f0317cdee1781b27a59295909c77
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. * * The information contained herein is property of Nordic Semiconductor ASA. * Terms and conditions of usage are described in detail in NORDIC * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. * * Licensees are granted free, non-transferable use of the information. NO * WARRANTY of ANY KIND is provided. This heading must NOT be removed from * the file. * */ #include "ble_bondmngr.h" #include <stdlib.h> #include <stdint.h> #include <string.h> #include "nordic_common.h" #include "nrf_error.h" #include "ble_gap.h" #include "ble_srv_common.h" #include "app_util.h" #include "nrf_assert.h" //#include "nrf.h" #include "nrf51_bitfields.h" #include "crc16.h" #include "pstorage.h" #include "ble_bondmngr_cfg.h" #define CCCD_SIZE 6 /**< Number of bytes needed for storing the state of one CCCD. */ #define CRC_SIZE 2 /**< Size of CRC in sys_attribute data. */ #define SYS_ATTR_BUFFER_MAX_LEN (((BLE_BONDMNGR_CCCD_COUNT + 1) * CCCD_SIZE) + CRC_SIZE) /**< Size of sys_attribute data. */ #define MAX_NUM_CENTRAL_WHITE_LIST MIN(BLE_BONDMNGR_MAX_BONDED_CENTRALS, 8) /**< Maximum number of whitelisted centrals supported.*/ #define MAX_BONDS_IN_FLASH 10 /**< Maximum number of bonds that can be stored in flash. */ #define BOND_MANAGER_DATA_SIGNATURE 0x53240000 /**@defgroup ble_bond_mngr_sec_access Bond Manager Security Status Access Macros * @brief The following group of macros abstract access to Security Status with a peer. * @{ */ #define SEC_STATUS_INIT_VAL 0x00 /**< Initialization value for security status flags. */ #define ENC_STATUS_SET_VAL 0x01 /**< Bitmask for encryption status. */ #define BOND_IN_PROGRESS_SET_VAL 0x02 /**< Bitmask for 'bonding in progress'. */ /**@brief Macro for setting the Encryption Status for current link. * * @details Macro for setting the Encryption Status for current link. */ #define ENCRYPTION_STATUS_SET() \ do \ { \ m_sec_con_status |= ENC_STATUS_SET_VAL; \ } while (0) /**@brief Macro for getting the Encryption Status for current link. * * @details Macro for getting the Encryption Status for current link. */ #define ENCRYPTION_STATUS_GET() \ (((m_sec_con_status & ENC_STATUS_SET_VAL) == 0) ? false : true) /**@brief Macro for resetting the Encryption Status for current link. * * @details Macro for resetting the Encryption Status for current link. */ #define ENCRYPTION_STATUS_RESET() \ do \ { \ m_sec_con_status &= (~ENC_STATUS_SET_VAL); \ } while (0) /**@brief Macro for resetting the Bonding In Progress status for current link. * * @details Macro for resetting the Bonding In Progress status for current link. */ #define BONDING_IN_PROGRESS_STATUS_SET() \ do \ { \ m_sec_con_status |= BOND_IN_PROGRESS_SET_VAL; \ } while (0) /**@brief Macro for setting the Bonding In Progress status for current link. * * @details Macro for setting the Bonding In Progress status for current link. */ #define BONDING_IN_PROGRESS_STATUS_GET() \ (((m_sec_con_status & BOND_IN_PROGRESS_SET_VAL) == 0) ? false: true) /**@brief Macro for resetting the Bonding In Progress status for current link. * * @details Macro for resetting the Bonding In Progress status for current link. */ #define BONDING_IN_PROGRESS_STATUS_RESET() \ do \ { \ m_sec_con_status &= (~BOND_IN_PROGRESS_SET_VAL); \ } while (0) /**@brief Macro for resetting all security status flags for current link. * * @details Macro for resetting all security status flags for current link. */ #define SECURITY_STATUS_RESET() \ do \ { \ m_sec_con_status = SEC_STATUS_INIT_VAL; \ } while (0) /** @} */ /**@brief Verify module's initialization status. * * @details Verify module's initialization status. Returns NRF_INVALID_STATE in case a module API * is called without initializing the module. */ #define VERIFY_MODULE_INITIALIZED() \ do \ { \ if (!m_is_bondmngr_initialized) \ { \ return NRF_ERROR_INVALID_STATE; \ } \ } while(0) /**@brief This structure contains the Bonding Information for one central. */ typedef struct { int32_t central_handle; /**< Central's handle (NOTE: Size is 32 bits just to make struct size dividable by 4). */ ble_gap_evt_auth_status_t auth_status; /**< Central authentication data. */ ble_gap_evt_sec_info_request_t central_id_info; /**< Central identification info. */ ble_gap_addr_t central_addr; /**< Central's address. */ } central_bond_t; STATIC_ASSERT(sizeof(central_bond_t) % 4 == 0); /**@brief This structure contains the System Attributes information related to one central. */ typedef struct { int32_t central_handle; /**< Central's handle (NOTE: Size is 32 bits just to make struct size dividable by 4). */ uint8_t sys_attr[SYS_ATTR_BUFFER_MAX_LEN]; /**< Central sys_attribute data. */ uint32_t sys_attr_size; /**< Central sys_attribute data's size (NOTE: Size is 32 bits just to make struct size dividable by 4). */ } central_sys_attr_t; STATIC_ASSERT(sizeof(central_sys_attr_t) % 4 == 0); /**@brief This structure contains the Bonding Information and System Attributes related to one * central. */ typedef struct { central_bond_t bond; /**< Bonding information. */ central_sys_attr_t sys_attr; /**< System attribute information. */ } central_t; /**@brief This structure contains the whitelisted addresses. */ typedef struct { int8_t central_handle; /**< Central's handle. */ ble_gap_addr_t * p_addr; /**< Pointer to the central's address if BLE_GAP_ADDR_TYPE_PUBLIC. */ } whitelist_addr_t; /**@brief This structure contains the whitelisted IRKs. */ typedef struct { int8_t central_handle; /**< Central's handle. */ ble_gap_irk_t * p_irk; /**< Pointer to the central's irk if available. */ } whitelist_irk_t; static bool m_is_bondmngr_initialized = false; /**< Flag for checking if module has been initialized. */ static ble_bondmngr_init_t m_bondmngr_config; /**< Configuration as specified by the application. */ static uint16_t m_conn_handle; /**< Current connection handle. */ static central_t m_central; /**< Current central data. */ static central_t m_centrals_db[BLE_BONDMNGR_MAX_BONDED_CENTRALS]; /**< Pointer to start of bonded centrals database. */ static uint8_t m_centrals_in_db_count; /**< Number of bonded centrals. */ static whitelist_addr_t m_whitelist_addr[MAX_NUM_CENTRAL_WHITE_LIST]; /**< List of central's addresses for the whitelist. */ static whitelist_irk_t m_whitelist_irk[MAX_NUM_CENTRAL_WHITE_LIST]; /**< List of central's IRKs for the whitelist. */ static uint8_t m_addr_count; /**< Number of addresses in the whitelist. */ static uint8_t m_irk_count; /**< Number of IRKs in the whitelist. */ static uint16_t m_crc_bond_info; /**< Combined CRC for all Bonding Information currently stored in flash. */ static uint16_t m_crc_sys_attr; /**< Combined CRC for all System Attributes currently stored in flash. */ static pstorage_handle_t mp_flash_bond_info; /**< Pointer to flash location to write next Bonding Information. */ static pstorage_handle_t mp_flash_sys_attr; /**< Pointer to flash location to write next System Attribute information. */ static uint8_t m_bond_info_in_flash_count; /**< Number of Bonding Information currently stored in flash. */ static uint8_t m_sys_attr_in_flash_count; /**< Number of System Attributes currently stored in flash. */ static uint8_t m_sec_con_status; /**< Variable to denote security status.*/ static bool m_bond_loaded; /**< Variable to indicate if the bonding information of the currently connected central is available in the RAM.*/ static bool m_sys_attr_loaded; /**< Variable to indicate if the system attribute information of the currently connected central is loaded from the database and set in the S110 SoftDevice.*/ static uint32_t m_bond_crc_array[BLE_BONDMNGR_MAX_BONDED_CENTRALS]; static uint32_t m_sys_crc_array[BLE_BONDMNGR_MAX_BONDED_CENTRALS]; /**@brief Function for extracting the CRC from an encoded 32 bit number that typical resides in * the flash memory * * @param[in] header Header containing CRC and magic number. * @param[out] p_crc Extracted CRC. * * @retval NRF_SUCCESS CRC successfully extracted. * @retval NRF_ERROR_NOT_FOUND Flash seems to be empty. * @retval NRF_ERROR_INVALID_DATA Header does not contain the magic number. */ static uint32_t crc_extract(uint32_t header, uint16_t * p_crc) { if ((header & 0xFFFF0000U) == BOND_MANAGER_DATA_SIGNATURE) { *p_crc = (uint16_t)(header & 0x0000FFFFU); return NRF_SUCCESS; } else if (header == 0xFFFFFFFFU) { return NRF_ERROR_NOT_FOUND; } else { return NRF_ERROR_INVALID_DATA; } } /**@brief Function for storing the Bonding Information of the specified central to the flash. * * @param[in] p_bond Bonding information to be stored. * * @return NRF_SUCCESS on success, an error_code otherwise. */ static uint32_t bond_info_store(central_bond_t * p_bond) { uint32_t err_code; pstorage_handle_t dest_block; // Check if flash is full if (m_bond_info_in_flash_count >= MAX_BONDS_IN_FLASH) { return NRF_ERROR_NO_MEM; } // Check if this is the first bond to be stored if (m_bond_info_in_flash_count == 0) { // Initialize CRC m_crc_bond_info = crc16_compute(NULL, 0, NULL); } // Get block pointer from base err_code = pstorage_block_identifier_get(&mp_flash_bond_info,m_bond_info_in_flash_count,&dest_block); if (err_code != NRF_SUCCESS) { return err_code; } // Write Bonding Information err_code = pstorage_store(&dest_block, (uint8_t *)p_bond, sizeof(central_bond_t), sizeof(uint32_t)); if (err_code != NRF_SUCCESS) { return err_code; } m_crc_bond_info = crc16_compute((uint8_t *)p_bond, sizeof(central_bond_t), &m_crc_bond_info); // Write header m_bond_crc_array[m_bond_info_in_flash_count] = (BOND_MANAGER_DATA_SIGNATURE | m_crc_bond_info); err_code = pstorage_store (&dest_block, (uint8_t *)&m_bond_crc_array[m_bond_info_in_flash_count],sizeof(uint32_t),0); if (err_code != NRF_SUCCESS) { return err_code; } m_bond_info_in_flash_count++; return NRF_SUCCESS; } /**@brief Function for storing the System Attributes related to a specified central in flash. * * @param[in] p_sys_attr System Attributes to be stored. * * @return NRF_SUCCESS on success, an error_code otherwise. */ static uint32_t sys_attr_store(central_sys_attr_t * p_sys_attr) { uint32_t err_code; pstorage_handle_t dest_block; // Check if flash is full. if (m_sys_attr_in_flash_count >= MAX_BONDS_IN_FLASH) { return NRF_ERROR_NO_MEM; } // Check if this is the first time any System Attributes is stored. if (m_sys_attr_in_flash_count == 0) { // Initialize CRC m_crc_sys_attr = crc16_compute(NULL, 0, NULL); } // Get block pointer from base err_code = pstorage_block_identifier_get(&mp_flash_sys_attr,m_sys_attr_in_flash_count,&dest_block); if (err_code != NRF_SUCCESS) { return err_code; } // Write System Attributes in flash. err_code = pstorage_store(&dest_block, (uint8_t *)p_sys_attr, sizeof(central_sys_attr_t), sizeof(uint32_t)); if (err_code != NRF_SUCCESS) { return err_code; } m_crc_sys_attr = crc16_compute((uint8_t *)p_sys_attr, sizeof(central_sys_attr_t), &m_crc_sys_attr); // Write header. m_sys_crc_array[m_sys_attr_in_flash_count] = (BOND_MANAGER_DATA_SIGNATURE | m_crc_sys_attr); err_code = pstorage_store (&dest_block, (uint8_t *)&m_sys_crc_array[m_sys_attr_in_flash_count], sizeof(uint32_t), 0); if (err_code != NRF_SUCCESS) { return err_code; } m_sys_attr_in_flash_count++; return NRF_SUCCESS; } /**@brief Function for loading the Bonding Information of one central from flash. * * @param[out] p_bond Loaded Bonding Information. * * @return NRF_SUCCESS on success, otherwise an error code. */ static uint32_t bonding_info_load_from_flash(central_bond_t * p_bond) { pstorage_handle_t source_block; uint32_t err_code; uint32_t crc; uint16_t crc_header; // Check if this is the first bond to be loaded, in which case the // m_bond_info_in_flash_count variable would have the intial value 0. if (m_bond_info_in_flash_count == 0) { // Initialize CRC. m_crc_bond_info = crc16_compute(NULL, 0, NULL); } // Get block pointer from base err_code = pstorage_block_identifier_get(&mp_flash_bond_info, m_bond_info_in_flash_count, &source_block); if (err_code != NRF_SUCCESS) { return err_code; } err_code = pstorage_load((uint8_t *)&crc, &source_block, sizeof(uint32_t), 0); if (err_code != NRF_SUCCESS) { return err_code; } // Extract CRC from header. err_code = crc_extract(crc, &crc_header); if (err_code != NRF_SUCCESS) { return err_code; } // Load central. err_code = pstorage_load((uint8_t *)p_bond, &source_block, sizeof(central_bond_t), sizeof(uint32_t)); if (err_code != NRF_SUCCESS) { return err_code; } // Check CRC. m_crc_bond_info = crc16_compute((uint8_t *)p_bond, sizeof(central_bond_t), &m_crc_bond_info); if (m_crc_bond_info == crc_header) { m_bond_info_in_flash_count++; return NRF_SUCCESS; } else { return NRF_ERROR_INVALID_DATA; } } /**@brief Function for loading the System Attributes related to one central from flash. * * @param[out] p_sys_attr Loaded System Attributes. * * @return NRF_SUCCESS on success, otherwise an error code. */ static uint32_t sys_attr_load_from_flash(central_sys_attr_t * p_sys_attr) { pstorage_handle_t source_block; uint32_t err_code; uint32_t crc; uint16_t crc_header; // Check if this is the first time System Attributes is loaded from flash, in which case the // m_sys_attr_in_flash_count variable would have the initial value 0. if (m_sys_attr_in_flash_count == 0) { // Initialize CRC. m_crc_sys_attr = crc16_compute(NULL, 0, NULL); } // Get block pointer from base err_code = pstorage_block_identifier_get(&mp_flash_sys_attr, m_sys_attr_in_flash_count, &source_block); if (err_code != NRF_SUCCESS) { return err_code; } err_code = pstorage_load((uint8_t *)&crc, &source_block, sizeof(uint32_t), 0); if (err_code != NRF_SUCCESS) { return err_code; } // Extract CRC from header. err_code = crc_extract(crc, &crc_header); if (err_code != NRF_SUCCESS) { return err_code; } err_code = pstorage_load((uint8_t *)p_sys_attr, &source_block, sizeof(central_sys_attr_t), sizeof(uint32_t)); if (err_code != NRF_SUCCESS) { return err_code; } // Check CRC. m_crc_sys_attr = crc16_compute((uint8_t *)p_sys_attr, sizeof(central_sys_attr_t), &m_crc_sys_attr); if (m_crc_sys_attr == crc_header) { m_sys_attr_in_flash_count++; return NRF_SUCCESS; } else { return NRF_ERROR_INVALID_DATA; } } /**@brief Function for erasing the flash pages that contain Bonding Information and System * Attributes. * * @return NRF_SUCCESS on success, otherwise an error code. */ static uint32_t flash_pages_erase(void) { uint32_t err_code; err_code = pstorage_clear(&mp_flash_bond_info, MAX_BONDS_IN_FLASH); if (err_code == NRF_SUCCESS) { err_code = pstorage_clear(&mp_flash_sys_attr, MAX_BONDS_IN_FLASH); } return err_code; } /**@brief Function for checking if Bonding Information in RAM is different from that in * flash. * * @return TRUE if Bonding Information in flash and RAM are different, FALSE otherwise. */ static bool bond_info_changed(void) { int i; uint16_t crc = crc16_compute(NULL, 0, NULL); // Compute CRC for all bonds in database. for (i = 0; i < m_centrals_in_db_count; i++) { crc = crc16_compute((uint8_t *)&m_centrals_db[i].bond, sizeof(central_bond_t), &crc); } // Compare the computed CRS to CRC stored in flash. return (crc != m_crc_bond_info); } /**@brief Function for checking if System Attributes in RAM is different from that in flash. * * @return TRUE if System Attributes in flash and RAM are different, FALSE otherwise. */ static bool sys_attr_changed(void) { int i; uint16_t crc = crc16_compute(NULL, 0, NULL); // Compute CRC for all System Attributes in database. for (i = 0; i < m_centrals_in_db_count; i++) { crc = crc16_compute((uint8_t *)&m_centrals_db[i].sys_attr, sizeof(central_sys_attr_t), &crc); } // Compare the CRC of System Attributes in flash with that of the System Attributes in memory. return (crc != m_crc_sys_attr); } /**@brief Function for setting the System Attributes for specified central to the SoftDevice, or * clearing the System Attributes if central is a previously unknown. * * @param[in] p_central Central for which the System Attributes is to be set. * * @return NRF_SUCCESS on success, otherwise an error code. */ static uint32_t central_sys_attr_set(central_t * p_central) { uint8_t * p_sys_attr; if (m_central.sys_attr.sys_attr_size != 0) { if (m_central.sys_attr.sys_attr_size > SYS_ATTR_BUFFER_MAX_LEN) { return NRF_ERROR_INTERNAL; } p_sys_attr = m_central.sys_attr.sys_attr; } else { p_sys_attr = NULL; } return sd_ble_gatts_sys_attr_set(m_conn_handle, p_sys_attr, m_central.sys_attr.sys_attr_size); } /**@brief Function for updating the whitelist data structures. */ static void update_whitelist(void) { int i; for (i = 0, m_addr_count = 0, m_irk_count = 0; i < m_centrals_in_db_count; i++) { central_bond_t * p_bond = &m_centrals_db[i].bond; if (p_bond->auth_status.central_kex.irk) { m_whitelist_irk[m_irk_count].central_handle = p_bond->central_handle; m_whitelist_irk[m_irk_count].p_irk = &(p_bond->auth_status.central_keys.irk); m_irk_count++; } if (p_bond->central_addr.addr_type != BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE) { m_whitelist_addr[m_addr_count].central_handle = p_bond->central_handle; m_whitelist_addr[m_addr_count].p_addr = &(p_bond->central_addr); m_addr_count++; } } } /**@brief Function for handling the authentication status event related to a new central. * * @details This function adds the new central to the database and stores the central's Bonding * Information to flash. It also notifies the application when the new bond is created, * and sets the System Attributes to prepare the stack for connection with the new * central. * * @param[in] p_auth_status New authentication status. * * @return NRF_SUCCESS on success, otherwise an error code. */ static uint32_t on_auth_status_from_new_central(ble_gap_evt_auth_status_t * p_auth_status) { uint32_t err_code; if (m_centrals_in_db_count >= BLE_BONDMNGR_MAX_BONDED_CENTRALS) { return NRF_ERROR_NO_MEM; } // Update central. m_central.bond.auth_status = *p_auth_status; m_central.bond.central_id_info.div = p_auth_status->periph_keys.enc_info.div; m_central.sys_attr.sys_attr_size = 0; // Add new central to database. m_central.bond.central_handle = m_centrals_in_db_count; m_centrals_db[m_centrals_in_db_count++] = m_central; update_whitelist(); m_bond_loaded = true; // Clear System Attributes. err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0); if (err_code != NRF_SUCCESS) { return err_code; } // Write new central's Bonding Information to flash. err_code = bond_info_store(&m_central.bond); if ((err_code == NRF_ERROR_NO_MEM) && (m_bondmngr_config.evt_handler != NULL)) { ble_bondmngr_evt_t evt; evt.evt_type = BLE_BONDMNGR_EVT_BOND_FLASH_FULL; evt.central_handle = m_central.bond.central_handle; evt.central_id = m_central.bond.central_id_info.div; m_bondmngr_config.evt_handler(&evt); } else if (err_code != NRF_SUCCESS) { return err_code; } // Pass the event to application. if (m_bondmngr_config.evt_handler != NULL) { ble_bondmngr_evt_t evt; evt.evt_type = BLE_BONDMNGR_EVT_NEW_BOND; evt.central_handle = m_central.bond.central_handle; evt.central_id = m_central.bond.central_id_info.div; m_bondmngr_config.evt_handler(&evt); } return NRF_SUCCESS; } /**@brief Function for updating the current central's entry in the database. */ static uint32_t central_update(void) { uint32_t err_code; int32_t central_handle = m_central.bond.central_handle; if ((central_handle >= 0) && (central_handle < m_centrals_in_db_count)) { // Update the database based on whether the bond and system attributes have // been loaded or not to avoid overwriting information that was not used in the // connection session. if (m_bond_loaded) { m_centrals_db[central_handle].bond = m_central.bond; } if (m_sys_attr_loaded) { m_centrals_db[central_handle].sys_attr = m_central.sys_attr; } update_whitelist(); err_code = NRF_SUCCESS; } else { err_code = NRF_ERROR_INTERNAL; } return err_code; } /**@brief Function for searching for the central in the database of known centrals. * * @details If the central is found, the variable m_central will be populated with all the * information (Bonding Information and System Attributes) related to that central. * * @param[in] central_id Central Identifier. * @return NRF_SUCCESS on success, otherwise an error code. */ static uint32_t central_find_in_db(uint16_t central_id) { int i; for (i = 0; i < m_centrals_in_db_count; i++) { if (central_id == m_centrals_db[i].bond.central_id_info.div) { m_central = m_centrals_db[i]; return NRF_SUCCESS; } } return NRF_ERROR_NOT_FOUND; } /**@brief Function for loading all Bonding Information and System Attributes from flash. * * @return NRF_SUCCESS on success, otherwise an error code. */ static uint32_t load_all_from_flash(void) { uint32_t err_code; int i; m_centrals_in_db_count = 0; while (m_centrals_in_db_count < BLE_BONDMNGR_MAX_BONDED_CENTRALS) { central_bond_t central_bond_info; int central_handle; // Load Bonding Information. err_code = bonding_info_load_from_flash(&central_bond_info); if (err_code == NRF_ERROR_NOT_FOUND) { // No more bonds in flash. break; } else if (err_code != NRF_SUCCESS) { return err_code; } central_handle = central_bond_info.central_handle; if (central_handle > m_centrals_in_db_count) { // Central handle value(s) missing in flash. This should never happen. return NRF_ERROR_INVALID_DATA; } else { // Add/update Bonding Information in central array. m_centrals_db[central_handle].bond = central_bond_info; if (central_handle == m_centrals_in_db_count) { // New central handle, clear System Attributes. m_centrals_db[central_handle].sys_attr.sys_attr_size = 0; m_centrals_db[central_handle].sys_attr.central_handle = INVALID_CENTRAL_HANDLE; m_centrals_in_db_count++; } else { // Entry was updated, do nothing. } } } // Load System Attributes for all previously known centrals. for (i = 0; i < m_centrals_in_db_count; i++) { central_sys_attr_t central_sys_attr; // Load System Attributes. err_code = sys_attr_load_from_flash(&central_sys_attr); if (err_code == NRF_ERROR_NOT_FOUND) { // No more System Attributes in flash. break; } else if (err_code != NRF_SUCCESS) { return err_code; } if (central_sys_attr.central_handle > m_centrals_in_db_count) { // Central handle value(s) missing in flash. This should never happen. return NRF_ERROR_INVALID_DATA; } else { // Add/update Bonding Information in central array. m_centrals_db[central_sys_attr.central_handle].sys_attr = central_sys_attr; } } // Initialize the remaining empty bond entries in the memory. for (i = m_centrals_in_db_count; i < BLE_BONDMNGR_MAX_BONDED_CENTRALS; i++) { m_centrals_db[i].bond.central_handle = INVALID_CENTRAL_HANDLE; m_centrals_db[i].sys_attr.sys_attr_size = 0; m_centrals_db[i].sys_attr.central_handle = INVALID_CENTRAL_HANDLE; } // Update whitelist data structures. update_whitelist(); return NRF_SUCCESS; } /**@brief Function for handling the connected event received from the BLE stack. * * @param[in] p_ble_evt Event received from the BLE stack. */ static void on_connect(ble_evt_t * p_ble_evt) { m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle; m_central.bond.central_handle = INVALID_CENTRAL_HANDLE; m_central.bond.central_addr = p_ble_evt->evt.gap_evt.params.connected.peer_addr; m_central.sys_attr.sys_attr_size = 0; if (p_ble_evt->evt.gap_evt.params.connected.irk_match) { uint8_t irk_idx = p_ble_evt->evt.gap_evt.params.connected.irk_match_idx; if ((irk_idx >= MAX_NUM_CENTRAL_WHITE_LIST) || (m_whitelist_irk[irk_idx].central_handle >= BLE_BONDMNGR_MAX_BONDED_CENTRALS)) { m_bondmngr_config.error_handler(NRF_ERROR_INTERNAL); } else { m_central = m_centrals_db[m_whitelist_irk[irk_idx].central_handle]; } } else { int i; for (i = 0; i < m_addr_count; i++) { ble_gap_addr_t * p_cur_addr = m_whitelist_addr[i].p_addr; if (memcmp(p_cur_addr->addr, m_central.bond.central_addr.addr, BLE_GAP_ADDR_LEN) == 0) { m_central = m_centrals_db[m_whitelist_addr[i].central_handle]; break; } } } if (m_central.bond.central_handle != INVALID_CENTRAL_HANDLE) { // Reset bond and system attributes loaded variables. m_bond_loaded = false; m_sys_attr_loaded = false; // Do not set the system attributes of the central on connection. if (m_bondmngr_config.evt_handler != NULL) { ble_bondmngr_evt_t evt; evt.evt_type = BLE_BONDMNGR_EVT_CONN_TO_BONDED_CENTRAL; evt.central_handle = m_central.bond.central_handle; evt.central_id = m_central.bond.central_id_info.div; m_bondmngr_config.evt_handler(&evt); } } } /**@brief Function for handling the 'System Attributes Missing' event received from the * SoftDevice. * * @param[in] p_ble_evt Event received from the BLE stack. */ static void on_sys_attr_missing(ble_evt_t * p_ble_evt) { uint32_t err_code; if ( (m_central.bond.central_handle == INVALID_CENTRAL_HANDLE) || !ENCRYPTION_STATUS_GET() || BONDING_IN_PROGRESS_STATUS_GET() ) { err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0); } else { // Current central is valid, use its data. Set the corresponding sys_attr. err_code = central_sys_attr_set(&m_central); if (err_code == NRF_SUCCESS) { // Set System Attributes loaded status variable. m_sys_attr_loaded = true; } } if (err_code != NRF_SUCCESS) { m_bondmngr_config.error_handler(err_code); } } /**@brief Function for handling the new authentication status event, received from the * SoftDevice, related to an already bonded central. * * @details This function also writes the updated Bonding Information to flash and notifies the * application. * * @param[in] p_auth_status Updated authentication status. */ static void auth_status_update(ble_gap_evt_auth_status_t * p_auth_status) { uint32_t err_code; // Authentication status changed, update Bonding Information. m_central.bond.auth_status = *p_auth_status; m_central.bond.central_id_info.div = p_auth_status->periph_keys.enc_info.div; memset(&(m_centrals_db[m_central.bond.central_handle]), 0, sizeof(central_t)); m_centrals_db[m_central.bond.central_handle] = m_central; // Write updated Bonding Information to flash. err_code = bond_info_store(&m_central.bond); if ((err_code == NRF_ERROR_NO_MEM) && (m_bondmngr_config.evt_handler != NULL)) { ble_bondmngr_evt_t evt; evt.evt_type = BLE_BONDMNGR_EVT_BOND_FLASH_FULL; evt.central_handle = m_central.bond.central_handle; evt.central_id = m_central.bond.central_id_info.div; m_bondmngr_config.evt_handler(&evt); } else if (err_code != NRF_SUCCESS) { m_bondmngr_config.error_handler(err_code); } // Pass the event to the application. if (m_bondmngr_config.evt_handler != NULL) { ble_bondmngr_evt_t evt; evt.evt_type = BLE_BONDMNGR_EVT_AUTH_STATUS_UPDATED; evt.central_handle = m_central.bond.central_handle; evt.central_id = m_central.bond.central_id_info.div; m_bondmngr_config.evt_handler(&evt); } } /**@brief Function for handling the Authentication Status event received from the BLE stack. * * @param[in] p_ble_evt Event received from the BLE stack. */ static void on_auth_status(ble_gap_evt_auth_status_t * p_auth_status) { if (p_auth_status->auth_status != BLE_GAP_SEC_STATUS_SUCCESS) { return; } // Verify if its pairing and not bonding if (!ENCRYPTION_STATUS_GET()) { return; } if (m_central.bond.central_handle == INVALID_CENTRAL_HANDLE) { uint32_t err_code = central_find_in_db(p_auth_status->periph_keys.enc_info.div); if (err_code == NRF_SUCCESS) { // Possible DIV Collision indicate error to application, // not storing the new LTK err_code = NRF_ERROR_FORBIDDEN; } else { // Add the new device to data base err_code = on_auth_status_from_new_central(p_auth_status); } if (err_code != NRF_SUCCESS) { m_bondmngr_config.error_handler(err_code); } } else { m_bond_loaded = true; // Receiving a auth status again when already in have existing information! auth_status_update(p_auth_status); } } /**@brief Function for handling the Security Info Request event received from the BLE stack. * * @param[in] p_ble_evt Event received from the BLE stack. */ static void on_sec_info_request(ble_evt_t * p_ble_evt) { uint32_t err_code; err_code = central_find_in_db(p_ble_evt->evt.gap_evt.params.sec_info_request.div); if (err_code == NRF_SUCCESS) { // Bond information has been found and loaded for security procedures. Reflect this in the // status variable m_bond_loaded = true; // Central found in the list of bonded central. Use the encryption info for this central. err_code = sd_ble_gap_sec_info_reply(m_conn_handle, &m_central.bond.auth_status.periph_keys.enc_info, NULL); if (err_code != NRF_SUCCESS) { m_bondmngr_config.error_handler(err_code); } // Do not set the sys_attr yet, should be set only when sec_update is successful. } else if (err_code == NRF_ERROR_NOT_FOUND) { m_central.bond.central_id_info = p_ble_evt->evt.gap_evt.params.sec_info_request; // New central. err_code = sd_ble_gap_sec_info_reply(m_conn_handle, NULL, NULL); if (err_code != NRF_SUCCESS) { m_bondmngr_config.error_handler(err_code); } // Initialize the sys_attr. err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0); } if (err_code != NRF_SUCCESS) { m_bondmngr_config.error_handler(err_code); } } /**@brief Function for handling the Connection Security Update event received from the BLE * stack. * * @param[in] p_ble_evt Event received from the BLE stack. */ static void on_sec_update(ble_gap_evt_conn_sec_update_t * p_sec_update) { uint8_t security_mode = p_sec_update->conn_sec.sec_mode.sm; uint8_t security_level = p_sec_update->conn_sec.sec_mode.lv; if (((security_mode == 1) && (security_level > 1)) || ((security_mode == 2) && (security_level != 0))) { ENCRYPTION_STATUS_SET(); uint32_t err_code = central_sys_attr_set(&m_central); if (err_code != NRF_SUCCESS) { m_bondmngr_config.error_handler(err_code); } else { m_sys_attr_loaded = true; } if (m_bondmngr_config.evt_handler != NULL) { ble_bondmngr_evt_t evt; evt.evt_type = BLE_BONDMNGR_EVT_ENCRYPTED; evt.central_handle = m_central.bond.central_handle; evt.central_id = m_central.bond.central_id_info.div; m_bondmngr_config.evt_handler(&evt); } } } /**@brief Function for handling the Connection Security Parameters Request event received from * the BLE stack. * * @param[in] p_ble_evt Event received from the BLE stack. */ static void on_sec_param_request(ble_gap_evt_sec_params_request_t * p_sec_update) { if (p_sec_update->peer_params.bond) { BONDING_IN_PROGRESS_STATUS_SET(); if (m_central.bond.central_handle != INVALID_CENTRAL_HANDLE) { // Bonding request received from a bonded central, make all system attributes null m_central.sys_attr.sys_attr_size = 0; memset(m_central.sys_attr.sys_attr, 0, SYS_ATTR_BUFFER_MAX_LEN); } } } void ble_bondmngr_on_ble_evt(ble_evt_t * p_ble_evt) { if (!m_is_bondmngr_initialized) { m_bondmngr_config.error_handler(NRF_ERROR_INVALID_STATE); } switch (p_ble_evt->header.evt_id) { case BLE_GAP_EVT_CONNECTED: on_connect(p_ble_evt); break; // NOTE: All actions to be taken on the Disconnected event are performed in // ble_bondmngr_bonded_centrals_store(). This function must be called from the // Disconnected handler of the application before advertising is restarted (to make // sure the flash blocks are cleared while the radio is inactive). case BLE_GAP_EVT_DISCONNECTED: SECURITY_STATUS_RESET(); break; case BLE_GATTS_EVT_SYS_ATTR_MISSING: on_sys_attr_missing(p_ble_evt); break; case BLE_GAP_EVT_AUTH_STATUS: on_auth_status(&p_ble_evt->evt.gap_evt.params.auth_status); break; case BLE_GAP_EVT_SEC_INFO_REQUEST: on_sec_info_request(p_ble_evt); break; case BLE_GAP_EVT_SEC_PARAMS_REQUEST: on_sec_param_request(&p_ble_evt->evt.gap_evt.params.sec_params_request); break; case BLE_GAP_EVT_CONN_SEC_UPDATE: on_sec_update(&p_ble_evt->evt.gap_evt.params.conn_sec_update); break; default: // No implementation needed. break; } } uint32_t ble_bondmngr_bonded_centrals_store(void) { uint32_t err_code; int i; VERIFY_MODULE_INITIALIZED(); if (m_central.bond.central_handle != INVALID_CENTRAL_HANDLE) { // Fetch System Attributes from stack. uint16_t sys_attr_size = SYS_ATTR_BUFFER_MAX_LEN; err_code = sd_ble_gatts_sys_attr_get(m_conn_handle, m_central.sys_attr.sys_attr, &sys_attr_size); if (err_code != NRF_SUCCESS) { return err_code; } m_central.sys_attr.central_handle = m_central.bond.central_handle; m_central.sys_attr.sys_attr_size = (uint16_t)sys_attr_size; // Update the current central. err_code = central_update(); if (err_code != NRF_SUCCESS) { return err_code; } } // Save Bonding Information if changed. if (bond_info_changed()) { // Erase flash page. err_code = pstorage_clear(&mp_flash_bond_info,MAX_BONDS_IN_FLASH); if (err_code != NRF_SUCCESS) { return err_code; } // Store bond information for all centrals. m_bond_info_in_flash_count = 0; for (i = 0; i < m_centrals_in_db_count; i++) { err_code = bond_info_store(&m_centrals_db[i].bond); if (err_code != NRF_SUCCESS) { return err_code; } } } // Save System Attributes, if changed. if (sys_attr_changed()) { // Erase flash page. err_code = pstorage_clear(&mp_flash_sys_attr, MAX_BONDS_IN_FLASH); if (err_code != NRF_SUCCESS) { return err_code; } // Store System Attributes for all centrals. m_sys_attr_in_flash_count = 0; for (i = 0; i < m_centrals_in_db_count; i++) { err_code = sys_attr_store(&m_centrals_db[i].sys_attr); if (err_code != NRF_SUCCESS) { return err_code; } } } m_conn_handle = BLE_CONN_HANDLE_INVALID; m_central.bond.central_handle = INVALID_CENTRAL_HANDLE; m_central.sys_attr.central_handle = INVALID_CENTRAL_HANDLE; m_central.sys_attr.sys_attr_size = 0; m_bond_loaded = false; m_sys_attr_loaded = false; return NRF_SUCCESS; } uint32_t ble_bondmngr_sys_attr_store(void) { uint32_t err_code; if (m_central.sys_attr.sys_attr_size == 0) { // Connected to new central. So the flash block for System Attributes for this // central is empty. Hence no erase is needed. uint16_t sys_attr_size = SYS_ATTR_BUFFER_MAX_LEN; // Fetch System Attributes from stack. err_code = sd_ble_gatts_sys_attr_get(m_conn_handle, m_central.sys_attr.sys_attr, &sys_attr_size); if (err_code != NRF_SUCCESS) { return err_code; } m_central.sys_attr.central_handle = m_central.bond.central_handle; m_central.sys_attr.sys_attr_size = (uint16_t)sys_attr_size; // Copy the System Attributes to database. m_centrals_db[m_central.bond.central_handle].sys_attr = m_central.sys_attr; // Write new central's System Attributes to flash. return (sys_attr_store(&m_central.sys_attr)); } else { // Will not write to flash because System Attributes of an old central would already be // in flash and so this operation needs a flash erase operation. return NRF_ERROR_INVALID_STATE; } } uint32_t ble_bondmngr_bonded_centrals_delete(void) { VERIFY_MODULE_INITIALIZED(); m_centrals_in_db_count = 0; m_bond_info_in_flash_count = 0; m_sys_attr_in_flash_count = 0; return flash_pages_erase(); } uint32_t ble_bondmngr_central_addr_get(int8_t central_handle, ble_gap_addr_t * p_central_addr) { if ( (central_handle == INVALID_CENTRAL_HANDLE) || (central_handle >= m_centrals_in_db_count) || (p_central_addr == NULL) || ( m_centrals_db[central_handle].bond.central_addr.addr_type == BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE ) ) { return NRF_ERROR_INVALID_PARAM; } *p_central_addr = m_centrals_db[central_handle].bond.central_addr; return NRF_SUCCESS; } uint32_t ble_bondmngr_whitelist_get(ble_gap_whitelist_t * p_whitelist) { static ble_gap_addr_t * s_addr[MAX_NUM_CENTRAL_WHITE_LIST]; static ble_gap_irk_t * s_irk[MAX_NUM_CENTRAL_WHITE_LIST]; int i; for (i = 0; i < m_irk_count; i++) { s_irk[i] = m_whitelist_irk[i].p_irk; } for (i = 0; i < m_addr_count; i++) { s_addr[i] = m_whitelist_addr[i].p_addr; } p_whitelist->addr_count = m_addr_count; p_whitelist->pp_addrs = (m_addr_count != 0) ? s_addr : NULL; p_whitelist->irk_count = m_irk_count; p_whitelist->pp_irks = (m_irk_count != 0) ? s_irk : NULL; return NRF_SUCCESS; } static void bm_pstorage_cb_handler(pstorage_handle_t * handle, uint8_t op_code, uint32_t result, uint8_t * p_data, uint32_t data_len) { if (result != NRF_SUCCESS) { m_bondmngr_config.error_handler(result); } } uint32_t ble_bondmngr_init(ble_bondmngr_init_t * p_init) { pstorage_module_param_t param; uint32_t err_code; if (p_init->error_handler == NULL) { return NRF_ERROR_INVALID_PARAM; } if (BLE_BONDMNGR_MAX_BONDED_CENTRALS > MAX_BONDS_IN_FLASH) { return NRF_ERROR_DATA_SIZE; } param.block_size = sizeof (central_bond_t) + sizeof (uint32_t); param.block_count = MAX_BONDS_IN_FLASH; param.cb = bm_pstorage_cb_handler; // Blocks are requested twice, once for bond information and once for system attributes. // The number of blocks requested has to be the maximum number of bonded devices that // need to be supported. However, the size of blocks can be different if the sizes of // system attributes and bonds are not too close. err_code = pstorage_register(&param, &mp_flash_bond_info); if (err_code != NRF_SUCCESS) { return err_code; } param.block_size = sizeof(central_sys_attr_t) + sizeof(uint32_t); err_code = pstorage_register(&param, &mp_flash_sys_attr); if (err_code != NRF_SUCCESS) { return err_code; } m_bondmngr_config = *p_init; memset(&m_central, 0, sizeof(central_t)); m_central.bond.central_handle = INVALID_CENTRAL_HANDLE; m_conn_handle = BLE_CONN_HANDLE_INVALID; m_centrals_in_db_count = 0; m_bond_info_in_flash_count = 0; m_sys_attr_in_flash_count = 0; SECURITY_STATUS_RESET(); // Erase all stored centrals if specified. if (m_bondmngr_config.bonds_delete) { err_code = flash_pages_erase(); if (err_code != NRF_SUCCESS) { return err_code; } m_centrals_in_db_count = 0; int i; for (i = m_centrals_in_db_count; i < BLE_BONDMNGR_MAX_BONDED_CENTRALS; i++) { m_centrals_db[i].bond.central_handle = INVALID_CENTRAL_HANDLE; m_centrals_db[i].sys_attr.sys_attr_size = 0; m_centrals_db[i].sys_attr.central_handle = INVALID_CENTRAL_HANDLE; } } else { // Load bond manager data from flash. err_code = load_all_from_flash(); if (err_code != NRF_SUCCESS) { return err_code; } } m_is_bondmngr_initialized = true; return NRF_SUCCESS; } uint32_t ble_bondmngr_central_ids_get(uint16_t * p_central_ids, uint16_t * p_length) { VERIFY_MODULE_INITIALIZED(); int i; if (p_length == NULL) { return NRF_ERROR_NULL; } if (*p_length < m_centrals_in_db_count) { // Length of the input array is not enough to fit all known central identifiers. return NRF_ERROR_DATA_SIZE; } *p_length = m_centrals_in_db_count; if (p_central_ids == NULL) { // Only the length field was required to be filled. return NRF_SUCCESS; } for (i = 0; i < m_centrals_in_db_count; i++) { p_central_ids[i] = m_centrals_db[i].bond.central_id_info.div; } return NRF_SUCCESS; } uint32_t ble_bondmngr_bonded_central_delete(uint16_t central_id) { VERIFY_MODULE_INITIALIZED(); int8_t central_handle_to_be_deleted = INVALID_CENTRAL_HANDLE; uint8_t i; // Search for the handle of the central. for (i = 0; i < m_centrals_in_db_count; i++) { if (m_centrals_db[i].bond.central_id_info.div == central_id) { central_handle_to_be_deleted = i; break; } } if (central_handle_to_be_deleted == INVALID_CENTRAL_HANDLE) { // Central ID not found. return NRF_ERROR_NOT_FOUND; } // Delete the central in RAM. for (i = central_handle_to_be_deleted; i < (m_centrals_in_db_count - 1); i++) { // Overwrite the current central entry with the next one. m_centrals_db[i] = m_centrals_db[i + 1]; // Decrement the value of handle. m_centrals_db[i].bond.central_handle--; if (INVALID_CENTRAL_HANDLE != m_centrals_db[i].sys_attr.central_handle) { m_centrals_db[i].sys_attr.central_handle--; } } // Clear the last database entry. memset(&(m_centrals_db[m_centrals_in_db_count - 1]), 0, sizeof(central_t)); m_centrals_in_db_count--; uint32_t err_code; // Reinitialize the pointers to the memory where bonding info and System Attributes are stored // in flash. // Refresh the data in the flash memory (both Bonding Information and System Attributes). // Erase and rewrite bonding info and System Attributes. err_code = flash_pages_erase(); if (err_code != NRF_SUCCESS) { return err_code; } m_bond_info_in_flash_count = 0; m_sys_attr_in_flash_count = 0; for (i = 0; i < m_centrals_in_db_count; i++) { err_code = bond_info_store(&(m_centrals_db[i].bond)); if (err_code != NRF_SUCCESS) { return err_code; } } for (i = 0; i < m_centrals_in_db_count; i++) { err_code = sys_attr_store(&(m_centrals_db[i].sys_attr)); if (err_code != NRF_SUCCESS) { return err_code; } } update_whitelist(); return NRF_SUCCESS; } uint32_t ble_bondmngr_is_link_encrypted (bool * status) { VERIFY_MODULE_INITIALIZED(); (*status) = ENCRYPTION_STATUS_GET(); return NRF_SUCCESS; }
33.175549
234
0.594349
2697c546ea3da0d71d51f7cd8512991e28feccbc
646
cpp
C++
src/215.kth_largest_element_in_an_array/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
1
2016-07-02T17:44:10.000Z
2016-07-02T17:44:10.000Z
src/215.kth_largest_element_in_an_array/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
null
null
null
src/215.kth_largest_element_in_an_array/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
1
2019-12-21T04:57:15.000Z
2019-12-21T04:57:15.000Z
class Solution { public: int findKthLargest(vector<int>& nums, int k) { int left = 0, right = nums.size() - 1; while (left < right) { int pivot = nums[left]; int i = left, j = right; while (i < j) { while (i < j && nums[j] < pivot) j--; nums[i] = nums[j]; while (i < j && nums[i] >= pivot) i++; nums[j] = nums[i]; } nums[i] = pivot; if (i == k - 1) return nums[i]; else if (i < k - 1) left = i + 1; else right = i - 1; } return nums[k - 1]; } };
29.363636
54
0.380805
269b575a872832cd67ba16173326f301c9046e39
4,527
cc
C++
modules/kernel/arch/x86_64/scheduler-arch.cc
eryjus/centuryos2
526a39c0f434b29a43d85e6b5b1ffa1ced885b25
[ "BSD-3-Clause" ]
null
null
null
modules/kernel/arch/x86_64/scheduler-arch.cc
eryjus/centuryos2
526a39c0f434b29a43d85e6b5b1ffa1ced885b25
[ "BSD-3-Clause" ]
null
null
null
modules/kernel/arch/x86_64/scheduler-arch.cc
eryjus/centuryos2
526a39c0f434b29a43d85e6b5b1ffa1ced885b25
[ "BSD-3-Clause" ]
null
null
null
//=================================================================================================================== // // scheduler-arch.cc -- Architecture-specific functions elements for the process // // Copyright (c) 2021 -- Adam Clark // Licensed under "THE BEER-WARE LICENSE" // See License.md for details. // // ------------------------------------------------------------------------------------------------------------------ // // Date Tracker Version Pgmr Description // ----------- ------- ------- ---- --------------------------------------------------------------------------- // 2021-May-26 Initial v0.0.9b ADCL Initial version // //=================================================================================================================== #include "types.h" #include "stacks.h" #include "kernel-funcs.h" #include "heap.h" #include "scheduler.h" // // -- This is the lock to get permission to map the stack for initialization // ---------------------------------------------------------------------- Spinlock_t mmuStackInitLock = {0}; // // -- build the stack needed to start a new process // --------------------------------------------- void ProcessNewStack(Process_t *proc, Addr_t startingAddr) { Addr_t *stack; Frame_t *stackFrames = NULL; const size_t frameCount = STACK_SIZE / PAGE_SIZE; KernelPrintf("Creating a new Process stack\n"); KernelPrintf(".. allocating frames for the stack\n"); stackFrames = (Frame_t *)HeapAlloc(sizeof (Frame_t *) * frameCount, false); assert_msg(stackFrames != NULL, "HeapAlloc() ran out of memory allocating stack frames!"); KernelPrintf(".. Temporary Stack Frames are located at %p\n", stackFrames); for (int i = 0; i < frameCount; i ++) { KernelPrintf(".. allocating stack frame %d of %d\n", i + 1, frameCount); stackFrames[i] = PmmAlloc(); } KernelPrintf(".. Locking the stack build spinlock\n"); Addr_t flags = DisableInt(); SpinLock(&mmuStackInitLock); { KernelPrintf(".. Mapping the stack to the temporary build address\n"); for (int i = 0; i < frameCount; i ++) { MmuMapPage(MMU_STACK_INIT_VADDR + (PAGE_SIZE * i), stackFrames[i], PG_WRT); } KernelPrintf(".. Building the stack contents\n"); stack = (Addr_t *)(MMU_STACK_INIT_VADDR + STACK_SIZE); *--stack = (Addr_t)ProcessEnd; // -- just in case, we will self-terminate *--stack = startingAddr; // -- this is the process starting point *--stack = (Addr_t)ProcessStart; // -- initialize a new process *--stack = 0; // -- rax *--stack = 0; // -- rbx *--stack = 0; // -- rcx *--stack = 0; // -- rdx *--stack = 0; // -- rsi *--stack = 0; // -- rdi *--stack = 0; // -- rbp *--stack = 0; // -- r8 *--stack = 0; // -- r9 *--stack = 0; // -- r10 *--stack = 0; // -- r11 *--stack = 0; // -- r12 *--stack = 0; // -- r13 *--stack = 0; // -- r14 *--stack = 0; // -- r15 KernelPrintf(".. Unmapping the stack from temporary address space\n"); for (int i = 0; i < frameCount; i ++) { MmuUnmapPage(MMU_STACK_INIT_VADDR + (PAGE_SIZE * i)); } KernelPrintf(".. Unlocking the spinlock\n"); SpinUnlock(&mmuStackInitLock); RestoreInt(flags); } KernelPrintf(".. Finding a stack address\n"); Addr_t stackLoc = StackFind(); // get a new stack assert(stackLoc != 0); proc->tosProcessSwap = ((Addr_t)stack - MMU_STACK_INIT_VADDR) + stackLoc; KernelPrintf("Mapping the stack into address space %p\n", GetAddressSpace()); for (int i = 0; i < frameCount; i ++) { KernelPrintf(".. in space %p: frame %d (%p to %p)\n", proc->virtAddrSpace, i, stackLoc + (PAGE_SIZE * i), stackFrames[i]); MmuMapPageEx(proc->virtAddrSpace, stackLoc + (PAGE_SIZE * i), stackFrames[i], PG_WRT); KernelPrintf(".. page mapped in the other address space\n"); } HeapFree(stackFrames); }
41.53211
117
0.456815
269d05c443de786d7da37be9593012adcfb37aa9
828
cpp
C++
Regression_test/examples/threshold/src/threshold.cpp
minseongg/dynamatic
268d97690f128569da46e4f39a99346e93ee9d4e
[ "MIT" ]
46
2019-11-16T13:44:07.000Z
2022-03-12T14:28:44.000Z
Regression_test/examples/threshold/src/threshold.cpp
minseongg/dynamatic
268d97690f128569da46e4f39a99346e93ee9d4e
[ "MIT" ]
11
2020-05-12T17:20:51.000Z
2022-02-04T10:04:59.000Z
Regression_test/examples/threshold/src/threshold.cpp
minseongg/dynamatic
268d97690f128569da46e4f39a99346e93ee9d4e
[ "MIT" ]
22
2020-02-21T21:33:40.000Z
2022-02-24T06:50:41.000Z
#include <stdlib.h> #include "threshold.h" void threshold(inout_int_t red[1000], inout_int_t green[1000], inout_int_t blue[1000], in_int_t th) { for (int i = 0; i < 1000; i++) { int sum = red[i] + green [i] + blue [i]; if (sum <= th) { red[i] = 0; green [i] = 0; blue [i] = 0; } } } #define AMOUNT_OF_TEST 1 int main(void){ inout_int_t red[AMOUNT_OF_TEST][1000]; inout_int_t green[AMOUNT_OF_TEST][1000]; inout_int_t blue[AMOUNT_OF_TEST][1000]; inout_int_t th[AMOUNT_OF_TEST]; for(int i = 0; i < AMOUNT_OF_TEST; ++i){ th[i] = (rand() % 100); for(int j = 0; j < 1000; ++j){ red[i][j] = (rand() % 100); green[i][j] = (rand() % 100); blue[i][j] = (rand() % 100); } } //for(int i = 0; i < AMOUNT_OF_TEST; ++i){ int i = 0; threshold(red[i], green[i], blue[i], th[i]); //} }
18.818182
101
0.570048
269d8a6d9b8f916c3dda647e0ed287f1f9313bef
2,491
cpp
C++
src/io/OutputFile.cpp
feliwir/libcharta
4581ad4dc0751264ed6104a49260e7e070dfc141
[ "Apache-2.0" ]
null
null
null
src/io/OutputFile.cpp
feliwir/libcharta
4581ad4dc0751264ed6104a49260e7e070dfc141
[ "Apache-2.0" ]
8
2021-05-20T11:15:34.000Z
2021-05-21T12:29:48.000Z
src/io/OutputFile.cpp
feliwir/libcharta
4581ad4dc0751264ed6104a49260e7e070dfc141
[ "Apache-2.0" ]
2
2021-05-24T14:43:46.000Z
2021-05-25T08:31:41.000Z
/* Source File : OutputFile.cpp Copyright 2011 Gal Kahana PDFWriter 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 "io/OutputFile.h" #include "Trace.h" #include "io/OutputBufferedStream.h" #include "io/OutputFileStream.h" charta::OutputFile::OutputFile() { mOutputStream = nullptr; } charta::OutputFile::~OutputFile() { CloseFile(); } charta::EStatusCode charta::OutputFile::OpenFile(const std::string &inFilePath, bool inAppend) { EStatusCode status; do { status = CloseFile(); if (status != charta::eSuccess) { TRACE_LOG1("charta::OutputFile::OpenFile, Unexpected Failure. Couldn't close previously open file - %s", mFilePath.c_str()); break; } auto outputFileStream = std::make_unique<OutputFileStream>(); status = outputFileStream->Open(inFilePath, inAppend); // explicitly open, so status may be retrieved if (status != charta::eSuccess) { TRACE_LOG1("charta::OutputFile::OpenFile, Unexpected Failure. Cannot open file for writing - %s", inFilePath.c_str()); break; } mOutputStream = new OutputBufferedStream(std::move(outputFileStream)); mFilePath = inFilePath; } while (false); return status; } charta::EStatusCode charta::OutputFile::CloseFile() { if (nullptr == mOutputStream) { return charta::eSuccess; } mOutputStream->Flush(); auto *outputStream = (OutputFileStream *)mOutputStream->GetTargetStream(); EStatusCode status = outputStream->Close(); // explicitly close, so status may be retrieved delete mOutputStream; // will delete the referenced file stream as well mOutputStream = nullptr; return status; } charta::IByteWriterWithPosition *charta::OutputFile::GetOutputStream() { return mOutputStream; } const std::string &charta::OutputFile::GetFilePath() { return mFilePath; }
27.988764
116
0.674428
269ec50b603ce86bd3a199865737aeb708178b24
1,222
cpp
C++
plugins/hifiKinect/src/KinectProvider.cpp
Darlingnotin/Antisocial_VR
f1debafb784ed5a63a40fe9b80790fbaccfedfce
[ "Apache-2.0" ]
272
2021-01-07T03:06:08.000Z
2022-03-25T03:54:07.000Z
plugins/hifiKinect/src/KinectProvider.cpp
Darlingnotin/Antisocial_VR
f1debafb784ed5a63a40fe9b80790fbaccfedfce
[ "Apache-2.0" ]
1,021
2020-12-12T02:33:32.000Z
2022-03-31T23:36:37.000Z
plugins/hifiKinect/src/KinectProvider.cpp
Darlingnotin/Antisocial_VR
f1debafb784ed5a63a40fe9b80790fbaccfedfce
[ "Apache-2.0" ]
77
2020-12-15T06:59:34.000Z
2022-03-23T22:18:04.000Z
// // Created by Brad Hefta-Gaub on 2016/12/7 // Copyright 2016 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include <mutex> #include <QtCore/QObject> #include <QtCore/QtPlugin> #include <QtCore/QStringList> #include <plugins/RuntimePlugin.h> #include <plugins/InputPlugin.h> #include "KinectPlugin.h" class KinectProvider : public QObject, public InputProvider { Q_OBJECT Q_PLUGIN_METADATA(IID InputProvider_iid FILE "plugin.json") Q_INTERFACES(InputProvider) public: KinectProvider(QObject* parent = nullptr) : QObject(parent) {} virtual ~KinectProvider() {} virtual InputPluginList getInputPlugins() override { static std::once_flag once; std::call_once(once, [&] { InputPluginPointer plugin(new KinectPlugin()); if (plugin->isSupported()) { _inputPlugins.push_back(plugin); } }); return _inputPlugins; } virtual void destroyInputPlugins() override { _inputPlugins.clear(); } private: InputPluginList _inputPlugins; }; #include "KinectProvider.moc"
24.44
88
0.680033
26a0be9f2af8de90d7f9795281eff836adf25290
7,004
hh
C++
src/memo/cli/KeyValueStore.hh
infinit/memo
3a8394d0f647efe03ccb8bfe885a7279cb8be8a6
[ "Apache-2.0" ]
124
2017-06-22T19:20:54.000Z
2021-12-23T21:36:37.000Z
src/memo/cli/KeyValueStore.hh
infinit/memo
3a8394d0f647efe03ccb8bfe885a7279cb8be8a6
[ "Apache-2.0" ]
4
2017-08-21T15:57:29.000Z
2019-01-10T02:52:35.000Z
src/memo/cli/KeyValueStore.hh
infinit/memo
3a8394d0f647efe03ccb8bfe885a7279cb8be8a6
[ "Apache-2.0" ]
12
2017-06-29T09:15:35.000Z
2020-12-31T12:39:52.000Z
#pragma once #include <elle/das/cli.hh> #include <memo/cli/Object.hh> #include <memo/cli/Mode.hh> #include <memo/cli/fwd.hh> #include <memo/cli/symbols.hh> #include <memo/symbols.hh> namespace memo { namespace cli { class KeyValueStore : public Object<KeyValueStore> { public: using Self = KeyValueStore; KeyValueStore(Memo& cli); using Modes = decltype(elle::meta::list(cli::create, cli::delete_, cli::export_, cli::fetch, cli::import, cli::list, cli::pull, cli::push, cli::run)); using Strings = std::vector<std::string>; /*---------------. | Mode: create. | `---------------*/ Mode<Self, void (decltype(cli::name)::Formal<std::string const&>, decltype(cli::network)::Formal<std::string const&>, decltype(cli::description = boost::optional<std::string>()), decltype(cli::push_key_value_store = false), decltype(cli::output = boost::optional<std::string>()), decltype(cli::push = false)), decltype(modes::mode_create)> create; void mode_create(std::string const& name, std::string const& network, boost::optional<std::string> description = {}, bool push_key_value_store = false, boost::optional<std::string> output = {}, bool push = false); /*---------------. | Mode: delete. | `---------------*/ Mode<Self, void (decltype(cli::name)::Formal<std::string const&>, decltype(cli::pull = false), decltype(cli::purge = false)), decltype(modes::mode_delete)> delete_; void mode_delete(std::string const& name, bool pull, bool purge); /*---------------. | Mode: export. | `---------------*/ Mode<Self, void (decltype(cli::name)::Formal<std::string const&>, decltype(cli::output = boost::optional<std::string>())), decltype(modes::mode_export)> export_; void mode_export(std::string const& volume_name, boost::optional<std::string> const& output_name = {}); /*--------------. | Mode: fetch. | `--------------*/ Mode<Self, void (decltype(cli::name = boost::optional<std::string>()), decltype(cli::network = boost::optional<std::string>())), decltype(modes::mode_fetch)> fetch; void mode_fetch(boost::optional<std::string> volume_name = {}, boost::optional<std::string> network_name = {}); /*---------------. | Mode: import. | `---------------*/ Mode<Self, void (decltype(cli::input = boost::optional<std::string>())), decltype(modes::mode_import)> import; void mode_import(boost::optional<std::string> input_name = {}); /*-------------. | Mode: list. | `-------------*/ Mode<Self, void (), decltype(modes::mode_list)> list; void mode_list(); /*-------------. | Mode: pull. | `-------------*/ Mode<Self, void (decltype(cli::name)::Formal<std::string const&>, decltype(cli::purge = false)), decltype(modes::mode_pull)> pull; void mode_pull(std::string const& name, bool purge = false); /*-------------. | Mode: push. | `-------------*/ Mode<Self, void (decltype(cli::name)::Formal<std::string const&>), decltype(modes::mode_push)> push; void mode_push(std::string const& name); /*------------. | Mode: run. | `------------*/ Mode<Self, void (decltype(cli::name)::Formal<std::string const&>, decltype(cli::grpc)::Formal<std::string const&>, decltype(cli::allow_root_creation = false), decltype(cli::peer = Strings{}), decltype(cli::async = false), decltype(cli::cache = false), decltype(cli::cache_ram_size = boost::optional<int>()), decltype(cli::cache_ram_ttl = boost::optional<int>()), decltype(cli::cache_ram_invalidation = boost::optional<int>()), decltype(cli::cache_disk_size = boost::optional<uint64_t>()), decltype(cli::fetch_endpoints = false), decltype(cli::fetch = false), decltype(cli::push_endpoints = false), decltype(cli::push = false), decltype(cli::publish = false), decltype(cli::endpoints_file = boost::optional<std::string>()), decltype(cli::peers_file = boost::optional<std::string>()), decltype(cli::port = boost::optional<int>()), decltype(cli::listen = boost::optional<std::string>()), decltype(cli::fetch_endpoints_interval = boost::optional<int>()), decltype(cli::no_local_endpoints = false), decltype(cli::no_public_endpoints = false), decltype(cli::advertise_host = Strings{}), decltype(cli::grpc_port_file = boost::optional<std::string>())), decltype(modes::mode_run)> run; void mode_run(std::string const& name, std::string const& grpc, bool allow_root_creation = false, Strings peer = {}, bool async = false, bool cache = false, boost::optional<int> cache_ram_size = {}, boost::optional<int> cache_ram_ttl = {}, boost::optional<int> cache_ram_invalidation = {}, boost::optional<uint64_t> cache_disk_size = {}, bool fetch_endpoints = false, bool fetch = false, bool push_endpoints = false, bool push = false, bool publish = false, boost::optional<std::string> const& endpoint_file = {}, boost::optional<std::string> const& peers_file = {}, boost::optional<int> port = {}, boost::optional<std::string> listen = {}, boost::optional<int> fetch_endpoints_interval = {}, bool no_local_endpoints = false, bool no_public_endpoints = false, Strings advertise_host = {}, boost::optional<std::string> grpc_port_file = {}); }; } }
34.673267
81
0.476442
26a2512667b7fa764d14d10841ddb0f642869fb1
1,205
cpp
C++
src/gfa/types.cpp
ggonnella/gfaviz
9cb990948eaf66e6f501e70908fe1d8c0ff0242d
[ "ISC" ]
41
2018-12-19T17:32:44.000Z
2021-11-27T03:44:53.000Z
src/gfa/types.cpp
ggonnella/gfaviz
9cb990948eaf66e6f501e70908fe1d8c0ff0242d
[ "ISC" ]
16
2019-01-17T13:36:02.000Z
2021-12-13T21:18:45.000Z
src/gfa/types.cpp
niehus/gfaviz
9cb990948eaf66e6f501e70908fe1d8c0ff0242d
[ "ISC" ]
2
2018-11-01T12:53:26.000Z
2018-11-07T06:31:03.000Z
#include "gfa/types.h" #include "gfa/line.h" GfaVariance::GfaVariance() { is_set = false; } void GfaVariance::set(unsigned long _val) { is_set = true; val=_val; } ostream& operator<< (ostream &out, const GfaVariance &v) { v.print(out); return out; } void GfaVariance::print(ostream &out) const { if (!is_set) out << '*'; else out << val; } GfaPos::GfaPos() { val = 0; is_end = false; } GfaRef::GfaRef() { is_resolved = false; } void GfaRef::resolve(GfaLine *_r) { ptr = _r; type = ptr->getType(); is_resolved = true; } const string& GfaRef::getName() const{ if (is_resolved) return ptr->getName(); else return name; } ostream& operator<< (ostream &out, const GfaRef &r) { r.print(out); return out; } void GfaRef::print(ostream &out,bool print_orientation, char delimiter) const { out << getName(); if (print_orientation) { if (delimiter != 0) out << delimiter; out << (is_reverse ? '-' : '+'); } } ostream& operator<< (ostream &out, const GfaPos &p) { p.print(out); return out; } void GfaPos::print(ostream &out, bool include_sentinel) const { out << val; if (include_sentinel && is_end) out << (char)GFA_SENTINEL; }
18.538462
79
0.628216
26a5fa3870e7d9939e9a10f6124b408b1d15a119
583
cc
C++
src/figureknight.cc
zerozez/qt-chess
4a066195f656cb57e83f49beeaa9e244796b18d3
[ "Apache-2.0" ]
5
2018-05-09T05:09:50.000Z
2021-07-30T06:48:21.000Z
src/figureknight.cc
zerozez/qt-chess
4a066195f656cb57e83f49beeaa9e244796b18d3
[ "Apache-2.0" ]
null
null
null
src/figureknight.cc
zerozez/qt-chess
4a066195f656cb57e83f49beeaa9e244796b18d3
[ "Apache-2.0" ]
5
2017-11-29T23:49:25.000Z
2021-06-10T15:13:07.000Z
#include <movepoints.hpp> #include "figureknight.hpp" FigureKnight::FigureKnight(const uint x, const uint y, FigureIntf::Color side, QObject *parent) : FigureIntf(x, y, side, new MovePoints(), parent) { MovePoints *points = defMoveList(); points->addPoint(2, 1); points->addPoint(2, -1); points->addPoint(-2, 1); points->addPoint(-2, -1); points->addPoint(1, 2); points->addPoint(1, -2); points->addPoint(-1, 2); points->addPoint(-1, -2); points->setCurrent(x, y); } QString FigureKnight::imagePath() const { return s_path; }
24.291667
78
0.636364
26a889910b55f98ee3c9093b47d7d9cc2bf7dd96
1,251
cpp
C++
src/Engine/Material/BSDF_CookTorrance.cpp
trygas/CGHomework
2dfff76f407b8a7ba87c5ba9d12a4428708ffbbe
[ "MIT" ]
289
2020-01-28T09:07:10.000Z
2022-03-25T09:00:25.000Z
src/Engine/Material/BSDF_CookTorrance.cpp
Ricahrd-Li/ASAP_ARAP_Parameterization
c12d83605ce9ea9cac29efbd991d21e2b363e375
[ "MIT" ]
12
2020-02-19T07:11:14.000Z
2021-08-07T06:41:27.000Z
src/Engine/Material/BSDF_CookTorrance.cpp
Ricahrd-Li/ASAP_ARAP_Parameterization
c12d83605ce9ea9cac29efbd991d21e2b363e375
[ "MIT" ]
249
2020-02-01T08:14:36.000Z
2022-03-30T14:52:58.000Z
#include <Engine/Material/BSDF_CookTorrance.h> #include <Basic/Math.h> using namespace Ubpa; using namespace std; float BSDF_CookTorrance::NDF(const normalf & h) { cout << "WARNING::BSDF_CookTorrance:" << endl << "\t" << "not implemented" << endl; return 0.f; } float BSDF_CookTorrance::Fr(const normalf & wi, const normalf & h) { cout << "WARNING::BSDF_CookTorrance:" << endl << "\t" << "not implemented" << endl; return 0.f; } float BSDF_CookTorrance::G(const normalf & wo, const normalf & wi, const normalf & h){ cout << "WARNING::BSDF_CookTorrance:" << endl << "\t" << "not implemented" << endl; return 0.f; } const rgbf BSDF_CookTorrance::F(const normalf & wo, const normalf & wi, const pointf2 & texcoord) { cout << "WARNING::BSDF_CookTorrance:" << endl << "\t" << "not implemented" << endl; return 0.f; } float BSDF_CookTorrance::PDF(const normalf & wo, const normalf & wi, const pointf2 & texcoord) { cout << "WARNING::BSDF_CookTorrance:" << endl << "\t" << "not implemented" << endl; return 0.f; } const rgbf BSDF_CookTorrance::Sample_f(const normalf & wo, const pointf2 & texcoord, normalf & wi, float & pd) { cout << "WARNING::BSDF_CookTorrance:" << endl << "\t" << "not implemented" << endl; return 0.f; }
28.431818
112
0.663469
26a95ca0515650cbcad75558cecc3efda0da5953
1,652
cpp
C++
src/main.cpp
amitsingh19975/ML
fbd79128f86cfbd8f09e16b0ca1ab5ab2deaa11b
[ "MIT" ]
null
null
null
src/main.cpp
amitsingh19975/ML
fbd79128f86cfbd8f09e16b0ca1ab5ab2deaa11b
[ "MIT" ]
null
null
null
src/main.cpp
amitsingh19975/ML
fbd79128f86cfbd8f09e16b0ca1ab5ab2deaa11b
[ "MIT" ]
null
null
null
#include "inculde/headers.h" #include <iostream> #include <iomanip> using namespace ML; using namespace std; int main(){ // // cout<<setprecision(numeric_limits<double>::max_digits10); string trainF = "/Users/Amit/Desktop/Python/ML/test/cars"; // string testF = "/Users/Amit/Desktop/Python/ML/test/data"; CSV frameTrain(trainF); // // CSV frameTest(testF); // std::vector<double> trainD = { // {1,2,3,4,5,6,7,8} // }; // frameTrain.info(); PPrint::print(frameTrain); // std::vector<std::vector<double>> testD = { // {5,6,7,8}, // {5,6,7,8} // }; // Frame frameTrain(trainD); // frameTrain.print(); // f.print(); // frameTrain.normalize(); // frameTrain.dropCol(0); // frameTrain.labelToNumber(0); auto y = frameTrain[{"brand"}]; auto X = frameTrain.colSlice(0); // PPrint::print(X); // auto X = frameTrain[{"radius_mean", "texture_mean", "smoothness_mean", // "compactness_mean", "symmetry_mean", "fractal_dimension_mean", // "radius_se", "texture_se", "smoothness_se", "compactness_se", // "symmetry_se", "fractal_dimension_se"}]; // PCA p(X); // FrameShared f = p.getReducedFrame(); // PPrint::print(frameTrain); // auto [X_train,X_test,y_train,y_test] = frameTrain.split(X,y,30); // KMean k(3,42,300); // k.train(X_train); // auto q = k.predict(X_test,y_test); // Metrics m(y_test,p); // cout<<k.adjRSquared()<<'\n'; // m.confusionMatrix(); // m.listRates(); // std::vector<std::vector<double>> M = { // {3.0,1.0}, // {1.0,3.0}, // }; return 0; }
31.769231
77
0.577482
26aa86402b96ead305469e8b6ddda32908ac8aa2
2,415
cpp
C++
implementations/C++/02_BasicMatOps/default_main.cpp
bluenote10/SimpleLanguageBenchmarks
1bf616b8241844a4424412db7d3829169531e76d
[ "MIT" ]
1
2019-04-14T05:21:20.000Z
2019-04-14T05:21:20.000Z
implementations/C++/02_BasicMatOps/default_main.cpp
bluenote10/SimpleLanguageBenchmarks
1bf616b8241844a4424412db7d3829169531e76d
[ "MIT" ]
null
null
null
implementations/C++/02_BasicMatOps/default_main.cpp
bluenote10/SimpleLanguageBenchmarks
1bf616b8241844a4424412db7d3829169531e76d
[ "MIT" ]
null
null
null
#include <vector> #include <iostream> #include <fstream> #include <sstream> #include <cstdlib> #include <chrono> #include <cmath> struct Matrix { int N; std::vector<double> data; Matrix operator+(Matrix const& that) const { Matrix result; result.N = N; result.data.resize(data.size()); for (unsigned int i=0; i < data.size(); ++i) { result.data[i] = data[i] + that.data[i]; } return result; } Matrix operator*(Matrix const& that) const { Matrix result; result.N = N; result.data.resize(data.size()); for (int i=0; i < N; ++i) { for (int j=0; j < N; ++j) { double sum = 0; for (int k=0; k < N; ++k) { sum += data[i*N+k] * that.data[k*N+j]; } result.data[i*N+j] = sum; } } return result; } double diag_sum() const { double sum = 0; for (int i=0; i < N; ++i) { sum += data[i*(N+1)]; } return sum; } }; Matrix read_csv(std::string filename) { std::vector<double> data; std::string cell; std::string line; std::ifstream filestream(filename); while (std::getline(filestream, line)) { std::stringstream linestream(line); while (std::getline(linestream, cell, ';')) { double value = std::stod(cell); data.push_back(value); } } return Matrix{(int) sqrt(data.size()), data}; } int main(int argc, char** argv) { std::chrono::system_clock::time_point t1; std::chrono::system_clock::time_point t2; float elapsed_seconds; if (argc != 4) { exit(EXIT_FAILURE); } // read t1 = std::chrono::system_clock::now(); Matrix m_A = read_csv(argv[2]); Matrix m_B = read_csv(argv[3]); t2 = std::chrono::system_clock::now(); elapsed_seconds = std::chrono::duration<float>(t2 - t1).count(); std::cout << elapsed_seconds << std::endl; // add t1 = std::chrono::system_clock::now(); Matrix m_add = m_A + m_B; t2 = std::chrono::system_clock::now(); elapsed_seconds = std::chrono::duration<float>(t2 - t1).count(); std::cout << elapsed_seconds << std::endl; // multiply t1 = std::chrono::system_clock::now(); Matrix m_mul = m_A * m_B; t2 = std::chrono::system_clock::now(); elapsed_seconds = std::chrono::duration<float>(t2 - t1).count(); std::cout << elapsed_seconds << std::endl; // print checks std::cout << m_add.diag_sum() << std::endl; std::cout << m_mul.diag_sum() << std::endl; }
22.783019
66
0.593375
26aaca0b24611b659b37f098826c03e808543bb7
1,148
cpp
C++
libs/liblynel/test/src/lynel/matrix.cpp
tybl/tybl
cc74416d3d982177d46b89c0ca44f3a8e1cf00d6
[ "Unlicense" ]
1
2022-02-11T21:25:53.000Z
2022-02-11T21:25:53.000Z
libs/liblynel/test/src/lynel/matrix.cpp
tybl/tybl
cc74416d3d982177d46b89c0ca44f3a8e1cf00d6
[ "Unlicense" ]
15
2021-08-21T13:41:29.000Z
2022-03-08T14:13:43.000Z
libs/liblynel/test/src/lynel/matrix.cpp
tybl/tybl
cc74416d3d982177d46b89c0ca44f3a8e1cf00d6
[ "Unlicense" ]
null
null
null
// License: The Unlicense (https://unlicense.org) #include "lynel/matrix.hpp" #include <doctest/doctest.h> using namespace tybl::lynel; TEST_CASE("matrix::operator==()") { matrix<double,3,3> a = { 0,1,2,3,4,5,6,7,8 }; matrix<double,3,3> b = { 0,1,2,3,4,5,6,7,8 }; matrix<double,3,3> c = { 1,1,2,3,4,5,6,7,8 }; matrix<double,3,3> d = { 0,1,2,3,4,5,6,7,9 }; CHECK(a == a); CHECK(a == b); CHECK(!(a == c)); CHECK(!(b == d)); } TEST_CASE("aggregate initialization and correct positional assignment of values") { // NOLINT matrix<double,3,3> m = { 0,1,2,3,4,5,6,7,8 }; CHECK(m(0,0) == 0.0); CHECK(m(0,1) == 1.0); CHECK(m(0,2) == 2.0); CHECK(m(1,0) == 3.0); CHECK(m(1,1) == 4.0); CHECK(m(1,2) == 5.0); CHECK(m(2,0) == 6.0); CHECK(m(2,1) == 7.0); CHECK(m(2,2) == 8.0); } TEST_CASE("scalar multiplication") { matrix<double,3,3> m = { 0,1,2, 3,4,5, 6,7,8 }; matrix<double,3,3> a = { 0,2,4,6,8,10,12,14,16 }; m *= 2.0; CHECK(a == m); } TEST_CASE("transpose 3x3") { matrix<double,3,3> m = { 0,1,2,3,4,5,6,7,8 }; matrix<double,3,3> mt = { 0,3,6,1,4,7,2,5,8 }; auto n = transpose(m); CHECK(n == mt); }
24.956522
93
0.542683
26ab2352cf40ab3491f62cdd3d63bba3bc279c60
1,598
cpp
C++
src/gps/tk/ProjectionEckert4.cpp
KIT-IAI/GMLToolbox-gps
c8953e08431a2a945f7fc03f3cff114222826ece
[ "Apache-2.0" ]
1
2021-05-04T06:22:54.000Z
2021-05-04T06:22:54.000Z
src/gps/tk/ProjectionEckert4.cpp
KIT-IAI/GMLToolbox-gps
c8953e08431a2a945f7fc03f3cff114222826ece
[ "Apache-2.0" ]
null
null
null
src/gps/tk/ProjectionEckert4.cpp
KIT-IAI/GMLToolbox-gps
c8953e08431a2a945f7fc03f3cff114222826ece
[ "Apache-2.0" ]
1
2020-07-13T12:14:58.000Z
2020-07-13T12:14:58.000Z
#include "StdAfx.h" #include "Projection.h" #include "ProjectionUtils.h" #include "ProjectionEckert4.h" #define _USE_MATH_DEFINES #include <math.h> CProjectionEckert4::CProjectionEckert4 () { } CProjectionEckert4::~CProjectionEckert4 () { } void CProjectionEckert4::Initialize (CCfgMapProjection & proj) { a = proj.m_fAxis; lon0 = DEG2RAD (proj.m_fOriginLongitude); fe = UnitsToMeters (proj.m_lUnits, proj.m_fFalseEasting); fn = UnitsToMeters (proj.m_lUnits, proj.m_fFalseNorthing); q = 2.0 + M_PI_2; ra0 = 0.42223820031577120149 * a; ra1 = 1.32650042817700232218 * a; } void CProjectionEckert4::Forward () { double lat = m_fLatitude; double lon = m_fLongitude; double dlam = lon - lon0; double t = lat / 2.0; double dt = 1.0; while (fabs (dt) > 4.85e-10) { double sint = sin (t); double cost = cos (t); double num = t + sint * cost + 2.0 * sint; dt = -(num - q * sin (lat)) / (2.0 * cost * (1.0 + cost)); t += dt; } m_fEasting = ra0 * dlam * (1.0 + cos (t)) + fe; m_fNorthing = ra1 * sin (t) + fn; } void CProjectionEckert4::Inverse () { double dx = m_fEasting - fe; double dy = m_fNorthing - fn; double i = dy / ra1; if (i > 1.0) i = 1.0; else if (i < -1.0) i = -1.0; double t = asin (i); double sint = sin (t); double cost = cos (t); double num = t + sint * cost + 2.0 * sint; double lat = asin (num / q); double lon = lon0 + dx / (ra0 * (1 + cost)); m_fLatitude = lat; m_fLongitude = lon; }
18.581395
66
0.576971
26ac579234928e9635367395573f4d42e9a065c9
805
cpp
C++
problems/1189-maximum-number-of-balloons.cpp
ZhongRuoyu/leetcode
a905ec08e9b8ad8931d09e03efb154a648790c78
[ "MIT" ]
1
2022-01-11T06:32:41.000Z
2022-01-11T06:32:41.000Z
problems/1189-maximum-number-of-balloons.cpp
ZhongRuoyu/LeetCode
7472ef8b868165b485e5ce0676226bbe95561b73
[ "MIT" ]
null
null
null
problems/1189-maximum-number-of-balloons.cpp
ZhongRuoyu/LeetCode
7472ef8b868165b485e5ce0676226bbe95561b73
[ "MIT" ]
null
null
null
// Solved 2021-04-09 11:34 // Runtime: 4 ms (80.85%) // Memory Usage: 6.5 MB (67.36%) class Solution { public: int maxNumberOfBalloons(string text) { unordered_map<char, int> lookup[2]{ {{'a', 0}, {'b', 0}, {'n', 0}}, {{'l', 0}, {'o', 0}}}; for (auto &ch : text) { if (ch == 'a' || ch == 'b' || ch == 'n') { ++lookup[0][ch]; } else if (ch == 'l' || ch == 'o') { ++lookup[1][ch]; } } int res = 0, i; while (true) { for (i = 0; i != 2; ++i) { for (auto &pair : lookup[i]) { pair.second -= i + 1; if (pair.second < 0) return res; } } ++res; } } };
26.833333
54
0.33913
26ac80c078b14510e88e45ebc37e3e0029bcbe72
213
cpp
C++
leetcode.com/0912 Sort an Array/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/0912 Sort an Array/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/0912 Sort an Array/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
#include <algorithm> #include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> sortArray(vector<int>& nums) { sort(nums.begin(), nums.end()); return nums; } };
15.214286
44
0.661972
26adb3d9943b8ee8a33b935fe87e6ad5d0233046
4,140
hpp
C++
image/globals.hpp
mywoodstock/woo
7a6e39b2914ec8ff5bf52c3aa5217214532390e4
[ "BSL-1.0" ]
1
2017-05-09T14:25:18.000Z
2017-05-09T14:25:18.000Z
image/globals.hpp
mywoodstock/woo
7a6e39b2914ec8ff5bf52c3aa5217214532390e4
[ "BSL-1.0" ]
null
null
null
image/globals.hpp
mywoodstock/woo
7a6e39b2914ec8ff5bf52c3aa5217214532390e4
[ "BSL-1.0" ]
null
null
null
/** * Project: The Stock Libraries * * File: globals.hpp * Created: Jun 05, 2012 * * Author: Abhinav Sarje <abhinav.sarje@gmail.com> * * Copyright (c) 2012-2017 Abhinav Sarje * Distributed under the Boost Software License. * See accompanying LICENSE file. */ #ifndef __GLOBALS_HPP__ #define __GLOBALS_HPP__ #include <boost/array.hpp> #include <vector> #include <cmath> #include "typedefs.hpp" namespace stock { typedef struct vector2_t { boost::array <real_t, 2> vec_; /* constructors */ vector2_t() { vec_[0] = 0; vec_[1] = 0; } // vector2_t() vector2_t(real_t a, real_t b) { vec_[0] = a; vec_[1] = b; } // vector2_t() vector2_t(vector2_t& a) { vec_[0] = a[0]; vec_[1] = a[1]; } // vector2_t() vector2_t(const vector2_t& a) { vec_ = a.vec_; } // vector2_t() /* operators */ vector2_t& operator=(const vector2_t& a) { vec_ = a.vec_; return *this; } // operator= vector2_t& operator=(vector2_t& a) { vec_ = a.vec_; return *this; } // operator= real_t& operator[](int i) { return vec_[i]; } // operator[] } vector2_t; typedef struct vector3_t { boost::array <real_t, 3> vec_; /* constructors */ vector3_t() { vec_[0] = 0; vec_[1] = 0; vec_[2] = 0; } // vector3_t() vector3_t(real_t a, real_t b, real_t c) { vec_[0] = a; vec_[1] = b; vec_[2] = c; } // vector3_t() vector3_t(vector3_t& a) { vec_[0] = a[0]; vec_[1] = a[1]; vec_[2] = a[2]; } // vector3_t() vector3_t(const vector3_t& a) { vec_ = a.vec_; } // vector3_t() /* operators */ vector3_t& operator=(const vector3_t& a) { vec_ = a.vec_; return *this; } // operator= vector3_t& operator=(vector3_t& a) { vec_ = a.vec_; return *this; } // operator= real_t& operator[](int i) { return vec_[i]; } // operator[] vector3_t operator+(int toadd) { return vector3_t(vec_[0] + toadd, vec_[1] + toadd, vec_[2] + toadd); } // operator+() vector3_t operator+(vector3_t toadd) { return vector3_t(vec_[0] + toadd[0], vec_[1] + toadd[1], vec_[2] + toadd[2]); } // operator+() vector3_t operator-(int tosub) { return vector3_t(vec_[0] - tosub, vec_[1] - tosub, vec_[2] - tosub); } // operator-() vector3_t operator-(vector3_t tosub) { return vector3_t(vec_[0] - tosub[0], vec_[1] - tosub[1], vec_[2] - tosub[2]); } // operator-() vector3_t operator/(vector3_t todiv) { return vector3_t(vec_[0] / todiv[0], vec_[1] / todiv[1], vec_[2] / todiv[2]); } // operator/() } vector3_t; typedef struct matrix3x3_t { typedef boost::array<real_t, 3> mat3_t; mat3_t mat_[3]; /* constructors */ matrix3x3_t() { for(int i = 0; i < 3; ++ i) for(int j = 0; j < 3; ++ j) mat_[i][j] = 0.0; } // matrix3x3_t() matrix3x3_t(const matrix3x3_t& a) { mat_[0] = a.mat_[0]; mat_[1] = a.mat_[1]; mat_[2] = a.mat_[2]; } // matrix3x3_t /* operators */ mat3_t& operator[](unsigned int index) { return mat_[index]; } // operator[]() mat3_t& operator[](int index) { return mat_[index]; } // operator[]() matrix3x3_t& operator=(matrix3x3_t& a) { for(int i = 0; i < 3; ++ i) for(int j = 0; j < 3; ++ j) mat_[i][j] = a[i][j]; return *this; } // operstor=() matrix3x3_t operator+(int toadd) { matrix3x3_t sum; for(int i = 0; i < 3; ++ i) for(int j = 0; j < 3; ++ j) sum.mat_[i][j] = mat_[i][j] + toadd; return sum; } // operator+() matrix3x3_t operator+(matrix3x3_t& toadd) { matrix3x3_t sum; for(int i = 0; i < 3; ++ i) for(int j = 0; j < 3; ++ j) sum.mat_[i][j] = mat_[i][j] + toadd[i][j]; return sum; } // operator+() matrix3x3_t operator*(int tomul) { matrix3x3_t prod; for(int i = 0; i < 3; ++ i) for(int j = 0; j < 3; ++ j) prod.mat_[i][j] = mat_[i][j] * tomul; return prod; } // operator*() matrix3x3_t operator*(matrix3x3_t& tomul) { matrix3x3_t prod; for(int i = 0; i < 3; ++ i) for(int j = 0; j < 3; ++ j) prod.mat_[i][j] = mat_[i][j] * tomul[i][j]; return prod; } // operator*() } matrix3x3_t; } // namespace stock #endif /* __GLOBALS_HPP__ */
21.122449
80
0.572464
26aed0a38df84b58cd7c72fdc67a16f3eda0840d
1,424
cpp
C++
aws-cpp-sdk-proton/source/model/ListRepositorySyncDefinitionsResult.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-proton/source/model/ListRepositorySyncDefinitionsResult.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-proton/source/model/ListRepositorySyncDefinitionsResult.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/proton/model/ListRepositorySyncDefinitionsResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::Proton::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; ListRepositorySyncDefinitionsResult::ListRepositorySyncDefinitionsResult() { } ListRepositorySyncDefinitionsResult::ListRepositorySyncDefinitionsResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } ListRepositorySyncDefinitionsResult& ListRepositorySyncDefinitionsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("nextToken")) { m_nextToken = jsonValue.GetString("nextToken"); } if(jsonValue.ValueExists("syncDefinitions")) { Array<JsonView> syncDefinitionsJsonList = jsonValue.GetArray("syncDefinitions"); for(unsigned syncDefinitionsIndex = 0; syncDefinitionsIndex < syncDefinitionsJsonList.GetLength(); ++syncDefinitionsIndex) { m_syncDefinitions.push_back(syncDefinitionsJsonList[syncDefinitionsIndex].AsObject()); } } return *this; }
28.48
138
0.778792
26b0fcd469e70a25de15e4e818b4827deb831f5c
3,096
cpp
C++
app/src/main/jni/nativeCode/common/myJNIHelper.cpp
nul318/CatchTime
496322a04852f08422fd2b696561f704d3d796c5
[ "Apache-2.0" ]
51
2016-08-01T13:11:08.000Z
2021-11-15T10:14:10.000Z
app/src/main/jni/nativeCode/common/myJNIHelper.cpp
nul318/CatchTime
496322a04852f08422fd2b696561f704d3d796c5
[ "Apache-2.0" ]
8
2017-02-08T06:12:00.000Z
2021-12-03T11:24:07.000Z
app/src/main/jni/nativeCode/common/myJNIHelper.cpp
nul318/CatchTime
496322a04852f08422fd2b696561f704d3d796c5
[ "Apache-2.0" ]
24
2016-12-22T06:42:10.000Z
2022-03-17T09:51:33.000Z
/* * Copyright 2016 Anand Muralidhar * * 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 "myJNIHelper.h" #include "misc.h" #include <android/asset_manager_jni.h> MyJNIHelper::MyJNIHelper(JNIEnv *env, jobject obj, jobject assetManager, jstring pathToInternalDir) { // get a native instance of the asset manager // assetManager is passed from Java and should not be garbage collected! apkAssetManager = AAssetManager_fromJava(env, assetManager); //Save app internal data storage path -- we will extract assets and save here const char *cPathToInternalDir; cPathToInternalDir = env->GetStringUTFChars(pathToInternalDir, NULL ) ; apkInternalPath = std::string(cPathToInternalDir); env->ReleaseStringUTFChars(pathToInternalDir, cPathToInternalDir); //mutex for thread safety pthread_mutex_init(&threadMutex, NULL ); } MyJNIHelper::~MyJNIHelper() { pthread_mutex_destroy( &threadMutex); } /** * Search for a file in assets, extract it, save it in internal storage, and return the new path */ bool MyJNIHelper::ExtractAssetReturnFilename(std::string assetName, std::string & filename, bool checkIfFileIsAvailable) { // construct the filename in internal storage by concatenating with path to internal storage filename = apkInternalPath + "/" + GetFileName(assetName); // check if the file was previously extracted and is available in app's internal dir FILE* file = fopen(filename.c_str(), "rb"); if (file && checkIfFileIsAvailable) { MyLOGI("Found extracted file in assets: %s", filename.c_str()); fclose(file); pthread_mutex_unlock( &threadMutex); return true; } // let us look for the file in assets bool result = false; // AAsset objects are not thread safe and need to be protected with mutex pthread_mutex_lock( &threadMutex); // Open file AAsset* asset = AAssetManager_open(apkAssetManager, assetName.c_str(), AASSET_MODE_STREAMING); char buf[BUFSIZ]; int nb_read = 0; if (asset != NULL) { FILE* out = fopen(filename.c_str(), "w"); while ((nb_read = AAsset_read(asset, buf, BUFSIZ)) > 0) { fwrite(buf, nb_read, 1, out); } fclose(out); AAsset_close(asset); result = true; MyLOGI("Asset extracted: %s", filename.c_str()); } else { MyLOGE("Asset not found: %s", assetName.c_str()); } pthread_mutex_unlock( &threadMutex); return result; }
32.589474
101
0.675388
26b30d30371c8e92875b23274f95d280f413303d
53
cc
C++
tests/CompileTests/ElsaTestCases/t0100.cc
maurizioabba/rose
7597292cf14da292bdb9a4ef573001b6c5b9b6c0
[ "BSD-3-Clause" ]
488
2015-01-09T08:54:48.000Z
2022-03-30T07:15:46.000Z
tests/CompileTests/ElsaTestCases/t0100.cc
sujankh/rose-matlab
7435d4fa1941826c784ba97296c0ec55fa7d7c7e
[ "BSD-3-Clause" ]
174
2015-01-28T18:41:32.000Z
2022-03-31T16:51:05.000Z
tests/CompileTests/ElsaTestCases/t0100.cc
sujankh/rose-matlab
7435d4fa1941826c784ba97296c0ec55fa7d7c7e
[ "BSD-3-Clause" ]
146
2015-04-27T02:48:34.000Z
2022-03-04T07:32:53.000Z
class X { int y; void foo() { X::y++; } };
7.571429
14
0.358491
564be89ba37b356a87ced8fd135c687a0a5395e7
1,663
hpp
C++
ToolsDialog.hpp
chrisoldwood/FarmMonitor
5b9802ff2b9a3a64d74f8705769212822563c4cd
[ "MIT" ]
4
2018-01-31T13:12:02.000Z
2020-09-11T13:13:58.000Z
ToolsDialog.hpp
chrisoldwood/FarmMonitor
5b9802ff2b9a3a64d74f8705769212822563c4cd
[ "MIT" ]
null
null
null
ToolsDialog.hpp
chrisoldwood/FarmMonitor
5b9802ff2b9a3a64d74f8705769212822563c4cd
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// //! \file ToolsDialog.hpp //! \brief The ToolsDialog class declaration. //! \author Chris Oldwood // Check for previous inclusion #ifndef TOOLSDIALOG_HPP #define TOOLSDIALOG_HPP #if _MSC_VER > 1000 #pragma once #endif #include <WCL/CommonUI.hpp> #include "Tools.hpp" //////////////////////////////////////////////////////////////////////////////// //! The dialog used to edit the set of tools. class ToolsDialog : public CDialog { public: //! Default constructor. ToolsDialog(); // // Members. // Tools m_tools; //! The set of tools. private: //! The view columns enum Column { TOOL_NAME, COMMAND_LINE, }; // // Controls. // CListView m_view; //! The tools view. // // Message handlers. // //! Dialog initialisation handler. virtual void OnInitDialog(); //! OK button handler. virtual bool OnOk(); //! Tool view selection change handler. LRESULT onToolSelected(NMHDR& header); //! Tool double-clicked handler. LRESULT onToolDoubleClicked(NMHDR& header); //! Add button handler. void onAddTool(); //! Copy button handler. void onCopyTool(); //! Edit button handler. void onEditTool(); //! Delete button handler. void onDeleteTool(); //! Up button handler. void onMoveToolUp(); //! Down button handler. void onMoveToolDown(); // // Internal methods. // //! Update the state of the UI. void updateUi(); //! Add an item to the view. void addItemToView(ConstToolPtr tool, bool select = false); //! Update an item in the view. void updateViewItem(size_t row, ConstToolPtr tool); }; #endif // TOOLSDIALOG_HPP
17.88172
80
0.616957
564f9a0f58d404c300022d0cc7880be326f3de29
1,558
cpp
C++
math.cpp
razordemo/THE-SCENE-IS-DEAD
b83c03c919535fdacffe11ee98a6fa5f551e79a8
[ "CC0-1.0" ]
8
2021-12-13T16:10:52.000Z
2022-03-13T10:00:33.000Z
math.cpp
razordemo/THE-SCENE-IS-DEAD
b83c03c919535fdacffe11ee98a6fa5f551e79a8
[ "CC0-1.0" ]
null
null
null
math.cpp
razordemo/THE-SCENE-IS-DEAD
b83c03c919535fdacffe11ee98a6fa5f551e79a8
[ "CC0-1.0" ]
1
2021-12-27T11:47:07.000Z
2021-12-27T11:47:07.000Z
__declspec(naked) int rounding_common() { __asm { fnstcw [ESP-8] fldcw [ESP] fistp dword ptr [ESP] pop EAX fldcw [ESP-12] ret } } __declspec(naked) int __cdecl floorf(float x) { __asm { fld dword ptr [ESP+4] push 0x73f jmp rounding_common } } __declspec(naked) int __cdecl floor(double x) { __asm { fld qword ptr [ESP+4] push 0x73f jmp rounding_common } } __declspec(naked) int __cdecl roundf(float x) { __asm { fld dword ptr [ESP+4] push 0x33f jmp rounding_common } } __declspec(naked) int __cdecl round(double x) { __asm { fld qword ptr [ESP+4] push 0x33f jmp rounding_common } } __declspec(naked) int __cdecl ceilf(float x) { __asm { fld dword ptr [ESP+4] push 0xb3f jmp rounding_common } } __declspec(naked) int __cdecl ceil(double x) { __asm { fld qword ptr [ESP+4] push 0xb3f jmp rounding_common } } __declspec(naked) int __cdecl truncf(float x) { __asm { fld dword ptr [ESP+4] push 0xf3f jmp rounding_common } } __declspec(naked) int __cdecl trunc(double x) { __asm { fld qword ptr [ESP+4] push 0xf3f jmp rounding_common } }
16.752688
46
0.488447
565341ee5667668b6426c1dcb40bdf30c5d59d8e
11,305
cpp
C++
app.cpp
alxga/utils
01ca9fb2084ba5e7bead20b45f52b3557ce8c337
[ "MIT" ]
null
null
null
app.cpp
alxga/utils
01ca9fb2084ba5e7bead20b45f52b3557ce8c337
[ "MIT" ]
null
null
null
app.cpp
alxga/utils
01ca9fb2084ba5e7bead20b45f52b3557ce8c337
[ "MIT" ]
null
null
null
/* Copyright (c) 2018-2019 Alexander A. Ganin. All rights reserved. Twitter: @alxga. Website: alexganin.com. Licensed under the MIT License. See LICENSE file in the project root for full license information. */ #include "stdafx.h" #ifdef HAVE_MPI # include <mpi.h> #endif #include "Utils/utils.h" using namespace std; App *App::sm_app = NULL; App::App(const char *name) { if (sm_app != NULL) throw Exception("Multiple instances of the App class"); m_logFile = NULL; m_logDirId = -1; m_args = new StrCmdArgMap(); strcpy(m_name, name); strcpy(m_wdir, FS::curDir()); strcpy(m_inDir, m_wdir); strcpy(m_outDir, m_wdir); sm_app = this; } App::~App() { sm_app = NULL; delete m_args; } void App::setWDir(const char *v) { strcpy(m_wdir, v); } void App::setInDir(const char *v) { strcpy(m_inDir, v); } void App::setOutDir(const char *v) { strcpy(m_outDir, v); } const char *App::logDirName() const { static char ret[MAXPATHLENGTH]; if (m_logDirId < 1) sprintf(ret, "log_%s", name()); else sprintf(ret, "log_%s-%d", name(), m_logDirId); return ret; } void App::initLog() { char path[MAXPATHLENGTH]; const char ps = FS::pathSep(); sprintf(path, "%s%c%s%c%d.log", wdir(), ps, logDirName(), ps, mpiRank()); m_logFile = fopen(path, "wb"); if (m_logFile == NULL) throw Exception("Unable to open the log file for writing"); } void App::log(const char *txt, ...) const { if (m_logFile != NULL) { static char buffer[1024]; va_list aptr; va_start(aptr, txt); vsprintf(buffer, txt, aptr); va_end(aptr); fprintf(m_logFile, "%s" ENDL, buffer); fflush(m_logFile); } } void App::deinitLog() { if (m_logFile != NULL) { fclose(m_logFile); m_logFile = NULL; } } int App::run(int argc, char *argv[]) { int retCode = 0; bool ready = false; char ldir[MAXPATHLENGTH]; const char ps = FS::pathSep(); m_logDirId = 0; sprintf(ldir, "%s%c%s", wdir(), ps, logDirName()); while (FS::fsEntryExist(ldir)) { m_logDirId++; sprintf(ldir, "%s%c%s", wdir(), ps, logDirName()); } FS::makeDir(wdir(), logDirName()); initLog(); unsigned int seed = (unsigned int) time(NULL); srand(seed); log("Random seeded with %X", seed); log("Our rank is %d of %d processes", mpiRank(), mpiSize()); try { beforeMain(); retCode = main(); afterMain(); } catch (const Exception &e) { log("Unhandled exception: %s", e.message()); retCode = -1; } deinitLog(); return retCode; } bool App::hasArg(const char *name) const { return m_args->find(name) != m_args->end(); } std::string App::argValue(const char *name) const { return (*m_args)[name].m_value; } double App::argNum(const char *name) const { return (*m_args)[name].m_num; } void App::parseArgs(int argc, char *argv[]) { m_args->clear(); for (int i = 0; i < argc; i++) { CmdArg arg; arg.parse(argv[i]); if (arg.m_name.length() > 0) (*m_args)[arg.m_name] = arg; } if (hasArg("wdir")) setWDir(argValue("wdir").c_str()); else throw Exception("Working directory must be specified with command argument -wdir=<path>"); if (hasArg("indir")) setInDir(argValue("indir").c_str()); else setInDir(wdir()); if (hasArg("outdir")) setOutDir(argValue("outdir").c_str()); else setOutDir(wdir()); if (!FS::fsEntryExist(wdir()) || !FS::fsEntryExist(outDir()) || !FS::fsEntryExist(inDir())) throw Exception("Incorrect working, output, or input directory specified"); } const char *IDataPool::indexLogStr(int ix) { static char ret[100]; sprintf(ret, "Index %d", ix); return ret; } #ifdef HAVE_MPI class MPISendMgr : public IMPISendMgr { int m_dst; public: MPISendMgr(int dst) : m_dst(dst) { } virtual int SendResultsMsgData(int msgData) { int msg = MSG(WMSG_RESULTS, msgData); return MPI_Ssend(&msg, 1, MPI_INT, m_dst, 0, MPI_COMM_WORLD); } virtual int Send(const void *buf, int count, void *pDatatype) { MPI_Datatype* pdt = (MPI_Datatype*)pDatatype; return MPI_Ssend(buf, count, *pdt, m_dst, 0, MPI_COMM_WORLD); } }; class MPIRecvMgr : public IMPIRecvMgr { int m_src; public: MPIRecvMgr(int src, int resultsMsgData) : m_src(src) { m_resultsMsgData = resultsMsgData; } virtual int Recv(void *buf, int count, void *pDatatype) { MPI_Status s; MPI_Datatype* pdt = (MPI_Datatype*)pDatatype; return MPI_Recv(buf, count, *pdt, m_src, 0, MPI_COMM_WORLD, &s); } }; class MPIDbgSendRecvMgr : public IMPISendMgr, public IMPIRecvMgr { struct Buffer { char *data; int size; }; std::queue<Buffer> m_buffers; public: inline bool hasData() const { return m_buffers.size() > 0; } virtual int SendResultsMsgData(int msgData) { m_resultsMsgData = msgData; return MPI_SUCCESS; } virtual int Send(const void *buf, int count, void* pDatatype) { int sz; MPI_Datatype* pdt = (MPI_Datatype*)pDatatype; MPI_Type_size(*pdt, &sz); sz *= count; Buffer b = { new char[sz], sz }; m_buffers.push(b); memcpy(b.data, buf, sz); return MPI_SUCCESS; } virtual int Recv(void *buf, int count, void* pDatatype) { int sz; MPI_Datatype* pdt = (MPI_Datatype*)pDatatype; MPI_Type_size(*pdt, &sz); sz *= count; Buffer b = m_buffers.front(); if (b.size != sz) throw Exception("MPI read calls should be for the same amount of bytes " "as previous MPI write calls in DEBUG emulation runs"); memcpy(buf, b.data, sz); delete[] b.data; m_buffers.pop(); return MPI_SUCCESS; } }; #endif MPIApp *MPIApp::sm_mpiApp = NULL; MPIApp::MPIApp(const char *name, IDataPool *dp) : App(name) { #ifdef HAVE_MPI if (sm_mpiApp != NULL) throw Exception("Multiple instances of the MPIApp class"); sm_mpiApp = this; m_dp = dp; m_mpiRank = 0; #else throw Exception("Rebuild the Utils library with HAVE_MPI macro " "defined to use MPIApp"); #endif } int MPIApp::run(int argc, char *argv[]) { #ifdef HAVE_MPI int retCode = 0; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &m_mpiRank); MPI_Comm_size(MPI_COMM_WORLD, &m_mpiSize); initMPITypes(); if (m_mpiRank != 0) { MPI_Status s; MPI_Recv(&m_logDirId, 1, MPI_INT, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &s); } else { char ldir[MAXPATHLENGTH]; const char ps = FS::pathSep(); m_logDirId = 0; sprintf(ldir, "%s%c%s", wdir(), ps, logDirName()); while (FS::fsEntryExist(ldir)) { m_logDirId++; sprintf(ldir, "%s%c%s", wdir(), ps, logDirName()); } FS::makeDir(wdir(), logDirName()); for (int i = 1; i < m_mpiSize; i++) MPI_Ssend(&m_logDirId, 1, MPI_INT, i, 0, MPI_COMM_WORLD); } initLog(); // call after MPI starting routines to have a rank unsigned int seed = ((unsigned int) time(NULL)) * (m_mpiRank + 1); srand(seed); log("Random seeded with %X", seed); log("Our rank is %d of %d processes", m_mpiRank, m_mpiSize); try { beforeMain(); if (m_mpiRank == 0) retCode = main(); else retCode = mainMPI(); afterMain(); } catch (const Exception &e) { log("Unhandled exception: %s", e.message()); log("Aborting MPI from process %d", m_mpiRank); MPI_Abort(MPI_COMM_WORLD, -1); // the code below should not execute as MPI_Abort does not return log("Failed to abort MPI from process %d", m_mpiRank); return -1; } deinitMPITypes(); MPI_Finalize(); deinitLog(); return retCode; #else throw Exception("Rebuild the Utils library with HAVE_MPI macro " "defined to use MPIApp"); #endif } int MPIApp::main() { #ifdef HAVE_MPI MPI_Status s; bool ready = m_dp->checkFS(); log("Main ready state is %s", ready ? "true" : "false"); int *tasks = new int[m_mpiSize]; auto_del<int> del_tasks(tasks, true); for (int i = 0; i < m_mpiSize; i++) tasks[i] = -1; std::list<int> tasksSyncing; m_dp->resetIndex(); if (m_mpiSize > 1) { // real MPI scenario #ifdef _DEBUG MessageBoxA(0, "Master MPI", "Master MPI", MB_OK); #endif int procsFinished = 0; while (procsFinished < m_mpiSize - 1) { int msg; MPI_Recv(&msg, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &s); int src = s.MPI_SOURCE; if (src > 0 && src < m_mpiSize) { int cmd = MSG_CMD(msg); if (cmd == WMSG_RESULTS) { int ix = tasks[src]; MPIRecvMgr mgr(src, MSG_DATA(msg)); receiveResults(mgr, ix); log("Received results for %s from process %d", m_dp->indexLogStr(ix), src); } if (cmd == WMSG_READY) { if (tasks[src] < 0) log("Process %d is ready, no previous tasks", src); else log("Process %d is ready, previous task was %s", src, m_dp->indexLogStr(tasks[src])); tasks[src] = -1; tasksSyncing.push_back(src); while (tasksSyncing.size() > 0 && !iterationSync()) { int task = tasksSyncing.front(); tasksSyncing.pop_front(); int ix = m_dp->nextIndex(); if (ix < 0) { int msg = MSG(MSG_QUIT, 0); log("Quitting process %d", task); MPI_Ssend(&msg, 1, MPI_INT, task, 0, MPI_COMM_WORLD); procsFinished++; } else { if (!m_dp->createDirs(ix)) throw Exception("Unable to create an output directory"); tasks[task] = ix; int msg = MSG(MSG_RUN, ix); log("Running %s on process %d", m_dp->indexLogStr(ix), task); MPI_Ssend(&msg, 1, MPI_INT, task, 0, MPI_COMM_WORLD); } } } } else break; } } else { // emulate MPI in a single process/thread for debugging while (true) { // let the master process aggregate results // as we only have one worker process this should never return true if (iterationSync()) throw Exception("Unexpected operation"); int ix = m_dp->nextIndex(); if (ix < 0) break; if (!m_dp->createDirs(ix)) throw Exception("Unable to create an output directory"); MPIDbgSendRecvMgr sendRecvMgr; calcIndex(ix); sendResults(sendRecvMgr, ix); if (sendRecvMgr.hasData()) receiveResults(sendRecvMgr, ix); } } log("Returning from runMainMPI"); return 0; #else throw Exception("Rebuild the Utils library with HAVE_MPI macro " "defined to use MPIApp"); #endif } int MPIApp::mainMPI() { #ifdef HAVE_MPI MPISendMgr sendRecvMgr(0); while (true) { MPI_Status s; int msg = MSG(WMSG_READY, 0); MPI_Ssend(&msg, 1, MPI_INT, 0, 0, MPI_COMM_WORLD); MPI_Recv(&msg, 1, MPI_INT, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &s); int cmd = MSG_CMD(msg); if (cmd != MSG_RUN) break; int ix = MSG_DATA(msg); calcIndex(ix); sendResults(sendRecvMgr, ix); } return 0; #else throw Exception("Rebuild the Utils library with HAVE_MPI macro " "defined to use MPIApp"); #endif }
21.533333
94
0.603096
565489757ce1fd9e8bd5ab39a63f70b20df0e50f
4,838
cc
C++
xapian/xapian-core-1.2.13/backends/flint/flint_termlisttable.cc
pgs7179/xapian_modified
0229c9efb9eca19be4c9f463cd4b793672f24198
[ "MIT" ]
2
2021-01-13T21:17:42.000Z
2021-01-13T21:17:42.000Z
xapian/xapian-core-1.2.13/backends/flint/flint_termlisttable.cc
Loslove55/tailbench
fbbf3f31e3f0af1bb7db7f07c2e7193b84abb1eb
[ "MIT" ]
null
null
null
xapian/xapian-core-1.2.13/backends/flint/flint_termlisttable.cc
Loslove55/tailbench
fbbf3f31e3f0af1bb7db7f07c2e7193b84abb1eb
[ "MIT" ]
null
null
null
/** @file flint_termlisttable.cc * @brief Subclass of FlintTable which holds termlists. */ /* Copyright (C) 2007,2008 Olly Betts * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <config.h> #include <xapian/document.h> #include <xapian/error.h> #include <xapian/termiterator.h> #include "flint_termlisttable.h" #include "flint_utils.h" #include "debuglog.h" #include "omassert.h" #include "str.h" #include "stringutils.h" #include <string> using namespace std; void FlintTermListTable::set_termlist(Xapian::docid did, const Xapian::Document & doc, flint_doclen_t doclen) { LOGCALL_VOID(DB, "FlintTermListTable::set_termlist", did | doc | doclen); Xapian::doccount termlist_size = doc.termlist_count(); if (termlist_size == 0) { // doclen is sum(wdf) so should be zero if there are no terms. Assert(doclen == 0); Assert(doc.termlist_begin() == doc.termlist_end()); add(flint_docid_to_key(did), string()); return; } string tag = F_pack_uint(doclen); Xapian::TermIterator t = doc.termlist_begin(); if (t != doc.termlist_end()) { tag += F_pack_uint(termlist_size); string prev_term = *t; // Previous database versions encoded a boolean here, which was // always false (and F_pack_bool() encodes false as a '0'). We can // just omit this and successfully read old and new termlists // except in the case where the next byte is a '0' - in this case // we need keep the '0' so that the decoder can just skip any '0' // it sees in this position (this shouldn't be a common case - 48 // character terms aren't very common, and the first term // alphabetically is likely to be shorter than average). if (prev_term.size() == '0') tag += '0'; tag += char(prev_term.size()); tag += prev_term; tag += F_pack_uint(t.get_wdf()); --termlist_size; while (++t != doc.termlist_end()) { const string & term = *t; // If there's a shared prefix with the previous term, we don't // store it explicitly, but just store the length of the shared // prefix. In general, this is a big win. size_t reuse = common_prefix_length(prev_term, term); // reuse must be <= prev_term.size(), and we know that value while // decoding. So if the wdf is small enough that we can multiply it // by (prev_term.size() + 1), add reuse and fit the result in a // byte, then we can pack reuse and the wdf into a single byte and // save ourselves a byte. We actually need to add one to the wdf // before multiplying so that a wdf of 0 can be detected by the // decoder. size_t packed = 0; Xapian::termcount wdf = t.get_wdf(); // If wdf >= 128, then we aren't going to be able to pack it in so // don't even try to avoid the calculation overflowing and making // us think we can. if (wdf < 127) packed = (wdf + 1) * (prev_term.size() + 1) + reuse; if (packed && packed < 256) { // We can pack the wdf into the same byte. tag += char(packed); tag += char(term.size() - reuse); tag.append(term.data() + reuse, term.size() - reuse); } else { tag += char(reuse); tag += char(term.size() - reuse); tag.append(term.data() + reuse, term.size() - reuse); // FIXME: pack wdf after reuse next time we rejig the format // incompatibly. tag += F_pack_uint(wdf); } prev_term = *t; --termlist_size; } } Assert(termlist_size == 0); add(flint_docid_to_key(did), tag); } flint_doclen_t FlintTermListTable::get_doclength(Xapian::docid did) const { LOGCALL(DB, flint_doclen_t, "FlintTermListTable::get_doclength", did); string tag; if (!get_exact_entry(flint_docid_to_key(did), tag)) throw Xapian::DocNotFoundError("No termlist found for document " + str(did)); if (tag.empty()) RETURN(0); const char * pos = tag.data(); const char * end = pos + tag.size(); flint_doclen_t doclen; if (!F_unpack_uint(&pos, end, &doclen)) { const char *msg; if (pos == 0) { msg = "Too little data for doclen in termlist"; } else { msg = "Overflowed value for doclen in termlist"; } throw Xapian::DatabaseCorruptError(msg); } RETURN(doclen); }
32.689189
77
0.673419
56552f854b8b9d39c69acb10804e90e7397e6248
3,101
cpp
C++
CODEJAM/2014/ROUND1C/b.cpp
henviso/contests
aa8a5ce9ed4524e6c3130ee73af7640e5a86954c
[ "Apache-2.0" ]
null
null
null
CODEJAM/2014/ROUND1C/b.cpp
henviso/contests
aa8a5ce9ed4524e6c3130ee73af7640e5a86954c
[ "Apache-2.0" ]
null
null
null
CODEJAM/2014/ROUND1C/b.cpp
henviso/contests
aa8a5ce9ed4524e6c3130ee73af7640e5a86954c
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cstdio> #include <string> #include <cstring> #include <cstdlib> #include <stack> #include <algorithm> #include <cctype> #include <vector> #include <queue> #include <tr1/unordered_map> #include <cmath> #include <map> #include <bitset> #include <set> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef vector<int> vi; typedef pair<int,int> ii; typedef vector< ii > vii; ///////////////////////////////UTIL///////////////////////////////// #define ALL(x) (x).begin(),x.end() #define CLEAR0(v) memset(v, 0, sizeof(v)) #define CLEAR(v, x) memset(v, x, sizeof(v)) #define IN0(x, n) ((x) > -1 && (x) < n) #define IN(x, a, b) ((x) >= a && (x) <= b) #define COPY(a, b) memcpy(a, b, sizeof(a)) #define CMP(a, b) memcmp(a, b, sizeof(a)) #define REP(i,n) for(int i = 0; i<n; i++) #define REPP(i,a,n) for(int i = a; i<n; i++) #define REPD(i,n) for(int i = n-1; i>-1; i--) #define REPDP(i,a,n) for(int i = n-1; i>=a; i--) #define pb push_back #define pf push_front #define sz size() #define mp make_pair /////////////////////////////NUMERICAL////////////////////////////// #define INCMOD(a,b,c) (((a)+b)%c) #define DECMOD(a,b,c) (((a)+c-b)%c) #define ROUNDINT(a) (int)((double)(a) + 0.5) #define INF 0x3f3f3f3f #define EPS 1e-9 /////////////////////////////BITWISE//////////////////////////////// #define CHECK(S, j) (S & (1 << j)) #define CHECKFIRST(S) (S & (-S)) //PRECISA DE UMA TABELA PARA TRANSFORMAR EM INDICE #define SET(S, j) S |= (1 << j) #define SETALL(S, j) S = (1 << j)-1 //J PRIMEIROS #define UNSET(S, j) S &= ~(1 << j) #define TOOGLE(S, j) S ^= (1 << j) ///////////////////////////////64 BITS////////////////////////////// #define LCHECK(S, j) (S & (1ULL << j)) #define LSET(S, j) S |= (1ULL << j) #define LSETALL(S, j) S = (1ULL << j)-1ULL //J PRIMEIROS #define LUNSET(S, j) S &= ~(1ULL << j) #define LTOOGLE(S, j) S ^= (1ULL << j) #define MOD 1000000007LL //__builtin_popcount(m) //scanf(" %d ", &t); typedef unsigned long long hash; string simplify(string &a){ //cout << " STRING A " << a << endl; string res = "$"; int i = 0; while(i < a.length()){ if(a[i] != res[res.length()-1]) res += a[i]; i++; } //cout << " SIMPLIFICADA " << res.substr(1) << endl; return res.substr(1); } bool hasRepeated(string &a){ if(a.length() > 26) return true; bool vis[30]; CLEAR0(vis); REP(i, a.length()){ if(vis[(a[i]-'a')]) return true; vis[(a[i]-'a')] = true; } return false; } bool valid(string &a){ return !hasRepeated(a); } pair<int, string> s[1000]; int N, t; int main(){ cin >> t; REPP(ca, 1, t+1){ cin >> N; ll ans = 1LL; REP(i, N){ cin >> s[i].second; s[i].second = simplify(s[i].second); if(!valid(s[i].second)) ans = 0LL; s[i].first = i; } if(ans == 0LL) cout << "Case #" << ca << ": " << ans << endl; else{ ll ans = 0LL; sort(s, s+N); do{ //cout << " N " << N << endl; string c = ""; REP(i, N) c += s[i].second; c = simplify(c); ans = ((ans+valid(c))%MOD); }while(next_permutation(s, s+N)); cout << "Case #" << ca << ": " << ans << endl; } } }
25.841667
84
0.529507
5656eb3c3c81ecbc3e43d10f40a9d44a605d675a
2,177
cpp
C++
src/catalog/catalog_entry/sequence_catalog_entry.cpp
AldoMyrtaj/duckdb
3aa4978a2ceab8df25e4b20c388bcd7629de73ed
[ "MIT" ]
1
2022-02-07T14:37:01.000Z
2022-02-07T14:37:01.000Z
src/catalog/catalog_entry/sequence_catalog_entry.cpp
AldoMyrtaj/duckdb
3aa4978a2ceab8df25e4b20c388bcd7629de73ed
[ "MIT" ]
32
2021-09-24T23:50:09.000Z
2022-03-29T09:37:26.000Z
src/catalog/catalog_entry/sequence_catalog_entry.cpp
AldoMyrtaj/duckdb
3aa4978a2ceab8df25e4b20c388bcd7629de73ed
[ "MIT" ]
null
null
null
#include "duckdb/catalog/catalog_entry/sequence_catalog_entry.hpp" #include "duckdb/catalog/catalog_entry/schema_catalog_entry.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/field_writer.hpp" #include "duckdb/parser/parsed_data/create_sequence_info.hpp" #include "duckdb/catalog/dependency_manager.hpp" #include <algorithm> #include <sstream> namespace duckdb { SequenceCatalogEntry::SequenceCatalogEntry(Catalog *catalog, SchemaCatalogEntry *schema, CreateSequenceInfo *info) : StandardEntry(CatalogType::SEQUENCE_ENTRY, schema, catalog, info->name), usage_count(info->usage_count), counter(info->start_value), increment(info->increment), start_value(info->start_value), min_value(info->min_value), max_value(info->max_value), cycle(info->cycle) { this->temporary = info->temporary; } void SequenceCatalogEntry::Serialize(Serializer &serializer) { FieldWriter writer(serializer); writer.WriteString(schema->name); writer.WriteString(name); writer.WriteField<uint64_t>(usage_count); writer.WriteField<int64_t>(increment); writer.WriteField<int64_t>(min_value); writer.WriteField<int64_t>(max_value); writer.WriteField<int64_t>(counter); writer.WriteField<bool>(cycle); writer.Finalize(); } unique_ptr<CreateSequenceInfo> SequenceCatalogEntry::Deserialize(Deserializer &source) { auto info = make_unique<CreateSequenceInfo>(); FieldReader reader(source); info->schema = reader.ReadRequired<string>(); info->name = reader.ReadRequired<string>(); info->usage_count = reader.ReadRequired<uint64_t>(); info->increment = reader.ReadRequired<int64_t>(); info->min_value = reader.ReadRequired<int64_t>(); info->max_value = reader.ReadRequired<int64_t>(); info->start_value = reader.ReadRequired<int64_t>(); info->cycle = reader.ReadRequired<bool>(); reader.Finalize(); return info; } string SequenceCatalogEntry::ToSQL() { std::stringstream ss; ss << "CREATE SEQUENCE "; ss << name; ss << " INCREMENT BY " << increment; ss << " MINVALUE " << min_value; ss << " MAXVALUE " << max_value; ss << " START " << counter; ss << " " << (cycle ? "CYCLE" : "NO CYCLE") << ";"; return ss.str(); } } // namespace duckdb
34.555556
114
0.747359
56579e54ba5cf939dd05730da3ab5320b8cfbc5b
1,077
cpp
C++
proj-e/tests/internal_test.cpp
romz-pl/b-plus-tree
5af2db1c4188d507d0ff28eac91dc255d4e49a35
[ "Apache-2.0" ]
1
2019-02-01T09:10:11.000Z
2019-02-01T09:10:11.000Z
proj-e/tests/internal_test.cpp
romz-pl/b-plus-tree
5af2db1c4188d507d0ff28eac91dc255d4e49a35
[ "Apache-2.0" ]
3
2017-10-30T07:38:49.000Z
2017-10-30T08:55:50.000Z
proj-e/tests/internal_test.cpp
romz-pl/b-plus-tree
5af2db1c4188d507d0ff28eac91dc255d4e49a35
[ "Apache-2.0" ]
null
null
null
#include <gtest/gtest.h> #include <internal.h> // // // TEST(Internal, init) { using Key = int; using Data = int; btree::Internal< Key, Data > internal( nullptr ); const Key key = 2; const Data data = 3; const btree::Leaf< Key, Data >::value_type x( key, data ); internal.insert_value( 0, x ); EXPECT_EQ( internal.value( 0 ), x ); EXPECT_EQ( internal.count( ), 1U ); btree::Internal< Key, Data > c0( nullptr ); btree::Internal< Key, Data > c1( nullptr ); internal.set_child( 0, &c0 ); internal.set_child( 1, &c1 ); const btree::Leaf< Key, Data >::value_type y( key + 1, data + 1 ); internal.insert_value( 0, y ); EXPECT_EQ( internal.value( 0 ), y ); EXPECT_EQ( internal.value( 1 ), x ); EXPECT_EQ( internal.count( ), 2U ); btree::Internal< Key, Data > c2( nullptr ); internal.set_child( 1, &c2 ); internal.remove_value( 0 ); EXPECT_EQ( internal.value( 0 ), x ); EXPECT_EQ( internal.count( ), 1U ); internal.remove_value( 0 ); EXPECT_EQ( internal.count( ), 0U ); }
22.914894
70
0.593315
565863bfca891d32ceac2d062331b9e295cbce2e
2,793
cpp
C++
MusicPlayer.cpp
nickkantack/ArduinoSong
5d71dd4758937fcb58f647dc02fe593d0f7bdcae
[ "MIT" ]
null
null
null
MusicPlayer.cpp
nickkantack/ArduinoSong
5d71dd4758937fcb58f647dc02fe593d0f7bdcae
[ "MIT" ]
null
null
null
MusicPlayer.cpp
nickkantack/ArduinoSong
5d71dd4758937fcb58f647dc02fe593d0f7bdcae
[ "MIT" ]
null
null
null
#include <Arduino.h> #include "Note.h" #include "MusicPlayer.h" #define NOTE_QUEUE_SIZE 100 float _beats_per_second = 1.0; bool _is_buzzer_high; bool _is_playing; bool _is_mid_song; int _buzzer_pin = A0; int _note_index_in_queue; unsigned long _micros_of_last_buzzer_switch; unsigned long _micros_of_note_start; unsigned long _saved_micros_to_next_note; Note _notes[NOTE_QUEUE_SIZE]; int _number_of_notes; MusicPlayer::MusicPlayer() { // No configuration } void MusicPlayer::set_pin(int pin) { _buzzer_pin = pin; pinMode(pin, OUTPUT); digitalWrite(pin, LOW); } void MusicPlayer::set_tempo(float beats_per_second) { _beats_per_second = beats_per_second; } void MusicPlayer::enqueue_note(Note note) { _notes[_number_of_notes] = note; _number_of_notes++; } void MusicPlayer::start() { if (_note_index_in_queue < _number_of_notes) { _is_playing = true; if (_is_mid_song) { _micros_of_note_start = micros() + _notes[_note_index_in_queue].get_period_micros() - _saved_micros_to_next_note; } else { _micros_of_note_start = micros(); } _is_mid_song = true; } } void MusicPlayer::pause() { _saved_micros_to_next_note = get_micros_of_current_note_end() - (micros() - _micros_of_note_start); if (_is_playing) { _is_mid_song = true; } _is_playing = false; } void MusicPlayer::reset_player() { pause(); _note_index_in_queue = 0; } void MusicPlayer::clear_queue() { _note_index_in_queue = 0; _number_of_notes = 0; } void MusicPlayer::handle() { // Flip the buzzer if needed unsigned long now_micros = micros(); if (_note_index_in_queue >= _number_of_notes) { _is_playing = false; _is_mid_song = false; return; } Note currentNote = _notes[_note_index_in_queue]; if (now_micros - _micros_of_last_buzzer_switch > currentNote.get_period_micros()) { _is_buzzer_high = !_is_buzzer_high; digitalWrite(_buzzer_pin, _is_buzzer_high); _micros_of_last_buzzer_switch = now_micros; } // Advance the note if needed if (now_micros - _micros_of_note_start > get_duration_of_current_note_micros()) { _note_index_in_queue++; if (_note_index_in_queue < _number_of_notes) { _micros_of_note_start = now_micros; } } } unsigned long MusicPlayer::get_duration_of_current_note_micros() { float seconds_per_beat = 1 / _beats_per_second; Note current_note = _notes[_note_index_in_queue]; return 1000000L * seconds_per_beat * current_note.get_beat_fraction(); } unsigned long MusicPlayer::get_micros_of_current_note_end() { float seconds_per_beat = 1 / _beats_per_second; Note current_note = _notes[_note_index_in_queue]; unsigned long duration_of_current_note_micros = get_duration_of_current_note_micros(); return duration_of_current_note_micros - _micros_of_note_start; }
26.855769
119
0.756534
5659f243a4ca9717204ad2bbb3d2d565772ee6ff
1,246
cpp
C++
GameGuy/src/Panels/AudioPanel.cpp
salvorizza/GameGuy
b539d5be002387907fe5d6e6e9da5deae234c182
[ "MIT" ]
null
null
null
GameGuy/src/Panels/AudioPanel.cpp
salvorizza/GameGuy
b539d5be002387907fe5d6e6e9da5deae234c182
[ "MIT" ]
null
null
null
GameGuy/src/Panels/AudioPanel.cpp
salvorizza/GameGuy
b539d5be002387907fe5d6e6e9da5deae234c182
[ "MIT" ]
null
null
null
#include "Panels/AudioPanel.h" #include <imgui.h> namespace GameGuy { AudioPanel::AudioPanel() : Panel("Audio Panel ", false, true) { } AudioPanel::~AudioPanel() { } void AudioPanel::addSample(size_t time, double left, double right) { std::lock_guard<std::mutex> lc(mMutex); if (mSamples.size() > MAX_SAMPLES) mSamples.pop_front(); mSamples.push_back(std::make_tuple(time, left, right)); } void AudioPanel::onImGuiRender() { std::lock_guard<std::mutex> lc(mMutex); ImVec2 pos = ImGui::GetWindowPos(); ImVec2 region = ImGui::GetContentRegionAvail(); ImDrawList* drawList = ImGui::GetWindowDrawList(); float xInc = region.x / MAX_SAMPLES; float amp = region.y / 4; ImVec2 previousPos = { pos.x,pos.y + region.y / 2.0f }; for (auto& sample : mSamples) { ImVec2 currentPos; currentPos.y = pos.y + (region.y / 2) + (std::get<1>(sample) * amp); currentPos.x = previousPos.x + xInc; drawList->AddLine(previousPos, currentPos, ImColor(255,0,0)); previousPos = currentPos; } drawList->AddLine({ pos.x,pos.y + region.y / 2.0f }, { pos.x + region.x,pos.y + region.y / 2.0f }, ImColor(255,255,255, 75)); //drawList->AddRectFilled({ 10,10 }, { 40,40 }, ImColor(255, 255, 255)); } }
22.654545
127
0.654896
565bd4355598dc7147bc724f18a0ae8d4768cb67
5,842
cpp
C++
client/Client.cpp
MohamedAshrafTolba/http-client-server
3776f1a5ff1921564d6c288be0ba870dbdacce22
[ "MIT" ]
null
null
null
client/Client.cpp
MohamedAshrafTolba/http-client-server
3776f1a5ff1921564d6c288be0ba870dbdacce22
[ "MIT" ]
null
null
null
client/Client.cpp
MohamedAshrafTolba/http-client-server
3776f1a5ff1921564d6c288be0ba870dbdacce22
[ "MIT" ]
null
null
null
#include "Client.h" #include <sstream> #include <fstream> #include <iostream> #include <thread> #include <mutex> #include <sys/stat.h> #include <condition_variable> #include "../strutil.h" Client::Client(std::string &host_name, std::string &port_number, std::string &requests_file, bool dry_run) { socket = new Socket(host_name, port_number); this->requests_file = requests_file; this->dry_run = dry_run; } Client::~Client() { if (socket != nullptr) { delete socket; } } void Client::run() { std::mutex pipelined_requests_mutex; std::mutex running_mutex; std::mutex socket_mutex; bool running = true; auto f = [&] { running_mutex.lock(); while (running) { running_mutex.unlock(); pipelined_requests_mutex.lock(); if (pipelined_requests.empty()) { pipelined_requests_mutex.unlock(); std::this_thread::sleep_for(std::chrono::seconds(2)); } else { std::string file_name = pipelined_requests.front(); pipelined_requests.pop(); pipelined_requests_mutex.unlock(); socket_mutex.lock(); get_response(GET, file_name); socket_mutex.unlock(); } } pipelined_requests_mutex.lock(); while (!pipelined_requests.empty()) { std::string file_name = pipelined_requests.front(); pipelined_requests.pop(); socket_mutex.lock(); get_response(GET, file_name); socket_mutex.unlock(); } pipelined_requests_mutex.unlock(); }; std::thread *pipelining_thread = nullptr; std::ifstream requests_file_stream(requests_file); std::string request; while (std::getline(requests_file_stream, request)) { if (request.empty()) { continue; } std::stringstream split_stream(request); std::string method, file_name; split_stream >> method; if (!split_stream.eof() && split_stream.tellg() != -1) { split_stream >> file_name; } else { perror("Skipping request: File name is missing"); continue; } RequestMethod req_method = NOP; if (strutil::iequals(method, "GET")) { req_method = GET; } else if (strutil::iequals(method, "POST")) { req_method = POST; } if (req_method == POST) { if (pipelining_thread) { running_mutex.lock(); running = false; running_mutex.unlock(); pipelining_thread->join(); delete pipelining_thread; pipelining_thread = nullptr; } socket_mutex.lock(); make_request(req_method, file_name); get_response(POST, file_name); socket_mutex.unlock(); } else { if (!pipelining_thread) { running = true; pipelining_thread = new std::thread(f); } socket_mutex.lock(); make_request(req_method, file_name); socket_mutex.unlock(); pipelined_requests_mutex.lock(); pipelined_requests.push(file_name); pipelined_requests_mutex.unlock(); } } running_mutex.lock(); running = false; running_mutex.unlock(); pipelining_thread->join(); } int Client::get_client_socket_fd() const { return socket->get_socket_fd(); } std::string Client::get_requests_file() const { return requests_file; } bool Client::is_dry_run() const { return dry_run; } std::string Client::read_file(std::string &file_name) { std::string file_path = "." + file_name; std::ifstream input_stream(file_path); std::string contents(std::istreambuf_iterator<char>(input_stream), {}); input_stream.close(); return contents; } long Client::get_file_size(std::string filename) { struct stat stat_buf; int rc = stat(filename.c_str(), &stat_buf); return rc == 0 ? stat_buf.st_size : -1; } void Client::write_file(std::string &file_name, std::string &contents) { std::string file_path = "." + file_name; std::ofstream output_stream(file_path); output_stream << contents; output_stream.close(); } void Client::make_request(RequestMethod method, std::string &file_name) { std::stringstream request_stream; const static std::string req_method[] = {"GET", "POST", "INVALID"}; request_stream << req_method[method] << ' ' << file_name << ' ' << HTTP_VERSION << "\r\n"; if (method == POST) { request_stream << "Content-Length: " << get_file_size("." + file_name) << "\r\n\r\n"; } else { request_stream << "\r\n"; } std::string request = request_stream.str(); socket->send_http_msg(request); } std::string Client::get_response(RequestMethod method, std::string &file_name) { std::string headers = socket->receive_http_msg_headers(); std::cout << file_name << "\n-----------------------\n" << headers <<"\n----------------------------\n"; std::string file_path = "." + file_name; if (method == POST) { if (headers.find("200 OK") != std::string::npos) { std::string file_contents = read_file(file_name); socket->send_http_msg(file_contents); } return headers; } HttpRequest request(headers); // Hacky implementation to parse the options std::string content_length_str = request.get_options()["Content-Length"]; int content_length = atoi(content_length_str.c_str()); std::string body = socket->receive_http_msg_body(content_length); if (!dry_run) { write_file(file_name, body); } return headers + "\r\n\r\n" + body; }
32.455556
108
0.590894
565bd74681a343d68e75972f65068e4e72a62bf1
1,324
hpp
C++
dev/Basic/long/database/entity/TenureTransitionRate.hpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
50
2018-12-21T08:21:38.000Z
2022-01-24T09:47:59.000Z
dev/Basic/long/database/entity/TenureTransitionRate.hpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
2
2018-12-19T13:42:47.000Z
2019-05-13T04:11:45.000Z
dev/Basic/long/database/entity/TenureTransitionRate.hpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
27
2018-11-28T07:30:34.000Z
2022-02-05T02:22:26.000Z
//Copyright (c) 2016 Singapore-MIT Alliance for Research and Technology //Licensed under the terms of the MIT License, as described in the file: //license.txt (http://opensource.org/licenses/MIT) /* * TenureTransitionRate.hpp * * Created on: 5 Feb 2016 * Author: Chetan Rogbeer <chetan.rogbeer@smart.mit.edu> */ #pragma once #include "Common.hpp" #include "Types.hpp" using namespace std; namespace sim_mob { namespace long_term { class TenureTransitionRate { public: TenureTransitionRate( BigSerial id = 0, string ageGroup = "", string currentStatus = "", string futureStatus = "", double rate = 0.0 ); virtual ~TenureTransitionRate(); BigSerial getId() const; string getAgeGroup() const; string getCurrentStatus() const; string getFutureStatus() const; double getRate() const; /** * Operator to print the data. */ friend std::ostream& operator<<(std::ostream& strm, const TenureTransitionRate& data); private: friend class TenureTransitionRateDao; BigSerial id; string ageGroup; string currentStatus; string futureStatus; double rate; }; } }
24.981132
147
0.599698
565d2f1faea0c63caadf19f1161daada56985a2b
5,614
cpp
C++
lap_sqm_mex_avx512.cpp
bykovda/legendre_transform
1ee6bf8951ce7bebf5abd88bc4ffd956fd6613b1
[ "MIT" ]
null
null
null
lap_sqm_mex_avx512.cpp
bykovda/legendre_transform
1ee6bf8951ce7bebf5abd88bc4ffd956fd6613b1
[ "MIT" ]
null
null
null
lap_sqm_mex_avx512.cpp
bykovda/legendre_transform
1ee6bf8951ce7bebf5abd88bc4ffd956fd6613b1
[ "MIT" ]
null
null
null
/* TODO: rename to fenchel lap_sqm_mex(x1, y1, z1, x2, y2, z2, g2, fun_id, sign) calculates R[j] = max_j {g2[j] - f(xyz1[i], xyz2[j])} when sign = +1 R[j] = min_j {g2[j] - f(xyz1[i], xyz2[j])} when sign = -1 returns R and ind = argmax/argmin The kernel f is defined by fun_id: fun_id = 0 : f = -(x1 x2 + y1 y2 + z1 z2) fun_id = 10 : f = -(x1 x2 + y1 y2) fun_id = 1 : f = -log[1 - (x1 x2 + y1 y2 + z1 z2)] (and +infinity if log-argument is negative) fun_id = 101: f = 1 - (x1 x2 + y1 y2 + z1 z2) (see the Note below) fun_id = 2 : f = sqrt[1 + (x1-x2)^2 + (y1-y2)^2] fun_id = 3 : f = -sqrt[1 - (x1-x2)^2 - (y1-y2)^2] (and +infinity if sqrt-argument is negative) fun_id = 4 : f = sqrt[(x1-x2)^2 + (y1-y2)^2 + (z1-z2)^2] fun_id = 5 : f = -sqrt[(z1-z2)^2 - (x1-x2)^2 - (y1-y2)^2] (and +infinity if sqrt-argument is negative) Note: when fun_id = 101 the function calculates max_j {g2[j] / f(xyz1[i], xyz2[j])} when sign = +1 min_j {g2[j] / f(xyz1[i], xyz2[j])} when sign = -1 */ #include <mex.h> #include <limits> #include <omp.h> #include <immintrin.h> #define simd_block 8 #define fp double #define inf std::numeric_limits<fp>::infinity() void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) { // input data double* XS1 = mxGetPr(prhs[0]); double* YS1 = mxGetPr(prhs[1]); double* ZS1 = mxGetPr(prhs[2]); const int n1 = (int)mxGetM(prhs[0]); double* XS2 = mxGetPr(prhs[3]); double* YS2 = mxGetPr(prhs[4]); double* ZS2 = mxGetPr(prhs[5]); const int n2 = (int)mxGetM(prhs[3]); double* GS2 = mxGetPr(prhs[6]); const int fun_id = (int)*mxGetPr(prhs[7]); const fp sign = (fp)*mxGetPr(prhs[8]); const bool to_max = sign > 0; // output data plhs[0] = mxCreateDoubleMatrix(n1, 1, mxREAL); double* R1 = (double*)mxGetData(plhs[0]); plhs[1] = mxCreateDoubleMatrix(n1, 1, mxREAL); double* ind = (double*)mxGetData(plhs[1]); //plhs[1] = mxCreateNumericMatrix(n1, 1, mxUINT32_CLASS, mxREAL); //unsigned int *ind = (unsigned int *) mxGetData(plhs[1]); const bool cf3D = !((fun_id == 10) || (fun_id == 2) || (fun_id == 3)); // 3D cost function // Copying xyz1 to make sure they are aligned & casting type to fp fp* xs1 = (fp*)_mm_malloc(n1 * sizeof(fp), 64); fp* ys1 = (fp*)_mm_malloc(n1 * sizeof(fp), 64); fp* zs1 = cf3D ? (fp*)_mm_malloc(n1 * sizeof(fp), 64) : NULL; if (!xs1 || !ys1 || (cf3D && !zs1)) return; for (int i = 0; i < n1; i++) { xs1[i] = (fp)XS1[i]; ys1[i] = (fp)YS1[i]; } if (cf3D) for (int i = 0; i < n1; i++) zs1[i] = (fp)ZS1[i]; // Copying xyzg2 to bigger arrays with length being a multiple of simd_block & casting type to fp const int n_blocks = 1 + (n2 - 1) / simd_block; const int n2_ext = n_blocks * simd_block; fp* xs2 = (fp*)_mm_malloc(n2_ext * sizeof(fp), 64); // = new fp[n2_ext]; fp* ys2 = (fp*)_mm_malloc(n2_ext * sizeof(fp), 64); fp* zs2 = cf3D ? (fp*)_mm_malloc(n2_ext * sizeof(fp), 64) : NULL; fp* gs2 = (fp*)_mm_malloc(n2_ext * sizeof(fp), 64); if (!xs2 || !ys2 || (cf3D && !zs2) || !gs2) return; for (int i = 0; i < n2; i++) { xs2[i] = (fp)XS2[i]; ys2[i] = (fp)YS2[i]; gs2[i] = (fp)GS2[i]; } for (int i = n2; i < n2_ext; i++) { xs2[i] = xs2[n2-1]; ys2[i] = ys2[n2-1]; gs2[i] = gs2[n2-1]; } if (cf3D) { for (int i = 0; i < n2; i++) zs2[i] = (fp)ZS2[i]; for (int i = n2; i < n2_ext; i++) zs2[i] = (fp)zs2[n2-1]; } #pragma omp parallel for for (int i = 0; i < n1; i++) { const __m512d _x1 = _mm512_set1_pd(xs1[i]); const __m512d _y1 = _mm512_set1_pd(ys1[i]); const __m512d _z1 = cf3D ? _mm512_set1_pd(zs1[i]) : __m512d(); __m512d _best_val = _mm512_set1_pd(to_max ? -inf : inf); __m512i _best_block = _mm512_set1_epi64(-1); const __m512d _minf = _mm512_set1_pd(-inf); const __m512d zeros = _mm512_setzero_pd(); for (int jb = 0; jb < n_blocks; jb++) { int j = jb * simd_block; const __m512d _x2 = _mm512_load_pd(&xs2[j]); const __m512d _y2 = _mm512_load_pd(&ys2[j]); const __m512d _z2 = cf3D ? _mm512_load_pd(&zs2[j]) : __m512d(); __m512d res; #include "cost_fun_avx512.cpp" const __m512d _g = _mm512_load_pd(&gs2[j]); if (fun_id == 101) res = _mm512_div_pd(_g, res); else res = _mm512_sub_pd(_g, res); const __mmask8 msk2 = _mm512_cmplt_pd_mask(_best_val, res); // best_val < res if (to_max) { _best_val = _mm512_mask_blend_pd(msk2, _best_val, res); _best_block = _mm512_mask_blend_epi64(msk2, _best_block, _mm512_set1_epi64(jb)); } else { _best_val = _mm512_mask_blend_pd(msk2, res, _best_val); _best_block = _mm512_mask_blend_epi64(msk2, _mm512_set1_epi64(jb), _best_block); } } fp* As = (fp*)_mm_malloc(simd_block * sizeof(fp), 64); long long int* Is = (long long int*)_mm_malloc(simd_block * sizeof(long long int), 64); _mm512_store_pd(As, _best_val); _mm512_store_epi64(Is, _best_block); fp best_val = to_max ? -inf : +inf; int best_ind = -1; for (int j = 0; j < simd_block; j++) { fp a = As[j]; if (((!to_max) && (a < best_val)) || (to_max && (a > best_val))) { best_val = a; best_ind = Is[j] * simd_block + j; } } if (best_ind > n2 - 1) best_ind = n2 - 1; R1[i] = best_val; ind[i] = best_ind + 1; // Converting to MATLAB format _mm_free(As); _mm_free(Is); } _mm_free(xs1); _mm_free(xs2); _mm_free(ys1); _mm_free(ys2); if (cf3D) { _mm_free(zs1); _mm_free(zs2); } _mm_free(gs2); }
29.39267
103
0.587104
565d4c7873c1304bc864ac21bd65e7ac298ba816
2,387
cpp
C++
RemovalTool/RemovalTool.cpp
rmusser01/living-off-the-land
b215c7db70d42aa36263dcff2d7858b6894730af
[ "BSD-2-Clause" ]
124
2020-09-08T12:53:19.000Z
2022-03-22T18:45:14.000Z
RemovalTool/RemovalTool.cpp
hidemepls785/living-off-the-land
b215c7db70d42aa36263dcff2d7858b6894730af
[ "BSD-2-Clause" ]
10
2021-03-29T22:11:20.000Z
2021-12-09T08:07:34.000Z
RemovalTool/RemovalTool.cpp
hidemepls785/living-off-the-land
b215c7db70d42aa36263dcff2d7858b6894730af
[ "BSD-2-Clause" ]
26
2020-09-08T12:53:20.000Z
2022-03-15T19:58:34.000Z
#include <Windows.h> #include "../Global/NativeRegistry.h" int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { LPCSTR error = NULL; BOOL removed = FALSE; // Delete registry value HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\(Default), where Injector.exe is stored. HKEY key; if (RegOpenKeyExA(HKEY_CURRENT_USER, "Software\\Microsoft\\Internet Explorer", 0, KEY_ALL_ACCESS, &key) == ERROR_SUCCESS) { DWORD size; LSTATUS result = RegQueryValueExA(key, NULL, 0, NULL, NULL, &size); if (result == ERROR_FILE_NOT_FOUND) { } else if (result == ERROR_SUCCESS) { if (size >= 2) { LPBYTE buffer = new BYTE[size]; if (RegQueryValueExA(key, NULL, 0, NULL, buffer, &size) == ERROR_SUCCESS) { if (buffer[0] == 'M' && buffer[1] == 'Z') { if (RegDeleteValueA(key, NULL) == ERROR_SUCCESS) { removed = TRUE; } else { error = "Could not delete registry value 'HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\(Default)'."; } } } else { error = "Could not read registry value 'HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\(Default)'."; } } } else { error = "Could not query registry value 'HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\(Default)'."; } } else { error = "Could not open registry key 'HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer'."; } if (!error) { // Delete registry value HKCU\...\Run\{NULL}X, where the startup script is stored. // This is a null embedded registry value. Only the native API can delete it. nt_cpp::Udc path = nt_cpp::GetCurrentUserPath() + L"\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\\\0X"; if (nt_cpp::QueryValue(path).type != 0) { if (nt_cpp::DeleteValue(path)) { removed = TRUE; } else { error = "Could not delete registry value 'HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\\{NULL}X'."; } } } if (error != NULL) MessageBoxA(NULL, error, "Living Off The Land - Removal Tool", MB_OK | MB_ICONERROR); else if (removed) MessageBoxA(NULL, "Removed successfully.", "Living Off The Land - Removal Tool", MB_OK | MB_ICONASTERISK); else MessageBoxA(NULL, "Nothing to remove.", "Living Off The Land - Removal Tool", MB_OK | MB_ICONASTERISK); }
32.256757
127
0.668203
565e30463b4f98a0b1e179f888c0f6748885652a
1,029
cpp
C++
app/src/main/cpp/IPlayBuilder.cpp
yishuinanfeng/UnitedPlayer
3e3e43ac7ecaa6636965870420eda600205be34d
[ "Apache-2.0" ]
100
2020-02-01T05:39:16.000Z
2022-03-15T06:54:27.000Z
app/src/main/cpp/IPlayBuilder.cpp
yishuinanfeng/UnitedPlayer
3e3e43ac7ecaa6636965870420eda600205be34d
[ "Apache-2.0" ]
null
null
null
app/src/main/cpp/IPlayBuilder.cpp
yishuinanfeng/UnitedPlayer
3e3e43ac7ecaa6636965870420eda600205be34d
[ "Apache-2.0" ]
16
2020-02-04T05:52:42.000Z
2021-08-09T07:15:27.000Z
// // Created by yanxi on 2019/10/28. // #include "IPlayBuilder.h" #include "IPlayer.h" #include "IDemux.h" #include "XLog.h" #include "IDecode.h" #include "IResample.h" #include "IAudioPlay.h" #include "IVideoView.h" IPlayer *IPlayBuilder::BuildPlayer(unsigned int index) { IPlayer *play = CreatePalyer(index); IDemux *iDemux = CreateDemux(); IDecode *audioDecode = CreateDecode(); IDecode *videoDecode = CreateDecode(); //解复用一帧之后,通知解码器 iDemux->AddOberver(audioDecode); iDemux->AddOberver(videoDecode); IVideoView *iVideoView = CreateVideoView(); //解码一帧之后,通知显示模块 videoDecode->AddOberver(iVideoView); IResample *resample = CreateResample(); audioDecode->AddOberver(resample); IAudioPlay *audioPlay = CreateAudioPlay(); resample->AddOberver(audioPlay); play->iDemux = iDemux; play->audioPlay = audioPlay; play->audioDecode = audioDecode; play->videoDecode = videoDecode; play->resample = resample; play->videoView = iVideoView; return play; }
27.078947
56
0.697765
565ea2dbe5b5bc0ade95a826f48e162f5851317d
133,992
cpp
C++
module/mpc-be/SRC/src/filters/transform/MPCVideoDec/MPCVideoDec.cpp
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
module/mpc-be/SRC/src/filters/transform/MPCVideoDec/MPCVideoDec.cpp
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
module/mpc-be/SRC/src/filters/transform/MPCVideoDec/MPCVideoDec.cpp
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
/* * (C) 2006-2020 see Authors.txt * * This file is part of MPC-BE. * * MPC-BE is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * MPC-BE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "stdafx.h" #include <atlbase.h> #include <MMReg.h> #include "MPCVideoDec.h" #include "DXVADecoder/DXVAAllocator.h" #include "FfmpegContext.h" #include "../../../DSUtil/CPUInfo.h" #include "../../../DSUtil/D3D9Helper.h" #include "../../../DSUtil/DSUtil.h" #include "../../../DSUtil/ffmpeg_log.h" #include "../../../DSUtil/GolombBuffer.h" #include "../../../DSUtil/SysVersion.h" #include "../../../DSUtil/DXVAState.h" #include "../../parser/AviSplitter/AviSplitter.h" #include "../../parser/OggSplitter/OggSplitter.h" #include "../../parser/MpegSplitter/MpegSplitter.h" #include "../../Lock.h" #include <moreuuids.h> #include <FilterInterfaces.h> #include "Version.h" #pragma warning(push) #pragma warning(disable: 4005) #pragma warning(disable: 5033) extern "C" { #include <ffmpeg/libavcodec/avcodec.h> #include <ffmpeg/libavcodec/dxva2.h> #include <ffmpeg/libavutil/intreadwrite.h> #include <ffmpeg/libavutil/imgutils.h> #include <ffmpeg/libavutil/mastering_display_metadata.h> #include <ffmpeg/libavutil/opt.h> #include <ffmpeg/libavutil/pixdesc.h> } #pragma warning(pop) #ifdef _DEBUG #pragma comment(lib, "libmfx_d.lib") #else #pragma comment(lib, "libmfx.lib") #endif // option names #define OPT_REGKEY_VideoDec L"Software\\MPC-BE Filters\\MPC Video Decoder" #define OPT_SECTION_VideoDec L"Filters\\MPC Video Decoder" #define OPT_ThreadNumber L"ThreadNumber" #define OPT_DiscardMode L"DiscardMode" #define OPT_ScanType L"ScanType" #define OPT_ARMode L"ARMode" #define OPT_DXVACheck L"DXVACheckCompatibility" #define OPT_DisableDXVA_SD L"DisableDXVA_SD" #define OPT_SW_prefix L"Sw_" #define OPT_SwRGBLevels L"SwRGBLevels" #define MAX_AUTO_THREADS 32 #pragma region any_constants #ifdef REGISTER_FILTER #define OPT_REGKEY_VCodecs L"Software\\MPC-BE Filters\\MPC Video Decoder\\Codecs" static const struct vcodec_t { const LPCWSTR opt_name; const unsigned __int64 flag; } vcodecs[] = { {L"h264", CODEC_H264 }, {L"h264_mvc", CODEC_H264_MVC }, {L"mpeg1", CODEC_MPEG1 }, {L"mpeg3", CODEC_MPEG2 }, {L"vc1", CODEC_VC1 }, {L"msmpeg4", CODEC_MSMPEG4 }, {L"xvid", CODEC_XVID }, {L"divx", CODEC_DIVX }, {L"wmv", CODEC_WMV }, {L"hevc", CODEC_HEVC }, {L"vp356", CODEC_VP356 }, {L"vp89", CODEC_VP89 }, {L"theora", CODEC_THEORA }, {L"mjpeg", CODEC_MJPEG }, {L"dv", CODEC_DV }, {L"lossless", CODEC_LOSSLESS }, {L"prores", CODEC_PRORES }, {L"canopus", CODEC_CANOPUS }, {L"screc", CODEC_SCREC }, {L"indeo", CODEC_INDEO }, {L"h263", CODEC_H263 }, {L"svq3", CODEC_SVQ3 }, {L"realv", CODEC_REALV }, {L"dirac", CODEC_DIRAC }, {L"binkv", CODEC_BINKV }, {L"amvv", CODEC_AMVV }, {L"flash", CODEC_FLASH }, {L"utvd", CODEC_UTVD }, {L"png", CODEC_PNG }, {L"uncompressed", CODEC_UNCOMPRESSED}, {L"dnxhd", CODEC_DNXHD }, {L"cinepak", CODEC_CINEPAK }, {L"quicktime", CODEC_QT }, {L"cineform", CODEC_CINEFORM }, {L"hap", CODEC_HAP }, {L"av1", CODEC_AV1 }, // dxva codecs {L"h264_dxva", CODEC_H264_DXVA }, {L"hevc_dxva", CODEC_HEVC_DXVA }, {L"mpeg2_dxva", CODEC_MPEG2_DXVA}, {L"vc1_dxva", CODEC_VC1_DXVA }, {L"wmv3_dxva", CODEC_WMV3_DXVA }, {L"vp9_dxva", CODEC_VP9_DXVA } }; #endif struct FFMPEG_CODECS { const CLSID* clsMinorType; const enum AVCodecID nFFCodec; const int FFMPEGCode; const int DXVACode; }; struct { const enum AVCodecID nCodecId; const GUID decoderGUID; const bool bHighBitdepth; } DXVAModes [] = { // H.264 { AV_CODEC_ID_H264, DXVA2_ModeH264_E, false }, { AV_CODEC_ID_H264, DXVA2_ModeH264_F, false }, { AV_CODEC_ID_H264, DXVA2_Intel_H264_ClearVideo, false }, // HEVC { AV_CODEC_ID_HEVC, DXVA2_ModeHEVC_VLD_Main10, true }, { AV_CODEC_ID_HEVC, DXVA2_ModeHEVC_VLD_Main, false }, // MPEG2 { AV_CODEC_ID_MPEG2VIDEO, DXVA2_ModeMPEG2_VLD, false }, // VC1 { AV_CODEC_ID_VC1, DXVA2_ModeVC1_D2010, false }, { AV_CODEC_ID_VC1, DXVA2_ModeVC1_D, false }, // WMV3 { AV_CODEC_ID_WMV3, DXVA2_ModeVC1_D2010, false }, { AV_CODEC_ID_WMV3, DXVA2_ModeVC1_D, false }, // VP9 { AV_CODEC_ID_VP9, DXVA2_ModeVP9_VLD_10bit_Profile2, true }, { AV_CODEC_ID_VP9, DXVA2_ModeVP9_VLD_Profile0, false } }; FFMPEG_CODECS ffCodecs[] = { // Flash video { &MEDIASUBTYPE_FLV1, AV_CODEC_ID_FLV1, VDEC_FLV, -1 }, { &MEDIASUBTYPE_flv1, AV_CODEC_ID_FLV1, VDEC_FLV, -1 }, { &MEDIASUBTYPE_FLV4, AV_CODEC_ID_VP6F, VDEC_FLV, -1 }, { &MEDIASUBTYPE_flv4, AV_CODEC_ID_VP6F, VDEC_FLV, -1 }, { &MEDIASUBTYPE_VP6F, AV_CODEC_ID_VP6F, VDEC_FLV, -1 }, { &MEDIASUBTYPE_vp6f, AV_CODEC_ID_VP6F, VDEC_FLV, -1 }, // VP3 { &MEDIASUBTYPE_VP30, AV_CODEC_ID_VP3, VDEC_VP356, -1 }, { &MEDIASUBTYPE_VP31, AV_CODEC_ID_VP3, VDEC_VP356, -1 }, // VP5 { &MEDIASUBTYPE_VP50, AV_CODEC_ID_VP5, VDEC_VP356, -1 }, { &MEDIASUBTYPE_vp50, AV_CODEC_ID_VP5, VDEC_VP356, -1 }, // VP6 { &MEDIASUBTYPE_VP60, AV_CODEC_ID_VP6, VDEC_VP356, -1 }, { &MEDIASUBTYPE_vp60, AV_CODEC_ID_VP6, VDEC_VP356, -1 }, { &MEDIASUBTYPE_VP61, AV_CODEC_ID_VP6, VDEC_VP356, -1 }, { &MEDIASUBTYPE_vp61, AV_CODEC_ID_VP6, VDEC_VP356, -1 }, { &MEDIASUBTYPE_VP62, AV_CODEC_ID_VP6, VDEC_VP356, -1 }, { &MEDIASUBTYPE_vp62, AV_CODEC_ID_VP6, VDEC_VP356, -1 }, { &MEDIASUBTYPE_VP6A, AV_CODEC_ID_VP6A, VDEC_VP356, -1 }, { &MEDIASUBTYPE_vp6a, AV_CODEC_ID_VP6A, VDEC_VP356, -1 }, // VP7 { &MEDIASUBTYPE_VP70, AV_CODEC_ID_VP7, VDEC_VP789, -1 }, // VP8 { &MEDIASUBTYPE_VP80, AV_CODEC_ID_VP8, VDEC_VP789, -1 }, // VP9 { &MEDIASUBTYPE_VP90, AV_CODEC_ID_VP9, VDEC_VP789, VDEC_DXVA_VP9 }, // Xvid { &MEDIASUBTYPE_XVID, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_xvid, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_XVIX, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_xvix, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, // DivX { &MEDIASUBTYPE_DX50, AV_CODEC_ID_MPEG4, VDEC_DIVX, -1 }, { &MEDIASUBTYPE_dx50, AV_CODEC_ID_MPEG4, VDEC_DIVX, -1 }, { &MEDIASUBTYPE_DIVX, AV_CODEC_ID_MPEG4, VDEC_DIVX, -1 }, { &MEDIASUBTYPE_divx, AV_CODEC_ID_MPEG4, VDEC_DIVX, -1 }, { &MEDIASUBTYPE_Divx, AV_CODEC_ID_MPEG4, VDEC_DIVX, -1 }, // WMV1/2/3 { &MEDIASUBTYPE_WMV1, AV_CODEC_ID_WMV1, VDEC_WMV, -1 }, { &MEDIASUBTYPE_wmv1, AV_CODEC_ID_WMV1, VDEC_WMV, -1 }, { &MEDIASUBTYPE_WMV2, AV_CODEC_ID_WMV2, VDEC_WMV, -1 }, { &MEDIASUBTYPE_wmv2, AV_CODEC_ID_WMV2, VDEC_WMV, -1 }, { &MEDIASUBTYPE_WMV3, AV_CODEC_ID_WMV3, VDEC_WMV, VDEC_DXVA_WMV3 }, { &MEDIASUBTYPE_wmv3, AV_CODEC_ID_WMV3, VDEC_WMV, VDEC_DXVA_WMV3 }, // WMVP { &MEDIASUBTYPE_WMVP, AV_CODEC_ID_WMV3IMAGE, VDEC_WMV, -1 }, // MPEG-2 { &MEDIASUBTYPE_MPEG2_VIDEO, AV_CODEC_ID_MPEG2VIDEO, VDEC_MPEG2, VDEC_DXVA_MPEG2 }, { &MEDIASUBTYPE_MPG2, AV_CODEC_ID_MPEG2VIDEO, VDEC_MPEG2, VDEC_DXVA_MPEG2 }, // MPEG-1 { &MEDIASUBTYPE_MPEG1Packet, AV_CODEC_ID_MPEG1VIDEO, VDEC_MPEG1, -1 }, { &MEDIASUBTYPE_MPEG1Payload, AV_CODEC_ID_MPEG1VIDEO, VDEC_MPEG1, -1 }, // MSMPEG-4 { &MEDIASUBTYPE_DIV3, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_div3, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_DVX3, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_dvx3, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_MP43, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_mp43, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_COL1, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_col1, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_DIV4, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_div4, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_DIV5, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_div5, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_DIV6, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_div6, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_AP41, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_ap41, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_MPG3, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_mpg3, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_DIV2, AV_CODEC_ID_MSMPEG4V2, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_div2, AV_CODEC_ID_MSMPEG4V2, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_MP42, AV_CODEC_ID_MSMPEG4V2, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_mp42, AV_CODEC_ID_MSMPEG4V2, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_MPG4, AV_CODEC_ID_MSMPEG4V1, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_mpg4, AV_CODEC_ID_MSMPEG4V1, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_DIV1, AV_CODEC_ID_MSMPEG4V1, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_div1, AV_CODEC_ID_MSMPEG4V1, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_MP41, AV_CODEC_ID_MSMPEG4V1, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_mp41, AV_CODEC_ID_MSMPEG4V1, VDEC_MSMPEG4, -1 }, // AMV Video { &MEDIASUBTYPE_AMVV, AV_CODEC_ID_AMV, VDEC_AMV, -1 }, // MJPEG { &MEDIASUBTYPE_MJPG, AV_CODEC_ID_MJPEG, VDEC_MJPEG, -1 }, { &MEDIASUBTYPE_QTJpeg, AV_CODEC_ID_MJPEG, VDEC_MJPEG, -1 }, { &MEDIASUBTYPE_MJPA, AV_CODEC_ID_MJPEG, VDEC_MJPEG, -1 }, { &MEDIASUBTYPE_MJPB, AV_CODEC_ID_MJPEGB, VDEC_MJPEG, -1 }, { &MEDIASUBTYPE_MJP2, AV_CODEC_ID_JPEG2000, VDEC_MJPEG, -1 }, { &MEDIASUBTYPE_MJ2C, AV_CODEC_ID_JPEG2000, VDEC_MJPEG, -1 }, // Cinepak { &MEDIASUBTYPE_CVID, AV_CODEC_ID_CINEPAK, VDEC_CINEPAK, -1 }, // DV VIDEO { &MEDIASUBTYPE_dvsl, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_dvsd, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_dvhd, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_dv25, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_dv50, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_dvh1, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_CDVH, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_CDVC, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, // Quicktime DV sybtypes (used in LAV Splitter) { &MEDIASUBTYPE_DVCP, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_DVPP, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_DV5P, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_DVC, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_DVH2, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_DVH3, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_DVH4, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_DVH5, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_DVH6, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_DVHQ, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_DVHP, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_AVdv, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_AVd1, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, // Quicktime { &MEDIASUBTYPE_8BPS, AV_CODEC_ID_8BPS, VDEC_QT, -1 }, { &MEDIASUBTYPE_QTRle, AV_CODEC_ID_QTRLE, VDEC_QT, -1 }, { &MEDIASUBTYPE_QTRpza, AV_CODEC_ID_RPZA, VDEC_QT, -1 }, // Screen recorder { &MEDIASUBTYPE_CSCD, AV_CODEC_ID_CSCD, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_TSCC, AV_CODEC_ID_TSCC, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_TSCC2, AV_CODEC_ID_TSCC2, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_VMnc, AV_CODEC_ID_VMNC, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_FLASHSV1, AV_CODEC_ID_FLASHSV, VDEC_SCREEN, -1 }, // { &MEDIASUBTYPE_FLASHSV2, AV_CODEC_ID_FLASHSV2, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_FPS1, AV_CODEC_ID_FRAPS, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_MSS1, AV_CODEC_ID_MSS1, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_MSS2, AV_CODEC_ID_MSS2, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_MSA1, AV_CODEC_ID_MSA1, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_MTS2, AV_CODEC_ID_MTS2, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_G2M2, AV_CODEC_ID_G2M, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_G2M3, AV_CODEC_ID_G2M, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_G2M4, AV_CODEC_ID_G2M, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_CRAM, AV_CODEC_ID_MSVIDEO1, VDEC_SCREEN, -1 }, // CRAM - Microsoft Video 1 { &MEDIASUBTYPE_FICV, AV_CODEC_ID_FIC, VDEC_SCREEN, -1 }, // UtVideo { &MEDIASUBTYPE_Ut_ULRA, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_ULRG, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_ULY0, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_ULY2, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_ULY4, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_ULH0, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_ULH2, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_ULH4, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, // UtVideo T2 { &MEDIASUBTYPE_Ut_UMRA, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_UMRG, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_UMY2, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_UMY4, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_UMH2, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_UMH4, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, // UtVideo Pro { &MEDIASUBTYPE_Ut_UQRA, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_UQRG, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_UQY0, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_UQY2, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, // DIRAC { &MEDIASUBTYPE_DRAC, AV_CODEC_ID_DIRAC, VDEC_DIRAC, -1 }, // Lossless Video { &MEDIASUBTYPE_HuffYUV, AV_CODEC_ID_HUFFYUV, VDEC_LOSSLESS, -1 }, { &MEDIASUBTYPE_HYMT, AV_CODEC_ID_HYMT, VDEC_LOSSLESS, -1 }, { &MEDIASUBTYPE_FFVHuff, AV_CODEC_ID_FFVHUFF, VDEC_LOSSLESS, -1 }, { &MEDIASUBTYPE_FFV1, AV_CODEC_ID_FFV1, VDEC_LOSSLESS, -1 }, { &MEDIASUBTYPE_Lagarith, AV_CODEC_ID_LAGARITH, VDEC_LOSSLESS, -1 }, { &MEDIASUBTYPE_MAGICYUV, AV_CODEC_ID_MAGICYUV, VDEC_LOSSLESS, -1 }, // Indeo 3/4/5 { &MEDIASUBTYPE_IV31, AV_CODEC_ID_INDEO3, VDEC_INDEO, -1 }, { &MEDIASUBTYPE_IV32, AV_CODEC_ID_INDEO3, VDEC_INDEO, -1 }, { &MEDIASUBTYPE_IV41, AV_CODEC_ID_INDEO4, VDEC_INDEO, -1 }, { &MEDIASUBTYPE_IV50, AV_CODEC_ID_INDEO5, VDEC_INDEO, -1 }, // H264/AVC { &MEDIASUBTYPE_H264, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_h264, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_X264, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_x264, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_VSSH, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_vssh, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_DAVC, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_davc, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_PAVC, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_pavc, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_AVC1, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_avc1, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_H264_bis, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, // H264 MVC { &MEDIASUBTYPE_AMVC, AV_CODEC_ID_H264, VDEC_H264_MVC, -1 }, { &MEDIASUBTYPE_MVC1, AV_CODEC_ID_H264, VDEC_H264_MVC, -1 }, // SVQ3 { &MEDIASUBTYPE_SVQ3, AV_CODEC_ID_SVQ3, VDEC_SVQ, -1 }, // SVQ1 { &MEDIASUBTYPE_SVQ1, AV_CODEC_ID_SVQ1, VDEC_SVQ, -1 }, // H263 { &MEDIASUBTYPE_H263, AV_CODEC_ID_H263, VDEC_H263, -1 }, { &MEDIASUBTYPE_h263, AV_CODEC_ID_H263, VDEC_H263, -1 }, { &MEDIASUBTYPE_S263, AV_CODEC_ID_H263, VDEC_H263, -1 }, { &MEDIASUBTYPE_s263, AV_CODEC_ID_H263, VDEC_H263, -1 }, // Real Video { &MEDIASUBTYPE_RV10, AV_CODEC_ID_RV10, VDEC_REAL, -1 }, { &MEDIASUBTYPE_RV20, AV_CODEC_ID_RV20, VDEC_REAL, -1 }, { &MEDIASUBTYPE_RV30, AV_CODEC_ID_RV30, VDEC_REAL, -1 }, { &MEDIASUBTYPE_RV40, AV_CODEC_ID_RV40, VDEC_REAL, -1 }, // Theora { &MEDIASUBTYPE_THEORA, AV_CODEC_ID_THEORA, VDEC_THEORA, -1 }, { &MEDIASUBTYPE_theora, AV_CODEC_ID_THEORA, VDEC_THEORA, -1 }, // WVC1 { &MEDIASUBTYPE_WVC1, AV_CODEC_ID_VC1, VDEC_VC1, VDEC_DXVA_VC1 }, { &MEDIASUBTYPE_wvc1, AV_CODEC_ID_VC1, VDEC_VC1, VDEC_DXVA_VC1 }, // WMVA { &MEDIASUBTYPE_WMVA, AV_CODEC_ID_VC1, VDEC_VC1, VDEC_DXVA_VC1 }, // WVP2 { &MEDIASUBTYPE_WVP2, AV_CODEC_ID_VC1IMAGE, VDEC_VC1, -1 }, // Apple ProRes { &MEDIASUBTYPE_apch, AV_CODEC_ID_PRORES, VDEC_PRORES, -1 }, { &MEDIASUBTYPE_apcn, AV_CODEC_ID_PRORES, VDEC_PRORES, -1 }, { &MEDIASUBTYPE_apcs, AV_CODEC_ID_PRORES, VDEC_PRORES, -1 }, { &MEDIASUBTYPE_apco, AV_CODEC_ID_PRORES, VDEC_PRORES, -1 }, { &MEDIASUBTYPE_ap4h, AV_CODEC_ID_PRORES, VDEC_PRORES, -1 }, { &MEDIASUBTYPE_ap4x, AV_CODEC_ID_PRORES, VDEC_PRORES, -1 }, { &MEDIASUBTYPE_icpf, AV_CODEC_ID_PRORES, VDEC_PRORES, -1 }, { &MEDIASUBTYPE_icod, AV_CODEC_ID_AIC, VDEC_PRORES, -1 }, // Bink Video { &MEDIASUBTYPE_BINKVI, AV_CODEC_ID_BINKVIDEO, VDEC_BINK, -1 }, { &MEDIASUBTYPE_BINKVB, AV_CODEC_ID_BINKVIDEO, VDEC_BINK, -1 }, // PNG { &MEDIASUBTYPE_PNG, AV_CODEC_ID_PNG, VDEC_PNG, -1 }, // Canopus { &MEDIASUBTYPE_CLLC, AV_CODEC_ID_CLLC, VDEC_CANOPUS, -1 }, { &MEDIASUBTYPE_CUVC, AV_CODEC_ID_HQ_HQA, VDEC_CANOPUS, -1 }, { &MEDIASUBTYPE_CHQX, AV_CODEC_ID_HQX, VDEC_CANOPUS, -1 }, // CineForm { &MEDIASUBTYPE_CFHD, AV_CODEC_ID_CFHD, VDEC_CINEFORM, -1 }, // HEVC { &MEDIASUBTYPE_HEVC, AV_CODEC_ID_HEVC, VDEC_HEVC, VDEC_DXVA_HEVC }, { &MEDIASUBTYPE_HVC1, AV_CODEC_ID_HEVC, VDEC_HEVC, VDEC_DXVA_HEVC }, { &MEDIASUBTYPE_HM10, AV_CODEC_ID_HEVC, VDEC_HEVC, VDEC_DXVA_HEVC }, // Avid DNxHD { &MEDIASUBTYPE_AVdn, AV_CODEC_ID_DNXHD, VDEC_DNXHD, -1 }, // Avid DNxHR { &MEDIASUBTYPE_AVdh, AV_CODEC_ID_DNXHD, VDEC_DNXHD, -1 }, // Other MPEG-4 { &MEDIASUBTYPE_MP4V, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_mp4v, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_M4S2, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_m4s2, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_MP4S, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_mp4s, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_3IV1, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_3iv1, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_3IV2, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_3iv2, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_3IVX, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_3ivx, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_BLZ0, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_blz0, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_DM4V, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_dm4v, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_FFDS, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_ffds, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_FVFW, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_fvfw, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_DXGM, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_dxgm, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_FMP4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_fmp4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_HDX4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_hdx4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_LMP4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_lmp4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_NDIG, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_ndig, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_RMP4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_rmp4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_SMP4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_smp4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_SEDG, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_sedg, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_UMP4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_ump4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_WV1F, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_wv1f, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, // Vidvox Hap { &MEDIASUBTYPE_Hap1, AV_CODEC_ID_HAP, VDEC_HAP, -1 }, { &MEDIASUBTYPE_Hap5, AV_CODEC_ID_HAP, VDEC_HAP, -1 }, { &MEDIASUBTYPE_HapA, AV_CODEC_ID_HAP, VDEC_HAP, -1 }, { &MEDIASUBTYPE_HapM, AV_CODEC_ID_HAP, VDEC_HAP, -1 }, { &MEDIASUBTYPE_HapY, AV_CODEC_ID_HAP, VDEC_HAP, -1 }, // AV1 { &MEDIASUBTYPE_AV01, AV_CODEC_ID_AV1, VDEC_AV1, -1 }, // uncompressed video { &MEDIASUBTYPE_v210, AV_CODEC_ID_V210, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_V410, AV_CODEC_ID_V410, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_r210, AV_CODEC_ID_R210, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_R10g, AV_CODEC_ID_R10K, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_R10k, AV_CODEC_ID_R10K, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_AVrp, AV_CODEC_ID_AVRP, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_Y8, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_Y800, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_Y16, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_I420, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_Y41B, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_Y42B, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_444P, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_cyuv, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_YVU9, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_IYUV, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_UYVY, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_YUY2, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_NV12, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_YV12, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_YV16, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_YV24, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_BGR48, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_BGRA64, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_b48r, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_b64a, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_LAV_RAWVIDEO, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 } }; /* Important: the order should be exactly the same as in ffCodecs[] */ const AMOVIESETUP_MEDIATYPE sudPinTypesIn[] = { // Flash video { &MEDIATYPE_Video, &MEDIASUBTYPE_FLV1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_flv1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FLV4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_flv4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VP6F }, { &MEDIATYPE_Video, &MEDIASUBTYPE_vp6f }, // VP3 { &MEDIATYPE_Video, &MEDIASUBTYPE_VP30 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VP31 }, // VP5 { &MEDIATYPE_Video, &MEDIASUBTYPE_VP50 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_vp50 }, // VP6 { &MEDIATYPE_Video, &MEDIASUBTYPE_VP60 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_vp60 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VP61 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_vp61 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VP62 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_vp62 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VP6A }, { &MEDIATYPE_Video, &MEDIASUBTYPE_vp6a }, // VP7 { &MEDIATYPE_Video, &MEDIASUBTYPE_VP70 }, // VP8 { &MEDIATYPE_Video, &MEDIASUBTYPE_VP80 }, // VP9 { &MEDIATYPE_Video, &MEDIASUBTYPE_VP90 }, // Xvid { &MEDIATYPE_Video, &MEDIASUBTYPE_XVID }, { &MEDIATYPE_Video, &MEDIASUBTYPE_xvid }, { &MEDIATYPE_Video, &MEDIASUBTYPE_XVIX }, { &MEDIATYPE_Video, &MEDIASUBTYPE_xvix }, // DivX { &MEDIATYPE_Video, &MEDIASUBTYPE_DX50 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_dx50 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DIVX }, { &MEDIATYPE_Video, &MEDIASUBTYPE_divx }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Divx }, // WMV1/2/3 { &MEDIATYPE_Video, &MEDIASUBTYPE_WMV1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_wmv1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_WMV2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_wmv2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_WMV3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_wmv3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_WMVP }, // MPEG-2 { &MEDIATYPE_Video, &MEDIASUBTYPE_MPEG2_VIDEO }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MPG2 }, // MPEG-1 { &MEDIATYPE_Video, &MEDIASUBTYPE_MPEG1Packet }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MPEG1Payload }, // MSMPEG-4 { &MEDIATYPE_Video, &MEDIASUBTYPE_DIV3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_div3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVX3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_dvx3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MP43 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_mp43 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_COL1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_col1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DIV4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_div4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DIV5 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_div5 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DIV6 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_div6 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_AP41 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ap41 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MPG3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_mpg3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DIV2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_div2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MP42 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_mp42 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MPG4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_mpg4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DIV1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_div1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MP41 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_mp41 }, // AMV Video { &MEDIATYPE_Video, &MEDIASUBTYPE_AMVV }, // MJPEG { &MEDIATYPE_Video, &MEDIASUBTYPE_MJPG }, { &MEDIATYPE_Video, &MEDIASUBTYPE_QTJpeg }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MJPA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MJPB }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MJP2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MJ2C }, // CINEPAK { &MEDIATYPE_Video, &MEDIASUBTYPE_CVID }, // DV VIDEO { &MEDIATYPE_Video, &MEDIASUBTYPE_dvsl }, { &MEDIATYPE_Video, &MEDIASUBTYPE_dvsd }, { &MEDIATYPE_Video, &MEDIASUBTYPE_dvhd }, { &MEDIATYPE_Video, &MEDIASUBTYPE_dv25 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_dv50 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_dvh1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_CDVH }, { &MEDIATYPE_Video, &MEDIASUBTYPE_CDVC }, // Quicktime DV sybtypes (used in LAV Splitter) { &MEDIATYPE_Video, &MEDIASUBTYPE_DVCP }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVPP }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DV5P }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVH2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVH3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVH4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVH5 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVH6 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVHQ }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVHP }, { &MEDIATYPE_Video, &MEDIASUBTYPE_AVdv }, { &MEDIATYPE_Video, &MEDIASUBTYPE_AVd1 }, // QuickTime video { &MEDIATYPE_Video, &MEDIASUBTYPE_8BPS }, { &MEDIATYPE_Video, &MEDIASUBTYPE_QTRle }, { &MEDIATYPE_Video, &MEDIASUBTYPE_QTRpza }, // Screen recorder { &MEDIATYPE_Video, &MEDIASUBTYPE_CSCD }, { &MEDIATYPE_Video, &MEDIASUBTYPE_TSCC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_TSCC2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VMnc }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FLASHSV1 }, // { &MEDIATYPE_Video, &MEDIASUBTYPE_FLASHSV2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FPS1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MSS1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MSS2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MSA1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MTS2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_G2M2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_G2M3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_G2M4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_CRAM }, // CRAM - Microsoft Video 1 { &MEDIATYPE_Video, &MEDIASUBTYPE_FICV }, // UtVideo { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULRA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULRG }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULY0 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULY2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULY4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULH0 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULH2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULH4 }, // UtVideo T2 { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UMRA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UMRG }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UMY2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UMY4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UMH2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UMH4 }, // UtVideo Pro { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UQRA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UQRG }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UQY0 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UQY2 }, // DIRAC { &MEDIATYPE_Video, &MEDIASUBTYPE_DRAC }, // Lossless Video { &MEDIATYPE_Video, &MEDIASUBTYPE_HuffYUV }, { &MEDIATYPE_Video, &MEDIASUBTYPE_HYMT }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FFVHuff }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FFV1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Lagarith }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MAGICYUV }, // Indeo 3/4/5 { &MEDIATYPE_Video, &MEDIASUBTYPE_IV31 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_IV32 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_IV41 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_IV50 }, // H264/AVC { &MEDIATYPE_Video, &MEDIASUBTYPE_H264 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_h264 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_X264 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_x264 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VSSH }, { &MEDIATYPE_Video, &MEDIASUBTYPE_vssh }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DAVC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_davc }, { &MEDIATYPE_Video, &MEDIASUBTYPE_PAVC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_pavc }, { &MEDIATYPE_Video, &MEDIASUBTYPE_AVC1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_avc1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_H264_bis }, // H264 MVC { &MEDIATYPE_Video, &MEDIASUBTYPE_AMVC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MVC1 }, // SVQ3 { &MEDIATYPE_Video, &MEDIASUBTYPE_SVQ3 }, // SVQ1 { &MEDIATYPE_Video, &MEDIASUBTYPE_SVQ1 }, // H263 { &MEDIATYPE_Video, &MEDIASUBTYPE_H263 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_h263 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_S263 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_s263 }, // Real video { &MEDIATYPE_Video, &MEDIASUBTYPE_RV10 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_RV20 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_RV30 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_RV40 }, // Theora { &MEDIATYPE_Video, &MEDIASUBTYPE_THEORA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_theora }, // VC1 { &MEDIATYPE_Video, &MEDIASUBTYPE_WVC1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_wvc1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_WMVA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_WVP2 }, // Apple ProRes { &MEDIATYPE_Video, &MEDIASUBTYPE_apch }, { &MEDIATYPE_Video, &MEDIASUBTYPE_apcn }, { &MEDIATYPE_Video, &MEDIASUBTYPE_apcs }, { &MEDIATYPE_Video, &MEDIASUBTYPE_apco }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ap4h }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ap4x }, { &MEDIATYPE_Video, &MEDIASUBTYPE_icpf }, { &MEDIATYPE_Video, &MEDIASUBTYPE_icod }, // Bink Video { &MEDIATYPE_Video, &MEDIASUBTYPE_BINKVI }, { &MEDIATYPE_Video, &MEDIASUBTYPE_BINKVB }, // PNG { &MEDIATYPE_Video, &MEDIASUBTYPE_PNG }, // Canopus { &MEDIATYPE_Video, &MEDIASUBTYPE_CLLC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_CUVC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_CHQX }, // CineForm { &MEDIATYPE_Video, &MEDIASUBTYPE_CFHD }, // HEVC { &MEDIATYPE_Video, &MEDIASUBTYPE_HEVC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_HVC1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_HM10 }, // Avid DNxHD { &MEDIATYPE_Video, &MEDIASUBTYPE_AVdn }, // Avid DNxHR { &MEDIATYPE_Video, &MEDIASUBTYPE_AVdh }, // Other MPEG-4 { &MEDIATYPE_Video, &MEDIASUBTYPE_MP4V }, { &MEDIATYPE_Video, &MEDIASUBTYPE_mp4v }, { &MEDIATYPE_Video, &MEDIASUBTYPE_M4S2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_m4s2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MP4S }, { &MEDIATYPE_Video, &MEDIASUBTYPE_mp4s }, { &MEDIATYPE_Video, &MEDIASUBTYPE_3IV1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_3iv1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_3IV2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_3iv2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_3IVX }, { &MEDIATYPE_Video, &MEDIASUBTYPE_3ivx }, { &MEDIATYPE_Video, &MEDIASUBTYPE_BLZ0 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_blz0 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DM4V }, { &MEDIATYPE_Video, &MEDIASUBTYPE_dm4v }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FFDS }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ffds }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FVFW }, { &MEDIATYPE_Video, &MEDIASUBTYPE_fvfw }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DXGM }, { &MEDIATYPE_Video, &MEDIASUBTYPE_dxgm }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FMP4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_fmp4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_HDX4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_hdx4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_LMP4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_lmp4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_NDIG }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ndig }, { &MEDIATYPE_Video, &MEDIASUBTYPE_RMP4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_rmp4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_SMP4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_smp4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_SEDG }, { &MEDIATYPE_Video, &MEDIASUBTYPE_sedg }, { &MEDIATYPE_Video, &MEDIASUBTYPE_UMP4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ump4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_WV1F }, { &MEDIATYPE_Video, &MEDIASUBTYPE_wv1f }, // Vidvox Hap { &MEDIATYPE_Video, &MEDIASUBTYPE_Hap1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Hap5 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_HapA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_HapM }, { &MEDIATYPE_Video, &MEDIASUBTYPE_HapY }, // AV1 { &MEDIATYPE_Video, &MEDIASUBTYPE_AV01 }, }; const AMOVIESETUP_MEDIATYPE sudPinTypesInUncompressed[] = { // uncompressed video { &MEDIATYPE_Video, &MEDIASUBTYPE_v210 }, // YUV 4:2:2 10-bit { &MEDIATYPE_Video, &MEDIASUBTYPE_V410 }, // YUV 4:4:4 10-bit { &MEDIATYPE_Video, &MEDIASUBTYPE_r210 }, // RGB30 { &MEDIATYPE_Video, &MEDIASUBTYPE_R10g }, // RGB30 { &MEDIATYPE_Video, &MEDIASUBTYPE_R10k }, // RGB30 { &MEDIATYPE_Video, &MEDIASUBTYPE_AVrp }, // RGB30 { &MEDIATYPE_Video, &MEDIASUBTYPE_Y8 }, // Y 8-bit (monochrome) { &MEDIATYPE_Video, &MEDIASUBTYPE_Y800 }, // Y 8-bit (monochrome) { &MEDIATYPE_Video, &MEDIASUBTYPE_Y16 }, // Y 16-bit (monochrome) { &MEDIATYPE_Video, &MEDIASUBTYPE_I420 }, // YUV 4:2:0 Planar { &MEDIATYPE_Video, &MEDIASUBTYPE_Y41B }, // YUV 4:1:1 Planar { &MEDIATYPE_Video, &MEDIASUBTYPE_Y42B }, // YUV 4:2:2 Planar { &MEDIATYPE_Video, &MEDIASUBTYPE_444P }, // YUV 4:4:4 Planar { &MEDIATYPE_Video, &MEDIASUBTYPE_cyuv }, // UYVY flipped vertically { &MEDIATYPE_Video, &MEDIASUBTYPE_YVU9 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_IYUV }, { &MEDIATYPE_Video, &MEDIASUBTYPE_UYVY }, { &MEDIATYPE_Video, &MEDIASUBTYPE_YUY2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_NV12 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_YV12 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_YV16 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_YV24 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_BGR48 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_BGRA64 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_b48r }, { &MEDIATYPE_Video, &MEDIASUBTYPE_b64a }, { &MEDIATYPE_Video, &MEDIASUBTYPE_LAV_RAWVIDEO }, }; #pragma endregion any_constants const AMOVIESETUP_MEDIATYPE sudPinTypesOut[] = { {&MEDIATYPE_Video, &MEDIASUBTYPE_NV12}, {&MEDIATYPE_Video, &MEDIASUBTYPE_YV12}, {&MEDIATYPE_Video, &MEDIASUBTYPE_YUY2}, {&MEDIATYPE_Video, &MEDIASUBTYPE_YV16}, {&MEDIATYPE_Video, &MEDIASUBTYPE_AYUV}, {&MEDIATYPE_Video, &MEDIASUBTYPE_YV24}, {&MEDIATYPE_Video, &MEDIASUBTYPE_P010}, {&MEDIATYPE_Video, &MEDIASUBTYPE_P210}, {&MEDIATYPE_Video, &MEDIASUBTYPE_Y410}, {&MEDIATYPE_Video, &MEDIASUBTYPE_P016}, {&MEDIATYPE_Video, &MEDIASUBTYPE_P216}, {&MEDIATYPE_Video, &MEDIASUBTYPE_Y416}, {&MEDIATYPE_Video, &MEDIASUBTYPE_RGB32}, }; #ifdef REGISTER_FILTER const AMOVIESETUP_PIN sudpPins[] = { {L"Input", FALSE, FALSE, FALSE, FALSE, &CLSID_NULL, nullptr, _countof(sudPinTypesIn), sudPinTypesIn}, {L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, nullptr, _countof(sudPinTypesOut), sudPinTypesOut} }; const AMOVIESETUP_PIN sudpPinsUncompressed[] = { {L"Input", FALSE, FALSE, FALSE, FALSE, &CLSID_NULL, nullptr, _countof(sudPinTypesInUncompressed), sudPinTypesInUncompressed}, {L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, nullptr, _countof(sudPinTypesOut), sudPinTypesOut} }; CLSID Converter_clsID = GUIDFromCString(L"{0B7FA55E-FA38-4671-A2F2-B8F300C955C4}"); const AMOVIESETUP_FILTER sudFilters[] = { {&__uuidof(CMPCVideoDecFilter), MPCVideoDecName, MERIT_NORMAL + 1, _countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory}, {&Converter_clsID, MPCVideoConvName, MERIT_NORMAL + 1, _countof(sudpPinsUncompressed), sudpPinsUncompressed, CLSID_LegacyAmFilterCategory} // merit of video converter must be lower than merit of video renderers }; CFactoryTemplate g_Templates[] = { {sudFilters[0].strName, sudFilters[0].clsID, CreateInstance<CMPCVideoDecFilter>, nullptr, &sudFilters[0]}, {sudFilters[1].strName, sudFilters[1].clsID, CreateInstance<CMPCVideoDecFilter>, nullptr, &sudFilters[1]}, {L"CMPCVideoDecPropertyPage", &__uuidof(CMPCVideoDecSettingsWnd), CreateInstance<CInternalPropertyPageTempl<CMPCVideoDecSettingsWnd> >}, {L"CMPCVideoDecPropertyPage2", &__uuidof(CMPCVideoDecCodecWnd), CreateInstance<CInternalPropertyPageTempl<CMPCVideoDecCodecWnd> >}, }; int g_cTemplates = _countof(g_Templates); STDAPI DllRegisterServer() { return AMovieDllRegisterServer2(TRUE); } STDAPI DllUnregisterServer() { return AMovieDllRegisterServer2(FALSE); } #include "../../filters/Filters.h" CFilterApp theApp; #else #include "../../../DSUtil/Profile.h" #endif BOOL CALLBACK EnumFindProcessWnd (HWND hwnd, LPARAM lParam) { DWORD procid = 0; WCHAR WindowClass[40]; GetWindowThreadProcessId(hwnd, &procid); GetClassName(hwnd, WindowClass, _countof(WindowClass)); if (procid == GetCurrentProcessId() && wcscmp(WindowClass, MPC_WND_CLASS_NAMEW) == 0) { HWND* pWnd = (HWND*) lParam; *pWnd = hwnd; return FALSE; } return TRUE; } #define CleanDXVAVariable() { m_DXVADecoderGUID = GUID_NULL; ZeroMemory(&m_DXVA2Config, sizeof(m_DXVA2Config)); } // CMPCVideoDecFilter CMPCVideoDecFilter::CMPCVideoDecFilter(LPUNKNOWN lpunk, HRESULT* phr) : CBaseVideoFilter(L"MPC - Video decoder", lpunk, phr, __uuidof(this)) , m_nThreadNumber(0) , m_nDiscardMode(AVDISCARD_DEFAULT) , m_nScanType(SCAN_AUTO) , m_nARMode(2) , m_nDXVACheckCompatibility(1) , m_nDXVA_SD(0) , m_nSwRGBLevels(0) , m_pAVCodec(nullptr) , m_pAVCtx(nullptr) , m_pFrame(nullptr) , m_pParser(nullptr) , m_nCodecNb(-1) , m_nCodecId(AV_CODEC_ID_NONE) , m_bCalculateStopTime(false) , m_bReorderBFrame(false) , m_nBFramePos(0) , m_bWaitKeyFrame(false) , m_DXVADecoderGUID(GUID_NULL) , m_nActiveCodecs(CODECS_ALL & ~CODEC_H264_MVC) , m_rtAvrTimePerFrame(0) , m_rtLastStop(0) , m_rtStartCache(INVALID_TIME) , m_bDXVACompatible(true) , m_nARX(0) , m_nARY(0) , m_bUseDXVA(true) , m_bUseFFmpeg(true) , m_pDXVADecoder(nullptr) , m_pVideoOutputFormat(nullptr) , m_nVideoOutputCount(0) , m_hDevice(INVALID_HANDLE_VALUE) , m_bWaitingForKeyFrame(TRUE) , m_bRVDropBFrameTimings(FALSE) , m_bInterlaced(FALSE) , m_dwSYNC(0) , m_bDecodingStart(FALSE) , m_bHighBitdepth(FALSE) , m_dRate(1.0) , m_pMSDKDecoder(nullptr) , m_iMvcOutputMode(MVC_OUTPUT_Auto) , m_bMvcSwapLR(false) , m_MVC_Base_View_R_flag(FALSE) , m_dxva_pix_fmt(AV_PIX_FMT_NONE) { if (phr) { *phr = S_OK; } if (m_pOutput) { delete m_pOutput; } m_pOutput = DNew CVideoDecOutputPin(L"CVideoDecOutputPin", this, phr, L"Output"); if (!m_pOutput) { *phr = E_OUTOFMEMORY; return; } for (int i = 0; i < PixFmt_count; i++) { if (i == PixFmt_AYUV || i == PixFmt_RGB48) { m_fPixFmts[i] = false; } else { m_fPixFmts[i] = true; } } memset(&m_DDPixelFormat, 0, sizeof(m_DDPixelFormat)); memset(&m_DXVAFilters, false, sizeof(m_DXVAFilters)); memset(&m_VideoFilters, false, sizeof(m_VideoFilters)); m_VideoFilters[VDEC_UNCOMPRESSED] = true; #ifdef REGISTER_FILTER CRegKey key; ULONG len = 255; if (ERROR_SUCCESS == key.Open(HKEY_CURRENT_USER, OPT_REGKEY_VideoDec, KEY_READ)) { DWORD dw; if (ERROR_SUCCESS == key.QueryDWORDValue(OPT_ThreadNumber, dw)) { m_nThreadNumber = dw; } if (ERROR_SUCCESS == key.QueryDWORDValue(OPT_DiscardMode, dw)) { m_nDiscardMode = dw; } if (ERROR_SUCCESS == key.QueryDWORDValue(OPT_ScanType, dw)) { m_nScanType = (MPC_SCAN_TYPE)dw; } if (ERROR_SUCCESS == key.QueryDWORDValue(OPT_ARMode, dw)) { m_nARMode = dw; } if (ERROR_SUCCESS == key.QueryDWORDValue(OPT_DXVACheck, dw)) { m_nDXVACheckCompatibility = dw; } if (ERROR_SUCCESS == key.QueryDWORDValue(OPT_DisableDXVA_SD, dw)) { m_nDXVA_SD = dw; } for (int i = 0; i < PixFmt_count; i++) { CString optname = OPT_SW_prefix; optname += GetSWOF(i)->name; if (ERROR_SUCCESS == key.QueryDWORDValue(optname, dw)) { m_fPixFmts[i] = !!dw; } } if (ERROR_SUCCESS == key.QueryDWORDValue(OPT_SwRGBLevels, dw)) { m_nSwRGBLevels = dw; } } if (ERROR_SUCCESS == key.Open(HKEY_CURRENT_USER, OPT_REGKEY_VCodecs, KEY_READ)) { m_nActiveCodecs = 0; for (size_t i = 0; i < _countof(vcodecs); i++) { DWORD dw = 1; key.QueryDWORDValue(vcodecs[i].opt_name, dw); if (dw) { m_nActiveCodecs |= vcodecs[i].flag; } } } #else CProfile& profile = AfxGetProfile(); profile.ReadInt(OPT_SECTION_VideoDec, OPT_ThreadNumber, m_nThreadNumber, 0, 16); profile.ReadInt(OPT_SECTION_VideoDec, OPT_ScanType, *(int*)&m_nScanType); profile.ReadInt(OPT_SECTION_VideoDec, OPT_ARMode, m_nARMode); profile.ReadInt(OPT_SECTION_VideoDec, OPT_DiscardMode, m_nDiscardMode); profile.ReadInt(OPT_SECTION_VideoDec, OPT_DXVACheck, m_nDXVACheckCompatibility); profile.ReadInt(OPT_SECTION_VideoDec, OPT_DisableDXVA_SD, m_nDXVA_SD); profile.ReadInt(OPT_SECTION_VideoDec, OPT_SwRGBLevels, m_nSwRGBLevels); for (int i = 0; i < PixFmt_count; i++) { CString optname = OPT_SW_prefix; optname += GetSWOF(i)->name; profile.ReadBool(OPT_SECTION_VideoDec, optname, m_fPixFmts[i]); } #endif if (m_nDiscardMode != AVDISCARD_BIDIR) { m_nDiscardMode = AVDISCARD_DEFAULT; } m_nDXVACheckCompatibility = std::clamp(m_nDXVACheckCompatibility, 0, 3); if (m_nScanType > SCAN_PROGRESSIVE) { m_nScanType = SCAN_AUTO; } if (m_nSwRGBLevels != 1) { m_nSwRGBLevels = 0; } #ifdef DEBUG_OR_LOG av_log_set_callback(ff_log); #else av_log_set_callback(nullptr); #endif m_FormatConverter.SetOptions(m_nSwRGBLevels); HWND hWnd = nullptr; EnumWindows(EnumFindProcessWnd, (LPARAM)&hWnd); DetectVideoCard(hWnd); #ifdef _DEBUG // Check codec definition table size_t nCodecs = _countof(ffCodecs); size_t nPinTypes = _countof(sudPinTypesIn); size_t nPinTypesUncompressed = _countof(sudPinTypesInUncompressed); ASSERT(nCodecs == nPinTypes + nPinTypesUncompressed ); for (size_t i = 0; i < nPinTypes; i++) { ASSERT(ffCodecs[i].clsMinorType == sudPinTypesIn[i].clsMinorType); } for (size_t i = 0; i < nPinTypesUncompressed ; i++) { ASSERT(ffCodecs[nPinTypes + i].clsMinorType == sudPinTypesInUncompressed[i].clsMinorType); } #endif } CMPCVideoDecFilter::~CMPCVideoDecFilter() { Cleanup(); } void CMPCVideoDecFilter::DetectVideoCard(HWND hWnd) { m_nPCIVendor = 0; m_nPCIDevice = 0; m_VideoDriverVersion = 0; auto pD3D9 = D3D9Helper::Direct3DCreate9(); if (pD3D9) { D3DADAPTER_IDENTIFIER9 AdapID9 = {}; if (pD3D9->GetAdapterIdentifier(D3D9Helper::GetAdapter(pD3D9, hWnd), 0, &AdapID9) == S_OK) { m_nPCIVendor = AdapID9.VendorId; m_nPCIDevice = AdapID9.DeviceId; m_VideoDriverVersion = AdapID9.DriverVersion.QuadPart; if (SysVersion::IsWin81orLater() && (m_VideoDriverVersion & 0xffff00000000) == 0 && (m_VideoDriverVersion & 0xffff) == 0) { // fix bug in GetAdapterIdentifier() m_VideoDriverVersion = (m_VideoDriverVersion & 0xffff000000000000) | ((m_VideoDriverVersion & 0xffff0000) << 16) | 0xffffffff; } m_strDeviceDescription.Format(L"%S (%04X:%04X)", AdapID9.Description, m_nPCIVendor, m_nPCIDevice); } pD3D9->Release(); } } REFERENCE_TIME CMPCVideoDecFilter::GetFrameDuration() { if (m_nCodecId == AV_CODEC_ID_MPEG2VIDEO || m_nCodecId == AV_CODEC_ID_MPEG1VIDEO) { if (m_pAVCtx->time_base.num && m_pAVCtx->time_base.den) { REFERENCE_TIME frame_duration = (UNITS * m_pAVCtx->time_base.num / m_pAVCtx->time_base.den) * m_pAVCtx->ticks_per_frame; return frame_duration; } } return m_rtAvrTimePerFrame; } void CMPCVideoDecFilter::UpdateFrameTime(REFERENCE_TIME& rtStart, REFERENCE_TIME& rtStop) { if (rtStart == INVALID_TIME) { rtStart = m_rtLastStop; rtStop = INVALID_TIME; } if (rtStop == INVALID_TIME || m_bCalculateStopTime) { REFERENCE_TIME frame_duration = GetFrameDuration(); if (m_pFrame && m_pFrame->repeat_pict) { frame_duration = frame_duration * 3 / 2; } rtStop = rtStart + (frame_duration / m_dRate); } m_rtLastStop = rtStop; } void CMPCVideoDecFilter::GetFrameTimeStamp(AVFrame* pFrame, REFERENCE_TIME& rtStart, REFERENCE_TIME& rtStop) { // Reorder B-Frames if needed if (m_bReorderBFrame && m_pAVCtx->has_b_frames) { rtStart = m_tBFrameDelay[m_nBFramePos].rtStart; rtStop = m_tBFrameDelay[m_nBFramePos].rtStop; } else { rtStart = pFrame->best_effort_timestamp; if (pFrame->pkt_duration) { rtStop = rtStart + pFrame->pkt_duration; } else { rtStop = INVALID_TIME; } } } bool CMPCVideoDecFilter::AddFrameSideData(IMediaSample* pSample, AVFrame* pFrame) { CheckPointer(pSample, false); CheckPointer(pFrame, false); CComPtr<IMediaSideData> pMediaSideData; if (SUCCEEDED(pSample->QueryInterface(&pMediaSideData))) { HRESULT hr = E_FAIL; if (AVFrameSideData* sd = av_frame_get_side_data(pFrame, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA)) { if (sd->size == sizeof(AVMasteringDisplayMetadata)) { AVMasteringDisplayMetadata* metadata = (AVMasteringDisplayMetadata*)sd->data; MediaSideDataHDR hdr = { 0 }; if (metadata->has_primaries) { // export the display primaries in GBR order hdr.display_primaries_x[0] = av_q2d(metadata->display_primaries[1][0]); hdr.display_primaries_y[0] = av_q2d(metadata->display_primaries[1][1]); hdr.display_primaries_x[1] = av_q2d(metadata->display_primaries[2][0]); hdr.display_primaries_y[1] = av_q2d(metadata->display_primaries[2][1]); hdr.display_primaries_x[2] = av_q2d(metadata->display_primaries[0][0]); hdr.display_primaries_y[2] = av_q2d(metadata->display_primaries[0][1]); hdr.white_point_x = av_q2d(metadata->white_point[0]); hdr.white_point_y = av_q2d(metadata->white_point[1]); } if (metadata->has_luminance) { hdr.max_display_mastering_luminance = av_q2d(metadata->max_luminance); hdr.min_display_mastering_luminance = av_q2d(metadata->min_luminance); } hr = pMediaSideData->SetSideData(IID_MediaSideDataHDR, (const BYTE*)&hdr, sizeof(hdr)); } else { DLog(L"CMPCVideoDecFilter::AddFrameSideData(): Found HDR data of an unexpected size (%d)", sd->size); } } else if (m_FilterInfo.masterDataHDR) { hr = pMediaSideData->SetSideData(IID_MediaSideDataHDR, (const BYTE*)m_FilterInfo.masterDataHDR, sizeof(MediaSideDataHDR)); SAFE_DELETE(m_FilterInfo.masterDataHDR); } if (AVFrameSideData* sd = av_frame_get_side_data(pFrame, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL)) { if (sd->size == sizeof(AVContentLightMetadata)) { hr = pMediaSideData->SetSideData(IID_MediaSideDataHDRContentLightLevel, (const BYTE*)sd->data, sd->size); } else { DLog(L"CMPCVideoDecFilter::AddFrameSideData(): Found HDR Light Level data of an unexpected size (%d)", sd->size); } } else if (m_FilterInfo.HDRContentLightLevel) { hr = pMediaSideData->SetSideData(IID_MediaSideDataHDRContentLightLevel, (const BYTE*)m_FilterInfo.HDRContentLightLevel, sizeof(MediaSideDataHDRContentLightLevel)); SAFE_DELETE(m_FilterInfo.HDRContentLightLevel); } return (hr == S_OK); } return false; } // some codecs can reset the values width/height on initialization int CMPCVideoDecFilter::PictWidth() { return m_pAVCtx->width ? m_pAVCtx->width : m_pAVCtx->coded_width; } int CMPCVideoDecFilter::PictHeight() { return m_pAVCtx->height ? m_pAVCtx->height : m_pAVCtx->coded_height; } static bool IsFFMPEGEnabled(FFMPEG_CODECS ffcodec, const bool FFmpegFilters[VDEC_COUNT]) { if (ffcodec.FFMPEGCode < 0 || ffcodec.FFMPEGCode >= VDEC_COUNT) { return false; } return FFmpegFilters[ffcodec.FFMPEGCode]; } static bool IsDXVAEnabled(FFMPEG_CODECS ffcodec, const bool DXVAFilters[VDEC_DXVA_COUNT]) { if (ffcodec.DXVACode < 0 || ffcodec.DXVACode >= VDEC_DXVA_COUNT) { return false; } return DXVAFilters[ffcodec.DXVACode]; } int CMPCVideoDecFilter::FindCodec(const CMediaType* mtIn, BOOL bForced/* = FALSE*/) { m_bUseFFmpeg = false; m_bUseDXVA = false; for (size_t i = 0; i < _countof(ffCodecs); i++) if (mtIn->subtype == *ffCodecs[i].clsMinorType) { #ifndef REGISTER_FILTER m_bUseFFmpeg = bForced || IsFFMPEGEnabled(ffCodecs[i], m_VideoFilters); m_bUseDXVA = bForced || IsDXVAEnabled(ffCodecs[i], m_DXVAFilters); return ((m_bUseDXVA || m_bUseFFmpeg) ? i : -1); #else bool bCodecActivated = false; m_bUseFFmpeg = true; switch (ffCodecs[i].nFFCodec) { case AV_CODEC_ID_FLV1 : case AV_CODEC_ID_VP6F : bCodecActivated = (m_nActiveCodecs & CODEC_FLASH) != 0; break; case AV_CODEC_ID_MPEG4 : if ((*ffCodecs[i].clsMinorType == MEDIASUBTYPE_DX50) || // DivX (*ffCodecs[i].clsMinorType == MEDIASUBTYPE_dx50) || (*ffCodecs[i].clsMinorType == MEDIASUBTYPE_DIVX) || (*ffCodecs[i].clsMinorType == MEDIASUBTYPE_divx) || (*ffCodecs[i].clsMinorType == MEDIASUBTYPE_Divx) ) { bCodecActivated = (m_nActiveCodecs & CODEC_DIVX) != 0; } else { bCodecActivated = (m_nActiveCodecs & CODEC_XVID) != 0; // Xvid/MPEG-4 } break; case AV_CODEC_ID_WMV1 : case AV_CODEC_ID_WMV2 : case AV_CODEC_ID_WMV3IMAGE : bCodecActivated = (m_nActiveCodecs & CODEC_WMV) != 0; break; case AV_CODEC_ID_WMV3 : m_bUseDXVA = (m_nActiveCodecs & CODEC_WMV3_DXVA) != 0; m_bUseFFmpeg = (m_nActiveCodecs & CODEC_WMV) != 0; bCodecActivated = m_bUseDXVA || m_bUseFFmpeg; break; case AV_CODEC_ID_MSMPEG4V3 : case AV_CODEC_ID_MSMPEG4V2 : case AV_CODEC_ID_MSMPEG4V1 : bCodecActivated = (m_nActiveCodecs & CODEC_MSMPEG4) != 0; break; case AV_CODEC_ID_H264 : if ((*ffCodecs[i].clsMinorType == MEDIASUBTYPE_MVC1) || (*ffCodecs[i].clsMinorType == MEDIASUBTYPE_AMVC)) { bCodecActivated = (m_nActiveCodecs & CODEC_H264_MVC) != 0; } else { m_bUseDXVA = (m_nActiveCodecs & CODEC_H264_DXVA) != 0; m_bUseFFmpeg = (m_nActiveCodecs & CODEC_H264) != 0; bCodecActivated = m_bUseDXVA || m_bUseFFmpeg; } break; case AV_CODEC_ID_HEVC : m_bUseDXVA = (m_nActiveCodecs & CODEC_HEVC_DXVA) != 0; m_bUseFFmpeg = (m_nActiveCodecs & CODEC_HEVC) != 0; bCodecActivated = m_bUseDXVA || m_bUseFFmpeg; break; case AV_CODEC_ID_SVQ3 : case AV_CODEC_ID_SVQ1 : bCodecActivated = (m_nActiveCodecs & CODEC_SVQ3) != 0; break; case AV_CODEC_ID_H263 : bCodecActivated = (m_nActiveCodecs & CODEC_H263) != 0; break; case AV_CODEC_ID_DIRAC : bCodecActivated = (m_nActiveCodecs & CODEC_DIRAC) != 0; break; case AV_CODEC_ID_DVVIDEO : bCodecActivated = (m_nActiveCodecs & CODEC_DV) != 0; break; case AV_CODEC_ID_THEORA : bCodecActivated = (m_nActiveCodecs & CODEC_THEORA) != 0; break; case AV_CODEC_ID_VC1 : m_bUseDXVA = (m_nActiveCodecs & CODEC_VC1_DXVA) != 0; m_bUseFFmpeg = (m_nActiveCodecs & CODEC_VC1) != 0; bCodecActivated = m_bUseDXVA || m_bUseFFmpeg; break; case AV_CODEC_ID_VC1IMAGE : bCodecActivated = (m_nActiveCodecs & CODEC_VC1) != 0; break; case AV_CODEC_ID_AMV : bCodecActivated = (m_nActiveCodecs & CODEC_AMVV) != 0; break; case AV_CODEC_ID_LAGARITH : bCodecActivated = (m_nActiveCodecs & CODEC_LOSSLESS) != 0; break; case AV_CODEC_ID_VP3 : case AV_CODEC_ID_VP5 : case AV_CODEC_ID_VP6 : case AV_CODEC_ID_VP6A : bCodecActivated = (m_nActiveCodecs & CODEC_VP356) != 0; break; case AV_CODEC_ID_VP7 : case AV_CODEC_ID_VP8 : bCodecActivated = (m_nActiveCodecs & CODEC_VP89) != 0; break; case AV_CODEC_ID_VP9 : m_bUseDXVA = (m_nActiveCodecs & CODEC_VP9_DXVA) != 0; m_bUseFFmpeg = (m_nActiveCodecs & CODEC_VP89) != 0; bCodecActivated = m_bUseDXVA || m_bUseFFmpeg; break; case AV_CODEC_ID_MJPEG : case AV_CODEC_ID_MJPEGB : bCodecActivated = (m_nActiveCodecs & CODEC_MJPEG) != 0; break; case AV_CODEC_ID_INDEO3 : case AV_CODEC_ID_INDEO4 : case AV_CODEC_ID_INDEO5 : bCodecActivated = (m_nActiveCodecs & CODEC_INDEO) != 0; break; case AV_CODEC_ID_UTVIDEO : bCodecActivated = (m_nActiveCodecs & CODEC_UTVD) != 0; break; case AV_CODEC_ID_CSCD : case AV_CODEC_ID_TSCC : case AV_CODEC_ID_TSCC2 : case AV_CODEC_ID_VMNC : bCodecActivated = (m_nActiveCodecs & CODEC_SCREC) != 0; break; case AV_CODEC_ID_RV10 : case AV_CODEC_ID_RV20 : case AV_CODEC_ID_RV30 : case AV_CODEC_ID_RV40 : bCodecActivated = (m_nActiveCodecs & CODEC_REALV) != 0; break; case AV_CODEC_ID_MPEG2VIDEO : m_bUseDXVA = (m_nActiveCodecs & CODEC_MPEG2_DXVA) != 0; m_bUseFFmpeg = (m_nActiveCodecs & CODEC_MPEG2) != 0; bCodecActivated = m_bUseDXVA || m_bUseFFmpeg; break; case AV_CODEC_ID_MPEG1VIDEO : bCodecActivated = (m_nActiveCodecs & CODEC_MPEG1) != 0; break; case AV_CODEC_ID_PRORES : bCodecActivated = (m_nActiveCodecs & CODEC_PRORES) != 0; break; case AV_CODEC_ID_BINKVIDEO : bCodecActivated = (m_nActiveCodecs & CODEC_BINKV) != 0; break; case AV_CODEC_ID_PNG : bCodecActivated = (m_nActiveCodecs & CODEC_PNG) != 0; break; case AV_CODEC_ID_CLLC : case AV_CODEC_ID_HQ_HQA : case AV_CODEC_ID_HQX : bCodecActivated = (m_nActiveCodecs & CODEC_CANOPUS) != 0; break; case AV_CODEC_ID_CFHD : bCodecActivated = (m_nActiveCodecs & VDEC_CINEFORM) != 0; break; case AV_CODEC_ID_V210 : case AV_CODEC_ID_V410 : case AV_CODEC_ID_R210 : case AV_CODEC_ID_R10K : case AV_CODEC_ID_RAWVIDEO : bCodecActivated = (m_nActiveCodecs & CODEC_UNCOMPRESSED) != 0; break; case AV_CODEC_ID_DNXHD : bCodecActivated = (m_nActiveCodecs & CODEC_DNXHD) != 0; break; case AV_CODEC_ID_CINEPAK : bCodecActivated = (m_nActiveCodecs & CODEC_CINEPAK) != 0; break; case AV_CODEC_ID_8BPS : case AV_CODEC_ID_QTRLE : case AV_CODEC_ID_RPZA : bCodecActivated = (m_nActiveCodecs & CODEC_QT) != 0; break; case AV_CODEC_ID_HAP : bCodecActivated = (m_nActiveCodecs & CODEC_HAP) != 0; break; case AV_CODEC_ID_AV1 : bCodecActivated = (m_nActiveCodecs & CODEC_AV1) != 0; break; } if (!bCodecActivated && !bForced) { m_bUseFFmpeg = false; } return ((bForced || bCodecActivated) ? i : -1); #endif } return -1; } void CMPCVideoDecFilter::Cleanup() { CAutoLock cAutoLock(&m_csReceive); CleanupFFmpeg(); SAFE_DELETE(m_pMSDKDecoder); SAFE_DELETE(m_pDXVADecoder); SAFE_DELETE_ARRAY(m_pVideoOutputFormat); CleanupD3DResources(); m_FilterInfo.Clear(); } void CMPCVideoDecFilter::CleanupD3DResources() { if (m_hDevice != INVALID_HANDLE_VALUE) { m_pDeviceManager->CloseDeviceHandle(m_hDevice); m_hDevice = INVALID_HANDLE_VALUE; } m_pDeviceManager.Release(); m_pDecoderService.Release(); } void CMPCVideoDecFilter::CleanupFFmpeg() { m_pAVCodec = nullptr; av_parser_close(m_pParser); m_pParser = nullptr; if (m_pAVCtx) { av_freep(&m_pAVCtx->hwaccel_context); avcodec_free_context(&m_pAVCtx); } av_frame_free(&m_pFrame); m_FormatConverter.Cleanup(); m_nCodecNb = -1; m_nCodecId = AV_CODEC_ID_NONE; } STDMETHODIMP CMPCVideoDecFilter::NonDelegatingQueryInterface(REFIID riid, void** ppv) { return QI(IMPCVideoDecFilter) QI(ISpecifyPropertyPages) QI(ISpecifyPropertyPages2) __super::NonDelegatingQueryInterface(riid, ppv); } HRESULT CMPCVideoDecFilter::CheckInputType(const CMediaType* mtIn) { for (size_t i = 0; i < _countof(sudPinTypesIn); i++) { if ((mtIn->majortype == *sudPinTypesIn[i].clsMajorType) && (mtIn->subtype == *sudPinTypesIn[i].clsMinorType)) { return S_OK; } } for (size_t i = 0; i < _countof(sudPinTypesInUncompressed); i++) { if ((mtIn->majortype == *sudPinTypesInUncompressed[i].clsMajorType) && (mtIn->subtype == *sudPinTypesInUncompressed[i].clsMinorType)) { return S_OK; } } return VFW_E_TYPE_NOT_ACCEPTED; } HRESULT CMPCVideoDecFilter::CheckTransform(const CMediaType* mtIn, const CMediaType* mtOut) { return CheckInputType(mtIn); // TODO - add check output MediaType } HRESULT CMPCVideoDecFilter::SetMediaType(PIN_DIRECTION direction, const CMediaType *pmt) { if (direction == PINDIR_INPUT) { HRESULT hr = InitDecoder(pmt); if (FAILED(hr)) { return hr; } BuildOutputFormat(); if (UseDXVA2() && (m_pCurrentMediaType != *pmt)) { hr = ReinitDXVA2Decoder(); if (FAILED(hr)) { return hr; } } m_bDecodingStart = FALSE; m_pCurrentMediaType = *pmt; } else if (direction == PINDIR_OUTPUT) { BITMAPINFOHEADER bihOut; if (!ExtractBIH(&m_pOutput->CurrentMediaType(), &bihOut)) { return E_FAIL; } m_FormatConverter.UpdateOutput2(bihOut.biCompression, bihOut.biWidth, bihOut.biHeight); } return __super::SetMediaType(direction, pmt); } bool CMPCVideoDecFilter::IsDXVASupported() { if (m_nCodecId != AV_CODEC_ID_NONE) { // Enabled by user ? if (m_bUseDXVA) { // is the file compatible ? if (m_bDXVACompatible) { // Does the codec suppport DXVA ? for (int i = 0; i < _countof(DXVAModes); i++) { if (m_nCodecId == DXVAModes[i].nCodecId) { return true; } } } } } return false; } HRESULT CMPCVideoDecFilter::FindDecoderConfiguration() { DLog(L"CMPCVideoDecFilter::FindDecoderConfiguration(DXVA2)"); HRESULT hr = E_FAIL; CleanDXVAVariable(); if (m_pDecoderService) { UINT cDecoderGuids = 0; GUID* pDecoderGuids = nullptr; GUID decoderGuid = GUID_NULL; BOOL bFoundDXVA2Configuration = FALSE; DXVA2_ConfigPictureDecode config = { 0 }; if (SUCCEEDED(hr = m_pDecoderService->GetDecoderDeviceGuids(&cDecoderGuids, &pDecoderGuids)) && cDecoderGuids) { std::vector<GUID> supportedDecoderGuids; DLog(L" => Enumerating supported DXVA2 modes:"); for (UINT iGuid = 0; iGuid < cDecoderGuids; iGuid++) { const auto& guid = pDecoderGuids[iGuid]; #ifdef DEBUG_OR_LOG CString msg; msg.Format(L" %s", GetGUIDString(guid)); #endif if (IsSupportedDecoderMode(guid)) { #ifdef DEBUG_OR_LOG msg.Append(L" - supported"); #endif if (guid == DXVA2_ModeH264_E || guid == DXVA2_ModeH264_F) { supportedDecoderGuids.insert(supportedDecoderGuids.cbegin(), guid); } else { supportedDecoderGuids.emplace_back(guid); } } #ifdef DEBUG_OR_LOG DLog(msg); #endif } if (!supportedDecoderGuids.empty()) { for (const auto& guid : supportedDecoderGuids) { DLog(L" => Attempt : %s", GetGUIDString(guid)); if (DXVA2_Intel_H264_ClearVideo == guid) { const int width_mbs = m_nSurfaceWidth / 16; const int height_mbs = m_nSurfaceWidth / 16; const int max_ref_frames_dpb41 = std::min(11, 32768 / (width_mbs * height_mbs)); if (m_pAVCtx->refs > max_ref_frames_dpb41) { DLog(L" => Too many reference frames for Intel H.264 ClearVideo decoder, skip"); continue; } } // Find a configuration that we support. if (FAILED(hr = FindDXVA2DecoderConfiguration(m_pDecoderService, guid, &config, &bFoundDXVA2Configuration))) { break; } if (bFoundDXVA2Configuration) { // Found a good configuration. Save the GUID. decoderGuid = guid; DLog(L" => Use : %s", GetGUIDString(decoderGuid)); break; } } } } if (pDecoderGuids) { CoTaskMemFree(pDecoderGuids); } if (!bFoundDXVA2Configuration) { hr = E_FAIL; // Unable to find a configuration. } if (SUCCEEDED(hr)) { m_DXVA2Config = config; m_DXVADecoderGUID = decoderGuid; } } return hr; } #define H264_CHECK_PROFILE(profile) \ (((profile) & ~FF_PROFILE_H264_CONSTRAINED) <= FF_PROFILE_H264_HIGH) #define HEVC_CHECK_PROFILE(profile) \ ((profile) <= FF_PROFILE_HEVC_MAIN_10) #define VP9_CHECK_PROFILE(profile) \ ((profile) == FF_PROFILE_VP9_0 || (profile) == FF_PROFILE_VP9_2) static bool check_dxva_compatible(const AVCodecID& codec, const AVPixelFormat& pix_fmt, const int& profile) { switch (codec) { case AV_CODEC_ID_MPEG2VIDEO: if (pix_fmt != AV_PIX_FMT_YUV420P && pix_fmt != AV_PIX_FMT_YUVJ420P) { return false; } break; case AV_CODEC_ID_H264: if (pix_fmt != AV_PIX_FMT_YUV420P && pix_fmt != AV_PIX_FMT_YUVJ420P) { return false; } if (profile != FF_PROFILE_UNKNOWN && !H264_CHECK_PROFILE(profile)) { return false; } break; case AV_CODEC_ID_HEVC: if (pix_fmt != AV_PIX_FMT_YUV420P && pix_fmt != AV_PIX_FMT_YUVJ420P && pix_fmt != AV_PIX_FMT_YUV420P10) { return false; } if (profile != FF_PROFILE_UNKNOWN && !HEVC_CHECK_PROFILE(profile)) { return false; } break; case AV_CODEC_ID_VP9: if (pix_fmt != AV_PIX_FMT_YUV420P && pix_fmt != AV_PIX_FMT_YUVJ420P && pix_fmt != AV_PIX_FMT_YUV420P10) { return false; } if (profile != FF_PROFILE_UNKNOWN && !VP9_CHECK_PROFILE(profile)) { return false; } break; case AV_CODEC_ID_WMV3: case AV_CODEC_ID_VC1: if (profile == FF_PROFILE_VC1_COMPLEX) { return false; } } return true; } HRESULT CMPCVideoDecFilter::InitDecoder(const CMediaType *pmt) { DLog(L"CMPCVideoDecFilter::InitDecoder()"); const BOOL bChangeType = (m_pCurrentMediaType != *pmt); const BOOL bReinit = (m_pAVCtx != nullptr); int64_t x264_build = -1; if (m_nCodecId == AV_CODEC_ID_H264 && bReinit && !bChangeType) { int64_t val = -1; if (av_opt_get_int(m_pAVCtx->priv_data, "x264_build", 0, &val) >= 0) { x264_build = val; } } redo: CleanupFFmpeg(); const int nNewCodec = FindCodec(pmt, bReinit); if (nNewCodec == -1) { return VFW_E_TYPE_NOT_ACCEPTED; } // Prevent connection to the video decoder - need to support decoding of uncompressed video (v210, V410, Y8, I420) CComPtr<IBaseFilter> pFilter = GetFilterFromPin(m_pInput->GetConnected()); if (pFilter && IsVideoDecoder(pFilter, true)) { return VFW_E_TYPE_NOT_ACCEPTED; } m_nCodecNb = nNewCodec; if (bChangeType) { ExtractAvgTimePerFrame(pmt, m_rtAvrTimePerFrame); int wout, hout; ExtractDim(pmt, wout, hout, m_nARX, m_nARY); UNREFERENCED_PARAMETER(wout); UNREFERENCED_PARAMETER(hout); } m_bMVC_Output_TopBottom = FALSE; if (pmt->subtype == MEDIASUBTYPE_AMVC || pmt->subtype == MEDIASUBTYPE_MVC1) { if (!m_pMSDKDecoder) { m_pMSDKDecoder = DNew CMSDKDecoder(this); } HRESULT hr = m_pMSDKDecoder->InitDecoder(pmt); if (hr != S_OK) { SAFE_DELETE(m_pMSDKDecoder); } if (m_pMSDKDecoder) { m_bMVC_Output_TopBottom = m_iMvcOutputMode == MVC_OUTPUT_TopBottom; return S_OK; } return VFW_E_TYPE_NOT_ACCEPTED; } m_nCodecId = ffCodecs[nNewCodec].nFFCodec; m_pAVCodec = avcodec_find_decoder(m_nCodecId); CheckPointer(m_pAVCodec, VFW_E_UNSUPPORTED_VIDEO); if (bChangeType) { const CLSID clsidInput = GetCLSID(m_pInput->GetConnected()); const BOOL bNotTrustSourceTimeStamp = (clsidInput == GUIDFromCString(L"{A2E7EDBB-DCDD-4C32-A2A9-0CFBBE6154B4}") // Daum PotPlayer's MKV Source || clsidInput == CLSID_WMAsfReader); // WM ASF Reader m_bCalculateStopTime = (m_nCodecId == AV_CODEC_ID_H264 || m_nCodecId == AV_CODEC_ID_DIRAC || (m_nCodecId == AV_CODEC_ID_MPEG4 && pmt->formattype == FORMAT_MPEG2Video) || bNotTrustSourceTimeStamp); m_bRVDropBFrameTimings = (m_nCodecId == AV_CODEC_ID_RV10 || m_nCodecId == AV_CODEC_ID_RV20 || m_nCodecId == AV_CODEC_ID_RV30 || m_nCodecId == AV_CODEC_ID_RV40); auto ReadSourceHeader = [&]() { if (m_dwSYNC != 0) { return; } m_dwSYNC = -1; CString fn; BeginEnumFilters(m_pGraph, pEF, pBF) { CComQIPtr<IFileSourceFilter> pFSF = pBF; if (pFSF) { LPOLESTR pFN = nullptr; AM_MEDIA_TYPE mt; if (SUCCEEDED(pFSF->GetCurFile(&pFN, &mt)) && pFN && *pFN) { fn = CString(pFN); CoTaskMemFree(pFN); } break; } } EndEnumFilters if (!fn.IsEmpty() && ::PathFileExistsW(fn)) { CFile f; CFileException fileException; if (!f.Open(fn, CFile::modeRead | CFile::typeBinary | CFile::shareDenyNone, &fileException)) { DLog(L"CMPCVideoDecFilter::ReadSource() : Can't open file '%s', error = %u", fn, fileException.m_cause); return; } f.Read(&m_dwSYNC, sizeof(m_dwSYNC)); f.Close(); } }; auto IsAVI = [&]() { ReadSourceHeader(); return (m_dwSYNC == MAKEFOURCC('R','I','F','F')); }; auto IsOGG = [&]() { ReadSourceHeader(); return (m_dwSYNC == MAKEFOURCC('O','g','g','S')); }; // Enable B-Frame reorder m_bReorderBFrame = !(clsidInput == __uuidof(CMpegSourceFilter) || clsidInput == __uuidof(CMpegSplitterFilter)) && !(m_pAVCodec->capabilities & AV_CODEC_CAP_FRAME_THREADS) && !(m_nCodecId == AV_CODEC_ID_MPEG1VIDEO || m_nCodecId == AV_CODEC_ID_MPEG2VIDEO) || (m_nCodecId == AV_CODEC_ID_MPEG4 && pmt->formattype != FORMAT_MPEG2Video) || clsidInput == __uuidof(CAviSourceFilter) || clsidInput == __uuidof(CAviSplitterFilter) || clsidInput == __uuidof(COggSourceFilter) || clsidInput == __uuidof(COggSplitterFilter) || IsAVI() || IsOGG(); } m_pAVCtx = avcodec_alloc_context3(m_pAVCodec); CheckPointer(m_pAVCtx, E_POINTER); if (m_nCodecId == AV_CODEC_ID_MPEG2VIDEO || m_nCodecId == AV_CODEC_ID_MPEG1VIDEO || pmt->subtype == MEDIASUBTYPE_H264 || pmt->subtype == MEDIASUBTYPE_h264 || pmt->subtype == MEDIASUBTYPE_X264 || pmt->subtype == MEDIASUBTYPE_x264 || pmt->subtype == MEDIASUBTYPE_H264_bis || pmt->subtype == MEDIASUBTYPE_HEVC) { m_pParser = av_parser_init(m_nCodecId); } if (bReinit && m_nDecoderMode == MODE_SOFTWARE) { m_bUseDXVA = false; } SetThreadCount(); m_pFrame = av_frame_alloc(); CheckPointer(m_pFrame, E_POINTER); BITMAPINFOHEADER *pBMI = nullptr; bool bInterlacedFieldPerSample = false; if (pmt->formattype == FORMAT_VideoInfo) { VIDEOINFOHEADER* vih = (VIDEOINFOHEADER*)pmt->pbFormat; pBMI = &vih->bmiHeader; } else if (pmt->formattype == FORMAT_VideoInfo2) { VIDEOINFOHEADER2* vih2 = (VIDEOINFOHEADER2*)pmt->pbFormat; pBMI = &vih2->bmiHeader; bInterlacedFieldPerSample = vih2->dwInterlaceFlags & AMINTERLACE_IsInterlaced && vih2->dwInterlaceFlags & AMINTERLACE_1FieldPerSample; } else if (pmt->formattype == FORMAT_MPEGVideo) { MPEG1VIDEOINFO* mpgv = (MPEG1VIDEOINFO*)pmt->pbFormat; pBMI = &mpgv->hdr.bmiHeader; } else if (pmt->formattype == FORMAT_MPEG2Video) { MPEG2VIDEOINFO* mpg2v = (MPEG2VIDEOINFO*)pmt->pbFormat; pBMI = &mpg2v->hdr.bmiHeader; bInterlacedFieldPerSample = mpg2v->hdr.dwInterlaceFlags & AMINTERLACE_IsInterlaced && mpg2v->hdr.dwInterlaceFlags & AMINTERLACE_1FieldPerSample; } else { return VFW_E_INVALIDMEDIATYPE; } if (m_nCodecId == AV_CODEC_ID_MPEG2VIDEO && bInterlacedFieldPerSample && m_nPCIVendor == PCIV_ATI) { m_bUseDXVA = false; } if (bChangeType) { m_bWaitKeyFrame = m_nCodecId == AV_CODEC_ID_VC1 || m_nCodecId == AV_CODEC_ID_VC1IMAGE || m_nCodecId == AV_CODEC_ID_WMV3 || m_nCodecId == AV_CODEC_ID_WMV3IMAGE || m_nCodecId == AV_CODEC_ID_MPEG2VIDEO || m_nCodecId == AV_CODEC_ID_RV30 || m_nCodecId == AV_CODEC_ID_RV40 || m_nCodecId == AV_CODEC_ID_VP3 || m_nCodecId == AV_CODEC_ID_THEORA || m_nCodecId == AV_CODEC_ID_MPEG4; } m_pAVCtx->codec_id = m_nCodecId; m_pAVCtx->codec_tag = pBMI->biCompression ? pBMI->biCompression : pmt->subtype.Data1; if (m_pAVCtx->codec_tag == MAKEFOURCC('m','p','g','2')) { m_pAVCtx->codec_tag = MAKEFOURCC('M','P','E','G'); } m_pAVCtx->coded_width = pBMI->biWidth; m_pAVCtx->coded_height = abs(pBMI->biHeight); m_pAVCtx->bits_per_coded_sample = pBMI->biBitCount; m_pAVCtx->workaround_bugs = FF_BUG_AUTODETECT; m_pAVCtx->skip_frame = (AVDiscard)m_nDiscardMode; m_pAVCtx->opaque = this; if (IsDXVASupported()) { m_pAVCtx->hwaccel_context = (dxva_context *)av_mallocz(sizeof(dxva_context)); m_pAVCtx->get_format = av_get_format; m_pAVCtx->get_buffer2 = av_get_buffer; m_pAVCtx->slice_flags |= SLICE_FLAG_ALLOW_FIELD; } AllocExtradata(pmt); AVDictionary* options = nullptr; if (m_nCodecId == AV_CODEC_ID_H264 && x264_build != -1) { av_dict_set_int(&options, "x264_build", x264_build, 0); } avcodec_lock; const int ret = avcodec_open2(m_pAVCtx, m_pAVCodec, &options); avcodec_unlock; if (options) { av_dict_free(&options); } if (ret < 0) { return VFW_E_INVALIDMEDIATYPE; } if (m_nCodecId == AV_CODEC_ID_AV1 && m_pAVCtx->extradata) { if (AVCodecParserContext* pParser = av_parser_init(m_nCodecId)) { BYTE* pOutBuffer = nullptr; int pOutLen = 0; int used_bytes = av_parser_parse2(pParser, m_pAVCtx, &pOutBuffer, &pOutLen, m_pAVCtx->extradata, m_pAVCtx->extradata_size, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0); if (pOutLen > 0) { m_pAVCtx->pix_fmt = (enum AVPixelFormat)pParser->format; } av_parser_close(pParser); } } FillAVCodecProps(m_pAVCtx, pBMI); if (pFilter) { CComPtr<IExFilterInfo> pIExFilterInfo; if (SUCCEEDED(pFilter->QueryInterface(&pIExFilterInfo))) { if (m_nCodecId == AV_CODEC_ID_H264) { int value = 0; if (SUCCEEDED(pIExFilterInfo->GetPropertyInt("VIDEO_DELAY", &value))) { m_pAVCtx->has_b_frames = value; } } if (bChangeType) { m_FilterInfo.Clear(); int value = 0; if (SUCCEEDED(pIExFilterInfo->GetPropertyInt("VIDEO_PROFILE", &value))) { m_FilterInfo.profile = value; } if (SUCCEEDED(pIExFilterInfo->GetPropertyInt("VIDEO_PIXEL_FORMAT", &value))) { m_FilterInfo.pix_fmt = value; } if (SUCCEEDED(pIExFilterInfo->GetPropertyInt("VIDEO_INTERLACED", &value))) { m_FilterInfo.interlaced = value; } if (!m_bReorderBFrame && (m_nCodecId == AV_CODEC_ID_H264 || m_nCodecId == AV_CODEC_ID_HEVC)) { if (SUCCEEDED(pIExFilterInfo->GetPropertyInt("VIDEO_FLAG_ONLY_DTS", &value)) && value == 1) { m_bReorderBFrame = true; } } unsigned size = 0; LPVOID pData = nullptr; if (SUCCEEDED(pIExFilterInfo->GetPropertyBin("VIDEO_COLOR_SPACE", &pData, &size))) { if (size == sizeof(ColorSpace)) { auto const colorSpace = (ColorSpace*)pData; if (colorSpace->MatrixCoefficients < AVCOL_SPC_NB && colorSpace->MatrixCoefficients != AVCOL_SPC_RGB && colorSpace->MatrixCoefficients != AVCOL_SPC_UNSPECIFIED && colorSpace->MatrixCoefficients != AVCOL_SPC_RESERVED) { m_FilterInfo.colorspace = colorSpace->MatrixCoefficients; } if (colorSpace->Primaries < AVCOL_PRI_NB && colorSpace->Primaries != AVCOL_PRI_RESERVED0 && colorSpace->Primaries != AVCOL_PRI_UNSPECIFIED && colorSpace->Primaries != AVCOL_PRI_RESERVED) { m_FilterInfo.color_primaries = colorSpace->Primaries; } if (colorSpace->TransferCharacteristics < AVCOL_TRC_NB && colorSpace->TransferCharacteristics != AVCOL_TRC_RESERVED0 && colorSpace->TransferCharacteristics != AVCOL_TRC_UNSPECIFIED && colorSpace->TransferCharacteristics != AVCOL_TRC_RESERVED) { m_FilterInfo.color_trc = colorSpace->TransferCharacteristics; } if (colorSpace->ChromaLocation < AVCHROMA_LOC_NB && colorSpace->ChromaLocation != AVCHROMA_LOC_UNSPECIFIED) { m_FilterInfo.chroma_sample_location = colorSpace->ChromaLocation; } if (colorSpace->Range < AVCOL_RANGE_NB && colorSpace->Range != AVCOL_RANGE_UNSPECIFIED) { m_FilterInfo.color_range = colorSpace->Range; } } LocalFree(pData); } if (SUCCEEDED(pIExFilterInfo->GetPropertyBin("HDR_MASTERING_METADATA", &pData, &size))) { if (size == sizeof(MediaSideDataHDR)) { m_FilterInfo.masterDataHDR = DNew MediaSideDataHDR; memcpy(m_FilterInfo.masterDataHDR, pData, size); } LocalFree(pData); } if (SUCCEEDED(pIExFilterInfo->GetPropertyBin("HDR_CONTENT_LIGHT_LEVEL", &pData, &size))) { if (size == sizeof(MediaSideDataHDRContentLightLevel)) { m_FilterInfo.HDRContentLightLevel = DNew MediaSideDataHDRContentLightLevel; memcpy(m_FilterInfo.HDRContentLightLevel, pData, size); } LocalFree(pData); } if (SUCCEEDED(pIExFilterInfo->GetPropertyBin("PALETTE", &pData, &size))) { if (size == sizeof(m_Palette)) { m_bHasPalette = true; memcpy(m_Palette, pData, size); } LocalFree(pData); } } } } if (m_FilterInfo.profile != -1) { m_pAVCtx->profile = m_FilterInfo.profile; } if (m_FilterInfo.pix_fmt != AV_PIX_FMT_NONE) { m_pAVCtx->pix_fmt = (AVPixelFormat)m_FilterInfo.pix_fmt; } m_nAlign = 16; if (m_nCodecId == AV_CODEC_ID_MPEG2VIDEO) { m_nAlign <<= 1; } else if (m_nCodecId == AV_CODEC_ID_HEVC) { m_nAlign = 128; } m_nSurfaceWidth = FFALIGN(m_pAVCtx->coded_width, m_nAlign); m_nSurfaceHeight = FFALIGN(m_pAVCtx->coded_height, m_nAlign); const int depth = GetLumaBits(m_pAVCtx->pix_fmt); m_bHighBitdepth = (depth == 10) && ((m_nCodecId == AV_CODEC_ID_HEVC && m_pAVCtx->profile == FF_PROFILE_HEVC_MAIN_10) || (m_nCodecId == AV_CODEC_ID_VP9 && m_pAVCtx->profile == FF_PROFILE_VP9_2)); m_dxvaExtFormat = GetDXVA2ExtendedFormat(m_pAVCtx, m_pFrame); m_dxva_pix_fmt = m_pAVCtx->pix_fmt; if (bChangeType && IsDXVASupported()) { do { m_bDXVACompatible = false; if (!DXVACheckFramesize(m_nCodecId, PictWidth(), PictHeight(), m_nPCIVendor, m_nPCIDevice, m_VideoDriverVersion)) { // check frame size break; } if (m_nCodecId == AV_CODEC_ID_H264) { if (m_nDXVA_SD && m_nSurfaceWidth < 1280) { // check "Disable DXVA for SD" option break; } const int nCompat = FFH264CheckCompatibility(m_nSurfaceWidth, m_nSurfaceHeight, m_pAVCtx, m_nPCIVendor, m_nPCIDevice, m_VideoDriverVersion); if ((nCompat & DXVA_PROFILE_HIGHER_THAN_HIGH) || (nCompat & DXVA_HIGH_BIT)) { // DXVA unsupported break; } if (nCompat) { bool bDXVACompatible = true; switch (m_nDXVACheckCompatibility) { case 0: bDXVACompatible = false; break; case 1: bDXVACompatible = (nCompat == DXVA_UNSUPPORTED_LEVEL); break; case 2: bDXVACompatible = (nCompat == DXVA_TOO_MANY_REF_FRAMES); break; } if (!bDXVACompatible) { break; } } } else if (!check_dxva_compatible(m_nCodecId, m_pAVCtx->pix_fmt, m_pAVCtx->profile)) { break; } m_bDXVACompatible = true; } while (false); if (!m_bDXVACompatible) { goto redo; } } av_frame_unref(m_pFrame); if (UseDXVA2() && m_pDXVADecoder) { m_pDXVADecoder->FillHWContext(); } return S_OK; } static const VIDEO_OUTPUT_FORMATS DXVAFormats[] = { // DXVA2 8bit {&MEDIASUBTYPE_NV12, 1, 12, FCC('dxva')}, }; static const VIDEO_OUTPUT_FORMATS DXVAFormats10bit[] = { // DXVA2 10bit {&MEDIASUBTYPE_P010, 1, 24, FCC('dxva')}, }; void CMPCVideoDecFilter::BuildOutputFormat() { SAFE_DELETE_ARRAY(m_pVideoOutputFormat); // === New swscaler options int nSwIndex[PixFmt_count] = { 0 }; int nSwCount = 0; const enum AVPixelFormat pix_fmt = m_pMSDKDecoder ? AV_PIX_FMT_NV12 : (m_pAVCtx->sw_pix_fmt != AV_PIX_FMT_NONE ? m_pAVCtx->sw_pix_fmt : m_pAVCtx->pix_fmt); if (pix_fmt != AV_PIX_FMT_NONE) { const AVPixFmtDescriptor* av_pfdesc = av_pix_fmt_desc_get(pix_fmt); if (av_pfdesc) { int lumabits = av_pfdesc->comp[0].depth; const MPCPixelFormat* OutList = nullptr; if (av_pfdesc->nb_components <= 2) { // greyscale formats with and without alfa channel if (lumabits <= 8) { OutList = YUV420_8; } else if (lumabits <= 10) { OutList = YUV420_10; } else { OutList = YUV420_16; } } else if (av_pfdesc->flags & (AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_PAL)) { if (lumabits <= 10) { OutList = RGB_8; } else { OutList = RGB_16; } } else if (av_pfdesc->nb_components >= 3) { if (av_pfdesc->log2_chroma_w == 1 && av_pfdesc->log2_chroma_h == 1) { // 4:2:0 if (lumabits <= 8) { OutList = YUV420_8; } else if (lumabits <= 10) { OutList = YUV420_10; } else { OutList = YUV420_16; } } else if (av_pfdesc->log2_chroma_w == 1 && av_pfdesc->log2_chroma_h == 0) { // 4:2:2 if (lumabits <= 8) { OutList = YUV422_8; } else if (lumabits <= 10) { OutList = YUV422_10; } else { OutList = YUV422_16; } } else if (av_pfdesc->log2_chroma_w == 0 && av_pfdesc->log2_chroma_h == 0) { // 4:4:4 if (lumabits <= 8) { OutList = YUV444_8; } else if (lumabits <= 10) { OutList = YUV444_10; } else { OutList = YUV444_16; } } } if (OutList == nullptr) { OutList = YUV420_8; } for (int i = 0; i < PixFmt_count; i++) { int index = OutList[i]; if (m_fPixFmts[index]) { nSwIndex[nSwCount++] = index; } } } } if (!m_fPixFmts[PixFmt_YUY2] || nSwCount == 0) { // if YUY2 has not been added yet, then add it to the end of the list nSwIndex[nSwCount++] = PixFmt_YUY2; } m_nVideoOutputCount = m_bUseFFmpeg ? nSwCount : 0; if (IsDXVASupported()) { m_nVideoOutputCount += m_bHighBitdepth ? _countof(DXVAFormats10bit) : _countof(DXVAFormats); } m_pVideoOutputFormat = DNew VIDEO_OUTPUT_FORMATS[m_nVideoOutputCount]; int nPos = 0; if (IsDXVASupported()) { if (m_bHighBitdepth) { memcpy(&m_pVideoOutputFormat[nPos], DXVAFormats10bit, sizeof(DXVAFormats10bit)); nPos += _countof(DXVAFormats10bit); } else { memcpy(&m_pVideoOutputFormat[nPos], DXVAFormats, sizeof(DXVAFormats)); nPos += _countof(DXVAFormats); } } // Software rendering if (m_bUseFFmpeg) { for (int i = 0; i < nSwCount; i++) { const SW_OUT_FMT* swof = GetSWOF(nSwIndex[i]); m_pVideoOutputFormat[nPos + i].subtype = swof->subtype; m_pVideoOutputFormat[nPos + i].biCompression = swof->biCompression; m_pVideoOutputFormat[nPos + i].biBitCount = swof->bpp; m_pVideoOutputFormat[nPos + i].biPlanes = 1; // This value must be set to 1. } } } void CMPCVideoDecFilter::GetOutputFormats(int& nNumber, VIDEO_OUTPUT_FORMATS** ppFormats) { nNumber = m_nVideoOutputCount; *ppFormats = m_pVideoOutputFormat; } static void ReconstructH264Extra(BYTE *extra, unsigned& extralen, int NALSize) { CH264Nalu Nalu; Nalu.SetBuffer(extra, extralen, NALSize); bool pps_present = false; bool bNeedReconstruct = false; while (Nalu.ReadNext()) { const NALU_TYPE nalu_type = Nalu.GetType(); if (nalu_type == NALU_TYPE_PPS) { pps_present = true; } else if (nalu_type == NALU_TYPE_SPS) { bNeedReconstruct = pps_present; break; } } if (bNeedReconstruct) { BYTE* dst = (uint8_t *)av_mallocz(extralen); if (!dst) { return; } size_t dstlen = 0; Nalu.SetBuffer(extra, extralen, NALSize); while (Nalu.ReadNext()) { if (Nalu.GetType() == NALU_TYPE_SPS) { memcpy(dst, Nalu.GetNALBuffer(), Nalu.GetLength()); dstlen += Nalu.GetLength(); break; } } Nalu.SetBuffer(extra, extralen, NALSize); while (Nalu.ReadNext()) { if (Nalu.GetType() != NALU_TYPE_SPS) { memcpy(dst + dstlen, Nalu.GetNALBuffer(), Nalu.GetLength()); dstlen += Nalu.GetLength(); } } memcpy(extra, dst, extralen); av_freep(&dst); } } void CMPCVideoDecFilter::AllocExtradata(const CMediaType* pmt) { // code from LAV ... // Process Extradata BYTE *extra = nullptr; unsigned extralen = 0; getExtraData((const BYTE *)pmt->Format(), pmt->FormatType(), pmt->FormatLength(), nullptr, &extralen); BOOL bH264avc = FALSE; if (pmt->formattype == FORMAT_MPEG2Video && (m_pAVCtx->codec_tag == MAKEFOURCC('a','v','c','1') || m_pAVCtx->codec_tag == MAKEFOURCC('A','V','C','1') || m_pAVCtx->codec_tag == MAKEFOURCC('C','C','V','1'))) { DLog(L"CMPCVideoDecFilter::AllocExtradata() : processing AVC1 extradata of %d bytes", extralen); // Reconstruct AVC1 extradata format MPEG2VIDEOINFO *mp2vi = (MPEG2VIDEOINFO *)pmt->Format(); extralen += 7; extra = (uint8_t *)av_mallocz(extralen + AV_INPUT_BUFFER_PADDING_SIZE); extra[0] = 1; extra[1] = (BYTE)mp2vi->dwProfile; extra[2] = 0; extra[3] = (BYTE)mp2vi->dwLevel; extra[4] = (BYTE)(mp2vi->dwFlags ? mp2vi->dwFlags : 4) - 1; // only process extradata if available uint8_t ps_count = 0; if (extralen > 7) { // Actually copy the metadata into our new buffer unsigned actual_len; getExtraData((const BYTE *)pmt->Format(), pmt->FormatType(), pmt->FormatLength(), extra + 6, &actual_len); ReconstructH264Extra(extra + 6, actual_len, 2); // Count the number of SPS/PPS in them and set the length // We'll put them all into one block and add a second block with 0 elements afterwards // The parsing logic does not care what type they are, it just expects 2 blocks. BYTE *p = extra + 6, *end = extra + 6 + actual_len; BOOL bSPS = FALSE, bPPS = FALSE; while (p + 1 < end) { unsigned len = (((unsigned)p[0] << 8) | p[1]) + 2; if (p + len > end) { break; } if ((p[2] & 0x1F) == 7) bSPS = TRUE; if ((p[2] & 0x1F) == 8) bPPS = TRUE; ps_count++; p += len; } } extra[5] = ps_count; extra[extralen - 1] = 0; bH264avc = TRUE; } else if (extralen > 0) { DLog(L"CMPCVideoDecFilter::AllocExtradata() : processing extradata of %d bytes", extralen); // Just copy extradata for other formats extra = (uint8_t *)av_mallocz(extralen + AV_INPUT_BUFFER_PADDING_SIZE); getExtraData((const BYTE *)pmt->Format(), pmt->FormatType(), pmt->FormatLength(), extra, nullptr); if (m_nCodecId == AV_CODEC_ID_H264) { ReconstructH264Extra(extra, extralen, 0); } else if (m_nCodecId == AV_CODEC_ID_HEVC) { // try Reconstruct NAL units sequence into NAL Units in Byte-Stream Format BYTE* dst = nullptr; int dst_len = 0; BOOL vps_present = FALSE, sps_present = FALSE, pps_present = FALSE; CH265Nalu Nalu; Nalu.SetBuffer(extra, extralen, 2); while (!(vps_present && sps_present && pps_present) && Nalu.ReadNext()) { const NALU_TYPE nalu_type = Nalu.GetType(); switch (nalu_type) { case NALU_TYPE_HEVC_VPS: case NALU_TYPE_HEVC_SPS: case NALU_TYPE_HEVC_PPS: if (nalu_type == NALU_TYPE_HEVC_VPS) { if (vps_present) continue; vc_params_t params = { 0 }; if (!HEVCParser::ParseVideoParameterSet(Nalu.GetDataBuffer() + 2, Nalu.GetDataLength() - 2, params)) { break; } vps_present = TRUE; } else if (nalu_type == NALU_TYPE_HEVC_SPS) { if (sps_present) continue; vc_params_t params = { 0 }; if (!HEVCParser::ParseSequenceParameterSet(Nalu.GetDataBuffer() + 2, Nalu.GetDataLength() - 2, params)) { break; } sps_present = TRUE; } else if (nalu_type == NALU_TYPE_HEVC_PPS) { if (pps_present) continue; pps_present = TRUE; } static const BYTE start_code[] = { 0, 0, 1 }; static const UINT start_code_size = sizeof(start_code); dst = (BYTE *)av_realloc_f(dst, dst_len + Nalu.GetDataLength() + start_code_size + AV_INPUT_BUFFER_PADDING_SIZE, 1); memcpy(dst + dst_len, start_code, start_code_size); dst_len += start_code_size; memcpy(dst + dst_len, Nalu.GetDataBuffer(), Nalu.GetDataLength()); dst_len += Nalu.GetDataLength(); } } if (vps_present && sps_present && pps_present) { av_freep(&extra); extra = dst; extralen = dst_len; } else { av_freep(&dst); } } else if (m_nCodecId == AV_CODEC_ID_VP9) { // use code from LAV // read custom vpcC headers if (extralen >= 16 && AV_RB32(extra) == 'vpcC' && AV_RB8(extra + 4) == 1) { m_pAVCtx->profile = AV_RB8(extra + 8); m_pAVCtx->color_primaries = (AVColorPrimaries)AV_RB8(extra + 11); m_pAVCtx->color_trc = (AVColorTransferCharacteristic)AV_RB8(extra + 12); m_pAVCtx->colorspace = (AVColorSpace)AV_RB8(extra + 13); m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV420P; int bitdepth = AV_RB8(extra + 10) >> 4; if (m_pAVCtx->profile == FF_PROFILE_VP9_2) { if (bitdepth == 10) { m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV420P10; } else if (bitdepth == 12) { m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV420P12; } } else if (m_pAVCtx->profile == FF_PROFILE_VP9_3) { if (bitdepth == 10) { m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV422P10; } else if (bitdepth == 12) { m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV422P12; } } av_freep(&extra); extralen = 0; } } else if (m_nCodecId == AV_CODEC_ID_AV1) { if (extralen >= 8 && AV_RB32(extra) == 'av1C' && AV_RB8(extra + 4) == 0x81) { CGolombBuffer gb(extra + 5, extralen - 5); const unsigned seq_profile = gb.BitRead(3); gb.BitRead(5); // seq_level_idx gb.BitRead(1); // seq_tier const unsigned high_bitdepth = gb.BitRead(1); const unsigned twelve_bit = gb.BitRead(1); const unsigned monochrome = gb.BitRead(1); const unsigned chroma_subsampling_x = gb.BitRead(1); const unsigned chroma_subsampling_y = gb.BitRead(1); enum Dav1dPixelLayout { DAV1D_PIXEL_LAYOUT_I400, ///< monochrome DAV1D_PIXEL_LAYOUT_I420, ///< 4:2:0 planar DAV1D_PIXEL_LAYOUT_I422, ///< 4:2:2 planar DAV1D_PIXEL_LAYOUT_I444, ///< 4:4:4 planar }; enum Dav1dBitDepth { DAV1D_8BIT, DAV1D_10BIT, DAV1D_12BIT, }; static const enum AVPixelFormat pix_fmts[][3] = { { AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY10, AV_PIX_FMT_GRAY12 }, { AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV420P12 }, { AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV422P12 }, { AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV444P10, AV_PIX_FMT_YUV444P12 }, }; Dav1dBitDepth bitdepth_index = DAV1D_8BIT; Dav1dPixelLayout layout = DAV1D_PIXEL_LAYOUT_I420; switch (seq_profile) { case FF_PROFILE_AV1_MAIN: bitdepth_index = high_bitdepth ? DAV1D_10BIT : DAV1D_8BIT; layout = monochrome ? DAV1D_PIXEL_LAYOUT_I400 : DAV1D_PIXEL_LAYOUT_I420; break; case FF_PROFILE_AV1_HIGH: bitdepth_index = high_bitdepth ? DAV1D_10BIT : DAV1D_8BIT; layout = DAV1D_PIXEL_LAYOUT_I444; break; case FF_PROFILE_AV1_PROFESSIONAL: bitdepth_index = high_bitdepth ? (twelve_bit ? DAV1D_12BIT : DAV1D_10BIT) : DAV1D_8BIT; if (monochrome) { layout = DAV1D_PIXEL_LAYOUT_I400; } else { if (bitdepth_index < DAV1D_12BIT) { layout = DAV1D_PIXEL_LAYOUT_I422; } else { if (chroma_subsampling_x && chroma_subsampling_y) { layout = DAV1D_PIXEL_LAYOUT_I420; } else if (chroma_subsampling_x && !chroma_subsampling_y) { layout = DAV1D_PIXEL_LAYOUT_I422; } else if (!chroma_subsampling_x && !chroma_subsampling_y) { layout = DAV1D_PIXEL_LAYOUT_I444; } } } break; } m_pAVCtx->profile = seq_profile; m_pAVCtx->pix_fmt = pix_fmts[layout][bitdepth_index]; av_freep(&extra); extralen = 0; } } } // Hack to discard invalid MP4 metadata with AnnexB style video if (m_nCodecId == AV_CODEC_ID_H264 && !bH264avc && extra && extra[0] == 1) { av_freep(&extra); extralen = 0; } m_pAVCtx->extradata = extra; m_pAVCtx->extradata_size = (int)extralen; } HRESULT CMPCVideoDecFilter::CompleteConnect(PIN_DIRECTION direction, IPin* pReceivePin) { if (direction == PINDIR_OUTPUT) { if (IsDXVASupported() && SUCCEEDED(ConfigureDXVA2(pReceivePin))) { HRESULT hr = E_FAIL; for (;;) { CComPtr<IDirectXVideoDecoderService> pDXVA2Service; hr = m_pDeviceManager->GetVideoService(m_hDevice, IID_PPV_ARGS(&pDXVA2Service)); if (FAILED(hr)) { DLog(L"CMPCVideoDecFilter::CompleteConnect() : IDirect3DDeviceManager9::GetVideoService() - FAILED (0x%08x)", hr); break; } if (!pDXVA2Service) { break; } const UINT numSurfaces = std::max(m_DXVA2Config.ConfigMinRenderTargetBuffCount, 1ui16); LPDIRECT3DSURFACE9 pSurfaces[DXVA2_MAX_SURFACES] = {}; hr = pDXVA2Service->CreateSurface( m_nSurfaceWidth, m_nSurfaceHeight, numSurfaces - 1, m_VideoDesc.Format, D3DPOOL_DEFAULT, 0, DXVA2_VideoDecoderRenderTarget, pSurfaces, nullptr); if (FAILED(hr)) { DLog(L"CMPCVideoDecFilter::CompleteConnect() : IDirectXVideoDecoderService::CreateSurface() - FAILED (0x%08x)", hr); break; } CComPtr<IDirectXVideoDecoder> pDirectXVideoDec; hr = m_pDecoderService->CreateVideoDecoder(m_DXVADecoderGUID, &m_VideoDesc, &m_DXVA2Config, pSurfaces, numSurfaces, &pDirectXVideoDec); if (FAILED(hr)) { DLog(L"CMPCVideoDecFilter::CompleteConnect() : IDirectXVideoDecoder::CreateVideoDecoder() - FAILED (0x%08x)", hr); } for (UINT i = 0; i < numSurfaces; i++) { SAFE_RELEASE(pSurfaces[i]); } if (SUCCEEDED(hr) && SUCCEEDED(SetEVRForDXVA2(pReceivePin))) { m_nDecoderMode = MODE_DXVA2; } break; } if (FAILED(hr)) { CleanDXVAVariable(); CleanupD3DResources(); SAFE_DELETE(m_pDXVADecoder); m_nDecoderMode = MODE_SOFTWARE; DXVAState::ClearState(); } } if (m_nDecoderMode == MODE_SOFTWARE) { if (!m_bUseFFmpeg) { return VFW_E_INVALIDMEDIATYPE; } if (IsDXVASupported()) { HRESULT hr; if (FAILED(hr = InitDecoder(&m_pCurrentMediaType))) { return hr; } ChangeOutputMediaFormat(2); } } DetectVideoCard_EVR(pReceivePin); if (m_pMSDKDecoder) { m_MVC_Base_View_R_flag = FALSE; BeginEnumFilters(m_pGraph, pEF, pBF) { if (CComQIPtr<IPropertyBag> pPB = pBF) { CComVariant var; if (SUCCEEDED(pPB->Read(L"STEREOSCOPIC3DMODE", &var, nullptr)) && var.vt == VT_BSTR) { CString mode(var.bstrVal); mode.MakeLower(); m_MVC_Base_View_R_flag = mode == L"mvc_rl"; break; } } } EndEnumFilters; } } return __super::CompleteConnect (direction, pReceivePin); } HRESULT CMPCVideoDecFilter::DecideBufferSize(IMemAllocator* pAllocator, ALLOCATOR_PROPERTIES* pProperties) { if (UseDXVA2()) { if (m_pInput->IsConnected() == FALSE) { return E_UNEXPECTED; } pProperties->cBuffers = 22; HRESULT hr = S_OK; ALLOCATOR_PROPERTIES Actual; if (FAILED(hr = pAllocator->SetProperties(pProperties, &Actual))) { return hr; } return pProperties->cBuffers > Actual.cBuffers || pProperties->cbBuffer > Actual.cbBuffer ? E_FAIL : NOERROR; } else { return __super::DecideBufferSize(pAllocator, pProperties); } } HRESULT CMPCVideoDecFilter::BeginFlush() { return __super::BeginFlush(); } HRESULT CMPCVideoDecFilter::EndFlush() { CAutoLock cAutoLock(&m_csReceive); HRESULT hr = __super::EndFlush(); if (m_pAVCtx && avcodec_is_open(m_pAVCtx)) { avcodec_flush_buffers(m_pAVCtx); } return hr; } HRESULT CMPCVideoDecFilter::NewSegment(REFERENCE_TIME rtStart, REFERENCE_TIME rtStop, double dRate) { DLog(L"CMPCVideoDecFilter::NewSegment()"); CAutoLock cAutoLock(&m_csReceive); if (m_pAVCtx) { avcodec_flush_buffers(m_pAVCtx); } if (m_pParser) { av_parser_close(m_pParser); m_pParser = av_parser_init(m_nCodecId); } if (m_pMSDKDecoder) { m_pMSDKDecoder->Flush(); } m_dRate = dRate; m_bWaitingForKeyFrame = TRUE; m_rtStartCache = INVALID_TIME; m_rtLastStop = 0; if (m_bReorderBFrame) { m_nBFramePos = 0; m_tBFrameDelay[0].rtStart = m_tBFrameDelay[0].rtStop = INVALID_TIME; m_tBFrameDelay[1].rtStart = m_tBFrameDelay[1].rtStop = INVALID_TIME; } if (m_bDecodingStart && m_pAVCtx) { if (m_nCodecId == AV_CODEC_ID_H264 || m_nCodecId == AV_CODEC_ID_MPEG2VIDEO) { InitDecoder(&m_pCurrentMediaType); } if (UseDXVA2() && m_nCodecId == AV_CODEC_ID_H264 && m_nPCIVendor == PCIV_ATI) { HRESULT hr = ReinitDXVA2Decoder(); if (FAILED(hr)) { return hr; } } } return __super::NewSegment(rtStart, rtStop, dRate); } HRESULT CMPCVideoDecFilter::EndOfStream() { CAutoLock cAutoLock(&m_csReceive); m_pMSDKDecoder ? m_pMSDKDecoder->EndOfStream() : Decode(nullptr, 0, INVALID_TIME, INVALID_TIME); return __super::EndOfStream(); } HRESULT CMPCVideoDecFilter::BreakConnect(PIN_DIRECTION dir) { if (dir == PINDIR_INPUT) { Cleanup(); } return __super::BreakConnect (dir); } void CMPCVideoDecFilter::SetTypeSpecificFlags(IMediaSample* pMS) { if (CComQIPtr<IMediaSample2> pMS2 = pMS) { AM_SAMPLE2_PROPERTIES props; if (SUCCEEDED(pMS2->GetProperties(sizeof(props), (BYTE*)&props))) { props.dwTypeSpecificFlags &= ~0x7f; switch (m_nScanType) { case SCAN_AUTO : if (m_nCodecId == AV_CODEC_ID_HEVC) { props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_WEAVE; } else if (m_FilterInfo.interlaced != -1) { switch (m_FilterInfo.interlaced) { case 0 : props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_WEAVE; break; case 1 : props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_FIELD1FIRST; break; } } else { if (!m_pFrame->interlaced_frame) { props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_WEAVE; } if (m_pFrame->top_field_first) { props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_FIELD1FIRST; } if (m_pFrame->repeat_pict) { props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_REPEAT_FIELD; } } break; case SCAN_PROGRESSIVE : props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_WEAVE; break; case SCAN_TOPFIELD : props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_FIELD1FIRST; break; } switch (m_pFrame->pict_type) { case AV_PICTURE_TYPE_I : case AV_PICTURE_TYPE_SI : props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_I_SAMPLE; break; case AV_PICTURE_TYPE_P : case AV_PICTURE_TYPE_SP : props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_P_SAMPLE; break; default : props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_B_SAMPLE; break; } pMS2->SetProperties(sizeof(props), (BYTE*)&props); } } m_bInterlaced = m_pFrame->interlaced_frame; } // from LAVVideo DXVA2_ExtendedFormat CMPCVideoDecFilter::GetDXVA2ExtendedFormat(AVCodecContext *ctx, AVFrame *frame) { DXVA2_ExtendedFormat fmt = { 0 }; if (m_FormatConverter.GetOutPixFormat() == PixFmt_RGB32 || m_FormatConverter.GetOutPixFormat() == PixFmt_RGB48) { return fmt; } auto color_primaries = m_FilterInfo.color_primaries != -1 ? m_FilterInfo.color_primaries : ctx->color_primaries; auto colorspace = m_FilterInfo.colorspace != -1 ? m_FilterInfo.colorspace : ctx->colorspace; auto color_trc = m_FilterInfo.color_trc != -1 ? m_FilterInfo.color_trc : ctx->color_trc; auto chroma_sample_location = m_FilterInfo.chroma_sample_location != -1 ? m_FilterInfo.chroma_sample_location : ctx->chroma_sample_location; auto color_range = m_FilterInfo.color_range != -1 ? m_FilterInfo.color_range : ctx->color_range; // Color Primaries switch(color_primaries) { case AVCOL_PRI_BT709: fmt.VideoPrimaries = DXVA2_VideoPrimaries_BT709; break; case AVCOL_PRI_BT470M: fmt.VideoPrimaries = DXVA2_VideoPrimaries_BT470_2_SysM; break; case AVCOL_PRI_BT470BG: fmt.VideoPrimaries = DXVA2_VideoPrimaries_BT470_2_SysBG; break; case AVCOL_PRI_SMPTE170M: fmt.VideoPrimaries = DXVA2_VideoPrimaries_SMPTE170M; break; case AVCOL_PRI_SMPTE240M: fmt.VideoPrimaries = DXVA2_VideoPrimaries_SMPTE240M; break; // Values from newer Windows SDK (MediaFoundation) case AVCOL_PRI_BT2020: fmt.VideoPrimaries = VIDEOPRIMARIES_BT2020; break; case AVCOL_PRI_SMPTE428: // XYZ fmt.VideoPrimaries = VIDEOPRIMARIES_XYZ; break; case AVCOL_PRI_SMPTE431: // DCI-P3 fmt.VideoPrimaries = VIDEOPRIMARIES_DCI_P3; break; } // Color Space / Transfer Matrix switch (colorspace) { case AVCOL_SPC_BT709: fmt.VideoTransferMatrix = DXVA2_VideoTransferMatrix_BT709; break; case AVCOL_SPC_BT470BG: case AVCOL_SPC_SMPTE170M: fmt.VideoTransferMatrix = DXVA2_VideoTransferMatrix_BT601; break; case AVCOL_SPC_SMPTE240M: fmt.VideoTransferMatrix = DXVA2_VideoTransferMatrix_SMPTE240M; break; // Values from newer Windows SDK (MediaFoundation) case AVCOL_SPC_BT2020_CL: case AVCOL_SPC_BT2020_NCL: fmt.VideoTransferMatrix = VIDEOTRANSFERMATRIX_BT2020_10; break; // Custom values, not official standard, but understood by madVR, YCGCO understood by EVR-CP case AVCOL_SPC_FCC: fmt.VideoTransferMatrix = VIDEOTRANSFERMATRIX_FCC; break; case AVCOL_SPC_YCGCO: fmt.VideoTransferMatrix = VIDEOTRANSFERMATRIX_YCgCo; break; case AVCOL_SPC_UNSPECIFIED: if (ctx->width <= 1024 && ctx->height <= 576) { // SD fmt.VideoTransferMatrix = DXVA2_VideoTransferMatrix_BT601; } else { // HD fmt.VideoTransferMatrix = DXVA2_VideoTransferMatrix_BT709; } } // Color Transfer Function switch(color_trc) { case AVCOL_TRC_BT709: case AVCOL_TRC_SMPTE170M: case AVCOL_TRC_BT2020_10: case AVCOL_TRC_BT2020_12: fmt.VideoTransferFunction = DXVA2_VideoTransFunc_709; break; case AVCOL_TRC_GAMMA22: fmt.VideoTransferFunction = DXVA2_VideoTransFunc_22; break; case AVCOL_TRC_GAMMA28: fmt.VideoTransferFunction = DXVA2_VideoTransFunc_28; break; case AVCOL_TRC_SMPTE240M: fmt.VideoTransferFunction = DXVA2_VideoTransFunc_240M; break; case AVCOL_TRC_LOG: fmt.VideoTransferFunction = MFVideoTransFunc_Log_100; break; case AVCOL_TRC_LOG_SQRT: fmt.VideoTransferFunction = MFVideoTransFunc_Log_316; break; // Values from newer Windows SDK (MediaFoundation) case AVCOL_TRC_SMPTEST2084: fmt.VideoTransferFunction = VIDEOTRANSFUNC_2084; break; case AVCOL_TRC_ARIB_STD_B67: fmt.VideoTransferFunction = VIDEOTRANSFUNC_HLG; break; } if (frame->format == AV_PIX_FMT_XYZ12LE || frame->format == AV_PIX_FMT_XYZ12BE) { fmt.VideoPrimaries = DXVA2_VideoPrimaries_BT709; } // Chroma location switch(chroma_sample_location) { case AVCHROMA_LOC_LEFT: fmt.VideoChromaSubsampling = DXVA2_VideoChromaSubsampling_MPEG2; break; case AVCHROMA_LOC_CENTER: fmt.VideoChromaSubsampling = DXVA2_VideoChromaSubsampling_MPEG1; break; case AVCHROMA_LOC_TOPLEFT: fmt.VideoChromaSubsampling = DXVA2_VideoChromaSubsampling_Cosited; break; } // Color Range, 0-255 or 16-235 if (color_range == AVCOL_RANGE_JPEG || frame->format == AV_PIX_FMT_YUVJ420P || frame->format == AV_PIX_FMT_YUVJ422P || frame->format == AV_PIX_FMT_YUVJ444P || frame->format == AV_PIX_FMT_YUVJ440P || frame->format == AV_PIX_FMT_YUVJ411P) { fmt.NominalRange = DXVA2_NominalRange_0_255; } else { fmt.NominalRange = DXVA2_NominalRange_16_235; } // HACK: 1280 is the value when only chroma location is set to MPEG2, do not bother to send this information, as its the same for basically every clip if ((fmt.value & ~0xff) != 0 && (fmt.value & ~0xff) != 1280) { fmt.SampleFormat = AMCONTROL_USED | AMCONTROL_COLORINFO_PRESENT; } else { fmt.value = 0; } return fmt; } static inline BOOL GOPFound(BYTE *buf, int len) { if (buf && len > 0) { CGolombBuffer gb(buf, len); BYTE state = 0x00; while (gb.NextMpegStartCode(state)) { if (state == 0xb8) { // GOP return TRUE; } } } return FALSE; } HRESULT CMPCVideoDecFilter::FillAVPacket(AVPacket *avpkt, const BYTE *buffer, int buflen) { int size = buflen; if (m_nCodecId == AV_CODEC_ID_PRORES) { // code from ffmpeg/libavutil/mem.c -> av_fast_realloc() size = (buflen + AV_INPUT_BUFFER_PADDING_SIZE) + (buflen + AV_INPUT_BUFFER_PADDING_SIZE) / 16 + 32; } if (av_new_packet(avpkt, size) < 0) { return E_OUTOFMEMORY; } memcpy(avpkt->data, buffer, buflen); if (size > buflen) { memset(avpkt->data + buflen, 0, size - buflen); } return S_OK; } #define Continue { av_frame_unref(m_pFrame); continue; } HRESULT CMPCVideoDecFilter::DecodeInternal(AVPacket *avpkt, REFERENCE_TIME rtStartIn, REFERENCE_TIME rtStopIn, BOOL bPreroll/* = FALSE*/) { if (avpkt) { if (m_bWaitingForKeyFrame) { if (m_nCodecId == AV_CODEC_ID_MPEG2VIDEO && GOPFound(avpkt->data, avpkt->size)) { m_bWaitingForKeyFrame = FALSE; } if (m_nCodecId == AV_CODEC_ID_VP8 || m_nCodecId == AV_CODEC_ID_VP9) { const BOOL bKeyFrame = m_nCodecId == AV_CODEC_ID_VP8 ? !(avpkt->data[0] & 1) : !(avpkt->data[0] & 4); if (bKeyFrame) { DLog(L"CMPCVideoDecFilter::DecodeInternal(): Found VP8/9 key-frame, resuming decoding"); m_bWaitingForKeyFrame = FALSE; } else { return S_OK; } } } if (m_bHasPalette) { m_bHasPalette = false; uint32_t *pal = (uint32_t *)av_packet_new_side_data(avpkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE); memcpy(pal, m_Palette, AVPALETTE_SIZE); } } int ret = avcodec_send_packet(m_pAVCtx, avpkt); if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) { if (UseDXVA2() && !m_bDXVACompatible) { SAFE_DELETE(m_pDXVADecoder); m_nDecoderMode = MODE_SOFTWARE; DXVAState::ClearState(); InitDecoder(&m_pCurrentMediaType); ChangeOutputMediaFormat(2); } return S_FALSE; } for (;;) { ret = avcodec_receive_frame(m_pAVCtx, m_pFrame); if (ret < 0 && ret != AVERROR(EAGAIN)) { av_frame_unref(m_pFrame); return S_FALSE; } if (m_bWaitKeyFrame) { if (m_bWaitingForKeyFrame && ret >= 0) { if (m_pFrame->key_frame) { DLog(L"CMPCVideoDecFilter::DecodeInternal(): Found key-frame, resuming decoding"); m_bWaitingForKeyFrame = FALSE; } else { ret = AVERROR(EAGAIN); } } } if (ret < 0 || !m_pFrame->data[0]) { av_frame_unref(m_pFrame); break; } UpdateAspectRatio(); HRESULT hr = S_OK; if (UseDXVA2()) { hr = m_pDXVADecoder->DeliverFrame(); Continue; } GetFrameTimeStamp(m_pFrame, rtStartIn, rtStopIn); if (m_bRVDropBFrameTimings && m_pFrame->pict_type == AV_PICTURE_TYPE_B) { rtStartIn = m_rtLastStop; rtStopIn = INVALID_TIME; } bool bSampleTime = !(m_nCodecId == AV_CODEC_ID_MJPEG && rtStartIn == INVALID_TIME); UpdateFrameTime(rtStartIn, rtStopIn); if (bPreroll || rtStartIn < 0) { Continue; } CComPtr<IMediaSample> pOut; BYTE* pDataOut = nullptr; DXVA2_ExtendedFormat dxvaExtFormat = GetDXVA2ExtendedFormat(m_pAVCtx, m_pFrame); if (FAILED(hr = GetDeliveryBuffer(m_pAVCtx->width, m_pAVCtx->height, &pOut, GetFrameDuration(), &dxvaExtFormat)) || FAILED(hr = pOut->GetPointer(&pDataOut))) { Continue; } // Check alignment on rawvideo, which can be off depending on the source file AVFrame* pTmpFrame = nullptr; if (m_nCodecId == AV_CODEC_ID_RAWVIDEO) { for (size_t i = 0; i < 4; i++) { if ((intptr_t)m_pFrame->data[i] % 16u || m_pFrame->linesize[i] % 16u) { // copy the frame, its not aligned properly and would crash later pTmpFrame = av_frame_alloc(); pTmpFrame->format = m_pFrame->format; pTmpFrame->width = m_pFrame->width; pTmpFrame->height = m_pFrame->height; pTmpFrame->colorspace = m_pFrame->colorspace; pTmpFrame->color_range = m_pFrame->color_range; av_frame_get_buffer(pTmpFrame, AV_INPUT_BUFFER_PADDING_SIZE); av_image_copy(pTmpFrame->data, pTmpFrame->linesize, (const uint8_t**)m_pFrame->data, m_pFrame->linesize, (AVPixelFormat)m_pFrame->format, m_pFrame->width, m_pFrame->height); break; } } } if (pTmpFrame) { m_FormatConverter.Converting(pDataOut, pTmpFrame); av_frame_free(&pTmpFrame); } else { m_FormatConverter.Converting(pDataOut, m_pFrame); } if (bSampleTime) { pOut->SetTime(&rtStartIn, &rtStopIn); } pOut->SetMediaTime(nullptr, nullptr); SetTypeSpecificFlags(pOut); AddFrameSideData(pOut, m_pFrame); hr = m_pOutput->Deliver(pOut); av_frame_unref(m_pFrame); } return S_OK; } HRESULT CMPCVideoDecFilter::ParseInternal(const BYTE *buffer, int buflen, REFERENCE_TIME rtStartIn, REFERENCE_TIME rtStopIn, BOOL bPreroll) { BOOL bFlush = (buffer == nullptr); BYTE* pDataBuffer = (BYTE*)buffer; HRESULT hr = S_OK; while (buflen > 0 || bFlush) { REFERENCE_TIME rtStart = rtStartIn, rtStop = rtStopIn; BYTE *pOutBuffer = nullptr; int pOutLen = 0; int used_bytes = av_parser_parse2(m_pParser, m_pAVCtx, &pOutBuffer, &pOutLen, pDataBuffer, buflen, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0); if (used_bytes == 0 && pOutLen == 0 && !bFlush) { DLog(L"CMPCVideoDecFilter::ParseInternal() - could not process buffer, starving?"); break; } else if (used_bytes > 0) { buflen -= used_bytes; pDataBuffer += used_bytes; } // Update start time cache // If more data was read then output, update the cache (incomplete frame) // If output is bigger or equal, a frame was completed, update the actual rtStart with the cached value, and then overwrite the cache if (used_bytes > pOutLen) { if (rtStartIn != INVALID_TIME) { m_rtStartCache = rtStartIn; } /* } else if (used_bytes == pOutLen || ((used_bytes + 9) == pOutLen)) { // Why +9 above? // Well, apparently there are some broken MKV muxers that like to mux the MPEG-2 PICTURE_START_CODE block (which is 9 bytes) in the package with the previous frame // This would cause the frame timestamps to be delayed by one frame exactly, and cause timestamp reordering to go wrong. // So instead of failing on those samples, lets just assume that 9 bytes are that case exactly. m_rtStartCache = rtStartIn = INVALID_TIME; } else if (pOut_size > used_bytes) { */ } else { rtStart = m_rtStartCache; m_rtStartCache = rtStartIn; // The value was used once, don't use it for multiple frames, that ends up in weird timings rtStartIn = INVALID_TIME; } if (pOutLen > 0) { AVPacket *avpkt = av_packet_alloc(); if (FAILED(hr = FillAVPacket(avpkt, pOutBuffer, pOutLen))) { break; } avpkt->pts = rtStart; hr = DecodeInternal(avpkt, rtStartIn, rtStopIn, bPreroll); av_packet_free(&avpkt); if (FAILED(hr)) { break; } } else if (bFlush) { hr = DecodeInternal(nullptr, INVALID_TIME, INVALID_TIME); break; } } return hr; } HRESULT CMPCVideoDecFilter::Decode(const BYTE *buffer, int buflen, REFERENCE_TIME rtStartIn, REFERENCE_TIME rtStopIn, BOOL bSyncPoint/* = FALSE*/, BOOL bPreroll/* = FALSE*/) { HRESULT hr = S_OK; if (m_bReorderBFrame) { m_tBFrameDelay[m_nBFramePos].rtStart = rtStartIn; m_tBFrameDelay[m_nBFramePos].rtStop = rtStopIn; m_nBFramePos = !m_nBFramePos; } if (m_pParser) { hr = ParseInternal(buffer, buflen, rtStartIn, rtStopIn, bPreroll); } else { if (!buffer) { return DecodeInternal(nullptr, INVALID_TIME, INVALID_TIME); } AVPacket *avpkt = av_packet_alloc(); if (FAILED(FillAVPacket(avpkt, buffer, buflen))) { return E_OUTOFMEMORY; } avpkt->pts = rtStartIn; if (rtStartIn != INVALID_TIME && rtStopIn != INVALID_TIME) { avpkt->duration = rtStopIn - rtStartIn; } avpkt->flags = bSyncPoint ? AV_PKT_FLAG_KEY : 0; hr = DecodeInternal(avpkt, rtStartIn, rtStopIn, bPreroll); av_packet_free(&avpkt); } return hr; } // change colorspace details/output media format // 1 - change swscaler colorspace details // 2 - change output media format HRESULT CMPCVideoDecFilter::ChangeOutputMediaFormat(int nType) { HRESULT hr = S_OK; if (!m_pOutput || !m_pOutput->IsConnected()) { return hr; } // change swscaler colorspace details if (nType >= 1) { m_FormatConverter.SetOptions(m_nSwRGBLevels); } // change output media format if (nType == 2) { CAutoLock cObjectLock(m_pLock); BuildOutputFormat(); IPin* pPin = m_pOutput->GetConnected(); if (IsVideoRenderer(GetFilterFromPin(pPin))) { hr = NotifyEvent(EC_DISPLAY_CHANGED, (LONG_PTR)pPin, 0); if (S_OK != hr) { hr = E_FAIL; } } else { int nNumber; VIDEO_OUTPUT_FORMATS* pFormats; GetOutputFormats(nNumber, &pFormats); for (int i = 0; i < nNumber * 2; i++) { CMediaType mt; if (SUCCEEDED(GetMediaType(i, &mt))) { hr = pPin->QueryAccept(&mt); if (hr == S_OK) { hr = ReconnectPin(pPin, &mt); if (hr == S_OK) { return hr; } } } } return E_FAIL; } } return hr; } void CMPCVideoDecFilter::SetThreadCount() { if (m_pAVCtx) { if (IsDXVASupported() || m_nCodecId == AV_CODEC_ID_MPEG4) { m_pAVCtx->thread_count = 1; } else { int nThreadNumber = (m_nThreadNumber > 0) ? m_nThreadNumber : CPUInfo::GetProcessorNumber(); m_pAVCtx->thread_count = std::clamp(nThreadNumber, 1, MAX_AUTO_THREADS); if (m_nCodecId == AV_CODEC_ID_AV1) { av_opt_set_int(m_pAVCtx->priv_data, "tilethreads", m_pAVCtx->thread_count == 1 ? 1 : (m_pAVCtx->thread_count < 8 ? 2 : 4), 0); av_opt_set_int(m_pAVCtx->priv_data, "framethreads", m_pAVCtx->thread_count, 0); } } } } HRESULT CMPCVideoDecFilter::Transform(IMediaSample* pIn) { HRESULT hr; BYTE* buffer; int buflen; REFERENCE_TIME rtStart = INVALID_TIME; REFERENCE_TIME rtStop = INVALID_TIME; if (FAILED(hr = pIn->GetPointer(&buffer))) { return hr; } buflen = pIn->GetActualDataLength(); if (buflen == 0) { return S_OK; } hr = pIn->GetTime(&rtStart, &rtStop); if (FAILED(hr)) { rtStart = rtStop = INVALID_TIME; DLogIf(!m_bDecodingStart, L"CMPCVideoDecFilter::Transform(): input sample without timestamps!"); } else if (hr == VFW_S_NO_STOP_TIME || rtStop - 1 <= rtStart) { rtStop = INVALID_TIME; } if (UseDXVA2()) { CheckPointer(m_pDXVA2Allocator, E_UNEXPECTED); } hr = m_pMSDKDecoder ? m_pMSDKDecoder->Decode(buffer, buflen, rtStart, rtStop) : Decode(buffer, buflen, rtStart, rtStop, pIn->IsSyncPoint() == S_OK, pIn->IsPreroll() == S_OK); m_bDecodingStart = TRUE; return hr; } void CMPCVideoDecFilter::UpdateAspectRatio() { if (m_nARMode) { bool bSetAR = true; if (m_nARMode == 2) { CMediaType& mt = m_pInput->CurrentMediaType(); if (mt.formattype == FORMAT_VideoInfo2 || mt.formattype == FORMAT_MPEG2_VIDEO || mt.formattype == FORMAT_DiracVideoInfo) { VIDEOINFOHEADER2* vih2 = (VIDEOINFOHEADER2*)mt.pbFormat; bSetAR = (!vih2->dwPictAspectRatioX && !vih2->dwPictAspectRatioY); } if (!bSetAR && (m_nARX && m_nARY)) { CSize aspect(m_nARX, m_nARY); ReduceDim(aspect); SetAspect(aspect); } } if (bSetAR) { if (m_pAVCtx && (m_pAVCtx->sample_aspect_ratio.num > 0) && (m_pAVCtx->sample_aspect_ratio.den > 0)) { CSize aspect(m_pAVCtx->sample_aspect_ratio.num * m_pAVCtx->width, m_pAVCtx->sample_aspect_ratio.den * m_pAVCtx->height); ReduceDim(aspect); SetAspect(aspect); } } } else if (m_nARX && m_nARY) { CSize aspect(m_nARX, m_nARY); ReduceDim(aspect); SetAspect(aspect); } } void CMPCVideoDecFilter::FlushDXVADecoder() { if (m_pDXVADecoder) { CAutoLock cAutoLock(&m_csReceive); if (m_pAVCtx && avcodec_is_open(m_pAVCtx)) { avcodec_flush_buffers(m_pAVCtx); } } } void CMPCVideoDecFilter::FillInVideoDescription(DXVA2_VideoDesc& videoDesc, D3DFORMAT Format/* = D3DFMT_A8R8G8B8*/) { memset(&videoDesc, 0, sizeof(videoDesc)); videoDesc.SampleWidth = m_nSurfaceWidth; videoDesc.SampleHeight = m_nSurfaceHeight; videoDesc.Format = Format; videoDesc.UABProtectionLevel = 1; } BOOL CMPCVideoDecFilter::IsSupportedDecoderMode(const GUID& decoderGUID) { if (IsDXVASupported()) { for (int i = 0; i < _countof(DXVAModes); i++) { if (DXVAModes[i].nCodecId == m_nCodecId && DXVAModes[i].decoderGUID == decoderGUID && DXVAModes[i].bHighBitdepth == !!m_bHighBitdepth) { return true; } } } return FALSE; } BOOL CMPCVideoDecFilter::IsSupportedDecoderConfig(const D3DFORMAT& nD3DFormat, const DXVA2_ConfigPictureDecode& config, bool& bIsPrefered) { bIsPrefered = (config.ConfigBitstreamRaw == (m_nCodecId == AV_CODEC_ID_H264 ? 2 : 1)); return (m_bHighBitdepth && nD3DFormat == MAKEFOURCC('P', '0', '1', '0') || (!m_bHighBitdepth && (nD3DFormat == MAKEFOURCC('N', 'V', '1', '2') || nD3DFormat == MAKEFOURCC('I', 'M', 'C', '3')))); } HRESULT CMPCVideoDecFilter::FindDXVA2DecoderConfiguration(IDirectXVideoDecoderService *pDecoderService, const GUID& guidDecoder, DXVA2_ConfigPictureDecode *pSelectedConfig, BOOL *pbFoundDXVA2Configuration) { HRESULT hr = S_OK; UINT cFormats = 0; UINT cConfigurations = 0; bool bIsPrefered = false; D3DFORMAT *pFormats = nullptr; DXVA2_ConfigPictureDecode *pConfig = nullptr; // Find the valid render target formats for this decoder GUID. hr = pDecoderService->GetDecoderRenderTargets(guidDecoder, &cFormats, &pFormats); if (SUCCEEDED(hr)) { // Look for a format that matches our output format. for (UINT iFormat = 0; iFormat < cFormats; iFormat++) { // Fill in the video description. Set the width, height, format, and frame rate. DXVA2_VideoDesc VideoDesc; FillInVideoDescription(VideoDesc, pFormats[iFormat]); // Get the available configurations. hr = pDecoderService->GetDecoderConfigurations(guidDecoder, &VideoDesc, nullptr, &cConfigurations, &pConfig); if (FAILED(hr)) { continue; } // Find a supported configuration. for (UINT iConfig = 0; iConfig < cConfigurations; iConfig++) { if (IsSupportedDecoderConfig(pFormats[iFormat], pConfig[iConfig], bIsPrefered)) { // This configuration is good. if (bIsPrefered || !*pbFoundDXVA2Configuration) { *pbFoundDXVA2Configuration = TRUE; *pSelectedConfig = pConfig[iConfig]; FillInVideoDescription(m_VideoDesc, pFormats[iFormat]); } if (bIsPrefered) { break; } } } CoTaskMemFree(pConfig); } // End of formats loop. } CoTaskMemFree(pFormats); // Note: It is possible to return S_OK without finding a configuration. return hr; } HRESULT CMPCVideoDecFilter::ConfigureDXVA2(IPin *pPin) { HRESULT hr = S_OK; CleanupD3DResources(); CComPtr<IMFGetService> pGetService; // Query the pin for IMFGetService. hr = pPin->QueryInterface(IID_PPV_ARGS(&pGetService)); // Get the Direct3D device manager. if (SUCCEEDED(hr)) { hr = pGetService->GetService(MR_VIDEO_ACCELERATION_SERVICE, IID_PPV_ARGS(&m_pDeviceManager)); } // Open a new device handle. if (SUCCEEDED(hr)) { hr = m_pDeviceManager->OpenDeviceHandle(&m_hDevice); } // Get the video decoder service. if (SUCCEEDED(hr)) { hr = m_pDeviceManager->GetVideoService(m_hDevice, IID_PPV_ARGS(&m_pDecoderService)); } if (SUCCEEDED(hr)) { hr = FindDecoderConfiguration(); } if (FAILED(hr)) { CleanupD3DResources(); } return hr; } HRESULT CMPCVideoDecFilter::SetEVRForDXVA2(IPin *pPin) { CComPtr<IMFGetService> pGetService; HRESULT hr = pPin->QueryInterface(IID_PPV_ARGS(&pGetService)); if (SUCCEEDED(hr)) { CComPtr<IDirectXVideoMemoryConfiguration> pVideoConfig; hr = pGetService->GetService(MR_VIDEO_ACCELERATION_SERVICE, IID_PPV_ARGS(&pVideoConfig)); if (SUCCEEDED(hr)) { // Notify the EVR. DXVA2_SurfaceType surfaceType; DWORD dwTypeIndex = 0; for (;;) { hr = pVideoConfig->GetAvailableSurfaceTypeByIndex(dwTypeIndex, &surfaceType); if (FAILED(hr)) { break; } if (surfaceType == DXVA2_SurfaceType_DecoderRenderTarget) { hr = pVideoConfig->SetSurfaceType(DXVA2_SurfaceType_DecoderRenderTarget); break; } ++dwTypeIndex; } } } return hr; } HRESULT CMPCVideoDecFilter::CreateDXVA2Decoder(LPDIRECT3DSURFACE9* ppDecoderRenderTargets, UINT nNumRenderTargets) { DLog(L"CMPCVideoDecFilter::CreateDXVA2Decoder()"); HRESULT hr; CComPtr<IDirectXVideoDecoder> pDirectXVideoDec; SAFE_DELETE(m_pDXVADecoder); hr = m_pDecoderService->CreateVideoDecoder(m_DXVADecoderGUID, &m_VideoDesc, &m_DXVA2Config, ppDecoderRenderTargets, nNumRenderTargets, &pDirectXVideoDec); if (SUCCEEDED(hr)) { m_pDXVADecoder = DNew CDXVA2Decoder(this, pDirectXVideoDec, &m_DXVADecoderGUID, &m_DXVA2Config, ppDecoderRenderTargets, nNumRenderTargets); } if (FAILED(hr)) { CleanDXVAVariable(); } return hr; } HRESULT CMPCVideoDecFilter::ReinitDXVA2Decoder() { HRESULT hr = E_FAIL; SAFE_DELETE(m_pDXVADecoder); if (m_pDXVA2Allocator && IsDXVASupported() && SUCCEEDED(FindDecoderConfiguration())) { hr = RecommitAllocator(); } return hr; } HRESULT CMPCVideoDecFilter::InitAllocator(IMemAllocator **ppAlloc) { HRESULT hr = S_FALSE; m_pDXVA2Allocator = DNew CVideoDecDXVAAllocator(this, &hr); if (!m_pDXVA2Allocator) { return E_OUTOFMEMORY; } if (FAILED(hr)) { SAFE_DELETE(m_pDXVA2Allocator); return hr; } // Return the IMemAllocator interface. return m_pDXVA2Allocator->QueryInterface(IID_PPV_ARGS(ppAlloc)); } HRESULT CMPCVideoDecFilter::RecommitAllocator() { HRESULT hr = S_OK; if (m_pDXVA2Allocator) { // Re-Commit the allocator (creates surfaces and new decoder) hr = m_pDXVA2Allocator->Decommit(); if (m_pDXVA2Allocator->DecommitInProgress()) { DLog(L"CMPCVideoDecFilter::RecommitAllocator() : WARNING! DXVA2 Allocator is still busy, trying to flush downstream"); GetOutputPin()->GetConnected()->BeginFlush(); GetOutputPin()->GetConnected()->EndFlush(); if (m_pDXVA2Allocator->DecommitInProgress()) { DLog(L"CMPCVideoDecFilter::RecommitAllocator() : WARNING! Flush had no effect, decommit of the allocator still not complete"); } else { DLog(L"CMPCVideoDecFilter::RecommitAllocator() : Flush was successfull, decommit completed!"); } } hr = m_pDXVA2Allocator->Commit(); } return hr; } // ISpecifyPropertyPages2 STDMETHODIMP CMPCVideoDecFilter::GetPages(CAUUID* pPages) { CheckPointer(pPages, E_POINTER); #ifdef REGISTER_FILTER pPages->cElems = 2; #else pPages->cElems = 1; #endif pPages->pElems = (GUID*)CoTaskMemAlloc(sizeof(GUID) * pPages->cElems); pPages->pElems[0] = __uuidof(CMPCVideoDecSettingsWnd); #ifdef REGISTER_FILTER pPages->pElems[1] = __uuidof(CMPCVideoDecCodecWnd); #endif return S_OK; } STDMETHODIMP CMPCVideoDecFilter::CreatePage(const GUID& guid, IPropertyPage** ppPage) { CheckPointer(ppPage, E_POINTER); if (*ppPage != nullptr) { return E_INVALIDARG; } HRESULT hr; if (guid == __uuidof(CMPCVideoDecSettingsWnd)) { (*ppPage = DNew CInternalPropertyPageTempl<CMPCVideoDecSettingsWnd>(nullptr, &hr))->AddRef(); } #ifdef REGISTER_FILTER else if (guid == __uuidof(CMPCVideoDecCodecWnd)) { (*ppPage = DNew CInternalPropertyPageTempl<CMPCVideoDecCodecWnd>(nullptr, &hr))->AddRef(); } #endif return *ppPage ? S_OK : E_FAIL; } // EVR functions HRESULT CMPCVideoDecFilter::DetectVideoCard_EVR(IPin *pPin) { IMFGetService* pGetService; HRESULT hr = pPin->QueryInterface(IID_PPV_ARGS(&pGetService)); if (SUCCEEDED(hr)) { // Try to get the adapter description of the active DirectX 9 device. IDirect3DDeviceManager9* pDevMan9; hr = pGetService->GetService(MR_VIDEO_ACCELERATION_SERVICE, IID_PPV_ARGS(&pDevMan9)); if (SUCCEEDED(hr)) { HANDLE hDevice; hr = pDevMan9->OpenDeviceHandle(&hDevice); if (SUCCEEDED(hr)) { IDirect3DDevice9* pD3DDev9; hr = pDevMan9->LockDevice(hDevice, &pD3DDev9, TRUE); if (hr == DXVA2_E_NEW_VIDEO_DEVICE) { // Invalid device handle. Try to open a new device handle. hr = pDevMan9->CloseDeviceHandle(hDevice); if (SUCCEEDED(hr)) { hr = pDevMan9->OpenDeviceHandle(&hDevice); // Try to lock the device again. if (SUCCEEDED(hr)) { hr = pDevMan9->LockDevice(hDevice, &pD3DDev9, TRUE); } } } if (SUCCEEDED(hr)) { D3DDEVICE_CREATION_PARAMETERS DevPar9; hr = pD3DDev9->GetCreationParameters(&DevPar9); if (SUCCEEDED(hr)) { IDirect3D9* pD3D9; hr = pD3DDev9->GetDirect3D(&pD3D9); if (SUCCEEDED(hr)) { D3DADAPTER_IDENTIFIER9 AdapID9; hr = pD3D9->GetAdapterIdentifier(DevPar9.AdapterOrdinal, 0, &AdapID9); if (SUCCEEDED(hr)) { // copy adapter description m_nPCIVendor = AdapID9.VendorId; m_nPCIDevice = AdapID9.DeviceId; m_VideoDriverVersion = AdapID9.DriverVersion.QuadPart; if (SysVersion::IsWin81orLater() && (m_VideoDriverVersion & 0xffff00000000) == 0 && (m_VideoDriverVersion & 0xffff) == 0) { // fix bug in GetAdapterIdentifier() m_VideoDriverVersion = (m_VideoDriverVersion & 0xffff000000000000) | ((m_VideoDriverVersion & 0xffff0000) << 16) | 0xffffffff; } m_strDeviceDescription.Format(L"%S (%04X:%04X)", AdapID9.Description, m_nPCIVendor, m_nPCIDevice); } } pD3D9->Release(); } pD3DDev9->Release(); pDevMan9->UnlockDevice(hDevice, FALSE); } pDevMan9->CloseDeviceHandle(hDevice); } pDevMan9->Release(); } pGetService->Release(); } return hr; } HRESULT CMPCVideoDecFilter::SetFFMpegCodec(int nCodec, bool bEnabled) { CAutoLock cAutoLock(&m_csProps); if (nCodec < 0 || nCodec >= VDEC_COUNT) { return E_FAIL; } m_VideoFilters[nCodec] = bEnabled; return S_OK; } HRESULT CMPCVideoDecFilter::SetDXVACodec(int nCodec, bool bEnabled) { CAutoLock cAutoLock(&m_csProps); if (nCodec < 0 || nCodec >= VDEC_DXVA_COUNT) { return E_FAIL; } m_DXVAFilters[nCodec] = bEnabled; return S_OK; } // IFFmpegDecFilter STDMETHODIMP CMPCVideoDecFilter::SaveSettings() { #ifdef REGISTER_FILTER CRegKey key; if (ERROR_SUCCESS == key.Create(HKEY_CURRENT_USER, OPT_REGKEY_VideoDec)) { key.SetDWORDValue(OPT_ThreadNumber, m_nThreadNumber); key.SetDWORDValue(OPT_DiscardMode, m_nDiscardMode); key.SetDWORDValue(OPT_ScanType, (int)m_nScanType); key.SetDWORDValue(OPT_ARMode, m_nARMode); key.SetDWORDValue(OPT_DXVACheck, m_nDXVACheckCompatibility); key.SetDWORDValue(OPT_DisableDXVA_SD, m_nDXVA_SD); // === New swscaler options for (int i = 0; i < PixFmt_count; i++) { CString optname = OPT_SW_prefix; optname += GetSWOF(i)->name; key.SetDWORDValue(optname, m_fPixFmts[i]); } key.SetDWORDValue(OPT_SwRGBLevels, m_nSwRGBLevels); // } if (ERROR_SUCCESS == key.Create(HKEY_CURRENT_USER, OPT_REGKEY_VCodecs)) { for (size_t i = 0; i < _countof(vcodecs); i++) { DWORD dw = m_nActiveCodecs & vcodecs[i].flag ? 1 : 0; key.SetDWORDValue(vcodecs[i].opt_name, dw); } } #else CProfile& profile = AfxGetProfile(); profile.WriteInt(OPT_SECTION_VideoDec, OPT_ThreadNumber, m_nThreadNumber); profile.WriteInt(OPT_SECTION_VideoDec, OPT_DiscardMode, m_nDiscardMode); profile.WriteInt(OPT_SECTION_VideoDec, OPT_ScanType, (int)m_nScanType); profile.WriteInt(OPT_SECTION_VideoDec, OPT_ARMode, m_nARMode); profile.WriteInt(OPT_SECTION_VideoDec, OPT_DXVACheck, m_nDXVACheckCompatibility); profile.WriteInt(OPT_SECTION_VideoDec, OPT_DisableDXVA_SD, m_nDXVA_SD); profile.WriteInt(OPT_SECTION_VideoDec, OPT_SwRGBLevels, m_nSwRGBLevels); for (int i = 0; i < PixFmt_count; i++) { CString optname = OPT_SW_prefix; optname += GetSWOF(i)->name; profile.WriteBool(OPT_SECTION_VideoDec, optname, m_fPixFmts[i]); } #endif return S_OK; } // === IMPCVideoDecFilter STDMETHODIMP CMPCVideoDecFilter::SetThreadNumber(int nValue) { CAutoLock cAutoLock(&m_csProps); m_nThreadNumber = nValue; return S_OK; } STDMETHODIMP_(int) CMPCVideoDecFilter::GetThreadNumber() { CAutoLock cAutoLock(&m_csProps); return m_nThreadNumber; } STDMETHODIMP CMPCVideoDecFilter::SetDiscardMode(int nValue) { if (nValue != AVDISCARD_DEFAULT && nValue != AVDISCARD_BIDIR) { return E_INVALIDARG; } CAutoLock cAutoLock(&m_csProps); m_nDiscardMode = nValue; if (m_pAVCtx) { m_pAVCtx->skip_frame = (AVDiscard)m_nDiscardMode; } return S_OK; } STDMETHODIMP_(int) CMPCVideoDecFilter::GetDiscardMode() { CAutoLock cAutoLock(&m_csProps); return m_nDiscardMode; } STDMETHODIMP CMPCVideoDecFilter::SetScanType(MPC_SCAN_TYPE nValue) { CAutoLock cAutoLock(&m_csProps); m_nScanType = nValue; return S_OK; } STDMETHODIMP_(MPC_SCAN_TYPE) CMPCVideoDecFilter::GetScanType() { CAutoLock cAutoLock(&m_csProps); return m_nScanType; } STDMETHODIMP_(GUID*) CMPCVideoDecFilter::GetDXVADecoderGuid() { return m_pGraph && m_pDXVADecoder ? &m_DXVADecoderGUID : nullptr; } STDMETHODIMP CMPCVideoDecFilter::SetActiveCodecs(ULONGLONG nValue) { CAutoLock cAutoLock(&m_csProps); m_nActiveCodecs = nValue; return S_OK; } STDMETHODIMP_(ULONGLONG) CMPCVideoDecFilter::GetActiveCodecs() { CAutoLock cAutoLock(&m_csProps); return m_nActiveCodecs; } STDMETHODIMP CMPCVideoDecFilter::SetARMode(int nValue) { CAutoLock cAutoLock(&m_csProps); m_nARMode = nValue; return S_OK; } STDMETHODIMP_(int) CMPCVideoDecFilter::GetARMode() { CAutoLock cAutoLock(&m_csProps); return m_nARMode; } STDMETHODIMP CMPCVideoDecFilter::SetDXVACheckCompatibility(int nValue) { CAutoLock cAutoLock(&m_csProps); m_nDXVACheckCompatibility = nValue; return S_OK; } STDMETHODIMP_(int) CMPCVideoDecFilter::GetDXVACheckCompatibility() { CAutoLock cAutoLock(&m_csProps); return m_nDXVACheckCompatibility; } STDMETHODIMP CMPCVideoDecFilter::SetDXVA_SD(int nValue) { CAutoLock cAutoLock(&m_csProps); m_nDXVA_SD = nValue; return S_OK; } STDMETHODIMP_(int) CMPCVideoDecFilter::GetDXVA_SD() { CAutoLock cAutoLock(&m_csProps); return m_nDXVA_SD; } // === New swscaler options STDMETHODIMP CMPCVideoDecFilter::SetSwRefresh(int nValue) { CAutoLock cAutoLock(&m_csProps); if (nValue && ((m_pAVCtx && m_nDecoderMode == MODE_SOFTWARE) || m_pMSDKDecoder)) { ChangeOutputMediaFormat(nValue); } return S_OK; } STDMETHODIMP CMPCVideoDecFilter::SetSwPixelFormat(MPCPixelFormat pf, bool enable) { CAutoLock cAutoLock(&m_csProps); if (pf < 0 || pf >= PixFmt_count) { return E_INVALIDARG; } m_fPixFmts[pf] = enable; return S_OK; } STDMETHODIMP_(bool) CMPCVideoDecFilter::GetSwPixelFormat(MPCPixelFormat pf) { CAutoLock cAutoLock(&m_csProps); if (pf < 0 || pf >= PixFmt_count) { return false; } return m_fPixFmts[pf]; } STDMETHODIMP CMPCVideoDecFilter::SetSwRGBLevels(int nValue) { CAutoLock cAutoLock(&m_csProps); m_nSwRGBLevels = nValue; return S_OK; } STDMETHODIMP_(int) CMPCVideoDecFilter::GetSwRGBLevels() { CAutoLock cAutoLock(&m_csProps); return m_nSwRGBLevels; } STDMETHODIMP_(int) CMPCVideoDecFilter::GetColorSpaceConversion() { CAutoLock cAutoLock(&m_csProps); if (!m_pAVCtx) { return -1; // no decoder } if (m_nDecoderMode != MODE_SOFTWARE || m_pAVCtx->pix_fmt == AV_PIX_FMT_NONE || m_FormatConverter.GetOutPixFormat() == PixFmt_None) { return -2; // no conversion } const AVPixFmtDescriptor* av_pfdesc = av_pix_fmt_desc_get(m_pAVCtx->pix_fmt); if (!av_pfdesc) { return -2; } bool in_rgb = !!(av_pfdesc->flags & (AV_PIX_FMT_FLAG_RGB|AV_PIX_FMT_FLAG_PAL)); bool out_rgb = (m_FormatConverter.GetOutPixFormat() == PixFmt_RGB32 || m_FormatConverter.GetOutPixFormat() == PixFmt_RGB48); if (in_rgb < out_rgb) { return 1; // YUV->RGB conversion } if (in_rgb > out_rgb) { return 2; // RGB->YUV conversion } return 0; // YUV->YUV or RGB->RGB conversion } STDMETHODIMP CMPCVideoDecFilter::SetMvcOutputMode(int nMode, bool bSwapLR) { CAutoLock cAutoLock(&m_csProps); if (nMode < 0 || nMode > MVC_OUTPUT_TopBottom) { return E_INVALIDARG; } m_iMvcOutputMode = nMode; m_bMvcSwapLR = bSwapLR; if (m_pMSDKDecoder) { m_pMSDKDecoder->SetOutputMode(nMode, bSwapLR); } return S_OK; } STDMETHODIMP_(int) CMPCVideoDecFilter::GetMvcActive() { return (m_pMSDKDecoder != nullptr) ? 1 + m_pMSDKDecoder->GetHwAcceleration() : 0; } STDMETHODIMP_(CString) CMPCVideoDecFilter::GetInformation(MPCInfo index) { CAutoLock cAutoLock(&m_csProps); CString infostr; switch (index) { case INFO_MPCVersion: infostr.Format(L"%s (build %d)", MPC_VERSION_WSTR, MPC_VERSION_REV); break; case INFO_InputFormat: if (m_pAVCtx) { const auto& pix_fmt = m_pDXVADecoder ? m_pAVCtx->sw_pix_fmt : m_pAVCtx->pix_fmt; infostr = m_pAVCtx->codec_descriptor->name; if (m_pAVCtx->codec_id == AV_CODEC_ID_RAWVIDEO) { infostr.AppendFormat(L" '%s'", FourccToWStr(m_pAVCtx->codec_tag)); } if (const AVPixFmtDescriptor* desc = av_pix_fmt_desc_get(pix_fmt)) { if (desc->flags & AV_PIX_FMT_FLAG_PAL) { infostr.Append(L", palettized RGB"); } else if (desc->nb_components == 1 || desc->nb_components == 2) { infostr.AppendFormat(L", Gray %d-bit", GetLumaBits(pix_fmt)); } else if(desc->flags & AV_PIX_FMT_FLAG_RGB) { int bidepth = 0; for (int i = 0; i < desc->nb_components; i++) { bidepth += desc->comp[i].depth; } infostr.Append(desc->flags & AV_PIX_FMT_FLAG_ALPHA ? L", RGBA" : L", RGB"); infostr.AppendFormat(L" %dbpp", bidepth); } else if (desc->nb_components == 0) { // unknown } else { infostr.Append(desc->flags & AV_PIX_FMT_FLAG_ALPHA ? L", YUVA" : L", YUV"); infostr.AppendFormat(L" %d-bit %s", GetLumaBits(pix_fmt), GetChromaSubsamplingStr(pix_fmt)); if (desc->name && !strncmp(desc->name, "yuvj", 4)) { infostr.Append(L" full range"); } } } } else if (m_pMSDKDecoder) { infostr = L"h264(MVC 3D), YUV 8-bit, 4:2:0"; } break; case INFO_FrameSize: if (m_win && m_hin) { __int64 sarx = (__int64)m_arx * m_hin; __int64 sary = (__int64)m_ary * m_win; ReduceDim(sarx, sary); infostr.Format(L"%dx%d, SAR %d:%d, DAR %d:%d", m_win, m_hin, (int)sarx, (int)sary, m_arx, m_ary); } break; case INFO_OutputFormat: if (GUID* DxvaGuid = GetDXVADecoderGuid()) { infostr.Format(L"DXVA2 (%s)", GetDXVAMode(*DxvaGuid)); break; } if (const SW_OUT_FMT* swof = GetSWOF(m_FormatConverter.GetOutPixFormat())) { infostr.Format(L"%s (%d-bit %s)", swof->name, swof->luma_bits, GetChromaSubsamplingStr(swof->av_pix_fmt)); } break; case INFO_GraphicsAdapter: infostr = m_strDeviceDescription; break; } return infostr; } HRESULT CMPCVideoDecFilter::CheckDXVA2Decoder(AVCodecContext *c) { CheckPointer(m_pAVCtx, E_POINTER); HRESULT hr = S_OK; if (m_pDXVADecoder) { if ((m_nSurfaceWidth != FFALIGN(c->coded_width, m_nAlign) || m_nSurfaceHeight != FFALIGN(c->coded_height, m_nAlign)) || ((m_nCodecId == AV_CODEC_ID_HEVC || m_nCodecId == AV_CODEC_ID_VP9) && m_dxva_pix_fmt != m_pAVCtx->sw_pix_fmt)) { const int depth = GetLumaBits(m_pAVCtx->sw_pix_fmt); const BOOL bHighBitdepth = (depth == 10) && ((m_nCodecId == AV_CODEC_ID_HEVC && m_pAVCtx->profile == FF_PROFILE_HEVC_MAIN_10) || (m_nCodecId == AV_CODEC_ID_VP9 && m_pAVCtx->profile == FF_PROFILE_VP9_2)); const auto bBitdepthChanged = (m_bHighBitdepth != bHighBitdepth); m_nSurfaceWidth = FFALIGN(c->coded_width, m_nAlign); m_nSurfaceHeight = FFALIGN(c->coded_height, m_nAlign); m_bHighBitdepth = bHighBitdepth; avcodec_flush_buffers(c); if (SUCCEEDED(hr = FindDecoderConfiguration())) { if (bBitdepthChanged) { ChangeOutputMediaFormat(2); } hr = RecommitAllocator(); } if (FAILED(hr)) { SAFE_DELETE(m_pDXVADecoder); m_nDecoderMode = MODE_SOFTWARE; DXVAState::ClearState(); InitDecoder(&m_pCurrentMediaType); ChangeOutputMediaFormat(2); } m_dxva_pix_fmt = m_pAVCtx->sw_pix_fmt; } } return hr; } int CMPCVideoDecFilter::av_get_buffer(struct AVCodecContext *c, AVFrame *pic, int flags) { CMPCVideoDecFilter* pFilter = static_cast<CMPCVideoDecFilter*>(c->opaque); CheckPointer(pFilter->m_pDXVADecoder, -1); if (!check_dxva_compatible(c->codec_id, c->sw_pix_fmt, c->profile)) { pFilter->m_bDXVACompatible = false; return -1; } if (FAILED(pFilter->CheckDXVA2Decoder(c))) { return -1; } return pFilter->m_pDXVADecoder->get_buffer_dxva(pic); } enum AVPixelFormat CMPCVideoDecFilter::av_get_format(struct AVCodecContext *c, const enum AVPixelFormat * pix_fmts) { CMPCVideoDecFilter* pFilter = static_cast<CMPCVideoDecFilter*>(c->opaque); const enum AVPixelFormat *p; for (p = pix_fmts; *p != -1; p++) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p); if (!desc || !(desc->flags & AV_PIX_FMT_FLAG_HWACCEL)) break; if (*p == AV_PIX_FMT_DXVA2_VLD) { if (FAILED(pFilter->CheckDXVA2Decoder(c))) { continue; } break; } } return *p; } // CVideoDecOutputPin CVideoDecOutputPin::CVideoDecOutputPin(TCHAR* pObjectName, CBaseVideoFilter* pFilter, HRESULT* phr, LPCWSTR pName) : CBaseVideoOutputPin(pObjectName, pFilter, phr, pName) , m_pVideoDecFilter(static_cast<CMPCVideoDecFilter*>(pFilter)) { } CVideoDecOutputPin::~CVideoDecOutputPin() { } HRESULT CVideoDecOutputPin::InitAllocator(IMemAllocator **ppAlloc) { if (m_pVideoDecFilter && m_pVideoDecFilter->UseDXVA2()) { return m_pVideoDecFilter->InitAllocator(ppAlloc); } return __super::InitAllocator(ppAlloc); } namespace MPCVideoDec { void GetSupportedFormatList(FORMATS& fmts) { fmts.clear(); for (size_t i = 0; i < _countof(sudPinTypesIn); i++) { FORMAT fmt = { sudPinTypesIn[i].clsMajorType, ffCodecs[i].clsMinorType, ffCodecs[i].FFMPEGCode, ffCodecs[i].DXVACode }; fmts.push_back(fmt); } } } // namespace MPCVideoDec
31.857347
250
0.707311
565fc0923bd94d8fe5517012355b458a73609f61
839
hpp
C++
user.hpp
chenillax/E4C_Challenge_Carbozer
3c23b9f106d6b148b84ff2af7e87f8a4ece8b771
[ "Apache-2.0" ]
null
null
null
user.hpp
chenillax/E4C_Challenge_Carbozer
3c23b9f106d6b148b84ff2af7e87f8a4ece8b771
[ "Apache-2.0" ]
null
null
null
user.hpp
chenillax/E4C_Challenge_Carbozer
3c23b9f106d6b148b84ff2af7e87f8a4ece8b771
[ "Apache-2.0" ]
null
null
null
#ifndef __USER__ #define __USER__ #include <cstdio> #include <cstdlib> #include <iostream> #include <vector> #include <string> /* The differents enumerations we need to our algortithm */ enum class Terminal_device { Phone, Pc, ChromeCast, Tablet}; enum class Quality { Auto, p144, p240, p360,p480,p720,p1080}; enum class Stream { Wifi, Net}; enum class Localisation {France, Germany, Spain, GreatBritain, Italy,Norway, Sweden,Poland,Belgium,Portugal}; class Terminal { public: Terminal_device device; public : Terminal(){}; Terminal(Terminal_device device); //returns the embedded emission of the device double embedded_emission(); //returns the emission the device consumes (gC02eq/hours) (We chose thant the "auto mode" is the mean of each quality.) double emission_per_hours(); }; #endif
24.676471
123
0.724672
56611e4af95260dd0beb1455713d0ae31848f32e
8,270
cpp
C++
src/test/test-basic-psi.cpp
cryptohuism/tpsi
e60c9faaf1bb13b92a6c3656d5ebc784759838bf
[ "Apache-2.0" ]
1
2022-01-10T06:31:00.000Z
2022-01-10T06:31:00.000Z
src/test/test-basic-psi.cpp
cryptohuism/tpsi
e60c9faaf1bb13b92a6c3656d5ebc784759838bf
[ "Apache-2.0" ]
null
null
null
src/test/test-basic-psi.cpp
cryptohuism/tpsi
e60c9faaf1bb13b92a6c3656d5ebc784759838bf
[ "Apache-2.0" ]
null
null
null
#include "basic_psi.h" #include <stdio.h> #include <iostream> #include <iomanip> #include <cstdlib> #include <cmath> #include <sys/time.h> #include "tfhe.h" #include "polynomials.h" #include "lwesamples.h" #include "lwekey.h" #include "lweparams.h" #include "tlwe.h" #include "tgsw.h" using namespace std; // ********************************************************************************** // ********************************* MAIN ******************************************* // ********************************************************************************** void dieDramatically(string message) { cerr << message << endl; abort(); } //EXPORT void tLweExtractKey(LweKey* result, const TLweKey* key); //TODO: change the name and put in a .h //EXPORT void tfhe_createLweBootstrappingKeyFFT(LweBootstrappingKeyFFT* bk, const LweKey* key_in, const TGswKey* rgsw_key); //EXPORT void tfhe_bootstrapFFT(LweSample* result, const LweBootstrappingKeyFFT* bk, Torus32 mu1, Torus32 mu0, const LweSample* x); #ifndef NDEBUG extern const TLweKey *debug_accum_key; extern const LweKey *debug_extract_key; extern const LweKey *debug_in_key; #endif int32_t main(int32_t argc, char **argv) { #ifndef NDEBUG cout << "DEBUG MODE!" << endl; #endif const int32_t nb_re_samples = 55; // nb_re_samples is equal to s_y, the number of receiver's items. const int32_t nb_se_samples = 1000; // nb_re_samples is equal to s_x, the number of sender's items. const int32_t nb_trials = 10; // generate params int32_t minimum_lambda = 100; TFheGateBootstrappingParameterSet *params = new_default_gate_bootstrapping_parameters(minimum_lambda); const LweParams *in_out_params = params->in_out_params; // generate the secret keyset TFheGateBootstrappingSecretKeySet *keyset = new_random_gate_bootstrapping_secret_keyset(params); const int32_t sigma_exp = params->tgsw_params->tlwe_params->N /2; // sigma = 9 when N = 1024 srand((unsigned)time(NULL)); for (int32_t trial = 0; trial < nb_trials; ++trial) { // sample Y for receiver int32_t *receiver_items = new int32_t[nb_re_samples]; sampleItems(receiver_items, nb_re_samples, sigma_exp); // receiver encrypts Y and sends ciphertext reciever_se to sender TLweSample *reciever_se = new_TLweSample_array(nb_re_samples, params->tgsw_params->tlwe_params); // generate inputs (0-->nb_re_samples=63) for (int32_t i = 0; i < nb_re_samples; ++i) { bootsRlweEncrypt(reciever_se + i, *(receiver_items + i), keyset); } // sample X for sender int32_t *sender_items = new int32_t[nb_se_samples]; sampleItems(sender_items, nb_se_samples, sigma_exp); /** test * let sender_items[i] = receiver_items[i] for some random items, and receiver * would decrypt reciever_re[i] to true for these i. * */ for (int32_t i = 0; i < nb_re_samples; ++i) if(rand() % 3 == 1) sender_items[i] = receiver_items[i]; // evaluate the EXTRACT function cout << "starting extract function...trial " << trial << endl; clock_t begin = clock(); LweSample *reciever_re = new_LweSample_array(nb_re_samples, &params->tgsw_params->tlwe_params->extracted_lweparams); for (int32_t i = 0; i < nb_re_samples; ++i) { bootsExtract(reciever_re + i, reciever_se + i, sender_items, nb_se_samples, in_out_params, params->tgsw_params->tlwe_params); /** In fact, we decrypt it using n-lwe secret key instead of N-lwe secret key now if * we use Keyswitch function. What's more, this code can also be simplified within * generating n-Lwe secret key and bootstrarpping keys. * * LweSample *reciever_re = new_LweSample_array(nb_re_samples, in_out_params); * bootsKeySwitch(reciever_re + i, keyset->cloud.bk->ks, u + i); */ } clock_t end = clock(); cout << "finished extract function tree" << endl; cout << "time extract (microsecs)... " << end - begin; cout << " with (|X|=" << nb_se_samples << ", |Y|=" << nb_re_samples << ")" << endl; /** verification * The receiver encrypts messages to tlwe ciphertext while receives lwe ciphertext. * Therefore, it's worth noting that the decryption lwe key 'Nkey' is extracted * from the tlwe key, and the decryption key is a vector while the tlwe key is a * polynomial. What's more, they have the same information. */ LweKey *Nkey = new_LweKey(&params->tgsw_params->tlwe_params->extracted_lweparams); tLweExtractKey(Nkey, &keyset->tgsw_key->tlwe_key); for (int32_t i = 0; i < nb_re_samples; ++i) { bool mess = 0; for (int32_t j = 0; j < nb_se_samples; ++j) { if (*(receiver_items + i) == *(sender_items + j)) { mess = 1; break; } } bool out = bootsLweDecrypt(reciever_re + i, Nkey); if (out != mess) { cout << "ERROR!!! " << trial << "," << i << " - "; cout << t32tod(lwePhase(reciever_re + i, Nkey)) << endl; } } // test full psi begin LweSample *test_and = new_LweSample_array(nb_re_samples-1, in_out_params); LweSample *test_or = new_LweSample_array(nb_re_samples-1, in_out_params); LweSample *test_nand = new_LweSample_array(nb_re_samples-1, in_out_params); LweSample *reno = new_LweSample_array(nb_re_samples, in_out_params); for (int32_t i = 0; i < nb_re_samples; ++i) { bootsKeySwitch(reno + i, keyset->cloud.bk->ks, reciever_re + i); //cout << "mu1 is " << lwePhase(reno + i, keyset->lwe_key) << endl; renormalize(reno + i, in_out_params); } //for(int32_t i = 0; i < nb_re_samples; ++i) cout << "mu2 is " << lwePhase(reno + i, keyset->lwe_key) << endl; // after renormalize for (int32_t i = 0; i < nb_re_samples - 1; ++i) { bootsAND(test_and + i, reno + i, reno + i+1, &keyset->cloud); bootsOR(test_or + i, reno + i, reno + i+1, &keyset->cloud); bootsNAND(test_nand + i, reno + i, reno + i+1, &keyset->cloud); } for (int32_t i = 0; i < nb_re_samples - 1; ++i) { bool out_and = bootsSymDecrypt(test_and + i, keyset); bool out_or = bootsSymDecrypt(test_or + i, keyset); bool out_nand = bootsSymDecrypt(test_nand + i, keyset); if (out_and != (bootsSymDecrypt(reno + i, keyset) && bootsSymDecrypt(reno + i+1, keyset))) { cout << "ERROR!!! AND" << trial << "," << i << " - "; cout << t32tod(lwePhase(test_and + i, keyset->lwe_key)) << endl; } cout << "(out_and= " << out_and << ") ?= " << (bootsSymDecrypt(reno + i, keyset) && bootsSymDecrypt(reno + i+1, keyset)) << endl; if (out_or != (bootsSymDecrypt(reno + i, keyset) || bootsSymDecrypt(reno + i+1, keyset))) { cout << "ERROR!!! OR" << trial << "," << i << " - "; cout << t32tod(lwePhase(test_or + i, keyset->lwe_key)) << endl; } cout << "(out_or = " << out_or << ") ?= " << (bootsSymDecrypt(reno + i, keyset) || bootsSymDecrypt(reno + i+1, keyset)) << endl; if (out_nand != 1 - bootsSymDecrypt(reno + i, keyset) * bootsSymDecrypt(reno + i+1, keyset)) { cout << "ERROR!!! NAND" << trial << "," << i << " - "; cout << t32tod(lwePhase(test_nand + i, keyset->lwe_key)) << endl; } cout << "(out_nand = " << out_nand << ") ?= " << 1 - bootsSymDecrypt(reno + i, keyset) * bootsSymDecrypt(reno + i+1, keyset) << endl; } // test full psi end delete[] sender_items; delete[] receiver_items; delete_TLweSample_array(nb_re_samples, reciever_se); delete_LweSample_array(nb_re_samples, reciever_re); } delete_gate_bootstrapping_secret_keyset(keyset); delete_gate_bootstrapping_parameters(params); return 0; }
43.072917
145
0.585127
56630015bb06d9de967c4e747d9407f2d116dd69
1,086
cpp
C++
cpp/src/main.cpp
cnloni/othello
f80f190e505b6a4dd2b2bd49054651dbea4f00fa
[ "Apache-2.0" ]
1
2021-01-16T03:34:06.000Z
2021-01-16T03:34:06.000Z
cpp/src/main.cpp
cnloni/othello
f80f190e505b6a4dd2b2bd49054651dbea4f00fa
[ "Apache-2.0" ]
null
null
null
cpp/src/main.cpp
cnloni/othello
f80f190e505b6a4dd2b2bd49054651dbea4f00fa
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include "b36.hpp" #include "board.hpp" using namespace std; void execute(uint64_t bp, uint64_t wp, int turn, int alpha, int beta) { Board<B36> board; int result = board.getBestResult(bp, wp, turn, alpha, beta); cout << board.getFinalBoardString() << endl; cout << "Initial = " << board.getInitialNodeString() << endl; cout << "Final = " << board.getFinalNodeString() << endl; cout << "Result = " << result << endl; cout << "Moves = " << board.getMoveListString() << endl; cout << "Count = " << board.getNodeCount() << endl; cout << "Elapsed = " << board.getElapsedTime() << endl; } //12駒から int main12() { execute(1753344, 81854976, 0, -6, -2); return 0; } //14駒から int main14() { execute(551158016, 69329408, 0, -6, -2); return 0; } //16駒から int main16() { execute(550219776, 70271748, 0, -6, -2); return 0; } int main(int narg, char** argv) { int sel = 12; if (narg > 1) { sel = atoi(argv[1]); } cout << "Selected = " << sel << endl; switch(sel) { case 14: return main14(); case 16: return main16(); default: return main12(); } }
21.72
71
0.617864
5664c4ef1c5b2b7b8b5d2ca9902fd2afaa132a88
23,964
cpp
C++
basecode/debugger/environment.cpp
Alaboudi1/bootstrap
4ec4629424ad6fe70c84d95d79b2132f24832379
[ "MIT" ]
32
2018-05-14T23:26:54.000Z
2020-06-14T10:13:20.000Z
basecode/debugger/environment.cpp
Alaboudi1/bootstrap
4ec4629424ad6fe70c84d95d79b2132f24832379
[ "MIT" ]
79
2018-08-01T11:50:45.000Z
2020-11-17T13:40:06.000Z
basecode/debugger/environment.cpp
Alaboudi1/bootstrap
4ec4629424ad6fe70c84d95d79b2132f24832379
[ "MIT" ]
14
2021-01-08T05:05:19.000Z
2022-03-27T14:56:56.000Z
// ---------------------------------------------------------------------------- // // Basecode Bootstrap Compiler // Copyright (C) 2018 Jeff Panici // All rights reserved. // // This software source file is licensed under the terms of MIT license. // For details, please read the LICENSE file. // // ---------------------------------------------------------------------------- #include <vm/terp.h> #include <vm/label.h> #include <vm/assembler.h> #include <common/defer.h> #include <parser/token.h> #include <compiler/session.h> #include <common/string_support.h> #include "environment.h" #include "stack_window.h" #include "header_window.h" #include "footer_window.h" #include "output_window.h" #include "memory_window.h" #include "errors_window.h" #include "command_window.h" #include "assembly_window.h" #include "registers_window.h" namespace basecode::debugger { std::unordered_map<command_type_t, command_handler_function_t> environment::s_command_handlers = { {command_type_t::help, std::bind(&environment::on_help, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, {command_type_t::find, std::bind(&environment::on_find, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, {command_type_t::goto_line, std::bind(&environment::on_goto_line, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, {command_type_t::show_memory, std::bind(&environment::on_show_memory, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, {command_type_t::read_memory, std::bind(&environment::on_read_memory, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, {command_type_t::write_memory, std::bind(&environment::on_write_memory, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, }; /////////////////////////////////////////////////////////////////////////// environment::environment(compiler::session& session) :_session(session) { } environment::~environment() { delete _stack_window; delete _output_window; delete _header_window; delete _footer_window; delete _memory_window; delete _command_window; delete _assembly_window; delete _registers_window; } int environment::ch() const { return _ch; } void environment::draw_all() { _header_window->draw(*this); _footer_window->draw(*this); _assembly_window->draw(*this); _registers_window->draw(*this); _memory_window->draw(*this); _output_window->draw(*this); _stack_window->draw(*this); _command_window->draw(*this); _errors_window->draw(*this); refresh(); } void environment::pop_state() { if (_state_stack.empty()) return; _state_stack.pop(); } void environment::cancel_command() { if (current_state() != debugger_state_t::command_entry) return; pop_state(); _header_window->mark_dirty(); _command_window->mark_dirty(); draw_all(); } bool environment::run(common::result& r) { auto& terp = _session.terp(); _output_window->start_redirect(); while (true) { auto pc = terp.register_file().r[vm::register_pc].qw; auto bp = breakpoint(pc); if (bp != nullptr && bp->enabled && current_state() != debugger_state_t::break_s) { push_state(debugger_state_t::break_s); _header_window->mark_dirty(); _assembly_window->mark_dirty(); } auto user_step = false; _ch = getch(); switch (_ch) { case KEY_F(1): { push_state(debugger_state_t::command_entry); _header_window->mark_dirty(); _command_window->reset(); break; } case KEY_F(2): { terp.reset(); pc = terp.register_file().r[vm::register_pc].qw; unwind_state_stack(); _output_window->clear(); _stack_window->mark_dirty(); _header_window->mark_dirty(); _memory_window->mark_dirty(); _registers_window->mark_dirty(); _assembly_window->move_to_address(pc); break; } case KEY_F(3): { goto _exit; } case KEY_F(8): { if (current_state() == debugger_state_t::break_s) { pop_state(); if (current_state() == debugger_state_t::running) { pop_state(); push_state(debugger_state_t::single_step); } } if (current_state() == debugger_state_t::single_step) { user_step = true; } else { // XXX: state error } break; } case KEY_F(9): { switch (current_state()) { case debugger_state_t::ended: case debugger_state_t::errored: case debugger_state_t::running: case debugger_state_t::command_entry: case debugger_state_t::command_execute: { break; } case debugger_state_t::stopped: { push_state(debugger_state_t::single_step); _assembly_window->move_to_address(pc); break; } case debugger_state_t::break_s: { pop_state(); if (current_state() == debugger_state_t::single_step) { pop_state(); push_state(debugger_state_t::running); } break; } case debugger_state_t::single_step: { pop_state(); push_state(debugger_state_t::running); break; } } _header_window->mark_dirty(); break; } case CTRL('c'): { if (current_state() == debugger_state_t::running) pop_state(); _stack_window->mark_dirty(); _header_window->mark_dirty(); _output_window->mark_dirty(); _memory_window->mark_dirty(); _assembly_window->mark_dirty(); _registers_window->mark_dirty(); break; } case CTRL('r'): { _registers_window->update(*this); break; } case ERR: { break; } default: { switch (current_state()) { case debugger_state_t::errored: { _errors_window->update(*this); _errors_window->mark_dirty(); break; } case debugger_state_t::command_entry: _command_window->update(*this); _command_window->mark_dirty(); _header_window->mark_dirty(); break; default: _assembly_window->update(*this); break; } break; } } bool execute_next_step; if (user_step) { execute_next_step = current_state() == debugger_state_t::single_step; } else { execute_next_step = current_state() == debugger_state_t::running; }; if (execute_next_step) { common::result step_result {}; auto success = terp.step(step_result); if (!success) { pop_state(); push_state(debugger_state_t::errored); _errors_window->visible(true); } else { pc = terp.register_file().r[vm::register_pc].qw; if (terp.has_exited()) { pop_state(); push_state(debugger_state_t::ended); } else { _assembly_window->move_to_address(pc); } } _stack_window->mark_dirty(); _header_window->mark_dirty(); _memory_window->mark_dirty(); _registers_window->mark_dirty(); } _output_window->process_buffers(); draw_all(); refresh(); } _exit: _output_window->stop_redirect(); return true; } void environment::unwind_state_stack() { while (!_state_stack.empty()) _state_stack.pop(); } breakpoint_t* environment::add_breakpoint( uint64_t address, breakpoint_type_t type) { auto bp = breakpoint(address); if (bp != nullptr) return bp; auto it = _breakpoints.insert(std::make_pair( address, breakpoint_t{true, address, type})); return &it.first->second; } compiler::session& environment::session() { return _session; } bool environment::shutdown(common::result& r) { endwin(); return true; } bool environment::initialize(common::result& r) { initscr(); start_color(); raw(); keypad(stdscr, true); noecho(); nodelay(stdscr, true); init_pair(1, COLOR_BLUE, COLOR_WHITE); init_pair(2, COLOR_BLUE, COLOR_YELLOW); init_pair(3, COLOR_RED, COLOR_WHITE); init_pair(4, COLOR_CYAN, COLOR_WHITE); _main_window = new window(nullptr, stdscr); _main_window->initialize(); _header_window = new header_window( _main_window, 0, 0, _main_window->max_width(), 1); _header_window->initialize(); _footer_window = new footer_window( _main_window, 0, _main_window->max_height() - 1, _main_window->max_width(), 1); _footer_window->initialize(); _command_window = new command_window( _main_window, 0, _main_window->max_height() - 2, _main_window->max_width(), 1); _command_window->initialize(); _assembly_window = new assembly_window( _main_window, 0, 1, _main_window->max_width() - 23, _main_window->max_height() - 15); _assembly_window->initialize(); _registers_window = new registers_window( _main_window, _main_window->max_width() - 23, 1, 23, _main_window->max_height() - 15); _registers_window->initialize(); _stack_window = new stack_window( _main_window, _main_window->max_width() - 44, _main_window->max_height() - 14, 44, 12); _stack_window->initialize(); auto left_section = _main_window->max_width() - _stack_window->width(); _memory_window = new memory_window( _main_window, 0, _main_window->max_height() - 14, left_section / 2, 12); _memory_window->address(reinterpret_cast<uint64_t>(_session.terp().heap())); _memory_window->initialize(); _output_window = new output_window( _main_window, _memory_window->x() + _memory_window->width(), _memory_window->y(), _memory_window->width(), _memory_window->height()); _output_window->initialize(); _errors_window = new errors_window( _main_window, 2, 2, _main_window->max_width() - 2, _main_window->max_height() - 2); _errors_window->visible(false); _errors_window->initialize(); // XXX: since we only have the one listing source file for now // automatically select it. auto& listing = _session.assembler().listing(); auto file_names = listing.file_names(); if (!file_names.empty()) _assembly_window->source_file(listing.source_file(file_names.front())); refresh(); draw_all(); return true; } debugger_state_t environment::current_state() const { if (_state_stack.empty()) return debugger_state_t::stopped; return _state_stack.top(); } void environment::push_state(debugger_state_t state) { _state_stack.push(state); } void environment::remove_breakpoint(uint64_t address) { _breakpoints.erase(address); } breakpoint_t* environment::breakpoint(uint64_t address) { auto it = _breakpoints.find(address); if (it == _breakpoints.end()) return nullptr; return &it->second; } bool environment::execute_command(const std::string& input) { if (input.empty()) { cancel_command(); return true; } common::result result {}; push_state(debugger_state_t::command_execute); _header_window->mark_dirty(); _command_window->mark_dirty(); draw_all(); defer({ pop_state(); _command_window->reset(); _header_window->mark_dirty(); _command_window->mark_dirty(); draw_all(); }); std::string part {}; std::vector<std::string> parts {}; size_t index = 0; auto in_quotes = false; while (index < input.size()) { auto c = input[index]; if (isspace(c)) { if (!in_quotes) { parts.emplace_back(part); part.clear(); } else { part += " "; } } else if (isalnum(c) || c == '_' || c == '$' || c == '.' || c == ':' || c == ';' || c == '/' || c == '%' || c == '-' || c == ',' || c == '@') { part += c; } else if (c == '\"' || c == '\'') { if (in_quotes) { part += '\''; parts.emplace_back(part); part.clear(); in_quotes = false; } else { part += '\''; in_quotes = true; } } ++index; } if (!part.empty()) parts.emplace_back(part); command_data_t cmd_data {}; cmd_data.name = parts[0]; if (!cmd_data.parse(result)) return false; command_t cmd {}; cmd.command = cmd_data; index = 1; for (const auto& kvp : cmd.command.prototype.params) { if (kvp.second.required && index < parts.size()) { auto param = parts[index]; auto first_char = param[0]; auto upper_first_char = std::toupper(param[0]); if (first_char == '@') { number_data_t data {}; data.radix = 8; data.input = param; if (data.parse(data.value) != syntax::conversion_result_t::success) break; cmd.arguments.insert(std::make_pair(kvp.first, data)); } else if (first_char == '%') { number_data_t data {}; data.radix = 2; data.input = param; if (data.parse(data.value) != syntax::conversion_result_t::success) return false; cmd.arguments.insert(std::make_pair(kvp.first, data)); } else if (first_char == '$') { number_data_t data {}; data.radix = 16; data.input = param; if (data.parse(data.value) != syntax::conversion_result_t::success) return false; cmd.arguments.insert(std::make_pair(kvp.first, data)); } else if (isdigit(first_char)) { number_data_t data {}; data.radix = 10; data.input = param; if (data.parse(data.value) != syntax::conversion_result_t::success) return false; cmd.arguments.insert(std::make_pair(kvp.first, data)); } else if (first_char == '\'') { string_data_t data {}; data.input = param.substr(1, param.length() - 1); cmd.arguments.insert(std::make_pair(kvp.first, data)); } else if (first_char == '_') { symbol_data_t data {}; data.input = param; } else if (upper_first_char == 'I' || upper_first_char == 'F' || upper_first_char == 'S' || upper_first_char == 'P') { register_data_t data {}; data.input = param; common::result r; if (!data.parse(r)) { symbol_data_t symbol_data {}; symbol_data.input = param; cmd.arguments.insert(std::make_pair(kvp.first, symbol_data)); } else { cmd.arguments.insert(std::make_pair(kvp.first, data)); } } else { result.error( "X000", fmt::format( "unrecognized parameter '{}' value: {}", kvp.second.name, param)); break; } } else { result.error( "X000", fmt::format("missing required parameter: {}", kvp.second.name)); break; } ++index; } if (result.is_failed()) { return false; } auto handler_it = s_command_handlers.find(cmd.command.prototype.type); if (handler_it == s_command_handlers.end()) { result.error( "X000", fmt::format("no command handler: {}", cmd.command.name)); return false; } return handler_it->second(this, result, cmd); } uint64_t environment::get_address(const command_argument_t* arg) const { uint64_t address = 0; switch (arg->type()) { case command_parameter_type_t::symbol: { auto sym = arg->data<symbol_data_t>(); if (sym != nullptr) { auto& assembler = _session.assembler(); auto label = assembler.find_label(sym->input); if (label != nullptr) address = label->address(); } break; } case command_parameter_type_t::number: { auto number = arg->data<number_data_t>(); if (number != nullptr) address = number->value; break; } case command_parameter_type_t::register_t: { auto reg = arg->data<register_data_t>(); if (reg != nullptr) address = register_value(*reg); break; } default: { break; } } return address; } uint64_t environment::register_value(const register_data_t& reg) const { auto& terp = _session.terp(); auto register_file = terp.register_file(); uint64_t value = 0; switch (reg.value) { case vm::registers_t::pc: { value = register_file.r[vm::register_pc].qw + reg.offset; break; } case vm::registers_t::sp: { value = register_file.r[vm::register_sp].qw + reg.offset; break; } case vm::registers_t::fp: { value = register_file.r[vm::register_fp].qw + reg.offset; break; } case vm::registers_t::sr: { value = register_file.r[vm::register_sr].qw + reg.offset; break; } default: { if (reg.type == vm::register_type_t::integer) { value = register_file.r[vm::register_integer_start + reg.value].qw + reg.offset; } else { value = register_file.r[vm::register_float_start + reg.value].qw + reg.offset; } break; } } return value; } bool environment::on_help(common::result& r, const command_t& command) { return true; } bool environment::on_find(common::result& r, const command_t& command) { return true; } bool environment::on_goto_line(common::result& r, const command_t& command) { auto line_number_arg = command.arg("line_number"); if (line_number_arg != nullptr) { auto line_number = line_number_arg->data<number_data_t>(); _assembly_window->move_to_line(line_number->value); } return true; } bool environment::on_show_memory(common::result& r, const command_t& command) { auto address_arg = command.arg("address"); if (address_arg != nullptr) { auto address = get_address(address_arg); if (address != 0) { _memory_window->address(address); } } return true; } bool environment::on_read_memory(common::result& r, const command_t& command) { auto address_arg = command.arg("address"); if (address_arg != nullptr) { auto& terp = _session.terp(); auto address = get_address(address_arg); if (address != 0) { auto value = terp.read(command.command.size, address); fmt::print("\n*read memory\n*-----------\n"); fmt::print("*${:016X}: ", address); auto value_ptr = reinterpret_cast<uint8_t*>(&value); for (size_t i = 0; i < vm::op_size_in_bytes(command.command.size); i++) fmt::print("{:02X} ", *value_ptr++); fmt::print("\n"); } } return true; } bool environment::on_write_memory(common::result& r, const command_t& command) { return true; } };
34.780842
151
0.473919
56659cb88b0cfa964ba4b8fa8851357d424c3a07
4,689
cpp
C++
src/library/BlackBox_Ring.cpp
RoboticsBrno/BlackBox_library
2047f0102f1aacc780b8a7ba1d20da9dba3f63b4
[ "MIT" ]
1
2021-06-23T15:34:46.000Z
2021-06-23T15:34:46.000Z
src/library/BlackBox_Ring.cpp
RoboticsBrno/BlackBox_library
2047f0102f1aacc780b8a7ba1d20da9dba3f63b4
[ "MIT" ]
9
2020-03-09T19:50:34.000Z
2021-07-18T12:06:11.000Z
src/library/BlackBox_Ring.cpp
RoboticsBrno/BlackBox_library
2047f0102f1aacc780b8a7ba1d20da9dba3f63b4
[ "MIT" ]
1
2020-03-09T16:10:25.000Z
2020-03-09T16:10:25.000Z
#include "library/BlackBox_Ring.hpp" #include "library/BlackBox_pinout.hpp" #include <SmartLeds.h> #include <cmath> #include <cstdio> #include <cstdlib> #include <mutex> namespace BlackBox { int Index::trim(int index) { return (60 + (index % ledCount)) % ledCount; } Index& Index::trimThis() { m_value = trim(m_value); return *this; } Index::Index(int i_index) : m_value(trim(i_index)) { } Index::Index(Coords other) : m_value(trim(atan2(other.x, other.y) * 3.14 * 3)) { } int Index::value() const { return m_value; } Index& Index::operator+=(const Index& i_other) { m_value += i_other.m_value; return trimThis(); } Index& Index::operator-=(const Index& i_other) { m_value -= i_other.m_value; return trimThis(); } Index& Index::operator++() { m_value++; return trimThis(); } Index& Index::operator--() { m_value--; return trimThis(); } bool Index::operator<(const Index& i_other) const { return m_value < i_other.m_value; } bool Index::operator>(const Index& i_other) const { return m_value > i_other.m_value; } bool Index::operator<=(const Index& i_other) const { return m_value <= i_other.m_value; } bool Index::operator>=(const Index& i_other) const { return m_value >= i_other.m_value; } bool Index::operator==(const Index& i_other) const { return m_value == i_other.m_value; } bool Index::operator!=(const Index& i_other) const { return m_value != i_other.m_value; } Index::operator int() const { return m_value; } // uint32 Ring::blend(unsigned color1, unsigned color2, unsigned alpha) { // https://gist.github.com/XProger/96253e93baccfbf338de // unsigned rb = color1 & 0xff00ff; // unsigned g = color1 & 0x00ff00; // rb += ((color2 & 0xff00ff) - rb) * alpha >> 8; // g += ((color2 & 0x00ff00) - g) * alpha >> 8; // return (rb & 0xff00ff) | (g & 0xff00); // } Ring::Ring(int i_count) : m_leds(LED_WS2812, i_count, Pins::Leds::Data, channel, DoubleBuffer) , m_buffer(new Rgb[i_count]) , m_count(i_count) , m_darkModeValue(10) , m_isDarkModeEnabled(false) , m_beginning(0) { } void Ring::show() { std::scoped_lock l(m_mutex); Index j = m_beginning; for (int i = 0; i < m_count; i++) { #if BB_HW_VER == 0x0100 m_leds[j] = (*this)[m_count - i]; #elif BB_HW_VER == 0x0101 m_leds[j] = (*this)[i]; #else #error "Invalid BB_HW_VER" #endif if (m_isDarkModeEnabled) m_leds[j].stretchChannelsEvenly(m_darkModeValue); ++j; } m_leds.wait(); m_leds.show(); } void Ring::wait() { m_leds.wait(); } void Ring::drawArc(Rgb i_rgb, Index i_beginnig, Index i_ending, ArcType i_arcType) { std::scoped_lock l(m_mutex); if ((i_arcType == ArcType::ShorterDistance) || (i_arcType == ArcType::LongerDistance)) { if (i_arcType == ArcType::ShorterDistance) { i_arcType = (abs(i_beginnig - i_ending) <= (m_count / 2)) ? ArcType::Clockwise : ArcType::CounterClockwise; } else { i_arcType = (abs(i_beginnig - i_ending) > (m_count / 2)) ? ArcType::Clockwise : ArcType::CounterClockwise; } } if (i_arcType == ArcType::Clockwise) for (Index i = i_beginnig; true; ++i) { m_buffer[i] = i_rgb; std::printf("%i\n", int(i)); if (i == i_ending) break; } else for (Index i = i_ending; i != i_beginnig; ++i) { std::printf("%i\n", int(i)); m_buffer[i] = i_rgb; } } void Ring::drawCircle(Rgb i_rgb) { std::scoped_lock l(m_mutex); for (int i = 0; i < m_count; i++) m_buffer[i] = i_rgb; } void Ring::draw(std::unique_ptr<Rgb[]> i_buffer) { std::scoped_lock l(m_mutex); for (int i = 0; i < m_count; i++) { m_buffer[i] = i_buffer[i]; } } void Ring::clear() { drawCircle(Rgb(0, 0, 0)); } void Ring::enableDarkMode() { std::scoped_lock l(m_mutex); m_isDarkModeEnabled = true; } void Ring::disableDarkMode() { std::scoped_lock l(m_mutex); m_isDarkModeEnabled = false; } void Ring::setDarkModeValue(int i_value) { std::scoped_lock l(m_mutex); m_darkModeValue = i_value; } const Rgb& Ring::operator[](const Index& i_index) const { std::scoped_lock l(m_mutex); return m_buffer[i_index.value()]; } Rgb& Ring::operator[](const Index& i_index) { std::scoped_lock l(m_mutex); return m_buffer[i_index.value()]; } void Ring::rotate(Index i_beginning) { std::scoped_lock l(m_mutex); m_beginning = i_beginning; } } // namespace BlackBox
23.923469
129
0.605246
5667f34649cc5613d2e1363d1942879c29e8cc79
1,718
cc
C++
lib/utils.cc
pauldevine/fluxengine
a107d4f17f3ecf69cfcde916f4468b44712b1253
[ "MIT" ]
null
null
null
lib/utils.cc
pauldevine/fluxengine
a107d4f17f3ecf69cfcde916f4468b44712b1253
[ "MIT" ]
null
null
null
lib/utils.cc
pauldevine/fluxengine
a107d4f17f3ecf69cfcde916f4468b44712b1253
[ "MIT" ]
null
null
null
#include "globals.h" #include "utils.h" bool emergencyStop = false; static const char* WHITESPACE = " \t\n\r\f\v"; static const char* SEPARATORS = "/\\"; void ErrorException::print() const { std::cerr << message << '\n'; } bool beginsWith(const std::string& value, const std::string& ending) { if (ending.size() > value.size()) return false; return std::equal(ending.begin(), ending.end(), value.begin()); } // Case-insensitive for endings within ASCII. bool endsWith(const std::string& value, const std::string& ending) { if (ending.size() > value.size()) return false; std::string lowercase(ending.size(), 0); std::transform(value.rbegin(), value.rbegin() + ending.size(), lowercase.begin(), [](unsigned char c) { return std::tolower(c); }); return std::equal(ending.rbegin(), ending.rend(), value.rbegin()) || std::equal(ending.rbegin(), ending.rend(), lowercase.begin()); } std::string leftTrimWhitespace(std::string value) { value.erase(0, value.find_first_not_of(WHITESPACE)); return value; } std::string rightTrimWhitespace(std::string value) { value.erase(value.find_last_not_of(WHITESPACE) + 1); return value; } std::string trimWhitespace(const std::string& value) { return leftTrimWhitespace(rightTrimWhitespace(value)); } std::string getLeafname(const std::string& value) { constexpr char sep = '/'; size_t i = value.find_last_of(SEPARATORS); if (i != std::string::npos) { return value.substr(i + 1, value.length() - i); } return value; } void testForEmergencyStop() { if (emergencyStop) throw EmergencyStopException(); }
22.906667
73
0.638533
566d612e789c06c43ad236e9688c509257bc4523
7,764
hpp
C++
libraries/belle/Source/Core/Prim/Complex.hpp
jogawebb/Spaghettis
78f21ba3065ce316ef0cb84e94aecc9e8787343d
[ "Zlib", "BSD-2-Clause", "BSD-3-Clause" ]
47
2017-09-05T02:49:22.000Z
2022-01-20T08:11:47.000Z
libraries/belle/Source/Core/Prim/Complex.hpp
jogawebb/Spaghettis
78f21ba3065ce316ef0cb84e94aecc9e8787343d
[ "Zlib", "BSD-2-Clause", "BSD-3-Clause" ]
106
2018-05-16T14:58:52.000Z
2022-01-12T13:57:24.000Z
libraries/belle/Source/Core/Prim/Complex.hpp
jogawebb/Spaghettis
78f21ba3065ce316ef0cb84e94aecc9e8787343d
[ "Zlib", "BSD-2-Clause", "BSD-3-Clause" ]
11
2018-05-16T06:44:51.000Z
2021-11-10T07:04:46.000Z
/* Copyright (c) 2007-2013 William Andrew Burnson. Copyright (c) 2013-2020 Nicolas Danet. */ /* < http://opensource.org/licenses/BSD-2-Clause > */ // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- namespace prim { // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - template < class T > class Complex { // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: Complex (T x = T(), T y = T()) : x_ (x), y_ (y) { } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- #if PRIM_CPP11 public: Complex (const Complex < T > &) = default; Complex (Complex < T > &&) = default; Complex < T > & operator = (const Complex < T > &) = default; Complex < T > & operator = (Complex < T > &&) = default; #endif // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: T& getX() { return x_; } const T& getX() const { return x_; } T& getY() { return y_; } const T& getY() const { return y_; } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: const Complex < T > operator += (Complex < T > c) { x_ += c.x_; y_ += c.y_; return *this; } const Complex < T > operator -= (Complex < T > c) { x_ -= c.x_; y_ -= c.y_; return *this; } const Complex < T > operator *= (Complex < T > c) { T x = (x_ * c.x_ - y_ * c.y_); T y = (x_ * c.y_ + c.x_ * y_); x_ = x; y_ = y; return *this; } const Complex < T > operator /= (Complex < T > c) { double d = (c.x_ * c.x_) + (c.y_ * c.y_); T x = static_cast < T > ((x_ * c.x_ + y_ * c.y_) / d); T y = static_cast < T > ((c.x_ * y_ - x_ * c.y_) / d); x_ = x; y_ = y; return *this; } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: double angle() const { double t = atan2 (y_, x_); if (t < 0.0) { t += kTwoPi; } return t; } double magnitude() const { double x = static_cast < double > (x_); double y = static_cast < double > (y_); return sqrt (x * x + y * y); } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: void setAngle (double a) { setPolar (a, magnitude()); } void setMagnitude (double m) { setPolar (angle(), m); } void setPolar (double a, double m) { *this = Complex < T >::withPolar (a, m); } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: const Complex < T > operator -() { return Complex (-x_, -y_); } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: static Complex < T > withPolar (double a, double m) { return Complex < T > (T (std::cos (a) * m), T (std::sin (a) * m)); } private: T x_; T y_; private: PRIM_LEAK_DETECTOR (Complex) // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - friend bool operator != (Complex < T > a, Complex < T > b) { return !(a == b); } friend bool operator == (Complex < T > a, Complex < T > b) { return (a.x_ == b.x_) && (a.y_ == b.y_); } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - friend const Complex < T > operator + (Complex < T > a, Complex < T > b) { return a += b; } friend const Complex < T > operator - (Complex < T > a, Complex < T > b) { return a -= b; } friend const Complex < T > operator * (Complex < T > a, Complex < T > b) { return a *= b; } friend const Complex < T > operator / (Complex < T > a, Complex < T > b) { return a /= b; } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- /* < http://www.cs.princeton.edu/~rs/AlgsDS07/16Geometric.pdf > */ // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - friend int clockwiseOrder (Complex < T > a, Complex < T > b, Complex < T > c) { double t1 = (static_cast < double > (b.x_) - static_cast < double > (a.x_)); double t2 = (static_cast < double > (c.y_) - static_cast < double > (a.y_)); double t3 = (static_cast < double > (b.y_) - static_cast < double > (a.y_)); double t4 = (static_cast < double > (c.x_) - static_cast < double > (a.x_)); double d = (t1 * t2) - (t3 * t4); if (d < 0) { return 1; } /* Clockwise. */ else if (d > 0) { return -1; } /* Counterclockwise. */ else { return 0; /* Collinear. */ } } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- }; // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- } // namespace prim // ----------------------------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------------------------
30.687747
110
0.238408
566f3a6aa4a7d3ed0971e84c8c6282ffa26cafea
1,910
hpp
C++
framework/graphics/graphics/render_target/render_target.hpp
YiJiangFengYun/vulkan-graphics-examples
e7b788b8f47dd238b08840c019940c7c52335a54
[ "MIT" ]
1
2018-03-01T01:05:25.000Z
2018-03-01T01:05:25.000Z
framework/graphics/graphics/render_target/render_target.hpp
YiJiangFengYun/vulkan-graphics-examples
e7b788b8f47dd238b08840c019940c7c52335a54
[ "MIT" ]
null
null
null
framework/graphics/graphics/render_target/render_target.hpp
YiJiangFengYun/vulkan-graphics-examples
e7b788b8f47dd238b08840c019940c7c52335a54
[ "MIT" ]
null
null
null
#ifndef VG_RENDER_TARGET_HPP #define VG_RENDER_TARGET_HPP #include "graphics/global.hpp" namespace vg { class BaseRenderTarget { public: BaseRenderTarget(uint32_t framebufferWidth = 0u , uint32_t framebufferHeight = 0u ); uint32_t getFramebufferWidth() const; uint32_t getFramebufferHeight() const; const fd::Rect2D & getRenderArea() const; void setRenderArea(const fd::Rect2D & area); uint32_t getClearValueCount() const; const vk::ClearValue *getClearValues() const; void setClearValues(const vk::ClearValue *pClearValue, uint32_t clearValueCount); protected: uint32_t m_framebufferWidth; uint32_t m_framebufferHeight; fd::Rect2D m_renderArea; std::vector<vk::ClearValue> m_clearValues; }; class OnceRenderTarget : public BaseRenderTarget { public: OnceRenderTarget(uint32_t framebufferWidth = 0u , uint32_t framebufferHeight = 0u ); const vk::RenderPass * getRenderPass() const; const vk::Framebuffer * getFramebuffer() const; protected: vk::RenderPass *m_pRenderPass; vk::Framebuffer *m_pFramebuffer; }; class MultiRenderTarget : public BaseRenderTarget { public: MultiRenderTarget(uint32_t framebufferWidth = 0u , uint32_t framebufferHeight = 0u ); const vk::RenderPass * getFirstRenderPass() const; const vk::RenderPass * getSecondRenderPass() const; const vk::Framebuffer * getFirstFramebuffer() const; const vk::Framebuffer * getSecondFramebuffer() const; protected: vk::RenderPass *m_pFirstRenderPass; vk::RenderPass *m_pSecondRenderPass; vk::Framebuffer *m_pFirstFramebuffer; vk::Framebuffer *m_pSecondFramebuffer; }; } //vg #endif //VG_RENDER_TARGET_HPP
32.372881
89
0.66178