hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | 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 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
63a80bbe143fb119463e5d2338a7175850b44a13 | 75,656 | cpp | C++ | source/solution_zoo/xstream/methods/fasterrcnnmethod/src/faster_rcnn_imp.cpp | HorizonRobotics-Platform/AI-EXPRESS | 413206d88dae1fbd465ced4d60b2a1769d15c171 | [
"BSD-2-Clause"
] | 98 | 2020-09-11T13:52:44.000Z | 2022-03-23T11:52:02.000Z | source/solution_zoo/xstream/methods/fasterrcnnmethod/src/faster_rcnn_imp.cpp | HorizonRobotics-Platform/ai-express | 413206d88dae1fbd465ced4d60b2a1769d15c171 | [
"BSD-2-Clause"
] | 8 | 2020-10-19T14:23:30.000Z | 2022-03-16T01:00:07.000Z | source/solution_zoo/xstream/methods/fasterrcnnmethod/src/faster_rcnn_imp.cpp | HorizonRobotics-Platform/AI-EXPRESS | 413206d88dae1fbd465ced4d60b2a1769d15c171 | [
"BSD-2-Clause"
] | 28 | 2020-09-17T14:20:35.000Z | 2022-01-10T16:26:00.000Z | //
// Created by yaoyao.sun on 2019-04-23.
// Copyright (c) 2019 Horizon Robotics. All rights reserved.
//
#include <assert.h>
#include <stdint.h>
#include <algorithm>
#include <fstream>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include <unordered_map>
#include "bpu_predict/bpu_parse_utils.h"
#include "bpu_predict/bpu_parse_utils_extension.h"
#include "bpu_predict/bpu_predict.h"
#include "hobotlog/hobotlog.hpp"
#include "hobotxsdk/xstream_data.h"
#include "hobotxstream/profiler.h"
#include "horizon/vision_type/vision_type.hpp"
#include "json/json.h"
#include "opencv2/imgproc.hpp"
#include "FasterRCNNMethod/FasterRCNNMethod.h"
#include "FasterRCNNMethod/config.h"
#include "FasterRCNNMethod/faster_rcnn_imp.h"
#include "FasterRCNNMethod/result.h"
#include "FasterRCNNMethod/util.h"
#include "FasterRCNNMethod/yuv_utils.h"
#include "common/common.h"
#ifdef X3
#include "./bpu_predict_x3.h"
#endif
#define DMA_ALIGN_SIZE 64
#define BPU_CEIL_ALIGN(len) \
((((len) + DMA_ALIGN_SIZE - 1) / DMA_ALIGN_SIZE) * DMA_ALIGN_SIZE)
using hobot::vision::Attribute;
using hobot::vision::BBox;
using hobot::vision::CVImageFrame;
using hobot::vision::Landmarks;
using hobot::vision::Point;
using hobot::vision::Pose3D;
using hobot::vision::PymImageFrame;
using hobot::vision::Segmentation;
using xstream::BaseDataPtr;
using xstream::BaseDataVector;
using xstream::FasterRCNNParam;
using xstream::InputParamPtr;
using xstream::XStreamData;
using ImageFramePtr = std::shared_ptr<hobot::vision::ImageFrame>;
namespace faster_rcnn_method {
// used to decide output info for each layer of model. first we should use hbcc
// interface to get model's info,
// and get each layer's output info, then config it in config file.
static std::map<std::string, FasterRCNNBranchOutType> str2faster_rcnn_out_type =
{{"bbox", FasterRCNNBranchOutType::BBOX},
{"kps", FasterRCNNBranchOutType::KPS},
{"mask", FasterRCNNBranchOutType::MASK},
{"reid", FasterRCNNBranchOutType::REID},
{"lmks2_label", FasterRCNNBranchOutType::LMKS2_LABEL},
{"lmks2_offset", FasterRCNNBranchOutType::LMKS2_OFFSET},
{"lmks1", FasterRCNNBranchOutType::LMKS1},
{"3d_pose", FasterRCNNBranchOutType::POSE_3D},
{"plate_color", FasterRCNNBranchOutType::PLATE_COLOR},
{"plate_row", FasterRCNNBranchOutType::PLATE_ROW},
{"kps_label", FasterRCNNBranchOutType::KPS_LABEL},
{"kps_offset", FasterRCNNBranchOutType::KPS_OFFSET},
{"lmks", FasterRCNNBranchOutType::LMKS}};
void FasterRCNNImp::ParseConfig(const std::string &config_file) {
FR_Config cfg_jv;
std::ifstream infile(config_file.c_str());
infile >> cfg_jv;
config_.reset(new Config(cfg_jv));
core_id_ = config_->GetIntValue("core_id", 2);
auto net_info = config_->GetSubConfig("net_info");
model_name_ = net_info->GetSTDStringValue("model_name");
model_version_ = net_info->GetSTDStringValue("model_version", "1.0.0");
std::vector<std::shared_ptr<Config>> model_out_sequence =
net_info->GetSubConfigArray("model_out_sequence");
LOGD << "rcnn branch out type:";
for (size_t i = 0; i < model_out_sequence.size(); ++i) {
std::string type_str = model_out_sequence[i]->GetSTDStringValue("type");
HOBOT_CHECK(!type_str.empty());
LOGD << type_str;
if (str2faster_rcnn_out_type.find(type_str) ==
str2faster_rcnn_out_type.end()) {
out_level2rcnn_branch_info_[i].type = FasterRCNNBranchOutType::INVALID;
} else {
out_level2rcnn_branch_info_[i].type = str2faster_rcnn_out_type[type_str];
out_level2rcnn_branch_info_[i].name =
model_out_sequence[i]->GetSTDStringValue("name");
out_level2rcnn_branch_info_[i].box_name =
model_out_sequence[i]->GetSTDStringValue("box_name");
out_level2rcnn_branch_info_[i].labels =
model_out_sequence[i]->GetLabelsMap("labels");
}
}
model_input_width_ = net_info->GetIntValue("model_input_width", 960);
model_input_height_ = net_info->GetIntValue("model_input_height", 540);
pyramid_layer_ = net_info->GetIntValue("pyramid_layer", 4);
resize_input_width_ = model_input_width_;
resize_input_height_ = model_input_height_;
kps_pos_distance_ = net_info->GetFloatValue("kps_pos_distance", 0.1);
kps_feat_width_ = net_info->GetIntValue("kps_feat_width", 16);
kps_feat_height_ = net_info->GetIntValue("kps_feat_height", 16);
kps_points_number_ = net_info->GetIntValue("kps_points_number", 17);
kps_feat_stride_ = net_info->GetIntValue("kps_feat_stride", 16);
kps_anchor_param_ = net_info->GetFloatValue("kps_anchor_param", 0.0);
lmk_feat_height_ = net_info->GetIntValue("lmk_feat_height", 8);
lmk_feat_width_ = net_info->GetIntValue("lmk_feat_width", 8);
lmk_feat_stride_ = net_info->GetIntValue("lmk_feat_stride", 16);
lmk_points_number_ = net_info->GetIntValue("lmk_points_number", 5);
lmk_pos_distance_ = net_info->GetFloatValue("lmk_pos_distance", 12);
lmk_anchor_param_ = net_info->GetFloatValue("lmk_anchor_param", 0.0);
face_pose_number_ = net_info->GetIntValue("3d_pose_number", 3);
plate_color_num_ = net_info->GetIntValue("plate_color_num", 6);
plate_row_num_ = net_info->GetIntValue("plate_row_num", 2);
face_pv_thr_ = net_info->GetFloatValue("face_pv_thr", 0.0);
method_outs_ = config_->GetSTDStringArray("method_outs");
LOGD << "method out type:";
for (const auto &method_out : method_outs_) {
LOGD << method_out;
}
is_crop_ = config_->GetBoolValue("is_crop", false);
std::string parent_path = GetParentPath(config_file);
bpu_config_path_ =
parent_path + config_->GetSTDStringValue("bpu_config_path");
model_file_path_ =
parent_path + config_->GetSTDStringValue("model_file_path");
LOGD << "config file parent path: " << parent_path
<< " bpu_config_path: " << bpu_config_path_
<< " model_file_path: " << model_file_path_;
}
void FasterRCNNImp::GetModelInfo(const std::string &model_name) {
uint32_t output_layer_num = bpu_model_->output_num;
for (size_t i = 0; i < output_layer_num; ++i) {
const auto &branch_info = out_level2rcnn_branch_info_[i];
auto out_type = branch_info.type;
// get shifts
const uint8_t *shift_value = bpu_model_->outputs[i].shifts;
LOGD << "out_type:" << static_cast<int>(out_type)
<< " shift_len:" << bpu_model_->outputs[i].shift_len;
// dim of per shape = 4
int aligned_shape_dim = bpu_model_->outputs[i].aligned_shape.ndim;
HOBOT_CHECK(aligned_shape_dim == 4)
<< "aligned_shape_dim = " << aligned_shape_dim;
int *aligned_dim = new int[aligned_shape_dim];
for (int dim = 0; dim < aligned_shape_dim; dim++) {
aligned_dim[dim] = bpu_model_->outputs[i].aligned_shape.d[dim];
}
switch (out_type) {
case FasterRCNNBranchOutType::INVALID:
break;
case FasterRCNNBranchOutType::KPS:
// TODO(yaoyao.sun) pack into a function
for (int idx = 0; idx < bpu_model_->outputs[i].shift_len; idx++) {
kps_shifts_.push_back(shift_value[idx]);
}
aligned_kps_dim = aligned_dim;
break;
case FasterRCNNBranchOutType::KPS_LABEL:
// TODO(yaoyao.sun) pack into a function
kps_label_shift_ = shift_value[0];
aligned_kps_label_dim = aligned_dim;
break;
case FasterRCNNBranchOutType::KPS_OFFSET:
// TODO(yaoyao.sun) pack into a function
kps_offset_shift_ = shift_value[0];
aligned_kps_offset_dim = aligned_dim;
break;
case FasterRCNNBranchOutType::MASK:
mask_shift_ = shift_value[0];
aligned_mask_dim = aligned_dim;
break;
case FasterRCNNBranchOutType::REID:
reid_shift_ = shift_value[0];
aligned_reid_dim = aligned_dim;
break;
case FasterRCNNBranchOutType::LMKS:
lmks_shift_ = shift_value[0];
aligned_lmks_dim = aligned_dim;
break;
case FasterRCNNBranchOutType::LMKS2_LABEL:
lmks2_label_shift_ = shift_value[0];
aligned_lmks2_label_dim = aligned_dim;
break;
case FasterRCNNBranchOutType::LMKS2_OFFSET:
lmks2_offset_shift_ = shift_value[0];
aligned_lmks2_offset_dim = aligned_dim;
break;
case FasterRCNNBranchOutType::LMKS1:
lmks1_shift_ = shift_value[0];
aligned_lmks1_dim = aligned_dim;
break;
case FasterRCNNBranchOutType::POSE_3D:
face_pose_shift_ = shift_value[0];
aligned_face_pose_dim = aligned_dim;
break;
case FasterRCNNBranchOutType::PLATE_COLOR:
plate_color_shift_ = shift_value[0];
aligned_plate_color_dim = aligned_dim;
HOBOT_CHECK(plate_color_num_ <= aligned_plate_color_dim[3]);
break;
case FasterRCNNBranchOutType::PLATE_ROW:
plate_row_shift_ = shift_value[0];
aligned_plate_row_dim = aligned_dim;
HOBOT_CHECK(plate_row_num_ <= aligned_plate_row_dim[3]);
break;
default:
break;
}
}
}
int FasterRCNNImp::Init(const std::string &config_file) {
faster_rcnn_param_ = nullptr;
// parse config file.
ParseConfig(config_file);
int ret = 0;
// load model
{
std::ifstream ifs(model_file_path_.c_str(),
std::ios::in | std::ios::binary);
if (!ifs) {
HOBOT_CHECK(0) << "Open model file: " << model_file_path_ << " failed";
}
ifs.seekg(0, std::ios::end);
int model_length = ifs.tellg();
ifs.seekg(0, std::ios::beg);
char *model_bin = new char[sizeof(char) * model_length];
ifs.read(model_bin, model_length);
ifs.close();
bpu_model_ = new BPU_MODEL_S();
ret = HB_BPU_loadModel(model_bin, model_length, bpu_model_);
HOBOT_CHECK(ret == 0) << "load model failed" << HB_BPU_getErrorName(ret);
delete[] model_bin;
}
LOGD << "BPU_getModelOutputInfo success.";
GetModelInfo(model_name_);
return 0;
}
void FasterRCNNImp::RunSingleFrameWithinCrop(
const std::vector<BaseDataPtr> &frame_input,
std::vector<BaseDataPtr> &frame_output) {
HOBOT_CHECK(frame_input.size() == 2)
<< "please insure that frame_input[0] is the image frame, "
<< "frame_input[1] is the vector of body boxes";
RUN_PROCESS_TIME_PROFILER("FasterRCNN RunSingleFrameWithinCrop");
RUN_FPS_PROFILER("FasterRCNN RunSingleFrameWithinCrop");
const auto frame_img_ = frame_input[0];
for (size_t out_index = 0; out_index < method_outs_.size(); ++out_index) {
frame_output.push_back(std::make_shared<xstream::BaseDataVector>());
}
auto xstream_img =
std::static_pointer_cast<XStreamData<ImageFramePtr>>(frame_img_);
auto xstream_rois = std::static_pointer_cast<BaseDataVector>(frame_input[1]);
size_t rois_num = xstream_rois->datas_.size();
std::string img_type = xstream_img->value->type;
LOGD << "image type: " << img_type << std::endl;
for (size_t roi_idx = 0; roi_idx < rois_num; roi_idx++) {
HobotXStreamImageToolsResizeInfo resize_info;
int src_img_height = 0, src_img_width = 0;
int padding_right = 0, padding_bottom = 0;
float scale = 0;
// 1. prepare data for croping
std::shared_ptr<XStreamData<hobot::vision::BBox>> p_roi;
p_roi = std::static_pointer_cast<XStreamData<hobot::vision::BBox>>(
xstream_rois->datas_[roi_idx]);
hobot::vision::BBox *norm_box = &(p_roi->value);
if (p_roi->state_ != xstream::DataState::VALID) {
LOGI << "BBox is not valid";
continue;
}
if (img_type == kPyramidImage) {
auto pyramid_image =
std::static_pointer_cast<PymImageFrame>(xstream_img->value);
uint8_t *nv12_data;
// 2. crop and resize Roi
CropPadAndResizeRoi(norm_box, pyramid_image,
&nv12_data, &resize_info, &scale);
padding_right =
resize_info.padding_right_ / resize_info.width_ratio_;
padding_right &= ~1;
padding_bottom =
resize_info.padding_bottom_ / resize_info.height_ratio_;
padding_bottom &= ~1;
src_img_height = resize_info.src_height_ + padding_bottom;
src_img_width = resize_info.src_width_ + padding_right;
int img_len = src_img_width * src_img_height * 3 / 2;
RunModel(nv12_data, img_len, src_img_width,
src_img_height, BPU_TYPE_IMG_NV12_SEPARATE);
HobotXStreamFreeImage(nv12_data);
} else if (img_type == kCVImageFrame) {
// TODO(zhy)
} else {
HOBOT_CHECK(0) << "Do not support such img_type: " << img_type;
}
{
RUN_PROCESS_TIME_PROFILER("FasterRCNN SinglePerson PostProcess");
RUN_FPS_PROFILER("FasterRCNN SinglePerson PostProcess");
// Post process
FlushOutputTensor();
GetFrameOutput(src_img_width * scale, src_img_height * scale,
frame_output, norm_box);
}
}
}
void FasterRCNNImp::RunSingleFrame(const std::vector<BaseDataPtr> &frame_input,
std::vector<BaseDataPtr> &frame_output) {
if (is_crop_) {
RunSingleFrameWithinCrop(frame_input, frame_output);
} else {
// only one input slot -> PyramidImage or CVImage
HOBOT_CHECK(frame_input.size() == 1);
const auto frame_img_ = frame_input[0];
for (size_t out_index = 0; out_index < method_outs_.size(); ++out_index) {
frame_output.push_back(std::make_shared<xstream::BaseDataVector>());
}
auto xstream_img =
std::static_pointer_cast<XStreamData<ImageFramePtr>>(frame_img_);
std::string img_type = xstream_img->value->type;
LOGD << "image type: " << img_type << std::endl;
int ret = 0;
int src_img_width = 0;
int src_img_height = 0;
int target_pym_layer_width = 0;
int target_pym_layer_height = 0;
{
RUN_PROCESS_TIME_PROFILER("FasterRCNN RunModelFromPyramid");
RUN_FPS_PROFILER("FasterRCNN RunModelFromPyramid");
if (img_type == kPyramidImage) {
auto pyramid_image =
std::static_pointer_cast<PymImageFrame>(xstream_img->value);
#ifdef X2
src_img_height = pyramid_image->img.src_img.height;
src_img_width = pyramid_image->img.src_img.width;
target_pym_layer_height =
pyramid_image->img.down_scale[pyramid_layer_].height;
target_pym_layer_width =
pyramid_image->img.down_scale[pyramid_layer_].width;
#endif
#ifdef X3
src_img_height = pyramid_image->down_scale[0].height;
src_img_width = pyramid_image->down_scale[0].width;
target_pym_layer_height =
pyramid_image->down_scale[pyramid_layer_].height;
target_pym_layer_width =
pyramid_image->down_scale[pyramid_layer_].width;
#endif
resize_input_width_ = target_pym_layer_width;
resize_input_height_ = target_pym_layer_height;
LOGD << "img_height: " << pyramid_image->Height()
<< ", img_width: " << pyramid_image->Width()
<< ", img_y length: " << pyramid_image->DataSize()
<< ", img_uv length: " << pyramid_image->DataUVSize();
if (model_input_width_ != target_pym_layer_width ||
model_input_height_ != target_pym_layer_height) {
// get pym level 4 (960*540), then pad to 960*544
{
RUN_PROCESS_TIME_PROFILER("FasterRCNN PaddingImage");
uint8_t *pOutputImg = nullptr;
int output_img_size = 0;
int output_img_width = 0;
int output_img_height = 0;
int first_stride = 0;
int second_stride = 0;
#ifdef X2
auto input_img = pyramid_image->img.down_scale[pyramid_layer_];
int y_size = input_img.height * input_img.step;
int uv_size = y_size >> 1;
const uint8_t *input_nv12_data[3] =
{reinterpret_cast<uint8_t *>(input_img.y_vaddr),
reinterpret_cast<uint8_t *>(input_img.c_vaddr), nullptr};
const int input_nv12_size[3] = {y_size, uv_size, 0};
ret = HobotXStreamCropYuvImageWithPaddingBlack(
input_nv12_data, input_nv12_size,
input_img.width, input_img.height,
input_img.step, input_img.step, IMAGE_TOOLS_RAW_YUV_NV12,
0, 0, model_input_width_ - 1, model_input_height_ - 1,
&pOutputImg, &output_img_size,
&output_img_width, &output_img_height,
&first_stride, &second_stride);
#endif
#ifdef X3
auto input_img = pyramid_image->down_scale[pyramid_layer_];
int y_size = input_img.height * input_img.stride;
int uv_size = y_size >> 1;
const uint8_t *input_nv12_data[3] =
{reinterpret_cast<uint8_t *>(input_img.y_vaddr),
reinterpret_cast<uint8_t *>(input_img.c_vaddr), nullptr};
const int input_nv12_size[3] = {y_size, uv_size, 0};
ret = HobotXStreamCropYuvImageWithPaddingBlack(
input_nv12_data, input_nv12_size, input_img.width, input_img.height,
input_img.stride, input_img.stride, IMAGE_TOOLS_RAW_YUV_NV12,
0, 0, model_input_width_ - 1, model_input_height_ - 1,
&pOutputImg, &output_img_size,
&output_img_width, &output_img_height,
&first_stride, &second_stride);
#endif
if (ret < 0) {
LOGE << "fail to crop image";
free(pOutputImg);
return;
}
HOBOT_CHECK(output_img_width == model_input_width_)
<< "cropped image width "<< output_img_width
<< " not equals to model input width " << model_input_width_;
HOBOT_CHECK(output_img_height == model_input_height_)
<< "cropped image height " << output_img_height
<< " not equals to model input height " << model_input_height_;
int img_len = model_input_width_ * model_input_height_ * 3 / 2;
LOGD << "Begin call RunModel";
ret = RunModel(pOutputImg, img_len, BPU_TYPE_IMG_NV12_SEPARATE);
if (ret != 0) {
LOGE << "Run model failed: " << HB_BPU_getErrorName(ret);
HobotXStreamFreeImage(pOutputImg);
return;
}
HobotXStreamFreeImage(pOutputImg);
}
} else {
LOGD << "Begin call RunModel";
ret = RunModelFromPym(pyramid_image.get(), pyramid_layer_,
BPU_TYPE_IMG_NV12_SEPARATE);
if (ret != 0) {
LOGE << "Run model failed: " << HB_BPU_getErrorName(ret);
// ReleaseOutputTensor();
return;
}
}
} else if (img_type == kCVImageFrame) {
auto cv_image =
std::static_pointer_cast<CVImageFrame>(xstream_img->value);
HOBOT_CHECK(cv_image->pixel_format ==
HorizonVisionPixelFormat::kHorizonVisionPixelFormatRawBGR);
src_img_height = cv_image->Height();
src_img_width = cv_image->Width();
LOGD << "image height: " << src_img_height
<< "width: " << src_img_width;
auto img_mat = cv_image->img;
cv::Mat resized_mat = img_mat;
if (src_img_height != model_input_height_ &&
src_img_width != model_input_width_) {
LOGD << "need resize.";
cv::resize(img_mat, resized_mat,
cv::Size(model_input_width_, model_input_height_));
}
resize_input_width_ = model_input_width_;
resize_input_height_ = model_input_height_;
cv::Mat img_nv12;
uint8_t *bgr_data = resized_mat.ptr<uint8_t>();
bgr_to_nv12(bgr_data, model_input_height_, model_input_width_,
img_nv12);
uint8_t *nv12_data = img_nv12.ptr<uint8_t>();
int img_len = model_input_width_ * model_input_height_ * 3 / 2;
LOGD << "nv12 img_len: " << img_len;
LOGD << "Begin call RunModel";
ret = RunModel(nv12_data, img_len, BPU_TYPE_IMG_NV12_SEPARATE);
if (ret != 0) {
LOGE << "Run model failed: " << HB_BPU_getErrorName(ret);
// ReleaseOutputTensor();
return;
}
} else {
HOBOT_CHECK(0) << "Not support this input type: " << img_type;
}
}
RUN_PROCESS_TIME_PROFILER("FasterRCNN PostProcess");
RUN_FPS_PROFILER("FasterRCNN PostProcess");
// Post process
FlushOutputTensor();
GetFrameOutput(src_img_width, src_img_height, frame_output);
// release output tensor
// ReleaseOutputTensor();
}
}
void FasterRCNNImp::GetFrameOutput(int src_img_width, int src_img_height,
std::vector<BaseDataPtr> &frame_output,
BBox *bbox) {
FasterRCNNOutMsg det_result;
PostProcess(det_result);
CoordinateTransform(det_result, src_img_width, src_img_height,
resize_input_width_, resize_input_height_,
bbox);
for (auto &boxes : det_result.boxes) {
LOGD << boxes.first << ", num: " << boxes.second.size();
for (auto &box : boxes.second) {
LOGD << box;
}
}
// TODO(yaoyao.sun) Packaged into a function, GetResultMsg()
// convert FasterRCNNOutMsg to xstream data structure
std::map<std::string, std::shared_ptr<BaseDataVector>> xstream_det_result;
// get landmark by landmark2 and landmark1.
if (det_result.landmarks.find("landmark2") != det_result.landmarks.end() &&
det_result.landmarks.find("landmark1") != det_result.landmarks.end()) {
std::vector<Landmarks> vec_landmarks;
auto &landmarks2 = det_result.landmarks["landmark2"];
auto &landmarks1 = det_result.landmarks["landmark1"];
HOBOT_CHECK(landmarks2.size() == landmarks1.size())
<< "landmarks2's size not equal to landmarks1's size.";
for (size_t lmk_index = 0; lmk_index < landmarks2.size(); ++lmk_index) {
Landmarks landmarks;
auto &landmark2 = landmarks2[lmk_index];
auto &landmark1 = landmarks1[lmk_index];
HOBOT_CHECK(landmark2.values.size() == landmark1.values.size())
<< "landmark2's size not equal to landmark1's size.";
for (size_t point_index = 0; point_index < landmark2.values.size();
++point_index) {
auto &landmark2_point = landmark2.values[point_index];
auto &landmark1_point = landmark1.values[point_index];
if (landmark2_point.score > 0.5) {
landmarks.values.push_back(std::move(landmark2_point));
} else {
landmarks.values.push_back(std::move(landmark1_point));
}
}
vec_landmarks.push_back(landmarks);
}
det_result.landmarks["landmark"] = vec_landmarks;
det_result.landmarks.erase("landmark2");
det_result.landmarks.erase("landmark1");
}
std::set<int> invalid_idx;
// box
for (const auto &boxes : det_result.boxes) {
xstream_det_result[boxes.first] =
std::make_shared<xstream::BaseDataVector>();
xstream_det_result[boxes.first]->name_ = "rcnn_" + boxes.first;
for (uint i = 0; i < boxes.second.size(); ++i) {
const auto &box = boxes.second[i];
if (boxes.first == "face_box") {
if (box.score < face_pv_thr_) {
invalid_idx.emplace(i);
continue;
}
}
auto xstream_box = std::make_shared<XStreamData<BBox>>();
xstream_box->value = std::move(box);
xstream_det_result[boxes.first]->datas_.push_back(xstream_box);
}
}
// landmark
for (const auto &landmarks_vec : det_result.landmarks) {
xstream_det_result[landmarks_vec.first] =
std::make_shared<xstream::BaseDataVector>();
xstream_det_result[landmarks_vec.first]->name_ =
"rcnn_" + landmarks_vec.first;
for (uint i = 0; i < landmarks_vec.second.size(); ++i) {
if (invalid_idx.find(i) != invalid_idx.end()) {
continue;
}
const auto &landmarks = landmarks_vec.second[i];
LOGD << "lmk point: [";
for (const auto &point : landmarks.values) {
LOGD << point.x << "," << point.y << "," << point.score;
}
LOGD << "]";
auto xstream_landmark = std::make_shared<XStreamData<Landmarks>>();
xstream_landmark->value = std::move(landmarks);
xstream_det_result[landmarks_vec.first]->datas_.push_back(
xstream_landmark);
}
}
// feature
for (const auto &feature_vec : det_result.features) {
xstream_det_result[feature_vec.first] =
std::make_shared<xstream::BaseDataVector>();
xstream_det_result[feature_vec.first]->name_ = "rcnn_" + feature_vec.first;
for (auto &feature : feature_vec.second) {
auto xstream_feature = std::make_shared<XStreamData<Feature>>();
xstream_feature->value = std::move(feature);
xstream_det_result[feature_vec.first]->datas_.push_back(xstream_feature);
}
}
// segmentations
for (const auto &segmentation_vec : det_result.segmentations) {
xstream_det_result[segmentation_vec.first] =
std::make_shared<xstream::BaseDataVector>();
xstream_det_result[segmentation_vec.first]->name_ =
"rcnn_" + segmentation_vec.first;
for (auto &segmentation : segmentation_vec.second) {
auto xstream_segmentation = std::make_shared<XStreamData<Segmentation>>();
xstream_segmentation->value = std::move(segmentation);
xstream_det_result[segmentation_vec.first]->datas_.push_back(
xstream_segmentation);
}
}
// poses
for (const auto &pose_vec : det_result.poses) {
xstream_det_result[pose_vec.first] =
std::make_shared<xstream::BaseDataVector>();
xstream_det_result[pose_vec.first]->name_ = "rcnn_" + pose_vec.first;
for (uint i = 0; i < pose_vec.second.size(); ++i) {
if (invalid_idx.find(i) != invalid_idx.end()) {
continue;
}
const auto &pose = pose_vec.second[i];
auto xstream_pose = std::make_shared<XStreamData<Pose3D>>();
xstream_pose->value = std::move(pose);
xstream_det_result[pose_vec.first]->datas_.push_back(xstream_pose);
}
}
// attributes
for (const auto &attribute_vec : det_result.attributes) {
xstream_det_result[attribute_vec.first] =
std::make_shared<xstream::BaseDataVector>();
xstream_det_result[attribute_vec.first]->name_ =
"rcnn_" + attribute_vec.first;
for (auto &attribute : attribute_vec.second) {
auto xstream_attribute = std::make_shared<XStreamData<Attribute<int>>>();
xstream_attribute->value = std::move(attribute);
xstream_det_result[attribute_vec.first]->datas_.push_back(
xstream_attribute);
}
}
// for (size_t out_index = 0; out_index < method_outs_.size(); ++out_index) {
// if (xstream_det_result[method_outs_[out_index]]) {
// frame_output[out_index] = xstream_det_result[method_outs_[out_index]];
// }
// }
for (size_t out_index = 0; out_index < method_outs_.size(); ++out_index) {
if (xstream_det_result[method_outs_[out_index]]) {
auto frame_out_slot = std::static_pointer_cast<
xstream::BaseDataVector>(frame_output[out_index]);
auto det_result_slot = xstream_det_result[method_outs_[out_index]];
frame_out_slot->datas_.insert(frame_out_slot->datas_.end(),
det_result_slot->datas_.begin(),
det_result_slot->datas_.end());
}
}
}
void FasterRCNNImp::PostProcess(FasterRCNNOutMsg &det_result) {
void* lmk2_label_out_put = nullptr;
void* lmk2_offset_out_put = nullptr;
void* kps_label_out_put = nullptr;
void* kps_offset_out_put = nullptr;
for (int out_level = 0; out_level < bpu_model_->output_num; ++out_level) {
const auto &branch_info = out_level2rcnn_branch_info_[out_level];
auto out_type = branch_info.type;
switch (out_type) {
case FasterRCNNBranchOutType::INVALID:
break;
case FasterRCNNBranchOutType::BBOX:
GetRppRects(det_result.boxes, out_level,
branch_info.name, branch_info.labels);
break;
case FasterRCNNBranchOutType::LMKS2_LABEL:
lmk2_label_out_put = output_tensors_[out_level].data.virAddr;
break;
case FasterRCNNBranchOutType::LMKS2_OFFSET:
lmk2_offset_out_put = output_tensors_[out_level].data.virAddr;
break;
case FasterRCNNBranchOutType::KPS_LABEL:
kps_label_out_put = output_tensors_[out_level].data.virAddr;
break;
case FasterRCNNBranchOutType::KPS_OFFSET:
kps_offset_out_put = output_tensors_[out_level].data.virAddr;
break;
default:
break;
}
}
for (int out_level = 0; out_level < bpu_model_->output_num; ++out_level) {
const auto &branch_info = out_level2rcnn_branch_info_[out_level];
auto out_type = branch_info.type;
switch (out_type) {
case FasterRCNNBranchOutType::INVALID:
break;
case FasterRCNNBranchOutType::KPS:
LOGD << "begin GetKps";
GetKps(det_result.landmarks[branch_info.name],
output_tensors_[out_level].data.virAddr,
det_result.boxes[branch_info.box_name]);
break;
case FasterRCNNBranchOutType::KPS_LABEL:
LOGD << "begin GetKps2";
GetKps2(det_result.landmarks["kps"], kps_label_out_put,
kps_offset_out_put, det_result.boxes[branch_info.box_name]);
break;
case FasterRCNNBranchOutType::MASK:
LOGD << "begin GetMask";
GetMask(det_result.segmentations[branch_info.name],
output_tensors_[out_level].data.virAddr,
det_result.boxes[branch_info.box_name]);
break;
case FasterRCNNBranchOutType::REID:
LOGD << "begin GetReid";
GetReid(det_result.features[branch_info.name],
output_tensors_[out_level].data.virAddr,
det_result.boxes[branch_info.box_name]);
break;
case FasterRCNNBranchOutType::LMKS:
LOGD << "begin GetLMKS";
GetLMKS(det_result.landmarks["landmark"],
output_tensors_[out_level].data.virAddr,
det_result.boxes[branch_info.box_name]);
break;
case FasterRCNNBranchOutType::LMKS2_LABEL:
LOGD << "begin GetLMKS2";
GetLMKS2(det_result.landmarks["landmark2"], lmk2_label_out_put,
lmk2_offset_out_put, det_result.boxes[branch_info.box_name]);
break;
case FasterRCNNBranchOutType::LMKS1:
LOGD << "begin GetLMKS1";
GetLMKS1(det_result.landmarks["landmark1"],
output_tensors_[out_level].data.virAddr,
det_result.boxes[branch_info.box_name]);
break;
case FasterRCNNBranchOutType::POSE_3D:
LOGD << "begin GetPose";
GetPose(det_result.poses[branch_info.name],
output_tensors_[out_level].data.virAddr,
det_result.boxes[branch_info.box_name]);
break;
case FasterRCNNBranchOutType::PLATE_COLOR:
LOGD << "begin GetPlateColor";
GetPlateColor(&(det_result.attributes[branch_info.name]),
output_tensors_[out_level].data.virAddr,
det_result.boxes[branch_info.box_name]);
break;
case FasterRCNNBranchOutType::PLATE_ROW:
LOGD << "begin GetPlateRow";
GetPlateRow(&(det_result.attributes[branch_info.name]),
output_tensors_[out_level].data.virAddr,
det_result.boxes[branch_info.box_name]);
break;
default:
break;
}
}
}
void FasterRCNNImp::GetRppRects(
std::map<std::string, std::vector<BBox>> &boxes,
int index, const std::string &name,
const std::unordered_map<int, std::string> &labels) {
BPU_RPP_BBOX rpp_bbox;
int ret = HB_BPU_parseRPPResult(bpu_model_,
output_tensors_.data(),
index,
&rpp_bbox);
if (ret != 0) {
LOGE << "here parse model output failed.";
return;
}
int nBox = rpp_bbox.bbox_num;
HOBOT_CHECK(rpp_bbox.result_type == BPU_RPP_BBOX::bbox_type_f32);
auto box_ptr = rpp_bbox.bbox_ptr_f32;
LOGD << "rpp box num: " << nBox;
for (int i = 0; i < nBox; ++i) {
hobot::vision::BBox box;
box.x1 = box_ptr[i].left;
box.y1 = box_ptr[i].top;
box.x2 = box_ptr[i].right;
box.y2 = box_ptr[i].bottom;
box.score = box_ptr[i].score;
int type = box_ptr[i].class_label;
if (labels.find(type) != labels.end()) {
box.category_name = labels.at(type);
} else {
box.category_name = name;
}
boxes[box.category_name].push_back(std::move(box));
}
}
void FasterRCNNImp::GetKps(std::vector<Landmarks> &kpss,
void* output,
const std::vector<BBox> &body_boxes) {
int32_t *kps_feature = reinterpret_cast<int32_t *>(output);
float pos_distance = kps_pos_distance_ * kps_feat_width_;
size_t body_box_num = body_boxes.size();
int feature_size = aligned_kps_dim[1] *
aligned_kps_dim[2] *
aligned_kps_dim[3];
int h_stride = aligned_kps_dim[2] * aligned_kps_dim[3];
int w_stride = aligned_kps_dim[3];
for (size_t box_id = 0; box_id < body_box_num; ++box_id) {
const auto &body_box = body_boxes[box_id];
float x1 = body_box.x1;
float y1 = body_box.y1;
float x2 = body_box.x2;
float y2 = body_box.y2;
float w = x2 - x1 + 1;
float h = y2 - y1 + 1;
float scale_x = kps_feat_width_ / w;
float scale_y = kps_feat_height_ / h;
Landmarks skeleton;
skeleton.values.resize(kps_points_number_);
auto *mxnet_out_for_one_point_begin = kps_feature + feature_size * box_id;
for (int kps_id = 0; kps_id < kps_points_number_; ++kps_id) {
// find the best position
int max_w = 0;
int max_h = 0;
int max_score_before_shift = mxnet_out_for_one_point_begin[kps_id];
int32_t *mxnet_out_for_one_point = nullptr;
for (int hh = 0; hh < kps_feat_height_; ++hh) {
for (int ww = 0; ww < kps_feat_width_; ++ww) {
mxnet_out_for_one_point =
mxnet_out_for_one_point_begin + hh * h_stride + ww * w_stride;
if (mxnet_out_for_one_point[kps_id] > max_score_before_shift) {
max_w = ww;
max_h = hh;
max_score_before_shift = mxnet_out_for_one_point[kps_id];
}
}
}
float max_score =
GetFloatByInt(max_score_before_shift, kps_shifts_[kps_id]);
// get delta
mxnet_out_for_one_point =
mxnet_out_for_one_point_begin + max_h * h_stride + max_w * w_stride;
const auto x_delta =
mxnet_out_for_one_point[2 * kps_id + kps_points_number_];
const auto x_shift = kps_shifts_[2 * kps_id + kps_points_number_];
float fp_delta_x = GetFloatByInt(x_delta, x_shift) * pos_distance;
const auto y_delta =
mxnet_out_for_one_point[2 * kps_id + kps_points_number_ + 1];
const auto y_shift = kps_shifts_[2 * kps_id + kps_points_number_ + 1];
float fp_delta_y = GetFloatByInt(y_delta, y_shift) * pos_distance;
Point point;
point.x =
(max_w + fp_delta_x + 0.46875 + kps_anchor_param_) / scale_x + x1;
point.y =
(max_h + fp_delta_y + 0.46875 + kps_anchor_param_) / scale_y + y1;
point.score = SigMoid(max_score);
skeleton.values[kps_id] = point;
}
kpss.push_back(std::move(skeleton));
}
}
void FasterRCNNImp::GetKps2(
std::vector<hobot::vision::Landmarks> &kpss,
void* kps_label_output, void* kps_offset_output,
const std::vector<hobot::vision::BBox> &body_boxes) {
int32_t *label_feature = reinterpret_cast<int32_t *>(kps_label_output);
int32_t *offset_feature = reinterpret_cast<int32_t *>(kps_offset_output);
int input_height = kps_feat_height_ * kps_feat_stride_;
int input_width = kps_feat_width_ * kps_feat_stride_;
float base_center = (kps_feat_stride_ - 1) / 2.0;
int label_feature_size = aligned_kps_label_dim[1] * aligned_kps_label_dim[2] *
aligned_kps_label_dim[3];
int label_h_stride = aligned_kps_label_dim[2] * aligned_kps_label_dim[3];
int label_w_stride = aligned_kps_label_dim[3];
int offset_feature_size = aligned_kps_offset_dim[1] *
aligned_kps_offset_dim[2] *
aligned_kps_offset_dim[3];
int offset_h_stride = aligned_kps_offset_dim[2] * aligned_kps_offset_dim[3];
int offset_w_stride = aligned_kps_offset_dim[3];
size_t body_box_num = body_boxes.size();
for (size_t box_id = 0; box_id < body_box_num; ++box_id) {
const auto &body_box = body_boxes[box_id];
float x1 = body_box.x1;
float y1 = body_box.y1;
float x2 = body_box.x2;
float y2 = body_box.y2;
float w = x2 - x1 + 1;
float h = y2 - y1 + 1;
float scale_x = w / input_width;
float scale_y = h / input_height;
float scale_pos_x = kps_pos_distance_ * scale_x;
float scale_pos_y = kps_pos_distance_ * scale_y;
Landmarks skeleton;
skeleton.values.resize(kps_points_number_);
auto *label_feature_begin = label_feature + label_feature_size * box_id;
for (int kps_id = 0; kps_id < kps_points_number_; ++kps_id) {
// find the best position
int max_w = 0;
int max_h = 0;
int max_score_before_shift = label_feature_begin[kps_id];
int32_t *mxnet_out_for_one_point = nullptr;
for (int hh = 0; hh < kps_feat_height_; ++hh) {
for (int ww = 0; ww < kps_feat_width_; ++ww) {
mxnet_out_for_one_point =
label_feature_begin + hh * label_h_stride + ww * label_w_stride;
if (mxnet_out_for_one_point[kps_id] > max_score_before_shift) {
max_w = ww;
max_h = hh;
max_score_before_shift = mxnet_out_for_one_point[kps_id];
}
}
}
float max_score = GetFloatByInt(max_score_before_shift, kps_label_shift_);
float base_x = (max_w * kps_feat_stride_ + base_center) * scale_x + x1;
float base_y = (max_h * kps_feat_stride_ + base_center) * scale_y + y1;
// get delta
int32_t *offset_feature_begin =
offset_feature + offset_feature_size * box_id;
mxnet_out_for_one_point = offset_feature_begin + max_h * offset_h_stride +
max_w * offset_w_stride;
const auto x_delta = mxnet_out_for_one_point[2 * kps_id];
float fp_delta_x = GetFloatByInt(x_delta, kps_offset_shift_);
const auto y_delta = mxnet_out_for_one_point[2 * kps_id + 1];
float fp_delta_y = GetFloatByInt(y_delta, kps_offset_shift_);
Point point;
point.x = base_x + fp_delta_x * scale_pos_x;
point.y = base_y + fp_delta_y * scale_pos_y;
point.score = SigMoid(max_score);
skeleton.values[kps_id] = point;
}
kpss.push_back(std::move(skeleton));
}
}
void FasterRCNNImp::GetMask(std::vector<Segmentation> &masks,
void* output,
const std::vector<BBox> &body_boxes) {
size_t body_box_num = body_boxes.size();
int32_t *mask_feature = reinterpret_cast<int32_t *>(output);
int feature_size =
aligned_mask_dim[1] * aligned_mask_dim[2] * aligned_mask_dim[3];
int h_stride = aligned_mask_dim[2] * aligned_mask_dim[3];
int w_stride = aligned_mask_dim[3];
for (size_t box_id = 0; box_id < body_box_num; ++box_id) {
int32_t *mask_feature_begin = mask_feature + feature_size * box_id;
int32_t *mxnet_out_for_one_box = nullptr;
float fp_for_this_mask;
Segmentation mask;
for (int hh = 0; hh < aligned_mask_dim[1]; ++hh) {
for (int ww = 0; ww < aligned_mask_dim[2]; ++ww) {
mxnet_out_for_one_box =
mask_feature_begin + hh * h_stride + ww * w_stride;
fp_for_this_mask = GetFloatByInt(mxnet_out_for_one_box[0], mask_shift_);
mask.values.push_back(fp_for_this_mask);
}
}
mask.height = aligned_mask_dim[1];
mask.width = aligned_mask_dim[2];
masks.push_back(std::move(mask));
}
}
void FasterRCNNImp::GetReid(std::vector<Feature> &reids,
void* output,
const std::vector<BBox> &body_boxes) {
size_t body_box_num = body_boxes.size();
int32_t *reid_feature = reinterpret_cast<int32_t *>(output);
int feature_size =
aligned_reid_dim[1] * aligned_reid_dim[2] * aligned_reid_dim[3];
for (size_t box_id = 0; box_id < body_box_num; ++box_id) {
int32_t *mxnet_out_for_one_box = reid_feature + feature_size * box_id;
float fp_for_this_reid;
Feature reid;
for (int32_t reid_i = 0; reid_i < aligned_reid_dim[3]; ++reid_i) {
fp_for_this_reid =
GetFloatByInt(mxnet_out_for_one_box[reid_i], reid_shift_);
reid.values.push_back(fp_for_this_reid);
}
// l2norm
l2_norm(reid);
reids.push_back(std::move(reid));
}
}
void FasterRCNNImp::GetLMKS(
std::vector<hobot::vision::Landmarks> &landmarks, void* output,
const std::vector<hobot::vision::BBox> &face_boxes) {
int32_t *lmk_feature = reinterpret_cast<int32_t *>(output);
float pos_distance = lmk_pos_distance_ * lmk_feat_width_;
size_t face_box_num = face_boxes.size();
int feature_size =
aligned_lmks_dim[1] * aligned_lmks_dim[2] * aligned_lmks_dim[3];
int h_stride = aligned_lmks_dim[2] * aligned_lmks_dim[3];
int w_stride = aligned_lmks_dim[3];
for (size_t box_id = 0; box_id < face_box_num; ++box_id) {
const auto &face_box = face_boxes[box_id];
float x1 = face_box.x1;
float y1 = face_box.y1;
float x2 = face_box.x2;
float y2 = face_box.y2;
float w = x2 - x1 + 1;
float h = y2 - y1 + 1;
float scale_x = lmk_feat_width_ / w;
float scale_y = lmk_feat_height_ / h;
Landmarks landmark;
landmark.values.resize(lmk_points_number_);
for (int lmk_id = 0; lmk_id < lmk_points_number_; ++lmk_id) {
int32_t *lmk_feature_begin = lmk_feature + feature_size * box_id;
// find the best position
int max_w = 0;
int max_h = 0;
int max_score_before_shift = lmk_feature_begin[lmk_id];
int32_t *mxnet_out_for_one_point = nullptr;
for (int hh = 0; hh < lmk_feat_height_; ++hh) {
for (int ww = 0; ww < lmk_feat_width_; ++ww) {
mxnet_out_for_one_point =
lmk_feature_begin + hh * h_stride + ww * w_stride;
if (mxnet_out_for_one_point[lmk_id] > max_score_before_shift) {
max_w = ww;
max_h = hh;
max_score_before_shift = mxnet_out_for_one_point[lmk_id];
}
}
}
float max_score = GetFloatByInt(max_score_before_shift, lmks_shift_);
// get delta
mxnet_out_for_one_point =
lmk_feature_begin + max_h * h_stride + max_w * w_stride;
const auto x_delta =
mxnet_out_for_one_point[2 * lmk_id + lmk_points_number_];
const auto x_shift = kps_shifts_[2 * lmk_id + lmk_points_number_];
float fp_delta_x = GetFloatByInt(x_delta, x_shift) * pos_distance;
const auto y_delta =
mxnet_out_for_one_point[2 * lmk_id + lmk_points_number_ + 1];
const auto y_shift = kps_shifts_[2 * lmk_id + lmk_points_number_ + 1];
float fp_delta_y = GetFloatByInt(y_delta, y_shift) * pos_distance;
Point point;
point.x =
(max_w + fp_delta_x + 0.46875 + lmk_anchor_param_) / scale_x + x1;
point.y =
(max_h + fp_delta_y + 0.46875 + lmk_anchor_param_) / scale_y + y1;
point.score = max_score;
landmark.values[lmk_id] = point;
}
landmarks.push_back(std::move(landmark));
}
}
void FasterRCNNImp::GetLMKS2(std::vector<Landmarks> &landmarks,
void* lmks2_label_output,
void* lmks2_offset_output,
const std::vector<BBox> &face_boxes) {
int32_t *label_feature = reinterpret_cast<int32_t *>(lmks2_label_output);
int32_t *offset_feature = reinterpret_cast<int32_t *>(lmks2_offset_output);
int input_height = lmk_feat_height_ * lmk_feat_stride_;
int input_width = lmk_feat_width_ * lmk_feat_stride_;
float base_center = (lmk_feat_stride_ - 1) / 2.0;
size_t face_box_num = face_boxes.size();
int label_feature_size = aligned_lmks2_label_dim[1] *
aligned_lmks2_label_dim[2] *
aligned_lmks2_label_dim[3];
int label_h_stride = aligned_lmks2_label_dim[2] * aligned_lmks2_label_dim[3];
int label_w_stride = aligned_lmks2_label_dim[3];
int offset_feature_size = aligned_lmks2_offset_dim[1] *
aligned_lmks2_offset_dim[2] *
aligned_lmks2_offset_dim[3];
int offset_h_stride =
aligned_lmks2_offset_dim[2] * aligned_lmks2_offset_dim[3];
int offset_w_stride = aligned_lmks2_offset_dim[3];
for (size_t box_id = 0; box_id < face_box_num; ++box_id) {
const auto &face_box = face_boxes[box_id];
float x1 = face_box.x1;
float y1 = face_box.y1;
float x2 = face_box.x2;
float y2 = face_box.y2;
float w = x2 - x1 + 1;
float h = y2 - y1 + 1;
assert(input_width != 0 && input_height != 0);
float scale_x = w / input_width;
float scale_y = h / input_height;
float scale_pos_x = lmk_pos_distance_ * scale_x;
float scale_pos_y = lmk_pos_distance_ * scale_y;
Landmarks landmark;
landmark.values.resize(lmk_points_number_);
int32_t *label_feature_begin = label_feature + label_feature_size * box_id;
int32_t *offset_feature_begin =
offset_feature + offset_feature_size * box_id;
for (int kps_id = 0; kps_id < lmk_points_number_; ++kps_id) {
// find the best position
int max_w = 0;
int max_h = 0;
int max_score_before_shift = label_feature_begin[kps_id];
int32_t *mxnet_out_for_one_point = nullptr;
for (int hh = 0; hh < lmk_feat_height_; ++hh) {
for (int ww = 0; ww < lmk_feat_width_; ++ww) {
mxnet_out_for_one_point =
label_feature_begin + hh * label_h_stride + ww * label_w_stride;
if (mxnet_out_for_one_point[kps_id] > max_score_before_shift) {
max_w = ww;
max_h = hh;
max_score_before_shift = mxnet_out_for_one_point[kps_id];
}
}
}
float max_score = GetFloatByInt(max_score_before_shift,
lmks2_label_shift_);
float base_x = (max_w * lmk_feat_stride_ + base_center) * scale_x + x1;
float base_y = (max_h * lmk_feat_stride_ + base_center) * scale_y + y1;
// get delta
mxnet_out_for_one_point = offset_feature_begin + max_h * offset_h_stride +
max_w * offset_w_stride;
auto x_delta = mxnet_out_for_one_point[2 * kps_id];
float fp_delta_x = GetFloatByInt(x_delta, lmks2_offset_shift_);
auto y_delta = mxnet_out_for_one_point[2 * kps_id + 1];
float fp_delta_y = GetFloatByInt(y_delta, lmks2_offset_shift_);
Point point;
point.x = base_x + fp_delta_x * scale_pos_x;
point.y = base_y + fp_delta_y * scale_pos_y;
point.score = SigMoid(max_score);
landmark.values[kps_id] = point;
}
landmarks.push_back(std::move(landmark));
}
}
void FasterRCNNImp::GetLMKS1(std::vector<Landmarks> &landmarks,
void* output,
const std::vector<BBox> &face_boxes) {
size_t face_box_num = face_boxes.size();
int32_t *lmks1_feature =
reinterpret_cast<int32_t *>(output);
int feature_size =
aligned_lmks1_dim[1] * aligned_lmks1_dim[2] * aligned_lmks1_dim[3];
for (size_t box_id = 0; box_id < face_box_num; ++box_id) {
const auto &face_box = face_boxes[box_id];
float x1 = face_box.x1;
float y1 = face_box.y1;
float x2 = face_box.x2;
float y2 = face_box.y2;
float w = x2 - x1 + 1;
float h = y2 - y1 + 1;
int32_t *mxnet_out_for_this_box = lmks1_feature + feature_size * box_id;
hobot::vision::Landmarks landmark;
for (int i = 0; i < lmk_points_number_; ++i) {
float x =
GetFloatByInt(mxnet_out_for_this_box[2 * i], lmks1_shift_) * w + x1;
float y =
GetFloatByInt(mxnet_out_for_this_box[2 * i + 1], lmks1_shift_) * h +
y1;
landmark.values.push_back(Point(x, y));
}
landmarks.push_back(std::move(landmark));
}
}
void FasterRCNNImp::GetPose(std::vector<Pose3D> &face_pose,
void* output,
const std::vector<BBox> &face_boxes) {
size_t face_box_num = face_boxes.size();
int32_t *pose_feature = reinterpret_cast<int32_t *>(output);
int feature_size = aligned_face_pose_dim[1] * aligned_face_pose_dim[2] *
aligned_face_pose_dim[3];
for (size_t box_id = 0; box_id < face_box_num; ++box_id) {
int32_t *mxnet_out_for_one_box = pose_feature + feature_size * box_id;
hobot::vision::Pose3D pose;
pose.yaw = GetFloatByInt(mxnet_out_for_one_box[0], face_pose_shift_) * 90.0;
LOGD << "pose.yaw: " << pose.yaw;
pose.pitch =
GetFloatByInt(mxnet_out_for_one_box[1], face_pose_shift_) * 90.0;
LOGD << "pose.pitch: " << pose.pitch;
pose.roll =
GetFloatByInt(mxnet_out_for_one_box[2], face_pose_shift_) * 90.0;
LOGD << "pose.roll: " << pose.roll;
face_pose.push_back(pose);
}
}
void FasterRCNNImp::GetPlateColor(
std::vector<hobot::vision::Attribute<int>> *plates_color,
void* output,
const std::vector<hobot::vision::BBox> &plate_boxes) {
size_t plate_box_num = plate_boxes.size();
int32_t *plate_color_feature = reinterpret_cast<int32_t *>(output);
int feature_size = aligned_plate_color_dim[1] * aligned_plate_color_dim[2] *
aligned_plate_color_dim[3];
LOGD << "plate color: ";
for (size_t box_id = 0; box_id < plate_box_num; ++box_id) {
int32_t *mxnet_out_for_one_box =
plate_color_feature + feature_size * box_id;
hobot::vision::Attribute<int> one_plate_color;
int max_index = 0;
float max_score = -1000;
for (int32_t color_index = 0; color_index < plate_color_num_;
++color_index) {
float color_score =
GetFloatByInt(mxnet_out_for_one_box[color_index], plate_color_shift_);
if (color_score > max_score) {
max_score = color_score;
max_index = color_index;
}
}
one_plate_color.value = max_index;
one_plate_color.score = max_score;
LOGD << "value: " << one_plate_color.value
<< ", score: " << one_plate_color.score << "\n";
plates_color->push_back(one_plate_color);
}
}
void FasterRCNNImp::GetPlateRow(
std::vector<hobot::vision::Attribute<int>> *plates_row,
void* output,
const std::vector<hobot::vision::BBox> &plate_boxes) {
size_t plate_box_num = plate_boxes.size();
int32_t *plate_row_feature = reinterpret_cast<int32_t *>(output);
int feature_size = aligned_plate_row_dim[1] * aligned_plate_row_dim[2] *
aligned_plate_row_dim[3];
LOGD << "plate row: ";
for (size_t box_id = 0; box_id < plate_box_num; ++box_id) {
int32_t *mxnet_out_for_one_box = plate_row_feature + feature_size * box_id;
hobot::vision::Attribute<int> one_plate_row;
int max_index = 0;
float max_score = -1000;
for (int32_t row_index = 0; row_index < plate_row_num_; ++row_index) {
float row_score =
GetFloatByInt(mxnet_out_for_one_box[row_index], plate_row_shift_);
if (row_score > max_score) {
max_score = row_score;
max_index = row_index;
}
}
one_plate_row.value = max_index;
one_plate_row.score = max_score;
LOGD << "value: " << one_plate_row.value
<< ", score: " << one_plate_row.score << "\n";
plates_row->push_back(one_plate_row);
}
}
int FasterRCNNImp::RunModel(
uint8_t *img_data, int data_length,
int image_width, int image_height,
BPU_DATA_TYPE_E data_type) {
{
RUN_PROCESS_TIME_PROFILER("Run FasterRCNNImp PrepareInputTensor");
RUN_FPS_PROFILER("Run FasterRCNNImp PrepareInputTensor");
// 1. prepare input
PrepareInputTensor(img_data, data_length,
image_width, image_height, data_type);
}
// 2. prepare output tensor
PrepareOutputTensor();
// 3. run
BPU_RUN_CTRL_S run_ctrl_s;
run_ctrl_s.core_id = core_id_;
run_ctrl_s.resize_type = 1;
BPU_TASK_HANDLE task_handle;
int ret = 0;
{
RUN_PROCESS_TIME_PROFILER("Run FasterRCNNImp HB_BPU_runModel");
RUN_FPS_PROFILER("Run FasterRCNNImp HB_BPU_runModel");
ret = HB_BPU_runModel(bpu_model_,
input_tensors_.data(),
bpu_model_->input_num,
output_tensors_.data(),
bpu_model_->output_num,
&run_ctrl_s,
true,
&task_handle);
}
if (ret != 0) {
LOGE << "bpu run model failed, " << HB_BPU_getErrorName(ret);
// release input
ReleaseInputTensor(input_tensors_);
return ret;
}
{
RUN_PROCESS_TIME_PROFILER("Run FasterRCNNImp HB_BPU_waitModelDone");
RUN_FPS_PROFILER("Run FasterRCNNImp HB_BPU_waitModelDone");
}
// 4. release input
ReleaseInputTensor(input_tensors_);
return 0;
}
int FasterRCNNImp::RunModel(uint8_t *img_data,
int data_length,
BPU_DATA_TYPE_E data_type) {
// 1. prepare input
PrepareInputTensor(img_data, data_length, data_type);
// 2. prepare output tensor
PrepareOutputTensor();
// 3. run
BPU_RUN_CTRL_S run_ctrl_s;
run_ctrl_s.core_id = core_id_;
BPU_TASK_HANDLE task_handle;
int ret = HB_BPU_runModel(bpu_model_,
input_tensors_.data(),
bpu_model_->input_num,
output_tensors_.data(),
bpu_model_->output_num,
&run_ctrl_s,
true,
&task_handle);
if (ret != 0) {
LOGE << "bpu run model failed, " << HB_BPU_getErrorName(ret);
// release input
ReleaseInputTensor(input_tensors_);
return ret;
}
// 4. release input
ReleaseInputTensor(input_tensors_);
return 0;
}
int FasterRCNNImp::RunModelFromPym(void* pyramid,
int pym_layer,
BPU_DATA_TYPE_E data_type) {
auto pyramid_image =
reinterpret_cast<PymImageFrame*>(pyramid);
// 1. prepare input
input_tensors_.resize(bpu_model_->input_num);
for (int i = 0; i < bpu_model_->input_num; i++) {
BPU_TENSOR_S &tensor = input_tensors_[i];
BPU_MODEL_NODE_S &node = bpu_model_->inputs[i];
tensor.data_type = data_type;
tensor.data_shape.layout = node.shape.layout;
tensor.aligned_shape.layout = node.shape.layout;
int h_idx, w_idx, c_idx;
HB_BPU_getHWCIndex(tensor.data_type,
&tensor.data_shape.layout,
&h_idx, &w_idx, &c_idx);
LOGD << "node data_type: " << node.data_type;
int node_h_idx, node_w_idx, node_c_idx;
HB_BPU_getHWCIndex(node.data_type,
&node.shape.layout,
&node_h_idx, &node_w_idx, &node_c_idx);
tensor.data_shape.ndim = 4;
tensor.data_shape.d[0] = 1;
tensor.data_shape.d[h_idx] = node.shape.d[node_h_idx];
tensor.data_shape.d[w_idx] = node.shape.d[node_w_idx];
tensor.data_shape.d[c_idx] = node.shape.d[node_c_idx];
tensor.aligned_shape.ndim = 4;
tensor.aligned_shape.d[0] = 1;
tensor.aligned_shape.d[h_idx] = node.aligned_shape.d[node_h_idx];
tensor.aligned_shape.d[w_idx] = node.aligned_shape.d[node_w_idx];
tensor.aligned_shape.d[c_idx] = node.aligned_shape.d[node_c_idx];
LOGD << "input_tensor.data_shape.d[0]: " << tensor.data_shape.d[0] << ", "
<< "input_tensor.data_shape.d[1]: " << tensor.data_shape.d[1] << ", "
<< "input_tensor.data_shape.d[2]: " << tensor.data_shape.d[2] << ", "
<< "input_tensor.data_shape.d[3]: " << tensor.data_shape.d[3] << ", "
<< "input_tensor.data_shape.layout: " << tensor.data_shape.layout;
int image_height = tensor.data_shape.d[h_idx];
int image_width = tensor.data_shape.d[w_idx];
int image_channel = tensor.data_shape.d[c_idx];
int stride = tensor.aligned_shape.d[w_idx];
LOGD << "image_height: " << image_height << ", "
<< "image_width: " << image_width << ", "
<< "image channel: " << image_channel << ", "
<< "stride: " << stride;
switch (data_type) {
case BPU_TYPE_IMG_NV12_SEPARATE: {
#ifdef X2
int y_length = image_height * stride;
int uv_length = image_height / 2 * stride;
HB_SYS_bpuMemAlloc("in_data0", y_length, true, &tensor.data);
HB_SYS_bpuMemAlloc("in_data1", uv_length, true, &tensor.data_ext);
uint8_t* y_data = reinterpret_cast<uint8_t *>(
pyramid_image->img.down_scale[pym_layer].y_vaddr);
// Copy y data to data0
uint8_t *y = reinterpret_cast<uint8_t *>(tensor.data.virAddr);
for (int h = 0; h < image_height; ++h) {
auto *raw = y + h * stride;
memcpy(raw, y_data, image_width);
y_data += image_width;
}
HB_SYS_flushMemCache(&tensor.data, HB_SYS_MEM_CACHE_CLEAN);
// Copy uv data to data_ext
uint8_t* uv_data = reinterpret_cast<uint8_t *>(
pyramid_image->img.down_scale[pym_layer].c_vaddr);
uint8_t *uv = reinterpret_cast<uint8_t *>(tensor.data_ext.virAddr);
int uv_height = image_height / 2;
for (int i = 0; i < uv_height; ++i) {
auto *raw = uv + i * stride;
memcpy(raw, uv_data, image_width);
uv_data += image_width;
}
HB_SYS_flushMemCache(&tensor.data_ext, HB_SYS_MEM_CACHE_CLEAN);
#endif
#ifdef X3
// Copy y data to data0
tensor.data.virAddr = reinterpret_cast<void*>(
pyramid_image->down_scale[pym_layer].y_vaddr);
tensor.data.phyAddr = pyramid_image->down_scale[pym_layer].y_paddr;
tensor.data.memSize = image_height * stride;
// HB_SYS_flushMemCache(&tensor.data, HB_SYS_MEM_CACHE_CLEAN);
// Copy uv data to data_ext
tensor.data_ext.virAddr = reinterpret_cast<void*>(
pyramid_image->down_scale[pym_layer].c_vaddr);
tensor.data_ext.phyAddr = pyramid_image->down_scale[pym_layer].c_paddr;
tensor.data_ext.memSize = (image_height + 1) / 2 * stride;
// HB_SYS_flushMemCache(&tensor.data_ext, HB_SYS_MEM_CACHE_CLEAN);
#endif
break;
}
default:
HOBOT_CHECK(0) << "unsupport data_type: " << data_type;
break;
}
}
// 2. prepare output tensor
PrepareOutputTensor();
// 3. run
BPU_RUN_CTRL_S run_ctrl_s;
run_ctrl_s.core_id = core_id_;
BPU_TASK_HANDLE task_handle;
int ret = HB_BPU_runModel(bpu_model_,
input_tensors_.data(),
bpu_model_->input_num,
output_tensors_.data(),
bpu_model_->output_num,
&run_ctrl_s,
true,
&task_handle);
if (ret != 0) {
LOGE << "bpu run model failed, " << HB_BPU_getErrorName(ret);
#ifdef X2
ReleaseInputTensor(input_tensors_);
#endif
return ret;
}
#ifdef X2
ReleaseInputTensor(input_tensors_);
#endif
return 0;
}
void FasterRCNNImp::PrepareInputTensor(uint8_t *img_data,
int data_length,
BPU_DATA_TYPE_E data_type) {
input_tensors_.resize(bpu_model_->input_num);
for (int i = 0; i < bpu_model_->input_num; i++) {
BPU_TENSOR_S &tensor = input_tensors_[i];
BPU_MODEL_NODE_S &node = bpu_model_->inputs[i];
tensor.data_type = data_type;
tensor.data_shape.layout = node.shape.layout;
tensor.aligned_shape.layout = node.shape.layout;
int h_idx, w_idx, c_idx;
HB_BPU_getHWCIndex(tensor.data_type,
&tensor.data_shape.layout,
&h_idx, &w_idx, &c_idx);
LOGD << "node data_type: " << node.data_type;
int node_h_idx, node_w_idx, node_c_idx;
HB_BPU_getHWCIndex(node.data_type,
&node.shape.layout,
&node_h_idx, &node_w_idx, &node_c_idx);
tensor.data_shape.ndim = 4;
tensor.data_shape.d[0] = 1;
tensor.data_shape.d[h_idx] = node.shape.d[node_h_idx];
tensor.data_shape.d[w_idx] = node.shape.d[node_w_idx];
tensor.data_shape.d[c_idx] = node.shape.d[node_c_idx];
tensor.aligned_shape.ndim = 4;
tensor.aligned_shape.d[0] = 1;
tensor.aligned_shape.d[h_idx] = node.aligned_shape.d[node_h_idx];
tensor.aligned_shape.d[w_idx] = node.aligned_shape.d[node_w_idx];
tensor.aligned_shape.d[c_idx] = node.aligned_shape.d[node_c_idx];
LOGD << "input_tensor.data_shape.d[0]: " << tensor.data_shape.d[0] << ", "
<< "input_tensor.data_shape.d[1]: " << tensor.data_shape.d[1] << ", "
<< "input_tensor.data_shape.d[2]: " << tensor.data_shape.d[2] << ", "
<< "input_tensor.data_shape.d[3]: " << tensor.data_shape.d[3] << ", "
<< "input_tensor.data_shape.layout: " << tensor.data_shape.layout;
int image_height = tensor.data_shape.d[h_idx];
int image_width = tensor.data_shape.d[w_idx];
int image_channel = tensor.data_shape.d[c_idx];
LOGD << "image_height: " << image_height << ", "
<< "image_width: " << image_width << ", "
<< "image channel: " << image_channel;
switch (data_type) {
case BPU_TYPE_IMG_NV12_SEPARATE: {
int stride = tensor.aligned_shape.d[w_idx];
int y_length = image_height * stride;
int uv_length = image_height / 2 * stride;
HB_SYS_bpuMemAlloc("in_data0", y_length, true, &tensor.data);
HB_SYS_bpuMemAlloc("in_data1", uv_length, true, &tensor.data_ext);
HOBOT_CHECK(image_height*image_width*3/2 == data_length)
<< "Input img length error!";
// Copy y data to data0
uint8_t *y = reinterpret_cast<uint8_t *>(tensor.data.virAddr);
for (int h = 0; h < image_height; ++h) {
auto *raw = y + h * stride;
memcpy(raw, img_data, image_width);
img_data += image_width;
}
HB_SYS_flushMemCache(&tensor.data, HB_SYS_MEM_CACHE_CLEAN);
// Copy uv data to data_ext
uint8_t *uv = reinterpret_cast<uint8_t *>(tensor.data_ext.virAddr);
int uv_height = image_height / 2;
for (int i = 0; i < uv_height; ++i) {
auto *raw = uv + i * stride;
memcpy(raw, img_data, image_width);
img_data += image_width;
}
HB_SYS_flushMemCache(&tensor.data_ext, HB_SYS_MEM_CACHE_CLEAN);
break;
}
default:
HOBOT_CHECK(0) << "unsupport data_type: " << data_type;
break;
}
}
}
int FasterRCNNImp::PrepareInputTensor(
uint8_t *img_data, int data_length,
int image_width, int image_height,
BPU_DATA_TYPE_E data_type) {
input_tensors_.resize(bpu_model_->input_num);
for (int i = 0; i < bpu_model_->input_num; i++) {
BPU_TENSOR_S &tensor = input_tensors_.at(i);
BPU_MODEL_NODE_S &node = bpu_model_->inputs[i];
tensor.data_type = data_type;
tensor.data_shape.layout = node.shape.layout;
tensor.aligned_shape.layout = node.shape.layout;
LOGD << "node data_type: " << node.data_type;
int h_idx, w_idx, c_idx;
HB_BPU_getHWCIndex(tensor.data_type,
&tensor.data_shape.layout,
&h_idx, &w_idx, &c_idx);
tensor.data_shape.ndim = 4;
tensor.data_shape.d[0] = 1;
tensor.data_shape.d[h_idx] = image_height;
tensor.data_shape.d[w_idx] = image_width;
tensor.data_shape.d[c_idx] = node.shape.d[c_idx];
tensor.aligned_shape.ndim = 4;
tensor.aligned_shape.d[0] = 1;
tensor.aligned_shape.d[h_idx] = image_height;
tensor.aligned_shape.d[w_idx] = (image_width + 15) & ~15;
tensor.aligned_shape.d[c_idx] = node.aligned_shape.d[c_idx];
LOGD << "input_tensor.data_shape.d[0]: " << tensor.data_shape.d[0] << ", "
<< "input_tensor.data_shape.d[1]: " << tensor.data_shape.d[1] << ", "
<< "input_tensor.data_shape.d[2]: " << tensor.data_shape.d[2] << ", "
<< "input_tensor.data_shape.d[3]: " << tensor.data_shape.d[3] << ", "
<< "input_tensor.data_shape.layout: " << tensor.data_shape.layout;
int image_channel = tensor.data_shape.d[c_idx];
int stride = tensor.aligned_shape.d[w_idx];
LOGD << "image_height: " << image_height << ", "
<< "image_width: " << image_width << ", "
<< "image channel: " << image_channel << ", "
<< "stride: " << stride;
switch (data_type) {
case BPU_TYPE_IMG_NV12_SEPARATE: {
int y_length = image_height * stride;
int uv_length = image_height * stride / 2;
HB_SYS_bpuMemAlloc("in_data0", y_length, true, &tensor.data);
HB_SYS_bpuMemAlloc("in_data1", uv_length, true, &tensor.data_ext);
// Copy y data to data0
uint8_t *y = reinterpret_cast<uint8_t *>(tensor.data.virAddr);
for (int h = 0; h < image_height; ++h) {
auto *raw = y + h * stride;
memcpy(raw, img_data, image_width);
img_data += image_width;
}
HB_SYS_flushMemCache(&tensor.data, HB_SYS_MEM_CACHE_CLEAN);
// Copy uv data to data_ext
uint8_t *uv = reinterpret_cast<uint8_t *>(tensor.data_ext.virAddr);
int uv_height = image_height / 2;
for (int i = 0; i < uv_height; ++i) {
auto *raw = uv + i * stride;
memcpy(raw, img_data, image_width);
img_data += image_width;
}
HB_SYS_flushMemCache(&tensor.data_ext, HB_SYS_MEM_CACHE_CLEAN);
break;
}
default:
HOBOT_CHECK(0) << "unsupport data_type: " << data_type;
break;
}
}
return 0;
}
void FasterRCNNImp::FlushOutputTensor() {
if (!output_tensors_alloced_) {
return;
}
for (int i = 0; i < bpu_model_->output_num; i++) {
if (HB_SYS_isMemCachable(&(output_tensors_[i].data))) {
HB_SYS_flushMemCache(&(output_tensors_[i].data),
HB_SYS_MEM_CACHE_INVALIDATE);
}
}
}
void FasterRCNNImp::PrepareOutputTensor() {
if (output_tensors_alloced_) {
return;
}
output_tensors_.resize(bpu_model_->output_num);
for (int i = 0; i < bpu_model_->output_num; i++) {
BPU_TENSOR_S &tensor = output_tensors_[i];
BPU_MODEL_NODE_S &node = bpu_model_->outputs[i];
tensor.data_type = node.data_type;
tensor.data_shape = node.shape;
tensor.aligned_shape = node.aligned_shape;
int output_size = 1;
for (int j = 0; j < node.aligned_shape.ndim; j++) {
output_size *= node.aligned_shape.d[j];
LOGD << "node.aligned_shape.d[j]:" << node.aligned_shape.d[j];
}
if (node.data_type == BPU_TYPE_TENSOR_F32 ||
node.data_type == BPU_TYPE_TENSOR_S32 ||
node.data_type == BPU_TYPE_TENSOR_U32) {
output_size *= 4;
}
// output_size需要按16对齐
output_size = ALIGN_16(output_size);
LOGD << "output_size: " << output_size;
HB_SYS_bpuMemAlloc("out_data0", output_size, true, &tensor.data);
}
output_tensors_alloced_ = true;
}
void FasterRCNNImp::ReleaseInputTensor(
std::vector<BPU_TENSOR_S> &input_tensors) {
for (size_t i = 0; i < input_tensors.size(); i++) {
BPU_TENSOR_S *tensor = &input_tensors[i];
switch (tensor->data_type) {
case BPU_TYPE_IMG_BGRP:
case BPU_TYPE_IMG_RGBP:
case BPU_TYPE_IMG_Y:
case BPU_TYPE_IMG_RGB:
case BPU_TYPE_IMG_BGR:
case BPU_TYPE_IMG_YUV444:
case BPU_TYPE_IMG_YUV_NV12:
case BPU_TYPE_TENSOR_U8:
case BPU_TYPE_TENSOR_S8:
case BPU_TYPE_TENSOR_F32:
case BPU_TYPE_TENSOR_S32:
case BPU_TYPE_TENSOR_U32:
HB_SYS_bpuMemFree(&(tensor->data));
break;
case BPU_TYPE_IMG_NV12_SEPARATE:
HB_SYS_bpuMemFree(&(tensor->data));
HB_SYS_bpuMemFree(&(tensor->data_ext));
default:
break;
}
}
}
void FasterRCNNImp::ReleaseOutputTensor() {
for (size_t i = 0; i < output_tensors_.size(); i++) {
HB_SYS_bpuMemFree(&output_tensors_[i].data);
}
}
void FasterRCNNImp::Finalize() {
if (output_tensors_alloced_) {
ReleaseOutputTensor();
output_tensors_alloced_ = false;
}
if (bpu_model_) {
// release model
HB_BPU_releaseModel(bpu_model_);
}
}
int FasterRCNNImp::CropPadAndResizeRoi(
hobot::vision::BBox *norm_box,
uint8_t *pym_src_y_data, uint8_t *pym_src_uv_data,
int pym_src_w, int pym_src_h,
int pym_src_y_size, int pym_src_uv_size,
int pym_src_y_stride, int pym_src_uv_stride,
uint8_t **img_data, HobotXStreamImageToolsResizeInfo *resize_info) {
uint8_t *pym_dst_data = nullptr;
int pym_dst_size, pym_dst_w, pym_dst_h, pym_dst_y_stride, pym_dst_uv_stride;
const uint8_t *input_yuv_data[3] = {pym_src_y_data,
pym_src_uv_data,
nullptr};
const int input_yuv_size[3] = {pym_src_y_size, pym_src_uv_size, 0};
int ret = 0;
{
RUN_PROCESS_TIME_PROFILER("Run FasterRCNNImp CropYUVImage");
RUN_FPS_PROFILER("Run FasterRCNNImp CropYUVImage");
if (norm_box->x2 > pym_src_w) {
LOGD << "norm_box:" << *norm_box;
LOGD << "pym_src_w:" << pym_src_w << " pym_src_h:" << pym_src_h;
norm_box->x2 = pym_src_w;
}
if (norm_box->y2 > pym_src_h) {
LOGD << "norm_box:" << *norm_box;
LOGD << "pym_src_w:" << pym_src_w << " pym_src_h:" << pym_src_h;
norm_box->y2 = pym_src_h;
}
ret = HobotXStreamCropYUVImage(
input_yuv_data, input_yuv_size, pym_src_w, pym_src_h, pym_src_y_stride,
pym_src_uv_stride, IMAGE_TOOLS_RAW_YUV_NV12, norm_box->x1, norm_box->y1,
norm_box->x2 - 1, norm_box->y2 - 1, &pym_dst_data, &pym_dst_size,
&pym_dst_w, &pym_dst_h, &pym_dst_y_stride, &pym_dst_uv_stride);
HOBOT_CHECK(ret == 0)
<< "crop img failed"
<< ", pym_src_y_size:" << pym_src_y_size << ", pym_src_w:" << pym_src_w
<< ", pym_src_h:" << pym_src_h << ", pym_src_y_stride:" << pym_src_y_stride
<< ", pym_src_uv_stride:" << pym_src_uv_stride;
}
pym_src_y_data = pym_dst_data;
pym_src_y_size = pym_dst_size;
pym_src_uv_data = nullptr;
pym_src_uv_size = 0;
pym_src_w = pym_dst_w;
pym_src_h = pym_dst_h;
pym_src_y_stride = pym_dst_y_stride;
pym_src_uv_stride = pym_dst_uv_stride;
RUN_PROCESS_TIME_PROFILER("Run FasterRCNNImp PadYUVImage");
RUN_FPS_PROFILER("Run FasterRCNNImp PadYUVImage");
resize_info->src_height_ = pym_dst_h;
resize_info->src_width_ = pym_dst_w;
CalcResizeInfo(resize_info);
const uint8_t padding_value[3] = {0, 128, 128};
int padding_right =
resize_info->padding_right_ / resize_info->width_ratio_;
padding_right &= ~1;
int padding_bottom =
resize_info->padding_bottom_ / resize_info->height_ratio_;
padding_bottom &= ~1;
ret = HobotXStreamPadImage(
pym_src_y_data, pym_src_y_size,
pym_src_w, pym_src_h,
pym_src_y_stride, pym_src_uv_stride,
IMAGE_TOOLS_RAW_YUV_NV12,
0, padding_right, 0, padding_bottom,
padding_value,
&pym_dst_data, &pym_dst_size,
&pym_dst_w, &pym_dst_h,
&pym_dst_y_stride, &pym_dst_uv_stride);
// static uint32_t id = 0;
// std::string output_file_path = std::to_string(id++) + ".yuv";
// std::ofstream outfile(output_file_path, std::ios::out | std::ios::binary);
// outfile.write(reinterpret_cast<const char *>(pym_dst_data), pym_dst_size);
// outfile.close();
// free the crop image
HobotXStreamFreeImage(pym_src_y_data);
HOBOT_CHECK(ret == 0)
<< "resize img failed, ret: " << ret
<< ", pym_src_y_size:" << pym_src_y_size << ", pym_src_w:" << pym_src_w
<< ", pym_src_h:" << pym_src_h << ", pym_src_y_stride:" << pym_src_y_stride
<< ", pym_src_uv_stride:" << pym_src_uv_stride;
*img_data = pym_dst_data;
return 0;
}
void FasterRCNNImp::CalcResizeInfo(
HobotXStreamImageToolsResizeInfo *resize_info) {
resize_info->dst_width_ = model_input_width_;
resize_info->dst_height_ = model_input_height_;
float width_ratio = static_cast<float>(model_input_width_)
/ resize_info->src_width_;
float height_ratio = static_cast<float>(model_input_height_)
/ resize_info->src_height_;
// fix_aspect_ratio
float ratio = width_ratio;
if (ratio > height_ratio) {
ratio = height_ratio;
}
resize_info->padding_right_ = model_input_width_ / ratio
- resize_info->src_width_;
resize_info->padding_bottom_ = model_input_height_ / ratio
- resize_info->src_height_;
resize_info->width_ratio_ = 1;
resize_info->height_ratio_ = 1;
}
int FasterRCNNImp::GetPymScaleInfo(
const std::shared_ptr<hobot::vision::PymImageFrame>& pyramid,
hobot::vision::BBox *norm_box,
uint8_t* &pym_src_y_data, uint8_t* &pym_src_uv_data,
int &pym_src_w, int &pym_src_h,
int &pym_src_y_size, int &pym_src_uv_size,
int &pym_src_y_stride, int &pym_src_uv_stride, float &scale) {
auto box_width = norm_box->Width();
auto box_height = norm_box->Height();
auto min_cost_scale = 1, minareadiff = INT_MAX;
int target_area = model_input_width_ * model_input_height_;
int box_area = box_height * box_width;
for (int i = min_cost_scale; i <= 3; i++) {
int areadiff = std::abs(box_area - target_area);
if (minareadiff > areadiff) {
minareadiff = areadiff;
min_cost_scale = i;
}
box_area >>= 2;
}
int pyramid_scale = 1 << (min_cost_scale - 1);
pyramid_scale = (pyramid_scale == 1 ? 0 : pyramid_scale) * 2;
assert(pyramid_scale >= 0 && pyramid_scale < DOWN_SCALE_MAX);
#ifdef X2
auto &pyramid_down_scale = pyramid->img.down_scale[pyramid_scale];
pym_src_y_stride = pyramid_down_scale.step;
pym_src_uv_stride = pyramid_down_scale.step;
#endif
#ifdef X3
auto &pyramid_down_scale = pyramid->down_scale[pyramid_scale];
pym_src_y_stride = pyramid_down_scale.stride;
pym_src_uv_stride = pyramid_down_scale.stride;
#endif
pym_src_y_data = reinterpret_cast<uint8_t *>(
pyramid_down_scale.y_vaddr);
pym_src_uv_data = reinterpret_cast<uint8_t *>(
pyramid_down_scale.c_vaddr);
pym_src_w = pyramid_down_scale.width;
pym_src_h = pyramid_down_scale.height;
pym_src_y_size = pym_src_y_stride * pym_src_h;
pym_src_uv_size = pym_src_uv_stride * pym_src_h / 2;
scale = 1 << (min_cost_scale - 1);
return 0;
}
int FasterRCNNImp::CropPadAndResizeRoi(
hobot::vision::BBox *norm_box,
const std::shared_ptr<hobot::vision::PymImageFrame>& pyramid,
uint8_t **img_data, HobotXStreamImageToolsResizeInfo *resize_info,
float *scale) {
int ret;
uint8_t *pym_src_y_data , *pym_src_uv_data;
int pym_src_w, pym_src_h;
int pym_src_y_size, pym_src_uv_size;
int pym_src_y_stride, pym_src_uv_stride;
GetPymScaleInfo(
pyramid, norm_box,
pym_src_y_data, pym_src_uv_data,
pym_src_w, pym_src_h,
pym_src_y_size, pym_src_uv_size,
pym_src_y_stride, pym_src_uv_stride, *scale);
auto scale_box = *norm_box;
scale_box.x1 /= *scale, scale_box.x2 /= *scale;
scale_box.y1 /= *scale, scale_box.y2 /= *scale;
ret = CropPadAndResizeRoi(
&scale_box,
pym_src_y_data, pym_src_uv_data,
pym_src_w, pym_src_h,
pym_src_y_size, pym_src_uv_size,
pym_src_y_stride, pym_src_uv_stride,
img_data, resize_info);
return ret;
}
} // namespace faster_rcnn_method
| 37.771343 | 80 | 0.651898 | [
"shape",
"vector",
"model"
] |
63aad3b56d469cc1c4ec597ed14869d02695c4a1 | 3,079 | cc | C++ | src/pcl_viewer_custom.cc | vincentlooi/labelme_3D | c083299ac512c6f6bc0ae35cabda8f39bc3953f4 | [
"MIT"
] | 8 | 2019-01-08T16:05:58.000Z | 2021-12-27T10:29:27.000Z | src/pcl_viewer_custom.cc | vincentlooi/labelme_3D | c083299ac512c6f6bc0ae35cabda8f39bc3953f4 | [
"MIT"
] | null | null | null | src/pcl_viewer_custom.cc | vincentlooi/labelme_3D | c083299ac512c6f6bc0ae35cabda8f39bc3953f4 | [
"MIT"
] | 4 | 2019-08-12T18:42:55.000Z | 2020-06-30T06:48:33.000Z | #include "pcl_viewer_custom.hh"
#include <vtkVersion.h>
#include <vtkPolyData.h>
#include <vtkCamera.h>
#include <vtkWindowToImageFilter.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkObjectFactory.h>
#if VTK_RENDERING_BACKEND_OPENGL_VERSION < 2
#include <pcl/visualization/vtk/vtkVertexBufferObjectMapper.h>
#endif
// Standard VTK macro for *New ()
vtkStandardNewMacro(PCLInteractorCustom);
void PCLInteractorCustom::OnKeyDown ()
{
using namespace pcl::visualization;
if (!init_)
{
pcl::console::print_error ("[PCLVisualizerInteractorStyle] Interactor style not initialized. Please call Initialize () before continuing.\n");
return;
}
if (!rens_)
{
pcl::console::print_error ("[PCLVisualizerInteractorStyle] No renderer collection given! Use SetRendererCollection () before continuing.\n");
return;
}
FindPokedRenderer (Interactor->GetEventPosition ()[0], Interactor->GetEventPosition ()[1]);
if (wif_->GetInput () == NULL)
{
wif_->SetInput (Interactor->GetRenderWindow ());
wif_->Modified ();
// snapshot_writer_->Modified ();
}
// Save the initial windows width/height
if (win_height_ == -1 || win_width_ == -1)
{
int *win_size = Interactor->GetRenderWindow ()->GetSize ();
win_height_ = win_size[0];
win_width_ = win_size[1];
}
// // Get the status of special keys (Cltr+Alt+Shift)
// bool shift = Interactor->GetShiftKey ();
// bool ctrl = Interactor->GetControlKey ();
// bool alt = Interactor->GetAltKey ();
// bool keymod = false;
// switch (modifier_)
// {
// case INTERACTOR_KB_MOD_ALT:
// {
// keymod = alt;
// break;
// }
// case INTERACTOR_KB_MOD_CTRL:
// {
// keymod = ctrl;
// break;
// }
// case INTERACTOR_KB_MOD_SHIFT:
// {
// keymod = shift;
// break;
// }
// }
std::string key (Interactor->GetKeySym ());
if (key.find ("XF86ZoomIn") != std::string::npos)
zoomIn ();
else if (key.find ("XF86ZoomOut") != std::string::npos)
zoomOut ();
switch (Interactor->GetKeyCode ())
{
case 27: // ESC
{
Interactor->ExitCallback ();
return;
}
case 'q': case 'Q': case 'e': case 'E':
{
break;
}
default:
{
Superclass::OnKeyDown ();
break;
}
}
KeyboardEvent event (true, Interactor->GetKeySym (), Interactor->GetKeyCode (), Interactor->GetAltKey (), Interactor->GetControlKey (), Interactor->GetShiftKey ());
keyboard_signal_ (event);
rens_->Render ();
Interactor->Render ();
}
void PCLInteractorCustom::OnChar ()
{
// Make sure we ignore the same events we handle in OnKeyDown to avoid calling things twice
FindPokedRenderer (Interactor->GetEventPosition ()[0], Interactor->GetEventPosition ()[1]);
std::string key (Interactor->GetKeySym ());
if (key.find ("XF86ZoomIn") != std::string::npos)
zoomIn ();
else if (key.find ("XF86ZoomOut") != std::string::npos)
zoomOut ();
switch (Interactor->GetKeyCode ())
{
case 'q': case 'Q': case 'e': case 'E':
{
break;
}
default:
{
Superclass::OnChar ();
break;
}
}
}
| 22.977612 | 165 | 0.659955 | [
"render"
] |
63acbf651c9dc690f6d63d98b35ce342473bfab6 | 843 | cc | C++ | app/menus/menu_model.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | 11 | 2015-03-20T04:08:08.000Z | 2021-11-15T15:51:36.000Z | app/menus/menu_model.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | app/menus/menu_model.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2009 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 "app/menus/menu_model.h"
namespace menus {
bool MenuModel::GetModelAndIndexForCommandId(int command_id,
MenuModel** model, int* index) {
int item_count = (*model)->GetItemCount();
for (int i = 0; i < item_count; ++i) {
if ((*model)->GetTypeAt(i) == TYPE_SUBMENU) {
MenuModel* submenu_model = (*model)->GetSubmenuModelAt(i);
if (GetModelAndIndexForCommandId(command_id, &submenu_model, index)) {
*model = submenu_model;
return true;
}
}
if ((*model)->GetCommandIdAt(i) == command_id) {
*index = i;
return true;
}
}
return false;
}
} // namespace
| 29.068966 | 77 | 0.616845 | [
"model"
] |
63afc81814400f4fc0288ed91ed586cf4b852abc | 24,022 | hpp | C++ | lib/event/EventManager.hpp | carnegie-technologies/pravala-toolkit | 77dac4a910dc0692b7515a8e3b77d34eb2888256 | [
"Apache-2.0"
] | null | null | null | lib/event/EventManager.hpp | carnegie-technologies/pravala-toolkit | 77dac4a910dc0692b7515a8e3b77d34eb2888256 | [
"Apache-2.0"
] | null | null | null | lib/event/EventManager.hpp | carnegie-technologies/pravala-toolkit | 77dac4a910dc0692b7515a8e3b77d34eb2888256 | [
"Apache-2.0"
] | 2 | 2020-02-07T00:16:51.000Z | 2020-02-11T15:10:45.000Z | /*
* Copyright 2019 Carnegie Technologies
*
* 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.
*/
#pragma once
#include "basic/Thread.hpp"
#include "basic/MsvcSupport.hpp"
#include "basic/SimpleArray.hpp"
#include "basic/Mutex.hpp"
#include "TimerManager.hpp"
// Debugging of file descriptor operations (setting handlers, etc.)
// #define EVENT_MANAGER_DEBUG_FD_OPS 1
#ifdef USE_LIBEVENT
struct event;
#endif
namespace Pravala
{
/// @brief Event Manager.
class EventManager: public TimerManager
{
public:
/// @brief To be inherited by classes that wish to receive information about file descriptor events
class FdEventHandler
{
public:
/// @brief Function called when an event occurs on specific descriptor.
///
/// This method should be defined in classes to be able to subscribe to events.
/// @param [in] fd File descriptor that generated this event.
/// @param [in] events Is a bit sum of Event* values and describes what kind of events were detected.
virtual void receiveFdEvent ( int fd, short events ) = 0;
/// @brief Virtual destructor
virtual ~FdEventHandler()
{
}
};
/// @brief To be inherited by classes that wish to receive information about file descriptor events
class ChildEventHandler
{
public:
/// @brief Function called when the child process exits.
///
/// This method should be defined in classes to be able to subscribe to child exit events.
/// @param [in] childPid PID of the child that exited.
/// @param [in] childStatus exit status of the child process. It's one of Child* enums.
/// @param [in] statusValue Depending on the exit status, this can be either
/// child's return code (for ChildExited), or the value of the signal that terminated
/// the child (ChildSignal), or the value of the signal that stopped the child (ChildStopped).
virtual void receiveChildEvent ( int childPid, int childStatus, int statusValue ) = 0;
/// @brief Virtual destructor
virtual ~ChildEventHandler()
{
}
};
/// @brief To be inherited by classes that wish to subscribe to end-of-loop events
class LoopEndEventHandler
{
public:
/// @brief Default constructor
LoopEndEventHandler(): _endOfLoopId ( 0 )
{
}
/// @brief Callback in the object that happens at the end of event loop
virtual void receiveLoopEndEvent() = 0;
/// @brief Virtual destructor
/// Unsubscribes this object from the end-of-loop events
virtual ~LoopEndEventHandler()
{
EventManager::loopEndUnsubscribe ( this );
}
private:
/// @brief An identifier of the end-of-loop queue
uint8_t _endOfLoopId;
friend class EventManager;
};
/// @brief To be inherited by classes that wish to receive signal notifications
class SignalHandler
{
public:
/// @brief Default constructor
SignalHandler()
{
}
/// @brief Callback in the object called when a signal is received
/// @param [in] sigRcvd A Signal* value, which contains the signal received
virtual void receiveSignalEvent ( int sigRcvd ) = 0;
/// @brief Virtual destructor
/// Unsubscribes this object from signal notifications.
virtual ~SignalHandler()
{
EventManager::signalUnsubscribe ( this );
}
};
/// @brief To be inherited by classes that wish to receive notification when the EventManager is shutting down.
class ShutdownHandler
{
public:
/// @brief Default constructor
ShutdownHandler()
{
}
/// @brief Callback in the object called when the EventManager is shutting down.
virtual void receiveShutdownEvent() = 0;
/// @brief Virtual destructor
/// Unsubscribes this object from shutdown notifications.
virtual ~ShutdownHandler()
{
EventManager::shutdownUnsubscribe ( this );
}
};
/// @brief Child exit codes.
enum
{
ChildExited, ///< Child process exited normally
ChildSignal, ///< Child process was killed by a signal
ChildStopped, ///< Child process was stopped (by a signal)
ChildContinued ///< Child process has been resumed
};
static const int EventRead; ///< "Read" event on the file descriptor
static const int EventWrite; ///< "Write" event on the file descriptor
static const int SignalHUP; ///< SIGHUP signal
static const int SignalUsr1; ///< SIGUSR1 signal
static const int SignalUsr2; ///< SIGUSR2 signal
/// @brief Static method that returns the number of existing EventManagers.
/// It does NOT create the EventManager if it doesn't exist.
/// This function returning >0 does NOT mean that current thread has an EventManager.
/// @note It is safe to use this function without an existing EventManager.
/// @see _numManagers
/// @return the number of existing EventManagers
static size_t getNumManagers();
/// @brief Static method that returns true if this thread's EventManager has already been initialized.
/// @return True if this thread's EventManager has already been initialized; False otherwise.
static inline bool isInitialized()
{
return ( _instance != 0 );
}
/// @brief Static method that checks if this thread's EventManager acts as a "primary" manager.
/// At the moment the only difference is that the "primary" manager handles signals.
/// @return True if this thread's EventManager acts as a primary manager.
static inline bool isPrimaryManager()
{
return ( _instance != 0 && _instance->_isPrimaryManager );
}
/// @brief Creates and initializes the EventManager.
///
/// It should be called before using most of the other methods in this class.
/// @return Standard error code.
static ERRCODE init();
/// @brief Shuts down this thread's EventManager.
///
/// The caller should make sure that the EventManager is not running, otherwise this function will fail.
/// @param [in] force If set to true, some checks will be skipped. If it is false, this function will check
/// if anything is still using the manager (timers, FD handlers, etc.) and it will fail
/// if that's the case.
/// @return Standard error code.
static ERRCODE shutdown ( bool force = false );
/// @brief Start monitoring for events.
///
/// This function doesn't exit until stop() is called, or an interrupt signal is received.
/// @note This function can only be used after this thread's EventManager has been initialized using init().
static void run();
/// @brief Stops monitoring for events.
/// This functions doesn't actually stop anything, it just marks,
/// that run() function should exit after the next internal loop.
/// @note It is safe to use this function without an existing EventManager.
static void stop();
/// @brief Returns current time used by this thread's EventManager.
/// @note This function can only be used after this thread's EventManager has been initialized using init().
/// @param [in] refresh If true, current time will be refreshed before it's returned.
/// This is somewhat heavier operation, so the use should be limited to cases that
/// require most up-to-date time.
/// @return Current time from the moment it was last refreshed.
static const Time & getCurrentTime ( bool refresh = false );
/// @brief Sets the object to receive events detected on specific file descriptor.
/// @note This function can only be used after this thread's EventManager has been initialized using init().
/// @param [in] fd File descriptor for which events need to be monitored. It has to be valid (>=0)!
/// @param [in] handler Object that should receive event notifications. It has to be valid (!=0)!
/// @param [in] events Bit sum of Event* values that we want to receive notifications for.
static void setFdHandler ( int fd, FdEventHandler * handler, int events );
/// @brief Disables monitoring of specific file descriptor and removes handler for it.
///
/// It does not delete the handler's object, just removes its pointers from internal
/// data structures.
/// @note It is safe to use this function without an existing EventManager.
/// @param [in] fd File descriptor for which events should not be monitored anymore.
/// Invalid FDs (<0) are ignored.
static void removeFdHandler ( int fd );
/// @brief Returns events for which given file descriptors is monitored.
/// @note It is safe to use this function without an existing EventManager.
/// @param [in] fd File descriptor to be checked. If it is invalid, no events (0) will be returned.
/// @return Bit sum of Event* values describing which events this file descriptor is monitored for.
static int getFdEvents ( int fd );
/// @brief Sets list of events to monitor file descriptor for.
/// @note This function can only be used after this thread's EventManager has been initialized using init().
/// @note This function can only be used if there already is a registered FD handler for this FD.
/// @param [in] fd File descriptor which settings we are modifying. It has to be valid (>=0)!
/// @param [in] events Bit sum of Event* values that we want to receive notifications for.
static void setFdEvents ( int fd, int events );
/// @brief Enables EventWrite events on file descriptor.
///
/// It doesn't modify EventRead settings for that descriptor, just adds
/// (if needed) EventWrite monitoring.
/// @note This function can only be used after this thread's EventManager has been initialized using init().
/// @note This function can only be used if there already is a registered FD handler for this FD.
/// @param [in] fd File descriptor for which write events need to be monitored. It has to be valid (>=0)!
static void enableWriteEvents ( int fd );
/// @brief Disables EventWrite events on file descriptor.
///
/// It doesn't modify EventRead settings for that descriptor, just removes
/// (if needed) EventWrite monitoring.
/// @note It is safe to use this function without an existing EventManager.
/// @note This function doesn't do anything if the handler for this FD is not registered.
/// @param [in] fd File descriptor for which write events shouldn't be monitored anymore.
/// It has to be valid (>=0)!
static void disableWriteEvents ( int fd );
/// @brief Enables EventRead events on file descriptor.
///
/// It doesn't modify EventRead settings for that descriptor, just adds
/// (if needed) EventRead monitoring.
/// @note This function can only be used after this thread's EventManager has been initialized using init().
/// @note This function can only be used if there already is a registered FD handler for this FD.
/// @param [in] fd File descriptor for which Read events need to be monitored. It has to be valid (>=0)!
static void enableReadEvents ( int fd );
/// @brief Disables EventRead events on file descriptor.
///
/// It doesn't modify EventRead settings for that descriptor, just removes
/// (if needed) EventRead monitoring.
/// @note It is safe to use this function without an existing EventManager.
/// @note This function doesn't do anything if the handler for this FD is not registered.
/// @param [in] fd File descriptor for which Read events shouldn't be monitored anymore.
/// It has to be valid (>=0)!
static void disableReadEvents ( int fd );
/// @brief Closes file descriptor and removes event monitoring for it.
///
/// First it uninstalls handler for this file descriptor, disables all events
/// on this file descriptor, and calls close() on it.
/// @note It is safe to use this function without an existing EventManager.
/// @param [in] fd File descriptor to be closed. If < 0 is passed, it is ignored and nothing happens.
/// @return True if the close was successful; False otherwise.
/// It fails if the FD was invalid, or if there was system error.
static bool closeFd ( int fd );
/// @brief Adds the object at the end of "End-of-loop" callback list
///
/// If this object already has existing end-of-loop subscription it is not be added again.
/// After performing the callback, event is removed from the list. If, inside this callback,
/// an object tries to subscribe again, it will be subscribed for the next end of loop.
/// @note This function can only be used after this thread's EventManager has been initialized using init().
/// @param [in] handler A pointer to the object that wants to receive this notification.
static void loopEndSubscribe ( LoopEndEventHandler * handler );
/// @brief Removes end-of-loop subscription for the specified object.
/// @note It is safe to use this function without an existing EventManager.
/// @param [in] handler A pointer to the object that should be removed from the end-of-loop event list.
static void loopEndUnsubscribe ( LoopEndEventHandler * handler );
/// @brief Adds the object to the list of objects to receive notifications about the signals
/// @note Those notifications are only generated for SIGHUP, SIGUSR1 and SIGUSR2
/// @note This function can only be used after this thread's EventManager has been initialized using init().
/// @param [in] handler A pointer to the object that wants to receive this notification.
static void signalSubscribe ( SignalHandler * handler );
/// @brief Removes signal event subscription
/// @note It is safe to use this function without an existing EventManager.
/// @param [in] handler A pointer to the object that should be removed from the signal subscription list.
static void signalUnsubscribe ( SignalHandler * handler );
/// @brief Adds the object to the list of objects to receive 'shutdown' notification
/// @note This function can only be used after this thread's EventManager has been initialized using init().
/// @param [in] handler A pointer to the object that wants to receive this notification.
static void shutdownSubscribe ( ShutdownHandler * handler );
/// @brief Removes shutdown event subscription
/// @note It is safe to use this function without an existing EventManager.
/// @param [in] handler A pointer to the object that should be removed from the shutdown subscription list.
static void shutdownUnsubscribe ( ShutdownHandler * handler );
/// @brief Sets the object to receive information when specified child finishes.
/// @note This function can only be used after this thread's EventManager has been initialized using init().
/// @param [in] pid PID of the child.
/// @param [in] handler Object that should receive the notification.
static void setChildHandler ( int pid, ChildEventHandler * handler );
/// @brief Disables monitoring of specific child pid and removes handler for it.
///
/// It does not delete the handler's object, just removes its pointers from internal
/// data structures.
/// @note It is safe to use this function without an existing EventManager.
/// @param [in] pid PID of the child process for which the handler should be removed.
static void removeChildHandler ( int pid );
protected:
/// @brief Internal structure for describing events and their receivers
struct FdEventInfo
{
FdEventHandler * handler; ///< Object that will be notified about events
#ifdef USE_LIBEVENT
struct event * libEventState; ///< libevent event struct (only used by libevent)
#endif
int events; ///< Currently set events - bit sum of Event*
};
/// @brief Array with description of events.
SimpleArray<FdEventInfo> _events;
/// @brief The list of subscriptions to the End-Of-Loop event
List<LoopEndEventHandler *> _loopEndQueue;
/// @brief The list of subscriptions to the End-Of-Loop event while they are being processed
List<LoopEndEventHandler *> _processedLoopEndQueue;
/// @brief The list of subscriptions to signal event
List<SignalHandler *> _signalHandlers;
/// @brief The list of subscriptions to shutdown event
List<ShutdownHandler *> _shutdownHandlers;
/// @brief HashMap storing children pids and associated objects that
/// should receive information about specific child process.
HashMap<int, ChildEventHandler *> _childHandlers;
/// @brief Set to true in the primary EventManager.
/// @see _primaryManagerExists
const bool _isPrimaryManager;
/// @brief Marks if this EventManager is working.
///
/// Makes run() function break its loop if it is set to false.
bool _working;
uint8_t _currentEndOfLoopId; ///< The ID of the current end-of-loop queue
/// @brief Constructor
EventManager();
/// @brief Destructor
virtual ~EventManager();
/// @brief Exposes pointer to the instance of the EventManager.
/// @return Current pointer to the instance of the EventManager.
static inline EventManager * getInstance()
{
return _instance;
}
/// @brief Handles timers and end-of-loop events
/// Should be called at the end of every event loop
void runEndOfLoop();
/// @brief Notifies signal handlers
/// @param [in] sigRcvd The signal received
void notifySignalHandlers ( int sigRcvd );
/// @brief Shuts down this thread's EventManager.
/// This function can be overloaded by the specific implementation.
/// The base version only checks if this EventManager is running and, if 'force' is set to false,
/// whether anything is still using it.
/// @note If this function returns code that's considered 'OK', this manager's destructor will be called.
/// @param [in] force If true, it will try harder and potentially skip some checks.
/// @return Standard error code.
virtual ERRCODE implShutdown ( bool force );
/// @brief Start monitoring for events.
///
/// This function doesn't exit until stop() is called, or an interrupt signal is received.
virtual void implRun() = 0;
/// @brief Sets the object to receive events detected on specific file descriptor.
///
/// @param [in] fd File descriptor for which events need to be monitored. It should be valid (>=0).
/// @param [in] handler Object that should receive event notifications. It should be valid (!=0).
/// @param [in] events Bit sum of Event* values that we want to receive notifications for.
virtual void implSetFdHandler ( int fd, FdEventHandler * handler, int events ) = 0;
/// @brief Disables monitoring of specific file descriptor and removes handler for it.
///
/// It does not delete the handler's object, just removes its pointers from internal
/// data structures.
/// @param [in] fd File descriptor for which events should not be monitored anymore. It should be valid (>=0).
virtual void implRemoveFdHandler ( int fd ) = 0;
/// @brief Sets list of events to monitor file descriptor for.
///
/// @note The handler for this FD should be already subscribed.
/// @param [in] fd File descriptor which settings we are modifying. It should be valid (>=0).
/// @param [in] events Bit sum of Event* values that we want to receive notifications for.
virtual void implSetFdEvents ( int fd, int events ) = 0;
friend class Timer;
private:
/// @brief A mutex controlling access to _numManagers and _primaryManagerExists.
static Mutex _mutex;
/// @brief The number of created EventManagers (across all threads).
/// When it's 0, it means that EventManager has never been created (or it has been created and later destroyed)
/// and it's safe to do anything.
///
/// When this is >0, at least one EventManager exists, and you should not create any child processes
/// (e.g. with Utils::forkChild) that use EventManager as bad things will happen!
///
/// You can however, use EventManager after a pthread_create, as that will return a new and different
/// instance of EventManager.
static size_t _numManagers;
/// @brief Set when a primary EventManager exists.
/// The first EventManager created will be the "primary" one.
/// However, if that EventManager is destroyed, this flag will be unset.
/// The next EventManager created will become the new primary manager,
/// even if at that point there are other EventManagers.
/// The difference between primary and non-primary managers is, at the moment, signal handling.
/// Only the primary manager handles signals.
static bool _primaryManagerExists;
/// @brief A pointer to this thread's instance of the EventManager.
static THREAD_LOCAL EventManager * _instance;
/// @brief This function should be called whenever an EventManager is created.
/// It always increments the _numCreated counter.
/// It also inspects _primaryManagerExists. If that flag is set to 'false',
/// this function sets it to 'true' and returns 'true'.
/// Otherwise it returns false (the counter is still incremented).
/// @return True if the calling EventManager should become a new primary manager.
static bool newManagerCreated();
};
}
| 50.150313 | 119 | 0.635251 | [
"object"
] |
63b2d2be0026d66add53aae997996e0a4d286999 | 772 | cxx | C++ | cli/tasks/db-task.cxx | Sigill/Elfxplore | 1da52555ab7b71fd0a6e9f23d1051050259eb44a | [
"MIT"
] | null | null | null | cli/tasks/db-task.cxx | Sigill/Elfxplore | 1da52555ab7b71fd0a6e9f23d1051050259eb44a | [
"MIT"
] | null | null | null | cli/tasks/db-task.cxx | Sigill/Elfxplore | 1da52555ab7b71fd0a6e9f23d1051050259eb44a | [
"MIT"
] | null | null | null | #include "db-task.hxx"
#include <iostream>
#include "Database3.hxx"
namespace bpo = boost::program_options;
boost::program_options::options_description DB_Task::options()
{
bpo::options_description opt("Options");
opt.add_options()
("clear-symbols", "Clear the symbols table.")
("optimize", "Optimize database.")
("vacuum", "Vacuum (compact) database.");
return opt;
}
void DB_Task::parse_args(const std::vector<std::string>& args)
{
bpo::store(bpo::command_line_parser(args).options(options()).run(), vm);
bpo::notify(vm);
}
void DB_Task::execute(Database3& db)
{
if (vm.count("clear-symbols")) {
db.truncate_symbols();
}
if (vm.count("optimize")) {
db.optimize();
}
if (vm.count("vacuum")) {
db.vacuum();
}
}
| 19.3 | 74 | 0.651554 | [
"vector"
] |
63b6a545a2220868587c030e35268a3ed627b13a | 24,655 | cpp | C++ | src/lib/objects/acatalogue.cpp | leaderit/ananas-qt4 | 6830bf5074b316582a38f6bed147a1186dd7cc95 | [
"MIT"
] | 1 | 2021-03-16T21:47:41.000Z | 2021-03-16T21:47:41.000Z | src/lib/objects/acatalogue.cpp | leaderit/ananas-qt4 | 6830bf5074b316582a38f6bed147a1186dd7cc95 | [
"MIT"
] | null | null | null | src/lib/objects/acatalogue.cpp | leaderit/ananas-qt4 | 6830bf5074b316582a38f6bed147a1186dd7cc95 | [
"MIT"
] | null | null | null | /****************************************************************************
** $Id: acatalogue.cpp,v 1.3 2008/11/09 21:09:11 leader Exp $
**
** Catalogue metadata object implementation file of
** Ananas application library
**
** Created : 20031201
**
** Copyright (C) 2003-2004 Leader InfoTech. All rights reserved.
** Copyright (C) 2003-2004 Grigory Panov, Yoshkar-Ola.
**
** This file is part of the Designer application of the Ananas
** automation accounting system.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.leaderit.ru/page=ananas or email sales@leaderit.ru
** See http://www.leaderit.ru/gpl/ for GPL licensing information.
**
** Contact org@leaderit.ru if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "acfg.h"
#include "aobject.h"
#include "adatabase.h"
#include "acatalogue.h"
#include "alog.h"
//Added by qt3to4:
#include <Q3ValueList>
/*!\en
*\_en \ru
*\_ru
*/
aCatalogue::aCatalogue( aCfgItem context, aDatabase * adb )
:aObject( context, adb, 0, "aCatalogue")
{
concrete = !context.isNull();
initObject();
}
/*!\en
*\_en \ru
*\_ru
*/
aCatalogue::aCatalogue(QString name, aDatabase * adb)
:aObject( "Catalogue."+name, adb, 0, "aCatalogue")
{
if ( name.isEmpty() ) concrete = false;
else concrete = true;
initObject();
}
ERR_Code
aCatalogue::initObject()
{
ERR_Code err = aObject::initObject();
if ( err ) return err;
aCfgItem g = md->find( obj, md_group ), e = md->find( obj, md_element );
err = tableInsert( aDatabase::tableDbName( *md, e ), e );
if ( err ) return err;
return tableInsert( aDatabase::tableDbName( *md, g ), g, md_group );
}
/*
Q_ULLONG
aCatalogue::getCatGroup()
{
aSQLTable * t = table();
if ( !t ) return 0;
if ( !selected() ) return 0;
return t->sysValue("idg").toULongLong();
}*/
qulonglong
aCatalogue::getGroup()
{
aSQLTable * t = table(md_group);
if ( !t ) return 0;
if ( !selected(md_group) ) return 0;
return t->sysValue("id").toULongLong();
}
ERR_Code
aCatalogue::setGroup( qulonglong idg )
{
aSQLTable * t = table();
if ( !t ) return err_notable;
if ( !selected() ) return err_notselected;
t->setSysValue( "idg", idg );
t->primeUpdate();
t->update();
return err_noerror;
}
ERR_Code
aCatalogue::SetGroup( aCatalogue * cat )
{
if ( !cat ) return setGroup( 0 );
else return setGroup(cat->getGroup());
}
qulonglong
aCatalogue::getOwner()
{
aSQLTable * t = table();
if ( !t ) return 0;
if ( !selected() ) return 0;
return t->sysValue("ido").toULongLong();
}
ERR_Code
aCatalogue::setOwner( qulonglong ido )
{
aSQLTable * t = table();
if ( !t ) return err_notable;
if ( !selected() ) return err_notselected;;
t->setSysValue( "ido", ido );
t->primeUpdate();
t->update();
return err_noerror;
}
ERR_Code
aCatalogue::SetOwner( aCatalogue * cat )
{
if ( !cat ) return setOwner( 0 );
else return setOwner(cat->getUid());
}
ERR_Code
aCatalogue::New( bool child )
{
qulonglong group = getGroup(), parent = getUid();
ERR_Code err = aObject::New();
if ( err ) return err;
aSQLTable * t = table();
t->setSysValue( "idg", group );
if ( child ) t->setSysValue( "ido", parent );
t->primeUpdate();
t->update();
if ( group ) groupSelect();
setSelected(true);
return err_noerror;
}
ERR_Code
aCatalogue::New( )
{
return New(false);
}
ERR_Code
aCatalogue::Delete()
{
aSQLTable * t = table();
if ( !t ) return err_notable;
if ( !selected() ) return err_notselected;
qulonglong ido = t->sysValue("id").toULongLong();
if ( ido )
{
aLog::print(aLog::Debug, tr("aCatalogue delete ido=%1").arg(ido));
aCatalogue cat( obj, db );
while ( !cat.selectByOwner(ido) )
{
cat.Delete();
}
}
return aObject::Delete();
}
ERR_Code
aCatalogue::Update()
{
ERR_Code err = aObject::Update();
if ( !err )
{
aLog::print(aLog::Debug, tr("aCatalogue update"));
err = TableUpdate( md_group );
if(err)
{
aLog::print(aLog::Error, tr("aCatalogue update groups error %1").arg(err));
}
else
{
aLog::print(aLog::Debug, tr("aCatalogue update groups"));
}
}
else
{
aLog::print(aLog::Error, tr("aCatalogue update elements error %1").arg(err));
}
return err;
}
ERR_Code
aCatalogue::Copy()
{
return aObject::Copy();
}
ERR_Code
aCatalogue::Select( bool grouponly )
{
aSQLTable * t = table();
if ( !t ) return err_notable;
// setSelected(true,md_group);
// setSelected(true);
qulonglong idg = getGroup();
QString flt = "";
// groupSelect();
if ( grouponly ) flt = QString("idg=%1").arg( idg );
if ( t->select( flt ) )
if ( t->first() )
{
setSelected(true);
qulonglong newidg = t->sysValue("idg").toULongLong();
aLog::print(aLog::Debug, tr("aCatalogue select group id=%1").arg(idg));
if ( newidg != idg ) groupSelect( newidg );
return err_noerror;
}
else return err_notselected;
else return err_selecterror;
}
/*!
*\~english
* Select group.
* Get group id from current element and select group table
* with this id.
*\~russian
*\~
* \return \~english Error code \~russian \~
*/
int
aCatalogue::GroupSelect()
{
aSQLTable * t = table();
if(!t) return err_notable;
if ( !selected() ) return err_notselected;;
qulonglong idg = t->sysValue("idg").toULongLong();
return groupSelect(idg);
}
void
aCatalogue::UnSelect( bool grouponly )
{
if (!grouponly )
{
setSelected(false);
}
setSelected(false, md_group);
}
ERR_Code
aCatalogue::groupSelect ( qulonglong idg )
{
if ( !idg ) return err_noerror;
aSQLTable * t = table( md_group );
if ( !t ) return err_notable;
setSelected( false, md_group );
if ( t->select( idg ) )
if ( t->first() )
{
setSelected( true, md_group );
return err_noerror;
}
else return err_notselected;
else return err_selecterror;
}
ERR_Code
aCatalogue::groupSelect ()
{
aSQLTable * t = table(md_group);
if ( !t ) return err_notable;
qulonglong idg = t->sysValue("id").toULongLong();
return groupSelect( idg );
}
ERR_Code
aCatalogue::selectByOwner ( qulonglong ido )
{
aSQLTable * t = table();
if ( !t ) return err_notable;
if ( t->select(QString("ido=%1").arg(ido),false) )
if ( t->first() )
{
setSelected(true);
return err_noerror;
}
else return err_notselected;
else return err_selecterror;
}
ERR_Code
aCatalogue::selectByGroup ( qulonglong idg )
{
aSQLTable * t = table();
if ( !t ) return err_notable;
setSelected(false);
if ( t->select(QString("idg=%1").arg(idg),false ) )
if ( t->first() )
{
setSelected(true);
return err_noerror;
}
else return err_notselected;
else return err_selecterror;
}
ERR_Code
aCatalogue::groupByParent(qulonglong idp )
{
aSQLTable * t = table( md_group );
if ( !t ) return err_notable;
//f ( !selected(md_group) ) return err_notselected;
setSelected( false, md_group );
if ( t->select(QString("idp=%1").arg(idp),false) )
if ( t->first() )
{
setSelected(true,md_group);
return err_noerror;
}
else
{
return err_notselected;
}
else return err_selecterror;
}
/*!\en
* Select groups depth level.
* \param level (in) - level
\_en \ru
*
*\_ru
*/
int
aCatalogue::selectByLevel(int level )
{
aSQLTable * t = table(md_group);
if ( !t ) return err_notable;
// if ( !selected(md_group) ) return err_notselected;
setSelected( false, md_group );
if ( t->select(QString("level=%1").arg(level),false) )
if ( t->first() )
{
setSelected(true, md_group);
return err_noerror;
}
else
{
return err_notselected;
}
else
{
return err_selecterror;
}
}
/*!\en
* Gets id of group on the id of element
* \param ide (in) - id of element.
* \return id of group.
\_en \ru
* Получает идентификационный номер группы по номеру элемента
* \param ide (in) - идентификационный номер элемента.
* \return идентификационный номер группы.
*\_ru
*/
qulonglong
aCatalogue::idGroupByElement(qulonglong ide )
{
aSQLTable * t = table();
if ( !t ) return 0;
t->select(QString("id=%1").arg(ide), false);
if ( t->first() )
{
setSelected(true);
return sysValue("idg").toLongLong();
}
else return 0;
}
ERR_Code
aCatalogue::GroupNew( bool reparent )
{
aSQLTable * te = table(), *tg = table( md_group );
if ( !te || !tg ) return err_notable;
// groupSelect();
// setSelected(true, md_group);
qulonglong idp = getGroup(), level = tg->sysValue("level").toULongLong(),
idg = tg->primeInsert()->value("id").toULongLong();
if ( tg->insert() )
{
if ( idp ) level++;
tg->select( idg );
if ( !tg->first() ) return err_selecterror;
tg->selected = true;
aLog::print(aLog::Info,tr("aCatalogue new group with id=%1").arg(idg) );
tg->setSysValue("idp",idp);
tg->setSysValue("level",level);
if ( reparent ) te->setSysValue("idg",idg);
}
return Update();
}
/*!\en
* Inserts new group in groups table
* \param parentId (in) - id parent group, or 0 if no parent.
\_en \ru
* Вставляет новую группу в таблицу групп
* \param parentId (in) - идентификационный номер группы предка или 0 если нет предка.
*\_ru
*/
ERR_Code
aCatalogue::newGroup(qulonglong parentId )
{
aSQLTable *tg = table( md_group );
if (!tg ) return err_notable;
setSelected(true, md_group);
tg->select(parentId);
setSelected(true,md_group);
qulonglong level, idg;
if(tg->first())
{
level = tg->sysValue("level").toULongLong()+1;
}
else level=0;
QSqlRecord* rec = tg->primeInsert(); // get edit buffer for table groups
idg = rec->value("id").toULongLong();
aLog::print(aLog::Info,tr("aCatalogue new group with id=%1").arg(idg) );
rec->setValue("id",idg );
rec->setValue("idp",parentId);
rec->setValue("level",level);
rec->setValue("df","0");
tg->insert(); // insert record
tg->select(QString("id=%1").arg(idg),false); // set cursor to inserted record
tg->first();
setSelected(true,md_group);
//tg->update();
return groupSelect(idg);
}
/*!\en
* Inserts new element in elements table
* \param parentId (in) - id parent group.
\_en \ru
* Вставляет новый элемент в таблицу элементов
* \param parentId (in) - идентификационный номер группы предка.
*\_ru
*/
ERR_Code
aCatalogue::newElement(qulonglong parentId )
{
aSQLTable *te = table();
if (!te) return err_notable;
QSqlRecord *rec;
qulonglong ide;
rec = te->primeInsert(); // get edit buffer for table elements
ide = rec->value("id").toULongLong();
rec->setValue("id",ide); // set defult values for all user fields = id
//for(uint i=0; i< rec->count(); i++)
//{
// rec->setValue(i,ide);
// printf("%s\n",rec->fieldName(i).ascii());
//}
rec->setValue("idg",parentId);
rec->setValue("df","0");
rec->setNull("ido");
te->insert(); // insert edit buffer as new line in table
te->select(QString("id=%1").arg(ide),false); // set cursor to inserted record
te->first();
setSelected(true);
return err_noerror;
}
/*!\en
* Mark deleted element only. Don't supports link one to many.
* \return id of deleted element.
\_en \ru
* Только выделяет удаляемый элемент. Не поддерживает связь один ко многим.
* \return идентификационный номер удаляемого элемента.
*\_ru
*/
qulonglong
aCatalogue::setMarkDeletedElement(qulonglong id_el,bool del)
{
select(id_el);
SetMarkDeleted(del);
Update();
return table()->sysValue("id").toULongLong();
}
qulonglong
aCatalogue::setMarkDeletedGroup(qulonglong id_gr, bool del)
{
groupSelect(id_gr);
SetMarkDeleted(del, md_group);
GroupUpdate();
return table()->sysValue("id").toULongLong();
}
/*!\en
* Delets element only. Don't supports link one to many.
* \return id of deleted element.
\_en \ru
* Только удаляет элемент. Не поддерживает связь один ко многим.
* \return идентификационный номер удаляемого элемента.
*\_ru
*/
qulonglong
aCatalogue::delElement()
{
aSQLTable * t = table();
qulonglong ide=0;
if ( !t ) return ide;
ide = t->sysValue("id").toULongLong();
if ( ide )
{
aLog::print(aLog::Info,tr("aCatalogue delete element with id=%1").arg(ide));
t->primeDelete();
t->del();
setSelected( false );
}
return ide;
}
/*!\en
* Mark deleted group with child elements and groups.
* \param idg (in) - id mark deleted group.
* \param listDelId (in,out) - list of id mark deleted elements and groups.
\_en \ru
* Выделяет удаляемую группу с дочерними элементами и группами.
* При первом вызове параметр listDelId должен быть пустой, он не обнуляется
* автоматически при вызове этой функции.
* Функция рекурсивно вызывает сама себя для всех дочерних подгрупп и
* добавляет их id в список. Также туда добавляются и id элементов,
* содержащихся в этих группах. Для изменения атрибута удаления используте функции
* setElementMarkDeleted(id)(для элементов) и setGroupMarkDeleted(id) (для групп)
* \param idg (in) - идентификационный номер выделенной для удаления группы.
* \param listDelId (in,out) - список идентификационных номеров выделенных для удаления элементов и групп.
*\_ru
*/
void
aCatalogue::getMarkDeletedList(qulonglong idg,
Q3ValueList<qulonglong> &listDelId)
{
Q3ValueList<qulonglong> lst;
aSQLTable * tg = table ( md_group );
if ( !tg ) return;
qulonglong tmp;
if ( idg )
{
// delete elements in group;
if(selectByGroup(idg)==err_noerror)
{
do
{
listDelId << sysValue("id").toULongLong();
}
while(Next());
}
if (groupByParent(idg)==err_noerror)
{
do
{
lst << GroupSysValue("id").toULongLong();
}while(NextInGroupTable());
Q3ValueList<qulonglong>::iterator it = lst.begin();
while(it!= lst.end())
{
getMarkDeletedList((*it),listDelId);
++it;
}
}
}
tg->select(QString("id=%1").arg(idg),false);
if(tg->first())
{
listDelId << idg;
}
return;
}
bool
aCatalogue::isGroupMarkDeleted()
{
return IsMarkDeleted(md_group);
}
bool
aCatalogue::isElementMarkDeleted()
{
return IsMarkDeleted();
}
/*!\en
* Delets group with child elements and groups.
* \param idg (in) - id deleted group.
* \param listDelId (in,out) - list of id deleted elements and groups.
\_en \ru
* Физически удаляет группу со всеми ее дочерними элементами и группами.
* \param idg (in) - идентификационный номер выделенной для удаления группы.
* \param listDelId (in,out) - список идентификационных номеров выделенных для удаления элементов и групп.
*\_ru
*/
qulonglong
aCatalogue::delGroup(qulonglong idg, Q3ValueList<qulonglong> &listDelId)
{
aSQLTable * tg = table ( md_group );
if ( !tg ) return 0;
//if ( !selected( md_group ) ) return err_notselected;
qulonglong tmp;// idg = tg->sysValue("id").toULongLong();
groupSelect(idg);
if ( idg )
{
aLog::print(aLog::Info,tr("aCatalogue delete group with id=%1").arg(idg));
// printf("idg=" LLU_SPEC "\n",idg);
// delete elements in group;
while(selectByGroup(idg)==err_noerror)
{
listDelId << delElement();
}
while (groupByParent(idg)==err_noerror)
{
delGroup(GroupSysValue("id").toULongLong(), listDelId);
//printf(">>>idg=%lu\n",tmp);
}
}
tg->select(QString("id=%1").arg(idg),false);
if(tg->first())
{
tg->primeDelete();
tg->del();
listDelId << idg;
setSelected( false, md_group );
}
return idg;
}
ERR_Code
aCatalogue::GroupDelete()
{
aSQLTable * tg = table ( md_group );
if ( !tg ) return err_notable;
getGroup();
if ( !selected( md_group ) )
{
aLog::print(aLog::Info,tr("aCatalogue delete without selection"));
//debug_message(">>not seletc in delete\n");
return err_notselected;
}
qulonglong idg = tg->sysValue("id").toULongLong();
if ( idg )
{
//printf("idg=" LLU_SPEC "\n",idg);
aCatalogue cat( obj,db );
while ( !cat.selectByGroup(idg) ) cat.Delete();
while ( !cat.groupByParent(idg) )
{
//printf("delete group\n");
cat.GroupDelete();
}
}
tg->primeDelete();
tg->del();
aLog::print(aLog::Info,tr("aCatalogue delete group with id=%1").arg(idg));
if(tg->first())
{
setSelected( true, md_group );
}
else
{
setSelected( false, md_group );
}
return err_noerror;
}
ERR_Code
aCatalogue::GroupMarkDeleted()
{
aSQLTable * t = table ( md_group );
if ( !t ) return err_notable;
if ( !selected( md_group ) ) return err_notselected;
if ( SetMarkDeleted( true, md_group ) ) return err_noerror;
else return err_deleteerror;
}
ERR_Code
aCatalogue::GroupUpdate()
{
aLog::print(aLog::Debug, tr("aCatalogue update group"));
return TableUpdate( md_group );
}
ERR_Code
aCatalogue::GroupSetGroup( aCatalogue * cat )
{
aSQLTable * t = table( md_group );
if ( !t ) return err_notable;
qulonglong newidp, oldidp = t->sysValue("idp").toULongLong();
if ( !cat ) newidp = 0;
else newidp = cat->getGroup();
if ( newidp == oldidp ) return err_noerror;
t->setSysValue( "idp", newidp );
t->primeUpdate();
t->update();
return err_noerror;
}
QVariant
aCatalogue::GroupValue( const QString & name )
{
aSQLTable * t = table( md_group );
if ( !t ) return QVariant::Invalid;
return t->value( name );
}
/*!\en
* Gets system field value in table of group.
* \param name (in) - field name.
* \return field value or QVariant::Invalid if no field.
\_en \ru
*\_ru
*/
QVariant
aCatalogue::GroupSysValue( const QString & name )
{
aSQLTable * t = table( md_group );
if ( !t ) return QVariant::Invalid;
//if(name=="id") return t->sysValue(name).toString();
return t->sysValue( name );//.toString();
}
ERR_Code
aCatalogue::GroupSetValue( const QString & name, const QVariant & value )
{
aSQLTable * t = table( md_group );
if ( !t ) return err_notable;
if ( !selected( md_group ) ) return err_notselected;
if ( t->setValue( name, value ) ) return err_noerror;
else return err_fieldnotfound;
}
ERR_Code
aCatalogue::GroupSetSysValue( const QString & name, const QVariant & value )
{
aSQLTable * t = table( md_group );
if ( !t ) return err_notable;
if ( !selected( md_group ) ) return err_notselected;
t->setSysValue( name, value);
return err_noerror;
//else return err_fieldnotfound;
}
QVariant
aCatalogue::GetElementValue(QVariant ide, const QString &fname)
{
aSQLTable * t = table();
if ( !t ) return "";
t->select(ide.toULongLong());
if ( !t->first() ) return "";
else return t->value( fname );
}
bool
aCatalogue::Next()
{
return aObject::Next(); //return !groupSelect();
//else return false;
}
bool
aCatalogue::Prev()
{
return aObject::Prev(); //return !groupSelect();
// else return false;
}
bool
aCatalogue::First()
{
return aObject::First(); //return !groupSelect();
//else return false;
}
bool
aCatalogue::Last()
{
return aObject::Last(); //return !groupSelect();
//else return false;
}
bool
aCatalogue::NextInGroupTable()
{
return aObject::Next(md_group);
}
bool
aCatalogue::PrevInGroupTable()
{
return aObject::Prev(md_group);
}
bool
aCatalogue::FirstInGroupTable()
{
return aObject::First(md_group);
}
bool
aCatalogue::LastInGroupTable()
{
return aObject::Last(md_group);
}
/*!\en
* Gets list user and calculation fields in table of elements.
\_en \ru
*\_ru
*/
QStringList
aCatalogue::getUserFields()
{
QStringList l;
aSQLTable *t = table();
if(t) l = t->getUserFields();
return l;
}
/*!\en
* Gets list user and calculation fields in table of Groups.
\_en \ru
*\_ru
*/
QStringList
aCatalogue::getGroupUserFields()
{
QStringList l;
aSQLTable *t = table( md_group );
if(t) l = t->getUserFields();
return l;
}
aCfgItem
aCatalogue::displayStringContext()
{
return md->find( md->find( obj, md_element ), md_string_view );
}
aCatElement::aCatElement(aCfgItem context, aDatabase * adb)
:aObject( context, adb, 0, "aElement")
{
}
aCatGroup::aCatGroup(aCfgItem context, aDatabase * adb)
:aObject( context, adb, 0, "aGroup")
{
int err = initObject();
}
/*!
*\ru
* Возвращает id родительской группы
*\_ru
*/
qulonglong
aCatGroup::parentUid()
{
if ( !selected() ) return 0;
else return table()->sysValue("idp").toULongLong();
}
void
aCatGroup::setLevel( qulonglong newLevel )
{
if ( !selected() ) return;
aSQLTable * t = table();
qulonglong level = t->sysValue("level").toULongLong();
if ( level == newLevel ) return;
aCatGroup tgr( obj, db );
QString query;
query = QString("UPDATE %1 SET level=%2 WHERE id=%3")\
.arg(t->tableName).arg(newLevel).arg(getUid());
// printf("%s\n",(const char*) query);
db->db()->exec(query);
if ( !tgr.SelectChild( this ));
do
{
tgr.setLevel( newLevel + 1 );
}
while ( tgr.Next() );
}
QString
aCatGroup::trSysName( const QString & sname )
{
if (( sname == "Level" )||( sname == QString::fromUtf8("Уровень") )) return "Level";
return "";
}
QVariant
aCatGroup::sysValue( const QString & sname )
{
if ( sname == "Level" )
return table()->sysValue("level");
return QVariant::Invalid;
}
/*!
*\~english
* Init object.
* We can work with object only after inited.
* Auto call from constructor.
*\~russian
*\brief Инициализирует объект элементом конфигурации.
*
* Мы можем работать с объектом после его инициализации.
* Функция вызывается из конструктора.
*\~
* \return \en error code. \_en \ru
код ошибки.\_ru
*/
ERR_Code
aCatGroup::initObject()
{
ERR_Code err = aObject::initObject();
if ( err ) return err;
aCfgItem g = md->find( obj, md_group );
return tableInsert( aDatabase::tableDbName( *md, g ), g );
}
/*!
*\ru
*\brief Ничего не делает. Возвращает 0.
*
*\return Код ошибки.
*\_ru
*/
ERR_Code
aCatGroup::New(aCatGroup *group)
{
int rc = 0;
return rc;
}
/*!
*\en
* Create new group in table.
* New group added in root group and have level 0.
* \return Error code.
*\_en
*\ru
* \brief Добавляет группу в справочник.
*
* Группа добавляется как корневая и имеет уровень 0.
* \return Код ошибки.
*\_ru
*/
ERR_Code
aCatGroup::New()
{
int rc = 0;
qulonglong level = 0, idg=0, idp = 0;
aSQLTable * t;
aLog::print(aLog::Info, tr("aCatGroup new group"));
int err = aObject::New();
if(!err)
{
aLog::print(aLog::Info, tr( "aCatGroup new group ok"));
setSelected(true);
}
else
{
aLog::print(aLog::Error, tr("aCatGroup new group error %1").arg(err));
}
return err;
}
/*!
*\~english
* Select all groups.
* Select all groups use filter (if it's seted).
*\~russian
* \brief Выбирает все группы.
*
* Выбирает все группы используя фильтр (если он установлен).
*\~
*\return \~english Error code. \~russian Код ошибки.\~
*/
ERR_Code
aCatGroup::Select()
{
return aObject::select("");
}
/*!
*\~english
* Select all childs.
* Select childs ( not include ) for parent.
* If parent = 0 or not parent, selected all root groups.
*\~russian
* Выбирает всех потомков.
* Выбирает всех потомков (первого уровня) для группы parent.
* Если параметр отсутствует или нулевой, находятся все группы 0 - уровня.
* Навигация по выбранным записям стандартная(Next(), Prev(), First(), Last())
*\~
*\param parent - \~english parent group. \~russian родительская группа.\~
*\return \~english Error code. \~russian Код ошибки.\~
*/
ERR_Code
aCatGroup::SelectChild( aCatGroup * parent )
{
qulonglong idp = 0;
if ( parent ) idp = parent->getUid();
QString query;
query = QString("idp=%1").arg(idp);
// printf("%s\n",(const char*)query);
return select(query);
}
/*!
*\~english
* Set parent for group.
* Set for current group new parent.
* Check for cycle parent and recalc levels.
*\~russian
* Устанавливает родителя для группы.
* устанавливает текущей группе родителя переданного в качестве параметра.
* Выполняется проверка на циклическое присваивание и пересчет уровней вложенности.
*\~
*\param parent - \~english new parent group. \~russian новая родительская группа.\~
*\return \~english Error code. \~russian Код ошибки.\~
*/
ERR_Code
aCatGroup::SetParent( aCatGroup * parent )
{
aSQLTable * t = table();
if ( !t ) return err_notable;
qulonglong idp = 0, uid = getUid();
if ( parent ) idp = parent->getUid();
if ( idp == uid ) return err_cyclereparent;
qulonglong level, tmpid = idp;
aCatGroup tg( obj, db );
while ( tmpid )
{
tg.select(tmpid);
tmpid = tg.parentUid();
if ( tmpid == uid ) return err_cyclereparent;
}
QString query;
query = QString("UPDATE %1 SET idp=%2 WHERE id=%3").arg(t->tableName).arg(idp).arg(uid);
level = parent->Value("Level").toULongLong();
// printf("%s\n",(const char*)query);
QSqlDatabase tdb = *db->db();
tdb.exec(query);
if ( !tdb.lastError().type() )
{
if (idp) setLevel(level+1);
else setLevel(0);
return err_noerror;
}
else return err_execerror;
}
aCfgItem
aCatGroup::displayStringContext()
{
return md->find( md->find( obj, md_group ), md_string_view );
}
| 21.495205 | 106 | 0.665423 | [
"object"
] |
63b8b7c7cbb1e6fa13f8a654ce36290b3e989a99 | 682 | cpp | C++ | Problems/0769. Max Chunks To Make Sorted.cpp | KrKush23/LeetCode | 2a87420a65347a34fba333d46e1aa6224c629b7a | [
"MIT"
] | null | null | null | Problems/0769. Max Chunks To Make Sorted.cpp | KrKush23/LeetCode | 2a87420a65347a34fba333d46e1aa6224c629b7a | [
"MIT"
] | null | null | null | Problems/0769. Max Chunks To Make Sorted.cpp | KrKush23/LeetCode | 2a87420a65347a34fba333d46e1aa6224c629b7a | [
"MIT"
] | null | null | null | class Solution {
public:
int maxChunksToSorted(vector<int>& arr) {
// SOLUTION 1 =============================
stack<int> st;
for(auto i:arr){
int curMax = (st.empty()) ? i : max(i, st.top());
while(!st.empty() and st.top() > i)
st.pop();
st.push(curMax);
}
return st.size();
// SOLUTION 2 =============================
int cnt{0}, curMax{-1};
for(int i=0; i<arr.size(); i++){
curMax = max(curMax, arr[i]);
if(curMax == i)
cnt++;
}
return cnt;
}
};
| 24.357143 | 61 | 0.347507 | [
"vector"
] |
63bac102ee2d22eb6d7867da4d0f46d082832e06 | 2,120 | cc | C++ | Geometry/CommonTopologies/src/RectangularStripTopology.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | Geometry/CommonTopologies/src/RectangularStripTopology.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | Geometry/CommonTopologies/src/RectangularStripTopology.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #include "Geometry/CommonTopologies/interface/RectangularStripTopology.h"
#include <iostream>
#include <cmath>
#include <algorithm>
RectangularStripTopology::RectangularStripTopology(int ns, float p, float l) :
thePitch(p), theNumberOfStrips(ns), theStripLength(l) {
theOffset = -0.5f*theNumberOfStrips * thePitch;
#ifdef VERBOSE
cout <<"Constructing RectangularStripTopology with"
<<" nstrips = "<<ns
<<" pitch = "<<p
<<" length = "<<l
<<endl;
#endif
}
LocalPoint
RectangularStripTopology::localPosition(float strip) const {
return LocalPoint( strip*thePitch + theOffset, 0.0f);
}
LocalPoint
RectangularStripTopology::localPosition(const MeasurementPoint& mp) const {
return LocalPoint( mp.x()*thePitch+theOffset, mp.y()*theStripLength);
}
LocalError
RectangularStripTopology::localError(float /*strip*/, float stripErr2) const{
return LocalError(stripErr2 * thePitch*thePitch,
0.f,
theStripLength*theStripLength*(1.f/12.f));
}
LocalError
RectangularStripTopology::localError(const MeasurementPoint& /*mp*/,
const MeasurementError& merr) const{
return LocalError(merr.uu() * thePitch*thePitch,
merr.uv() * thePitch*theStripLength,
merr.vv() * theStripLength*theStripLength);
}
float
RectangularStripTopology::strip(const LocalPoint& lp) const {
float aStrip = (lp.x() - theOffset) / thePitch;
if (aStrip < 0 ) aStrip = 0;
else if (aStrip > theNumberOfStrips) aStrip = theNumberOfStrips;
return aStrip;
}
float
RectangularStripTopology::coveredStrips(const LocalPoint& lp1, const LocalPoint& lp2) const {
return (lp1.x()-lp2.x())/thePitch;
}
MeasurementPoint
RectangularStripTopology::measurementPosition(const LocalPoint& lp) const {
return MeasurementPoint((lp.x()-theOffset)/thePitch,
lp.y()/theStripLength);
}
MeasurementError
RectangularStripTopology::measurementError(const LocalPoint& /*lp*/,
const LocalError& lerr) const {
return MeasurementError(lerr.xx()/(thePitch*thePitch),
lerr.xy()/(thePitch*theStripLength),
lerr.yy()/(theStripLength*theStripLength));
}
| 29.444444 | 94 | 0.722642 | [
"geometry"
] |
63bdb96b20ff62e3e1fdb420c25bfb6c7d285bd5 | 5,698 | hpp | C++ | openstudiocore/src/openstudio_lib/YearSettingsWidget.hpp | hellok-coder/OS-Testing | e9e18ad9e99f709a3f992601ed8d2e0662175af4 | [
"blessing"
] | 1 | 2019-11-12T02:07:03.000Z | 2019-11-12T02:07:03.000Z | openstudiocore/src/openstudio_lib/YearSettingsWidget.hpp | hellok-coder/OS-Testing | e9e18ad9e99f709a3f992601ed8d2e0662175af4 | [
"blessing"
] | 1 | 2019-02-04T23:30:45.000Z | 2019-02-04T23:30:45.000Z | openstudiocore/src/openstudio_lib/YearSettingsWidget.hpp | hellok-coder/OS-Testing | e9e18ad9e99f709a3f992601ed8d2e0662175af4 | [
"blessing"
] | null | null | null | /***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2019, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************************************************/
#ifndef OPENSTUDIO_YEARSETTINGSWIDGET_HPP
#define OPENSTUDIO_YEARSETTINGSWIDGET_HPP
#include "../model/Model.hpp"
#include "../model/Model_Impl.hpp"
#include "../model/YearDescription.hpp"
#include "../model/YearDescription_Impl.hpp"
#include <nano/nano_signal_slot.hpp> // Signal-Slot replacement
#include <QRadioButton>
#include <QWidget>
class QDate;
class QDateEdit;
namespace openstudio {
class OSComboBox2;
class OSSwitch2;
class YearSettingsWidget : public QWidget, public Nano::Observer
{
Q_OBJECT
public:
static const int FIRSTYEAR;
static const int LASTYEAR;
// A list of the weeks in the month. 1st, 2nd, 3rd, 4th, Last
static std::vector<std::string> weeksInMonth();
// A list of the days in the week. Monday, Tuesday...
static std::vector<std::string> daysOfWeek();
// A list of the months.
static std::vector<std::string> months();
YearSettingsWidget(const model::Model & model, QWidget * parent = nullptr);
bool calendarYearChecked();
virtual ~YearSettingsWidget() {}
signals:
void calendarYearSelected(int year);
void firstDayofYearSelected(const QString & firstDayofYear);
void daylightSavingTimeClicked(bool enabled);
void dstStartDayOfWeekAndMonthChanged(int newWeek, int intDay, int newMonth);
void dstStartDateChanged(const QDate & newdate);
void dstEndDayOfWeekAndMonthChanged(int newWeek, int newDay, int newMonth);
void dstEndDateChanged(const QDate & newdate);
public slots:
void scheduleRefresh();
private slots:
void refresh();
void onCalendarYearChanged(int index);
void onCalendarYearButtonClicked();
void onFirstDayofYearClicked();
void onWorkspaceObjectAdd(std::shared_ptr<openstudio::detail::WorkspaceObject_Impl> wo, const openstudio::IddObjectType& type, const openstudio::UUID& uuid);
void onWorkspaceObjectRemove(std::shared_ptr<openstudio::detail::WorkspaceObject_Impl> wo, const openstudio::IddObjectType& type, const openstudio::UUID& uuid);
void onDstStartDayWeekMonthChanged();
//void onDstStartDateChanged();
void onDstEndDayWeekMonthChanged();
//void onDstEndDateChanged();
void onDefineStartByDayWeekMonthClicked();
void onDefineEndByDayWeekMonthClicked();
void onDefineStartByDateClicked();
void onDefineEndByDateClicked();
//void emitNewDSTStartDate();
//void emitNewDSTEndDate();
private:
// year selection section
QRadioButton * m_calendarYearButton = nullptr;
OSComboBox2 * m_calendarYearEdit = nullptr;
QRadioButton * m_firstDayOfYearButton = nullptr;
OSComboBox2 * m_firstDayOfYearEdit = nullptr;
// daylight savings section
OSSwitch2 * m_dstOnOffButton = nullptr;
QRadioButton * m_dayOfWeekAndMonthStartButton = nullptr;
OSComboBox2 * m_startWeekBox = nullptr;
OSComboBox2 * m_startDayBox = nullptr;
OSComboBox2 * m_startMonthBox = nullptr;
QRadioButton * m_dateStartButton = nullptr;
QDateEdit * m_startDateEdit = nullptr;
QRadioButton * m_dayOfWeekAndMonthEndButton = nullptr;
OSComboBox2 * m_endWeekBox = nullptr;
OSComboBox2 * m_endDayBox = nullptr;
OSComboBox2 * m_endMonthBox = nullptr;
QRadioButton * m_dateEndButton = nullptr;
QDateEdit * m_endDateEdit = nullptr;
// other
boost::optional<model::YearDescription> m_yearDescription;
model::Model m_model;
bool m_dirty;
};
} // openstudio
#endif // OPENSTUDIO_YEARSETTINGSWIDGET_HPP
| 30.967391 | 162 | 0.734117 | [
"vector",
"model"
] |
63bf19c79ffd44a6cf1e747095d4fe0ac8726e81 | 1,295 | cpp | C++ | C++/0073-Set-Matrix-Zeroes/soln.cpp | wyaadarsh/LeetCode-Solutions | 3719f5cb059eefd66b83eb8ae990652f4b7fd124 | [
"MIT"
] | 5 | 2020-07-24T17:48:59.000Z | 2020-12-21T05:56:00.000Z | C++/0073-Set-Matrix-Zeroes/soln.cpp | zhangyaqi1989/LeetCode-Solutions | 2655a1ffc8678ad1de6c24295071308a18c5dc6e | [
"MIT"
] | null | null | null | C++/0073-Set-Matrix-Zeroes/soln.cpp | zhangyaqi1989/LeetCode-Solutions | 2655a1ffc8678ad1de6c24295071308a18c5dc6e | [
"MIT"
] | 2 | 2020-07-24T17:49:01.000Z | 2020-08-31T19:57:35.000Z | typedef vector< int > vi;
typedef vector< vi > vvi;
typedef pair< int,int > ii;
typedef long long ll;
#define REP(i,a,b) for (int i = a; i < b; i++)
#define sz(a) int((a).size())
#define pb push_back
#define all(c) (c).begin(),(c).end()
#define tr(c,i) for(typeof((c).begin() i = (c).begin(); i != (c).end(); i++)
#define present(c,x) ((c).find(x) != (c).end())
#define cpresent(c,x) (find(all(c),x) != (c).end())
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
bool rowZero = false, colZero = false;
int m = sz(matrix), n = sz(matrix[0]);
REP(i,0,m) {
if (matrix[i][0] == 0) colZero = true;
}
REP(j,0,n) {
if (matrix[0][j] == 0) rowZero = true;
}
REP(i,1,m) {
REP(j,1,n) {
if(matrix[i][j] == 0)
matrix[i][0] = matrix[0][j] = 0;
}
}
REP(i,1,m) {
REP(j,1,n) {
if(matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
}
}
// cout << rowZero << " " << colZero << endl;
if(rowZero) {
REP(j,0,n) matrix[0][j] = 0;
}
if (colZero) {
REP(i,0,m) matrix[i][0] = 0;
}
}
};
| 28.152174 | 76 | 0.425483 | [
"vector"
] |
63c3308965ad51aa75299db0416f697296fe8aff | 2,950 | cc | C++ | soa/js/testing/js_exception_passing_module.cc | etnrlz/rtbkit | 0d9cd9e2ee2d7580a27453ad0a2d815410d87091 | [
"Apache-2.0"
] | 737 | 2015-01-04T01:40:46.000Z | 2022-03-07T10:09:23.000Z | js/testing/js_exception_passing_module.cc | leobispo/soa | 57eeddd841157250232004af9a4d69b487c43ae3 | [
"Apache-2.0"
] | 56 | 2015-01-05T16:01:03.000Z | 2020-06-22T19:02:37.000Z | js/testing/js_exception_passing_module.cc | leobispo/soa | 57eeddd841157250232004af9a4d69b487c43ae3 | [
"Apache-2.0"
] | 329 | 2015-01-01T06:54:27.000Z | 2022-02-12T22:21:02.000Z | /* v8_inheritance_module.cc -*- C++ -*-
Jeremy Barnes, 26 July 2010
Copyright (c) 2010 Datacratic. All rights reserved.
Module to test v8 inheritance from C++.
*/
#include <signal.h>
#include "soa/js/js_wrapped.h"
#include "soa/js/js_utils.h"
#include "soa/js/js_registry.h"
#include "v8.h"
#include "jml/compiler/compiler.h"
using namespace v8;
using namespace std;
using namespace Datacratic;
using namespace Datacratic::JS;
struct TestException {
};
const char * TestExceptionName = "TestException";
const char * TestModule = "exc";
struct TestExceptionJS
: public JSWrapped2<TestException, TestExceptionJS,
TestExceptionName, TestModule> {
static Persistent<v8::FunctionTemplate>
Initialize()
{
Persistent<FunctionTemplate> t = Register(New, Setup);
// Instance methods
NODE_SET_PROTOTYPE_METHOD(t, "testMlException", testMlException);
NODE_SET_PROTOTYPE_METHOD(t, "testMlException2", testMlException2);
NODE_SET_PROTOTYPE_METHOD(t, "testStdException", testStdException);
NODE_SET_PROTOTYPE_METHOD(t, "testPassThrough", testPassThrough);
return t;
}
static Handle<Value>
New(const Arguments & args)
{
try {
new TestExceptionJS();
return args.This();
} HANDLE_JS_EXCEPTIONS;
}
static Handle<Value>
testMlException(const Arguments & args)
{
try {
try {
throw ML::Exception("hello");
} catch (const ML::Exception & exc) {
//cerr << "exc is at " << &exc << endl;
throw;
}
} HANDLE_JS_EXCEPTIONS;
}
static Handle<Value>
testMlException2(const Arguments & args)
{
try {
throw ML::Exception("hello2");
} HANDLE_JS_EXCEPTIONS;
}
static Handle<Value>
testStdException(const Arguments & args)
{
try {
try {
throw std::logic_error("bad medicine");
} catch (const std::exception & exc) {
//cerr << "exc is at " << &exc << endl;
throw;
}
} HANDLE_JS_EXCEPTIONS;
}
static Handle<Value>
testPassThrough(const Arguments & args)
{
try {
v8::Local<v8::Function> fn(v8::Function::Cast(*args[0]));
if (fn.IsEmpty())
throw ML::Exception("should have gotten throwing function in");
// Call the function
v8::Handle<v8::Value> result = fn->Call(args.This(), 0, 0);
if (result.IsEmpty())
throw JSPassException();
throw ML::Exception("test was supposed to have a function that threw");
} HANDLE_JS_EXCEPTIONS;
}
};
extern "C" void
init(Handle<v8::Object> target)
{
registry.init(target, TestModule);
}
| 25.877193 | 83 | 0.573898 | [
"object"
] |
63c4454ae86ad636a4664daf076ec810d5cac4af | 1,263 | cpp | C++ | LeetCode/4. Median of Two Sorted Arrays.cpp | anubhawbhalotia/Competitive-Programming | 32d7003abf9af4999b3dfa78fe1df9022ebbf50b | [
"MIT"
] | null | null | null | LeetCode/4. Median of Two Sorted Arrays.cpp | anubhawbhalotia/Competitive-Programming | 32d7003abf9af4999b3dfa78fe1df9022ebbf50b | [
"MIT"
] | null | null | null | LeetCode/4. Median of Two Sorted Arrays.cpp | anubhawbhalotia/Competitive-Programming | 32d7003abf9af4999b3dfa78fe1df9022ebbf50b | [
"MIT"
] | 1 | 2020-05-20T18:36:31.000Z | 2020-05-20T18:36:31.000Z | class Solution {
public:
double findMedianSortedArrays(vector<int>& n1, vector<int>& n2) {
int m = n1.size(), n = n2.size(), p = (m + n - 1) / 2;
if(m == 0)
return (n2[n / 2] + n2[(n - 1) / 2]) / 2.0;
if(n == 0)
return (n1[m / 2] + n1[(m - 1) / 2]) / 2.0;
int l = max(-1, p - n - 1), r = min(p - 1, m - 1);
while(l < r)
{
int mid = floor((l + r) / 2.0);
if(mid + 1 < m && mid != (p - 1))
{
if(n1[mid + 1] < n2[p - (mid + 1) - 1])
{
l = mid + 1;
continue;
}
}
if(p - (mid + 1) < n && mid != -1)
{
if(n2[p - (mid + 1)] < n1[mid])
{
r = mid - 1;
continue;
}
}
r = mid;
}
multiset <int> s;
for(int i = l + 1; i < min(m, l + 3); i++)
s.insert(n1[i]);
for(int i = p - (l + 1); i < min(p - (l + 1) + 2, n); i++)
s.insert(n2[i]);
if((m + n) % 2 == 1)
return *s.begin();
else
return (*s.begin() + *(++s.begin())) / 2.0;
}
}; | 30.804878 | 69 | 0.292162 | [
"vector"
] |
63cf8ea491f0d26d9b40295092a2f7b778f22599 | 1,266 | hpp | C++ | src/ProgrammersGlasses/modules/INode.hpp | vividos/ProgrammersGlasses | d54f4dce46aa1db1b2fb5db8f6b00366aaf23e02 | [
"MIT"
] | 1 | 2020-05-11T11:46:38.000Z | 2020-05-11T11:46:38.000Z | src/ProgrammersGlasses/modules/INode.hpp | vividos/ProgrammersGlasses | d54f4dce46aa1db1b2fb5db8f6b00366aaf23e02 | [
"MIT"
] | null | null | null | src/ProgrammersGlasses/modules/INode.hpp | vividos/ProgrammersGlasses | d54f4dce46aa1db1b2fb5db8f6b00366aaf23e02 | [
"MIT"
] | null | null | null | //
// Programmer's Glasses - a developer's file content viewer
// Copyright (c) 2020 Michael Fink
//
/// \file INode.hpp
/// \brief single node in a tree structure of a reader
//
#pragma once
#include <vector>
#include <memory>
class IContentView;
/// Icon IDs from resources for node tree items
enum class NodeTreeIconID : UINT
{
nodeTreeIconDocument = 1024, ///< general document icon
nodeTreeIconLibrary = 1025, ///< library icon
nodeTreeIconBinary = 1026, ///< binary data icon
nodeTreeIconItem = 1027, ///< item (list item) icon
nodeTreeIconObject = 1028, ///< object (file) icon
nodeTreeIconTable = 1029, ///< table icon
};
/// \brief Node interface
/// \details specifies one node in the file's tree node structure
class INode
{
public:
/// dtor
virtual ~INode() noexcept {}
/// returns a display name for the node
virtual const CString& DisplayName() const = 0;
/// returns the node tree icon ID
virtual NodeTreeIconID IconID() const = 0;
/// Returns the list of child nodes of the file tree
virtual const std::vector<std::shared_ptr<INode>>& ChildNodes() const = 0;
/// returns a content view to display the node's data
virtual std::shared_ptr<IContentView> GetContentView() = 0;
};
| 27.521739 | 77 | 0.683254 | [
"object",
"vector"
] |
63d178f3e2d5311195ada89a68db19423bfebcf1 | 7,933 | cpp | C++ | dev/Code/Framework/AzFramework/AzFramework/Scene/SceneSystemComponent.cpp | pawandayma/lumberyard | e178f173f9c21369efd8c60adda3914e502f006a | [
"AML"
] | 1,738 | 2017-09-21T10:59:12.000Z | 2022-03-31T21:05:46.000Z | dev/Code/Framework/AzFramework/AzFramework/Scene/SceneSystemComponent.cpp | olivier-be/lumberyard | 3d688932f919dbf5821f0cb8a210ce24abe39e9e | [
"AML"
] | 427 | 2017-09-29T22:54:36.000Z | 2022-02-15T19:26:50.000Z | dev/Code/Framework/AzFramework/AzFramework/Scene/SceneSystemComponent.cpp | olivier-be/lumberyard | 3d688932f919dbf5821f0cb8a210ce24abe39e9e | [
"AML"
] | 671 | 2017-09-21T08:04:01.000Z | 2022-03-29T14:30:07.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <AzFramework/Scene/SceneSystemComponent.h>
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
#include <AzFramework/Scene/Scene.h>
namespace AzFramework
{
void SceneSystemComponent::Reflect(AZ::ReflectContext* context)
{
if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
{
serializeContext->Class<SceneSystemComponent, AZ::Component>();
if (AZ::EditContext* editContext = serializeContext->GetEditContext())
{
editContext->Class<SceneSystemComponent>(
"Scene System Component", "System component responsible for owning scenes")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::Category, "Editor")
->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System", 0xc94d118b))
;
}
}
}
SceneSystemComponent::SceneSystemComponent() = default;
SceneSystemComponent::~SceneSystemComponent() = default;
void SceneSystemComponent::Activate()
{
// Connect busses
SceneSystemRequestBus::Handler::BusConnect();
}
void SceneSystemComponent::Deactivate()
{
// Disconnect Busses
SceneSystemRequestBus::Handler::BusDisconnect();
}
void SceneSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
{
provided.push_back(AZ_CRC("SceneSystemComponentService", 0xd8975435));
}
void SceneSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
{
incompatible.push_back(AZ_CRC("SceneSystemComponentService", 0xd8975435));
}
AZ::Outcome<Scene*, AZStd::string> SceneSystemComponent::CreateScene(AZStd::string_view name)
{
Scene* existingScene = GetScene(name);
if (existingScene)
{
return AZ::Failure<AZStd::string>("A scene already exists with this name.");
}
auto newScene = AZStd::make_unique<Scene>(name);
Scene* scenePointer = newScene.get();
m_scenes.push_back(AZStd::move(newScene));
SceneSystemNotificationBus::Broadcast(&SceneSystemNotificationBus::Events::SceneCreated, *scenePointer);
return AZ::Success(scenePointer);
}
Scene* SceneSystemComponent::GetScene(AZStd::string_view name)
{
auto sceneIterator = AZStd::find_if(m_scenes.begin(), m_scenes.end(),
[name](auto& scene) -> bool
{
return scene->GetName() == name;
}
);
return sceneIterator == m_scenes.end() ? nullptr : sceneIterator->get();
}
AZStd::vector<Scene*> SceneSystemComponent::GetAllScenes()
{
AZStd::vector<Scene*> scenes;
scenes.resize_no_construct(m_scenes.size());
for (size_t i = 0; i < m_scenes.size(); ++i)
{
scenes.at(i) = m_scenes.at(i).get();
}
return scenes;
}
bool SceneSystemComponent::RemoveScene(AZStd::string_view name)
{
for (size_t i = 0; i < m_scenes.size(); ++i)
{
auto& scenePtr = m_scenes.at(i);
if (scenePtr->GetName() == name)
{
// Remove any entityContext mappings.
Scene* scene = scenePtr.get();
for (auto entityContextScenePairIt = m_entityContextToScenes.begin(); entityContextScenePairIt != m_entityContextToScenes.end();)
{
AZStd::pair<EntityContextId, Scene*>& pair = *entityContextScenePairIt;
if (pair.second == scene)
{
// swap and pop back.
*entityContextScenePairIt = m_entityContextToScenes.back();
m_entityContextToScenes.pop_back();
}
else
{
++entityContextScenePairIt;
}
}
SceneSystemNotificationBus::Broadcast(&SceneSystemNotificationBus::Events::SceneAboutToBeRemoved, *scene);
SceneNotificationBus::Event(scene, &SceneNotificationBus::Events::SceneAboutToBeRemoved);
m_scenes.erase(&scenePtr);
return true;
}
}
AZ_Warning("SceneSystemComponent", false, "Attempting to remove scene name \"%.*s\", but that scene was not found.", static_cast<int>(name.size()), name.data());
return false;
}
bool SceneSystemComponent::SetSceneForEntityContextId(EntityContextId entityContextId, Scene* scene)
{
Scene* existingSceneForEntityContext = GetSceneFromEntityContextId(entityContextId);
if (existingSceneForEntityContext)
{
// This entity context is already mapped and must be unmapped explictely before it can be changed.
char entityContextIdString[EntityContextId::MaxStringBuffer];
entityContextId.ToString(entityContextIdString, sizeof(entityContextIdString));
AZ_Warning("SceneSystemComponent", false, "Failed to set a scene for entity context %s, scene is already set for that entity context.", entityContextIdString);
return false;
}
m_entityContextToScenes.emplace_back(entityContextId, scene);
SceneNotificationBus::Event(scene, &SceneNotificationBus::Events::EntityContextMapped, entityContextId);
return true;
}
bool SceneSystemComponent::RemoveSceneForEntityContextId(EntityContextId entityContextId, Scene* scene)
{
if (!scene || entityContextId.IsNull())
{
return false;
}
for (auto entityContextScenePairIt = m_entityContextToScenes.begin(); entityContextScenePairIt != m_entityContextToScenes.end();)
{
AZStd::pair<EntityContextId, Scene*>& pair = *entityContextScenePairIt;
if (!(pair.first == entityContextId && pair.second == scene))
{
++entityContextScenePairIt;
}
else
{
// swap and pop back.
*entityContextScenePairIt = m_entityContextToScenes.back();
m_entityContextToScenes.pop_back();
SceneNotificationBus::Event(scene, &SceneNotificationBus::Events::EntityContextUnmapped, entityContextId);
return true;
}
}
char entityContextIdString[EntityContextId::MaxStringBuffer];
entityContextId.ToString(entityContextIdString, sizeof(entityContextIdString));
AZ_Warning("SceneSystemComponent", false, "Failed to remove scene \"%.*s\" for entity context %s, entity context is not currently mapped to that scene.", static_cast<int>(scene->GetName().size()), scene->GetName().data(), entityContextIdString);
return false;
}
Scene* SceneSystemComponent::GetSceneFromEntityContextId(EntityContextId entityContextId)
{
for (AZStd::pair<EntityContextId, Scene*>& pair : m_entityContextToScenes)
{
if (pair.first == entityContextId)
{
return pair.second;
}
}
return nullptr;
}
} // AzFramework | 39.665 | 253 | 0.629522 | [
"vector"
] |
63d3530c9e328bdc3bbd40174d507ea50bc7fe17 | 11,298 | cpp | C++ | qmf/wals/WALSEngine.cpp | taozhijiang/qmf | ed2a46222f7e6113b61fb36ce669190ed6e0965a | [
"Apache-2.0"
] | 1 | 2020-05-03T09:23:58.000Z | 2020-05-03T09:23:58.000Z | qmf/wals/WALSEngine.cpp | taozhijiang/qmf | ed2a46222f7e6113b61fb36ce669190ed6e0965a | [
"Apache-2.0"
] | null | null | null | qmf/wals/WALSEngine.cpp | taozhijiang/qmf | ed2a46222f7e6113b61fb36ce669190ed6e0965a | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2016 Quora, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <algorithm>
#include <random>
#include <omp.h>
#include <qmf/wals/WALSEngine.h>
namespace qmf {
WALSEngine::WALSEngine(const WALSConfig& config,
const std::unique_ptr<MetricsEngine>& metricsEngine,
const size_t nthreads)
: config_(config), metricsEngine_(metricsEngine), parallel_(nthreads) {
if (metricsEngine_ && !metricsEngine_->testAvgMetrics().empty() &&
metricsEngine_->config().numTestUsers == 0) {
LOG(WARNING) << "computing average test metrics on all users can be slow! "
"Set numTestUsers > 0 to sample some of them";
}
}
void WALSEngine::init(const std::vector<DatasetElem>& dataset) {
CHECK(!userFactors_ && !itemFactors_)
<< "engine was already initialized with train data";
auto mutableDataset = dataset;
groupSignals(userSignals_, userIndex_, mutableDataset);
// swap userId with itemId
for (auto& elem : mutableDataset) {
// g++ will complain for "cannot bind packed field to xxx&"
#if !defined(__GNUC__)
std::swap(elem.userId, elem.itemId);
#else
auto tmp = elem.userId;
elem.userId = elem.itemId;
elem.itemId = tmp;
#endif
}
groupSignals(itemSignals_, itemIndex_, mutableDataset);
userFactors_ = std::make_unique<FactorData>(nusers(), config_.nfactors);
itemFactors_ = std::make_unique<FactorData>(nitems(), config_.nfactors);
if (config_.DistributionFile.empty()) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<Double> distr(
-config_.initDistributionBound, config_.initDistributionBound);
auto genUnif = [&distr, &gen](auto...) { return distr(gen); };
// don't need to initialize user factors
itemFactors_->setFactors(genUnif);
} else {
itemFactors_->setFactors(config_.DistributionFile);
}
}
void WALSEngine::initTest(const std::vector<DatasetElem>& testDataset) {
CHECK(testUsers_.empty()) << "engine was already initialized with test data";
// initialize data for test average metrics
if (metricsEngine_ && !metricsEngine_->testAvgMetrics().empty()) {
initAvgTestData(
testUsers_, testLabels_, testScores_, testDataset, userIndex_, itemIndex_,
metricsEngine_->config().numTestUsers, metricsEngine_->config().seed);
}
}
void WALSEngine::optimize() {
CHECK(userFactors_ && itemFactors_)
<< "no factor data, have you initialized the engine?";
for (size_t epoch = 1; epoch <= config_.nepochs; ++epoch) {
// fix item factors, update user factors
iterate(*userFactors_, userIndex_, userSignals_, *itemFactors_, itemIndex_);
// fix user factors, update item factors
const Double loss = iterate(
*itemFactors_, itemIndex_, itemSignals_, *userFactors_, userIndex_);
LOG(INFO) << "epoch " << epoch << ": train loss = " << loss;
// evaluate
evaluate(epoch);
}
}
void WALSEngine::evaluate(const size_t epoch) {
// evaluate test average metrics
if (metricsEngine_ && !metricsEngine_->testAvgMetrics().empty() &&
!testUsers_.empty() &&
(metricsEngine_->config().alwaysCompute || epoch == config_.nepochs)) {
LOG(INFO) << "do compute evaluate ..." << std::endl;
computeTestScores(
testScores_, testUsers_, *userFactors_, *itemFactors_, parallel_);
metricsEngine_->computeAndRecordTestAvgMetrics(
epoch, testLabels_, testScores_, parallel_);
}
}
void WALSEngine::saveUserFactors(const std::string& fileName) const {
CHECK(userFactors_) << "user factors wasn't initialized";
saveFactors(*userFactors_, userIndex_, fileName);
}
void WALSEngine::saveItemFactors(const std::string& fileName) const {
CHECK(itemFactors_) << "item factors wasn't initialized";
saveFactors(*itemFactors_, itemIndex_, fileName);
}
size_t WALSEngine::nusers() const {
return userIndex_.size();
}
size_t WALSEngine::nitems() const {
return itemIndex_.size();
}
void WALSEngine::groupSignals(std::vector<SignalGroup>& signals,
IdIndex& index,
std::vector<DatasetElem>& dataset) {
sortDataset(dataset);
const int64_t InvalidId = std::numeric_limits<int64_t>::min();
int64_t prevId = InvalidId;
std::vector<Signal> group;
for (const auto& elem : dataset) {
if (elem.userId != prevId) {
if (prevId != InvalidId) {
signals.emplace_back(SignalGroup{prevId, group});
}
prevId = elem.userId;
group.clear();
}
group.emplace_back(Signal{elem.itemId, elem.value});
}
if (prevId != InvalidId) {
signals.emplace_back(SignalGroup{prevId, group});
}
for (size_t i = 0; i < signals.size(); ++i) {
const size_t idx = index.getOrSetIdx(signals[i].sourceId);
CHECK_EQ(idx, i);
}
}
void WALSEngine::sortDataset(std::vector<DatasetElem>& dataset) {
std::sort(dataset.begin(), dataset.end(), [](const auto& x, const auto& y) {
if (x.userId != y.userId) {
return x.userId < y.userId;
}
return x.itemId < y.itemId;
});
}
Double WALSEngine::iterate(FactorData& leftData,
const IdIndex& leftIndex,
const std::vector<SignalGroup>& leftSignals,
const FactorData& rightData,
const IdIndex& rightIndex) {
auto genZero = [](auto...) { return 0.0; };
leftData.setFactors(genZero);
Matrix& X = leftData.getFactors();
const Matrix& Y = rightData.getFactors();
// Matrix YtY = computeXtX(Y);
Matrix YtY(X.ncols(), X.ncols());
computeXtX(Y, &YtY);
#if 0
// omp_set_num_threads(16);
const size_t count = leftSignals.size();
Double loss = 0.0;
const auto alpha = config_.confidenceWeight;
const auto lambda = config_.regularizationLambda;
#pragma omp parallel reduction(+ : loss)
{
#pragma omp for
for (size_t i = 0; i < count; ++i) {
const size_t leftIdx = leftIndex.idx(leftSignals[i].sourceId);
loss += updateFactorsForOne(X.data(leftIdx), X.ncols(), Y, rightIndex,
leftSignals[i], YtY, alpha, lambda);
}
}
return loss / nusers() / nitems();
#else
auto map = [&X, &leftIndex, &Y, &rightIndex, &leftSignals, YtY,
alpha = config_.confidenceWeight,
lambda = config_.regularizationLambda](const size_t taskId) {
return updateFactorsForOne(
X, leftIndex, Y, rightIndex, leftSignals[taskId], YtY, alpha, lambda);
};
auto reduce = [](Double sum, Double x) { return sum + x; };
Double loss = parallel_.mapReduce(leftSignals.size(), map, reduce, 0.0);
return loss / nusers() / nitems();
#endif
}
Matrix WALSEngine::computeXtX(const Matrix& X) {
const size_t nrows = X.nrows();
const size_t ntasks = parallel_.nthreads();
const size_t taskSize = (nrows + ntasks - 1) / ntasks;
auto map = [&X, taskSize](const size_t taskId) {
const size_t ncols = X.ncols();
Matrix XtX(ncols, ncols);
const size_t l = taskId * taskSize;
const size_t r = std::min(X.nrows(), (taskId + 1) * taskSize);
for (size_t k = l; k < r; ++k) {
for (size_t i = 0; i < ncols; ++i) {
for (size_t j = 0; j < ncols; ++j) {
XtX(i, j) += X(k, i) * X(k, j);
}
}
}
return XtX;
};
auto reduce = [](const Matrix& S, const Matrix& X) { return S + X; };
Matrix O(X.ncols(), X.ncols());
return parallel_.mapReduce(ntasks, map, reduce, O);
}
void WALSEngine::computeXtX(const Matrix& X, Matrix* out) {
// assert X and out samesize
// omp_set_num_threads(16);
out->clear();
const size_t nrows = X.nrows();
const size_t ncols = X.ncols();
#pragma omp parallel for
for (size_t k = 0; k < nrows; ++k) {
for (size_t i = 0; i < ncols; ++i) {
for (size_t j = 0; j < ncols; ++j) {
(*out)(i, j) += X(k, i) * X(k, j);
}
}
}
}
Double WALSEngine::updateFactorsForOne(Matrix& X,
const IdIndex& leftIndex,
const Matrix& Y,
const IdIndex& rightIndex,
const SignalGroup& signalGroup,
Matrix A,
const Double alpha,
const Double lambda) {
Double loss = 0.0;
const size_t n = X.ncols();
Vector b(n);
for (const auto& signal : signalGroup.group) {
const size_t rightIdx = rightIndex.idx(signal.id);
for (size_t i = 0; i < n; ++i) {
b(i) += Y(rightIdx, i) * (1.0 + alpha * signal.value);
for (size_t j = 0; j < n; ++j) {
A(i, j) += Y(rightIdx, i) * alpha * signal.value * Y(rightIdx, j);
}
}
// for term p^t * C * p
loss += 1.0 + alpha * signal.value;
}
// B = Y^t * C * Y
Matrix B = A;
for (size_t i = 0; i < n; ++i) {
A(i, i) += lambda;
}
// A * x = b
Vector x = linearSymmetricSolve(A, b);
// x^t * Y^t * C * Y * x
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < n; ++j) {
loss += B(i, j) * x(i) * x(j);
}
}
// -2 * x^t * Y^t * C * p
for (size_t i = 0; i < n; ++i) {
loss -= 2 * x(i) * b(i);
}
const size_t leftIdx = leftIndex.idx(signalGroup.sourceId);
for (size_t i = 0; i < n; ++i) {
X(leftIdx, i) = x(i);
}
return loss;
}
Double WALSEngine::updateFactorsForOne(Double* result,
const size_t n,
const Matrix& Y,
const IdIndex& rightIndex,
const SignalGroup& signalGroup,
Matrix A,
const Double alpha,
const Double lambda) {
Double loss = 0.0;
Vector b(n);
for (const auto& signal : signalGroup.group) {
const size_t rightIdx = rightIndex.idx(signal.id);
for (size_t i = 0; i < n; ++i) {
b(i) += Y(rightIdx, i) * (1.0 + alpha * signal.value);
for (size_t j = 0; j < n; ++j) {
A(i, j) += Y(rightIdx, i) * alpha * signal.value * Y(rightIdx, j);
}
}
// for term p^t * C * p
loss += 1.0 + alpha * signal.value;
}
// B = Y^t * C * Y
Matrix B = A;
for (size_t i = 0; i < n; ++i) {
A(i, i) += lambda;
}
// A * x = b
Vector x = linearSymmetricSolve(A, b);
// x^t * Y^t * C * Y * x
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < n; ++j) {
loss += B(i, j) * x(i) * x(j);
}
}
// -2 * x^t * Y^t * C * p
for (size_t i = 0; i < n; ++i) {
loss -= 2 * x(i) * b(i);
}
for (size_t i = 0; i < n; ++i) {
*(result + i) = x(i);
}
return loss;
}
} // namespace qmf
| 31.558659 | 80 | 0.589839 | [
"vector"
] |
63d8e67fbaf0da7f44b180964a26a6544effd201 | 3,549 | cpp | C++ | leetcode/algorithms/bfs/Q200-number-of-islands.cpp | jatin69/Revision-cpp | 52742ea76ee2440d92b116252399360fef46e0c7 | [
"MIT"
] | 4 | 2020-01-16T14:49:46.000Z | 2021-08-23T12:45:19.000Z | leetcode/algorithms/bfs/Q200-number-of-islands.cpp | jatin69/coding-practice | 52742ea76ee2440d92b116252399360fef46e0c7 | [
"MIT"
] | 2 | 2018-06-06T13:08:11.000Z | 2018-10-02T19:07:32.000Z | leetcode/algorithms/bfs/Q200-number-of-islands.cpp | jatin69/coding-practice | 52742ea76ee2440d92b116252399360fef46e0c7 | [
"MIT"
] | 5 | 2018-10-02T13:49:16.000Z | 2021-08-11T07:29:50.000Z | /*
* Author : Jatin Rohilla
* Date : June-July-2019
*
* Compiler : g++ 5.1.0
* flags : -std=c++14
*/
#include<bits/stdc++.h>
using namespace std;
// better - 12ms
class Solution {
public:
void capture(vector<vector<char>>& grid, int i, int j){
if(i<0 || j<0 || i>=grid.size() || j>=grid[0].size()){
return;
}
if(grid[i][j]!='1'){
return;
}
grid[i][j] = '2';
capture(grid, i, j+1);
capture(grid, i, j-1);
capture(grid, i+1, j);
capture(grid, i-1, j);
}
int numIslands(vector<vector<char>>& grid) {
int noOfIslands = 0;
for(int i=0; i<grid.size(); ++i){
for(int j = 0; j<grid[0].size(); ++j){
if(grid[i][j]=='1'){
noOfIslands++;
capture(grid, i, j);
}
}
}
return noOfIslands;
}
};
// naive - 84ms
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
// edge case
if(grid.size()==0){
return 0;
}
int init_i = 0;
int init_j = 0;
int i;
int j;
int noOfIslands = 0;
queue<pair<int, int>> q;
set<pair<int, int>> s;
while(1){
if(q.empty()){
bool flag = false;
i = init_i;
j = init_j;
while(i < grid.size()){
while(j < grid[0].size()){
cout << "checking : i is " << i << " and j is " << j << "\n";
if(s.find({i, j})==s.end() && grid[i][j]=='1'){
flag = true;
break;
}
j++;
}
if(flag){
break;
}
i++;
j = 0;
}
cout << "i is " << i << " and j is " << j << "\n";
if(i==grid.size()){
break;
}
init_i = i;
init_j = j+2;
noOfIslands++;
q.push({i, j});
s.insert({i, j});
}
std::tie(i, j) = q.front(); q.pop();
// cout << "popped : i is " << i << " and j is " << j << "\n";
// top
if( i-1 >=0 && grid[i-1][j]=='1' && s.find({i-1, j})==s.end() ){
// cout << "process : i is " << i+1 << " and j is " << j << "\n";
q.push({i-1, j});
s.insert({i-1, j});
}
// bottom
if( i+1 < grid.size() && grid[i+1][j]=='1' && s.find({i+1, j})==s.end() ){
// cout << "process : i is " << i+1 << " and j is " << j << "\n";
q.push({i+1, j});
s.insert({i+1, j});
}
// left
if( j-1 >=0 && grid[i][j-1]=='1' && s.find({i, j-1})==s.end() ){
// cout << "process : i is " << i << " and j is " << j+1 << "\n";
q.push({i, j-1});
s.insert({i, j-1});
}
// right
if( j+1 < grid[0].size() && grid[i][j+1]=='1' && s.find({i, j+1})==s.end() ){
// cout << "process : i is " << i << " and j is " << j+1 << "\n";
q.push({i, j+1});
s.insert({i, j+1});
}
}
return noOfIslands;
}
};
| 26.288889 | 91 | 0.32009 | [
"vector"
] |
63da7fb3464b24646f48b7b3763c1e60766624ee | 1,697 | cc | C++ | src/lib.cc | rbrisita/node-ntsuspend | 1ad2b43b156dfaa893f750c201f0681b2c87106b | [
"MIT"
] | 4 | 2021-05-28T23:53:29.000Z | 2021-12-16T02:38:03.000Z | src/lib.cc | rbrisita/node-ntsuspend | 1ad2b43b156dfaa893f750c201f0681b2c87106b | [
"MIT"
] | 2 | 2021-05-28T23:58:13.000Z | 2021-11-08T17:20:10.000Z | src/lib.cc | rbrisita/node-ntsuspend | 1ad2b43b156dfaa893f750c201f0681b2c87106b | [
"MIT"
] | 1 | 2021-06-17T05:13:19.000Z | 2021-06-17T05:13:19.000Z | #include <windows.h>
#include <napi.h>
#include <math.h>
#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)
typedef NTSTATUS (NTAPI *pNtSuspendProcess)(IN HANDLE ProcessHandle);
static pNtSuspendProcess NtSuspendProcess;
static pNtSuspendProcess NtResumeProcess;
static inline bool ntsuspend(const Napi::Value pid, pNtSuspendProcess suspend_or_resume) {
if (!pid.IsNumber()) {
return false;
}
const auto number_pid = pid.ToNumber();
const auto double_pid = number_pid.DoubleValue();
const DWORD dword_pid = number_pid.Uint32Value();
if (isnan(double_pid) || !isfinite(double_pid) || (double) dword_pid != double_pid) {
return false;
}
const HANDLE process_handle = OpenProcess(PROCESS_SUSPEND_RESUME, FALSE, dword_pid);
if (process_handle == NULL) {
return false;
}
const NTSTATUS status = suspend_or_resume(process_handle);
CloseHandle(process_handle);
return NT_SUCCESS(status);
}
static inline Napi::Boolean suspend(const Napi::CallbackInfo& info) {
return Napi::Boolean::New(info.Env(), ntsuspend(info[0], NtSuspendProcess));
}
static inline Napi::Boolean resume(const Napi::CallbackInfo& info) {
return Napi::Boolean::New(info.Env(), ntsuspend(info[0], NtResumeProcess));
}
static Napi::Object init(Napi::Env env, Napi::Object exports) {
const HMODULE ntdll = GetModuleHandle("ntdll");
NtSuspendProcess = (pNtSuspendProcess)GetProcAddress(ntdll, "NtSuspendProcess");
NtResumeProcess = (pNtSuspendProcess)GetProcAddress(ntdll, "NtResumeProcess");
exports.Set("suspend", Napi::Function::New(env, suspend));
exports.Set("resume", Napi::Function::New(env, resume));
return exports;
}
NODE_API_MODULE(NODE_GYP_MODULE_NAME, init)
| 33.27451 | 90 | 0.746022 | [
"object"
] |
63dc26ef0ba12bef8e258dc2ed364af16285a9b1 | 32,035 | hpp | C++ | include/bencode/detail/bvalue/basic_bvalue.hpp | fbdtemme/bencode | edf7dd5b580c44723821dbf737c8412d628294e4 | [
"MIT"
] | 25 | 2020-08-24T01:54:10.000Z | 2021-12-22T08:55:54.000Z | include/bencode/detail/bvalue/basic_bvalue.hpp | fbdtemme/bencode | edf7dd5b580c44723821dbf737c8412d628294e4 | [
"MIT"
] | 1 | 2021-12-29T05:38:56.000Z | 2021-12-29T05:38:56.000Z | include/bencode/detail/bvalue/basic_bvalue.hpp | fbdtemme/bencode | edf7dd5b580c44723821dbf737c8412d628294e4 | [
"MIT"
] | 4 | 2020-08-18T19:31:26.000Z | 2022-02-01T18:57:51.000Z | #pragma once
#include <compare>
#include <iosfwd>
#include <limits>
#include <type_traits>
#include <variant>
#include <fmt/format.h>
#include "bencode/detail/concepts.hpp"
#include "bencode/detail/utils.hpp"
#include "bencode/detail/bad_conversion.hpp"
#include "bencode/detail/bencode_type.hpp"
#include "bencode/detail/bvalue/bvalue_policy.hpp"
#include "bencode/detail/out_of_range.hpp"
#include "bencode/detail/bvalue/accessors.hpp"
#include "bencode/detail/bvalue/assignment.hpp"
#include "bencode/detail/bvalue/comparison.hpp"
namespace bencode {
namespace detail {
/// Helper function for private access to storage object
template <typename Policy>
constexpr const auto& get_storage(const basic_bvalue<Policy>& value) noexcept;
template <typename Policy>
constexpr auto& get_storage(basic_bvalue<Policy>& value) noexcept;
template <typename Policy>
constexpr const auto* get_storage(const basic_bvalue<Policy>* value) noexcept;
template <typename Policy>
constexpr auto* get_storage(basic_bvalue<Policy>* value) noexcept;
#if defined(_MSC_VER)
// forward declarations
template <typename U, typename Policy, typename T>
requires serializable<T>
inline void assign_to_bvalue(basic_bvalue<Policy>& bvalue, U&& value);
#else
// forward declarations
template <typename U, typename Policy, typename T = std::remove_cvref_t<U>>
requires serializable<T>
inline void assign_to_bvalue(basic_bvalue<Policy>& bvalue, U&& value);
#endif
template <basic_bvalue_instantiation BV>
decltype(auto) evaluate(const bpointer& pointer, BV&& bv);
template <basic_bvalue_instantiation BV>
bool contains(const bpointer& pointer, const BV& bv);
} // namespace detail
/// A class template storing a bencoded bvalue.
///
/// An instance of basic_bvalue at any given time either holds a bvalue of one of the
/// bencode data types, or uninitialized_type in the case of error or no bvalue.
/// A single bvalue can store large and complicated bencoded data structures consisting
/// of arbitrarily nested lists and dicts with many sub-values, that are again bvalue instances.
///
/// @tparam Policy instantation of bvalue_policy to defining the storage types
template <typename Policy>
class basic_bvalue
{
public:
using policy_type = Policy;
// storage type aliasesPolicy
using uninitialized_type = detail::policy_uninitialized_t<policy_type>;
using integer_type = detail::policy_integer_t<policy_type>;
using string_type = detail::policy_string_t<policy_type>;
using list_type = detail::policy_list_t<policy_type>;
using dict_type = detail::policy_dict_t<policy_type>;
using string_init_list = detail::policy_string_init_list_t<policy_type>;
using list_init_list = detail::policy_list_init_list_t<policy_type>;
using dict_init_list = detail::policy_dict_init_list_t<policy_type>;
using reference = basic_bvalue<policy_type>&;
using pointer = basic_bvalue<policy_type>*;
using const_reference = const basic_bvalue<policy_type>&;
using const_pointer = const basic_bvalue<policy_type>*;
// iterator aliases
using list_iterator = typename list_type::iterator;
using list_const_iterator = typename list_type::const_iterator;
using list_reverse_iterator = typename list_type::reverse_iterator;
using list_const_reverse_iterator = typename list_type::const_reverse_iterator;
using dict_iterator = typename dict_type::iterator;
using dict_const_iterator = typename dict_type::const_iterator;
using dict_reverse_iterator = typename dict_type::reverse_iterator;
using dict_const_reverse_iterator = typename dict_type::const_reverse_iterator;
using storage_type = std::variant<uninitialized_type,
integer_type,
string_type,
list_type,
dict_type>;
using dict_value_type = typename dict_type::value_type;
using dict_key_type = typename dict_type::key_type;
using list_value_type = typename list_type::value_type;
using string_value_type = typename string_type::value_type;
constexpr basic_bvalue() noexcept = default;
constexpr basic_bvalue(const basic_bvalue& other) noexcept(std::is_nothrow_copy_constructible_v<storage_type>) = default;
constexpr basic_bvalue(basic_bvalue&& other) noexcept(std::is_nothrow_move_constructible_v<storage_type>) = default;
basic_bvalue(dict_init_list il)
: basic_bvalue(dict_type{})
{
auto& bdict = *std::get_if<dict_type>(&storage_);
for (auto&& elem: il) {
bdict[std::move(elem.first)] = std::move(elem.second);
}
}
//===========================================================================//
// converting copy/move constructors //
//===========================================================================//
/// Copy/move constructor for exact matches to one of the storage_types
template <typename U, typename T = std::remove_cvref_t<U>>
/// \cond CONCEPTS
requires bvalue_alternative_type<T, basic_bvalue>
/// \endcond
constexpr basic_bvalue(U&& v)
noexcept(noexcept(storage_type(std::in_place_type<std::remove_cvref_t<T>>, std::forward<U>(v))))
: storage_(std::in_place_type<T>, std::forward<U>(v))
{}
/// Copy/move constructor for types that can be converted to bvalue using built-in conversions
/// or used defined types that implement are convertible to bvalue though
/// bencode_assign_to_bvalue().
template <typename U, typename T = std::remove_cvref_t<U>>
/// \cond CONCEPTS
requires (!basic_bvalue_instantiation<T>) &&
(!bvalue_alternative_type<T, basic_bvalue>) &&
serializable<T>
/// \endcond
constexpr basic_bvalue(U&& v)
noexcept(noexcept(detail::assign_to_bvalue(std::declval<basic_bvalue&>(), std::forward<U>(v))))
{
detail::assign_to_bvalue(*this, std::forward<U>(v));
}
template <bencode_type T, typename... Args>
/// \cond CONCEPTS
requires std::constructible_from<bvalue_alternative_t<T, basic_bvalue>, Args...>
/// \endcond
explicit constexpr basic_bvalue(bencode_type_tag<T>, Args&& ... args)
: storage_(std::in_place_type<bvalue_alternative_t<T, basic_bvalue>>,
std::forward<Args>(args)...)
{};
template <bencode_type T, typename... Args>
/// \cond CONCEPTS
requires std::constructible_from<string_type, string_init_list, Args...> && (T == bencode_type::string)
/// \endcond
explicit constexpr basic_bvalue(bencode_type_tag<T>,
string_init_list il,
Args&& ... args)
: storage_(std::in_place_type<bvalue_alternative_t<T, basic_bvalue>>,
std::move(il), std::forward<Args>(args)...)
{};
template <bencode_type T, typename... Args>
/// \cond CONCEPTS
requires std::constructible_from<list_type, list_init_list, Args...> && (T == bencode_type::list)
/// \endcond
explicit constexpr basic_bvalue(bencode_type_tag<T>,
list_init_list il,
Args&& ... args)
: storage_(std::in_place_type<list_type>,
std::move(il), std::forward<Args>(args)...)
{};
template <bencode_type T, typename... Args, typename = std::enable_if_t<T == bencode_type::dict>>
/// \cond CONCEPTS
requires std::constructible_from<dict_type, dict_init_list, Args...>
/// \endcond
explicit constexpr basic_bvalue(bencode_type_tag<T>,
dict_init_list il,
Args&& ... args)
: storage_(std::in_place_type<dict_type>,
std::move(il), std::forward<Args>(args)...)
{};
//===========================================================================//
// copy/move assignment and swap operators //
//===========================================================================//
public:
// TODO: add converting assignment operator instead of current implicit construction + move
constexpr basic_bvalue& operator=(const basic_bvalue& rhs) = default;
constexpr basic_bvalue& operator=(basic_bvalue&& rhs) noexcept(std::is_nothrow_move_assignable_v<storage_type>) = default;
template <typename T>
/// \cond CONCEPTS
requires bvalue_alternative_type<std::remove_cvref_t<T>, basic_bvalue>
/// \endcond
basic_bvalue& operator=(T&& rhs) {
// only forward exact alternative types to the variant assignment operator
// all other types will pass through the traits_old interface to determine
// the result of an assignment operation.
storage_.operator=(std::forward<T>(rhs));
return *this;
}
public:
/// Discards the current active alternative and sets the storage to the uninitialized state.
void discard()
{
storage_.template emplace<uninitialized_type>();
}
//===========================================================================//
// Emplace a variant type in an existing object //
//===========================================================================//
/// Construct an integer in place.
/// @param args arguments to forward to the integer alternative constructor.
/// @returns A reference to the new contained bvalue.
template <typename... Args>
/// \cond CONCEPTS
requires std::constructible_from<integer_type, Args...>
/// \endcond
constexpr integer_type& emplace_integer(Args&&... args)
{
return storage_.template emplace<integer_type>(std::forward<Args>(args)...);
}
/// Construct a string in place.
/// @param args arguments to forward to the integer alternative constructor.
/// @returns A reference to the new contained bvalue.
template <typename... Args>
/// \cond CONCEPTS
requires std::constructible_from<string_type, Args...>
/// \endcond
string_type& emplace_string(Args&&... args)
{
return storage_.template emplace<string_type>(std::forward<Args>(args)...);
}
/// @copydoc emplace_string()
template <typename... Args>
/// \cond CONCEPTS
requires std::constructible_from<string_type, string_init_list, Args...>
/// \endcond
string_type& emplace_string(string_init_list il, Args&&... args)
{
return storage_.template emplace<string_type>(std::move(il), std::forward<Args>(args)...);
}
/// Construct a list in place.
/// @param args arguments to forward to the list alternative constructor.
/// @returns A reference to the new contained bvalue.
template <typename... Args>
/// \cond CONCEPTS
requires std::constructible_from<list_type, Args...>
/// \endcond
list_type& emplace_list(Args&&... args)
{
return storage_.template emplace<list_type>(std::forward<Args>(args)...);
}
/// @copydoc emplace_list()
template <typename... Args>
/// \cond CONCEPTS
requires std::constructible_from<list_type, list_init_list, Args...>
/// \endcond
list_type& emplace_list(list_init_list il, Args&&... args)
{
return storage_.template emplace<list_type>(std::move(il), std::forward<Args>(args)...);
}
/// Construct a dict in place.
/// @param args arguments to forward to the dict alternative constructor.
/// @returns A reference to the new contained bvalue.
template <typename... Args>
/// \cond CONCEPTS
requires std::constructible_from<dict_type, Args...>
/// \endcond
dict_type& emplace_dict(Args&&... args)
{
return storage_.template emplace<dict_type>(std::forward<Args>(args)...);
}
/// @copydoc emplace_dict(Args&&... args)
template <typename... Args>
/// \cond CONCEPTS
/// \endcond
requires std::constructible_from<dict_type, dict_init_list, Args...>
/// \endcond
dict_type& emplace_dict(dict_init_list il, Args&&... args)
{
return storage_.template emplace<dict_type>(std::move(il), std::forward<Args>(args)...);
}
/// Emplace a type T
template <bencode_type T, typename... Args>
/// \cond CONCEPTS
requires std::constructible_from<bvalue_alternative_t<T, basic_bvalue>, Args...>
/// \endcond
decltype(auto) emplace(Args&&... args)
{
using Type = bvalue_alternative_t<T, basic_bvalue>;
return storage_.template emplace<Type>(std::forward<Args>(args)...);
}
template <bencode_type T, typename... Args, typename = std::enable_if_t<T == bencode_type::dict>>
/// \cond CONCEPTS
requires std::constructible_from<dict_init_list, Args...>
/// \endcond
decltype(auto) emplace(dict_init_list il, Args&& ... args)
{
using Type = bvalue_alternative_t<T, basic_bvalue>;
return storage_.template emplace<Type>(std::move(il), std::forward<Args>(args)...);
}
template <bencode_type T, typename... Args, typename = std::enable_if_t<T == bencode_type::list>>
/// \cond CONCEPTS
requires std::constructible_from<list_init_list, Args...>
/// \endcond
decltype(auto) emplace(list_init_list il, Args&& ... args)
{
using Type = bvalue_alternative_t<T, basic_bvalue>;
return storage_.template emplace<Type>(std::move(il), std::forward<Args>(args)...);
}
template <bencode_type T, typename... Args>
/// \cond CONCEPTS
requires std::constructible_from<string_init_list, Args...> && (T == bencode_type::string)
/// \endcond
decltype(auto) emplace(string_init_list il, Args&& ... args)
{
using Type = bvalue_alternative_t<T, basic_bvalue>;
return storage_.template emplace<Type>(std::move(il), std::forward<Args>(args)...);
}
//===========================================================================//
// Inspect current alternative //
//===========================================================================//
/// return the type as a value_type enumeration
/// @returns bencode_type enum specifying the current active alternative
constexpr auto type() const noexcept -> enum bencode_type
{ return static_cast<enum bencode_type>(storage_.index()); }
//===========================================================================//
// Access current alternative //
//===========================================================================//
public:
/// @brief Returns whether the bvalue hold a value.
/// @return Return true if the container is NOT in the unitialized state,
/// false otherwise.
explicit operator bool() const noexcept
{ return (!(storage_.valueless_by_exception() || is_uninitialized())); }
//===========================================================================//
// checked and unchecked access at()/operator[] //
//===========================================================================//
public:
/// Returns a reference to the element at specified location pos, with bounds checking.
/// If pos is not within the range of the container, an exception of type out_of_range is
/// thrown.
/// If the current active alternative is not a list, and exception of type
/// bencode::bad_bvalue_access is thrown.
/// @param pos position of the element to return
/// @returns Reference to the requested element.
/// @throws out_of_range if !(pos < size())
/// @throws bad_bvalue_access if the current active alternative is not list.
reference at(std::size_t pos)
{
if (!is_list())
throw bad_bvalue_access("bvalue alternative type is not list");
auto* l = std::get_if<list_type>(&storage_);
if (pos >= l->size()) [[unlikely]]
throw out_of_range(fmt::format("list index \"{}\" is out of range", pos));
return l->operator[](pos);
}
/// @copydoc at(std::size_t)
const_reference at(std::size_t pos) const
{
if (!is_list()) [[unlikely]]
throw bad_bvalue_access("bvalue alternative type is not list");
const auto* l = std::get_if<list_type>(&storage_);
if (pos >= l->size()) [[unlikely]]
throw out_of_range(fmt::format("list index \"{}\" is out of range", pos));
return l->operator[](pos);
}
/// Returns a reference to the mapped bvalue of the element with key equivalent to key.
/// If the current active alternative is not a dict, and exception of type
/// bencode::bad_bvalue_access is thrown.
/// If no such element exists, an exception of type out_of_range is thrown.
/// @param pos the key of the element to find
/// @returns Reference to the mapped bvalue of the requested element
/// @throw out_of_range if the container does not have an element with the specified key,
/// @throw bencode::bad_bvalue_access if the current active alternative is not dict.
reference at(const string_type& key)
{
if (!is_dict()) [[unlikely]]
throw bad_bvalue_access("bvalue alternative type is not dict");
auto* d = std::get_if<dict_type>(&storage_);
if (!d->contains(key)) [[unlikely]]
throw out_of_range(fmt::format("dict key \"{}\" not found", key));
return d->operator[](key);
}
/// @copydoc at(const string_type&)
const_reference at(const string_type& key) const
{
if (!is_dict()) [[unlikely]]
throw bad_bvalue_access("bvalue alternative type is not dict");
auto* d = std::get_if<dict_type>(&storage_);
if (auto it = d->find(key); it != d->end()) [[likely]]
return it->second;
throw out_of_range(fmt::format("dict key \"{}\" not found", key));
}
/// Return a reference to the bvalue referenced by a bpointer.
/// @throws bpointer_error when the pointer does not resolve for this value
const_reference at(const bpointer& pointer) const
{
return detail::evaluate(pointer, *this);
}
/// @copydoc at(const bpointer& pointer)
reference at(const bpointer& pointer)
{
return detail::evaluate(pointer, *this);
}
/// Returns a reference to the element at specified location pos.
/// No bounds checking is performed.
/// If the active alternative is not a list an exception of type bencode::bad_bvalue_access is thrown.
/// @param pos position of the element to return
/// @returns Reference to the requested element
reference operator[](std::size_t pos)
{
if (!is_list()) [[unlikely]]
throw bad_bvalue_access("bvalue alternative type is not list");
return (*std::get_if<list_type>(&storage_))[pos];
}
/// @copydoc operator[](std::size_t pos)
const_reference operator[](std::size_t pos) const
{
if (!is_list()) [[unlikely]]
throw bad_bvalue_access("bvalue alternative type is not list");
return (*std::get_if<list_type>(&storage_))[pos];
}
/// Returns a reference to the bvalue that is mapped to a key equivalent to key,
/// performing an insertion if such key does not already exist.
/// If the bvalue is unintialized an empty dict will be created in place.
/// If the active alternative is not a dict an exception of type bencode::bad_bvalue_access is thrown.
/// @param key the key of the element to find
/// @returns Reference to the mapped bvalue of the new element if no element with key key existed.
/// Otherwise a reference to the mapped bvalue of the existing element whose key is equivalent to key.
reference operator[](const string_type& key)
{
if (is_uninitialized()) [[unlikely]]
emplace_dict();
else if (!is_dict()) [[unlikely]]
throw bad_bvalue_access("bvalue alternative type is not dict");
return (*std::get_if<dict_type>(&storage_))[key];
}
/// @copydoc operator[](const string_type&)
reference operator[](string_type&& key)
{
if (is_uninitialized()) [[unlikely]]
emplace_dict();
else if (!is_dict()) [[unlikely]]
throw bad_bvalue_access("bvalue alternative type is not dict");
return (*std::get_if<dict_type>(&storage_))[std::move(key)];
}
/// Returns a reference to the first element in the container.
/// Calling front on an empty container is undefined
/// @returns reference to the first element
/// @throws bad_bvalue_access when current active alternative is not a list.
reference front()
{
if (!is_list()) [[unlikely]]
throw bad_bvalue_access("bvalue alternative type is not list");
return std::get_if<list_type>(&storage_)->front();
}
/// @copydoc front()
const_reference front() const
{
if (!is_list()) [[unlikely]]
throw bad_bvalue_access("bvalue alternative type is not list");
return std::get_if<list_type>(&storage_)->front();
}
/// Returns a reference to the last element in the container.
/// Calling back on an empty container is undefined
/// @returns reference to the last element
/// @throws bad_bvalue_access when current active alternative is not a list.
reference back()
{
if (!is_list()) [[unlikely]]
throw bad_bvalue_access("bvalue alternative type is not list");
return std::get_if<list_type>(&storage_)->back();
}
/// @copydoc back()
const_reference back() const
{
if (!is_list()) [[unlikely]]
throw bad_bvalue_access("bvalue alternative type is not list");
return std::get_if<list_type>(&storage_)->back();
}
/// Appends a new element to the end of a list.
/// If the active alternative is uninintialized, first constructs an empty list in place.
/// If the active alternative is not a list, an exception of type bencode::bad_bvalue_access
/// is thrown. The arguments args... are forwarded to the constructor of the list type.
/// @param args arguments to forward to the constructor of the element
/// @returns Reference to the mapped bvalue of the new element if no element with key key
/// existed. Otherwise a reference to the mapped bvalue of the existing element whose key is
/// equivalent to key.
template <typename... Args>
reference emplace_back(Args&&... args)
{
if (is_uninitialized()) [[unlikely]] emplace_list();
else if (!is_list()) [[unlikely]]
throw bad_bvalue_access("bvalue alternative type is not list");
return std::get_if<list_type>(&storage_)->emplace_back(std::forward<Args>(args)...);
}
/// Appends the given element bvalue to the end of a list.
/// If the active alternative is uninintialized, first constructs an empty list in place.
/// If the active alternative is not a list, an exception of type bencode::bad_bvalue_access
/// is thrown. The arguments args... are forwarded to the constructor of the list type.
/// @param value the bvalue of the element to append
void push_back(const list_value_type& value)
{
if (is_uninitialized()) [[unlikely]] emplace_list();
else if (!is_list()) [[unlikely]]
throw bad_bvalue_access("bvalue alternative type is not list");
auto* ptr = std::get_if<list_type>(&storage_);
ptr->push_back(value);
}
/// @copydoc push_back(const list_value_type&)
void push_back(list_value_type&& value)
{
if (is_uninitialized()) [[unlikely]] emplace_list();
else if (!is_list()) [[unlikely]]
throw bad_bvalue_access("bvalue alternative type is not list");
auto* ptr = std::get_if<list_type>(&storage_);
ptr->push_back(std::move(value));
}
/// Checks if there is an element with key equivalent to key in the container.
/// If the active alternative is not a dict, an exception of type bad_bvalue_access is thrown.
/// @param key key bvalue of the element to search for
/// @returns true if there is such an element, otherwise false.
bool contains(const dict_key_type& key) const
{
if (!is_dict())
throw bad_bvalue_access("bvalue alternative type is not dict");
auto& bdict = *std::get_if<dict_type>(&storage_);
return bdict.find(key) != end(bdict);
}
/// Checks if there is an element that compares equivalent to key in the container.
/// If the active alternative is not a dict, an exception of type bad_bvalue_access is thrown.
/// This overload only participates in overload resolution if the
/// map_type key_compare function supports transparent comparison.
/// @param key key bvalue of the element to search for
/// @returns true if there is such an element, otherwise false.
template <typename K>
/// \cond CONCEPTS
requires std::totally_ordered_with<K, dict_key_type> &&
requires() { typename detail::policy_dict_key_compare<Policy>::is_transparent; }
/// \endcond
bool contains(const K& key) const
{
if (!is_dict())
throw bad_bvalue_access("bvalue alternative type is not dict");
auto& bdict = *std::get_if<dict_type>(&storage_);
return bdict.find(key) != end(bdict);
}
/// Return a reference to the bvalue referenced by a bpointer.
/// @throws bpointer_error when the pointer does not resolve for this value
bool contains(const bpointer& pointer) const
{
return detail::contains(pointer, *this);
}
/// Remove all elements from the current alternative.
/// If the current alternative is a dict, list, string, calls clear on the underlying container.
/// If the current alternative is an integer, set the bvalue to zero.
/// If the current alternative is uninitialized, do nothing.
void clear() noexcept
{
std::visit([](auto&& arg) {
using T = std::decay_t<decltype(arg)>;
if constexpr (std::is_same_v<T, uninitialized_type>)
return;
else if constexpr (std::is_same_v<T, integer_type>)
arg = 0;
else
arg.clear();
}, storage_);
}
public:
void swap(basic_bvalue& other)
noexcept(noexcept(std::declval<storage_type>().swap(std::declval<storage_type>())))
{ storage_.swap(other.storage_); }
/// Compares the contents of two basic_bvalue types.
/// @param that the basic_bvalue whose content to compare
/// @returns true of the lhs and rhs compare equal, false otherwise.
constexpr bool operator==(const basic_bvalue& that) const noexcept
{
if (this->type() == that.type()) {
auto r = (this->storage_ == that.storage_);
return r;
} else {
return this->type() == that.type();
}
}
/// Compares the content of the current alternative with the content of that
/// lexicographically.
/// @param that the basic_bvalue whose content to compare
/// @returns
/// std::partial_ordering::unordered if the current alternatives are of different types,
/// otherwise return the result of the comparison as a std::weak_ordering.
constexpr std::weak_ordering operator<=>(const basic_bvalue& that) const noexcept
{
if (this->type() == that.type()) {
return std::compare_weak_order_fallback(this->storage_, that.storage_);
}
else {
return this->type() <=> that.type();
}
}
/// Compares the current alternatives content with that.
/// @param that the bvalue to compare to.
/// @returns true of the lhs and rhs compare equal, false otherwise.
template <typename T>
/// \cond CONCEPTS
requires (!basic_bvalue_instantiation<T>)
/// \endcond
constexpr auto operator==(const T& that) const noexcept -> bool
{
return detail::compare_equality_with_bvalue(*this, that);
}
/// Compares the current alternatives content with that.
/// @param that the basic_bvalue whose content to compare
/// @returns
/// std::partial_ordering::unordered if the current alternatives are of different types,
/// otherwise return the result of the comparison as a std::weak_ordering.
template <typename T>
/// \cond CONCEPTS
requires (!basic_bvalue_instantiation<T>)
/// \endcond
constexpr auto operator<=>(const T& that) const noexcept -> std::weak_ordering
{
return detail::compare_three_way_with_bvalue(*this, that);
}
private:
template <typename T, class... Args >
constexpr explicit basic_bvalue(std::in_place_type_t<T>,
Args&&... args)
: storage_(std::in_place_type<T>, std::forward<Args>(args)...)
{}
template <std::size_t I, class... Args >
constexpr explicit basic_bvalue(std::in_place_index_t<I>,
Args&&... args)
: storage_(std::in_place_index<I>, std::forward<Args>(args)...)
{}
template <typename T, typename U, class... Args >
constexpr explicit basic_bvalue(std::in_place_type_t<T>,
std::initializer_list<U> il,
Args&&... args)
: storage_(std::in_place_type<T>, std::move(il), std::forward<Args>(args)...)
{}
template <std::size_t I, typename U, class... Args >
constexpr explicit basic_bvalue(std::in_place_index_t<I>,
std::initializer_list<U> il,
Args&&... args)
: storage_(std::in_place_index<I>, std::move(il), std::forward<Args>(args)...)
{}
#define BENCODE_IS_ALTERNATIVE_TYPE_FUNCTION_TEMPLATE(ALTERNATIVE_TYPE) \
constexpr bool is_##ALTERNATIVE_TYPE() const noexcept \
{ return std::holds_alternative<ALTERNATIVE_TYPE##_type>(storage_); } \
BENCODE_IS_ALTERNATIVE_TYPE_FUNCTION_TEMPLATE(uninitialized)
BENCODE_IS_ALTERNATIVE_TYPE_FUNCTION_TEMPLATE(integer)
BENCODE_IS_ALTERNATIVE_TYPE_FUNCTION_TEMPLATE(string)
BENCODE_IS_ALTERNATIVE_TYPE_FUNCTION_TEMPLATE(list)
BENCODE_IS_ALTERNATIVE_TYPE_FUNCTION_TEMPLATE(dict)
#undef BENCODE_IS_ALTERNATIVE_TYPE_FUNCTION_TEMPLATE
constexpr bool is_primitive() const noexcept
{ return !is_structured(); }
constexpr bool is_structured() const noexcept
{ return is_list() || is_dict(); }
template <typename P>
friend constexpr const auto& detail::get_storage(const basic_bvalue<P>& value) noexcept;
template <typename P>
friend constexpr auto& detail::get_storage(basic_bvalue<P>& value) noexcept;
template <typename P>
friend constexpr const auto* detail::get_storage(const basic_bvalue<P>* value) noexcept;
template <typename P>
friend constexpr auto* detail::get_storage(basic_bvalue<P>* value) noexcept;
storage_type storage_;
};
template <typename Policy>
struct serialization_traits<basic_bvalue<Policy>> : serializes_to_runtime_type {};
//============================================================================//
// Helper classes //
//============================================================================//
/// Alias for basic_bvalue<default_bvalue_policy>
using bvalue = basic_bvalue<default_bvalue_policy>;
} // namespace bencode
| 41.766623 | 126 | 0.625597 | [
"object"
] |
63dca029e26c83639be2430467693aaa2d09f28b | 5,464 | cpp | C++ | src/Intersection.cpp | xichen-de/ConcurrentTrafficSimulation | 27418cdd44b6bd74ab798fe319de70549ba54ef7 | [
"MIT"
] | null | null | null | src/Intersection.cpp | xichen-de/ConcurrentTrafficSimulation | 27418cdd44b6bd74ab798fe319de70549ba54ef7 | [
"MIT"
] | null | null | null | src/Intersection.cpp | xichen-de/ConcurrentTrafficSimulation | 27418cdd44b6bd74ab798fe319de70549ba54ef7 | [
"MIT"
] | null | null | null | // MIT License
//
// Copyright (c) 2021 Xi Chen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <iostream>
#include <thread>
#include <chrono>
#include <future>
#include <random>
#include "Street.h"
#include "Intersection.h"
#include "Vehicle.h"
/* Implementation of class "WaitingVehicles" */
int WaitingVehicles::getSize() {
std::lock_guard<std::mutex> lock(_mutex);
return _vehicles.size();
}
void WaitingVehicles::pushBack(std::shared_ptr<Vehicle> vehicle, std::promise<void> &&promise) {
std::lock_guard<std::mutex> lock(_mutex);
_vehicles.push_back(vehicle);
_promises.push_back(std::move(promise));
}
void WaitingVehicles::permitEntryToFirstInQueue() {
std::lock_guard<std::mutex> lock(_mutex);
// get entries from the front of both queues
auto firstPromise = _promises.begin();
auto firstVehicle = _vehicles.begin();
// fulfill promise and send signal back that permission to enter has been granted
firstPromise->set_value();
// remove front elements from both queues
_vehicles.erase(firstVehicle);
_promises.erase(firstPromise);
}
/* Implementation of class "Intersection" */
Intersection::Intersection() {
_type = ObjectType::objectIntersection;
_isBlocked = false;
}
void Intersection::addStreet(std::shared_ptr<Street> street) {
_streets.push_back(street);
}
std::vector<std::shared_ptr<Street>> Intersection::queryStreets(std::shared_ptr<Street> incoming) {
// store all outgoing streets in a vector ...
std::vector<std::shared_ptr<Street>> outgoings;
for (auto it: _streets) {
if (incoming->getID() != it->getID()) // ... except the street making the inquiry
{
outgoings.push_back(it);
}
}
return outgoings;
}
// adds a new vehicle to the queue and returns once the vehicle is allowed to enter
void Intersection::addVehicleToQueue(std::shared_ptr<Vehicle> vehicle) {
std::unique_lock<std::mutex> lck(_mtx);
std::cout << "Intersection #" << _id << "::addVehicleToQueue: thread id = " << std::this_thread::get_id()
<< std::endl;
lck.unlock();
// add new vehicle to the end of the waiting line
std::promise<void> prmsVehicleAllowedToEnter;
std::future<void> ftrVehicleAllowedToEnter = prmsVehicleAllowedToEnter.get_future();
_waitingVehicles.pushBack(vehicle, std::move(prmsVehicleAllowedToEnter));
// wait until the vehicle is allowed to enter
ftrVehicleAllowedToEnter.wait();
lck.lock();
std::cout << "Intersection #" << _id << ": Vehicle #" << vehicle->getID() << " is granted entry." << std::endl;
if (_trafficLight.getCurrentPhase() == TrafficLightPhase::red) {
_trafficLight.waitForGreen();
}
lck.unlock();
}
void Intersection::vehicleHasLeft(std::shared_ptr<Vehicle> vehicle) {
//std::cout << "Intersection #" << _id << ": Vehicle #" << vehicle->getID() << " has left." << std::endl;
// unblock queue processing
this->setIsBlocked(false);
}
void Intersection::setIsBlocked(bool isBlocked) {
_isBlocked = isBlocked;
//std::cout << "Intersection #" << _id << " isBlocked=" << isBlocked << std::endl;
}
// virtual function which is executed in a thread
void Intersection::simulate() // using threads + promises/futures + exceptions
{
_trafficLight.simulate();
// launch vehicle queue processing in a thread
threads.emplace_back(std::thread(&Intersection::processVehicleQueue, this));
}
void Intersection::processVehicleQueue() {
// print id of the current thread
//std::cout << "Intersection #" << _id << "::processVehicleQueue: thread id = " << std::this_thread::get_id() << std::endl;
// continuously process the vehicle queue
while (true) {
// sleep at every iteration to reduce CPU usage
std::this_thread::sleep_for(std::chrono::milliseconds(1));
// only proceed when at least one vehicle is waiting in the queue
if (_waitingVehicles.getSize() > 0 && !_isBlocked) {
// set intersection to "blocked" to prevent other vehicles from entering
this->setIsBlocked(true);
// permit entry to first vehicle in the queue (FIFO)
_waitingVehicles.permitEntryToFirstInQueue();
}
}
}
bool Intersection::trafficLightIsGreen() {
if (_trafficLight.getCurrentPhase() == TrafficLightPhase::green)
return true;
else
return false;
} | 34.802548 | 127 | 0.69235 | [
"vector"
] |
63df5032f53516197cc8f9a079634c42a4212c83 | 921 | cpp | C++ | Algorithm_1001-2000/id1035_UncrossedLines/code.cpp | Louis266/LeetCode | 467a25ae2206d1c1e3ec52c155d3cb07395d5f95 | [
"MIT"
] | null | null | null | Algorithm_1001-2000/id1035_UncrossedLines/code.cpp | Louis266/LeetCode | 467a25ae2206d1c1e3ec52c155d3cb07395d5f95 | [
"MIT"
] | null | null | null | Algorithm_1001-2000/id1035_UncrossedLines/code.cpp | Louis266/LeetCode | 467a25ae2206d1c1e3ec52c155d3cb07395d5f95 | [
"MIT"
] | null | null | null | #include <vector>
#include <iostream>
using namespace std;
int maxUncrossedLines(vector<int>& nums1, vector<int>& nums2) {
int m = nums1.size();
int n = nums2.size();
vector<vector<int> > dp (m+1, vector<int>(n+1));
for (int i = 1; i <= m; i++)
{
int num1 = nums1[i-1];
for (int j = 1; j <= n; j++)
{
int num2 = nums2[j-1];
if (num1 == num2)
{
dp[i][j] = dp[i-1][j-1] + 1;
}else
{
dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
}
}
}
return dp[m][n];
}
int main(){
vector<int> nums1;
nums1.push_back(1);
nums1.push_back(4);
nums1.push_back(2);
vector<int> nums2;
nums2.push_back(1);
nums2.push_back(2);
nums2.push_back(4);
cout << maxUncrossedLines(nums1, nums2) << endl;
} | 18.795918 | 63 | 0.446254 | [
"vector"
] |
63e4e586106072baef407650c7d89e26a8f004cf | 584 | hh | C++ | src/Waffle/Container/Argument/ArgumentResolverInterface.hh | azjezz/waffle | 3a880ac4e7bd10739bc7134aaf1a531bfb623ba3 | [
"MIT"
] | 5 | 2018-11-27T20:20:13.000Z | 2018-12-28T15:30:35.000Z | src/Waffle/Container/Argument/ArgumentResolverInterface.hh | azjezz/waffle | 3a880ac4e7bd10739bc7134aaf1a531bfb623ba3 | [
"MIT"
] | 3 | 2018-12-13T19:11:09.000Z | 2018-12-21T01:11:51.000Z | src/Waffle/Container/Argument/ArgumentResolverInterface.hh | azjezz/waffle | 3a880ac4e7bd10739bc7134aaf1a531bfb623ba3 | [
"MIT"
] | null | null | null | <?hh // strict
namespace Waffle\Container\Argument;
use type Waffle\Container\ContainerAwareInterface;
use type ReflectionFunctionAbstract;
interface ArgumentResolverInterface extends ContainerAwareInterface
{
/**
* Resolve a vector of arguments to their concrete implementations.
*/
public function resolveArguments(vec<mixed> $arguments): vec<mixed>;
/**
* Resolves the correct arguments to be passed to a method.
*/
public function reflectArguments(
ReflectionFunctionAbstract $method, dict<string, mixed> $args
): vec<mixed>;
}
| 26.545455 | 72 | 0.731164 | [
"vector"
] |
63ee1825b2aa3ca84b3903449a422bd2f6bd8cc7 | 23,867 | cpp | C++ | Source/Source/KG3DEngine/KG3DEngine/KG3DFlexibleBody.cpp | uvbs/FullSource | 07601c5f18d243fb478735b7bdcb8955598b9a90 | [
"MIT"
] | 2 | 2018-07-26T07:58:14.000Z | 2019-05-31T14:32:18.000Z | Jx3Full/Source/Source/KG3DEngine/KG3DEngine/KG3DFlexibleBody.cpp | RivenZoo/FullSource | cfd7fd7ad422fd2dae5d657a18839c91ff9521fd | [
"MIT"
] | null | null | null | Jx3Full/Source/Source/KG3DEngine/KG3DEngine/KG3DFlexibleBody.cpp | RivenZoo/FullSource | cfd7fd7ad422fd2dae5d657a18839c91ff9521fd | [
"MIT"
] | 5 | 2021-02-03T10:25:39.000Z | 2022-02-23T07:08:37.000Z | //////////////////////////////////////////////////////////////////////////////////
////
//// FileName : KG3DFlexibleBody.cpp
//// Version : 1.0
//// Creator : Wu Caizhong
//// Create Date : 2008/12/24 15:12:14
//// Comment :
////
//////////////////////////////////////////////////////////////////////////////////
//
#include "StdAfx.h"
#include "KG3DFlexibleBody.h"
#include "KG3DModel.h"
#include "./PhysiscSystem/KG3DPhysiscScene.h"
////////////////////////////////////////////////////////////////////////////////
bool _IsFirstFlexiBoneName(LPCTSTR szName)
{
if (_tcslen(szName) < 5)
return false;
if (
(szName[0] != 'F' && szName[0] != 'f') ||
(szName[1] != 'B' && szName[1] != 'b') ||
(szName[2] != 'R' && szName[2] != 'r')
)
return false;
if ((szName[3] == '_') || (szName[4] == '_'))
{
return true;
}
return false;
}
bool _IsSubFlexiBoneName(LPCTSTR szName)
{
if (_tcslen(szName) < 5)
return false;
if (
(szName[0] != 'F' && szName[0] != 'f') ||
(szName[1] != 'B' && szName[1] != 'b')
)
return false;
if ((szName[2] == '_') || (szName[3] == '_'))
{
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
class KG3DFlexibleBody : public IKG3DFlexibleBody
{
public:
// for IUnknown
virtual ULONG STDMETHODCALLTYPE AddRef();
virtual ULONG STDMETHODCALLTYPE Release();
virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject);
// for IKG3DFlexibleBody
virtual HRESULT AddToPhysicsScene(KG3DPhysiscScene *pPhysicsScene);
virtual HRESULT RemoveFromPhysicsScene();
virtual HRESULT Update();
public:
KG3DFlexibleBody();
~KG3DFlexibleBody();
// maybe return S_OK, E_FAIL, KG3D_E_NO_FLEXIBLE_BODY_DATA
//HRESULT Init(KG3DModel *pModel);
HRESULT InitFromMesh(KG3DMesh *pMesh);
HRESULT UnInit();
HRESULT CloneFromMesh(KG3DFlexibleBody* pDest,KG3DModel* pModel);
private:
//HRESULT _AppendBoneOfChain(DWORD dwFirstBoneIndex);
HRESULT _AppendBoneOfChainFromMesh(DWORD dwFirstBoneIndex);
private:
ULONG m_ulRefCount;
KG3DModel *m_pModel;
KG3DMesh *m_pMesh;
HANDLE m_hPhysiceFlexibleBody;
KG3DPhysiscScene *m_pPhysicsScene;
////////////////////////////////////////////////////////////////////////////
struct FLEXIBLE_NORMAL_BONE_EX : public FLEXIBLE_NORMAL_BONE
{
DWORD dwIndex;
};
std::vector<FLEXIBLE_NORMAL_BONE_EX> m_vecNormalBone;
struct FLEXIBLE_DRIVER_BONE_EX : public FLEXIBLE_DRIVER_BONE
{
DWORD dwIndex;
};
std::vector<FLEXIBLE_DRIVER_BONE_EX> m_vecDriverBone;
};
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
KG3DFlexibleBody::KG3DFlexibleBody() :
m_ulRefCount(1),
m_pModel(NULL),
m_pMesh(NULL),
m_hPhysiceFlexibleBody(NULL),
m_pPhysicsScene(NULL)
{
}
KG3DFlexibleBody::~KG3DFlexibleBody()
{
ASSERT(!m_pModel);
ASSERT(m_vecDriverBone.empty());
ASSERT(!m_pPhysicsScene);
ASSERT(!m_hPhysiceFlexibleBody);
}
////////////////////////////////////////////////////////////////////////////
// interface function //
////////////////////////////////////////////////////////////////////////////
ULONG KG3DFlexibleBody::AddRef(void)
{
return (ULONG)KG_InterlockedIncrement((long *)&m_ulRefCount);
}
ULONG KG3DFlexibleBody::Release(void)
{
ULONG uNewRefCount = (ULONG)KG_InterlockedDecrement((long *)&m_ulRefCount);
if (uNewRefCount == 0)
{
UnInit();
delete this;
}
return uNewRefCount;
}
HRESULT KG3DFlexibleBody::QueryInterface(REFIID riid, void **ppvObject)
{
KG_USE_ARGUMENT(riid);
KG_USE_ARGUMENT(ppvObject);
return KG_E_FAIL;
}
////////////////////////////////////////////////////////////////////////////////
HRESULT KG3DFlexibleBody::AddToPhysicsScene(KG3DPhysiscScene *pPhysicsScene)
{
HRESULT hrResult = E_FAIL;
HRESULT hrRetCode = E_FAIL;
std::vector<FLEXIBLE_DRIVER_BONE *> vecDriverBonePtr;
std::vector<FLEXIBLE_NORMAL_BONE *> vecNormalBonePtr;
std::vector<FLEXIBLE_DRIVER_BONE_EX>::iterator itDriverBone;
std::vector<FLEXIBLE_DRIVER_BONE_EX>::iterator itDriverBoneEnd;
std::vector<FLEXIBLE_NORMAL_BONE_EX>::iterator itNormalBone;
std::vector<FLEXIBLE_NORMAL_BONE_EX>::iterator itNormalBoneEnd;
KG_ASSERT_EXIT(pPhysicsScene);
KG_ASSERT_EXIT(!m_pPhysicsScene && "Already in physics scene");
vecDriverBonePtr.reserve(m_vecDriverBone.size());
itDriverBoneEnd = m_vecDriverBone.end();
for (itDriverBone = m_vecDriverBone.begin(); itDriverBone != itDriverBoneEnd; ++itDriverBone)
{
vecDriverBonePtr.push_back(&(*itDriverBone));
}
vecNormalBonePtr.reserve(m_vecNormalBone.size());
itNormalBoneEnd = m_vecNormalBone.end();
for (itNormalBone = m_vecNormalBone.begin(); itNormalBone != itNormalBoneEnd; ++itNormalBone)
{
vecNormalBonePtr.push_back(&(*itNormalBone));
}
hrRetCode = pPhysicsScene->CreateFlexibleBody(
(unsigned)vecDriverBonePtr.size(), &(vecDriverBonePtr[0]),
(unsigned)vecNormalBonePtr.size(), &(vecNormalBonePtr[0]),
&m_hPhysiceFlexibleBody
);
KGLOG_COM_PROCESS_ERROR(hrRetCode);
m_pPhysicsScene = pPhysicsScene;
hrResult = S_OK;
Exit0:
return hrResult;
}
////////////////////////////////////////////////////////////////////////////////
HRESULT KG3DFlexibleBody::RemoveFromPhysicsScene()
{
HRESULT hrResult = E_FAIL;
HRESULT hrRetCode = E_FAIL;
KG_ASSERT_EXIT(m_pPhysicsScene && "Not in physics scene");
if (m_hPhysiceFlexibleBody)
{
hrRetCode = m_pPhysicsScene->ReleaseFlexibleBody(m_hPhysiceFlexibleBody);
KGLOG_COM_PROCESS_ERROR(hrRetCode);
m_hPhysiceFlexibleBody = NULL;
}
m_pPhysicsScene = NULL;
hrRetCode =
hrResult = S_OK;
Exit0:
return hrResult;
}
////////////////////////////////////////////////////////////////////////////////
HRESULT KG3DFlexibleBody::Update()
{
HRESULT hrResult = E_FAIL;
HRESULT hrRetCode = E_FAIL;
FLEXIBLE_DRIVER_BONE_EX *pDriverBoneEx = NULL;
FLEXIBLE_NORMAL_BONE_EX *pNormalBoneEx = NULL;
unsigned i = 0;
unsigned uBoneCount = 0;
KG_ASSERT_EXIT(m_pModel);
if(m_pPhysicsScene)
{
// -------------------- input --------------------
uBoneCount = (unsigned)m_vecDriverBone.size();
ASSERT(uBoneCount > 0);
pDriverBoneEx = &(m_vecDriverBone[0]);
for (i = 0; i < uBoneCount; ++i)
{
hrRetCode = m_pModel->GetBoneMatrix(pDriverBoneEx->dwIndex, &(pDriverBoneEx->WorldPose));
KGLOG_COM_PROCESS_ERROR(hrRetCode);
++pDriverBoneEx;
}
hrRetCode = m_pPhysicsScene->UpdateFlexibleBody(m_hPhysiceFlexibleBody);
KGLOG_COM_PROCESS_ERROR(hrRetCode);
// -------------------- output --------------------
D3DXMATRIX matWorldInv;
m_pModel->GetMatrixWorldInv(matWorldInv);
uBoneCount = (unsigned)m_vecNormalBone.size();
ASSERT(uBoneCount > 0);
pNormalBoneEx = &(m_vecNormalBone[0]);
for (i = 0; i < uBoneCount; ++i)
{
hrRetCode = m_pModel->SetBoneMatrix(pNormalBoneEx->dwIndex, &(pNormalBoneEx->WorldPose),matWorldInv);
KGLOG_COM_PROCESS_ERROR(hrRetCode);
++pNormalBoneEx;
}
}
else
{
uBoneCount = (unsigned)m_vecDriverBone.size();
ASSERT(uBoneCount > 0);
pDriverBoneEx = &(m_vecDriverBone[0]);
for (i = 0; i < uBoneCount; ++i)
{
m_pModel->UpdataBoneFamily(pDriverBoneEx->dwIndex);
++pDriverBoneEx;
}
}
hrResult = S_OK;
Exit0:
return hrResult;
}
////////////////////////////////////////////////////////////////////////////////
//HRESULT KG3DFlexibleBody::Init(KG3DModel *pModel)
//{
// HRESULT hrResult = E_FAIL;
// HRESULT hrRetCode = E_FAIL;
// int nRetCode = 0;
// unsigned i = 0;
// unsigned j = 0;
// FLEXIBLE_DRIVER_BONE_EX *pDriverBone = NULL;
// FLEXIBLE_BONE_CHAIN BoneChain;
// DWORD dwBoneCount = 0;
// DWORD dwParentIndex = 0;
// DWORD dwChildCount = 0;
// const DWORD *pdwChildIndexs = NULL;
// const char *pcszBoneName = NULL;
//
// KGLOG_PROCESS_ERROR(pModel);
// ASSERT(!m_pModel);
// m_pModel = pModel;
// //m_pModel->AddRef(); // don't add parent object's reference count,
// // if do it, resource can't be release, reference to email from wucaizhong@kingsoft.com at 2009/02/21
//
// hrRetCode = m_pModel->GetNumBones((int *)&dwBoneCount);
// KGLOG_COM_PROCESS_ERROR(hrRetCode);
//
// for (i = 0; i < dwBoneCount; ++i)
// {
// // find first bone of a flexible body
// pcszBoneName = m_pModel->GetBoneName(i);
// ASSERT(pcszBoneName);
//
// nRetCode = _IsFirstFlexiBoneName(pcszBoneName);
// if (!nRetCode)
// continue;
//
// hrRetCode = m_pModel->GetBoneFamily(i, &dwParentIndex, &dwChildCount, &pdwChildIndexs);
// ASSERT(SUCCEEDED(hrRetCode));
// if (dwParentIndex >= dwBoneCount)
// {
// KGLogPrintf(KGLOG_ERR, "[FlexibleBody] (dwParentIndex >= dwBoneCount) Bone %s Model:%s", pcszBoneName, m_pModel->m_scName.c_str());
// KG_PROCESS_ERROR(false);
// }
//
// // found exist or new the first flexible bone's driver bone
// for (j = 0; j < m_vecDriverBone.size(); ++j)
// {
// pDriverBone = &(m_vecDriverBone[j]);
// if (pDriverBone->dwIndex == dwParentIndex)
// {
// break;
// }
// }
// if (j == m_vecDriverBone.size())
// {
// pcszBoneName = m_pModel->GetBoneName(dwParentIndex);
// ASSERT(pcszBoneName);
//
// //#ifdef _DEBUG
// nRetCode = _IsFirstFlexiBoneName(pcszBoneName);
// if (nRetCode)
// {
// KGLogPrintf(KGLOG_ERR, "[FlexibleBody] Bone name error(%s), Model:%s", pcszBoneName, m_pModel->m_scName.c_str());
// //ASSERT(!nRetCode);
// KG_PROCESS_ERROR(false);
// }
// nRetCode = _IsSubFlexiBoneName(pcszBoneName);
// if (nRetCode)
// {
// KGLogPrintf(KGLOG_ERR, "[FlexibleBody] Bone name error(%s), Model:%s", pcszBoneName, m_pModel->m_scName.c_str());
// //ASSERT(!nRetCode);
// KG_PROCESS_ERROR(false);
// }
// //#endif
//
// m_vecDriverBone.resize(j + 1);
// pDriverBone = &(m_vecDriverBone[j]);
//
// pDriverBone->pcszName = pcszBoneName;
// hrRetCode = m_pModel->GetBoneMatrixOrg(dwParentIndex, &(pDriverBone->InitPose));
// ASSERT(SUCCEEDED(hrRetCode));
// pDriverBone->WorldPose = pDriverBone->InitPose;
// pDriverBone->dwIndex = dwParentIndex;
// }
// ASSERT(pDriverBone);
//
// // build bone chain
// BoneChain.uFirstBoneIndex = (unsigned)m_vecNormalBone.size();
//
// hrRetCode = _AppendBoneOfChain(i);
// KGLOG_COM_PROCESS_ERROR(hrRetCode);
//
// BoneChain.uBoneCount = (unsigned)m_vecNormalBone.size() - BoneChain.uFirstBoneIndex;
// pDriverBone->vecBoneChain.push_back(BoneChain);
// }
//
// KG_PROCESS_ERROR_RET_COM_CODE(m_vecDriverBone.size() > 0, KG3D_E_NO_FLEXIBLE_BODY_DATA);
// ASSERT(m_vecNormalBone.size() > 0);
//
// hrResult = S_OK;
//Exit0:
// if (FAILED(hrResult))
// {
// m_vecNormalBone.clear();
// m_vecDriverBone.clear();
// //KG_COM_RELEASE(m_pModel);
// m_pModel = NULL;
// }
// return hrResult;
//
//}
////////////////////////////////////////////////////////////////////////////////
HRESULT KG3DFlexibleBody::InitFromMesh(KG3DMesh *pMesh)
{
HRESULT hrResult = E_FAIL;
HRESULT hrRetCode = E_FAIL;
int nRetCode = 0;
unsigned i = 0;
unsigned j = 0;
FLEXIBLE_DRIVER_BONE_EX *pDriverBone = NULL;
FLEXIBLE_BONE_CHAIN BoneChain;
DWORD dwBoneCount = 0;
DWORD dwParentIndex = 0;
DWORD dwChildCount = 0;
const DWORD *pdwChildIndexs = NULL;
const char *pcszBoneName = NULL;
KGLOG_PROCESS_ERROR(pMesh);
ASSERT(!m_pMesh);
m_pMesh = pMesh;
//m_pModel->AddRef(); // don't add parent object's reference count,
// if do it, resource can't be release, reference to email from wucaizhong@kingsoft.com at 2009/02/21
hrRetCode = m_pMesh->GetNumBones((int *)&dwBoneCount);
KGLOG_COM_PROCESS_ERROR(hrRetCode);
for (i = 0; i < dwBoneCount; ++i)
{
// find first bone of a flexible body
pcszBoneName = m_pMesh->GetBoneName(i);
ASSERT(pcszBoneName);
nRetCode = _IsFirstFlexiBoneName(pcszBoneName);
if (!nRetCode)
continue;
hrRetCode = m_pMesh->GetBoneFamily(i, &dwParentIndex, &dwChildCount, &pdwChildIndexs);
ASSERT(SUCCEEDED(hrRetCode));
if (dwParentIndex >= dwBoneCount)
{
KGLogPrintf(KGLOG_ERR, "[FlexibleBody] (dwParentIndex >= dwBoneCount) Bone %s Model:%s", pcszBoneName, m_pModel->m_scName.c_str());
KG_PROCESS_ERROR(false);
}
// found exist or new the first flexible bone's driver bone
for (j = 0; j < m_vecDriverBone.size(); ++j)
{
pDriverBone = &(m_vecDriverBone[j]);
if (pDriverBone->dwIndex == dwParentIndex)
{
break;
}
}
if (j == m_vecDriverBone.size())
{
pcszBoneName = m_pMesh->GetBoneName(dwParentIndex);
ASSERT(pcszBoneName);
//#ifdef _DEBUG
nRetCode = _IsFirstFlexiBoneName(pcszBoneName);
if (nRetCode)
{
KGLogPrintf(KGLOG_ERR, "[FlexibleBody] Bone name error(%s), Model:%s", pcszBoneName, m_pModel->m_scName.c_str());
//ASSERT(!nRetCode);
KG_PROCESS_ERROR(false);
}
nRetCode = _IsSubFlexiBoneName(pcszBoneName);
if (nRetCode)
{
KGLogPrintf(KGLOG_ERR, "[FlexibleBody] Bone name error(%s), Model:%s", pcszBoneName, m_pModel->m_scName.c_str());
//ASSERT(!nRetCode);
KG_PROCESS_ERROR(false);
}
//#endif
m_vecDriverBone.resize(j + 1);
pDriverBone = &(m_vecDriverBone[j]);
pDriverBone->pcszName = pcszBoneName;
pDriverBone->InitPose = *m_pMesh->GetBoneMatrix(dwParentIndex);
ASSERT(SUCCEEDED(hrRetCode));
pDriverBone->WorldPose = pDriverBone->InitPose;
pDriverBone->dwIndex = dwParentIndex;
}
ASSERT(pDriverBone);
// build bone chain
BoneChain.uFirstBoneIndex = (unsigned)m_vecNormalBone.size();
hrRetCode = _AppendBoneOfChainFromMesh(i);
KGLOG_COM_PROCESS_ERROR(hrRetCode);
BoneChain.uBoneCount = (unsigned)m_vecNormalBone.size() - BoneChain.uFirstBoneIndex;
pDriverBone->vecBoneChain.push_back(BoneChain);
}
KG_PROCESS_ERROR_RET_COM_CODE(m_vecDriverBone.size() > 0, KG3D_E_NO_FLEXIBLE_BODY_DATA);
ASSERT(m_vecNormalBone.size() > 0);
hrResult = S_OK;
Exit0:
if (FAILED(hrResult))
{
m_vecNormalBone.clear();
m_vecDriverBone.clear();
m_pMesh = NULL;
}
return hrResult;
}
////////////////////////////////////////////////////////////////////////////////
HRESULT KG3DFlexibleBody::UnInit()
{
m_vecDriverBone.clear();
m_vecNormalBone.clear();
ASSERT(!m_pPhysicsScene);
ASSERT(!m_hPhysiceFlexibleBody);
//KG_COM_RELEASE(m_pModel);
m_pModel = NULL;
return S_OK;
}
////////////////////////////////////////////////////////////////////////////////
//HRESULT KG3DFlexibleBody::_AppendBoneOfChain(DWORD dwFirstBoneIndex)
//{
// HRESULT hrResult = E_FAIL;
// HRESULT hrRetCode = E_FAIL;
// int nRetCode = false;
// DWORD dwCurrentIndex = 0;
// FLEXIBLE_NORMAL_BONE_EX *pCurrentBone = NULL;
// DWORD dwParentIndex = 0;
// DWORD dwChildCount = 0;
// const DWORD *pdwChildIndexs = NULL;
// const char *pcszBoneName = NULL;
//
// ASSERT(m_pModel);
//
// dwCurrentIndex = dwFirstBoneIndex;
// while (true)
// {
// pcszBoneName = m_pModel->GetBoneName(dwCurrentIndex);
// KGLOG_PROCESS_ERROR(pcszBoneName);
//#ifdef _DEBUG
// nRetCode = _IsFirstFlexiBoneName(pcszBoneName);
// if (!nRetCode)
// {
// nRetCode = _IsSubFlexiBoneName(pcszBoneName);
// ASSERT(nRetCode);
// }
//#endif // _DEBUG
//
// hrRetCode = m_pModel->GetBoneFamily(
// dwCurrentIndex, &dwParentIndex, &dwChildCount, &pdwChildIndexs
// );
// KGLOG_COM_PROCESS_ERROR(hrRetCode);
//
// m_vecNormalBone.resize(m_vecNormalBone.size() + 1);
// pCurrentBone = &(m_vecNormalBone[m_vecNormalBone.size() - 1]);
// pCurrentBone->pcszName = pcszBoneName;
// hrRetCode = m_pModel->GetBoneMatrixOrg(dwCurrentIndex, &(pCurrentBone->InitPose));
// ASSERT(SUCCEEDED(hrRetCode));
// pCurrentBone->WorldPose = pCurrentBone->InitPose;
// pCurrentBone->fLength = 10.0f;
// pCurrentBone->dwIndex = dwCurrentIndex;
//
// if (dwCurrentIndex != dwFirstBoneIndex)
// {
// FLEXIBLE_NORMAL_BONE_EX *pParentBone = pCurrentBone - 1; // do not use value of pCurrentBone in last loop, m_vecNormalBone.resize maybe move memory
// D3DXVECTOR3 vCur = D3DXVECTOR3(
// pCurrentBone->InitPose._41,
// pCurrentBone->InitPose._42,
// pCurrentBone->InitPose._43
// );
// D3DXVECTOR3 vParent = D3DXVECTOR3(
// pParentBone->InitPose._41,
// pParentBone->InitPose._42,
// pParentBone->InitPose._43
// );
//
// pParentBone->fLength = D3DXVec3Length(&(vParent - vCur));
// }
//
// if (dwChildCount == 0)
// break;
//
// ASSERT(dwChildCount == 1);
// dwCurrentIndex = *pdwChildIndexs;
// }
//
// hrResult = S_OK;
//Exit0:
// return hrResult;
//}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
HRESULT KG3DFlexibleBody::_AppendBoneOfChainFromMesh(DWORD dwFirstBoneIndex)
{
HRESULT hrResult = E_FAIL;
HRESULT hrRetCode = E_FAIL;
int nRetCode = false;
DWORD dwCurrentIndex = 0;
FLEXIBLE_NORMAL_BONE_EX *pCurrentBone = NULL;
DWORD dwParentIndex = 0;
DWORD dwChildCount = 0;
const DWORD *pdwChildIndexs = NULL;
const char *pcszBoneName = NULL;
ASSERT(m_pMesh);
dwCurrentIndex = dwFirstBoneIndex;
while (true)
{
pcszBoneName = m_pMesh->GetBoneName(dwCurrentIndex);
KGLOG_PROCESS_ERROR(pcszBoneName);
#ifdef _DEBUG
nRetCode = _IsFirstFlexiBoneName(pcszBoneName);
if (!nRetCode)
{
nRetCode = _IsSubFlexiBoneName(pcszBoneName);
ASSERT(nRetCode);
}
#endif // _DEBUG
hrRetCode = m_pMesh->GetBoneFamily(
dwCurrentIndex, &dwParentIndex, &dwChildCount, &pdwChildIndexs
);
KGLOG_COM_PROCESS_ERROR(hrRetCode);
m_vecNormalBone.resize(m_vecNormalBone.size() + 1);
pCurrentBone = &(m_vecNormalBone[m_vecNormalBone.size() - 1]);
pCurrentBone->pcszName = pcszBoneName;
pCurrentBone->InitPose = *m_pMesh->GetBoneMatrix(dwCurrentIndex);
pCurrentBone->WorldPose = pCurrentBone->InitPose;
pCurrentBone->fLength = 10.0f;
pCurrentBone->dwIndex = dwCurrentIndex;
if (dwCurrentIndex != dwFirstBoneIndex)
{
FLEXIBLE_NORMAL_BONE_EX *pParentBone = pCurrentBone - 1; // do not use value of pCurrentBone in last loop, m_vecNormalBone.resize maybe move memory
D3DXVECTOR3 vCur = D3DXVECTOR3(
pCurrentBone->InitPose._41,
pCurrentBone->InitPose._42,
pCurrentBone->InitPose._43
);
D3DXVECTOR3 vParent = D3DXVECTOR3(
pParentBone->InitPose._41,
pParentBone->InitPose._42,
pParentBone->InitPose._43
);
pParentBone->fLength = D3DXVec3Length(&(vParent - vCur));
}
if (dwChildCount == 0)
break;
ASSERT(dwChildCount == 1);
dwCurrentIndex = *pdwChildIndexs;
}
hrResult = S_OK;
Exit0:
return hrResult;
}
////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////
HRESULT KG3DCreateFlexibleBodyFromModel(
KG3DModel *pModel, IKG3DFlexibleBody **ppiRetFlexibleBody
)
{
HRESULT hrResult = E_FAIL;
HRESULT hrRetCode = E_FAIL;
KG3DFlexibleBody *pFlexibleBody = NULL;
int nFlexibleBodyInitFlag = false;
KG3DMesh* pMesh = NULL;
KGLOG_PROCESS_ERROR(pModel);
KGLOG_PROCESS_ERROR(ppiRetFlexibleBody);
pMesh = pModel->GetMesh();
KGLOG_PROCESS_ERROR(pMesh);
if(!pMesh->m_lpFlexibleBody)
{
hrResult = KG3D_E_NO_FLEXIBLE_BODY_DATA;
}
KG_PROCESS_ERROR(pMesh->m_lpFlexibleBody);
KG3DFlexibleBody* pSrc = static_cast<KG3DFlexibleBody*>(pMesh->m_lpFlexibleBody);
pFlexibleBody = new KG3DFlexibleBody();
KGLOG_PROCESS_ERROR(pFlexibleBody);
hrRetCode = pSrc->CloneFromMesh(pFlexibleBody,pModel);
/*if (hrRetCode != KG3D_E_NO_FLEXIBLE_BODY_DATA)
KGLOG_COM_PROC_ERR_RET_ERR(hrRetCode);
else
KG_COM_PROC_ERR_RET_ERR(hrRetCode);*/
nFlexibleBodyInitFlag = true;
*ppiRetFlexibleBody = pFlexibleBody;
hrResult = S_OK;
Exit0:
if (FAILED(hrResult))
{
if (nFlexibleBodyInitFlag)
{
pFlexibleBody->UnInit();
nFlexibleBodyInitFlag = false;
}
KG_DELETE(pFlexibleBody);
}
return hrResult;
}
HRESULT KG3DCreateFlexibleBodyFromMesh(
KG3DMesh *pMesh, IKG3DFlexibleBody **ppiRetFlexibleBody
)
{
HRESULT hrResult = E_FAIL;
HRESULT hrRetCode = E_FAIL;
KG3DFlexibleBody *pFlexibleBody = NULL;
int nFlexibleBodyInitFlag = false;
KGLOG_PROCESS_ERROR(pMesh);
KGLOG_PROCESS_ERROR(ppiRetFlexibleBody);
pFlexibleBody = new KG3DFlexibleBody();
KGLOG_PROCESS_ERROR(pFlexibleBody);
hrRetCode = pFlexibleBody->InitFromMesh(pMesh);
if (hrRetCode != KG3D_E_NO_FLEXIBLE_BODY_DATA)
KGLOG_COM_PROC_ERR_RET_ERR(hrRetCode);
else
KG_COM_PROC_ERR_RET_ERR(hrRetCode);
nFlexibleBodyInitFlag = true;
*ppiRetFlexibleBody = pFlexibleBody;
hrResult = S_OK;
Exit0:
if (FAILED(hrResult))
{
if (nFlexibleBodyInitFlag)
{
pFlexibleBody->UnInit();
nFlexibleBodyInitFlag = false;
}
KG_DELETE(pFlexibleBody);
}
return hrResult;
}
////////////////////////////////////////////////////////////////////////////////
HRESULT KG3DIsFlexibleBodyBone(const char cszBoneName[], int *pnRetFlexibleBoneFlag)
{
HRESULT hrResult = E_FAIL;
KGLOG_PROCESS_ERROR(cszBoneName);
KGLOG_PROCESS_ERROR(pnRetFlexibleBoneFlag);
*pnRetFlexibleBoneFlag = _IsFirstFlexiBoneName(cszBoneName);
if (!*pnRetFlexibleBoneFlag)
{
*pnRetFlexibleBoneFlag = _IsSubFlexiBoneName(cszBoneName);
}
hrResult = S_OK;
Exit0:
return hrResult;
}
HRESULT KG3DFlexibleBody::CloneFromMesh(KG3DFlexibleBody* pDest,KG3DModel* pModel)
{
pDest->m_pModel = pModel;
pDest->m_vecDriverBone = m_vecDriverBone;
pDest->m_vecNormalBone = m_vecNormalBone;
return S_OK;
}
| 30.71686 | 162 | 0.587296 | [
"object",
"vector",
"model"
] |
63f1b21515553b98f37f63226085598fd32097f8 | 4,085 | cc | C++ | SimG4Core/Application/test/SimTrackSimVertexDumper.cc | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 1 | 2020-02-07T11:20:02.000Z | 2020-02-07T11:20:02.000Z | SimG4Core/Application/test/SimTrackSimVertexDumper.cc | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 7 | 2016-07-17T02:34:54.000Z | 2019-08-13T07:58:37.000Z | SimG4Core/Application/test/SimTrackSimVertexDumper.cc | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 2 | 2019-09-27T08:33:22.000Z | 2019-11-14T10:52:30.000Z | // -*- C++ -*-
//
// Package: SimTrackerDumper
// Class: SimTrackSimVertexDumper
//
/*
Description: <one line class summary>
Implementation:
<Notes on implementation>
*/
//
//
// system include files
#include <memory>
#include "SimG4Core/Application/test/SimTrackSimVertexDumper.h"
// user include files
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/EDAnalyzer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "SimDataFormats/TrackingHit/interface/PSimHit.h"
#include "SimDataFormats/TrackingHit/interface/PSimHitContainer.h"
#include "SimDataFormats/Track/interface/SimTrack.h"
#include "SimDataFormats/Track/interface/SimTrackContainer.h"
#include "SimDataFormats/Vertex/interface/SimVertex.h"
#include "SimDataFormats/Vertex/interface/SimVertexContainer.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "SimDataFormats/GeneratorProducts/interface/HepMCProduct.h"
#include "HepMC/GenEvent.h"
SimTrackSimVertexDumper::SimTrackSimVertexDumper(const edm::ParameterSet& iConfig)
: HepMCLabel(iConfig.getParameter<edm::InputTag>("moduleLabelHepMC")),
SimTkLabel(iConfig.getParameter<edm::InputTag>("moduleLabelTk")),
SimVtxLabel(iConfig.getParameter<edm::InputTag>("moduleLabelVtx")),
dumpHepMC(iConfig.getUntrackedParameter<bool>("dumpHepMC", "false")) {}
//
// member functions
//
// ------------ method called to produce the data ------------
void SimTrackSimVertexDumper::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) {
using namespace edm;
using namespace HepMC;
std::vector<SimTrack> theSimTracks;
std::vector<SimVertex> theSimVertexes;
Handle<HepMCProduct> MCEvt;
Handle<SimTrackContainer> SimTk;
Handle<SimVertexContainer> SimVtx;
iEvent.getByLabel(HepMCLabel, MCEvt);
const HepMC::GenEvent* evt = MCEvt->GetEvent();
iEvent.getByLabel(SimTkLabel, SimTk);
iEvent.getByLabel(SimVtxLabel, SimVtx);
theSimTracks.insert(theSimTracks.end(), SimTk->begin(), SimTk->end());
theSimVertexes.insert(theSimVertexes.end(), SimVtx->begin(), SimVtx->end());
std::cout << "\n SimVertex / SimTrack structure dump \n" << std::endl;
std::cout << " SimVertex in the event = " << theSimVertexes.size() << std::endl;
std::cout << " SimTracks in the event = " << theSimTracks.size() << std::endl;
std::cout << "\n" << std::endl;
for (unsigned int isimvtx = 0; isimvtx < theSimVertexes.size(); isimvtx++) {
std::cout << "SimVertex " << isimvtx << " = " << theSimVertexes[isimvtx] << "\n" << std::endl;
for (unsigned int isimtk = 0; isimtk < theSimTracks.size(); isimtk++) {
if (theSimTracks[isimtk].vertIndex() >= 0 && std::abs(theSimTracks[isimtk].vertIndex()) == (int)isimvtx) {
std::cout << " SimTrack " << isimtk << " = " << theSimTracks[isimtk]
<< " Track Id = " << theSimTracks[isimtk].trackId() << std::endl;
// for debugging purposes
if (dumpHepMC) {
if (theSimTracks[isimtk].genpartIndex() != -1) {
HepMC::GenParticle* part = evt->barcode_to_particle(theSimTracks[isimtk].genpartIndex());
if (part) {
std::cout << " ---> Corresponding to HepMC particle " << *part << std::endl;
} else {
std::cout << " ---> Corresponding HepMC particle to barcode " << theSimTracks[isimtk].genpartIndex()
<< " not in selected event " << std::endl;
}
}
}
}
}
std::cout << "\n" << std::endl;
}
for (std::vector<SimTrack>::iterator isimtk = theSimTracks.begin(); isimtk != theSimTracks.end(); ++isimtk) {
if (isimtk->noVertex()) {
std::cout << "SimTrack without an associated Vertex = " << *isimtk << std::endl;
}
}
return;
}
//define this as a plug-in
DEFINE_FWK_MODULE(SimTrackSimVertexDumper);
| 36.473214 | 114 | 0.675398 | [
"vector"
] |
63f1cb7a0b779c3aed7cce7fe3942eb5b67b0dd5 | 1,244 | cpp | C++ | src/util/cfg.cpp | jie-meng/Util | edf197b61f8606c72fc8f3b0bdbb46b57187b2ff | [
"MIT"
] | 6 | 2017-07-16T17:55:54.000Z | 2021-01-06T15:40:49.000Z | src/util/cfg.cpp | joshua-meng/Util | edf197b61f8606c72fc8f3b0bdbb46b57187b2ff | [
"MIT"
] | 30 | 2015-05-08T03:21:10.000Z | 2017-05-07T12:37:06.000Z | src/util/cfg.cpp | joshua-meng/Util | edf197b61f8606c72fc8f3b0bdbb46b57187b2ff | [
"MIT"
] | 2 | 2017-03-16T08:48:34.000Z | 2017-06-20T10:56:19.000Z | #include "cfg.hpp"
#include <vector>
#include <list>
#include <algorithm>
#include "file.hpp"
namespace util
{
typedef std::vector<std::string> StrVector;
typedef std::list<std::string> StrList;
void TextCfg::load(const std::string& cfg_file)
{
cfg_file_ = cfg_file;
cfg_map_.clear();
if (isPathFile(cfg_file))
{
std::string text = readTextFile(cfg_file);
StrList line_list;
strSplit(text, "\n", line_list);
StrVector vec;
for (StrList::iterator it = line_list.begin(); it != line_list.end(); ++it)
{
vec.clear();
strSplit(*it, "=", vec, 2);
if (2 == vec.size())
cfg_map_[strTrim(vec[0])] = strTrim(vec[1]);
}
}
}
void TextCfg::save(const std::string& cfg_file)
{
StrList line_list;
for (CfgMap::iterator it = cfg_map_.begin(); it != cfg_map_.end(); ++it)
line_list.push_back(it->first + " = " + it->second);
line_list.sort();
StrList::iterator pend = remove_if(line_list.begin(), line_list.end(), TextCfg::isEmpty);
std::string text = strJoin(line_list.begin(), pend, "\n");
writeTextFile(cfg_file, text);
}
void TextCfg::save()
{
save(cfg_file_);
}
} // namespace util
| 23.471698 | 93 | 0.598875 | [
"vector"
] |
1204ec9bbb617d3ec4e092cb2a4988b52b2a66de | 18,947 | hh | C++ | unisim/component/cxx/processor/arm/cpu.hh | binsec/unisim_archisec | 6556a45c180b6769dc1850ff3f695707d8835e90 | [
"BSD-3-Clause"
] | null | null | null | unisim/component/cxx/processor/arm/cpu.hh | binsec/unisim_archisec | 6556a45c180b6769dc1850ff3f695707d8835e90 | [
"BSD-3-Clause"
] | null | null | null | unisim/component/cxx/processor/arm/cpu.hh | binsec/unisim_archisec | 6556a45c180b6769dc1850ff3f695707d8835e90 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2007-2019,
* Commissariat a l'Energie Atomique (CEA)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - Neither the name of CEA nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Yves Lhuillier (yves.lhuillier@cea.fr), Daniel Gracia Perez (daniel.gracia-perez@cea.fr)
*/
#ifndef __UNISIM_COMPONENT_CXX_PROCESSOR_ARM_CPU_HH__
#define __UNISIM_COMPONENT_CXX_PROCESSOR_ARM_CPU_HH__
#include <unisim/component/cxx/vector/vector.hh>
#include <unisim/component/cxx/processor/arm/exception.hh>
#include <unisim/component/cxx/processor/arm/psr.hh>
#include <unisim/component/cxx/processor/arm/cp15.hh>
#include <unisim/kernel/logger/logger.hh>
#include <unisim/util/endian/endian.hh>
#include <unisim/util/inlining/inlining.hh>
#include <unisim/service/interfaces/registers.hh>
#include <unisim/service/interfaces/register.hh>
#include <map>
#include <set>
#include <stdexcept>
#include <inttypes.h>
namespace unisim {
namespace component {
namespace cxx {
namespace processor {
namespace arm {
/** Base class for the ARM family.
*
* This class is the base for all the cpu's of the ARM processor
* family, for that purpose it defines the basic registers and
* different methods to handle them.
*/
template <typename FP_IMPL, typename CPU_IMPL>
struct CPU
: public virtual unisim::kernel::Object
, public unisim::kernel::Service<unisim::service::interfaces::Registers>
{
typedef FP_IMPL FP;
typedef typename FP::F64 F64;
typedef typename FP::F32 F32;
typedef uint8_t U8;
typedef uint16_t U16;
typedef uint32_t U32;
typedef uint64_t U64;
typedef int8_t S8;
typedef int16_t S16;
typedef int32_t S32;
typedef int64_t S64;
typedef bool BOOL;
/*
* ARM architecture constants
*/
/* values of the different condition codes */
static uint32_t const COND_EQ = 0x00;
static uint32_t const COND_NE = 0x01;
static uint32_t const COND_CS_HS = 0x02;
static uint32_t const COND_CC_LO = 0x03;
static uint32_t const COND_MI = 0x04;
static uint32_t const COND_PL = 0x05;
static uint32_t const COND_VS = 0x06;
static uint32_t const COND_VC = 0x07;
static uint32_t const COND_HI = 0x08;
static uint32_t const COND_LS = 0x09;
static uint32_t const COND_GE = 0x0a;
static uint32_t const COND_LT = 0x0b;
static uint32_t const COND_GT = 0x0c;
static uint32_t const COND_LE = 0x0d;
static uint32_t const COND_AL = 0x0e;
/* mask for valid bits in processor control and status registers */
static uint32_t const PSR_UNALLOC_MASK = 0x00f00000;
/* Number of logic registers */
static unsigned const num_log_gprs = 16;
/** Base class for the ARM Modes
*
* This class is the base for all ARM Modes specifying the interface
* of Mode related operation. Basically it specifies accessors for
* banked registers and SPSR. It also introduce an internal swaping
* mechanism to save/restore bancked registers.
*/
struct Mode
{
Mode( char const* _suffix ) : suffix( _suffix ) {} char const* suffix;
virtual ~Mode() {}
virtual bool HasBR( unsigned index ) { return false; }
virtual bool HasSPSR() { return false; }
virtual void SetSPSR(uint32_t value ) { throw std::logic_error("No SPSR for this mode"); };
virtual uint32_t GetSPSR() { throw std::logic_error("No SPSR for this mode"); return 0; };
virtual void Swap( CPU& cpu ) {};
};
//=====================================================================
//= Logger =
//=====================================================================
/** Unisim logging services. */
unisim::kernel::logger::Logger logger;
/** Verbosity of the CPU implementation */
bool verbose;
//=====================================================================
//= public service imports/exports =
//=====================================================================
//=====================================================================
//= Constructor/Destructor =
//=====================================================================
CPU(const char* name, Object* parent);
~CPU();
/********************************************/
/* General Purpose Registers access methods */
/********************************************/
/* GPR access functions */
/** Get the value contained by a GPR.
*
* @param id the register index
* @return the value contained by the register
*/
uint32_t GetGPR(uint32_t id) const
{
return gpr[id];
}
/** Assign a GPR with a value coming from the Execute stage (See
* ARM's ALUWritePC). In ARMv7 architectures this is interworking
* except in thumb state.
*
* @param id the register index
* @param val the value to set
*/
void SetGPR(uint32_t id, uint32_t val)
{
if (id != 15) gpr[id] = val;
else if (cpsr.Get( T )) this->Branch( val, B_JMP );
else this->BranchExchange( val, B_JMP );
}
/** Assign a GPR with a value coming from the Memory stage. From
* ARMv5T architectures, this is always interworking (exchanging
* branch when destination register is PC).
*
* @param id the register index
* @param val the value to set
*/
void SetGPR_mem(uint32_t id, uint32_t val)
{
if (id != 15) gpr[id] = val;
else this->BranchExchange( val, B_JMP );
}
enum branch_type_t { B_JMP = 0, B_CALL, B_RET, B_EXC, B_DBG, B_RFE };
/** Sets the PC (and potentially exchanges mode ARM<->Thumb)
*
* @param val the value to set PC
*/
void BranchExchange(uint32_t target, branch_type_t branch_type)
{
this->cpsr.Set( T, target & 1 );
this->Branch( target, branch_type );
}
/** Sets the PC (fixing alignment and preserving mode)
*
* @param val the value to set PC
*/
void Branch(uint32_t target, branch_type_t branch_type)
{
this->next_insn_addr = target & (this->cpsr.Get( T ) ? -2 : -4);
}
/** Gets the current instruction address
*
*/
uint32_t GetCIA()
{ return this->current_insn_addr; }
/** Gets the next instruction address (as currently computed)
*
*/
uint32_t GetNIA()
{ return this->next_insn_addr; }
/******************************************/
/* Program Status Register access methods */
/******************************************/
/** Get the CPSR register.
*
* @return the CPSR structured register.
*/
PSR& CPSR() { return cpsr; };
void SetCPSR( uint32_t bits, uint32_t mask );
uint32_t GetCPSR() const { return cpsr.Get(ALL32); }
uint32_t GetNZCV() const { return cpsr.Get(NZCV); }
/** Get the endian configuration of the processor.
*
* @return the endian being used
*/
unisim::util::endian::endian_type
GetEndianness() const
{
return (this->cpsr.Get( E ) == 0) ? unisim::util::endian::E_LITTLE_ENDIAN : unisim::util::endian::E_BIG_ENDIAN;
}
/** Determine wether the processor instruction stream is inside an
* IT block.
*/
bool itblock() const { return CPU_IMPL::Config::insnsT2 ? cpsr.InITBlock() : false; }
/** Return the current condition associated to the IT state of the
* processor.
*/
uint32_t itcond() const { return CPU_IMPL::Config::insnsT2 ? cpsr.ITGetCondition() : COND_AL; }
bool m_isit; /* determines wether current instruction is an IT one. */
void ITSetState( uint32_t cond, uint32_t mask )
{
this->cpsr.ITSetState( cond, mask );
m_isit = true;
}
void ITAdvance()
{
if (m_isit)
this->m_isit = false;
else if (this->itblock())
this->cpsr.ITAdvance();
}
/*********************************************/
/* Modes and Banked Registers access methods */
/*********************************************/
Mode& GetMode(uint8_t mode)
{
typename ModeMap::iterator itr = modes.find(mode);
if (itr == modes.end()) UnpredictableInsnBehaviour();
return *(itr->second);
}
unsigned GetPL();
void RequiresPL(unsigned rpl);
Mode& CurrentMode() { return GetMode(cpsr.Get(M)); }
/** Get the value contained by a banked register GPR.
*
* Returns the value contained by a banked register. It is the same
* than GetGPR but mode can be different from the running mode.
*
* @param mode the mode of banked register
* @param idx the register index
* @return the value contained by the register
*/
uint32_t GetBankedRegister( uint8_t foreign_mode, uint32_t idx )
{
uint8_t running_mode = cpsr.Get( M );
if (running_mode == foreign_mode) return GetGPR( idx );
GetMode(running_mode).Swap(*this); // OUT
GetMode(foreign_mode).Swap(*this); // IN
uint32_t value = GetGPR( idx );
GetMode(foreign_mode).Swap(*this); // OUT
GetMode(running_mode).Swap(*this); // IN
return value;
}
/** Set the value contained by a user GPR.
*
* Sets the value contained by a user GPR. It is the same than
* SetGPR but mode can be different from the running mode.
*
* @param mode the mode of banked register
* @param idx the register index
* @param val the value to set
*/
void SetBankedRegister( uint8_t foreign_mode, uint32_t idx, uint32_t value )
{
uint8_t running_mode = cpsr.Get( M );
if (running_mode == foreign_mode) return SetGPR( idx, value );
GetMode(running_mode).Swap(*this); // OUT
GetMode(foreign_mode).Swap(*this); // IN
SetGPR( idx, value );
GetMode(foreign_mode).Swap(*this); // OUT
GetMode(running_mode).Swap(*this); // IN
}
/************************************************************************/
/* Exception handling START */
/************************************************************************/
public:
bool Test( bool cond ) { return cond; }
virtual void UnpredictableInsnBehaviour();
void CallSupervisor( uint32_t imm );
bool IntegerZeroDivide( bool zero_div ) { return zero_div; }
virtual void WaitForInterrupt() {}; // Implementation-defined
protected:
uint32_t HandleAsynchronousException( uint32_t );
uint32_t ExcVectorBase();
void TakeReset();
void TakePhysicalFIQorIRQException( bool isIRQ );
virtual void BranchToFIQorIRQvector( bool isIRQ );
void TakeSVCException();
void TakeDataOrPrefetchAbortException( bool isdata );
void TakeUndefInstrException();
/************************************************************************/
/* Exception handling END */
/************************************************************************/
/**************************/
/* CP15 Interface START */
/**************************/
public:
struct CP15Reg
{
virtual ~CP15Reg() {}
virtual void CheckPermissions(uint8_t, uint8_t, uint8_t, uint8_t, CPU_IMPL& cpu, bool) const { cpu.RequiresPL(1); }
virtual void Write(uint8_t crn, uint8_t op1, uint8_t crm, uint8_t op2, CPU_IMPL& cpu, uint32_t value) const
{
cpu.logger << unisim::kernel::logger::DebugError << "Writing " << Description(crn, op1, crm, op2)
<< " (pc=" << std::hex << cpu.current_insn_addr << std::dec << ")" << unisim::kernel::logger::EndDebugError;
cpu.UnpredictableInsnBehaviour();
}
virtual uint32_t Read(uint8_t crn, uint8_t op1, uint8_t crm, uint8_t op2, CPU_IMPL& cpu) const
{
cpu.logger << unisim::kernel::logger::DebugError << "Reading " << Description(crn, op1, crm, op2)
<< " (pc=" << std::hex << cpu.current_insn_addr << std::dec << ")" << unisim::kernel::logger::EndDebugError;
cpu.UnpredictableInsnBehaviour();
return 0;
}
virtual void Describe(uint8_t crn, uint8_t op1, uint8_t crm, uint8_t op2, std::ostream& sink) const
{
sink << Description(crn, op1, crm, op2);
}
struct Description
{
Description(uint8_t _crn, uint8_t _op1, uint8_t _crm, uint8_t _op2) : crn(_crn), op1(_op1), crm(_crm), op2(_op2) {}
friend std::ostream& operator << (std::ostream& sink, Description const& d)
{ return sink << "CR15{crn=" << int(d.crn) << ", op1=" << int(d.op1) << ", crm=" << int(d.crm) << ", op2=" << int(d.op2) << "}"; }
uint8_t crn; uint8_t op1; uint8_t crm; uint8_t op2;
};
};
static CP15Reg* CP15GetRegister(uint8_t crn, uint8_t op1, uint8_t crm, uint8_t op2);
void CP15ResetRegisters();
/**************************/
/* CP15 Interface END */
/**************************/
protected:
/*
* Memory access variables
*/
/* Storage for Modes and banked registers */
typedef std::map<uint8_t, Mode*> ModeMap;
ModeMap modes;
/** Storage for the logical registers */
uint32_t gpr[num_log_gprs];
uint32_t current_insn_addr, next_insn_addr;
/** PSR registers */
PSR cpsr;
/***********************************/
/* System control registers START */
/***********************************/
uint32_t SCTLR; //< System Control Register
uint32_t CPACR; //< CPACR, Coprocessor Access Control Register
/***********************************/
/* System control registers END */
/***********************************/
/****************************************************/
/* Process, context and thread ID registers START */
/****************************************************/
uint32_t CONTEXTIDR; //< Context ID Register
uint32_t TPIDRURW; //< User Read/Write Thread ID Register
uint32_t TPIDRURO; //< User Read-Only Thread ID Register
uint32_t TPIDRPRW; //< PL1 only Thread ID Register
/****************************************************/
/* Process, context and thread ID registers END */
/****************************************************/
public:
// VFP/NEON registers
virtual void FPTrap( unsigned fpx ) { throw std::logic_error("unimplemented FP trap"); }
U32 FPSCR, FPEXC;
U32 RoundTowardsZeroFPSCR() const { U32 fpscr = FPSCR; RMode.Set( fpscr, U32(RoundTowardsZero) ); return fpscr; }
U32 RoundToNearestFPSCR() const { U32 fpscr = FPSCR; RMode.Set( fpscr, U32(RoundToNearest) ); return fpscr; }
U32 StandardValuedFPSCR() const { return AHP.Mask( FPSCR ) | 0x03000000; }
static unsigned const VECTORCOUNT = 32;
struct VUConfig
{
static unsigned const BYTECOUNT = 8;
template <typename T> using TypeInfo = unisim::component::cxx::vector::VectorTypeInfo<T,0>;
typedef U8 Byte;
};
unisim::component::cxx::vector::VUnion<VUConfig> vector_views[VECTORCOUNT];
uint8_t vector_data[VECTORCOUNT][VUConfig::BYTECOUNT];
//====================================================================
//= Special Registers access methods
//====================================================================
template <typename T>
T vector_read(unsigned reg, unsigned sub)
{
return (vector_views[reg].GetConstStorage(&vector_data[reg], T(), VUConfig::BYTECOUNT))[sub];
}
U32 GetVSU( unsigned reg ) { return vector_read<U32> (reg/2, reg%2); }
U64 GetVDU( unsigned reg ) { return vector_read<U64> (reg, 0); }
F32 GetVSR( unsigned reg ) { return vector_read<F32> (reg/2, reg%2); }
F64 GetVDR( unsigned reg ) { return vector_read<F64> (reg, 0); }
template <class ELEMT>
ELEMT GetVDE( unsigned reg, unsigned idx, ELEMT const& trait )
{
return ELEMT( vector_read<ELEMT>(reg, idx) );
}
U8 GetTVU8(unsigned r0, unsigned elts, unsigned regs, U8 idx, U8 oob)
{
auto r = idx/elts;
return r < regs ? GetVDE((r0 + r) % 32, idx % elts, U8()) : oob;
}
template <typename T>
void vector_write(unsigned reg, unsigned sub, T value )
{
(vector_views[reg].GetStorage(&vector_data[reg], value, VUConfig::BYTECOUNT))[sub] = value;
}
void SetVSU( unsigned reg, U32 const& val ) { vector_write( reg/2, reg%2, val ); }
void SetVDU( unsigned reg, U64 const& val ) { vector_write( reg, 0, val ); }
void SetVSR( unsigned reg, F32 const& val ) { vector_write( reg/2, reg%2, val ); }
void SetVDR( unsigned reg, F64 const& val ) { vector_write( reg, 0, val ); }
template <class ELEMT>
void SetVDE( unsigned reg, unsigned idx, ELEMT const& value )
{
vector_write(reg, idx, value);
}
/*************************************/
/* Debug Registers START */
/*************************************/
public:
virtual unisim::service::interfaces::Register* GetRegister( const char* name );
virtual void ScanRegisters( unisim::service::interfaces::RegisterScanner& scanner );
unisim::kernel::ServiceExport<unisim::service::interfaces::Registers> registers_export;
protected:
/** The registers interface for debugging purpose */
typedef std::map<std::string, unisim::service::interfaces::Register*> RegistersRegistry;
RegistersRegistry registers_registry;
typedef std::set<unisim::kernel::VariableBase*> VariableRegisterPool;
VariableRegisterPool variable_register_pool;
/*************************************/
/* Debug Registers END */
/*************************************/
virtual void Sync() = 0;
};
} // end of namespace arm
} // end of namespace processor
} // end of namespace cxx
} // end of namespace component
} // end of namespace unisim
#endif // __UNISIM_COMPONENT_CXX_PROCESSOR_ARM_CPU_HH__
| 35.481273 | 136 | 0.601837 | [
"object",
"vector"
] |
1206a44a31e6dc4d5d1f53b4cb7b638a4ae788ed | 485 | hpp | C++ | projects/PolyhedralModel/projects/spmd-generator/toolboxes/rose-toolbox.hpp | maurizioabba/rose | 7597292cf14da292bdb9a4ef573001b6c5b9b6c0 | [
"BSD-3-Clause"
] | 4 | 2015-03-17T13:52:21.000Z | 2022-01-12T05:32:47.000Z | projects/PolyhedralModel/projects/spmd-generator/toolboxes/rose-toolbox.hpp | sujankh/rose-matlab | 7435d4fa1941826c784ba97296c0ec55fa7d7c7e | [
"BSD-3-Clause"
] | null | null | null | projects/PolyhedralModel/projects/spmd-generator/toolboxes/rose-toolbox.hpp | sujankh/rose-matlab | 7435d4fa1941826c784ba97296c0ec55fa7d7c7e | [
"BSD-3-Clause"
] | 2 | 2019-02-19T01:27:51.000Z | 2019-02-19T12:29:49.000Z |
#ifndef __ROSE_TOOLBOX_HPP__
#define __ROSE_TOOLBOX_HPP__
#include <vector>
#include <utility>
class SgExpression;
#include "rose/Variable.hpp"
SgExpression * vecToExp(std::vector<std::pair<RoseVariable, int> > & vec);
SgExpression * genAnd(std::vector<SgExpression *> & terms);
SgExpression * genMin(std::vector<SgExpression *> & terms);
SgExpression * genMax(std::vector<SgExpression *> & terms);
SgExpression * simplify(SgExpression * exp);
#endif /* __ROSE_TOOLBOX_HPP__ */
| 24.25 | 74 | 0.750515 | [
"vector"
] |
1209800588304b3193ad33e334bcd963fc8e6c0f | 5,232 | cpp | C++ | src/GrassObject.cpp | YuqiaoZhang/ResponsiveGrassDemo | 3b5a5c0fdd45e5433ca7bf64139140458c34078f | [
"BSD-3-Clause"
] | null | null | null | src/GrassObject.cpp | YuqiaoZhang/ResponsiveGrassDemo | 3b5a5c0fdd45e5433ca7bf64139140458c34078f | [
"BSD-3-Clause"
] | null | null | null | src/GrassObject.cpp | YuqiaoZhang/ResponsiveGrassDemo | 3b5a5c0fdd45e5433ca7bf64139140458c34078f | [
"BSD-3-Clause"
] | null | null | null | /**
* (c) Klemens Jahrmann
* klemens.jahrmann@net1220.at
*/
#include "GrassObject.h"
GrassObject::GrassObject(const std::string& filename, const SceneObjectGeometry::BasicGeometry type, const glm::vec3& scale, const bool generatePhysicalObject, const float staticFriction, const float dynamicFriction, const float restitution, const float angularDamping, const float physicalDensity, const std::vector<GrassCreateBladeParams>& params, Shader* drawShader, const bool isStatic, glm::mat4& position, const glm::vec4& tessellationProps, const glm::vec4& textureTileAndOffset, const glm::vec4& heightMapTileAndOffset, float ambientCoefficient, float diffuseCoefficient, float specularCoefficient, float specularExponent)
: SceneObject(drawShader, 0, isStatic, position, tessellationProps, textureTileAndOffset, heightMapTileAndOffset, ambientCoefficient, diffuseCoefficient, specularCoefficient, specularExponent), grass(0), faces()
{
AssimpImporter::ImportModel* model = AssimpImporter::importModel(filename);
if (model == 0)
{
std::cout << "ERROR GrassObject: Could not load model!" << std::endl;
return;
}
std::vector<AssimpImporter::ImportModel*> models;
std::vector<glm::mat4> modelMatrices;
models.push_back(model);
modelMatrices.push_back(glm::mat4(1.0f));
float xMin = FLT_MAX;
float yMin = FLT_MAX;
float zMin = FLT_MAX;
float xMax = -FLT_MAX;
float yMax = -FLT_MAX;
float zMax = -FLT_MAX;
for (unsigned int i = 0; i < models.size(); i++)
{
AssimpImporter::ImportModel* m = models[i];
glm::mat4 modMatrix = modelMatrices[i];
glm::mat3 invTrans = glm::inverse(glm::transpose(glm::mat3(modMatrix)));
for (unsigned int j = 0; j < m->index.size(); j += 3)
{
Geometry::Vertex v1;
v1.position = glm::vec3(modMatrix * glm::vec4(m->position[m->index[j]] * scale, 1.0f));
v1.normal = invTrans * m->normal[m->index[j]];
if (m->tangent.size() > 0)
v1.tangent = invTrans * m->tangent[m->index[j]];
if (m->bitangent.size() > 0)
v1.bitangent = invTrans * m->bitangent[m->index[j]];
Geometry::Vertex v2;
v2.position = glm::vec3(modMatrix * glm::vec4(m->position[m->index[j + 1]] * scale, 1.0f));
v2.normal = invTrans * m->normal[m->index[j + 1]];
if (m->tangent.size() > 0)
v2.tangent = invTrans * m->tangent[m->index[j + 1]];
if (m->bitangent.size() > 0)
v2.bitangent = invTrans * m->bitangent[m->index[j + 1]];
Geometry::Vertex v3;
v3.position = glm::vec3(modMatrix * glm::vec4(m->position[m->index[j + 2]] * scale, 1.0f));
v3.normal = invTrans * m->normal[m->index[j + 2]];
if (m->tangent.size() > 0)
v3.tangent = invTrans * m->tangent[m->index[j + 2]];
if (m->bitangent.size() > 0)
v3.bitangent = invTrans * m->bitangent[m->index[j + 2]];
xMin = glm::min(xMin, glm::min(v1.position.x, glm::min(v2.position.x, v3.position.x)));
yMin = glm::min(yMin, glm::min(v1.position.y, glm::min(v2.position.y, v3.position.y)));
zMin = glm::min(zMin, glm::min(v1.position.z, glm::min(v2.position.z, v3.position.z)));
xMax = glm::max(xMax, glm::max(v1.position.x, glm::max(v2.position.x, v3.position.x)));
yMax = glm::max(yMax, glm::max(v1.position.y, glm::max(v2.position.y, v3.position.y)));
zMax = glm::max(zMax, glm::max(v1.position.z, glm::max(v2.position.z, v3.position.z)));
Geometry::TriangleFace f(v1,v2,v3);
faces.push_back(f);
}
for (unsigned int j = 0; j < m->children.size(); j++)
{
models.push_back(m->children[j]);
modelMatrices.push_back(m->children[j]->transform * modMatrix);
}
}
Clock c;
c.Tick();
grass = new Grass(params, faces);
c.Tick();
std::cout << "Grass generation time: " << std::to_string(c.LastFrameTime()) << std::endl;
grass->parentObject = this;
attachGeometry(new SceneObjectGeometry(model, type, scale, false, false, 0, generatePhysicalObject, staticFriction, dynamicFriction, restitution, angularDamping, physicalDensity));
float maxBladeHeight = -FLT_MAX;
for (auto p : params)
{
maxBladeHeight = glm::max(maxBladeHeight, p.bladeMaxHeight);
}
bounds->inflate(glm::vec3(maxBladeHeight, maxBladeHeight, maxBladeHeight));
}
GrassObject::GrassObject(const GrassObject& other) : SceneObject(other), grass(0), faces(other.faces)
{
if (other.grass != 0)
{
grass = new Grass(*other.grass);
}
}
GrassObject::GrassObject(const GrassObject& other, const std::vector<GrassCreateBladeParams>& params) : SceneObject(other), grass(0), faces(other.faces)
{
grass = new Grass(params, faces);
grass->parentObject = this;
bounds = geometry->getBoundingObject();
float maxBladeHeight = -FLT_MAX;
for (auto p : params)
{
maxBladeHeight = glm::max(maxBladeHeight, p.bladeMaxHeight);
}
bounds->inflate(glm::vec3(maxBladeHeight, maxBladeHeight, maxBladeHeight));
}
GrassObject::~GrassObject()
{
}
void GrassObject::update(const Camera& cam, const Clock& time)
{
SceneObject::update(cam, time);
}
void GrassObject::draw(const Camera& cam)
{
if (visible)
{
SceneObject::draw(cam);
}
}
void GrassObject::drawGrass(const Camera& cam, const Clock& time)
{
if (visible)
{
grass->Draw((float)time.LastFrameTime(), cam);
}
}
void GrassObject::parentDraw(glm::mat4& parentMatrix)
{
if (visible)
{
SceneObject::parentDraw(parentMatrix);
}
} | 34.88 | 630 | 0.692469 | [
"geometry",
"vector",
"model",
"transform"
] |
120ba7a59a69d03c2ca72ebd3fa41c389a2bfe41 | 27,658 | cpp | C++ | media/codec2/components/gav1/C2SoftGav1Dec.cpp | Dreadwyrm/lhos_frameworks_av | 62c63ccfdf5c79a3ad9be4836f473da9398c671b | [
"Apache-2.0"
] | null | null | null | media/codec2/components/gav1/C2SoftGav1Dec.cpp | Dreadwyrm/lhos_frameworks_av | 62c63ccfdf5c79a3ad9be4836f473da9398c671b | [
"Apache-2.0"
] | null | null | null | media/codec2/components/gav1/C2SoftGav1Dec.cpp | Dreadwyrm/lhos_frameworks_av | 62c63ccfdf5c79a3ad9be4836f473da9398c671b | [
"Apache-2.0"
] | 2 | 2021-07-08T07:42:11.000Z | 2021-07-09T21:56:10.000Z | /*
* Copyright (C) 2019 The Android Open Source Project
*
* 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.
*/
//#define LOG_NDEBUG 0
#define LOG_TAG "C2SoftGav1Dec"
#include "C2SoftGav1Dec.h"
#include <C2Debug.h>
#include <C2PlatformSupport.h>
#include <SimpleC2Interface.h>
#include <log/log.h>
#include <media/stagefright/foundation/AUtils.h>
#include <media/stagefright/foundation/MediaDefs.h>
namespace android {
// codecname set and passed in as a compile flag from Android.bp
constexpr char COMPONENT_NAME[] = CODECNAME;
class C2SoftGav1Dec::IntfImpl : public SimpleInterface<void>::BaseParams {
public:
explicit IntfImpl(const std::shared_ptr<C2ReflectorHelper> &helper)
: SimpleInterface<void>::BaseParams(
helper, COMPONENT_NAME, C2Component::KIND_DECODER,
C2Component::DOMAIN_VIDEO, MEDIA_MIMETYPE_VIDEO_AV1) {
noPrivateBuffers(); // TODO: account for our buffers here.
noInputReferences();
noOutputReferences();
noInputLatency();
noTimeStretch();
addParameter(DefineParam(mAttrib, C2_PARAMKEY_COMPONENT_ATTRIBUTES)
.withConstValue(new C2ComponentAttributesSetting(
C2Component::ATTRIB_IS_TEMPORAL))
.build());
addParameter(
DefineParam(mSize, C2_PARAMKEY_PICTURE_SIZE)
.withDefault(new C2StreamPictureSizeInfo::output(0u, 320, 240))
.withFields({
C2F(mSize, width).inRange(2, 2048, 2),
C2F(mSize, height).inRange(2, 2048, 2),
})
.withSetter(SizeSetter)
.build());
addParameter(DefineParam(mProfileLevel, C2_PARAMKEY_PROFILE_LEVEL)
.withDefault(new C2StreamProfileLevelInfo::input(
0u, C2Config::PROFILE_AV1_0, C2Config::LEVEL_AV1_2_1))
.withFields({C2F(mProfileLevel, profile)
.oneOf({C2Config::PROFILE_AV1_0,
C2Config::PROFILE_AV1_1}),
C2F(mProfileLevel, level)
.oneOf({
C2Config::LEVEL_AV1_2,
C2Config::LEVEL_AV1_2_1,
C2Config::LEVEL_AV1_2_2,
C2Config::LEVEL_AV1_3,
C2Config::LEVEL_AV1_3_1,
C2Config::LEVEL_AV1_3_2,
})})
.withSetter(ProfileLevelSetter, mSize)
.build());
mHdr10PlusInfoInput = C2StreamHdr10PlusInfo::input::AllocShared(0);
addParameter(
DefineParam(mHdr10PlusInfoInput, C2_PARAMKEY_INPUT_HDR10_PLUS_INFO)
.withDefault(mHdr10PlusInfoInput)
.withFields({
C2F(mHdr10PlusInfoInput, m.value).any(),
})
.withSetter(Hdr10PlusInfoInputSetter)
.build());
mHdr10PlusInfoOutput = C2StreamHdr10PlusInfo::output::AllocShared(0);
addParameter(
DefineParam(mHdr10PlusInfoOutput, C2_PARAMKEY_OUTPUT_HDR10_PLUS_INFO)
.withDefault(mHdr10PlusInfoOutput)
.withFields({
C2F(mHdr10PlusInfoOutput, m.value).any(),
})
.withSetter(Hdr10PlusInfoOutputSetter)
.build());
addParameter(
DefineParam(mMaxSize, C2_PARAMKEY_MAX_PICTURE_SIZE)
.withDefault(new C2StreamMaxPictureSizeTuning::output(0u, 320, 240))
.withFields({
C2F(mSize, width).inRange(2, 2048, 2),
C2F(mSize, height).inRange(2, 2048, 2),
})
.withSetter(MaxPictureSizeSetter, mSize)
.build());
addParameter(DefineParam(mMaxInputSize, C2_PARAMKEY_INPUT_MAX_BUFFER_SIZE)
.withDefault(new C2StreamMaxBufferSizeInfo::input(
0u, 320 * 240 * 3 / 4))
.withFields({
C2F(mMaxInputSize, value).any(),
})
.calculatedAs(MaxInputSizeSetter, mMaxSize)
.build());
C2ChromaOffsetStruct locations[1] = {C2ChromaOffsetStruct::ITU_YUV_420_0()};
std::shared_ptr<C2StreamColorInfo::output> defaultColorInfo =
C2StreamColorInfo::output::AllocShared(1u, 0u, 8u /* bitDepth */,
C2Color::YUV_420);
memcpy(defaultColorInfo->m.locations, locations, sizeof(locations));
defaultColorInfo = C2StreamColorInfo::output::AllocShared(
{C2ChromaOffsetStruct::ITU_YUV_420_0()}, 0u, 8u /* bitDepth */,
C2Color::YUV_420);
helper->addStructDescriptors<C2ChromaOffsetStruct>();
addParameter(DefineParam(mColorInfo, C2_PARAMKEY_CODED_COLOR_INFO)
.withConstValue(defaultColorInfo)
.build());
addParameter(
DefineParam(mDefaultColorAspects, C2_PARAMKEY_DEFAULT_COLOR_ASPECTS)
.withDefault(new C2StreamColorAspectsTuning::output(
0u, C2Color::RANGE_UNSPECIFIED, C2Color::PRIMARIES_UNSPECIFIED,
C2Color::TRANSFER_UNSPECIFIED, C2Color::MATRIX_UNSPECIFIED))
.withFields(
{C2F(mDefaultColorAspects, range)
.inRange(C2Color::RANGE_UNSPECIFIED, C2Color::RANGE_OTHER),
C2F(mDefaultColorAspects, primaries)
.inRange(C2Color::PRIMARIES_UNSPECIFIED,
C2Color::PRIMARIES_OTHER),
C2F(mDefaultColorAspects, transfer)
.inRange(C2Color::TRANSFER_UNSPECIFIED,
C2Color::TRANSFER_OTHER),
C2F(mDefaultColorAspects, matrix)
.inRange(C2Color::MATRIX_UNSPECIFIED,
C2Color::MATRIX_OTHER)})
.withSetter(DefaultColorAspectsSetter)
.build());
// TODO: support more formats?
addParameter(DefineParam(mPixelFormat, C2_PARAMKEY_PIXEL_FORMAT)
.withConstValue(new C2StreamPixelFormatInfo::output(
0u, HAL_PIXEL_FORMAT_YCBCR_420_888))
.build());
}
static C2R SizeSetter(bool mayBlock,
const C2P<C2StreamPictureSizeInfo::output> &oldMe,
C2P<C2StreamPictureSizeInfo::output> &me) {
(void)mayBlock;
C2R res = C2R::Ok();
if (!me.F(me.v.width).supportsAtAll(me.v.width)) {
res = res.plus(C2SettingResultBuilder::BadValue(me.F(me.v.width)));
me.set().width = oldMe.v.width;
}
if (!me.F(me.v.height).supportsAtAll(me.v.height)) {
res = res.plus(C2SettingResultBuilder::BadValue(me.F(me.v.height)));
me.set().height = oldMe.v.height;
}
return res;
}
static C2R MaxPictureSizeSetter(
bool mayBlock, C2P<C2StreamMaxPictureSizeTuning::output> &me,
const C2P<C2StreamPictureSizeInfo::output> &size) {
(void)mayBlock;
// TODO: get max width/height from the size's field helpers vs.
// hardcoding
me.set().width = c2_min(c2_max(me.v.width, size.v.width), 4096u);
me.set().height = c2_min(c2_max(me.v.height, size.v.height), 4096u);
return C2R::Ok();
}
static C2R MaxInputSizeSetter(
bool mayBlock, C2P<C2StreamMaxBufferSizeInfo::input> &me,
const C2P<C2StreamMaxPictureSizeTuning::output> &maxSize) {
(void)mayBlock;
// assume compression ratio of 2
me.set().value =
(((maxSize.v.width + 63) / 64) * ((maxSize.v.height + 63) / 64) * 3072);
return C2R::Ok();
}
static C2R DefaultColorAspectsSetter(
bool mayBlock, C2P<C2StreamColorAspectsTuning::output> &me) {
(void)mayBlock;
if (me.v.range > C2Color::RANGE_OTHER) {
me.set().range = C2Color::RANGE_OTHER;
}
if (me.v.primaries > C2Color::PRIMARIES_OTHER) {
me.set().primaries = C2Color::PRIMARIES_OTHER;
}
if (me.v.transfer > C2Color::TRANSFER_OTHER) {
me.set().transfer = C2Color::TRANSFER_OTHER;
}
if (me.v.matrix > C2Color::MATRIX_OTHER) {
me.set().matrix = C2Color::MATRIX_OTHER;
}
return C2R::Ok();
}
static C2R ProfileLevelSetter(
bool mayBlock, C2P<C2StreamProfileLevelInfo::input> &me,
const C2P<C2StreamPictureSizeInfo::output> &size) {
(void)mayBlock;
(void)size;
(void)me; // TODO: validate
return C2R::Ok();
}
std::shared_ptr<C2StreamColorAspectsTuning::output>
getDefaultColorAspects_l() {
return mDefaultColorAspects;
}
static C2R Hdr10PlusInfoInputSetter(bool mayBlock,
C2P<C2StreamHdr10PlusInfo::input> &me) {
(void)mayBlock;
(void)me; // TODO: validate
return C2R::Ok();
}
static C2R Hdr10PlusInfoOutputSetter(bool mayBlock,
C2P<C2StreamHdr10PlusInfo::output> &me) {
(void)mayBlock;
(void)me; // TODO: validate
return C2R::Ok();
}
private:
std::shared_ptr<C2StreamProfileLevelInfo::input> mProfileLevel;
std::shared_ptr<C2StreamPictureSizeInfo::output> mSize;
std::shared_ptr<C2StreamMaxPictureSizeTuning::output> mMaxSize;
std::shared_ptr<C2StreamMaxBufferSizeInfo::input> mMaxInputSize;
std::shared_ptr<C2StreamColorInfo::output> mColorInfo;
std::shared_ptr<C2StreamPixelFormatInfo::output> mPixelFormat;
std::shared_ptr<C2StreamColorAspectsTuning::output> mDefaultColorAspects;
std::shared_ptr<C2StreamHdr10PlusInfo::input> mHdr10PlusInfoInput;
std::shared_ptr<C2StreamHdr10PlusInfo::output> mHdr10PlusInfoOutput;
};
C2SoftGav1Dec::C2SoftGav1Dec(const char *name, c2_node_id_t id,
const std::shared_ptr<IntfImpl> &intfImpl)
: SimpleC2Component(
std::make_shared<SimpleInterface<IntfImpl>>(name, id, intfImpl)),
mIntf(intfImpl),
mCodecCtx(nullptr) {
gettimeofday(&mTimeStart, nullptr);
gettimeofday(&mTimeEnd, nullptr);
}
C2SoftGav1Dec::~C2SoftGav1Dec() { onRelease(); }
c2_status_t C2SoftGav1Dec::onInit() {
return initDecoder() ? C2_OK : C2_CORRUPTED;
}
c2_status_t C2SoftGav1Dec::onStop() {
mSignalledError = false;
mSignalledOutputEos = false;
return C2_OK;
}
void C2SoftGav1Dec::onReset() {
(void)onStop();
c2_status_t err = onFlush_sm();
if (err != C2_OK) {
ALOGW("Failed to flush the av1 decoder. Trying to hard reset.");
destroyDecoder();
if (!initDecoder()) {
ALOGE("Hard reset failed.");
}
}
}
void C2SoftGav1Dec::onRelease() { destroyDecoder(); }
c2_status_t C2SoftGav1Dec::onFlush_sm() {
Libgav1StatusCode status = mCodecCtx->SignalEOS();
if (status != kLibgav1StatusOk) {
ALOGE("Failed to flush av1 decoder. status: %d.", status);
return C2_CORRUPTED;
}
// Dequeue frame (if any) that was enqueued previously.
const libgav1::DecoderBuffer *buffer;
status = mCodecCtx->DequeueFrame(&buffer);
if (status != kLibgav1StatusOk && status != kLibgav1StatusNothingToDequeue) {
ALOGE("Failed to dequeue frame after flushing the av1 decoder. status: %d",
status);
return C2_CORRUPTED;
}
mSignalledError = false;
mSignalledOutputEos = false;
return C2_OK;
}
static int GetCPUCoreCount() {
int cpuCoreCount = 1;
#if defined(_SC_NPROCESSORS_ONLN)
cpuCoreCount = sysconf(_SC_NPROCESSORS_ONLN);
#else
// _SC_NPROC_ONLN must be defined...
cpuCoreCount = sysconf(_SC_NPROC_ONLN);
#endif
CHECK(cpuCoreCount >= 1);
ALOGV("Number of CPU cores: %d", cpuCoreCount);
return cpuCoreCount;
}
bool C2SoftGav1Dec::initDecoder() {
mSignalledError = false;
mSignalledOutputEos = false;
mCodecCtx.reset(new libgav1::Decoder());
if (mCodecCtx == nullptr) {
ALOGE("mCodecCtx is null");
return false;
}
libgav1::DecoderSettings settings = {};
settings.threads = GetCPUCoreCount();
ALOGV("Using libgav1 AV1 software decoder.");
Libgav1StatusCode status = mCodecCtx->Init(&settings);
if (status != kLibgav1StatusOk) {
ALOGE("av1 decoder failed to initialize. status: %d.", status);
return false;
}
return true;
}
void C2SoftGav1Dec::destroyDecoder() { mCodecCtx = nullptr; }
void fillEmptyWork(const std::unique_ptr<C2Work> &work) {
uint32_t flags = 0;
if (work->input.flags & C2FrameData::FLAG_END_OF_STREAM) {
flags |= C2FrameData::FLAG_END_OF_STREAM;
ALOGV("signalling eos");
}
work->worklets.front()->output.flags = (C2FrameData::flags_t)flags;
work->worklets.front()->output.buffers.clear();
work->worklets.front()->output.ordinal = work->input.ordinal;
work->workletsProcessed = 1u;
}
void C2SoftGav1Dec::finishWork(uint64_t index,
const std::unique_ptr<C2Work> &work,
const std::shared_ptr<C2GraphicBlock> &block) {
std::shared_ptr<C2Buffer> buffer =
createGraphicBuffer(block, C2Rect(mWidth, mHeight));
auto fillWork = [buffer, index](const std::unique_ptr<C2Work> &work) {
uint32_t flags = 0;
if ((work->input.flags & C2FrameData::FLAG_END_OF_STREAM) &&
(c2_cntr64_t(index) == work->input.ordinal.frameIndex)) {
flags |= C2FrameData::FLAG_END_OF_STREAM;
ALOGV("signalling eos");
}
work->worklets.front()->output.flags = (C2FrameData::flags_t)flags;
work->worklets.front()->output.buffers.clear();
work->worklets.front()->output.buffers.push_back(buffer);
work->worklets.front()->output.ordinal = work->input.ordinal;
work->workletsProcessed = 1u;
};
if (work && c2_cntr64_t(index) == work->input.ordinal.frameIndex) {
fillWork(work);
} else {
finish(index, fillWork);
}
}
void C2SoftGav1Dec::process(const std::unique_ptr<C2Work> &work,
const std::shared_ptr<C2BlockPool> &pool) {
work->result = C2_OK;
work->workletsProcessed = 0u;
work->worklets.front()->output.configUpdate.clear();
work->worklets.front()->output.flags = work->input.flags;
if (mSignalledError || mSignalledOutputEos) {
work->result = C2_BAD_VALUE;
return;
}
size_t inOffset = 0u;
size_t inSize = 0u;
C2ReadView rView = mDummyReadView;
if (!work->input.buffers.empty()) {
rView = work->input.buffers[0]->data().linearBlocks().front().map().get();
inSize = rView.capacity();
if (inSize && rView.error()) {
ALOGE("read view map failed %d", rView.error());
work->result = C2_CORRUPTED;
return;
}
}
bool codecConfig =
((work->input.flags & C2FrameData::FLAG_CODEC_CONFIG) != 0);
bool eos = ((work->input.flags & C2FrameData::FLAG_END_OF_STREAM) != 0);
ALOGV("in buffer attr. size %zu timestamp %d frameindex %d, flags %x", inSize,
(int)work->input.ordinal.timestamp.peeku(),
(int)work->input.ordinal.frameIndex.peeku(), work->input.flags);
if (codecConfig) {
fillEmptyWork(work);
return;
}
int64_t frameIndex = work->input.ordinal.frameIndex.peekll();
if (inSize) {
uint8_t *bitstream = const_cast<uint8_t *>(rView.data() + inOffset);
int32_t decodeTime = 0;
int32_t delay = 0;
GETTIME(&mTimeStart, nullptr);
TIME_DIFF(mTimeEnd, mTimeStart, delay);
const Libgav1StatusCode status =
mCodecCtx->EnqueueFrame(bitstream, inSize, frameIndex,
/*buffer_private_data=*/nullptr);
GETTIME(&mTimeEnd, nullptr);
TIME_DIFF(mTimeStart, mTimeEnd, decodeTime);
ALOGV("decodeTime=%4d delay=%4d\n", decodeTime, delay);
if (status != kLibgav1StatusOk) {
ALOGE("av1 decoder failed to decode frame. status: %d.", status);
work->result = C2_CORRUPTED;
work->workletsProcessed = 1u;
mSignalledError = true;
return;
}
}
(void)outputBuffer(pool, work);
if (eos) {
drainInternal(DRAIN_COMPONENT_WITH_EOS, pool, work);
mSignalledOutputEos = true;
} else if (!inSize) {
fillEmptyWork(work);
}
}
static void copyOutputBufferToYuvPlanarFrame(uint8_t *dst, const uint8_t *srcY,
const uint8_t *srcU,
const uint8_t *srcV, size_t srcYStride,
size_t srcUStride, size_t srcVStride,
size_t dstYStride, size_t dstUVStride,
uint32_t width, uint32_t height) {
uint8_t *const dstStart = dst;
for (size_t i = 0; i < height; ++i) {
memcpy(dst, srcY, width);
srcY += srcYStride;
dst += dstYStride;
}
dst = dstStart + dstYStride * height;
for (size_t i = 0; i < height / 2; ++i) {
memcpy(dst, srcV, width / 2);
srcV += srcVStride;
dst += dstUVStride;
}
dst = dstStart + (dstYStride * height) + (dstUVStride * height / 2);
for (size_t i = 0; i < height / 2; ++i) {
memcpy(dst, srcU, width / 2);
srcU += srcUStride;
dst += dstUVStride;
}
}
static void convertYUV420Planar16ToY410(uint32_t *dst, const uint16_t *srcY,
const uint16_t *srcU,
const uint16_t *srcV, size_t srcYStride,
size_t srcUStride, size_t srcVStride,
size_t dstStride, size_t width,
size_t height) {
// Converting two lines at a time, slightly faster
for (size_t y = 0; y < height; y += 2) {
uint32_t *dstTop = (uint32_t *)dst;
uint32_t *dstBot = (uint32_t *)(dst + dstStride);
uint16_t *ySrcTop = (uint16_t *)srcY;
uint16_t *ySrcBot = (uint16_t *)(srcY + srcYStride);
uint16_t *uSrc = (uint16_t *)srcU;
uint16_t *vSrc = (uint16_t *)srcV;
uint32_t u01, v01, y01, y23, y45, y67, uv0, uv1;
size_t x = 0;
for (; x < width - 3; x += 4) {
u01 = *((uint32_t *)uSrc);
uSrc += 2;
v01 = *((uint32_t *)vSrc);
vSrc += 2;
y01 = *((uint32_t *)ySrcTop);
ySrcTop += 2;
y23 = *((uint32_t *)ySrcTop);
ySrcTop += 2;
y45 = *((uint32_t *)ySrcBot);
ySrcBot += 2;
y67 = *((uint32_t *)ySrcBot);
ySrcBot += 2;
uv0 = (u01 & 0x3FF) | ((v01 & 0x3FF) << 20);
uv1 = (u01 >> 16) | ((v01 >> 16) << 20);
*dstTop++ = 3 << 30 | ((y01 & 0x3FF) << 10) | uv0;
*dstTop++ = 3 << 30 | ((y01 >> 16) << 10) | uv0;
*dstTop++ = 3 << 30 | ((y23 & 0x3FF) << 10) | uv1;
*dstTop++ = 3 << 30 | ((y23 >> 16) << 10) | uv1;
*dstBot++ = 3 << 30 | ((y45 & 0x3FF) << 10) | uv0;
*dstBot++ = 3 << 30 | ((y45 >> 16) << 10) | uv0;
*dstBot++ = 3 << 30 | ((y67 & 0x3FF) << 10) | uv1;
*dstBot++ = 3 << 30 | ((y67 >> 16) << 10) | uv1;
}
// There should be at most 2 more pixels to process. Note that we don't
// need to consider odd case as the buffer is always aligned to even.
if (x < width) {
u01 = *uSrc;
v01 = *vSrc;
y01 = *((uint32_t *)ySrcTop);
y45 = *((uint32_t *)ySrcBot);
uv0 = (u01 & 0x3FF) | ((v01 & 0x3FF) << 20);
*dstTop++ = ((y01 & 0x3FF) << 10) | uv0;
*dstTop++ = ((y01 >> 16) << 10) | uv0;
*dstBot++ = ((y45 & 0x3FF) << 10) | uv0;
*dstBot++ = ((y45 >> 16) << 10) | uv0;
}
srcY += srcYStride * 2;
srcU += srcUStride;
srcV += srcVStride;
dst += dstStride * 2;
}
}
static void convertYUV420Planar16ToYUV420Planar(
uint8_t *dst, const uint16_t *srcY, const uint16_t *srcU,
const uint16_t *srcV, size_t srcYStride, size_t srcUStride,
size_t srcVStride, size_t dstYStride, size_t dstUVStride,
size_t width, size_t height) {
uint8_t *dstY = (uint8_t *)dst;
size_t dstYSize = dstYStride * height;
size_t dstUVSize = dstUVStride * height / 2;
uint8_t *dstV = dstY + dstYSize;
uint8_t *dstU = dstV + dstUVSize;
for (size_t y = 0; y < height; ++y) {
for (size_t x = 0; x < width; ++x) {
dstY[x] = (uint8_t)(srcY[x] >> 2);
}
srcY += srcYStride;
dstY += dstYStride;
}
for (size_t y = 0; y < (height + 1) / 2; ++y) {
for (size_t x = 0; x < (width + 1) / 2; ++x) {
dstU[x] = (uint8_t)(srcU[x] >> 2);
dstV[x] = (uint8_t)(srcV[x] >> 2);
}
srcU += srcUStride;
srcV += srcVStride;
dstU += dstUVStride;
dstV += dstUVStride;
}
}
bool C2SoftGav1Dec::outputBuffer(const std::shared_ptr<C2BlockPool> &pool,
const std::unique_ptr<C2Work> &work) {
if (!(work && pool)) return false;
const libgav1::DecoderBuffer *buffer;
const Libgav1StatusCode status = mCodecCtx->DequeueFrame(&buffer);
if (status != kLibgav1StatusOk && status != kLibgav1StatusNothingToDequeue) {
ALOGE("av1 decoder DequeueFrame failed. status: %d.", status);
return false;
}
// |buffer| can be NULL if status was equal to kLibgav1StatusOk or
// kLibgav1StatusNothingToDequeue. This is not an error. This could mean one
// of two things:
// - The EnqueueFrame() call was either a flush (called with nullptr).
// - The enqueued frame did not have any displayable frames.
if (!buffer) {
return false;
}
const int width = buffer->displayed_width[0];
const int height = buffer->displayed_height[0];
if (width != mWidth || height != mHeight) {
mWidth = width;
mHeight = height;
C2StreamPictureSizeInfo::output size(0u, mWidth, mHeight);
std::vector<std::unique_ptr<C2SettingResult>> failures;
c2_status_t err = mIntf->config({&size}, C2_MAY_BLOCK, &failures);
if (err == C2_OK) {
work->worklets.front()->output.configUpdate.push_back(
C2Param::Copy(size));
} else {
ALOGE("Config update size failed");
mSignalledError = true;
work->result = C2_CORRUPTED;
work->workletsProcessed = 1u;
return false;
}
}
// TODO(vigneshv): Add support for monochrome videos since AV1 supports it.
CHECK(buffer->image_format == libgav1::kImageFormatYuv420);
std::shared_ptr<C2GraphicBlock> block;
uint32_t format = HAL_PIXEL_FORMAT_YV12;
if (buffer->bitdepth == 10) {
IntfImpl::Lock lock = mIntf->lock();
std::shared_ptr<C2StreamColorAspectsTuning::output> defaultColorAspects =
mIntf->getDefaultColorAspects_l();
if (defaultColorAspects->primaries == C2Color::PRIMARIES_BT2020 &&
defaultColorAspects->matrix == C2Color::MATRIX_BT2020 &&
defaultColorAspects->transfer == C2Color::TRANSFER_ST2084) {
format = HAL_PIXEL_FORMAT_RGBA_1010102;
}
}
C2MemoryUsage usage = {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
c2_status_t err = pool->fetchGraphicBlock(align(mWidth, 16), mHeight, format,
usage, &block);
if (err != C2_OK) {
ALOGE("fetchGraphicBlock for Output failed with status %d", err);
work->result = err;
return false;
}
C2GraphicView wView = block->map().get();
if (wView.error()) {
ALOGE("graphic view map failed %d", wView.error());
work->result = C2_CORRUPTED;
return false;
}
ALOGV("provided (%dx%d) required (%dx%d), out frameindex %d", block->width(),
block->height(), mWidth, mHeight, (int)buffer->user_private_data);
uint8_t *dst = const_cast<uint8_t *>(wView.data()[C2PlanarLayout::PLANE_Y]);
size_t srcYStride = buffer->stride[0];
size_t srcUStride = buffer->stride[1];
size_t srcVStride = buffer->stride[2];
C2PlanarLayout layout = wView.layout();
size_t dstYStride = layout.planes[C2PlanarLayout::PLANE_Y].rowInc;
size_t dstUVStride = layout.planes[C2PlanarLayout::PLANE_U].rowInc;
if (buffer->bitdepth == 10) {
const uint16_t *srcY = (const uint16_t *)buffer->plane[0];
const uint16_t *srcU = (const uint16_t *)buffer->plane[1];
const uint16_t *srcV = (const uint16_t *)buffer->plane[2];
if (format == HAL_PIXEL_FORMAT_RGBA_1010102) {
convertYUV420Planar16ToY410(
(uint32_t *)dst, srcY, srcU, srcV, srcYStride / 2, srcUStride / 2,
srcVStride / 2, dstYStride / sizeof(uint32_t), mWidth, mHeight);
} else {
convertYUV420Planar16ToYUV420Planar(dst, srcY, srcU, srcV, srcYStride / 2,
srcUStride / 2, srcVStride / 2,
dstYStride, dstUVStride, mWidth, mHeight);
}
} else {
const uint8_t *srcY = (const uint8_t *)buffer->plane[0];
const uint8_t *srcU = (const uint8_t *)buffer->plane[1];
const uint8_t *srcV = (const uint8_t *)buffer->plane[2];
copyOutputBufferToYuvPlanarFrame(dst, srcY, srcU, srcV, srcYStride, srcUStride,
srcVStride, dstYStride, dstUVStride,
mWidth, mHeight);
}
finishWork(buffer->user_private_data, work, std::move(block));
block = nullptr;
return true;
}
c2_status_t C2SoftGav1Dec::drainInternal(
uint32_t drainMode, const std::shared_ptr<C2BlockPool> &pool,
const std::unique_ptr<C2Work> &work) {
if (drainMode == NO_DRAIN) {
ALOGW("drain with NO_DRAIN: no-op");
return C2_OK;
}
if (drainMode == DRAIN_CHAIN) {
ALOGW("DRAIN_CHAIN not supported");
return C2_OMITTED;
}
const Libgav1StatusCode status = mCodecCtx->SignalEOS();
if (status != kLibgav1StatusOk) {
ALOGE("Failed to flush av1 decoder. status: %d.", status);
return C2_CORRUPTED;
}
while (outputBuffer(pool, work)) {
}
if (drainMode == DRAIN_COMPONENT_WITH_EOS && work &&
work->workletsProcessed == 0u) {
fillEmptyWork(work);
}
return C2_OK;
}
c2_status_t C2SoftGav1Dec::drain(uint32_t drainMode,
const std::shared_ptr<C2BlockPool> &pool) {
return drainInternal(drainMode, pool, nullptr);
}
class C2SoftGav1Factory : public C2ComponentFactory {
public:
C2SoftGav1Factory()
: mHelper(std::static_pointer_cast<C2ReflectorHelper>(
GetCodec2PlatformComponentStore()->getParamReflector())) {}
virtual c2_status_t createComponent(
c2_node_id_t id, std::shared_ptr<C2Component> *const component,
std::function<void(C2Component *)> deleter) override {
*component = std::shared_ptr<C2Component>(
new C2SoftGav1Dec(COMPONENT_NAME, id,
std::make_shared<C2SoftGav1Dec::IntfImpl>(mHelper)),
deleter);
return C2_OK;
}
virtual c2_status_t createInterface(
c2_node_id_t id, std::shared_ptr<C2ComponentInterface> *const interface,
std::function<void(C2ComponentInterface *)> deleter) override {
*interface = std::shared_ptr<C2ComponentInterface>(
new SimpleInterface<C2SoftGav1Dec::IntfImpl>(
COMPONENT_NAME, id,
std::make_shared<C2SoftGav1Dec::IntfImpl>(mHelper)),
deleter);
return C2_OK;
}
virtual ~C2SoftGav1Factory() override = default;
private:
std::shared_ptr<C2ReflectorHelper> mHelper;
};
} // namespace android
extern "C" ::C2ComponentFactory *CreateCodec2Factory() {
ALOGV("in %s", __func__);
return new ::android::C2SoftGav1Factory();
}
extern "C" void DestroyCodec2Factory(::C2ComponentFactory *factory) {
ALOGV("in %s", __func__);
delete factory;
}
| 35.323116 | 84 | 0.620182 | [
"vector"
] |
120ce80e5c0f1d8c6554c7b6eb2abc1730dc7dd6 | 101,548 | cpp | C++ | sdktools/debuggers/exts/extdll/analyze.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | sdktools/debuggers/exts/extdll/analyze.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | sdktools/debuggers/exts/extdll/analyze.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //----------------------------------------------------------------------------
//
// Generic failure analysis framework.
//
// Copyright (C) Microsoft Corporation, 2001.
//
//----------------------------------------------------------------------------
#include "precomp.h"
#pragma hdrstop
#include <time.h>
BOOL g_SymbolsReloaded;
HRESULT
ModuleParams::Update(void)
{
HRESULT Status;
ULONG i;
DEBUG_MODULE_PARAMETERS Params;
if (m_Valid)
{
return S_OK;
}
if ((Status = g_ExtSymbols->GetModuleByModuleName(m_Name, 0,
&i, &m_Base)) == S_OK &&
(Status = g_ExtSymbols->GetModuleParameters(1, &m_Base, i,
&Params)) == S_OK)
{
m_Size = Params.Size;
m_Valid = TRUE;
}
return Status;
}
// Read a null terminated string from the address specified.
BOOL ReadAcsiiString(ULONG64 Address, PCHAR DestBuffer, ULONG BufferLen)
{
ULONG OneByteRead;
ULONG BytesRead = 0;
if (Address && DestBuffer)
{
while (BufferLen && ReadMemory(Address, DestBuffer, 1, &OneByteRead))
{
BytesRead++;
if ((*DestBuffer) == 0)
{
return BytesRead;
}
BufferLen--;
DestBuffer++;
Address++;
}
}
return 0;
}
LONG
FaExceptionFilter(
struct _EXCEPTION_POINTERS *ExceptionInfo
)
{
ULONG Code = ExceptionInfo->ExceptionRecord->ExceptionCode;
if (Code == E_OUTOFMEMORY || Code == E_INVALIDARG)
{
// Expected exceptions that the analysis code
// can throw to terminate the analysis. Drop
// into the handler.
return EXCEPTION_EXECUTE_HANDLER;
}
// Otherwise this isn't an exception we expected.
// Let it continue on so that it isn't hidden and
// can be debugged.
return EXCEPTION_CONTINUE_SEARCH;
}
BOOL
FaGetSymbol(
ULONG64 Address,
PCHAR Name,
PULONG64 Disp,
ULONG NameSize
)
{
CHAR Buffer[MAX_PATH] = {0};
*Name = 0;
GetSymbol(Address, Name, Disp);
if (*Name == 0)
{
//
// Get the actual Image name from debugger module list
//
ULONG Index;
CHAR ModBuffer[100];
ULONG64 Base;
if (S_OK == g_ExtSymbols->
GetModuleByOffset(Address, 0, &Index, &Base))
{
if (g_ExtSymbols->
GetModuleNames(Index, Base,
ModBuffer, sizeof(ModBuffer), NULL,
NULL, 0, NULL,
NULL, 0, NULL) == S_OK)
{
PCHAR Break = strrchr(ModBuffer, '\\');
if (Break)
{
CopyString(ModBuffer, Break + 1, sizeof(ModBuffer));
}
CopyString(Name, ModBuffer, NameSize);
if (Break = strchr(Name, '.'))
{
*Break = 0;
}
*Disp = Address - Base;
}
}
}
return (*Name != 0);
}
BOOL
FaIsFunctionAddr(
ULONG64 IP,
PSTR FuncName
)
// Check if IP is in the function FuncName
{
static ULONG64 s_LastIP = 0;
static CHAR s_Buffer[MAX_PATH];
CHAR *Scan, *FnIP;
ULONG64 Disp;
if (s_LastIP != IP)
{
// This would make it faster for multiple IsFunctionAddr for same IP
GetSymbol(IP, s_Buffer, &Disp);
s_LastIP = IP;
}
if (Scan = strchr(s_Buffer, '!'))
{
FnIP = Scan + 1;
while (*FnIP == '_')
{
++FnIP;
}
}
else
{
FnIP = &s_Buffer[0];
}
return !strncmp(FnIP, FuncName, strlen(FuncName));
}
BOOL
FaGetFollowupInfo(
IN OPTIONAL ULONG64 Addr,
PCHAR SymbolName,
PCHAR Owner,
ULONG OwnerSize
)
{
EXT_TRIAGE_FOLLOWUP FollowUp = &_EFN_GetTriageFollowupFromSymbol;
DEBUG_TRIAGE_FOLLOWUP_INFO Info;
CHAR Buffer[MAX_PATH];
if (!*SymbolName)
{
ULONG64 Disp;
FaGetSymbol(Addr, Buffer, &Disp, sizeof(Buffer));
SymbolName = Buffer;
}
if (*SymbolName)
{
Info.SizeOfStruct = sizeof(Info);
Info.OwnerName = Owner;
Info.OwnerNameSize = (USHORT)OwnerSize;
if ((*FollowUp)(g_ExtClient, SymbolName, &Info) > TRIAGE_FOLLOWUP_IGNORE)
{
// This is an interesting routine to followup on
return TRUE;
}
}
if (Owner)
{
*Owner=0;
}
return FALSE;
}
HRESULT
FaGetPoolTagFollowup(
PCHAR szPoolTag,
PSTR Followup,
ULONG FollowupSize
)
{
ULONG PoolTag;
DEBUG_POOLTAG_DESCRIPTION TagDesc = {0};
PGET_POOL_TAG_DESCRIPTION pGetTagDesc = NULL;
TagDesc.SizeOfStruct = sizeof(TagDesc);
if (g_ExtControl->
GetExtensionFunction(0, "GetPoolTagDescription",
(FARPROC*)&pGetTagDesc) == S_OK &&
pGetTagDesc)
{
PoolTag = *((PULONG) szPoolTag);
if ((*pGetTagDesc)(PoolTag, &TagDesc) == S_OK)
{
PCHAR Dot;
if (Dot = strchr(TagDesc.Binary, '.'))
{
*Dot = 0;
}
if (TagDesc.Binary[0])
{
if (FaGetFollowupInfo(0, TagDesc.Binary, Followup, FollowupSize))
{
return S_OK;
}
}
if (TagDesc.Owner[0])
{
CopyString(Followup, TagDesc.Owner, FollowupSize);
return S_OK;
}
}
}
return E_FAIL;
}
ULONG64
FaGetImplicitStackOffset(
void
)
{
// IDebugRegisters::GetStackOffset not used since it
// ignores implicit context
ULONG64 Stk = 0;
switch (g_TargetMachine)
{
case IMAGE_FILE_MACHINE_I386:
Stk = GetExpression("@esp");
break;
case IMAGE_FILE_MACHINE_IA64:
Stk = GetExpression("@sp");
break;
case IMAGE_FILE_MACHINE_AMD64:
Stk = GetExpression("@rsp");
break;
}
return Stk;
}
DECLARE_API( analyze )
{
ULONG EventType, ProcId, ThreadId;
BOOL Force = FALSE;
BOOL ForceUser = FALSE;
INIT_API();
if (g_ExtControl->GetLastEventInformation(&EventType, &ProcId, &ThreadId,
NULL, 0, NULL,
NULL, 0, NULL) != S_OK)
{
ExtErr("Unable to get last event information\n");
goto Exit;
}
//
// Check for -f in both cases
//
PCSTR tmpArgs = args;
while (*args)
{
if (*args == '-')
{
++args;
if (*args == 'f')
{
Force = TRUE;
break;
} else if (!strncmp(args, "show",4))
{
Force = TRUE;
} else if (*args == 'u')
{
// could be use for user stack anlysis in k-mode
// ForceUser = TRUE;
}
}
++args;
}
args = tmpArgs;
//
// Call the correct routine to process the event.
//
if ((EventType == DEBUG_EVENT_EXCEPTION) || (Force == TRUE))
{
ULONG DebugType, DebugQual;
if (g_ExtControl->GetDebuggeeType(&DebugType, &DebugQual) != S_OK)
{
ExtErr("Unable to determine debuggee type\n");
Status = E_FAIL;
}
else
{
if (ForceUser)
{
DebugType = DEBUG_CLASS_USER_WINDOWS;
}
switch(DebugType)
{
case DEBUG_CLASS_KERNEL:
//
// For live debug sessions force the symbols to get reloaded
// the first time as we find many sessions where the
// debugger got reconnected and no module list exists.
// This also happens for user mode breaks in kd where the
// module list is wrong.
//
if ((g_TargetQualifier == DEBUG_KERNEL_CONNECTION) &&
(!g_SymbolsReloaded++))
{
g_ExtSymbols->Reload("");
}
Status = AnalyzeBugCheck(args);
break;
case DEBUG_CLASS_USER_WINDOWS:
Status = AnalyzeUserException(args);
break;
case DEBUG_CLASS_UNINITIALIZED:
ExtErr("No debuggee\n");
Status = E_FAIL;
default:
ExtErr("Unknown debuggee type\n");
Status = E_INVALIDARG;
}
}
}
else if (EventType == 0)
{
dprintf("The debuggee is ready to run\n");
Status = S_OK;
}
else
{
Status = E_NOINTERFACE;
}
if (Status == E_NOINTERFACE)
{
g_ExtControl->Execute(DEBUG_OUTCTL_ALL_CLIENTS, ".lastevent",
DEBUG_EXECUTE_DEFAULT);
}
Exit:
EXIT_API();
return Status;
}
HRESULT
_EFN_GetFailureAnalysis(
IN PDEBUG_CLIENT Client,
IN ULONG Flags,
OUT PDEBUG_FAILURE_ANALYSIS* Analysis
)
{
BOOL Enter = (g_ExtClient != Client);
HRESULT Hr;
if (Enter)
{
INIT_API();
}
ULONG DebugType, DebugQual;
if ((Hr = g_ExtControl->GetDebuggeeType(&DebugType,
&DebugQual)) != S_OK)
{
ExtErr("Unable to determine debuggee type\n");
}
else if (DebugType == DEBUG_CLASS_KERNEL)
{
BUGCHECK_ANALYSIS Bc;
*Analysis = (IDebugFailureAnalysis*)BcAnalyze(&Bc, Flags);
Hr = *Analysis ? S_OK : E_OUTOFMEMORY;
}
else if (DebugType == DEBUG_CLASS_USER_WINDOWS)
{
EX_STATE ExState;
*Analysis = (IDebugFailureAnalysis*)UeAnalyze(&ExState, Flags);
Hr = *Analysis ? S_OK : E_OUTOFMEMORY;
}
else
{
Hr = E_INVALIDARG;
}
if (Enter)
{
EXIT_API();
}
return Hr;
}
DECLARE_API( dumpfa )
{
INIT_API();
ULONG64 Address = GetExpression(args);
if (Address)
{
ULONG64 Data;
ULONG64 DataUsed;
ULONG EntrySize;
EntrySize = GetTypeSize("ext!_FA_ENTRY");
InitTypeRead(Address, ext!DebugFailureAnalysis);
Data = ReadField(m_Data);
DataUsed = ReadField(m_DataUsed);
g_ExtControl->Output(1, "DataUsed %x\n", (ULONG)DataUsed);
while (DataUsed > EntrySize)
{
ULONG FullSize;
InitTypeRead(Data, ext!_FA_ENTRY);
g_ExtControl->Output(1,
"Type = %08lx - Size = %x\n",
(ULONG)ReadField(Tag),
ReadField(DataSize));
FullSize = (ULONG)ReadField(FullSize);
Data += FullSize;
DataUsed -= FullSize;
}
}
EXIT_API();
return S_OK;
}
//----------------------------------------------------------------------------
//
// DebugFailureAnalysisImpl.
//
//----------------------------------------------------------------------------
#define FA_ALIGN(Size) (((Size) + 7) & ~7)
#define FA_GROW_BY 4096
#if DBG
#define SCORCH_ENTRY(Entry) \
memset((Entry) + 1, 0xdb, (Entry)->FullSize - sizeof(*(Entry)))
#else
#define SCORCH_ENTRY(Entry)
#endif
#define RAISE_ERROR(Code) RaiseException(Code, 0, 0, NULL)
DebugFailureAnalysis::DebugFailureAnalysis(void)
{
m_Refs = 1;
m_FailureClass = DEBUG_CLASS_UNINITIALIZED;
m_FailureType = DEBUG_FLR_UNKNOWN;
m_FailureCode = 0;
m_Data = NULL;
m_DataLen = 0;
m_DataUsed = 0;
ZeroMemory(PossibleFollowups, sizeof(PossibleFollowups));
BestClassFollowUp = (FlpClasses)0;
}
DebugFailureAnalysis::~DebugFailureAnalysis(void)
{
free(m_Data);
}
STDMETHODIMP
DebugFailureAnalysis::QueryInterface(
THIS_
IN REFIID InterfaceId,
OUT PVOID* Interface
)
{
HRESULT Status;
*Interface = NULL;
Status = S_OK;
if (IsEqualIID(InterfaceId, IID_IUnknown) ||
IsEqualIID(InterfaceId, __uuidof(IDebugFailureAnalysis)))
{
*Interface = (IDebugFailureAnalysis *)this;
AddRef();
}
else
{
Status = E_NOINTERFACE;
}
return Status;
}
STDMETHODIMP_(ULONG)
DebugFailureAnalysis::AddRef(
THIS
)
{
return InterlockedIncrement((PLONG)&m_Refs);
}
STDMETHODIMP_(ULONG)
DebugFailureAnalysis::Release(
THIS
)
{
LONG Refs = InterlockedDecrement((PLONG)&m_Refs);
if (Refs == 0)
{
delete this;
}
return Refs;
}
STDMETHODIMP_(ULONG)
DebugFailureAnalysis::GetFailureClass(void)
{
return m_FailureClass;
}
STDMETHODIMP_(DEBUG_FAILURE_TYPE)
DebugFailureAnalysis::GetFailureType(void)
{
return m_FailureType;
}
STDMETHODIMP_(ULONG)
DebugFailureAnalysis::GetFailureCode(void)
{
return m_FailureCode;
}
STDMETHODIMP_(FA_ENTRY*)
DebugFailureAnalysis::Get(FA_TAG Tag)
{
FA_ENTRY* Entry = NULL;
while ((Entry = NextEntry(Entry)) != NULL)
{
if (Entry->Tag == Tag)
{
return Entry;
}
}
return NULL;
}
STDMETHODIMP_(FA_ENTRY*)
DebugFailureAnalysis::GetNext(FA_ENTRY* Entry, FA_TAG Tag, FA_TAG TagMask)
{
while ((Entry = NextEntry(Entry)) != NULL)
{
if ((Entry->Tag & TagMask) == Tag)
{
return Entry;
}
}
return NULL;
}
STDMETHODIMP_(FA_ENTRY*)
DebugFailureAnalysis::GetString(FA_TAG Tag, PSTR Str, ULONG MaxSize)
{
FA_ENTRY* Entry = Get(Tag);
if (Entry != NULL)
{
if (Entry->DataSize > MaxSize)
{
return NULL;
}
CopyString(Str, FA_ENTRY_DATA(PSTR, Entry),MaxSize);
}
return Entry;
}
STDMETHODIMP_(FA_ENTRY*)
DebugFailureAnalysis::GetBuffer(FA_TAG Tag, PVOID Buf, ULONG Size)
{
FA_ENTRY* Entry = Get(Tag);
if (Entry != NULL)
{
if (Entry->DataSize != Size)
{
return NULL;
}
memcpy(Buf, FA_ENTRY_DATA(PUCHAR, Entry), Size);
}
return Entry;
}
STDMETHODIMP_(FA_ENTRY*)
DebugFailureAnalysis::GetUlong(FA_TAG Tag, PULONG Value)
{
return GetBuffer(Tag, Value, sizeof(*Value));
}
STDMETHODIMP_(FA_ENTRY*)
DebugFailureAnalysis::GetUlong64(FA_TAG Tag, PULONG64 Value)
{
return GetBuffer(Tag, Value, sizeof(*Value));
}
STDMETHODIMP_(FA_ENTRY*)
DebugFailureAnalysis::NextEntry(FA_ENTRY* Entry)
{
if (Entry == NULL)
{
Entry = (FA_ENTRY*)m_Data;
}
else
{
Entry = (FA_ENTRY*)((PUCHAR)Entry + Entry->FullSize);
}
if (ValidEntry(Entry))
{
return Entry;
}
else
{
return NULL;
}
}
FA_ENTRY*
DebugFailureAnalysis::Set(FA_TAG Tag, ULONG Size)
{
FA_ENTRY* Entry;
ULONG FullSize;
// Compute full rounded size.
FullSize = sizeof(FA_ENTRY) + FA_ALIGN(Size);
// Check and see if there's already an entry.
Entry = Get(Tag);
if (Entry != NULL)
{
// If it's already large enough use it and
// pack in remaining data.
if (Entry->FullSize >= FullSize)
{
ULONG Pack = Entry->FullSize - FullSize;
if (Pack > 0)
{
PackData((PUCHAR)Entry + FullSize, Pack);
Entry->FullSize = (USHORT)FullSize;
}
Entry->DataSize = (USHORT)Size;
SCORCH_ENTRY(Entry);
return Entry;
}
// Entry is too small so remove it.
PackData((PUCHAR)Entry, Entry->FullSize);
}
return Add(Tag, Size);
}
FA_ENTRY*
DebugFailureAnalysis::SetString(FA_TAG Tag, PSTR Str)
{
ULONG Size = strlen(Str) + 1;
FA_ENTRY* Entry = Set(Tag, Size);
if (Entry != NULL)
{
memcpy(FA_ENTRY_DATA(PSTR, Entry), Str, Size);
}
return Entry;
}
FA_ENTRY*
DebugFailureAnalysis::SetStrings(FA_TAG Tag, ULONG Count, PSTR* Strs)
{
ULONG i;
ULONG Size = 0;
for (i = 0; i < Count; i++)
{
Size += strlen(Strs[i]) + 1;
}
// Put a double terminator at the very end.
Size++;
FA_ENTRY* Entry = Set(Tag, Size);
if (Entry != NULL)
{
PSTR Data = FA_ENTRY_DATA(PSTR, Entry);
for (i = 0; i < Count; i++)
{
Size = strlen(Strs[i]) + 1;
memcpy(Data, Strs[i], Size);
Data += Size;
}
*Data = 0;
}
return Entry;
}
FA_ENTRY*
DebugFailureAnalysis::SetBuffer(FA_TAG Tag, PVOID Buf, ULONG Size)
{
FA_ENTRY* Entry = Set(Tag, Size);
if (Entry != NULL)
{
memcpy(FA_ENTRY_DATA(PUCHAR, Entry), Buf, Size);
}
return Entry;
}
FA_ENTRY*
DebugFailureAnalysis::Add(FA_TAG Tag, ULONG Size)
{
// Compute full rounded size.
ULONG FullSize = sizeof(FA_ENTRY) + FA_ALIGN(Size);
FA_ENTRY* Entry = AllocateEntry(FullSize);
if (Entry != NULL)
{
Entry->Tag = Tag;
Entry->FullSize = (USHORT)FullSize;
Entry->DataSize = (USHORT)Size;
SCORCH_ENTRY(Entry);
}
return Entry;
}
ULONG
DebugFailureAnalysis::Delete(FA_TAG Tag, FA_TAG TagMask)
{
ULONG Deleted = 0;
FA_ENTRY* Entry = NextEntry(NULL);
while (Entry != NULL)
{
if ((Entry->Tag & TagMask) == Tag)
{
PackData((PUCHAR)Entry, Entry->FullSize);
Deleted++;
// Check and see if we packed away the last entry.
if (!ValidEntry(Entry))
{
break;
}
}
else
{
Entry = NextEntry(Entry);
}
}
return Deleted;
}
void
DebugFailureAnalysis::Empty(void)
{
// Reset used to just the header.
m_DataUsed = 0;
}
FA_ENTRY*
DebugFailureAnalysis::AllocateEntry(ULONG FullSize)
{
// Sizes must fit in USHORTs. This shouldn't be
// a big problem since analyses shouldn't have
// huge data items in them.
if (FullSize > 0xffff)
{
RAISE_ERROR(E_INVALIDARG);
return NULL;
}
if (m_DataUsed + FullSize > m_DataLen)
{
ULONG NewLen = m_DataLen;
do
{
NewLen += FA_GROW_BY;
}
while (m_DataUsed + FullSize > NewLen);
PUCHAR NewData = (PUCHAR)realloc(m_Data, NewLen);
if (NewData == NULL)
{
RAISE_ERROR(E_OUTOFMEMORY);
return NULL;
}
m_Data = NewData;
m_DataLen = NewLen;
}
FA_ENTRY* Entry = (FA_ENTRY*)(m_Data + m_DataUsed);
m_DataUsed += FullSize;
return Entry;
}
void
DebugFailureAnalysis::DbFindBucketInfo(
void
)
{
SolutionDatabaseHandler *Db;
CHAR Solution[SOLUTION_TEXT_SIZE];
CHAR SolOSVer[OS_VER_SIZE];
ULONG RaidBug;
FA_ENTRY* BucketEntry;
FA_ENTRY* GBucketEntry;
FA_ENTRY* DriverNameEntry = NULL;
FA_ENTRY* TimeStampEntry = NULL;
static CHAR SolvedBucket[MAX_PATH] = {0}, SolvedgBucket[MAX_PATH] = {0};
static CHAR SolutionString[MAX_PATH] = {0};
static ULONG SolutionId = 0, SolutionType, SolutionIdgBucket = 0;
if (GetProcessingFlags() & FAILURE_ANALYSIS_NO_DB_LOOKUP)
{
return;
}
if (!(BucketEntry = Get(DEBUG_FLR_BUCKET_ID)))
{
return;
}
if (!strcmp(SolvedBucket, FA_ENTRY_DATA(PCHAR, BucketEntry)))
{
if (SolutionType != CiSolUnsolved)
{
SetString(DEBUG_FLR_INTERNAL_SOLUTION_TEXT, SolutionString);
}
SetUlong(DEBUG_FLR_SOLUTION_ID, SolutionId);
SetUlong(DEBUG_FLR_SOLUTION_TYPE, SolutionType);
// Generic bucket
if (BucketEntry = Get(DEBUG_FLR_DEFAULT_BUCKET_ID))
{
if (!strcmp(SolvedgBucket, FA_ENTRY_DATA(PCHAR, BucketEntry)))
{
SetUlong(DEBUG_FLR_DEFAULT_SOLUTION_ID, SolutionIdgBucket);
}
}
return;
}
// if (!(DriverNameEntry = Get(DEBUG_FLR_IMAGE_NAME)) ||
// !(TimeStampEntry = Get(DEBUG_FLR_IMAGE_TIMESTAMP)))
// {
// return;
// }
HRESULT Hr;
BOOL SolDbInitialized = g_SolDb != NULL;
if (!SolDbInitialized)
{
if (FAILED(Hr = InitializeDatabaseHandlers(g_ExtControl, 4)))
{
// dprintf("Database initialize failed %lx\n", Hr);
return;
}
SolDbInitialized = TRUE;
}
if (g_SolDb->ConnectToDataBase())
{
if (GBucketEntry = Get(DEBUG_FLR_DEFAULT_BUCKET_ID))
{
CopyString(SolvedgBucket, FA_ENTRY_DATA(PCHAR, GBucketEntry), sizeof(SolvedgBucket));
}
//
// List crashes for the same bucket
//
CopyString(SolvedBucket, FA_ENTRY_DATA(PCHAR, BucketEntry), sizeof(SolvedBucket));
if (SUCCEEDED(Hr = g_SolDb->GetSolutionFromDB(FA_ENTRY_DATA(PCHAR, BucketEntry),
SolvedgBucket, NULL, 0,
// FA_ENTRY_DATA(PCHAR, DriverNameEntry),
// (ULONG)(*FA_ENTRY_DATA(PULONG64, TimeStampEntry)),
0, Solution, SOLUTION_TEXT_SIZE,
&SolutionId, &SolutionType,
&SolutionIdgBucket)))
{
if (SolutionId != 0)
{
SetString(DEBUG_FLR_INTERNAL_SOLUTION_TEXT, Solution);
CopyString(SolutionString, Solution, sizeof(SolutionString));
} else
{
SolutionId = -1; // unsolved
SolutionType = 0;
}
if (SolutionIdgBucket == 0)
{
SolutionIdgBucket = -1; // unsolved
}
SetUlong(DEBUG_FLR_SOLUTION_ID, SolutionId);
SetUlong(DEBUG_FLR_SOLUTION_TYPE, SolutionType);
SetUlong(DEBUG_FLR_DEFAULT_SOLUTION_ID, SolutionIdgBucket);
} else
{
// We did not succesfully look up in DB
SolvedgBucket[0] = '\0';
SolvedBucket[0] = '\0';
}
#if 0
if (SolOSVer[0] != '\0')
{
SetString(DEBUG_FLR_FIXED_IN_OSVERSION, SolOSVer);
}
}
if (Db->FindRaidBug(FA_ENTRY_DATA(PCHAR, Entry),
&RaidBug) == S_OK)
{
SetUlong64(DEBUG_FLR_INTERNAL_RAID_BUG, RaidBug);
}
#endif
}
;
if (SolDbInitialized)
{
UnInitializeDatabaseHandlers(FALSE);
}
return;
}
FLR_LOOKUP_TABLE FlrLookupTable[] = {
DEBUG_FLR_RESERVED , "RESERVED"
,DEBUG_FLR_DRIVER_OBJECT , "DRIVER_OBJECT"
,DEBUG_FLR_DEVICE_OBJECT , "DEVICE_OBJECT"
,DEBUG_FLR_INVALID_PFN , "INVALID_PFN"
,DEBUG_FLR_WORKER_ROUTINE , "WORKER_ROUTINE"
,DEBUG_FLR_WORK_ITEM , "WORK_ITEM"
,DEBUG_FLR_INVALID_DPC_FOUND , "INVALID_DPC_FOUND"
,DEBUG_FLR_PROCESS_OBJECT , "PROCESS_OBJECT"
,DEBUG_FLR_FAILED_INSTRUCTION_ADDRESS , "FAILED_INSTRUCTION_ADDRESS"
,DEBUG_FLR_LAST_CONTROL_TRANSFER , "LAST_CONTROL_TRANSFER"
,DEBUG_FLR_ACPI_EXTENSION , "ACPI_EXTENSION"
,DEBUG_FLR_ACPI_OBJECT , "ACPI_OBJECT"
,DEBUG_FLR_PROCESS_NAME , "PROCESS_NAME"
,DEBUG_FLR_READ_ADDRESS , "READ_ADDRESS"
,DEBUG_FLR_WRITE_ADDRESS , "WRITE_ADDRESS"
,DEBUG_FLR_CRITICAL_SECTION , "CRITICAL_SECTION"
,DEBUG_FLR_BAD_HANDLE , "BAD_HANDLE"
,DEBUG_FLR_INVALID_HEAP_ADDRESS , "INVALID_HEAP_ADDRESS"
,DEBUG_FLR_IRP_ADDRESS , "IRP_ADDRESS"
,DEBUG_FLR_IRP_MAJOR_FN , "IRP_MAJOR_FN"
,DEBUG_FLR_IRP_MINOR_FN , "IRP_MINOR_FN"
,DEBUG_FLR_IRP_CANCEL_ROUTINE , "IRP_CANCEL_ROUTINE"
,DEBUG_FLR_IOSB_ADDRESS , "IOSB_ADDRESS"
,DEBUG_FLR_INVALID_USEREVENT , "INVALID_USEREVENT"
,DEBUG_FLR_PREVIOUS_MODE , "PREVIOUS_MODE"
,DEBUG_FLR_CURRENT_IRQL , "CURRENT_IRQL"
,DEBUG_FLR_PREVIOUS_IRQL , "PREVIOUS_IRQL"
,DEBUG_FLR_REQUESTED_IRQL , "REQUESTED_IRQL"
,DEBUG_FLR_ASSERT_DATA , "ASSERT_DATA"
,DEBUG_FLR_ASSERT_FILE , "ASSERT_FILE_LOCATION"
,DEBUG_FLR_EXCEPTION_PARAMETER1 , "EXCEPTION_PARAMETER1"
,DEBUG_FLR_EXCEPTION_PARAMETER2 , "EXCEPTION_PARAMETER2"
,DEBUG_FLR_EXCEPTION_PARAMETER3 , "EXCEPTION_PARAMETER3"
,DEBUG_FLR_EXCEPTION_PARAMETER4 , "EXCEPTION_PARAMETER4"
,DEBUG_FLR_EXCEPTION_RECORD , "EXCEPTION_RECORD"
,DEBUG_FLR_POOL_ADDRESS , "POOL_ADDRESS"
,DEBUG_FLR_CORRUPTING_POOL_ADDRESS , "CORRUPTING_POOL_ADDRESS"
,DEBUG_FLR_CORRUPTING_POOL_TAG , "CORRUPTING_POOL_TAG"
,DEBUG_FLR_FREED_POOL_TAG , "FREED_POOL_TAG"
,DEBUG_FLR_SPECIAL_POOL_CORRUPTION_TYPE , "SPECIAL_POOL_CORRUPTION_TYPE"
,DEBUG_FLR_FILE_ID , "FILE_ID"
,DEBUG_FLR_FILE_LINE , "FILE_LINE"
,DEBUG_FLR_BUGCHECK_STR , "BUGCHECK_STR"
,DEBUG_FLR_BUGCHECK_SPECIFIER , "BUGCHECK_SPECIFIER"
,DEBUG_FLR_DRIVER_VERIFIER_IO_VIOLATION_TYPE, "DRIVER_VERIFIER_IO_VIOLATION_TYPE"
,DEBUG_FLR_EXCEPTION_CODE , "EXCEPTION_CODE"
,DEBUG_FLR_STATUS_CODE , "STATUS_CODE"
,DEBUG_FLR_IOCONTROL_CODE , "IOCONTROL_CODE"
,DEBUG_FLR_MM_INTERNAL_CODE , "MM_INTERNAL_CODE"
,DEBUG_FLR_DRVPOWERSTATE_SUBCODE , "DRVPOWERSTATE_SUBCODE"
,DEBUG_FLR_CORRUPT_MODULE_LIST , "CORRUPT_MODULE_LIST"
,DEBUG_FLR_BAD_STACK , "BAD_STACK"
,DEBUG_FLR_ZEROED_STACK , "ZEROED_STACK"
,DEBUG_FLR_WRONG_SYMBOLS , "WRONG_SYMBOLS"
,DEBUG_FLR_FOLLOWUP_DRIVER_ONLY , "FOLLOWUP_DRIVER_ONLY"
,DEBUG_FLR_CPU_OVERCLOCKED , "CPU_OVERCLOCKED"
,DEBUG_FLR_MANUAL_BREAKIN , "MANUAL_BREAKIN"
,DEBUG_FLR_POSSIBLE_INVALID_CONTROL_TRANSFER, "POSSIBLE_INVALID_CONTROL_TRANSFER"
,DEBUG_FLR_POISONED_TB , "POISONED_TB"
,DEBUG_FLR_UNKNOWN_MODULE , "UNKNOWN_MODULE"
,DEBUG_FLR_ANALYZAABLE_POOL_CORRUPTION , "ANALYZAABLE_POOL_CORRUPTION"
,DEBUG_FLR_SINGLE_BIT_ERROR , "SINGLE_BIT_ERROR"
,DEBUG_FLR_TWO_BIT_ERROR , "TWO_BIT_ERROR"
,DEBUG_FLR_INVALID_KERNEL_CONTEXT , "INVALID_KERNEL_CONTEXT"
,DEBUG_FLR_DISK_HARDWARE_ERROR , "DISK_HARDWARE_ERROR"
,DEBUG_FLR_POOL_CORRUPTOR , "POOL_CORRUPTOR"
,DEBUG_FLR_MEMORY_CORRUPTOR , "MEMORY_CORRUPTOR"
,DEBUG_FLR_UNALIGNED_STACK_POINTER , "UNALIGNED_STACK_POINTER"
,DEBUG_FLR_OLD_OS_VERSION , "OLD_OS_VERSION"
,DEBUG_FLR_BUGCHECKING_DRIVER , "BUGCHECKING_DRIVER"
,DEBUG_FLR_BUCKET_ID , "BUCKET_ID"
,DEBUG_FLR_IMAGE_NAME , "IMAGE_NAME"
,DEBUG_FLR_SYMBOL_NAME , "SYMBOL_NAME"
,DEBUG_FLR_FOLLOWUP_NAME , "FOLLOWUP_NAME"
,DEBUG_FLR_STACK_COMMAND , "STACK_COMMAND"
,DEBUG_FLR_STACK_TEXT , "STACK_TEXT"
,DEBUG_FLR_INTERNAL_SOLUTION_TEXT , "INTERNAL_SOLUTION_TEXT"
,DEBUG_FLR_MODULE_NAME , "MODULE_NAME"
,DEBUG_FLR_INTERNAL_RAID_BUG , "INTERNAL_RAID_BUG"
,DEBUG_FLR_FIXED_IN_OSVERSION , "FIXED_IN_OSVERSION"
,DEBUG_FLR_DEFAULT_BUCKET_ID , "DEFAULT_BUCKET_ID"
,DEBUG_FLR_FAULTING_IP , "FAULTING_IP"
,DEBUG_FLR_FAULTING_MODULE , "FAULTING_MODULE"
,DEBUG_FLR_IMAGE_TIMESTAMP , "DEBUG_FLR_IMAGE_TIMESTAMP"
,DEBUG_FLR_FOLLOWUP_IP , "FOLLOWUP_IP"
,DEBUG_FLR_FAULTING_THREAD , "FAULTING_THREAD"
,DEBUG_FLR_CONTEXT , "CONTEXT"
,DEBUG_FLR_TRAP_FRAME , "TRAP_FRAME"
,DEBUG_FLR_TSS , "TSS"
,DEBUG_FLR_SHOW_ERRORLOG , "ERROR_LOG"
,DEBUG_FLR_MASK_ALL , "MASK_ALL"
// Zero entry Must be last;
,DEBUG_FLR_INVALID , "INVALID"
};
void
DebugFailureAnalysis::OutputEntryParam(DEBUG_FLR_PARAM_TYPE Type)
{
FA_ENTRY *Entry = Get(Type);
if (Entry)
{
OutputEntry(Entry);
}
}
void
DebugFailureAnalysis::OutputEntry(FA_ENTRY* Entry)
{
CHAR Buffer[MAX_PATH];
CHAR Module[MAX_PATH];
ULONG64 Base;
ULONG64 Address;
ULONG OutCtl;
ULONG i = 0;
OutCtl = DEBUG_OUTCTL_AMBIENT;
switch(Entry->Tag)
{
// These are just tags - don't print out
case DEBUG_FLR_CORRUPT_MODULE_LIST:
case DEBUG_FLR_BAD_STACK:
case DEBUG_FLR_ZEROED_STACK:
case DEBUG_FLR_WRONG_SYMBOLS:
case DEBUG_FLR_FOLLOWUP_DRIVER_ONLY:
case DEBUG_FLR_UNKNOWN_MODULE:
case DEBUG_FLR_ANALYZAABLE_POOL_CORRUPTION:
case DEBUG_FLR_INVALID_KERNEL_CONTEXT:
case DEBUG_FLR_SOLUTION_TYPE:
case DEBUG_FLR_MANUAL_BREAKIN:
// soluion ids from DB
case DEBUG_FLR_SOLUTION_ID:
case DEBUG_FLR_DEFAULT_SOLUTION_ID:
// Field folded into others
case DEBUG_FLR_BUGCHECK_SPECIFIER:
return;
// Marged with other output
return;
}
//
// Find the entry in the description table
//
while(FlrLookupTable[i].Data &&
Entry->Tag != FlrLookupTable[i].Data)
{
i++;
}
dprintf("\n%s: ", FlrLookupTable[i].String);
switch(Entry->Tag)
{
// Notification to user
case DEBUG_FLR_DISK_HARDWARE_ERROR:
// FlrLookupTable value has already been printed
dprintf("There was error with disk hardware\n");
break;
// Strings:
case DEBUG_FLR_ASSERT_DATA:
case DEBUG_FLR_ASSERT_FILE:
case DEBUG_FLR_BUCKET_ID:
case DEBUG_FLR_DEFAULT_BUCKET_ID:
case DEBUG_FLR_STACK_TEXT:
case DEBUG_FLR_STACK_COMMAND:
case DEBUG_FLR_INTERNAL_SOLUTION_TEXT:
case DEBUG_FLR_FIXED_IN_OSVERSION:
case DEBUG_FLR_BUGCHECK_STR:
case DEBUG_FLR_IMAGE_NAME:
case DEBUG_FLR_MODULE_NAME:
case DEBUG_FLR_PROCESS_NAME:
case DEBUG_FLR_FOLLOWUP_NAME:
case DEBUG_FLR_POOL_CORRUPTOR:
case DEBUG_FLR_MEMORY_CORRUPTOR:
case DEBUG_FLR_BUGCHECKING_DRIVER:
case DEBUG_FLR_SYMBOL_NAME:
case DEBUG_FLR_CORRUPTING_POOL_TAG:
case DEBUG_FLR_FREED_POOL_TAG:
dprintf(" %s\n", FA_ENTRY_DATA(PCHAR, Entry));
break;
// DWORDs:
case DEBUG_FLR_PREVIOUS_IRQL:
case DEBUG_FLR_CURRENT_IRQL:
case DEBUG_FLR_MM_INTERNAL_CODE:
case DEBUG_FLR_SPECIAL_POOL_CORRUPTION_TYPE:
case DEBUG_FLR_PREVIOUS_MODE:
case DEBUG_FLR_IMAGE_TIMESTAMP:
case DEBUG_FLR_SINGLE_BIT_ERROR:
case DEBUG_FLR_TWO_BIT_ERROR:
dprintf(" %lx\n", *FA_ENTRY_DATA(PULONG64, Entry));
break;
// DWORDs:
case DEBUG_FLR_INTERNAL_RAID_BUG:
case DEBUG_FLR_OLD_OS_VERSION:
dprintf(" %d\n", *FA_ENTRY_DATA(PULONG64, Entry));
break;
// Pointers
case DEBUG_FLR_PROCESS_OBJECT:
case DEBUG_FLR_DEVICE_OBJECT:
case DEBUG_FLR_DRIVER_OBJECT:
case DEBUG_FLR_ACPI_OBJECT:
case DEBUG_FLR_IRP_ADDRESS:
case DEBUG_FLR_EXCEPTION_PARAMETER1:
case DEBUG_FLR_EXCEPTION_PARAMETER2:
case DEBUG_FLR_FAULTING_THREAD:
case DEBUG_FLR_WORK_ITEM:
dprintf(" %p\n", *FA_ENTRY_DATA(PULONG64, Entry));
break;
// Pointers to code
case DEBUG_FLR_WORKER_ROUTINE:
case DEBUG_FLR_IRP_CANCEL_ROUTINE:
case DEBUG_FLR_FAILED_INSTRUCTION_ADDRESS:
case DEBUG_FLR_FAULTING_IP:
case DEBUG_FLR_FOLLOWUP_IP:
case DEBUG_FLR_FAULTING_MODULE:
FaGetSymbol(*FA_ENTRY_DATA(PULONG64, Entry), Buffer, &Address, sizeof(Buffer));
dprintf("\n%s+%I64lx\n", Buffer, Address);
g_ExtControl->OutputDisassemblyLines(OutCtl, 0, 1,
*FA_ENTRY_DATA(PULONG64, Entry),
0, NULL, NULL, NULL, NULL);
break;
// Address description
case DEBUG_FLR_READ_ADDRESS:
case DEBUG_FLR_WRITE_ADDRESS:
case DEBUG_FLR_POOL_ADDRESS:
case DEBUG_FLR_CORRUPTING_POOL_ADDRESS:
{
PCSTR Desc = DescribeAddress(*FA_ENTRY_DATA(PULONG64, Entry));
if (!Desc)
{
Desc = "";
}
dprintf(" %p %s\n", *FA_ENTRY_DATA(PULONG64, Entry), Desc);
break;
}
case DEBUG_FLR_EXCEPTION_CODE:
case DEBUG_FLR_STATUS_CODE:
{
DEBUG_DECODE_ERROR Err;
Err.Code = (ULONG) *FA_ENTRY_DATA(PULONG, Entry);
Err.TreatAsStatus = (Entry->Tag == DEBUG_FLR_STATUS_CODE);
// dprintf(" %lx", *FA_ENTRY_DATA(PULONG, Entry));
DecodeErrorForMessage( &Err );
if (!Err.TreatAsStatus)
{
dprintf("(%s) %#x (%u) - %s\n",
Err.Source, Err.Code, Err.Code, Err.Message);
}
else
{
dprintf("(%s) %#x - %s\n",
Err.Source, Err.Code, Err.Message);
}
break;
}
case DEBUG_FLR_CPU_OVERCLOCKED:
dprintf(" *** Machine was determined to be overclocked !\n");
break;
case DEBUG_FLR_ACPI_EXTENSION:
dprintf(" %p -- (!acpikd.acpiext %p)\n", *FA_ENTRY_DATA(PULONG64, Entry),
*FA_ENTRY_DATA(PULONG64, Entry));
sprintf(Buffer, "!acpikd.acpiext %I64lx", *FA_ENTRY_DATA(PULONG64, Entry));
g_ExtControl->Execute(OutCtl, Buffer, DEBUG_EXECUTE_DEFAULT);
break;
case DEBUG_FLR_TRAP_FRAME:
dprintf(" %p -- (.trap %I64lx)\n", *FA_ENTRY_DATA(PULONG64, Entry),
*FA_ENTRY_DATA(PULONG64, Entry));
sprintf(Buffer, ".trap %I64lx", *FA_ENTRY_DATA(PULONG64, Entry));
g_ExtControl->Execute(OutCtl, Buffer, DEBUG_EXECUTE_DEFAULT);
g_ExtControl->Execute(OutCtl, ".trap", DEBUG_EXECUTE_DEFAULT);
break;
case DEBUG_FLR_CONTEXT:
dprintf(" %p -- (.cxr %I64lx)\n", *FA_ENTRY_DATA(PULONG64, Entry),
*FA_ENTRY_DATA(PULONG64, Entry));
sprintf(Buffer, ".cxr %I64lx", *FA_ENTRY_DATA(PULONG64, Entry));
g_ExtControl->Execute(OutCtl, Buffer, DEBUG_EXECUTE_DEFAULT);
g_ExtControl->Execute(OutCtl, ".cxr", DEBUG_EXECUTE_DEFAULT);
break;
case DEBUG_FLR_EXCEPTION_RECORD:
dprintf(" %p -- (.exr %I64lx)\n", *FA_ENTRY_DATA(PULONG64, Entry),
*FA_ENTRY_DATA(PULONG64, Entry));
sprintf(Buffer, ".exr %I64lx", *FA_ENTRY_DATA(PULONG64, Entry));
g_ExtControl->Execute(OutCtl, Buffer, DEBUG_EXECUTE_DEFAULT);
break;
case DEBUG_FLR_TSS:
dprintf(" %p -- (.tss %I64lx)\n", *FA_ENTRY_DATA(PULONG64, Entry),
*FA_ENTRY_DATA(PULONG64, Entry));
sprintf(Buffer, ".tss %I64lx", *FA_ENTRY_DATA(PULONG64, Entry));
g_ExtControl->Execute(OutCtl, Buffer, DEBUG_EXECUTE_DEFAULT);
g_ExtControl->Execute(OutCtl, ".trap", DEBUG_EXECUTE_DEFAULT);
break;
case DEBUG_FLR_LAST_CONTROL_TRANSFER:
case DEBUG_FLR_POSSIBLE_INVALID_CONTROL_TRANSFER:
dprintf(" from %p to %p\n",
FA_ENTRY_DATA(PULONG64, Entry)[0],
FA_ENTRY_DATA(PULONG64, Entry)[1]);
break;
case DEBUG_FLR_CRITICAL_SECTION:
dprintf("%p (!cs -s %p)\n",
*FA_ENTRY_DATA(PULONG64, Entry),
*FA_ENTRY_DATA(PULONG64, Entry));
break;
case DEBUG_FLR_BAD_HANDLE:
dprintf("%p (!htrace %p)\n",
*FA_ENTRY_DATA(PULONG64, Entry),
*FA_ENTRY_DATA(PULONG64, Entry));
break;
case DEBUG_FLR_INVALID_HEAP_ADDRESS:
dprintf("%p (!heap -p -a %p)\n",
*FA_ENTRY_DATA(PULONG64, Entry),
*FA_ENTRY_DATA(PULONG64, Entry));
break;
case DEBUG_FLR_SHOW_ERRORLOG:
g_ExtControl->Execute(OutCtl, "!errlog", DEBUG_EXECUTE_DEFAULT);
break;
default:
dprintf(" *** Unknown TAG in analysis list %lx\n\n",
Entry->Tag);
return;
}
return;
}
void
DebugFailureAnalysis::Output()
{
ULONG RetVal;
FA_ENTRY* Entry;
BOOL Verbose = (GetProcessingFlags() & FAILURE_ANALYSIS_VERBOSE);
//
// In verbose mode, show everything that we figured out during analysis
//
if (Verbose)
{
Entry = NULL;
while (Entry = NextEntry(Entry))
{
OutputEntry(Entry);
}
}
if (Get(DEBUG_FLR_POISONED_TB))
{
dprintf("*** WARNING: nt!MmPoisonedTb is non-zero:\n"
"*** The machine has been manipulated using the kernel debugger.\n"
"*** MachineOwner should be contacted first\n\n\n");
}
PCHAR SolInOS = NULL;
if (Entry = Get(DEBUG_FLR_FIXED_IN_OSVERSION))
{
SolInOS = FA_ENTRY_DATA(PCHAR, Entry);
}
PCHAR Solution = NULL;
if (Entry = Get(DEBUG_FLR_INTERNAL_SOLUTION_TEXT))
{
Solution = FA_ENTRY_DATA(PCHAR, Entry);
}
//
// Print the bad driver if we are not in verbose mode - otherwise
// is is printed out using the params
//
if (!Verbose && !Solution)
{
if (Entry = Get(DEBUG_FLR_CORRUPTING_POOL_TAG))
{
dprintf("Probably pool corruption caused by Tag: %s\n",
FA_ENTRY_DATA(PCHAR, Entry));
}
else
{
PCHAR DriverName = NULL;
PCHAR SymName = NULL;
if (Entry = Get(DEBUG_FLR_IMAGE_NAME))
{
DriverName = FA_ENTRY_DATA(PCHAR, Entry);
}
if (Entry = Get(DEBUG_FLR_SYMBOL_NAME))
{
SymName = FA_ENTRY_DATA(PCHAR, Entry);
}
if (DriverName || SymName)
{
dprintf("Probably caused by : ");
if (SymName && DriverName)
{
dprintf("%s ( %s )\n", DriverName, SymName);
}
else if (SymName)
{
dprintf("%s\n", SymName);
}
else
{
dprintf("%s\n", DriverName);
}
}
}
}
if (Verbose || !Solution)
{
PCHAR FollowupAlias = NULL;
//
// Print what the user should do:
// - Followup person
// - Solution text if there is one.
//
if (Entry = Get(DEBUG_FLR_FOLLOWUP_NAME))
{
dprintf("\nFollowup: %s\n", FA_ENTRY_DATA(PCHAR, Entry));
}
else
{
dprintf(" *** Followup info cannot be found !!! Please contact \"Debugger Team\"\n");
}
dprintf("---------\n");
if (Entry = Get(DEBUG_FLR_POSSIBLE_INVALID_CONTROL_TRANSFER))
{
CHAR Buffer[MAX_PATH];
ULONG64 Address;
FaGetSymbol(FA_ENTRY_DATA(PULONG64, Entry)[0], Buffer, &Address, sizeof(Buffer));
dprintf(" *** Possible invalid call from %p ( %s+0x%1p )\n",
FA_ENTRY_DATA(PULONG64, Entry)[0],
Buffer,
Address);
FaGetSymbol(FA_ENTRY_DATA(PULONG64, Entry)[1], Buffer, &Address, sizeof(Buffer));
dprintf(" *** Expected target %p ( %s+0x%1p )\n",
FA_ENTRY_DATA(PULONG64, Entry)[1],
Buffer,
Address);
}
dprintf("\n");
}
if (Entry = Get(DEBUG_FLR_INTERNAL_RAID_BUG))
{
dprintf("Raid bug for this failure: %d\n\n",
*FA_ENTRY_DATA(PULONG64, Entry));
}
if (Solution)
{
dprintf(" This problem has a known fix.\n"
" Please connect to the following URL for details:\n"
" ------------------------------------------------\n"
" %s\n\n",
Solution);
}
if (SolInOS)
{
dprintf(" This has been fixed in : %s\n", SolInOS);
}
}
LPSTR
TimeToStr(
ULONG TimeDateStamp,
BOOL DateOnly
)
{
LPSTR TimeDateStr; // pointer to static cruntime buffer.
static char datebuffer[100];
tm * pTime;
time_t TDStamp = (time_t) (LONG) TimeDateStamp;
// Handle invalid \ page out timestamps, since ctime blows up on
// this number
if ((TimeDateStamp == 0) || (TimeDateStamp == -1))
{
return "unknown_date";
}
else if (DateOnly)
{
pTime = localtime(&TDStamp);
sprintf(datebuffer, "%d_%d_%d",
pTime->tm_mon + 1, pTime->tm_mday, pTime->tm_year + 1900);
return datebuffer;
}
else
{
// TimeDateStamp is always a 32 bit quantity on the target,
// and we need to sign extend for 64 bit host since time_t
// has been extended to 64 bits.
TDStamp = (time_t) (LONG) TimeDateStamp;
TimeDateStr = ctime((time_t *)&TDStamp);
if (TimeDateStr)
{
TimeDateStr[strlen(TimeDateStr) - 1] = 0;
}
else
{
TimeDateStr = "***** Invalid";
}
return TimeDateStr;
}
}
void
DebugFailureAnalysis::GenerateBucketId(void)
{
ULONG LengthUsed = 0;
CHAR BucketId[MAX_PATH] = {0};
PSTR BucketPtr = BucketId;
PSTR Str;
FA_ENTRY* Entry;
FA_ENTRY* NameEntry;
FA_ENTRY* ModuleEntry;
ULONG ModuleTimestamp = 0;
CHAR Command[MAX_PATH] = {0};
CHAR followup[MAX_PATH];
//
// Set the final command string
//
if (Entry = Get(DEBUG_FLR_STACK_COMMAND))
{
CopyString(Command, FA_ENTRY_DATA(PSTR, Entry), sizeof(Command) - 5);
strcat(Command, " ; ");
}
strcat(Command, "kb");
SetString(DEBUG_FLR_STACK_COMMAND, Command);
if (Get(DEBUG_FLR_OLD_OS_VERSION))
{
SetString(DEBUG_FLR_DEFAULT_BUCKET_ID, "OLD_OS");
}
//
// Don't change the bucket ID for these two things as the debugger code
// to detect them is not 100% reliable.
//
//if (Get(DEBUG_FLR_CPU_OVERCLOCKED))
//{
// SetString(DEBUG_FLR_BUCKET_ID, "CPU_OVERCLOCKED");
// return;
//}
//
//
// If the faulting module exists:
// Get the module timestamp of the faulting module.
// Check if it is an old driver.
//
ModuleEntry = Get(DEBUG_FLR_MODULE_NAME);
if (ModuleEntry)
{
ULONG Index;
ULONG64 Base;
DEBUG_MODULE_PARAMETERS Params;
g_ExtSymbols->GetModuleByModuleName(FA_ENTRY_DATA(PCHAR, ModuleEntry),
0, &Index, &Base);
if (Base &&
g_ExtSymbols->GetModuleParameters(1, &Base, Index, &Params) == S_OK)
{
ModuleTimestamp = Params.TimeDateStamp;
}
}
NameEntry = Get(DEBUG_FLR_IMAGE_NAME);
if (NameEntry)
{
if (!strcmp(FA_ENTRY_DATA(PCHAR, NameEntry), "Unknown_Image"))
{
NameEntry = NULL;
}
}
if (ModuleTimestamp && NameEntry)
{
PCHAR String;
ULONG LookupTimestamp;
String = g_pTriager->GetFollowupStr("OldImages",
FA_ENTRY_DATA(PCHAR, NameEntry));
if (String)
{
LookupTimestamp = strtol(String, NULL, 16);
//
// If the driver is known to be bad, just use driver name
//
if (LookupTimestamp > ModuleTimestamp)
{
if (FaGetFollowupInfo(NULL,
FA_ENTRY_DATA(PCHAR, ModuleEntry),
followup,
sizeof(followup)))
{
SetString(DEBUG_FLR_FOLLOWUP_NAME, followup);
}
//sprintf(BucketPtr, "OLD_IMAGE_%s_TS_%lX",
// FA_ENTRY_DATA(PCHAR, NameEntry),
// ModuleTimestamp);
PrintString(BucketPtr, sizeof(BucketId) - LengthUsed, "OLD_IMAGE_%s",
FA_ENTRY_DATA(PCHAR, NameEntry));
SetString(DEBUG_FLR_BUCKET_ID, BucketId);
return;
}
}
}
if (Entry = Get(DEBUG_FLR_POSSIBLE_INVALID_CONTROL_TRANSFER))
{
if (Get(DEBUG_FLR_SINGLE_BIT_ERROR))
{
SetString(DEBUG_FLR_BUCKET_ID, "SINGLE_BIT_CPU_CALL_ERROR");
}
else if (Get(DEBUG_FLR_TWO_BIT_ERROR))
{
SetString(DEBUG_FLR_BUCKET_ID, "TWO_BIT_CPU_CALL_ERROR");
}
else
{
SetString(DEBUG_FLR_BUCKET_ID, "CPU_CALL_ERROR");
}
return;
}
if (Entry = Get(DEBUG_FLR_MANUAL_BREAKIN))
{
SetString(DEBUG_FLR_BUCKET_ID, "MANUAL_BREAKIN");
SetString(DEBUG_FLR_FOLLOWUP_NAME, "MachineOwner");
return;
}
if (!PossibleFollowups[FlpSpecific].Owner[0])
{
BOOL bPoolTag = FALSE;
if (Entry = Get(DEBUG_FLR_BUGCHECKING_DRIVER))
{
PrintString(BucketPtr, sizeof(BucketId) - LengthUsed,
"%s_BUGCHECKING_DRIVER_%s",
FA_ENTRY_DATA(PCHAR, Get(DEBUG_FLR_BUGCHECK_STR)),
FA_ENTRY_DATA(PCHAR, Entry));
}
else if (Entry = Get(DEBUG_FLR_MEMORY_CORRUPTOR))
{
PrintString(BucketPtr, sizeof(BucketId) - LengthUsed,
"MEMORY_CORRUPTION_%s",
FA_ENTRY_DATA(PCHAR, Entry));
}
else if (Entry = Get(DEBUG_FLR_POOL_CORRUPTOR))
{
PrintString(BucketPtr, sizeof(BucketId) - LengthUsed,
"POOL_CORRUPTION_%s",
FA_ENTRY_DATA(PCHAR, Entry));
}
else if (Entry = Get(DEBUG_FLR_CORRUPTING_POOL_TAG))
{
PrintString(BucketPtr, sizeof(BucketId) - LengthUsed,
"CORRUPTING_POOLTAG_%s",
FA_ENTRY_DATA(PCHAR, Entry));
bPoolTag = TRUE;
}
if (Entry)
{
if (bPoolTag &&
(FaGetPoolTagFollowup(FA_ENTRY_DATA(PCHAR, Entry),
followup,
sizeof(followup)) == S_OK))
{
SetString(DEBUG_FLR_FOLLOWUP_NAME, followup);
} else if (FaGetFollowupInfo(NULL,
FA_ENTRY_DATA(PCHAR, Entry),
followup,
sizeof(followup)))
{
SetString(DEBUG_FLR_FOLLOWUP_NAME, followup);
}
SetString(DEBUG_FLR_BUCKET_ID, BucketId);
return;
}
}
//
// Only check this after as we could still have found a bad driver
// with a bad stack (like drivers that cause stack corruption ...)
//
Str = NULL;
Entry = NULL;
while (Entry = NextEntry(Entry))
{
switch(Entry->Tag)
{
case DEBUG_FLR_WRONG_SYMBOLS:
Str = "WRONG_SYMBOLS";
break;
case DEBUG_FLR_BAD_STACK:
Str = "BAD_STACK";
break;
case DEBUG_FLR_ZEROED_STACK:
Str = "ZEROED_STACK";
break;
case DEBUG_FLR_INVALID_KERNEL_CONTEXT:
Str = "INVALID_KERNEL_CONTEXT";
break;
case DEBUG_FLR_CORRUPT_MODULE_LIST:
Str = "CORRUPT_MODULELIST";
break;
break;
}
if (Str)
{
if (FaGetFollowupInfo(NULL,
"ProcessingError",
followup,
sizeof(followup)))
{
SetString(DEBUG_FLR_FOLLOWUP_NAME, followup);
}
SetString(DEBUG_FLR_BUCKET_ID, Str);
return;
}
}
//
// Add failure code.
//
if (Entry = Get(DEBUG_FLR_BUGCHECK_STR))
{
PrintString(BucketPtr, sizeof(BucketId) - LengthUsed, "%s", FA_ENTRY_DATA(PCHAR, Entry));
LengthUsed += strlen(BucketPtr);
BucketPtr = BucketId + LengthUsed;
}
if (Entry = Get(DEBUG_FLR_BUGCHECK_SPECIFIER))
{
PrintString(BucketPtr, sizeof(BucketId) - LengthUsed, "%s", FA_ENTRY_DATA(PCHAR, Entry));
LengthUsed += strlen(BucketPtr);
BucketPtr = BucketId + LengthUsed;
}
//
// If it's driver only, but the failure is not in a driver, then show the
// full name of the failure. If we could not get the name, or we really
// have a driver only, show the name of the image.
//
if ( (Entry = Get(DEBUG_FLR_SYMBOL_NAME)) &&
( !Get(DEBUG_FLR_FOLLOWUP_DRIVER_ONLY) ||
(BestClassFollowUp < FlpUnknownDrv)))
{
//
// If the faulting IP and the read address are the same, this is
// an interesting scenario we want to catch.
//
if (Get(DEBUG_FLR_FAILED_INSTRUCTION_ADDRESS))
{
PrintString(BucketPtr,
sizeof(BucketId) - LengthUsed,
"_BAD_IP");
LengthUsed += strlen(BucketPtr);
BucketPtr = BucketId + LengthUsed;
}
PrintString(BucketPtr,
sizeof(BucketId) - LengthUsed,
"_%s",
FA_ENTRY_DATA(PCHAR, Entry));
LengthUsed += strlen(BucketPtr);
BucketPtr = BucketId + LengthUsed;
}
else if (NameEntry)
{
PrintString(BucketPtr,
sizeof(BucketId) - LengthUsed,
"_IMAGE_%s",
FA_ENTRY_DATA(PCHAR, NameEntry));
LengthUsed += strlen(BucketPtr);
BucketPtr = BucketId + LengthUsed;
// Also add timestamp in this case.
if (ModuleTimestamp)
{
PrintString(BucketPtr,
sizeof(BucketId) - LengthUsed,
"_DATE_%s",
TimeToStr(ModuleTimestamp, TRUE));
LengthUsed += strlen(BucketPtr);
BucketPtr = BucketId + LengthUsed;
}
}
//
// Store the bucket ID in the analysis structure
//
//BucketDone:
for (PCHAR Scan = &BucketId[0]; *Scan; ++Scan)
{
// remove special chars that cause problems for IIS or SQL
if (*Scan == '<' || *Scan == '>' || *Scan == '|' ||
*Scan == '`' || *Scan == '\''|| (!isprint(*Scan)) )
{
*Scan = '_';
}
}
SetString(DEBUG_FLR_BUCKET_ID, BucketId);
}
void
DebugFailureAnalysis::AnalyzeStack(void)
{
PDEBUG_OUTPUT_CALLBACKS PrevCB;
ULONG i;
BOOL BoostToSpecific = FALSE;
ULONG64 TrapFrame = 0;
ULONG64 Thread = 0;
ULONG64 ImageNameAddr = 0;
DEBUG_STACK_FRAME Stk[MAX_STACK_FRAMES];
ULONG Frames = 0;
ULONG Trap0EFrameLimit = 2;
ULONG64 OriginalFaultingAddress = 0;
CHAR Command[50] = {0};
FA_ENTRY* Entry;
BOOL BadContext = FALSE;
ULONG PtrSize = IsPtr64() ? 8 : 4;
BOOL IsVrfBugcheck = FALSE;
//
// If someone provided a best followup already, just return
//
if (PossibleFollowups[MaxFlpClass-1].Owner[0])
{
return;
}
if (g_TargetClass == DEBUG_CLASS_KERNEL)
{
// Check if CPU is overclocked
//if (BcIsCpuOverClocked())
//{
// SetUlong64(DEBUG_FLR_CPU_OVERCLOCKED, -1);
//
// BestClassFollowUp = FlpOSInternalRoutine;
// strcpy(PossibleFollowups[FlpOSInternalRoutine].Owner, "MachineOwner");
// return;
//}
//
// Check if this bugcheck has any specific followup that independant
// of the failure stack
//
if (Entry = Get(DEBUG_FLR_BUGCHECK_STR))
{
PCHAR String;
String = g_pTriager->GetFollowupStr("bugcheck",
FA_ENTRY_DATA(PCHAR, Entry));
if (String)
{
if (!strncmp(String, "maybe_", 6))
{
BestClassFollowUp = FlpOSRoutine;
CopyString(PossibleFollowups[FlpOSRoutine].Owner,
String + 6,
sizeof(PossibleFollowups[FlpOSRoutine].Owner));
}
else if (!strncmp(String, "specific_", 9))
{
BoostToSpecific = TRUE;
}
else
{
BestClassFollowUp = FlpSpecific;
CopyString(PossibleFollowups[FlpSpecific].Owner,
String,
sizeof(PossibleFollowups[FlpSpecific].Owner));
return;
}
}
}
}
//
// Add trap frame, context info from the current stack
//
// Note(kksharma):We only need one of these to get to
// faulting stack (and only one of them should
// be available otherwise somethings wrong)
//
Entry = NULL;
while (Entry = NextEntry(Entry))
{
switch(Entry->Tag)
{
case DEBUG_FLR_CONTEXT:
sprintf(Command, ".cxr %I64lx",
*FA_ENTRY_DATA(PULONG64, Entry));
break;
case DEBUG_FLR_TRAP_FRAME:
sprintf(Command, ".trap %I64lx",
*FA_ENTRY_DATA(PULONG64, Entry));
break;
case DEBUG_FLR_TSS:
sprintf(Command, ".tss %I64lx",
*FA_ENTRY_DATA(PULONG64, Entry));
break;
case DEBUG_FLR_FAULTING_THREAD:
sprintf(Command, ".thread %I64lx",
*FA_ENTRY_DATA(PULONG64, Entry));
break;
case DEBUG_FLR_EXCEPTION_RECORD:
if (*FA_ENTRY_DATA(PULONG64, Entry) == -1)
{
sprintf(Command, ".ecxr");
}
break;
case DEBUG_FLR_FAULTING_IP:
case DEBUG_FLR_FAULTING_MODULE:
//
// We already have some info from the bugcheck
// Use that address to start off with.
// But if we could not use it to set any followup, then continue
// lookinh for the others.
//
if (OriginalFaultingAddress = *FA_ENTRY_DATA(PULONG64, Entry))
{
if (!GetTriageInfoFromStack(0, 1, OriginalFaultingAddress,
PossibleFollowups,
&BestClassFollowUp))
{
OriginalFaultingAddress = 0;
}
}
break;
default:
break;
}
if (Command[0] && OriginalFaultingAddress)
{
break;
}
}
RepeatGetCommand:
if (!Command[0])
{
//
// Get the current stack.
//
if (S_OK != g_ExtControl->GetStackTrace(0, 0, 0, Stk, MAX_STACK_FRAMES,
&Frames))
{
Frames = 0;
}
//
// Make sure this is a valid stack to analyze. Such as for kernel mode
// try to recognize stack after user breakin and send to machineowner
//
if (m_FailureType == DEBUG_FLR_KERNEL &&
m_FailureCode == 0 && Frames >= 3)
{
if (IsManualBreakin(Stk, Frames))
{
// set machine owner as followup
SetUlong(DEBUG_FLR_MANUAL_BREAKIN, TRUE);
strcpy(PossibleFollowups[MaxFlpClass-1].Owner, "MachineOwner");
PossibleFollowups[MaxFlpClass-1].InstructionOffset = Stk[0].InstructionOffset;
return;
}
}
//
// Get the current stack and check if we can get trap
// frame/context from it
//
ULONG64 ExceptionPointers = 0;
for (i = 0; i < Frames; ++i)
{
#if 0
// Stack walker taskes care of these when walking stack
if (GetTrapFromStackFrameFPO(&stk[i], &TrapFrame))
{
break;
}
#endif
//
// First argument of this function is the assert
// Second argument of this function is the file name
// Third argument of this function is the line number
//
if (FaIsFunctionAddr(Stk[i].InstructionOffset, "RtlAssert"))
{
ULONG Len;
CHAR AssertData[MAX_PATH + 1] = {0};
if (Len = ReadAcsiiString(Stk[i].Params[0],
AssertData,
sizeof(AssertData)))
{
SetString(DEBUG_FLR_ASSERT_DATA, AssertData);
}
if (Len = ReadAcsiiString(Stk[i].Params[1],
AssertData,
sizeof(AssertData)))
{
strncat(AssertData, " at Line ", sizeof(AssertData) - Len);
Len = strlen(AssertData);
PrintString(AssertData + Len,
sizeof(AssertData) - Len - 1,
"%I64lx",
Stk[i].Params[2]);
SetString(DEBUG_FLR_ASSERT_FILE, AssertData);
}
}
// If Trap 0E is the second or 3rd frame on the stack, we can just
// switch to that trap frame.
// Otherwise, we want to leave it as is because the failure is
// most likely due to the frames between bugcheck and trap0E
//
// ebp of KiTrap0E is the trap frame
//
if ((i <= Trap0EFrameLimit) &&
FaIsFunctionAddr(Stk[i].InstructionOffset, "KiTrap0E"))
{
TrapFrame = Stk[i].Reserved[2];
break;
}
//
// take first param - spin lock - and it contains the thread that
// owns the spin lock.
// Make sure to zero the bottom bit as it is always set ...
//
if ((i == 0) &&
FaIsFunctionAddr(Stk[i].InstructionOffset,
"SpinLockSpinningForTooLong"))
{
if (ReadPointer(Stk[0].Params[0], &Thread) &&
Thread)
{
Thread &= ~0x1;
}
break;
}
//
// First arg of KiMemoryFault is the trap frame
//
if (FaIsFunctionAddr(Stk[i].InstructionOffset, "KiMemoryFault") ||
FaIsFunctionAddr(Stk[i].InstructionOffset,
"Ki386CheckDivideByZeroTrap"))
{
TrapFrame = Stk[i].Params[0];
break;
}
//
// Third arg of KiMemoryFault is the trap frame
//
if (FaIsFunctionAddr(Stk[i].InstructionOffset,
"KiDispatchException"))
{
TrapFrame = Stk[i].Params[2];
break;
}
//
// First argument of this function is EXCEPTION_POINTERS
//
if (FaIsFunctionAddr(Stk[i].InstructionOffset,
"PspUnhandledExceptionInSystemThread"))
{
ExceptionPointers = Stk[i].Params[0];
break;
}
//
// First argument of this function is a BUGCHECK_DATA structure
// The thread is the second parameter in that data structure
//
if (FaIsFunctionAddr(Stk[i].InstructionOffset,
"WdBugCheckStuckDriver") ||
FaIsFunctionAddr(Stk[i].InstructionOffset,
"WdpBugCheckStuckDriver"))
{
ReadPointer(Stk[i].Params[0] + PtrSize, &Thread);
break;
}
//
// First argument of these functions are EXCEPTION_POINTERS
//
if (FaIsFunctionAddr(Stk[i].InstructionOffset,
"PopExceptionFilter") ||
FaIsFunctionAddr(Stk[i].InstructionOffset,
"RtlUnhandledExceptionFilter2"))
{
ExceptionPointers = Stk[i].Params[0];
break;
}
//
// THIRD argument has the name of Exe
// nt!PspCatchCriticalBreak(char* Msg, void* Object,unsigned char* ImageFileName)
//
if (FaIsFunctionAddr(Stk[i].InstructionOffset,
"PspCatchCriticalBreak"))
{
ImageNameAddr = Stk[i].Params[2];
break;
}
//
// VERIFIER : Look for possible verifier failures
// verifier!VerifierStopMessage means verifier caused the break
//
if (FaIsFunctionAddr(Stk[i].InstructionOffset,
"VerifierStopMessage"))
{
IsVrfBugcheck = TRUE;
break;
}
}
if (ExceptionPointers)
{
ULONG64 Exr = 0, Cxr = 0;
if (!ReadPointer(ExceptionPointers, &Exr) ||
!ReadPointer(ExceptionPointers + PtrSize, &Cxr))
{
// dprintf("Unable to read exception pointers at %p\n",
// ExcepPtr);
}
if (Exr)
{
SetUlong64(DEBUG_FLR_EXCEPTION_RECORD, Exr);
}
if (Cxr)
{
sprintf(Command, ".cxr %I64lx", Cxr);
SetUlong64(DEBUG_FLR_CONTEXT, Cxr);
}
}
if (TrapFrame)
{
sprintf(Command, ".trap %I64lx", TrapFrame);
SetUlong64(DEBUG_FLR_TRAP_FRAME, TrapFrame);
}
if (Thread)
{
sprintf(Command, ".thread %I64lx", Thread);
SetUlong64(DEBUG_FLR_FAULTING_THREAD, Thread);
}
if (ImageNameAddr)
{
CHAR Buffer[50]={0}, *pImgExt;
ULONG cb;
if (ReadMemory(ImageNameAddr, Buffer, sizeof(Buffer) - 1, &cb) &&
Buffer[0])
{
if (pImgExt = strchr(Buffer, '.'))
{
// we do not want imageextension here
*pImgExt = 0;
}
SetString(DEBUG_FLR_MODULE_NAME, Buffer);
}
}
if (IsVrfBugcheck)
{
ULONG64 AvrfCxr = 0;
// We hit this when app verifier breaks into kd and usermode
// analysis isn't called
if (DoVerifierAnalysis(NULL, this) == S_OK)
{
if (GetUlong64(DEBUG_FLR_CONTEXT, &AvrfCxr) != NULL)
{
sprintf(Command, ".cxr %I64lx", AvrfCxr);
}
}
}
}
//
// execute the command and get an updated stack
//
if (Command[0])
{
g_ExtControl->Execute(DEBUG_OUTCTL_IGNORE, Command,
DEBUG_EXECUTE_NOT_LOGGED);
if (g_ExtControl->GetStackTrace(0, 0, 0, Stk, MAX_STACK_FRAMES,
&Frames) != S_OK)
{
Frames = 0;
}
}
//
// Get relevant stack
//
// We can get stack with 1 frame because a .trap can bring us to the
// faulting instruction, and if it's a 3rd party driver with no symbols
// and image, the stack can be 1 frame - although a very valid one.
//
if (Frames)
{
ULONG64 Values[3];
Values[0] = Stk[0].ReturnOffset;
Values[1] = Stk[0].InstructionOffset;
Values[2] = Stk[0].StackOffset;
SetUlong64s(DEBUG_FLR_LAST_CONTROL_TRANSFER, 3, Values);
// If everything on the stack is user mode in the case of a kernel
// mode failure, we got some bad context information.
if (IsFollowupContext(Values[0],Values[1],Values[2]) != FollowYes)
{
SetUlong64(DEBUG_FLR_INVALID_KERNEL_CONTEXT, 0);
BadContext = TRUE;
}
else
{
GetTriageInfoFromStack(&Stk[0], Frames, 0, PossibleFollowups,
&BestClassFollowUp);
}
}
ULONG64 StackBase = FaGetImplicitStackOffset();
//
// If the stack pointer is not aligned, take a note of that.
//
if (StackBase & 0x3)
{
Set(DEBUG_FLR_UNALIGNED_STACK_POINTER, 0);
}
//
// If we have an image name (possibly directly from the bugcheck
// information) try to get the followup from that.
//
if ((BestClassFollowUp < FlpUnknownDrv) &&
(Entry = Get(DEBUG_FLR_MODULE_NAME)))
{
FaGetFollowupInfo(NULL,
FA_ENTRY_DATA(PCHAR, Entry),
PossibleFollowups[FlpUnknownDrv].Owner,
sizeof(PossibleFollowups[FlpUnknownDrv].Owner));
if (PossibleFollowups[FlpUnknownDrv].Owner[0])
{
BestClassFollowUp = FlpUnknownDrv;
}
}
//
// If we could not find anything at this point, look further up the stack
// for a trap frame to catch failures of this kind:
// nt!RtlpBreakWithStatusInstruction
// nt!KiBugCheckDebugBreak+0x19
// nt!KeBugCheck2+0x499
// nt!KeBugCheckEx+0x19
// nt!_KiTrap0E+0x224
//
if (!Command[0] &&
(BestClassFollowUp < FlpOSFilterDrv) &&
(Trap0EFrameLimit != 0xff))
{
Trap0EFrameLimit = 0xff;
goto RepeatGetCommand;
}
//
// Last resort, manually read the stack and look for some symbol
// to followup on.
//
if ((BadContext == FALSE) &&
((BestClassFollowUp == FlpIgnore) ||
((BestClassFollowUp < FlpOSRoutine) && (Frames <= 2))))
{
FindFollowupOnRawStack(StackBase,
PossibleFollowups,
&BestClassFollowUp);
}
//
// Get something !
//
if (BestClassFollowUp < FlpOSRoutine)
{
if (!BestClassFollowUp)
{
PossibleFollowups[FlpOSInternalRoutine].InstructionOffset =
GetExpression("@$ip");
}
if (!PossibleFollowups[FlpOSInternalRoutine].Owner[0] ||
!_stricmp(PossibleFollowups[FlpOSInternalRoutine].Owner, "ignore"))
{
FaGetFollowupInfo(NULL,
"default",
PossibleFollowups[FlpOSInternalRoutine].Owner,
sizeof(PossibleFollowups[FlpOSInternalRoutine].Owner));
BestClassFollowUp = FlpOSRoutine;
}
}
//
// Special handling so a bugcheck EA can always take predence over a pool
// corruption.
//
if (BoostToSpecific)
{
for (i = MaxFlpClass-1; i ; i--)
{
if (PossibleFollowups[i].Owner[0])
{
PossibleFollowups[FlpSpecific] = PossibleFollowups[i];
break;
}
}
}
//
// Get the faulting stack
//
g_OutCapCb.Reset();
g_OutCapCb.Output(0, "\n");
g_ExtClient->GetOutputCallbacks(&PrevCB);
g_ExtClient->SetOutputCallbacks(&g_OutCapCb);
g_ExtControl->OutputStackTrace(DEBUG_OUTCTL_THIS_CLIENT |
DEBUG_OUTCTL_NOT_LOGGED, Stk, Frames,
DEBUG_STACK_ARGUMENTS |
DEBUG_STACK_FRAME_ADDRESSES |
DEBUG_STACK_SOURCE_LINE);
g_ExtClient->SetOutputCallbacks(PrevCB);
if (*g_OutCapCb.GetCapturedText())
{
SetString(DEBUG_FLR_STACK_TEXT, g_OutCapCb.GetCapturedText());
}
//
// Reset the current state to normal so !analyze does not have any
// side-effects
//
if (Command[0])
{
SetString(DEBUG_FLR_STACK_COMMAND, Command);
//
// Clear the set context
//
g_ExtControl->Execute(DEBUG_OUTCTL_IGNORE, ".cxr 0; .thread",
DEBUG_EXECUTE_NOT_LOGGED);
}
}
VOID
DebugFailureAnalysis::FindFollowupOnRawStack(
ULONG64 StackBase,
PFOLLOWUP_DESCS PossibleFollowups,
FlpClasses *BestClassFollowUp
)
{
#define NUM_ADDRS 200
ULONG i;
ULONG PtrSize = IsPtr64() ? 8 : 4;
BOOL AddressFound = FALSE;
BOOL ZeroedStack = TRUE;
ULONG64 AddrToLookup;
FlpClasses RawStkBestFollowup;
if (*BestClassFollowUp >= FlpUnknownDrv)
{
// Any better fron raw stack won't be as accurate as what we have
return;
} else if (*BestClassFollowUp == FlpIgnore)
{
// We don't want to followup on os internal routine here
RawStkBestFollowup = FlpOSInternalRoutine;
} else
{
RawStkBestFollowup = *BestClassFollowUp;
}
// Align stack to natural pointer size.
StackBase &= ~((ULONG64)PtrSize - 1);
for (i = 0; i < NUM_ADDRS; i++)
{
if (!ReadPointer(StackBase, &AddrToLookup))
{
break;
}
StackBase+= PtrSize;
if (AddrToLookup)
{
FOLLOW_ADDRESS Follow;
ZeroedStack = FALSE;
Follow = IsPotentialFollowupAddress(AddrToLookup);
if (Follow == FollowStop)
{
break;
}
else if (Follow == FollowSkip)
{
continue;
}
AddressFound = TRUE;
GetTriageInfoFromStack(0, 1, AddrToLookup,
PossibleFollowups,
&RawStkBestFollowup);
if (RawStkBestFollowup == FlpUnknownDrv)
{
break;
}
}
}
if (!AddressFound)
{
if (ZeroedStack)
{
SetUlong64(DEBUG_FLR_ZEROED_STACK, 0);
}
else
{
SetUlong64(DEBUG_FLR_BAD_STACK, 0);
}
}
if (RawStkBestFollowup > FlpOSInternalRoutine)
{
*BestClassFollowUp = RawStkBestFollowup;
}
}
BOOL
DebugFailureAnalysis::GetTriageInfoFromStack(
PDEBUG_STACK_FRAME Stack,
ULONG Frames,
ULONG64 SingleInstruction,
PFOLLOWUP_DESCS PossibleFollowups,
FlpClasses *BestClassFollowUp)
{
ULONG i;
EXT_TRIAGE_FOLLOWUP FollowUp = &_EFN_GetTriageFollowupFromSymbol;
BOOL bStat = FALSE;
BOOL IgnorePoolCorruptionFlp = FALSE;
FOLLOW_ADDRESS Follow;
if (Get(DEBUG_FLR_ANALYZAABLE_POOL_CORRUPTION))
{
IgnorePoolCorruptionFlp = TRUE;
}
for (i = 0; i < Frames; ++i)
{
ULONG64 Disp;
ULONG64 Instruction;
CHAR Module[20] = {0};
CHAR Buffer[MAX_PATH];
CHAR Owner[100];
DWORD dwOwner;
DEBUG_TRIAGE_FOLLOWUP_INFO Info;
FlpClasses ClassFollowUp = FlpIgnore;
FlpClasses StoreClassFollowUp = FlpIgnore;
Instruction = SingleInstruction;
if (!SingleInstruction)
{
Instruction = Stack[i].InstructionOffset;
}
//
// Determine how to process this address.
//
Follow = IsPotentialFollowupAddress(Instruction);
if (Follow == FollowStop)
{
break;
}
else if (Follow == FollowSkip)
{
continue;
}
Buffer[0] = 0;
FaGetSymbol(Instruction, Buffer, &Disp, sizeof(Buffer));
if (Buffer[0] == 0)
{
//
// Either its a bad stack or someone jumped called to bad IP
//
continue;
}
//
// Check if this routine has any special significance for getting
// faulting module
//
PCHAR Routine = strchr(Buffer, '!');
if (Routine)
{
*Routine = 0;
}
CopyString(Module, Buffer, sizeof(Module));
if (Routine)
{
*Routine = '!';
Routine++;
if (Stack && !strcmp(Routine, "IopCompleteRequest"))
{
// First argument is Irp Tail, get the driver from Irp
ULONG TailOffset = 0;
ULONG64 Irp;
GetFieldOffset("nt!_IRP", "Tail", &TailOffset);
if (TailOffset)
{
FA_ENTRY* Entry = NULL;
PCHAR ModuleName = NULL;
Irp = Stack[i].Params[0] - TailOffset;
SetUlong64(DEBUG_FLR_IRP_ADDRESS, Irp);
if (BcGetDriverNameFromIrp(this, Irp, NULL, NULL))
{
if (Entry = Get(DEBUG_FLR_IMAGE_NAME))
{
CopyString(Buffer, FA_ENTRY_DATA(PCHAR, Entry), sizeof(Buffer));
PCHAR Dot;
if (Dot = strchr(Buffer, '.'))
{
*Dot = 0;
CopyString(Module, Buffer, sizeof(Module));
}
}
}
}
}
else if ((i == 0) && Stack &&
!strcmp(Routine, "ObpCloseHandleTableEntry"))
{
//
// Check for possible memory corruption
// 2nd parameter is HANDLE_TABLE_ENTRY
//
if (CheckForCorruptionInHTE(Stack[i].Params[1], Owner, sizeof(Owner)))
{
// We have pool corrupting PoolTag in analysis
// continue with default analysis for now
}
}
}
ClassFollowUp = GetFollowupClass(Instruction, Module, Routine);
if (ClassFollowUp == FlpIgnore)
{
continue;
}
Info.SizeOfStruct = sizeof(Info);
Info.OwnerName = &Owner[0];
Info.OwnerNameSize = sizeof(Owner);
if (dwOwner = (*FollowUp)(g_ExtClient, Buffer, &Info))
{
PCHAR pOwner = Owner;
if (dwOwner == TRIAGE_FOLLOWUP_IGNORE)
{
ClassFollowUp = FlpIgnore;
}
else if (!strncmp(Owner, "maybe_", 6))
{
pOwner = Owner + 6;
ClassFollowUp = (FlpClasses) ((ULONG) ClassFollowUp - 1);
}
else if (!strncmp(Owner, "last_", 5))
{
pOwner = Owner + 5;
ClassFollowUp = FlpOSInternalRoutine;
}
else if (!strncmp(Owner, "specific_", 9))
{
pOwner = Owner + 9;
ClassFollowUp = FlpSpecific;
}
else if (!_stricmp(Owner, "pool_corruption"))
{
if (IgnorePoolCorruptionFlp)
{
continue;
}
//
// If we have non-kernel followups already on the stack
// it could be them no correctly handling this stack.
// If we only have kernel calls, then it must be pool
// corruption.
//
// We later rely on a pool corruption always being marked
// as a FlpUnknownDrv
//
StoreClassFollowUp = FlpUnknownDrv;
ClassFollowUp = FlpOSFilterDrv;
}
if (StoreClassFollowUp == FlpIgnore)
{
StoreClassFollowUp = ClassFollowUp;
}
//
// Save this entry if it's better than anything else we have.
//
if (ClassFollowUp > *BestClassFollowUp)
{
bStat = TRUE;
*BestClassFollowUp = StoreClassFollowUp;
CopyString(PossibleFollowups[StoreClassFollowUp].Owner,
pOwner,
sizeof(PossibleFollowups[StoreClassFollowUp].Owner));
PossibleFollowups[StoreClassFollowUp].InstructionOffset =
Instruction;
if (StoreClassFollowUp == FlpUnknownDrv)
{
// Best match possible
return bStat;
}
}
}
}
return bStat;
}
BOOL
DebugFailureAnalysis::AddCorruptModules(void)
{
//
// Check if we have an old build. Anything smaller than OSBuild
// and not identified specifically by build number in the list is old.
//
PCHAR String;
CHAR BuildString[7];
ULONG BuildNum = 0;
BOOL FoundCorruptor = FALSE;
BOOL PoolCorruption = FALSE;
ULONG Loaded;
ULONG Unloaded;
CHAR Name[MAX_PATH];
CHAR ImageName[MAX_PATH];
CHAR CorruptModule[MAX_PATH];
FA_ENTRY *Entry;
FA_ENTRY *BugCheckEntry;
sprintf(BuildString, "%d", g_TargetBuild);
if (!g_pTriager->GetFollowupStr("OSBuild", BuildString))
{
if (String = g_pTriager->GetFollowupStr("OSBuild", "old"))
{
BuildNum = strtol(String, NULL, 10);
if (BuildNum > g_TargetBuild)
{
SetUlong64(DEBUG_FLR_OLD_OS_VERSION, g_TargetBuild);
}
}
}
//
// If we have a specific solution, return
// if we can't get a module list, return
//
if (PossibleFollowups[FlpSpecific].Owner[0] ||
(g_ExtSymbols->GetNumberModules(&Loaded, &Unloaded) != S_OK))
{
return FALSE;
}
//
// Determine if the failure was likely caused by a pool corruption
//
if ((BestClassFollowUp < FlpUnknownDrv) ||
!_stricmp(PossibleFollowups[FlpUnknownDrv].Owner, "pool_corruption"))
{
PoolCorruption = TRUE;
}
BugCheckEntry = Get(DEBUG_FLR_BUGCHECK_STR);
//
// Loop three types to find the types of corruptors in order.
// the order must match the order in which we generate the bucket name
// for these types so the image name ends up correct.
//
for (ULONG TypeLoop = 0; TypeLoop < 3; TypeLoop++)
{
if ((TypeLoop == 0) && !BugCheckEntry)
{
continue;
}
if ((TypeLoop == 2) && !PoolCorruption)
{
continue;
}
for (ULONG Index = 0; Index < Loaded + Unloaded; Index++)
{
ULONG64 Base;
DEBUG_FLR_PARAM_TYPE Type = (DEBUG_FLR_PARAM_TYPE)0;
PCHAR Scan;
PCHAR DriverName;
DEBUG_MODULE_PARAMETERS Params;
ULONG Start, End = 0;
if (g_ExtSymbols->GetModuleByIndex(Index, &Base) != S_OK)
{
continue;
}
if (g_ExtSymbols->GetModuleNames(Index, Base,
ImageName, MAX_PATH, NULL,
Name, MAX_PATH, NULL,
NULL, 0, NULL) != S_OK)
{
continue;
}
if (g_ExtSymbols->GetModuleParameters(1, &Base, Index,
&Params) != S_OK)
{
continue;
}
//
// Strip the path
//
DriverName = ImageName;
if (Scan = strrchr(DriverName, '\\'))
{
DriverName = Scan+1;
}
//
// Look for the module in both the various bad drivers list.
// poolcorruptor and memorycorruptor lists in triage.ini
//
switch (TypeLoop)
{
case 0:
Type = DEBUG_FLR_BUGCHECKING_DRIVER;
PrintString(CorruptModule, sizeof(CorruptModule), "%s_%s",
FA_ENTRY_DATA(PCHAR, BugCheckEntry), DriverName);
g_pTriager->GetFollowupDate("bugcheckingDriver", CorruptModule,
&Start, &End);
break;
case 1:
Type = DEBUG_FLR_MEMORY_CORRUPTOR;
g_pTriager->GetFollowupDate("memorycorruptors", DriverName,
&Start, &End);
break;
case 2:
//
// Only look at kernel mode pool corruptors if the failure
// is a kernel mode crash (and same for user mode), because
// a kernel pool corruptor will almost never affect an app
// (apps don't see data in pool blocks)
//
if ((BOOL)(GetFailureType() != DEBUG_FLR_KERNEL) ==
(BOOL)((Params.Flags & DEBUG_MODULE_USER_MODE) != 0))
{
Type = DEBUG_FLR_POOL_CORRUPTOR;
g_pTriager->GetFollowupDate("poolcorruptors", DriverName,
&Start, &End);
}
break;
}
//
// Add it to the list if it's really known to be a bad driver.
//
if (End)
{
//
// Check to see if the timestamp is older than a fixed
// driver. If the module is unloaded and no fix is know,
// then also mark it as bad
//
if ( (Params.TimeDateStamp &&
(Params.TimeDateStamp < End) &&
(Params.TimeDateStamp >= Start)) ||
((Params.Flags & DEBUG_MODULE_UNLOADED) &&
(End == 0xffffffff)) )
{
// Don't store the timestamp on memory corrupting
// modules to simplify bucketing annd allow for
// name lookup.
//
//sprintf(CorruptModule, "%s_%08lx",
// DriverName, Params.TimeDateStamp);
//
// Store the first driver we find as the cause,
// bug accumulate the list of known memory corruptors.
//
if (!FoundCorruptor)
{
SetString(DEBUG_FLR_MODULE_NAME, Name);
SetString(DEBUG_FLR_IMAGE_NAME, DriverName);
SetUlong64(DEBUG_FLR_IMAGE_TIMESTAMP,
Params.TimeDateStamp);
FoundCorruptor = TRUE;
}
//
// Remove the dot since we check the followup
// based on that string.
//
if (Scan = strrchr(DriverName, '.'))
{
*Scan = 0;
}
if (strlen(DriverName) < sizeof(CorruptModule))
{
CopyString(CorruptModule, DriverName,
sizeof(CorruptModule));
}
Entry = Add(Type, strlen(CorruptModule) + 1);
if (Entry)
{
CopyString(FA_ENTRY_DATA(PCHAR, Entry),
CorruptModule, Entry->FullSize);
}
}
}
}
}
return FoundCorruptor;
}
void
DebugFailureAnalysis::SetSymbolNameAndModule()
{
ULONG64 Address = 0;
CHAR Buffer[MAX_PATH];
ULONG64 Disp, Base = 0;
ULONG Index;
ULONG i;
//
// Store the best followup name in the analysis results
//
for (i = MaxFlpClass-1; i ; i--)
{
if (PossibleFollowups[i].Owner[0])
{
if (PossibleFollowups[i].InstructionOffset)
{
Address = PossibleFollowups[i].InstructionOffset;
SetUlong64(DEBUG_FLR_FOLLOWUP_IP,
PossibleFollowups[i].InstructionOffset);
}
SetString(DEBUG_FLR_FOLLOWUP_NAME, PossibleFollowups[i].Owner);
break;
}
}
//
// Now that we have the followip, get the module names.
//
// The address may not be set in the case where we just
// had a driver name with no real address for it
//
if (Address)
{
//
// Try to get the full symbol name.
// leave space for Displacement
//
Buffer[0] = 0;
if (FaGetSymbol(Address, Buffer, &Disp, sizeof(Buffer) - 20))
{
sprintf(Buffer + strlen(Buffer), "+%I64lx", Disp);
SetString(DEBUG_FLR_SYMBOL_NAME, Buffer);
}
//
// Now get the Mod name
//
g_ExtSymbols->GetModuleByOffset(Address, 0, &Index, &Base);
if (Base)
{
CHAR ModBuf[100];
CHAR ImageBuf[100];
PCHAR Scan;
PCHAR ImageName;
if (g_ExtSymbols->GetModuleNames(Index, Base,
ImageBuf, sizeof(ImageBuf), NULL,
ModBuf, sizeof(ModBuf), NULL,
NULL, 0, NULL) == S_OK)
{
//
// Check for unknown module.
// If it's not, then we should have something valid.
//
if (!strstr(ModBuf, "Unknown"))
{
//
// Strip the path - keep the extension
//
ImageName = ImageBuf;
if (Scan = strrchr(ImageName, '\\'))
{
ImageName = Scan+1;
}
SetString(DEBUG_FLR_MODULE_NAME, ModBuf);
SetString(DEBUG_FLR_IMAGE_NAME, ImageName);
DEBUG_MODULE_PARAMETERS Params;
ULONG TimeStamp = 0;
if (g_ExtSymbols->GetModuleParameters(1, &Base, Index,
&Params) == S_OK)
{
TimeStamp = Params.TimeDateStamp;
}
SetUlong64(DEBUG_FLR_IMAGE_TIMESTAMP, TimeStamp);
return;
}
}
}
}
//
// If we make it here there was an error getting module name,
// so set things to "unknown".
//
if (!Get(DEBUG_FLR_MODULE_NAME))
{
SetUlong64(DEBUG_FLR_UNKNOWN_MODULE, 1);
SetString(DEBUG_FLR_MODULE_NAME, "Unknown_Module");
SetString(DEBUG_FLR_IMAGE_NAME, "Unknown_Image");
SetUlong64(DEBUG_FLR_IMAGE_TIMESTAMP, 0);
}
}
HRESULT
DebugFailureAnalysis::CheckModuleSymbols(PSTR ModName, PSTR ShowName)
{
ULONG ModIndex;
ULONG64 ModBase;
DEBUG_MODULE_PARAMETERS ModParams;
if (S_OK != g_ExtSymbols->GetModuleByModuleName(ModName, 0, &ModIndex,
&ModBase))
{
ExtErr("***** Debugger could not find %s in module list, "
"dump might be corrupt.\n"
"***** Followup with Debugger team\n\n",
ModName);
SetString(DEBUG_FLR_CORRUPT_MODULE_LIST, ModName);
return E_FAILURE_CORRUPT_MODULE_LIST;
}
else if ((S_OK != g_ExtSymbols->GetModuleParameters(1, &ModBase, 0,
&ModParams)) ||
(ModParams.SymbolType == DEBUG_SYMTYPE_NONE) ||
(ModParams.SymbolType == DEBUG_SYMTYPE_EXPORT))
// (ModParams.Flags & DEBUG_MODULE_SYM_BAD_CHECKSUM))
{
ExtErr("***** %s symbols are WRONG. Please fix symbols to "
"do analysis.\n\n", ShowName);
SetUlong64(DEBUG_FLR_WRONG_SYMBOLS, ModBase);
return E_FAILURE_WRONG_SYMBOLS;
}
return S_OK;
}
void
DebugFailureAnalysis::ProcessInformation(void)
{
//
// Analysis of abstracted information.
//
// Now that raw information has been gathered,
// perform abstract analysis of the gathered
// information to produce even higher-level
// information. The process iterates until no
// new information is produced.
//
AnalyzeStack();
while (ProcessInformationPass())
{
// Iterate.
}
//
// Only add corrupt modules if we did not find a specific solution.
//
// If we do find a memory corruptor, the followup and name will be set
// from the module name as part of bucketing.
if (!AddCorruptModules())
{
SetSymbolNameAndModule();
}
GenerateBucketId();
DbFindBucketInfo();
}
ULONG64
GetControlTransferTargetX86(ULONG64 StackOffset, PULONG64 ReturnOffset)
{
ULONG Done;
UCHAR InstrBuf[8];
ULONG StackReturn;
ULONG64 Target;
ULONG JumpCount;
//
// Check that we just performed a call, which implies
// the first value on the stack is equal to the return address
// computed during stack walk.
//
if (!ReadMemory(StackOffset, &StackReturn, 4, &Done) ||
(Done != 4) ||
StackReturn != (ULONG)*ReturnOffset)
{
return 0;
}
//
// Check for call rel32 instruction.
//
if (!ReadMemory(*ReturnOffset - 5, InstrBuf, 5, &Done) ||
(Done != 5) ||
(InstrBuf[0] != 0xe8))
{
return 0;
}
Target = (LONG64)(LONG)
((ULONG)*ReturnOffset + *(ULONG UNALIGNED *)&InstrBuf[1]);
// Adjust the return offset to point to the start of the instruction.
(*ReturnOffset) -= 5;
//
// We may have called an import thunk or something else which
// immediately jumps somewhere else, so follow jumps.
//
JumpCount = 8;
for (;;)
{
if (!ReadMemory(Target, InstrBuf, 6, &Done) ||
Done < 5)
{
// We expect to be able to read the target memory
// as that's where we think IP is. If this fails
// we need to flag it as a problem.
return Target;
}
if (InstrBuf[0] == 0xe9)
{
Target = (LONG64)(LONG)
((ULONG)Target + 5 + *(ULONG UNALIGNED *)&InstrBuf[1]);
}
else if (InstrBuf[0] == 0xff && InstrBuf[1] == 0x25)
{
ULONG64 Ind;
if (Done < 6)
{
// We see a jump but we don't have all the
// memory. To avoid spurious errors we just
// give up.
return 0;
}
Ind = (LONG64)(LONG)*(ULONG UNALIGNED *)&InstrBuf[2];
if (!ReadMemory(Ind, &Target, 4, &Done) ||
Done != 4)
{
return 0;
}
Target = (LONG64)(LONG)Target;
}
else
{
break;
}
if (JumpCount-- == 0)
{
// We've been tracing jumps too long, just give up.
return 0;
}
}
return Target;
}
BOOL
DebugFailureAnalysis::ProcessInformationPass(void)
{
ULONG Done;
ULONG64 ExceptionCode;
ULONG64 Arg1, Arg2;
ULONG64 Values[2];
ULONG PtrSize = IsPtr64() ? 8 : 4;
FA_ENTRY* Entry;
//
// Determine if the current fault is due to inability
// to execute an instruction. The checks are:
// 1. A read access violation at the current IP indicates
// the current instruction memory is invalid.
// 2. An illegal instruction fault indicates the current
// instruction is invalid.
//
if (!Get(DEBUG_FLR_FAILED_INSTRUCTION_ADDRESS))
{
if (GetUlong64(DEBUG_FLR_EXCEPTION_CODE, &ExceptionCode) &&
(ExceptionCode == STATUS_ILLEGAL_INSTRUCTION) &&
GetUlong64(DEBUG_FLR_FAULTING_IP, &Arg1))
{
// Invalid instruction.
SetUlong64(DEBUG_FLR_FAILED_INSTRUCTION_ADDRESS, Arg1);
return TRUE;
}
if ( // ExceptionCode == STATUS_ACCESS_VIOLATION &&
GetUlong64(DEBUG_FLR_READ_ADDRESS, &Arg1) &&
GetUlong64(DEBUG_FLR_FAULTING_IP, &Arg2) &&
Arg1 == Arg2)
{
// Invalid instruction.
SetUlong64(DEBUG_FLR_FAILED_INSTRUCTION_ADDRESS, Arg1);
return TRUE;
}
}
//
// If we've determined that the current failure is
// due to inability to execute an instruction, check
// and see whether there's a call to the instruction.
// If the instruction prior at the return address can be analyzed,
// check for known instruction sequences to see if perhaps
// the processor incorrectly handled a control transfer.
//
if (!Get(DEBUG_FLR_POSSIBLE_INVALID_CONTROL_TRANSFER) &&
(Entry = Get(DEBUG_FLR_LAST_CONTROL_TRANSFER)))
{
ULONG64 ReturnOffset = FA_ENTRY_DATA(PULONG64, Entry)[0];
Arg2 = FA_ENTRY_DATA(PULONG64, Entry)[1];
ULONG64 StackOffset = FA_ENTRY_DATA(PULONG64, Entry)[2];
ULONG64 Target = 0;
switch(g_TargetMachine)
{
case IMAGE_FILE_MACHINE_I386:
Target = GetControlTransferTargetX86(StackOffset, &ReturnOffset);
break;
}
if (Target && Target != Arg2)
{
char Sym1[MAX_PATH], Sym2[MAX_PATH];
ULONG64 Disp;
//
// If both addresses are within the same function
// we assume that there has been some execution
// in the function and therefore this doesn't
// actually indicate a problem.
// NOTE - DbgBreakPointWithStatus has an internal label
// which messes up symbols, so account for that too by
// checking we are 10 bytes within the function.
//
FaGetSymbol(Target, Sym1, &Disp, sizeof(Sym1));
FaGetSymbol(Arg2, Sym2, &Disp, sizeof(Sym2));
if ((Arg2 - Target > 10) &&
(strcmp(Sym1, Sym2) != 0))
{
PCHAR String;
ULONG64 BitDiff;
ULONG64 BitDiff2;
Values[0] = ReturnOffset;
Values[1] = Target;
SetUlong64s(DEBUG_FLR_POSSIBLE_INVALID_CONTROL_TRANSFER,
2, Values);
//
// If the difference between the two address is a power of 2,
// then it's a single bit error.
// Also, to avoid sign extension issues due to a 1 bit error
// in the top bit, check if the difference betweent the two is
// only the sign extensions, and zero out the top 32 bits if
// it's the case.
//
BitDiff = Arg2 ^ Target;
if ((BitDiff >> 32) == 0xFFFFFFFF)
{
BitDiff &= 0xFFFFFFFF;
}
if (!(BitDiff2 = (BitDiff & (BitDiff - 1))))
{
Set(DEBUG_FLR_SINGLE_BIT_ERROR, 1);
}
if (!(BitDiff2 & (BitDiff2 - 1)))
{
Set(DEBUG_FLR_TWO_BIT_ERROR, 1);
}
if (String = g_pTriager->GetFollowupStr("badcpu", ""))
{
BestClassFollowUp = FlpSpecific;
CopyString(PossibleFollowups[FlpSpecific].Owner,
String,
sizeof(PossibleFollowups[FlpSpecific].Owner));
SetString(DEBUG_FLR_MODULE_NAME, "No_Module");
SetString(DEBUG_FLR_IMAGE_NAME, "No_Image");
SetUlong64(DEBUG_FLR_IMAGE_TIMESTAMP, 0);
}
return TRUE;
}
}
}
//
// If the process is determine to be of importance to this failure,
// also expose the process name.
// This will overwrite the PROCESS_NAME of the default process.
//
if (GetUlong64(DEBUG_FLR_PROCESS_OBJECT, &Arg1) &&
!Get(DEBUG_FLR_PROCESS_NAME))
{
ULONG NameOffset;
CHAR Name[17];
if (!GetFieldOffset("nt!_EPROCESS", "ImageFileName", &NameOffset) &&
NameOffset)
{
if (ReadMemory(Arg1 + NameOffset, Name, sizeof(Name), &Done) &&
(Done == sizeof(Name)))
{
Name[16] = 0;
SetString(DEBUG_FLR_PROCESS_NAME, Name);
return TRUE;
}
}
}
return FALSE;
}
| 29.256122 | 103 | 0.5045 | [
"object"
] |
120ebc5fc94670d0ebacbed0233655628052e3c0 | 32,088 | cxx | C++ | Common/DataModel/Testing/Cxx/otherStructuredGrid.cxx | LongerVisionUSA/VTK | 1170774b6611c71b95c28bb821d51c2c18ff091f | [
"BSD-3-Clause"
] | 1 | 2019-05-31T14:00:53.000Z | 2019-05-31T14:00:53.000Z | Common/DataModel/Testing/Cxx/otherStructuredGrid.cxx | LongerVisionUSA/VTK | 1170774b6611c71b95c28bb821d51c2c18ff091f | [
"BSD-3-Clause"
] | null | null | null | Common/DataModel/Testing/Cxx/otherStructuredGrid.cxx | LongerVisionUSA/VTK | 1170774b6611c71b95c28bb821d51c2c18ff091f | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Visualization Toolkit
Module: otherStructuredGrid.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME
// .SECTION Description
// this program tests vtkStructuredGrid
#include "vtkCell.h"
#include "vtkDebugLeaks.h"
#include "vtkDoubleArray.h"
#include "vtkFloatArray.h"
#include "vtkGenericCell.h"
#include "vtkIdList.h"
#include "vtkLongArray.h"
#include "vtkMathUtilities.h"
#include "vtkNew.h"
#include "vtkPointData.h"
#include "vtkShortArray.h"
#include "vtkStructuredGrid.h"
#include <cstdlib>
#include <sstream>
int TestOSG_0d(ostream& strm)
{
int i, k;
vtkNew<vtkStructuredGrid> sg0D;
vtkNew<vtkPoints> onepoints;
for (k = 0; k < 1; k++)
{
onepoints->InsertNextPoint(0.0, 0.0, 0.0);
}
sg0D->SetDimensions(1, 1, 1);
sg0D->SetPoints(onepoints);
if (sg0D->GetCellSize(0) != 1)
{
std::cerr << "vtkStructuredGrid::GetCellSize(cellId) wrong for 0D structured grid.\n";
return 1;
}
vtkNew<vtkShortArray> shortScalars3D;
vtkNew<vtkShortArray> shortScalars0D;
shortScalars0D->SetNumberOfComponents(1);
shortScalars0D->SetNumberOfTuples(1);
int l = 0;
shortScalars0D->InsertComponent(l, 0, 0);
sg0D->GetPointData()->SetScalars(shortScalars0D);
// Test GetCell
vtkNew<vtkIdList> ids;
int cellId;
int ii;
cellId = 0;
vtkCell* cell0D = sg0D->GetCell(0);
strm << "cell0D: " << *cell0D;
sg0D->GetCellPoints(cellId, ids);
strm << "Ids for cell " << cellId << " are ";
for (ii = 0; ii < ids->GetNumberOfIds(); ii++)
{
strm << ids->GetId(ii) << " ";
}
strm << endl << endl;
// Test GetCell(i,j,k)
cellId = 0;
cell0D = sg0D->GetCell(0, 0, 0);
if (cell0D == nullptr)
{
std::cerr << "vtkStructuredGrid::GetCell returned nullptr instead of a valid cell.\n";
return EXIT_FAILURE;
}
if (cell0D->GetCellType() != VTK_VERTEX)
{
std::cerr << "vtkStructuredGrid::GetCell returned the wrong cell type.\n"
<< "Expected: " << VTK_VERTEX << " Returned: " << cell0D->GetCellType() << '\n';
return EXIT_FAILURE;
}
strm << "cell0D: " << *cell0D;
sg0D->GetCellPoints(cellId, ids);
strm << "Ids for cell " << cellId << " are ";
for (ii = 0; ii < ids->GetNumberOfIds(); ii++)
{
strm << ids->GetId(ii) << " ";
}
strm << endl << endl;
// Test Thread Safe GetCell
vtkNew<vtkGenericCell> gcell0D;
i = 10;
sg0D->GetCell(0, gcell0D);
strm << "gcell0D: " << *gcell0D;
// Test GetCellBounds
double bounds[6];
sg0D->GetCellBounds(i, bounds);
strm << "GetCellBounds(sg0D): " << bounds[0] << ", " << bounds[1] << ", " << bounds[2] << ", "
<< bounds[3] << ", " << bounds[4] << ", " << bounds[5] << endl;
// Test GetPoint
double point[6];
sg0D->GetPoint(0, point);
strm << "GetPoint(sg0D): " << point[0] << ", " << point[1] << ", " << point[2] << endl;
// Test GetCellType
strm << "GetCellType(sg0D): " << sg0D->GetCellType(0) << endl;
// Test GetActualMemorySize
strm << "GetActualMemorySize(sg0D): " << sg0D->GetActualMemorySize() << endl;
return EXIT_SUCCESS;
}
int TestOSG_1dx(ostream& strm)
{
int i;
vtkNew<vtkStructuredGrid> sg1Dx;
vtkNew<vtkPoints> xpoints;
for (i = 0; i < 20; i++)
{
xpoints->InsertNextPoint((double)i, 0.0, 0.0);
}
sg1Dx->SetDimensions(20, 1, 1);
sg1Dx->SetPoints(xpoints);
if (sg1Dx->GetCellSize(0) != 2)
{
std::cerr << "vtkStructuredGrid::GetCellSize(cellId) wrong for 1D structured grid.\n";
return 1;
}
vtkNew<vtkShortArray> shortScalars1D;
shortScalars1D->SetNumberOfComponents(1);
shortScalars1D->SetNumberOfTuples(20);
int l = 0;
for (i = 0; i < 20; i++)
{
shortScalars1D->InsertComponent(l, 0, i);
l++;
}
sg1Dx->GetPointData()->SetScalars(shortScalars1D);
// Test GetCell
vtkNew<vtkIdList> ids;
int cellId;
int ii;
i = 10;
cellId = i;
vtkCell* cell1D = sg1Dx->GetCell(i);
strm << "cell1D: " << *cell1D;
sg1Dx->GetCellPoints(cellId, ids);
strm << "Ids for cell " << cellId << " are ";
for (ii = 0; ii < ids->GetNumberOfIds(); ii++)
{
strm << ids->GetId(ii) << " ";
}
strm << endl << endl;
// Test GetCell(i,j,k)
i = 10;
cellId = i;
cell1D = sg1Dx->GetCell(i, 0, 0);
if (cell1D == nullptr)
{
std::cerr << "vtkStructuredGrid::GetCell returned nullptr instead of a valid cell.\n";
return EXIT_FAILURE;
}
if (cell1D->GetCellType() != VTK_LINE)
{
std::cerr << "vtkStructuredGrid::GetCell returned the wrong cell type.\n"
<< "Expected: " << VTK_LINE << " Returned: " << cell1D->GetCellType() << '\n';
return EXIT_FAILURE;
}
double bounds[6];
cell1D->GetBounds(bounds);
if (!vtkMathUtilities::FuzzyCompare(bounds[2], bounds[3]))
{
std::cerr << "sg1Dx has finite width along y\n";
return EXIT_FAILURE;
}
else if (!vtkMathUtilities::FuzzyCompare(bounds[4], bounds[5]))
{
std::cerr << "sg1Dx has finite width along z\n";
return EXIT_FAILURE;
}
strm << "cell1D: " << *cell1D;
sg1Dx->GetCellPoints(cellId, ids);
strm << "Ids for cell " << cellId << " are ";
for (ii = 0; ii < ids->GetNumberOfIds(); ii++)
{
strm << ids->GetId(ii) << " ";
}
strm << endl << endl;
// Test Thread Safe GetCell
vtkNew<vtkGenericCell> gcell1D;
i = 10;
sg1Dx->GetCell(i, gcell1D);
strm << "gcell1D: " << *gcell1D;
// Test GetCellBounds
sg1Dx->GetCellBounds(i, bounds);
strm << "GetCellBounds(sg1x): " << bounds[0] << ", " << bounds[1] << ", " << bounds[2] << ", "
<< bounds[3] << ", " << bounds[4] << ", " << bounds[5] << endl;
// Test GetPoint
double point[6];
sg1Dx->GetPoint(i, point);
strm << "GetPoint(sg1x): " << point[0] << ", " << point[1] << ", " << point[2] << endl;
// Test FindPoint
double point3D[3] = { 10, 12, 14 };
point3D[0] = 10;
point3D[1] = 0;
point3D[2] = 0;
sg1Dx->GetPoint(sg1Dx->FindPoint(point3D), point);
strm << "FindPoint(" << point3D[0] << ", " << point3D[1] << ", " << point3D[2]
<< ") = " << point[0] << ", " << point[1] << ", " << point[2] << endl;
// Test FindAndGetCell
double pcoords[3], weights[8];
int subId;
vtkCell* dummyCell = nullptr;
point3D[0] = 10.5;
point3D[1] = 0.0;
point3D[2] = 0.0;
dummyCell = nullptr;
vtkCell* found = sg1Dx->FindAndGetCell(point3D, dummyCell, 0, 0, subId, pcoords, weights);
if (found == nullptr)
{
strm << "FindAndGetCell(sg1Dx) not found!" << endl;
return EXIT_FAILURE;
}
strm << "FindAndGetCell(sg1Dx): " << *found;
strm << "pcoords: " << pcoords[0] << endl;
strm << "weights: " << weights[0] << ", " << weights[1] << endl;
// Test GetCellType
strm << "GetCellType(sg1Dx): " << sg1Dx->GetCellType(0) << endl;
// Test GetActualMemorySize
strm << "GetActualMemorySize(sg1Dx): " << sg1Dx->GetActualMemorySize() << endl;
return EXIT_SUCCESS;
}
int TestOSG_1dy(ostream& strm)
{
int i, j;
vtkNew<vtkStructuredGrid> sg1Dy;
vtkNew<vtkPoints> ypoints;
for (j = 0; j < 20; j++)
{
ypoints->InsertNextPoint(0.0, (double)j, 0.0);
}
sg1Dy->SetDimensions(1, 20, 1);
sg1Dy->SetPoints(ypoints);
strm << *sg1Dy;
if (sg1Dy->GetCellSize(0) != 2)
{
std::cerr << "vtkStructuredGrid::GetCellSize(cellId) wrong for 1D structured grid.\n";
return 1;
}
vtkNew<vtkShortArray> shortScalars1D;
shortScalars1D->SetNumberOfComponents(1);
shortScalars1D->SetNumberOfTuples(20);
int l = 0;
for (i = 0; i < 20; i++)
{
shortScalars1D->InsertComponent(l, 0, i);
l++;
}
sg1Dy->GetPointData()->SetScalars(shortScalars1D);
// Test GetCell
vtkNew<vtkIdList> ids;
int cellId;
int ii;
i = 10;
cellId = i;
vtkCell* cell1D = sg1Dy->GetCell(i);
strm << "cell1D: " << *cell1D;
sg1Dy->GetCellPoints(cellId, ids);
strm << "Ids for cell " << cellId << " are ";
for (ii = 0; ii < ids->GetNumberOfIds(); ii++)
{
strm << ids->GetId(ii) << " ";
}
strm << endl << endl;
// Test GetCell(i,j,k)
i = 10;
cellId = i;
cell1D = sg1Dy->GetCell(0, i, 0);
if (cell1D == nullptr)
{
std::cerr << "vtkStructuredGrid::GetCell returned nullptr instead of a valid cell.\n";
return EXIT_FAILURE;
}
if (cell1D->GetCellType() != VTK_LINE)
{
std::cerr << "vtkStructuredGrid::GetCell returned the wrong cell type.\n"
<< "Expected: " << VTK_LINE << " Returned: " << cell1D->GetCellType() << '\n';
return EXIT_FAILURE;
}
double bounds[6];
cell1D->GetBounds(bounds);
if (!vtkMathUtilities::FuzzyCompare(bounds[0], bounds[1]))
{
std::cerr << "sg1Dy has finite width along x\n";
return EXIT_FAILURE;
}
else if (!vtkMathUtilities::FuzzyCompare(bounds[4], bounds[5]))
{
std::cerr << "sg1Dy has finite width along z\n";
return EXIT_FAILURE;
}
strm << "cell1D: " << *cell1D;
sg1Dy->GetCellPoints(cellId, ids);
strm << "Ids for cell " << cellId << " are ";
for (ii = 0; ii < ids->GetNumberOfIds(); ii++)
{
strm << ids->GetId(ii) << " ";
}
strm << endl << endl;
// Test Thread Safe GetCell
vtkNew<vtkGenericCell> gcell1D;
i = 10;
sg1Dy->GetCell(i, gcell1D);
strm << "gcell1D: " << *gcell1D;
// Test GetCellBounds
sg1Dy->GetCellBounds(i, bounds);
strm << "GetCellBounds(sg1Dy): " << bounds[0] << ", " << bounds[1] << ", " << bounds[2] << ", "
<< bounds[3] << ", " << bounds[4] << ", " << bounds[5] << endl;
// Test GetPoint
double point[6];
sg1Dy->GetPoint(i, point);
strm << "GetPoint(sg1Dy): " << point[0] << ", " << point[1] << ", " << point[2] << endl;
// Test FindPoint
double point3D[3] = { 10, 12, 14 };
point3D[0] = 0;
point3D[1] = 12;
point3D[2] = 0;
sg1Dy->GetPoint(sg1Dy->FindPoint(point3D), point);
strm << "FindPoint(" << point3D[0] << ", " << point3D[1] << ", " << point3D[2]
<< ") = " << point[0] << ", " << point[1] << ", " << point[2] << endl;
// Test FindAndGetCell
double pcoords[3], weights[8];
int subId;
vtkCell* dummyCell = nullptr;
point3D[0] = 0.0;
point3D[1] = 12.1;
point3D[2] = 0.0;
dummyCell = nullptr;
vtkCell* found = sg1Dy->FindAndGetCell(point3D, dummyCell, 0, 0, subId, pcoords, weights);
if (found == nullptr)
{
strm << "FindAndGetCell(sg1Dy) not found!" << endl;
return EXIT_FAILURE;
}
strm << "FindAndGetCell(sg1Dy): " << *found;
strm << "pcoords: " << pcoords[0] << endl;
strm << "weights: " << weights[0] << ", " << weights[1] << endl;
// Test GetCellType
strm << "GetCellType(sg1Dy): " << sg1Dy->GetCellType(0) << endl;
// Test GetActualMemorySize
strm << "GetActualMemorySize(sg1Dy): " << sg1Dy->GetActualMemorySize() << endl;
return EXIT_SUCCESS;
}
int TestOSG_1dz(ostream& strm)
{
int i, k;
vtkNew<vtkStructuredGrid> sg1Dz;
vtkNew<vtkPoints> zpoints;
for (k = 0; k < 20; k++)
{
zpoints->InsertNextPoint(0.0, 0.0, (double)k);
}
sg1Dz->SetDimensions(1, 1, 20);
sg1Dz->SetPoints(zpoints);
if (sg1Dz->GetCellSize(0) != 2)
{
std::cerr << "vtkStructuredGrid::GetCellSize(cellId) wrong for 1D structured grid.\n";
return 1;
}
vtkNew<vtkShortArray> shortScalars1D;
shortScalars1D->SetNumberOfComponents(1);
shortScalars1D->SetNumberOfTuples(20);
int l = 0;
for (i = 0; i < 20; i++)
{
shortScalars1D->InsertComponent(l, 0, i);
l++;
}
sg1Dz->GetPointData()->SetScalars(shortScalars1D);
// Test GetCell
vtkNew<vtkIdList> ids;
int cellId;
int ii;
i = 10;
cellId = i;
vtkCell* cell1D = sg1Dz->GetCell(i);
strm << "cell1D: " << *cell1D;
sg1Dz->GetCellPoints(cellId, ids);
strm << "Ids for cell " << cellId << " are ";
for (ii = 0; ii < ids->GetNumberOfIds(); ii++)
{
strm << ids->GetId(ii) << " ";
}
strm << endl << endl;
// Test GetCell(i,j,k)
i = 10;
cellId = i;
cell1D = sg1Dz->GetCell(0, 0, i);
if (cell1D == nullptr)
{
std::cerr << "vtkStructuredGrid::GetCell returned nullptr instead of a valid cell.\n";
return EXIT_FAILURE;
}
if (cell1D->GetCellType() != VTK_LINE)
{
std::cerr << "vtkStructuredGrid::GetCell returned the wrong cell type.\n"
<< "Expected: " << VTK_LINE << " Returned: " << cell1D->GetCellType() << '\n';
return EXIT_FAILURE;
}
double bounds[6];
cell1D->GetBounds(bounds);
if (!vtkMathUtilities::FuzzyCompare(bounds[0], bounds[1]))
{
std::cerr << "sg1Dz has finite width along x\n";
return EXIT_FAILURE;
}
else if (!vtkMathUtilities::FuzzyCompare(bounds[2], bounds[3]))
{
std::cerr << "sg1Dz has finite width along y\n";
return EXIT_FAILURE;
}
strm << "cell1D: " << *cell1D;
sg1Dz->GetCellPoints(cellId, ids);
strm << "Ids for cell " << cellId << " are ";
for (ii = 0; ii < ids->GetNumberOfIds(); ii++)
{
strm << ids->GetId(ii) << " ";
}
strm << endl << endl;
// Test Thread Safe GetCell
vtkNew<vtkGenericCell> gcell1D;
i = 10;
sg1Dz->GetCell(i, gcell1D);
strm << "gcell1D: " << *gcell1D;
// Test GetCellBounds
sg1Dz->GetCellBounds(i, bounds);
strm << "GetCellBounds(sg1Dz): " << bounds[0] << ", " << bounds[1] << ", " << bounds[2] << ", "
<< bounds[3] << ", " << bounds[4] << ", " << bounds[5] << endl;
// Test GetPoint
double point[6];
sg1Dz->GetPoint(i, point);
strm << "GetPoint(sg1Dz): " << point[0] << ", " << point[1] << ", " << point[2] << endl;
// Test FindPoint
double point3D[3] = { 10, 12, 14 };
point3D[0] = 0;
point3D[1] = 0;
point3D[2] = 14;
sg1Dz->GetPoint(sg1Dz->FindPoint(point3D), point);
strm << "FindPoint(" << point3D[0] << ", " << point3D[1] << ", " << point3D[2]
<< ") = " << point[0] << ", " << point[1] << ", " << point[2] << endl;
// Test FindAndGetCell
double pcoords[3], weights[8];
int subId;
vtkCell* dummyCell = nullptr;
point3D[0] = 0.0;
point3D[1] = 0.0;
point3D[2] = 14.7;
dummyCell = nullptr;
vtkCell* found = sg1Dz->FindAndGetCell(point3D, dummyCell, 0, 0, subId, pcoords, weights);
if (found == nullptr)
{
strm << "FindAndGetCell(sg1Dz) not found!" << endl;
return EXIT_FAILURE;
}
strm << "FindAndGetCell(sg1Dz): " << *found;
strm << "pcoords: " << pcoords[0] << endl;
strm << "weights: " << weights[0] << ", " << weights[1] << endl;
// Test GetCellType
strm << "GetCellType(sg1Dz): " << sg1Dz->GetCellType(0) << endl;
// Test GetActualMemorySize
strm << "GetActualMemorySize(sg1Dz): " << sg1Dz->GetActualMemorySize() << endl;
return EXIT_SUCCESS;
}
int TestOSG_2dxy(ostream& strm)
{
int i, j;
vtkNew<vtkStructuredGrid> sg2Dxy;
vtkNew<vtkPoints> xypoints;
for (j = 0; j < 20; j++)
{
for (i = 0; i < 20; i++)
{
xypoints->InsertNextPoint((double)i, (double)j, 0.0);
}
}
sg2Dxy->SetDimensions(20, 20, 1);
sg2Dxy->SetPoints(xypoints);
if (sg2Dxy->GetCellSize(0) != 4)
{
std::cerr << "vtkStructuredGrid::GetCellSize(cellId) wrong for 2D structured grid.\n";
return 1;
}
vtkNew<vtkShortArray> shortScalars2D;
shortScalars2D->SetNumberOfComponents(2);
shortScalars2D->SetNumberOfTuples(20 * 20);
int l = 0;
for (j = 0; j < 20; j++)
{
for (i = 0; i < 20; i++)
{
shortScalars2D->InsertComponent(l, 0, i);
shortScalars2D->InsertComponent(l, 0, j);
l++;
}
}
sg2Dxy->GetPointData()->SetScalars(shortScalars2D);
// Test GetCell
vtkNew<vtkIdList> ids;
int cellId;
int ii;
i = 10;
j = 15;
cellId = j * 19 + i;
vtkCell* cell2D = sg2Dxy->GetCell(cellId);
strm << "cell2D: " << *cell2D;
sg2Dxy->GetCellPoints(cellId, ids);
strm << "Ids for cell " << cellId << " are ";
for (ii = 0; ii < ids->GetNumberOfIds(); ii++)
{
strm << ids->GetId(ii) << " ";
}
strm << endl << endl;
// Test GetCell(i,j,k)
i = 10;
j = 15;
cellId = j * 19 + i;
cell2D = sg2Dxy->GetCell(i, j, 0);
if (cell2D == nullptr)
{
std::cerr << "vtkStructuredGrid::GetCell returned nullptr instead of a valid cell.\n";
return EXIT_FAILURE;
}
if (cell2D->GetCellType() != VTK_QUAD)
{
std::cerr << "vtkStructuredGrid::GetCell returned the wrong cell type.\n"
<< "Expected: " << VTK_QUAD << " Returned: " << cell2D->GetCellType() << '\n';
return EXIT_FAILURE;
}
double bounds[6];
cell2D->GetBounds(bounds);
if (!vtkMathUtilities::FuzzyCompare(bounds[4], bounds[5]))
{
std::cerr << "sg2Dxy has finite width along z\n";
return EXIT_FAILURE;
}
strm << "cell2D: " << *cell2D;
sg2Dxy->GetCellPoints(cellId, ids);
strm << "Ids for cell " << cellId << " are ";
for (ii = 0; ii < ids->GetNumberOfIds(); ii++)
{
strm << ids->GetId(ii) << " ";
}
strm << endl << endl;
// Test Thread Safe GetCell
vtkNew<vtkGenericCell> gcell2D;
i = 10;
j = 15;
sg2Dxy->GetCell(j * 19 + i, gcell2D);
strm << "gcell2D: " << *gcell2D;
// Test GetCellBounds
sg2Dxy->GetCellBounds(j * 19 + i, bounds);
strm << "GetCellBounds(sg2Dxy): " << bounds[0] << ", " << bounds[1] << ", " << bounds[2] << ", "
<< bounds[3] << ", " << bounds[4] << ", " << bounds[5] << endl;
// Test GetPoint
double point[6];
sg2Dxy->GetPoint(j * 20 + i, point);
strm << "GetPoint(sg2Dxy): " << point[0] << ", " << point[1] << ", " << point[2] << endl;
// Test FindPoint
double point3D[3] = { 10, 12, 14 };
point3D[0] = 10;
point3D[1] = 12;
point3D[2] = 0;
sg2Dxy->GetPoint(sg2Dxy->FindPoint(point3D), point);
strm << "FindPoint(" << point3D[0] << ", " << point3D[1] << ", " << point3D[2]
<< ") = " << point[0] << ", " << point[1] << ", " << point[2] << endl;
// Test FindAndGetCell
double pcoords[3], weights[8];
int subId;
vtkCell* dummyCell = nullptr;
point3D[0] = 10.5;
point3D[1] = 12.1;
point3D[2] = 0;
pcoords[0] = pcoords[1] = pcoords[2] = 0.0;
dummyCell = nullptr;
vtkCell* found = sg2Dxy->FindAndGetCell(point3D, dummyCell, 0, 0, subId, pcoords, weights);
if (found == nullptr)
{
strm << "FindAndGetCell(sg2Dxy) not found!" << endl;
return EXIT_FAILURE;
}
strm << "FindAndGetCell(sg2Dxy): " << *found;
strm << "pcoords: " << pcoords[0] << ", " << pcoords[1] << endl;
strm << "weights: " << weights[0] << ", " << weights[1] << ", " << weights[2] << ", "
<< weights[3] << endl;
// Test GetCellType
strm << "GetCellType(sg2Dxy): " << sg2Dxy->GetCellType(0) << endl;
// Test GetActualMemorySize
strm << "GetActualMemorySize(sg2Dxy): " << sg2Dxy->GetActualMemorySize() << endl;
return EXIT_SUCCESS;
}
int TestOSG_2dxz(ostream& strm)
{
int i, j, k;
vtkNew<vtkStructuredGrid> sg2Dxz;
vtkNew<vtkPoints> xzpoints;
for (k = 0; k < 20; k++)
{
for (i = 0; i < 20; i++)
{
xzpoints->InsertNextPoint((double)i, 0.0, (double)k);
}
}
sg2Dxz->SetDimensions(20, 1, 20);
sg2Dxz->SetPoints(xzpoints);
if (sg2Dxz->GetCellSize(0) != 4)
{
std::cerr << "vtkStructuredGrid::GetCellSize(cellId) wrong for 2D structured grid.\n";
return 1;
}
vtkNew<vtkShortArray> shortScalars2D;
shortScalars2D->SetNumberOfComponents(2);
shortScalars2D->SetNumberOfTuples(20 * 20);
int l = 0;
for (j = 0; j < 20; j++)
{
for (i = 0; i < 20; i++)
{
shortScalars2D->InsertComponent(l, 0, i);
shortScalars2D->InsertComponent(l, 0, j);
l++;
}
}
sg2Dxz->GetPointData()->SetScalars(shortScalars2D);
// Test GetCell
vtkNew<vtkIdList> ids;
int cellId;
int ii;
i = 10;
j = 15;
cellId = j * 19 + i;
vtkCell* cell2D = sg2Dxz->GetCell(j * 19 + i);
strm << "cell2D: " << *cell2D;
sg2Dxz->GetCellPoints(cellId, ids);
strm << "Ids for cell " << cellId << " are ";
for (ii = 0; ii < ids->GetNumberOfIds(); ii++)
{
strm << ids->GetId(ii) << " ";
}
strm << endl << endl;
// Test GetCell(i,j,k)
i = 10;
j = 15;
cellId = j * 19 + i;
cell2D = sg2Dxz->GetCell(i, 0, j);
if (cell2D == nullptr)
{
std::cerr << "vtkStructuredGrid::GetCell returned nullptr instead of a valid cell.\n";
return EXIT_FAILURE;
}
if (cell2D->GetCellType() != VTK_QUAD)
{
std::cerr << "vtkStructuredGrid::GetCell returned the wrong cell type.\n"
<< "Expected: " << VTK_QUAD << " Returned: " << cell2D->GetCellType() << '\n';
return EXIT_FAILURE;
}
double bounds[6];
cell2D->GetBounds(bounds);
if (!vtkMathUtilities::FuzzyCompare(bounds[2], bounds[3]))
{
std::cerr << "sg2Dxz has finite width along y\n";
return EXIT_FAILURE;
}
strm << "cell2D: " << *cell2D;
sg2Dxz->GetCellPoints(cellId, ids);
strm << "Ids for cell " << cellId << " are ";
for (ii = 0; ii < ids->GetNumberOfIds(); ii++)
{
strm << ids->GetId(ii) << " ";
}
strm << endl << endl;
// Test Thread Safe GetCell
vtkNew<vtkGenericCell> gcell2D;
i = 10;
j = 15;
sg2Dxz->GetCell(j * 19 + i, gcell2D);
strm << "gcell2D: " << *gcell2D;
// Test GetCellBounds
sg2Dxz->GetCellBounds(j * 19 + i, bounds);
strm << "GetCellBounds(sg2Dxz): " << bounds[0] << ", " << bounds[1] << ", " << bounds[2] << ", "
<< bounds[3] << ", " << bounds[4] << ", " << bounds[5] << endl;
// Test GetPoint
double point[6];
sg2Dxz->GetPoint(j * 20 + i, point);
strm << "GetPoint(sg2Dxz): " << point[0] << ", " << point[1] << ", " << point[2] << endl;
// Test FindPoint
double point3D[3] = { 10, 12, 14 };
point3D[0] = 10;
point3D[1] = 0;
point3D[2] = 14;
sg2Dxz->GetPoint(sg2Dxz->FindPoint(point3D), point);
strm << "FindPoint(" << point3D[0] << ", " << point3D[1] << ", " << point3D[2]
<< ") = " << point[0] << ", " << point[1] << ", " << point[2] << endl;
// Test FindAndGetCell
double pcoords[3], weights[8];
int subId;
vtkCell* dummyCell = nullptr;
point3D[0] = 10.5;
point3D[1] = 0.0;
point3D[2] = 14.7;
pcoords[0] = pcoords[1] = pcoords[2] = 0.0;
weights[0] = weights[1] = weights[2] = weights[3] = 0.0;
dummyCell = nullptr;
vtkCell* found = sg2Dxz->FindAndGetCell(point3D, dummyCell, 0, 0, subId, pcoords, weights);
if (found == nullptr)
{
strm << "FindAndGetCell(sg2Dxz) not found!" << endl;
return EXIT_FAILURE;
}
strm << "FindAndGetCell(sg2Dxz): " << *found;
strm << "pcoords: " << pcoords[0] << ", " << pcoords[1] << endl;
strm << "weights: " << weights[0] << ", " << weights[1] << ", " << weights[2] << ", "
<< weights[3] << endl;
// Test GetCellType
strm << "GetCellType(sg2Dxz): " << sg2Dxz->GetCellType(0) << endl;
// Test GetActualMemorySize
strm << "GetActualMemorySize(sg2Dxz): " << sg2Dxz->GetActualMemorySize() << endl;
return EXIT_SUCCESS;
}
int TestOSG_2dyz(ostream& strm)
{
int i, j, k;
vtkNew<vtkStructuredGrid> sg2Dyz;
vtkNew<vtkPoints> yzpoints;
for (k = 0; k < 20; k++)
{
for (j = 0; j < 20; j++)
{
yzpoints->InsertNextPoint(0.0, (double)j, (double)k);
}
}
sg2Dyz->SetDimensions(1, 20, 20);
sg2Dyz->SetPoints(yzpoints);
if (sg2Dyz->GetCellSize(0) != 4)
{
std::cerr << "vtkStructuredGrid::GetCellSize(cellId) wrong for 2D structured grid.\n";
return 1;
}
vtkNew<vtkShortArray> shortScalars2D;
shortScalars2D->SetNumberOfComponents(2);
shortScalars2D->SetNumberOfTuples(20 * 20);
int l = 0;
for (j = 0; j < 20; j++)
{
for (i = 0; i < 20; i++)
{
shortScalars2D->InsertComponent(l, 0, i);
shortScalars2D->InsertComponent(l, 0, j);
l++;
}
}
sg2Dyz->GetPointData()->SetScalars(shortScalars2D);
// Test GetCell
vtkNew<vtkIdList> ids;
int cellId;
int ii;
i = 10;
j = 15;
cellId = j * 19 + i;
vtkCell* cell2D = sg2Dyz->GetCell(j * 19 + i);
strm << "cell2D: " << *cell2D;
sg2Dyz->GetCellPoints(cellId, ids);
strm << "Ids for cell " << cellId << " are ";
for (ii = 0; ii < ids->GetNumberOfIds(); ii++)
{
strm << ids->GetId(ii) << " ";
}
strm << endl << endl;
// Test GetCell(i,j,k)
i = 10;
j = 15;
cellId = j * 19 + i;
cell2D = sg2Dyz->GetCell(0, i, j);
if (cell2D == nullptr)
{
std::cerr << "vtkStructuredGrid::GetCell returned nullptr instead of a valid cell.\n";
return EXIT_FAILURE;
}
if (cell2D->GetCellType() != VTK_QUAD)
{
std::cerr << "vtkStructuredGrid::GetCell returned the wrong cell type.\n"
<< "Expected: " << VTK_QUAD << " Returned: " << cell2D->GetCellType() << '\n';
return EXIT_FAILURE;
}
double bounds[6];
cell2D->GetBounds(bounds);
if (!vtkMathUtilities::FuzzyCompare(bounds[0], bounds[1]))
{
std::cerr << "sg2Dyz has finite width along x\n";
return EXIT_FAILURE;
}
strm << "cell2D: " << *cell2D;
sg2Dyz->GetCellPoints(cellId, ids);
strm << "Ids for cell " << cellId << " are ";
for (ii = 0; ii < ids->GetNumberOfIds(); ii++)
{
strm << ids->GetId(ii) << " ";
}
strm << endl << endl;
// Test Thread Safe GetCell
vtkNew<vtkGenericCell> gcell2D;
i = 10;
j = 15;
sg2Dyz->GetCell(j * 19 + i, gcell2D);
strm << "gcell2D: " << *gcell2D;
// Test GetCellBounds
sg2Dyz->GetCellBounds(j * 19 + i, bounds);
strm << "GetCellBounds(sg2Dyz): " << bounds[0] << ", " << bounds[1] << ", " << bounds[2] << ", "
<< bounds[3] << ", " << bounds[4] << ", " << bounds[5] << endl;
// Test GetPoint
double point[6];
sg2Dyz->GetPoint(j * 20 + i, point);
strm << "GetPoint(sg2Dyz): " << point[0] << ", " << point[1] << ", " << point[2] << endl;
// Test FindPoint
double point3D[3] = { 10, 12, 14 };
point3D[0] = 0;
point3D[1] = 12;
point3D[2] = 14;
sg2Dyz->GetPoint(sg2Dyz->FindPoint(point3D), point);
strm << "FindPoint(" << point3D[0] << ", " << point3D[1] << ", " << point3D[2]
<< ") = " << point[0] << ", " << point[1] << ", " << point[2] << endl;
// Test FindAndGetCell
double pcoords[3], weights[8];
int subId;
vtkCell* dummyCell = nullptr;
point3D[0] = 0.0;
point3D[1] = 12.1;
point3D[2] = 14.7;
pcoords[0] = pcoords[1] = pcoords[2] = 0.0;
weights[0] = weights[1] = weights[2] = weights[3] = 0.0;
dummyCell = nullptr;
vtkCell* found = sg2Dyz->FindAndGetCell(point3D, dummyCell, 0, 0, subId, pcoords, weights);
if (found == nullptr)
{
strm << "FindAndGetCell(sg2Dyz) not found!" << endl;
return EXIT_FAILURE;
}
strm << "FindAndGetCell(sg2Dyz): " << *found;
strm << "pcoords: " << pcoords[0] << ", " << pcoords[1] << endl;
strm << "weights: " << weights[0] << ", " << weights[1] << ", " << weights[2] << ", "
<< weights[3] << endl;
// Test GetCellType
strm << "GetCellType(sg2Dyz): " << sg2Dyz->GetCellType(0) << endl;
// Test GetActualMemorySize
strm << "GetActualMemorySize(sg2Dyz): " << sg2Dyz->GetActualMemorySize() << endl;
return EXIT_SUCCESS;
}
int TestOSG_3d(ostream& strm)
{
int i, j, k;
vtkNew<vtkStructuredGrid> sg3D;
vtkNew<vtkPoints> xyzpoints;
for (k = 0; k < 20; k++)
{
for (j = 0; j < 20; j++)
{
for (i = 0; i < 20; i++)
{
xyzpoints->InsertNextPoint((double)i, (double)j, (double)k);
}
}
}
sg3D->SetDimensions(20, 20, 20);
sg3D->SetPoints(xyzpoints);
if (sg3D->GetCellSize(0) != 8)
{
std::cerr << "vtkStructuredGrid::GetCellSize(cellId) wrong for 3D structured grid.\n";
return 1;
}
vtkNew<vtkShortArray> shortScalars3D;
shortScalars3D->SetNumberOfComponents(3);
shortScalars3D->SetNumberOfTuples(20 * 20 * 20);
int l = 0;
for (k = 0; k < 20; k++)
{
for (j = 0; j < 20; j++)
{
for (i = 0; i < 20; i++)
{
shortScalars3D->InsertComponent(l, 0, i);
shortScalars3D->InsertComponent(l, 0, j);
shortScalars3D->InsertComponent(l, 0, k);
l++;
}
}
}
sg3D->GetPointData()->SetScalars(shortScalars3D);
strm << "sg3D:" << *sg3D;
// Test shallow copy
vtkNew<vtkStructuredGrid> scsg3D;
scsg3D->ShallowCopy(sg3D);
strm << "ShallowCopy(sg3D):" << *scsg3D;
// Test deep copy
vtkNew<vtkStructuredGrid> dcsg3D;
dcsg3D->DeepCopy(sg3D);
strm << "DeepCopy(sg3D):" << *dcsg3D;
// Test GetCell
vtkNew<vtkIdList> ids;
int cellId;
int ii;
i = 10;
j = 15;
k = 7;
cellId = k * (19 * 19) + j * 19 + i;
vtkCell* cell3D = sg3D->GetCell(cellId);
strm << "cell3D: " << *cell3D;
sg3D->GetCellPoints(cellId, ids);
strm << "Ids for cell " << cellId << " are ";
for (ii = 0; ii < ids->GetNumberOfIds(); ii++)
{
strm << ids->GetId(ii) << " ";
}
strm << endl << endl;
// Test GetCell(i,j,k)
i = 10;
j = 15;
k = 7;
cellId = k * (19 * 19) + j * 19 + i;
cell3D = sg3D->GetCell(i, j, k);
if (cell3D == nullptr)
{
std::cerr << "vtkStructuredGrid::GetCell returned nullptr instead of a valid cell.\n";
return EXIT_FAILURE;
}
if (cell3D->GetCellType() != VTK_HEXAHEDRON)
{
std::cerr << "vtkStructuredGrid::GetCell returned the wrong cell type.\n"
<< "Expected: " << VTK_HEXAHEDRON << " Returned: " << cell3D->GetCellType() << '\n';
return EXIT_FAILURE;
}
strm << "cell3D: " << *cell3D;
sg3D->GetCellPoints(cellId, ids);
strm << "Ids for cell " << cellId << " are ";
for (ii = 0; ii < ids->GetNumberOfIds(); ii++)
{
strm << ids->GetId(ii) << " ";
}
strm << endl << endl;
// Test Thread Safe GetCell
vtkNew<vtkGenericCell> gcell3D;
i = 10;
j = 15;
k = 7;
sg3D->GetCell(k * (19 * 19) + j * 19 + i, gcell3D);
strm << "gcell3D: " << *gcell3D;
// Test GetCellBounds
double bounds[6];
sg3D->GetCellBounds(k * (19 * 19) + j * 19 + i, bounds);
strm << "GetCellBounds(sg3D): " << bounds[0] << ", " << bounds[1] << ", " << bounds[2] << ", "
<< bounds[3] << ", " << bounds[4] << ", " << bounds[5] << endl;
// Test GetPoint
double point[6];
sg3D->GetPoint(k * (20 * 20) + j * 20 + i, point);
strm << "GetPoint(sg3D): " << point[0] << ", " << point[1] << ", " << point[2] << endl;
// Test FindPoint
double point3D[3] = { 10, 12, 14 };
sg3D->GetPoint(sg3D->FindPoint(point3D), point);
strm << "FindPoint(" << point3D[0] << ", " << point3D[1] << ", " << point3D[2]
<< ") = " << point[0] << ", " << point[1] << ", " << point[2] << endl;
// Test FindAndGetCell
double pcoords[3], weights[8];
int subId;
vtkCell* dummyCell = nullptr;
point3D[0] = 10.5;
point3D[1] = 12.1;
point3D[2] = 14.7;
strm << "FindAndGetCell(sg3D): "
<< *sg3D->FindAndGetCell(point3D, dummyCell, 0, 0, subId, pcoords, weights);
strm << "pcoords: " << pcoords[0] << ", " << pcoords[1] << ", " << pcoords[2] << endl;
strm << "weights: " << weights[0] << ", " << weights[1] << ", " << weights[2] << ", "
<< weights[3] << ", " << weights[4] << ", " << weights[5] << ", " << weights[6] << ", "
<< weights[7] << endl;
// Test GetCellType
strm << "GetCellType(sg3D): " << sg3D->GetCellType(0) << endl;
// Test GetActualMemorySize
strm << "GetActualMemorySize(sg3D): " << sg3D->GetActualMemorySize() << endl;
return EXIT_SUCCESS;
}
int TestOSG(ostream& strm)
{
int ret = EXIT_SUCCESS;
strm << "Testing vtkStructuredGrid" << endl;
ret = TestOSG_0d(strm);
if (ret != EXIT_SUCCESS)
{
return ret;
}
ret = TestOSG_1dx(strm);
if (ret != EXIT_SUCCESS)
{
return ret;
}
ret = TestOSG_1dy(strm);
if (ret != EXIT_SUCCESS)
{
return ret;
}
ret = TestOSG_1dz(strm);
if (ret != EXIT_SUCCESS)
{
return ret;
}
ret = TestOSG_2dxy(strm);
if (ret != EXIT_SUCCESS)
{
return ret;
}
ret = TestOSG_2dxz(strm);
if (ret != EXIT_SUCCESS)
{
return ret;
}
ret = TestOSG_2dyz(strm);
if (ret != EXIT_SUCCESS)
{
return ret;
}
ret = TestOSG_3d(strm);
if (ret != EXIT_SUCCESS)
{
return ret;
}
strm << "Testing completed" << endl;
return ret;
}
int otherStructuredGrid(int, char*[])
{
std::ostringstream vtkmsg_with_warning_C4701;
return TestOSG(vtkmsg_with_warning_C4701);
}
| 25.08835 | 98 | 0.577568 | [
"3d"
] |
120ebca448a3670354939e245b9139bc50d0d2d3 | 1,657 | cpp | C++ | src/Utils/Python/ConstantsPython.cpp | DockBio/utilities | 213ed5ac2a64886b16d0fee1fcecb34d36eea9e9 | [
"BSD-3-Clause"
] | null | null | null | src/Utils/Python/ConstantsPython.cpp | DockBio/utilities | 213ed5ac2a64886b16d0fee1fcecb34d36eea9e9 | [
"BSD-3-Clause"
] | null | null | null | src/Utils/Python/ConstantsPython.cpp | DockBio/utilities | 213ed5ac2a64886b16d0fee1fcecb34d36eea9e9 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file
* @copyright This code is licensed under the 3-clause BSD license.\n
* Copyright ETH Zurich, Laboratory for Physical Chemistry, Reiher Group.\n
* See LICENSE.txt for details.
*/
#include <Utils/Geometry/ElementData.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
using namespace Scine::Utils;
void init_constants(pybind11::module& m) {
m.attr("ELEMENTARY_CHARGE") = Constants::elementaryCharge;
m.attr("AVOGADRO_NUMBER") = Constants::avogadroNumber;
m.attr("PI") = Constants::pi;
m.attr("RAD_PER_DEGREE") = Constants::rad_per_degree;
m.attr("DEGREE_PER_RAD") = Constants::degree_per_rad;
m.attr("METER_PER_BOHR") = Constants::meter_per_bohr;
m.attr("BOHR_PER_METER") = Constants::bohr_per_meter;
m.attr("ANGSTROM_PER_METER") = Constants::angstrom_per_meter;
m.attr("METER_PER_ANGSTROM") = Constants::meter_per_angstrom;
m.attr("ANGSTROM_PER_BOHR") = Constants::angstrom_per_bohr;
m.attr("BOHR_PER_ANGSTROM") = Constants::bohr_per_angstrom;
m.attr("HARTREE_PER_EV") = Constants::hartree_per_ev;
m.attr("EV_PER_HARTREE") = Constants::ev_per_hartree;
m.attr("JOULE_PER_HARTREE") = Constants::joule_per_hartree;
m.attr("HARTREE_PER_JOULE") = Constants::hartree_per_joule;
m.attr("JOULE_PER_CALORIE") = Constants::joule_per_calorie;
m.attr("CALORIE_PER_JOULE") = Constants::calorie_per_joule;
m.attr("KJPERMOL_PER_HARTREE") = Constants::kJPerMol_per_hartree;
m.attr("HARTREE_PER_KJPERMOL") = Constants::hartree_per_kJPerMol;
m.attr("KCALPERMOL_PER_HARTREE") = Constants::kCalPerMol_per_hartree;
m.attr("HARTREE_PER_KCALPERMOL") = Constants::hartree_per_kCalPerMol;
}
| 46.027778 | 86 | 0.750754 | [
"geometry"
] |
1219a1f327fe84268c4bc5db26996ef8e8508bc5 | 10,212 | cpp | C++ | gempyrelib/src/graphics.cpp | mmertama/Gempyre | 7fa25471f565a95d9959c1345ce86cc6aaa1d5d5 | [
"MIT"
] | 3 | 2021-01-07T07:52:44.000Z | 2021-08-06T06:13:17.000Z | gempyrelib/src/graphics.cpp | mmertama/Gempyre | 7fa25471f565a95d9959c1345ce86cc6aaa1d5d5 | [
"MIT"
] | null | null | null | gempyrelib/src/graphics.cpp | mmertama/Gempyre | 7fa25471f565a95d9959c1345ce86cc6aaa1d5d5 | [
"MIT"
] | 1 | 2020-03-24T14:12:39.000Z | 2020-03-24T14:12:39.000Z | #include "gempyre_graphics.h"
#include "gempyre_utils.h"
#include <any>
using namespace Gempyre;
CanvasData::~CanvasData() {
}
CanvasDataPtr CanvasElement::makeCanvas(int width, int height) { //could be const, but is it sustainable?
gempyre_graphics_assert(width > 0 && height > 0, "Graphics size is expected be more than zero");
m_tile = std::shared_ptr<CanvasData>(new CanvasData(/*std::min(width,*/ TileWidth/*)*/, /*td::min(height,*/ TileHeight/*)*/, m_id));
return std::shared_ptr<CanvasData>(new CanvasData(width, height, m_id)); //private cannot use make_...
}
CanvasElement::~CanvasElement() {
m_tile.reset();
}
void CanvasElement::paint(const CanvasDataPtr& canvas) {
if(!canvas) {
GempyreUtils::log(GempyreUtils::LogLevel::Error, "Won't paint as canvas is NULL");
return;
}
if(!m_tile) {
GempyreUtils::log(GempyreUtils::LogLevel::Error, "Won't paint as buffer is NULL");
return;
}
if(canvas->height <= 0 || canvas->width <= 0 ) {
GempyreUtils::log(GempyreUtils::LogLevel::Debug, "Won't paint as canvas size is 0");
return;
}
GempyreUtils::log(GempyreUtils::LogLevel::Debug, "Sending canvas data");
for(auto j = 0 ; j < canvas->height ; j += TileHeight) {
const auto height = std::min(TileHeight, canvas->height - j);
for(auto i = 0 ; i < canvas->width ; i += TileWidth) {
const auto width = std::min(TileWidth, canvas->width - i);
const auto srcPos = canvas->data() + i + (j * canvas->width);
GempyreUtils::log(GempyreUtils::LogLevel::Debug_Trace, "Copy canvas frame", i, j, width, height);
for(int h = 0; h < height; h++) {
const auto lineStart = srcPos + (h * canvas->width);
auto trgPos = m_tile->data() + width * h;
std::copy(lineStart, lineStart + width, trgPos);
}
GempyreUtils::log(GempyreUtils::LogLevel::Debug_Trace, "Sending canvas frame", i, j, width, height);
m_tile->writeHeader({static_cast<CanvasData::Data::dataT>(i),
static_cast<CanvasData::Data::dataT>(j),
static_cast<CanvasData::Data::dataT>(width),
static_cast<CanvasData::Data::dataT>(height)});
send(m_tile);
}
}
GempyreUtils::log(GempyreUtils::LogLevel::Debug, "Sent canvas data");
}
std::string CanvasElement::addImage(const std::string& url, const std::function<void (const std::string& id)> &loaded) {
const auto name = generateId("image");
Gempyre::Element imageElement(*m_ui, name, "IMG", /*m_ui->root()*/*this);
if(loaded)
imageElement.subscribe("load", [loaded, name](const Gempyre::Event&) {
loaded(name);
});
imageElement.setAttribute("style", "display:none");
imageElement.setAttribute("src", url);
return name;
}
std::vector<std::string> CanvasElement::addImages(const std::vector<std::string>& urls, const std::function<void (const std::vector<std::string>)>& loaded) {
std::vector<std::string> names;
auto result = std::make_shared<std::map<std::string, bool>>();
std::for_each(urls.begin(), urls.end(), [this, &names, loaded, &result](const auto& url){
const auto name = addImage(url, [loaded, result](const std::string& id) {
(*result)[id] = true;
if(loaded && std::find_if(result->begin(), result->end(), [](const auto& r){return !r.second;}) == result->end()) {
std::vector<std::string> keys;
std::transform(result->begin(), result->end(), std::back_inserter(keys), [](const auto& it){return it.first;});
loaded(keys);
}
});
result->emplace(name, false);
names.push_back(name);
});
return names;
}
void CanvasElement::paintImage(const std::string& imageId, int x, int y, const Rect& clippingRect) const {
auto This = const_cast<CanvasElement*>(this);
if(clippingRect.width <= 0 || clippingRect.height <= 0)
This->send("paint_image", std::unordered_map<std::string, std::any>{{"image", imageId},
{"pos", std::vector<int>{x, y}}});
else
This->send("paint_image", std::unordered_map<std::string, std::any>{{"image", imageId},
{"pos", std::vector<int>{x, y}},
{"clip", std::vector<int>{clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height}}});
}
void CanvasElement::paintImage(const std::string& imageId, const Rect& targetRect, const Element::Rect& clippingRect) const {
if(targetRect.width <= 0 || targetRect.height <= 0)
return;
auto This = const_cast<CanvasElement*>(this);
if(clippingRect.width <= 0 || clippingRect.height <= 0)
This->send("paint_image", std::unordered_map<std::string, std::any>{{"image", imageId},
{"rect", std::vector<int>{targetRect.x, targetRect.y, targetRect.width, targetRect.height}}});
else
This->send("paint_image", std::unordered_map<std::string, std::any>{{"image", imageId},
{"rect", std::vector<int>{targetRect.x, targetRect.y, targetRect.width, targetRect.height}},
{"clip", std::vector<int>{clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height}}});
}
void CanvasElement::draw(const CanvasElement::CommandList &canvasCommands) const {
if(canvasCommands.empty())
return;
std::vector<std::string> commandString;
/*std::transform(canvasCommands.begin(), canvasCommands.end(), std::back_inserter(commandString), [](auto&& arg) -> std::string {
if(const auto doubleval = std::get_if<double>(&arg))
return std::to_string(*doubleval);
if(const auto intval = std::get_if<int>(&arg))
return std::to_string(*intval);
return std::get<std::string>(arg);
});*/
const auto str = [](auto&& arg) -> std::string {
if(const auto doubleval = std::get_if<double>(&arg))
return std::to_string(*doubleval);
if(const auto intval = std::get_if<int>(&arg))
return std::to_string(*intval);
return std::string(std::get<std::string>(arg));
};
for(auto&& cmd : canvasCommands) {
auto s = str(cmd);
commandString.emplace_back(s);
}
auto This = const_cast<CanvasElement*>(this);
This->send("canvas_draw", std::unordered_map<std::string, std::any>{
{"commands", commandString}}, true);
}
void CanvasElement::draw(const FrameComposer& frameComposer) const {
draw(frameComposer.composed());
}
void CanvasElement::drawCompleted(const DrawCallback& drawCompletedCallback) {
subscribe("event_notify", [this](const Event& ev) {
if(m_drawCallback && ev.properties.at("name") == "canvas_draw") {
m_drawCallback();
}
});
m_drawCallback = drawCompletedCallback;
send("event_notify", std::unordered_map<std::string, std::any>{
{"name", "canvas_draw"},
{"add", drawCompletedCallback != nullptr}
});
}
void CanvasElement::erase(bool resized) const {
if(resized || m_width <= 0 || m_height <= 0) {
const auto rv = rect();
if(rv) {
m_width = rv->width;
m_height = rv->height;
} else {
return;
}
}
draw({"clearRect", 0, 0, m_width, m_height});
}
Graphics::Graphics(const Gempyre::CanvasElement& element, int width, int height) : m_element(element), m_canvas(m_element.makeCanvas(width, height)) {
GempyreUtils::log(GempyreUtils::LogLevel::Debug, "Graphics consructed", width, height);
}
/**
* @function Graphics
* @param element
*
* Creates a Graphics without a Canvas, call `create` to construct an actual Canvas.
*/
Graphics::Graphics(const Gempyre::CanvasElement& element) : m_element(element) {
GempyreUtils::log(GempyreUtils::LogLevel::Info, "Graphics without canvas created, create() must be called");
}
void Graphics::drawRect(const Element::Rect& rect, Color::type color) {
if(rect.width <= 0 || rect.width <= 0)
return;
const auto x = std::max(0, rect.x);
const auto y = std::max(0, rect.y);
const auto width = (x + rect.width >= m_canvas->width) ? m_canvas->width - rect.x : rect.width;
const auto height = (y + rect.height >= m_canvas->height) ? m_canvas->height - rect.y : rect.height;
auto pos = m_canvas->data() + (x + y * m_canvas->width);
for(int j = 0; j < height; j++) {
std::fill(pos, pos + width, color);
pos += m_canvas->width;
}
}
void Graphics::merge(const Graphics& other) {
if(other.m_canvas == m_canvas)
return;
gempyre_graphics_assert(other.m_canvas->size() == m_canvas->size(), "Canvas sizes must match")
auto pos = m_canvas->data();
const auto posOther = other.m_canvas->data();
for(auto i = 0U; i < m_canvas->size(); i++) {
const auto p = pos[i];
const auto po = posOther[i];
const auto ao = Color::alpha(po);
const auto a = Color::alpha(p);
const auto r = Color::r(p) * (0xFF - ao);
const auto g = Color::g(p) * (0xFF - ao);
const auto b = Color::b(p) * (0xFF - ao);
const auto ro = (Color::r(po) * ao);
const auto go = (Color::g(po) * ao);
const auto bo = (Color::b(po) * ao);
const auto pix = Color::rgbaClamped((r + ro) / 0xFF , (g + go) / 0xFF, (b + bo) / 0xFF, a);
pos[i] = pix;
}
}
Graphics Graphics::clone() const {
Graphics other(m_element);
other.create(m_canvas->width, m_canvas->height);
std::copy(m_canvas->begin(), m_canvas->end(), other.m_canvas->data());
return other;
}
void Graphics::update() {
if(m_canvas)
m_element.paint(m_canvas);
}
| 42.907563 | 175 | 0.585096 | [
"vector",
"transform"
] |
1219e1eac99fd59b372b44991d7b73fcbbc2b8d1 | 1,676 | cpp | C++ | libot/core/memberreference.cpp | goossens/ObjectTalk | ca1d4f558b5ad2459b376102744d52c6283ec108 | [
"MIT"
] | 6 | 2021-11-12T15:03:53.000Z | 2022-01-28T18:30:33.000Z | libot/core/memberreference.cpp | goossens/ObjectTalk | ca1d4f558b5ad2459b376102744d52c6283ec108 | [
"MIT"
] | null | null | null | libot/core/memberreference.cpp | goossens/ObjectTalk | ca1d4f558b5ad2459b376102744d52c6283ec108 | [
"MIT"
] | null | null | null | // ObjectTalk Scripting Language
// Copyright (c) 1993-2022 Johan A. Goossens. All rights reserved.
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
//
// Include files
//
#include "ot/function.h"
#include "ot/boundfunction.h"
#include "ot/memberreference.h"
//
// OtMemberReferenceClass::deref
//
OtObject OtMemberReferenceClass::deref() {
OtObject result = object->get(member);
// never create bound functions for Model or Class members
if (object->isKindOf("Module")) { // || object->isKindOf("Class")) {
return result;
// create bound function if required
} else if (result && (result->isKindOf("Function") || result->isKindOf("ByteCodeFunction"))) {
return OtBoundFunctionClass::create(object, result);
// it's just a member variable
} else {
return result;
}
}
//
// OtMemberReferenceClass::assign
//
OtObject OtMemberReferenceClass::assign(OtObject value) {
return object->set(member, value);
}
//
// OtMemberReferenceClass::getMeta
//
OtType OtMemberReferenceClass::getMeta() {
static OtType type = nullptr;
if (!type) {
type = OtTypeClass::create<OtMemberReferenceClass>("MemberReference", OtReferenceClass::getMeta());
type->set("__deref__", OtFunctionClass::create(&OtMemberReferenceClass::deref));
type->set("__assign__", OtFunctionClass::create(&OtMemberReferenceClass::assign));
}
return type;
}
//
// OtMemberReferenceClass::create
//
OtMemberReference OtMemberReferenceClass::create(OtObject o, const std::string& m) {
OtMemberReference member = std::make_shared<OtMemberReferenceClass>(o, m);
member->setType(getMeta());
return member;
}
| 22.648649 | 101 | 0.723747 | [
"object",
"model"
] |
121e11aa967e36b827887d6699a271cbf22b6f27 | 12,287 | cpp | C++ | olp-cpp-sdk-dataservice-write/src/IndexLayerClientImpl.cpp | heremaps/here-olp-edge-sdk-cpp | b8afbd496390e3ef4eba2e6ff2b78a63352a48e9 | [
"Apache-2.0"
] | 21 | 2019-07-03T07:26:52.000Z | 2019-09-04T08:35:07.000Z | olp-cpp-sdk-dataservice-write/src/IndexLayerClientImpl.cpp | heremaps/here-olp-sdk-cpp | b8afbd496390e3ef4eba2e6ff2b78a63352a48e9 | [
"Apache-2.0"
] | 639 | 2019-09-13T17:14:24.000Z | 2020-05-13T11:49:14.000Z | olp-cpp-sdk-dataservice-write/src/IndexLayerClientImpl.cpp | heremaps/here-olp-edge-sdk-cpp | b8afbd496390e3ef4eba2e6ff2b78a63352a48e9 | [
"Apache-2.0"
] | 10 | 2019-07-03T07:52:18.000Z | 2019-08-22T01:13:09.000Z | /*
* Copyright (C) 2019-2021 HERE Europe B.V.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
#include "IndexLayerClientImpl.h"
#include <boost/format.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <olp/core/client/CancellationContext.h>
#include "ApiClientLookup.h"
#include "Common.h"
#include "generated/BlobApi.h"
#include "generated/ConfigApi.h"
#include "generated/IndexApi.h"
#include <atomic>
namespace {
std::string GenerateUuid() {
static boost::uuids::random_generator gen;
return boost::uuids::to_string(gen());
}
} // namespace
namespace olp {
namespace dataservice {
namespace write {
IndexLayerClientImpl::IndexLayerClientImpl(client::HRN catalog,
client::OlpClientSettings settings)
: catalog_(std::move(catalog)),
catalog_settings_(catalog_, settings),
settings_(std::move(settings)),
apiclient_config_(nullptr),
apiclient_blob_(nullptr),
apiclient_index_(nullptr),
pending_requests_(std::make_shared<client::PendingRequests>()),
init_in_progress_(false) {}
IndexLayerClientImpl::~IndexLayerClientImpl() {
tokenList_.CancelAll();
pending_requests_->CancelAllAndWait();
}
olp::client::CancellationToken IndexLayerClientImpl::InitApiClients(
std::shared_ptr<client::CancellationContext> cancel_context,
InitApiClientsCallback callback) {
auto self = shared_from_this();
std::unique_lock<std::mutex> ul{mutex_, std::try_to_lock};
if (init_in_progress_) {
ul.unlock();
cond_var_.wait(ul, [self]() { return !self->init_in_progress_; });
ul.lock();
}
if (apiclient_index_ && !apiclient_index_->GetBaseUrl().empty()) {
callback(boost::none);
return {};
}
init_in_progress_ = true;
auto cancel_function = [callback]() {
callback(client::ApiError(client::ErrorCode::Cancelled,
"Operation cancelled.", true));
};
apiclient_blob_ = client::OlpClientFactory::Create(settings_);
apiclient_config_ = client::OlpClientFactory::Create(settings_);
apiclient_index_ = client::OlpClientFactory::Create(settings_);
auto indexApi_callback = [=](ApiClientLookup::ApisResponse apis) {
std::lock_guard<std::mutex> lg{self->mutex_};
self->init_in_progress_ = false;
if (!apis.IsSuccessful()) {
callback(std::move(apis.GetError()));
self->cond_var_.notify_one();
} else {
self->apiclient_index_->SetBaseUrl(apis.GetResult().at(0).GetBaseUrl());
callback(boost::none);
self->cond_var_.notify_all();
}
};
auto indexApi_function = [=]() -> olp::client::CancellationToken {
return ApiClientLookup::LookupApi(self->apiclient_index_, "index", "v1",
self->catalog_, indexApi_callback);
};
auto blobApi_callback = [=](ApiClientLookup::ApisResponse apis) {
if (!apis.IsSuccessful()) {
callback(std::move(apis.GetError()));
std::lock_guard<std::mutex> lg{self->mutex_};
self->init_in_progress_ = false;
self->cond_var_.notify_one();
return;
}
self->apiclient_blob_->SetBaseUrl(apis.GetResult().at(0).GetBaseUrl());
cancel_context->ExecuteOrCancelled(indexApi_function, cancel_function);
};
ul.unlock();
return ApiClientLookup::LookupApi(self->apiclient_blob_, "blob", "v1",
self->catalog_, blobApi_callback);
}
void IndexLayerClientImpl::CancelPendingRequests() {
pending_requests_->CancelAll();
tokenList_.CancelAll();
}
client::CancellableFuture<PublishIndexResponse>
IndexLayerClientImpl::PublishIndex(const model::PublishIndexRequest& request) {
auto promise = std::make_shared<std::promise<PublishIndexResponse> >();
auto cancel_token =
PublishIndex(request, [promise](PublishIndexResponse response) {
promise->set_value(std::move(response));
});
return client::CancellableFuture<PublishIndexResponse>(cancel_token, promise);
}
client::CancellationToken IndexLayerClientImpl::PublishIndex(
model::PublishIndexRequest request, const PublishIndexCallback& callback) {
auto publish_task =
[=](client::CancellationContext context) -> PublishIndexResponse {
if (!request.GetData()) {
return client::ApiError(client::ErrorCode::InvalidArgument,
"Request data empty.");
}
if (request.GetLayerId().empty()) {
return client::ApiError(client::ErrorCode::InvalidArgument,
"Request layer Id empty.");
}
const auto data_handle = GenerateUuid();
auto blob_api_response = ApiClientLookup::LookupApiClient(
catalog_, context, "blob", "v1", settings_);
if (!blob_api_response.IsSuccessful()) {
return blob_api_response.GetError();
}
auto index_api_response = ApiClientLookup::LookupApiClient(
catalog_, context, "index", "v1", settings_);
if (!index_api_response.IsSuccessful()) {
return index_api_response.GetError();
}
auto layer_settings_response = catalog_settings_.GetLayerSettings(
context, request.GetBillingTag(), request.GetLayerId());
if (!layer_settings_response.IsSuccessful()) {
return layer_settings_response.GetError();
}
auto layer_settings = layer_settings_response.GetResult();
if (layer_settings.content_type.empty()) {
auto errmsg = boost::format(
"Unable to find the Layer ID (%1%) "
"provided in the PublishIndexRequest in the "
"Catalog specified when creating "
"this IndexLayerClient instance.") %
request.GetLayerId();
return client::ApiError(client::ErrorCode::InvalidArgument, errmsg.str());
}
auto blob_response = BlobApi::PutBlob(
blob_api_response.GetResult(), request.GetLayerId(),
layer_settings.content_type, layer_settings.content_encoding,
data_handle, request.GetData(), request.GetBillingTag(), context);
if (!blob_response.IsSuccessful()) {
return blob_response.GetError();
}
auto index = request.GetIndex();
index.SetId(data_handle);
auto insert_indexes_response = IndexApi::InsertIndexes(
index_api_response.GetResult(), index, request.GetLayerId(),
request.GetBillingTag(), context);
if (!insert_indexes_response.IsSuccessful()) {
return insert_indexes_response.GetError();
}
model::ResponseOkSingle res;
res.SetTraceID(data_handle);
return PublishIndexResponse(std::move(res));
};
return AddTask(settings_.task_scheduler, pending_requests_,
std::move(publish_task), std::move(callback));
}
client::CancellableFuture<DeleteIndexDataResponse>
IndexLayerClientImpl::DeleteIndexData(
const model::DeleteIndexDataRequest& request) {
auto promise = std::make_shared<std::promise<DeleteIndexDataResponse> >();
auto cancel_token =
DeleteIndexData(request, [promise](DeleteIndexDataResponse response) {
promise->set_value(std::move(response));
});
return client::CancellableFuture<DeleteIndexDataResponse>(cancel_token,
promise);
}
client::CancellationToken IndexLayerClientImpl::DeleteIndexData(
const model::DeleteIndexDataRequest& request,
const DeleteIndexDataCallback& callback) {
if (request.GetLayerId().empty() || request.GetIndexId().empty()) {
callback(DeleteIndexDataResponse(
client::ApiError(client::ErrorCode::InvalidArgument,
"Request layer ID or Index Id is not defined.")));
return client::CancellationToken();
}
auto layer_id = request.GetLayerId();
auto index_id = request.GetIndexId();
auto op_id = tokenList_.GetNextId();
auto cancel_context = std::make_shared<client::CancellationContext>();
auto self = shared_from_this();
auto cancel_function = [=]() {
self->tokenList_.RemoveTask(op_id);
callback(DeleteIndexDataResponse(client::ApiError(
client::ErrorCode::Cancelled, "Operation cancelled.", true)));
};
auto delete_index_data_function = [=]() -> client::CancellationToken {
return BlobApi::deleteBlob(
*self->apiclient_blob_, layer_id, index_id, boost::none,
[=](DeleteBlobRespone response) {
self->tokenList_.RemoveTask(op_id);
if (!response.IsSuccessful()) {
callback(DeleteBlobRespone(response.GetError()));
return;
}
callback(DeleteBlobRespone(client::ApiNoResult()));
});
};
auto init_api_client_callback =
[=](boost::optional<client::ApiError> init_api_error) {
if (init_api_error) {
self->tokenList_.RemoveTask(op_id);
callback(DeleteBlobRespone(init_api_error.get()));
return;
}
cancel_context->ExecuteOrCancelled(delete_index_data_function,
cancel_function);
};
auto init_api_client_function = [=]() -> client::CancellationToken {
return self->InitApiClients(cancel_context, init_api_client_callback);
};
cancel_context->ExecuteOrCancelled(init_api_client_function, cancel_function);
auto ret = client::CancellationToken(
[cancel_context]() { cancel_context->CancelOperation(); });
tokenList_.AddTask(op_id, ret);
return ret;
}
client::CancellableFuture<UpdateIndexResponse>
IndexLayerClientImpl::UpdateIndex(const model::UpdateIndexRequest& request) {
auto promise = std::make_shared<std::promise<UpdateIndexResponse> >();
auto cancel_token =
UpdateIndex(request, [promise](UpdateIndexResponse response) {
promise->set_value(std::move(response));
});
return client::CancellableFuture<UpdateIndexResponse>(cancel_token, promise);
}
client::CancellationToken IndexLayerClientImpl::UpdateIndex(
const model::UpdateIndexRequest& request,
const UpdateIndexCallback& callback) {
auto cancel_context = std::make_shared<client::CancellationContext>();
auto self = shared_from_this();
auto op_id = tokenList_.GetNextId();
auto cancel_function = [=]() {
self->tokenList_.RemoveTask(op_id);
callback(UpdateIndexResponse(client::ApiError(
client::ErrorCode::Cancelled, "Operation cancelled.", true)));
};
auto updateIndex_callback = [=](UpdateIndexResponse update_index_response) {
self->tokenList_.RemoveTask(op_id);
if (!update_index_response.IsSuccessful()) {
callback(UpdateIndexResponse(update_index_response.GetError()));
return;
}
callback(UpdateIndexResponse(client::ApiNoResult()));
};
auto UpdateIndex_function = [=]() -> client::CancellationToken {
return IndexApi::performUpdate(*self->apiclient_index_, request,
boost::none, updateIndex_callback);
};
cancel_context->ExecuteOrCancelled(
[=]() -> client::CancellationToken {
return self->InitApiClients(
cancel_context, [=](boost::optional<client::ApiError> api_error) {
if (api_error) {
self->tokenList_.RemoveTask(op_id);
callback(UpdateIndexResponse(api_error.get()));
return;
}
cancel_context->ExecuteOrCancelled(UpdateIndex_function,
cancel_function);
});
},
cancel_function);
auto token = client::CancellationToken(
[cancel_context]() { cancel_context->CancelOperation(); });
tokenList_.AddTask(op_id, token);
return token;
}
} // namespace write
} // namespace dataservice
} // namespace olp
| 35.409222 | 80 | 0.67722 | [
"model"
] |
1226d993e9a68b28500839f7f7065a0653d0ddd5 | 10,724 | cpp | C++ | src/luxcorescenedemo.cpp | SimonDanisch/LuxRay.jl | b949f6b5cec6280fba6be661b6beb21a14cb5d78 | [
"MIT"
] | null | null | null | src/luxcorescenedemo.cpp | SimonDanisch/LuxRay.jl | b949f6b5cec6280fba6be661b6beb21a14cb5d78 | [
"MIT"
] | 5 | 2015-11-07T16:25:34.000Z | 2015-11-07T16:31:06.000Z | src/luxcorescenedemo.cpp | SimonDanisch/LuxRay.jl | b949f6b5cec6280fba6be661b6beb21a14cb5d78 | [
"MIT"
] | 2 | 2015-11-07T11:43:49.000Z | 2021-10-01T18:02:04.000Z | /***************************************************************************
* Copyright 1998-2013 by authors (see AUTHORS.txt) *
* *
* This file is part of LuxRender. *
* *
* 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 <iostream>
#include <boost/filesystem/operations.hpp>
#include "luxrays/core/utils.h"
#include "luxrays/utils/ocl.h"
#include "luxcore/luxcore.h"
using namespace std;
using namespace luxrays;
using namespace luxcore;
static void CreateMesh(Scene *scene, const string &objName, const string &meshName,
const string &matName, const bool enableUV, const Point *p, const int p_length, Triangle *vi, const int vi_length, const UV *uv) {
// Define the object
scene->DefineMesh(meshName, 24, 12, p, vi, NULL, uv, NULL, NULL);
// Add the object to the scene
Properties props;
props.SetFromString(
"scene.objects." + objName + ".ply = " + meshName + "\n"
"scene.objects." + objName + ".material = " + matName + "\n"
);
scene->Parse(props);
}
static void DoRendering(RenderSession *session) {
const u_int haltTime = session->GetRenderConfig().GetProperties().Get(Property("batch.halttime")(0)).Get<u_int>();
const u_int haltSpp = session->GetRenderConfig().GetProperties().Get(Property("batch.haltspp")(0)).Get<u_int>();
const float haltThreshold = session->GetRenderConfig().GetProperties().Get(Property("batch.haltthreshold")(-1.f)).Get<float>();
char buf[512];
const Properties &stats = session->GetStats();
for (;;) {
boost::this_thread::sleep(boost::posix_time::millisec(1000));
session->UpdateStats();
const double elapsedTime = stats.Get("stats.renderengine.time").Get<double>();
if ((haltTime > 0) && (elapsedTime >= haltTime))
break;
const u_int pass = stats.Get("stats.renderengine.pass").Get<u_int>();
if ((haltSpp > 0) && (pass >= haltSpp))
break;
// Convergence test is update inside UpdateFilm()
const float convergence = stats.Get("stats.renderengine.convergence").Get<u_int>();
if ((haltThreshold >= 0.f) && (1.f - convergence <= haltThreshold))
break;
// Print some information about the rendering progress
sprintf(buf, "[Elapsed time: %3d/%dsec][Samples %4d/%d][Convergence %f%%][Avg. samples/sec % 3.2fM on %.1fK tris]",
int(elapsedTime), int(haltTime), pass, haltSpp, 100.f * convergence,
stats.Get("stats.renderengine.total.samplesec").Get<double>() / 1000000.0,
stats.Get("stats.dataset.trianglecount").Get<double>() / 1000.0);
SLG_LOG(buf);
}
// Save the rendered image
session->GetFilm().Save();
}
void InitRendering() {
try {
luxcore::Init();
cout << "LuxCore " << LUXCORE_VERSION_MAJOR << "." << LUXCORE_VERSION_MINOR << "\n" ;
//----------------------------------------------------------------------
// Build the scene to render
//----------------------------------------------------------------------
Scene *scene = new Scene();
// Setup the camera
scene->Parse(
Property("scene.camera.lookat.orig")(1.f , 6.f , 3.f) <<
Property("scene.camera.lookat.target")(0.f , 0.f , .5f) <<
Property("scene.camera.fieldofview")(60.f));
// Define texture maps
const u_int size = 500;
float *img = new float[size * size * 3];
float *ptr = img;
for (u_int y = 0; y < size; ++y) {
for (u_int x = 0; x < size; ++x) {
if ((x % 50 < 25) ^ (y % 50 < 25)) {
*ptr++ = 1.f;
*ptr++ = 0.f;
*ptr++ = 0.f;
} else {
*ptr++ = 1.f;
*ptr++ = 1.f;
*ptr++ = 0.f;
}
}
}
scene->DefineImageMap("check_texmap", img, 1.f, 3, size, size);
scene->Parse(
Property("scene.textures.map.type")("imagemap") <<
Property("scene.textures.map.file")("check_texmap") <<
Property("scene.textures.map.gamma")(1.f)
);
// Setup materials
scene->Parse(
Property("scene.materials.whitelight.type")("matte") <<
Property("scene.materials.whitelight.emission")(1000000.f, 1000000.f, 1000000.f) <<
Property("scene.materials.mat_white.type")("matte") <<
Property("scene.materials.mat_white.kd")("map") <<
Property("scene.materials.mat_red.type")("matte") <<
Property("scene.materials.mat_red.kd")(0.75f, 0.f, 0.f) <<
Property("scene.materials.mat_glass.type")("glass") <<
Property("scene.materials.mat_glass.kr")(0.9f, 0.9f, 0.9f) <<
Property("scene.materials.mat_glass.kt")(0.9f, 0.9f, 0.9f) <<
Property("scene.materials.mat_glass.exteriorior")(1.f) <<
Property("scene.materials.mat_glass.interiorior")(1.4f) <<
Property("scene.materials.mat_gold.type")("metal2") <<
Property("scene.materials.mat_gold.preset")("gold")
);
// Create the ground
CreateBox(scene, "ground", "mesh-ground", "mat_white", true, BBox(Point(-3.f,-3.f,-.1f), Point(3.f, 3.f, 0.f)));
// Create the red box
CreateBox(scene, "box01", "mesh-box01", "mat_red", false, BBox(Point(-.5f,-.5f, .2f), Point(.5f, .5f, 0.7f)));
// Create the glass box
CreateBox(scene, "box02", "mesh-box02", "mat_glass", false, BBox(Point(1.5f, 1.5f, .3f), Point(2.f, 1.75f, 1.5f)));
// Create the light
CreateBox(scene, "box03", "mesh-box03", "whitelight", false, BBox(Point(-1.75f, 1.5f, .75f), Point(-1.5f, 1.75f, .5f)));
//Create a monkey from ply-file
Properties props;
props.SetFromString(
"scene.objects.monkey.ply = samples/luxcorescenedemo/suzanne.ply\n" // load the ply-file
"scene.objects.monkey.material = mat_gold\n" // set material
"scene.objects.monkey.transformation = \
0.4 0.0 0.0 0.0 \
0.0 0.4 0.0 0.0 \
0.0 0.0 0.4 0.0 \
0.0 2.0 0.3 1.0\n" //scale and translate
);
scene->Parse(props);
// Create a SkyLight & SunLight
scene->Parse(
Property("scene.lights.skyl.type")("sky") <<
Property("scene.lights.skyl.dir")(0.166974f, 0.59908f, 0.783085f) <<
Property("scene.lights.skyl.turbidity")(2.2f) <<
Property("scene.lights.skyl.gain")(0.8f, 0.8f, 0.8f) <<
Property("scene.lights.sunl.type")("sun") <<
Property("scene.lights.sunl.dir")(0.166974f, 0.59908f, 0.783085f) <<
Property("scene.lights.sunl.turbidity")(2.2f) <<
Property("scene.lights.sunl.gain")(0.8f, 0.8f, 0.8f)
);
//----------------------------------------------------------------------
// Do the render
//----------------------------------------------------------------------
RenderConfig *config = new RenderConfig(
Property("renderengine.type")("PATHCPU") <<
Property("sampler.type")("RANDOM") <<
Property("opencl.platform.index")(-1) <<
Property("opencl.cpu.use")(true) <<
Property("opencl.gpu.use")(true) <<
Property("batch.halttime")(10) <<
Property("film.outputs.1.type")("RGB_TONEMAPPED") <<
Property("film.outputs.1.filename")("image.png"),
scene);
RenderSession *session = new RenderSession(config);
//----------------------------------------------------------------------
// Start the rendering
//----------------------------------------------------------------------
session->Start();
DoRendering(session);
boost::filesystem::rename("image.png", "image0.png");
//----------------------------------------------------------------------
// Edit a texture
//----------------------------------------------------------------------
SLG_LOG("Editing a texture...");
session->BeginSceneEdit();
scene->Parse(
Property("scene.textures.map.type")("constfloat3") <<
Property("scene.textures.map.value")(0.f, 0.f, 1.f));
session->EndSceneEdit();
// And redo the rendering
DoRendering(session);
boost::filesystem::rename("image.png", "image1.png");
//----------------------------------------------------------------------
// Edit a material
//----------------------------------------------------------------------
SLG_LOG("Editing a material...");
session->BeginSceneEdit();
scene->Parse(
Property("scene.materials.mat_white.type")("mirror") <<
Property("scene.materials.mat_white.kr")(.9f, .9f, .9f));
session->EndSceneEdit();
// And redo the rendering
DoRendering(session);
boost::filesystem::rename("image.png", "image2.png");
//----------------------------------------------------------------------
// Edit an object
//----------------------------------------------------------------------
SLG_LOG("Editing a material and an object...");
session->BeginSceneEdit();
scene->Parse(
Property("scene.materials.mat_white.type")("matte") <<
Property("scene.materials.mat_white.kr")(.7f, .7f, .7f));
CreateBox(scene, "box03", "mesh-box03", "mat_red", false, BBox(Point(-2.75f, 1.5f, .75f), Point(-.5f, 1.75f, .5f)));
// Rotate the monkey: so he can look what is happen with the light source
// Set the initial values
Vector t(0.0f, 2.0f, 0.3f);
Transform trans(Translate(t));
Transform scale(Scale(0.4f, 0.4f, 0.4f));
// Set rotate = 90
Transform rotate(RotateZ(90));
// Put all together and update object
trans = trans * scale * rotate;
scene->UpdateObjectTransformation("monkey", trans);
session->EndSceneEdit();
// And redo the rendering
DoRendering(session);
boost::filesystem::rename("image.png", "image3.png");
//----------------------------------------------------------------------
// Stop the rendering
session->Stop();
delete session;
delete config;
delete scene;
SLG_LOG("Done.");
#if !defined(LUXRAYS_DISABLE_OPENCL)
} catch (cl::Error err) {
SLG_LOG("OpenCL ERROR: " << err.what() << "(" << oclErrorString(err.err()) << ")");
return EXIT_FAILURE;
#endif
} catch (runtime_error err) {
SLG_LOG("RUNTIME ERROR: " << err.what());
return EXIT_FAILURE;
} catch (exception err) {
SLG_LOG("ERROR: " << err.what());
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 37.496503 | 132 | 0.556509 | [
"mesh",
"render",
"object",
"vector",
"transform",
"3d"
] |
122b3b7195ff7173c665b9bcaa327d7556d232cc | 287 | hh | C++ | includes/emmagic/stl.hh | arcanis/emmagic | 0144983123e5d380fdf3efc1af672cfb3d4a1de7 | [
"MIT",
"Unlicense"
] | 5 | 2019-10-28T11:03:43.000Z | 2022-01-31T20:41:26.000Z | includes/emmagic/stl.hh | arcanis/emmagic | 0144983123e5d380fdf3efc1af672cfb3d4a1de7 | [
"MIT",
"Unlicense"
] | null | null | null | includes/emmagic/stl.hh | arcanis/emmagic | 0144983123e5d380fdf3efc1af672cfb3d4a1de7 | [
"MIT",
"Unlicense"
] | null | null | null | #pragma once
#ifndef EMMAGIC_READY
# error "Please include 'emmagic/magic.hh' before this file"
#endif
#include "./stl/array.hh"
#include "./stl/list.hh"
#include "./stl/map.hh"
#include "./stl/optional.hh"
#include "./stl/set.hh"
#include "./stl/string.hh"
#include "./stl/vector.hh"
| 20.5 | 60 | 0.69338 | [
"vector"
] |
122c33be75a244caee6b649624458221c3ab23d7 | 2,178 | cpp | C++ | SNTDataBase/src/LoaderUnloader/CsvReader.cpp | mihaillatyshov/SNTDataBase | a8341cf57a4bb24315d3b6b5cad1ec1b286b2812 | [
"MIT"
] | 3 | 2021-06-29T08:27:17.000Z | 2021-09-09T16:01:35.000Z | SNTDataBase/src/LoaderUnloader/CsvReader.cpp | mihaillatyshov/SNTDataBase | a8341cf57a4bb24315d3b6b5cad1ec1b286b2812 | [
"MIT"
] | null | null | null | SNTDataBase/src/LoaderUnloader/CsvReader.cpp | mihaillatyshov/SNTDataBase | a8341cf57a4bb24315d3b6b5cad1ec1b286b2812 | [
"MIT"
] | null | null | null | #include "CsvReader.h"
#include <iostream>
#include <iomanip>
#include <fstream>
#include <filesystem>
#include <algorithm>
#include "Utils/Converter.h"
namespace LM
{
CsvReader::CsvReader(std::string_view _FileName)
: m_FileName(_FileName)
{
Load();
}
void CsvReader::RemoveColumn(int _Id)
{
std::for_each(m_Cells.begin(), m_Cells.end(), [_Id](std::vector<std::string>& _Row) { _Row.erase(_Row.begin() + _Id); });
m_ColumnsCount--;
}
void CsvReader::FillEmptyColumns(size_t size)
{
size = std::max(std::max_element(m_Cells.begin(), m_Cells.end(),
[](const std::vector<std::string>& V1, const std::vector<std::string>& V2)
{
return V1.size() > V2.size();
}
)->size(), size);
std::for_each(m_Cells.begin(), m_Cells.end(), [size](std::vector<std::string>& Row) { Row.resize(size); });
m_ColumnsCount = size;
}
void CsvReader::DebugPrint() const
{
for (size_t i = 0; i < m_Cells.size(); i++)
{
std::cout << std::setw(10) << i;
for (const auto& Cell : m_Cells[i])
{
std::cout << std::setw(15) << Cell;
}
std::cout << std::endl;
}
}
void CsvReader::Load()
{
std::ifstream Fin(std::filesystem::path(m_FileName, std::locale("en_US.UTF-8")));
m_IsFileOk = Fin.is_open();
if (!m_IsFileOk)
return;
std::string Line;
int MaskUTF;
Fin.get((char*)&MaskUTF, 4);
std::cout << "UTF-8 Mask: " << std::hex << MaskUTF << std::dec << std::endl;
if (MaskUTF != 0xbfbbef)
{
Fin.close();
Fin.open(m_FileName.data());
m_IsFileOk = Fin.is_open();
if (!m_IsFileOk)
return;
}
while (std::getline(Fin, Line))
{
m_Cells.push_back(std::vector<std::string>());
size_t Start = 0;
size_t Pos = Line.find(';');
while (Pos != std::string::npos)
{
//std::cout << Start << ";" << Pos - Start << " : " << Line.substr(Start, Pos - Start) << " ";
m_Cells.back().push_back(StrToUtf8(Line.substr(Start, Pos - Start)));
Start = Pos + 1;
Pos = Line.find(';', Start);
}
m_Cells.back().push_back(StrToUtf8(Line.substr(Start)));
}
m_RowsCount = m_Cells.size();
if (m_RowsCount > 0)
m_ColumnsCount = m_Cells[0].size();
FillEmptyColumns(0);
}
} | 23.170213 | 123 | 0.606061 | [
"vector"
] |
123475c9c65d90165246229729d675c5f6fcb913 | 19,317 | cpp | C++ | srcs/utils/opengl/UI/ABaseUI.cpp | tnicolas42/bomberman | 493d7243fabb1e5b6d5adfdcb5eb5973869b83a2 | [
"MIT"
] | 6 | 2020-03-13T16:45:13.000Z | 2022-03-30T18:20:48.000Z | srcs/utils/opengl/UI/ABaseUI.cpp | tnicolas42/bomberman | 493d7243fabb1e5b6d5adfdcb5eb5973869b83a2 | [
"MIT"
] | 191 | 2020-03-02T14:47:19.000Z | 2020-06-03T08:13:00.000Z | srcs/utils/opengl/UI/ABaseUI.cpp | tnicolas42/bomberman | 493d7243fabb1e5b6d5adfdcb5eb5973869b83a2 | [
"MIT"
] | null | null | null | #include "ABaseUI.hpp"
#include "ABaseMasterUI.hpp"
#include "Logging.hpp"
/**
* @brief Construct a new ABaseUI::ABaseUI object
*
* @param pos The position of the UI element
* @param size The size of the UI element
*/
ABaseUI::ABaseUI(glm::vec2 pos, glm::vec2 size)
: _enabled(true),
_selected(false),
_pos(pos),
_z(UI_DEF_Z),
_posOffset(UI_DEF_POS_OFFSET),
_size(size),
_color(UI_DEF_COLOR),
_value(UI_DEF_VALUE),
_selectedColor(UI_DEF_SELECTED_COLOR),
_selectedColorText(UI_DEF_SELECTED_COLOR_TEXT),
_borderColor(UI_DEF_BORDER_COLOR),
_borderSize(UI_DEF_BORDER_SIZE),
_mouseHoverColor(UI_DEF_MOUSE_HOVER_COLOR),
_mouseHoverColorText(UI_DEF_MOUSE_HOVER_COLOR_TEXT),
_mouseClickColor(UI_DEF_MOUSE_CLICK_COLOR),
_mouseClickColorText(UI_DEF_MOUSE_CLICK_COLOR_TEXT),
_text(UI_DEF_TEXT),
_textColor(UI_DEF_TEXT_COLOR),
_textFont(UI_DEF_TEXT_FOND),
_textScale(UI_DEF_TEXT_SCALE),
_textPadding(UI_DEF_TEXT_PADDING),
_textAlign(UI_DEF_TEXT_ALIGN),
_textOutline(UI_DEF_TEXT_OUTLINE),
_textOutlineColor(UI_DEF_TEXT_OUTLINE_COLOR),
_imgTextureID(0),
_imgHoverTextureID(0),
_imgDefSize({0, 0}),
_isClickableUI(true),
_mouseHover(false),
_rightClick(false),
_keyRightClickBindScancode(NO_SCANCODE),
_keyRightClickBindInput(InputType::NO_KEY),
_leftClick(false),
_keyLeftClickBindScancode(NO_SCANCODE),
_keyLeftClickBindInput(InputType::NO_KEY),
_rightListener(nullptr),
_leftListener(nullptr),
_leftValueListener(nullptr),
_master(nullptr)
{
if (!_isInit) {
logErr("You need to call ABaseUI::init() before creating UI objects");
return;
}
_allUI.push_back(this); // add pointer to the new UI in _allUI
}
/**
* @brief Construct a new ABaseUI::ABaseUI object
*
* @param src The object to do the copy
*/
ABaseUI::ABaseUI(ABaseUI const & src) {
*this = src;
}
/**
* @brief Destroy the ABaseUI::ABaseUI object
*/
ABaseUI::~ABaseUI() {
// remove reference in master
setMaster(nullptr);
// remove the reference to this UI
auto it = std::find(_allUI.begin(), _allUI.end(), this);
if (it == _allUI.end()) {
logErr("unable to find UI reference in allUI list");
}
else {
_allUI.erase(it);
}
}
/**
* @brief Copy this object
*
* @param rhs The object to copy
* @return ABaseUI& A reference to the copied object
*/
ABaseUI & ABaseUI::operator=(ABaseUI const & rhs) {
if (this != &rhs) {
logWarn("UI object copied");
_pos = rhs._pos;
_size = rhs._size;
}
return *this;
}
/**
* @brief This is the base update function of UI objects
*/
void ABaseUI::update() {
if (!_enabled || isTotallyOutOfScreen() || isPartiallyOutOfMaster())
return;
if (_isClickableUI) {
// buttons calculation only if the UI is clickable
_updateClick();
}
// update of UI element
_update();
}
/**
* @brief Called by update if UI is clickable. Update mousehover, mouseclick, ...
*/
void ABaseUI::_updateClick() {
glm::vec2 mousePos = Inputs::getMousePos();
mousePos.y = _winSize.y - mousePos.y;
/* state of the keys */
// right
bool keyRightDown = false;
if (_keyRightClickBindScancode != NO_SCANCODE && Inputs::getKeyByScancodeDown(_keyRightClickBindScancode))
keyRightDown = true;
if (_keyRightClickBindInput != InputType::NO_KEY && Inputs::getKeyDown(_keyRightClickBindInput))
keyRightDown = true;
bool keyRightUp = false;
if (_keyRightClickBindScancode != NO_SCANCODE && Inputs::getKeyByScancodeUp(_keyRightClickBindScancode))
keyRightUp = true;
if (_keyRightClickBindInput != InputType::NO_KEY && Inputs::getKeyUp(_keyRightClickBindInput))
keyRightUp = true;
// left
bool keyLeftDown = false;
if (_keyLeftClickBindScancode != NO_SCANCODE && Inputs::getKeyByScancodeDown(_keyLeftClickBindScancode))
keyLeftDown = true;
if (_keyLeftClickBindInput != InputType::NO_KEY && Inputs::getKeyDown(_keyLeftClickBindInput))
keyLeftDown = true;
bool keyLeftUp = false;
if (_keyLeftClickBindScancode != NO_SCANCODE && Inputs::getKeyByScancodeUp(_keyLeftClickBindScancode))
keyLeftUp = true;
if (_keyLeftClickBindInput != InputType::NO_KEY && Inputs::getKeyUp(_keyLeftClickBindInput))
keyLeftUp = true;
if (mousePos.x >= getRealPos().x && mousePos.x <= getRealPos().x + _size.x
&& mousePos.y >= getRealPos().y && mousePos.y <= getRealPos().y + _size.y)
{
_mouseHover = true;
if (Inputs::getLeftClickDown()) {
_leftClick = true;
}
if (Inputs::getRightClickDown()) {
_rightClick = true;
}
}
else {
_mouseHover = false;
}
if (keyRightDown) {
_rightClick = true;
}
if (keyLeftDown) {
_leftClick = true;
}
if (Inputs::getLeftClickUp() || keyLeftUp) {
if ((_mouseHover || keyLeftUp) && _leftClick && _leftListener)
*_leftListener = _leftClick;
if ((_mouseHover || keyLeftUp) && _leftClick && _leftValueListener)
*_leftValueListener = _value;
_leftClick = false;
}
if (Inputs::getRightClickUp() || keyRightUp) {
if ((_mouseHover || keyRightUp) && _rightClick && _rightListener)
*_rightListener = _rightClick;
_rightClick = false;
}
}
/**
* @brief This is the base draw function of UI objects
*/
void ABaseUI::draw() {
if (!_enabled || isTotallyOutOfScreen() || isPartiallyOutOfMaster())
return;
if (_showHelp) {
/* get shortcut if exist */
std::string helpText = "";
if (_keyLeftClickBindInput != InputType::NO_KEY)
helpText = Inputs::getKeyName(_keyLeftClickBindInput);
else if (_keyLeftClickBindScancode != NO_SCANCODE)
helpText = Inputs::getScancodeName(_keyLeftClickBindScancode);
/* show shortcut */
if (helpText != "") {
glm::vec2 tmpPos = getRealPos();
glm::vec2 tmpSize = _size;
/* get text informations */
uint32_t width = _textRender->strWidth(_helpFont, helpText, _helpTextScale);
uint32_t height = _textRender->strHeight(_helpFont, _helpTextScale);
tmpSize = glm::vec2(width + _helpPadding, height + _helpPadding);
tmpPos.x = getRealPos().x + _size.x - tmpSize.x - _borderSize - _helpPadding;
tmpPos.y = getRealPos().y + _borderSize + _helpPadding;
_drawText(tmpPos, tmpSize, _z, _helpFont, _helpTextScale, helpText, _textColor, TextAlign::CENTER, 0);
_drawBorderRect(tmpPos, tmpSize, _z, _helpBorderSize, _helpBorderColor);
_drawRect(tmpPos, tmpSize, _z, _color);
}
}
// draw the UI element
_draw();
}
/**
* @brief Called in setWinSize for all UI
*
* @param winScale2f Scale for new window size (vec2)
* @param winScale1f Scale for new window size (float)
*/
void ABaseUI::_resizeWin(glm::vec2 const & winScale2f, float winScale1f) {
// basics
_pos *= winScale2f;
_posOffset *= winScale2f;
_size *= winScale2f;
// border
_borderSize *= winScale1f;
// text
_textScale *= winScale1f;
_textPadding *= winScale1f;
}
/* listener */
/**
* @brief add a listener on the right click
*
* @param listener a pointer on the bool listener
* @return ABaseUI& a reference to the object
*/
ABaseUI & ABaseUI::addButtonRightListener(bool * listener) {
_rightListener = listener;
if (_rightListener)
*_rightListener = _rightClick;
return *this;
}
/**
* @brief add a listener on the left click
*
* @param listener a pointer on the bool listener
* @return ABaseUI& a reference to the object
*/
ABaseUI & ABaseUI::addButtonLeftListener(bool * listener) {
_leftListener = listener;
if (_leftListener)
*_leftListener = _leftClick;
return *this;
}
/**
* @brief add a listener on the left click who will be modify to value
*
* @param listener a pointer on te int64_t listener
* @param value the value the the listener will take.
* @return ABaseUI& a reference to the object
*/
ABaseUI & ABaseUI::addButtonLeftValueListener(int64_t * listener, int64_t value) {
_leftValueListener = listener;
_value = value;
return *this;
}
// -- setter -------------------------------------------------------------------
/**
* @brief Set the right click shortcut
*
* @param scancode The shortcut scancode
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setKeyRightClickScancode(SDL_Scancode scancode) {
_keyRightClickBindScancode = scancode; return *this;
}
/**
* @brief Set the left click shortcut
*
* @param scancode The shortcut scancode
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setKeyLeftClickScancode(SDL_Scancode scancode) {
_keyLeftClickBindScancode = scancode; return *this;
}
/**
* @brief Set the right click shortcut
*
* @param input The shortcut InputType
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setKeyRightClickInput(InputType::Enum input) {
_keyRightClickBindInput = input; return *this;
}
/**
* @brief Set the left click shortcut
*
* @param input The shortcut InputType
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setKeyLeftClickInput(InputType::Enum input) {
_keyLeftClickBindInput = input; return *this;
}
/**
* @brief Check if the UI element is partially out of the screen
*
* @return true if partially out of the screen
*/
bool ABaseUI::isPartiallyOutOfScreen() const {
glm::vec2 rpos = getRealPos();
if (rpos.x < 0 || rpos.y < 0 || rpos.x + _size.x > _winSize.x || rpos.y + _size.y > _winSize.y)
return true;
return false;
}
/**
* @brief Check if the UI element is totally out of the screen
*
* @return true if totally out of the screen
*/
bool ABaseUI::isTotallyOutOfScreen() const {
glm::vec2 rpos = getRealPos();
if (rpos.x + _size.x < 0 || rpos.y + _size.y < 0 || rpos.x > _winSize.x || rpos.y > _winSize.y)
return true;
return false;
}
/**
* @brief Check if the UI element is partially out of the master element
*
* @return true if partially out of the master element
* @return false if totally on master or if master doesn't exist
*/
bool ABaseUI::isPartiallyOutOfMaster() const {
if (_master == nullptr)
return false;
// relative pos in master
glm::vec2 posInMaster = getRealPos() - _master->getMasterPos();
// master size
glm::vec2 mSize = _master->getMasterSize();
if (posInMaster.x < 0 || posInMaster.y < 0 || posInMaster.x + _size.x > mSize.x || posInMaster.y + _size.y > mSize.y)
return true;
return false;
}
/**
* @brief Check if the UI element is totally out of the master element
*
* @return true if totally out of the master element
* @return false if partially or totally on master or if master doesn't exist
*/
bool ABaseUI::isTotallyOutOfMaster() const {
if (_master == nullptr)
return false;
// relative pos in master
glm::vec2 posInMaster = getRealPos() - _master->getMasterPos();
// master size
glm::vec2 mSize = _master->getMasterSize();
if (posInMaster.x + _size.x < 0 || posInMaster.y + _size.y < 0 || posInMaster.x > mSize.x || posInMaster.y > mSize.y)
return true;
return false;
}
/**
* @brief Enable / disable UI
*
* @param enabled enable
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setEnabled(bool enabled) { _enabled = enabled; return *this; }
/**
* @brief Selected / unselected UI
*
* @param selected selected
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setSelected(bool selected) { _selected = selected; return *this; }
/**
* @brief Set position
*
* @param pos Position
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setPos(glm::vec2 pos) { _pos = pos; return *this; }
/**
* @brief Set Z (used for transparency)
*
* @param z z
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setZ(float z) { _z = z; return *this; }
/**
* @brief Set position offset (to move object whitout change position)
*
* @param offset The offset
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setPosOffset(glm::vec2 offset) { _posOffset = offset; return *this; }
/**
* @brief Add to position offset (to move object whitout change position)
*
* @param offset The offset
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::addPosOffset(glm::vec2 offset) { _posOffset += offset; return *this; }
/**
* @brief Set the object size
*
* @param size The new size
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setSize(glm::vec2 size) { _size = size; return *this; }
/**
* @brief Auto calculate size from the text size
*
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setCalculatedSize() {
uint32_t width = _textRender->strWidth(_textFont, _text, _textScale);
uint32_t height = _textRender->strHeight(_textFont, _textScale);
_size = glm::vec2(width + _textPadding * 2, height + _textPadding * 2);;
return *this;
}
/**
* @brief Set the color
*
* @param color Color
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setColor(glm::vec4 color) { _color = color; return *this; }
/**
* @brief Set the color selected
*
* @param color Color selected
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setSelectedColor(glm::vec4 color) { _selectedColor = color; return *this; }
/**
* @brief Set the color selected text
*
* @param color Color selected text
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setSelectedColorText(glm::vec4 color) { _selectedColorText = color; return *this; }
/**
* @brief Set the border color
*
* @param color The border color
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setBorderColor(glm::vec4 color) { _borderColor = color; return *this; }
/**
* @brief Set the border size
*
* @param size The border size
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setBorderSize(float size) { _borderSize = size; return *this; }
/**
* @brief Set the mouse hover color
*
* @param color Mouse hover color
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setMouseHoverColor(glm::vec4 color) { _mouseHoverColor = color; return *this; }
/**
* @brief Set the mouse hover color text
*
* @param color Mouse hover color text
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setMouseHoverColorText(glm::vec4 color) { _mouseHoverColorText = color; return *this; }
/**
* @brief Set the mouse click color
*
* @param color mouse click color
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setMouseClickColor(glm::vec4 color) { _mouseClickColor = color; return *this; }
/**
* @brief Set the mouse click color text
*
* @param color mouse click color text
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setMouseClickColorText(glm::vec4 color) { _mouseClickColorText = color; return *this; }
/**
* @brief Set the text
*
* @param text The text
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setText(std::string const & text) { _text = text; return *this; }
/**
* @brief Set the text color
*
* @param color Text color
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setTextColor(glm::vec4 color) { _textColor = color; return *this; }
/**
* @brief Set the text font
*
* @param font The text font
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setTextFont(std::string const & font) { _textFont = font; return *this; }
/**
* @brief Set the text scale
*
* @param scale The text scale
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setTextScale(float scale) { _textScale = scale; return *this; }
/**
* @brief Set the text padding
*
* @param padding the text padding
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setTextPadding(float padding) { _textPadding = padding; return *this; }
/**
* @brief Set the text alignment
*
* @param align The text alignment
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setTextAlign(TextAlign::Enum align) { _textAlign = align; return *this; }
/**
* @brief Set the text outline
*
* @param outline The text outline
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setTextOutline(float outline) { _textOutline = outline; return *this; }
/**
* @brief Set the text outline color
*
* @param color Text outline color
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setTextOutlineColor(glm::vec4 color) { _textOutlineColor = color; return *this; }
/**
* @brief Set the master object
*
* @param master The master object
* @return ABaseUI& A reference to this UI element
*/
ABaseUI & ABaseUI::setMaster(ABaseMasterUI * master) {
if (_master != nullptr)
_master->removeChild(this);
_master = master;
if (_master != nullptr)
_master->addChild(this);
return *this;
}
/* getter */
/**
* @brief Get mouse hover state
*
* @return true If mouse hover
*/
bool ABaseUI::getMouseHover() const { return _mouseHover; }
/**
* @brief Get mouse right click
*
* @return true If mouse right is clicked
*/
bool ABaseUI::getMouseRightClick() const { return _rightClick; }
/**
* @brief Get mouse left click
*
* @return true If mouse left clicked
*/
bool ABaseUI::getMouseLeftClick() const { return _leftClick; }
/**
* @brief Know if the element is enabled
*
* @return true If enabled
*/
bool ABaseUI::isEnabled() const { return _enabled; }
/**
* @brief Get the position
*
* @return glm::vec2& The position
*/
glm::vec2 & ABaseUI::getPos() { return _pos; }
/**
* @brief Get tje position
*
* @return glm::vec2 const& The position
*/
glm::vec2 const & ABaseUI::getPos() const { return _pos; }
/**
* @brief Get the z position
*
* @return float the z position
*/
float ABaseUI::getZ() const { return _z; }
/**
* @brief Get the ui color
*
* @return glm::vec4 the ui color in rgba order
*/
glm::vec4 ABaseUI::getColor() const { return _color; }
/**
* @brief Get the real position (position + master position + offset)
*
* @return glm::vec2 The real position
*/
glm::vec2 ABaseUI::getRealPos() const {
glm::vec2 masterPos = (_master) ? _master->getMasterRealPos() : glm::vec2(0, 0);
return masterPos + _pos + _posOffset;
}
/**
* @brief Get the size
*
* @return glm::vec2& The size
*/
glm::vec2 & ABaseUI::getSize() { return _size; }
/**
* @brief Get the size
*
* @return glm::vec2 const& The size
*/
glm::vec2 const & ABaseUI::getSize() const { return _size; }
/**
* @brief Get the rectangle Shader
*
* @return Shader& The rectangle shader
*/
Shader & ABaseUI::getRectShader() { return *_rectShader; }
/**
* @brief Get the text width
*
* @return uint32_t The text width
*/
uint32_t ABaseUI::getTextWidth() const {
return _textRender->strWidth(_textFont, _text, _textScale) + _textPadding * 2;
}
/**
* @brief Get the text
*
* @return std::string The text
*/
std::string ABaseUI::getText() const { return _text; }
/**
* @brief Get the default image size
*
* @return glm::ivec2& The def image size
*/
glm::ivec2 & ABaseUI::getImgDefSize() { return _imgDefSize; }
/**
* @brief Get the default image size
*
* @return glm::ivec2 const& The def image size
*/
glm::ivec2 const & ABaseUI::getImgDefSize() const { return _imgDefSize; }
// -- exception ----------------------------------------------------------------
ABaseUI::UIException::UIException()
: std::runtime_error("UI Exception") {}
ABaseUI::UIException::UIException(const char* what_arg)
: std::runtime_error(std::string(std::string("UIError: ") + what_arg).c_str()) {}
| 28.282577 | 118 | 0.695967 | [
"object"
] |
123614dc932ba0fde1afd54d0af7bbded3c12db8 | 7,239 | cpp | C++ | rc110_core/rc110_teleop/src/rc110_joy_teleop.cpp | z-Nakajima/robocar110_ros | 30b53866c61a06565bc2e4030af5eeaf2c3fed26 | [
"MIT"
] | 7 | 2021-09-23T22:44:33.000Z | 2022-03-02T22:33:31.000Z | rc110_core/rc110_teleop/src/rc110_joy_teleop.cpp | z-Nakajima/robocar110_ros | 30b53866c61a06565bc2e4030af5eeaf2c3fed26 | [
"MIT"
] | 5 | 2022-01-07T04:58:57.000Z | 2022-02-09T07:33:49.000Z | rc110_core/rc110_teleop/src/rc110_joy_teleop.cpp | z-Nakajima/robocar110_ros | 30b53866c61a06565bc2e4030af5eeaf2c3fed26 | [
"MIT"
] | 2 | 2021-11-11T08:05:24.000Z | 2021-12-24T02:07:03.000Z | /*
* Copyright (C) 2020 ZMP Inc info@zmp.co.jp
*
* Distributed under the MIT License (http://opensource.org/licenses/MIT)
*
* Written by btran
*/
#include "rc110_joy_teleop.hpp"
#include <std_srvs/SetBool.h>
#include <topic_tools/MuxSelect.h>
namespace zmp
{
namespace
{
enum AxisSetting { AXIS_ID, AXIS_MAX, AXIS_MIN };
float correctLeverAngle(float y, float x) // x, y (- [-1.0 .. 1.0]
{
return y * (1 - std::fabs(x) / 2); // [0 .. 1] is distributed on both y axis and [0 .. pi/2] angle of lever
}
bool isLeverAxis(const std::vector<double>& axis)
{
return axis[AXIS_MIN] < 0;
}
} // namespace
Rc110JoyTeleop::Rc110JoyTeleop(ros::NodeHandle& nh, ros::NodeHandle& pnh) :
m_drivePub(nh.advertise<ackermann_msgs::AckermannDriveStamped>("drive_manual", 1))
{
pnh.param<int>("base_dead_man_button", m_param.deadManButton, m_param.deadManButton);
pnh.param<int>("gear_up_button", m_param.gearUpButton, m_param.gearUpButton);
pnh.param<int>("gear_down_button", m_param.gearDownButton, m_param.gearDownButton);
pnh.param<int>("board_button", m_param.boardButton, m_param.boardButton);
pnh.param<int>("ad_button", m_param.adButton, m_param.adButton);
pnh.param("steering", m_param.steering, m_param.steering);
pnh.param("steering_aux", m_param.steeringAuxiliary, m_param.steeringAuxiliary);
pnh.param("accel", m_param.accel, m_param.accel);
pnh.param<std::string>("base_frame_id", m_param.frameId, m_param.frameId);
updateAxis(m_param.steering, 28.0 * 1.3); // by default, max value + 30% to being able to reach max easily
updateAxis(m_param.accel, 1.0);
if (m_param.steeringAuxiliary == -1) {
m_param.steeringAuxiliary = m_param.steering[AXIS_ID] - 1;
}
std::vector<double> gears = pnh.param("gears", m_param.gears);
if (!gears.empty()) {
m_param.gears = gears;
}
pnh.param("rate", m_param.rate, m_param.rate);
m_timer = pnh.createTimer(ros::Duration(1 / m_param.rate), [this](const ros::TimerEvent&) { publishDrive(); });
m_subscribers.push_back(nh.subscribe("joy", 1, &zmp::Rc110JoyTeleop::onJoy, this));
m_subscribers.push_back(nh.subscribe("robot_status", 1, &Rc110JoyTeleop::onRobotStatus, this));
m_subscribers.push_back(nh.subscribe("mux_drive/selected", 1, &Rc110JoyTeleop::onAdModeChanged, this));
}
void Rc110JoyTeleop::updateAxis(std::vector<double>& axis, double defaultMax)
{
switch (axis.size()) {
case 0:
throw std::runtime_error("Please, specify all axes!");
case 1:
axis = {axis[AXIS_ID], defaultMax, -defaultMax};
break;
case 2:
axis = {axis[AXIS_ID], axis[AXIS_MAX], -axis[AXIS_MAX]};
break;
}
if (axis[AXIS_MIN] < axis[AXIS_MAX]) {
m_axisDirection[axis[AXIS_ID]] = 1;
} else {
m_axisDirection[axis[AXIS_ID]] = -1;
std::swap(axis[AXIS_MIN], axis[AXIS_MAX]);
}
}
void Rc110JoyTeleop::publishDrive()
{
if (m_param.deadManButton == -1) {
// if dead man button deactivated, publish when there are motion commands in last 500 ms
if ((ros::Time::now() - m_lastTime).toSec() < 0.5) {
m_drivePub.publish(m_driveMessage);
}
} else if (m_joyMessage) {
// if dead man button is activated, use it
if (m_joyMessage->buttons[m_param.deadManButton]) {
m_drivePub.publish(m_driveMessage);
m_stopMessagePublished = false;
} else if (!m_stopMessagePublished) {
// and send additional stop message, immediately after button release
m_drivePub.publish(ackermann_msgs::AckermannDriveStamped());
m_stopMessagePublished = true;
}
}
}
void Rc110JoyTeleop::updateToggles(const sensor_msgs::Joy::ConstPtr& message)
{
if (checkButtonClicked(message, m_param.boardButton)) {
std_srvs::SetBool service;
service.request.data = uint8_t(!m_boardEnabled); // toggle board
ros::service::call("enable_board", service);
}
if (checkButtonClicked(message, m_param.adButton)) {
topic_tools::MuxSelect service;
service.request.topic = m_adEnabled ? "drive_manual" : "drive_ad"; // toggle AD
ros::service::call("mux_drive/select", service);
}
}
bool Rc110JoyTeleop::checkButtonClicked(const sensor_msgs::Joy::ConstPtr& message, int button)
{
return m_joyMessage && message->buttons[button] && !m_joyMessage->buttons[button];
}
bool Rc110JoyTeleop::checkAxisChanged(const sensor_msgs::Joy::ConstPtr& message, int axis)
{
return m_joyMessage && message->axes[axis] != m_joyMessage->axes[axis];
}
float Rc110JoyTeleop::getAxisValue(const sensor_msgs::Joy::ConstPtr& message, int axis)
{
return axis == -1 ? 0.f : message->axes[axis];
}
float Rc110JoyTeleop::mapAxisValue(const std::vector<double>& axis, float value)
{
// workaround for joy_node bug which does not read initial axis value
if (value != 0.f) {
m_axisActivated[axis[AXIS_ID]] = true;
}
if (!m_axisActivated[axis[AXIS_ID]]) {
return 0.f;
}
// value is [-1 .. 1], mapped to [min, max]
float minValue = axis[AXIS_MIN];
float maxValue = axis[AXIS_MAX];
value = (value + 1) / 2;
value = minValue + value * (maxValue - minValue);
return m_axisDirection[axis[AXIS_ID]] * value;
}
void Rc110JoyTeleop::onJoy(const sensor_msgs::Joy::ConstPtr& message)
{
auto minGear = -1; // reverse gear, 1st gear, 2nd gear, and so on
auto maxGear = int(m_param.gears.size()) - 1;
auto steeringValue = getAxisValue(message, m_param.steering[AXIS_ID]);
if (isLeverAxis(m_param.accel)) {
float steeringAux = getAxisValue(message, m_param.steeringAuxiliary);
steeringValue = correctLeverAngle(steeringValue, steeringAux);
}
steeringValue = mapAxisValue(m_param.steering, steeringValue);
auto accelValue = mapAxisValue(m_param.accel, getAxisValue(message, m_param.accel[AXIS_ID]));
if (checkButtonClicked(message, m_param.gearUpButton)) ++m_gear;
if (checkButtonClicked(message, m_param.gearDownButton)) --m_gear;
// for lever, reverse gear is activated by pulling the lever back
if (isLeverAxis(m_param.accel)) {
m_gear = accelValue < 0 ? -1 : std::max(0, m_gear);
}
// limit gear, and if no accelerator, initialize with lowest gear
m_gear = std::fabs(accelValue) > 0.01f ? std::clamp(m_gear, minGear, maxGear) : std::min(0, m_gear);
// reverse gear speed equal to negative first gear
auto gearFactor = m_gear < 0 ? -1 * float(m_param.gears[0]) : float(m_param.gears[m_gear]);
m_driveMessage.drive.steering_angle = angles::from_degrees(steeringValue);
m_driveMessage.drive.speed = std::fabs(accelValue) * gearFactor;
m_driveMessage.header.stamp = ros::Time::now();
m_driveMessage.header.frame_id = m_param.frameId;
updateToggles(message);
m_joyMessage = message;
m_lastTime = ros::Time::now();
}
void Rc110JoyTeleop::onRobotStatus(const rc110_msgs::Status& message)
{
m_boardEnabled = message.board_enabled;
}
void Rc110JoyTeleop::onAdModeChanged(const std_msgs::String& message)
{
m_adEnabled = message.data == "drive_ad";
}
} // namespace zmp
| 36.376884 | 115 | 0.677303 | [
"vector"
] |
72ea281886cf893dfbc6250d6c80d9e2c84578d1 | 4,580 | cc | C++ | tools/StructGridInterpolation.cc | vbertone/NangaParbat | 49529d0a2e810dfe0ec676c8e96081be39a8800d | [
"MIT"
] | 3 | 2020-01-16T17:15:54.000Z | 2020-01-17T10:59:39.000Z | tools/StructGridInterpolation.cc | vbertone/NangaParbat | 49529d0a2e810dfe0ec676c8e96081be39a8800d | [
"MIT"
] | null | null | null | tools/StructGridInterpolation.cc | vbertone/NangaParbat | 49529d0a2e810dfe0ec676c8e96081be39a8800d | [
"MIT"
] | 3 | 2020-01-18T22:10:02.000Z | 2020-08-01T18:42:36.000Z | //
// Author: Valerio Bertone: valerio.bertone@cern.ch
// Chiara Bissolotti: chiara.bissolotti01@universitadipavia.it
//
#include "NangaParbat/createtmdgrid.h"
#include "NangaParbat/factories.h"
#include "NangaParbat/bstar.h"
#include "NangaParbat/nonpertfunctions.h"
#include <LHAPDF/LHAPDF.h>
#include <sys/stat.h>
#include <fstream>
#include <cstring>
//_________________________________________________________________________________
int main(int argc, char* argv[])
{
// Check that the input is correct otherwise stop the code
if (argc < 5 || strcmp(argv[1], "--help") == 0)
{
std::cout << "\nInvalid Parameters:" << std::endl;
std::cout << "Syntax: ./StructGridInterpolation <grid main folder> <grid name> <n. repl.> <output>\n" << std::endl;
std::cout << "<grid main folder>: relative path to the folder where the grids are;" << std::endl;
std::cout << "<n. repl>: number of the replica grid to interpolate. \n" << std::endl;
exit(-10);
}
const std::string Folder = std::string(argv[1]);
const std::string Name = std::string(argv[2]);
const std::string Output = std::string(argv[4]);
// Select flavour
const int ifl = 2; // quark up
// Read values
YAML::Node kin = YAML::LoadFile("inputs/StructGridInterpolation.yaml");
const std::vector<double> qTgoQ = kin["qToQ"].as<std::vector<double>>();
const std::vector<double> Qg = kin["Q"].as<std::vector<double>>();
const std::vector<double> xg = kin["x"].as<std::vector<double>>();
const std::vector<double> zg = kin["z"].as<std::vector<double>>();
// ===========================================================================
// Read info file
std::cout << "\n";
std::cout << "Reading info file: " + Folder + "/" + Name + "/" + Name + ".info" + " ..." << std::endl;
YAML::Node const& infofile = YAML::LoadFile(Folder + "/" + Name + "/" + Name + ".info");
// Create directory to store the output
mkdir(Output.c_str(), ACCESSPERMS);
std::cout << "Creating folder " + Output << std::endl;
std::cout << "\n";
// Start intepolation
std::cout << "Starting interpolation of " + std::string(argv[2]) + " ..." << std::endl;
// Read Structure function in grid
NangaParbat::StructGrid* SFs = NangaParbat::mkSF(Name, Folder, std::stoi(argv[3]));
// Read grids and test interpolation
for (int iq = 0; iq < (int) Qg.size(); iq++)
{
const double Q = Qg[iq];
for (int ix = 0; ix < (int) xg.size(); ix++)
{
const double x = xg[ix];
for (int iz = 0; iz < (int) zg.size(); iz++)
{
// value of z
const double z = zg[iz];
/*
// Values of qT
const double qTmin = Q * 1e-4;
const double qTmax = 3 * Q;
const int nqT = 40;
const double qTstp = (qTmax - qTmin)/ nqT;
*/
// Fill vectors with grid interpolation
std::vector<double> gridinterp;
// for (double qT = qTmin; qT <= qTmax * ( 1 + 1e-5 ); qT += qTstp)
// gridinterp.push_back(SFs->Evaluate(x ,z, qT, Q));
for (const double qToQ : qTgoQ)
gridinterp.push_back(SFs->Evaluate(x ,z, qToQ * Q, Q));
// YAML Emitter
YAML::Emitter em;
em << YAML::BeginMap;
em << YAML::Key << "ifl" << YAML::Value << ifl;
em << YAML::Key << "Q" << YAML::Value << Q;
em << YAML::Key << "x" << YAML::Value << x;
em << YAML::Key << "z" << YAML::Value << z;
em << YAML::Key << "qT" << YAML::Value << YAML::Flow << YAML::BeginSeq;
// for (double qT = qTmin; qT <= qTmax * ( 1 + 1e-5 ); qT += qTstp)
// em << qT;
for (const double qToQ : qTgoQ)
em << qToQ * Q;
em << YAML::EndSeq;
em << YAML::Key << "Grid interpolation" << YAML::Value << YAML::Flow << YAML::BeginSeq;
for (int i = 0; i < (int) gridinterp.size(); i++)
em << gridinterp[i];
em << YAML::EndSeq;
em << YAML::EndMap;
// Produce output file
std::ofstream fout(Output + "/" + infofile["StructFuncType"].as<std::string>() + "_Q_" + std::to_string(Q) + "_x_" + std::to_string(x) + "_z_" + std::to_string(z) + ".yaml");
fout << em.c_str() << std::endl;
fout.close();
}
}
}
delete SFs;
return 0;
}
| 37.540984 | 189 | 0.521616 | [
"vector"
] |
72ef033df526d8a00670730762385ba67970fdf4 | 20,250 | cc | C++ | chrome/browser/sync/sync_setup_wizard_unittest.cc | SlimKatLegacy/android_external_chromium | bc611cda58cc18d0dbaa8a7aee05eb3c0742e573 | [
"BSD-3-Clause"
] | 2 | 2017-05-19T08:53:12.000Z | 2017-08-28T11:59:26.000Z | chrome/browser/sync/sync_setup_wizard_unittest.cc | SlimKatLegacy/android_external_chromium | bc611cda58cc18d0dbaa8a7aee05eb3c0742e573 | [
"BSD-3-Clause"
] | 2 | 2017-07-25T09:37:22.000Z | 2017-08-04T07:18:56.000Z | chrome/browser/sync/sync_setup_wizard_unittest.cc | SlimKatLegacy/android_external_chromium | bc611cda58cc18d0dbaa8a7aee05eb3c0742e573 | [
"BSD-3-Clause"
] | 2 | 2020-01-12T00:55:53.000Z | 2020-11-04T06:36:41.000Z | // Copyright (c) 2011 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.
// TODO(jhawkins): Rewrite these tests to handle the new inlined sync UI.
#include "chrome/browser/sync/sync_setup_wizard.h"
#include "base/json/json_writer.h"
#include "base/memory/scoped_ptr.h"
#include "base/stl_util-inl.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/sync/profile_sync_factory_mock.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/sync_setup_flow.h"
#include "chrome/browser/sync/sync_setup_flow_handler.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/common/net/gaia/google_service_auth_error.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/browser_with_test_window_test.h"
#include "chrome/test/test_browser_window.h"
#include "chrome/test/testing_profile.h"
#include "testing/gtest/include/gtest/gtest.h"
static const char kTestUser[] = "chrome.p13n.test@gmail.com";
static const char kTestPassword[] = "passwd";
static const char kTestCaptcha[] = "pizzamyheart";
static const char kTestCaptchaUrl[] = "http://pizzamyheart/";
typedef GoogleServiceAuthError AuthError;
// A PSS subtype to inject.
class ProfileSyncServiceForWizardTest : public ProfileSyncService {
public:
ProfileSyncServiceForWizardTest(ProfileSyncFactory* factory, Profile* profile)
: ProfileSyncService(factory, profile, ""),
user_cancelled_dialog_(false) {
RegisterPreferences();
ResetTestStats();
}
virtual ~ProfileSyncServiceForWizardTest() { }
virtual void OnUserSubmittedAuth(const std::string& username,
const std::string& password,
const std::string& captcha,
const std::string& access_code) {
username_ = username;
password_ = password;
captcha_ = captcha;
}
virtual void OnUserChoseDatatypes(bool sync_everything,
const syncable::ModelTypeSet& chosen_types) {
user_chose_data_types_ = true;
chosen_data_types_ = chosen_types;
}
virtual void OnUserCancelledDialog() {
user_cancelled_dialog_ = true;
}
virtual void SetPassphrase(const std::string& passphrase,
bool is_explicit,
bool is_creation) {
passphrase_ = passphrase;
}
virtual string16 GetAuthenticatedUsername() const {
return UTF8ToUTF16(username_);
}
void set_auth_state(const std::string& last_email,
const AuthError& error) {
last_attempted_user_email_ = last_email;
last_auth_error_ = error;
}
void set_passphrase_required(bool required) {
observed_passphrase_required_ = required;
}
void ResetTestStats() {
username_.clear();
password_.clear();
captcha_.clear();
user_cancelled_dialog_ = false;
user_chose_data_types_ = false;
keep_everything_synced_ = false;
chosen_data_types_.clear();
}
std::string username_;
std::string password_;
std::string captcha_;
bool user_cancelled_dialog_;
bool user_chose_data_types_;
bool keep_everything_synced_;
syncable::ModelTypeSet chosen_data_types_;
std::string passphrase_;
private:
DISALLOW_COPY_AND_ASSIGN(ProfileSyncServiceForWizardTest);
};
class TestingProfileWithSyncService : public TestingProfile {
public:
TestingProfileWithSyncService() {
sync_service_.reset(new ProfileSyncServiceForWizardTest(&factory_, this));
}
virtual ProfileSyncService* GetProfileSyncService() {
return sync_service_.get();
}
private:
ProfileSyncFactoryMock factory_;
scoped_ptr<ProfileSyncService> sync_service_;
};
class TestBrowserWindowForWizardTest : public TestBrowserWindow {
public:
explicit TestBrowserWindowForWizardTest(Browser* browser)
: TestBrowserWindow(browser), flow_(NULL),
was_show_html_dialog_called_(false) {
}
virtual ~TestBrowserWindowForWizardTest() {
if (flow_.get()) {
// The handler contract is that they are valid for the lifetime of the
// sync login overlay, but are cleaned up after the dialog is closed
// and/or deleted.
flow_.reset();
}
}
bool TestAndResetWasShowHTMLDialogCalled() {
bool ret = was_show_html_dialog_called_;
was_show_html_dialog_called_ = false;
return ret;
}
// Simulates the user (or browser view hierarchy) closing the html dialog.
// Handles cleaning up the delegate and associated handlers.
void CloseDialog() {
if (flow_.get()) {
// The flow deletes itself here. Don't use reset().
flow_.release()->OnDialogClosed("");
}
}
SyncSetupFlow* flow() { return flow_.get(); }
private:
// In real life, this is owned by the view that is opened by the browser. We
// mock all that out, so we need to take ownership so the flow doesn't leak.
scoped_ptr<SyncSetupFlow> flow_;
bool was_show_html_dialog_called_;
};
class SyncSetupWizardTest : public BrowserWithTestWindowTest {
public:
SyncSetupWizardTest()
: test_window_(NULL),
wizard_(NULL) { }
virtual ~SyncSetupWizardTest() { }
virtual void SetUp() {
set_profile(new TestingProfileWithSyncService());
profile()->CreateBookmarkModel(false);
// Wait for the bookmarks model to load.
profile()->BlockUntilBookmarkModelLoaded();
set_browser(new Browser(Browser::TYPE_NORMAL, profile()));
test_window_ = new TestBrowserWindowForWizardTest(browser());
set_window(test_window_);
browser()->set_window(window());
BrowserList::SetLastActive(browser());
service_ = static_cast<ProfileSyncServiceForWizardTest*>(
profile()->GetProfileSyncService());
wizard_.reset(new SyncSetupWizard(service_));
}
virtual void TearDown() {
test_window_ = NULL;
service_ = NULL;
wizard_.reset();
}
TestBrowserWindowForWizardTest* test_window_;
scoped_ptr<SyncSetupWizard> wizard_;
ProfileSyncServiceForWizardTest* service_;
};
// See http://code.google.com/p/chromium/issues/detail?id=40715 for
// why we skip the below tests on OS X. We don't use DISABLED_ as we
// would have to change the corresponding FRIEND_TEST() declarations.
#if defined(OS_MACOSX)
#define SKIP_TEST_ON_MACOSX() \
do { LOG(WARNING) << "Test skipped on OS X"; return; } while (0)
#else
#define SKIP_TEST_ON_MACOSX() do {} while (0)
#endif
TEST_F(SyncSetupWizardTest, DISABLED_InitialStepLogin) {
SKIP_TEST_ON_MACOSX();
DictionaryValue dialog_args;
SyncSetupFlow::GetArgsForGaiaLogin(service_, &dialog_args);
std::string json_start_args;
base::JSONWriter::Write(&dialog_args, false, &json_start_args);
ListValue credentials;
std::string auth = "{\"user\":\"";
auth += std::string(kTestUser) + "\",\"pass\":\"";
auth += std::string(kTestPassword) + "\",\"captcha\":\"";
auth += std::string(kTestCaptcha) + "\",\"access_code\":\"";
auth += std::string() + "\"}";
credentials.Append(new StringValue(auth));
EXPECT_FALSE(wizard_->IsVisible());
EXPECT_FALSE(test_window_->flow());
wizard_->Step(SyncSetupWizard::GAIA_LOGIN);
EXPECT_TRUE(wizard_->IsVisible());
EXPECT_TRUE(test_window_->TestAndResetWasShowHTMLDialogCalled());
EXPECT_EQ(SyncSetupWizard::GAIA_LOGIN, test_window_->flow()->current_state_);
EXPECT_EQ(SyncSetupWizard::DONE, test_window_->flow()->end_state_);
EXPECT_EQ(json_start_args, test_window_->flow()->dialog_start_args_);
#if 0
// Simulate the user submitting credentials.
test_window_->flow()->flow_handler_->HandleSubmitAuth(&credentials);
EXPECT_TRUE(wizard_->IsVisible());
EXPECT_EQ(SyncSetupWizard::GAIA_LOGIN, test_window_->flow()->current_state_);
EXPECT_EQ(kTestUser, service_->username_);
EXPECT_EQ(kTestPassword, service_->password_);
EXPECT_EQ(kTestCaptcha, service_->captcha_);
EXPECT_FALSE(service_->user_cancelled_dialog_);
service_->ResetTestStats();
#endif
// Simulate failed credentials.
AuthError invalid_gaia(AuthError::INVALID_GAIA_CREDENTIALS);
service_->set_auth_state(kTestUser, invalid_gaia);
wizard_->Step(SyncSetupWizard::GAIA_LOGIN);
EXPECT_TRUE(wizard_->IsVisible());
EXPECT_FALSE(test_window_->TestAndResetWasShowHTMLDialogCalled());
EXPECT_EQ(SyncSetupWizard::GAIA_LOGIN, test_window_->flow()->current_state_);
dialog_args.Clear();
SyncSetupFlow::GetArgsForGaiaLogin(service_, &dialog_args);
EXPECT_EQ(5U, dialog_args.size());
std::string iframe_to_show;
dialog_args.GetString("iframeToShow", &iframe_to_show);
EXPECT_EQ("login", iframe_to_show);
std::string actual_user;
dialog_args.GetString("user", &actual_user);
EXPECT_EQ(kTestUser, actual_user);
int error = -1;
dialog_args.GetInteger("error", &error);
EXPECT_EQ(static_cast<int>(AuthError::INVALID_GAIA_CREDENTIALS), error);
service_->set_auth_state(kTestUser, AuthError::None());
// Simulate captcha.
AuthError captcha_error(AuthError::FromCaptchaChallenge(
std::string(), GURL(kTestCaptchaUrl), GURL()));
service_->set_auth_state(kTestUser, captcha_error);
wizard_->Step(SyncSetupWizard::GAIA_LOGIN);
SyncSetupFlow::GetArgsForGaiaLogin(service_, &dialog_args);
EXPECT_EQ(5U, dialog_args.size());
dialog_args.GetString("iframeToShow", &iframe_to_show);
EXPECT_EQ("login", iframe_to_show);
std::string captcha_url;
dialog_args.GetString("captchaUrl", &captcha_url);
EXPECT_EQ(kTestCaptchaUrl, GURL(captcha_url).spec());
error = -1;
dialog_args.GetInteger("error", &error);
EXPECT_EQ(static_cast<int>(AuthError::CAPTCHA_REQUIRED), error);
service_->set_auth_state(kTestUser, AuthError::None());
// Simulate success.
wizard_->Step(SyncSetupWizard::GAIA_SUCCESS);
EXPECT_TRUE(wizard_->IsVisible());
EXPECT_FALSE(test_window_->TestAndResetWasShowHTMLDialogCalled());
// In a non-discrete run, GAIA_SUCCESS immediately transitions you to
// SYNC_EVERYTHING.
EXPECT_EQ(SyncSetupWizard::SYNC_EVERYTHING,
test_window_->flow()->current_state_);
// That's all we're testing here, just move on to DONE. We'll test the
// "choose data types" scenarios elsewhere.
wizard_->Step(SyncSetupWizard::SETTING_UP); // No merge and sync.
wizard_->Step(SyncSetupWizard::DONE); // No merge and sync.
EXPECT_TRUE(wizard_->IsVisible());
EXPECT_FALSE(test_window_->TestAndResetWasShowHTMLDialogCalled());
EXPECT_EQ(SyncSetupWizard::DONE, test_window_->flow()->current_state_);
}
TEST_F(SyncSetupWizardTest, DISABLED_ChooseDataTypesSetsPrefs) {
SKIP_TEST_ON_MACOSX();
wizard_->Step(SyncSetupWizard::GAIA_LOGIN);
wizard_->Step(SyncSetupWizard::GAIA_SUCCESS);
wizard_->Step(SyncSetupWizard::CONFIGURE);
ListValue data_type_choices_value;
std::string data_type_choices = "{\"keepEverythingSynced\":false,";
data_type_choices += "\"syncBookmarks\":true,\"syncPreferences\":true,";
data_type_choices += "\"syncThemes\":false,\"syncPasswords\":false,";
data_type_choices += "\"syncAutofill\":false,\"syncExtensions\":false,";
data_type_choices += "\"syncTypedUrls\":true,\"syncApps\":true,";
data_type_choices += "\"syncSessions\":false,\"usePassphrase\":false}";
data_type_choices_value.Append(new StringValue(data_type_choices));
#if 0
// Simulate the user choosing data types; bookmarks, prefs, typed
// URLS, and apps are on, the rest are off.
test_window_->flow()->flow_handler_->HandleConfigure(
&data_type_choices_value);
EXPECT_TRUE(wizard_->IsVisible());
EXPECT_TRUE(test_window_->TestAndResetWasShowHTMLDialogCalled());
EXPECT_FALSE(service_->keep_everything_synced_);
EXPECT_EQ(service_->chosen_data_types_.count(syncable::BOOKMARKS), 1U);
EXPECT_EQ(service_->chosen_data_types_.count(syncable::PREFERENCES), 1U);
EXPECT_EQ(service_->chosen_data_types_.count(syncable::THEMES), 0U);
EXPECT_EQ(service_->chosen_data_types_.count(syncable::PASSWORDS), 0U);
EXPECT_EQ(service_->chosen_data_types_.count(syncable::AUTOFILL), 0U);
EXPECT_EQ(service_->chosen_data_types_.count(syncable::EXTENSIONS), 0U);
EXPECT_EQ(service_->chosen_data_types_.count(syncable::TYPED_URLS), 1U);
EXPECT_EQ(service_->chosen_data_types_.count(syncable::APPS), 1U);
#endif
test_window_->CloseDialog();
}
TEST_F(SyncSetupWizardTest, DISABLED_EnterPassphraseRequired) {
SKIP_TEST_ON_MACOSX();
wizard_->Step(SyncSetupWizard::GAIA_LOGIN);
wizard_->Step(SyncSetupWizard::GAIA_SUCCESS);
wizard_->Step(SyncSetupWizard::CONFIGURE);
wizard_->Step(SyncSetupWizard::SETTING_UP);
service_->set_passphrase_required(true);
wizard_->Step(SyncSetupWizard::ENTER_PASSPHRASE);
EXPECT_EQ(SyncSetupWizard::ENTER_PASSPHRASE,
test_window_->flow()->current_state_);
#if 0
ListValue value;
value.Append(new StringValue("{\"passphrase\":\"myPassphrase\","
"\"mode\":\"gaia\"}"));
test_window_->flow()->flow_handler_->HandlePassphraseEntry(&value);
EXPECT_EQ("myPassphrase", service_->passphrase_);
#endif
}
TEST_F(SyncSetupWizardTest, DISABLED_PassphraseMigration) {
SKIP_TEST_ON_MACOSX();
wizard_->Step(SyncSetupWizard::PASSPHRASE_MIGRATION);
#if 0
ListValue value;
value.Append(new StringValue("{\"option\":\"explicit\","
"\"passphrase\":\"myPassphrase\"}"));
test_window_->flow()->flow_handler_->HandleFirstPassphrase(&value);
EXPECT_EQ("myPassphrase", service_->passphrase_);
ListValue value2;
value2.Append(new StringValue("{\"option\":\"nothanks\","
"\"passphrase\":\"myPassphrase\"}"));
test_window_->flow()->flow_handler_->HandleFirstPassphrase(&value2);
EXPECT_EQ(service_->chosen_data_types_.count(syncable::PASSWORDS), 0U);
#endif
}
TEST_F(SyncSetupWizardTest, DISABLED_DialogCancelled) {
SKIP_TEST_ON_MACOSX();
wizard_->Step(SyncSetupWizard::GAIA_LOGIN);
// Simulate the user closing the dialog.
test_window_->CloseDialog();
EXPECT_FALSE(wizard_->IsVisible());
EXPECT_TRUE(service_->user_cancelled_dialog_);
EXPECT_EQ(std::string(), service_->username_);
EXPECT_EQ(std::string(), service_->password_);
wizard_->Step(SyncSetupWizard::GAIA_LOGIN);
EXPECT_TRUE(wizard_->IsVisible());
EXPECT_TRUE(test_window_->TestAndResetWasShowHTMLDialogCalled());
wizard_->Step(SyncSetupWizard::GAIA_LOGIN);
EXPECT_FALSE(test_window_->TestAndResetWasShowHTMLDialogCalled());
test_window_->CloseDialog();
EXPECT_FALSE(wizard_->IsVisible());
EXPECT_TRUE(service_->user_cancelled_dialog_);
EXPECT_EQ(std::string(), service_->username_);
EXPECT_EQ(std::string(), service_->password_);
}
TEST_F(SyncSetupWizardTest, DISABLED_InvalidTransitions) {
SKIP_TEST_ON_MACOSX();
wizard_->Step(SyncSetupWizard::GAIA_SUCCESS);
EXPECT_FALSE(wizard_->IsVisible());
EXPECT_FALSE(test_window_->TestAndResetWasShowHTMLDialogCalled());
wizard_->Step(SyncSetupWizard::DONE);
EXPECT_FALSE(wizard_->IsVisible());
EXPECT_FALSE(test_window_->TestAndResetWasShowHTMLDialogCalled());
wizard_->Step(SyncSetupWizard::DONE_FIRST_TIME);
EXPECT_FALSE(wizard_->IsVisible());
EXPECT_FALSE(test_window_->TestAndResetWasShowHTMLDialogCalled());
wizard_->Step(SyncSetupWizard::GAIA_LOGIN);
wizard_->Step(SyncSetupWizard::DONE);
EXPECT_EQ(SyncSetupWizard::GAIA_LOGIN, test_window_->flow()->current_state_);
wizard_->Step(SyncSetupWizard::DONE_FIRST_TIME);
EXPECT_EQ(SyncSetupWizard::GAIA_LOGIN, test_window_->flow()->current_state_);
wizard_->Step(SyncSetupWizard::SETUP_ABORTED_BY_PENDING_CLEAR);
EXPECT_EQ(SyncSetupWizard::GAIA_LOGIN,
test_window_->flow()->current_state_);
wizard_->Step(SyncSetupWizard::GAIA_SUCCESS);
EXPECT_EQ(SyncSetupWizard::SYNC_EVERYTHING,
test_window_->flow()->current_state_);
wizard_->Step(SyncSetupWizard::FATAL_ERROR);
EXPECT_EQ(SyncSetupWizard::FATAL_ERROR, test_window_->flow()->current_state_);
}
TEST_F(SyncSetupWizardTest, DISABLED_FullSuccessfulRunSetsPref) {
SKIP_TEST_ON_MACOSX();
wizard_->Step(SyncSetupWizard::GAIA_LOGIN);
wizard_->Step(SyncSetupWizard::GAIA_SUCCESS);
wizard_->Step(SyncSetupWizard::SETTING_UP);
wizard_->Step(SyncSetupWizard::DONE);
test_window_->CloseDialog();
EXPECT_FALSE(wizard_->IsVisible());
EXPECT_TRUE(service_->profile()->GetPrefs()->GetBoolean(
prefs::kSyncHasSetupCompleted));
}
TEST_F(SyncSetupWizardTest, DISABLED_FirstFullSuccessfulRunSetsPref) {
SKIP_TEST_ON_MACOSX();
wizard_->Step(SyncSetupWizard::GAIA_LOGIN);
wizard_->Step(SyncSetupWizard::GAIA_SUCCESS);
wizard_->Step(SyncSetupWizard::SETTING_UP);
wizard_->Step(SyncSetupWizard::DONE_FIRST_TIME);
test_window_->CloseDialog();
EXPECT_FALSE(wizard_->IsVisible());
EXPECT_TRUE(service_->profile()->GetPrefs()->GetBoolean(
prefs::kSyncHasSetupCompleted));
}
TEST_F(SyncSetupWizardTest, DISABLED_AbortedByPendingClear) {
SKIP_TEST_ON_MACOSX();
wizard_->Step(SyncSetupWizard::GAIA_LOGIN);
wizard_->Step(SyncSetupWizard::GAIA_SUCCESS);
wizard_->Step(SyncSetupWizard::SETUP_ABORTED_BY_PENDING_CLEAR);
EXPECT_EQ(SyncSetupWizard::SETUP_ABORTED_BY_PENDING_CLEAR,
test_window_->flow()->current_state_);
test_window_->CloseDialog();
EXPECT_FALSE(wizard_->IsVisible());
}
TEST_F(SyncSetupWizardTest, DISABLED_DiscreteRunChooseDataTypes) {
SKIP_TEST_ON_MACOSX();
// For a discrete run, we need to have ran through setup once.
wizard_->Step(SyncSetupWizard::GAIA_LOGIN);
wizard_->Step(SyncSetupWizard::GAIA_SUCCESS);
wizard_->Step(SyncSetupWizard::DONE);
test_window_->CloseDialog();
EXPECT_TRUE(test_window_->TestAndResetWasShowHTMLDialogCalled());
wizard_->Step(SyncSetupWizard::CONFIGURE);
EXPECT_TRUE(test_window_->TestAndResetWasShowHTMLDialogCalled());
EXPECT_EQ(SyncSetupWizard::DONE, test_window_->flow()->end_state_);
wizard_->Step(SyncSetupWizard::DONE);
test_window_->CloseDialog();
EXPECT_FALSE(wizard_->IsVisible());
}
TEST_F(SyncSetupWizardTest,
DISABLED_DiscreteRunChooseDataTypesAbortedByPendingClear) {
SKIP_TEST_ON_MACOSX();
// For a discrete run, we need to have ran through setup once.
wizard_->Step(SyncSetupWizard::GAIA_LOGIN);
wizard_->Step(SyncSetupWizard::GAIA_SUCCESS);
wizard_->Step(SyncSetupWizard::DONE);
test_window_->CloseDialog();
EXPECT_TRUE(test_window_->TestAndResetWasShowHTMLDialogCalled());
wizard_->Step(SyncSetupWizard::CONFIGURE);
EXPECT_TRUE(test_window_->TestAndResetWasShowHTMLDialogCalled());
EXPECT_EQ(SyncSetupWizard::DONE, test_window_->flow()->end_state_);
wizard_->Step(SyncSetupWizard::SETUP_ABORTED_BY_PENDING_CLEAR);
EXPECT_EQ(SyncSetupWizard::SETUP_ABORTED_BY_PENDING_CLEAR,
test_window_->flow()->current_state_);
test_window_->CloseDialog();
EXPECT_FALSE(wizard_->IsVisible());
}
TEST_F(SyncSetupWizardTest, DISABLED_DiscreteRunGaiaLogin) {
SKIP_TEST_ON_MACOSX();
DictionaryValue dialog_args;
// For a discrete run, we need to have ran through setup once.
wizard_->Step(SyncSetupWizard::GAIA_LOGIN);
wizard_->Step(SyncSetupWizard::GAIA_SUCCESS);
wizard_->Step(SyncSetupWizard::SETTING_UP);
wizard_->Step(SyncSetupWizard::DONE);
test_window_->CloseDialog();
EXPECT_TRUE(test_window_->TestAndResetWasShowHTMLDialogCalled());
wizard_->Step(SyncSetupWizard::GAIA_LOGIN);
EXPECT_EQ(SyncSetupWizard::GAIA_SUCCESS, test_window_->flow()->end_state_);
AuthError invalid_gaia(AuthError::INVALID_GAIA_CREDENTIALS);
service_->set_auth_state(kTestUser, invalid_gaia);
wizard_->Step(SyncSetupWizard::GAIA_LOGIN);
EXPECT_TRUE(wizard_->IsVisible());
SyncSetupFlow::GetArgsForGaiaLogin(service_, &dialog_args);
EXPECT_EQ(5U, dialog_args.size());
std::string iframe_to_show;
dialog_args.GetString("iframeToShow", &iframe_to_show);
EXPECT_EQ("login", iframe_to_show);
std::string actual_user;
dialog_args.GetString("user", &actual_user);
EXPECT_EQ(kTestUser, actual_user);
int error = -1;
dialog_args.GetInteger("error", &error);
EXPECT_EQ(static_cast<int>(AuthError::INVALID_GAIA_CREDENTIALS), error);
service_->set_auth_state(kTestUser, AuthError::None());
wizard_->Step(SyncSetupWizard::GAIA_SUCCESS);
EXPECT_TRUE(test_window_->TestAndResetWasShowHTMLDialogCalled());
}
#undef SKIP_TEST_ON_MACOSX
| 37.709497 | 80 | 0.749185 | [
"model"
] |
72f1f7641c6906c15de0ebb2b64e0af858b882df | 8,293 | cpp | C++ | cluster_points.cpp | luccosta/tmr-hdl-writer | 9971809b20d69fcc76a827ebf57b9937d7f44b4e | [
"MIT"
] | null | null | null | cluster_points.cpp | luccosta/tmr-hdl-writer | 9971809b20d69fcc76a827ebf57b9937d7f44b4e | [
"MIT"
] | null | null | null | cluster_points.cpp | luccosta/tmr-hdl-writer | 9971809b20d69fcc76a827ebf57b9937d7f44b4e | [
"MIT"
] | null | null | null | #include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <utility>
#include <memory>
#include <iterator>
#include <cstdlib>
#include <cmath>
using namespace std;
class Circuito;
struct Matrices{double M[2][2];};
struct Matriz
{
double SF[4];
};
struct l_porta
{
string outp, gate, name;
vector <string> inps;
vector <string> tagL;
bool clusteRoot;
};
class Circuito
{
friend class Porta_Logica;
double R; // Confiabilidade total do circuito
vector <string> input;
map <string, Matriz> output; // Estruturas associativas com a chave sendo o nome
map <string, Matriz> wire; // dado ao elemento e o valor sendo o apontador espec�fico
vector <double> coeficiente; // Coeficiente an de cada funout
vector <l_porta> lp; // Linhas de Porta
vector <string> funout_r; // Funouts reconvergentes
vector <string> CRL; // Cluster Root List
vector <string> gates; // Portas no invent�rio "models"
// Auxiliares
vector <string> output_aux;
vector <string> wire_aux;
public:
Circuito(string arq){
R = 0;
setup();
LeituraNetlist(arq);
}
void setup();
void LeituraNetlist(string);
};
void Circuito::setup(){
ifstream mod;
mod.open("models.txt");
string aux, line, prev;
if (mod.is_open()){ // Coleta das portas no invent�rio
mod >> aux;
while(getline(mod, line)){
if (prev != aux)
gates.push_back(aux);
prev = aux;
mod >> aux;
}
}
}
void Circuito::LeituraNetlist(string arq){
ifstream nl;
nl.open(arq.data());
string aux, aux2, aux3;
string sub; // String tempor�ria utilizada para armazenar substrings que diminuem gradualmente
int n_entradas, start = -1;
unsigned int fixo, it, add = 0;
char final;
string porta, saida;
l_porta tp; // Cada elemento � correspondente a uma linha do Verilog (tempor�rio)
if (nl.is_open())
{
while(getline(nl, aux))
{
if ((aux[0] == '/' && aux[1] == '/') || aux == "") {start++;}
// Coment�rio Linha em branco
else {
if (aux[0]!= ' ')
aux2 = aux.substr(0, aux.find(' '));
aux3 = '.';
if (aux2 == "module"){start++;}
// Desnecess�rio. Somente necess�rio para reutiliza��o no Verilog
if (aux2 == "input" || aux2 == "output" || aux2 == "wire"){ // Inicializa��o dos elementos b�sicos
start++;
if (aux[0] != ' ')
it = aux.find(' ') + 1;
else if (aux2 == "wire")
it = 5;
else if (aux2 == "input")
it = 6;
else if (aux2 == "output")
it = 7;
fixo = it;
while(it < aux.find_last_of(',') && aux.find_last_of(',') != -1){
sub = aux.substr(it, aux.size() - it);
aux3 = sub.substr(0, sub.find(','));
if (aux2 == "input")
input.push_back(aux3);
if (aux2 == "output")
output_aux.push_back(aux3);
if (aux2 == "wire")
wire_aux.push_back(aux3);
it = fixo + sub.find_first_of(',') + 1;
fixo = it;
}
if (aux.find(';') != -1){ // Leitura do ultimo elemento antes do ;
sub = aux.substr(it, aux.size() - it);
if (aux2 == "input")
input.push_back(sub.substr(0, sub.size() - 1));
if (aux2 == "output")
output_aux.push_back(sub.substr(0, sub.size() - 1));
if (aux2 == "wire")
wire_aux.push_back(sub.substr(0, sub.size() - 1));
}
}
// Desenvolvimento das portas
for(vector <string>::iterator itr = gates.begin(); itr != gates.end(); ++itr)
if (aux2 == *itr){
tp.inps.clear();
if (aux2 == "buf") // GAMBIARRA
add = 1;
it = aux.find(' ') + 1;
sub = aux.substr(it, aux.size() - it);
porta = sub.substr(0, sub.find(" ")); // Nome da porta l�gica
n_entradas = - 48 + (int)porta[aux2.size() + add]; // N�mero de entradas da porta l�gica
it = sub.find(' ') + 2;
sub = sub.substr(it, aux.size() - it); // Elimina��o do nome da porta e do primeiro parentese
saida = sub.substr(0, sub.find(','));
add = 0;
tp.gate = aux2;
tp.name = porta;
tp.outp = saida;
// ARGUMENTOS DE ENTRADA
for (int i = 0; i < n_entradas; i++){
if (i == n_entradas - 1)
final = ')';
else
final = ',';
it = sub.find(',') + 2;
sub = sub.substr(it, sub.size() - it);
aux3 = sub.substr(0, sub.find(final));
tp.inps.push_back(aux3);
}
lp.push_back(tp);
}
}
}
}
// Captura de funouts reconvergentes
for(vector <l_porta>::iterator busca = lp.begin(); busca !=lp.end() - 1; ++busca)
for(vector <l_porta>::iterator rpeat = busca+1; rpeat !=lp.end(); ++rpeat)
for(vector <string>::iterator it = (*busca).inps.begin(); it !=(*busca).inps.end(); ++it)
for(vector <string>::iterator itr = (*rpeat).inps.begin(); itr !=(*rpeat).inps.end(); ++itr)
if (*it == *itr)
funout_r.push_back(*it);
// Apagando repetidos
//if (!funout_r.empty())
// for(vector <string>::iterator itra = funout_r.begin(); itra !=funout_r.end() - 1; ++itra)
// for(vector <string>::iterator itr = itra + 1; itr !=funout_r.end(); ++itr)
// if (*itra == *itr){
// funout_r.erase(itr);
// }
// CLUSTERIZA��O
bool out, alredyExist;
map <string, vector<string> > tagMemory; // <outp, pr�ximos n�s>
vector <string> auxS;
// Forma��o tagMemory
for (vector<l_porta>::reverse_iterator it = lp.rbegin(); it != lp.rend(); ++it)
{
for (vector<string>::iterator itra = (it->inps).begin(); itra != (it->inps).end(); ++itra){
alredyExist = false;
for(map<string, vector<string> >::iterator itr = tagMemory.begin(); itr != tagMemory.end(); ++itr)
if (*itra == itr -> first){
alredyExist=true;
(itr->second).push_back(it->outp);
}
if (!alredyExist){
auxS.push_back(it->outp);
tagMemory.insert(pair<string, vector<string> > (*itra, auxS));
auxS.clear();
}
}
}
// Forma��o tagList
for (vector<l_porta>::reverse_iterator it = lp.rbegin(); it != lp.rend(); ++it)
{
out = false;
for (vector<string>::iterator iter = output_aux.begin(); iter != output_aux.end(); ++iter)
if (it->outp == *iter)
out = true;
if (out) {
it->tagL.push_back(it->outp);
}
else {
for (map<string, vector<string> >::iterator itra = tagMemory.begin(); itra != tagMemory.end(); ++itra){
if (itra -> first == it->outp)
for (vector<string>::iterator ite = (itra->second).begin(); ite != (itra->second).end(); ++ite)
for (vector<l_porta>::iterator itr = (it+1).base()+1; itr != lp.end(); ++itr)
if (itr->outp == *ite)
{
for(vector<string>::iterator iter = (itr->tagL).begin(); iter != (itr->tagL).end(); ++iter)
(it->tagL).push_back(*iter);
}
}
for(vector<string>::iterator iter = (it->tagL).begin(); iter != (it->tagL).end(); ++iter) // Exclus�o dos repetidos
{
alredyExist = false;
for(vector<string>::iterator itr = auxS.begin(); itr != auxS.end(); ++itr)
if (*iter == *itr)
alredyExist = true;
if(!alredyExist){
auxS.push_back(*iter);
}
}
it->tagL = auxS;
auxS.clear();
}
}
// Forma��o Cluster Root List
for (vector<l_porta>::reverse_iterator it = lp.rbegin(); it != lp.rend(); ++it)
{
it->clusteRoot = false;
out = false;
for (vector<string>::iterator iter = output_aux.begin(); iter != output_aux.end(); ++iter)
if (it->outp == *iter)
out = true;
if (out) {
CRL.push_back(it->outp);
it->clusteRoot = true;
}
else {
it->clusteRoot = true;
for (map<string, vector<string> >::iterator itra = tagMemory.begin(); itra != tagMemory.end(); ++itra)
if (itra -> first == it->outp)
for (vector<string>::iterator ite = (itra->second).begin(); ite != (itra->second).end(); ++ite)
for (vector<l_porta>::iterator itr = (it+1).base()+1; itr != lp.end(); ++itr)
if (itr->outp == *ite)
if (((it->tagL).size() == (itr->tagL).size())) // Tamanho da TL do pai igual a do filho
it->clusteRoot = false;
if (it->clusteRoot == true)
CRL.push_back(it->outp);
}
}
cout << "Cluster Root List: ";
for(vector<string>::iterator iter = CRL.begin(); iter != CRL.end(); ++iter)
cout << *iter << " ";
cout << endl;
}
int main(int argc, char** argv)
{
string arq;
cout << fixed;
cout << setprecision(6);
arq = argv[1]; // Definição do arquivo verilog
Circuito Main(arq);
return 0;
} | 27.922559 | 118 | 0.580851 | [
"vector"
] |
72f247a16e94ded8963658f7d620b30b83efeb18 | 799 | cpp | C++ | DP div250/PalindromicSubstringsDiv2.cpp | fastestmk/Competitive-Programming-Solutions | cbd211337ede4a26e3bb5c0b2c271a760b468da8 | [
"MIT"
] | null | null | null | DP div250/PalindromicSubstringsDiv2.cpp | fastestmk/Competitive-Programming-Solutions | cbd211337ede4a26e3bb5c0b2c271a760b468da8 | [
"MIT"
] | null | null | null | DP div250/PalindromicSubstringsDiv2.cpp | fastestmk/Competitive-Programming-Solutions | cbd211337ede4a26e3bb5c0b2c271a760b468da8 | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
using namespace std;
class PalindromicSubstringsDiv2{
public:
int count(vector<string>, vector<string>);
};
int PalindromicSubstringsDiv2::count(vector<string> S1, vector<string> S2){
string res;
for(int i = 0; i < S1.size(); ++i){
res += S1[i];
}
for(int i = 0; i < S2.size(); ++i){
res += S2[i];
}
int n = res.size();
int ans = 0;
for(int i = 0; i < n; ++i){
for(int j = 0; j <= i && j+i < n; ++j){
if(res[i-j] == res[i+j])
ans++;
else
break;
}
for(int j = 0; j <= i && j+i+1 < n; ++j){
if(res[i-j] == res[i+j+1])
ans++;
else
break;
}
}
return ans;
}
| 19.975 | 75 | 0.429287 | [
"vector"
] |
72f3c7d38df4a9adeafa7f7b756da98de3b35835 | 660 | cpp | C++ | PAT/B1013.cpp | iphelf/Programming-Practice | 2a95bb7153957b035427046b250bf7ffc6b00906 | [
"WTFPL"
] | null | null | null | PAT/B1013.cpp | iphelf/Programming-Practice | 2a95bb7153957b035427046b250bf7ffc6b00906 | [
"WTFPL"
] | null | null | null | PAT/B1013.cpp | iphelf/Programming-Practice | 2a95bb7153957b035427046b250bf7ffc6b00906 | [
"WTFPL"
] | null | null | null | #include<stdio.h>
#include<string.h>
#include<vector>
using namespace std;
const int MAXN=1e6;
bool isPrime[MAXN+1];
vector<int> prime;
int main(void){
// freopen("in.txt","r",stdin);
int M,N;
scanf("%d%d",&M,&N);
memset(isPrime,true,sizeof isPrime);
isPrime[1]=false;
prime.push_back(0);
for(int i=2;i<=MAXN;i++) if(isPrime[i]){
for(int j=i*2;j<=MAXN;j+=i) isPrime[j]=false;
prime.push_back(i);
}
int len=N-M+1;
for(int i=0;i<len;i++)
printf("%d%c",prime[i+M],((i%10==9||i==len-1)?'\n':' '));
return 0;
}
/*
5 27
11 13 17 19 23 29 31 37 41 43
47 53 59 61 67 71 73 79 83 89
97 101 103
*/
| 18.857143 | 65 | 0.569697 | [
"vector"
] |
72f8e9a5c8ba14bc2e70e26989d5ca76ed8227fe | 15,773 | hpp | C++ | stan/math/prim/err/check_flag_sundials.hpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | stan/math/prim/err/check_flag_sundials.hpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | stan/math/prim/err/check_flag_sundials.hpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_MATH_PRIM_ERR_CHECK_FLAG_SUNDIALS_HPP
#define STAN_MATH_PRIM_ERR_CHECK_FLAG_SUNDIALS_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err/domain_error.hpp>
#include <kinsol/kinsol.h>
#include <cvodes/cvodes.h>
#include <array>
namespace stan {
namespace math {
#define CHECK_CVODES_CALL(call) cvodes_check(call, #call)
#define CHECK_IDAS_CALL(call) idas_check(call, #call)
#define CHECK_KINSOL_CALL(call) kinsol_check(call, #call)
/**
* Map cvodes error flag to acutally error msg. The most frequent
* errors are put at the top. An alternative would be to use std::map
* but in our case the difference would be negligible. Note that we
* don't use CVGetReturnFlagName function to retrieve the constant
* because sanitizer indicates it contains mem leak.
*
* @param flag
*
* @return error msg string constant and actuall informative msg
*/
inline std::array<std::string, 2> cvodes_flag_msg(int flag) {
std::array<std::string, 2> msg;
switch (flag) {
case -1:
msg = {"CV_TOO_MUCH_WORK",
"The solver took mxstep internal steps but could not reach tout"};
break; // NOLINT
case -2:
msg = {"CV_TOO_MUCH_ACC",
"The solver could not satisfy the accuracy demanded by the user "
"for some internal step"};
break; // NOLINT
case -3:
msg = {"CV_ERR_FAILURE",
"Error test failures occurred too many times during one internal "
"time step or minimum step size was reached"};
break; // NOLINT
case -4:
msg = {"CV_CONV_FAILURE",
"Convergence test failures occurred too many times during one "
"internal time step or minimum step size was reached"};
break; // NOLINT
case -8:
msg = {"CV_RHSFUNC_FAIL",
"The right-hand side function failed in an unrecoverable manner"};
break; // NOLINT
case -9:
msg = {"CV_FIRST_RHSFUNC_ERR",
"The right-hand side function failed at the first call"};
break; // NOLINT
case -10:
msg = {"CV_REPTD_RHSFUNC_ERR",
"The right-hand side function had repetead recoverable errors"};
break; // NOLINT
case -11:
msg = {"CV_UNREC_RHSFUNC_ERR",
"The right-hand side function had a recoverable error, but no "
"recovery is possible"};
break; // NOLINT
case -27:
msg = {"CV_TOO_CLOSE",
"The output and initial times are too close to each other"};
break; // NOLINT
default:
switch (flag) {
case -5:
msg = {"CV_LINIT_FAIL",
"The linear solver's initialization function failed"};
break; // NOLINT
case -6:
msg = {"CV_LSETUP_FAIL",
"The linear solver's setup function failed in an "
"unrecoverable manner"};
break; // NOLINT
case -7:
msg = {"CV_LSOLVE_FAIL",
"The linear solver's solve function failed in an "
"unrecoverable manner"};
break; // NOLINT
case -20:
msg = {"CV_MEM_FAIL", "A memory allocation failed"};
break; // NOLINT
case -21:
msg = {"CV_MEM_NULL", "The cvode_mem argument was NULL"};
break; // NOLINT
case -22:
msg = {"CV_ILL_INPUT", "One of the function inputs is illegal"};
break; // NOLINT
case -23:
msg = {"CV_NO_MALLOC",
"The CVODE memory block was not allocated by a call to "
"CVodeMalloc"};
break; // NOLINT
case -24:
msg = {"CV_BAD_K",
"The derivative order k is larger than the order used"};
break; // NOLINT
case -25:
msg = {"CV_BAD_T", "The time t s outside the last step taken"};
break; // NOLINT
case -26:
msg = {"CV_BAD_DKY", "The output derivative vector is NULL"};
break; // NOLINT
case -40:
msg = {"CV_BAD_IS",
"The sensitivity index is larger than the number of "
"sensitivities computed"};
break; // NOLINT
case -41:
msg = {"CV_NO_SENS",
"Forward sensitivity integration was not activated"};
break; // NOLINT
case -42:
msg = {"CV_SRHSFUNC_FAIL",
"The sensitivity right-hand side function failed in an "
"unrecoverable manner"};
break; // NOLINT
case -43:
msg = {"CV_FIRST_SRHSFUNC_ER",
"The sensitivity right-hand side function failed at the first "
"call"};
break; // NOLINT
case -44:
msg = {"CV_REPTD_SRHSFUNC_ER",
"The sensitivity ight-hand side function had repetead "
"recoverable errors"};
break; // NOLINT
case -45:
msg = {"CV_UNREC_SRHSFUNC_ER",
"The sensitivity right-hand side function had a recoverable "
"error, but no recovery is possible"};
break; // NOLINT
case -101:
msg = {"CV_ADJMEM_NULL", "The cvadj_mem argument was NULL"};
break; // NOLINT
case -103:
msg = {"CV_BAD_TB0",
"The final time for the adjoint problem is outside the "
"interval over which the forward problem was solved"};
break; // NOLINT
case -104:
msg = {"CV_BCKMEM_NULL",
"The cvodes memory for the backward problem was not created"};
break; // NOLINT
case -105:
msg = {"CV_REIFWD_FAIL",
"Reinitialization of the forward problem failed at the first "
"checkpoint"};
break; // NOLINT
case -106:
msg = {
"CV_FWD_FAIL",
"An error occured during the integration of the forward problem"};
break; // NOLINT
case -107:
msg = {"CV_BAD_ITASK", "Wrong task for backward integration"};
break; // NOLINT
case -108:
msg = {"CV_BAD_TBOUT",
"The desired output time is outside the interval over which "
"the forward problem was solved"};
break; // NOLINT
case -109:
msg = {"CV_GETY_BADT", "Wrong time in interpolation function"};
break; // NOLINT
}
}
return msg;
}
/**
* Throws a std::runtime_error exception when a Sundial function fails
* (i.e. returns a negative flag)
*
* @param flag Error flag
* @param func_name Name of the function that returned the flag
* @throw <code>std::runtime_error</code> if the flag is negative
*/
inline void cvodes_check(int flag, const char* func_name) {
if (flag < 0) {
std::ostringstream ss;
ss << func_name << " failed with error flag " << flag << ": \n"
<< cvodes_flag_msg(flag).at(1) << ".";
if (flag == -1 || flag == -4) {
throw std::domain_error(ss.str());
} else {
throw std::runtime_error(ss.str());
}
}
}
inline std::array<std::string, 2> idas_flag_msg(int flag) {
std::array<std::string, 2> msg;
switch (flag) {
case -1:
msg = {"IDA_TOO_MUCH_WORK",
"The solver took mxstep internal steps but could not reach tout."};
break; // NOLINT
case -2:
msg = {"IDA_TOO_MUCH_ACC",
"The solver could not satisfy the accuracy demanded by the user "
"for some internal step."};
break; // NOLINT
case -3:
msg = {"IDA_ERR_FAIL",
"Error test failures occurred too many times during one internal "
"time step or minimum step size was reached."};
break; // NOLINT
case -4:
msg = {"IDA_CONV_FAIL",
"Convergence test failures occurred too many times during one "
"internal time step or minimum step size was reached."};
break; // NOLINT
case -5:
msg = {"IDA_LINIT_FAIL",
"The linear solver’s initialization function failed."};
break; // NOLINT
case -6:
msg = {"IDA_LSETUP_FAIL",
"The linear solver’s setup function failed in an unrecoverable "
"manner."};
break; // NOLINT
case -7:
msg = {"IDA_LSOLVE_FAIL",
"The linear solver’s solve function failed in an unrecoverable "
"manner."};
break; // NOLINT
case -8:
msg = {"IDA_RES_FAIL",
"The user-provided residual function failed in an unrecoverable "
"manner."};
break; // NOLINT
case -9:
msg = {"IDA_REP_RES_FAIL",
"The user-provided residual function repeatedly returned a "
"recoverable error flag, but the solver was unable to recover."};
break; // NOLINT
case -10:
msg = {"IDA_RTFUNC_FAIL",
"The rootfinding function failed in an unrecoverable manner."};
break; // NOLINT
case -11:
msg = {"IDA_CONSTR_FAIL",
"The inequality constraints were violated and the solver was "
"unable to recover."};
break; // NOLINT
case -12:
msg = {"IDA_FIRST_RES_FAIL",
"The user-provided residual function failed recoverably on the "
"first call."};
break; // NOLINT
case -13:
msg = {"IDA_LINESEARCH_FAIL", "The line search failed."};
break; // NOLINT
default:
switch (flag) {
case -14:
msg = {"IDA_NO_RECOVERY",
"The residual function, linear solver setup function, or "
"linear solver solve function had a recoverable failure, but "
"IDACalcIC could not recover."};
break; // NOLINT
case -15:
msg = {"IDA_NLS_INIT_FAIL",
"The nonlinear solver’s init routine failed."};
break; // NOLINT
case -16:
msg = {"IDA_NLS_SETUP_FAIL",
"The nonlinear solver’s setup routine failed."};
break; // NOLINT
case -20:
msg = {"IDA_MEM_NULL", "The ida mem argument was NULL."};
break; // NOLINT
case -21:
msg = {"IDA_MEM_FAIL", "A memory allocation failed."};
break; // NOLINT
case -22:
msg = {"IDA_ILL_INPUT", "One of the function inputs is illegal."};
break; // NOLINT
case -23:
msg = {"IDA_NO_MALLOC",
"The idas memory was not allocated by a call to IDAInit."};
break; // NOLINT
case -24:
msg = {"IDA_BAD_EWT", "Zero value of some error weight component."};
break; // NOLINT
case -25:
msg = {"IDA_BAD_K", "The k-th derivative is not available."};
break; // NOLINT
case -26:
msg = {"IDA_BAD_T", "The time t is outside the last step taken."};
break; // NOLINT
case -27:
msg = {
"IDA_BAD_DKY",
"The vector argument where derivative should be stored is NULL."};
break; // NOLINT
case -30:
msg = {"IDA_NO_QUAD", "Quadratures were not initialized."};
break; // NOLINT
case -31:
msg = {"IDA_QRHS_FAIL",
"The user-provided right-hand side function for quadratures "
"failed in an unrecoverable manner."};
break; // NOLINT
case -32:
msg = {"IDA_FIRST_QRHS_ERR",
"The user-provided right-hand side function for quadratures "
"failed -in an unrecoverable manner on the first call."};
break; // NOLINT
case -33:
msg = {"IDA_REP_QRHS_ERR",
"The user-provided right-hand side repeatedly returned a re- "
"coverable error flag, but the solver was unable to recover."};
break; // NOLINT
case -40:
msg = {"IDA_NO_SENS", "Sensitivities were not initialized."};
break; // NOLINT
case -41:
msg = {"IDA_SRES_FAIL",
"The user-provided sensitivity residual function failed in an "
"unrecoverable manner."};
break; // NOLINT
case -42:
msg = {"IDA_REP_SRES_ERR",
"The user-provided sensitivity residual function repeatedly "
"re- turned a recoverable error flag, but the solver was "
"unable to recover."};
break; // NOLINT
case -43:
msg = {"IDA_BAD_IS", "The sensitivity identifier is not valid."};
break; // NOLINT
case -50:
msg = {"IDA_NO_QUADSENS",
"Sensitivity-dependent quadratures were not initialized."};
break; // NOLINT
case -51:
msg = {"IDA_QSRHS_FAIL",
"The user-provided sensitivity-dependent quadrature right- "
"hand side function failed in an unrecoverable manner."};
break; // NOLINT
case -52:
msg = {"IDA_FIRST_QSRHS_ERR",
"The user-provided sensitivity-dependent quadrature right- "
"hand side function failed in an unrecoverable manner on the "
"first call."};
break; // NOLINT
case -53:
msg = {"IDA_REP_QSRHS_ERR",
"The user-provided sensitivity-dependent quadrature right- "
"hand side repeatedly returned a recoverable error flag, but "
"the solver was unable to recover."};
break; // NOLINT
}
}
return msg;
}
inline void idas_check(int flag, const char* func_name) {
if (flag < 0) {
std::ostringstream ss;
ss << func_name << " failed with error flag " << flag << ": \n"
<< idas_flag_msg(flag).at(1);
if (flag == -1 || flag == -4) {
throw std::domain_error(ss.str());
} else {
throw std::runtime_error(ss.str());
}
}
}
/**
* Throws an exception message when the functions in KINSOL
* fails. "KINGetReturnFlagName()" from SUNDIALS has a mem leak bug so
* until it's fixed we cannot use it to extract flag error string.
*
* @param flag Error flag
* @param func_name calling function name
* @throw <code>std::runtime_error</code> if the flag is negative.
*/
inline void kinsol_check(int flag, const char* func_name) {
if (flag < 0) {
std::ostringstream ss;
ss << "algebra_solver failed with error flag " << flag << ".";
throw std::runtime_error(ss.str());
}
}
/**
* Throws an exception message when the KINSol() call fails.
* When the exception is caused
* by a tuning parameter the user controls, gives a specific
* error.
*
* @param flag Error flag
* @param func_name calling function name
* @param max_num_steps max number of nonlinear iterations.
* @throw <code>std::runtime_error</code> if the flag is negative.
* @throw <code>std::domain_error</code> if the flag indicates max
* number of steps is exceeded.
*/
inline void kinsol_check(int flag, const char* func_name,
long int max_num_steps) { // NOLINT(runtime/int)
std::ostringstream ss;
if (flag == -6) {
domain_error("algebra_solver", "maximum number of iterations",
max_num_steps, "(", ") was exceeded in the solve.");
} else if (flag == -11) {
ss << "The linear solver’s setup function failed "
<< "in an unrecoverable manner.";
throw std::runtime_error(ss.str());
} else if (flag < 0) {
ss << "algebra_solver failed with error flag " << flag << ".";
throw std::runtime_error(ss.str());
}
}
} // namespace math
} // namespace stan
#endif
| 36.852804 | 80 | 0.564192 | [
"vector"
] |
f40141fe0fe9317b2996606ba327b6f0326bc950 | 2,183 | cpp | C++ | solutions/LeetCode/C++/757.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 854 | 2018-11-09T08:06:16.000Z | 2022-03-31T06:05:53.000Z | solutions/LeetCode/C++/757.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 29 | 2019-06-02T05:02:25.000Z | 2021-11-15T04:09:37.000Z | solutions/LeetCode/C++/757.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 347 | 2018-12-23T01:57:37.000Z | 2022-03-12T14:51:21.000Z | __________________________________________________________________________________________________
sample 32 ms submission
static const auto _ = []() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
class Solution {
public:
static bool interval_compare(const vector <int>& interval_1, const vector <int>& interval_2)
{
return interval_1[1] < interval_2[1] || (interval_1[1] == interval_2[1] && interval_1[0] < interval_2[0]);
}
int intersectionSizeTwo(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end(), interval_compare);
int ans = 0, second_last = -1, last = -1;
for(const auto& interval : intervals)
{
if(interval[0] > last)
{
last = interval[1];
second_last = interval[1] - 1;
ans += 2;
}
else if(interval[0] > second_last)
{
if(last == interval[1])
second_last = interval[1] - 1;
else
{
second_last = last;
last = interval[1];
}
ans++;
}
}
return ans;
}
};
__________________________________________________________________________________________________
sample 15176 kb submission
class Solution {
public:
static bool cmp (const vector<int>& a, const vector<int>& b) {
if (a[1]==b[1])
return a[0]>b[0];
else
return a[1]<b[1];
}
int intersectionSizeTwo(vector<vector<int>>& intervals) {
int ans=0, p1=-1, p2=-1, N=intervals.size();
sort(intervals.begin(),intervals.end(),cmp);
for (int i=0;i<N;i++) {
if (intervals[i][0]<=p1)
continue;
if (intervals[i][0]>p2) {
ans+=2;
p2=intervals[i][1];
p1=p2-1;
}
else {
++ans;
p1=p2;
p2=intervals[i][1];
}
}
return ans;
}
};
__________________________________________________________________________________________________
| 29.90411 | 114 | 0.543747 | [
"vector"
] |
f40bdc1849a7f42d0ff30b1ed2866f46b93fc5af | 10,063 | cpp | C++ | rest-server/src/services/admin_dao.cpp | OS-WASABI/CADG | b214edff82d4238e51569a42a6bdfab6806d768f | [
"BSD-3-Clause"
] | null | null | null | rest-server/src/services/admin_dao.cpp | OS-WASABI/CADG | b214edff82d4238e51569a42a6bdfab6806d768f | [
"BSD-3-Clause"
] | 22 | 2018-10-26T17:30:24.000Z | 2019-04-15T23:38:18.000Z | rest-server/src/services/admin_dao.cpp | OS-WASABI/CADG | b214edff82d4238e51569a42a6bdfab6806d768f | [
"BSD-3-Clause"
] | 1 | 2019-03-23T16:02:17.000Z | 2019-03-23T16:02:17.000Z | // Copyright 2018 Vaniya Agrawal, Ross Arcemont, Kristofer Hoadley,
// Shawn Hulce, Michael McCulley
/**
* Implementation of AdminDao.
*
* @file admin_dao.cpp
* @authors Kristofer Hoadley, Micheal McCulley
* @date November, 2018
*/
#include <string>
#include <vector>
#include "admin_dao.hpp"
#include "nanodbc.hpp"
namespace cadg_rest {
AdminDao& AdminDao::Instance() {
static AdminDao instance;
return instance;
}
AdminDao::AdminDao() : logger(Logger::Instance()) {
std::string db_admin_name__ = getEnvVar("DB_ADMIN_NAME");
logger.Log(LogLevel::INFO, "The env db_admin_name__ is: " + db_admin_name__);
db_admin_table__ = getEnvVar("DB_ADMIN_TABLE");
logger.Log(LogLevel::INFO, "The env db_admin_table__ is: " + db_admin_table__);
std::string db_password = getEnvVar("DB_PASSWORD");
logger.Log(LogLevel::INFO, "The env db_password is: " + db_password);
std::string db_port = getEnvVar("DB_PORT");
if (db_port.empty()) {
db_port = "3306"; // default port
}
logger.Log(LogLevel::INFO, "The env db_port is: " + db_port);
std::string db_server = getEnvVar("DB_SERVER");
if (db_server.empty()) {
db_server = "127.0.0.1"; // localhost
}
std::string salt__ = getEnvVar("ADMIN_SALT");
logger.Log(LogLevel::INFO, "The env db_server is: " + db_server);
std::string db_uid = getEnvVar("DB_UID");
logger.Log(LogLevel::INFO, "The env db_uid is: " + db_uid);
conn_str__ = "Driver={MySQL8Driver};Server="+ db_server +";Port="+ db_port +";Database="
+ db_admin_name__ +";Uid="+ db_uid +";Pwd="+ db_password +";";
logger.Log(LogLevel::INFO, "The connection string is: " + conn_str__);
}
std::optional<std::vector<Admin>> AdminDao::GetAdmins() {
try {
nanodbc::connection connection(conn_str__);
nanodbc::result results = execute(connection, NANODBC_TEXT(
std::string("select id, first_name, last_name, username, email, ") +
std::string("phone, address, country, state_region, zip from ") +
db_admin_table__ + ";"));
std::vector<Admin> db_admins;
while (results.next()) {
db_admins.push_back(Admin {
results.get<int>(0, 0),
results.get<std::string>(1, ""),
results.get<std::string>(2, ""),
results.get<std::string>(3, ""),
results.get<std::string>(4, ""),
results.get<std::string>(5, ""),
results.get<std::string>(6, ""),
results.get<std::string>(7, ""),
results.get<std::string>(8, ""),
results.get<std::string>(9, "")});
}
return db_admins;
} catch (std::exception& e) {
logger.Log(LogLevel::ERR, e.what(), "AdminDao", "GetAdmins");
return std::nullopt;
}
}
std::optional<std::vector<Admin>> AdminDao::GetAdminsByName(const std::string& name) {
// TODO(Kris): implement GetAdminsByName
return std::nullopt;
}
std::optional<Admin> AdminDao::GetAdminByID(int id) {
try {
nanodbc::connection connection(conn_str__);
nanodbc::statement statement(connection);
prepare(statement, NANODBC_TEXT(
std::string("SELECT id, first_name, last_name, username, email, ") +
std::string("phone, address, country, state_region, zip ") +
std::string("FROM ")+ db_admin_table__ +
std::string(" WHERE id = ?;")));
statement.bind(0, &id);
auto results = execute(statement);
if (results.next()) {
return Admin {
results.get<int>(0, 0),
results.get<std::string>(1, ""),
results.get<std::string>(2, ""),
results.get<std::string>(3, ""),
results.get<std::string>(4, ""),
results.get<std::string>(5, ""),
results.get<std::string>(6, ""),
results.get<std::string>(7, ""),
results.get<std::string>(8, ""),
results.get<std::string>(9, "")};
} else {
Admin admin;
return admin; // empty admin, or not found. id = 0.
}
} catch (std::exception& e) {
logger.Log(LogLevel::ERR, e.what(), "AdminDao", "GetAdmins");
return std::nullopt;
}
return std::nullopt;
}
std::optional<bool> AdminDao::RemoveAdmin(int id) {
// TODO(Kris): implement RemoveAdmin
return std::nullopt;
}
std::optional<bool> AdminDao::AddAdmin(Admin admin) {
logger.Log(LogLevel::INFO, "AdminDao", "AddAdmin", std::string("Admin id: ")+ std::to_string(admin.id) +
", first_name: "+ admin.first_name +
", last_name: "+ admin.first_name +
", username: "+ admin.username +
", email: "+ admin.email +
", phone: "+ admin.phone +
", address: "+ admin.address +
", country: "+ admin.country +
", state_region: "+ admin.state_region +
", zip: "+ admin.zip);
try {
nanodbc::connection connection(conn_str__);
nanodbc::statement statement(connection);
prepare(statement, NANODBC_TEXT("insert into "+ db_admin_table__ +
" (first_name, last_name, username, email, phone, address, country, state_region, zip)"+
" values(?,?,?,?,?,?,?,?,?);"));
nanodbc::string const first_name = NANODBC_TEXT(admin.first_name);
statement.bind(0, first_name.c_str());
nanodbc::string const last_name = NANODBC_TEXT(admin.last_name);
statement.bind(1, last_name.c_str());
nanodbc::string const username = NANODBC_TEXT(admin.username);
statement.bind(2, username.c_str());
nanodbc::string const email = NANODBC_TEXT(admin.email);
statement.bind(3, email.c_str());
nanodbc::string const phone = NANODBC_TEXT(admin.phone);
statement.bind(4, phone.c_str());
nanodbc::string const address = NANODBC_TEXT(admin.address);
statement.bind(5, address.c_str());
nanodbc::string const country = NANODBC_TEXT(admin.country);
statement.bind(6, country.c_str());
nanodbc::string const state_region = NANODBC_TEXT(admin.state_region);
statement.bind(7, state_region.c_str());
nanodbc::string const zip = NANODBC_TEXT(admin.zip);
statement.bind(8, zip.c_str());
execute(statement);
nanodbc::result results = execute(connection, NANODBC_TEXT("SELECT LAST_INSERT_ID();"));
results.next();
int newId = results.get<int>(0, 0);
logger.Log(LogLevel::DEBUG, "Has id: " + newId);
if (results.next() && newId > 0) {
admin.id = newId;
}
} catch (std::exception& e) {
logger.Log(LogLevel::ERR, e.what(), "AdminDao", "AddAdmin");
return std::nullopt;
}
return true;
}
std::optional<bool> AdminDao::UpdateAdminPassword(int id, std::string password) {
logger.Log(LogLevel::DEBUG, "Updating Password to: " + password);
try {
nanodbc::connection connection(conn_str__);
nanodbc::statement statement(connection);
prepare(statement, NANODBC_TEXT("UPDATE "+ db_admin_table__ +
" SET password = SHA2(?,256)"+
" WHERE id = ?"));
nanodbc::string const new_password = NANODBC_TEXT(password + salt__);
statement.bind(0, new_password.c_str());
statement.bind(1, &id);
// TODO(ALL): Verify the DB inserted successfully (check return value of execute).
execute(statement);
} catch (std::exception& e) {
logger.Log(LogLevel::ERR, e.what(), "AdminDao", "UpdateAdminPassword");
return std::nullopt;
}
return true;
}
std::optional<bool> AdminDao::VerifyAdminPassword(std::string username, std::string password) {
try {
nanodbc::connection connection(conn_str__);
nanodbc::statement statement(connection);
prepare(statement, NANODBC_TEXT("select id from " + db_admin_table__ +
" where password = SHA2(?, 256) AND username = ?;"));
nanodbc::string const new_password = NANODBC_TEXT(password + salt__);
statement.bind(0, new_password.c_str());
nanodbc::string const nano_username = NANODBC_TEXT(username);
statement.bind(1, nano_username.c_str());
auto results = execute(statement);
if (results.next()) {
return results.get<int>(0, 0);
} else {
return false;
}
} catch (std::exception& e) {
logger.Log(LogLevel::ERR, e.what(), "AdminDao", "VerifyAdminPassword");
return std::nullopt;
}
}
std::optional<std::string> AdminDao::GetAdminPassword(int id) {
try {
nanodbc::connection connection(conn_str__);
nanodbc::result results = execute(connection, NANODBC_TEXT(
std::string("SELECT password")+
std::string(" FROM ")+ db_admin_table__ +
std::string(" WHERE id = ")+ std::to_string(id) +";"));
std::vector<Admin> db_admins;
if (results.next()) {
return results.get<std::string>(0, "not set");
} else {
return std::string();
}
} catch (std::exception& e) {
logger.Log(LogLevel::ERR, e.what(), "AdminDao", "GetAdminPassword");
return std::nullopt;
}
}
std::optional<bool> AdminDao::UpdateAdmin(Admin admin_info) {
// TODO(Kris): implement UpdateAdmin
return std::nullopt;
}
} // namespace cadg_rest
| 44.724444 | 108 | 0.562556 | [
"vector"
] |
f40d2557a8717a889c71ee5c52f12bb81a563e6e | 8,477 | cpp | C++ | 3-1-Cpp Programming II/StoreQT/Merchandise.cpp | Awdrtgg/Coursework-Projects | d48124b71e477f71b6370f5c3317c6800f8fdb06 | [
"MIT"
] | 3 | 2018-12-02T13:52:55.000Z | 2019-02-26T13:19:50.000Z | 3-1-Cpp Programming II/StoreQT/Merchandise.cpp | Awdrtgg/Coursework-Projects | d48124b71e477f71b6370f5c3317c6800f8fdb06 | [
"MIT"
] | null | null | null | 3-1-Cpp Programming II/StoreQT/Merchandise.cpp | Awdrtgg/Coursework-Projects | d48124b71e477f71b6370f5c3317c6800f8fdb06 | [
"MIT"
] | null | null | null | /*************************************************************************
* Copyright (c)2017, by Beijing University of Posts and Telecommunications
* All rights reserved.
* FileName: Merchandise.cpp
* System: Windows 10
* Author: Xiao Yunming
* Date: 2017.12.15
* Version: 1.0
* Description:
Complete the methods of class Merchandise, Book, Food and Clothes.
*
* Last Modified:
2017.12.22, By Xiao Yunming
*************************************************************************/
#include "Store.h"
// ------------------------- Merchan operations -------------------------
Merchandise::Merchandise(vector<string> v, sql::Connection *con) {
this->kind = v[0];
this->name = v[1];
this->origin_price = stof(v[2]);
this->amount = stoi(v[3]);
this->intro = v[4];
this->con = con;
}
Merchandise::Merchandise(const Merchandise &m) {
this->kind = m.kind;
this->name = m.name;
this->origin_price = m.origin_price;
this->amount = m.amount;
this->intro = m.intro;
this->con = m.con;
}
// ------------------------------- Book ----------------------------------
Book::Book(vector<string> v, sql::Connection *con) : Merchandise(v, con) {
this->cutoff = stof(v[NUM_ATTR_MERCH]);
this->isbn = v[NUM_ATTR_MERCH + 1];
this->writer = v[NUM_ATTR_MERCH + 2];
this->publisher = v[NUM_ATTR_MERCH + 3];
}
Book::Book(const Book &b) : Merchandise(b) {
this->cutoff = b.cutoff;
this->isbn = b.isbn;
this->writer = b.writer;
this->publisher = b.publisher;
}
float Book::GetPrice() {
return (this->origin_price * this->amount * this->cutoff);
}
string Book::Where() {
// return the tail string for this specific item in a MySQL sentence
string where = " where ";
where += "(kind=\'" + this->kind + "\' AND ";
where += "name=\'" + this->name + "\' AND ";
where += "intro=\'" + this->intro + "\' AND ";
where += "isbn=\'" + this->isbn + "\' AND ";
where += "writer=\'" + this->writer + "\')";
return where;
}
int Book::Add() {
// Add a new item
try {
this->con->setSchema("store");
sql::PreparedStatement *prep_stmt;
string cmd = "insert into book(kind, name, org_price, amount, intro, cut_off, isbn, writer, publisher) ";
cmd += "values (?, ?, ?, ?, ?, ?, ?, ?, ?)";
cout << cmd << endl;
prep_stmt = this->con->prepareStatement(cmd);
prep_stmt->setString(1, this->kind);
prep_stmt->setString(2, this->name);
prep_stmt->setDouble(3, this->origin_price);
prep_stmt->setInt(4, this->amount);
prep_stmt->setString(5, this->intro);
prep_stmt->setDouble(6, this->cutoff);
prep_stmt->setString(7, this->isbn);
prep_stmt->setString(8, this->writer);
prep_stmt->setString(9, this->publisher);
prep_stmt->execute();
}
catch (sql::SQLException &e) {
return FAIL;
}
catch (std::invalid_argument &e) {
return FAIL;
}
return SUCCESS;
}
int Book::Edit() {
// Edit this item in the database
try {
this->con->setSchema("store");
sql::PreparedStatement *prep_stmt;
string cmd = "update book set kind=?, name=?, org_price=?, amount=?, intro=?, cut_off=?, isbn=?, writer=?, publisher=? ";
cmd += this->Where();
cout << cmd << endl;
prep_stmt = this->con->prepareStatement(cmd);
prep_stmt->setString(1, this->kind);
prep_stmt->setString(2, this->name);
prep_stmt->setDouble(3, this->origin_price);
prep_stmt->setInt(4, this->amount);
prep_stmt->setString(5, this->intro);
prep_stmt->setDouble(6, this->cutoff);
prep_stmt->setString(7, this->isbn);
prep_stmt->setString(8, this->writer);
prep_stmt->setString(9, this->publisher);
prep_stmt->executeUpdate();
}
catch (sql::SQLException &e) {
return FAIL;
}
catch (std::invalid_argument &e) {
return FAIL;
}
return SUCCESS;
}
// ------------------------------- Food ----------------------------------
Food::Food(vector<string> v, sql::Connection *con) : Merchandise(v, con) {
this->cutoff = stof(v[NUM_ATTR_MERCH]);
this->exp_date = v[NUM_ATTR_MERCH + 1];
}
Food::Food(const Food &f) : Merchandise(f) {
this->cutoff = f.cutoff;
this->exp_date = f.exp_date;
}
float Food::GetPrice() {
return (this->origin_price * this->amount * this->cutoff);
}
string Food::Where() {
// return the tail string for this specific item in a MySQL sentence
string where = " where ";
where += "(kind=\'" + this->kind + "\' AND ";
where += "name=\'" + this->name + "\' AND ";
where += "intro=\'" + this->intro + "\' AND ";
where += "exp_date=\'" + this->exp_date + "\')";
return where;
}
int Food::Add() {
// Add a new item
try {
this->con->setSchema("store");
sql::PreparedStatement *prep_stmt;
string cmd = "insert into food(kind, name, org_price, amount, intro, cut_off, exp_date) ";
cmd += "values (?, ?, ?, ?, ?, ?, ?)";
cout << cmd << endl;
prep_stmt = this->con->prepareStatement(cmd);
prep_stmt->setString(1, this->kind);
prep_stmt->setString(2, this->name);
prep_stmt->setDouble(3, this->origin_price);
prep_stmt->setInt(4, this->amount);
prep_stmt->setString(5, this->intro);
prep_stmt->setDouble(6, this->cutoff);
prep_stmt->setString(7, this->exp_date);
prep_stmt->execute();
}
catch (sql::SQLException &e) {
return FAIL;
}
catch (std::invalid_argument &e) {
return FAIL;
}
return SUCCESS;
}
int Food::Edit() {
// Edit this item in the database
try {
this->con->setSchema("store");
sql::PreparedStatement *prep_stmt;
string cmd = "update food set kind=?, name=?, org_price=?, amount=?, intro=?, cut_off=?, exp_date=? ";
cmd += this->Where();
cout << cmd << endl;
prep_stmt = this->con->prepareStatement(cmd);
prep_stmt->setString(1, this->kind);
prep_stmt->setString(2, this->name);
prep_stmt->setDouble(3, this->origin_price);
prep_stmt->setInt(4, this->amount);
prep_stmt->setString(5, this->intro);
prep_stmt->setDouble(6, this->cutoff);
prep_stmt->setString(7, this->exp_date);
prep_stmt->executeUpdate();
}
catch (sql::SQLException &e) {
return FAIL;
}
catch (std::invalid_argument &e) {
return FAIL;
}
return SUCCESS;
}
// ------------------------------- Clothes ----------------------------------
Clothes::Clothes(vector<string> v, sql::Connection *con) : Merchandise(v, con) {
this->cutoff = stof(v[NUM_ATTR_MERCH]);
this->material = v[NUM_ATTR_MERCH + 1];
this->size = v[NUM_ATTR_MERCH + 2];
}
Clothes::Clothes(const Clothes &c) : Merchandise(c) {
this->cutoff = c.cutoff;
this->material = c.material;
this->size = c.size;
}
float Clothes::GetPrice() {
return (this->origin_price * this->amount * this->cutoff);
}
string Clothes::Where() {
// return the tail string for this specific item in a MySQL sentence
string where = " where ";
where += "(kind=\'" + this->kind + "\' AND ";
where += "name=\'" + this->name + "\' AND ";
where += "intro=\'" + this->intro + "\' AND ";
where += "material=\'" + this->material + "\' AND ";
where += "size=\'" + this->size + "\')";
return where;
}
int Clothes::Add() {
// Add a new item
try {
this->con->setSchema("store");
sql::PreparedStatement *prep_stmt;
string cmd = "insert into clothes(kind, name, org_price, amount, intro, cut_off, material, size) ";
cmd += "values (?, ?, ?, ?, ?, ?, ?, ?)";
cout << cmd << endl;
prep_stmt = this->con->prepareStatement(cmd);
prep_stmt->setString(1, this->kind);
prep_stmt->setString(2, this->name);
prep_stmt->setDouble(3, this->origin_price);
prep_stmt->setInt(4, this->amount);
prep_stmt->setString(5, this->intro);
prep_stmt->setDouble(6, this->cutoff);
prep_stmt->setString(7, this->material);
prep_stmt->setString(8, this->size);
prep_stmt->execute();
}
catch (sql::SQLException &e) {
return FAIL;
}
catch (std::invalid_argument &e) {
return FAIL;
}
return SUCCESS;
}
int Clothes::Edit() {
// Edit this item in the database
try {
this->con->setSchema("store");
sql::PreparedStatement *prep_stmt;
string cmd = "update clothes set kind=?, name=?, org_price=?, amount=?, intro=?, cut_off=?, material=?, size=? ";
cmd += this->Where();
cout << cmd << endl;
prep_stmt = this->con->prepareStatement(cmd);
prep_stmt->setString(1, this->kind);
prep_stmt->setString(2, this->name);
prep_stmt->setDouble(3, this->origin_price);
prep_stmt->setInt(4, this->amount);
prep_stmt->setString(5, this->intro);
prep_stmt->setDouble(6, this->cutoff);
prep_stmt->setString(7, this->material);
prep_stmt->setString(8, this->size);
prep_stmt->executeUpdate();
}
catch (sql::SQLException &e) {
return FAIL;
}
catch (std::invalid_argument &e) {
return FAIL;
}
return SUCCESS;
}
| 28.931741 | 123 | 0.617435 | [
"vector"
] |
f41741e5cd24fc9325560896c4724a42ff8c175c | 1,230 | hpp | C++ | src/include/LogRendererSystem.hpp | jmher019/GameEngine-UIComponents | 8606ca75e6c7e0542d4415b16f0d32e93a814e89 | [
"MIT"
] | null | null | null | src/include/LogRendererSystem.hpp | jmher019/GameEngine-UIComponents | 8606ca75e6c7e0542d4415b16f0d32e93a814e89 | [
"MIT"
] | null | null | null | src/include/LogRendererSystem.hpp | jmher019/GameEngine-UIComponents | 8606ca75e6c7e0542d4415b16f0d32e93a814e89 | [
"MIT"
] | null | null | null | #ifndef LOG_RENDERER_SYSTEM_HPP
#define LOG_RENDERER_SYSTEM_HPP
#include <Timer.hpp>
#include <UIElement.hpp>
#include <LogMessage.hpp>
class LogRendererSystem {
private:
static unique_ptr<UIElement> logDisplayer;
static vec4 logNormalColor;
static vec4 logWarningColor;
static vec4 logErrorColor;
static vector<LogMessage> logMessages;
static bool initialized;
public:
static void startUp(void);
static void shutDown(void);
static bool isInitialized(void);
static void pushLogMessage(const string& message, const GLfloat& timeAllowedForDisplay, const LogMessageType& type);
static void overwriteTopLogMessage(const string& message, const GLfloat& timeAllowedForDisplay, const LogMessageType& type);
static void setUIShader(const shared_ptr<Shader>& uiShader) noexcept;
static void setTextShader(const shared_ptr<Shader>& textShader) noexcept;
static void setLogNormalColor(const vec4& logNormalColor) noexcept;
static void setLogWarningColor(const vec4& logNormalColor) noexcept;
static void setLogErrorColor(const vec4& logNormalColor) noexcept;
static void renderMessages(const mat4& ProjectionViewMatrix);
};
#endif // !LOG_RENDERER_SYSTEM_HPP
| 29.285714 | 128 | 0.779675 | [
"vector"
] |
f420f748ae7e95d66f988e7922c98284525e0520 | 15,306 | cpp | C++ | blades/xtreemfs/cpp/src/libxtreemfs/file_info.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 4 | 2016-04-26T03:43:54.000Z | 2016-11-17T08:09:04.000Z | blades/xtreemfs/cpp/src/libxtreemfs/file_info.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 17 | 2015-01-05T21:06:22.000Z | 2015-12-07T20:45:44.000Z | blades/xtreemfs/cpp/src/libxtreemfs/file_info.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 3 | 2016-04-26T03:43:55.000Z | 2020-11-06T11:02:08.000Z | /*
* Copyright (c) 2011 by Michael Berlin, Zuse Institute Berlin
*
* Licensed under the BSD License, see LICENSE file for details.
*
*/
#include "libxtreemfs/file_info.h"
#include "libxtreemfs/file_handle_implementation.h"
#include "libxtreemfs/helper.h"
#include "libxtreemfs/options.h"
#include "libxtreemfs/volume_implementation.h"
#include "libxtreemfs/xtreemfs_exception.h"
#include "util/logging.h"
#include "xtreemfs/MRC.pb.h"
#include "xtreemfs/OSD.pb.h"
using namespace xtreemfs::pbrpc;
using namespace xtreemfs::util;
using namespace std;
namespace xtreemfs {
FileInfo::FileInfo(
ClientImplementation* client,
VolumeImplementation* volume,
uint64_t file_id,
const std::string& path,
bool replicate_on_close,
const xtreemfs::pbrpc::XLocSet& xlocset,
const std::string& client_uuid)
: client_(client),
volume_(volume),
file_id_(file_id),
path_(path),
replicate_on_close_(replicate_on_close),
reference_count_(0),
xlocset_(xlocset),
osd_uuid_container_(xlocset),
client_uuid_(client_uuid),
osd_write_response_(NULL),
osd_write_response_status_(kClean),
#ifdef _MSC_VER
// Disable "warning C4355: 'this' : used in base member initializer list".
// We can ignore that warning because we know that AsyncWriteHandler's
// constructor doesn't dereference the pointer passed to it.
#pragma warning(push)
#pragma warning(disable:4355)
#endif // _MSC_VER
async_write_handler_(this,
&osd_uuid_iterator_,
volume->uuid_resolver(),
volume->osd_service_client(),
volume->auth_bogus(),
volume->user_credentials_bogus(),
volume->volume_options(),
client->GetAsyncWriteCallbackQueue()) {
#ifdef _MSC_VER
#pragma warning(pop)
#endif // _MSC_VER
// Add the head OSD UUIDs of all replicas to the UUID Iterator.
for (int i = 0; i < xlocset_.replicas_size(); i++) {
osd_uuid_iterator_.AddUUID(xlocset_.replicas(i).osd_uuids(0));
}
if (volume->volume_options().object_cache_size > 0) {
const int object_size =
xlocset_.replicas(0).striping_policy().stripe_size() * 1024;
object_cache_.reset(
new ObjectCache(volume->volume_options().object_cache_size,
object_size));
}
}
FileInfo::~FileInfo() {
assert(active_locks_.size() == 0);
}
FileHandleImplementation* FileInfo::CreateFileHandle(
const xtreemfs::pbrpc::XCap& xcap,
bool async_writes_enabled) {
return CreateFileHandle(xcap, async_writes_enabled, false);
}
FileHandleImplementation* FileInfo::CreateFileHandle(
const xtreemfs::pbrpc::XCap& xcap,
bool async_writes_enabled,
bool used_for_pending_filesize_update) {
FileHandleImplementation* file_handle = new FileHandleImplementation(
client_,
volume_->client_uuid(),
this,
xcap,
volume_->mrc_uuid_iterator(),
&osd_uuid_iterator_,
&osd_uuid_container_,
volume_->uuid_resolver(),
volume_->mrc_service_client(),
volume_->osd_service_client(),
volume_->stripe_translators(),
async_writes_enabled,
object_cache_.get(),
volume_->volume_options(),
volume_->auth_bogus(),
volume_->user_credentials_bogus());
// Add file_handle to list.
if (!used_for_pending_filesize_update) {
boost::mutex::scoped_lock lock_refcount(mutex_);
boost::mutex::scoped_lock lock_fhlist(open_file_handles_mutex_);
++reference_count_;
open_file_handles_.push_back(file_handle);
}
return file_handle;
}
void FileInfo::CloseFileHandle(FileHandleImplementation* file_handle) {
// Pending async writes and file size updates have already been flushed
// by file_handle.
// Remove file handle.
{
boost::mutex::scoped_lock lock_fhlist(open_file_handles_mutex_);
open_file_handles_.remove(file_handle);
}
// Waiting does not require a lock on the open_file_handles_.
file_handle->WaitForAsyncOperations();
// Defer the deletion of file_handle as it might be needed by
// VolumeImplementation::CloseFile() to release all locks.
// At this point the file_handle is already removed from the list of open file
// handles, but the reference_count is not decreased yet. This has to happen
// after locking the open_file_table_ in Volume.
volume_->CloseFile(file_id_, this, file_handle);
}
int FileInfo::DecreaseReferenceCount() {
boost::mutex::scoped_lock lock(mutex_);
--reference_count_;
assert(reference_count_ >= 0);
return reference_count_;
}
void FileInfo::MergeStatAndOSDWriteResponse(xtreemfs::pbrpc::Stat* stat) {
boost::mutex::scoped_lock lock(osd_write_response_mutex_);
if (osd_write_response_.get()) {
// Check if information in Stat is newer than osd_write_response_.
if (stat->truncate_epoch() < osd_write_response_->truncate_epoch() ||
(stat->truncate_epoch() == osd_write_response_->truncate_epoch()
&& stat->size() < osd_write_response_->size_in_bytes())) {
// Information in Stat has to be merged with osd_write_response_.
stat->set_size(osd_write_response_->size_in_bytes());
stat->set_truncate_epoch(osd_write_response_->truncate_epoch());
if (Logging::log->loggingActive(LEVEL_DEBUG)) {
Logging::log->getLog(LEVEL_DEBUG)
<< "getattr: merged infos from osd_write_response, size: "
<< stat->size() << endl;
}
}
}
}
bool FileInfo::TryToUpdateOSDWriteResponse(
xtreemfs::pbrpc::OSDWriteResponse* response,
const xtreemfs::pbrpc::XCap& xcap) {
assert(response);
boost::mutex::scoped_lock lock(osd_write_response_mutex_);
// Determine the new maximum of osd_write_response_.
if (CompareOSDWriteResponses(response, osd_write_response_.get()) == 1) {
// Take over pointer.
osd_write_response_.reset(response);
osd_write_response_xcap_.CopyFrom(xcap);
osd_write_response_status_ = kDirty;
return true;
} else {
return false;
}
}
void FileInfo::WriteBackFileSizeAsync(const RPCOptions& options) {
boost::mutex::scoped_lock lock(osd_write_response_mutex_);
// Only update pending file size updates.
if (osd_write_response_.get() && osd_write_response_status_ == kDirty) {
FileHandleImplementation* file_handle =
CreateFileHandle(osd_write_response_xcap_, false, true);
pending_filesize_updates_.push_back(file_handle);
osd_write_response_status_ = kDirtyAndAsyncPending;
file_handle->set_osd_write_response_for_async_write_back(
*(osd_write_response_.get()));
file_handle->WriteBackFileSizeAsync(options);
}
}
void FileInfo::RenewXCapsAsync(const RPCOptions& options) {
boost::mutex::scoped_lock lock(open_file_handles_mutex_);
for (list<FileHandleImplementation*>::iterator it =
open_file_handles_.begin();
it != open_file_handles_.end();
++it) {
(*it)->ExecutePeriodTasks(options);
}
}
void FileInfo::GetOSDWriteResponse(
xtreemfs::pbrpc::OSDWriteResponse* response) {
boost::mutex::scoped_lock lock(osd_write_response_mutex_);
if (osd_write_response_) {
response->CopyFrom(*(osd_write_response_.get()));
}
}
void FileInfo::GetPath(std::string* path) {
boost::mutex::scoped_lock lock(mutex_);
*path = path_;
}
void FileInfo::RenamePath(const std::string& path,
const std::string& new_path) {
boost::mutex::scoped_lock lock(mutex_);
if (path_ == path) {
path_ = new_path;
}
}
void FileInfo::WaitForPendingFileSizeUpdates() {
boost::mutex::scoped_lock lock(osd_write_response_mutex_);
WaitForPendingFileSizeUpdatesHelper(&lock);
}
void FileInfo::WaitForPendingFileSizeUpdatesHelper(
boost::mutex::scoped_lock* lock) {
assert(lock->owns_lock());
while (pending_filesize_updates_.size() > 0) {
osd_write_response_cond_.wait(*lock);
}
}
void FileInfo::AsyncFileSizeUpdateResponseHandler(
const xtreemfs::pbrpc::OSDWriteResponse& owr,
FileHandleImplementation* file_handle,
bool success) {
boost::mutex::scoped_lock lock(osd_write_response_mutex_);
// Only change the status if the OSDWriteResponse has not changed meanwhile.
if (CompareOSDWriteResponses(&owr, osd_write_response_.get()) == 0) {
// The status must not have changed.
assert(osd_write_response_status_ == kDirtyAndAsyncPending);
if (success) {
osd_write_response_status_ = kClean;
} else {
osd_write_response_status_ = kDirty; // Still dirty.
}
}
// Always remove the temporary FileHandle.
pending_filesize_updates_.remove(file_handle);
delete file_handle;
if (pending_filesize_updates_.size() == 0) {
osd_write_response_cond_.notify_all();
}
}
void FileInfo::GetAttr(const xtreemfs::pbrpc::UserCredentials& user_credentials,
xtreemfs::pbrpc::Stat* stat) {
string path;
GetPath(&path);
volume_->GetAttr(user_credentials, path, false, stat, this);
}
void FileInfo::Flush(FileHandleImplementation* file_handle) {
Flush(file_handle, false);
}
void FileInfo::Flush(FileHandleImplementation* file_handle, bool close_file) {
// We don't wait only for file_handle's pending writes but for all writes of
// this file.
WaitForPendingAsyncWrites();
FlushPendingFileSizeUpdate(file_handle, close_file);
}
void FileInfo::FlushPendingFileSizeUpdate(
FileHandleImplementation* file_handle) {
FlushPendingFileSizeUpdate(file_handle, false);
}
void FileInfo::FlushPendingFileSizeUpdate(FileHandleImplementation* file_handle,
bool close_file) {
// File size write back.
boost::mutex::scoped_lock lock(osd_write_response_mutex_);
bool no_response_sent = true;
if (osd_write_response_.get()) {
WaitForPendingFileSizeUpdatesHelper(&lock);
if (osd_write_response_status_ == kDirty) {
osd_write_response_status_ = kDirtyAndSyncPending;
// Create a copy of OSDWriteResponse to pass to FileHandle.
OSDWriteResponse response_copy(*(osd_write_response_.get()));
lock.unlock();
try {
file_handle->WriteBackFileSize(response_copy, close_file);
} catch (const XtreemFSException&) {
osd_write_response_status_ = kDirty;
throw; // Rethrow error.
}
lock.lock();
no_response_sent = false;
// Only update the status if the response object has not changed
// meanwhile.
if (CompareOSDWriteResponses(osd_write_response_.get(),
&response_copy) == 0) {
osd_write_response_status_ = kClean;
}
}
}
if (no_response_sent && close_file && replicate_on_close_) {
// Send an explicit close only if the on-close-replication should be
// triggered. Use an empty OSDWriteResponse object therefore.
OSDWriteResponse empty_osd_write_response;
file_handle->WriteBackFileSize(empty_osd_write_response, close_file);
}
}
void FileInfo::CheckLock(const xtreemfs::pbrpc::Lock& lock,
xtreemfs::pbrpc::Lock* conflicting_lock,
bool* lock_for_pid_cached,
bool* cached_lock_for_pid_equal,
bool* conflict_found) {
assert(conflicting_lock);
assert(lock_for_pid_cached);
assert(cached_lock_for_pid_equal);
assert(lock.client_uuid() == client_uuid_);
boost::mutex::scoped_lock mutex_lock(active_locks_mutex_);
*cached_lock_for_pid_equal = false;
*conflict_found = false;
*lock_for_pid_cached = false;
for (map<unsigned int, Lock*>::iterator it = active_locks_.begin();
it != active_locks_.end();
++it) {
if (it->first == lock.client_pid()) {
*lock_for_pid_cached = true;
if (CheckIfLocksAreEqual(lock, *(it->second))) {
*cached_lock_for_pid_equal = true;
}
continue;
}
if (CheckIfLocksDoConflict(lock, *(it->second))) {
*conflict_found = true;
conflicting_lock->CopyFrom(*(it->second));
// A conflicting lock has a higher priority than a cached lock with the
// same PID.
break;
}
}
}
bool FileInfo::CheckIfProcessHasLocks(int process_id) {
boost::mutex::scoped_lock mutex_lock(active_locks_mutex_);
// There may be only up to one lock per process_id. No loop required.
map<unsigned int, Lock*>::const_iterator it = active_locks_.find(process_id);
return it != active_locks_.end();
}
void FileInfo::PutLock(const xtreemfs::pbrpc::Lock& lock) {
assert(lock.client_uuid() == client_uuid_);
boost::mutex::scoped_lock mutex_lock(active_locks_mutex_);
map<unsigned int, Lock*>::iterator it = active_locks_.find(lock.client_pid());
if (it != active_locks_.end()) {
delete it->second;
active_locks_.erase(it);
}
Lock* new_lock = new Lock(lock);
active_locks_[lock.client_pid()] = new_lock;
}
void FileInfo::DelLock(const xtreemfs::pbrpc::Lock& lock) {
assert(lock.client_uuid() == client_uuid_);
boost::mutex::scoped_lock mutex_lock(active_locks_mutex_);
map<unsigned int, Lock*>::iterator it = active_locks_.find(lock.client_pid());
if (it != active_locks_.end()) {
// Only up to one lock per PID. If its unlocked, just delete it.
delete it->second;
active_locks_.erase(it);
}
}
void FileInfo::ReleaseLockOfProcess(FileHandleImplementation* file_handle,
int process_id) {
boost::mutex::scoped_lock mutex_lock(active_locks_mutex_);
// There may be only up to one lock per process_id. No loop required.
map<unsigned int, Lock*>::iterator it = active_locks_.find(process_id);
if (it != active_locks_.end()) {
Lock lock(*(it->second));
// Leave critical section.
mutex_lock.unlock();
file_handle->ReleaseLock(lock);
}
}
void FileInfo::ReleaseAllLocks(FileHandleImplementation* file_handle) {
// Do not use pointers here to ensure the deletion of this list - otherwise
// a ReleaseLock() may fail and the memory wont be freed.
list<Lock> active_locks_copy;
{
// Create a copy to avoid longer locking periods and ensure that ReleaseLock
// can delete the lock from active_locks_ without invalidating the iterator.
boost::mutex::scoped_lock mutex_lock(active_locks_mutex_);
for (map<unsigned int, Lock*>::iterator it = active_locks_.begin();
it != active_locks_.end();
++it) {
active_locks_copy.push_back((*(it->second)));
}
}
for (list<Lock>::const_iterator it = active_locks_copy.begin();
it != active_locks_copy.end();
++it) {
// The lock itself will be deleted by ReleaseLock.
file_handle->ReleaseLock(*it);
}
}
void FileInfo::AsyncWrite(AsyncWriteBuffer* write_buffer) {
async_write_handler_.Write(write_buffer);
}
void FileInfo::WaitForPendingAsyncWrites() {
async_write_handler_.WaitForPendingWrites();
}
bool FileInfo::WaitForPendingAsyncWritesNonBlocking(
boost::condition* condition_variable,
bool* wait_completed,
boost::mutex* wait_completed_mutex) {
return async_write_handler_.
WaitForPendingWritesNonBlocking(condition_variable,
wait_completed,
wait_completed_mutex);
}
} // namespace xtreemfs
| 32.427966 | 80 | 0.697831 | [
"object"
] |
f42129f3dcc45d94fa02abfb191fb1383afc55ad | 775 | cpp | C++ | tests/history.cpp | claby2/claditor | 3dfbef9001a7b46712c2dfc960ce06e727f17ae9 | [
"MIT"
] | null | null | null | tests/history.cpp | claby2/claditor | 3dfbef9001a7b46712c2dfc960ce06e727f17ae9 | [
"MIT"
] | null | null | null | tests/history.cpp | claby2/claditor | 3dfbef9001a7b46712c2dfc960ce06e727f17ae9 | [
"MIT"
] | null | null | null | #include "history.hpp"
#include <catch2/catch.hpp>
#include <string>
#include <vector>
TEST_CASE("History has unsaved changes", "[history]") {
History history;
std::vector<std::string> original_lines = {"foo", "bar"};
std::vector<std::string> new_lines = {"hello", "world"};
history.set_content(original_lines);
bool unsaved_changes = history.has_unsaved_changes(new_lines);
REQUIRE(unsaved_changes);
}
TEST_CASE("History has no unsaved changes", "[history]") {
History history;
std::vector<std::string> original_lines = {"foo", "bar"};
std::vector<std::string> new_lines = {"foo", "bar"};
history.set_content(original_lines);
bool unsaved_changes = history.has_unsaved_changes(new_lines);
REQUIRE_FALSE(unsaved_changes);
}
| 32.291667 | 66 | 0.699355 | [
"vector"
] |
f422f2014eba6f0debaee635a2177081e6942473 | 4,732 | hpp | C++ | scripting.hpp | voodooattack/ADWIF | 5267400362f66986ab138e376807720584f52811 | [
"BSD-2-Clause"
] | 6 | 2015-05-24T17:51:08.000Z | 2020-06-07T09:33:35.000Z | scripting.hpp | voodooattack/ADWIF | 5267400362f66986ab138e376807720584f52811 | [
"BSD-2-Clause"
] | null | null | null | scripting.hpp | voodooattack/ADWIF | 5267400362f66986ab138e376807720584f52811 | [
"BSD-2-Clause"
] | 2 | 2019-05-27T14:47:48.000Z | 2022-02-04T05:39:56.000Z | /* Copyright (c) 2013, Abdullah A. Hassan <voodooattack@hotmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SCRIPTING_HPP
#define SCRIPTING_HPP
#include <v8.h>
#include <string>
namespace ADWIF
{
class Scripting
{
public:
static void createContext(v8::Persistent<v8::Context> & out, v8::Isolate * isolate = v8::Isolate::GetCurrent());
static bool executeScript(const std::string & source, std::string & exception, v8::Handle<v8::Value> & result /*, v8::Isolate * isolate = v8::Isolate::GetCurrent() */);
template<class T>
static v8::Handle<T> PersistentToHandle(v8::Persistent<T> & persistent, v8::Isolate * isolate = v8::Isolate::GetCurrent())
{
v8::HandleScope handle_scope(isolate);
v8::Handle<T> templ = v8::Local<T>::New(isolate, persistent);
return handle_scope.Close(templ);
}
template<class T>
static void HandleToPersistent(v8::Handle<T> handle, v8::Persistent<T> & persistent, v8::Isolate * isolate = v8::Isolate::GetCurrent())
{
v8::HandleScope handle_scope(isolate);
persistent.Reset(isolate, handle);
}
template<class T>
static v8::Handle<v8::Object> wrap(T * object, v8::Handle<v8::ObjectTemplate> templ, v8::Isolate * isolate = v8::Isolate::GetCurrent())
{
v8::HandleScope handle_scope(isolate);
v8::Handle<v8::Object> result = templ->NewInstance();
v8::Handle<v8::External> wrapped = v8::External::New(object);
result->SetInternalField(0, wrapped);
return handle_scope.Close(result);
}
template<class T>
static v8::Handle<v8::Object> wrap(T * object, v8::Persistent<v8::ObjectTemplate> templ, v8::Isolate * isolate = v8::Isolate::GetCurrent())
{
v8::HandleScope handle_scope(isolate);
v8::Handle<T> temp = PersistentToHandle(templ);
v8::Handle<v8::Object> result = temp->NewInstance();
v8::Handle<v8::External> wrapped = v8::External::New(object);
result->SetInternalField(0, wrapped);
return handle_scope.Close(result);
}
template<class T>
static T * unwrap(v8::Handle<v8::Object> object)
{
v8::Handle<v8::External> field = v8::Handle<v8::External>::Cast(object->GetInternalField(0));
void * ptr = field->Value();
return reinterpret_cast<T *>(ptr);
}
};
class TemplateBuilder
{
public:
TemplateBuilder(v8::Isolate * isolate = v8::Isolate::GetCurrent());
TemplateBuilder & accessor(
const std::string & name,
v8::AccessorGetterCallback getter,
v8::AccessorSetterCallback setter = nullptr,
v8::Handle<v8::Value> data = v8::Handle<v8::Value>(),
v8::AccessControl settings = v8::DEFAULT,
v8::PropertyAttribute attribute = v8::None,
v8::Handle<v8::AccessorSignature> signature = v8::Handle<v8::AccessorSignature>());
TemplateBuilder & indexedPropertyHandler(
v8::IndexedPropertyGetterCallback getter,
v8::IndexedPropertySetterCallback setter = nullptr,
v8::IndexedPropertyQueryCallback query = nullptr,
v8::IndexedPropertyDeleterCallback deleter = nullptr,
v8::IndexedPropertyEnumeratorCallback enumerator = nullptr,
v8::Handle<v8::Value> data = v8::Handle<v8::Value>());
v8::Handle<v8::ObjectTemplate> getTemplate();
void getTemplate(v8::Persistent<v8::ObjectTemplate> & out);
private:
v8::Persistent<v8::ObjectTemplate> myTemplate;
v8::Isolate * myIsolate;
};
}
#endif // SCRIPTING_HPP
| 42.25 | 172 | 0.702451 | [
"object"
] |
f4285239d540fba1bbee1de46638216ab94a7229 | 19,000 | cpp | C++ | src/prod/src/Common/Directory.test.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/Common/Directory.test.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/Common/Directory.test.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
#include <boost/test/unit_test.hpp>
#include "Common/boost-taef.h"
#if defined(PLATFORM_UNIX)
#include <sys/stat.h>
#endif
using namespace std;
Common::StringLiteral const TraceType("DirectoryTest");
namespace Common
{
class DirectoryTest
{
protected:
static StringLiteral const TestSource;
static StringLiteral const TestRootDir;
DirectoryTest() { BOOST_REQUIRE(MethodSetup()); }
TEST_METHOD_SETUP( MethodSetup );
~DirectoryTest() { BOOST_REQUIRE(MethodCleanup()); }
TEST_METHOD_CLEANUP( MethodCleanup );
void CreateTestDirectory(
wstring const & rootDirName,
wstring const & fileNamePrefix,
wstring const & subDirPrefix,
int fileCount,
int subDirCount,
int dirDepth,
wstring const & fileExt = L"");
void VerifyTestDirectoryExists(
wstring const & rootDirName,
wstring const & fileNamePrefix,
wstring const & subDirPrefix,
int fileCount,
int subDirCount,
int dirDepth,
wstring const & fileExt = L"");
void VerifyTestDirectoryNotExists(
wstring const & rootDirName);
void VerifyFileExists(
wstring const & fileName);
void VerifyFileNotExists(
wstring const & fileName);
static wstring GetTestRootDir();
};
StringLiteral const DirectoryTest::TestSource("DirectoryTest");
StringLiteral const DirectoryTest::TestRootDir("DirectoryTest_Root");
BOOST_FIXTURE_TEST_SUITE(DirectoryTestSuite,DirectoryTest)
BOOST_AUTO_TEST_CASE(ArchiveTest)
{
Trace.WriteInfo(DirectoryTest::TestSource, "*** ArchiveTest");
// Replace non-existent destination
auto srcRoot = Path::Combine(GetTestRootDir(), L"ArchiveTestRoot");
int fileCount = 5;
int subDirCount = 5;
int subDirDepth = 3;
wstring src = Path::Combine(GetTestRootDir(), L"Directory.src");
wstring zip = Path::Combine(GetTestRootDir(), L"Directory.zip");
wstring zip2 = Path::Combine(GetTestRootDir(), L"Directory2.zip");
wstring dest = Path::Combine(GetTestRootDir(), L"Directory.dest");
CreateTestDirectory(
src,
L"MyFile",
L"MySubDir",
fileCount,
subDirCount,
subDirDepth);
VerifyTestDirectoryExists(
src,
L"MyFile",
L"MySubDir",
fileCount,
subDirCount,
subDirDepth);
VerifyTestDirectoryNotExists(dest);
VerifyFileNotExists(zip);
VerifyFileNotExists(zip2);
auto error = Directory::CreateArchive(src, zip);
VERIFY_IS_TRUE(error.IsSuccess(), wformatString("CreateArchive failed: {0}", error).c_str());
VerifyFileExists(zip);
File srcFile;
error = srcFile.TryOpen(zip, FileMode::Open, FileAccess::Read, FileShare::None, FileAttributes::Normal);
VERIFY_IS_TRUE(error.IsSuccess(), wformatString("TryOpen {0} failed: {1}", zip, error).c_str());
File destFile;
error = destFile.TryOpen(zip2, FileMode::CreateNew, FileAccess::Write, FileShare::None, FileAttributes::Normal);
VERIFY_IS_TRUE(error.IsSuccess(), wformatString("TryOpen {0} failed: {1}", zip2, error).c_str());
size_t bufferSize = 64 * 1024;
vector<byte> buffer;
buffer.resize(bufferSize);
DWORD bytesRead = 0;
DWORD totalBytesRead = 0;
do
{
error = srcFile.TryRead2(buffer.data(), static_cast<int>(buffer.size()), bytesRead);
VERIFY_IS_TRUE(error.IsSuccess(), wformatString("TryRead2 failed: {0}", error).c_str());
if (error.IsSuccess() && bytesRead > 0)
{
totalBytesRead += bytesRead;
Trace.WriteInfo("ArchiveTest", "Read {0} bytes: total={1}", bytesRead, totalBytesRead);
DWORD bytesWritten;
error = destFile.TryWrite2(buffer.data(), bytesRead, bytesWritten);
VERIFY_IS_TRUE(error.IsSuccess() && bytesWritten == bytesRead, wformatString("TryRead2 failed: {0} read={1} written={2}", error, bytesRead, bytesWritten).c_str());
}
else
{
Trace.WriteInfo("ArchiveTest", "Read failed bytes: error={0} read={1} total={2}", error, bytesRead, totalBytesRead);
}
} while (bytesRead > 0);
error = srcFile.Close2();
VERIFY_IS_TRUE(error.IsSuccess(), wformatString("Close2 {0} failed: {1}", zip, error).c_str());
error = destFile.Close2();
VERIFY_IS_TRUE(error.IsSuccess(), wformatString("Close2 {0} failed: {1}", zip2, error).c_str());
VerifyFileExists(zip2);
error = Directory::ExtractArchive(zip2, dest);
VERIFY_IS_TRUE(error.IsSuccess(), wformatString("ExtractArchive failed: {0}", error).c_str());
VerifyTestDirectoryExists(
dest,
L"MyFile",
L"MySubDir",
fileCount,
subDirCount,
subDirDepth);
VerifyTestDirectoryExists(
src,
L"MyFile",
L"MySubDir",
fileCount,
subDirCount,
subDirDepth);
}
BOOST_AUTO_TEST_CASE(DeleteTest)
{
Trace.WriteInfo(DirectoryTest::TestSource, "*** DeleteTest");
// Replace non-existent destination
auto testDir = Path::Combine(GetTestRootDir(), L"Directory.test");
auto missingDir = Path::Combine(GetTestRootDir(), L"Directory.missing");
int fileCount = 5;
int subDirCount = 5;
int subDirDepth = 3;
CreateTestDirectory(
testDir,
L"MyFile",
L"MySubDir",
fileCount,
subDirCount,
subDirDepth);
VerifyTestDirectoryExists(
testDir,
L"MyFile",
L"MySubDir",
fileCount,
subDirCount,
subDirDepth);
VerifyTestDirectoryNotExists(missingDir);
// Happy path
auto error = Directory::Delete(testDir, true);
VERIFY_IS_TRUE(error.IsSuccess(), wformatString("Delete failed: {0}", error).c_str());
error = Directory::Delete(missingDir, true);
VERIFY_IS_TRUE(
error.ReadValue() == ErrorCodeValue::DirectoryNotFound,
wformatString("Delete returned wrong ErrorCode: {0}, expected {1}", error, ErrorCodeValue::DirectoryNotFound).c_str());
}
BOOST_AUTO_TEST_CASE(GetSubDirectoriesTest)
{
Trace.WriteInfo(DirectoryTest::TestSource, "*** GetSubDirectoriesTest");
auto testDir = Path::Combine(GetTestRootDir(), L"Directory.test");
int fileCount = 5;
int subDirCount = 5;
int subDirDepth = 3;
CreateTestDirectory(
testDir,
L"MyFile",
L"MySubDir",
fileCount,
subDirCount,
subDirDepth);
VerifyTestDirectoryExists(
testDir,
L"MyFile",
L"MySubDir",
fileCount,
subDirCount,
subDirDepth);
vector<wstring> subDirectories = Directory::GetSubDirectories(testDir, wformatString("*{0}*", "MySubDir"), true, true);
auto subDirectoryCount = subDirectories.size();
VERIFY_IS_TRUE(subDirectoryCount == subDirCount, wformatString("Number of subdirectories doesnot match. ExpecteCount:{0}, SubDirectoryCount:{1}", subDirectoryCount, subDirCount).c_str());
vector<wstring> subDirectoryWithSinglePattern = Directory::GetSubDirectories(testDir, wformatString("*{0}", "MySubDir"), true, true);
auto subDirectoryWithPatternCount = subDirectoryWithSinglePattern.size();
VERIFY_IS_TRUE(subDirectoryWithPatternCount == 0, wformatString("Number of subdirectories doesnot match. ExpecteCount:{0}, SubDirectoryCount:{1}", subDirectoryWithPatternCount, 0).c_str());
vector<wstring> singleSubDirectory = Directory::GetSubDirectories(testDir, wformatString("*{0}*", "MySubDir1"), true, true);
auto singleSubDirectoryCount = singleSubDirectory.size();
VERIFY_IS_TRUE(singleSubDirectoryCount == 1, wformatString("Number of subdirectories doesnot match. ExpecteCount:{0}, SubDirectoryCount:{1}", singleSubDirectoryCount, 1).c_str());
vector<wstring> missingDirectory = Directory::GetSubDirectories(testDir, wformatString("*{0}*", "Foo"), true, true);
auto missingDirectoryCount = missingDirectory.size();
VERIFY_IS_TRUE(missingDirectoryCount == 0, wformatString("Number of subdirectories doesnot match. ExpecteCount:{0}, SubDirectoryCount:{1}", missingDirectoryCount, 0).c_str());
vector<wstring> singleSubDirectoryWithSinglePattern = Directory::GetSubDirectories(testDir, wformatString("*{0}", "MySubDir1"), true, true);
auto singleSubDirectoryWithPatternCount = singleSubDirectoryWithSinglePattern.size();
VERIFY_IS_TRUE(singleSubDirectoryWithPatternCount == 1, wformatString("Number of subdirectories doesnot match. ExpecteCount:{0}, SubDirectoryCount:{1}", singleSubDirectoryWithPatternCount, 1).c_str());
}
BOOST_AUTO_TEST_CASE(GetFilesInDirectoriesTest)
{
Trace.WriteInfo(DirectoryTest::TestSource, "*** GetFilesInDirectoriesTest");
auto testDir = Path::Combine(GetTestRootDir(), L"Directory.test");
int fileCount = 5;
int subDirCount = 5;
int subDirDepth = 3;
CreateTestDirectory(
testDir,
L"MyFile",
L"MySubDir",
fileCount,
subDirCount,
subDirDepth,
L".xml");
VerifyTestDirectoryExists(
testDir,
L"MyFile",
L"MySubDir",
fileCount,
subDirCount,
subDirDepth,
L".xml");
CreateTestDirectory(
testDir,
L"MyFile1",
L"MySubDir",
1,
0,
0,
L".txt");
// There is only 1 txt file in top directory. Serach all subdirectories should return only 1 file.
vector<wstring> topDirectoriesTxtFiles = Directory::GetFiles(testDir, L"*.txt", true, false);
Trace.WriteInfo("GetFilesTest", " txtFiles ExpectedCount:{0}, SubDirectoryCount:{1}", 1, topDirectoriesTxtFiles.size());
VERIFY_IS_TRUE(1 == topDirectoriesTxtFiles.size(), wformatString("Number of files doesnot match. ExpecteCount:{0}, FilesCount:{1}", 1, topDirectoriesTxtFiles.size()).c_str());
// Get the file with the absolute name in top directory
vector<wstring> topDirectoriesXmlFile = Directory::GetFiles(testDir, L"MyFile0.xml", true, true);
Trace.WriteInfo("GetFilesTest", " txtFiles ExpectedCount:{0}, SubDirectoryCount:{1}", 1, topDirectoriesXmlFile.size());
VERIFY_IS_TRUE(1 == topDirectoriesXmlFile.size(), wformatString("Number of files doesnot match. ExpecteCount:{0}, FilesCount:{1}", 1, topDirectoriesXmlFile.size()).c_str());
// All the subdirectories have xml files. Serach to top directory should result in only top directory files.
vector<wstring> subDirectoriesFiles = Directory::GetFiles(testDir, L"*.xml", true, true);
Trace.WriteInfo("GetFilesTest", "xmlFiles ExpectedCount:{0}, SubDirectoryCount:{1}", fileCount, subDirectoriesFiles.size());
VERIFY_IS_TRUE(fileCount == subDirectoriesFiles.size(), wformatString("Number of files doesnot match. ExpecteCount:{0}, FilesCount:{1}", fileCount, subDirectoriesFiles.size()).c_str());
}
#if defined(PLATFORM_UNIX)
BOOST_AUTO_TEST_CASE(DirectoryPermissionsTest)
{
Trace.WriteInfo(DirectoryTest::TestSource, "*** DirectoryPermissionsTest");
auto testDir = Path::Combine(GetTestRootDir(), L"Directory.test");
int fileCount = 1;
int subDirCount = 1;
int subDirDepth = 0;
CreateTestDirectory(
testDir,
L"MyFile",
L"MySubDir",
fileCount,
subDirCount,
subDirDepth);
VerifyTestDirectoryExists(
testDir,
L"MyFile",
L"MySubDir",
fileCount,
subDirCount,
subDirDepth);
string pathA = FileNormalizePath(Path::ConvertToNtPath(testDir).c_str());
struct stat stat_data;
VERIFY_IS_TRUE(stat(pathA.c_str(), &stat_data) == 0, wformatString("Unable to retreive the stat for the directory").c_str());
int mode = stat_data.st_mode;
// Permission should be 755
VERIFY_IS_TRUE(mode & S_IRUSR, L"User reda permission not set");
VERIFY_IS_TRUE(mode & S_IWUSR, L"User write permission not set");
VERIFY_IS_TRUE(mode & S_IXUSR, L"User execute permission not set");
VERIFY_IS_TRUE(mode & S_IRGRP, L"Group read permission not set");
VERIFY_IS_TRUE(mode & S_IXGRP, L"Group execute permission not set");
VERIFY_IS_TRUE(mode & ~S_IWGRP, L"Group write permission set");
VERIFY_IS_TRUE(mode & S_IROTH, L"Others read permission not set");
VERIFY_IS_TRUE(mode & S_IXOTH, L"Others read permission not set");
VERIFY_IS_TRUE(mode & ~S_IWOTH, L"Others write permission set");
auto path = Path::Combine(Directory::GetCurrentDirectory(), testDir);
VERIFY_IS_TRUE(Directory::Exists(path), L"Directory doesn;t exist");
auto error = File::AllowAccessToAll(path);
Trace.WriteInfo("DirectoryPermissionsTest", "SetAttributes for {0} completed with {1}", testDir, error);
VERIFY_IS_TRUE(error.IsSuccess(), wformatString("Unable to set permissions for the directory {0}", testDir).c_str());
struct stat stat_data_1;
VERIFY_IS_TRUE(stat(pathA.c_str(), &stat_data_1) == 0, wformatString("Unable to retreive the stat for the directory").c_str());
int mode1 = stat_data_1.st_mode;
// Permission should be 777
VERIFY_IS_TRUE(mode1 & S_IRUSR, L"User reda permission not set");
VERIFY_IS_TRUE(mode1 & S_IWUSR, L"User write permission not set");
VERIFY_IS_TRUE(mode1 & S_IXUSR, L"User execute permission not set");
VERIFY_IS_TRUE(mode1 & S_IRGRP, L"Group read permission not set");
VERIFY_IS_TRUE(mode1 & S_IXGRP, L"Group execute permission not set");
VERIFY_IS_TRUE(mode1 & S_IWGRP, L"Group write permission not set");
VERIFY_IS_TRUE(mode1 & S_IROTH, L"Others read permission not set");
VERIFY_IS_TRUE(mode1 & S_IXOTH, L"Others read permission not set");
VERIFY_IS_TRUE(mode1 & S_IWOTH, L"Others write permission not set");
}
#endif
BOOST_AUTO_TEST_SUITE_END()
void DirectoryTest::CreateTestDirectory(
wstring const & rootDirName,
wstring const & fileNamePrefix,
wstring const & subDirPrefix,
int fileCount,
int subDirCount,
int dirDepth,
wstring const & fileExt)
{
if (!Directory::Exists(rootDirName))
{
Directory::Create(rootDirName);
}
if (dirDepth < 0) { return; }
for (int fx=0; fx<fileCount; ++fx)
{
auto fileName = Path::Combine(rootDirName, wformatString("{0}{1}{2}", fileNamePrefix, fx, fileExt));
File file;
auto error = file.TryOpen(fileName, FileMode::OpenOrCreate, FileAccess::Write);
VERIFY_IS_TRUE_FMT(error.IsSuccess(), "TryOpen({0}) error={1}", fileName, error);
file.Write(
reinterpret_cast<const void*>(fileName.c_str()),
static_cast<int>(fileName.size() * sizeof(wchar_t)));
file.Flush();
file.Close();
}
for (int dx=0; dx<subDirCount; ++dx)
{
auto subDirName = Path::Combine(rootDirName, wformatString("{0}{1}", subDirPrefix, dx));
CreateTestDirectory(
subDirName,
fileNamePrefix,
subDirPrefix,
fileCount,
subDirCount,
dirDepth - 1,
fileExt);
}
}
void DirectoryTest::VerifyTestDirectoryExists(
wstring const & rootDirName,
wstring const & fileNamePrefix,
wstring const & subDirPrefix,
int fileCount,
int subDirCount,
int dirDepth,
wstring const & fileExt)
{
bool exists = Directory::Exists(rootDirName);
VERIFY_IS_TRUE_FMT( exists, "Directory {0} exists={1}", rootDirName, exists );
if (dirDepth < 0) { return; }
for (int fx=0; fx<fileCount; ++fx)
{
auto fileName = Path::Combine(rootDirName, wformatString("{0}{1}{2}", fileNamePrefix, fx, fileExt));
exists = File::Exists(fileName);
VERIFY_IS_TRUE_FMT( exists, "File {0} exists={1}", fileName, exists );
}
for (int dx=0; dx<subDirCount; ++dx)
{
auto subDirName = Path::Combine(rootDirName, wformatString("{0}{1}", subDirPrefix, dx));
VerifyTestDirectoryExists(
subDirName,
fileNamePrefix,
subDirPrefix,
fileCount,
subDirCount,
dirDepth - 1,
fileExt);
}
}
void DirectoryTest::VerifyTestDirectoryNotExists(
wstring const & rootDirName)
{
bool exists = Directory::Exists(rootDirName);
VERIFY_IS_TRUE_FMT( !exists, "Directory {0} exists={1}", rootDirName, exists );
}
void DirectoryTest::VerifyFileExists(
wstring const & fileName)
{
bool exists = File::Exists(fileName);
VERIFY_IS_TRUE_FMT( exists, "File {0} exists={1}", fileName, exists );
}
void DirectoryTest::VerifyFileNotExists(
wstring const & fileName)
{
bool exists = File::Exists(fileName);
VERIFY_IS_TRUE_FMT( !exists, "File {0} exists={1}", fileName, exists );
}
wstring DirectoryTest::GetTestRootDir()
{
return wformatString("{0}", TestRootDir);
}
bool DirectoryTest::MethodSetup()
{
Config cfg;
if (Directory::Exists(GetTestRootDir()))
{
Directory::Delete(GetTestRootDir(), true);
}
Directory::Create(GetTestRootDir());
return true;
}
bool DirectoryTest::MethodCleanup()
{
if (Directory::Exists(GetTestRootDir()))
{
Directory::Delete(GetTestRootDir(), true);
}
return true;
}
}
| 36.608863 | 209 | 0.612684 | [
"vector"
] |
f42a1bb55c76837d4fcc119dc6649b008289ec9b | 1,598 | hxx | C++ | A_tour_of_cpp/src/060_Chapter_6/Workspace.hxx | NaPiZip/Programming_basics_c- | d84bf4baa25fbcf28b12fb06be7a6270c143effc | [
"MIT"
] | null | null | null | A_tour_of_cpp/src/060_Chapter_6/Workspace.hxx | NaPiZip/Programming_basics_c- | d84bf4baa25fbcf28b12fb06be7a6270c143effc | [
"MIT"
] | null | null | null | A_tour_of_cpp/src/060_Chapter_6/Workspace.hxx | NaPiZip/Programming_basics_c- | d84bf4baa25fbcf28b12fb06be7a6270c143effc | [
"MIT"
] | null | null | null | // Copyright 2019, Nawin
template<typename T>
section_6_2::Vector<T>::Vector(int sz) : element_{ new T[sz] }, sz_{sz} {
for (auto idx = 0; idx != sz_; ++idx) {
element_[idx] = 0;
}
}
template<typename T>
section_6_2::Vector<T>::Vector(std::initializer_list<T> list) :
element_{ new T[list.size()] },
sz_{ static_cast<int>(list.size()) } {
int idx = 0;
for (auto item : list) {
element_[idx++] = item;
}
}
template<typename T>
section_6_2::Vector<T>::Vector(const Vector<T>& v) :
element_{ new T[v.sz_] },
sz_{ v.sz_ } {
for (auto idx = 0; idx != sz_; ++idx) {
element_[idx] = v.element_[idx];
}
}
template<typename T>
T& section_6_2::Vector<T>::operator[](int i) {
return element_[i];
}
template<typename T>
const T& section_6_2::Vector<T>::operator[](int i) const {
return element_[i];
}
template<typename T>
void section_6_2::Vector<T>::push_back(T val) {
T* new_data = new T[sz_ + 1];
for (auto idx = 0; idx != sz_; ++idx) {
new_data[idx] = element_[idx];
}
delete[] element_;
element_ = new_data;
element_[sz_++] = val;
}
template<typename T>
T* section_6_2::Vector<T>::begin() {
return size() ? &(*this)[0] : nullptr;
}
template<typename T>
T* section_6_2::Vector<T>::end() {
return size() ? &(*this)[0]+size() : nullptr;
}
template<typename T>
int section_6_2::Vector<T>::size() const {
return sz_;
}
template<typename T>
template<typename Iter>
section_6_2::Vector2<T>::Vector2(Iter b, Iter e) : Vector<T>(0) {
// @TODO ask in Slack how this works
}
| 22.828571 | 74 | 0.603254 | [
"vector"
] |
f430eafc25131684f0f59e07702faa1666ab4d38 | 38,030 | cpp | C++ | Unix/tests/codec/mof/blue/test_mofserializer.cpp | DalavanCloud/omi | 6d8bf93ea036a58cea78a24b4fb293d2f4d5ad33 | [
"MIT"
] | 1 | 2018-09-30T01:04:47.000Z | 2018-09-30T01:04:47.000Z | Unix/tests/codec/mof/blue/test_mofserializer.cpp | DalavanCloud/omi | 6d8bf93ea036a58cea78a24b4fb293d2f4d5ad33 | [
"MIT"
] | null | null | null | Unix/tests/codec/mof/blue/test_mofserializer.cpp | DalavanCloud/omi | 6d8bf93ea036a58cea78a24b4fb293d2f4d5ad33 | [
"MIT"
] | null | null | null | /*
**==============================================================================
**
** Copyright (c) Microsoft Corporation. All rights reserved. See file LICENSE
** for license information.
**
**==============================================================================
*/
#include <vector>
#include <string>
#include <micodec.h>
#include <nits.h>
#include "Class1.h"
#include "Class2.h"
#include "Widget.h"
#include "Gadget.h"
#include "Link.h"
#include "Container.h"
#include "Assoc1.h"
#include "SubClass.h"
#include "Thing.h"
#include "instance.h"
#include "class.h"
using namespace std;
#if (MI_CHAR_TYPE == 1)
# define T(STR) STR
#else
# define __T(STR) L ## STR
# define T(STR) __T(STR)
#endif
#define TRACE printf("TRACE: %s(%u)\n", __FILE__, __LINE__)
extern "C"
{
extern MI_SchemaDecl schemaDecl;
}
//=============================================================================
//
// CHECK()
//
//=============================================================================
#define CHECK(COND) NitsAssert(COND, T("CHECK"))
//=============================================================================
//
// STRCMP()
// STRLEN()
// STRCHR()
// PRINTF()
// String
//
//=============================================================================
#if (MI_CHAR_TYPE == 1)
# define STRCMP strcmp
# define STRLEN strlen
# define STRCHR strchr
# define PRINTF printf
typedef string String;
#else
# define STRCMP ::wcscmp
# define STRLEN ::wcslen
# define STRCHR ::wcschr
# define PRINTF ::wprintf
typedef wstring String;
#endif
//=============================================================================
//
// Serializer
//
// Simple wrapper class for MI_Serializer (to simply tests below).
//
//=============================================================================
class Serializer
{
public:
Serializer()
{
memset(&m_app, 0, sizeof(m_app));
m_result = MI_Application_NewSerializer_Mof(
&m_app,
0,
(MI_Char*)T("MOF"),
&m_serializer);
}
~Serializer()
{
if (m_result != MI_RESULT_OK)
return;
ft()->Close(&m_serializer);
}
template<class T>
bool SerializeInstance(
const T& instance,
MI_Uint32 flags,
vector<MI_Char>& data)
{
return _SerializeInstance(&instance.__instance, flags, data);
}
bool SerializeClass(
const MI_Class* clss,
MI_Uint32 flags,
vector<MI_Char>& data)
{
if (m_result != MI_RESULT_OK)
return false;
#if 0
MI_Uint8* buffer = m_buffer;
MI_Uint32 bufferLength = sizeof(m_buffer);
MI_Uint32 bufferNeeded = sizeof(m_buffer);
#else
MI_Uint8* buffer = NULL;
MI_Uint32 bufferLength = 0;
MI_Uint32 bufferNeeded = 0;
#endif
for (;;)
{
MI_Result r = ft()->SerializeClass(
&m_serializer,
flags,
clss,
buffer,
bufferLength,
&bufferNeeded);
if (r != MI_RESULT_OK && bufferLength < bufferNeeded)
{
buffer = (MI_Uint8*)malloc(bufferNeeded);
if (!buffer)
return false;
bufferLength = bufferNeeded;
continue;
}
if (r != MI_RESULT_OK)
return false;
data.insert(
data.end(),
(const MI_Char*)buffer,
(const MI_Char*)(buffer + bufferNeeded));
if (buffer != m_buffer)
free(buffer);
return true;
}
}
operator bool() const
{
return m_result == MI_RESULT_OK;
}
private:
MI_SerializerFT* ft()
{
return (MI_SerializerFT*)m_serializer.reserved2;
}
bool _SerializeInstance(
const MI_Instance* instance,
MI_Uint32 flags,
vector<MI_Char>& data)
{
if (m_result != MI_RESULT_OK)
return false;
#if 0
MI_Uint8* buffer = m_buffer;
MI_Uint32 bufferLength = sizeof(m_buffer);
MI_Uint32 bufferNeeded = sizeof(m_buffer);
#else
MI_Uint8* buffer = NULL;
MI_Uint32 bufferLength = 0;
MI_Uint32 bufferNeeded = 0;
#endif
for (;;)
{
MI_Result r = ft()->SerializeInstance(
&m_serializer,
flags,
instance,
buffer,
bufferLength,
&bufferNeeded);
if (r != MI_RESULT_OK && bufferLength < bufferNeeded)
{
buffer = (MI_Uint8*)malloc(bufferNeeded);
if (!buffer)
return false;
bufferLength = bufferNeeded;
continue;
}
if (r != MI_RESULT_OK)
return false;
data.insert(
data.end(),
(const MI_Char*)buffer,
(const MI_Char*)(buffer + bufferNeeded));
if (buffer != m_buffer)
free(buffer);
return true;
}
}
MI_Result m_result;
MI_Application m_app;
MI_Serializer m_serializer;
MI_Uint8 m_buffer[4096];
};
//=============================================================================
//
// _ConstructInstance()
//
// Helper function to construct MI_Instances by classname:
//
//=============================================================================
static bool _ConstructInstance(
MI_Instance* instance,
const MI_Char* className)
{
const MI_ClassDecl* cd = 0;
for (MI_Uint32 i = 0; i < schemaDecl.numClassDecls; i++)
{
if (STRCMP(schemaDecl.classDecls[i]->name, className) == 0)
{
cd = schemaDecl.classDecls[i];
break;
}
}
if (!cd)
return false;
Test_Instance_Construct(instance, cd);
return true;
}
//=============================================================================
//
// _ConstructClass()
//
// Helper function to construct MI_Classs by classname:
//
//=============================================================================
static bool _ConstructClass(
MI_Class* clss,
const MI_Char* className)
{
const MI_ClassDecl* cd = 0;
for (MI_Uint32 i = 0; i < schemaDecl.numClassDecls; i++)
{
if (STRCMP(schemaDecl.classDecls[i]->name, className) == 0)
{
cd = schemaDecl.classDecls[i];
break;
}
}
if (!cd)
return false;
Test_Class_Construct(clss, cd);
return true;
}
//=============================================================================
//
// _Diff()
//
//=============================================================================
static bool _Diff(
const MI_Char* data1,
const MI_Char* data2)
{
const MI_Char* p = data1;
const MI_Char* q = data2;
unsigned int line = 1;
while (*p && *q)
{
const MI_Char* pend = STRCHR(p, '\n');
if (!pend)
pend = p + STRLEN(p);
const MI_Char* qend = STRCHR(q, '\n');
if (!qend)
qend = q + STRLEN(q);
String line1(p, pend - p);
String line2(q, qend - q);
if (line1 != line2)
{
PRINTF(T("\n********** line: %u\n"), line);
PRINTF(T("< %s\n"), line1.c_str());
PRINTF(T("> %s\n"), line2.c_str());
return false;
}
#if 0
PRINTF(T("LINE[%s]\n"), line1.c_str());
#endif
if (*pend == '\n')
pend++;
if (*qend == '\n')
qend++;
line++;
p = pend;
q = qend;
}
if (*p)
{
PRINTF(T("\n********** line: %u\n"), line);
PRINTF(T("< %s\n"), p);
return false;
}
if (*q)
{
PRINTF(T("\n********** line: %u\n"), line);
PRINTF(T("> %s\n"), q);
return false;
}
return true;
}
//=============================================================================
//
// TestCreateMofSerializer()
//
//=============================================================================
NitsTest(TestCreateMofSerializer)
{
Serializer ser;
CHECK(ser == true);
}
NitsEndTest
//=============================================================================
//
// TestSerializeClass1()
//
//=============================================================================
NitsTest(TestSerializeClass1)
{
const MI_Char expect[] =
T("instance of Class1\n")
T("{\n")
T(" Key = 56789;\n")
T(" Msg = \"The answer\\nis \\\"5\\\"\";\n")
T(" Flag = True;\n")
T(" Numbers = {1, 2, 3, 4, 5};\n")
T(" Colors = {\"RED\", \"GREEN\", \"BLUE\"};\n")
#if defined(CONFIG_ENABLE_WCHAR)
T(" Unprintable = \"\\X0001\\X0002\\X007F\";\n")
T(" Char = '\\X007F';\n")
#else
T(" Unprintable = \"\\X01\\X02\\X7F\";\n")
T(" Char = '\\X7F';\n")
#endif
T("};\n")
T("\n");
// Construct the serializer:
Serializer ser;
CHECK(ser);
// Construct Class1:
Class1 inst;
CHECK(_ConstructInstance(&inst.__instance, T("Class1")));
// Class1.Key:
inst.Key.exists = MI_TRUE;
inst.Key.value = 56789;
// Class1.Flag:
inst.Flag.exists = MI_TRUE;
inst.Flag.value = MI_TRUE;
// Class1.Msg:
inst.Msg.exists = MI_TRUE;
inst.Msg.value = T("The answer\nis \"5\"");
// Class1.Numbers:
{
static MI_Uint8 data[] = { 1, 2, 3, 4, 5 };
MI_Uint32 size = MI_COUNT(data);
inst.Numbers.exists = MI_TRUE;
inst.Numbers.value.data = data;
inst.Numbers.value.size = size;
}
// Class1.Colors:
{
static MI_Char* data[] = { (MI_Char*)T("RED"), (MI_Char*)T("GREEN"), (MI_Char*)T("BLUE") };
MI_Uint32 size = MI_COUNT(data);
inst.Colors.exists = MI_TRUE;
inst.Colors.value.data = data;
inst.Colors.value.size = size;
}
// Class1.Msg:
{
inst.Unprintable.exists = MI_TRUE;
static const MI_Char str[4] = { 1, 2, 127, '\0' };
inst.Unprintable.value = (MI_Char*)str;
}
// Class1.Char:
inst.Char.exists = MI_TRUE;
inst.Char.value = (MI_Char)127;
// Serialize the instance:
vector<MI_Char> data;
CHECK(ser.SerializeInstance(inst, 0, data));
data.push_back('\0');
// Check against expected buffer:
CHECK(_Diff(&data[0], expect));
}
NitsEndTest
//=============================================================================
//
// TestSerializeLink()
//
//=============================================================================
NitsTest(TestSerializeLink)
{
const MI_Char expect[] =
T("instance of Widget as $Alias00000002\n")
T("{\n")
T(" Key = 1001;\n")
T("};\n")
T("\n")
T("instance of Gadget as $Alias00000003\n")
T("{\n")
T(" Key = 2001;\n")
T("};\n")
T("\n")
T("instance of Link\n")
T("{\n")
T(" Left = $Alias00000002;\n")
T(" Right = $Alias00000003;\n")
T("};\n")
T("\n")
T("instance of Embedded as $Alias00000009\n")
T("{\n")
T(" Key = 3001;\n")
T("};\n")
T("\n")
T("instance of Widget as $Alias0000000A\n")
T("{\n")
T(" Key = 1001;\n")
T(" Emb = $Alias00000009;\n")
T("};\n")
T("\n")
T("instance of Embedded as $Alias0000000B\n")
T("{\n")
T(" Key = 3001;\n")
T("};\n")
T("\n")
T("instance of Embedded as $Alias0000000C\n")
T("{\n")
T(" Key = 3001;\n")
T("};\n")
T("\n")
T("instance of Gadget as $Alias0000000D\n")
T("{\n")
T(" Key = 2001;\n")
T(" Emb = {$Alias0000000B, $Alias0000000C};\n")
T("};\n")
T("\n")
T("instance of Container\n")
T("{\n")
T(" Wid = $Alias0000000A;\n")
T(" Gad = $Alias0000000D;\n")
T("};\n")
T("\n");
// Construct the serializer:
Serializer ser;
CHECK(ser);
// Construct Embedded:
Embedded embedded;
CHECK(_ConstructInstance(&embedded.__instance, T("Embedded")));
// Construct Widget:
Widget widget;
CHECK(_ConstructInstance(&widget.__instance, T("Widget")));
// Construct Gadget:
Gadget gadget;
CHECK(_ConstructInstance(&gadget.__instance, T("Gadget")));
// Construct Link:
Link link;
CHECK(_ConstructInstance(&link.__instance, T("Link")));
Container container;
CHECK(_ConstructInstance(&container.__instance, T("Container")));
// Embedded.Key:
embedded.Key.exists = MI_TRUE;
embedded.Key.value = 3001;
// Widget.Key:
widget.Key.exists = MI_TRUE;
widget.Key.value = 1001;
// Embedded.Key:
widget.Emb.exists = MI_TRUE;
widget.Emb.value = &embedded;
// Gadget.Key:
gadget.Key.exists = MI_TRUE;
gadget.Key.value = 2001;
// Gadget.Emb:
{
static const Embedded* data[2];
data[0] = &embedded;
data[1] = &embedded;
gadget.Emb.exists = MI_TRUE;
gadget.Emb.value.data = (Embedded**)data;
gadget.Emb.value.size = MI_COUNT(data);
}
// Link.Left:
link.Left.exists = MI_TRUE;
link.Left.value = &widget;
// Link.Right:
link.Right.exists = MI_TRUE;
link.Right.value = &gadget;
// Container.Wid:
container.Wid.exists = MI_TRUE;
container.Wid.value = &widget;
// Container.Gad:
container.Gad.exists = MI_TRUE;
container.Gad.value = &gadget;
// Serialize the instance:
vector<MI_Char> data;
CHECK(ser.SerializeInstance(link, 0, data));
CHECK(ser.SerializeInstance(container, 0, data));
data.push_back('\0');
#if 0
wprintf(L"DATA[%s]\n", &data[0]);
#endif
// Check against expected buffer:
CHECK(_Diff(&data[0], expect));
}
NitsEndTest
//=============================================================================
//
// TestSerializeClass2()
//
//=============================================================================
NitsTest(TestSerializeClass2)
{
const MI_Char expect[] =
T("instance of Class2\n")
T("{\n")
T(" Key = 12345;\n")
T(" B = True;\n")
T(" U8 = 8;\n")
T(" S8 = -8;\n")
T(" U16 = 16;\n")
T(" S16 = -16;\n")
T(" U32 = 32;\n")
T(" S32 = -32;\n")
T(" U64 = 64;\n")
T(" S64 = -64;\n")
T(" R32 = 1.00000000000000000000000E+00;\n")
T(" R64 = 1.0000000000000000000000000000000000000000000000000000E+00;\n")
T(" DT1 = \"20101225123011.123456-360\";\n")
T(" DT2 = \"12345678151617.123456:000\";\n")
T(" S = \"Hello World!\";\n")
T(" C16 = 'A';\n")
T(" BA = {True, False, True};\n")
T(" U8A = {0, 255};\n")
T(" S8A = {-128, 127};\n")
T(" U16A = {0, 65535};\n")
T(" S16A = {-32768, 32767};\n")
T(" U32A = {0, 4294967295};\n")
T(" S32A = {-2147483648, 2147483647};\n")
T(" U64A = {0, 18446744073709551615};\n")
T(" S64A = {-9223372036854775808, 9223372036854775807};\n")
T(" R32A = {0.00000000000000000000000E+00};\n")
T(" R64A = {0.0000000000000000000000000000000000000000000000000000E+00};\n")
T(" DTA = {\"20101225123011.123456-360\"};\n")
T(" SA = {\"RED\", \"GREEN\", \"BLUE\"};\n")
T(" C16A = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};\n")
T("};\n")
T("\n");
// Construct the serializer:
Serializer ser;
CHECK(ser);
// Construct Class2:
Class2 inst;
CHECK(_ConstructInstance(&inst.__instance, T("Class2")));
// Class2.Key:
inst.Key.exists = MI_TRUE;
inst.Key.value = 12345;
// Class2.B:
inst.B.exists = MI_TRUE;
inst.B.value = MI_TRUE;
// Class2.U8:
inst.U8.exists = MI_TRUE;
inst.U8.value = 8;
// Class2.S8:
inst.S8.exists = MI_TRUE;
inst.S8.value = -8;
// Class2.U16:
inst.U16.exists = MI_TRUE;
inst.U16.value = 16;
// Class2.S16:
inst.S16.exists = MI_TRUE;
inst.S16.value = -16;
// Class2.U32:
inst.U32.exists = MI_TRUE;
inst.U32.value = 32;
// Class2.S32:
inst.S32.exists = MI_TRUE;
inst.S32.value = -32;
// Class2.U64:
inst.U64.exists = MI_TRUE;
inst.U64.value = 64;
// Class2.S64:
inst.S64.exists = MI_TRUE;
inst.S64.value = -64;
// Class2.R32:
inst.R32.exists = MI_TRUE;
inst.R32.value = 1.0;
// Class2.R64:
inst.R64.exists = MI_TRUE;
inst.R64.value = 1.0;
// Class2.DT1:
MI_Datetime dt1;
dt1.isTimestamp = MI_TRUE;
dt1.u.timestamp.year = 2010;
dt1.u.timestamp.month = 12;
dt1.u.timestamp.day = 25;
dt1.u.timestamp.hour = 12;
dt1.u.timestamp.minute = 30;
dt1.u.timestamp.second = 11;
dt1.u.timestamp.microseconds = 123456;
dt1.u.timestamp.utc = -360;
inst.DT1.exists = MI_TRUE;
inst.DT1.value = dt1;
// Class2.DT2:
MI_Datetime dt2;
dt2.isTimestamp = MI_FALSE;
dt2.u.interval.days = 12345678;
dt2.u.interval.hours = 15;
dt2.u.interval.minutes = 16;
dt2.u.interval.seconds = 17;
dt2.u.interval.microseconds = 123456;
inst.DT2.exists = MI_TRUE;
inst.DT2.value = dt2;
// Class2.S:
inst.S.exists = MI_TRUE;
inst.S.value = T("Hello World!");
// Class2.C16:
inst.C16.exists = MI_TRUE;
inst.C16.value = 'A';
// Class2.BA:
{
static MI_Boolean data[] = { MI_TRUE, MI_FALSE, MI_TRUE };
inst.BA.exists = MI_TRUE;
inst.BA.value.data = data;
inst.BA.value.size = MI_COUNT(data);
}
// Class2.U8A:
{
static MI_Uint8 data[] = { 0, 255 };
inst.U8A.exists = MI_TRUE;
inst.U8A.value.data = data;
inst.U8A.value.size = MI_COUNT(data);
}
// Class2.S8A:
{
static MI_Sint8 data[] = { -128, 127 };
inst.S8A.exists = MI_TRUE;
inst.S8A.value.data = data;
inst.S8A.value.size = MI_COUNT(data);
}
// Class2.U16A:
{
static MI_Uint16 data[] = { 0, 65535 };
inst.U16A.exists = MI_TRUE;
inst.U16A.value.data = data;
inst.U16A.value.size = MI_COUNT(data);
}
// Class2.S16A:
{
static MI_Sint16 data[] = { -32768, 32767 };
inst.S16A.exists = MI_TRUE;
inst.S16A.value.data = data;
inst.S16A.value.size = MI_COUNT(data);
}
// Class2.U32A:
{
static MI_Uint32 data[] = { 0, 4294967295UL };
inst.U32A.exists = MI_TRUE;
inst.U32A.value.data = data;
inst.U32A.value.size = MI_COUNT(data);
}
// Class2.S32A:
{
static MI_Sint32 data[] = { -2147483647-1, 2147483647 };
inst.S32A.exists = MI_TRUE;
inst.S32A.value.data = data;
inst.S32A.value.size = MI_COUNT(data);
}
// Class2.U64A:
{
static MI_Uint64 data[] = { 0, 18446744073709551615ULL };
inst.U64A.exists = MI_TRUE;
inst.U64A.value.data = data;
inst.U64A.value.size = MI_COUNT(data);
}
// Class2.S64A:
{
static MI_Sint64 data[] =
{
-9223372036854775807LL-1LL,
9223372036854775807LL
};
inst.S64A.exists = MI_TRUE;
inst.S64A.value.data = data;
inst.S64A.value.size = MI_COUNT(data);
}
// Class2.R32A:
{
static MI_Real32 data[] = { 0 };
inst.R32A.exists = MI_TRUE;
inst.R32A.value.data = data;
inst.R32A.value.size = MI_COUNT(data);
}
// Class2.R64A:
{
static MI_Real64 data[] = { 0 };
inst.R64A.exists = MI_TRUE;
inst.R64A.value.data = data;
inst.R64A.value.size = MI_COUNT(data);
}
// Class2.DTA:
{
static MI_Datetime data[] = { dt1 };
inst.DTA.exists = MI_TRUE;
inst.DTA.value.data = data;
inst.DTA.value.size = MI_COUNT(data);
}
// Class2.SA
{
static MI_Char* data[] = { (MI_Char*)T("RED"), (MI_Char*)T("GREEN"), (MI_Char*)T("BLUE") };
MI_Uint32 size = MI_COUNT(data);
inst.SA.exists = MI_TRUE;
inst.SA.value.data = data;
inst.SA.value.size = size;
}
// Class2.C16A:
{
static MI_Char16 data[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G' };
MI_Uint32 size = MI_COUNT(data);
inst.C16A.exists = MI_TRUE;
inst.C16A.value.data = data;
inst.C16A.value.size = size;
}
// Serialize the instance:
vector<MI_Char> data;
CHECK(ser.SerializeInstance(inst, 0, data));
data.push_back('\0');
// Check against expected buffer:
CHECK(_Diff(&data[0], expect));
}
NitsEndTest
//=============================================================================
//
// TestSerializeClass1Schema()
//
//=============================================================================
NitsTest(TestSerializeClass1Schema)
{
MI_Class clss;
const MI_Char expect[] =
T("[TERMINAL, Association, Color(\"PINK\"), Flag(False)]\n")
T("class Assoc1 : Assoc0\n")
T("{\n")
T(" [KEY]\n")
T(" Widget REF Left;\n")
T(" Boolean B = True;\n")
T(" [Values{\"PINK\", \"CYAN\", \"MAGENTA\"}, ValueMap{\"1\", \"2\", \"3\"}]\n")
T(" Uint8 U8 = 8;\n")
T(" [Colors{\"RED\", \"GREEN\", \"BLUE\"}]\n")
T(" Sint8 S8 = -8;\n")
T(" Uint16 U16 = 16;\n")
T(" Sint16 S16 = -16;\n")
T(" Uint32 U32 = 32;\n")
T(" Sint32 S32 = -32;\n")
T(" Uint64 U64 = 64;\n")
T(" Sint64 S64 = -64;\n")
T(" Real32 R32 = 0.00000000000000000000000E+00;\n")
T(" Real64 R64 = 0.0000000000000000000000000000000000000000000000000000E+00;\n")
T(" Datetime DT1 = \"20101225123011.123456-360\";\n")
T(" Datetime DT2 = \"12345678151617.123456:000\";\n")
T(" String S = \"My String\";\n")
T(" Char16 C16 = 'A';\n")
T(" Boolean BA[] = {True, False};\n")
T(" Uint8 U8A[] = {8};\n")
T(" Sint8 S8A[] = {-8, 0, 8};\n")
T(" Uint16 U16A[] = {16};\n")
T(" Sint16 S16A[] = {-16, 0, 16};\n")
T(" Uint32 U32A[] = {32};\n")
T(" Sint32 S32A[] = {-32, 0, 32};\n")
T(" Uint64 U64A[] = {64};\n")
T(" Sint64 S64A[] = {-64, 0, 64};\n")
T(" Real32 R32A[] = {0.00000000000000000000000E+00};\n")
T(" Real64 R64A[] = {0.0000000000000000000000000000000000000000000000000000E+00};\n")
T(" Datetime DTA[] = {\"20101225123011.123456-360\", \"12345678151617.123456:000\"};\n")
T(" String SA[] = {\"One\", \"Two\"};\n")
T(" Char16 C16A[] = {'A', 'B', 'C'};\n")
T(" [STATIC, Description(\"Fool\"), Color(\"Blue\")]\n")
T(" Uint32 Foo(\n")
T(" [IN]\n")
T(" Real32 X,\n")
T(" [IN]\n")
T(" Real32 Y,\n")
T(" [IN(False), OUT]\n")
T(" Real32 Z);\n")
T(" [Description(\"Foo2\")]\n")
T(" String Foo2(\n")
T(" [IN]\n")
T(" Widget REF WidIn,\n")
T(" [IN]\n")
T(" Gadget REF GadIn,\n")
T(" [IN]\n")
T(" Boolean BIn,\n")
T(" [IN]\n")
T(" Uint8 U8In,\n")
T(" [IN]\n")
T(" Sint8 S8In,\n")
T(" [IN]\n")
T(" Uint16 U16In,\n")
T(" [IN]\n")
T(" Sint16 S16In,\n")
T(" [IN]\n")
T(" Uint32 U32In,\n")
T(" [IN]\n")
T(" Sint32 S32In,\n")
T(" [IN]\n")
T(" Uint64 U64In,\n")
T(" [IN]\n")
T(" Sint64 S64In,\n")
T(" [IN]\n")
T(" Real32 R32In,\n")
T(" [IN]\n")
T(" Real64 R64In,\n")
T(" [IN]\n")
T(" Datetime DT1In,\n")
T(" [IN]\n")
T(" Datetime DT2In,\n")
T(" [IN]\n")
T(" String SIn,\n")
T(" [IN]\n")
T(" Char16 C16In,\n")
T(" [IN]\n")
T(" Boolean BAIn[],\n")
T(" [IN]\n")
T(" Uint8 U8AIn[],\n")
T(" [IN]\n")
T(" Sint8 S8AIn[],\n")
T(" [IN]\n")
T(" Uint16 U16AIn[],\n")
T(" [IN]\n")
T(" Sint16 S16AIn[],\n")
T(" [IN]\n")
T(" Uint32 U32AIn[],\n")
T(" [IN]\n")
T(" Sint32 S32AIn[],\n")
T(" [IN]\n")
T(" Uint64 U64AIn[],\n")
T(" [IN]\n")
T(" Sint64 S64AIn[],\n")
T(" [IN]\n")
T(" Real32 R32AIn[],\n")
T(" [IN]\n")
T(" Real64 R64AIn[],\n")
T(" [IN]\n")
T(" Datetime DTAIn[],\n")
T(" [IN]\n")
T(" String SAIn[],\n")
T(" [IN]\n")
T(" Char16 C16AIn[],\n")
T(" [IN(False), OUT]\n")
T(" Widget REF WidOut,\n")
T(" [IN(False), OUT]\n")
T(" Gadget REF GadOut,\n")
T(" [IN(False), OUT]\n")
T(" Boolean BOut,\n")
T(" [IN(False), OUT]\n")
T(" Uint8 U8Out,\n")
T(" [IN(False), OUT]\n")
T(" Sint8 S8Out,\n")
T(" [IN(False), OUT]\n")
T(" Uint16 U16Out,\n")
T(" [IN(False), OUT]\n")
T(" Sint16 S16Out,\n")
T(" [IN(False), OUT]\n")
T(" Uint32 U32Out,\n")
T(" [IN(False), OUT]\n")
T(" Sint32 S32Out,\n")
T(" [IN(False), OUT]\n")
T(" Uint64 U64Out,\n")
T(" [IN(False), OUT]\n")
T(" Sint64 S64Out,\n")
T(" [IN(False), OUT]\n")
T(" Real32 R32Out,\n")
T(" [IN(False), OUT]\n")
T(" Real64 R64Out,\n")
T(" [IN(False), OUT]\n")
T(" Datetime DT1Out,\n")
T(" [IN(False), OUT]\n")
T(" Datetime DT2Out,\n")
T(" [IN(False), OUT]\n")
T(" String SOut,\n")
T(" [IN(False), OUT]\n")
T(" Char16 C16Out,\n")
T(" [IN(False), OUT]\n")
T(" Boolean BAOut[],\n")
T(" [IN(False), OUT]\n")
T(" Uint8 U8AOut[],\n")
T(" [IN(False), OUT]\n")
T(" Sint8 S8AOut[],\n")
T(" [IN(False), OUT]\n")
T(" Uint16 U16AOut[],\n")
T(" [IN(False), OUT]\n")
T(" Sint16 S16AOut[],\n")
T(" [IN(False), OUT]\n")
T(" Uint32 U32AOut[],\n")
T(" [IN(False), OUT]\n")
T(" Sint32 S32AOut[],\n")
T(" [IN(False), OUT]\n")
T(" Uint64 U64AOut[],\n")
T(" [IN(False), OUT]\n")
T(" Sint64 S64AOut[],\n")
T(" [IN(False), OUT]\n")
T(" Real32 R32AOut[],\n")
T(" [IN(False), OUT]\n")
T(" Real64 R64AOut[],\n")
T(" [IN(False), OUT]\n")
T(" Datetime DTAOut[],\n")
T(" [IN(False), OUT]\n")
T(" String SAOut[],\n")
T(" [IN(False), OUT]\n")
T(" Char16 C16AOut[],\n")
T(" [IN, OUT]\n")
T(" Widget REF WidInOut,\n")
T(" [IN, OUT]\n")
T(" Gadget REF GadInOut,\n")
T(" [IN, OUT]\n")
T(" Boolean BInOut,\n")
T(" [IN, OUT]\n")
T(" Uint8 U8InOut,\n")
T(" [IN, OUT]\n")
T(" Sint8 S8InOut,\n")
T(" [IN, OUT]\n")
T(" Uint16 U16InOut,\n")
T(" [IN, OUT]\n")
T(" Sint16 S16InOut,\n")
T(" [IN, OUT]\n")
T(" Uint32 U32InOut,\n")
T(" [IN, OUT]\n")
T(" Sint32 S32InOut,\n")
T(" [IN, OUT]\n")
T(" Uint64 U64InOut,\n")
T(" [IN, OUT]\n")
T(" Sint64 S64InOut,\n")
T(" [IN, OUT]\n")
T(" Real32 R32InOut,\n")
T(" [IN, OUT]\n")
T(" Real64 R64InOut,\n")
T(" [IN, OUT]\n")
T(" Datetime DT1InOut,\n")
T(" [IN, OUT]\n")
T(" Datetime DT2InOut,\n")
T(" [IN, OUT]\n")
T(" String SInOut,\n")
T(" [IN, OUT]\n")
T(" Char16 C16InOut,\n")
T(" [IN, OUT]\n")
T(" Boolean BAInOut[],\n")
T(" [IN, OUT]\n")
T(" Uint8 U8AInOut[],\n")
T(" [IN, OUT]\n")
T(" Sint8 S8AInOut[],\n")
T(" [IN, OUT]\n")
T(" Uint16 U16AInOut[],\n")
T(" [IN, OUT]\n")
T(" Sint16 S16AInOut[],\n")
T(" [IN, OUT]\n")
T(" Uint32 U32AInOut[],\n")
T(" [IN, OUT]\n")
T(" Sint32 S32AInOut[],\n")
T(" [IN, OUT]\n")
T(" Uint64 U64AInOut[],\n")
T(" [IN, OUT]\n")
T(" Sint64 S64AInOut[],\n")
T(" [IN, OUT]\n")
T(" Real32 R32AInOut[],\n")
T(" [IN, OUT]\n")
T(" Real64 R64AInOut[],\n")
T(" [IN, OUT]\n")
T(" Datetime DTAInOut[],\n")
T(" [IN, OUT]\n")
T(" String SAInOut[],\n")
T(" [IN, OUT]\n")
T(" Char16 C16AInOut[]);\n")
T("};\n")
T("\n");
// Create the class.
CHECK(_ConstructClass(&clss, T("Assoc1")));
// Construct the serializer:
Serializer ser;
CHECK(ser);
// Serialize the class:
vector<MI_Char> data;
CHECK(ser.SerializeClass(&clss, 0, data));
data.push_back('\0');
#if 0
wprintf(L"DATA[%s]\n", &data[0]);
#endif
// Check against expected buffer:
CHECK(_Diff(&data[0], expect));
}
NitsEndTest
//=============================================================================
//
// TestSerializeContainerSchema()
//
//=============================================================================
NitsTest(TestSerializeContainerSchema)
{
MI_Class clss;
const MI_Char expect[] =
T("class Container\n")
T("{\n")
T(" [KEY]\n")
T(" Uint32 Key;\n")
T(" [EmbeddedInstance(\"Widget\")]\n")
T(" String Wid;\n")
T(" [EmbeddedInstance(\"Gadget\")]\n")
T(" String Gad;\n")
T(" Uint32 Foo1();\n")
T(" Uint32 Foo2(\n")
T(" [IN, EmbeddedInstance(\"Widget\")]\n")
T(" String Wid,\n")
T(" [IN(False), OUT, EmbeddedInstance(\"Gadget\")]\n")
T(" String Gad);\n")
T("};\n")
T("\n");
// Create the class.
CHECK(_ConstructClass(&clss, T("Container")));
// Construct the serializer:
Serializer ser;
CHECK(ser);
// Serialize the class:
vector<MI_Char> data;
CHECK(ser.SerializeClass(&clss, 0, data));
data.push_back('\0');
#if 0
wprintf(L"DATA[%s]\n", &data[0]);
#endif
// Check against expected buffer:
CHECK(_Diff(&data[0], expect));
}
NitsEndTest
//=============================================================================
//
// TestSerializeSubClassSchema()
//
//=============================================================================
NitsTest(TestSerializeSubClassSchema)
{
MI_Class clss;
const MI_Char expect[] =
T("[ABSTRACT]\n")
T("class SuperClass\n")
T("{\n")
T(" [KEY]\n")
T(" String Key;\n")
T("};\n")
T("\n")
T("[TERMINAL]\n")
T("class SubClass : SuperClass\n")
T("{\n")
T(" [KEY]\n")
T(" String Key;\n")
T(" Uint32 Count;\n")
T(" String Color;\n")
T("};\n")
T("\n");
// Create the class.
CHECK(_ConstructClass(&clss, T("SubClass")));
// Construct the serializer:
Serializer ser;
CHECK(ser);
// Serialize the class:
vector<MI_Char> data;
CHECK(ser.SerializeClass(&clss, MI_SERIALIZER_FLAGS_CLASS_DEEP, data));
data.push_back('\0');
#if 0
wprintf(L"DATA[%s]\n", &data[0]);
#endif
// Check against expected buffer:
CHECK(_Diff(&data[0], expect));
}
NitsEndTest
//=============================================================================
//
// TestSerializeSubClass()
//
//=============================================================================
NitsTest(TestSerializeSubClass)
{
const MI_Char expect[] =
T("[ABSTRACT]\n")
T("class SuperClass\n")
T("{\n")
T(" [KEY]\n")
T(" String Key;\n")
T("};\n")
T("\n")
T("[TERMINAL]\n")
T("class SubClass : SuperClass\n")
T("{\n")
T(" [KEY]\n")
T(" String Key;\n")
T(" Uint32 Count;\n")
T(" String Color;\n")
T("};\n")
T("\n")
T("instance of SubClass\n")
T("{\n")
T(" Key = \"Red\";\n")
T("};\n")
T("\n");
// Construct the serializer:
Serializer ser;
CHECK(ser);
// Construct SubClass:
SubClass inst;
CHECK(_ConstructInstance(&inst.__instance, T("SubClass")));
// SubClass.Key:
inst.Key.exists = MI_TRUE;
inst.Key.value = T("Red");
// Serialize the instance:
vector<MI_Char> data;
CHECK(ser.SerializeInstance(
inst,
MI_SERIALIZER_FLAGS_CLASS_DEEP|MI_SERIALIZER_FLAGS_INSTANCE_WITH_CLASS,
data));
data.push_back('\0');
#if 0
wprintf(L"DATA[%s]\n", &data[0]);
#endif
// Check against expected buffer:
CHECK(_Diff(&data[0], expect));
}
NitsEndTest
//=============================================================================
//
// TestSerializeThing()
//
//=============================================================================
NitsTest(TestSerializeThing)
{
const MI_Char expect[] =
T("instance of Embedded as $Alias00000001\n")
T("{\n")
T(" Key = 1001;\n")
T("};\n")
T("\n")
T("instance of Thing\n")
T("{\n")
T(" Key = 2001;\n")
T(" Obj = $Alias00000001;\n")
T("};\n")
T("\n");
// Construct the serializer:
Serializer ser;
CHECK(ser);
// Construct Embedded:
Embedded embedded;
CHECK(_ConstructInstance(&embedded.__instance, T("Embedded")));
// Construct Widget:
Thing thing;
CHECK(_ConstructInstance(&thing.__instance, T("Thing")));
// Embedded.Key:
embedded.Key.exists = MI_TRUE;
embedded.Key.value = 1001;
// Thing.Key:
thing.Key.exists = MI_TRUE;
thing.Key.value = 2001;
// Thing.Obj:
thing.Obj.exists = MI_TRUE;
thing.Obj.value = &embedded.__instance;
// Serialize the instance:
vector<MI_Char> data;
CHECK(ser.SerializeInstance(thing, 0, data));
data.push_back('\0');
#if 0
wprintf(L"DATA[%s]\n", &data[0]);
#endif
// Check against expected buffer:
CHECK(_Diff(&data[0], expect));
}
NitsEndTest
//=============================================================================
//
// TestSerializeThingSchema()
//
//=============================================================================
NitsTest(TestSerializeThingSchema)
{
MI_Class clss;
const MI_Char expect[] =
T("class Thing\n")
T("{\n")
T(" [KEY]\n")
T(" Uint32 Key;\n")
T(" [EmbeddedObject]\n")
T(" String Obj;\n")
T("};\n")
T("\n");
// Create the class.
CHECK(_ConstructClass(&clss, T("Thing")));
// Construct the serializer:
Serializer ser;
CHECK(ser);
// Serialize the class:
vector<MI_Char> data;
CHECK(ser.SerializeClass(&clss, MI_SERIALIZER_FLAGS_CLASS_DEEP, data));
data.push_back('\0');
#if 0
wprintf(L"DATA[%s]\n", &data[0]);
#endif
// Check against expected buffer:
CHECK(_Diff(&data[0], expect));
}
NitsEndTest
//=============================================================================
//
// TestSerializeClass2EmptyArray()
//
//=============================================================================
NitsTest(TestSerializeClass2EmptyArray)
{
const MI_Char expect[] =
T("instance of Class2\n")
T("{\n")
T(" SA = {};\n")
T(" C16A = {};\n")
T("};\n")
T("\n");
// Construct the serializer:
Serializer ser;
CHECK(ser);
// Construct Class2:
Class2 inst;
CHECK(_ConstructInstance(&inst.__instance, T("Class2")));
// Class2.SA
{
inst.SA.exists = MI_TRUE;
inst.SA.value.data = NULL;
inst.SA.value.size = 0;
}
// Class2.C16A:
{
inst.C16A.exists = MI_TRUE;
inst.C16A.value.data = NULL;
inst.C16A.value.size = 0;
}
// Serialize the instance:
vector<MI_Char> data;
CHECK(ser.SerializeInstance(inst, 0, data));
data.push_back('\0');
// Check against expected buffer:
CHECK(_Diff(&data[0], expect));
}
NitsEndTest
| 26.501742 | 99 | 0.440941 | [
"vector"
] |
f433f9227dd8258e64827f53ce1025e0f5810672 | 525 | hpp | C++ | src/SmaCounter.hpp | BitsonFire/signal-estimator | 7348473517d64b95f7ca9b34e07bfdd2236ffa7f | [
"MIT"
] | null | null | null | src/SmaCounter.hpp | BitsonFire/signal-estimator | 7348473517d64b95f7ca9b34e07bfdd2236ffa7f | [
"MIT"
] | null | null | null | src/SmaCounter.hpp | BitsonFire/signal-estimator | 7348473517d64b95f7ca9b34e07bfdd2236ffa7f | [
"MIT"
] | null | null | null | /* Copyright (c) 2020 Victor Gaydov
*
* This code is licensed under the MIT License.
*/
#pragma once
#include <vector>
namespace signal_estimator {
// simple moving average
class SmaCounter {
public:
SmaCounter(size_t size);
SmaCounter(const SmaCounter&) = delete;
SmaCounter& operator=(const SmaCounter&) = delete;
double add(double);
private:
std::vector<double> window_;
size_t head_ {};
size_t tail_ {};
size_t size_ {};
double avg_ {};
};
} // namespace signal_estimator
| 15.909091 | 54 | 0.670476 | [
"vector"
] |
f437d1a1975a7f0a4698dea0faf7c1309ad1bdba | 1,007 | cpp | C++ | countingSort/main.cpp | Luke-zhang-04/Sorting_Algorithms | dc89ce0f1651252b30509062fddff72d423689a3 | [
"Unlicense"
] | 1 | 2020-01-03T10:09:33.000Z | 2020-01-03T10:09:33.000Z | countingSort/main.cpp | Luke-zhang-04/Sorting_Algorithms | dc89ce0f1651252b30509062fddff72d423689a3 | [
"Unlicense"
] | 1 | 2020-06-11T13:46:57.000Z | 2020-06-11T13:46:57.000Z | countingSort/main.cpp | Luke-zhang-04/Sorting_Algorithms | dc89ce0f1651252b30509062fddff72d423689a3 | [
"Unlicense"
] | 2 | 2020-01-03T10:17:39.000Z | 2020-06-13T06:15:17.000Z | #include <vector>
#include "main.h"
#include "../utils/max.h"
/**
* Main countingsort function
* @param array - array to sort
* @returns void; sorts in-place
*/
void countingSort(std::vector<int> &array) {
std::vector<int> count;
std::vector<int> output; //create output array
// Fill arrays
for (unsigned int i = 0; i < max(array) + 1; i++) {
count.push_back(0);
} for (unsigned int i = 0; i < array.size(); i++) {
count[array[i]]++;
}
// Iterate through given array, and add 1 to the index which is the value of array[i]
for (unsigned int i = 1; i < count.size(); i++) {
count[i] += count[i-1];
}
// Go through array and add previous index's value to the current index
for (unsigned int i = 0; i < array.size(); i++) {
output.push_back(0);
}
// Iterate through array and plug in sorted values
for (const int &i : array) {
output[count[i]-1] = i;
count[i]--;
}
array = output;
}
| 25.175 | 89 | 0.571003 | [
"vector"
] |
f442a07345c2199fcd0577657de431756d95ecc3 | 5,211 | cpp | C++ | src/mio/http_server.cpp | Ryooooooga/mio | 9ec4e0819eb0eda35e4a4a314ca6aa8aeeedcd9d | [
"MIT"
] | 1 | 2021-09-14T15:07:23.000Z | 2021-09-14T15:07:23.000Z | src/mio/http_server.cpp | Ryooooooga/mio | 9ec4e0819eb0eda35e4a4a314ca6aa8aeeedcd9d | [
"MIT"
] | null | null | null | src/mio/http_server.cpp | Ryooooooga/mio | 9ec4e0819eb0eda35e4a4a314ca6aa8aeeedcd9d | [
"MIT"
] | null | null | null | #include "mio/http_server.hpp"
#include <cassert>
#include <sstream>
#include <thread>
#include <netinet/in.h>
#include <unistd.h>
#include "mio/application.hpp"
#include "mio/bodies/x_www_form_url_encoded.hpp"
#include "mio/http1/request.hpp"
#include "mio/http1/response.hpp"
#include "mio/sockets/socket.hpp"
#include "mio/util/trim.hpp"
namespace mio {
namespace {
constexpr std::size_t max_header_size = 4096;
constexpr std::size_t max_header_lines = 100;
http1::response convert_to_http1_response(const http_response& from, std::span<http1::header> buffer) {
http1::response res{};
res.http_version = "HTTP/1.1";
res.status_code = from.status_code();
size_t n = 0;
for (const auto& header_entries = from.headers().entries(); n < header_entries.size() && n < buffer.size(); n++) {
buffer[n].key = header_entries[n].key;
buffer[n].value = header_entries[n].value;
}
res.headers = buffer.subspan(0, n);
res.body = from.body();
return res;
}
} // namespace
http_server::http_server(std::unique_ptr<application>&& app)
: app_(std::move(app)) {
assert(app_);
}
http_server::~http_server() noexcept = default;
void http_server::listen(std::uint16_t port) {
sockets::socket socket{sockets::address_family::inet, sockets::socket_type::stream};
socket.set_reuse_addr(true);
socket.listen(port);
for (;;) {
std::thread{&http_server::on_client_accepted, this, socket.accept()}.detach();
}
}
void http_server::on_client_accepted(http_server* self, sockets::socket client_socket) noexcept {
const auto& app = self->app_;
bool keep_alive;
do {
char buffer[max_header_size];
http1::header headers[max_header_lines];
http_response res{500};
try {
std::size_t pos = 0;
std::size_t header_size;
http1::request http1_req{};
// TODO: too large request header
for (;;) {
const auto size_read = client_socket.receive(buffer + pos, max_header_size - pos);
if (size_read == 0) {
return; // Connection closed.
}
pos += size_read;
const auto parse_result = http1::parse_request(http1_req, headers, std::string_view{buffer, pos}, header_size);
if (parse_result == http1::parse_result::completed) {
break;
} else if (parse_result == http1::parse_result::in_progress) {
continue;
} else {
throw std::runtime_error{"invalid request"};
}
}
http_headers headers{};
for (const auto& header : http1_req.headers) {
headers.append(header.key, header.value);
}
std::vector<std::byte> body(reinterpret_cast<const std::byte*>(buffer + header_size), reinterpret_cast<const std::byte*>(buffer + pos));
body.resize(headers.content_length());
for (pos -= header_size; pos < headers.content_length();) {
const auto size_read = client_socket.receive(body.data() + pos, headers.content_length() - pos);
if (size_read == 0) {
return; // Connection closed.
}
pos += size_read;
}
http_request req{
http1_req.method,
http1_req.request_uri,
http1_req.http_version,
std::move(headers),
std::move(body),
};
keep_alive = req.headers().get("connection") == "keep-alive";
req.headers().remove("connection");
req.headers().remove("keep-alive");
if (const auto content_type = req.headers().get("content-type")) {
const auto type = util::trim(content_type->substr(0, content_type->find(';')));
if (type == "application/x-www-form-urlencoded") {
bodies::parse_x_www_form_url_encoded(req);
}
}
res = app->on_request(req);
} catch (const std::exception& e) {
res = app->on_error(e);
} catch (...) {
res = app->on_unknown_error();
}
try {
res.headers().set("connection", keep_alive ? "keep-alive" : "close");
const auto http1_res = convert_to_http1_response(res, headers);
std::ostringstream oss;
http1::write_response(oss, http1_res);
const auto s = oss.str();
client_socket.send(s.data(), s.size());
} catch (...) {
}
} while (keep_alive);
}
} // namespace mio
| 35.209459 | 152 | 0.517367 | [
"vector"
] |
f45f56cdae5e213f321a3523057c330ea0265d75 | 10,974 | cpp | C++ | ctf.cpp | KhodrJ/FastCTF | 61a836fa558b2e97b00a0c34ccddbb3d7e4103a9 | [
"MIT"
] | 2 | 2021-12-09T23:39:03.000Z | 2021-12-17T18:07:56.000Z | ctf.cpp | KhodrJ/FastCTF | 61a836fa558b2e97b00a0c34ccddbb3d7e4103a9 | [
"MIT"
] | null | null | null | ctf.cpp | KhodrJ/FastCTF | 61a836fa558b2e97b00a0c34ccddbb3d7e4103a9 | [
"MIT"
] | null | null | null | /*
* ==================================================================================
*
* ______ _ _____ _______ ______
* | ____| | | / ____|__ __| ____|
* | |__ __ _ ___| |_| | | | | |__
* | __/ _` / __| __| | | | | __|
* | | | (_| \__ \ |_| |____ | | | |
* |_| \__,_|___/\__|\_____| |_| |_|
*
*
* FastCTF: A Robust Solver for Conduction Transfer Function Coefficients
*
* Date: 28 March, 2021
* Author: Khodr Jaber
*
*
*
* A simple code that computes both conduction transfer functions and response factors based on Taylor series expansions of the Laplace domain solution to the one-dimensional heat equation. The inversion of this approximated solution is performed by generating a polynomial s-transfer function and applying the residue theorem. The z-transfer function is then applied to recover the CTFs and response factors.
*
* ==================================================================================
*/
#include "c_poly.h"
Poly GetSeriesT_00(int ord, double L, double alpha)
{
VCD coeffs = {};
for (int i = 0; i <= ord; i++)
coeffs.push_back( pow(L / sqrt(alpha), 2*i) / factorial(2*i) );
return Poly(coeffs);
}
Poly GetSeriesT_01(int ord, double L, double R, double alpha)
{
VCD coeffs = {};
for (int i = 0; i <= ord; i++)
coeffs.push_back( (R/L) * pow(L, 2*i+1) * pow(1.0 / sqrt(alpha), 2*i) / factorial(2*i+1) );
return Poly(coeffs);
}
Poly GetSeriesT_10(int ord, double L, double k, double alpha)
{
VCD coeffs = {0.0};
for (int i = 0; i < ord; i++)
coeffs.push_back( k * pow(L, 2*i+1) * pow(1.0 / sqrt(alpha), 2*(i+1)) / factorial(2*i+1) );
return Poly(coeffs);
}
Poly TFtoTaylor(Poly Num, Poly Den, int length)
{
VCD coeffs = {};
coeffs.push_back(Num.coeffs[0] / Den.coeffs[0]);
for (int i = 1; i < Den.coeffs.size(); i++)
{
cdouble sum = 0;
for (int j = 0; j < i; j++)
sum += coeffs[j] * Den.coeffs[i-j];
coeffs.push_back( (Num.coeffs[i] - sum) / Den.coeffs[0] );
}
for (int i = 0; i < length; i++)
{
cdouble sum = 0;
for (int j = 0; j < Den.coeffs.size()-1; j++)
sum += coeffs[j+i+1] * Den.coeffs[Den.coeffs.size()-1-j];
coeffs.push_back( -sum / Den.coeffs[0] );
}
return Poly(coeffs);
}
std::pair<Poly,Poly> ZTransform(cdouble res, cdouble root, int mult)
{
double A = -TIME_STEP * root.real();
double B = -TIME_STEP * root.imag();
double C = 2.0 * res.real();
double D = 2.0 * res.imag();
Poly Num(VCD{0});
Poly Den(VCD{0});
Poly z(VCD{0.0, -1.0});
if (root.imag() != 0.0)
{
Num = Poly(VCD {0.0, exp(A)*(D*sin(B) - C*cos(B)), C*exp(2*A)});
Den = Poly(VCD {1.0, -2*exp(A)*cos(B), exp(2*A)});
}
if (root.imag() == 0.0)
{
if (root.real() != 0.0)
{
Num = Poly(VCD {0.0, res.real()*exp(A)});
Den = Poly(VCD {-1.0, exp(A)});
}
else
std::cout << "Oops..." << std::endl;
}
return std::make_pair(Num, Den);
}
std::tuple<Poly, Poly, Poly> GetZTF(Poly Num, Poly Den, double U, int N_k)
{
// First: Numerator of z-transfer function.
// Second: Denominator of z-transfer function.
// Third: Response factors.
std::pair<VCD, std::vector<int>> RaR = RootsPoly(Den);
VCD roots = RaR.first;
std::vector<int> reps = RaR.second;
int N = roots.size();
Poly ZNum(VCD{0.0});
Poly ZDen(VCD{1.0});
std::vector<Poly> M_bar;
for (int i = 0; i < N; i++)
M_bar.push_back(Poly(VCD {1.0}));
// Get residues of linear and constant term.
cdouble alpha_1 = 0.0;
cdouble alpha_2 = TIME_STEP * U;
// Compute transfer function.
for (int i = 0; i < N; i++)
{
cdouble res = Residue(roots[i], 1, 1, Num, Den);
alpha_1 -= res;
if (fabs(res.imag()) > 0)
alpha_1 -= c(res.real(), -res.imag());
std::pair<Poly, Poly> ztf = ZTransform(res, roots[i], 1);
M_bar[i] = M_bar[i]*ztf.first;
for (int j = 0; j < N; j++)
if (j != i)
M_bar[j] = M_bar[j]*ztf.second;
ZDen = ZDen * ztf.second;
}
// Assemble.
Poly ZM_bar = Poly(VCD {0.0});
for (int i = 0; i < N; i++)
ZM_bar = ZM_bar + M_bar[i];
alpha_1 = -ZM_bar.coeffs[ZM_bar.Degree()] / ZDen.coeffs[ZDen.Degree()];
Poly M_bar_poly = ZM_bar;
Poly M_bar_z_poly = ZM_bar * Poly(VCD {0.0, 1.0});
Poly M_bar_zm_poly = ZM_bar; M_bar_zm_poly.coeffs.erase(M_bar_zm_poly.coeffs.begin());
ZNum = ZDen * Poly(VCD {alpha_2-alpha_1, alpha_1}) + (M_bar_z_poly + Poly(VCD {-2.0})*ZM_bar + M_bar_zm_poly);
if (ZNum.Degree() > ZDen.Degree())
ZNum.coeffs.erase(ZNum.coeffs.end()-1);
cdouble normal = 1.0 / ZDen.coeffs[ZDen.Degree()];
ZNum = ZNum * Poly(VCD {normal / TIME_STEP});
ZDen = ZDen * Poly(VCD {normal});
// Compute response factors.
Poly Yk = Poly(VCD {0});
Poly Ykin = Poly(VCD {0});
Poly ZNum_F = ZNum; ZNum_F.Flip();
Poly ZDen_F = ZDen; ZDen_F.Flip();
Yk = TFtoTaylor(ZNum_F, ZDen_F, N_k);
return std::make_tuple(ZNum, ZDen, Yk);
}
std::pair<Poly, Poly> Pade(Poly taylor, int m, int n)
{
VCD vec_num = {};
VCD vec_den = {1.0};
int N = m+n+1;
int NRHS = 1;
double *A = new double[N*N]{0.0};
int LDA = N;
int *IPIV = new int[N];
double *B = new double[N];
int LDB = N;
int INFO;
for (int i = 0; i < n+1; i++)
{
A[i+N*i] = -1.0;
B[i] = -taylor.coeffs[i].real();
for (int j = n+1; j < (n+1)+i; j++)
A[i+N*j] = taylor.coeffs[i - (j-(n+1)+1)].real();
}
for (int i = n+1; i < N; i++)
{
B[i] = -taylor.coeffs[m+1 + (i-(n+1))].real();
for (int j = n+1; j < N; j++)
A[i+N*j] = taylor.coeffs[(i-(n+1)) + (m+1)-1 - (j-(n+1))].real();
}
dgesv_(&N, &NRHS, A, &LDA, IPIV, B, &LDB, &INFO);
for (int i = 0; i < n+1; i++)
vec_num.push_back(B[i]);
for (int i = n+1; i < N; i++)
vec_den.push_back(B[i]);
delete[] A, B, IPIV;
return std::make_pair(Poly(vec_num), Poly(vec_den));
}
Poly TaylorRecover(Poly Num, Poly Den, Poly Q)
{
Poly P(VCD {0});
Poly NQ = Num*Q;
for (int i = 0; i < Q.coeffs.size(); i++)
{
cdouble sum = 0.0;
for (int j = 0; j < i; j++)
sum += P.coeffs[j] * Den.coeffs[i-j];
P.coeffs.push_back( (NQ.coeffs[i] - sum) / Den.coeffs[0] );
}
return P;
}
int main(int argc, char *argv[])
{
int i, j, N, N_layers, ord, p_ord, N_k;
double R_o, R_i, **layer_dat;
std::ifstream input;
std::ofstream output_x, output_y, output_z;
// Read input.
input.open("input.txt");
input >> N_layers >> R_o >> R_i;
layer_dat = new double*[N_layers];
for (i = 0; i < N_layers; i++)
{
layer_dat[i] = new double[5];
for (j = 0; j < 5; j++)
input >> layer_dat[i][j];
}
input.close();
for (i = 0; i < N_layers; i++)
{
if (layer_dat[i][0] != 0)
layer_dat[i][4] = 0.001*layer_dat[i][0] / layer_dat[i][1];
}
// Compute U value.
double U = 0.0;
for (i = 0; i < N_layers; i++)
U += layer_dat[i][4];
U = 1.0/(U+R_i+R_o);
// Parameters.
ord = 20;
p_ord = 5;
N_k = 144;
N = 50;
// STEP ONE: Compute transmission matrix polynomials.
Poly T_00 = Poly(VCD {1.0});
Poly T_01 = Poly(VCD {R_o});
Poly T_10 = Poly(VCD {0.0});
Poly T_11 = Poly(VCD {1.0});
Poly T_00_t = Poly(VCD {0});
Poly T_01_t = Poly(VCD {0});
Poly T_10_t = Poly(VCD {0});
Poly T_11_t = Poly(VCD {0});
for (i = 0; i < N_layers+1; i++)
{
if (i < N_layers)
{
double L_i = layer_dat[i][0]*0.001;
double k_i = layer_dat[i][1];
double rho_i = layer_dat[i][2];
double C_pi = layer_dat[i][3];
double R_i_ = layer_dat[i][4];
double alpha_i = k_i / (rho_i*C_pi);
if (L_i != 0)
{
T_00_t = GetSeriesT_00(ord, L_i, alpha_i);
T_01_t = GetSeriesT_01(ord, L_i, R_i_, alpha_i);
T_10_t = GetSeriesT_10(ord, L_i, k_i, alpha_i);
T_11_t = GetSeriesT_00(ord, L_i, alpha_i);
}
else
{
T_00_t = Poly(VCD {1.0});
T_01_t = Poly(VCD {R_i_});
T_10_t = Poly(VCD {0.0});
T_11_t = Poly(VCD {1.0});
}
}
else
{
T_00_t = Poly(VCD {1.0});
T_01_t = Poly(VCD {R_i});
T_10_t = Poly(VCD {0.0});
T_11_t = Poly(VCD {1.0});
}
Poly T_00_tmp = T_00_t*T_00 + T_01_t*T_10;
Poly T_01_tmp = T_00_t*T_01 + T_01_t*T_11;
Poly T_10_tmp = T_10_t*T_00 + T_11_t*T_10;
Poly T_11_tmp = T_10_t*T_01 + T_11_t*T_11;
T_00 = T_00_tmp;
T_01 = T_01_tmp;
T_10 = T_10_tmp;
T_11 = T_11_tmp;
}
// STEP TWO: Compute inversion and assemble transfer functions.
// Cross.
Poly NumS_Y(VCD {1.0});
Poly DenS_Y = T_01;
std::pair<Poly, Poly> PadeS_Y = Pade(DenS_Y, p_ord, p_ord);
std::tuple<Poly, Poly, Poly> PadeZ_Y = GetZTF(PadeS_Y.second, Poly(VCD {0, 0, 1}) * PadeS_Y.first, U, N_k);
Poly Yk_Y = std::get<2>(PadeZ_Y);
std::cout << "Verification of Y: " << std::get<0>(PadeZ_Y).SumCoeffs() / std::get<1>(PadeZ_Y).SumCoeffs() << std::endl;
// External.
Poly NumS_X(VCD {0}), DenS_X(VCD {0});
for (int i = 0; i < p_ord+1; i++)
{
//NumS_X.coeffs.push_back(T_00.coeffs[i]);
//DenS_X.coeffs.push_back(T_01.coeffs[i]);
}
DenS_X = PadeS_Y.first;
NumS_X = TaylorRecover(T_00, T_01, DenS_X);
std::tuple<Poly, Poly, Poly> PadeZ_X = GetZTF(NumS_X, Poly(VCD {0, 0, 1}) * DenS_X, U, N_k);
Poly Yk_X = std::get<2>(PadeZ_X);
std::cout << "Verification of X: " << std::get<0>(PadeZ_X).SumCoeffs() / std::get<1>(PadeZ_X).SumCoeffs() << std::endl;
//Internal.
Poly NumS_Z(VCD {0}), DenS_Z(VCD {0});
for (int i = 0; i < p_ord+1; i++)
{
//NumS_Z.coeffs.push_back(T_11.coeffs[i]);
//DenS_Z.coeffs.push_back(T_01.coeffs[i]);
}
DenS_Z = PadeS_Y.first;
NumS_Z = TaylorRecover(T_11, T_01, DenS_Z);
std::tuple<Poly, Poly, Poly> PadeZ_Z = GetZTF(NumS_Z, Poly(VCD {0, 0, 1}) * DenS_Z, U, N_k);
Poly Yk_Z = std::get<2>(PadeZ_Z);
std::cout << "Verification of Z: " << std::get<0>(PadeZ_Z).SumCoeffs() / std::get<1>(PadeZ_Z).SumCoeffs() << std::endl;
std::cout << std::endl;
// PRINT OUTPUT.
std::cout << "In descending order...\n" << std::endl;
std::cout << std::setprecision(10) << "a_k: " << std::endl;
std::get<0>(PadeZ_X).Print(p_ord, 1); std::cout << "Sum of a_k: " << std::get<0>(PadeZ_X).SumCoeffs() << std::endl;
std::cout << "\nb_k: " << std::endl;
std::get<0>(PadeZ_Y).Print(p_ord, 1); std::cout << "Sum of b_k: " << std::get<0>(PadeZ_Y).SumCoeffs() << std::endl;
std::cout << "\nc_k: " << std::endl;
std::get<0>(PadeZ_Z).Print(p_ord, 1); std::cout << "Sum of c_k: " << std::get<0>(PadeZ_Z).SumCoeffs() << std::endl;
std::cout << "\nd_k: " << std::endl;
std::get<1>(PadeZ_Z).Print(p_ord, 1); std::cout << "Sum of d_k: " << std::get<1>(PadeZ_Y).SumCoeffs() << std::endl << std::endl;
// Uncomment to print response factors.
//std::get<2>(PadeZ_X).Print(std::get<2>(PadeZ_X).Degree(), 1); std::cout << std::endl;
//std::get<2>(PadeZ_Y).Print(std::get<2>(PadeZ_Y).Degree(), 1); std::cout << std::endl;
//std::get<2>(PadeZ_Z).Print(std::get<2>(PadeZ_Z).Degree(), 1); dstd::cout << std::endl;
std::cout << "U: " << U << std::endl;
return 0;
}
| 28.210797 | 412 | 0.564243 | [
"vector"
] |
f463baf2d9307c18efd0d56df26d6749ae02e40d | 9,902 | cpp | C++ | sp/src/game/server/prop_bomb.cpp | ZombieRoxtar/cZeroR | 8c67b9e2e2da2479581d5a3863b8598d44ee69bb | [
"Unlicense"
] | 2 | 2016-11-22T04:25:54.000Z | 2020-02-02T12:24:42.000Z | sp/src/game/server/prop_bomb.cpp | ZombieRoxtar/cZeroR | 8c67b9e2e2da2479581d5a3863b8598d44ee69bb | [
"Unlicense"
] | null | null | null | sp/src/game/server/prop_bomb.cpp | ZombieRoxtar/cZeroR | 8c67b9e2e2da2479581d5a3863b8598d44ee69bb | [
"Unlicense"
] | null | null | null | //===== Copyright Bit Mage's Stuff, All rights probably reserved. =====
//
// Purpose: Prop with a specialized Use function
//
//=============================================================================
#include "cbase.h"
#include "prop_bomb.h"
#include "trigger_special_zone.h"
#include "sprite.h"
#include "explode.h"
#include "in_buttons.h"
#include "vguiscreen.h"
#include "soundent.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define SF_BOMB_START_ON 0x00000001 // This very dangerous bomb starts right away
#define SF_BOMB_SHOULD_EXPLODE 0x00000002 // Explode for real, most just fire the output
#define SF_BOMB_GLOW_AFTER_EXPLOSION 0x00000003 // Glow RED atfer the bomb is "done"
#define SF_BOMB_GLOW_OVERRIDE 0x00000004 // Allow bomb's red glow to override any other
#define BOMB_ZONE_TYPE ZONE_DEFUSE
// When it explodes TODO: KeyValue? Check < defuse time?
#define BOMB_FUSE_TIME 30.0f
#define SPRITE_TOGGLE_TIME 0.5f
#define BOMB_BEEP_TIME 2.0f
#define BOMB_THINK_TIME 0.125f // 1/8th of a second. Use this with SetNextThink
#define BOMB_GLOW_COLOR 255, 0, 0, 160
#define C4_LED_GLOW "sprites/glow02.vmt"
LINK_ENTITY_TO_CLASS(prop_bomb, CPropBomb);
BEGIN_DATADESC(CPropBomb)
DEFINE_FIELD(m_iCaps, FIELD_INTEGER),
DEFINE_FIELD(m_hC4Screen, FIELD_EHANDLE),
DEFINE_KEYFIELD(m_iszZoneName, FIELD_STRING, "ZoneName"),
DEFINE_THINKFUNC(Off),
DEFINE_THINKFUNC(Tick),
DEFINE_INPUTFUNC(FIELD_VOID, "Start", InputStart),
DEFINE_INPUTFUNC(FIELD_VOID, "Explode", Explode),
DEFINE_OUTPUT(m_OnPlayerUse, "OnPlayerUse"),
DEFINE_OUTPUT(m_OnPlayerUnUse, "OnPlayerUnUse"),
DEFINE_OUTPUT(m_OnTimerExpired, "OnTimerExpired"),
END_DATADESC()
void CPropBomb::Spawn()
{
BaseClass::Spawn();
PrecacheScriptSound("c4.disarmstart");
PrecacheScriptSound("c4.disarmfinish");
PrecacheScriptSound("c4.click");
PrecacheMaterial(C4_LED_GLOW);
m_iCaps = NULL;
m_flTickedTime = 0.0f;
m_flNextBeepTime =
m_flNextBlinkTime =
m_flNextThinkTime = gpGlobals->curtime;
if (HasSpawnFlags(SF_BOMB_START_ON))
Start();
}
// This and BaseClass::Precache() called by BaseClass::Spawn()
void CPropBomb::Precache()
{
PrecacheScriptSound("c4.disarmstart");
PrecacheScriptSound("c4.disarmfinish");
PrecacheScriptSound("c4.click");
PrecacheModel(C4_LED_GLOW);
}
void CPropBomb::Activate()
{
BaseClass::Activate();
CBaseEntity* pResult = gEntList.FindEntityByNameWithin
(NULL, m_iszZoneName.ToCStr(), GetLocalOrigin(), 256);
m_pDefusezone = dynamic_cast < CSpecialZone* > (pResult);
if ((m_pDefusezone) && (m_pDefusezone->GetType() == BOMB_ZONE_TYPE))
return;
Warning(
"The prop_bomb with an incompatible or missing zone at (%f, %f, %f) cannot be defused!\n",
GetLocalOrigin().x, GetLocalOrigin().y, GetLocalOrigin().z);
}
void CPropBomb::InputStart(inputdata_t &inputData)
{
Start();
}
void CPropBomb::Start(void)
{
if (!m_bActive)
{
m_bActive = true;
m_iCaps = FCAP_CONTINUOUS_USE | FCAP_USE_IN_RADIUS;
m_flStartedTime = gpGlobals->curtime;
SpawnPanel();
SpriteStart();
// We can glow red when either no glow is current, or the mapper has allowed override
if ((!IsGlowEffectActive()) || (HasSpawnFlags(SF_BOMB_GLOW_OVERRIDE)))
{
if (IsGlowEffectActive())
{
m_bGlowOverriden = true;
m_OldColor.r = m_fGlowRed;
m_OldColor.g = m_fGlowGreen;
m_OldColor.b = m_fGlowBlue;
m_OldColor.a = m_fGlowAlpha;
}
else
{
m_bAutoGlowing = true;
}
color32 glowColor = { BOMB_GLOW_COLOR };
SetGlowEffectColor(glowColor.r, glowColor.g, glowColor.b);
SetGlowEffectAlpha(glowColor.a);
AddGlowEffect();
}
if (!m_bPlayerOn)
{
SetThink(&CPropBomb::Tick);
SetNextThink(gpGlobals->curtime + BOMB_THINK_TIME);
}
if (!m_pDefusezone) // Just in case...
Warning(
"The prop_bomb with an incompatible or missing zone at (%f, %f, %f) cannot be defused!\n",
GetLocalOrigin().x, GetLocalOrigin().y, GetLocalOrigin().z);
}
}
void CPropBomb::SpriteStart()
{
if (!m_bSpriteReady)
{
int nLedAttachmentIndex = this->LookupAttachment("led");
if (nLedAttachmentIndex <= 0)
{
/*
This model doesn't have the attachment point,
skip the sprite so it doesn't spawn under the model
//*/
return;
}
Vector vecAttachment;
this->GetAttachment(nLedAttachmentIndex, vecAttachment);
m_hSprite = CSprite::SpriteCreate(C4_LED_GLOW, vecAttachment, false);
m_pSprite = (CSprite *)m_hSprite.Get();
if (m_pSprite)
{
m_pSprite->SetTransparency(kRenderTransAdd, BOMB_GLOW_COLOR, kRenderFxNone);
m_pSprite->SetScale(0.125f);
m_bSpriteReady = true;
}
}
else
{
m_pSprite->TurnOn();
}
}
void CPropBomb::Tick()
{
m_flTickedTime = gpGlobals->curtime - m_flStartedTime;
if (m_flNextBeepTime <= gpGlobals->curtime)
{
EmitSound("c4.click");
m_flNextBeepTime = gpGlobals->curtime + (BOMB_BEEP_TIME - (BOMB_BEEP_TIME * (m_flTickedTime / BOMB_FUSE_TIME))); // Beep faster as time ticks away
}
if (m_flNextBlinkTime <= gpGlobals->curtime)
{
if (m_bSpriteReady)
m_pSprite->InputToggleSprite(inputdata_t());
m_flNextBlinkTime = gpGlobals->curtime + SPRITE_TOGGLE_TIME;
// Scare NPCs
CSoundEnt::InsertSound(SOUND_DANGER, GetAbsOrigin(), 512, SPRITE_TOGGLE_TIME);
}
if (!m_bPlayerOn && m_bActive)
{
SetThink(&CPropBomb::Tick);
SetNextThink(gpGlobals->curtime + BOMB_THINK_TIME);
}
if (m_flTickedTime >= BOMB_FUSE_TIME)
{
m_OnTimerExpired.FireOutput(this, this);
m_bActive = false;
m_iCaps = NULL;
if (m_bSpriteReady)
m_pSprite->TurnOff();
StopGlowing();
if (HasSpawnFlags(SF_BOMB_SHOULD_EXPLODE))
{
variant_t emptyVariant;
this->AcceptInput("Explode", NULL, NULL, emptyVariant, 0);
}
}
}
void CPropBomb::SpawnPanel()
{
CBaseAnimating *pEntityToSpawnOn = this;
char *pOrgLL = "controlpanel0_ll";
char *pOrgUR = "controlpanel0_ur";
Assert(pEntityToSpawnOn);
// Lookup the attachment point...
int nLLAttachmentIndex = pEntityToSpawnOn->LookupAttachment(pOrgLL);
int nURAttachmentIndex = pEntityToSpawnOn->LookupAttachment(pOrgUR);
if ((nLLAttachmentIndex <= 0) || (nURAttachmentIndex <= 0))
{
return;
}
const char *pScreenName = "c4_panel";
const char *pScreenClassname = "vgui_screen";
// Compute the screen size from the attachment points...
matrix3x4_t panelToWorld;
pEntityToSpawnOn->GetAttachment(nLLAttachmentIndex, panelToWorld);
matrix3x4_t worldToPanel;
MatrixInvert(panelToWorld, worldToPanel);
// Now get the lower right position + transform into panel space
Vector lr, lrlocal;
pEntityToSpawnOn->GetAttachment(nURAttachmentIndex, panelToWorld);
MatrixGetColumn(panelToWorld, 3, lr);
VectorTransform(lr, worldToPanel, lrlocal);
float flWidth = lrlocal.x;
float flHeight = lrlocal.y;
CVGuiScreen *pScreen = CreateVGuiScreen(pScreenClassname, pScreenName, pEntityToSpawnOn, this, nLLAttachmentIndex);
pScreen->SetActualSize(flWidth, flHeight);
pScreen->SetActive(true);
pScreen->SetTransparency(true);
m_hC4Screen.Set(pScreen);
}
void CPropBomb::StopGlowing(bool force)
{
if (!force)
{
// If we did an override (if/when we armed) put back the old color, if that's what the mapper wants
if (m_bGlowOverriden && !HasSpawnFlags(SF_BOMB_GLOW_AFTER_EXPLOSION))
{
SetGlowEffectColor(m_OldColor.r, m_OldColor.g, m_OldColor.b);
SetGlowEffectAlpha(m_OldColor.a);
}
else
{
if (m_bAutoGlowing) // I want defused (or "exploded") bombs to stop glowing ONLY when auto-red. The mapper can handle it otherwise.
{
RemoveGlowEffect();
}
}
}
else
{
RemoveGlowEffect();
}
m_bGlowOverriden = false;
m_bAutoGlowing = false;
}
void CPropBomb::Explode(inputdata_t &inputData)
{
Assert(m_hC4Screen != NULL);
m_hC4Screen->SUB_Remove();
if (m_bSpriteReady)
m_pSprite->Remove();
StopGlowing(true);
ExplosionCreate(GetLocalOrigin(), GetAbsAngles(), this, 1024, 128, true);
Remove();
}
void CPropBomb::Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value)
{
if (!m_bActive)
return;
Tick();
if (!pActivator || !pActivator->IsPlayer())
return;
/*
We need to set the think func to Off() whilst a player is +USEing this
but it's okay, this (use) func is spammed during that time.
Seems that the think (Off()) will actually not run until the player to lets go.
*/
SetThink(&CPropBomb::Off);
SetNextThink(gpGlobals->curtime + BOMB_THINK_TIME);
if (!m_bPlayerOn)
{
pPlayer = static_cast < CBasePlayer* >(pActivator);
m_bPlayerOn = true;
m_OnPlayerUse.FireOutput(pActivator, this);
if (pPlayer->GetActiveWeapon())
{
if (!pPlayer->GetActiveWeapon()->CanHolster() || !pPlayer->GetActiveWeapon()->Holster())
{
/* The weapon cannot be holstered
return;
//?*/
}
}
pPlayer->m_Local.m_iHideHUD |= HIDEHUD_WEAPONSELECTION;
if (m_pDefusezone) // Just in case...
m_pDefusezone->StartUsing(pPlayer);
EmitSound("c4.disarmstart");
}
}
// Called by player un-use
void CPropBomb::Off(void)
{
if (m_bPlayerOn)
{
m_bPlayerOn = false;
m_OnPlayerUnUse.FireOutput(this, this);
if (m_pDefusezone) // Just in case...
m_pDefusezone->StopUsing(pPlayer);
EmitSound("c4.disarmfinish");
if (pPlayer->GetActiveWeapon())
{
if (!pPlayer->GetActiveWeapon()->Deploy())
{
if (pPlayer->SwitchToNextBestWeapon(NULL))
{
// What if there is no weapon?
}
}
}
pPlayer->m_Local.m_iHideHUD &= ~HIDEHUD_WEAPONSELECTION;
}
/* This forces us to pretend the Use key isn't being held down.
Just in case... */
pPlayer->m_afButtonPressed |= IN_USE;
if (m_bActive)
{
SetThink(&CPropBomb::Tick);
SetNextThink(gpGlobals->curtime + BOMB_THINK_TIME);
}
else
{
SetThink(NULL);
}
}
// Defused, this is called by the zone
void CPropBomb::Deactivate(void)
{
m_bActive = false;
Assert(m_hC4Screen != NULL);
m_hC4Screen->SUB_Remove();
m_iCaps = NULL;
if (m_bSpriteReady)
m_pSprite->TurnOff();
StopGlowing();
}
| 25.324808 | 148 | 0.718239 | [
"vector",
"model",
"transform"
] |
f463e78b758807600be25f2ef6caaf1c20e1c684 | 775 | cpp | C++ | Dataset/Leetcode/train/13/114.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/13/114.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/13/114.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
int XXX(string s) {
map<string, int> table = {
{"M", 1000}, {"CM", 900}, {"D", 500}, {"CD", 400}, {"C", 100}, {"XC", 90}, {"L", 50}, {"XL", 40}, {"X", 10}, {"IX", 9},
{"V", 5}, {"IV", 4}, {"I", 1}
};
vector<string> key = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
int len_key = key.size(), i = 0;
int result = 0;
while(s.length() && i < len_key)
{
if(!s.compare(0, key[i].length(), key[i]))
{
result += table[key[i]];
s.erase(0, key[i].length());
}
else
{
++i;
}
}
return result;
}
};
| 26.724138 | 131 | 0.326452 | [
"vector"
] |
c2e1429837fcbabc8e3d671f6327caf6af651cdf | 588 | cpp | C++ | leetcode/377. Combination Sum IV/s1.cpp | zhuohuwu0603/leetcode_cpp_lzl124631x | 6a579328810ef4651de00fde0505934d3028d9c7 | [
"Fair"
] | 787 | 2017-05-12T05:19:57.000Z | 2022-03-30T12:19:52.000Z | leetcode/377. Combination Sum IV/s1.cpp | aerlokesh494/LeetCode | 0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f | [
"Fair"
] | 8 | 2020-03-16T05:55:38.000Z | 2022-03-09T17:19:17.000Z | leetcode/377. Combination Sum IV/s1.cpp | aerlokesh494/LeetCode | 0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f | [
"Fair"
] | 247 | 2017-04-30T15:07:50.000Z | 2022-03-30T09:58:57.000Z | // OJ: https://leetcode.com/problems/combination-sum-iv/
// Author: github.com/lzl124631x
// Time: O(NT)
// Space: O(T)
class Solution {
unordered_map<int, int> m {{0, 1}};
int dp(vector<int>& nums, int target) {
if (m.count(target)) return m[target];
int cnt = 0;
for (int n : nums) {
if (n > target) break;
cnt += dp(nums, target - n);
}
return m[target] = cnt;
}
public:
int combinationSum4(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
return dp(nums, target);
}
}; | 28 | 56 | 0.540816 | [
"vector"
] |
c2ed7788cf1e81db043a2f989c69f1930c9871c3 | 2,787 | hpp | C++ | goop/generic/geometry.hpp | johannes-braun/goop-gfx | f2a5dbac3d18299efdffe900e0e1d615c0c3c98d | [
"MIT"
] | null | null | null | goop/generic/geometry.hpp | johannes-braun/goop-gfx | f2a5dbac3d18299efdffe900e0e1d615c0c3c98d | [
"MIT"
] | null | null | null | goop/generic/geometry.hpp | johannes-braun/goop-gfx | f2a5dbac3d18299efdffe900e0e1d615c0c3c98d | [
"MIT"
] | null | null | null | #pragma once
#include <span>
#include <rnu/math/math.hpp>
#include <vector>
#include <memory>
#include <mutex>
#include "draw_state.hpp"
#include "mapped_buffer.hpp"
namespace goop
{
struct vertex
{
rnu::vec3 position;
rnu::vec3 normal;
rnu::vec2 uv[3];
rnu::vec4ui8 color;
rnu::vec4ui16 joints;
rnu::vec4 weights;
};
vertex mix(vertex const& lhs, vertex const& rhs, float t);
struct vertex_offset
{
std::ptrdiff_t vertex_offset;
std::size_t vertex_count;
std::ptrdiff_t index_offset;
std::size_t index_count;
};
struct indirect
{
std::uint32_t count;
std::uint32_t prim_count;
std::uint32_t first_index;
std::uint32_t base_vertex;
std::uint32_t base_instance;
};
enum class display_type
{
surfaces,
outlines,
vertices
};
static constexpr indirect make_indirect(vertex_offset const& offset)
{
return indirect{
.count = static_cast<std::uint32_t>(offset.index_count),
.prim_count = 1,
.first_index = static_cast<std::uint32_t>(offset.index_offset),
.base_vertex = static_cast<std::uint32_t>(offset.vertex_offset),
.base_instance = 0
};
}
class geometry_base
{
public:
using index_type = std::uint32_t;
geometry_base() = default;
geometry_base(geometry_base const&) = delete;
geometry_base& operator=(geometry_base const&) = delete;
geometry_base(geometry_base&&) noexcept = default;
geometry_base& operator=(geometry_base&&) noexcept = default;
~geometry_base();
void set_display_type(display_type type);
display_type display_type() const;
void clear();
void free_client_memory();
vertex_offset append_vertices(std::span<vertex const> vertices, std::span<index_type const> indices = {});
vertex_offset append_empty_vertices(std::size_t vertex_count, std::size_t index_count = 0);
void draw(draw_state_base& state, vertex_offset offset);
void draw(draw_state_base& state, std::span<vertex_offset const> offsets);
void draw(draw_state_base& state, mapped_buffer_base<indirect> const& indirects, size_t count, ptrdiff_t first = 0);
void prepare();
protected:
virtual void upload(std::span<vertex const> vertices, std::span<geometry_base::index_type const> indices) = 0;
virtual void draw_ranges(std::span<vertex_offset const> offsets) = 0;
virtual void draw_ranges(mapped_buffer_base<indirect> const& indirects, size_t count, ptrdiff_t first = 0) = 0;
mutable bool _dirty = false;
mutable std::mutex _data_mutex;
goop::display_type _display_type;
std::vector<vertex> _staging_vertices;
std::vector<index_type> _staging_indices;
};
} | 29.336842 | 121 | 0.681378 | [
"vector"
] |
c2efc7ac00cad09434d9b0cba2922e2e08aa69ba | 3,356 | cpp | C++ | src/Game.cpp | cjmar/battleship | 8fb895ebe7b89ddd1640f78b6607cfbbdb33cde9 | [
"MIT"
] | null | null | null | src/Game.cpp | cjmar/battleship | 8fb895ebe7b89ddd1640f78b6607cfbbdb33cde9 | [
"MIT"
] | null | null | null | src/Game.cpp | cjmar/battleship | 8fb895ebe7b89ddd1640f78b6607cfbbdb33cde9 | [
"MIT"
] | null | null | null | #include "Game.h"
#include <iostream>
#include "TextureManager.h"
bool DRAW_GRID = false;
using namespace Battleship;
SDL_Renderer* Game::renderer = nullptr;
SDL_Texture* Game::spriteSheet = nullptr;
bool Game::running = false;
TTF_Font* Game::font = nullptr;
int Game::GAME_WIDTH = 0;
int Game::GAME_HEIGHT = 0;
int Game::mouseX = 0;
int Game::mouseY = 0;
float Game::gameScale = 1.5;
Game::Game()
{
window = nullptr;
frameNum = 0;
}
Game::~Game() {}
void Game::init(char* title, int width, int height)
{
Game::GAME_WIDTH = width;
Game::GAME_HEIGHT = height;
//initialize SDL2
if (SDL_Init(SDL_INIT_EVERYTHING) == 0)
{
window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, Game::GAME_WIDTH, Game::GAME_HEIGHT, 0);
renderer = SDL_CreateRenderer(window, -1, 0);
if (renderer)
{
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
}
if (!IMG_Init(IMG_INIT_PNG))
{
std::cout << IMG_GetError() << "\n";
}
if (TTF_Init() == 0)
{
font = TTF_OpenFont("assets/Peace.ttf", 30);
if (font == nullptr)
{
std::cout << "TTF_OpenFont() says: \"" << TTF_GetError() << "\" \n";
}
}
running = true;
}
spriteSheet = TextureManager::loadTexture("assets/atlas.png");
sceneManager.startScene(SceneManager::TitleScreen);
}
//Called every frame
void Game::update(unsigned int frame)
{
frameNum = frame;
sceneManager.update();
}
void Game::eventHandler()
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
//System events
switch (event.type)
{
case SDL_QUIT:
quit();
break;
//Keyboard events
case SDL_KEYDOWN:
switch (event.key.keysym.sym)
{
case SDLK_w:
case SDLK_UP:
break;
}
//Mouse motion event
case SDL_MOUSEMOTION:
Game::mouseX = event.motion.x;
Game::mouseY = event.motion.y;
sceneManager.mouseMoveEvent(Game::mouseX, Game::mouseY);
break;
case SDL_MOUSEBUTTONDOWN:
sceneManager.mouseDownEvent(Game::mouseX, Game::mouseY, event.button.button);
break;
case SDL_MOUSEBUTTONUP:
sceneManager.mouseUpEvent(Game::mouseX, Game::mouseY, event.button.button);
break;
}
}
}
void Game::render()
{
SDL_RenderClear(renderer);
sceneManager.render();
if (DRAW_GRID)
{
//Draw a grid to help debugging
SDL_SetRenderDrawColor(Battleship::Game::renderer, 0, 0, 0, 255);
for (int x = 0; x < Battleship::Game::GAME_WIDTH; x += 48)
{
SDL_RenderDrawLine(Battleship::Game::renderer, x, 0, x, Battleship::Game::GAME_HEIGHT);
}
for (int y = 0; y < Battleship::Game::GAME_HEIGHT; y += 48)
{
SDL_RenderDrawLine(Battleship::Game::renderer, 0, y, Battleship::Game::GAME_WIDTH, y);
}
}
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderPresent(renderer);
}
bool Game::isRunning() { return running; };
void Game::quit() { running = false; };
unsigned int Game::getFrameNum() { return frameNum; };
void Game::clean()
{
SDL_DestroyWindow(window);
SDL_DestroyRenderer(renderer);
SDL_Quit();
}
void Game::changeScene(SceneManager::SceneType type_in)
{
sceneManager.startScene(type_in);
}
void Game::printRect(SDL_Rect& r)
{
std::cout << "{" << r.x << ", " << r.y << ", " << r.w << ", " << r.h << "}\n";
} | 21.240506 | 124 | 0.636472 | [
"render"
] |
c2fc1bf835493108d4c206919a09d560a1941ea1 | 276 | cpp | C++ | atcoder/abc109/a.cpp | Lambda1/atcoder | a4a57ddc21cc29b8b795173630e1d07db4abb559 | [
"MIT"
] | null | null | null | atcoder/abc109/a.cpp | Lambda1/atcoder | a4a57ddc21cc29b8b795173630e1d07db4abb559 | [
"MIT"
] | null | null | null | atcoder/abc109/a.cpp | Lambda1/atcoder | a4a57ddc21cc29b8b795173630e1d07db4abb559 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
#include <map>
int main(int argc,char *argv[])
{
int a,b;
std::cin >> a >> b;
if(a%2 && b%2) std::cout << "Yes" << std::endl;
else std::cout << "No" << std::endl;
return 0;
}
| 16.235294 | 48 | 0.594203 | [
"vector"
] |
c2fe1bac6cee854a2b18137677ec2218cdc53297 | 1,232 | cc | C++ | chromium/mash/wm/shelf_layout.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/mash/wm/shelf_layout.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/mash/wm/shelf_layout.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2015 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 "mash/wm/shelf_layout.h"
#include "components/mus/public/cpp/property_type_converters.h"
#include "components/mus/public/cpp/window.h"
#include "components/mus/public/cpp/window_property.h"
#include "mash/wm/property_util.h"
#include "ui/gfx/geometry/rect.h"
namespace mash {
namespace wm {
ShelfLayout::ShelfLayout(mus::Window* owner) : LayoutManager(owner) {
AddLayoutProperty(mus::mojom::WindowManager::kPreferredSize_Property);
}
ShelfLayout::~ShelfLayout() {}
// We explicitly don't make assertions about the number of children in this
// layout as the number of children can vary when the application providing the
// shelf restarts.
void ShelfLayout::LayoutWindow(mus::Window* window) {
gfx::Size preferred_size = GetWindowPreferredSize(window);
gfx::Rect container_bounds = owner()->bounds();
container_bounds.set_origin(
gfx::Point(0, container_bounds.height() - preferred_size.height()));
container_bounds.set_height(preferred_size.height());
window->SetBounds(container_bounds);
}
} // namespace wm
} // namespace mash
| 33.297297 | 79 | 0.762175 | [
"geometry"
] |
6c02d7edfe5738b0d4e7977f52fd5179b784d970 | 3,948 | cc | C++ | src/neurogram_similiarity_index_measure.cc | sswensen/visqol | 943b42b7234d5d750b96521e1b10041dccd3c7ec | [
"Apache-2.0"
] | 292 | 2020-01-30T04:03:17.000Z | 2022-03-31T14:55:59.000Z | src/neurogram_similiarity_index_measure.cc | sswensen/visqol | 943b42b7234d5d750b96521e1b10041dccd3c7ec | [
"Apache-2.0"
] | 52 | 2020-04-04T13:31:28.000Z | 2022-03-31T00:31:55.000Z | src/neurogram_similiarity_index_measure.cc | sswensen/visqol | 943b42b7234d5d750b96521e1b10041dccd3c7ec | [
"Apache-2.0"
] | 76 | 2020-04-04T13:07:48.000Z | 2022-03-29T09:08:20.000Z | // Copyright 2019 Google LLC, Andrew Hines
//
// 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 "neurogram_similiarity_index_measure.h"
#include <algorithm>
#include <utility>
#include <vector>
#include "convolution_2d.h"
namespace Visqol {
PatchSimilarityResult NeurogramSimiliarityIndexMeasure::MeasurePatchSimilarity(
const ImagePatch &ref_patch, const ImagePatch °_patch) const {
const std::vector<double> w = {
0.0113033910173052, 0.0838251475442633, 0.0113033910173052,
0.0838251475442633, 0.619485845753726, 0.0838251475442633,
0.0113033910173052, 0.0838251475442633, 0.0113033910173052};
AMatrix<double> window(3, 3, std::move(w));
std::vector<double> k{0.01, 0.03};
double c1 = pow(k[0] * intensity_range_, 2);
double c3 = pow(k[1] * intensity_range_, 2) / 2;
auto mu_r = Convolution2D<double>::Valid2DConvWithBoundary(window, ref_patch);
auto mu_d = Convolution2D<double>::Valid2DConvWithBoundary(window, deg_patch);
auto ref_mu_sq = mu_r.PointWiseProduct(mu_r);
auto deg_mu_sq = mu_d.PointWiseProduct(mu_d);
auto mu_r_mu_d = mu_r.PointWiseProduct(mu_d);
auto ref_neuro_sq = ref_patch.PointWiseProduct(ref_patch);
auto deg_neuro_sq = deg_patch.PointWiseProduct(deg_patch);
auto conv2_ref_neuro_sq =
Convolution2D<double>::Valid2DConvWithBoundary(window, ref_neuro_sq);
auto sigma_r_sq = conv2_ref_neuro_sq - ref_mu_sq;
auto conv2_deg_neuro_sq =
Convolution2D<double>::Valid2DConvWithBoundary(window, deg_neuro_sq);
auto sigma_d_sq = conv2_deg_neuro_sq - deg_mu_sq;
auto ref_neuro_deg = ref_patch.PointWiseProduct(deg_patch);
auto conv2_ref_neuro_deg =
Convolution2D<double>::Valid2DConvWithBoundary(window, ref_neuro_deg);
auto sigma_r_d = conv2_ref_neuro_deg - mu_r_mu_d;
auto intensity_numer = mu_r_mu_d * 2.0 + c1;
auto intensity_denom = ref_mu_sq + deg_mu_sq + c1;
auto intensity = intensity_numer.PointWiseDivide(intensity_denom);
auto structure_numer = sigma_r_d + c3;
auto structure_denom = sigma_r_sq.PointWiseProduct(sigma_d_sq);
std::transform(structure_denom.begin(), structure_denom.end(),
structure_denom.begin(),
[&](decltype(*structure_denom.begin()) &d) {
// Avoid a nan is when stddev is negative.
// This occasionally happens with silent patches,
// which generate an epison negative value.
return (d < 0.) ? c3 : (sqrt(d) + c3);
});
auto structure = structure_numer.PointWiseDivide(structure_denom);
auto sim_map = intensity.PointWiseProduct(structure);
// These three matrices correspond to the similarity_result.proto fields
// such as fvnsim.
auto freq_band_deg_energy = deg_patch.Mean(kDimension::ROW);
auto freq_band_means = sim_map.Mean(kDimension::ROW);
auto freq_band_stddevs = sim_map.StdDev(kDimension::ROW);
double freq_band_sim_sum = 0;
std::for_each(freq_band_means.begin(), freq_band_means.end(),
[&](decltype(*freq_band_means.begin()) &d) {freq_band_sim_sum += d;});
auto mean_freq_band_means =
freq_band_sim_sum / freq_band_means.NumRows(); // A.K.A. NSIM
PatchSimilarityResult r;
r.similarity = mean_freq_band_means;
r.freq_band_deg_energy = std::move(freq_band_deg_energy);
r.freq_band_means = std::move(freq_band_means);
r.freq_band_stddevs = std::move(freq_band_stddevs);
return r;
}
} // namespace Visqol
| 43.384615 | 80 | 0.732523 | [
"vector",
"transform"
] |
6c05d52af936cdca38cb796075c459a78f1f1183 | 2,545 | cpp | C++ | src/OptPlan/Opt_Column.cpp | fsaintjacques/cstore | 3300a81c359c4a48e13ad397e3eb09384f57ccd7 | [
"BSD-2-Clause"
] | 14 | 2016-07-11T04:08:09.000Z | 2022-03-11T05:56:59.000Z | src/OptPlan/Opt_Column.cpp | ibrarahmad/cstore | 3300a81c359c4a48e13ad397e3eb09384f57ccd7 | [
"BSD-2-Clause"
] | null | null | null | src/OptPlan/Opt_Column.cpp | ibrarahmad/cstore | 3300a81c359c4a48e13ad397e3eb09384f57ccd7 | [
"BSD-2-Clause"
] | 13 | 2016-06-01T10:41:15.000Z | 2022-01-06T09:01:15.000Z | /*
* Opt_Column.h
* C-Store - Optimimzation
*
* Created by Nga Tran on 10/28/05.
*
* Questions, ask Nga Tran at nga@brandeis.edu or Tien Hoang at hoangt@brandeis.edu
*
* This class implements an attribute of a table
*/
#include "Opt_Column.h"
#include <iostream>
using namespace std;
// Default constructor
Opt_Column::Opt_Column() {
m_sColumnName = "";
m_sTableName = "";
m_sColumnAlias = "";
m_sTableAlias = "";
}
// Provide column and table names
Opt_Column::Opt_Column(string sColumnName, string sTableName) {
m_sColumnName = sColumnName;
m_sTableName = sTableName;
m_sColumnAlias = sColumnName;
m_sTableAlias = sTableName;
}
// Provide column and table names and column alias
Opt_Column::Opt_Column(string sColumnName, string sTableName, string sColumnAlias) {
m_sColumnName = sColumnName;
m_sTableName = sTableName;
m_sColumnAlias = sColumnAlias;
m_sTableAlias = "";
}
// Provide column and table names and their alias
Opt_Column::Opt_Column(string sColumnName, string sTableName, string sColumnAlias, string sTableAlias) {
m_sColumnName = sColumnName;
m_sTableName = sTableName;
m_sColumnAlias = sColumnAlias;
m_sTableAlias = sTableAlias;
}
// Default Destructor
Opt_Column::~Opt_Column()
{
}
// Clone
Opt_Column* Opt_Column::clone()
{
return new Opt_Column(m_sColumnName, m_sTableName, m_sColumnAlias, m_sTableAlias);
}
// Clone with new table names, new table alias
Opt_Column* Opt_Column::clone(string sTableName, string sTableAlias)
{
return new Opt_Column(m_sColumnName, sTableName, m_sColumnAlias, sTableAlias);
}
// Get and set functions
void Opt_Column::setColumnName(string sColumnName)
{
m_sColumnName = sColumnName;
}
string Opt_Column::getColumnName()
{
return m_sColumnName;
}
void Opt_Column::setTableName(string sTableName)
{
m_sTableName = sTableName;
}
string Opt_Column::getTableName()
{
return m_sTableName;
}
void Opt_Column::setColumnAlias(string sColumnAlias)
{
m_sColumnAlias = sColumnAlias;
}
string Opt_Column::getColumnAlias()
{
return m_sColumnAlias;
}
void Opt_Column::setTableAlias(string sTableAlias)
{
m_sTableAlias = sTableAlias;
}
string Opt_Column::getTableAlias()
{
return m_sTableAlias;
}
string Opt_Column::toStringNoTableDot() {
return m_sColumnName;
}
string Opt_Column::toString() {
string s = "";
if (m_sTableName.compare("") != 0) {
s = m_sTableName + ".";
}
s += m_sColumnName;
return s;
}
// Check if this object is a column
bool Opt_Column::isColumn()
{
return 1; // true
}
| 19.882813 | 104 | 0.733988 | [
"object"
] |
6c06dcfbddb80d5a7ba3ab977549729fbe70f1c6 | 10,315 | cpp | C++ | src/ObjectBuilderPlugin/PipeBuilderWidget.cpp | kirohy/hairo-world-plugin | bc5e5d32e022e3a3b926e4f9f35969fb9bcbdfe4 | [
"MIT"
] | null | null | null | src/ObjectBuilderPlugin/PipeBuilderWidget.cpp | kirohy/hairo-world-plugin | bc5e5d32e022e3a3b926e4f9f35969fb9bcbdfe4 | [
"MIT"
] | null | null | null | src/ObjectBuilderPlugin/PipeBuilderWidget.cpp | kirohy/hairo-world-plugin | bc5e5d32e022e3a3b926e4f9f35969fb9bcbdfe4 | [
"MIT"
] | null | null | null | /**
\file
\author Kenta Suzuki
*/
#include "PipeBuilderWidget.h"
#include <cnoid/Button>
#include <cnoid/EigenTypes>
#include <cnoid/EigenUtil>
#include <cnoid/MainWindow>
#include <cnoid/SpinBox>
#include <cnoid/stdx/filesystem>
#include <cnoid/YAMLWriter>
#include <QColorDialog>
#include <QGridLayout>
#include <QLabel>
#include <QVBoxLayout>
#include "gettext.h"
using namespace cnoid;
using namespace std;
namespace filesystem = cnoid::stdx::filesystem;
namespace cnoid {
class PipeBuilderWidgetImpl
{
public:
PipeBuilderWidgetImpl(PipeBuilderWidget* self);
PipeBuilderWidget* self;
DoubleSpinBox* massSpin;
DoubleSpinBox* innerDiameterSpin;
DoubleSpinBox* outerDiameterSpin;
DoubleSpinBox* lengthSpin;
SpinBox* angleSpin;
SpinBox* stepSpin;
PushButton* colorButton;
void writeYaml(const string& filename);
void onColorButtonClicked();
void onInnerDiameterChanged(const double& diameter);
void onOuterDiameterChanged(const double& diameter);
VectorXd calcInertia();
};
}
PipeBuilderWidget::PipeBuilderWidget()
{
impl = new PipeBuilderWidgetImpl(this);
}
PipeBuilderWidgetImpl::PipeBuilderWidgetImpl(PipeBuilderWidget* self)
: self(self)
{
QVBoxLayout* vbox = new QVBoxLayout();
QGridLayout* pgbox = new QGridLayout();
massSpin = new DoubleSpinBox();
innerDiameterSpin = new DoubleSpinBox();
outerDiameterSpin = new DoubleSpinBox();
lengthSpin = new DoubleSpinBox();
angleSpin = new SpinBox();
stepSpin = new SpinBox();
colorButton = new PushButton();
massSpin->setValue(1.0);
massSpin->setRange(0.001, 1000.0);
massSpin->setSingleStep(0.01);
massSpin->setDecimals(3);
innerDiameterSpin->setValue(0.03);
innerDiameterSpin->setRange(0.001, 1000.0);
innerDiameterSpin->setSingleStep(0.01);
innerDiameterSpin->setDecimals(3);
outerDiameterSpin->setValue(0.05);
outerDiameterSpin->setRange(0.001, 1000.0);
outerDiameterSpin->setSingleStep(0.01);
outerDiameterSpin->setDecimals(3);
lengthSpin->setValue(1.0);
lengthSpin->setRange(0.001, 1000.0);
lengthSpin->setSingleStep(0.01);
lengthSpin->setDecimals(3);
angleSpin->setValue(0);
angleSpin->setRange(0, 359);
stepSpin->setValue(30);
stepSpin->setRange(1, 120);
int index = 0;
pgbox->addWidget(new QLabel(_("Mass [kg]")), index, 0);
pgbox->addWidget(massSpin, index, 1);
pgbox->addWidget(new QLabel(_("Length [m]")), index, 2);
pgbox->addWidget(lengthSpin, index++, 3);
pgbox->addWidget(new QLabel(_("Inner diameter [m]")), index, 0);
pgbox->addWidget(innerDiameterSpin, index, 1);
pgbox->addWidget(new QLabel(_("Outer diameter [m]")), index, 2);
pgbox->addWidget(outerDiameterSpin, index++, 3);
pgbox->addWidget(new QLabel(_("Opening angle [deg]")), index, 0);
pgbox->addWidget(angleSpin, index, 1);
pgbox->addWidget(new QLabel(_("Step angle [deg]")), index, 2);
pgbox->addWidget(stepSpin, index++, 3);
pgbox->addWidget(new QLabel(_("Color [-]")), index, 0);
pgbox->addWidget(colorButton, index++, 1);
vbox->addLayout(pgbox);
self->setLayout(vbox);
colorButton->sigClicked().connect([&](){ onColorButtonClicked(); });
innerDiameterSpin->sigValueChanged().connect([&](double value){ onInnerDiameterChanged(value); });
outerDiameterSpin->sigValueChanged().connect([&](double value){ onOuterDiameterChanged(value); });
}
PipeBuilderWidget::~PipeBuilderWidget()
{
delete impl;
}
void PipeBuilderWidget::save(const string& filename)
{
impl->writeYaml(filename);
}
void PipeBuilderWidgetImpl::writeYaml(const string& filename)
{
filesystem::path path(filename);
double mass = massSpin->value();
double innerDiameter = innerDiameterSpin->value();
double outerDiameter = outerDiameterSpin->value();
double length = lengthSpin->value();
int angle = angleSpin->value();
int step = stepSpin->value();
if(!filename.empty()) {
YAMLWriter writer(filename);
string name = path.stem();
writer.startMapping(); // start of body map
writer.putKeyValue("format", "ChoreonoidBody");
writer.putKeyValue("formatVersion", "1.0");
writer.putKeyValue("angleUnit", "degree");
writer.putKeyValue("name", name);
writer.putKey("links");
writer.startListing(); // start of links list
writer.startMapping(); // start of links map
writer.putKeyValue("name", name);
writer.putKeyValue("jointType", "free");
writer.putKey("centerOfMass");
writer.startFlowStyleListing(); // start of centerOfMass list
for(int i = 0; i < 3; ++i) {
writer.putScalar(0.0);
}
writer.endListing(); // end of centerOfMass list
writer.putKeyValue("mass", mass);
writer.putKey("inertia");
writer.startFlowStyleListing(); // start of inertia list
VectorXd inertia;
inertia.resize(9);
inertia = calcInertia();
for(int i = 0; i < 9; ++i) {
writer.putScalar(inertia[i]);
}
writer.endListing(); // end of inertia list
writer.putKey("elements");
writer.startMapping(); // start of elements map
writer.putKey("Shape");
writer.startMapping(); // start of Shape map
writer.putKey("geometry");
writer.startMapping(); // start of geometry map
writer.putKeyValue("type", "Extrusion");
writer.putKey("crossSection");
writer.startFlowStyleListing(); // start of crossSection list
int range = 360 - angle;
double sx;
double sy;
for(int i = 0; i <= range; i += step) {
double x = outerDiameter * cos(i * TO_RADIAN);
double y = outerDiameter * sin(i * TO_RADIAN);
if(i == 0) {
sx = x;
sy = y;
}
writer.putScalar(x);
writer.putScalar(y);
}
for(int i = 0; i <= range; i += step) {
double x = innerDiameter * cos((range - i) * TO_RADIAN);
double y = innerDiameter * sin((range - i) * TO_RADIAN);
writer.putScalar(x);
writer.putScalar(y);
}
writer.putScalar(sx);
writer.putScalar(sy);
writer.endListing(); // end of crossSection list
writer.putKey("spine");
writer.startFlowStyleListing(); // start of spine list
Vector6 spine;
spine << 0.0, -length / 2.0, 0.0, 0.0, length / 2.0, 0.0;
for(int i = 0; i < 6; ++i) {
writer.putScalar(spine[i]);
}
writer.endListing(); // end of spine list
writer.endMapping(); // end of geometry map
writer.putKey("appearance");
writer.startFlowStyleMapping(); // start of appearance map
writer.putKey("material");
writer.startMapping(); // start of material map
writer.putKey("diffuseColor");
QPalette palette = colorButton->palette();
QColor color = palette.color(QPalette::Button);
double red = (double)color.red() / 255.0;
double green = (double)color.green() / 255.0;
double blue = (double)color.blue() / 255.0;
Vector3 diffuseColor(red, green, blue);
writer.startFlowStyleListing(); // start of diffuseColor list
for(int i = 0; i < 3; ++i) {
writer.putScalar(diffuseColor[i]);
}
writer.endListing(); // end of diffuseColor list
writer.endMapping(); // end of material map
writer.endMapping(); // end of appearance map
writer.endMapping(); // end of Shape map
writer.endMapping(); // end of elements map
writer.endMapping(); // end of links map
writer.endListing(); // end of links list
writer.endMapping(); // end of body map
}
}
void PipeBuilderWidgetImpl::onColorButtonClicked()
{
QColor selectedColor;
QColor currentColor = colorButton->palette().color(QPalette::Button);
QColorDialog dialog(MainWindow::instance());
dialog.setWindowTitle(_("Select a color"));
dialog.setCurrentColor(currentColor);
dialog.setOption (QColorDialog::DontUseNativeDialog);
if(dialog.exec()) {
selectedColor = dialog.currentColor();
} else {
selectedColor = currentColor;
}
QPalette palette;
palette.setColor(QPalette::Button, selectedColor);
colorButton->setPalette(palette);
}
void PipeBuilderWidgetImpl::onInnerDiameterChanged(const double& diameter)
{
double outerDiameter = outerDiameterSpin->value();
if(diameter >= outerDiameter) {
double innerDiameter = outerDiameter - 0.01;
innerDiameterSpin->setValue(innerDiameter);
}
}
void PipeBuilderWidgetImpl::onOuterDiameterChanged(const double& diameter)
{
double innerDiameter = innerDiameterSpin->value();
if(diameter <= innerDiameter) {
double outerDiameter = innerDiameter + 0.01;
outerDiameterSpin->setValue(outerDiameter);
}
}
VectorXd PipeBuilderWidgetImpl::calcInertia()
{
VectorXd innerInertia, outerInertia;
innerInertia.resize(9);
outerInertia.resize(9);
double length = lengthSpin->value();
double innerRadius = innerDiameterSpin->value();
double outerRadius = outerDiameterSpin->value();
double innerRate = innerRadius * innerRadius / outerRadius * outerRadius;
double outerRate = 1.0 - innerRate;
{
double mass = massSpin->value() * innerRate;
double radius = innerRadius;
double mainInertia = mass * radius * radius / 2.0;
double subInertia = mass * (3.0 * radius * radius + length * length) / 12.0;
double ix, iy, iz;
ix = iz = subInertia;
iy = mainInertia;
innerInertia << ix, 0.0, 0.0, 0.0, iy, 0.0, 0.0, 0.0, iz;
}
{
double mass = massSpin->value() * outerRate;
double radius = outerRadius;
double mainInertia = mass * radius * radius / 2.0;
double subInertia = mass * (3.0 * radius * radius + length * length) / 12.0;
double ix, iy, iz;
ix = iz = subInertia;
iy = mainInertia;
outerInertia << ix, 0.0, 0.0, 0.0, iy, 0.0, 0.0, 0.0, iz;
}
VectorXd inertia = outerInertia - innerInertia;
return inertia;
}
| 32.955272 | 102 | 0.636161 | [
"geometry",
"shape"
] |
6c11fbf71d9b2c8b5ee5b89ed44c7314fac2b1a9 | 1,840 | hpp | C++ | include/boost/rpc/message.hpp | bytemaster/Boost.RPC | a27795d37481fb5d53774cc8cf4270fff1f84964 | [
"Unlicense"
] | 23 | 2015-03-31T05:54:47.000Z | 2022-02-27T14:30:16.000Z | include/boost/rpc/message.hpp | bytemaster/Boost.RPC | a27795d37481fb5d53774cc8cf4270fff1f84964 | [
"Unlicense"
] | null | null | null | include/boost/rpc/message.hpp | bytemaster/Boost.RPC | a27795d37481fb5d53774cc8cf4270fff1f84964 | [
"Unlicense"
] | 13 | 2015-04-22T04:32:26.000Z | 2019-08-29T13:22:21.000Z | #ifndef __BOOST_RPC_MESSAGE_HPP_
#define __BOOST_RPC_MESSAGE_HPP_
#include <boost/reflect/reflect.hpp>
#include <boost/rpc/varint.hpp>
#include <boost/rpc/required.hpp>
#include <boost/optional.hpp>
namespace boost { namespace rpc {
using boost::optional;
/**
* Based upon the JSON-RPC 2.0 Specification
*/
struct error_object : public virtual boost::exception, public virtual std::exception
{
error_object( int32_t c = 0 )
:code(c){}
error_object( int32_t c, const std::string& msg )
:code(c),message(msg){}
~error_object() throw() {}
required<signed_int> code;
optional<std::string> message;
optional<std::string> data;
const char* what()const throw() { return message ? (*message).c_str() : "error object"; }
virtual void rethrow()const { BOOST_THROW_EXCEPTION(*this); }
};
/**
* This RPC message class is designed to work with the
* JSON-RPC 2.0 Specification, but should also
* serve well for Google Protocol Buffer spec.
*/
struct message
{
message(){}
message( const std::string& name )
:method(name){}
message( const std::string& name, const std::string& param )
:method(name),params(param){}
optional<signed_int> id; ///< Used to pair request/response
optional<signed_int> method_id; ///< Used for effecient calls
optional<std::string> method; ///< Used to call by name
optional<std::string> params; ///< JSON Param Array
optional<std::string> result; ///< Return value
optional<error_object> error; ///< Used in case of errors
};
} } // namespace boost::rpc
BOOST_REFLECT( boost::rpc::error_object, (code)(message)(data) )
BOOST_REFLECT( boost::rpc::message, (id)(method_id)(method)(params)(result)(error) )
#endif // __BOOST_RPC_MESSAGE_HPP_
| 29.206349 | 98 | 0.659783 | [
"object"
] |
6c14498be764343d63b077b0c076c56a3fe2715e | 3,686 | cpp | C++ | searchlib/src/vespa/searchlib/index/docidandfeatures.cpp | bowlofstew/vespa | 5212c7a5568769eadb5c5d99b6a503a70c82af48 | [
"Apache-2.0"
] | null | null | null | searchlib/src/vespa/searchlib/index/docidandfeatures.cpp | bowlofstew/vespa | 5212c7a5568769eadb5c5d99b6a503a70c82af48 | [
"Apache-2.0"
] | 1 | 2021-01-21T01:37:37.000Z | 2021-01-21T01:37:37.000Z | searchlib/src/vespa/searchlib/index/docidandfeatures.cpp | bowlofstew/vespa | 5212c7a5568769eadb5c5d99b6a503a70c82af48 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "docidandfeatures.h"
#include <vespa/vespalib/objects/nbostream.h>
#include <vespa/log/log.h>
LOG_SETUP(".index.docidandfeatures");
namespace search::index {
using vespalib::nbostream;
DocIdAndFeatures::DocIdAndFeatures()
: _docId(0),
_wordDocFeatures(),
_elements(),
_wordPositions(),
_blob(),
_bitOffset(0u),
_bitLength(0u),
_raw(false)
{ }
DocIdAndFeatures::DocIdAndFeatures(const DocIdAndFeatures &) = default;
DocIdAndFeatures & DocIdAndFeatures::operator = (const DocIdAndFeatures &) = default;
DocIdAndFeatures::~DocIdAndFeatures() { }
#if 0
void
DocIdAndFeatures::append(const DocIdAndFeatures &rhs, uint32_t localFieldId)
{
assert(!rhs.getRaw());
assert(rhs._fields.size() == 1);
const WordDocFieldFeatures &field = rhs._fields.front();
assert(field.getFieldId() == 0);
uint32_t numElements = field.getNumElements();
std::vector<WordDocFieldElementFeatures>::const_iterator element =
rhs._elements.begin();
std::vector<WordDocFieldElementWordPosFeatures>::const_iterator position =
rhs._wordPositions.begin();
assert(_fields.empty() || localFieldId > _fields.back().getFieldId());
_fields.push_back(field);
_fields.back().setFieldId(localFieldId);
for (uint32_t elementDone = 0; elementDone < numElements;
++elementDone, ++element) {
_elements.push_back(*element);
for (uint32_t posResidue = element->getNumOccs(); posResidue > 0;
--posResidue, ++position) {
_wordPositions.push_back(*position);
}
}
}
#endif
nbostream &
operator<<(nbostream &out, const WordDocElementFeatures &features)
{
out << features._elementId << features._numOccs <<
features._weight << features._elementLen;
return out;
}
nbostream &
operator>>(nbostream &in, WordDocElementFeatures &features)
{
in >> features._elementId >> features._numOccs >>
features._weight >> features._elementLen;
return in;
}
nbostream &
operator<<(nbostream &out, const WordDocElementWordPosFeatures &features)
{
out << features._wordPos;
return out;
}
nbostream &
operator>>(nbostream &in, WordDocElementWordPosFeatures &features)
{
in >> features._wordPos;
return in;
}
nbostream &
operator<<(nbostream &out, const DocIdAndFeatures &features)
{
out << features._docId;
out.saveVector(features._elements).
saveVector(features._wordPositions);
out.saveVector(features._blob);
out << features._bitOffset << features._bitLength << features._raw;
return out;
}
nbostream &
operator>>(nbostream &in, DocIdAndFeatures &features)
{
in >> features._docId;
in.restoreVector(features._elements).
restoreVector(features._wordPositions);
in.restoreVector(features._blob);
in >> features._bitOffset >> features._bitLength >> features._raw;
return in;
}
}
#include <vespa/vespalib/objects/nbostream.hpp>
namespace vespalib {
using search::index::WordDocElementFeatures;
using search::index::WordDocElementWordPosFeatures;
template nbostream& nbostream::saveVector<WordDocElementFeatures>(const std::vector<WordDocElementFeatures> &);
template nbostream& nbostream::restoreVector<WordDocElementFeatures>(std::vector<WordDocElementFeatures> &);
template nbostream& nbostream::saveVector<WordDocElementWordPosFeatures>(const std::vector<WordDocElementWordPosFeatures> &);
template nbostream& nbostream::restoreVector<WordDocElementWordPosFeatures>(std::vector<WordDocElementWordPosFeatures> &);
}
| 29.725806 | 129 | 0.71758 | [
"vector"
] |
6c18585e57af53074a0e79106d9d5793b526c9f8 | 25,996 | cpp | C++ | src/game/server/hl1/hl1_npc_hassassin.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 6 | 2022-01-23T09:40:33.000Z | 2022-03-20T20:53:25.000Z | src/game/server/hl1/hl1_npc_hassassin.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | null | null | null | src/game/server/hl1/hl1_npc_hassassin.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 1 | 2022-02-06T21:05:23.000Z | 2022-02-06T21:05:23.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "cbase.h"
#include "ai_default.h"
#include "ai_task.h"
#include "ai_schedule.h"
#include "ai_node.h"
#include "ai_hull.h"
#include "ai_hint.h"
#include "ai_memory.h"
#include "ai_route.h"
#include "ai_motor.h"
#include "soundent.h"
#include "game.h"
#include "npcevent.h"
#include "entitylist.h"
#include "activitylist.h"
#include "animation.h"
#include "basecombatweapon.h"
#include "IEffects.h"
#include "vstdlib/random.h"
#include "engine/IEngineSound.h"
#include "ammodef.h"
#include "util.h"
#include "hl1_ai_basenpc.h"
#include "hl1_basegrenade.h"
#include "movevars_shared.h"
#include "ai_basenpc.h"
ConVar sk_hassassin_health("sk_hassassin_health", "50");
//=========================================================
// monster-specific schedule types
//=========================================================
enum {
SCHED_ASSASSIN_EXPOSED = LAST_SHARED_SCHEDULE,// cover was blown.
SCHED_ASSASSIN_JUMP, // fly through the air
SCHED_ASSASSIN_JUMP_ATTACK, // fly through the air and shoot
SCHED_ASSASSIN_JUMP_LAND, // hit and run away
SCHED_ASSASSIN_FAIL,
SCHED_ASSASSIN_TAKE_COVER_FROM_ENEMY1,
SCHED_ASSASSIN_TAKE_COVER_FROM_ENEMY2,
SCHED_ASSASSIN_TAKE_COVER_FROM_BEST_SOUND,
SCHED_ASSASSIN_HIDE,
SCHED_ASSASSIN_HUNT,
};
Activity ACT_ASSASSIN_FLY_UP;
Activity ACT_ASSASSIN_FLY_ATTACK;
Activity ACT_ASSASSIN_FLY_DOWN;
//=========================================================
// monster-specific tasks
//=========================================================
enum {
TASK_ASSASSIN_FALL_TO_GROUND = LAST_SHARED_TASK + 1, // falling and waiting to hit ground
};
//=========================================================
// Monster's Anim Events Go Here
//=========================================================
#define ASSASSIN_AE_SHOOT1 1
#define ASSASSIN_AE_TOSS1 2
#define ASSASSIN_AE_JUMP 3
#define MEMORY_BADJUMP bits_MEMORY_CUSTOM1
class CNPC_HAssassin : public CHL1BaseNPC {
DECLARE_CLASS( CNPC_HAssassin, CHL1BaseNPC
);
public:
void Spawn(void);
void Precache(void);
int TranslateSchedule(int scheduleType);
void HandleAnimEvent(animevent_t *pEvent);
float MaxYawSpeed() { return 360.0f; }
void Shoot(void);
int MeleeAttack1Conditions(float flDot, float flDist);
int RangeAttack1Conditions(float flDot, float flDist);
int RangeAttack2Conditions(float flDot, float flDist);
int SelectSchedule(void);
void RunTask(const Task_t *pTask);
void StartTask(const Task_t *pTask);
Class_T Classify(void);
int GetSoundInterests(void);
void RunAI(void);
float m_flLastShot;
float m_flDiviation;
float m_flNextJump;
Vector m_vecJumpVelocity;
float m_flNextGrenadeCheck;
Vector m_vecTossVelocity;
bool m_fThrowGrenade;
int m_iTargetRanderamt;
int m_iFrustration;
int m_iAmmoType;
public:
DECLARE_DATADESC();
DEFINE_CUSTOM_AI;
};
LINK_ENTITY_TO_CLASS( monster_human_assassin, CNPC_HAssassin
);
BEGIN_DATADESC( CNPC_HAssassin )
DEFINE_FIELD( m_flLastShot, FIELD_TIME
),
DEFINE_FIELD( m_flDiviation, FIELD_FLOAT
),
DEFINE_FIELD( m_flNextJump, FIELD_TIME
),
DEFINE_FIELD( m_vecJumpVelocity, FIELD_VECTOR
),
DEFINE_FIELD( m_flNextGrenadeCheck, FIELD_TIME
),
DEFINE_FIELD( m_vecTossVelocity, FIELD_VECTOR
),
DEFINE_FIELD( m_fThrowGrenade, FIELD_BOOLEAN
),
DEFINE_FIELD( m_iTargetRanderamt, FIELD_INTEGER
),
DEFINE_FIELD( m_iFrustration, FIELD_INTEGER
),
//DEFINE_FIELD( m_iAmmoType, FIELD_INTEGER ),
END_DATADESC()
//=========================================================
// Spawn
//=========================================================
void CNPC_HAssassin::Spawn() {
Precache();
SetModel("models/hassassin.mdl");
SetHullType(HULL_HUMAN);
SetHullSizeNormal();
SetNavType(NAV_GROUND);
SetSolid(SOLID_BBOX);
AddSolidFlags(FSOLID_NOT_STANDABLE);
SetMoveType(MOVETYPE_STEP);
m_bloodColor = BLOOD_COLOR_RED;
ClearEffects();
m_iHealth = sk_hassassin_health.GetFloat();
m_flFieldOfView = VIEW_FIELD_WIDE; // indicates the width of this monster's forward view cone ( as a dotproduct result )
m_NPCState = NPC_STATE_NONE;
m_HackedGunPos = Vector(0, 24, 48);
m_iTargetRanderamt = 20;
SetRenderColor(255, 255, 255, 20);
m_nRenderMode = kRenderTransTexture;
CapabilitiesClear();
CapabilitiesAdd(bits_CAP_MOVE_GROUND);
CapabilitiesAdd(bits_CAP_INNATE_RANGE_ATTACK1 | bits_CAP_INNATE_RANGE_ATTACK2 | bits_CAP_INNATE_MELEE_ATTACK1);
NPCInit();
}
//=========================================================
// Precache - precaches all resources this monster needs
//=========================================================
void CNPC_HAssassin::Precache() {
m_iAmmoType = GetAmmoDef()->Index("9mmRound");
PrecacheModel("models/hassassin.mdl");
UTIL_PrecacheOther("npc_handgrenade");
PrecacheScriptSound("HAssassin.Shot");
PrecacheScriptSound("HAssassin.Beamsound");
PrecacheScriptSound("HAssassin.Footstep");
}
int CNPC_HAssassin::GetSoundInterests(void) {
return SOUND_WORLD |
SOUND_COMBAT |
SOUND_PLAYER |
SOUND_DANGER;
}
Class_T CNPC_HAssassin::Classify(void) {
return CLASS_HUMAN_MILITARY;
}
//=========================================================
// CheckMeleeAttack1 - jump like crazy if the enemy gets too close.
//=========================================================
int CNPC_HAssassin::MeleeAttack1Conditions(float flDot, float flDist) {
if (m_flNextJump < gpGlobals->curtime && (flDist <= 128 || HasMemory(MEMORY_BADJUMP)) && GetEnemy() != NULL) {
trace_t tr;
Vector vecMin = Vector(random->RandomFloat(0, -64), random->RandomFloat(0, -64), 0);
Vector vecMax = Vector(random->RandomFloat(0, 64), random->RandomFloat(0, 64), 160);
Vector vecDest = GetAbsOrigin() + Vector(random->RandomFloat(-64, 64), random->RandomFloat(-64, 64), 160);
UTIL_TraceHull(GetAbsOrigin() + Vector(0, 0, 36), GetAbsOrigin() + Vector(0, 0, 36), vecMin, vecMax, MASK_SOLID,
this, COLLISION_GROUP_NONE, &tr);
//NDebugOverlay::Box( GetAbsOrigin() + Vector( 0, 0, 36 ), vecMin, vecMax, 0,0, 255, 0, 2.0 );
if (tr.startsolid || tr.fraction < 1.0) {
return COND_TOO_CLOSE_TO_ATTACK;
}
float flGravity = GetCurrentGravity();
float time = sqrt(160 / (0.5 * flGravity));
float speed = flGravity * time / 160;
m_vecJumpVelocity = (vecDest - GetAbsOrigin()) * speed;
return COND_CAN_MELEE_ATTACK1;
}
if (flDist > 128)
return COND_TOO_FAR_TO_ATTACK;
return COND_NONE;
}
//=========================================================
// CheckRangeAttack1 - drop a cap in their ass
//
//=========================================================
int CNPC_HAssassin::RangeAttack1Conditions(float flDot, float flDist) {
if (!HasCondition(COND_ENEMY_OCCLUDED) && flDist > 64 && flDist <= 2048) {
trace_t tr;
Vector vecSrc = GetAbsOrigin() + m_HackedGunPos;
// verify that a bullet fired from the gun will hit the enemy before the world.
UTIL_TraceLine(vecSrc, GetEnemy()->BodyTarget(vecSrc), MASK_SOLID, this, COLLISION_GROUP_NONE, &tr);
if (tr.fraction == 1.0 || tr.m_pEnt == GetEnemy()) {
return COND_CAN_RANGE_ATTACK1;
}
}
return COND_NONE;
}
//=========================================================
// CheckRangeAttack2 - toss grenade is enemy gets in the way and is too close.
//=========================================================
int CNPC_HAssassin::RangeAttack2Conditions(float flDot, float flDist) {
m_fThrowGrenade = false;
if (!FBitSet (GetEnemy()->GetFlags(), FL_ONGROUND)) {
// don't throw grenades at anything that isn't on the ground!
return COND_NONE;
}
// don't get grenade happy unless the player starts to piss you off
if (m_iFrustration <= 2)
return COND_NONE;
if (m_flNextGrenadeCheck < gpGlobals->curtime && !HasCondition(COND_ENEMY_OCCLUDED) && flDist <= 512) {
Vector vTossPos;
QAngle vAngles;
GetAttachment("grenadehand", vTossPos, vAngles);
Vector vecToss = VecCheckThrow(this, vTossPos, GetEnemy()->WorldSpaceCenter(), flDist,
0.5); // use dist as speed to get there in 1 second
if (vecToss != vec3_origin) {
m_vecTossVelocity = vecToss;
// throw a hand grenade
m_fThrowGrenade = TRUE;
return COND_CAN_RANGE_ATTACK2;
}
}
return COND_NONE;
}
//=========================================================
// StartTask
//=========================================================
void CNPC_HAssassin::StartTask(const Task_t *pTask) {
switch (pTask->iTask) {
case TASK_RANGE_ATTACK2:
if (!m_fThrowGrenade) {
TaskComplete();
} else {
BaseClass::StartTask(pTask);
}
break;
case TASK_ASSASSIN_FALL_TO_GROUND:
m_flWaitFinished = gpGlobals->curtime + 2.0f;
break;
default:
BaseClass::StartTask(pTask);
break;
}
}
//=========================================================
// RunTask
//=========================================================
void CNPC_HAssassin::RunTask(const Task_t *pTask) {
switch (pTask->iTask) {
case TASK_ASSASSIN_FALL_TO_GROUND:
GetMotor()->SetIdealYawAndUpdate(GetEnemyLKP());
if (IsSequenceFinished()) {
if (GetAbsVelocity().z > 0) {
SetActivity(ACT_ASSASSIN_FLY_UP);
} else if (HasCondition(COND_SEE_ENEMY)) {
SetActivity(ACT_ASSASSIN_FLY_ATTACK);
SetCycle(0);
} else {
SetActivity(ACT_ASSASSIN_FLY_DOWN);
SetCycle(0);
}
ResetSequenceInfo();
}
if (GetFlags() & FL_ONGROUND) {
TaskComplete();
} else if (gpGlobals->curtime > m_flWaitFinished || GetAbsVelocity().z == 0.0) {
// I've waited two seconds and haven't hit the ground. Try to force it.
trace_t trace;
UTIL_TraceEntity(this, GetAbsOrigin(), GetAbsOrigin() - Vector(0, 0, 1), MASK_NPCSOLID, this,
COLLISION_GROUP_NONE, &trace);
if (trace.DidHitWorld()) {
SetGroundEntity(trace.m_pEnt);
} else {
// Try again in a couple of seconds.
m_flWaitFinished = gpGlobals->curtime + 2.0f;
}
}
break;
default:
BaseClass::RunTask(pTask);
break;
}
}
//=========================================================
// GetSchedule - Decides which type of schedule best suits
// the monster's current state and conditions. Then calls
// monster's member function to get a pointer to a schedule
// of the proper type.
//=========================================================
int CNPC_HAssassin::SelectSchedule(void) {
switch (m_NPCState) {
case NPC_STATE_IDLE:
case NPC_STATE_ALERT: {
if (HasCondition(COND_HEAR_DANGER) || HasCondition(COND_HEAR_COMBAT)) {
if (HasCondition(COND_HEAR_DANGER))
return SCHED_TAKE_COVER_FROM_BEST_SOUND;
else
return SCHED_INVESTIGATE_SOUND;
}
}
break;
case NPC_STATE_COMBAT: {
// dead enemy
if (HasCondition(COND_ENEMY_DEAD)) {
// call base class, all code to handle dead enemies is centralized there.
return BaseClass::SelectSchedule();
}
// flying?
if (GetMoveType() == MOVETYPE_FLYGRAVITY) {
if (GetFlags() & FL_ONGROUND) {
//Msg( "landed\n" );
// just landed
SetMoveType(MOVETYPE_STEP);
return SCHED_ASSASSIN_JUMP_LAND;
} else {
//Msg("jump\n");
// jump or jump/shoot
if (m_NPCState == NPC_STATE_COMBAT)
return SCHED_ASSASSIN_JUMP;
else
return SCHED_ASSASSIN_JUMP_ATTACK;
}
}
if (HasCondition(COND_HEAR_DANGER)) {
return SCHED_TAKE_COVER_FROM_BEST_SOUND;
}
if (HasCondition(COND_LIGHT_DAMAGE)) {
m_iFrustration++;
}
if (HasCondition(COND_HEAVY_DAMAGE)) {
m_iFrustration++;
}
// jump player!
if (HasCondition(COND_CAN_MELEE_ATTACK1)) {
//Msg( "melee attack 1\n");
return SCHED_MELEE_ATTACK1;
}
// throw grenade
if (HasCondition(COND_CAN_RANGE_ATTACK2)) {
//Msg( "range attack 2\n");
return SCHED_RANGE_ATTACK2;
}
// spotted
if (HasCondition(COND_SEE_ENEMY) && HasCondition(COND_ENEMY_FACING_ME)) {
//Msg("exposed\n");
m_iFrustration++;
return SCHED_ASSASSIN_EXPOSED;
}
// can attack
if (HasCondition(COND_CAN_RANGE_ATTACK1)) {
//Msg( "range attack 1\n" );
m_iFrustration = 0;
return SCHED_RANGE_ATTACK1;
}
if (HasCondition(COND_SEE_ENEMY)) {
//Msg( "face\n");
return SCHED_COMBAT_FACE;
}
// new enemy
if (HasCondition(COND_NEW_ENEMY)) {
//Msg( "take cover\n");
return SCHED_TAKE_COVER_FROM_ENEMY;
}
// ALERT( at_console, "stand\n");
return SCHED_ALERT_STAND;
}
break;
}
return BaseClass::SelectSchedule();
}
//=========================================================
// HandleAnimEvent - catches the monster-specific messages
// that occur when tagged animation frames are played.
//
// Returns number of events handled, 0 if none.
//=========================================================
void CNPC_HAssassin::HandleAnimEvent(animevent_t *pEvent) {
switch (pEvent->event) {
case ASSASSIN_AE_SHOOT1:
Shoot();
break;
case ASSASSIN_AE_TOSS1: {
Vector vTossPos;
QAngle vAngles;
GetAttachment("grenadehand", vTossPos, vAngles);
CHandGrenade *pGrenade = (CHandGrenade *) Create("grenade_hand", vTossPos, vec3_angle);
if (pGrenade) {
pGrenade->ShootTimed(this, m_vecTossVelocity, 2.0);
}
m_flNextGrenadeCheck = gpGlobals->curtime +
6;// wait six seconds before even looking again to see if a grenade can be thrown.
m_fThrowGrenade = FALSE;
// !!!LATER - when in a group, only try to throw grenade if ordered.
}
break;
case ASSASSIN_AE_JUMP: {
SetMoveType(MOVETYPE_FLYGRAVITY);
SetGroundEntity(NULL);
SetAbsVelocity(m_vecJumpVelocity);
m_flNextJump = gpGlobals->curtime + 3.0;
}
return;
default:
BaseClass::HandleAnimEvent(pEvent);
break;
}
}
//=========================================================
// Shoot
//=========================================================
void CNPC_HAssassin::Shoot(void) {
Vector vForward, vRight, vUp;
Vector vecShootOrigin;
QAngle vAngles;
if (GetEnemy() == NULL) {
return;
}
GetAttachment("guntip", vecShootOrigin, vAngles);
Vector vecShootDir = GetShootEnemyDir(vecShootOrigin);
if (m_flLastShot + 2 < gpGlobals->curtime) {
m_flDiviation = 0.10;
} else {
m_flDiviation -= 0.01;
if (m_flDiviation < 0.02)
m_flDiviation = 0.02;
}
m_flLastShot = gpGlobals->curtime;
AngleVectors(GetAbsAngles(), &vForward, &vRight, &vUp);
Vector vecShellVelocity = vRight * random->RandomFloat(40, 90) + vUp * random->RandomFloat(75, 200) +
vForward * random->RandomFloat(-40, 40);
EjectShell(GetAbsOrigin() + vUp * 32 + vForward * 12, vecShellVelocity, GetAbsAngles().y, 0);
FireBullets(1, vecShootOrigin, vecShootDir, Vector(m_flDiviation, m_flDiviation, m_flDiviation), 2048,
m_iAmmoType); // shoot +-8 degrees
//NDebugOverlay::Line( vecShootOrigin, vecShootOrigin + vecShootDir * 2048, 255, 0, 0, true, 2.0 );
CPASAttenuationFilter filter(this);
EmitSound(filter, entindex(), "HAssassin.Shot");
DoMuzzleFlash();
VectorAngles(vecShootDir, vAngles);
SetPoseParameter("shoot", vecShootDir.x);
m_cAmmoLoaded--;
}
//=========================================================
//=========================================================
int CNPC_HAssassin::TranslateSchedule(int scheduleType) {
// Msg( "%d\n", m_iFrustration );
switch (scheduleType) {
case SCHED_TAKE_COVER_FROM_ENEMY:
if (m_iHealth > 30)
return SCHED_ASSASSIN_TAKE_COVER_FROM_ENEMY1;
else
return SCHED_ASSASSIN_TAKE_COVER_FROM_ENEMY2;
case SCHED_TAKE_COVER_FROM_BEST_SOUND:
return SCHED_ASSASSIN_TAKE_COVER_FROM_BEST_SOUND;
case SCHED_FAIL:
if (m_NPCState == NPC_STATE_COMBAT)
return SCHED_ASSASSIN_FAIL;
break;
case SCHED_ALERT_STAND:
if (m_NPCState == NPC_STATE_COMBAT)
return SCHED_ASSASSIN_HIDE;
break;
//case SCHED_CHASE_ENEMY:
// return SCHED_ASSASSIN_HUNT;
case SCHED_MELEE_ATTACK1:
if (GetFlags() & FL_ONGROUND) {
if (m_flNextJump > gpGlobals->curtime) {
// can't jump yet, go ahead and fail
return SCHED_ASSASSIN_FAIL;
} else {
return SCHED_ASSASSIN_JUMP;
}
} else {
return SCHED_ASSASSIN_JUMP_ATTACK;
}
}
return BaseClass::TranslateSchedule(scheduleType);
}
//=========================================================
// RunAI
//=========================================================
void CNPC_HAssassin::RunAI(void) {
BaseClass::RunAI();
// always visible if moving
// always visible is not on hard
if (g_iSkillLevel != SKILL_HARD || GetEnemy() == NULL || m_lifeState == LIFE_DEAD || GetActivity() == ACT_RUN ||
GetActivity() == ACT_WALK || !(GetFlags() & FL_ONGROUND))
m_iTargetRanderamt = 255;
else
m_iTargetRanderamt = 20;
CPASAttenuationFilter filter(this);
if (GetRenderColor().a > m_iTargetRanderamt) {
if (GetRenderColor().a == 255) {
EmitSound(filter, entindex(), "HAssassin.Beamsound");
}
SetRenderColorA(MAX(GetRenderColor().a - 50, m_iTargetRanderamt));
m_nRenderMode = kRenderTransTexture;
} else if (GetRenderColor().a < m_iTargetRanderamt) {
SetRenderColorA(MIN(GetRenderColor().a + 50, m_iTargetRanderamt));
if (GetRenderColor().a == 255)
m_nRenderMode = kRenderNormal;
}
if (GetActivity() == ACT_RUN || GetActivity() == ACT_WALK) {
static int iStep = 0;
iStep = !iStep;
if (iStep) {
EmitSound(filter, entindex(), "HAssassin.Footstep");
}
}
}
AI_BEGIN_CUSTOM_NPC( monster_human_assassin, CNPC_HAssassin
)
DECLARE_TASK( TASK_ASSASSIN_FALL_TO_GROUND )
DECLARE_ACTIVITY( ACT_ASSASSIN_FLY_UP )
DECLARE_ACTIVITY( ACT_ASSASSIN_FLY_ATTACK )
DECLARE_ACTIVITY( ACT_ASSASSIN_FLY_DOWN )
//=========================================================
// AI Schedules Specific to this monster
//=========================================================
//=========================================================
// Enemy exposed assasin's cover
//=========================================================
//=========================================================
// > SCHED_ASSASSIN_EXPOSED
//=========================================================
DEFINE_SCHEDULE
(
SCHED_ASSASSIN_EXPOSED,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_RANGE_ATTACK1 0"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_ASSASSIN_JUMP"
" TASK_SET_SCHEDULE SCHEDULE:SCHED_TAKE_COVER_FROM_ENEMY"
" "
" Interrupts"
" COND_CAN_MELEE_ATTACK1"
)
//=========================================================
// > SCHED_ASSASSIN_JUMP
//=========================================================
DEFINE_SCHEDULE
(
SCHED_ASSASSIN_JUMP,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_PLAY_SEQUENCE ACTIVITY:ACT_HOP"
" TASK_SET_SCHEDULE SCHEDULE:SCHED_ASSASSIN_JUMP_ATTACK"
" "
" Interrupts"
)
//=========================================================
// > SCHED_ASSASSIN_JUMP_ATTACK
//=========================================================
DEFINE_SCHEDULE
(
SCHED_ASSASSIN_JUMP_ATTACK,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_ASSASSIN_JUMP_LAND"
" TASK_ASSASSIN_FALL_TO_GROUND 0"
" "
" Interrupts"
)
//=========================================================
// > SCHED_ASSASSIN_JUMP_LAND
//=========================================================
DEFINE_SCHEDULE
(
SCHED_ASSASSIN_JUMP_LAND,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_ASSASSIN_EXPOSED"
" TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE"
" TASK_REMEMBER MEMORY:CUSTOM1"
" TASK_FIND_NODE_COVER_FROM_ENEMY 0"
" TASK_RUN_PATH 0"
" TASK_FORGET MEMORY:CUSTOM1"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_REMEMBER MEMORY:INCOVER"
" TASK_FACE_ENEMY 0"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_RANGE_ATTACK1"
" "
" Interrupts"
)
//=========================================================
// Fail Schedule
//=========================================================
//=========================================================
// > SCHED_ASSASSIN_FAIL
//=========================================================
DEFINE_SCHEDULE
(
SCHED_ASSASSIN_FAIL,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE"
" TASK_WAIT_FACE_ENEMY 2"
" TASK_SET_SCHEDULE SCHEDULE:SCHED_CHASE_ENEMY"
" "
" Interrupts"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
" COND_CAN_RANGE_ATTACK1"
" COND_CAN_RANGE_ATTACK2"
" COND_CAN_MELEE_ATTACK1"
" COND_HEAR_DANGER"
" COND_HEAR_PLAYER"
)
//=========================================================
// > SCHED_ASSASSIN_TAKE_COVER_FROM_ENEMY1
//=========================================================
DEFINE_SCHEDULE
(
SCHED_ASSASSIN_TAKE_COVER_FROM_ENEMY1,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_WAIT 0.2"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_RANGE_ATTACK1"
" TASK_FIND_COVER_FROM_ENEMY 0"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_REMEMBER MEMORY:INCOVER"
" TASK_FACE_ENEMY 0"
" "
" Interrupts"
" COND_CAN_MELEE_ATTACK1"
" COND_NEW_ENEMY"
" COND_HEAR_DANGER"
)
//=========================================================
// > SCHED_ASSASSIN_TAKE_COVER_FROM_ENEMY2
//=========================================================
DEFINE_SCHEDULE
(
SCHED_ASSASSIN_TAKE_COVER_FROM_ENEMY2,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_WAIT 0.2"
" TASK_FACE_ENEMY 0"
" TASK_RANGE_ATTACK1 0"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_RANGE_ATTACK1"
" TASK_FIND_COVER_FROM_ENEMY 0"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_REMEMBER MEMORY:INCOVER"
" TASK_FACE_ENEMY 0"
" "
" Interrupts"
" COND_CAN_MELEE_ATTACK1"
" COND_NEW_ENEMY"
" COND_HEAR_DANGER"
)
//=========================================================
// hide from the loudest sound source
//=========================================================
//=========================================================
// > SCHED_ASSASSIN_TAKE_COVER_FROM_BEST_SOUND
//=========================================================
DEFINE_SCHEDULE
(
SCHED_ASSASSIN_TAKE_COVER_FROM_BEST_SOUND,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_MELEE_ATTACK1"
" TASK_STOP_MOVING 0"
" TASK_FIND_COVER_FROM_BEST_SOUND 0"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_REMEMBER MEMORY:INCOVER"
" TASK_TURN_LEFT 179"
" "
" Interrupts"
" COND_NEW_ENEMY"
)
//=========================================================
// > SCHED_ASSASSIN_HIDE
//=========================================================
DEFINE_SCHEDULE
(
SCHED_ASSASSIN_HIDE,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE"
" TASK_WAIT 2.0"
" TASK_SET_SCHEDULE SCHEDULE:SCHED_CHASE_ENEMY"
" Interrupts"
" COND_NEW_ENEMY"
" COND_SEE_ENEMY"
" COND_SEE_FEAR"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
" COND_PROVOKED"
" COND_HEAR_DANGER"
)
//=========================================================
// > SCHED_ASSASSIN_HUNT
//=========================================================
DEFINE_SCHEDULE
(
SCHED_ASSASSIN_HUNT,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_ASSASSIN_TAKE_COVER_FROM_ENEMY2"
" TASK_GET_PATH_TO_ENEMY 0"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" Interrupts"
" COND_NEW_ENEMY"
" COND_CAN_RANGE_ATTACK1"
" COND_HEAR_DANGER"
)
AI_END_CUSTOM_NPC()
| 29.0783 | 124 | 0.548084 | [
"vector"
] |
6c1e9f0003cd3bdc923219faccfb6a3422a0b4a1 | 167 | cpp | C++ | ceppengine/src/ceppengine/object.cpp | Winded/ceppengine | 52a9c1723dc45aba4d85d50e4c919ec8016c8d94 | [
"MIT"
] | 2 | 2017-11-13T11:29:03.000Z | 2017-11-13T12:09:12.000Z | ceppengine/src/ceppengine/object.cpp | Winded/ceppengine | 52a9c1723dc45aba4d85d50e4c919ec8016c8d94 | [
"MIT"
] | null | null | null | ceppengine/src/ceppengine/object.cpp | Winded/ceppengine | 52a9c1723dc45aba4d85d50e4c919ec8016c8d94 | [
"MIT"
] | null | null | null | #include "object.h"
#include <iostream>
namespace cepp {
Object::Object() : mRefCount(0)
{
}
Object::~Object()
{
assert(mRefCount == 0);
}
} // namespace cepp
| 10.4375 | 31 | 0.628743 | [
"object"
] |
6c23ef9c41494d6bf084411ae5ad89b4152e00cf | 77,875 | cpp | C++ | src/universal/ktxtexture.cpp | VladislavShubnikov/dwnsmpl | 10986b83bc32e0f552b41556ee81b6d425c2967d | [
"MIT"
] | null | null | null | src/universal/ktxtexture.cpp | VladislavShubnikov/dwnsmpl | 10986b83bc32e0f552b41556ee81b6d425c2967d | [
"MIT"
] | null | null | null | src/universal/ktxtexture.cpp | VladislavShubnikov/dwnsmpl | 10986b83bc32e0f552b41556ee81b6d425c2967d | [
"MIT"
] | null | null | null | // ****************************************************************************
//
// ****************************************************************************
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <math.h>
#include <string.h>
#include <assert.h>
#include "memtrack.h"
#include "ktxtexture.h"
// ****************************************************************************
// Defines
// ****************************************************************************
#define GAUSS_SMOOTH_MAX_SIDE (11*2+1)
// ****************************************************************************
// Vars
// ****************************************************************************
static float s_gaussWeights[GAUSS_SMOOTH_MAX_SIDE * GAUSS_SMOOTH_MAX_SIDE * GAUSS_SMOOTH_MAX_SIDE];
// KTX id sign
static unsigned char s_ktxIdFile[12] =
{
0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
};
static char *s_ktxTextureErrMessages[KTX_ERROR_COUNT] =
{
"OK", // [0] KTX_ERROR_OK
"No memory", // [1] KTX_ERROR_NO_MEMORY
"Wrong format", // [2] KTX_ERROR_WRONG_FORMAT
"Wrong size", // [3] KTX_ERROR_WRONG_SIZE
"Broken data content", // [4] KTX_ERROR_BROKEN_CONTENT
"Error write to file" // [5] KTX_ERROR_WRITE
};
// ****************************************************************************
// Methods
// ****************************************************************************
const char *KtxTextureGetErrorString(const KtxError err)
{
return s_ktxTextureErrMessages[ (int)err ];
}
KtxTexture::KtxTexture()
{
memset(&m_header, 0, sizeof(m_header) );
m_data = NULL;
m_dataSize = 0;
m_isCompressed = 0;
m_boxSize.x = m_boxSize.y = m_boxSize.z = 0.0f;
}
KtxTexture::~KtxTexture()
{
destroy();
}
void KtxTexture::destroy()
{
if (m_data != NULL)
delete [] m_data;
m_data = NULL;
m_dataSize = 0;
memset((char*)&m_header, 0, sizeof(m_header));
}
KtxError KtxTexture::createAs1ByteCopy(const KtxTexture *tex)
{
int sizeVolume;
const MUint32 *src;
// create 1 byte per pixel texture from 1/3/4 bpp texture
memcpy(&m_header.m_id, &tex->m_header, sizeof(KtxHeader));
// copy user key data
memcpy(&m_keyData, &tex->m_keyData, sizeof(KtxKeyData) );
// Created 1 byte per pixel texture
m_header.m_glFormat = KTX_GL_RED;
// GL_R8_EXT, GL_R8 (0x8229)
m_header.m_glInternalFormat = KTX_GL_R8_EXT;
m_header.m_glBaseInternalFormat = KTX_GL_RED;
sizeVolume = m_header.m_pixelWidth;
if (m_header.m_pixelHeight > 0)
sizeVolume *= m_header.m_pixelHeight;
if (m_header.m_pixelDepth > 0)
sizeVolume *= m_header.m_pixelDepth;
if (m_data != NULL)
delete [] m_data;
m_data = M_NEW( MUint8[sizeVolume] );
if (!m_data)
return KTX_ERROR_NO_MEMORY;
m_isCompressed = 0;
m_dataSize = sizeVolume;
// Convert 4 -> 1
if (tex->m_header.m_glFormat == KTX_GL_RGBA)
{
src = (const MUint32 *)tex->m_data;
MUint8 *dst = (MUint8*)m_data;
for (int i = 0; i < (int)sizeVolume; i++)
{
MUint32 val32 = src[i];
val32 >>= 24;
val32 &= 0xff;
dst[i] = (MUint8)val32;
}
}
// Convert 1 -> 1
if (tex->m_header.m_glFormat == KTX_GL_RED)
{
memcpy(m_data, tex->m_data, sizeVolume);
}
return KTX_ERROR_OK;
}
KtxError KtxTexture::createAsCopy(const KtxTexture *tex)
{
int sizeVolume;
// create 1 byte per pixel texture from 1/3/4 bpp texture
memcpy(&m_header, &tex->m_header, sizeof(KtxHeader));
sizeVolume = m_header.m_pixelWidth;
if (m_header.m_pixelHeight > 0)
sizeVolume *= m_header.m_pixelHeight;
if (m_header.m_pixelDepth > 0)
sizeVolume *= m_header.m_pixelDepth;
if (tex->m_header.m_glFormat == KTX_GL_RED)
sizeVolume *= 1;
if (tex->m_header.m_glFormat == KTX_GL_RGB)
sizeVolume *= 3;
if (tex->m_header.m_glFormat == KTX_GL_RGBA)
sizeVolume *= 4;
m_isCompressed = 0;
m_dataSize = sizeVolume;
// delete old data
if (m_data != NULL)
delete[] m_data;
m_data = M_NEW(MUint8[sizeVolume]);
if (!m_data)
return KTX_ERROR_NO_MEMORY;
// do copy
memcpy(m_data, tex->m_data, sizeVolume);
return KTX_ERROR_OK;
}
KtxError KtxTexture::create1D(const int xDim, const int bytesPerPixel)
{
int sizeVolume;
memcpy(m_header.m_id, s_ktxIdFile, sizeof(s_ktxIdFile));
m_header.m_endianness = 0x04030201;
m_header.m_glType = KTX_GL_UNSIGNED_BYTE;
m_header.m_glTypeSize = 1;
m_header.m_pixelWidth = xDim;
m_header.m_pixelHeight = 0;
m_header.m_pixelDepth = 0;
m_header.m_numberOfArrayElements = 0; // for non-array textures is 0.
m_header.m_numberOfFaces = 1;
m_header.m_numberOfMipmapLevels = 1;
//m_header.m_bytesOfKeyValueData = sizeof(s_keyValues);
m_header.m_bytesOfKeyValueData = 0;
switch (bytesPerPixel)
{
case 1:
{
m_header.m_glFormat = KTX_GL_RED;
// GL_R8_EXT, GL_R8 (0x8229)
m_header.m_glInternalFormat = KTX_GL_RED;
m_header.m_glBaseInternalFormat = KTX_GL_RED;
break;
}
case 3:
{
m_header.m_glFormat = KTX_GL_RGB;
// GL_RGB8_OES, GL_RGB8_EXT (0x8051)
m_header.m_glInternalFormat = KTX_GL_RGB;
m_header.m_glBaseInternalFormat = KTX_GL_RGB;
break;
}
case 4:
{
m_header.m_glFormat = KTX_GL_RGBA;
// GL_RGBA8_OES, GL_RGBA8_EXT (0x8058)
m_header.m_glInternalFormat = KTX_GL_RGBA;
m_header.m_glBaseInternalFormat = KTX_GL_RGBA;
break;
}
default:
{
// impossible pixel format
assert(bytesPerPixel < -5555);
return KTX_ERROR_WRONG_FORMAT;
}
} // switch
sizeVolume = xDim * bytesPerPixel;
m_data = M_NEW( MUint8[sizeVolume] );
if (!m_data)
return KTX_ERROR_NO_MEMORY;
memset(m_data, 0, sizeVolume);
m_isCompressed = 0;
m_dataSize = sizeVolume;
return KTX_ERROR_OK;
}
KtxError KtxTexture::create2D(
const int xDim,
const int yDim,
const int bytesPerPixel
)
{
int sizeVolume;
memcpy(m_header.m_id, s_ktxIdFile, sizeof(s_ktxIdFile));
m_header.m_endianness = 0x04030201;
m_header.m_glType = KTX_GL_UNSIGNED_BYTE;
m_header.m_glTypeSize = 1;
m_header.m_pixelWidth = xDim;
m_header.m_pixelHeight = yDim;
m_header.m_pixelDepth = 0;
m_header.m_numberOfArrayElements = 0; // for non-array textures is 0.
m_header.m_numberOfFaces = 1;
m_header.m_numberOfMipmapLevels = 1;
//m_header.m_bytesOfKeyValueData = sizeof(s_keyValues);
m_header.m_bytesOfKeyValueData = 0;
switch (bytesPerPixel)
{
case 1:
{
m_header.m_glFormat = KTX_GL_RED;
// GL_R8_EXT, GL_R8 (0x8229)
m_header.m_glInternalFormat = KTX_GL_RED;
m_header.m_glBaseInternalFormat = KTX_GL_RED;
break;
}
case 3:
{
m_header.m_glFormat = KTX_GL_RGB;
// GL_RGB8_OES, GL_RGB8_EXT (0x8051)
m_header.m_glInternalFormat = KTX_GL_RGB;
m_header.m_glBaseInternalFormat = KTX_GL_RGB;
break;
}
case 4:
{
m_header.m_glFormat = KTX_GL_RGBA;
// GL_RGBA8_OES, GL_RGBA8_EXT (0x8058)
m_header.m_glInternalFormat = KTX_GL_RGBA;
m_header.m_glBaseInternalFormat = KTX_GL_RGBA;
break;
}
default:
{
// impossible pixel format
assert(bytesPerPixel < -5555);
return KTX_ERROR_WRONG_FORMAT;
}
} // switch
sizeVolume = xDim * yDim * bytesPerPixel;
m_data = M_NEW( MUint8[sizeVolume] );
if (!m_data)
return KTX_ERROR_NO_MEMORY;
memset(m_data, 0, sizeVolume);
m_dataSize = sizeVolume;
m_isCompressed = 0;
return KTX_ERROR_OK;
}
KtxError KtxTexture::create3D(
const int xDim,
const int yDim,
const int zDim,
const int bytesPerPixel
)
{
int sizeVolume;
memcpy(m_header.m_id, s_ktxIdFile, sizeof(s_ktxIdFile));
m_header.m_endianness = 0x04030201;
m_header.m_glType = KTX_GL_UNSIGNED_BYTE;
m_header.m_glTypeSize = 1;
m_header.m_pixelWidth = xDim;
m_header.m_pixelHeight = yDim;
m_header.m_pixelDepth = zDim;
m_header.m_numberOfArrayElements = 0; // for non-array textures is 0.
m_header.m_numberOfFaces = 1;
m_header.m_numberOfMipmapLevels = 1;
//m_header.m_bytesOfKeyValueData = sizeof(s_keyValues);
m_header.m_bytesOfKeyValueData = 0;
switch (bytesPerPixel)
{
case 1:
{
m_header.m_glFormat = KTX_GL_RED;
// GL_R8_EXT, GL_R8 (0x8229)
m_header.m_glInternalFormat = KTX_GL_RED;
m_header.m_glBaseInternalFormat = KTX_GL_RED;
break;
}
case 3:
{
m_header.m_glFormat = KTX_GL_RGB;
// GL_RGB8_OES, GL_RGB8_EXT (0x8051)
m_header.m_glInternalFormat = KTX_GL_RGB;
m_header.m_glBaseInternalFormat = KTX_GL_RGB;
break;
}
case 4:
{
m_header.m_glFormat = KTX_GL_RGBA;
// GL_RGBA8_OES, GL_RGBA8_EXT (0x8058)
m_header.m_glInternalFormat = KTX_GL_RGBA;
m_header.m_glBaseInternalFormat = KTX_GL_RGBA;
break;
}
default:
{
// impossible pixel format
assert(bytesPerPixel < -5555);
return KTX_ERROR_WRONG_FORMAT;
}
} // switch
sizeVolume = xDim * yDim * zDim * bytesPerPixel;
m_data = M_NEW( MUint8[sizeVolume] );
if (!m_data)
return KTX_ERROR_NO_MEMORY;
memset(m_data, 0, sizeVolume);
m_dataSize = sizeVolume;
m_isCompressed = 0;
return KTX_ERROR_OK;
}
KtxError KtxTexture::saveToFileContent(FILE *file)
{
int sizeVolume, bytesPerPixel;
int numBytesWritten;
static char strKeyBuf[sizeof(int) * 2 + 8 * 2 + sizeof(V3f) * 2 + 8];
if ((unsigned char)m_header.m_id[0] != s_ktxIdFile[0])
return KTX_ERROR_BROKEN_CONTENT;
// Add bytes for key values
if (m_keyData.m_dataType == KTX_KEY_DATA_BBOX)
{
m_header.m_bytesOfKeyValueData = 0;
char *dst = strKeyBuf;
int pairSize = 8 + sizeof(V3f);
assert((pairSize & 3) == 0);
V3f *vBoxMin = reinterpret_cast<V3f*>(m_keyData.m_buffer);
V3f *vBoxMax = reinterpret_cast<V3f*>(m_keyData.m_buffer) + 1;
*((int*)dst) = pairSize;
dst += sizeof(pairSize);
strcpy(dst, "fBoxMin");
dst += strlen("fBoxMin") + 1;
memcpy(dst, vBoxMin, sizeof(V3f) );
dst += sizeof(V3f);
*((int*)dst) = pairSize;
dst += sizeof(pairSize);
strcpy(dst, "fBoxMax");
dst += strlen("fBoxMax") + 1;
memcpy(dst, vBoxMax, sizeof(V3f));
dst += sizeof(V3f);
m_header.m_bytesOfKeyValueData = (MUint32)(dst - strKeyBuf);
assert(m_header.m_bytesOfKeyValueData <= sizeof(strKeyBuf));
}
if (m_keyData.m_dataType == KTX_KEY_DATA_MIN_SIZE)
{
m_header.m_bytesOfKeyValueData = 0;
char *dst = strKeyBuf;
int pairSize = 8 + sizeof(V3d);
assert((pairSize & 3) == 0);
V3d *vBoxMin = reinterpret_cast<V3d*>(m_keyData.m_buffer);
V3d *vBoxSize = reinterpret_cast<V3d*>(m_keyData.m_buffer) + 1;
*((int*)dst) = pairSize;
dst += sizeof(pairSize);
strcpy(dst, "dBoxMin");
dst += strlen("dBoxMin") + 1;
memcpy(dst, vBoxMin, sizeof(V3d));
dst += sizeof(V3f);
*((int*)dst) = pairSize;
dst += sizeof(pairSize);
strcpy(dst, "dBoxSize");
dst += strlen("dBoxSize") + 1;
memcpy(dst, vBoxSize, sizeof(V3d));
dst += sizeof(V3d);
m_header.m_bytesOfKeyValueData = (MUint32)(dst - strKeyBuf);
assert(m_header.m_bytesOfKeyValueData <= sizeof(strKeyBuf));
}
bytesPerPixel =
(m_header.m_glFormat == KTX_GL_RED)?
1 : ((m_header.m_glFormat == KTX_GL_RGB)? 3: 4);
sizeVolume = m_header.m_pixelWidth * bytesPerPixel;
if (m_header.m_pixelHeight > 0)
sizeVolume *= m_header.m_pixelHeight;
if (m_header.m_pixelDepth > 0)
sizeVolume *= m_header.m_pixelDepth;
// write header to dest buffer
numBytesWritten = (int)fwrite(&m_header, 1, sizeof(m_header), file );
if (numBytesWritten != sizeof(m_header))
return KTX_ERROR_WRITE;
// write key values, if present in texture
if (
(m_keyData.m_dataType != KTX_KEY_DATA_NA) &&
m_header.m_bytesOfKeyValueData
)
{
numBytesWritten = (int)fwrite(strKeyBuf, 1, m_header.m_bytesOfKeyValueData, file);
if (numBytesWritten != (int)m_header.m_bytesOfKeyValueData)
return KTX_ERROR_WRITE;
} // if exists key data
// write volume size to dest buffer
numBytesWritten = (int)fwrite(&sizeVolume, 1, sizeof(sizeVolume), file);
if (numBytesWritten != sizeof(sizeVolume))
return KTX_ERROR_WRITE;
// write image bits
assert(m_data != NULL);
numBytesWritten = (int)fwrite(m_data, 1, sizeVolume, file);
if (numBytesWritten != sizeVolume)
return KTX_ERROR_WRITE;
return KTX_ERROR_OK;
}
KtxError KtxTexture::loadFromFileContent(FILE *file)
{
int numReadedBytes, xDim, yDim, zDim, bytesPerVoxel;
// numReadedBytes = (int)file.read( (char*)&m_header, sizeof(m_header) );
numReadedBytes = (int)fread(&m_header, 1, sizeof(m_header), file);
if (numReadedBytes != sizeof(m_header))
return KTX_ERROR_WRONG_SIZE;
// check is it KTX file header
if (memcmp(m_header.m_id, s_ktxIdFile, sizeof(s_ktxIdFile)) != 0)
return KTX_ERROR_BROKEN_CONTENT;
if (m_header.m_endianness != 0x04030201)
return KTX_ERROR_WRONG_FORMAT;
xDim = (int)m_header.m_pixelWidth;
yDim = (int)m_header.m_pixelHeight;
zDim = (int)m_header.m_pixelDepth;
USE_PARAM(xDim);
USE_PARAM(yDim);
USE_PARAM(zDim);
m_isCompressed = 0;
bytesPerVoxel = 0;
if (m_header.m_glFormat == KTX_GL_RED)
bytesPerVoxel = 1;
else if (m_header.m_glFormat == KTX_GL_RGB)
bytesPerVoxel = 3;
else if (m_header.m_glFormat == KTX_GL_RGBA)
bytesPerVoxel = 4;
else if (
(m_header.m_glInternalFormat == KTX_GL_COMPRESSED_RGB_S3TC_DXT1_EXT) &&
(m_header.m_glFormat == 0)
)
{
bytesPerVoxel = 1;
m_isCompressed = 1;
}
else if (
(m_header.m_glInternalFormat == KTX_GL_COMPRESSED_RGBA_S3TC_DXT5_EXT) &&
(m_header.m_glFormat == 0)
)
{
bytesPerVoxel = 1;
m_isCompressed = 1;
}
else
return KTX_ERROR_WRONG_FORMAT;
//volSize = xDim * yDim * zDim * bytesPerVoxel;
USE_PARAM(bytesPerVoxel);
if (m_header.m_bytesOfKeyValueData > 0)
{
char *userData;
userData = M_NEW(char[m_header.m_bytesOfKeyValueData + 8] );
if (!userData)
return KTX_ERROR_NO_MEMORY;
numReadedBytes = (int)fread(userData, 1, m_header.m_bytesOfKeyValueData, file);
if (numReadedBytes != (int)m_header.m_bytesOfKeyValueData)
{
delete [] userData;
return KTX_ERROR_WRONG_FORMAT;
}
V3f vBoxMin, vBoxMax;
// parse user data
static char strName[64];
char *src;
src = userData;
while (src - userData < (int)m_header.m_bytesOfKeyValueData)
{
int pairLen;
pairLen = *((int*)src);
USE_PARAM(pairLen);
src += sizeof(int);
char *dst;
for (
dst = strName;
(src[0] != 0) && (dst - strName < sizeof(strName)-1);
src++, dst++
)
{
*dst = *src;
}
*dst = 0;
src++;
if (strcmp(strName, "fBoxMin") == 0)
{
V3f *vertDstMin = reinterpret_cast<V3f*>(m_keyData.m_buffer);
m_keyData.m_dataType = KTX_KEY_DATA_BBOX;
V3f *vertData = reinterpret_cast<V3f*>(src);
*vertDstMin = *vertData;
vBoxMin = *vertData;
src += sizeof(V3f);
}
if (strcmp(strName, "fBoxMax") == 0)
{
V3f *vertDstMax = reinterpret_cast<V3f*>(m_keyData.m_buffer) + 1;
m_keyData.m_dataType = KTX_KEY_DATA_BBOX;
V3f *vertData = reinterpret_cast<V3f*>(src);
*vertDstMax = *vertData;
vBoxMax = *vertData;
src += sizeof(V3f);
m_boxSize.x = vBoxMax.x - vBoxMin.x;
m_boxSize.y = vBoxMax.y - vBoxMin.y;
m_boxSize.z = vBoxMax.z - vBoxMin.z;
}
if (strcmp(strName, "dBoxMin") == 0)
{
V3d *vertDstMin = reinterpret_cast<V3d*>(m_keyData.m_buffer);
m_keyData.m_dataType = KTX_KEY_DATA_MIN_SIZE;
V3d *vertData = reinterpret_cast<V3d*>(src);
*vertDstMin = *vertData;
src += sizeof(V3d);
}
if (strcmp(strName, "dBoxSize") == 0)
{
V3d *vertDstSize = reinterpret_cast<V3d*>(m_keyData.m_buffer) + 1;
m_keyData.m_dataType = KTX_KEY_DATA_MIN_SIZE;
V3d *vertData = reinterpret_cast<V3d*>(src);
*vertDstSize = *vertData;
src += sizeof(V3d);
}
} // while ! end of user key pairs
delete[] userData;
}
// read size
//numReadedBytes = (int)file.read( (char*)&m_dataSize, sizeof(m_dataSize) );
numReadedBytes = (int)fread(&m_dataSize, 1, sizeof(m_dataSize), file);
if (numReadedBytes != sizeof(m_dataSize))
return KTX_ERROR_WRONG_FORMAT;
if (m_dataSize > 1024 * 1024 * 512)
return KTX_ERROR_WRONG_FORMAT;
if (m_data)
delete [] m_data;
m_data = M_NEW(MUint8[m_dataSize]);
if (m_data == NULL)
return KTX_ERROR_NO_MEMORY;
//numReadedBytes = (int)file.read( (char*)m_data, m_dataSize);
numReadedBytes = (int)fread(m_data, 1, m_dataSize, file);
if (numReadedBytes != m_dataSize)
return KTX_ERROR_WRONG_SIZE;
if (m_keyData.m_dataType == KTX_KEY_DATA_MIN_SIZE)
{
KtxError err = enlargeByMinSize();
return err;
}
return KTX_ERROR_OK;
}
KtxError KtxTexture::enlargeByMinSize()
{
if (m_keyData.m_dataType != KTX_KEY_DATA_MIN_SIZE)
return KTX_ERROR_OK;
if (m_header.m_glFormat != KTX_GL_RGBA)
return KTX_ERROR_WRONG_FORMAT;
V3d *vBoxMin = reinterpret_cast<V3d*>(m_keyData.m_buffer);
V3d *vBoxSize = reinterpret_cast<V3d*>(m_keyData.m_buffer) + 1;
int xDimDst = vBoxSize->x;
int yDimDst = vBoxSize->y;
int zDimDst = vBoxSize->z;
int xDimSrc = getWidth();
int yDimSrc = getHeight();
int zDimSrc = getDepth();
int numPixelsDst = xDimDst * yDimDst * zDimDst;
MUint32 *pixelsDst = M_NEW(MUint32[numPixelsDst]);
if (pixelsDst == NULL)
return KTX_ERROR_NO_MEMORY;
// Clear with background
MUint32 *pixelsSrc = (MUint32*)m_data;
MUint32 valBackground = pixelsSrc[0];
for (int i = 0; i < numPixelsDst; i++)
{
pixelsDst[i] = valBackground;
}
// Copy part of volume
int x, y, z;
for (z = 0; z < zDimSrc; z++)
{
int zDst = z + vBoxMin->z;
int zDstOff = zDst * xDimDst * yDimDst;
for (y = 0; y < yDimSrc; y++)
{
int yDst = y + vBoxMin->y;
int yDstOff = yDst * xDimDst;
for (x = 0; x < xDimSrc; x++)
{
MUint32 val = *pixelsSrc++;
int xDst = x + vBoxMin->x;
int off = xDst + yDstOff + zDstOff;
pixelsDst[off] = val;
} // for (x)
} // for (y)
} // for (z)
// setup new dimensions
m_header.m_pixelWidth = xDimDst;
m_header.m_pixelHeight = yDimDst;
m_header.m_pixelDepth = zDimDst;
// assign new pixels array
delete[] m_data;
m_data = (MUint8*)pixelsDst;
return KTX_ERROR_OK;
}
static __inline const char *_readUntil(
const char *strStart,
const int bufSize,
const char *strBuf,
const char symMatch
)
{
const char *str = strBuf;
while (str[0] != symMatch)
{
str++;
if (str - strStart >= bufSize)
return NULL;
}
str++;
return str;
}
#define _IS_DIGIT(ch) ((((ch) >= '0') && ((ch) <= '9')) ||\
((ch) == 'e') || ((ch) == '.') || ((ch) == '-') || ((ch) == '+'))
static int _closestPowerOfTwoGreatOrEqual(const int val)
{
int i;
for (i = 1; i < 31; i++)
{
int dim = 1 << i;
if (val <= dim)
return dim;
}
return -1;
}
static void _copyAndAlignTexture(
const MUint8 *pixelsSrc,
const int xDimSrc,
const int yDimSrc,
const int zDimSrc,
MUint8 *pixelsDst,
const int xDimDst,
const int yDimDst,
const int zDimDst
)
{
int xyzDimDst;
int x, y, z;
int xDimSrc2 = xDimSrc / 2;
int yDimSrc2 = yDimSrc / 2;
int zDimSrc2 = zDimSrc / 2;
int xDimDst2 = xDimDst / 2;
int yDimDst2 = yDimDst / 2;
int zDimDst2 = zDimDst / 2;
xyzDimDst = xDimDst * yDimDst * zDimDst;
int xyzDimSrc = xDimSrc * yDimSrc * zDimSrc;
int numBlacks = 0;
int numWhites = 0;
for (x = 0; x < xyzDimSrc; x++)
{
MUint32 val = (MUint32)pixelsSrc[x];
if (val <= 32)
numBlacks++;
if (val >= 256 - 32)
numWhites++;
}
MUint32 valBackground;
if (numBlacks > numWhites)
valBackground = 0;
else
valBackground = 255;
memset((char*)pixelsDst, valBackground, xyzDimDst);
int indSrc = 0;
for (z = 0; z < zDimSrc; z++)
{
int zDst = z - zDimSrc2 + zDimDst2;
int zOff = zDst * (xDimDst * yDimDst);
for (y = 0; y < yDimSrc; y++)
{
int yDst = y - yDimSrc2 + yDimDst2;
int yOff = yDst * xDimDst;
for (x = 0; x < xDimSrc; x++)
{
int offDst;
MUint8 val = pixelsSrc[indSrc++];
int xDst = x - xDimSrc2 + xDimDst2;
offDst = xDst + yOff + zOff;
pixelsDst[offDst] = val;
} // for (x)
} // for (y)
} // for (z)
}
KtxError KtxTexture::createAs1ByteCopyPowerOfTwo(const KtxTexture *tex)
{
int sizeVolume;
// create 1 byte per pixel texture from 1/3/4 bpp texture
memcpy(&m_header.m_id, &tex->m_header, sizeof(KtxHeader));
// Make texture dimension as power of two.
m_header.m_pixelWidth =
_closestPowerOfTwoGreatOrEqual(tex->m_header.m_pixelWidth);
m_header.m_pixelHeight =
_closestPowerOfTwoGreatOrEqual(tex->m_header.m_pixelHeight);
m_header.m_pixelDepth =
_closestPowerOfTwoGreatOrEqual(tex->m_header.m_pixelDepth);
// copy user key data
memcpy(&m_keyData, &tex->m_keyData, sizeof(KtxKeyData));
// Created 1 byte per pixel texture
m_header.m_glFormat = KTX_GL_RED;
// GL_R8_EXT, GL_R8 (0x8229)
m_header.m_glInternalFormat = KTX_GL_R8_EXT;
m_header.m_glBaseInternalFormat = KTX_GL_RED;
sizeVolume = m_header.m_pixelWidth;
if (m_header.m_pixelHeight > 0)
sizeVolume *= m_header.m_pixelHeight;
if (m_header.m_pixelDepth > 0)
sizeVolume *= m_header.m_pixelDepth;
if (m_data != NULL)
delete[] m_data;
m_data = M_NEW(MUint8[sizeVolume]);
if (!m_data)
return KTX_ERROR_NO_MEMORY;
m_isCompressed = 0;
m_dataSize = sizeVolume;
// Convert 1 -> 1
assert(tex->m_header.m_glFormat == KTX_GL_RED);
//memcpy(m_data, tex->m_data, sizeVolume);
int xDimSrc = tex->m_header.m_pixelWidth;
int yDimSrc = tex->m_header.m_pixelHeight;
int zDimSrc = tex->m_header.m_pixelDepth;
int xDimDst = m_header.m_pixelWidth;
int yDimDst = m_header.m_pixelHeight;
int zDimDst = m_header.m_pixelDepth;
const MUint8 *pixelsSrc = tex->getData();
MUint8 *pixelsDst = getData();
_copyAndAlignTexture(
pixelsSrc,
xDimSrc, yDimSrc, zDimSrc,
pixelsDst,
xDimDst, yDimDst, zDimDst
);
return KTX_ERROR_OK;
}
KtxError KtxTexture::createAs1ByteCopyScaledDown(
const KtxTexture *tex,
const int scaleDownTimes
)
{
int sizeVolume;
// create 1 byte per pixel texture from 1/3/4 bpp texture
memcpy(&m_header.m_id, &tex->m_header, sizeof(KtxHeader));
// Make texture dimension as power of two.
m_header.m_pixelWidth = tex->m_header.m_pixelWidth / scaleDownTimes;
m_header.m_pixelHeight = tex->m_header.m_pixelHeight / scaleDownTimes;
m_header.m_pixelDepth = tex->m_header.m_pixelDepth / scaleDownTimes;
// copy user key data
memcpy(&m_keyData, &tex->m_keyData, sizeof(KtxKeyData));
// Created 1 byte per pixel texture
m_header.m_glFormat = KTX_GL_RED;
m_header.m_glInternalFormat = KTX_GL_R8_EXT; // GL_R8_EXT, GL_R8 (0x8229)
m_header.m_glBaseInternalFormat = KTX_GL_RED;
sizeVolume = m_header.m_pixelWidth;
if (m_header.m_pixelHeight > 0)
sizeVolume *= m_header.m_pixelHeight;
if (m_header.m_pixelDepth > 0)
sizeVolume *= m_header.m_pixelDepth;
if (m_data != NULL)
delete[] m_data;
m_data = M_NEW(MUint8[sizeVolume]);
if (!m_data)
return KTX_ERROR_NO_MEMORY;
m_isCompressed = 0;
m_dataSize = sizeVolume;
// Convert 1 -> 1
assert(tex->m_header.m_glFormat == KTX_GL_RED);
int xDimSrc = tex->m_header.m_pixelWidth;
int yDimSrc = tex->m_header.m_pixelHeight;
//int zDimSrc = tex->m_header.m_pixelDepth;
int xDimDst = m_header.m_pixelWidth;
int yDimDst = m_header.m_pixelHeight;
int zDimDst = m_header.m_pixelDepth;
const MUint8 *pixelsSrc = tex->getData();
MUint8 *pixelsDst = getData();
int x, y, z;
int indDst = 0;
for (z = 0; z < zDimDst; z++)
{
int zSrcMin = z * scaleDownTimes;
int zSrcMax = (z + 1) * scaleDownTimes;
for (y = 0; y < yDimDst; y++)
{
int ySrcMin = y * scaleDownTimes;
int ySrcMax = (y + 1) * scaleDownTimes;
for (x = 0; x < xDimDst; x++)
{
int xSrcMin = x * scaleDownTimes;
int xSrcMax = (x + 1) * scaleDownTimes;
MUint32 sum = 0;
int numPixels = 0;
int xx, yy, zz;
for (zz = zSrcMin; zz < zSrcMax; zz++)
{
for (yy = ySrcMin; yy < ySrcMax; yy++)
{
for (xx = xSrcMin; xx < xSrcMax; xx++)
{
int offSrc = xx + (yy * xDimSrc) + (zz * xDimSrc * yDimSrc);
sum += (MUint32)pixelsSrc[offSrc];
numPixels++;
}
}
}
sum = sum / numPixels;
pixelsDst[indDst] = (MUint8)sum;
indDst++;
}
}
}
return KTX_ERROR_OK;
}
static int V3dEqual(const V3d &va, const V3d &vb)
{
V3d v;
v.x = va.x - vb.x;
v.y = va.y - vb.y;
v.z = va.z - vb.z;
return ((v.x | v.y | v.z) == 0) ? 1: 0;
}
static void _addValueToArray(
V3d *arr,
const int maxArrElements,
const V3d &vecAdd,
int &numElements
)
{
int i;
for (i = 0; i < numElements; i++)
{
if (V3dEqual(arr[i], vecAdd))
return;
}
// add
assert(numElements < maxArrElements);
if (numElements < maxArrElements)
{
arr[numElements++] = vecAdd;
}
}
KtxError KtxTexture::createMask(
const KtxTexture *tex,
const int valBarrier,
const int numAddVoxels
)
{
KtxError err;
err = createAs1ByteCopy(tex);
if (err != KTX_ERROR_OK)
return err;
int xDim = getWidth();
int yDim = getHeight();
int zDim = getDepth();
int xyDim = xDim * yDim;
int xyzDim = xDim * yDim* zDim;
MUint8 *pixelsBina = M_NEW(MUint8[xyzDim]);
if (!pixelsBina)
return KTX_ERROR_NO_MEMORY;
static V3d offRing[128];
int numPixelsInRing;
int i, j;
int x, y, z;
int radius = numAddVoxels;
// build ring offsets
numPixelsInRing = 0;
for (j = 0; j < 16; j++)
{
float angleTeta = -3.1415926f / 2 + 3.1415926f * (float)j / 16.0f;
for (i = 0; i < 32; i++)
{
float anglePhi = 3.1415926f * 2.0f * (float)i / 32.0f;
z = (int)(radius * sinf(angleTeta));
float xy = radius * cosf(angleTeta);
x = (int)(xy * cosf(anglePhi));
y = (int)(xy * sinf(anglePhi));
V3d v;
v.x = x;
v.y = y;
v.z = z;
_addValueToArray(offRing, sizeof(offRing) / sizeof(offRing[0]),
v, numPixelsInRing);
}
} // for (j)
const MUint8 *pixelsSrc = tex->getData();
MUint8 *pixelsDst = getData();
int indDst;
indDst = 0;
for (z = 0; z < zDim; z++)
{
for (y = 0; y < yDim; y++)
{
for (x = 0; x < xDim; x++)
{
MUint32 valDst;
MUint32 val = (MUint32)pixelsSrc[indDst];
// binarize by barrier
valDst = (val <= (MUint32)valBarrier)? 0: 255;
pixelsBina[indDst] = (MUint8)valDst;
indDst++;
} // for (x)
} // for (y)
} // for (z)
// Dilatation
indDst = 0;
for (z = 0; z < zDim; z++)
{
for (y = 0; y < yDim; y++)
{
for (x = 0; x < xDim; x++)
{
if (pixelsBina[indDst])
{
pixelsDst[indDst] = pixelsBina[indDst];
indDst++;
continue;
}
// check neighbours
int hasNeibObject = 0;
for (i = 0; i < numPixelsInRing; i++)
{
int xDst = x + offRing[i].x;
int yDst = y + offRing[i].y;
int zDst = z + offRing[i].z;
if ( (xDst < 0) || (xDst >= xDim) )
continue;
if ( (yDst < 0) || (yDst >= yDim) )
continue;
if ( (zDst < 0) || (zDst >= zDim) )
continue;
int offNeigh = xDst + (yDst * xDim) + (zDst * xyDim);
if (pixelsBina[offNeigh])
{
hasNeibObject = 1;
break;
}
} // for (i) all neighbours in 3d sphere
pixelsDst[indDst] = (hasNeibObject)? 255: 0;
indDst++;
} // for (x)
} // for (y)
} // for (z)
delete[] pixelsBina;
return KTX_ERROR_OK;
}
// Perform smoothing for 1-byte 2d image
#define MAX_BOX_LEN 32
static void _boxFilter3d(
MUint8 *pixels,
const int xDim,
const int yDim,
const int zDim,
const int radius
)
{
static MUint32 history[MAX_BOX_LEN];
int boxLen = radius + radius + 1;
int x, y, z, dr, offLine, xyDim, zOff;
int multFast;
assert(boxLen <= MAX_BOX_LEN);
xyDim = xDim * yDim;
multFast = (int)(512.0f * 1.0f / (float)boxLen);
// horizontals processing
for (z = 0, zOff = 0; z < zDim; z++, zOff += xyDim)
{
for (y = 0, offLine = 0; y < yDim; y++, offLine += xDim)
{
MUint32 sum = 0;
for (dr = -radius; dr <= +radius; dr++)
{
x = (dr >= 0) ? dr : 0;
MUint32 val = (MUint32)pixels[zOff + offLine + x];
sum += val;
history[dr + radius] = val;
}
int indHistory = radius;
for (x = 0; x < xDim; x++)
{
// (x * 170 / 512) is almost the same as (x / 3)
pixels[zOff + offLine + x] = (MUint8)((sum * multFast) >> 9);
// update sum
int indMin = indHistory - radius;
indMin = (indMin >= 0) ? indMin : (indMin + boxLen);
sum -= history[indMin];
// update central history index
indHistory++;
if (indHistory >= boxLen)
indHistory = 0;
// add new element to history and sum
int indMax = indHistory + radius;
indMax = (indMax < boxLen) ? indMax : (indMax - boxLen);
int off = (x + radius + 1 < xDim) ? (x + radius + 1) : (xDim - 1);
history[indMax] = (MUint32)pixels[zOff + offLine + off];
sum += history[indMax];
} // for (x)
} // for (y)
} // for (z)
// vertical processing
for (z = 0, zOff = 0; z < zDim; z++, zOff += xyDim)
{
for (x = 0; x < xDim; x++)
{
MUint32 sum = 0;
for (dr = -radius; dr <= +radius; dr++)
{
y = (dr >= 0) ? dr : 0;
MUint32 val = (MUint32)pixels[x + y * xDim + zOff];
sum += val;
history[dr + radius] = val;
}
int indHistory = radius;
for (y = 0, offLine = 0; y < yDim; y++, offLine += xDim)
{
// (x * 170 / 512) is almost the same as (x / 3)
pixels[offLine + x + zOff] = (MUint8)((sum * multFast) >> 9);
// update sum
int indMin = indHistory - radius;
indMin = (indMin >= 0) ? indMin : (indMin + boxLen);
sum -= history[indMin];
// update central history index
indHistory++;
if (indHistory >= boxLen)
indHistory = 0;
// add new element to history and sum
int indMax = indHistory + radius;
indMax = (indMax < boxLen) ? indMax : (indMax - boxLen);
int yMax = (y + radius + 1 < yDim) ? (y + radius + 1) : (yDim - 1);
history[indMax] = (MUint32)pixels[x + yMax * xDim + zOff];
sum += history[indMax];
} // for (y)
} // for (x)
} // for (z)
// depth (z) processing
for (y = 0, offLine = 0; y < yDim; y++, offLine += xDim)
{
for (x = 0; x < xDim; x++)
{
MUint32 sum = 0;
for (dr = -radius; dr <= +radius; dr++)
{
z = (dr >= 0) ? dr : 0;
MUint32 val = (MUint32)pixels[x + offLine + z * xyDim];
sum += val;
history[dr + radius] = val;
}
int indHistory = radius;
for (z = 0, zOff = 0; z < zDim; z++, zOff += xyDim)
{
// (x * 170 / 512) is almost the same as (x / 3)
pixels[offLine + x + zOff] = (MUint8)((sum * multFast) >> 9);
// update sum
int indMin = indHistory - radius;
indMin = (indMin >= 0) ? indMin : (indMin + boxLen);
sum -= history[indMin];
// update central history index
indHistory++;
if (indHistory >= boxLen)
indHistory = 0;
// add new element to history and sum
int indMax = indHistory + radius;
indMax = (indMax < boxLen) ? indMax : (indMax - boxLen);
int zMax = (z + radius + 1 < zDim) ? (z + radius + 1) : (zDim - 1);
history[indMax] = (MUint32)pixels[x + offLine + zMax * xyDim];
sum += history[indMax];
} // for (z)
} // for (x)
} // for (y)
}
void KtxTexture::boxFilter3d(const int radius)
{
_boxFilter3d(m_data,
m_header.m_pixelWidth,
m_header.m_pixelHeight,
m_header.m_pixelDepth,
radius);
}
void KtxTexture::clearBorder()
{
int x, y, z;
int xDim = m_header.m_pixelWidth;
int yDim = m_header.m_pixelHeight;
int zDim = m_header.m_pixelDepth;
int xyzDim = xDim * yDim * zDim;
int numBlacks = 0;
int numWhites = 0;
for (x = 0; x < xyzDim; x++)
{
MUint32 val = (MUint32)m_data[x];
if (val <= 32)
numBlacks++;
if (val >= 256 - 32)
numWhites++;
}
MUint32 valBackground;
if (numBlacks > numWhites)
valBackground = 0;
else
valBackground = 255;
int indDst = 0;
for (z = 0; z < zDim; z++)
{
int isBorderZ = ((z == 0) || (z == zDim -1))? 1: 0;
for (y = 0; y < yDim; y++)
{
int isBorderY = ((y == 0) || (y == yDim - 1)) ? 1: 0;
for (x = 0; x < xDim; x++)
{
int isBorderX = ((x == 0) || (x == xDim - 1)) ? 1 : 0;
int isBorder = isBorderX | isBorderY | isBorderZ;
if (isBorder)
m_data[indDst] = (MUint8)valBackground;
indDst++;
} // for (x)
} // for (y)
} // for (z)
}
void KtxTexture::binarizeByBarrier(
const MUint8 valBarrier,
const MUint8 valLess,
const MUint8 valGreat
)
{
int xyzDim = m_header.m_pixelWidth *
m_header.m_pixelHeight *
m_header.m_pixelDepth;
int i;
for (i = 0; i < xyzDim; i++)
{
MUint8 val = m_data[i];
m_data[i] = (val <= valBarrier)? valLess: valGreat;
}
}
static int _getLargeEqualPowerOfTwo(const int val)
{
int i;
for (i = 1; i < 30; i++)
{
int pwr = 1 << i;
if (val <= pwr)
return pwr;
}
return -1;
}
static __inline float _cubicHermite(
const float aIn,
const float bIn,
const float cIn,
const float dIn,
const float t
)
{
float a = -aIn / 2.0f + (3.0f * bIn) / 2.0f - (3.0f * cIn) / 2.0f +
dIn / 2.0f;
float b = +aIn - (5.0f * bIn) / 2.0f + 2.0f * cIn - dIn / 2.0f;
float c = -aIn / 2.0f + cIn / 2.0f;
float d = bIn;
return a * t * t * t + b * t * t + c * t + d;
}
static __inline float _getIntensityClamped(
const MUint8 *volData,
const int xDimSrc,
const int yDimSrc,
const int zDimSrc,
const int x,
const int y,
const int z
)
{
int xx = (x < 0) ? 0 : ((x >= xDimSrc) ? (xDimSrc - 1) : x);
int yy = (y < 0) ? 0 : ((y >= yDimSrc) ? (yDimSrc - 1) : y);
int zz = (z < 0) ? 0 : ((z >= zDimSrc) ? (zDimSrc - 1) : z);
return (float)volData[xx + yy * xDimSrc + zz * xDimSrc * yDimSrc];
}
static void _getBicubicIntensity(
const MUint8 *volIntensity,
const int xDimSrc,
const int yDimSrc,
const int zDimSrc,
const float tx,
const float ty,
const float tz,
MUint8 *valIntensity
)
{
float x, y, z, xFract, yFract, zFract;
int xInt, yInt, zInt;
x = (tx * xDimSrc) - 0.5f;
y = (ty * yDimSrc) - 0.5f;
z = (tz * zDimSrc) - 0.5f;
xInt = (int)x;
yInt = (int)y;
zInt = (int)z;
xFract = x - floorf(x); // in [0..1]
yFract = y - floorf(y);
zFract = z - floorf(z);
float p000 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt - 1, yInt - 1, zInt - 1);
float p100 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 0, yInt - 1, zInt - 1);
float p200 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 1, yInt - 1, zInt - 1);
float p300 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 2, yInt - 1, zInt - 1);
float p010 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt - 1, yInt + 0, zInt - 1);
float p110 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 0, yInt + 0, zInt - 1);
float p210 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 1, yInt + 0, zInt - 1);
float p310 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 2, yInt + 0, zInt - 1);
float p020 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt - 1, yInt + 1, zInt - 1);
float p120 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 0, yInt + 1, zInt - 1);
float p220 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 1, yInt + 1, zInt - 1);
float p320 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 2, yInt + 1, zInt - 1);
float p030 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt - 1, yInt + 2, zInt - 1);
float p130 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 0, yInt + 2, zInt - 1);
float p230 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 1, yInt + 2, zInt - 1);
float p330 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 2, yInt + 2, zInt - 1);
float p001 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt - 1, yInt - 1, zInt + 0);
float p101 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 0, yInt - 1, zInt + 0);
float p201 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 1, yInt - 1, zInt + 0);
float p301 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 2, yInt - 1, zInt + 0);
float p011 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt - 1, yInt + 0, zInt + 0);
float p111 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 0, yInt + 0, zInt + 0);
float p211 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 1, yInt + 0, zInt + 0);
float p311 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 2, yInt + 0, zInt + 0);
float p021 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt - 1, yInt + 1, zInt + 0);
float p121 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 0, yInt + 1, zInt + 0);
float p221 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 1, yInt + 1, zInt + 0);
float p321 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 2, yInt + 1, zInt + 0);
float p031 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt - 1, yInt + 2, zInt + 0);
float p131 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 0, yInt + 2, zInt + 0);
float p231 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 1, yInt + 2, zInt + 0);
float p331 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 2, yInt + 2, zInt + 0);
float p002 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt - 1, yInt - 1, zInt + 1);
float p102 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 0, yInt - 1, zInt + 1);
float p202 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 1, yInt - 1, zInt + 1);
float p302 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 2, yInt - 1, zInt + 1);
float p012 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt - 1, yInt + 0, zInt + 1);
float p112 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 0, yInt + 0, zInt + 1);
float p212 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 1, yInt + 0, zInt + 1);
float p312 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 2, yInt + 0, zInt + 1);
float p022 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt - 1, yInt + 1, zInt + 1);
float p122 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 0, yInt + 1, zInt + 1);
float p222 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 1, yInt + 1, zInt + 1);
float p322 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 2, yInt + 1, zInt + 1);
float p032 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt - 1, yInt + 2, zInt + 1);
float p132 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 0, yInt + 2, zInt + 1);
float p232 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 1, yInt + 2, zInt + 1);
float p332 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 2, yInt + 2, zInt + 1);
float p003 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt - 1, yInt - 1, zInt + 2);
float p103 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 0, yInt - 1, zInt + 2);
float p203 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 1, yInt - 1, zInt + 2);
float p303 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 2, yInt - 1, zInt + 2);
float p013 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt - 1, yInt + 0, zInt + 2);
float p113 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 0, yInt + 0, zInt + 2);
float p213 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 1, yInt + 0, zInt + 2);
float p313 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 2, yInt + 0, zInt + 2);
float p023 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt - 1, yInt + 1, zInt + 2);
float p123 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 0, yInt + 1, zInt + 2);
float p223 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 1, yInt + 1, zInt + 2);
float p323 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 2, yInt + 1, zInt + 2);
float p033 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt - 1, yInt + 2, zInt + 2);
float p133 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 0, yInt + 2, zInt + 2);
float p233 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 1, yInt + 2, zInt + 2);
float p333 = _getIntensityClamped(volIntensity, xDimSrc, yDimSrc, zDimSrc, xInt + 2, yInt + 2, zInt + 2);
float col0, col1, col2, col3, row0, row1, row2, row3, res;
col0 = _cubicHermite(p000, p100, p200, p300, xFract);
col1 = _cubicHermite(p010, p110, p210, p310, xFract);
col2 = _cubicHermite(p020, p120, p220, p320, xFract);
col3 = _cubicHermite(p030, p130, p230, p330, xFract);
row0 = _cubicHermite(col0, col1, col2, col3, yFract);
col0 = _cubicHermite(p001, p101, p201, p301, xFract);
col1 = _cubicHermite(p011, p111, p211, p311, xFract);
col2 = _cubicHermite(p021, p121, p221, p321, xFract);
col3 = _cubicHermite(p031, p131, p231, p331, xFract);
row1 = _cubicHermite(col0, col1, col2, col3, yFract);
col0 = _cubicHermite(p002, p102, p202, p302, xFract);
col1 = _cubicHermite(p012, p112, p212, p312, xFract);
col2 = _cubicHermite(p022, p122, p222, p322, xFract);
col3 = _cubicHermite(p032, p132, p232, p332, xFract);
row2 = _cubicHermite(col0, col1, col2, col3, yFract);
col0 = _cubicHermite(p003, p103, p203, p303, xFract);
col1 = _cubicHermite(p013, p113, p213, p313, xFract);
col2 = _cubicHermite(p023, p123, p223, p323, xFract);
col3 = _cubicHermite(p033, p133, p233, p333, xFract);
row3 = _cubicHermite(col0, col1, col2, col3, yFract);
res = _cubicHermite(row0, row1, row2, row3, zFract);
res = (res < 0.0f) ? 0.0f : ((res > 255.0f) ? 255.0f : res);
*valIntensity = (MUint8)res;
}
static void _scaleDownTextureSmooth(
const MUint8 *pixelsSrc,
const int xDimSrc, const int yDimSrc, const int zDimSrc,
MUint8 *pixelsDst,
const int xDimDst, const int yDimDst, const int zDimDst
)
{
int x, y, z;
float xStep = 1.0f / xDimDst;
float yStep = 1.0f / yDimDst;
float zStep = 1.0f / zDimDst;
int indDst = 0;
for (z = 0; z < zDimDst; z++)
{
float tz = z * zStep;
for (y = 0; y < yDimDst; y++)
{
float ty = y * yStep;
for (x = 0; x < xDimDst; x++)
{
float tx = x * xStep;
MUint8 val;
_getBicubicIntensity(pixelsSrc, xDimSrc, yDimSrc, zDimSrc, tx, ty, tz, &val);
pixelsDst[indDst++] = val;
}
}
}
}
void _scaleUpTextureSmooth(
const MUint8 *volTextureSrc,
const int xDimSrc,
const int yDimSrc,
const int zDimSrc,
MUint8 *volTextureDst,
const int xDimDst,
const int yDimDst,
const int zDimDst
)
{
int offDst, x, y, z;
assert( (xDimSrc < xDimDst) || (yDimSrc < yDimDst) || (zDimSrc < zDimDst));
offDst = 0;
for (z = 0; z < zDimDst; z++)
{
float tz = (float)z / zDimDst;
for (y = 0; y < yDimDst; y++)
{
float ty = (float)y / yDimDst;
for (x = 0; x < xDimDst; x++)
{
float tx = (float)x / xDimDst;
MUint8 val;
_getBicubicIntensity(volTextureSrc, xDimSrc, yDimSrc, zDimSrc, tx, ty, tz, &val);
volTextureDst[offDst] = val;
// next voxel dst
offDst++;
} // for (x)
} // for (y)
} // for (z)
}
static void _scaleDownTextureRough(
const MUint8 *pixelsSrc,
const int xDimSrc, const int yDimSrc, const int zDimSrc,
MUint8 *pixelsDst,
const int xDimDst, const int yDimDst, const int zDimDst
)
{
int x, y, z;
assert(xDimDst <= xDimSrc);
assert(yDimDst <= yDimSrc);
assert(zDimDst <= zDimSrc);
float xScale = (float)xDimSrc / xDimDst;
float yScale = (float)yDimSrc / yDimDst;
float zScale = (float)zDimSrc / zDimDst;
int indDst = 0;
for (z = 0; z < zDimDst; z++)
{
int zSrcMin = (int)((z + 0) * zScale);
int zSrcMax = (int)((z + 1) * zScale);
for (y = 0; y < yDimDst; y++)
{
int ySrcMin = (int)((y + 0) * yScale);
int ySrcMax = (int)((y + 1) * yScale);
for (x = 0; x < xDimDst; x++)
{
int xSrcMin = (int)((x + 0) * xScale);
int xSrcMax = (int)((x + 1) * xScale);
int xx, yy, zz;
MUint32 sum = 0;
int numPixels = 0;
for (zz = zSrcMin; zz < zSrcMax; zz++)
{
int zSrcOff = zz * xDimSrc * yDimSrc;
for (yy = ySrcMin; yy < ySrcMax; yy++)
{
int ySrcOff = yy * xDimSrc;
for (xx = xSrcMin; xx < xSrcMax; xx++)
{
int offSrc = xx + ySrcOff + zSrcOff;
MUint32 valSrc = (MUint32)pixelsSrc[offSrc];
if (valSrc == 0)
continue;
sum += valSrc;
numPixels++;
}
}
}
MUint8 val = 0;
if (numPixels > 0)
val = (MUint8)(sum / (MUint32)numPixels);
pixelsDst[indDst++] = val;
}
}
}
}
static void _scaleUpTextureRough(
const MUint8 *pixelsSrc,
const int xDimSrc, const int yDimSrc, const int zDimSrc,
MUint8 *pixelsDst,
const int xDimDst, const int yDimDst, const int zDimDst
)
{
int x, y, z;
assert(xDimDst >= xDimSrc);
assert(yDimDst >= yDimSrc);
assert(zDimDst >= zDimSrc);
float xScale = (float)xDimSrc / xDimDst;
float yScale = (float)yDimSrc / yDimDst;
float zScale = (float)zDimSrc / zDimDst;
int indDst = 0;
for (z = 0; z < zDimDst; z++)
{
int zSrc = (int)((z + 0) * zScale);
int zOffSrc = zSrc * xDimSrc * yDimSrc;
for (y = 0; y < yDimDst; y++)
{
int ySrc = (int)((y + 0) * yScale);
int yOffSrc = ySrc * xDimSrc;
for (x = 0; x < xDimDst; x++)
{
int xSrc = (int)((x + 0) * xScale);
int offSrc = xSrc + yOffSrc + zOffSrc;
MUint8 val = pixelsSrc[offSrc];
pixelsDst[indDst++] = val;
}
}
}
}
KtxError KtxTexture::createAs1BytePowerByMaxSide(
const KtxTexture *tex,
const int maxDstDim,
const int isDstCubeTexture,
const int useSmoothInterpolation
)
{
int xDimSrc = tex->getWidth();
int yDimSrc = tex->getHeight();
int zDimSrc = tex->getDepth();
int maxSrcDim = xDimSrc;
if (yDimSrc > maxSrcDim)
maxSrcDim = yDimSrc;
if (zDimSrc > maxSrcDim)
maxSrcDim = zDimSrc;
float xKoef = (float)xDimSrc / maxSrcDim;
float yKoef = (float)yDimSrc / maxSrcDim;
float zKoef = (float)zDimSrc / maxSrcDim;
int xDimDst = (int)(maxDstDim * xKoef);
int yDimDst = (int)(maxDstDim * yKoef);
int zDimDst = (int)(maxDstDim * zKoef);
if (isDstCubeTexture)
yDimDst = zDimDst = xDimDst;
MUint8 *pixelsSmall = M_NEW(MUint8[xDimDst * yDimDst * zDimDst]);
if (pixelsSmall == NULL)
return KTX_ERROR_NO_MEMORY;
const MUint8 *pixelsSrc = tex->getData();
if (
(xDimSrc >= xDimDst) &&
(yDimSrc >= yDimDst) &&
(zDimSrc >= zDimDst)
)
{
if (useSmoothInterpolation)
_scaleDownTextureSmooth(
pixelsSrc,
xDimSrc, yDimSrc, zDimSrc,
pixelsSmall,
xDimDst, yDimDst, zDimDst
);
else
_scaleDownTextureRough(
pixelsSrc,
xDimSrc, yDimSrc, zDimSrc,
pixelsSmall,
xDimDst, yDimDst, zDimDst
);
}
else
{
if (useSmoothInterpolation)
_scaleUpTextureSmooth(
pixelsSrc,
xDimSrc, yDimSrc, zDimSrc,
pixelsSmall,
xDimDst, yDimDst, zDimDst
);
else
_scaleUpTextureRough(
pixelsSrc,
xDimSrc, yDimSrc, zDimSrc,
pixelsSmall,
xDimDst, yDimDst, zDimDst
);
}
int xDimFinal = _getLargeEqualPowerOfTwo(xDimDst);
int yDimFinal = _getLargeEqualPowerOfTwo(yDimDst);
int zDimFinal = _getLargeEqualPowerOfTwo(zDimDst);
MUint8 *pixelsFinal = M_NEW(MUint8[xDimFinal * yDimFinal* zDimFinal]);
if (pixelsFinal == NULL)
return KTX_ERROR_NO_MEMORY;
_copyAndAlignTexture(
pixelsSmall,
xDimDst, yDimDst, zDimDst,
pixelsFinal,
xDimFinal, yDimFinal, zDimFinal
);
delete[] pixelsSmall;
// create 1 byte per pixel texture from 1/3/4 bpp texture
memcpy(&m_header.m_id, &tex->m_header, sizeof(KtxHeader));
// Make texture dimension as power of two.
m_header.m_pixelWidth = xDimFinal;
m_header.m_pixelHeight = yDimFinal;
m_header.m_pixelDepth = zDimFinal;
// copy user key data
memcpy(&m_keyData, &tex->m_keyData, sizeof(KtxKeyData));
// Created 1 byte per pixel texture
m_header.m_glFormat = KTX_GL_RED;
m_header.m_glInternalFormat = KTX_GL_R8_EXT; // GL_R8_EXT, GL_R8 (0x8229)
m_header.m_glBaseInternalFormat = KTX_GL_RED;
int sizeVolume = m_header.m_pixelWidth;
if (m_header.m_pixelHeight > 0)
sizeVolume *= m_header.m_pixelHeight;
if (m_header.m_pixelDepth > 0)
sizeVolume *= m_header.m_pixelDepth;
m_data = pixelsFinal;
m_isCompressed = 0;
m_dataSize = sizeVolume;
return KTX_ERROR_OK;
}
KtxError KtxTexture::createAs1ByteLessSize(
const KtxTexture *tex,
const int xDimDst,
const int yDimDst,
const int zDimDst
)
{
int sizeVolume;
// create 1 byte per pixel texture from 1/3/4 bpp texture
memcpy(&m_header.m_id, &tex->m_header, sizeof(KtxHeader));
// Make texture dimension as power of two.
m_header.m_pixelWidth = xDimDst;
m_header.m_pixelHeight = yDimDst;
m_header.m_pixelDepth = zDimDst;
// copy user key data
memcpy(&m_keyData, &tex->m_keyData, sizeof(KtxKeyData));
// Created 1 byte per pixel texture
m_header.m_glFormat = KTX_GL_RED;
m_header.m_glInternalFormat = KTX_GL_R8_EXT; // GL_R8_EXT, GL_R8 (0x8229)
m_header.m_glBaseInternalFormat = KTX_GL_RED;
sizeVolume = m_header.m_pixelWidth;
if (m_header.m_pixelHeight > 0)
sizeVolume *= m_header.m_pixelHeight;
if (m_header.m_pixelDepth > 0)
sizeVolume *= m_header.m_pixelDepth;
if (m_data != NULL)
delete[] m_data;
m_data = M_NEW(MUint8[sizeVolume]);
if (!m_data)
return KTX_ERROR_NO_MEMORY;
m_isCompressed = 0;
m_dataSize = sizeVolume;
// Convert 1 -> 1
assert(tex->m_header.m_glFormat == KTX_GL_RED);
//memcpy(m_data, tex->m_data, sizeVolume);
int xDimSrc = tex->m_header.m_pixelWidth;
int yDimSrc = tex->m_header.m_pixelHeight;
int zDimSrc = tex->m_header.m_pixelDepth;
const MUint8 *pixelsSrc = tex->getData();
MUint8 *pixelsDst = getData();
_scaleDownTextureSmooth(
pixelsSrc,
xDimSrc, yDimSrc, zDimSrc,
pixelsDst,
xDimDst, yDimDst, zDimDst
);
return KTX_ERROR_OK;
}
KtxError KtxTexture::createAsSingleSphere(const int dim)
{
int sizeVolume;
int xDim = dim;
int yDim = dim;
int zDim = dim;
// Make texture dimension as power of two.
memcpy(m_header.m_id, s_ktxIdFile, sizeof(s_ktxIdFile));
m_header.m_endianness = 0x04030201;
m_header.m_glType = KTX_GL_UNSIGNED_BYTE;
m_header.m_glTypeSize = 1;
m_header.m_pixelWidth = xDim;
m_header.m_pixelHeight = yDim;
m_header.m_pixelDepth = zDim;
m_header.m_numberOfArrayElements = 0; // for non-array textures is 0.
m_header.m_numberOfFaces = 1;
m_header.m_numberOfMipmapLevels = 1;
//m_header.m_bytesOfKeyValueData = sizeof(s_keyValues);
m_header.m_bytesOfKeyValueData = 0;
m_header.m_glFormat = KTX_GL_RED;
m_header.m_glInternalFormat = KTX_GL_RED; // GL_R8_EXT, GL_R8 (0x8229)
m_header.m_glBaseInternalFormat = KTX_GL_RED;
// copy user key data
char *keyDataPtr = (char*)&m_keyData; // for happy cppcheck
int memSize = sizeof(KtxKeyData); // for happy cppcheck
memset(keyDataPtr, 0, memSize);
sizeVolume = m_header.m_pixelWidth;
if (m_header.m_pixelHeight > 0)
sizeVolume *= m_header.m_pixelHeight;
if (m_header.m_pixelDepth > 0)
sizeVolume *= m_header.m_pixelDepth;
if (m_data != NULL)
delete[] m_data;
m_data = M_NEW(MUint8[sizeVolume]);
if (!m_data)
return KTX_ERROR_NO_MEMORY;
m_isCompressed = 0;
m_dataSize = sizeVolume;
int xCenter = xDim >> 1;
int yCenter = yDim >> 1;
int zCenter = zDim >> 1;
const float KOEF_ROUGH = 0.05f;
int x, y, z;
int indDst = 0;
float radius = (float)(dim / 2);
for (z = 0; z < zDim; z++)
{
int dz = z - zCenter;
for (y = 0; y < yDim; y++)
{
int dy = y - yCenter;
for (x = 0; x < xDim; x++)
{
int dx = x - xCenter;
float r = sqrtf( (float)dx * dx + dy * dy + dz * dz) + 0.001f;
//float fVal = KOEF_ROUGH * 256.0f * (radius / r);
float fVal = (radius - r) * 256.0f * KOEF_ROUGH;
int val = (int)fVal;
if (val > 255)
val = 255;
if (val < 0)
val = 0;
m_data[indDst++] = (MUint8)(val);
} // for (x)
} // for (y)
} // for (z)
return KTX_ERROR_OK;
}
KtxError KtxTexture::createMinSizeTexture(const KtxTexture *tex, const int indexChannel)
{
//
// Store original texture size
// and top left corner offset
// in the user data area
//
int xDimSrc = tex->getWidth();
int yDimSrc = tex->getHeight();
int zDimSrc = tex->getDepth();
MUint32 format = tex->getGlFormat();
int bpp = (format == KTX_GL_RED)? 1: ((format == KTX_GL_RGB)? 3: 4);
if (bpp != 4)
{
return KTX_ERROR_WRONG_FORMAT;
}
// bbox
V3d vBoxMin, vBoxMax;
vBoxMin.x = vBoxMin.y = vBoxMin.z = 1<<24;
vBoxMax.x = vBoxMax.y = vBoxMax.z = 0;
int bitShift = indexChannel * 8;
int x, y, z;
const MUint32 *pixelsSrc = (MUint32*)tex->getData();
for (z = 0; z < zDimSrc; z++)
{
for (y = 0; y < yDimSrc; y++)
{
for (x = 0; x < xDimSrc; x++)
{
MUint32 val = *pixelsSrc;
// check G component
if ((val >> bitShift) & 0xff)
{
if (x < vBoxMin.x)
vBoxMin.x = x;
if (y < vBoxMin.y)
vBoxMin.y = y;
if (z < vBoxMin.z)
vBoxMin.z = z;
if (x > vBoxMax.x)
vBoxMax.x = x;
if (y > vBoxMax.y)
vBoxMax.y = y;
if (z > vBoxMax.z)
vBoxMax.z = z;
}
pixelsSrc++;
} // for (x)
} // for (y)
} // for (z)
int xDimDst = vBoxMax.x - vBoxMin.x + 1;
int yDimDst = vBoxMax.y - vBoxMin.y + 1;
int zDimDst = vBoxMax.z - vBoxMin.z + 1;
memcpy(&m_header.m_id, &tex->m_header, sizeof(KtxHeader));
m_header.m_pixelWidth = xDimDst;
m_header.m_pixelHeight = yDimDst;
m_header.m_pixelDepth = zDimDst;
int sizeVolume = xDimDst * yDimDst * zDimDst;
sizeVolume *= bpp;
if (m_data != NULL)
delete[] m_data;
m_data = M_NEW(MUint8[sizeVolume]);
if (!m_data)
return KTX_ERROR_NO_MEMORY;
m_isCompressed = 0;
m_dataSize = sizeVolume;
// Copy pixels
MUint32 *pixelsDst = (MUint32*)m_data;
pixelsSrc = (MUint32*)tex->getData();
for (z = 0; z < zDimDst; z++)
{
int zSrc = z + vBoxMin.z;
int zSrcOff = zSrc * xDimSrc * yDimSrc;
for (y = 0; y < yDimDst; y++)
{
int ySrc = y + vBoxMin.y;
int ySrcOff = ySrc * xDimSrc;
for (x = 0; x < xDimDst; x++)
{
int xSrc = x + vBoxMin.x;
int off = xSrc + ySrcOff + zSrcOff;
*pixelsDst = pixelsSrc[off];
pixelsDst++;
} // for (x)
} // for (y)
} // for (z)
// Setup user data
V3d vSize;
vSize.x = xDimSrc;
vSize.y = yDimSrc;
vSize.z = zDimSrc;
setKeyDataMinSize(vBoxMin, vSize);
return KTX_ERROR_OK;
}
void KtxTexture::setKeyDataBbox(const V3f &vMin, const V3f &vMax)
{
m_keyData.m_dataType = KTX_KEY_DATA_BBOX;
V3f *dst = reinterpret_cast<V3f*>(m_keyData.m_buffer);
dst[0] = vMin;
dst[1] = vMax;
}
void KtxTexture::setKeyDataMinSize(const V3d &vMin, const V3d &vSize)
{
m_keyData.m_dataType = KTX_KEY_DATA_MIN_SIZE;
V3d *dst = reinterpret_cast<V3d*>(m_keyData.m_buffer);
dst[0] = vMin;
dst[1] = vSize;
}
void KtxTexture::fillValZGreater(const int zTop, const MUint8 valToFill)
{
const int xDim = getWidth();
const int yDim = getHeight();
const int xyDim = xDim * yDim;
const int zDim = getDepth();
int z;
for (z = zTop; z < zDim; z++)
{
int zOff = z * xDim * yDim;
for (int i = 0; i < xyDim; i++)
{
m_data[zOff + i] = valToFill;
}
}
}
void KtxTexture::fillZeroYGreater(const int yClipMax)
{
// only 1 byte texture are suppoirted for this operation now
assert(getGlFormat() == KTX_GL_RED);
int xDim = getWidth();
int yDim = getHeight();
int zDim = getDepth();
assert(yClipMax < yDim);
for (int z = 0; z < zDim; z++)
{
int zOff = z * xDim * yDim;
for (int y = 0; y < yDim; y++)
{
int yOff = y * xDim;
for (int x = 0; x < xDim; x++)
{
int off = x + yOff + zOff;
if (y >= yClipMax)
m_data[off] = 0;
} // for (x)
} // for (y)
} // for (z)
}
void KtxTexture::gaussSmooth(const int gaussNeigh, const float gaussSigma)
{
int xDim = getWidth();
int yDim = getHeight();
int zDim = getDepth();
int xyzDim = xDim * yDim * zDim;
MUint8 *pixelsDst = M_NEW(MUint8[xyzDim]);
memset(pixelsDst, 0, xyzDim);
const float gaussKoef = 1.0f / (2.0f * gaussSigma * gaussSigma);
const int MAX_NEIGHS = 2 * 6 + 1;
static float koefs[MAX_NEIGHS * MAX_NEIGHS * MAX_NEIGHS];
int dx, dy, dz;
int offKoef = 0;
float wSum = 0.0f;
for (dz = -gaussNeigh; dz <= +gaussNeigh; dz++)
{
float kz = (float)dz / (float)gaussNeigh;
for (dy = -gaussNeigh; dy <= +gaussNeigh; dy++)
{
float ky = (float)dy / (float)gaussNeigh;
for (dx = -gaussNeigh; dx <= +gaussNeigh; dx++)
{
float kx = (float)dx / (float)gaussNeigh;
float w = expf(-(kx * kx + ky * ky + kz * kz) * gaussKoef);
koefs[offKoef ++] = w;
wSum += w;
} // for (dx)
} // for (dy)
} // for (dz)
// normalize koefs
int numElemsKoefs = 2 * gaussNeigh + 1;
numElemsKoefs = numElemsKoefs * numElemsKoefs * numElemsKoefs;
assert(numElemsKoefs == offKoef);
float scale = 1.0f / wSum;
for (int i = 0; i < numElemsKoefs; i++)
{
koefs[i] = koefs[i] * scale;
} // for (i)
int cx, cy, cz;
for (cz = gaussNeigh; cz < zDim - gaussNeigh; cz++)
{
int zOff = cz * xDim * yDim;
for (cy = gaussNeigh; cy < yDim - gaussNeigh; cy++)
{
int yOff = cy * xDim;
for (cx = gaussNeigh; cx < xDim - gaussNeigh; cx++)
{
int off = zOff + yOff + cx;
float valSum = 0.0f;
offKoef = 0;
for (dz = -gaussNeigh; dz <= +gaussNeigh; dz++)
{
int dzOff = dz * xDim * yDim;
for (dy = -gaussNeigh; dy <= +gaussNeigh; dy++)
{
int dyOff = dy * xDim;
for (dx = -gaussNeigh; dx <= +gaussNeigh; dx++)
{
float w = koefs[offKoef ++];
valSum += w * (float)m_data[off + dx + dyOff + dzOff];
} // for (dx)
} // for (dy)
} // for (dz)
valSum = (valSum <= 255.0f) ? valSum: 255.0f;
MUint8 vSum = (MUint8)valSum;
pixelsDst[off] = vSum;
} // for (cx)
} // for (cy)
} // for (cz)
memcpy(m_data, pixelsDst, xyzDim);
delete [] pixelsDst;
}
static int _scaleTextureDown(
const MUint8 *volTextureSrc,
const int xDimSrc,
const int yDimSrc,
const int zDimSrc,
const int xDimDst,
const int yDimDst,
const int zDimDst,
MUint8 *volTextureDst
)
{
const int ACC_BITS = 10;
const int ACC_HALF = 1 << (ACC_BITS - 1);
int xStep, yStep, zStep;
int indDst;
int xDst, yDst, zDst;
int zSrcAccL, zSrcAccH;
int x, y, z, zOff, yOff;
int xyDimSrc;
assert(xDimSrc > xDimDst);
assert(yDimSrc > yDimDst);
assert(zDimSrc > zDimDst);
xyDimSrc = xDimSrc * yDimSrc;
xStep = (xDimSrc << ACC_BITS) / xDimDst;
yStep = (yDimSrc << ACC_BITS) / yDimDst;
zStep = (zDimSrc << ACC_BITS) / zDimDst;
indDst = 0;
zSrcAccL = ACC_HALF;
zSrcAccH = zSrcAccL + zStep;
for (zDst = 0; zDst < zDimDst; zDst++, zSrcAccL += zStep, zSrcAccH += zStep)
{
int zSrcL = zSrcAccL >> ACC_BITS;
int zSrcH = zSrcAccH >> ACC_BITS;
int ySrcAccL = ACC_HALF;
int ySrcAccH = ySrcAccL + yStep;
for (yDst = 0; yDst < yDimDst; yDst++, ySrcAccL += yStep, ySrcAccH += yStep)
{
int ySrcL = ySrcAccL >> ACC_BITS;
int ySrcH = ySrcAccH >> ACC_BITS;
int xSrcAccL = ACC_HALF;
int xSrcAccH = xSrcAccL + xStep;
for (xDst = 0; xDst < xDimDst; xDst++, xSrcAccL += xStep, xSrcAccH += xStep)
{
int xSrcL = xSrcAccL >> ACC_BITS;
int xSrcH = xSrcAccH >> ACC_BITS;
// Accumulate sum
MUint32 sum = 0;
int numPixels = 0;
for (z = zSrcL, zOff = zSrcL * xyDimSrc; z < zSrcH; z++, zOff += xyDimSrc)
{
for (y = ySrcL, yOff = ySrcL * xDimSrc; y < ySrcH; y++, yOff += xDimSrc)
{
for (x = xSrcL; x < xSrcH; x++)
{
int offSrc = x + yOff + zOff;
sum += (MUint32)volTextureSrc[offSrc];
numPixels++;
} // for (x)
} // for (y)
} // for (z)
sum = sum / numPixels;
volTextureDst[indDst++] = (MUint8)sum;
} // for (xDst)
} // for (yDst)
} // for (zDst)
return 1;
}
int KtxTexture::scaleDownToSize(const int xDimDst, const int yDimDst, const int zDimDst)
{
int xDimSrc = getWidth();
int yDimSrc = getHeight();
int zDimSrc = getDepth();
int numPixelsDst = xDimDst * yDimDst * zDimDst;
MUint8 *pixelsDst = M_NEW(MUint8[numPixelsDst]);
if (!pixelsDst)
return -1;
_scaleTextureDown(m_data, xDimSrc, yDimSrc, zDimSrc, xDimDst, yDimDst, zDimDst, pixelsDst);
delete [] m_data;
m_data = pixelsDst;
m_header.m_pixelWidth = xDimDst;
m_header.m_pixelHeight = yDimDst;
m_header.m_pixelDepth = zDimDst;
return 1;
}
int KtxTexture::convertTo4bpp()
{
int numPixels = getWidth() * getHeight() * getDepth();
MUint8 *dataNew = M_NEW(MUint8[numPixels * 4]);
if (!dataNew)
return -1;
MUint32 *pixelsDst = (MUint32*)dataNew;
for (int i = 0; i < numPixels; i++)
{
MUint32 val = (MUint32)m_data[i];
val = val | (val << 8) | (val << 16) | (val << 24);
pixelsDst[i] = val;
} // for (i)
delete [] m_data;
m_data = dataNew;
m_header.m_glFormat = KTX_GL_RGBA;
m_header.m_glInternalFormat = KTX_GL_RGBA;
m_header.m_glBaseInternalFormat = KTX_GL_RGBA;
return 1;
}
// ******************************************************************
// Get symmetry
// ******************************************************************
int KtxTexture::getBoundingBox(V3d &vMin, V3d &vMax) const
{
assert(m_header.m_glFormat == KTX_GL_RED);
int x, y, z;
const int xDim = getWidth();
const int yDim = getHeight();
const int zDim = getDepth();
const int xDim2 = xDim / 2;
const int yDim2 = yDim / 2;
const int zDim2 = zDim / 2;
const int VAL_BACK_BARRIER = 80;
int isEdge;
isEdge = 1;
for (vMin.x = 1; (vMin.x < xDim2) && isEdge; vMin.x++)
{
for (y = 0; (y < yDim) && isEdge; y++)
{
for (z = 0; (z < zDim) && isEdge; z++)
{
int off = vMin.x + y * xDim + z * xDim * yDim;
MUint8 val = m_data[off];
if (val >= VAL_BACK_BARRIER)
isEdge = 0;
}
}
}
isEdge = 1;
for (vMax.x = xDim - 2; (vMax.x > xDim2) && isEdge; vMax.x--)
{
for (y = 0; (y < yDim) && isEdge; y++)
{
for (z = 0; (z < zDim) && isEdge; z++)
{
int off = vMax.x + y * xDim + z * xDim * yDim;
MUint8 val = m_data[off];
if (val >= VAL_BACK_BARRIER)
isEdge = 0;
}
}
}
// on Y
isEdge = 1;
for (vMin.y = 1; (vMin.y < yDim2) && isEdge; vMin.y++)
{
for (x = 0; (x < xDim) && isEdge; x++)
{
for (z = 0; (z < zDim) && isEdge; z++)
{
int off = x + (vMin.y * xDim) + (z * xDim * yDim);
MUint8 val = m_data[off];
if (val >= VAL_BACK_BARRIER)
isEdge = 0;
}
}
}
isEdge = 1;
for (vMax.y = yDim - 2; (vMax.y > yDim2) && isEdge; vMax.y--)
{
for (x = 0; (x < xDim) && isEdge; x++)
{
for (z = 0; (z < zDim) && isEdge; z++)
{
int off = x + (vMax.y * xDim) + (z * xDim * yDim);
MUint8 val = m_data[off];
if (val >= VAL_BACK_BARRIER)
isEdge = 0;
}
}
}
// on Z
isEdge = 1;
for (vMin.z = 1; (vMin.z < zDim2) && isEdge; vMin.z++)
{
for (x = 0; (x < xDim) && isEdge; x++)
{
for (y = 0; (y < yDim) && isEdge; y++)
{
int off = x + (y * xDim) + (vMin.z * xDim * yDim);
MUint8 val = m_data[off];
if (val >= VAL_BACK_BARRIER)
isEdge = 0;
}
}
}
for (vMax.z = zDim - 2; (vMax.z > zDim2) && isEdge; vMax.z--)
{
for (x = 0; (x < xDim) && isEdge; x++)
{
for (y = 0; (y < yDim) && isEdge; y++)
{
int off = x + (y * xDim) + (vMax.z * xDim * yDim);
MUint8 val = m_data[off];
if (val >= VAL_BACK_BARRIER)
isEdge = 0;
}
}
}
return 1;
}
int KtxTexture::getHorSliceSymmetry(const int z, float &xSym, float &ySym)
{
const int xDim = getWidth();
const int yDim = getHeight();
int offSlice = z * xDim * yDim;
V3d vMin, vMax;
getBoundingBox(vMin, vMax);
V2d vCenter, vRange;
vCenter.x = (vMin.x + vMax.x) / 2;
vCenter.y = (vMin.y + vMax.y) / 2;
vRange.x = (vMax.x - vMin.x) / 2 - 2;
vRange.y = (vMax.y - vMin.y) / 2 - 2;
float dif;
int numPixels;
int i, x, y;
dif = 0.0f;
numPixels = 0;
for (y = vMin.y; y < vMax.y; y++)
{
for (i = 4; i < vRange.x; i++)
{
int xL, xR;
MUint32 valL, valR;
float fValL, fValR, d, dBest;
dBest = +1.0e7f;
// off 0
xL = vCenter.x - i;
xR = vCenter.x + i;
valL = (MUint32)m_data[offSlice + y * xDim + xL];
valR = (MUint32)m_data[offSlice + y * xDim + xR];
fValL = (float)valL;
fValR = (float)valR;
d = fValR - fValL;
d = (d >= 0.0f) ? d: -d;
dBest = (d < dBest) ? d: dBest;
// off +1
xL = vCenter.x + 1 - i;
xR = vCenter.x + 1 + i;
valL = (MUint32)m_data[offSlice + y * xDim + xL];
valR = (MUint32)m_data[offSlice + y * xDim + xR];
fValL = (float)valL;
fValR = (float)valR;
d = fValR - fValL;
d = (d >= 0.0f) ? d : -d;
dBest = (d < dBest) ? d : dBest;
// off -1
xL = vCenter.x - 1 - i;
xR = vCenter.x - 1 + i;
valL = (MUint32)m_data[offSlice + y * xDim + xL];
valR = (MUint32)m_data[offSlice + y * xDim + xR];
fValL = (float)valL;
fValR = (float)valR;
d = fValR - fValL;
d = (d >= 0.0f) ? d : -d;
dBest = (d < dBest) ? d : dBest;
if (dBest > 20.0f)
dBest += 0.0000001f;
dif += dBest;
numPixels++;
} // for (x)
} // for (y)
dif /= (float)numPixels;
xSym = dif;
dif = 0.0f;
numPixels = 0;
for (x = vMin.x; x < vMax.x; x++)
{
for (y = vMin.y; y < vCenter.y; y++)
for (i = 4; i < vRange.x; i++)
{
int yL, yR;
MUint32 valL, valR;
float fValL, fValR, d, dBest;
dBest = +1.0e4f;
// off 0
yL = vCenter.y - i;
yR = vCenter.y + i;
valL = (MUint32)m_data[offSlice + yL * xDim + x];
valR = (MUint32)m_data[offSlice + yR * xDim + x];
fValL = (float)valL;
fValR = (float)valR;
d = fValR - fValL;
d = (d >= 0.0f) ? d : -d;
dBest = (d < dBest) ? d : dBest;
// off +1
yL = vCenter.y + 1 - i;
yR = vCenter.y + 1 + i;
valL = (MUint32)m_data[offSlice + yL * xDim + x];
valR = (MUint32)m_data[offSlice + yR * xDim + x];
fValL = (float)valL;
fValR = (float)valR;
d = fValR - fValL;
d = (d >= 0.0f) ? d : -d;
dBest = (d < dBest) ? d : dBest;
// off -1
yL = vCenter.y - 1 - i;
yR = vCenter.y - 1 + i;
valL = (MUint32)m_data[offSlice + yL * xDim + x];
valR = (MUint32)m_data[offSlice + yR * xDim + x];
fValL = (float)valL;
fValR = (float)valR;
d = fValR - fValL;
d = (d >= 0.0f) ? d : -d;
dBest = (d < dBest) ? d : dBest;
dif += dBest;
numPixels++;
} // for (x)
} // for (y)
dif /= (float)numPixels;
ySym = dif;
return 1;
}
int KtxTexture::scaleUpZ(const int zNew)
{
const int xDim = getWidth();
const int yDim = getHeight();
const int xyDim = xDim * yDim;
const int zDim = getDepth();
assert(zNew > (int)zDim);
const int divRest = zNew % zDim;
assert(divRest == 0);
MUint8 *pixelsNew = M_NEW(MUint8[xDim * yDim * zNew]);
if (!pixelsNew)
return -1;
int iDst = 0;
int zDst;
for (zDst = 0; zDst < zNew; zDst++)
{
int zSrc = zDim * zDst / zNew;
int zRatio = (zDim * zDst) % zNew;
zRatio = 1024 * zRatio / zNew;
int zNext = zSrc + 1;
if (zNext >= zDim)
zNext = zSrc;
const int zOff = zSrc * xyDim;
const int zOffNext = zNext * xyDim;
for (int i = 0; i < xyDim; i++)
{
// mix zSrc and zNext layers ith zRatio
MUint32 valSrc = (MUint32)m_data[zOff + i];
MUint32 valNext = (MUint32)m_data[zOffNext + i];
MUint32 valNew = (valSrc * (1024 - zRatio) + valNext * zRatio) >> 10;
pixelsNew[iDst++] = (MUint8)valNew;
} // for (i) all in xyDim
} // for (z)
delete [] m_data;
m_data = pixelsNew;
setDepth(zNew);
return 1;
}
int KtxTexture::rescale(const int xNew, const int yNew, const int zNew)
{
const int xDim = getWidth();
const int yDim = getHeight();
const int xyDim = xDim * yDim;
const int zDim = getDepth();
MUint8 *pixelsNew = M_NEW(MUint8[xNew * yNew * zNew]);
if (!pixelsNew)
return -1;
int offDst = 0;
int xDst, yDst, zDst;
for (zDst = 0; zDst < zNew; zDst++)
{
const int zSrc = zDim * zDst / zNew;
for (yDst = 0; yDst < yNew; yDst++)
{
const int ySrc = yDim * yDst / yNew;
for (xDst = 0; xDst < xNew; xDst++)
{
const int xSrc = xDim * xDst / xNew;
const int offSrc = xSrc + ySrc * xDim + zSrc * xyDim;
const MUint8 val = m_data[offSrc];
pixelsNew[offDst++] = val;
} // for (xDst)
} // for (yDst)
} // for (zDst)
delete [] m_data;
m_data = pixelsNew;
setWidth(xNew);
setHeight(yNew);
setDepth(zNew);
return 1;
}
| 29.917403 | 107 | 0.554607 | [
"3d"
] |
6c260ef082b19b8ae710fff93efba6edf24b8fb2 | 764 | cpp | C++ | code/LeetCode_11.cpp | Aden-Q/LeetCode | 4bbf772c886f42ce3d72d01fd737929b99df3eb3 | [
"MIT"
] | 1 | 2019-09-22T03:08:14.000Z | 2019-09-22T03:08:14.000Z | code/LeetCode_11.cpp | Aden-Q/leetcode | ebd4804edd4f172b9981b22c18d9ff654cf20762 | [
"Apache-2.0"
] | null | null | null | code/LeetCode_11.cpp | Aden-Q/leetcode | ebd4804edd4f172b9981b22c18d9ff654cf20762 | [
"Apache-2.0"
] | null | null | null | //盛最多水的容器
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxArea(vector<int>& height) {
int minvalue = 0;
int maxarea = 0;
int area;
for(int i=0;i<height.size();i++){
for(int j=height.size()-1;j>=i;j--){
minvalue = height[i] < height[j] ? height[i]:height[j];
area = minvalue * (j-i);
if(area > maxarea){
maxarea = area;
}
}
}
return maxarea;
}
};
int main(){
Solution test;
int r;
int vv[] = {1,8,6,2,5,4,8,3,7};
vector<int> v(vv, vv+9);
//cout << v.size() << endl;
r = test.maxArea(v);
cout << r << endl;
return 0;
}
| 20.648649 | 71 | 0.455497 | [
"vector"
] |
6c311953e728fabb5a795c9cf88e8e9cf5d5a250 | 1,365 | cpp | C++ | cf/1195/d.cpp | tusikalanse/acm-icpc | 20150f42752b85e286d812e716bb32ae1fa3db70 | [
"MIT"
] | 2 | 2021-06-09T12:27:07.000Z | 2021-06-11T12:02:03.000Z | cf/1195/d.cpp | tusikalanse/acm-icpc | 20150f42752b85e286d812e716bb32ae1fa3db70 | [
"MIT"
] | 1 | 2021-09-08T12:00:05.000Z | 2021-09-08T14:52:30.000Z | cf/1195/d.cpp | tusikalanse/acm-icpc | 20150f42752b85e286d812e716bb32ae1fa3db70 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10, mod = 998244353;
int f[25];
int a[N], n, ans, cnt[12];
vector<int> v[12];
int cc[12][12];
int pi[22], pj[22];
void pre(int i) {
for(auto f: v[i]) {
for(int len = 1; len <= i; ++len) {
cc[i][len] = (cc[i][len] + f % 10) % mod;
f /= 10;
}
}
}
int get(int x) {
int ans = 0;
while(x) {
ans++;
x /= 10;
}
return ans;
}
long long calc(int i, int j) {
long long ans = 0;
int now = 1, ii = 1, jj = 1;
memset(pi, 0, sizeof(pi));
memset(pj, 0, sizeof(pj));
while(ii <= i && jj <= j) {
pi[ii] = now;
now++, ii++;
pj[jj] = now;
now++, jj++;
}
while(ii <= i) {
pi[ii] = now;
now++, ii++;
}
while(jj <= j) {
pj[jj] = now;
now++, jj++;
}
for(int ii = 1; ii <= i; ++ii) {
ans = (ans + 1LL * cnt[j] * cc[i][ii] % mod * f[pi[ii]]) % mod;
}
for(int jj = 1; jj <= j; ++jj) {
ans = (ans + 1LL * cnt[i] * cc[j][jj] % mod * f[pj[jj]]) % mod;
}
return ans;
}
int main() {
scanf("%d", &n);
f[1] = 1;
for(int i = 2; i < 22; ++i)
f[i] = 10LL * f[i - 1] % mod;
for(int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
int c = get(a[i]);
cnt[c]++;
v[c].push_back(a[i]);
}
for(int i = 1; i <= 10; ++i)
pre(i);
for(int i = 1; i <= 10; ++i) {
for(int j = 1; j <= 10; ++j) {
ans = (ans + calc(i, j)) % mod;
}
}
printf("%d\n", ans);
return 0;
} | 17.278481 | 65 | 0.451282 | [
"vector"
] |
6c35cc242a6c4e4ce6d1ef36b025c93e3f9c7f03 | 654 | hpp | C++ | nonogram.hpp | thatoddmailbox/duck_hero | d96e379491b165dc0bb868ab2a0e4ef6f2365986 | [
"MIT"
] | 1 | 2021-02-19T05:09:10.000Z | 2021-02-19T05:09:10.000Z | nonogram.hpp | thatoddmailbox/duck_hero | d96e379491b165dc0bb868ab2a0e4ef6f2365986 | [
"MIT"
] | 2 | 2021-02-18T22:13:47.000Z | 2021-02-18T22:30:41.000Z | nonogram.hpp | thatoddmailbox/duck_hero | d96e379491b165dc0bb868ab2a0e4ef6f2365986 | [
"MIT"
] | null | null | null | #ifndef _NONOGRAM_HPP
#define _NONOGRAM_HPP
#include <cstdlib>
#include <vector>
namespace duckhero
{
enum NonogramCell
{
Empty,
Flagged,
Filled
};
class Nonogram
{
public:
int width, height;
std::vector<std::vector<NonogramCell>> data;
std::vector<std::vector<NonogramCell>> solution;
bool have_hints;
std::vector<std::vector<int>> horizontal_hints;
std::vector<std::vector<int>> vertical_hints;
bool mouse_down;
Nonogram();
void CreateDataArray();
void GenerateHints();
bool IsSolved();
std::vector<std::vector<int>>& GetHorizontalHints();
std::vector<std::vector<int>>& GetVerticalHints();
};
}
#endif | 15.571429 | 54 | 0.700306 | [
"vector"
] |
6c35ec2f9bf0240740dfd0f261e76c9bbf33cada | 45,310 | cpp | C++ | DxImageLoader/ktx_interface.cpp | hnjm/ImageViewer | f57908a0aae802380d615fc55c510cf609df8b52 | [
"MIT"
] | 1 | 2021-06-06T15:55:40.000Z | 2021-06-06T15:55:40.000Z | DxImageLoader/ktx_interface.cpp | hnjm/ImageViewer | f57908a0aae802380d615fc55c510cf609df8b52 | [
"MIT"
] | null | null | null | DxImageLoader/ktx_interface.cpp | hnjm/ImageViewer | f57908a0aae802380d615fc55c510cf609df8b52 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "ktx_interface.h"
#include "../dependencies/ktx/include/ktx.h"
#include <stdexcept>
#include <algorithm>
#include "VkFormat.h"
#include <unordered_map>
#include <string>
#include <thread>
#include "GliImage.h"
#include "interface.h"
gli::format convertFormat(VkFormat format);
VkFormat convertFormat(gli::format);
void ktx2_save_image(const char* filename, GliImage& image, gli::format format, int quality)
{
// convert format if it does not match
if(image.getFormat() != format)
{
auto tmp = image.convert(format, quality);
ktx2_save_image(filename, *tmp, format, quality);
return;
}
ktxTexture2* ktex;
ktxTextureCreateInfo i;
i.glInternalformat = 0; // ignored for ktx2
i.vkFormat = convertFormat(format);
i.baseWidth = image.getWidth(0);
i.baseHeight = image.getHeight(0);
i.baseDepth = image.getDepth(0);
if(i.baseDepth > 1) i.numDimensions = 3;
else if(i.baseHeight > 1 || quality < 100) i.numDimensions = 2;
else i.numDimensions = 1;
i.numLevels = image.getNumMipmaps();
i.numLayers = image.getNumNonFaceLayers();
i.numFaces = image.getNumFaces();
i.isArray = i.numLayers > 1;
i.generateMipmaps = false; // TODO let the user select
auto err = ktxTexture2_Create(&i, KTX_TEXTURE_CREATE_ALLOC_STORAGE, &ktex);
if(err != KTX_SUCCESS)
throw std::runtime_error(std::string("failed create ktx texture storage: ") + ktxErrorString(err));
// set image data for all layers, faces and levels
for(uint32_t layer = 0; layer < i.numLayers; ++layer)
{
for(uint32_t face = 0; face < i.numFaces; ++face)
{
for(uint32_t level = 0; level < i.numLevels; ++level)
{
uint32_t byteSize;
const uint8_t* data = image.getData(layer * i.numFaces + face, level, byteSize);
auto curDepth = image.getDepth(level);
if(curDepth == 1)
{
err = ktxTexture_SetImageFromMemory(ktxTexture(ktex), level, layer, face, data, byteSize);
if (err != KTX_SUCCESS)
throw std::runtime_error(std::string("could not set image data: ") + ktxErrorString(err));
}
else // for multiple depth slices => split as if it has multiple faces
{
auto sliceSize = byteSize / curDepth;
for(uint32_t z = 0; z < curDepth; ++z)
{
err = ktxTexture_SetImageFromMemory(ktxTexture(ktex), level, layer, z, data + z * sliceSize, sliceSize);
if (err != KTX_SUCCESS)
throw std::runtime_error(std::string("could not set image data: ") + ktxErrorString(err));
}
}
}
}
}
// optionally compress (if it was not already compressed)
if(!is_compressed(format) && quality < 100)
{
set_progress(0, "basis compression");
ktxBasisParams params = {};
params.structSize = sizeof(params);
params.threadCount = std::thread::hardware_concurrency();
params.compressionLevel = KTX_ETC1S_DEFAULT_COMPRESSION_LEVEL;
params.qualityLevel = std::max((quality * 254) / 99 + 1, 1); // scale quality [0, 99] between [1, 255]
// params.normalMap // TODO add this later?
// select uastc for everything that is not color (here: for everyhing that is not SRGB)
if(!gli::is_srgb(format))
{
params.uastc = KTX_TRUE;
params.uastcFlags = KTX_PACK_UASTC_MAX_LEVEL; // maximum supported quality
params.uastcRDO = KTX_TRUE; // Enable Rate Distortion Optimization (RDO) post-processing.
}
// optional if compression
err = ktxTexture2_CompressBasisEx(ktex, ¶ms);
if (err != KTX_SUCCESS)
throw std::runtime_error(std::string("failed to compress ktx texture: ") + ktxErrorString(err));
}
ktxTexture_WriteToNamedFile(ktxTexture(ktex), filename);
ktxTexture_Destroy(ktxTexture(ktex));
}
std::unique_ptr<image::IImage> ktx2_load(const char* filename)
{
ktxTexture* ktex;
auto err = ktxTexture_CreateFromNamedFile(filename, KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT, &ktex);
if (err != KTX_SUCCESS)
throw std::runtime_error(std::string("failed to load file: ") + ktxErrorString(err));
if (ktex->classId != ktxTexture2_c)
throw std::runtime_error("expected ktx2 texture but got ktx1 texture");
ktxTexture2* ktex2 = reinterpret_cast<ktxTexture2*>(ktex);
gli::format format = gli::FORMAT_UNDEFINED;
gli::format originalFormat = format;
if(ktxTexture2_NeedsTranscoding(ktex2)) // transcode from compressed format
{
const auto compressionSheme = ktex2->supercompressionScheme;
auto numComponents = ktxTexture2_GetNumComponents(ktex2);
// do transcoding
err = ktxTexture2_TranscodeBasis(ktex2, KTX_TTF_RGBA32, 0);
if (err != KTX_SUCCESS)
throw std::runtime_error(std::string("failed to transcode file: ") + ktxErrorString(err));
// set format and (previous) original format
format = convertFormat(VkFormat(ktex2->vkFormat));
if(compressionSheme == KTX_SS_BASIS_LZ) // ETC1S
switch (numComponents)
{
case 1: // should not happen (no matching srgb format)
case 2: // should not happen
case 3: originalFormat = gli::FORMAT_RGB_ETC2_SRGB_BLOCK8; break;
case 4: originalFormat = gli::FORMAT_RGBA_ETC2_SRGB_BLOCK8; break;
}
else // UASTC
originalFormat = gli::FORMAT_RGBA_ASTC_4X4_UNORM_BLOCK16; // astc has only rgba formats in the enum
}
else format = originalFormat = convertFormat(VkFormat(ktex2->vkFormat)); // no transcoding needed => read format directly
if (format == gli::FORMAT_UNDEFINED)
throw std::runtime_error("could not interpret format id " + std::to_string(ktex2->vkFormat));
// store data in gli storage to be able to convert it easily
auto res = std::make_unique<GliImage>(format, originalFormat,
ktex->numLayers, ktex->numFaces, ktex->numLevels,
ktex->baseWidth, ktex->baseHeight, ktex->baseDepth);
//auto ktxSize = ktxTexture_GetSize(ktex);
//assert(ktxSize == res->getSize());
//err = ktxTexture_LoadImageData(ktex, res->getData(), res->getSize());
//if (err != KTX_SUCCESS)
// throw std::runtime_error(std::string("could not load image data: ") + ktxErrorString(err));
ktx_uint32_t dstLayer = 0;
for(ktx_uint32_t srcLayer = 0; srcLayer < ktex->numLayers; ++srcLayer)
{
for(ktx_uint32_t srcFace = 0; srcFace < ktex->numFaces; ++srcFace)
{
for(ktx_uint32_t mip = 0; mip < ktex->numLevels; ++mip)
{
ktx_size_t offset = 0;
ktxTexture_GetImageOffset(ktex, ktx_uint32_t(mip), ktx_uint32_t(srcLayer), ktx_uint32_t(srcFace), &offset);
//ktex2->vtbl->GetImageOffset(ktex, mip, srcLayer, srcFace, &offset);
auto ktxLvlSize = ktxTexture_GetImageSize(ktex, ktx_uint32_t(mip));
ktxLvlSize *= res->getDepth(mip); // is not multiplied with depth layer
uint32_t size;
auto dstData = res->getData(dstLayer, mip, size);
if(ktxLvlSize != size)
throw std::runtime_error("suggested level size of gli does not match with ktx api");
memcpy(dstData, ktex->pData + offset, size);
}
++dstLayer;
}
}
ktxTexture_Destroy(ktex);
if (!image::isSupported(res->getFormat()))
{
res = res->convert(image::getSupportedFormat(res->getFormat()), 100);
}
if(ktex->orientation.y == KTX_ORIENT_Y_UP)
res->flip();
return res;
}
gli::format convertFormat(VkFormat format)
{
static std::unordered_map<VkFormat, gli::format> lookup = {
{VK_FORMAT_R4G4_UNORM_PACK8, gli::FORMAT_RG4_UNORM_PACK8},
{VK_FORMAT_R4G4B4A4_UNORM_PACK16, gli::FORMAT_RGBA4_UNORM_PACK16},
{VK_FORMAT_B4G4R4A4_UNORM_PACK16, gli::FORMAT_BGRA4_UNORM_PACK16},
{VK_FORMAT_R5G6B5_UNORM_PACK16, gli::FORMAT_R5G6B5_UNORM_PACK16},
{VK_FORMAT_B5G6R5_UNORM_PACK16, gli::FORMAT_B5G6R5_UNORM_PACK16},
{VK_FORMAT_R5G5B5A1_UNORM_PACK16, gli::FORMAT_RGB5A1_UNORM_PACK16},
{VK_FORMAT_B5G5R5A1_UNORM_PACK16, gli::FORMAT_BGR5A1_UNORM_PACK16},
{VK_FORMAT_A1R5G5B5_UNORM_PACK16, gli::FORMAT_A1RGB5_UNORM_PACK16},
{VK_FORMAT_R8_UNORM, gli::FORMAT_R8_UNORM_PACK8},
{VK_FORMAT_R8_SNORM, gli::FORMAT_R8_SNORM_PACK8},
{VK_FORMAT_R8_USCALED, gli::FORMAT_R8_USCALED_PACK8},
{VK_FORMAT_R8_SSCALED, gli::FORMAT_R8_SSCALED_PACK8},
{VK_FORMAT_R8_UINT, gli::FORMAT_R8_UINT_PACK8},
{VK_FORMAT_R8_SINT, gli::FORMAT_R8_SINT_PACK8},
{VK_FORMAT_R8_SRGB, gli::FORMAT_R8_SRGB_PACK8},
{VK_FORMAT_R8G8_UNORM, gli::FORMAT_RG8_UNORM_PACK8},
{VK_FORMAT_R8G8_SNORM, gli::FORMAT_RG8_SNORM_PACK8},
{VK_FORMAT_R8G8_USCALED, gli::FORMAT_RG8_USCALED_PACK8},
{VK_FORMAT_R8G8_SSCALED, gli::FORMAT_RG8_SSCALED_PACK8},
{VK_FORMAT_R8G8_UINT, gli::FORMAT_RG8_UINT_PACK8},
{VK_FORMAT_R8G8_SINT, gli::FORMAT_RG8_SINT_PACK8},
{VK_FORMAT_R8G8_SRGB, gli::FORMAT_RG8_SRGB_PACK8},
{VK_FORMAT_R8G8B8_UNORM, gli::FORMAT_RGB8_UNORM_PACK8},
{VK_FORMAT_R8G8B8_SNORM, gli::FORMAT_RGB8_SNORM_PACK8},
{VK_FORMAT_R8G8B8_USCALED, gli::FORMAT_RGB8_USCALED_PACK8},
{VK_FORMAT_R8G8B8_SSCALED, gli::FORMAT_RGB8_SSCALED_PACK8},
{VK_FORMAT_R8G8B8_UINT, gli::FORMAT_RGB8_UINT_PACK8},
{VK_FORMAT_R8G8B8_SINT, gli::FORMAT_RGB8_SINT_PACK8},
{VK_FORMAT_R8G8B8_SRGB, gli::FORMAT_RGB8_SRGB_PACK8},
{VK_FORMAT_B8G8R8_UNORM, gli::FORMAT_BGR8_UNORM_PACK8},
{VK_FORMAT_B8G8R8_SNORM, gli::FORMAT_BGR8_SNORM_PACK8},
{VK_FORMAT_B8G8R8_USCALED, gli::FORMAT_BGR8_USCALED_PACK8},
{VK_FORMAT_B8G8R8_SSCALED, gli::FORMAT_BGR8_SSCALED_PACK8},
{VK_FORMAT_B8G8R8_UINT, gli::FORMAT_BGR8_UINT_PACK8},
{VK_FORMAT_B8G8R8_SINT, gli::FORMAT_BGR8_SINT_PACK8},
{VK_FORMAT_B8G8R8_SRGB, gli::FORMAT_BGR8_SRGB_PACK8},
{VK_FORMAT_R8G8B8A8_UNORM, gli::FORMAT_RGBA8_UNORM_PACK8 },
{VK_FORMAT_R8G8B8A8_SNORM, gli::FORMAT_RGBA8_SNORM_PACK8 },
{VK_FORMAT_R8G8B8A8_USCALED, gli::FORMAT_RGBA8_USCALED_PACK8 },
{VK_FORMAT_R8G8B8A8_SSCALED, gli::FORMAT_RGBA8_SSCALED_PACK8 },
{VK_FORMAT_R8G8B8A8_UINT, gli::FORMAT_RGBA8_UINT_PACK8 },
{VK_FORMAT_R8G8B8A8_SINT, gli::FORMAT_RGBA8_SINT_PACK8 },
{VK_FORMAT_R8G8B8A8_SRGB, gli::FORMAT_RGBA8_SRGB_PACK8 },
{VK_FORMAT_B8G8R8A8_UNORM, gli::FORMAT_RGBA8_UNORM_PACK8 },
{VK_FORMAT_B8G8R8A8_SNORM, gli::FORMAT_RGBA8_SNORM_PACK8 },
{VK_FORMAT_B8G8R8A8_USCALED, gli::FORMAT_BGRA8_USCALED_PACK8 },
{VK_FORMAT_B8G8R8A8_SSCALED, gli::FORMAT_BGRA8_SSCALED_PACK8 },
{VK_FORMAT_B8G8R8A8_UINT, gli::FORMAT_BGRA8_UINT_PACK8 },
{VK_FORMAT_B8G8R8A8_SINT, gli::FORMAT_BGRA8_SINT_PACK8 },
{VK_FORMAT_B8G8R8A8_SRGB, gli::FORMAT_BGRA8_SRGB_PACK8 },
//{VK_FORMAT_A8B8G8R8_UNORM_PACK32, gli::FORMAT_ },
//{VK_FORMAT_A8B8G8R8_SNORM_PACK32, gli::FORMAT_ },
//{VK_FORMAT_A8B8G8R8_USCALED_PACK32, gli::FORMAT_ },
//{VK_FORMAT_A8B8G8R8_SSCALED_PACK32, gli::FORMAT_ },
//{VK_FORMAT_A8B8G8R8_UINT_PACK32, gli::FORMAT_ },
//{VK_FORMAT_A8B8G8R8_SINT_PACK32, gli::FORMAT_ },
//{VK_FORMAT_A8B8G8R8_SRGB_PACK32, gli::FORMAT_ },
//{VK_FORMAT_A2R10G10B10_UNORM_PACK32, gli::FORMAT_ },
//{VK_FORMAT_A2R10G10B10_SNORM_PACK32, gli::FORMAT_ },
//{VK_FORMAT_A2R10G10B10_USCALED_PACK32, gli::FORMAT_ },
//{VK_FORMAT_A2R10G10B10_SSCALED_PACK32, gli::FORMAT_ },
//{VK_FORMAT_A2R10G10B10_UINT_PACK32, gli::FORMAT_ },
//{VK_FORMAT_A2R10G10B10_SINT_PACK32, gli::FORMAT_ },
//{VK_FORMAT_A2B10G10R10_UNORM_PACK32, gli::FORMAT_ },
//{VK_FORMAT_A2B10G10R10_SNORM_PACK32, gli::FORMAT_ },
//{VK_FORMAT_A2B10G10R10_USCALED_PACK32, gli::FORMAT_ },
//{VK_FORMAT_A2B10G10R10_SSCALED_PACK32, gli::FORMAT_ },
//{VK_FORMAT_A2B10G10R10_UINT_PACK32, gli::FORMAT_ },
//{VK_FORMAT_A2B10G10R10_SINT_PACK32, gli::FORMAT_ },
{VK_FORMAT_R16_UNORM, gli::FORMAT_R16_UNORM_PACK16 },
{VK_FORMAT_R16_SNORM, gli::FORMAT_R16_SNORM_PACK16 },
{VK_FORMAT_R16_USCALED, gli::FORMAT_R16_USCALED_PACK16 },
{VK_FORMAT_R16_SSCALED, gli::FORMAT_R16_SSCALED_PACK16 },
{VK_FORMAT_R16_UINT, gli::FORMAT_R16_UINT_PACK16 },
{VK_FORMAT_R16_SINT, gli::FORMAT_R16_SINT_PACK16 },
{VK_FORMAT_R16_SFLOAT, gli::FORMAT_R16_SFLOAT_PACK16 },
{VK_FORMAT_R16G16_UNORM, gli::FORMAT_RG16_UNORM_PACK16 },
{VK_FORMAT_R16G16_SNORM, gli::FORMAT_RG16_SNORM_PACK16 },
{VK_FORMAT_R16G16_USCALED, gli::FORMAT_RG16_USCALED_PACK16 },
{VK_FORMAT_R16G16_SSCALED, gli::FORMAT_RG16_SSCALED_PACK16 },
{VK_FORMAT_R16G16_UINT, gli::FORMAT_RG16_UINT_PACK16 },
{VK_FORMAT_R16G16_SINT, gli::FORMAT_RG16_SINT_PACK16 },
{VK_FORMAT_R16G16_SFLOAT, gli::FORMAT_RG16_SFLOAT_PACK16 },
{VK_FORMAT_R16G16B16_UNORM, gli::FORMAT_RGB16_UNORM_PACK16 },
{VK_FORMAT_R16G16B16_SNORM, gli::FORMAT_RGB16_SNORM_PACK16 },
{VK_FORMAT_R16G16B16_USCALED, gli::FORMAT_RGB16_USCALED_PACK16 },
{VK_FORMAT_R16G16B16_SSCALED, gli::FORMAT_RGB16_SSCALED_PACK16 },
{VK_FORMAT_R16G16B16_UINT, gli::FORMAT_RGB16_UINT_PACK16 },
{VK_FORMAT_R16G16B16_SINT, gli::FORMAT_RGB16_SINT_PACK16 },
{VK_FORMAT_R16G16B16_SFLOAT, gli::FORMAT_RGB16_SFLOAT_PACK16 },
{VK_FORMAT_R16G16B16A16_UNORM, gli::FORMAT_RGBA16_UNORM_PACK16 },
{VK_FORMAT_R16G16B16A16_SNORM, gli::FORMAT_RGBA16_SNORM_PACK16 },
{VK_FORMAT_R16G16B16A16_USCALED, gli::FORMAT_RGBA16_USCALED_PACK16 },
{VK_FORMAT_R16G16B16A16_SSCALED, gli::FORMAT_RGBA16_SSCALED_PACK16 },
{VK_FORMAT_R16G16B16A16_UINT, gli::FORMAT_RGBA16_UINT_PACK16 },
{VK_FORMAT_R16G16B16A16_SINT, gli::FORMAT_RGBA16_SINT_PACK16 },
{VK_FORMAT_R16G16B16A16_SFLOAT, gli::FORMAT_RGBA16_SFLOAT_PACK16 },
{VK_FORMAT_R32_UINT, gli::FORMAT_R32_UINT_PACK32 },
{VK_FORMAT_R32_SINT, gli::FORMAT_R32_SINT_PACK32 },
{VK_FORMAT_R32_SFLOAT, gli::FORMAT_R32_SFLOAT_PACK32 },
{VK_FORMAT_R32G32_UINT, gli::FORMAT_RG32_UINT_PACK32 },
{VK_FORMAT_R32G32_SINT, gli::FORMAT_RG32_SINT_PACK32 },
{VK_FORMAT_R32G32_SFLOAT, gli::FORMAT_RG32_SFLOAT_PACK32 },
{VK_FORMAT_R32G32B32_UINT, gli::FORMAT_RGB32_UINT_PACK32 },
{VK_FORMAT_R32G32B32_SINT, gli::FORMAT_RGB32_SINT_PACK32 },
{VK_FORMAT_R32G32B32_SFLOAT, gli::FORMAT_RGB32_SFLOAT_PACK32 },
{VK_FORMAT_R32G32B32A32_UINT, gli::FORMAT_RGBA32_UINT_PACK32 },
{VK_FORMAT_R32G32B32A32_SINT, gli::FORMAT_RGBA32_SINT_PACK32 },
{VK_FORMAT_R32G32B32A32_SFLOAT, gli::FORMAT_RGBA32_SFLOAT_PACK32 },
{VK_FORMAT_R64_UINT, gli::FORMAT_R64_UINT_PACK64 },
{VK_FORMAT_R64_SINT, gli::FORMAT_R64_SINT_PACK64 },
{VK_FORMAT_R64_SFLOAT, gli::FORMAT_R64_SFLOAT_PACK64 },
{VK_FORMAT_R64G64_UINT, gli::FORMAT_RG64_UINT_PACK64 },
{VK_FORMAT_R64G64_SINT, gli::FORMAT_RG64_SINT_PACK64 },
{VK_FORMAT_R64G64_SFLOAT, gli::FORMAT_RG64_SFLOAT_PACK64 },
{VK_FORMAT_R64G64B64_UINT, gli::FORMAT_RGB64_UINT_PACK64 },
{VK_FORMAT_R64G64B64_SINT, gli::FORMAT_RGB64_SINT_PACK64 },
{VK_FORMAT_R64G64B64_SFLOAT, gli::FORMAT_RGB64_SFLOAT_PACK64 },
{VK_FORMAT_R64G64B64A64_UINT, gli::FORMAT_RGBA64_UINT_PACK64 },
{VK_FORMAT_R64G64B64A64_SINT, gli::FORMAT_RGBA64_SINT_PACK64 },
{VK_FORMAT_R64G64B64A64_SFLOAT, gli::FORMAT_RGBA64_SFLOAT_PACK64 },
{VK_FORMAT_B10G11R11_UFLOAT_PACK32, gli::FORMAT_RG11B10_UFLOAT_PACK32 },
//{VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, gli::FORMAT_ },
{VK_FORMAT_D16_UNORM, gli::FORMAT_D16_UNORM_PACK16 },
{VK_FORMAT_X8_D24_UNORM_PACK32, gli::FORMAT_D24_UNORM_PACK32 },
{VK_FORMAT_D32_SFLOAT, gli::FORMAT_D32_SFLOAT_PACK32 },
{VK_FORMAT_S8_UINT, gli::FORMAT_S8_UINT_PACK8 },
{VK_FORMAT_D16_UNORM_S8_UINT, gli::FORMAT_D16_UNORM_S8_UINT_PACK32 },
{VK_FORMAT_D24_UNORM_S8_UINT, gli::FORMAT_D24_UNORM_S8_UINT_PACK32 },
{VK_FORMAT_D32_SFLOAT_S8_UINT, gli::FORMAT_D32_SFLOAT_S8_UINT_PACK64 },
{VK_FORMAT_BC1_RGB_UNORM_BLOCK, gli::FORMAT_RGB_DXT1_UNORM_BLOCK8 },
{VK_FORMAT_BC1_RGB_SRGB_BLOCK, gli::FORMAT_RGB_DXT1_SRGB_BLOCK8 },
{VK_FORMAT_BC1_RGBA_UNORM_BLOCK, gli::FORMAT_RGBA_DXT1_UNORM_BLOCK8 },
{VK_FORMAT_BC1_RGBA_SRGB_BLOCK, gli::FORMAT_RGBA_DXT1_SRGB_BLOCK8 },
{VK_FORMAT_BC2_UNORM_BLOCK, gli::FORMAT_RGBA_DXT3_UNORM_BLOCK16 },
{VK_FORMAT_BC2_SRGB_BLOCK, gli::FORMAT_RGBA_DXT3_SRGB_BLOCK16 },
{VK_FORMAT_BC3_UNORM_BLOCK, gli::FORMAT_RGBA_DXT5_UNORM_BLOCK16 },
{VK_FORMAT_BC3_SRGB_BLOCK, gli::FORMAT_RGBA_DXT5_SRGB_BLOCK16 },
{VK_FORMAT_BC4_UNORM_BLOCK, gli::FORMAT_R_ATI1N_UNORM_BLOCK8 },
{VK_FORMAT_BC4_SNORM_BLOCK, gli::FORMAT_R_ATI1N_SNORM_BLOCK8 },
{VK_FORMAT_BC5_UNORM_BLOCK, gli::FORMAT_RG_ATI2N_UNORM_BLOCK16 },
{VK_FORMAT_BC5_SNORM_BLOCK, gli::FORMAT_RG_ATI2N_SNORM_BLOCK16 },
{VK_FORMAT_BC6H_UFLOAT_BLOCK, gli::FORMAT_RGB_BP_UFLOAT_BLOCK16 },
{VK_FORMAT_BC6H_SFLOAT_BLOCK, gli::FORMAT_RGB_BP_SFLOAT_BLOCK16 },
{VK_FORMAT_BC7_UNORM_BLOCK, gli::FORMAT_RGBA_BP_UNORM_BLOCK16 },
{VK_FORMAT_BC7_SRGB_BLOCK, gli::FORMAT_RGBA_BP_SRGB_BLOCK16 },
{VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK, gli::FORMAT_RGB_ETC2_UNORM_BLOCK8 },
{VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK, gli::FORMAT_RGB_ETC2_SRGB_BLOCK8 },
{VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK, gli::FORMAT_RGBA_ETC2_UNORM_BLOCK8 },
{VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK, gli::FORMAT_RGBA_ETC2_SRGB_BLOCK8 },
{VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK, gli::FORMAT_RGBA_ETC2_UNORM_BLOCK16 },
{VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK, gli::FORMAT_RGBA_ETC2_SRGB_BLOCK16 },
{VK_FORMAT_EAC_R11_UNORM_BLOCK, gli::FORMAT_R_EAC_UNORM_BLOCK8 },
{VK_FORMAT_EAC_R11_SNORM_BLOCK, gli::FORMAT_R_EAC_SNORM_BLOCK8 },
{VK_FORMAT_EAC_R11G11_UNORM_BLOCK, gli::FORMAT_RG_EAC_UNORM_BLOCK16 },
{VK_FORMAT_EAC_R11G11_SNORM_BLOCK, gli::FORMAT_RG_EAC_SNORM_BLOCK16 },
{VK_FORMAT_ASTC_4x4_UNORM_BLOCK, gli::FORMAT_RGBA_ASTC_4X4_UNORM_BLOCK16 },
{ VK_FORMAT_ASTC_5x4_UNORM_BLOCK, gli::FORMAT_RGBA_ASTC_5X4_UNORM_BLOCK16 },
{ VK_FORMAT_ASTC_5x5_UNORM_BLOCK, gli::FORMAT_RGBA_ASTC_5X5_UNORM_BLOCK16 },
{ VK_FORMAT_ASTC_6x5_UNORM_BLOCK, gli::FORMAT_RGBA_ASTC_6X5_UNORM_BLOCK16 },
{ VK_FORMAT_ASTC_6x6_UNORM_BLOCK, gli::FORMAT_RGBA_ASTC_6X6_UNORM_BLOCK16 },
{ VK_FORMAT_ASTC_8x5_UNORM_BLOCK, gli::FORMAT_RGBA_ASTC_8X5_UNORM_BLOCK16 },
{ VK_FORMAT_ASTC_8x6_UNORM_BLOCK, gli::FORMAT_RGBA_ASTC_8X6_UNORM_BLOCK16 },
{ VK_FORMAT_ASTC_8x8_UNORM_BLOCK, gli::FORMAT_RGBA_ASTC_8X8_UNORM_BLOCK16 },
{ VK_FORMAT_ASTC_10x5_UNORM_BLOCK, gli::FORMAT_RGBA_ASTC_10X5_UNORM_BLOCK16 },
{ VK_FORMAT_ASTC_10x6_UNORM_BLOCK, gli::FORMAT_RGBA_ASTC_10X6_UNORM_BLOCK16 },
{ VK_FORMAT_ASTC_10x8_UNORM_BLOCK, gli::FORMAT_RGBA_ASTC_10X8_UNORM_BLOCK16 },
{ VK_FORMAT_ASTC_10x10_UNORM_BLOCK, gli::FORMAT_RGBA_ASTC_10X10_UNORM_BLOCK16 },
{ VK_FORMAT_ASTC_12x10_UNORM_BLOCK, gli::FORMAT_RGBA_ASTC_12X10_UNORM_BLOCK16 },
{ VK_FORMAT_ASTC_12x12_UNORM_BLOCK, gli::FORMAT_RGBA_ASTC_12X12_UNORM_BLOCK16 },
{ VK_FORMAT_ASTC_4x4_SRGB_BLOCK, gli::FORMAT_RGBA_ASTC_4X4_SRGB_BLOCK16 },
{ VK_FORMAT_ASTC_5x4_SRGB_BLOCK, gli::FORMAT_RGBA_ASTC_5X4_SRGB_BLOCK16 },
{ VK_FORMAT_ASTC_5x5_SRGB_BLOCK, gli::FORMAT_RGBA_ASTC_5X5_SRGB_BLOCK16 },
{ VK_FORMAT_ASTC_6x5_SRGB_BLOCK, gli::FORMAT_RGBA_ASTC_6X5_SRGB_BLOCK16 },
{ VK_FORMAT_ASTC_6x6_SRGB_BLOCK, gli::FORMAT_RGBA_ASTC_6X6_SRGB_BLOCK16 },
{ VK_FORMAT_ASTC_8x5_SRGB_BLOCK, gli::FORMAT_RGBA_ASTC_8X5_SRGB_BLOCK16 },
{ VK_FORMAT_ASTC_8x6_SRGB_BLOCK, gli::FORMAT_RGBA_ASTC_8X6_SRGB_BLOCK16 },
{ VK_FORMAT_ASTC_8x8_SRGB_BLOCK, gli::FORMAT_RGBA_ASTC_8X8_SRGB_BLOCK16 },
{ VK_FORMAT_ASTC_10x5_SRGB_BLOCK, gli::FORMAT_RGBA_ASTC_10X5_SRGB_BLOCK16 },
{ VK_FORMAT_ASTC_10x6_SRGB_BLOCK, gli::FORMAT_RGBA_ASTC_10X6_SRGB_BLOCK16 },
{ VK_FORMAT_ASTC_10x8_SRGB_BLOCK, gli::FORMAT_RGBA_ASTC_10X8_SRGB_BLOCK16 },
{ VK_FORMAT_ASTC_10x10_SRGB_BLOCK, gli::FORMAT_RGBA_ASTC_10X10_SRGB_BLOCK16 },
{ VK_FORMAT_ASTC_12x10_SRGB_BLOCK, gli::FORMAT_RGBA_ASTC_12X10_SRGB_BLOCK16 },
{ VK_FORMAT_ASTC_12x12_SRGB_BLOCK, gli::FORMAT_RGBA_ASTC_12X12_SRGB_BLOCK16 },
//{VK_FORMAT_G8B8G8R8_422_UNORM, gli::FORMAT_ },
//{VK_FORMAT_B8G8R8G8_422_UNORM, gli::FORMAT_ },
//{VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM, gli::FORMAT_ },
//{VK_FORMAT_G8_B8R8_2PLANE_420_UNORM, gli::FORMAT_ },
//{VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM, gli::FORMAT_ },
//{VK_FORMAT_G8_B8R8_2PLANE_422_UNORM, gli::FORMAT_ },
//{VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM, gli::FORMAT_ },
//{VK_FORMAT_R10X6_UNORM_PACK16, gli::FORMAT_ },
//{VK_FORMAT_R10X6G10X6_UNORM_2PACK16, gli::FORMAT_ },
//{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16, gli::FORMAT_ },
//{VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16, gli::FORMAT_ },
//{VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16, gli::FORMAT_ },
//{VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16, gli::FORMAT_ },
//{VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16, gli::FORMAT_ },
//{VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16, gli::FORMAT_ },
//{VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16, gli::FORMAT_ },
//{VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16, gli::FORMAT_ },
//{VK_FORMAT_R12X4_UNORM_PACK16, gli::FORMAT_ },
//{VK_FORMAT_R12X4G12X4_UNORM_2PACK16, gli::FORMAT_ },
//{VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16, gli::FORMAT_ },
//{VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16, gli::FORMAT_ },
//{VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16, gli::FORMAT_ },
//{VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16, gli::FORMAT_ },
//{VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16, gli::FORMAT_ },
//{VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16, gli::FORMAT_ },
//{VK_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16, gli::FORMAT_ },
//{VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16, gli::FORMAT_ },
//{VK_FORMAT_G16B16G16R16_422_UNORM, gli::FORMAT_ },
//{VK_FORMAT_B16G16R16G16_422_UNORM, gli::FORMAT_ },
//{VK_FORMAT_G16_B16_R16_3PLANE_420_UNORM, gli::FORMAT_ },
//{VK_FORMAT_G16_B16R16_2PLANE_420_UNORM, gli::FORMAT_ },
//{VK_FORMAT_G16_B16_R16_3PLANE_422_UNORM, gli::FORMAT_ },
//{VK_FORMAT_G16_B16R16_2PLANE_422_UNORM, gli::FORMAT_ },
//{VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM, gli::FORMAT_ },
//{VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG, gli::FORMAT_ },
//{VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG, gli::FORMAT_ },
//{VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG, gli::FORMAT_ },
//{VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG, gli::FORMAT_ },
//{VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG, gli::FORMAT_ },
//{VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG, gli::FORMAT_ },
//{VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG, gli::FORMAT_ },
//{VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG, gli::FORMAT_ },
//{VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT, gli::FORMAT_ },
//{VK_FORMAT_ASTC_5x4_SFLOAT_BLOCK_EXT, gli::FORMAT_ },
//{VK_FORMAT_ASTC_5x5_SFLOAT_BLOCK_EXT, gli::FORMAT_ },
//{VK_FORMAT_ASTC_6x5_SFLOAT_BLOCK_EXT, gli::FORMAT_ },
//{VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT, gli::FORMAT_ },
//{VK_FORMAT_ASTC_8x5_SFLOAT_BLOCK_EXT, gli::FORMAT_ },
//{VK_FORMAT_ASTC_8x6_SFLOAT_BLOCK_EXT, gli::FORMAT_ },
//{VK_FORMAT_ASTC_8x8_SFLOAT_BLOCK_EXT, gli::FORMAT_ },
//{VK_FORMAT_ASTC_10x5_SFLOAT_BLOCK_EXT, gli::FORMAT_ },
//{VK_FORMAT_ASTC_10x6_SFLOAT_BLOCK_EXT, gli::FORMAT_ },
//{VK_FORMAT_ASTC_10x8_SFLOAT_BLOCK_EXT, gli::FORMAT_ },
//{VK_FORMAT_ASTC_10x10_SFLOAT_BLOCK_EXT, gli::FORMAT_ },
//{VK_FORMAT_ASTC_12x10_SFLOAT_BLOCK_EXT, gli::FORMAT_ },
//{VK_FORMAT_ASTC_12x12_SFLOAT_BLOCK_EXT, gli::FORMAT_ },
};
auto it = lookup.find(format);
if (it == lookup.end()) return gli::FORMAT_UNDEFINED;
return it->second;
}
VkFormat convertFormat(gli::format format)
{
switch (format) {
case gli::FORMAT_RG4_UNORM_PACK8: return VK_FORMAT_R4G4_UNORM_PACK8;
case gli::FORMAT_RGBA4_UNORM_PACK16: return VK_FORMAT_R4G4B4A4_UNORM_PACK16;
case gli::FORMAT_BGRA4_UNORM_PACK16: return VK_FORMAT_B4G4R4A4_UNORM_PACK16;
case gli::FORMAT_R5G6B5_UNORM_PACK16: return VK_FORMAT_R5G6B5_UNORM_PACK16;
case gli::FORMAT_B5G6R5_UNORM_PACK16: return VK_FORMAT_B5G6R5_UNORM_PACK16;
case gli::FORMAT_RGB5A1_UNORM_PACK16: return VK_FORMAT_R5G5B5A1_UNORM_PACK16;
case gli::FORMAT_BGR5A1_UNORM_PACK16: return VK_FORMAT_B5G5R5A1_UNORM_PACK16;
case gli::FORMAT_A1RGB5_UNORM_PACK16: return VK_FORMAT_A1R5G5B5_UNORM_PACK16;
case gli::FORMAT_R8_UNORM_PACK8: return VK_FORMAT_R8_UNORM;
case gli::FORMAT_R8_SNORM_PACK8: return VK_FORMAT_R8_SNORM;
case gli::FORMAT_R8_USCALED_PACK8: return VK_FORMAT_R8_USCALED;
case gli::FORMAT_R8_SSCALED_PACK8: return VK_FORMAT_R8_SSCALED;
case gli::FORMAT_R8_UINT_PACK8: return VK_FORMAT_R8_UINT;
case gli::FORMAT_R8_SINT_PACK8: return VK_FORMAT_R8_SINT;
case gli::FORMAT_R8_SRGB_PACK8: return VK_FORMAT_R8_SRGB;
case gli::FORMAT_RG8_UNORM_PACK8: return VK_FORMAT_R8G8_UNORM;
case gli::FORMAT_RG8_SNORM_PACK8: return VK_FORMAT_R8G8_SNORM;
case gli::FORMAT_RG8_USCALED_PACK8: return VK_FORMAT_R8G8_USCALED;
case gli::FORMAT_RG8_SSCALED_PACK8: return VK_FORMAT_R8G8_SSCALED;
case gli::FORMAT_RG8_UINT_PACK8: return VK_FORMAT_R8G8_UINT;
case gli::FORMAT_RG8_SINT_PACK8: return VK_FORMAT_R8G8_SINT;
case gli::FORMAT_RG8_SRGB_PACK8: return VK_FORMAT_R8G8_SRGB;
case gli::FORMAT_RGB8_UNORM_PACK8: return VK_FORMAT_R8G8B8_UNORM;
case gli::FORMAT_RGB8_SNORM_PACK8: return VK_FORMAT_R8G8B8_SNORM;
case gli::FORMAT_RGB8_USCALED_PACK8: return VK_FORMAT_R8G8B8_USCALED;
case gli::FORMAT_RGB8_SSCALED_PACK8: return VK_FORMAT_R8G8B8_SSCALED;
case gli::FORMAT_RGB8_UINT_PACK8: return VK_FORMAT_R8G8B8_UINT;
case gli::FORMAT_RGB8_SINT_PACK8: return VK_FORMAT_R8G8B8_SINT;
case gli::FORMAT_RGB8_SRGB_PACK8: return VK_FORMAT_R8G8B8_SRGB;
case gli::FORMAT_BGR8_UNORM_PACK8: return VK_FORMAT_B8G8R8_UNORM;
case gli::FORMAT_BGR8_SNORM_PACK8: return VK_FORMAT_B8G8R8_SNORM;
case gli::FORMAT_BGR8_USCALED_PACK8: return VK_FORMAT_B8G8R8_USCALED;
case gli::FORMAT_BGR8_SSCALED_PACK8: return VK_FORMAT_B8G8R8_SSCALED;
case gli::FORMAT_BGR8_UINT_PACK8: return VK_FORMAT_B8G8R8_UINT;
case gli::FORMAT_BGR8_SINT_PACK8: return VK_FORMAT_B8G8R8_SINT;
case gli::FORMAT_BGR8_SRGB_PACK8: return VK_FORMAT_B8G8R8_SRGB;
case gli::FORMAT_RGBA8_UNORM_PACK8: return VK_FORMAT_R8G8B8A8_UNORM;
case gli::FORMAT_RGBA8_SNORM_PACK8: return VK_FORMAT_R8G8B8A8_SNORM;
case gli::FORMAT_RGBA8_USCALED_PACK8: return VK_FORMAT_R8G8B8A8_USCALED;
case gli::FORMAT_RGBA8_SSCALED_PACK8: return VK_FORMAT_R8G8B8A8_SSCALED;
case gli::FORMAT_RGBA8_UINT_PACK8: return VK_FORMAT_R8G8B8A8_UINT;
case gli::FORMAT_RGBA8_SINT_PACK8: return VK_FORMAT_R8G8B8A8_SINT;
case gli::FORMAT_RGBA8_SRGB_PACK8: return VK_FORMAT_R8G8B8A8_SRGB;
case gli::FORMAT_BGRA8_UNORM_PACK8: return VK_FORMAT_B8G8R8A8_UNORM;
case gli::FORMAT_BGRA8_SNORM_PACK8: return VK_FORMAT_B8G8R8A8_SNORM;
case gli::FORMAT_BGRA8_USCALED_PACK8: return VK_FORMAT_B8G8R8A8_USCALED;
case gli::FORMAT_BGRA8_SSCALED_PACK8: return VK_FORMAT_B8G8R8A8_SSCALED;
case gli::FORMAT_BGRA8_UINT_PACK8: return VK_FORMAT_B8G8R8A8_UINT;
case gli::FORMAT_BGRA8_SINT_PACK8: return VK_FORMAT_B8G8R8A8_SINT;
case gli::FORMAT_BGRA8_SRGB_PACK8: return VK_FORMAT_B8G8R8A8_SRGB;
case gli::FORMAT_RGBA8_UNORM_PACK32: return VK_FORMAT_R8G8B8A8_UNORM;
case gli::FORMAT_RGBA8_SNORM_PACK32: return VK_FORMAT_R8G8B8A8_SNORM;
case gli::FORMAT_RGBA8_USCALED_PACK32: return VK_FORMAT_R8G8B8A8_USCALED;
case gli::FORMAT_RGBA8_SSCALED_PACK32: return VK_FORMAT_R8G8B8A8_SSCALED;
case gli::FORMAT_RGBA8_UINT_PACK32: return VK_FORMAT_R8G8B8A8_UINT;
case gli::FORMAT_RGBA8_SINT_PACK32: return VK_FORMAT_R8G8B8A8_SINT;
case gli::FORMAT_RGBA8_SRGB_PACK32: return VK_FORMAT_R8G8B8A8_SRGB;
case gli::FORMAT_R16_UNORM_PACK16: return VK_FORMAT_R16_UNORM;
case gli::FORMAT_R16_SNORM_PACK16: return VK_FORMAT_R16_SNORM;
case gli::FORMAT_R16_USCALED_PACK16: return VK_FORMAT_R16_USCALED;
case gli::FORMAT_R16_SSCALED_PACK16: return VK_FORMAT_R16_SSCALED;
case gli::FORMAT_R16_UINT_PACK16: return VK_FORMAT_R16_UINT;
case gli::FORMAT_R16_SINT_PACK16: return VK_FORMAT_R16_SINT;
case gli::FORMAT_R16_SFLOAT_PACK16: return VK_FORMAT_R16_SFLOAT;
case gli::FORMAT_RG16_UNORM_PACK16: return VK_FORMAT_R16_UNORM;
case gli::FORMAT_RG16_SNORM_PACK16: return VK_FORMAT_R16_SNORM;
case gli::FORMAT_RG16_USCALED_PACK16: return VK_FORMAT_R16G16_USCALED;
case gli::FORMAT_RG16_SSCALED_PACK16: return VK_FORMAT_R16G16_SSCALED;
case gli::FORMAT_RG16_UINT_PACK16: return VK_FORMAT_R16G16_UINT;
case gli::FORMAT_RG16_SINT_PACK16: return VK_FORMAT_R16G16_SINT;
case gli::FORMAT_RG16_SFLOAT_PACK16: return VK_FORMAT_R16G16_SFLOAT;
case gli::FORMAT_RGB16_UNORM_PACK16: return VK_FORMAT_R16G16B16_UNORM;
case gli::FORMAT_RGB16_SNORM_PACK16: return VK_FORMAT_R16G16B16_SNORM;
case gli::FORMAT_RGB16_USCALED_PACK16: return VK_FORMAT_R16G16B16_USCALED;
case gli::FORMAT_RGB16_SSCALED_PACK16: return VK_FORMAT_R16G16B16_SSCALED;
case gli::FORMAT_RGB16_UINT_PACK16: return VK_FORMAT_R16G16B16_UINT;
case gli::FORMAT_RGB16_SINT_PACK16: return VK_FORMAT_R16G16B16_SINT;
case gli::FORMAT_RGB16_SFLOAT_PACK16: return VK_FORMAT_R16G16B16_SFLOAT;
case gli::FORMAT_RGBA16_UNORM_PACK16: return VK_FORMAT_R16G16B16A16_UNORM;
case gli::FORMAT_RGBA16_SNORM_PACK16: return VK_FORMAT_R16G16B16_SNORM;
case gli::FORMAT_RGBA16_USCALED_PACK16: return VK_FORMAT_R16G16B16A16_USCALED;
case gli::FORMAT_RGBA16_SSCALED_PACK16: return VK_FORMAT_R16G16B16A16_SSCALED;
case gli::FORMAT_RGBA16_UINT_PACK16: return VK_FORMAT_R16G16B16A16_UINT;
case gli::FORMAT_RGBA16_SINT_PACK16: return VK_FORMAT_R16G16B16A16_SINT;
case gli::FORMAT_RGBA16_SFLOAT_PACK16: return VK_FORMAT_R16G16B16A16_SFLOAT;
case gli::FORMAT_R32_UINT_PACK32: return VK_FORMAT_R32_UINT;
case gli::FORMAT_R32_SINT_PACK32: return VK_FORMAT_R32_SINT;
case gli::FORMAT_R32_SFLOAT_PACK32: return VK_FORMAT_R32_SFLOAT;
case gli::FORMAT_RG32_UINT_PACK32: return VK_FORMAT_R32G32_UINT;
case gli::FORMAT_RG32_SINT_PACK32: return VK_FORMAT_R32G32_SINT;
case gli::FORMAT_RG32_SFLOAT_PACK32: return VK_FORMAT_R32G32_SFLOAT;
case gli::FORMAT_RGB32_UINT_PACK32: return VK_FORMAT_R32G32B32_UINT;
case gli::FORMAT_RGB32_SINT_PACK32: return VK_FORMAT_R32G32B32_SINT;
case gli::FORMAT_RGB32_SFLOAT_PACK32: return VK_FORMAT_R32G32B32_SFLOAT;
case gli::FORMAT_RGBA32_UINT_PACK32: return VK_FORMAT_R32G32B32A32_UINT;
case gli::FORMAT_RGBA32_SINT_PACK32: return VK_FORMAT_R32G32B32A32_SINT;
case gli::FORMAT_RGBA32_SFLOAT_PACK32: return VK_FORMAT_R32G32B32A32_SFLOAT;
case gli::FORMAT_R64_UINT_PACK64: return VK_FORMAT_R64_UINT;
case gli::FORMAT_R64_SINT_PACK64: return VK_FORMAT_R64_SINT;
case gli::FORMAT_R64_SFLOAT_PACK64: return VK_FORMAT_R64_SFLOAT;
case gli::FORMAT_RG64_UINT_PACK64: return VK_FORMAT_R64G64_UINT;
case gli::FORMAT_RG64_SINT_PACK64: return VK_FORMAT_R64G64_SINT;
case gli::FORMAT_RG64_SFLOAT_PACK64: return VK_FORMAT_R64G64_SFLOAT;
case gli::FORMAT_RGB64_UINT_PACK64: return VK_FORMAT_R64G64B64_UINT;
case gli::FORMAT_RGB64_SINT_PACK64: return VK_FORMAT_R64G64B64_SINT;
case gli::FORMAT_RGB64_SFLOAT_PACK64: return VK_FORMAT_R64G64B64_SFLOAT;
case gli::FORMAT_RGBA64_UINT_PACK64: return VK_FORMAT_R64G64B64A64_UINT;
case gli::FORMAT_RGBA64_SINT_PACK64: return VK_FORMAT_R64G64B64A64_SINT;
case gli::FORMAT_RGBA64_SFLOAT_PACK64: return VK_FORMAT_R64G64B64A64_SFLOAT;
case gli::FORMAT_D16_UNORM_PACK16: return VK_FORMAT_D16_UNORM;
case gli::FORMAT_D32_SFLOAT_PACK32: return VK_FORMAT_D32_SFLOAT;
case gli::FORMAT_S8_UINT_PACK8: return VK_FORMAT_S8_UINT;
case gli::FORMAT_D16_UNORM_S8_UINT_PACK32: return VK_FORMAT_D16_UNORM_S8_UINT;
case gli::FORMAT_D24_UNORM_S8_UINT_PACK32: return VK_FORMAT_D24_UNORM_S8_UINT;
case gli::FORMAT_D32_SFLOAT_S8_UINT_PACK64: return VK_FORMAT_D32_SFLOAT_S8_UINT;
case gli::FORMAT_RGB_DXT1_UNORM_BLOCK8: return VK_FORMAT_BC1_RGB_UNORM_BLOCK;
case gli::FORMAT_RGB_DXT1_SRGB_BLOCK8: return VK_FORMAT_BC1_RGB_SRGB_BLOCK;
case gli::FORMAT_RGBA_DXT1_UNORM_BLOCK8: return VK_FORMAT_BC1_RGBA_UNORM_BLOCK;
case gli::FORMAT_RGBA_DXT1_SRGB_BLOCK8: return VK_FORMAT_BC1_RGBA_SRGB_BLOCK;
case gli::FORMAT_RGBA_DXT3_UNORM_BLOCK16: return VK_FORMAT_BC2_UNORM_BLOCK;
case gli::FORMAT_RGBA_DXT3_SRGB_BLOCK16: return VK_FORMAT_BC2_SRGB_BLOCK;
case gli::FORMAT_RGBA_DXT5_UNORM_BLOCK16: return VK_FORMAT_BC3_UNORM_BLOCK;
case gli::FORMAT_RGBA_DXT5_SRGB_BLOCK16: return VK_FORMAT_BC3_SRGB_BLOCK;
case gli::FORMAT_RGB_ETC2_UNORM_BLOCK8: return VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK;
case gli::FORMAT_RGB_ETC2_SRGB_BLOCK8: return VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK;
case gli::FORMAT_RGBA_ETC2_UNORM_BLOCK8: return VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK;
case gli::FORMAT_RGBA_ETC2_SRGB_BLOCK8: return VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK;
case gli::FORMAT_R_EAC_UNORM_BLOCK8: return VK_FORMAT_EAC_R11_UNORM_BLOCK;
case gli::FORMAT_R_EAC_SNORM_BLOCK8: return VK_FORMAT_EAC_R11_SNORM_BLOCK;
case gli::FORMAT_RG_EAC_UNORM_BLOCK16: return VK_FORMAT_EAC_R11G11_UNORM_BLOCK;
case gli::FORMAT_RG_EAC_SNORM_BLOCK16: return VK_FORMAT_EAC_R11G11_SNORM_BLOCK;
case gli::FORMAT_RGBA_ASTC_4X4_UNORM_BLOCK16: return VK_FORMAT_ASTC_4x4_UNORM_BLOCK;
case gli::FORMAT_RGBA_ASTC_4X4_SRGB_BLOCK16: return VK_FORMAT_ASTC_4x4_SRGB_BLOCK;
case gli::FORMAT_RGBA_ASTC_5X4_UNORM_BLOCK16: return VK_FORMAT_ASTC_5x4_UNORM_BLOCK;
case gli::FORMAT_RGBA_ASTC_5X4_SRGB_BLOCK16: return VK_FORMAT_ASTC_5x4_SRGB_BLOCK;
case gli::FORMAT_RGBA_ASTC_5X5_UNORM_BLOCK16: return VK_FORMAT_ASTC_5x5_UNORM_BLOCK;
case gli::FORMAT_RGBA_ASTC_5X5_SRGB_BLOCK16: return VK_FORMAT_ASTC_5x5_SRGB_BLOCK;
case gli::FORMAT_RGBA_ASTC_6X5_UNORM_BLOCK16: return VK_FORMAT_ASTC_6x5_UNORM_BLOCK;
case gli::FORMAT_RGBA_ASTC_6X5_SRGB_BLOCK16: return VK_FORMAT_ASTC_6x5_SRGB_BLOCK;
case gli::FORMAT_RGBA_ASTC_6X6_UNORM_BLOCK16: return VK_FORMAT_ASTC_6x6_UNORM_BLOCK;
case gli::FORMAT_RGBA_ASTC_6X6_SRGB_BLOCK16: return VK_FORMAT_ASTC_6x6_SRGB_BLOCK;
case gli::FORMAT_RGBA_ASTC_8X5_UNORM_BLOCK16: return VK_FORMAT_ASTC_8x5_UNORM_BLOCK;
case gli::FORMAT_RGBA_ASTC_8X5_SRGB_BLOCK16: return VK_FORMAT_ASTC_8x5_SRGB_BLOCK;
case gli::FORMAT_RGBA_ASTC_8X6_UNORM_BLOCK16: return VK_FORMAT_ASTC_8x6_UNORM_BLOCK;
case gli::FORMAT_RGBA_ASTC_8X6_SRGB_BLOCK16: return VK_FORMAT_ASTC_8x6_SRGB_BLOCK;
case gli::FORMAT_RGBA_ASTC_8X8_UNORM_BLOCK16: return VK_FORMAT_ASTC_8x8_UNORM_BLOCK;
case gli::FORMAT_RGBA_ASTC_8X8_SRGB_BLOCK16: return VK_FORMAT_ASTC_8x8_SRGB_BLOCK;
case gli::FORMAT_RGBA_ASTC_10X5_UNORM_BLOCK16: return VK_FORMAT_ASTC_10x5_UNORM_BLOCK;
case gli::FORMAT_RGBA_ASTC_10X5_SRGB_BLOCK16: return VK_FORMAT_ASTC_10x5_SRGB_BLOCK;
case gli::FORMAT_RGBA_ASTC_10X6_UNORM_BLOCK16: return VK_FORMAT_ASTC_10x6_UNORM_BLOCK;
case gli::FORMAT_RGBA_ASTC_10X6_SRGB_BLOCK16: return VK_FORMAT_ASTC_10x6_SRGB_BLOCK;
case gli::FORMAT_RGBA_ASTC_10X8_UNORM_BLOCK16: return VK_FORMAT_ASTC_10x8_UNORM_BLOCK;
case gli::FORMAT_RGBA_ASTC_10X8_SRGB_BLOCK16: return VK_FORMAT_ASTC_10x8_SRGB_BLOCK;
case gli::FORMAT_RGBA_ASTC_10X10_UNORM_BLOCK16: return VK_FORMAT_ASTC_10x10_UNORM_BLOCK;
case gli::FORMAT_RGBA_ASTC_10X10_SRGB_BLOCK16: return VK_FORMAT_ASTC_10x10_SRGB_BLOCK;
case gli::FORMAT_RGBA_ASTC_12X10_UNORM_BLOCK16: return VK_FORMAT_ASTC_12x10_UNORM_BLOCK;
case gli::FORMAT_RGBA_ASTC_12X10_SRGB_BLOCK16: return VK_FORMAT_ASTC_12x10_SRGB_BLOCK;
case gli::FORMAT_RGBA_ASTC_12X12_UNORM_BLOCK16: return VK_FORMAT_ASTC_12x12_UNORM_BLOCK;
case gli::FORMAT_RGBA_ASTC_12X12_SRGB_BLOCK16: return VK_FORMAT_ASTC_12x12_SRGB_BLOCK;
case gli::FORMAT_RGB_PVRTC1_8X8_UNORM_BLOCK32: return VK_FORMAT_ASTC_8x8_UNORM_BLOCK;
case gli::FORMAT_L8_UNORM_PACK8: case gli::FORMAT_A8_UNORM_PACK8: return VK_FORMAT_R8_UNORM;
case gli::FORMAT_LA8_UNORM_PACK8: return VK_FORMAT_R8G8_UNORM;
case gli::FORMAT_L16_UNORM_PACK16: case gli::FORMAT_A16_UNORM_PACK16: return VK_FORMAT_R16_UNORM;
case gli::FORMAT_LA16_UNORM_PACK16: return VK_FORMAT_R16G16_UNORM;
case gli::FORMAT_BGR8_UNORM_PACK32: return VK_FORMAT_B8G8R8_UNORM;
case gli::FORMAT_BGR8_SRGB_PACK32: return VK_FORMAT_B8G8R8_SRGB;
case gli::FORMAT_D24_UNORM_PACK32: return VK_FORMAT_X8_D24_UNORM_PACK32;
case gli::FORMAT_R_ATI1N_UNORM_BLOCK8: return VK_FORMAT_BC4_UNORM_BLOCK;
case gli::FORMAT_R_ATI1N_SNORM_BLOCK8: return VK_FORMAT_BC4_SNORM_BLOCK;
case gli::FORMAT_RG_ATI2N_UNORM_BLOCK16: return VK_FORMAT_BC5_UNORM_BLOCK;
case gli::FORMAT_RG_ATI2N_SNORM_BLOCK16: return VK_FORMAT_BC5_SNORM_BLOCK;
case gli::FORMAT_RGB_BP_UFLOAT_BLOCK16: return VK_FORMAT_BC6H_UFLOAT_BLOCK;
case gli::FORMAT_RGB_BP_SFLOAT_BLOCK16: return VK_FORMAT_BC6H_SFLOAT_BLOCK;
case gli::FORMAT_RGBA_BP_UNORM_BLOCK16: return VK_FORMAT_BC7_UNORM_BLOCK;
case gli::FORMAT_RGBA_BP_SRGB_BLOCK16: return VK_FORMAT_BC7_SRGB_BLOCK;
case gli::FORMAT_RGBA_ETC2_UNORM_BLOCK16: return VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK;
case gli::FORMAT_RGBA_ETC2_SRGB_BLOCK16: return VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK;
// order different but same components (TODO experimental)
//case gli::FORMAT_RGB10A2_UNORM_PACK32:
// return VK_FORMAT_A2R10G10B10_UNORM_PACK32;
//case gli::FORMAT_RGB10A2_SNORM_PACK32:
// return VK_FORMAT_A2R10G10B10_SNORM_PACK32;
//case gli::FORMAT_RGB10A2_USCALED_PACK32:
// return VK_FORMAT_A2R10G10B10_USCALED_PACK32;
//case gli::FORMAT_RGB10A2_SSCALED_PACK32:
// return VK_FORMAT_A2R10G10B10_SSCALED_PACK32;
//case gli::FORMAT_RGB10A2_UINT_PACK32:
// return VK_FORMAT_A2R10G10B10_UINT_PACK32;
//case gli::FORMAT_RGB10A2_SINT_PACK32:
// return VK_FORMAT_A2R10G10B10_SINT_PACK32;
//case gli::FORMAT_BGR10A2_UNORM_PACK32:
// return VK_FORMAT_A2B10G10R10_UNORM_PACK32;
//case gli::FORMAT_BGR10A2_SNORM_PACK32:
// return VK_FORMAT_A2B10G10R10_SNORM_PACK32;
//case gli::FORMAT_BGR10A2_USCALED_PACK32:
// return VK_FORMAT_A2B10G10R10_USCALED_PACK32;
//case gli::FORMAT_BGR10A2_SSCALED_PACK32:
// return VK_FORMAT_A2B10G10R10_SSCALED_PACK32;
//case gli::FORMAT_BGR10A2_UINT_PACK32:
// return VK_FORMAT_A2B10G10R10_UINT_PACK32;
//case gli::FORMAT_BGR10A2_SINT_PACK32:
// return VK_FORMAT_A2B10G10R10_SINT_PACK32;
//case gli::FORMAT_RG11B10_UFLOAT_PACK32:
//case gli::FORMAT_RGB9E5_UFLOAT_PACK32:
// return VK_FORMAT_E5B9G9R9_UFLOAT_PACK32;
case gli::FORMAT_RGB_PVRTC1_8X8_SRGB_BLOCK32:
case gli::FORMAT_RGB_PVRTC1_16X8_UNORM_BLOCK32:
case gli::FORMAT_RGB_PVRTC1_16X8_SRGB_BLOCK32:
case gli::FORMAT_RGBA_PVRTC1_8X8_UNORM_BLOCK32:
case gli::FORMAT_RGBA_PVRTC1_8X8_SRGB_BLOCK32:
case gli::FORMAT_RGBA_PVRTC1_16X8_UNORM_BLOCK32:
case gli::FORMAT_RGBA_PVRTC1_16X8_SRGB_BLOCK32:
case gli::FORMAT_RGBA_PVRTC2_4X4_UNORM_BLOCK8:
case gli::FORMAT_RGBA_PVRTC2_4X4_SRGB_BLOCK8:
case gli::FORMAT_RGBA_PVRTC2_8X4_UNORM_BLOCK8:
case gli::FORMAT_RGBA_PVRTC2_8X4_SRGB_BLOCK8:
case gli::FORMAT_RGB_ETC_UNORM_BLOCK8:
case gli::FORMAT_RGB_ATC_UNORM_BLOCK8:
case gli::FORMAT_RGBA_ATCA_UNORM_BLOCK16:
case gli::FORMAT_RGBA_ATCI_UNORM_BLOCK16:
case gli::FORMAT_RG3B2_UNORM_PACK8:
default: break;
}
return VK_FORMAT_UNDEFINED;
}
std::vector<uint32_t> ktx2_get_export_formats()
{
return std::vector<uint32_t>{
gli::FORMAT_RG4_UNORM_PACK8,
gli::FORMAT_RGBA4_UNORM_PACK16,
gli::FORMAT_BGRA4_UNORM_PACK16,
gli::FORMAT_R5G6B5_UNORM_PACK16,
gli::FORMAT_B5G6R5_UNORM_PACK16,
gli::FORMAT_RGB5A1_UNORM_PACK16,
gli::FORMAT_BGR5A1_UNORM_PACK16,
gli::FORMAT_A1RGB5_UNORM_PACK16,
gli::FORMAT_R8_UNORM_PACK8,
gli::FORMAT_R8_SNORM_PACK8,
gli::FORMAT_R8_USCALED_PACK8,
gli::FORMAT_R8_SSCALED_PACK8,
gli::FORMAT_R8_UINT_PACK8,
gli::FORMAT_R8_SINT_PACK8,
gli::FORMAT_R8_SRGB_PACK8,
gli::FORMAT_RG8_UNORM_PACK8,
gli::FORMAT_RG8_SNORM_PACK8,
gli::FORMAT_RG8_USCALED_PACK8,
gli::FORMAT_RG8_SSCALED_PACK8,
gli::FORMAT_RG8_UINT_PACK8,
gli::FORMAT_RG8_SINT_PACK8,
gli::FORMAT_RG8_SRGB_PACK8,
gli::FORMAT_RGB8_UNORM_PACK8,
gli::FORMAT_RGB8_SNORM_PACK8,
gli::FORMAT_RGB8_USCALED_PACK8,
gli::FORMAT_RGB8_SSCALED_PACK8,
gli::FORMAT_RGB8_UINT_PACK8,
gli::FORMAT_RGB8_SINT_PACK8,
gli::FORMAT_RGB8_SRGB_PACK8,
gli::FORMAT_BGR8_UNORM_PACK8,
gli::FORMAT_BGR8_SNORM_PACK8,
gli::FORMAT_BGR8_USCALED_PACK8,
gli::FORMAT_BGR8_SSCALED_PACK8,
// those give some block size mismatch error from gli:
//gli::FORMAT_BGR8_UINT_PACK8,
//gli::FORMAT_BGR8_SINT_PACK8,
gli::FORMAT_BGR8_SRGB_PACK8,
gli::FORMAT_RGBA8_UNORM_PACK8,
gli::FORMAT_RGBA8_SNORM_PACK8,
gli::FORMAT_RGBA8_USCALED_PACK8,
gli::FORMAT_RGBA8_SSCALED_PACK8,
gli::FORMAT_RGBA8_UINT_PACK8,
gli::FORMAT_RGBA8_SINT_PACK8,
gli::FORMAT_RGBA8_SRGB_PACK8,
gli::FORMAT_BGRA8_UNORM_PACK8,
gli::FORMAT_BGRA8_SNORM_PACK8,
gli::FORMAT_BGRA8_USCALED_PACK8,
gli::FORMAT_BGRA8_SSCALED_PACK8,
gli::FORMAT_BGRA8_UINT_PACK8,
gli::FORMAT_BGRA8_SINT_PACK8,
gli::FORMAT_BGRA8_SRGB_PACK8,
gli::FORMAT_RGBA8_UNORM_PACK32,
gli::FORMAT_RGBA8_SNORM_PACK32,
gli::FORMAT_RGBA8_USCALED_PACK32,
gli::FORMAT_RGBA8_SSCALED_PACK32,
gli::FORMAT_RGBA8_UINT_PACK32,
gli::FORMAT_RGBA8_SINT_PACK32,
gli::FORMAT_RGBA8_SRGB_PACK32,
gli::FORMAT_R16_UNORM_PACK16,
gli::FORMAT_R16_SNORM_PACK16,
gli::FORMAT_R16_USCALED_PACK16,
gli::FORMAT_R16_SSCALED_PACK16,
gli::FORMAT_R16_UINT_PACK16,
gli::FORMAT_R16_SINT_PACK16,
gli::FORMAT_R16_SFLOAT_PACK16,
// can not set image data
//gli::FORMAT_RG16_UNORM_PACK16,
//gli::FORMAT_RG16_SNORM_PACK16,
gli::FORMAT_RG16_USCALED_PACK16,
gli::FORMAT_RG16_SSCALED_PACK16,
gli::FORMAT_RG16_UINT_PACK16,
gli::FORMAT_RG16_SINT_PACK16,
gli::FORMAT_RG16_SFLOAT_PACK16,
gli::FORMAT_RGB16_UNORM_PACK16,
gli::FORMAT_RGB16_SNORM_PACK16,
gli::FORMAT_RGB16_USCALED_PACK16,
gli::FORMAT_RGB16_SSCALED_PACK16,
gli::FORMAT_RGB16_UINT_PACK16,
gli::FORMAT_RGB16_SINT_PACK16,
gli::FORMAT_RGB16_SFLOAT_PACK16,
gli::FORMAT_RGBA16_UNORM_PACK16,
// gli::FORMAT_RGBA16_SNORM_PACK16, // can not set image data
gli::FORMAT_RGBA16_USCALED_PACK16,
gli::FORMAT_RGBA16_SSCALED_PACK16,
gli::FORMAT_RGBA16_UINT_PACK16,
gli::FORMAT_RGBA16_SINT_PACK16,
gli::FORMAT_RGBA16_SFLOAT_PACK16,
gli::FORMAT_R32_UINT_PACK32,
gli::FORMAT_R32_SINT_PACK32,
gli::FORMAT_R32_SFLOAT_PACK32,
gli::FORMAT_RG32_UINT_PACK32,
gli::FORMAT_RG32_SINT_PACK32,
gli::FORMAT_RG32_SFLOAT_PACK32,
gli::FORMAT_RGB32_UINT_PACK32,
gli::FORMAT_RGB32_SINT_PACK32,
gli::FORMAT_RGB32_SFLOAT_PACK32,
gli::FORMAT_RGBA32_UINT_PACK32,
gli::FORMAT_RGBA32_SINT_PACK32,
gli::FORMAT_RGBA32_SFLOAT_PACK32,
gli::FORMAT_R64_UINT_PACK64,
gli::FORMAT_R64_SINT_PACK64,
gli::FORMAT_R64_SFLOAT_PACK64,
gli::FORMAT_RG64_UINT_PACK64,
gli::FORMAT_RG64_SINT_PACK64,
gli::FORMAT_RG64_SFLOAT_PACK64,
gli::FORMAT_RGB64_UINT_PACK64,
gli::FORMAT_RGB64_SINT_PACK64,
gli::FORMAT_RGB64_SFLOAT_PACK64,
gli::FORMAT_RGBA64_UINT_PACK64,
gli::FORMAT_RGBA64_SINT_PACK64,
gli::FORMAT_RGBA64_SFLOAT_PACK64,
//gli::FORMAT_D16_UNORM_PACK16,
//gli::FORMAT_D32_SFLOAT_PACK32,
//gli::FORMAT_S8_UINT_PACK8,
//gli::FORMAT_D16_UNORM_S8_UINT_PACK32,
//gli::FORMAT_D24_UNORM_S8_UINT_PACK32,
//gli::FORMAT_D32_SFLOAT_S8_UINT_PACK64,
gli::FORMAT_RGB_DXT1_UNORM_BLOCK8,
gli::FORMAT_RGB_DXT1_SRGB_BLOCK8,
gli::FORMAT_RGBA_DXT1_UNORM_BLOCK8,
gli::FORMAT_RGBA_DXT1_SRGB_BLOCK8,
gli::FORMAT_RGBA_DXT3_UNORM_BLOCK16,
gli::FORMAT_RGBA_DXT3_SRGB_BLOCK16,
gli::FORMAT_RGBA_DXT5_UNORM_BLOCK16,
gli::FORMAT_RGBA_DXT5_SRGB_BLOCK16,
gli::FORMAT_RGB_ETC2_UNORM_BLOCK8,
gli::FORMAT_RGB_ETC2_SRGB_BLOCK8,
// compression error: the expected data size does not match the suggested data
//gli::FORMAT_RGBA_ETC2_UNORM_BLOCK8,
//gli::FORMAT_RGBA_ETC2_SRGB_BLOCK8,
// EAC formats are not supported
//gli::FORMAT_R_EAC_UNORM_BLOCK8,
//gli::FORMAT_R_EAC_SNORM_BLOCK8,
//gli::FORMAT_RG_EAC_UNORM_BLOCK16,
//gli::FORMAT_RG_EAC_SNORM_BLOCK16,
gli::FORMAT_RGBA_ASTC_4X4_UNORM_BLOCK16,
gli::FORMAT_RGBA_ASTC_4X4_SRGB_BLOCK16,
gli::FORMAT_RGBA_ASTC_5X4_UNORM_BLOCK16,
gli::FORMAT_RGBA_ASTC_5X4_SRGB_BLOCK16,
gli::FORMAT_RGBA_ASTC_5X5_UNORM_BLOCK16,
gli::FORMAT_RGBA_ASTC_5X5_SRGB_BLOCK16,
gli::FORMAT_RGBA_ASTC_6X5_UNORM_BLOCK16,
gli::FORMAT_RGBA_ASTC_6X5_SRGB_BLOCK16,
gli::FORMAT_RGBA_ASTC_6X6_UNORM_BLOCK16,
gli::FORMAT_RGBA_ASTC_6X6_SRGB_BLOCK16,
gli::FORMAT_RGBA_ASTC_8X5_UNORM_BLOCK16,
gli::FORMAT_RGBA_ASTC_8X5_SRGB_BLOCK16,
gli::FORMAT_RGBA_ASTC_8X6_UNORM_BLOCK16,
gli::FORMAT_RGBA_ASTC_8X6_SRGB_BLOCK16,
gli::FORMAT_RGBA_ASTC_8X8_UNORM_BLOCK16,
gli::FORMAT_RGBA_ASTC_8X8_SRGB_BLOCK16,
gli::FORMAT_RGBA_ASTC_10X5_UNORM_BLOCK16,
gli::FORMAT_RGBA_ASTC_10X5_SRGB_BLOCK16,
gli::FORMAT_RGBA_ASTC_10X6_UNORM_BLOCK16,
gli::FORMAT_RGBA_ASTC_10X6_SRGB_BLOCK16,
gli::FORMAT_RGBA_ASTC_10X8_UNORM_BLOCK16,
gli::FORMAT_RGBA_ASTC_10X8_SRGB_BLOCK16,
gli::FORMAT_RGBA_ASTC_10X10_UNORM_BLOCK16,
gli::FORMAT_RGBA_ASTC_10X10_SRGB_BLOCK16,
gli::FORMAT_RGBA_ASTC_12X10_UNORM_BLOCK16,
gli::FORMAT_RGBA_ASTC_12X10_SRGB_BLOCK16,
gli::FORMAT_RGBA_ASTC_12X12_UNORM_BLOCK16,
gli::FORMAT_RGBA_ASTC_12X12_SRGB_BLOCK16,
// compressed and not yet supported
//gli::FORMAT_RGB_PVRTC1_8X8_UNORM_BLOCK32,
//gli::FORMAT_A8_UNORM_PACK8,
//gli::FORMAT_LA8_UNORM_PACK8,
//gli::FORMAT_A16_UNORM_PACK16,
//gli::FORMAT_LA16_UNORM_PACK16,
// can not set image data
//gli::FORMAT_BGR8_UNORM_PACK32,
//gli::FORMAT_BGR8_SRGB_PACK32,
//gli::FORMAT_D24_UNORM_PACK32,
gli::FORMAT_R_ATI1N_UNORM_BLOCK8,
gli::FORMAT_R_ATI1N_SNORM_BLOCK8,
gli::FORMAT_RG_ATI2N_UNORM_BLOCK16,
gli::FORMAT_RG_ATI2N_SNORM_BLOCK16,
gli::FORMAT_RGB_BP_UFLOAT_BLOCK16,
gli::FORMAT_RGB_BP_SFLOAT_BLOCK16,
gli::FORMAT_RGBA_BP_UNORM_BLOCK16,
gli::FORMAT_RGBA_BP_SRGB_BLOCK16,
// ETC2 Block16 formats are not supported
//gli::FORMAT_RGBA_ETC2_UNORM_BLOCK16,
//gli::FORMAT_RGBA_ETC2_SRGB_BLOCK16,
};
} | 52.200461 | 123 | 0.804767 | [
"vector"
] |
6c36124dc28cc75c30039d07607629430cf3d025 | 1,829 | cpp | C++ | ishxiao/1026/12598332_AC_188MS_140K.cpp | ishx/poj | b4e5498117d7c8fc3d96eca2fa7f71f2dfa13c2d | [
"MIT"
] | null | null | null | ishxiao/1026/12598332_AC_188MS_140K.cpp | ishx/poj | b4e5498117d7c8fc3d96eca2fa7f71f2dfa13c2d | [
"MIT"
] | null | null | null | ishxiao/1026/12598332_AC_188MS_140K.cpp | ishx/poj | b4e5498117d7c8fc3d96eca2fa7f71f2dfa13c2d | [
"MIT"
] | null | null | null | //1026
#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <cstring>
#include <algorithm>
#include <string>
#include <map>
#include <set>
#define CL(arr, val) memset(arr, val, sizeof(arr))
#define REP(i, n) for((i) = 0; (i) < (n); ++(i))
#define FOR(i, l, h) for((i) = (l); (i) <= (h); ++(i))
#define FORD(i, h, l) for((i) = (h); (i) >= (l); --(i))
#define L(x) (x) << 1
#define R(x) (x) << 1 | 1
#define MID(l, r) (l + r) >> 1
#define Min(x, y) x < y ? x : y
#define Max(x, y) x < y ? y : x
#define E(x) (1 << (x))
typedef long long LL;
using namespace std;
const int N = 210;
char str[N];
char ans[N];
int a[N];
int vis[N];
int n, k;
void solve() {
int i, tmp;
CL(vis, 0);
for(i = 0; i < n; ++i) {
if(!vis[a[i]]) {
tmp = a[i]; vis[a[i]] ++;
while(tmp != i) {
vis[a[i]] ++;
tmp = a[tmp];
}
}
}
int pos;
for(i = 0; i < n; ++i) {
tmp = k%vis[a[i]];
pos = a[i];
while(tmp --) pos = a[pos];
ans[pos] = str[i];
}
}
int main() {
//freopen("data.in", "r", stdin);
int i, l, x;
while(scanf("%d", &n), n) {
CL(a, 0);
for(i = 0; i < n; ++i) {
scanf("%d", &x);
a[i] = x-1;
}
while(scanf("%d", &k), k) {
getchar();
gets(str);
k--;
l = strlen(str);
if(l < n) {
for(i = l; i < n; ++i) str[i] = ' ';
}
solve();
for(i = 0; i < n; ++i) {
printf("%c", ans[i]);
}
putchar('\n');
}
putchar('\n');
}
return 0;
} | 22.304878 | 58 | 0.360306 | [
"vector"
] |
6c41e4c5e64448ab8df643c7312826d99b16bc3f | 5,287 | cpp | C++ | src/core/Core/Config/ParameterBuilder.cpp | krieselreihe/litr | ffaa7ecd09bfede01f5eb6edc957562363eadfc2 | [
"MIT"
] | 3 | 2020-11-26T15:46:48.000Z | 2021-08-16T11:12:48.000Z | src/core/Core/Config/ParameterBuilder.cpp | krieselreihe/litr | ffaa7ecd09bfede01f5eb6edc957562363eadfc2 | [
"MIT"
] | 57 | 2020-09-21T08:00:29.000Z | 2022-03-31T18:46:29.000Z | src/core/Core/Config/ParameterBuilder.cpp | krieselreihe/litr | ffaa7ecd09bfede01f5eb6edc957562363eadfc2 | [
"MIT"
] | null | null | null | #include "ParameterBuilder.hpp"
#include "Core/Debug/Instrumentor.hpp"
#include "Core/Error/Handler.hpp"
#include "Core/Log.hpp"
namespace Litr::Config {
ParameterBuilder::ParameterBuilder(const toml::table& file, const toml::value& data, const std::string& name)
: m_File(file), m_Table(data), m_Parameter(CreateRef<Parameter>(name)) {
LITR_CORE_TRACE("Creating {}", *m_Parameter);
}
void ParameterBuilder::AddDescription() {
LITR_PROFILE_FUNCTION();
const std::string name{"description"};
if (!m_Table.contains(name)) {
Error::Handler::Push(Error::MalformedParamError(
R"(You're missing the "description" field.)",
m_File.at(m_Parameter->Name)
));
return;
}
const toml::value& description{toml::find(m_Table, name)};
if (!description.is_string()) {
Error::Handler::Push(Error::MalformedParamError(
fmt::format(R"(The "{}" can only be a string.)", name),
m_Table.at(name)
));
return;
}
m_Parameter->Description = description.as_string();
}
void ParameterBuilder::AddDescription(const std::string& description) {
LITR_PROFILE_FUNCTION();
m_Parameter->Description = description;
}
void ParameterBuilder::AddShortcut() {
AddShortcut({});
}
void ParameterBuilder::AddShortcut(const std::vector<Ref<Parameter>>& params) {
LITR_PROFILE_FUNCTION();
const std::string name{"shortcut"};
if (m_Table.contains(name)) {
const toml::value& shortcut{toml::find(m_Table, name)};
if (shortcut.is_string()) {
const std::string shortcutStr{shortcut.as_string()};
if (IsReservedName(shortcutStr)) {
Error::Handler::Push(Error::ReservedParamError(
fmt::format(R"(The shortcut name "{}" is reserved by Litr.)", shortcutStr),
m_Table.at(name)
));
return;
}
for (auto&& param : params) {
if (param->Shortcut == shortcutStr) {
Error::Handler::Push(Error::ValueAlreadyInUseError(
fmt::format(
R"(The shortcut name "{}" is already used for parameter "{}".)", shortcutStr, param->Name),
m_Table.at(name)
));
return;
}
}
m_Parameter->Shortcut = shortcutStr;
return;
}
Error::Handler::Push(Error::MalformedParamError(
fmt::format(R"(A "{}" can only be a string.)", name),
m_Table.at(name)
));
}
}
void ParameterBuilder::AddType() {
LITR_PROFILE_FUNCTION();
const std::string name{"type"};
if (m_Table.contains(name)) {
const toml::value& type{toml::find(m_Table, name)};
if (type.is_string()) {
if (type.as_string() == "string") {
m_Parameter->Type = Parameter::Type::STRING;
} else if (type.as_string() == "boolean") {
m_Parameter->Type = Parameter::Type::BOOLEAN;
} else {
Error::Handler::Push(Error::UnknownParamValueError(
fmt::format(
R"(The "{}" option as string can only be "string" or "boolean". Provided value "{}" is not known.)",
name, static_cast<std::string>(type.as_string())),
m_Table.at(name)
));
}
return;
}
if (type.is_array()) {
m_Parameter->Type = Parameter::Type::ARRAY;
for (auto&& option : type.as_array()) {
if (option.is_string()) {
m_Parameter->TypeArguments.emplace_back(option.as_string());
} else {
Error::Handler::Push(Error::MalformedParamError(
fmt::format(R"(The options provided in "{}" are not all strings.)", name),
m_Table.at(name)
));
}
}
return;
}
Error::Handler::Push(Error::MalformedParamError(
fmt::format(
R"(A "{}" can only be "string" or an array of options as strings.)", name),
m_Table.at(name)
));
}
}
void ParameterBuilder::AddDefault() {
LITR_PROFILE_FUNCTION();
const std::string name{"default"};
if (m_Table.contains(name)) {
const toml::value& def{toml::find(m_Table, name)};
if (def.is_string()) {
const std::string defaultValue{def.as_string()};
// Test if default value present in available options
if (m_Parameter->Type == Parameter::Type::ARRAY) {
const std::vector<std::string>& args{m_Parameter->TypeArguments};
if (std::find(args.begin(), args.end(), defaultValue) == args.end()) {
Error::Handler::Push(Error::MalformedParamError(
fmt::format(
R"(Cannot find default value "{}" inside "type" list defined in line {}.)",
defaultValue,
m_Table.at("type").location().line()
),
m_Table.at(name)
));
return;
}
}
m_Parameter->Default = defaultValue;
return;
}
Error::Handler::Push(Error::MalformedParamError(
fmt::format(R"(The field "{}" needs to be a string.)", name),
m_Table.at(name)
));
}
}
bool ParameterBuilder::IsReservedName(const std::string& name) {
LITR_PROFILE_FUNCTION();
const std::array<std::string, 4> reserved{
"help", "h",
"or", "and"
};
return std::find(reserved.begin(), reserved.end(), name) != reserved.end();
}
} // namespace Litr::Config
| 28.272727 | 116 | 0.594666 | [
"vector"
] |
6c493a94f35bdcd6bedbd570a7ba767f8db9ee56 | 3,240 | hpp | C++ | headers/select.hpp | elfring/libsocket | 3d54f82c5c5bc28aec289dab9d333030d67b3bb5 | [
"BSD-2-Clause"
] | 1 | 2017-05-20T13:53:45.000Z | 2017-05-20T13:53:45.000Z | headers/select.hpp | elfring/libsocket | 3d54f82c5c5bc28aec289dab9d333030d67b3bb5 | [
"BSD-2-Clause"
] | null | null | null | headers/select.hpp | elfring/libsocket | 3d54f82c5c5bc28aec289dab9d333030d67b3bb5 | [
"BSD-2-Clause"
] | 3 | 2015-01-08T12:31:26.000Z | 2020-09-02T13:46:26.000Z | # ifndef SELECT_H
# define SELECT_H
# include <vector>
# include <map>
# include <utility>
# include <list>
# include <cstring>
# include <sys/select.h>
/**
* @file select.hpp
*
* The class selectset provides a possibility to wait for data on multiple sockets.
*/
/*
The committers of the libsocket project, all rights reserved
(c) 2012, dermesser <lbo@spheniscida.de>
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
# include "socket.hpp"
namespace libsocket
{
/** @addtogroup libsocketplusplus
* @{
*/
/**
* @brief selectset provides a simple interface to the system call select(3).
*
* To watch different sockets for new data to read or a possibility to write without using threads, use
* this class. It is rather simple to use; add file descriptors (socket ids) using `add_fd()` specifying
* whether to watch them for reading or writing and then call `wait()`; once there's data to be read or written
* it returns a std::pair with vectors of `libsocket::socket*`, the first vector contains sockets ready for reading,
* the second one contains those sockets ready for writing. Usually it's necessary to cast them to the actual socket type
* using `dynamic_cast<>()`.
*/
class selectset
{
private:
std::vector<int> filedescriptors; ///< All file descriptors from the socket objects
std::map<int,socket*> fdsockmap; ///< A map containing the relations between the filedescriptors and the socket objects
bool set_up; ///< Stores if the class has been initiated
fd_set readset; ///< The fd_set for select with the descriptors waiting for read
fd_set writeset; ///< and the descriptors waiting for write
public:
selectset();
void add_fd(socket& sock, int method);
std::pair<std::vector<socket*>, std::vector<socket*> > wait(long long microsecs=0);
};
typedef std::pair<std::vector<libsocket::socket*>, std::vector<libsocket::socket*> > ready_socks;
/**
* @}
*/
}
#endif
| 38.571429 | 125 | 0.72284 | [
"vector"
] |
6c54fc550974b2ad6bdb1aec116983d580b584f4 | 10,171 | cc | C++ | cc/layer_sorter_unittest.cc | jianglong0156/chromium.src | d496dfeebb0f282468827654c2b3769b3378c087 | [
"BSD-3-Clause"
] | 5 | 2018-03-10T13:08:42.000Z | 2021-07-26T15:02:11.000Z | cc/layer_sorter_unittest.cc | sanyaade-mobiledev/chromium.src | d496dfeebb0f282468827654c2b3769b3378c087 | [
"BSD-3-Clause"
] | 1 | 2015-07-21T08:02:01.000Z | 2015-07-21T08:02:01.000Z | cc/layer_sorter_unittest.cc | jianglong0156/chromium.src | d496dfeebb0f282468827654c2b3769b3378c087 | [
"BSD-3-Clause"
] | 6 | 2016-11-14T10:13:35.000Z | 2021-01-23T15:29:53.000Z | // Copyright 2011 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 "config.h"
#include "cc/layer_sorter.h"
#include "cc/layer_impl.h"
#include "cc/math_util.h"
#include "cc/single_thread_proxy.h"
#include "testing/gtest/include/gtest/gtest.h"
#include <public/WebTransformationMatrix.h>
using namespace cc;
using WebKit::WebTransformationMatrix;
namespace {
// Note: In the following overlap tests, the "camera" is looking down the negative Z axis,
// meaning that layers with smaller z values (more negative) are further from the camera
// and therefore must be drawn before layers with higher z values.
TEST(LayerSorterTest, BasicOverlap)
{
LayerSorter::ABCompareResult overlapResult;
const float zThreshold = 0.1f;
float weight = 0;
// Trivial test, with one layer directly obscuring the other.
WebTransformationMatrix neg4Translate;
neg4Translate.translate3d(0, 0, -4);
LayerShape front(2, 2, neg4Translate);
WebTransformationMatrix neg5Translate;
neg5Translate.translate3d(0, 0, -5);
LayerShape back(2, 2, neg5Translate);
overlapResult = LayerSorter::checkOverlap(&front, &back, zThreshold, weight);
EXPECT_EQ(LayerSorter::BBeforeA, overlapResult);
EXPECT_EQ(1, weight);
overlapResult = LayerSorter::checkOverlap(&back, &front, zThreshold, weight);
EXPECT_EQ(LayerSorter::ABeforeB, overlapResult);
EXPECT_EQ(1, weight);
// One layer translated off to the right. No overlap should be detected.
WebTransformationMatrix rightTranslate;
rightTranslate.translate3d(10, 0, -5);
LayerShape backRight(2, 2, rightTranslate);
overlapResult = LayerSorter::checkOverlap(&front, &backRight, zThreshold, weight);
EXPECT_EQ(LayerSorter::None, overlapResult);
// When comparing a layer with itself, z difference is always 0.
overlapResult = LayerSorter::checkOverlap(&front, &front, zThreshold, weight);
EXPECT_EQ(0, weight);
}
TEST(LayerSorterTest, RightAngleOverlap)
{
LayerSorter::ABCompareResult overlapResult;
const float zThreshold = 0.1f;
float weight = 0;
WebTransformationMatrix perspectiveMatrix;
perspectiveMatrix.applyPerspective(1000);
// Two layers forming a right angle with a perspective viewing transform.
WebTransformationMatrix leftFaceMatrix;
leftFaceMatrix.rotate3d(0, 1, 0, -90);
leftFaceMatrix.translateRight3d(-1, 0, -5);
leftFaceMatrix.translate(-1, -1);
LayerShape leftFace(2, 2, perspectiveMatrix * leftFaceMatrix);
WebTransformationMatrix frontFaceMatrix;
frontFaceMatrix.translate3d(0, 0, -4);
frontFaceMatrix.translate(-1, -1);
LayerShape frontFace(2, 2, perspectiveMatrix * frontFaceMatrix);
overlapResult = LayerSorter::checkOverlap(&frontFace, &leftFace, zThreshold, weight);
EXPECT_EQ(LayerSorter::BBeforeA, overlapResult);
}
TEST(LayerSorterTest, IntersectingLayerOverlap)
{
LayerSorter::ABCompareResult overlapResult;
const float zThreshold = 0.1f;
float weight = 0;
WebTransformationMatrix perspectiveMatrix;
perspectiveMatrix.applyPerspective(1000);
// Intersecting layers. An explicit order will be returned based on relative z
// values at the overlapping features but the weight returned should be zero.
WebTransformationMatrix frontFaceMatrix;
frontFaceMatrix.translate3d(0, 0, -4);
frontFaceMatrix.translate(-1, -1);
LayerShape frontFace(2, 2, perspectiveMatrix * frontFaceMatrix);
WebTransformationMatrix throughMatrix;
throughMatrix.rotate3d(0, 1, 0, 45);
throughMatrix.translateRight3d(0, 0, -4);
throughMatrix.translate(-1, -1);
LayerShape rotatedFace(2, 2, perspectiveMatrix * throughMatrix);
overlapResult = LayerSorter::checkOverlap(&frontFace, &rotatedFace, zThreshold, weight);
EXPECT_NE(LayerSorter::None, overlapResult);
EXPECT_EQ(0, weight);
}
TEST(LayerSorterTest, LayersAtAngleOverlap)
{
LayerSorter::ABCompareResult overlapResult;
const float zThreshold = 0.1f;
float weight = 0;
// Trickier test with layers at an angle.
//
// -x . . . . 0 . . . . +x
// -z /
// : /----B----
// 0 C
// : ----A----/
// +z /
//
// C is in front of A and behind B (not what you'd expect by comparing centers).
// A and B don't overlap, so they're incomparable.
WebTransformationMatrix transformA;
transformA.translate3d(-6, 0, 1);
transformA.translate(-4, -10);
LayerShape layerA(8, 20, transformA);
WebTransformationMatrix transformB;
transformB.translate3d(6, 0, -1);
transformB.translate(-4, -10);
LayerShape layerB(8, 20, transformB);
WebTransformationMatrix transformC;
transformC.rotate3d(0, 1, 0, 40);
transformC.translate(-4, -10);
LayerShape layerC(8, 20, transformC);
overlapResult = LayerSorter::checkOverlap(&layerA, &layerC, zThreshold, weight);
EXPECT_EQ(LayerSorter::ABeforeB, overlapResult);
overlapResult = LayerSorter::checkOverlap(&layerC, &layerB, zThreshold, weight);
EXPECT_EQ(LayerSorter::ABeforeB, overlapResult);
overlapResult = LayerSorter::checkOverlap(&layerA, &layerB, zThreshold, weight);
EXPECT_EQ(LayerSorter::None, overlapResult);
}
TEST(LayerSorterTest, LayersUnderPathologicalPerspectiveTransform)
{
LayerSorter::ABCompareResult overlapResult;
const float zThreshold = 0.1f;
float weight = 0;
// On perspective projection, if w becomes negative, the re-projected point will be
// invalid and un-usable. Correct code needs to clip away portions of the geometry
// where w < 0. If the code uses the invalid value, it will think that a layer has
// different bounds than it really does, which can cause things to sort incorrectly.
WebTransformationMatrix perspectiveMatrix;
perspectiveMatrix.applyPerspective(1);
WebTransformationMatrix transformA;
transformA.translate3d(-15, 0, -2);
transformA.translate(-5, -5);
LayerShape layerA(10, 10, perspectiveMatrix * transformA);
// With this sequence of transforms, when layer B is correctly clipped, it will be
// visible on the left half of the projection plane, in front of layerA. When it is
// not clipped, its bounds will actually incorrectly appear much smaller and the
// correct sorting dependency will not be found.
WebTransformationMatrix transformB;
transformB.translate3d(0, 0, 0.7);
transformB.rotate3d(0, 45, 0);
transformB.translate(-5, -5);
LayerShape layerB(10, 10, perspectiveMatrix * transformB);
// Sanity check that the test case actually covers the intended scenario, where part
// of layer B go behind the w = 0 plane.
FloatQuad testQuad = FloatQuad(gfx::RectF(-0.5, -0.5, 1, 1));
bool clipped = false;
MathUtil::mapQuad(perspectiveMatrix * transformB, testQuad, clipped);
ASSERT_TRUE(clipped);
overlapResult = LayerSorter::checkOverlap(&layerA, &layerB, zThreshold, weight);
EXPECT_EQ(LayerSorter::ABeforeB, overlapResult);
}
TEST(LayerSorterTest, verifyExistingOrderingPreservedWhenNoZDiff)
{
DebugScopedSetImplThread thisScopeIsOnImplThread;
// If there is no reason to re-sort the layers (i.e. no 3d z difference), then the
// existing ordering provided on input should be retained. This test covers the fix in
// https://bugs.webkit.org/show_bug.cgi?id=75046. Before this fix, ordering was
// accidentally reversed, causing bugs in z-index ordering on websites when
// preserves3D triggered the LayerSorter.
// Input list of layers: [1, 2, 3, 4, 5].
// Expected output: [3, 4, 1, 2, 5].
// - 1, 2, and 5 do not have a 3d z difference, and therefore their relative ordering should be retained.
// - 3 and 4 do not have a 3d z difference, and therefore their relative ordering should be retained.
// - 3 and 4 should be re-sorted so they are in front of 1, 2, and 5.
scoped_ptr<LayerImpl> layer1 = LayerImpl::create(1);
scoped_ptr<LayerImpl> layer2 = LayerImpl::create(2);
scoped_ptr<LayerImpl> layer3 = LayerImpl::create(3);
scoped_ptr<LayerImpl> layer4 = LayerImpl::create(4);
scoped_ptr<LayerImpl> layer5 = LayerImpl::create(5);
WebTransformationMatrix BehindMatrix;
BehindMatrix.translate3d(0, 0, 2);
WebTransformationMatrix FrontMatrix;
FrontMatrix.translate3d(0, 0, 1);
layer1->setBounds(gfx::Size(10, 10));
layer1->setContentBounds(gfx::Size(10, 10));
layer1->setDrawTransform(BehindMatrix);
layer1->setDrawsContent(true);
layer2->setBounds(gfx::Size(20, 20));
layer2->setContentBounds(gfx::Size(20, 20));
layer2->setDrawTransform(BehindMatrix);
layer2->setDrawsContent(true);
layer3->setBounds(gfx::Size(30, 30));
layer3->setContentBounds(gfx::Size(30, 30));
layer3->setDrawTransform(FrontMatrix);
layer3->setDrawsContent(true);
layer4->setBounds(gfx::Size(40, 40));
layer4->setContentBounds(gfx::Size(40, 40));
layer4->setDrawTransform(FrontMatrix);
layer4->setDrawsContent(true);
layer5->setBounds(gfx::Size(50, 50));
layer5->setContentBounds(gfx::Size(50, 50));
layer5->setDrawTransform(BehindMatrix);
layer5->setDrawsContent(true);
std::vector<LayerImpl*> layerList;
layerList.push_back(layer1.get());
layerList.push_back(layer2.get());
layerList.push_back(layer3.get());
layerList.push_back(layer4.get());
layerList.push_back(layer5.get());
ASSERT_EQ(static_cast<size_t>(5), layerList.size());
EXPECT_EQ(1, layerList[0]->id());
EXPECT_EQ(2, layerList[1]->id());
EXPECT_EQ(3, layerList[2]->id());
EXPECT_EQ(4, layerList[3]->id());
EXPECT_EQ(5, layerList[4]->id());
LayerSorter layerSorter;
layerSorter.sort(layerList.begin(), layerList.end());
ASSERT_EQ(static_cast<size_t>(5), layerList.size());
EXPECT_EQ(3, layerList[0]->id());
EXPECT_EQ(4, layerList[1]->id());
EXPECT_EQ(1, layerList[2]->id());
EXPECT_EQ(2, layerList[3]->id());
EXPECT_EQ(5, layerList[4]->id());
}
} // namespace
| 37.951493 | 112 | 0.70878 | [
"geometry",
"vector",
"transform",
"3d"
] |
6c5dc853939592b45abbdff2235315246346e890 | 4,172 | cpp | C++ | src/gdal_linestring.cpp | blairdgeo/node-gdal | a9bb3c082b30605ed1668dd9fe49afd25a7bb9d6 | [
"Apache-2.0"
] | 1 | 2015-07-04T20:09:20.000Z | 2015-07-04T20:09:20.000Z | src/gdal_linestring.cpp | blairdgeo/node-gdal | a9bb3c082b30605ed1668dd9fe49afd25a7bb9d6 | [
"Apache-2.0"
] | null | null | null | src/gdal_linestring.cpp | blairdgeo/node-gdal | a9bb3c082b30605ed1668dd9fe49afd25a7bb9d6 | [
"Apache-2.0"
] | null | null | null |
#include "gdal_common.hpp"
#include "gdal_geometry.hpp"
#include "gdal_linestring.hpp"
#include "gdal_point.hpp"
#include "collections/linestring_points.hpp"
#include <stdlib.h>
namespace node_gdal {
Persistent<FunctionTemplate> LineString::constructor;
void LineString::Initialize(Handle<Object> target)
{
NanScope();
Local<FunctionTemplate> lcons = NanNew<FunctionTemplate>(LineString::New);
lcons->Inherit(NanNew(Geometry::constructor));
lcons->InstanceTemplate()->SetInternalFieldCount(1);
lcons->SetClassName(NanNew("LineString"));
NODE_SET_PROTOTYPE_METHOD(lcons, "toString", toString);
NODE_SET_PROTOTYPE_METHOD(lcons, "getLength", getLength);
NODE_SET_PROTOTYPE_METHOD(lcons, "value", value);
ATTR(lcons, "points", pointsGetter, READ_ONLY_SETTER);
target->Set(NanNew("LineString"), lcons->GetFunction());
NanAssignPersistent(constructor, lcons);
}
LineString::LineString(OGRLineString *geom)
: ObjectWrap(),
this_(geom),
owned_(true),
size_(0)
{
LOG("Created LineString [%p]", geom);
}
LineString::LineString()
: ObjectWrap(),
this_(NULL),
owned_(true),
size_(0)
{
}
LineString::~LineString()
{
if(this_) {
LOG("Disposing LineString [%p] (%s)", this_, owned_ ? "owned" : "unowned");
if (owned_) {
OGRGeometryFactory::destroyGeometry(this_);
NanAdjustExternalMemory(-size_);
}
LOG("Disposed LineString [%p]", this_);
this_ = NULL;
}
}
/**
* Concrete representation of a multi-vertex line.
*
* @example
* ```
* var lineString = new gdal.LineString();
* lineString.points.add(new gdal.Point(0,0));
* lineString.points.add(new gdal.Point(0,10));```
*
* @constructor
* @class gdal.LineString
* @extends gdal.Geometry
*/
NAN_METHOD(LineString::New)
{
NanScope();
LineString *f;
if (!args.IsConstructCall()) {
NanThrowError("Cannot call constructor as function, you need to use 'new' keyword");
NanReturnUndefined();
}
if (args[0]->IsExternal()) {
Local<External> ext = args[0].As<External>();
void* ptr = ext->Value();
f = static_cast<LineString *>(ptr);
} else {
if (args.Length() != 0) {
NanThrowError("LineString constructor doesn't take any arguments");
NanReturnUndefined();
}
f = new LineString(new OGRLineString());
}
Handle<Value> points = LineStringPoints::New(args.This());
args.This()->SetHiddenValue(NanNew("points_"), points);
f->Wrap(args.This());
NanReturnValue(args.This());
}
Handle<Value> LineString::New(OGRLineString *geom)
{
NanEscapableScope();
return NanEscapeScope(LineString::New(geom, true));
}
Handle<Value> LineString::New(OGRLineString *geom, bool owned)
{
NanEscapableScope();
if (!geom) {
return NanEscapeScope(NanNull());
}
//make a copy of geometry owned by a feature
// + no need to track when a feature is destroyed
// + no need to throw errors when a method trys to modify an owned read-only geometry
// - is slower
if (!owned) {
geom = static_cast<OGRLineString*>(geom->clone());
};
LineString *wrapped = new LineString(geom);
wrapped->owned_ = true;
UPDATE_AMOUNT_OF_GEOMETRY_MEMORY(wrapped);
Handle<Value> ext = NanNew<External>(wrapped);
Handle<Object> obj = NanNew(LineString::constructor)->GetFunction()->NewInstance(1, &ext);
return NanEscapeScope(obj);
}
NAN_METHOD(LineString::toString)
{
NanScope();
NanReturnValue(NanNew("LineString"));
}
/**
* Computes the length of the line string.
*
* @method getLength
* @return Number
*/
NODE_WRAPPED_METHOD_WITH_RESULT(LineString, getLength, Number, get_Length);
/**
* Returns the point at the specified distance along the line string.
*
* @method value
* @param {Number} distance
* @return {gdal.Point}
*/
NAN_METHOD(LineString::value)
{
NanScope();
LineString *geom = ObjectWrap::Unwrap<LineString>(args.This());
OGRPoint *pt = new OGRPoint();
double dist;
NODE_ARG_DOUBLE(0, "distance", dist);
geom->this_->Value(dist, pt);
NanReturnValue(Point::New(pt));
}
/**
* Points that make up the line string.
*
* @attribute points
* @type {gdal.LineStringPoints}
*/
NAN_GETTER(LineString::pointsGetter)
{
NanScope();
NanReturnValue(args.This()->GetHiddenValue(NanNew("points_")));
}
} // namespace node_gdal | 21.957895 | 91 | 0.704698 | [
"geometry",
"object"
] |
484833dbb87017db4e2737d1451e3831d5417739 | 1,486 | cpp | C++ | src/main_profiling.cpp | dudu3107/cpp-life-of-boids | 89b1edcd35aa7c957e61d7131a06025f6cdbc71f | [
"Apache-2.0"
] | null | null | null | src/main_profiling.cpp | dudu3107/cpp-life-of-boids | 89b1edcd35aa7c957e61d7131a06025f6cdbc71f | [
"Apache-2.0"
] | null | null | null | src/main_profiling.cpp | dudu3107/cpp-life-of-boids | 89b1edcd35aa7c957e61d7131a06025f6cdbc71f | [
"Apache-2.0"
] | null | null | null | #ifndef __GNUC__
#pragma region declarations
#endif
#include <glad/glad.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <array>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>
#include "lib/myMath/Vec2.hpp"
#include "lib/myMath/utils.hpp"
#include "resources/model/Flock.hpp"
#include "resources/graphics/glx.hpp"
#include "resources/graphics/graphics.hpp"
#include "resources/graphics/GraphicalManager.hpp"
#include "resources/graphics/oglTypes.hpp"
#include "resources/controller/flock_generator.hpp"
#ifndef __GNUC__
#pragma endregion
#endif
Flock* MAIN_pFLOCK = nullptr;
std::vector<Agent*> mainFlock;
int main() {
int size = 600;
mainFlock.reserve(size);
Flock flock = generate_parrot_flock(size);
MAIN_pFLOCK = &flock;
long int t = 0;
do {
std::cout << "Tour " << t << '\n';
for (auto& bird : *MAIN_pFLOCK) {
std::tuple<std::vector<Agent*>, std::vector<Agent*>> allNeighbors =
(*MAIN_pFLOCK).computeNeighbors(*bird); //this costs performance
std::vector<Agent*> bVec = std::get<0>(allNeighbors);
std::vector<Agent*> eVec = std::get<1>(allNeighbors);
(*bird).computeLaws(bVec, eVec);
(*bird).prepareMove();
(*bird).setNextPosition(keepPositionInScreen((*bird).getNextPosition(), 800, 800));
(*bird).move();
}
++t;
} while (t <= 100);
return 0;
}
| 24.766667 | 95 | 0.643338 | [
"vector",
"model"
] |
484f29d5e21de1cfb4722e59690cea4fd7e81fe8 | 206 | hpp | C++ | src/VideoSystem.hpp | feliwir/openSage-deprecated | 4e6b3e7da577d37892cd0dfae31701c502247fb9 | [
"MIT"
] | 4 | 2018-11-22T23:15:23.000Z | 2021-04-27T06:55:24.000Z | src/VideoSystem.hpp | feliwir/openSage-deprecated | 4e6b3e7da577d37892cd0dfae31701c502247fb9 | [
"MIT"
] | null | null | null | src/VideoSystem.hpp | feliwir/openSage-deprecated | 4e6b3e7da577d37892cd0dfae31701c502247fb9 | [
"MIT"
] | 1 | 2019-08-27T13:02:59.000Z | 2019-08-27T13:02:59.000Z | // Stephan Vedder 2015
#pragma once
#include <vector>
#include <thread>
#include <memory>
#include "Loaders/Vp6Stream.hpp"
class VideoSystem
{
public:
static void initialize();
static void release();
}; | 14.714286 | 32 | 0.73301 | [
"vector"
] |
485484f0ae175b302e3d41e288ab92bbe96f8208 | 1,524 | cpp | C++ | scenes/inf585/06_skinning/src/skinning.cpp | DanonOfficial/inf585_vcl | 32eb10c3ddeba8192943381462b437c8490a8c92 | [
"MIT"
] | 1 | 2020-01-09T19:33:20.000Z | 2020-01-09T19:33:20.000Z | scenes/inf585/06_skinning/src/skinning.cpp | DanonOfficial/inf585_vcl | 32eb10c3ddeba8192943381462b437c8490a8c92 | [
"MIT"
] | null | null | null | scenes/inf585/06_skinning/src/skinning.cpp | DanonOfficial/inf585_vcl | 32eb10c3ddeba8192943381462b437c8490a8c92 | [
"MIT"
] | 6 | 2020-02-25T14:33:11.000Z | 2021-03-07T11:26:03.000Z | #include "skinning.hpp"
namespace vcl
{
void normalize_weights(buffer<buffer<float>>& weights)
{
size_t const N = weights.size();
for (size_t k = 0; k < N; ++k) {
float s = 0.0f;
for(float w : weights[k]) s += w;
assert_vcl_no_msg(s>1e-5f);
for(float& w : weights[k]) w /= s;
}
}
// Linear Blend Skinning
void skinning_LBS_compute(
buffer<vec3>& position_skinned, // position to deform
buffer<vec3>& normal_skinned, // normal to deform
buffer<affine_rt> const& skeleton_current, // rigid transforms for skeleton joints in current pose
buffer<affine_rt> const& skeleton_rest_pose, // rigid transforms of skeleton joints in rest pose
buffer<vec3> const& position_rest_pose, // vertex positions of the mesh in rest pose
buffer<vec3> const& normal_rest_pose, // normal coordinates of the mesh in rest pose
rig_structure const& rig) // information of the skinning weights (joints and weights associated to a vertex)
{
size_t const N_vertex = position_rest_pose.size();
size_t const N_joint = skeleton_current.size();
// Sanity check on sizes of buffers
assert_vcl_no_msg(position_skinned.size()==N_vertex);
assert_vcl_no_msg(normal_skinned.size()==N_vertex);
assert_vcl_no_msg(normal_rest_pose.size()==N_vertex);
assert_vcl_no_msg(skeleton_rest_pose.size()==N_joint);
assert_vcl_no_msg(rig.joint.size()==N_vertex);
assert_vcl_no_msg(rig.weight.size()==N_vertex);
// To do
// Compute the Linear Blend Skinning ...
}
} | 34.636364 | 130 | 0.707349 | [
"mesh"
] |
485f7e3c09a501eecc23bb4373bd8d6d4c171347 | 34,226 | cpp | C++ | vnpy/api/xtp/vnxtp/generated_files/generated_functions_0.cpp | andrewchenshx/vnpy | b479ade5262f1bac460f05811a9db92a5ed465f1 | [
"MIT"
] | 10 | 2019-06-18T04:52:38.000Z | 2019-12-29T03:11:15.000Z | vnpy/api/xtp/vnxtp/generated_files/generated_functions_0.cpp | andrewchenshx/vnpy | b479ade5262f1bac460f05811a9db92a5ed465f1 | [
"MIT"
] | null | null | null | vnpy/api/xtp/vnxtp/generated_files/generated_functions_0.cpp | andrewchenshx/vnpy | b479ade5262f1bac460f05811a9db92a5ed465f1 | [
"MIT"
] | 1 | 2020-07-21T05:54:49.000Z | 2020-07-21T05:54:49.000Z | #include <iostream>
#include <string>
#include <pybind11/pybind11.h>
#include <autocxxpy/autocxxpy.hpp>
#include "module.hpp"
#include "wrappers.hpp"
#include "generated_functions.h"
#include "xtp_trader_api.h"
#include "xtp_quote_api.h"
void generate_vnxtp(pybind11::module & parent)
{
{
auto m = parent.def_submodule("XTP");
generate_sub_namespace_XTP(m);
}
generate_class_XTPRspInfoStruct(parent);
generate_class_XTPSpecificTickerStruct(parent);
generate_class_XTPMarketDataStockExData(parent);
generate_class_XTPMarketDataOptionExData(parent);
generate_class_XTPMarketDataStruct(parent);
generate_class_XTPQuoteStaticInfo(parent);
generate_class_OrderBookStruct(parent);
generate_class_XTPTickByTickEntrust(parent);
generate_class_XTPTickByTickTrade(parent);
generate_class_XTPTickByTickStruct(parent);
generate_class_XTPTickerPriceInfo(parent);
generate_class_XTPOrderInsertInfo(parent);
generate_class_XTPOrderCancelInfo(parent);
generate_class_XTPOrderInfo(parent);
generate_class_XTPTradeReport(parent);
generate_class_XTPQueryOrderReq(parent);
generate_class_XTPQueryReportByExecIdReq(parent);
generate_class_XTPQueryTraderReq(parent);
generate_class_XTPQueryAssetRsp(parent);
generate_class_XTPQueryStkPositionRsp(parent);
generate_class_XTPFundTransferNotice(parent);
generate_class_XTPQueryFundTransferLogReq(parent);
generate_class_XTPQueryStructuredFundInfoReq(parent);
generate_class_XTPStructuredFundInfo(parent);
generate_class_XTPQueryETFBaseReq(parent);
generate_class_XTPQueryETFBaseRsp(parent);
generate_class_XTPQueryETFComponentReq(parent);
generate_class_XTPQueryETFComponentRsp(parent);
generate_class_XTPQueryIPOTickerRsp(parent);
generate_class_XTPQueryIPOQuotaRsp(parent);
generate_class_XTPQueryOptionAuctionInfoReq(parent);
generate_class_XTPQueryOptionAuctionInfoRsp(parent);
generate_class_XTPCrdCashRepayRsp(parent);
generate_class_XTPCrdCashRepayDebtInterestFeeRsp(parent);
generate_class_XTPCrdCashRepayInfo(parent);
generate_class_XTPCrdDebtInfo(parent);
generate_class_XTPCrdFundInfo(parent);
generate_class_XTPClientQueryCrdDebtStockReq(parent);
generate_class_XTPCrdDebtStockInfo(parent);
generate_class_XTPClientQueryCrdPositionStockReq(parent);
generate_class_XTPClientQueryCrdPositionStkInfo(parent);
generate_class_XTPClientQueryCrdSurplusStkReqInfo(parent);
generate_class_XTPClientQueryCrdSurplusStkRspInfo(parent);
generate_class_XTPClientCrdExtendDebtInfo(parent);
generate_class_XTPFundTransferReq(parent);
generate_enum_XTP_LOG_LEVEL(parent);
generate_enum_XTP_PROTOCOL_TYPE(parent);
generate_enum_XTP_EXCHANGE_TYPE(parent);
generate_enum_XTP_MARKET_TYPE(parent);
generate_enum_XTP_PRICE_TYPE(parent);
generate_enum_XTP_ORDER_ACTION_STATUS_TYPE(parent);
generate_enum_XTP_ORDER_STATUS_TYPE(parent);
generate_enum_XTP_ORDER_SUBMIT_STATUS_TYPE(parent);
generate_enum_XTP_TE_RESUME_TYPE(parent);
generate_enum_ETF_REPLACE_TYPE(parent);
generate_enum_XTP_TICKER_TYPE(parent);
generate_enum_XTP_BUSINESS_TYPE(parent);
generate_enum_XTP_ACCOUNT_TYPE(parent);
generate_enum_XTP_FUND_TRANSFER_TYPE(parent);
generate_enum_XTP_FUND_OPER_STATUS(parent);
generate_enum_XTP_SPLIT_MERGE_STATUS(parent);
generate_enum_XTP_TBT_TYPE(parent);
generate_enum_XTP_OPT_CALL_OR_PUT_TYPE(parent);
generate_enum_XTP_OPT_EXERCISE_TYPE_TYPE(parent);
generate_enum_XTP_POSITION_DIRECTION_TYPE(parent);
generate_enum_XTP_CRD_CR_STATUS(parent);
generate_enum_XTP_MARKETDATA_TYPE(parent);
parent.attr("XTP_VERSION_LEN") = XTP_VERSION_LEN;
parent.attr("XTP_TRADING_DAY_LEN") = XTP_TRADING_DAY_LEN;
parent.attr("XTP_TICKER_LEN") = XTP_TICKER_LEN;
parent.attr("XTP_TICKER_NAME_LEN") = XTP_TICKER_NAME_LEN;
parent.attr("XTP_LOCAL_ORDER_LEN") = XTP_LOCAL_ORDER_LEN;
parent.attr("XTP_ORDER_EXCH_LEN") = XTP_ORDER_EXCH_LEN;
parent.attr("XTP_EXEC_ID_LEN") = XTP_EXEC_ID_LEN;
parent.attr("XTP_BRANCH_PBU_LEN") = XTP_BRANCH_PBU_LEN;
parent.attr("XTP_ACCOUNT_NAME_LEN") = XTP_ACCOUNT_NAME_LEN;
parent.attr("XTP_CREDIT_DEBT_ID_LEN") = XTP_CREDIT_DEBT_ID_LEN;
parent.attr("XTP_SIDE_BUY") = XTP_SIDE_BUY;
parent.attr("XTP_SIDE_SELL") = XTP_SIDE_SELL;
parent.attr("XTP_SIDE_PURCHASE") = XTP_SIDE_PURCHASE;
parent.attr("XTP_SIDE_REDEMPTION") = XTP_SIDE_REDEMPTION;
parent.attr("XTP_SIDE_SPLIT") = XTP_SIDE_SPLIT;
parent.attr("XTP_SIDE_MERGE") = XTP_SIDE_MERGE;
parent.attr("XTP_SIDE_COVER") = XTP_SIDE_COVER;
parent.attr("XTP_SIDE_FREEZE") = XTP_SIDE_FREEZE;
parent.attr("XTP_SIDE_MARGIN_TRADE") = XTP_SIDE_MARGIN_TRADE;
parent.attr("XTP_SIDE_SHORT_SELL") = XTP_SIDE_SHORT_SELL;
parent.attr("XTP_SIDE_REPAY_MARGIN") = XTP_SIDE_REPAY_MARGIN;
parent.attr("XTP_SIDE_REPAY_STOCK") = XTP_SIDE_REPAY_STOCK;
parent.attr("XTP_SIDE_STOCK_REPAY_STOCK") = XTP_SIDE_STOCK_REPAY_STOCK;
parent.attr("XTP_SIDE_SURSTK_TRANS") = XTP_SIDE_SURSTK_TRANS;
parent.attr("XTP_SIDE_GRTSTK_TRANSIN") = XTP_SIDE_GRTSTK_TRANSIN;
parent.attr("XTP_SIDE_GRTSTK_TRANSOUT") = XTP_SIDE_GRTSTK_TRANSOUT;
parent.attr("XTP_SIDE_UNKNOWN") = XTP_SIDE_UNKNOWN;
parent.attr("XTP_POSITION_EFFECT_INIT") = XTP_POSITION_EFFECT_INIT;
parent.attr("XTP_POSITION_EFFECT_OPEN") = XTP_POSITION_EFFECT_OPEN;
parent.attr("XTP_POSITION_EFFECT_CLOSE") = XTP_POSITION_EFFECT_CLOSE;
parent.attr("XTP_POSITION_EFFECT_FORCECLOSE") = XTP_POSITION_EFFECT_FORCECLOSE;
parent.attr("XTP_POSITION_EFFECT_CLOSETODAY") = XTP_POSITION_EFFECT_CLOSETODAY;
parent.attr("XTP_POSITION_EFFECT_CLOSEYESTERDAY") = XTP_POSITION_EFFECT_CLOSEYESTERDAY;
parent.attr("XTP_POSITION_EFFECT_FORCEOFF") = XTP_POSITION_EFFECT_FORCEOFF;
parent.attr("XTP_POSITION_EFFECT_LOCALFORCECLOSE") = XTP_POSITION_EFFECT_LOCALFORCECLOSE;
parent.attr("XTP_POSITION_EFFECT_CREDIT_FORCE_COVER") = XTP_POSITION_EFFECT_CREDIT_FORCE_COVER;
parent.attr("XTP_POSITION_EFFECT_CREDIT_FORCE_CLEAR") = XTP_POSITION_EFFECT_CREDIT_FORCE_CLEAR;
parent.attr("XTP_POSITION_EFFECT_CREDIT_FORCE_DEBT") = XTP_POSITION_EFFECT_CREDIT_FORCE_DEBT;
parent.attr("XTP_POSITION_EFFECT_CREDIT_FORCE_UNCOND") = XTP_POSITION_EFFECT_CREDIT_FORCE_UNCOND;
parent.attr("XTP_POSITION_EFFECT_UNKNOWN") = XTP_POSITION_EFFECT_UNKNOWN;
parent.attr("XTP_TRDT_COMMON") = XTP_TRDT_COMMON;
parent.attr("XTP_TRDT_CASH") = XTP_TRDT_CASH;
parent.attr("XTP_TRDT_PRIMARY") = XTP_TRDT_PRIMARY;
parent.attr("XTP_TRDT_CROSS_MKT_CASH") = XTP_TRDT_CROSS_MKT_CASH;
parent.attr("XTP_ORDT_Normal") = XTP_ORDT_Normal;
parent.attr("XTP_ORDT_DeriveFromQuote") = XTP_ORDT_DeriveFromQuote;
parent.attr("XTP_ORDT_DeriveFromCombination") = XTP_ORDT_DeriveFromCombination;
parent.attr("XTP_ORDT_Combination") = XTP_ORDT_Combination;
parent.attr("XTP_ORDT_ConditionalOrder") = XTP_ORDT_ConditionalOrder;
parent.attr("XTP_ORDT_Swap") = XTP_ORDT_Swap;
parent.attr("XTP_ERR_MSG_LEN") = XTP_ERR_MSG_LEN;
parent.attr("XTP_ACCOUNT_PASSWORD_LEN") = XTP_ACCOUNT_PASSWORD_LEN;
module_vnxtp::cross.record_assign(parent, "XTPRI", "XTPRI", "::XTPRspInfoStruct");
module_vnxtp::cross.record_assign(parent, "XTPST", "XTPST", "::XTPSpecificTickerStruct");
module_vnxtp::cross.record_assign(parent, "XTPMD", "XTPMD", "::XTPMarketDataStruct");
module_vnxtp::cross.record_assign(parent, "XTPQSI", "XTPQSI", "::XTPQuoteStaticInfo");
module_vnxtp::cross.record_assign(parent, "XTPOB", "XTPOB", "::OrderBookStruct");
module_vnxtp::cross.record_assign(parent, "XTPTBT", "XTPTBT", "::XTPTickByTickStruct");
module_vnxtp::cross.record_assign(parent, "XTPTPI", "XTPTPI", "::XTPTickerPriceInfo");
module_vnxtp::cross.record_assign(parent, "XTPQueryOrderRsp", "XTPQueryOrderRsp", "::XTPOrderInfo");
module_vnxtp::cross.record_assign(parent, "XTPQueryTradeRsp", "XTPQueryTradeRsp", "::XTPTradeReport");
module_vnxtp::cross.record_assign(parent, "XTPFundTransferLog", "XTPFundTransferLog", "::XTPFundTransferNotice");
module_vnxtp::cross.record_assign(parent, "XTPQueryETFBaseRsp", "XTPQueryETFBaseRsp", "::XTPQueryETFBaseRsp");
module_vnxtp::cross.record_assign(parent, "XTPQueryETFComponentReq", "XTPQueryETFComponentReq", "::XTPQueryETFComponentReq");
module_vnxtp::cross.record_assign(parent, "XTPCrdDebtInfo", "XTPCrdDebtInfo", "::XTPCrdDebtInfo");
module_vnxtp::cross.record_assign(parent, "XTPCrdFundInfo", "XTPCrdFundInfo", "::XTPCrdFundInfo");
module_vnxtp::cross.record_assign(parent, "XTPClientQueryCrdDebtStockReq", "XTPClientQueryCrdDebtStockReq", "::XTPClientQueryCrdDebtStockReq");
module_vnxtp::cross.record_assign(parent, "XTPCrdDebtStockInfo", "XTPCrdDebtStockInfo", "::XTPCrdDebtStockInfo");
module_vnxtp::cross.record_assign(parent, "XTPClientQueryCrdPositionStockReq", "XTPClientQueryCrdPositionStockReq", "::XTPClientQueryCrdPositionStockReq");
module_vnxtp::cross.record_assign(parent, "XTPClientQueryCrdPositionStkInfo", "XTPClientQueryCrdPositionStkInfo", "::XTPClientQueryCrdPositionStkInfo");
module_vnxtp::cross.record_assign(parent, "XTPClientQueryCrdSurplusStkReqInfo", "XTPClientQueryCrdSurplusStkReqInfo", "::XTPClientQueryCrdSurplusStkReqInfo");
module_vnxtp::cross.record_assign(parent, "XTPClientQueryCrdSurplusStkRspInfo", "XTPClientQueryCrdSurplusStkRspInfo", "::XTPClientQueryCrdSurplusStkRspInfo");
module_vnxtp::cross.record_assign(parent, "XTPClientCrdExtendDebtInfo", "XTPClientCrdExtendDebtInfo", "::XTPClientCrdExtendDebtInfo");
module_vnxtp::cross.record_assign(parent, "XTPFundTransferAck", "XTPFundTransferAck", "::XTPFundTransferNotice");
generate_caster_(parent);
}
void generate_sub_namespace_XTP(pybind11::module & parent)
{
{
auto m = parent.def_submodule("API");
generate_sub_namespace_XTP_API(m);
}
generate_caster_XTP(parent);
}
void generate_sub_namespace_XTP_API(pybind11::module & parent)
{
generate_class_XTP_API_TraderSpi(parent);
generate_class_XTP_API_TraderApi(parent);
generate_class_XTP_API_QuoteSpi(parent);
generate_class_XTP_API_QuoteApi(parent);
generate_caster_XTP_API(parent);
}
void generate_class_XTP_API_TraderSpi(pybind11::object & parent)
{
pybind11::class_<XTP::API::TraderSpi, PyTraderSpi> c(parent, "TraderSpi");
if constexpr (std::is_default_constructible_v<PyTraderSpi>)
c.def(pybind11::init<>());
c.def("OnDisconnected",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnDisconnected
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnError",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnError
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnOrderEvent",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnOrderEvent
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnTradeEvent",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnTradeEvent
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnCancelOrderError",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnCancelOrderError
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnQueryOrder",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnQueryOrder
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnQueryTrade",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnQueryTrade
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnQueryPosition",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnQueryPosition
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnQueryAsset",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnQueryAsset
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnQueryStructuredFund",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnQueryStructuredFund
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnQueryFundTransfer",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnQueryFundTransfer
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnFundTransfer",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnFundTransfer
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnQueryETF",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnQueryETF
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnQueryETFBasket",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnQueryETFBasket
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnQueryIPOInfoList",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnQueryIPOInfoList
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnQueryIPOQuotaInfo",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnQueryIPOQuotaInfo
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnQueryOptionAuctionInfo",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnQueryOptionAuctionInfo
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnCreditCashRepay",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnCreditCashRepay
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnQueryCreditCashRepayInfo",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnQueryCreditCashRepayInfo
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnQueryCreditFundInfo",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnQueryCreditFundInfo
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnQueryCreditDebtInfo",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnQueryCreditDebtInfo
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnQueryCreditTickerDebtInfo",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnQueryCreditTickerDebtInfo
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnQueryCreditAssetDebtInfo",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnQueryCreditAssetDebtInfo
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnQueryCreditTickerAssignInfo",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnQueryCreditTickerAssignInfo
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnQueryCreditExcessStock",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderSpi::OnQueryCreditExcessStock
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTP::API::TraderSpi, c);
module_vnxtp::objects.emplace("XTP::API::TraderSpi", c);
}
void generate_class_XTP_API_TraderApi(pybind11::object & parent)
{
pybind11::class_<
XTP::API::TraderApi,
std::unique_ptr<XTP::API::TraderApi, pybind11::nodelete>,
PyTraderApi
> c(parent, "TraderApi");
if constexpr (std::is_default_constructible_v<PyTraderApi>)
c.def(pybind11::init<>());
c.def_static("CreateTraderApi",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::CreateTraderApi
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("Release",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::Release
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("GetTradingDay",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::GetTradingDay
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("RegisterSpi",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::RegisterSpi
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("GetApiLastError",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::GetApiLastError
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("GetApiVersion",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::GetApiVersion
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("GetClientIDByXTPID",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::GetClientIDByXTPID
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("GetAccountByXTPID",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::GetAccountByXTPID
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("SubscribePublicTopic",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::SubscribePublicTopic
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("SetSoftwareVersion",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::SetSoftwareVersion
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("SetSoftwareKey",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::SetSoftwareKey
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("SetHeartBeatInterval",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::SetHeartBeatInterval
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("Login",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::Login
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("Logout",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::Logout
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("InsertOrder",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::InsertOrder
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("CancelOrder",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::CancelOrder
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("QueryOrderByXTPID",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::QueryOrderByXTPID
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("QueryOrders",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::QueryOrders
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("QueryTradesByXTPID",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::QueryTradesByXTPID
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("QueryTrades",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::QueryTrades
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("QueryPosition",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::QueryPosition
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("QueryAsset",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::QueryAsset
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("QueryStructuredFund",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::QueryStructuredFund
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("FundTransfer",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::FundTransfer
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("QueryFundTransfer",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::QueryFundTransfer
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("QueryETF",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::QueryETF
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("QueryETFTickerBasket",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::QueryETFTickerBasket
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("QueryIPOInfoList",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::QueryIPOInfoList
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("QueryIPOQuotaInfo",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::QueryIPOQuotaInfo
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("QueryOptionAuctionInfo",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::QueryOptionAuctionInfo
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("CreditCashRepay",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::CreditCashRepay
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("QueryCreditCashRepayInfo",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::QueryCreditCashRepayInfo
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("QueryCreditFundInfo",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::QueryCreditFundInfo
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("QueryCreditDebtInfo",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::QueryCreditDebtInfo
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("QueryCreditTickerDebtInfo",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::QueryCreditTickerDebtInfo
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("QueryCreditAssetDebtInfo",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::QueryCreditAssetDebtInfo
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("QueryCreditTickerAssignInfo",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::QueryCreditTickerAssignInfo
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("QueryCreditExcessStock",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&XTP::API::TraderApi::QueryCreditExcessStock
>,
brigand::list<
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTP::API::TraderApi, c);
module_vnxtp::objects.emplace("XTP::API::TraderApi", c);
}
| 38.369955 | 162 | 0.64004 | [
"object"
] |
485f99a57abdd81ce481000fb14d95bf3079a5e2 | 7,182 | cpp | C++ | descriptor.cpp | ESIR2-IN-promo2017/local-textures-descriptors | e7e1696c4097a21b534e6701dcb5fda9cfa90c03 | [
"CECILL-B"
] | null | null | null | descriptor.cpp | ESIR2-IN-promo2017/local-textures-descriptors | e7e1696c4097a21b534e6701dcb5fda9cfa90c03 | [
"CECILL-B"
] | 1 | 2016-04-07T08:40:11.000Z | 2017-05-15T09:17:47.000Z | descriptor.cpp | ESIR2-IN-promo2017/local-textures-descriptors | e7e1696c4097a21b534e6701dcb5fda9cfa90c03 | [
"CECILL-B"
] | null | null | null | /**
* @file descriptor.cpp
* @brief
* @author Amaury Louarn
* @version 1.0
* @date 2016-03-08
*/
#include "descriptor.h"
const int TAILLE = 12;
float getPixel(cv::Mat const& mat, long i, long j)
{
unsigned int ii = (unsigned int) std::max(0l, std::min(i, (long) mat.rows));
unsigned int jj = (unsigned int) std::max(0l, std::min(j, (long) mat.cols));
return mat.at<float>(ii,jj);
}
TextureDescriptor::TextureDescriptor()
{
}
TextureDescriptor::TextureDescriptor(std::vector<cv::Mat> const& attribVector, unsigned int i, unsigned int j, cv::Mat const& ponderations, unsigned int r):
m_descriptor(this->calculateSize(attribVector.size()), 1, CV_32F)
{
float beta = 1/sum(ponderations)[0];
cv::Mat mu = calculMoyenne(attribVector, i, j, ponderations, beta, r);
cv::Mat crp = cv::Mat::zeros(attribVector.size(), attribVector.size(), CV_32F);
for(long qi = 0; qi < 2*r+1; ++qi)
for(long qj = 0; qj < 2*r+1; ++qj)
{
cv::Mat z = extractAttribVector(attribVector, i + qi - r, j + qj - r) - mu;
crp += (z * z.t()) * (ponderations.at<float>(qi, qj));
}
crp *= beta;
cv::Mat choleskyMatrix;
this->Cholesky(crp, choleskyMatrix);
extractDescriptorFromCholesky(choleskyMatrix);
}
double TextureDescriptor::distance(TextureDescriptor const& rhs) const
{
//TODO
std::cout << "--> TextureDescriptor::distance(this=" << this << ", rhs=" << &rhs << ")" << std::endl;
float sum = 0.0;
std::cout << "this: " << this->m_descriptor.t() << std::endl;
std::cout << "rhs: " << rhs.m_descriptor.t() << std::endl;
if(this->m_descriptor.rows != rhs.m_descriptor.rows)
return 0.0;
for(int i=0; i < this->m_descriptor.rows; i++) {
float tmp = this->m_descriptor.at<float>(i, 0) - rhs.m_descriptor.at<float>(i, 0);
sum += tmp * tmp;
}
std::cout << "<-- TextureDescriptor::distance(return = sqrt(" << sum << ")" << std::endl;
return std::sqrt(sum);
}
cv::Mat TextureDescriptor::extractAttribVector(std::vector<cv::Mat> const& attribVector, long i, long j)
{
cv::Mat retAttribVector(attribVector.size(), 1, CV_32F, cv::Scalar(0));
for(unsigned int it = 0; it < attribVector.size(); ++it)
retAttribVector.at<float>(it,0) = getPixel(attribVector[it], i, j);
return retAttribVector;
}
cv::Mat TextureDescriptor::calculMoyenne(std::vector<cv::Mat> const& attribVector, unsigned int i, unsigned int j, cv::Mat const& ponderations, double beta, unsigned int r)
{
cv::Mat mu(attribVector.size(), 1, CV_32F, cv::Scalar(0));
for(unsigned int ii = 0; ii < 2*r+1; ++ii)
for(unsigned int jj = 0; jj < 2*r+1; ++jj)
mu += ponderations.at<float>(ii,jj) * extractAttribVector(attribVector, (long) i + ii - r, (long) j + jj - r);
return mu * beta;
}
void TextureDescriptor::Cholesky(cv::Mat const& A, cv::Mat & S)
{
CV_Assert(A.type() == CV_32F);
int dim = A.rows;
S.create(dim, dim, CV_32F);
cv::Mat E, M;
cv::eigen(A, E, M);
cv::Mat Ebis= cv::Mat::diag(E);
//assert that every eigenvalue is > 0
for(int i=0; i<TAILLE; i++)
for(int j=0; j<TAILLE; j++)
if(Ebis.at<float>(i,j)<0.0)
Ebis.at<float>(i,j)=0.0;
cv::Mat Abis= M.t()*Ebis*M;
for(int i = 0; i < dim; i++ ){
for(int j = 0; j < i; j++ )
S.at<float>(i,j) = 0.f;
float sum = 0.f;
for(int k = 0; k < i; k++ )
{
float val = S.at<float>(k,i);
sum += val*val;
}
S.at<float>(i,i) = std::sqrt(std::max(Abis.at<float>(i,i) - sum, 0.f));
float ival = 1.f/S.at<float>(i, i);
for(int j = i + 1; j < dim; j++)
{
sum = 0;
for(int k = 0; k < i; k++ )
sum += S.at<float>(k, i) * S.at<float>(k, j);
S.at<float>(i, j) = (Abis.at<float>(i, j) - sum)*ival;
}
}
transpose(S,S);
}
void TextureDescriptor::extractDescriptorFromCholesky(cv::Mat const& choleskyMatrix)
{
unsigned int position = 0;
for(int col = 0; col < choleskyMatrix.cols; ++col)
for(int row = col; row < choleskyMatrix.rows; ++row)
m_descriptor.at<float>(1, position++) = choleskyMatrix.at<float>(col, row);
}
unsigned int TextureDescriptor::calculateSize(unsigned int size)
{
unsigned int length = 0;
for(unsigned int i = size; i > 0; --i)
length += i;
return length;
}
/*----DESCRIPTOR----*/
Descriptor::Descriptor(cv::Mat const& img, unsigned int r):
m_patch_size(r),
m_w(img.cols),
m_h(img.rows),
m_attribVector(),
m_descriptors()
{
cvtColor(img, m_img, CV_BGR2Lab);
calculPonderations();
calculVecteurAttributs();
for(unsigned int i = 0; i < (unsigned int) m_img.rows; ++i)
for(unsigned int j = 0; j < (unsigned int) m_img.cols; ++j)
{
m_descriptors.push_back(new TextureDescriptor(m_attribVector, i, j, m_ponderations, m_patch_size));
}
}
Descriptor::~Descriptor()
{
for(auto descriptor: m_descriptors)
delete descriptor;
}
TextureDescriptor Descriptor::at(unsigned int i, unsigned int j) const
{
i %= m_h;
j %= m_w;
return *m_descriptors[i*m_w + j];
}
void Descriptor::calculPonderations()
{
m_ponderations = cv::Mat(2*m_patch_size+1, 2*m_patch_size+1, CV_32FC1);
float sigma_carre = std::pow((float) m_patch_size / 3.0, 2);
if(m_patch_size == 0)
sigma_carre = 1;
float Z = 0.0;
for (int i = -m_patch_size; i <= (long) m_patch_size; i++)
for (int j = -m_patch_size; j <= (long) m_patch_size; j++)
{
float dist_pq = (float) std::sqrt(i*i + j*j);
float w = exp(-(dist_pq) / (2.0 * sigma_carre));
m_ponderations.at<float>(i + m_patch_size, j + m_patch_size) = w;
Z += w;
}
m_ponderations /= Z;
m_beta = 1/Z;
}
void Descriptor::calculVecteurAttributs()
{
cv::Mat Lab[3];
for(unsigned int channel = 0; channel < 3; ++channel)
Lab[channel] = cv::Mat(m_img.rows, m_img.cols, CV_32F);
cv::split(m_img, Lab);
cv::Mat dLdx, dLdy, dadx, dady, dbdx, dbdy, d2Ldx2, d2Ldy2, d2Ldxdy;
cv::Sobel(Lab[0], dLdx, CV_32F, 1, 0, CV_SCHARR);
cv::Sobel(Lab[0], dLdy, CV_32F, 0, 1, CV_SCHARR);
cv::Sobel(Lab[1], dadx, CV_32F, 1, 0, CV_SCHARR);
cv::Sobel(Lab[1], dady, CV_32F, 0, 1, CV_SCHARR);
cv::Sobel(Lab[2], dbdx, CV_32F, 1, 0, CV_SCHARR);
cv::Sobel(Lab[2], dbdy, CV_32F, 0, 1, CV_SCHARR);
cv::Sobel(Lab[0], d2Ldx2, CV_32F, 2, 0);
cv::Sobel(Lab[0], d2Ldy2, CV_32F, 0, 2);
cv::Sobel(Lab[0], d2Ldxdy, CV_32F, 1, 1);
m_attribVector.push_back(abs(Lab[0]));
m_attribVector.push_back(abs(Lab[1]));
m_attribVector.push_back(abs(Lab[2]));
m_attribVector.push_back(abs(dLdx));
m_attribVector.push_back(abs(dLdy));
m_attribVector.push_back(abs(dadx));
m_attribVector.push_back(abs(dady));
m_attribVector.push_back(abs(dbdx));
m_attribVector.push_back(abs(dbdy));
m_attribVector.push_back(abs(d2Ldx2));
m_attribVector.push_back(abs(d2Ldy2));
m_attribVector.push_back(abs(d2Ldxdy));
}
| 30.432203 | 172 | 0.592175 | [
"vector"
] |
486a28d7c69082ed476c9e578ebe884c4b2ea8e1 | 558 | cpp | C++ | LintCode/14.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | 7 | 2019-02-25T13:15:00.000Z | 2021-12-21T22:08:39.000Z | LintCode/14.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | null | null | null | LintCode/14.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | 1 | 2019-04-03T06:12:46.000Z | 2019-04-03T06:12:46.000Z | class Solution {
public:
/**
* @param nums: The integer array.
* @param target: Target to find.
* @return: The first position of target. Position starts from 0.
*/
int bs(vector<int> &v,int a,int b,int t){
if(a==b){
return v[a]==t?a:-1;
}
int k = (a+b)/2;
if(v[k]==t && (k==a || v[k-1]!=t))//最左一个
return k;
if(v[k]<t)
return bs(v,k+1,b,t);
else//>=都往左找,这样有相同的数字时候找到的是第一次出现的那个数字
return bs(v,a,k-1,t);
}
int binarySearch(vector<int> &nums, int target) {
return bs(nums,0,nums.size()-1,target);
}
}; | 22.32 | 69 | 0.562724 | [
"vector"
] |
486e2db2ffbb609811123170e75a60aa3d391e5b | 3,972 | hpp | C++ | include/synthizer/generator.hpp | wiresong/synthizer | d6fb7a5f9eb0c5760411eee29b12a10fdd7ad420 | [
"Unlicense"
] | 25 | 2020-09-05T18:21:21.000Z | 2021-12-05T02:47:42.000Z | include/synthizer/generator.hpp | wiresong/synthizer | d6fb7a5f9eb0c5760411eee29b12a10fdd7ad420 | [
"Unlicense"
] | 77 | 2020-07-08T23:33:46.000Z | 2022-03-19T05:34:26.000Z | include/synthizer/generator.hpp | wiresong/synthizer | d6fb7a5f9eb0c5760411eee29b12a10fdd7ad420 | [
"Unlicense"
] | 9 | 2020-07-08T18:16:53.000Z | 2022-03-02T21:35:28.000Z | #pragma once
#include "synthizer/base_object.hpp"
#include "synthizer/fade_driver.hpp"
#include "synthizer/pausable.hpp"
#include "synthizer/property_internals.hpp"
#include "synthizer/types.hpp"
#include <atomic>
#include <cstdint>
#include <memory>
#include <optional>
namespace synthizer {
class Context;
/*
* A generator: an abstraction over the concept of producing audio.
*
* Examples of things that could be generators include noise, basic sine waves, and reading from streams.
*
* Generators have two pieces of functionality:
*
* - They output a block of samples, of up to config::MAX_CHANNELS channels (truncating if more).
* - They adopt to pitch bends in a generator-defined fashion to participate in doppler for moving sources, and/or if
* asked by the user.
*
* NOTE: users of generators should immediately convert the generator to a `GeneratorRef` (below).
* This is necessary to avoid "leaking" generators in complex scenarios, primarily around linger behavior, and also
* allows existant generators to know if they are in use.
* */
class Generator : public Pausable, public BaseObject {
public:
Generator(const std::shared_ptr<Context> &ctx) : BaseObject(ctx) {}
/* Return the number of channels this generator wants to output on the next block. */
virtual unsigned int getChannels() = 0;
/**
* Non-virtual internal callback. Implements pausing, gain, etc.
*
* Derived classes should override generateBlock.
* */
void run(float *output);
/**
* Output a complete block of audio of config::BLOCK_SIZE. Is expected to add to the output, not replace.
*
* Should respect the passed in FadeDriver for gain.
* */
virtual void generateBlock(float *output, FadeDriver *gain_driver) = 0;
/**
* Returns whether something is using this generator still.
* */
bool isInuse() { return this->use_count.load(std::memory_order_relaxed) != 0; }
bool wantsLinger() override;
std::optional<double> startLingering(const std::shared_ptr<CExposable> &ref,
double configured_timeout) override final;
/**
* All generators should support linger. This function allows the base class to do extra
* generator-specific logic like never lingering when paused, and so derived classes implement it instead of
* startLingering.
*
* The return value has the same meaning as startLingering, except that it may be modified
* by the generator.
* */
virtual std::optional<double> startGeneratorLingering() = 0;
#define PROPERTY_CLASS Generator
#define PROPERTY_LIST GENERATOR_PROPERTIES
#define PROPERTY_BASE BaseObject
#include "synthizer/property_impl.hpp"
private:
friend class GeneratorRef;
FadeDriver gain_driver{1.0, 1};
/**
* Maintained by GeneratorRef on our behalf.
* */
std::atomic<std::size_t> use_count = 0;
};
/**
* Like a weak_ptr, but lets us hook into various functionality
* when no weak references exist but strong ones do. Used ot let generators
* know when they're not being used, which is important for linger behaviors and various
* optimizations.
*
* This is fundamentally not a threadsafe object. Though it maintains the generator's `use_count` atomically,
* when the `use_count` reaches zero logic can occur which must execute only
* on the audio thread.
* */
class GeneratorRef {
public:
GeneratorRef();
GeneratorRef(const std::shared_ptr<Generator> &generator);
GeneratorRef(const std::weak_ptr<Generator> &weak);
GeneratorRef(const GeneratorRef &other);
GeneratorRef(GeneratorRef &&other);
GeneratorRef &operator=(const GeneratorRef &other);
GeneratorRef &operator=(GeneratorRef &&other);
~GeneratorRef();
std::shared_ptr<Generator> lock() const;
bool expired() const;
private:
/**
* Internal fucntion used to decrement the reference counts in the various
* assignment operators.
* */
void decRef();
std::weak_ptr<Generator> ref;
};
} // namespace synthizer | 31.776 | 117 | 0.728852 | [
"object"
] |
486efa6ff96965abd3e99995d0d04f52c8b279ba | 891 | hpp | C++ | include/zboss/math/shape.hpp | ZeroBone/ZBoss | 03f4636c613e7ddd0056df20b99eb961fb064581 | [
"MIT"
] | null | null | null | include/zboss/math/shape.hpp | ZeroBone/ZBoss | 03f4636c613e7ddd0056df20b99eb961fb064581 | [
"MIT"
] | null | null | null | include/zboss/math/shape.hpp | ZeroBone/ZBoss | 03f4636c613e7ddd0056df20b99eb961fb064581 | [
"MIT"
] | null | null | null | #ifndef ZBOSS_MATH_SHAPE_HPP
#define ZBOSS_MATH_SHAPE_HPP
#include <zboss/math/vector.hpp>
#include <vector>
namespace zboss {
struct Edge {
Vector2D start;
Vector2D end;
Edge(Vector2D s, Vector2D e) : start(s), end(e) {}
Vector2D as_vector() const {
return end - start;
}
};
class Shape {
public:
Shape();
Shape(const std::vector<Vector2D>& vertices);
Shape translate(const Vector2D& v) const;
Vector2D barycenter() const;
Shape rotate(float angle) const;
std::vector<float> projection(const Vector2D& v) const;
bool overlap(const Shape& other, Vector2D& mtv) const;
std::vector<Edge> get_edges() const;
private:
std::vector<Vector2D> vertices;
std::vector<Edge> edges;
};
}
#endif //ZBOSS_MATH_SHAPE_HPP | 17.470588 | 63 | 0.59596 | [
"shape",
"vector"
] |
4875078606ca3b9d1724db275ec06bdffacff2a4 | 3,111 | cpp | C++ | src/rrr/RRRTable.cpp | fgulan/bioinformatics-project | 151d666bb754c57fb237ecf469413766e203ab75 | [
"MIT"
] | null | null | null | src/rrr/RRRTable.cpp | fgulan/bioinformatics-project | 151d666bb754c57fb237ecf469413766e203ab75 | [
"MIT"
] | null | null | null | src/rrr/RRRTable.cpp | fgulan/bioinformatics-project | 151d666bb754c57fb237ecf469413766e203ab75 | [
"MIT"
] | null | null | null | //
// Created by Jure Cular on 28/12/2017.
//
#include <cassert>
#include <cmath>
#include "RRRTable.h"
// MARK: - Constructors -
RRRTable::RRRTable(block_size_t block_size) : table{block_size + 1},
bit_offset_vector(block_size + 1, 0),
block_size{block_size}
{
assert(block_size != 0);
for (size_t i = 0; i < block_size + 1; ++i) {
block_vector_t block(block_size, ZERO);
for (auto it = block.end() - i; it != block.end(); ++it) {
*it = ONE;
}
do {
table[i].emplace_back(block_vector_to_bit_block(block), rank_per_bit(block));
} while (std::next_permutation(block.begin(), block.end()));
bit_offset_vector[i] = static_cast<bit_offset_t>(std::ceil(std::log2(table[i].size())));
}
}
// MARK: - Public methods -
offset_t RRRTable::get_offset_for_rank(class_t rank, block_vector_t const &block) const
{
block_bit_t block_bits = block_vector_to_bit_block(block);
// This should never happen! It means that rank of
// block is not equal to rank or RRRTable is inconsistent.
offset_t offset = -1;
for (size_t i = 0, size = table[rank].size(); i < size; ++i) {
if (block_bits == table[rank][i].first) {
offset = i;
break;
}
}
return offset;
}
bit_offset_t RRRTable::get_bit_offset(class_t rank) const
{
return bit_offset_vector[rank];
}
class_t RRRTable::get_rank_at_index(class_t block_rank, offset_t offset, uint64_t index) const
{
return table[block_rank][offset].second[index];
}
size_t RRRTable::index_with_rank1(class_t block_rank, offset_t offset, class_t rank) const
{
rank_vector_per_bit_t rank_vector = table[block_rank][offset].second;
size_t index, size = rank_vector.size();
for (size_t i = 0; i < size; ++i) {
if (rank == rank_vector[i]) {
index = i;
break;
}
}
return index;
}
size_t RRRTable::index_with_rank0(class_t block_rank, offset_t offset, class_t rank) const
{
rank_vector_per_bit_t rank_vector = table[block_rank][offset].second;
size_t index, size = rank_vector.size();
for (size_t i = 0; i < size; ++i) {
if (rank == i + 1 - rank_vector[i]) {
index = i;
break;
}
}
return index;
}
// MARK: - Private methods -
rank_vector_per_bit_t RRRTable::rank_per_bit(block_vector_t const &vector) const
{
rank_vector_per_bit_t rank_per_bit_vector(vector.size());
uint8_t rank = 0;
for (size_t i = 0, size = rank_per_bit_vector.size(); i < size; ++i) {
rank += vector[i] - ZERO;
rank_per_bit_vector[i] = rank;
}
return rank_per_bit_vector;
}
block_bit_t RRRTable::block_vector_to_bit_block(block_vector_t const &block_vector) const
{
block_bit_t block = 0;
size_t i = 0, size = block_vector.size();
for (; i < size; ++i) {
block |= block_vector[i] - ZERO;
block <<= 1;
}
block <<= block_size - i;
block >>= 1;
return block;
}
| 25.925 | 96 | 0.60945 | [
"vector"
] |
48756fca47f631cfcdc6653a1fb0eb984f09ebea | 1,640 | cpp | C++ | codeBase/HackerRank/Algorithms/Search/Cut The Tree/Solution.cpp | suren3141/codeBase | 10ed9a56aca33631dc8c419cd83859c19dd6ff09 | [
"Apache-2.0"
] | 3 | 2020-03-16T14:59:08.000Z | 2021-07-28T20:51:53.000Z | codeBase/HackerRank/Algorithms/Search/Cut The Tree/Solution.cpp | suren3141/codeBase | 10ed9a56aca33631dc8c419cd83859c19dd6ff09 | [
"Apache-2.0"
] | 1 | 2020-03-15T10:57:02.000Z | 2020-03-15T10:57:02.000Z | codeBase/HackerRank/Algorithms/Search/Cut The Tree/Solution.cpp | killerilaksha/codeBase | 91cbd950fc90066903e58311000784aeba4ffc02 | [
"Apache-2.0"
] | 18 | 2020-02-17T23:17:37.000Z | 2021-07-28T20:52:13.000Z | /*
Copyright (C) 2020, Sathira Silva.
Problem Statement: Anna loves graph theory! She has a tree where each vertex is numbered from 1 to n, and each contains a data
value. The sum of a tree is the sum of all its nodes' data values. If she cuts an edge in her tree, she forms
two smaller trees. The difference between two trees is the absolute value between their sums.
Given a tree, determine which edge to cut so that the resulting trees have a minimal difference between them,
then return that difference.
Approach: Run DFS from root vertex to find all the subtree weights.
*/
#include <bits/stdc++.h>
using namespace std;
int n, minDifference, totalWeight;
const int MAX = (int) pow(10, 5) + 1;
vector<int> tree[MAX];
int weight[MAX];
bool visited[MAX];
int dfs(int u) {
int w = weight[u];
visited[u] = true;
for (int v: tree[u])
if (!visited[v])
w += dfs(v);
// Deduct w twice because totalWeight of the tree includes weight of the subtree w.
minDifference = min(minDifference, abs(totalWeight - 2 * w));
return w;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n;
for (int i = 1; i <= n; i ++)
cin >> weight[i];
for (int i = 0; i < n; i++) {
int u, v;
cin >> u >> v;
tree[u].push_back(v);
tree[v].push_back(u);
}
minDifference = 1e9, totalWeight = accumulate(weight, weight + n + 1, 0);
dfs(1);
cout << minDifference << endl;
return 0;
}
| 31.538462 | 134 | 0.584146 | [
"vector"
] |
4875cea3e487d9ae12c03bc077cf1ee08913df0c | 1,496 | cpp | C++ | Engine/Source/Audio/AudioClip.cpp | FloatyMonkey/FmEngine | f187f00c2d25ae662218de72b69ea57a93de6d41 | [
"MIT"
] | 15 | 2019-12-01T10:17:17.000Z | 2022-01-30T00:37:43.000Z | Engine/Source/Audio/AudioClip.cpp | FloatyMonkey/FmEngine | f187f00c2d25ae662218de72b69ea57a93de6d41 | [
"MIT"
] | null | null | null | Engine/Source/Audio/AudioClip.cpp | FloatyMonkey/FmEngine | f187f00c2d25ae662218de72b69ea57a93de6d41 | [
"MIT"
] | 2 | 2020-01-18T21:32:22.000Z | 2021-06-28T07:51:46.000Z | // Copyright (c) 2020 Lauro Oyen, FmEngine contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed.
#include "AudioClip.h"
#include "../ThirdParty/dr/dr_wav.h"
#include "../Utility/Logger/Log.h"
#include "../Utility/Memory.h"
#include <fstream>
namespace FM
{
AudioClip::AudioClip()
{
}
AudioClip::~AudioClip()
{
}
bool AudioClip::Load(const char* filename)
{
std::ifstream file(filename, std::ios::binary | std::ios::ate);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<char> buffer(size);
if (!file.read(buffer.data(), size))
{
FM_LOG(Error) << "Failed to open audio file: " << filename;
return false;
}
return LoadWav(&buffer[0], size, filename);
}
float AudioClip::Length() const
{
if (mSampleRate == 0) return 0;
return (float)mSampleCount / (float)mSampleRate;
}
bool AudioClip::LoadWav(const void* data, usize size, const char* filename)
{
drwav* decoder = new drwav;
if (!drwav_init_memory(decoder, data, size, nullptr))
{
FM_LOG(Error) << "Failed to decode WAV file: " << filename;
return false;
}
mSampleRate = decoder->sampleRate;
mSampleCount = decoder->totalPCMFrameCount;
mChannelCount = decoder->channels;
mData = std::vector<float>(mSampleCount * mChannelCount);
drwav_read_pcm_frames_f32(decoder, mSampleCount, &mData[0]);
drwav_uninit(decoder);
delete decoder;
return true;
}
}
| 21.070423 | 99 | 0.683824 | [
"vector"
] |
4876c6a528a4264ea395c2914838061936ba7a28 | 1,602 | hpp | C++ | B-CPP-500-LYN-5-1-babel/include/server/Asqlite3.hpp | Neotoxic-off/Epitech2024 | 8b3dd04fa9ac2b7019c0b5b1651975a7252d929b | [
"Apache-2.0"
] | 2 | 2022-02-07T12:44:51.000Z | 2022-02-08T12:04:08.000Z | B-CPP-500-LYN-5-1-babel/include/server/Asqlite3.hpp | Neotoxic-off/Epitech2024 | 8b3dd04fa9ac2b7019c0b5b1651975a7252d929b | [
"Apache-2.0"
] | null | null | null | B-CPP-500-LYN-5-1-babel/include/server/Asqlite3.hpp | Neotoxic-off/Epitech2024 | 8b3dd04fa9ac2b7019c0b5b1651975a7252d929b | [
"Apache-2.0"
] | 1 | 2022-01-23T21:26:06.000Z | 2022-01-23T21:26:06.000Z | /*
** EPITECH PROJECT, 2021
** B-CPP-500-LYN-5-1-babel-
** File description:
** ASqlite3
*/
#include "sqlite3.h"
#include "common/standard.h"
#include "common/User.hpp"
#ifndef ASQLITE3_HPP_
#define ASQLITE3_HPP_
#define DB_DIR "../user.db"
#define SELECT_QUERY(x) static_cast<std::string>("SELECT ") + x
#define FROM_QUERY(x) static_cast<std::string>("FROM ") + x
#define WHERE_QUERY(x) static_cast<std::string>("WHERE ") + x
#define INNERJOIN_QUERY(x) static_cast<std::string>("INNER JOIN ") + x
class Asqlite3 {
public:
Asqlite3();
~Asqlite3();
enum loginCode {SUCCESS, USER_NOT_EXIST, BAD_PASSWORD};
bool uploadData(struct UserApp user);
loginCode login(struct UserApp user);
std::string getUser(std::string username);
bool linkUser(std::string userfrom, std::string userto);
bool unlinkUser(std::string userfrom, std::string userto);
std::string getIdByUsername(std::string username);
std::vector<struct UserApp> getLinkedUser(std::string username);
bool checkUser(std::string username);
protected:
private:
std::string _res;
std::vector<struct UserApp> _linkedUser;
static int callbackUserExist(void *, int argc, char** argv, char** azColName);
static int callbackGetUser(void *, int argc, char** argv, char** azColName);
static int callbackFillContact(void *, int argc, char** argv, char** azColName);
static bool executeQuery(std::string sql, int (*callback)(void *, int, char **, char **), void *context);
};
#endif /* !ASQLITE3_HPP_ */
| 33.375 | 113 | 0.667291 | [
"vector"
] |
48794e5594c1abe684aec7ac8fb57ad4dd968fa5 | 2,155 | cpp | C++ | lib/structs/responses/notifications.cpp | govynnus/mtxclient | 3888ae70d51cdfe7b69d375560448f36991793e6 | [
"MIT"
] | 18 | 2019-03-11T20:23:53.000Z | 2022-02-25T20:55:27.000Z | lib/structs/responses/notifications.cpp | govynnus/mtxclient | 3888ae70d51cdfe7b69d375560448f36991793e6 | [
"MIT"
] | 55 | 2019-02-07T01:21:03.000Z | 2022-03-06T15:42:34.000Z | lib/structs/responses/notifications.cpp | govynnus/mtxclient | 3888ae70d51cdfe7b69d375560448f36991793e6 | [
"MIT"
] | 22 | 2019-02-24T17:28:31.000Z | 2022-03-10T22:40:22.000Z | #include "mtx/responses/notifications.hpp"
#include "mtx/responses/common.hpp"
#include <nlohmann/json.hpp>
using json = nlohmann::json;
namespace mtx {
namespace responses {
void
from_json(const json &obj, Notification &res)
{
res.actions = obj.at("actions").get<decltype(res.actions)>();
res.read = obj.at("read");
res.room_id = obj.at("room_id");
res.ts = obj.at("ts");
if (obj.find("profile_tag") != obj.end() && !obj.at("profile_tag").is_null())
res.profile_tag = obj.at("profile_tag");
// HACK to work around the fact that there isn't
// a method to parse a timeline event from a json object.
//
// TODO: Create method that retrieves a TimelineEvents variant from a json object.
// Ideally with an optional type to indicate failure.
std::vector<events::collections::TimelineEvents> tmp;
tmp.reserve(1);
json arr;
arr.push_back(obj.at("event"));
utils::parse_timeline_events(arr, tmp);
if (!tmp.empty())
res.event = tmp.at(0);
}
void
to_json(json &obj, const Notification &res)
{
obj["actions"] = res.actions;
obj["read"] = res.read;
obj["room_id"] = res.room_id;
obj["ts"] = res.ts;
// HACK to work around the fact that there isn't
// a method to parse a timeline event from a json object.
//
// TODO: Create method that retrieves a TimelineEvents variant from a json object.
// Ideally with an optional type to indicate failure.
std::vector<events::collections::TimelineEvents> tmp;
tmp.reserve(1);
json arr;
tmp.push_back(res.event);
utils::compose_timeline_events(arr, tmp);
if (!tmp.empty()) {
obj["event"] = arr;
}
if (!res.profile_tag.empty()) {
obj["profile_tag"] = res.profile_tag;
}
}
void
from_json(const json &obj, Notifications &res)
{
// res.next_token = obj.at("next_token").get<std::string>();
res.notifications = obj.at("notifications").get<std::vector<Notification>>();
}
void
to_json(json &obj, const Notifications ¬if)
{
obj["notifications"] = notif.notifications;
}
} // namespace responses
} // namespace mtx
| 25.963855 | 86 | 0.64594 | [
"object",
"vector"
] |
487a1f8f5077d5f21aa132248b9847458bd0caef | 3,572 | cc | C++ | zircon/system/ulib/hwreg/test/indirect-test.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | 3 | 2020-08-02T04:46:18.000Z | 2020-08-07T10:10:53.000Z | zircon/system/ulib/hwreg/test/indirect-test.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | null | null | null | zircon/system/ulib/hwreg/test/indirect-test.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | 1 | 2020-08-07T10:11:49.000Z | 2020-08-07T10:11:49.000Z | // Copyright 2019 The Fuchsia 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 <assert.h>
#include <stdio.h>
#include <zircon/types.h>
#include <climits>
#include <limits>
#include <hwreg/bitfields.h>
#include <hwreg/indirect.h>
#include <hwreg/mmio.h>
#include <zxtest/zxtest.h>
// This function exists so that the resulting code can be inspected easily in the
// object file.
static void compilation_test() {
typedef hwreg::IndirectIo<0x00, 0x04> Io;
volatile struct {
uint32_t index = 0xaa;
uint32_t reserved = 0xff;
uint32_t data = 0x11;
} fake_regs;
auto io = Io(static_cast<volatile void*>(&fake_regs));
io.Write<uint32_t>(1, 0);
io.Read<uint32_t>(0);
}
namespace {
template <typename IntType, typename IndexType>
void basic_access_test() {
typedef struct {
IndexType index;
// Test an indexed register with a reserved field in the middle.
IntType reserved;
IntType data;
} FakeRegs;
volatile FakeRegs fake_regs;
typedef hwreg::IndirectIo<
static_cast<uint32_t>(offsetof(FakeRegs, index)),
static_cast<uint32_t>(offsetof(FakeRegs, data)),
IndexType> Io;
fake_regs.index = 1;
fake_regs.reserved = 3;
fake_regs.data = 2;
Io io(hwreg::RegisterIo(static_cast<volatile void*>(&fake_regs)));
class Reg : public hwreg::RegisterBase<Reg, IntType> {
public:
static auto Get(uint32_t offset) { return hwreg::RegisterAddr<Reg>(offset); }
};
// Validate that reading from .data works
EXPECT_EQ(2, Reg::Get(0).ReadFrom(&io).reg_value());
EXPECT_EQ(0, fake_regs.index);
EXPECT_EQ(3, fake_regs.reserved);
// That reading from another register updates the index.
fake_regs.data = 6;
EXPECT_EQ(6, Reg::Get(2).ReadFrom(&io).reg_value());
EXPECT_EQ(2, fake_regs.index);
EXPECT_EQ(3, fake_regs.reserved);
// And writing also updates the index.
Reg::Get(0).ReadFrom(&io).set_reg_value(static_cast<IntType>(5)).WriteTo(&io);
EXPECT_EQ(0, fake_regs.index);
EXPECT_EQ(5, fake_regs.data);
EXPECT_EQ(3, fake_regs.reserved);
}
template <typename IntType>
void single_thread_test() {
basic_access_test<IntType, IntType>();
basic_access_test<IntType, uint8_t>();
}
TEST(SingleThreadTestCase, Uint8) { ASSERT_NO_FAILURES(single_thread_test<uint8_t>()); }
TEST(SingleThreadTestCase, Uint16) { ASSERT_NO_FAILURES(single_thread_test<uint16_t>()); }
TEST(SingleThreadTestCase, Uint32) { ASSERT_NO_FAILURES(single_thread_test<uint32_t>()); }
TEST(SingleThreadTestCase, Uint64) { ASSERT_NO_FAILURES(single_thread_test<uint64_t>()); }
TEST(AlignedAccessTest, Uint32) {
typedef struct {
uint16_t index;
uint16_t reserved;
uint32_t data;
} FakeRegs;
volatile FakeRegs fake_regs;
typedef hwreg::IndirectIo<offsetof(FakeRegs, index), offsetof(FakeRegs, data), uint16_t> Io;
fake_regs.index = 0xaaaa;
fake_regs.reserved = 0xffff;
fake_regs.data = 0x12345678;
Io io(hwreg::RegisterIo(static_cast<volatile void*>(&fake_regs)));
class MatchingReg : public hwreg::RegisterBase<MatchingReg, uint32_t> {
public:
static auto Get(uint32_t offset) { return hwreg::RegisterAddr<MatchingReg>(offset); }
};
EXPECT_EQ(0x12345678, MatchingReg::Get(0).ReadFrom(&io).reg_value());
class SmallReg : public hwreg::RegisterBase<SmallReg, uint16_t> {
public:
static auto Get(uint32_t offset) { return hwreg::RegisterAddr<SmallReg>(offset); }
};
EXPECT_EQ(fake_regs.data & 0xffff, SmallReg::Get(0).ReadFrom(&io).reg_value());
}
} // namespace
| 30.793103 | 94 | 0.723684 | [
"object"
] |
4881bb97b721a047e5222e6d37b4b0ae964b6ab2 | 37,084 | cpp | C++ | main.cpp | karelvaculik/ewaldis | 36a301f93ccd59bdf084e427251205432aa80dae | [
"Apache-2.0"
] | null | null | null | main.cpp | karelvaculik/ewaldis | 36a301f93ccd59bdf084e427251205432aa80dae | [
"Apache-2.0"
] | null | null | null | main.cpp | karelvaculik/ewaldis | 36a301f93ccd59bdf084e427251205432aa80dae | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <vector>
#include <map>
#include <fstream>
#include <string.h>
#include <sstream>
#include "src/DynamicGraph.h"
#include "src/DynamicGraphExamples.h"
#include "src/RandomGenerator.h"
#include <ctime>
#include <random>
#include "PatternMiner.h"
#include "commonutilstemplated.h"
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
static void show_usage(std::string name) {
std::cerr << "EWALDIS, version 1.0.0"
<< std::endl
<< "Author: Karel Vaculik (vaculik.dev@gmail.com)"
<< std::endl
<< std::endl
<< "Usage: " << name << " <option(s)>"
<< std::endl
<< std::endl
<< "NOTE: N stands for an integer, R for a real number, F a filename string"
<< std::endl
<< std::endl
<< "\t-h, --help\t\t\tShows this help message"
<< std::endl
<< "\t-v, --verbose\t\tVerbose output"
<< std::endl
<< std::endl
<< "MANDATORY ARGUMENTS:"
<< std::endl
<< "\t--vertices F\t\tSpecifies the input file with vertices"
<< std::endl
<< "\t--edges F\t\t\tSpecifies the input file with edges"
<< std::endl
<< "\t--train_pos F\t\tSpecifies the training input file with positive events"
<< std::endl
<< "\t--train_neg F\t\tSpecifies the training input file with negative events"
<< std::endl
<< "\t-o OUTPUT_DIR\t\tSpecifies the output directory"
<< std::endl
<< "\t-e {vertices,edges}\tSpecifies the type of events: either vertices or edges"
<< std::endl
<< "\t-a {nominal,numerical}\tSpecifies the type of edge attributes: either nominal or numerical"
<< std::endl
<< std::endl
<< "OPTIONAL ARGUMENTS:"
<< std::endl
<< "\t-p N\t\t\t\tSpecifies the number of patterns to be mined; 1 by default"
<< std::endl
<< "\t-n N\t\t\t\tSpecifies the size of sample from positive and negative events used for pattern mining; if not specified, all events are used"
<< std::endl
<< "\t--test_pos F\t\tSpecifies the test input file with positive events"
<< std::endl
<< "\t--test_neg F\t\tSpecifies the test input file with negative events"
<< std::endl
<< "\t-u\t\t\t\t\tTreat the input graph as undirected; if not specified, it is considered directed"
<< std::endl
<< "\t-m N\t\t\t\tSpecifies the maximum number of edges per pattern; 20 by default"
<< std::endl
<< "\t-w N\t\t\t\tSpecifies the number of random walks; 1000 by default"
<< std::endl
<< "\t-r R\t\t\t\tSpecifies the probability of random walks restart; decimal value from [0.0, 1.0]; 0.3 by default"
<< std::endl
<< "\t-pu R\t\t\t\tSpecifies the value of primary time unit; 1.0 by default"
<< std::endl
<< "\t-su R\t\t\t\tSpecifies the value of secondary time unit; 1.0 by default"
<< std::endl
<< "\t-ep N\t\t\t\tSpecifies the number of epochs in the genetic algorithm; 25 by default"
<< std::endl
<< "\t-se N\t\t\t\tSpecifies the number of subepochs in the genetic algorithm; 25 by default"
<< std::endl
<< "\t-ew N\t\t\t\tSpecifies the number of random walks used for evaluation; 10 by default"
<< std::endl
<< "\t--unicross\t\t\tUse uniform crossover instead of single-point crossover"
<< std::endl
<< "\t--baseline F\t\tOutput edges for baseline classifier"
<< std::endl
<< "\t-s N\t\t\t\tSpecifies seed for random generator"
<< std::endl;
}
template<typename Out>
void split(const std::string &s, char delim, Out result) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
*(result++) = item;
}
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, std::back_inserter(elems));
return elems;
}
Vertex ver(int v_id, std::string label, NominalEncoder *ne) {
std::map<std::string, double> attributes;
attributes["label"] = ne->get_encoding(label);
return Vertex(v_id, attributes);
}
Edge edg(int e_id, int f_id, int t_id, std::string label, timestamp_t timestamp, NominalEncoder *ne) {
std::map<std::string, double> attributes;
attributes["label"] = ne->get_encoding(label);
return Edge(e_id, f_id, t_id, timestamp, attributes);
}
std::vector<Vertex> read_vertices(string directory, bool has_header, NominalEncoder *ne) {
std::ifstream input(directory);
int line_number = 0;
std::vector<Vertex> vertices;
for (std::string line; getline(input, line);) {
if (!has_header || line_number > 0) {
std::vector<std::string> x = split(line, ',');
vertices.push_back(ver(std::stoi(x[0]), x[1], ne));
}
line_number++;
}
return vertices;
}
std::vector<Edge> read_edges(string directory, bool has_header, NominalEncoder *ne) {
std::ifstream input(directory);
int line_number = 0;
std::vector<Edge> edges;
for (std::string line; getline(input, line);) {
if (!has_header || line_number > 0) {
std::vector<std::string> x = split(line, ',');
edges.push_back(edg(std::stoi(x[0]), std::stoi(x[1]), std::stoi(x[2]), x[3], std::stod(x[4]), ne));
}
line_number++;
}
return edges;
}
void read_vertex_events(std::string directory, bool has_header,
std::vector<std::vector<int>> &vertex_ids,
std::vector<timestamp_t> &vertex_timestamps) {
vertex_ids.push_back(std::vector<int>());
std::ifstream input(directory);
int line_number = 0;
std::vector<Edge> edges;
for (std::string line; getline(input, line);) {
if (!has_header || line_number > 0) {
std::vector<std::string> x = split(line, ',');
vertex_ids[0].push_back(std::stoi(x[0]));
vertex_timestamps.push_back(std::stod(x[1]));
}
line_number++;
}
}
void read_edge_events(std::string directory, bool has_header,
std::vector<std::vector<int>> &edge_ids,
std::vector<std::vector<int>> &vertex_ids,
std::vector<timestamp_t> &vertex_timestamps) {
edge_ids.push_back(std::vector<int>());
vertex_ids.push_back(std::vector<int>());
vertex_ids.push_back(std::vector<int>());
std::ifstream input(directory);
int line_number = 0;
std::vector<Edge> edges;
for (std::string line; getline(input, line);) {
if (!has_header || line_number > 0) {
std::vector<std::string> x = split(line, ',');
edge_ids[0].push_back(std::stoi(x[0]));
vertex_ids[0].push_back(std::stoi(x[1]));
vertex_ids[1].push_back(std::stoi(x[2]));
vertex_timestamps.push_back(std::stod(x[3]));
}
line_number++;
}
}
void output_base_edges_for_classifier(DynamicGraph *graph,
std::vector<std::vector<int>> positive_event_edges,
std::vector<std::vector<int>> positive_event_vertices,
std::vector<timestamp_t> positive_event_times,
std::vector<std::vector<int>> negative_event_edges,
std::vector<std::vector<int>> negative_event_vertices,
std::vector<timestamp_t> negative_event_times,
std::string output_filename) {
ofstream myfile;
myfile.open(output_filename);
myfile << "id,label,timestamp,new_label,class" << std::endl;
for (int i = 0; i < positive_event_vertices.size(); ++i) {
for (int j = 0; j < positive_event_vertices[i].size(); ++j) {
std::vector<Edge *> edges = graph->get_adjacency_list().at(positive_event_vertices[i][j]);
for (auto &edge : edges) {
// add only edges that are not the event edges
// if there are no event edges, it is always ok
if (positive_event_edges.size() == 0 || edge->get_original_edge_id() != positive_event_edges[0][j]) {
// int time = (int) (positive_event_times[j] - edge->get_timestamp() + 1);
int time = (int) (positive_event_times[j] - edge->get_timestamp());
myfile << j << ","; // id
myfile << edge->get_attributes().at("label") << ","; // label
myfile << time << ","; // timestamp
myfile << "f" << edge->get_attributes().at("label") << "_" << time << ","; // new_label
myfile << "pos" << std::endl; // class
}
}
}
}
for (int i = 0; i < negative_event_vertices.size(); ++i) {
for (int j = 0; j < negative_event_vertices[i].size(); ++j) {
std::vector<Edge *> edges = graph->get_adjacency_list().at(negative_event_vertices[i][j]);
for (auto &edge : edges) {
// add only edges that are not the event edges
// if there are no event edges, it is always ok
if (negative_event_edges.size() == 0 || edge->get_original_edge_id() != negative_event_edges[0][j]) {
// int time = (int) (negative_event_times[j] - edge->get_timestamp() + 1);
int time = (int) (negative_event_times[j] - edge->get_timestamp());
myfile << (j + positive_event_times.size()) << ","; // id
myfile << edge->get_attributes().at("label") << ","; // label
myfile << time << ","; // timestamp
myfile << "f" << edge->get_attributes().at("label") << "_" << time << ","; // new_label
myfile << "neg" << std::endl; // class
}
}
}
}
myfile.close();
}
void run_process_new(std::string vertex_filename, std::string edge_filename,
std::string train_pos_filename, std::string train_neg_filename,
std::string output_dir, bool vertex_events, std::string edge_attributes_type,
int n_patterns, bool use_sample, int n_sample,
std::string test_pos_filename, std::string test_neg_filename,
bool undirected, int max_pattern_edges, int random_walks, double prob_restart,
timestamp_t time_unit_primary, timestamp_t time_unit_secondary,
int evolution_epochs, int evolution_subepochs, int evaluation_random_walks,
bool use_uniform_crossover, bool output_baseline_edges, bool use_seed, unsigned seed,
bool use_vertex_attributes, bool use_simple_init, bool limit_negative_population,
bool verbose) {
clock_t begin_total = clock();
clock_t begin_data_preparation = clock();
RandomGenerator random_generator;
if (use_seed) {
random_generator = RandomGenerator(seed);
} else {
random_generator = RandomGenerator();
}
NominalEncoder *ne = new NominalEncoder();
if (verbose) print("LOADING THE GRAPH ... ");
std::vector<Vertex> vertices = read_vertices(vertex_filename, true, ne);
std::vector<Edge> edges = read_edges(edge_filename, true, ne);
std::map<std::string, AttributeType> vertex_schema;
std::map<std::string, AttributeType> edge_schema;
vertex_schema["label"] = AttributeType::NOMINAL;
if (edge_attributes_type == "nominal") {
edge_schema["label"] = AttributeType::NOMINAL;
} else {
edge_schema["label"] = AttributeType::NUMERIC;
}
DynamicGraph graph = DynamicGraph(vertices, edges, vertex_schema, edge_schema, undirected);
if (verbose) println("DONE");
if (verbose) print("PREPARING EVENTS ... ");
// train positive
std::vector<std::vector<int>> positive_event_edges_train;
std::vector<std::vector<int>> positive_event_vertices_train;
std::vector<timestamp_t> positive_event_times_train;
// train negative
std::vector<std::vector<int>> negative_event_edges_train;
std::vector<std::vector<int>> negative_event_vertices_train;
std::vector<timestamp_t> negative_event_times_train;
// test positive
std::vector<std::vector<int>> positive_event_edges_test;
std::vector<std::vector<int>> positive_event_vertices_test;
std::vector<timestamp_t> positive_event_times_test;
// test negative
std::vector<std::vector<int>> negative_event_edges_test;
std::vector<std::vector<int>> negative_event_vertices_test;
std::vector<timestamp_t> negative_event_times_test;
if (vertex_events) {
read_vertex_events(train_pos_filename, true, positive_event_vertices_train, positive_event_times_train);
read_vertex_events(train_neg_filename, true, negative_event_vertices_train, negative_event_times_train);
if (test_pos_filename != "") {
read_vertex_events(test_pos_filename, true, positive_event_vertices_test, positive_event_times_test);
read_vertex_events(test_neg_filename, true, negative_event_vertices_test, negative_event_times_test);
}
} else {
read_edge_events(train_pos_filename, true, positive_event_edges_train, positive_event_vertices_train,
positive_event_times_train);
read_edge_events(train_neg_filename, true, negative_event_edges_train, negative_event_vertices_train,
negative_event_times_train);
if (test_pos_filename != "") {
read_edge_events(test_pos_filename, true, positive_event_edges_test, positive_event_vertices_test,
positive_event_times_test);
read_edge_events(test_neg_filename, true, negative_event_edges_test, negative_event_vertices_test,
negative_event_times_test);
}
}
// create directory if it does not exist
fs::path p = fs::u8path(output_dir);
if (!fs::is_directory(p) || !fs::exists(p)) { // Check if src folder exists
fs::create_directories(p); // create src folder
}
if (verbose) println("DONE");
if (output_baseline_edges) {
// print training edges
std::cout << "PRINTING BASELINE";
output_base_edges_for_classifier(&graph,
positive_event_edges_train, positive_event_vertices_train,
positive_event_times_train, negative_event_edges_train,
negative_event_vertices_train, negative_event_times_train,
output_dir + "/baseline_edges_data_train.csv");
// print test edges
output_base_edges_for_classifier(&graph,
positive_event_edges_test, positive_event_vertices_test,
positive_event_times_test, negative_event_edges_test,
negative_event_vertices_test, negative_event_times_test,
output_dir + "/baseline_edges_data_test.csv");
}
std::vector<DynamicGraph> train_graph_instances = graph.create_subgraph_instances(positive_event_times_train,
negative_event_times_train,
time_unit_primary);
std::vector<DynamicGraph> test_graph_instances = graph.create_subgraph_instances(positive_event_times_test,
negative_event_times_test,
time_unit_primary);
clock_t end_data_preparation = clock();
for (int pattern_number = 0; pattern_number < n_patterns; ++pattern_number) {
if (verbose) println("------ SEARCHING FOR PATTERN No. ", pattern_number);
clock_t begin_sampling = clock();
// prepare a seed of events for pattern extraction
// sample positive
std::vector<std::vector<int>> positive_event_edges_sample = {std::vector<int>()};
std::vector<std::vector<int>> positive_event_vertices_sample = {std::vector<int>(), std::vector<int>()};
std::vector<timestamp_t> positive_event_times_sample;
std::vector<int> selected_indices_positive = random_generator.generate_random_int_vector(n_sample,
positive_event_times_train.size());
for (int i = 0; i < n_sample; ++i) {
positive_event_edges_sample.at(0).push_back(positive_event_edges_train[0][selected_indices_positive[i]]);
positive_event_vertices_sample.at(0).push_back(
positive_event_vertices_train[0][selected_indices_positive[i]]);
positive_event_vertices_sample.at(1).push_back(
positive_event_vertices_train[1][selected_indices_positive[i]]);
positive_event_times_sample.push_back(positive_event_times_train[selected_indices_positive[i]]);
}
// sample negative
std::vector<std::vector<int>> negative_event_edges_sample = {std::vector<int>()};
std::vector<std::vector<int>> negative_event_vertices_sample = {std::vector<int>(), std::vector<int>()};
std::vector<timestamp_t> negative_event_times_sample;
std::vector<int> selected_indices_negative = random_generator.generate_random_int_vector(n_sample,
negative_event_times_train.size());
for (int i = 0; i < n_sample; ++i) {
negative_event_edges_sample.at(0).push_back(negative_event_edges_train[0][selected_indices_negative[i]]);
negative_event_vertices_sample.at(0).push_back(
negative_event_vertices_train[0][selected_indices_negative[i]]);
negative_event_vertices_sample.at(1).push_back(
negative_event_vertices_train[1][selected_indices_negative[i]]);
negative_event_times_sample.push_back(negative_event_times_train[selected_indices_negative[i]]);
}
clock_t end_sampling = clock();
clock_t begin_pattern_mining = clock();
std::vector<DynamicGraph> sample_graph_instances = graph.create_subgraph_instances(positive_event_times_sample,
negative_event_times_sample,
time_unit_primary);
PatternMiner pattern_miner = PatternMiner(sample_graph_instances, positive_event_vertices_sample,
positive_event_times_sample,
// PatternMiner pattern_miner = PatternMiner(&graph, positive_event_vertices_sample, positive_event_times_sample,
positive_event_edges_sample,
negative_event_vertices_sample, negative_event_times_sample,
negative_event_edges_sample,
use_vertex_attributes, time_unit_primary, time_unit_secondary,
random_walks, prob_restart, max_pattern_edges, evolution_epochs,
evolution_subepochs, &random_generator,
use_simple_init, use_uniform_crossover, limit_negative_population);
std::vector<std::vector<double>> populations_fitness(max_pattern_edges * evolution_epochs,
std::vector<double>());
std::vector<std::vector<double>> negative_populations_fitness(
max_pattern_edges * evolution_epochs * evolution_subepochs, std::vector<double>());
Pattern pattern = pattern_miner.mine_pattern(populations_fitness, negative_populations_fitness, verbose);
clock_t end_pattern_mining = clock();
clock_t begin_evaluation = clock();
if (verbose) print("ASSESSING PATTERN ... ");
std::vector<std::vector<double>> evaluation_sample = pattern_miner.evaluate_pattern(&pattern,
sample_graph_instances,
positive_event_vertices_sample,
positive_event_times_sample,
negative_event_vertices_sample,
negative_event_times_sample,
evaluation_random_walks);
std::vector<std::vector<double>> evaluation_train = pattern_miner.evaluate_pattern(&pattern,
train_graph_instances,
positive_event_vertices_train,
positive_event_times_train,
negative_event_vertices_train,
negative_event_times_train,
evaluation_random_walks);
std::vector<std::vector<double>> evaluation_test = pattern_miner.evaluate_pattern(&pattern,
test_graph_instances,
positive_event_vertices_test,
positive_event_times_test,
negative_event_vertices_test,
negative_event_times_test,
evaluation_random_walks);
// std::vector<std::vector<double>> evaluation_sample = pattern_miner.evaluate_pattern(&pattern, &graph, positive_event_vertices_sample, positive_event_times_sample,
// negative_event_vertices_sample, negative_event_times_sample, evaluation_random_walks);
//
// std::vector<std::vector<double>> evaluation_train = pattern_miner.evaluate_pattern(&pattern, &graph, positive_event_vertices_train, positive_event_times_train,
// negative_event_vertices_train, negative_event_times_train, evaluation_random_walks);
//
// std::vector<std::vector<double>> evaluation_test = pattern_miner.evaluate_pattern(&pattern, &graph, positive_event_vertices_test, positive_event_times_test,
// negative_event_vertices_test, negative_event_times_test, evaluation_random_walks);
clock_t end_evaluation = clock();
if (verbose) println("DONE");
pattern.clean_empty_instances();
double elapsed_secs_preparation =
double(end_data_preparation - begin_data_preparation + end_sampling - begin_sampling) / CLOCKS_PER_SEC;
double elapsed_secs_mining = double(end_pattern_mining - begin_pattern_mining) / CLOCKS_PER_SEC;
double elapsed_secs_evaluation = double(end_evaluation - begin_evaluation) / CLOCKS_PER_SEC;
std::string file_prefix = output_dir + "/results_" + std::to_string(pattern_number);
ofstream myfile;
myfile.open(file_prefix + ".txt");
// experiment parameters
myfile << "TOTAL_TIME_PREPARATION:" << std::to_string((int) elapsed_secs_preparation) << std::endl;
myfile << "TOTAL_TIME_MINING:" << std::to_string((int) elapsed_secs_mining) << std::endl;
myfile << "TOTAL_TIME_EVALUATION:" << std::to_string((int) elapsed_secs_evaluation) << std::endl;
myfile << "TIME_UNIT_PRIMARY:" << std::to_string(time_unit_primary) << std::endl;
myfile << "TIME_UNIT_SECONDARY:" << std::to_string(time_unit_secondary) << std::endl;
myfile << "RANDOM_WALKS:" << std::to_string(random_walks) << std::endl;
myfile << "PROB_RESTART:" << std::to_string(prob_restart) << std::endl;
myfile << "MAX_PATTERN_EDGES:" << std::to_string(max_pattern_edges) << std::endl;
myfile << "EVOLUTION_EPOCHS:" << std::to_string(evolution_epochs) << std::endl;
myfile << "EVOLUTION_SUBEPOCHS:" << std::to_string(evolution_subepochs) << std::endl;
myfile << "EVALUATION_RANDOM_WALKS:" << std::to_string(evaluation_random_walks) << std::endl;
// pattern itself
myfile << "PATTERN_EDGES:" << str(pattern.get_pattern_vertex_pairs()) << std::endl;
myfile << "PATTERN_SCORES:" << str(pattern.get_scores()) << std::endl;
myfile << "PATTERN_TIMESTAMPS:" << str(pattern.get_timestamps()) << std::endl;
myfile << "PATTERN_ATTRIBUTES:" << str(pattern.get_decoded_attributes(graph.get_edge_schema(), ne))
<< std::endl;
myfile << "PATTERN_DIRECTIONS:" << str(pattern.get_directions()) << std::endl;
myfile << "PATTERN_UNDIRECTED:" << str(graph.is_undirected()) << std::endl;
// evaluation results
myfile << "SAMPLE_EVALUATION_POSITIVE:" << str(evaluation_sample[0]) << std::endl;
myfile << "SAMPLE_EVALUATION_NEGATIVE:" << str(evaluation_sample[1]) << std::endl;
myfile << "TRAIN_EVALUATION_POSITIVE:" << str(evaluation_train[0]) << std::endl;
myfile << "TRAIN_EVALUATION_NEGATIVE:" << str(evaluation_train[1]) << std::endl;
myfile << "TEST_EVALUATION_POSITIVE:" << str(evaluation_test[0]) << std::endl;
myfile << "TEST_EVALUATION_NEGATIVE:" << str(evaluation_test[1]) << std::endl;
myfile.close();
int number_of_quantiles = 5;
ofstream myfile_positive;
myfile_positive.open(file_prefix + "_positive_population.txt");
for (int j = 0; j < populations_fitness.size(); ++j) {
for (int i = 0; i < number_of_quantiles; ++i) {
if (populations_fitness[j].size() > i) {
myfile_positive << populations_fitness[j][i];
}
if (i < number_of_quantiles - 1) {
myfile_positive << ",";
}
}
myfile_positive << std::endl;
}
myfile_positive.close();
ofstream myfile_negative;
myfile_negative.open(file_prefix + "_negative_population.txt");
for (int j = 0; j < negative_populations_fitness.size(); ++j) {
for (int i = 0; i < number_of_quantiles; ++i) {
if (negative_populations_fitness[j].size() > i) {
myfile_negative << negative_populations_fitness[j][i];
}
if (i < number_of_quantiles - 1) {
myfile_negative << ",";
}
}
myfile_negative << std::endl;
}
myfile_negative.close();
}
delete ne;
clock_t end_total = clock();
double elapsed_secs_total = double(end_total - begin_total) / CLOCKS_PER_SEC;
if (verbose) println("EXPERIMENT_TOTAL_TIME: ", ((int) elapsed_secs_total));
}
int main(int argc, char *argv[]) {
bool verbose = false;
// mandatory arguments
std::string vertex_filename = "";
std::string edge_filename = "";
std::string train_pos_filename = "";
std::string train_neg_filename = "";
std::string output_dir = "";
bool vertex_events;
std::string str_vertex_events = "";
std::string edge_attributes_type = "";
// optional arguments
int n_patterns = 1;
bool use_sample = false;
int n_sample = 0;
std::string test_pos_filename = "";
std::string test_neg_filename = "";
bool undirected = false;
int max_pattern_edges = 20;
int random_walks = 1000;
double prob_restart = 0.3;
timestamp_t time_unit_primary = 1.0;
timestamp_t time_unit_secondary = 1.0;
int evolution_epochs = 25;
int evolution_subepochs = 25;
int evaluation_random_walks = 10;
bool use_uniform_crossover = false;
bool output_baseline_edges = false;
bool use_seed = false;
unsigned seed = 1;
// these cannot be changed at this moment
bool use_vertex_attributes = false;
bool use_simple_init = false;
bool limit_negative_population = true;
// parse the arguments
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
if ((arg == "-h") || (arg == "--help")) {
show_usage(argv[0]);
return 0;
} else if ((arg == "-v") || (arg == "--verbose")) {
verbose = true;
}
// STRINGS
else if (arg == "--vertices" || arg == "--edges" || arg == "--train_pos" || arg == "--train_neg" ||
arg == "-o" || arg == "--test_pos" || arg == "--test_neg" || arg == "--baseline") {
if (i + 1 >= argc) {
std::cerr << arg << " option requires one argument." << std::endl;
return 1;
} else if (arg == "--vertices") {
vertex_filename = argv[++i];
} else if (arg == "--edges") {
edge_filename = argv[++i];
} else if (arg == "--train_pos") {
train_pos_filename = argv[++i];
} else if (arg == "--train_neg") {
train_neg_filename = argv[++i];
} else if (arg == "-o") {
output_dir = argv[++i];
} else if (arg == "--test_pos") {
test_pos_filename = argv[++i];
} else if (arg == "--test_neg") {
test_neg_filename = argv[++i];
}
}
// INTEGERS
else if (arg == "-p" || arg == "-n" || arg == "-m" || arg == "-w" || arg == "-ep" || arg == "-se" ||
arg == "-ew" || arg == "-s") {
if (i + 1 >= argc) {
std::cerr << arg << " option requires one argument." << std::endl;
return 1;
}
std::string str_number = argv[++i];
try {
int number = std::stoi(str_number);
if (arg == "-p") {
n_patterns = number;
} else if (arg == "-n") {
n_sample = number;
if (n_sample > 0) use_sample = true;
} else if (arg == "-m") {
max_pattern_edges = number;
} else if (arg == "-w") {
random_walks = number;
} else if (arg == "-ep") {
evolution_epochs = number;
} else if (arg == "-se") {
evolution_subepochs = number;
} else if (arg == "-ew") {
evaluation_random_walks = number;
} else if (arg == "-s") {
seed = number;
use_seed = true;
}
}
catch (std::exception &) {
std::cerr << arg << " option requires an integer argument." << std::endl;
}
}
// REALS
else if (arg == "-r" || arg == "-pu" || arg == "-su") {
if (i + 1 >= argc) {
std::cerr << arg << " option requires one argument." << std::endl;
return 1;
}
std::string str_number = argv[++i];
try {
double number = std::stod(str_number);
if (arg == "-r") {
if (number < 0 || number > 1) {
std::cerr << "-r option requires a numeric argument from interval [0, 1]" << std::endl;
return 1;
}
prob_restart = number;
} else if (arg == "-pu") {
if (number <= 0) {
std::cerr << "-pu option requires a positive numeric argument" << std::endl;
return 1;
}
time_unit_primary = number;
} else if (arg == "-su") {
if (number <= 0) {
std::cerr << "-su option requires a positive numeric argument" << std::endl;
return 1;
}
time_unit_secondary = number;
}
}
catch (std::exception &) {
std::cerr << arg << " option requires a numeric argument." << std::endl;
return 1;
}
}
// OTHERS
else if (arg == "-e") {
if (i + 1 < argc) { // Make sure we aren't at the end of argv!
str_vertex_events = argv[++i]; // Increment 'i' so we don't get the argument as the next argv[i].
if (str_vertex_events != "vertices" && str_vertex_events != "edges") {
std::cerr << "-e option requires either vertices or edges." << std::endl;
return 1;
} else {
vertex_events = str_vertex_events == "vertices";
}
} else { // Uh-oh, there was no argument to the destination option.
std::cerr << "-e option requires one argument." << std::endl;
return 1;
}
} else if (arg == "-a") {
if (i + 1 < argc) { // Make sure we aren't at the end of argv!
edge_attributes_type = argv[++i]; // Increment 'i' so we don't get the argument as the next argv[i].
if (edge_attributes_type != "nominal" && edge_attributes_type != "numerical") {
std::cerr << "-a option requires either nominal or numerical." << std::endl;
return 1;
}
} else { // Uh-oh, there was no argument to the destination option.
std::cerr << "-a option requires one argument." << std::endl;
return 1;
}
} else if (arg == "-u") {
undirected = true;
} else if (arg == "--unicross") {
use_uniform_crossover = true;
} else if (arg == "--baseline") {
output_baseline_edges = true;
}
}
// check mandatory arguments
if (vertex_filename == "" || edge_filename == "" || train_pos_filename == "" ||
train_neg_filename == "" || output_dir == "" || str_vertex_events == "" ||
edge_attributes_type == "")
{
std::cerr << "Options --vertices --edges --train_pos --train_neg -o -e -a are mandatory." << std::endl;
return 1;
}
run_process_new(vertex_filename, edge_filename,
train_pos_filename, train_neg_filename,
output_dir, vertex_events, edge_attributes_type,
n_patterns, use_sample, n_sample,
test_pos_filename, test_neg_filename,
undirected, max_pattern_edges, random_walks, prob_restart,
time_unit_primary, time_unit_secondary,
evolution_epochs, evolution_subepochs, evaluation_random_walks,
use_uniform_crossover, output_baseline_edges, use_seed, seed,
use_vertex_attributes, use_simple_init, limit_negative_population,
verbose);
return 0;
}
| 48.730618 | 180 | 0.540179 | [
"vector"
] |
48883611a4b1b31c78632b8e1e7143ed395ab32e | 2,596 | cpp | C++ | Tema_5_Ordenamiento/biblioteca/biblioteca/Biblioteca.cpp | vcubells/tc1031 | 43d328df12194be840e8c83966b814e5625347b3 | [
"MIT"
] | 10 | 2020-08-15T16:54:13.000Z | 2021-10-05T16:24:05.000Z | Tema_5_Ordenamiento/biblioteca/biblioteca/Biblioteca.cpp | vcubells/tc1031 | 43d328df12194be840e8c83966b814e5625347b3 | [
"MIT"
] | null | null | null | Tema_5_Ordenamiento/biblioteca/biblioteca/Biblioteca.cpp | vcubells/tc1031 | 43d328df12194be840e8c83966b814e5625347b3 | [
"MIT"
] | 4 | 2020-09-05T02:12:52.000Z | 2021-09-22T00:54:25.000Z | //
// Biblioteca.cpp
// biblioteca
//
// Created by Vicente Cubells Nonell on 09/09/20.
// Copyright © 2020 Vicente Cubells Nonell. All rights reserved.
//
#include "Biblioteca.hpp"
Biblioteca::~Biblioteca()
{
libros.clear();
}
void Biblioteca::adicionarLibro(Libro libro)
{
libros.push_back(libro);
}
std::vector<Libro> Biblioteca::eliminarLibro(std::string titulo)
{
int i = 0;
std::vector<Libro> eliminados;
long int size = libros.size();
while (i < size) {
if ( libros[i].Titulo() == titulo) {
eliminados.push_back(libros[i]);
libros.erase(libros.begin()+i);
}
++i;
}
return eliminados;
}
std::vector<Libro> Biblioteca::compara(Libro buscar, bool(comparador)(Libro, Libro))
{
int i = 0;
std::vector<Libro> encontrados;
long int size = libros.size();
while (i < size) {
if ( comparador(libros[i], buscar) ) {
encontrados.push_back(libros[i]);
}
++i;
}
return encontrados;
}
std::vector<Libro> Biblioteca::buscarAntesDeAño(int año)
{
Libro buscar;
buscar.Año() = año;
return compara(buscar, Libro::compara_año_asc);
}
std::vector<Libro> Biblioteca::buscarDespuesDeAño(int año)
{
Libro buscar;
buscar.Año() = año;
return compara(buscar, Libro::compara_año_desc);
}
std::vector<Libro> Biblioteca::buscarEntreAños(int despues, int antes)
{
int i = 0;
std::vector<Libro> encontrados;
long int size = libros.size();
while (i < size) {
if (libros[i].Año() >= despues && libros[i].Año() <= antes) {
encontrados.push_back(libros[i]);
}
++i;
}
return encontrados;
}
std::vector<Libro> Biblioteca::buscarPorAutor(std::string autor)
{
Libro buscar;
buscar.Autor() = autor;
return compara(buscar, Libro::compara_autor_eq);
}
std::vector<Libro> Biblioteca::buscarPorEditorial(std::string editorial)
{
Libro buscar;
buscar.Editorial() = editorial;
return compara(buscar, Libro::compara_editorial_eq);
}
void Biblioteca::ordenar(
std::vector<Libro>(* algoritmo)(std::vector<Libro>, bool(*)(Libro,Libro)),
bool(* compara)(Libro,Libro)
)
{
libros = algoritmo(libros, compara);
}
unsigned long Biblioteca::size()
{
return libros.size();
}
std::ostream & operator<<(std::ostream & os, const Biblioteca & biblioteca)
{
for (auto libro : biblioteca.libros) {
os << libro;
}
return os;
}
| 20.124031 | 99 | 0.597072 | [
"vector"
] |
48985970674e3bdf60cb0482aa742edc0885d7ac | 8,149 | cpp | C++ | hackathon/yang/neuronrecon/3rdparty/houghtransform/sphere.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 8 | 2019-11-01T11:46:46.000Z | 2022-03-21T12:07:47.000Z | hackathon/yang/neuronrecon/3rdparty/houghtransform/sphere.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | hackathon/yang/neuronrecon/3rdparty/houghtransform/sphere.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 3 | 2020-04-22T07:19:36.000Z | 2020-11-04T12:43:05.000Z | //
// sphere.cpp
// Class that implements direction quantization as described in
// Jeltsch, Dalitz, Pohle-Froehlich: "Hough Parameter Space
// Regularisation for Line Detection in 3D." VISAPP, pp. 345-352, 2016
//
// Author: Manuel Jeltsch, Tilman Schramke, Christoph Dalitz
// Date: 2017-03-16
// License: see LICENSE-BSD2
//
#include "sphere.h"
#include <math.h>
// creates the directions by subdivisions of icosahedron
void Sphere::fromIcosahedron(int subDivisions){
this->getIcosahedron();
for(int i = 0; i < subDivisions; i++) {
subDivide();
}
this->makeUnique();
}
// creates nodes and edges of icosahedron
void Sphere::getIcosahedron(){
vertices.clear();
triangles.clear();
float tau = 1.61803399; // golden_ratio
float norm = sqrt(1 + tau * tau);
float v = 1 / norm;
tau = tau / norm;
Vector3d vec;
vec.x = -v;
vec.y = tau;
vec.z = 0;
vertices.push_back(vec); // 1
vec.x = v;
vec.y = tau;
vec.z = 0;
vertices.push_back(vec); // 2
vec.x = 0;
vec.y = v;
vec.z = -tau;
vertices.push_back(vec); // 3
vec.x = 0;
vec.y = v;
vec.z = tau;
vertices.push_back(vec); // 4
vec.x = -tau;
vec.y = 0;
vec.z = -v;
vertices.push_back(vec); // 5
vec.x = tau;
vec.y = 0;
vec.z = -v;
vertices.push_back(vec); // 6
vec.x = -tau;
vec.y = 0;
vec.z = v;
vertices.push_back(vec); // 7
vec.x = tau;
vec.y = 0;
vec.z = v;
vertices.push_back(vec); // 8
vec.x = 0;
vec.y = -v;
vec.z = -tau;
vertices.push_back(vec); // 9
vec.x = 0;
vec.y = -v;
vec.z = tau;
vertices.push_back(vec); // 10
vec.x = -v;
vec.y = -tau;
vec.z = 0;
vertices.push_back(vec); // 11
vec.x = v;
vec.y = -tau;
vec.z = 0;
vertices.push_back(vec); // 12
// add all edges of all triangles
triangles.push_back(0);
triangles.push_back(1);
triangles.push_back(2); // 1
triangles.push_back(0);
triangles.push_back(1);
triangles.push_back(3); // 2
triangles.push_back(0);
triangles.push_back(2);
triangles.push_back(4); // 3
triangles.push_back(0);
triangles.push_back(4);
triangles.push_back(6); // 4
triangles.push_back(0);
triangles.push_back(3);
triangles.push_back(6); // 5
triangles.push_back(1);
triangles.push_back(2);
triangles.push_back(5); // 6
triangles.push_back(1);
triangles.push_back(3);
triangles.push_back(7); // 7
triangles.push_back(1);
triangles.push_back(5);
triangles.push_back(7); // 8
triangles.push_back(2);
triangles.push_back(4);
triangles.push_back(8); // 9
triangles.push_back(2);
triangles.push_back(5);
triangles.push_back(8); // 10
triangles.push_back(3);
triangles.push_back(6);
triangles.push_back(9); // 1
triangles.push_back(3);
triangles.push_back(7);
triangles.push_back(9); // 12
triangles.push_back(4);
triangles.push_back(8);
triangles.push_back(10); // 13
triangles.push_back(8);
triangles.push_back(10);
triangles.push_back(11); // 14
triangles.push_back(5);
triangles.push_back(8);
triangles.push_back(11); // 15
triangles.push_back(5);
triangles.push_back(7);
triangles.push_back(11); // 16
triangles.push_back(7);
triangles.push_back(9);
triangles.push_back(11); // 17
triangles.push_back(9);
triangles.push_back(10);
triangles.push_back(11); // 18
triangles.push_back(6);
triangles.push_back(9);
triangles.push_back(10); // 19
triangles.push_back(4);
triangles.push_back(6);
triangles.push_back(10); // 20
}
// one subdivision step
void Sphere::subDivide(){
unsigned int vert_num = vertices.size();
double norm;
// subdivide each triangle
int num = triangles.size() / 3;
for(int i = 0; i < num; i++) {
Vector3d a, b, c, d, e, f;
unsigned int ai, bi, ci, di, ei, fi;
ai = triangles.front();
triangles.pop_front();
bi = triangles.front();
triangles.pop_front();
ci = triangles.front();
triangles.pop_front();
a = vertices[ai];
b = vertices[bi];
c = vertices[ci];
// d = a+b
d.x = (a.x + b.x);
d.y = (a.y + b.y);
d.z = (a.z + b.z);
norm = sqrt(d.x * d.x + d.y * d.y + d.z * d.z);
d.x /= norm;
d.y /= norm;
d.z /= norm;
// e = b+c
e.x = (c.x + b.x);
e.y = (c.y + b.y);
e.z = (c.z + b.z);
norm = sqrt(e.x * e.x + e.y * e.y + e.z * e.z);
e.x /= norm;
e.y /= norm;
e.z /= norm;
// f = c+a
f.x = (a.x + c.x);
f.y = (a.y + c.y);
f.z = (a.z + c.z);
norm = sqrt(f.x * f.x + f.y * f.y + f.z * f.z);
f.x /= norm;
f.y /= norm;
f.z /= norm;
// add all new edge indices of new triangles to the triangles deque
bool d_found = false;
bool e_found = false;
bool f_found = false;
for(unsigned int j = vert_num; j < vertices.size(); j++) {
if(vertices[j] == d) {
d_found = true;
di = j;
continue;
}
if(vertices[j] == e) {
e_found = true;
ei = j;
continue;
}
if(vertices[j] == f) {
f_found = true;
fi = j;
continue;
}
}
if(!d_found) {
di = vertices.size();
vertices.push_back(d);
}
if(!e_found) {
ei = vertices.size();
vertices.push_back(e);
}
if(!f_found) {
fi = vertices.size();
vertices.push_back(f);
}
triangles.push_back(ai);
triangles.push_back(di);
triangles.push_back(fi);
triangles.push_back(di);
triangles.push_back(bi);
triangles.push_back(ei);
triangles.push_back(fi);
triangles.push_back(ei);
triangles.push_back(ci);
triangles.push_back(fi);
triangles.push_back(di);
triangles.push_back(ei);
}
}
// make vectors nondirectional and unique
void Sphere::makeUnique(){
for(unsigned int i = 0; i < vertices.size(); i++) {
if(vertices[i].z < 0) { // make hemisphere
vertices.erase(vertices.begin() + i);
// delete all triangles with vertex_i
int t = 0;
for(std::deque<unsigned int>::iterator it = triangles.begin();
it != triangles.end();) {
if(triangles[t] == i || triangles[t + 1] == i ||
triangles[t + 2] == i) {
it = triangles.erase(it);
it = triangles.erase(it);
it = triangles.erase(it);
} else {
++it;
++it;
++it;
t += 3;
}
}
// update indices
for(unsigned int j = 0; j < triangles.size(); j ++) {
if(triangles[j] > i) {
triangles[j]--;
}
}
i--;
} else if(vertices[i].z == 0) { // make equator vectors unique
if(vertices[i].x < 0) {
vertices.erase(vertices.begin() + i);
// delete all triangles with vertex_i
int t = 0;
for(std::deque<unsigned int>::iterator it = triangles.begin();
it != triangles.end();) {
if(triangles[t] == i || triangles[t + 1] == i ||
triangles[t + 2] == i) {
it = triangles.erase(it);
it = triangles.erase(it);
it = triangles.erase(it);
} else {
++it;
++it;
++it;
t += 3;
}
}
// update indices
for(unsigned int j = 0; j < triangles.size(); j ++) {
if(triangles[j] > i) {
triangles[j]--;
}
}
i--;
} else if(vertices[i].x == 0 && vertices[i].y == -1) {
vertices.erase(vertices.begin() + i);
// delete all triangles with vertex_i
int t = 0;
for(std::deque<unsigned int>::iterator it = triangles.begin();
it != triangles.end();) {
if(triangles[t] == i || triangles[t + 1] == i ||
triangles[t + 2] == i) {
it = triangles.erase(it);
it = triangles.erase(it);
it = triangles.erase(it);
} else {
++it;
++it;
++it;
t += 3;
}
}
// update indices
for(unsigned int j = 0; j < triangles.size(); j ++) {
if(triangles[j] > i) {
triangles[j]--;
}
}
i--;
}
}
}
}
| 24.398204 | 75 | 0.540189 | [
"3d"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.